skills-layer 0.2.13 → 0.2.14
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/package.json +1 -1
- package/public/skills-layer-public.mjs +33 -33
|
@@ -144,7 +144,7 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
|
|
|
144
144
|
`&&(i+=SF(o)))}return i};xF.exports=(e,t,n)=>String(e).normalize().replace(/\r\n/g,`
|
|
145
145
|
`).split(`
|
|
146
146
|
`).map(r=>Vte(r,t,n)).join(`
|
|
147
|
-
`)});var RF=z((Nwe,AF)=>{var Hte=Mi("stream"),EI=class extends Hte{#i=null;constructor(t={}){super(t),this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=t.replace,this._prompt=t.prompt||null,this._hadControl=!1}#r(t,n){return this._dest?this._dest[t]:this._src?this._src[t]:n}#t(t,...n){typeof this._dest?.[t]=="function"&&this._dest[t](...n),typeof this._src?.[t]=="function"&&this._src[t](...n)}get isTTY(){return this.#i!==null?this.#i:this.#r("isTTY",!1)}set isTTY(t){this.#i=t}get rows(){return this.#r("rows")}get columns(){return this.#r("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(t){this._src=t}pipe(t,n){return this._dest=t,super.pipe(t,n)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(t){if(this.muted){if(!this.replace)return!0;if(t.match(/^\u001b/))return t.indexOf(this._prompt)===0&&(t=t.slice(this._prompt.length),t=t.replace(/./g,this.replace),t=this._prompt+t),this._hadControl=!0,this.emit("data",t);this._prompt&&this._hadControl&&t.indexOf(this._prompt)===0&&(this._hadControl=!1,this.emit("data",this._prompt),t=t.slice(this._prompt.length)),t=t.toString().replace(/./g,this.replace)}this.emit("data",t)}end(t){this.muted&&(t&&this.replace?t=t.toString().replace(/./g,this.replace):t=null),t&&this.emit("data",t),this.emit("end")}destroy(...t){return this.#t("destroy",...t)}destroySoon(...t){return this.#t("destroySoon",...t)}close(...t){return this.#t("close",...t)}};AF.exports=EI});var $A="Your bank is reviewing a dispute on this payment. Access is paused until it is resolved.";function Ue(e,t="usd"){let n=t.toLowerCase(),r=n==="usd"?"US$":n==="gbp"?"\xA3":`${t.toUpperCase()} `;return`${e<0?"\u2212":""}${r}${(Math.abs(e)/100).toFixed(2)}`}function DA(e="windowed"){return e==="fallback_all_time"?"Popular all time \u2014 no verified installs in the current window.":e==="fallback_newest"?"Newest skills \u2014 no verified installs in the current window.":"Trending from verified installs in the current window."}var el=["verified","published_with_findings","high_risk","pending","unavailable","blocked"],TA=["low","elevated","high"];var OA=["featured","trending","newest","name","relevance","security","effectiveness","platform_score","installs","cost"],Ace=el.map(e=>({value:e,label:{verified:"Verified",published_with_findings:"Published with findings",high_risk:"High risk",pending:"Platform Score pending",unavailable:"Platform Score unavailable",blocked:"Blocked"}[e]}));var Oz="user_",LA=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Lz=/^user_[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/u;function jA(e){let t=e.indexOf("__");if(t<=0)return null;let n=e.slice(0,t).trim(),r=e.slice(t+2).trim();return!n.startsWith(Oz)||r.length===0?null:{ownerUserId:n,baseSlug:r}}function NA(e){if(/\s/u.test(e))return!1;if(LA.test(e))return!0;let t=jA(e);return t!==null&&Lz.test(t.ownerUserId)&&LA.test(t.baseSlug)}function Mr(e){return jA(e)?.baseSlug??e}function tl(e){let t=new URL(e),n=t.hostname==="localhost"||t.hostname==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(t.hostname);if(t.username||t.password||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new Error("Backend URLs require HTTPS (HTTP is allowed only on loopback) and must not contain credentials, a query, or a fragment.");return t}async function FA(e,t){tl(e);let n=!1;for(let r of["/","/health"])try{let i=await t(`${e.replace(/\/+$/u,"")}${r}`,{redirect:"error",signal:AbortSignal.timeout(5e3)});n=!0;let o=await i.json();if(i.ok&&o?.service==="skills-layer-api")return"ok"}catch{}return n?"backend_not_skills_layer":"backend_unreachable"}function BA(e){if(e===void 0)return 90;if(typeof e!="string"||!/^[1-9]\d*d$/iu.test(e.trim()))return null;let t=Number.parseInt(e.trim(),10);return Number.isSafeInteger(t)&&t<=365?t:null}function Gh(e){let t={...e};for(let n of["securityScore","scoreVector","publishedLedgerScore","effectiveBuyerTrustScore","scoreLabel"])delete t[n];for(let n of["securityPosture","trust","securityRuleSummary","ruleSummary"]){let r=t[n];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=Gh(r);n==="trust"&&delete i.score,t[n]=i}}return t}import{spawn as NM}from"node:child_process";import{createHash as Me,createPublicKey as Yne,randomBytes as Ge}from"node:crypto";import{constants as CB}from"node:fs";import{access as FM,appendFile as Xne,chmod as Qne,lstat as Xu,mkdir as Mo,open as Uo,readdir as ere,readFile as Fi,realpath as Fu,rename as zo,rm as We,stat as Ja,writeFile as ZP}from"node:fs/promises";import{basename as it,dirname as Be,join as K,posix as Lt,relative as Bu,resolve as qo,win32 as ot}from"node:path";import{createInterface as BM}from"node:readline/promises";import{spawn as e6}from"node:child_process";import{createHash as aR}from"node:crypto";import{chmod as Yh,lstat as lR,mkdir as cR,open as t6,readFile as Qh,rename as n6,rm as Ui,writeFile as ud}from"node:fs/promises";import{dirname as Xh,posix as r6,win32 as i6}from"node:path";import{posix as jz,win32 as qA}from"node:path";var Nz="https://github.com/vercel-labs/skills#supported-agents",cd="2026-07-15",Xt=["codex","claude-code","cursor","opencode","amp","kimi-code-cli","replit","universal","antigravity","augment","openclaw","cline","warp","codebuddy","command-code","continue","cortex","crush","deepagents","droid","gemini-cli","github-copilot","goose","junie","iflow-cli","kilo","kiro-cli","kode","mcpjam","mistral-vibe","mux","openhands","pi","qoder","qwen-code","roo","trae","trae-cn","windsurf","zencoder","neovate","pochi","adal","aider-desk","antigravity-cli","astrbot","autohand-code","bob","dexto","loaf","zed","codearts-agent","codemaker","codestudio","devin","eve","firebender","forgecode","hermes-agent","inference-sh","jazz","lingma","moxby","ona","qoder-cn","reasonix","rovodev","tabnine-cli","terramind","tinycloud","zcode","zenflow","promptscript"];var Fz={"kimi-cli":"kimi-code-cli"},ad=[Y("codex","Codex",".codex",{capabilities:Ze({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),Y("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:Ze({allowedTools:!0,hooks:!0,forkedContext:!0})}),Y("cursor","Cursor",".cursor",{capabilities:Ze({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),Y("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:Ze({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),yt("amp","Amp",".config/agents",{capabilities:Ze({allowedTools:!0})}),yt("kimi-code-cli","Kimi Code CLI",".agents",{legacyEnvVars:["KIMI_CLI_HOME"],legacyGlobalSkillsRelativePaths:[".config/agents/skills"]}),yt("replit","Replit",".config/agents"),yt("universal","Universal",".config/agents"),yt("antigravity","Antigravity",".gemini/antigravity",{capabilities:Ze({allowedTools:!0}),detectGlobal:!0}),Y("augment","Augment",".augment"),{id:"openclaw",displayName:"OpenClaw",envVar:"OPENCLAW_HOME",legacyEnvVars:[],capabilities:Ze({allowedTools:!0}),adapterRevision:cd,targets:{projectRootRelativePath:null,projectSkillsRelativePath:"skills",globalRootRelativePath:".openclaw",globalSkillsRelativePath:".openclaw/skills",projectCompatibleRelativePaths:[],projectLegacyRelativePaths:[],globalCompatibleRelativePaths:[],globalLegacyRelativePaths:[]},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:[".openclaw",".openclaw/skills"]}},yt("cline","Cline",".agents",{capabilities:Ze({allowedTools:!0,hooks:!0})}),yt("warp","Warp",".agents"),Y("codebuddy","CodeBuddy",".codebuddy",{capabilities:Ze({allowedTools:!0})}),Y("command-code","Command Code",".commandcode",{capabilities:Ze({allowedTools:!0})}),Y("continue","Continue",".continue"),Y("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),Y("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),yt("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),Y("droid","Droid",".factory"),yt("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),yt("github-copilot","GitHub Copilot",".copilot",{capabilities:Ze({allowedTools:!0}),detectGlobal:!0}),Y("goose","Goose",".goose",{globalRootRelativePath:".config/goose"}),Y("junie","Junie",".junie"),Y("iflow-cli","iFlow CLI",".iflow"),Y("kilo","Kilo Code",".kilocode"),Y("kiro-cli","Kiro CLI",".kiro"),Y("kode","Kode",".kode"),Y("mcpjam","MCPJam",".mcpjam"),Y("mistral-vibe","Mistral Vibe",".vibe"),Y("mux","Mux",".mux"),Y("openhands","OpenHands",".openhands",{capabilities:Ze({allowedTools:!0})}),Y("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:Ze({allowedTools:!0})}),Y("qoder","Qoder",".qoder",{capabilities:Ze({allowedTools:!0})}),Y("qwen-code","Qwen Code",".qwen"),Y("roo","Roo Code",".roo",{capabilities:Ze({allowedTools:!0})}),Y("trae","Trae",".trae",{detectProject:!1}),Y("trae-cn","Trae CN",".trae",{globalRootRelativePath:".trae-cn",detectProject:!1}),Y("windsurf","Windsurf",".windsurf",{globalRootRelativePath:".codeium/windsurf"}),Y("zencoder","Zencoder",".zencoder",{capabilities:Ze({allowedTools:!0})}),Y("neovate","Neovate",".neovate",{capabilities:Ze({allowedTools:!0})}),Y("pochi","Pochi",".pochi"),Y("adal","AdaL",".adal"),Y("aider-desk","AiderDesk",".aider-desk"),yt("antigravity-cli","Antigravity CLI",".gemini/antigravity-cli",{detectGlobal:!0}),Y("astrbot","AstrBot","data",{globalRootRelativePath:".astrbot",globalSkillsRelativePath:".astrbot/data/skills"}),Y("autohand-code","Autohand Code CLI",".autohand"),Y("bob","IBM Bob",".bob"),yt("dexto","Dexto",".agents"),yt("loaf","Loaf",".agents"),yt("zed","Zed",".agents"),Y("codearts-agent","CodeArts Agent",".codeartsdoer"),Y("codemaker","Codemaker",".codemaker"),Y("codestudio","Code Studio",".codestudio"),Y("devin","Devin for Terminal",".devin",{globalRootRelativePath:".config/devin"}),Y("eve","Eve","agent",{globalApplicable:!1}),yt("firebender","Firebender",".firebender",{detectGlobal:!0}),Y("forgecode","ForgeCode",".forge"),Y("hermes-agent","Hermes Agent",".hermes"),Y("inference-sh","inference.sh",".inferencesh"),Y("jazz","Jazz",".jazz"),Y("lingma","Lingma",".lingma"),Y("moxby","Moxby",".moxby"),Y("ona","Ona",".ona"),Y("qoder-cn","Qoder CN",".qoder",{globalRootRelativePath:".qoder-cn",detectProject:!1}),Y("reasonix","Reasonix",".reasonix"),Y("rovodev","Rovo Dev",".rovodev"),Y("tabnine-cli","Tabnine CLI",".tabnine/agent"),Y("terramind","Terramind",".terramind"),Y("tinycloud","Tinycloud",".tinycloud"),Y("zcode","ZCode",".zcode"),Y("zenflow","Zenflow",".zencoder",{detectProject:!1,detectGlobal:!1}),yt("promptscript","PromptScript",".agents",{globalApplicable:!1})];Uz(Xt,Fz);qz();function Qe(e=process.env,t=process.platform,n=process.cwd()){let r=HA(t),i=GA(e,t);return ad.map(o=>{let s=WA(o,e,r),a=o.targets.globalSkillsRelativePath!==null,l=a&&i&&o.targets.globalRootRelativePath?Yo(r,i,o.targets.globalRootRelativePath):null,c=a&&i&&o.targets.globalSkillsRelativePath?Yo(r,i,o.targets.globalSkillsRelativePath):null,u=o.targets.projectRootRelativePath?Yo(r,n,o.targets.projectRootRelativePath):null,d=a?s??l:null,p=Yo(r,n,o.targets.projectSkillsRelativePath),m=a?s?r.join(s,"skills"):c:null,h=od();return{id:o.id,displayName:o.displayName,envVar:o.envVar,capabilities:o.capabilities,detectionSources:[],targets:{projectRoot:u,projectSkillsPath:p,globalRoot:d,globalSkillsPath:m},installEvidence:h,adapterRevision:o.adapterRevision,pathContracts:{project:{status:"supported",preferredPath:p,preferredRelativePath:o.targets.projectSkillsRelativePath,compatibleReadOnlyPaths:sd(r,n,o.targets.projectCompatibleRelativePaths),legacyReadOnlyPaths:sd(r,n,o.targets.projectLegacyRelativePaths),evidence:od()},global:a?{status:"supported",preferredPath:m,preferredRelativePath:o.targets.globalSkillsRelativePath,compatibleReadOnlyPaths:i?sd(r,i,o.targets.globalCompatibleRelativePaths):[],legacyReadOnlyPaths:i?sd(r,i,o.targets.globalLegacyRelativePaths):[],evidence:od()}:{status:"not_applicable",preferredPath:null,preferredRelativePath:null,compatibleReadOnlyPaths:[],legacyReadOnlyPaths:[],evidence:od()}}}})}async function VA(e={}){let t=e.env??process.env,n=e.platform??process.platform,r=e.cwd??process.cwd(),i=HA(n),o=GA(t,n),s=Qe(t,n,r),a=e.pathExists??(async()=>!1);return(await Promise.all(s.map(async l=>{let c=Mz(l.id),u=[],d=WA(c,t,i);return(c.targets.globalSkillsRelativePath!==null&&d&&await a(d)||c.targets.globalSkillsRelativePath!==null&&d&&await a(i.join(d,"skills")))&&u.push("override"),c.detection.projectProbeRelativePaths.length>0&&await MA({basePath:r,relativePaths:c.detection.projectProbeRelativePaths,pathApi:i,pathExists:a})&&u.push("project"),o&&c.detection.globalProbeRelativePaths.length>0&&await MA({basePath:o,relativePaths:c.detection.globalProbeRelativePaths,pathApi:i,pathExists:a})&&u.push("global"),u.length===0?null:{...l,detectionSources:Bz(u)}}))).flatMap(l=>l?[l]:[])}function GA(e,t){return t==="win32"?ld(e.USERPROFILE,e.HOME):ld(e.HOME)}function HA(e){return e==="win32"?qA:jz}function ld(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Bz(e){return[...new Set(e)]}async function MA(e){for(let t of e.relativePaths)if(await e.pathExists(Yo(e.pathApi,e.basePath,t)))return!0;return!1}function Yo(e,t,n){return e.join(t,...n.split("/"))}function Y(e,t,n,r={}){let i=r.globalRootRelativePath??n,o=r.detectProject??!0,s=r.globalApplicable??!0,a=r.globalSkillsRelativePath??`${i}/skills`;return{id:e,displayName:t,envVar:r.envVar??KA(e),legacyEnvVars:r.legacyEnvVars??[],capabilities:r.capabilities??Ze(),adapterRevision:r.adapterRevision??cd,targets:{projectRootRelativePath:n,projectSkillsRelativePath:`${n}/skills`,globalRootRelativePath:s?i:null,globalSkillsRelativePath:s?a:null,projectCompatibleRelativePaths:r.compatibleProjectSkillsRelativePaths??[],projectLegacyRelativePaths:r.legacyProjectSkillsRelativePaths??[],globalCompatibleRelativePaths:r.compatibleGlobalSkillsRelativePaths??[],globalLegacyRelativePaths:r.legacyGlobalSkillsRelativePaths??[]},detection:{projectProbeRelativePaths:o?[n,`${n}/skills`]:[],globalProbeRelativePaths:s&&(r.detectGlobal??!0)?[i,a]:[]}}}function yt(e,t,n,r={}){let i=r.detectGlobal??!1,o=r.globalApplicable??!0;return{id:e,displayName:t,envVar:r.envVar??KA(e),legacyEnvVars:r.legacyEnvVars??[],capabilities:r.capabilities??Ze(),adapterRevision:r.adapterRevision??cd,targets:{projectRootRelativePath:".agents",projectSkillsRelativePath:".agents/skills",globalRootRelativePath:o?n:null,globalSkillsRelativePath:o?`${n}/skills`:null,projectCompatibleRelativePaths:r.compatibleProjectSkillsRelativePaths??[],projectLegacyRelativePaths:r.legacyProjectSkillsRelativePaths??[],globalCompatibleRelativePaths:r.compatibleGlobalSkillsRelativePaths??[],globalLegacyRelativePaths:r.legacyGlobalSkillsRelativePaths??[]},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:i&&o?[n,`${n}/skills`]:[]}}}function Ze(e={}){let t=["basic_skills"];return e.allowedTools&&t.push("allowed_tools"),e.hooks&&t.push("hooks"),e.forkedContext&&t.push("forked_context"),t.push("local_install"),t}function KA(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function Mz(e){return ad.find(t=>t.id===e)}function Uz(e,t){let n=new Set;for(let r of e){if(!UA(r))throw new Error(`Unsafe canonical agent id: ${JSON.stringify(r)}`);if(n.has(r))throw new Error(`Duplicate canonical agent id: ${r}`);n.add(r)}for(let r of Object.keys(t)){if(!UA(r))throw new Error(`Unsafe alias: ${JSON.stringify(r)}`);if(n.has(r))throw new Error(`Alias ${r} collides with a canonical agent id`);let i=new Set([r]),o=t[r];for(;!n.has(o);){if(i.has(o))throw new Error(`Agent alias cycle detected at ${o}`);i.add(o);let s=t[o];if(!s)throw new Error(`Agent alias ${r} has unknown target ${o}`);o=s}}}function UA(e){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}function od(){return{sourceUrl:Nz,checkedAt:cd,state:"contract_tested",supportedPlatforms:["darwin","linux","win32"],hostVersion:null}}function sd(e,t,n){return n.map(r=>({path:Yo(e,t,r),relativePath:r,access:"read_only"}))}function WA(e,t,n){let r=[{envVar:e.envVar,value:ld(t[e.envVar])},...e.legacyEnvVars.map(i=>({envVar:i,value:ld(t[i])}))].filter(i=>i.value!==void 0);if(r.length>1&&new Set(r.map(o=>zz(n,o.value))).size>1)throw new Error(`Conflicting canonical and legacy overrides for ${e.id}: ${r.map(o=>o.envVar).join(", ")}`);return r[0]?.value}function zz(e,t){let n=e.normalize(t);return e===qA?n.toLowerCase():n}function qz(){let e=ad.map(t=>t.id);if(e.length!==Xt.length||e.some((t,n)=>t!==Xt[n]))throw new Error("Agent definitions must exactly match the canonical supported-agent inventory");for(let t of ad){if(!zA(t.targets.projectSkillsRelativePath))throw new Error(`Unsafe project path contract for ${t.id}`);let n=t.targets.globalSkillsRelativePath;if(n!==null&&!zA(n))throw new Error(`Unsafe global path contract for ${t.id}`);if(t.targets.globalRootRelativePath===null!=(n===null))throw new Error(`Inconsistent global path contract for ${t.id}`)}}function zA(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}import{posix as Vz,win32 as Gz}from"node:path";var Hz="2026-10-25",Kz="2026-11-24",Hh={codex:{aliases:[],vendor:"OpenAI",productSurface:"Codex CLI and desktop"},vscode:{aliases:["code","visual-studio-code"],vendor:"Microsoft",productSurface:"Visual Studio Code MCP host"},"github-copilot-cli":{aliases:["copilot-cli"],vendor:"GitHub",productSurface:"GitHub Copilot CLI"},"claude-code":{aliases:[],vendor:"Anthropic",productSurface:"Claude Code"},cursor:{aliases:[],vendor:"Anysphere",productSurface:"Cursor"},cline:{aliases:[],vendor:"Cline",productSurface:"Cline extension"},"gemini-cli":{aliases:[],vendor:"Google",productSurface:"Gemini CLI"},windsurf:{aliases:[],vendor:"Cognition",productSurface:"Windsurf"},opencode:{aliases:[],vendor:"OpenCode",productSurface:"OpenCode CLI"},"kiro-cli":{aliases:[],vendor:"AWS",productSurface:"Kiro CLI"},kilo:{aliases:["kilo-code"],vendor:"Kilo Code",productSurface:"Kilo Code"},"qwen-code":{aliases:[],vendor:"Alibaba Cloud",productSurface:"Qwen Code"}},yr=[mn("codex","Codex","codex_toml",[],"https://developers.openai.com/codex/mcp/","Codex stores user MCP servers in its user config.",e=>he(e,Ee(e),".codex","config.toml")),mn("vscode","Visual Studio Code","json_servers",["github-copilot-chat"],"https://code.visualstudio.com/docs/agent-customization/mcp-servers","VS Code supports MCP servers in the user profile and through --add-mcp.",ZA,e=>[ZA(e),eR(e),...Yz(e),he(e,Ee(e),".vscode","extensions")]),mn("github-copilot-cli","GitHub Copilot CLI","json_copilot_mcp_servers",[],"https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-config-dir-reference","Copilot CLI stores user-level MCP definitions in ~/.copilot/mcp-config.json.",e=>he(e,hr(e.env?.COPILOT_HOME,he(e,Ee(e),".copilot")),"mcp-config.json")),mn("claude-code","Claude Code","json_mcp_servers",[],"https://docs.anthropic.com/en/docs/claude-code/mcp","Claude Code supports user-scoped MCP servers.",e=>he(e,Ee(e),".claude.json")),mn("cursor","Cursor","json_mcp_servers",[],"https://cursor.com/docs/mcp","Cursor supports a global ~/.cursor/mcp.json configuration.",e=>he(e,Ee(e),".cursor","mcp.json")),mn("cline","Cline","json_mcp_servers",[],"https://github.com/cline/cline/blob/main/docs/mcp/mcp-overview.mdx","Cline stores global MCP settings in its user data directory.",e=>he(e,Ee(e),".cline","data","settings","cline_mcp_settings.json")),mn("gemini-cli","Gemini CLI","json_mcp_servers",[],"https://google-gemini.github.io/gemini-cli/docs/tools/mcp-server.html","Gemini CLI reads user MCP servers from ~/.gemini/settings.json.",e=>he(e,Ee(e),".gemini","settings.json")),mn("windsurf","Windsurf","json_mcp_servers",[],"https://docs.windsurf.com/windsurf/cascade/mcp","Windsurf stores the user MCP configuration under ~/.codeium/windsurf.",e=>he(e,Ee(e),".codeium","windsurf","mcp_config.json")),mn("opencode","OpenCode","json_opencode_mcp",[],"https://opencode.ai/docs/mcp-servers/","OpenCode supports local MCP servers in its global configuration.",e=>he(e,Xo(e),"opencode","opencode.json")),mn("kiro-cli","Kiro CLI","json_mcp_servers",[],"https://kiro.dev/docs/mcp/configuration/","Kiro CLI supports a global MCP configuration under ~/.kiro/settings.",e=>he(e,Ee(e),".kiro","settings","mcp.json")),mn("kilo","Kilo Code","json_opencode_mcp",[],"https://kilo.ai/docs/automate/mcp/using-in-cli","Kilo Code supports MCP servers in its global configuration.",e=>he(e,Xo(e),"kilo","kilo.json")),mn("qwen-code","Qwen Code","json_mcp_servers",[],"https://qwenlm.github.io/qwen-code-docs/en/users/features/mcp/","Qwen Code reads user MCP servers from ~/.qwen/settings.json.",e=>he(e,Ee(e),".qwen","settings.json"))],JA=new Map(yr.map(e=>[e.id,e])),Wz=new Map([["code","vscode"],["visual-studio-code","vscode"],["copilot-cli","github-copilot-cli"]]),Zz=new Map([["github-copilot","vscode"],["github-copilot-chat","vscode"]]);function nl(e){let t=e.trim().toLowerCase(),n=Wz.get(t)??(JA.has(t)?t:null);if(n)return{status:"host",hostId:n};let r=Zz.get(t);return r?{status:"consumer",consumerId:t==="github-copilot"?"github-copilot-chat":t,hostId:r}:{status:"unknown",requestedClient:e}}function Kh(e){return JA.get(e)}function YA(e){let t=yr.filter(n=>Date.parse(`${n.evidence.reviewAfter}T23:59:59.999Z`)<Date.parse(e));return{evidenceStale:t.length>0,warnings:t.length>0?[`MCP compatibility evidence is due for review: ${t.map(n=>n.id).join(", ")}. Update the CLI if a host connection fails.`]:[]}}function XA(e){if(e==="universal")return{installAgentId:e,classification:"skills_only",hostId:null};let t=nl(e);return t.status==="host"?{installAgentId:e,classification:"host",hostId:t.hostId}:t.status==="consumer"?{installAgentId:e,classification:"consumer",hostId:t.hostId}:{installAgentId:e,classification:"unverified",hostId:null}}var Fce=Object.freeze([{id:"antigravity-cli",displayName:"Antigravity CLI",classification:"unverified",reason:"No fresh primary evidence in the Phase 126 evidence set proves a safe user-global automatic MCP lifecycle.",manualGuidance:"Do not mutate Antigravity configuration automatically; use its vendor documentation and request evidence review before promotion."}]);async function Wh(e){let t=[];for(let n of yr){let r=new Set([n.resolveConfigPath(e)]);n.id==="vscode"&&r.add(eR(e));let i=[...new Set(n.detectionPaths(e))],o=(await Promise.all(i.map(async m=>await e.pathExists(m)?m:null))).filter(m=>m!==null),s=await e.executableExists?.(n.id)??!1,a=o.map(m=>({kind:r.has(m)?"config":Xz(m)?"application":"user_data",path:m}));s&&a.push({kind:"executable",path:n.id});let l=a.some(m=>m.kind==="config"),c=a.length>0,u=e.runningHostIds?.includes(n.id)??!1,p=l&&(e.staleConfigHostIds?.includes(n.id)??!1)?"stale":u?"running":l?"configured":c?"installed":"unavailable";t.push({hostId:n.id,displayName:n.displayName,state:p,installed:c,running:u,configured:l,consumers:n.consumers.map(m=>({id:m,detected:e.extensionIds?.includes("github.copilot-chat")??!1})),signals:a,reason:Qz(p,a)})}return t}async function QA(e){return(await Wh(e)).filter(n=>n.installed).map(n=>{let r=Kh(n.hostId);return{hostId:n.hostId,displayName:n.displayName,detected:!0,configured:n.configured,consumers:n.consumers.filter(i=>i.detected).map(i=>i.id),evidence:r.evidence,signals:n.signals.map(i=>({kind:i.kind==="config"?"config":"installation",path:i.path}))}})}function mn(e,t,n,r,i,o,s,a){return{id:e,displayName:t,aliases:[...Hh[e].aliases],vendor:Hh[e].vendor,productSurface:Hh[e].productSurface,classification:"global_automatic",scope:"user_global",supportedPlatforms:["darwin","linux","win32"],supportedVersions:e==="windsurf"?"Legacy Windsurf releases using ~/.codeium/windsurf; the renamed Devin Desktop configuration is not claimed by this adapter.":"vendor-supported release with the cited global MCP mechanism",transport:"stdio",configKind:n,consumers:r,caveats:{reload:"Open a fresh agent session or restart the host after registration changes.",trust:"The host launches the existing tokenless Skills Layer bridge; raw remote credentials are never written to host config.",enterprisePolicy:"Managed enterprise policy can prevent or override user configuration and must be checked by the operator.",remote:"User-global scope is local to the active OS, WSL distribution, SSH host, container, or Codespace.",workspace:"Normal setup never writes workspace or project MCP configuration."},evidence:{sourceUrl:i,checkedAt:Hz,reviewAfter:Kz,owner:"mcp-client-support-owner",statement:o},resolveConfigPath:s,detectionPaths:a??(l=>[s(l),Jz(e,l)])}}function Jz(e,t){if(e==="claude-code")return he(t,Ee(t),".claude");if(e==="github-copilot-cli")return hr(t.env?.COPILOT_HOME,he(t,Ee(t),".copilot"));if(e==="windsurf")return he(t,Ee(t),".codeium","windsurf");if(e==="opencode")return he(t,Xo(t),"opencode");if(e==="kiro-cli")return he(t,Ee(t),".kiro");if(e==="kilo")return he(t,Xo(t),"kilo");let n={codex:".codex",cursor:".cursor",cline:".cline","gemini-cli":".gemini","qwen-code":".qwen"};return he(t,Ee(t),n[e]??`.${e}`)}function ZA(e){let t=e.platform??process.platform;return t==="darwin"?he(e,Ee(e),"Library","Application Support","Code","User","mcp.json"):t==="win32"?he(e,hr(e.env?.APPDATA,Ee(e)),"Code","User","mcp.json"):he(e,Xo(e),"Code","User","mcp.json")}function eR(e){let t=e.platform??process.platform;return t==="darwin"?he(e,Ee(e),"Library","Application Support","Code - Insiders","User","mcp.json"):t==="win32"?he(e,hr(e.env?.APPDATA,Ee(e)),"Code - Insiders","User","mcp.json"):he(e,Xo(e),"Code - Insiders","User","mcp.json")}function Yz(e){let t=e.platform??process.platform;return t==="darwin"?["/Applications/Visual Studio Code.app","/Applications/Visual Studio Code - Insiders.app",he(e,Ee(e),"Applications","Visual Studio Code.app"),he(e,Ee(e),"Applications","Visual Studio Code - Insiders.app")]:t==="win32"?[he(e,hr(e.env?.LOCALAPPDATA,Ee(e)),"Programs","Microsoft VS Code"),he(e,hr(e.env?.LOCALAPPDATA,Ee(e)),"Programs","Microsoft VS Code Insiders"),he(e,hr(e.env?.ProgramFiles,"C:\\Program Files"),"Microsoft VS Code")]:["/usr/share/code","/usr/share/code-insiders","/var/lib/flatpak/app/com.visualstudio.code",he(e,Ee(e),".local","share","code")]}function Xz(e){return/(?:\.app$|\/Applications\/|\\Programs\\|\/usr\/share\/|\/var\/lib\/flatpak\/)/u.test(e)}function Qz(e,t){return e==="unavailable"?"No executable, application, user-data, or global configuration signal was found.":e==="stale"?"A global configuration exists but was marked stale by lifecycle inspection.":e==="running"?"The host is running and at least one installed or configured signal was found.":e==="configured"?"A verified user-global configuration file exists.":`Installed signals found: ${t.map(n=>n.kind).join(", ")}.`}function Ee(e){let t=e.platform??process.platform;return hr(t==="win32"?e.env?.USERPROFILE:e.env?.HOME,e.env?.HOME,e.cwd,process.cwd())}function Xo(e){return hr(e.env?.XDG_CONFIG_HOME,he(e,Ee(e),".config"))}function he(e,...t){return((e.platform??process.platform)==="win32"?Gz:Vz).join(...t)}function hr(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()??process.cwd()}if(new Set(yr.map(e=>e.id)).size!==yr.length)throw new Error("duplicate MCP host id");if(yr.some(e=>!e.evidence.sourceUrl.startsWith("https://")))throw new Error("automatic MCP hosts require primary HTTPS evidence");if(Xt.length!==73)throw new Error("MCP host registry must not mutate the skill-install inventory");var Zh=Object.freeze([Object.freeze({origin:"https://api.skills-layer.com",audience:"https://api.skills-layer.com/mcp",environment:"production"}),Object.freeze({origin:"https://skills-layer.com",audience:"https://skills-layer.com/mcp",environment:"production"}),Object.freeze({origin:"https://api.staging.findfigg.co.uk",audience:"https://api.staging.findfigg.co.uk/mcp",environment:"staging"}),Object.freeze({origin:"https://staging.findfigg.co.uk",audience:"https://staging.findfigg.co.uk/mcp",environment:"staging"}),Object.freeze({origin:"https://api.preprod.findfigg.co.uk",audience:"https://api.preprod.findfigg.co.uk/mcp",environment:"preproduction"}),Object.freeze({origin:"https://preprod.findfigg.co.uk",audience:"https://preprod.findfigg.co.uk/mcp",environment:"preproduction"})]),tR=Object.freeze(Zh.map(e=>e.origin)),nR=Object.freeze(Zh.map(e=>e.audience));function rR(e){return Zh.some(t=>t.origin===e)}var ey="skills-layer-local-broker";function o6(e){return`broker_${aR("sha256").update(`skills-layer-mcp-broker-v1\0${e}`).digest("hex").slice(0,32)}`}var Bt="skills-layer",s6="2025-06-18",a6=["mcp","skills-layer-mcp-proxy.mjs"],l6=["mcp","skills-layer-mcp-broker.mjs"],c6=["mcp","skills-layer-mcp-broker.lock"],u6=new Set(["universal"]);function es(e){let t=YA(e.now),n=e.platform??process.platform,r=e.cwd??process.cwd(),i=e.stateDir??w6(e.env,n),o=e.mcpConfigPath??rl(n,i,"mcp.json"),s=rl(n,i,...a6),a=rl(n,i,...l6),l=zi(o).slice(0,32),c=n==="win32"?`\\\\.\\pipe\\skills-layer-mcp-${l}`:rl(n,"/tmp",`skills-layer-mcp-${l}.sock`),u=rl(n,i,...c6),d=e.nodePath??process.execPath,p=uR({mcpConfigPath:o}),m=(e.brokerSourceBuilder??dR)({mcpConfigPath:o,socketPath:c,lockPath:u}),h=zi(p),g=zi(m),y=new Set(yr.map(w=>w.id)),b=[...yr.map(w=>w.id),...Xt.filter(w=>!y.has(w))].map(w=>{if(y.has(w)){let C=Kh(w),P=C.resolveConfigPath({env:e.env,platform:n,cwd:r});return d6({agentId:w,displayName:C.displayName,configPath:P,configKind:C.configKind,bridgePath:s,brokerPath:a,brokerSocketPath:c,brokerLockPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:h,brokerChecksum:g,brokerSourceBuilder:e.brokerSourceBuilder})}if(u6.has(w))return oR({agentId:w,displayName:w,tier:"tier_3",status:"skills_only",verification:"skills_only",reason:"This agent is currently supported through Skills Layer skill files, not MCP auto-install.",instructions:[`Install skills for ${w} with \`skills-layer install <skill> --agent ${w}\`.`,"MCP auto-install is not claimed for this agent yet."]});let _=XA(w);return oR({agentId:w,displayName:w,tier:"tier_2",status:"manual_handoff",verification:"manual",reason:_.classification==="consumer"?`This install target consumes MCP through ${_.hostId}; configure that host instead.`:"MCP support or the safe writable global config shape has not been verified yet.",instructions:[`Add a local stdio MCP server named ${Bt}.`,`Command: ${d}`,`Args: ${s}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{...t,status:"mcp_registration_plan",serverName:Bt,mcpUrl:e.mcpUrl,bearerTokenEnvVar:e.bearerTokenEnvVar,clientId:e.clientId,environment:e.environment,generatedAt:e.now,bridgePath:s,brokerPath:a,brokerSocketPath:c,brokerLockPath:u,nodePath:d,mcpConfigPath:o,bridgeChecksum:h,brokerChecksum:g,automaticCount:b.filter(w=>w.status==="automatic").length,manualCount:b.filter(w=>w.status==="manual_handoff").length,skillsOnlyCount:b.filter(w=>w.status==="skills_only").length,unsupportedCount:b.filter(w=>w.status==="unsupported").length,targets:b}}async function qi(e){let t=es(e),n=b6(e.clientId),r=t.targets.find(y=>y.agentId===n),i=e.mcpConfig??await il(t.mcpConfigPath,{allowMissing:!0});if(!i)return iR({plan:t,target:r,mcpConfig:null,tokenConfig:null,tokenPresent:!1,tokenRefPresent:!1,bridgeExists:!1,checksumMatches:!1,brokerExists:!1,brokerChecksumMatches:!1,brokerInstalledChecksum:null,targetConfigured:!1,rawTokenLeaked:!1});let o=await Qo(t.bridgePath),s=o!==null,a=o!==null&&zi(o)===t.bridgeChecksum,l=await Qo(t.brokerPath),c=l!==null,u=l===null?null:zi(l),d=u===t.brokerChecksum,p=_6(i,r.agentId),m=Ct(p,"token"),h=Ct(p,"tokenRef"),g=await h6(r,m);return iR({plan:t,target:r,mcpConfig:i,tokenConfig:p,tokenPresent:!!m,tokenRefPresent:!!h,bridgeExists:s,checksumMatches:a,brokerExists:c,brokerChecksumMatches:d,brokerInstalledChecksum:u,targetConfigured:g.configured,rawTokenLeaked:g.rawTokenLeaked})}function uR(e){return`#!/usr/bin/env node
|
|
147
|
+
`)});var RF=z((Nwe,AF)=>{var Hte=Mi("stream"),EI=class extends Hte{#i=null;constructor(t={}){super(t),this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=t.replace,this._prompt=t.prompt||null,this._hadControl=!1}#r(t,n){return this._dest?this._dest[t]:this._src?this._src[t]:n}#t(t,...n){typeof this._dest?.[t]=="function"&&this._dest[t](...n),typeof this._src?.[t]=="function"&&this._src[t](...n)}get isTTY(){return this.#i!==null?this.#i:this.#r("isTTY",!1)}set isTTY(t){this.#i=t}get rows(){return this.#r("rows")}get columns(){return this.#r("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(t){this._src=t}pipe(t,n){return this._dest=t,super.pipe(t,n)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(t){if(this.muted){if(!this.replace)return!0;if(t.match(/^\u001b/))return t.indexOf(this._prompt)===0&&(t=t.slice(this._prompt.length),t=t.replace(/./g,this.replace),t=this._prompt+t),this._hadControl=!0,this.emit("data",t);this._prompt&&this._hadControl&&t.indexOf(this._prompt)===0&&(this._hadControl=!1,this.emit("data",this._prompt),t=t.slice(this._prompt.length)),t=t.toString().replace(/./g,this.replace)}this.emit("data",t)}end(t){this.muted&&(t&&this.replace?t=t.toString().replace(/./g,this.replace):t=null),t&&this.emit("data",t),this.emit("end")}destroy(...t){return this.#t("destroy",...t)}destroySoon(...t){return this.#t("destroySoon",...t)}close(...t){return this.#t("close",...t)}};AF.exports=EI});var $A="Your bank is reviewing a dispute on this payment. Access is paused until it is resolved.";function Ue(e,t="usd"){let n=t.toLowerCase(),r=n==="usd"?"US$":n==="gbp"?"\xA3":`${t.toUpperCase()} `;return`${e<0?"\u2212":""}${r}${(Math.abs(e)/100).toFixed(2)}`}function DA(e="windowed"){return e==="fallback_all_time"?"Popular all time \u2014 no verified installs in the current window.":e==="fallback_newest"?"Newest skills \u2014 no verified installs in the current window.":"Trending from verified installs in the current window."}var el=["verified","published_with_findings","high_risk","pending","unavailable","blocked"],TA=["low","elevated","high"];var OA=["featured","trending","newest","name","relevance","security","effectiveness","platform_score","installs","cost"],Ace=el.map(e=>({value:e,label:{verified:"Verified",published_with_findings:"Published with findings",high_risk:"High risk",pending:"Platform Score pending",unavailable:"Platform Score unavailable",blocked:"Blocked"}[e]}));var Oz="user_",LA=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Lz=/^user_[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/u;function jA(e){let t=e.indexOf("__");if(t<=0)return null;let n=e.slice(0,t).trim(),r=e.slice(t+2).trim();return!n.startsWith(Oz)||r.length===0?null:{ownerUserId:n,baseSlug:r}}function NA(e){if(/\s/u.test(e))return!1;if(LA.test(e))return!0;let t=jA(e);return t!==null&&Lz.test(t.ownerUserId)&&LA.test(t.baseSlug)}function Mr(e){return jA(e)?.baseSlug??e}function tl(e){let t=new URL(e),n=t.hostname==="localhost"||t.hostname==="[::1]"||/^127(?:\.\d{1,3}){3}$/u.test(t.hostname);if(t.username||t.password||t.search||t.hash||t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new Error("Backend URLs require HTTPS (HTTP is allowed only on loopback) and must not contain credentials, a query, or a fragment.");return t}async function FA(e,t){tl(e);let n=!1;for(let r of["/","/health"])try{let i=await t(`${e.replace(/\/+$/u,"")}${r}`,{redirect:"error",signal:AbortSignal.timeout(5e3)});n=!0;let o=await i.json();if(i.ok&&o?.service==="skills-layer-api")return"ok"}catch{}return n?"backend_not_skills_layer":"backend_unreachable"}function BA(e){if(e===void 0)return 90;if(typeof e!="string"||!/^[1-9]\d*d$/iu.test(e.trim()))return null;let t=Number.parseInt(e.trim(),10);return Number.isSafeInteger(t)&&t<=365?t:null}function Gh(e){let t={...e};for(let n of["securityScore","scoreVector","publishedLedgerScore","effectiveBuyerTrustScore","scoreLabel"])delete t[n];for(let n of["securityPosture","trust","securityRuleSummary","ruleSummary"]){let r=t[n];if(r&&typeof r=="object"&&!Array.isArray(r)){let i=Gh(r);n==="trust"&&delete i.score,t[n]=i}}return t}import{spawn as NM}from"node:child_process";import{createHash as Me,createPublicKey as Yne,randomBytes as Ge}from"node:crypto";import{constants as CB}from"node:fs";import{access as FM,appendFile as Xne,chmod as Qne,lstat as Xu,mkdir as Mo,open as Uo,readdir as ere,readFile as Fi,realpath as Fu,rename as zo,rm as We,stat as Ja,writeFile as ZP}from"node:fs/promises";import{basename as ot,dirname as Be,join as K,posix as Lt,relative as Bu,resolve as qo,win32 as st}from"node:path";import{createInterface as BM}from"node:readline/promises";import{spawn as e6}from"node:child_process";import{createHash as aR}from"node:crypto";import{chmod as Yh,lstat as lR,mkdir as cR,open as t6,readFile as Qh,rename as n6,rm as Ui,writeFile as ud}from"node:fs/promises";import{dirname as Xh,posix as r6,win32 as i6}from"node:path";import{posix as jz,win32 as qA}from"node:path";var Nz="https://github.com/vercel-labs/skills#supported-agents",cd="2026-07-15",Xt=["codex","claude-code","cursor","opencode","amp","kimi-code-cli","replit","universal","antigravity","augment","openclaw","cline","warp","codebuddy","command-code","continue","cortex","crush","deepagents","droid","gemini-cli","github-copilot","goose","junie","iflow-cli","kilo","kiro-cli","kode","mcpjam","mistral-vibe","mux","openhands","pi","qoder","qwen-code","roo","trae","trae-cn","windsurf","zencoder","neovate","pochi","adal","aider-desk","antigravity-cli","astrbot","autohand-code","bob","dexto","loaf","zed","codearts-agent","codemaker","codestudio","devin","eve","firebender","forgecode","hermes-agent","inference-sh","jazz","lingma","moxby","ona","qoder-cn","reasonix","rovodev","tabnine-cli","terramind","tinycloud","zcode","zenflow","promptscript"];var Fz={"kimi-cli":"kimi-code-cli"},ad=[Y("codex","Codex",".codex",{capabilities:Ze({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),Y("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:Ze({allowedTools:!0,hooks:!0,forkedContext:!0})}),Y("cursor","Cursor",".cursor",{capabilities:Ze({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),Y("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:Ze({allowedTools:!0}),compatibleProjectSkillsRelativePaths:[".agents/skills"]}),yt("amp","Amp",".config/agents",{capabilities:Ze({allowedTools:!0})}),yt("kimi-code-cli","Kimi Code CLI",".agents",{legacyEnvVars:["KIMI_CLI_HOME"],legacyGlobalSkillsRelativePaths:[".config/agents/skills"]}),yt("replit","Replit",".config/agents"),yt("universal","Universal",".config/agents"),yt("antigravity","Antigravity",".gemini/antigravity",{capabilities:Ze({allowedTools:!0}),detectGlobal:!0}),Y("augment","Augment",".augment"),{id:"openclaw",displayName:"OpenClaw",envVar:"OPENCLAW_HOME",legacyEnvVars:[],capabilities:Ze({allowedTools:!0}),adapterRevision:cd,targets:{projectRootRelativePath:null,projectSkillsRelativePath:"skills",globalRootRelativePath:".openclaw",globalSkillsRelativePath:".openclaw/skills",projectCompatibleRelativePaths:[],projectLegacyRelativePaths:[],globalCompatibleRelativePaths:[],globalLegacyRelativePaths:[]},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:[".openclaw",".openclaw/skills"]}},yt("cline","Cline",".agents",{capabilities:Ze({allowedTools:!0,hooks:!0})}),yt("warp","Warp",".agents"),Y("codebuddy","CodeBuddy",".codebuddy",{capabilities:Ze({allowedTools:!0})}),Y("command-code","Command Code",".commandcode",{capabilities:Ze({allowedTools:!0})}),Y("continue","Continue",".continue"),Y("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),Y("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),yt("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),Y("droid","Droid",".factory"),yt("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),yt("github-copilot","GitHub Copilot",".copilot",{capabilities:Ze({allowedTools:!0}),detectGlobal:!0}),Y("goose","Goose",".goose",{globalRootRelativePath:".config/goose"}),Y("junie","Junie",".junie"),Y("iflow-cli","iFlow CLI",".iflow"),Y("kilo","Kilo Code",".kilocode"),Y("kiro-cli","Kiro CLI",".kiro"),Y("kode","Kode",".kode"),Y("mcpjam","MCPJam",".mcpjam"),Y("mistral-vibe","Mistral Vibe",".vibe"),Y("mux","Mux",".mux"),Y("openhands","OpenHands",".openhands",{capabilities:Ze({allowedTools:!0})}),Y("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:Ze({allowedTools:!0})}),Y("qoder","Qoder",".qoder",{capabilities:Ze({allowedTools:!0})}),Y("qwen-code","Qwen Code",".qwen"),Y("roo","Roo Code",".roo",{capabilities:Ze({allowedTools:!0})}),Y("trae","Trae",".trae",{detectProject:!1}),Y("trae-cn","Trae CN",".trae",{globalRootRelativePath:".trae-cn",detectProject:!1}),Y("windsurf","Windsurf",".windsurf",{globalRootRelativePath:".codeium/windsurf"}),Y("zencoder","Zencoder",".zencoder",{capabilities:Ze({allowedTools:!0})}),Y("neovate","Neovate",".neovate",{capabilities:Ze({allowedTools:!0})}),Y("pochi","Pochi",".pochi"),Y("adal","AdaL",".adal"),Y("aider-desk","AiderDesk",".aider-desk"),yt("antigravity-cli","Antigravity CLI",".gemini/antigravity-cli",{detectGlobal:!0}),Y("astrbot","AstrBot","data",{globalRootRelativePath:".astrbot",globalSkillsRelativePath:".astrbot/data/skills"}),Y("autohand-code","Autohand Code CLI",".autohand"),Y("bob","IBM Bob",".bob"),yt("dexto","Dexto",".agents"),yt("loaf","Loaf",".agents"),yt("zed","Zed",".agents"),Y("codearts-agent","CodeArts Agent",".codeartsdoer"),Y("codemaker","Codemaker",".codemaker"),Y("codestudio","Code Studio",".codestudio"),Y("devin","Devin for Terminal",".devin",{globalRootRelativePath:".config/devin"}),Y("eve","Eve","agent",{globalApplicable:!1}),yt("firebender","Firebender",".firebender",{detectGlobal:!0}),Y("forgecode","ForgeCode",".forge"),Y("hermes-agent","Hermes Agent",".hermes"),Y("inference-sh","inference.sh",".inferencesh"),Y("jazz","Jazz",".jazz"),Y("lingma","Lingma",".lingma"),Y("moxby","Moxby",".moxby"),Y("ona","Ona",".ona"),Y("qoder-cn","Qoder CN",".qoder",{globalRootRelativePath:".qoder-cn",detectProject:!1}),Y("reasonix","Reasonix",".reasonix"),Y("rovodev","Rovo Dev",".rovodev"),Y("tabnine-cli","Tabnine CLI",".tabnine/agent"),Y("terramind","Terramind",".terramind"),Y("tinycloud","Tinycloud",".tinycloud"),Y("zcode","ZCode",".zcode"),Y("zenflow","Zenflow",".zencoder",{detectProject:!1,detectGlobal:!1}),yt("promptscript","PromptScript",".agents",{globalApplicable:!1})];Uz(Xt,Fz);qz();function et(e=process.env,t=process.platform,n=process.cwd()){let r=HA(t),i=GA(e,t);return ad.map(o=>{let s=WA(o,e,r),a=o.targets.globalSkillsRelativePath!==null,l=a&&i&&o.targets.globalRootRelativePath?Yo(r,i,o.targets.globalRootRelativePath):null,c=a&&i&&o.targets.globalSkillsRelativePath?Yo(r,i,o.targets.globalSkillsRelativePath):null,u=o.targets.projectRootRelativePath?Yo(r,n,o.targets.projectRootRelativePath):null,d=a?s??l:null,p=Yo(r,n,o.targets.projectSkillsRelativePath),m=a?s?r.join(s,"skills"):c:null,h=od();return{id:o.id,displayName:o.displayName,envVar:o.envVar,capabilities:o.capabilities,detectionSources:[],targets:{projectRoot:u,projectSkillsPath:p,globalRoot:d,globalSkillsPath:m},installEvidence:h,adapterRevision:o.adapterRevision,pathContracts:{project:{status:"supported",preferredPath:p,preferredRelativePath:o.targets.projectSkillsRelativePath,compatibleReadOnlyPaths:sd(r,n,o.targets.projectCompatibleRelativePaths),legacyReadOnlyPaths:sd(r,n,o.targets.projectLegacyRelativePaths),evidence:od()},global:a?{status:"supported",preferredPath:m,preferredRelativePath:o.targets.globalSkillsRelativePath,compatibleReadOnlyPaths:i?sd(r,i,o.targets.globalCompatibleRelativePaths):[],legacyReadOnlyPaths:i?sd(r,i,o.targets.globalLegacyRelativePaths):[],evidence:od()}:{status:"not_applicable",preferredPath:null,preferredRelativePath:null,compatibleReadOnlyPaths:[],legacyReadOnlyPaths:[],evidence:od()}}}})}async function VA(e={}){let t=e.env??process.env,n=e.platform??process.platform,r=e.cwd??process.cwd(),i=HA(n),o=GA(t,n),s=et(t,n,r),a=e.pathExists??(async()=>!1);return(await Promise.all(s.map(async l=>{let c=Mz(l.id),u=[],d=WA(c,t,i);return(c.targets.globalSkillsRelativePath!==null&&d&&await a(d)||c.targets.globalSkillsRelativePath!==null&&d&&await a(i.join(d,"skills")))&&u.push("override"),c.detection.projectProbeRelativePaths.length>0&&await MA({basePath:r,relativePaths:c.detection.projectProbeRelativePaths,pathApi:i,pathExists:a})&&u.push("project"),o&&c.detection.globalProbeRelativePaths.length>0&&await MA({basePath:o,relativePaths:c.detection.globalProbeRelativePaths,pathApi:i,pathExists:a})&&u.push("global"),u.length===0?null:{...l,detectionSources:Bz(u)}}))).flatMap(l=>l?[l]:[])}function GA(e,t){return t==="win32"?ld(e.USERPROFILE,e.HOME):ld(e.HOME)}function HA(e){return e==="win32"?qA:jz}function ld(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Bz(e){return[...new Set(e)]}async function MA(e){for(let t of e.relativePaths)if(await e.pathExists(Yo(e.pathApi,e.basePath,t)))return!0;return!1}function Yo(e,t,n){return e.join(t,...n.split("/"))}function Y(e,t,n,r={}){let i=r.globalRootRelativePath??n,o=r.detectProject??!0,s=r.globalApplicable??!0,a=r.globalSkillsRelativePath??`${i}/skills`;return{id:e,displayName:t,envVar:r.envVar??KA(e),legacyEnvVars:r.legacyEnvVars??[],capabilities:r.capabilities??Ze(),adapterRevision:r.adapterRevision??cd,targets:{projectRootRelativePath:n,projectSkillsRelativePath:`${n}/skills`,globalRootRelativePath:s?i:null,globalSkillsRelativePath:s?a:null,projectCompatibleRelativePaths:r.compatibleProjectSkillsRelativePaths??[],projectLegacyRelativePaths:r.legacyProjectSkillsRelativePaths??[],globalCompatibleRelativePaths:r.compatibleGlobalSkillsRelativePaths??[],globalLegacyRelativePaths:r.legacyGlobalSkillsRelativePaths??[]},detection:{projectProbeRelativePaths:o?[n,`${n}/skills`]:[],globalProbeRelativePaths:s&&(r.detectGlobal??!0)?[i,a]:[]}}}function yt(e,t,n,r={}){let i=r.detectGlobal??!1,o=r.globalApplicable??!0;return{id:e,displayName:t,envVar:r.envVar??KA(e),legacyEnvVars:r.legacyEnvVars??[],capabilities:r.capabilities??Ze(),adapterRevision:r.adapterRevision??cd,targets:{projectRootRelativePath:".agents",projectSkillsRelativePath:".agents/skills",globalRootRelativePath:o?n:null,globalSkillsRelativePath:o?`${n}/skills`:null,projectCompatibleRelativePaths:r.compatibleProjectSkillsRelativePaths??[],projectLegacyRelativePaths:r.legacyProjectSkillsRelativePaths??[],globalCompatibleRelativePaths:r.compatibleGlobalSkillsRelativePaths??[],globalLegacyRelativePaths:r.legacyGlobalSkillsRelativePaths??[]},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:i&&o?[n,`${n}/skills`]:[]}}}function Ze(e={}){let t=["basic_skills"];return e.allowedTools&&t.push("allowed_tools"),e.hooks&&t.push("hooks"),e.forkedContext&&t.push("forked_context"),t.push("local_install"),t}function KA(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function Mz(e){return ad.find(t=>t.id===e)}function Uz(e,t){let n=new Set;for(let r of e){if(!UA(r))throw new Error(`Unsafe canonical agent id: ${JSON.stringify(r)}`);if(n.has(r))throw new Error(`Duplicate canonical agent id: ${r}`);n.add(r)}for(let r of Object.keys(t)){if(!UA(r))throw new Error(`Unsafe alias: ${JSON.stringify(r)}`);if(n.has(r))throw new Error(`Alias ${r} collides with a canonical agent id`);let i=new Set([r]),o=t[r];for(;!n.has(o);){if(i.has(o))throw new Error(`Agent alias cycle detected at ${o}`);i.add(o);let s=t[o];if(!s)throw new Error(`Agent alias ${r} has unknown target ${o}`);o=s}}}function UA(e){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)}function od(){return{sourceUrl:Nz,checkedAt:cd,state:"contract_tested",supportedPlatforms:["darwin","linux","win32"],hostVersion:null}}function sd(e,t,n){return n.map(r=>({path:Yo(e,t,r),relativePath:r,access:"read_only"}))}function WA(e,t,n){let r=[{envVar:e.envVar,value:ld(t[e.envVar])},...e.legacyEnvVars.map(i=>({envVar:i,value:ld(t[i])}))].filter(i=>i.value!==void 0);if(r.length>1&&new Set(r.map(o=>zz(n,o.value))).size>1)throw new Error(`Conflicting canonical and legacy overrides for ${e.id}: ${r.map(o=>o.envVar).join(", ")}`);return r[0]?.value}function zz(e,t){let n=e.normalize(t);return e===qA?n.toLowerCase():n}function qz(){let e=ad.map(t=>t.id);if(e.length!==Xt.length||e.some((t,n)=>t!==Xt[n]))throw new Error("Agent definitions must exactly match the canonical supported-agent inventory");for(let t of ad){if(!zA(t.targets.projectSkillsRelativePath))throw new Error(`Unsafe project path contract for ${t.id}`);let n=t.targets.globalSkillsRelativePath;if(n!==null&&!zA(n))throw new Error(`Unsafe global path contract for ${t.id}`);if(t.targets.globalRootRelativePath===null!=(n===null))throw new Error(`Inconsistent global path contract for ${t.id}`)}}function zA(e){return e.length>0&&!e.startsWith("/")&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t.length>0&&t!=="."&&t!=="..")}import{posix as Vz,win32 as Gz}from"node:path";var Hz="2026-10-25",Kz="2026-11-24",Hh={codex:{aliases:[],vendor:"OpenAI",productSurface:"Codex CLI and desktop"},vscode:{aliases:["code","visual-studio-code"],vendor:"Microsoft",productSurface:"Visual Studio Code MCP host"},"github-copilot-cli":{aliases:["copilot-cli"],vendor:"GitHub",productSurface:"GitHub Copilot CLI"},"claude-code":{aliases:[],vendor:"Anthropic",productSurface:"Claude Code"},cursor:{aliases:[],vendor:"Anysphere",productSurface:"Cursor"},cline:{aliases:[],vendor:"Cline",productSurface:"Cline extension"},"gemini-cli":{aliases:[],vendor:"Google",productSurface:"Gemini CLI"},windsurf:{aliases:[],vendor:"Cognition",productSurface:"Windsurf"},opencode:{aliases:[],vendor:"OpenCode",productSurface:"OpenCode CLI"},"kiro-cli":{aliases:[],vendor:"AWS",productSurface:"Kiro CLI"},kilo:{aliases:["kilo-code"],vendor:"Kilo Code",productSurface:"Kilo Code"},"qwen-code":{aliases:[],vendor:"Alibaba Cloud",productSurface:"Qwen Code"}},yr=[mn("codex","Codex","codex_toml",[],"https://developers.openai.com/codex/mcp/","Codex stores user MCP servers in its user config.",e=>he(e,Ee(e),".codex","config.toml")),mn("vscode","Visual Studio Code","json_servers",["github-copilot-chat"],"https://code.visualstudio.com/docs/agent-customization/mcp-servers","VS Code supports MCP servers in the user profile and through --add-mcp.",ZA,e=>[ZA(e),eR(e),...Yz(e),he(e,Ee(e),".vscode","extensions")]),mn("github-copilot-cli","GitHub Copilot CLI","json_copilot_mcp_servers",[],"https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-config-dir-reference","Copilot CLI stores user-level MCP definitions in ~/.copilot/mcp-config.json.",e=>he(e,hr(e.env?.COPILOT_HOME,he(e,Ee(e),".copilot")),"mcp-config.json")),mn("claude-code","Claude Code","json_mcp_servers",[],"https://docs.anthropic.com/en/docs/claude-code/mcp","Claude Code supports user-scoped MCP servers.",e=>he(e,Ee(e),".claude.json")),mn("cursor","Cursor","json_mcp_servers",[],"https://cursor.com/docs/mcp","Cursor supports a global ~/.cursor/mcp.json configuration.",e=>he(e,Ee(e),".cursor","mcp.json")),mn("cline","Cline","json_mcp_servers",[],"https://github.com/cline/cline/blob/main/docs/mcp/mcp-overview.mdx","Cline stores global MCP settings in its user data directory.",e=>he(e,Ee(e),".cline","data","settings","cline_mcp_settings.json")),mn("gemini-cli","Gemini CLI","json_mcp_servers",[],"https://google-gemini.github.io/gemini-cli/docs/tools/mcp-server.html","Gemini CLI reads user MCP servers from ~/.gemini/settings.json.",e=>he(e,Ee(e),".gemini","settings.json")),mn("windsurf","Windsurf","json_mcp_servers",[],"https://docs.windsurf.com/windsurf/cascade/mcp","Windsurf stores the user MCP configuration under ~/.codeium/windsurf.",e=>he(e,Ee(e),".codeium","windsurf","mcp_config.json")),mn("opencode","OpenCode","json_opencode_mcp",[],"https://opencode.ai/docs/mcp-servers/","OpenCode supports local MCP servers in its global configuration.",e=>he(e,Xo(e),"opencode","opencode.json")),mn("kiro-cli","Kiro CLI","json_mcp_servers",[],"https://kiro.dev/docs/mcp/configuration/","Kiro CLI supports a global MCP configuration under ~/.kiro/settings.",e=>he(e,Ee(e),".kiro","settings","mcp.json")),mn("kilo","Kilo Code","json_opencode_mcp",[],"https://kilo.ai/docs/automate/mcp/using-in-cli","Kilo Code supports MCP servers in its global configuration.",e=>he(e,Xo(e),"kilo","kilo.json")),mn("qwen-code","Qwen Code","json_mcp_servers",[],"https://qwenlm.github.io/qwen-code-docs/en/users/features/mcp/","Qwen Code reads user MCP servers from ~/.qwen/settings.json.",e=>he(e,Ee(e),".qwen","settings.json"))],JA=new Map(yr.map(e=>[e.id,e])),Wz=new Map([["code","vscode"],["visual-studio-code","vscode"],["copilot-cli","github-copilot-cli"]]),Zz=new Map([["github-copilot","vscode"],["github-copilot-chat","vscode"]]);function nl(e){let t=e.trim().toLowerCase(),n=Wz.get(t)??(JA.has(t)?t:null);if(n)return{status:"host",hostId:n};let r=Zz.get(t);return r?{status:"consumer",consumerId:t==="github-copilot"?"github-copilot-chat":t,hostId:r}:{status:"unknown",requestedClient:e}}function Kh(e){return JA.get(e)}function YA(e){let t=yr.filter(n=>Date.parse(`${n.evidence.reviewAfter}T23:59:59.999Z`)<Date.parse(e));return{evidenceStale:t.length>0,warnings:t.length>0?[`MCP compatibility evidence is due for review: ${t.map(n=>n.id).join(", ")}. Update the CLI if a host connection fails.`]:[]}}function XA(e){if(e==="universal")return{installAgentId:e,classification:"skills_only",hostId:null};let t=nl(e);return t.status==="host"?{installAgentId:e,classification:"host",hostId:t.hostId}:t.status==="consumer"?{installAgentId:e,classification:"consumer",hostId:t.hostId}:{installAgentId:e,classification:"unverified",hostId:null}}var Fce=Object.freeze([{id:"antigravity-cli",displayName:"Antigravity CLI",classification:"unverified",reason:"No fresh primary evidence in the Phase 126 evidence set proves a safe user-global automatic MCP lifecycle.",manualGuidance:"Do not mutate Antigravity configuration automatically; use its vendor documentation and request evidence review before promotion."}]);async function Wh(e){let t=[];for(let n of yr){let r=new Set([n.resolveConfigPath(e)]);n.id==="vscode"&&r.add(eR(e));let i=[...new Set(n.detectionPaths(e))],o=(await Promise.all(i.map(async m=>await e.pathExists(m)?m:null))).filter(m=>m!==null),s=await e.executableExists?.(n.id)??!1,a=o.map(m=>({kind:r.has(m)?"config":Xz(m)?"application":"user_data",path:m}));s&&a.push({kind:"executable",path:n.id});let l=a.some(m=>m.kind==="config"),c=a.length>0,u=e.runningHostIds?.includes(n.id)??!1,p=l&&(e.staleConfigHostIds?.includes(n.id)??!1)?"stale":u?"running":l?"configured":c?"installed":"unavailable";t.push({hostId:n.id,displayName:n.displayName,state:p,installed:c,running:u,configured:l,consumers:n.consumers.map(m=>({id:m,detected:e.extensionIds?.includes("github.copilot-chat")??!1})),signals:a,reason:Qz(p,a)})}return t}async function QA(e){return(await Wh(e)).filter(n=>n.installed).map(n=>{let r=Kh(n.hostId);return{hostId:n.hostId,displayName:n.displayName,detected:!0,configured:n.configured,consumers:n.consumers.filter(i=>i.detected).map(i=>i.id),evidence:r.evidence,signals:n.signals.map(i=>({kind:i.kind==="config"?"config":"installation",path:i.path}))}})}function mn(e,t,n,r,i,o,s,a){return{id:e,displayName:t,aliases:[...Hh[e].aliases],vendor:Hh[e].vendor,productSurface:Hh[e].productSurface,classification:"global_automatic",scope:"user_global",supportedPlatforms:["darwin","linux","win32"],supportedVersions:e==="windsurf"?"Legacy Windsurf releases using ~/.codeium/windsurf; the renamed Devin Desktop configuration is not claimed by this adapter.":"vendor-supported release with the cited global MCP mechanism",transport:"stdio",configKind:n,consumers:r,caveats:{reload:"Open a fresh agent session or restart the host after registration changes.",trust:"The host launches the existing tokenless Skills Layer bridge; raw remote credentials are never written to host config.",enterprisePolicy:"Managed enterprise policy can prevent or override user configuration and must be checked by the operator.",remote:"User-global scope is local to the active OS, WSL distribution, SSH host, container, or Codespace.",workspace:"Normal setup never writes workspace or project MCP configuration."},evidence:{sourceUrl:i,checkedAt:Hz,reviewAfter:Kz,owner:"mcp-client-support-owner",statement:o},resolveConfigPath:s,detectionPaths:a??(l=>[s(l),Jz(e,l)])}}function Jz(e,t){if(e==="claude-code")return he(t,Ee(t),".claude");if(e==="github-copilot-cli")return hr(t.env?.COPILOT_HOME,he(t,Ee(t),".copilot"));if(e==="windsurf")return he(t,Ee(t),".codeium","windsurf");if(e==="opencode")return he(t,Xo(t),"opencode");if(e==="kiro-cli")return he(t,Ee(t),".kiro");if(e==="kilo")return he(t,Xo(t),"kilo");let n={codex:".codex",cursor:".cursor",cline:".cline","gemini-cli":".gemini","qwen-code":".qwen"};return he(t,Ee(t),n[e]??`.${e}`)}function ZA(e){let t=e.platform??process.platform;return t==="darwin"?he(e,Ee(e),"Library","Application Support","Code","User","mcp.json"):t==="win32"?he(e,hr(e.env?.APPDATA,Ee(e)),"Code","User","mcp.json"):he(e,Xo(e),"Code","User","mcp.json")}function eR(e){let t=e.platform??process.platform;return t==="darwin"?he(e,Ee(e),"Library","Application Support","Code - Insiders","User","mcp.json"):t==="win32"?he(e,hr(e.env?.APPDATA,Ee(e)),"Code - Insiders","User","mcp.json"):he(e,Xo(e),"Code - Insiders","User","mcp.json")}function Yz(e){let t=e.platform??process.platform;return t==="darwin"?["/Applications/Visual Studio Code.app","/Applications/Visual Studio Code - Insiders.app",he(e,Ee(e),"Applications","Visual Studio Code.app"),he(e,Ee(e),"Applications","Visual Studio Code - Insiders.app")]:t==="win32"?[he(e,hr(e.env?.LOCALAPPDATA,Ee(e)),"Programs","Microsoft VS Code"),he(e,hr(e.env?.LOCALAPPDATA,Ee(e)),"Programs","Microsoft VS Code Insiders"),he(e,hr(e.env?.ProgramFiles,"C:\\Program Files"),"Microsoft VS Code")]:["/usr/share/code","/usr/share/code-insiders","/var/lib/flatpak/app/com.visualstudio.code",he(e,Ee(e),".local","share","code")]}function Xz(e){return/(?:\.app$|\/Applications\/|\\Programs\\|\/usr\/share\/|\/var\/lib\/flatpak\/)/u.test(e)}function Qz(e,t){return e==="unavailable"?"No executable, application, user-data, or global configuration signal was found.":e==="stale"?"A global configuration exists but was marked stale by lifecycle inspection.":e==="running"?"The host is running and at least one installed or configured signal was found.":e==="configured"?"A verified user-global configuration file exists.":`Installed signals found: ${t.map(n=>n.kind).join(", ")}.`}function Ee(e){let t=e.platform??process.platform;return hr(t==="win32"?e.env?.USERPROFILE:e.env?.HOME,e.env?.HOME,e.cwd,process.cwd())}function Xo(e){return hr(e.env?.XDG_CONFIG_HOME,he(e,Ee(e),".config"))}function he(e,...t){return((e.platform??process.platform)==="win32"?Gz:Vz).join(...t)}function hr(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()??process.cwd()}if(new Set(yr.map(e=>e.id)).size!==yr.length)throw new Error("duplicate MCP host id");if(yr.some(e=>!e.evidence.sourceUrl.startsWith("https://")))throw new Error("automatic MCP hosts require primary HTTPS evidence");if(Xt.length!==73)throw new Error("MCP host registry must not mutate the skill-install inventory");var Zh=Object.freeze([Object.freeze({origin:"https://api.skills-layer.com",audience:"https://api.skills-layer.com/mcp",environment:"production"}),Object.freeze({origin:"https://skills-layer.com",audience:"https://skills-layer.com/mcp",environment:"production"}),Object.freeze({origin:"https://api.staging.findfigg.co.uk",audience:"https://api.staging.findfigg.co.uk/mcp",environment:"staging"}),Object.freeze({origin:"https://staging.findfigg.co.uk",audience:"https://staging.findfigg.co.uk/mcp",environment:"staging"}),Object.freeze({origin:"https://api.preprod.findfigg.co.uk",audience:"https://api.preprod.findfigg.co.uk/mcp",environment:"preproduction"}),Object.freeze({origin:"https://preprod.findfigg.co.uk",audience:"https://preprod.findfigg.co.uk/mcp",environment:"preproduction"})]),tR=Object.freeze(Zh.map(e=>e.origin)),nR=Object.freeze(Zh.map(e=>e.audience));function rR(e){return Zh.some(t=>t.origin===e)}var ey="skills-layer-local-broker";function o6(e){return`broker_${aR("sha256").update(`skills-layer-mcp-broker-v1\0${e}`).digest("hex").slice(0,32)}`}var Bt="skills-layer",s6="2025-06-18",a6=["mcp","skills-layer-mcp-proxy.mjs"],l6=["mcp","skills-layer-mcp-broker.mjs"],c6=["mcp","skills-layer-mcp-broker.lock"],u6=new Set(["universal"]);function es(e){let t=YA(e.now),n=e.platform??process.platform,r=e.cwd??process.cwd(),i=e.stateDir??w6(e.env,n),o=e.mcpConfigPath??rl(n,i,"mcp.json"),s=rl(n,i,...a6),a=rl(n,i,...l6),l=zi(o).slice(0,32),c=n==="win32"?`\\\\.\\pipe\\skills-layer-mcp-${l}`:rl(n,"/tmp",`skills-layer-mcp-${l}.sock`),u=rl(n,i,...c6),d=e.nodePath??process.execPath,p=uR({mcpConfigPath:o}),m=(e.brokerSourceBuilder??dR)({mcpConfigPath:o,socketPath:c,lockPath:u}),h=zi(p),g=zi(m),y=new Set(yr.map(w=>w.id)),b=[...yr.map(w=>w.id),...Xt.filter(w=>!y.has(w))].map(w=>{if(y.has(w)){let C=Kh(w),P=C.resolveConfigPath({env:e.env,platform:n,cwd:r});return d6({agentId:w,displayName:C.displayName,configPath:P,configKind:C.configKind,bridgePath:s,brokerPath:a,brokerSocketPath:c,brokerLockPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:h,brokerChecksum:g,brokerSourceBuilder:e.brokerSourceBuilder})}if(u6.has(w))return oR({agentId:w,displayName:w,tier:"tier_3",status:"skills_only",verification:"skills_only",reason:"This agent is currently supported through Skills Layer skill files, not MCP auto-install.",instructions:[`Install skills for ${w} with \`skills-layer install <skill> --agent ${w}\`.`,"MCP auto-install is not claimed for this agent yet."]});let _=XA(w);return oR({agentId:w,displayName:w,tier:"tier_2",status:"manual_handoff",verification:"manual",reason:_.classification==="consumer"?`This install target consumes MCP through ${_.hostId}; configure that host instead.`:"MCP support or the safe writable global config shape has not been verified yet.",instructions:[`Add a local stdio MCP server named ${Bt}.`,`Command: ${d}`,`Args: ${s}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{...t,status:"mcp_registration_plan",serverName:Bt,mcpUrl:e.mcpUrl,bearerTokenEnvVar:e.bearerTokenEnvVar,clientId:e.clientId,environment:e.environment,generatedAt:e.now,bridgePath:s,brokerPath:a,brokerSocketPath:c,brokerLockPath:u,nodePath:d,mcpConfigPath:o,bridgeChecksum:h,brokerChecksum:g,automaticCount:b.filter(w=>w.status==="automatic").length,manualCount:b.filter(w=>w.status==="manual_handoff").length,skillsOnlyCount:b.filter(w=>w.status==="skills_only").length,unsupportedCount:b.filter(w=>w.status==="unsupported").length,targets:b}}async function qi(e){let t=es(e),n=b6(e.clientId),r=t.targets.find(y=>y.agentId===n),i=e.mcpConfig??await il(t.mcpConfigPath,{allowMissing:!0});if(!i)return iR({plan:t,target:r,mcpConfig:null,tokenConfig:null,tokenPresent:!1,tokenRefPresent:!1,bridgeExists:!1,checksumMatches:!1,brokerExists:!1,brokerChecksumMatches:!1,brokerInstalledChecksum:null,targetConfigured:!1,rawTokenLeaked:!1});let o=await Qo(t.bridgePath),s=o!==null,a=o!==null&&zi(o)===t.bridgeChecksum,l=await Qo(t.brokerPath),c=l!==null,u=l===null?null:zi(l),d=u===t.brokerChecksum,p=_6(i,r.agentId),m=Ct(p,"token"),h=Ct(p,"tokenRef"),g=await h6(r,m);return iR({plan:t,target:r,mcpConfig:i,tokenConfig:p,tokenPresent:!!m,tokenRefPresent:!!h,bridgeExists:s,checksumMatches:a,brokerExists:c,brokerChecksumMatches:d,brokerInstalledChecksum:u,targetConfigured:g.configured,rawTokenLeaked:g.rawTokenLeaked})}function uR(e){return`#!/usr/bin/env node
|
|
148
148
|
import { spawn } from "node:child_process";
|
|
149
149
|
import { randomBytes } from "node:crypto";
|
|
150
150
|
import { createConnection } from "node:net";
|
|
@@ -689,7 +689,7 @@ process.once("SIGINT", () => server.close(() => void cleanup().finally(() => pro
|
|
|
689
689
|
`).trimEnd()}function mR(e){let t=e.split(/\r?\n/u),n=[],r=!1;for(let i of t){if(i.trim()==="[mcp_servers.skills-layer]"){r=!0;continue}r&&/^\s*\[.+\]\s*$/u.test(i)&&(r=!1),r||n.push(i)}return n.join(`
|
|
690
690
|
`).trimEnd()}async function dd(e,t){await cR(Xh(e),{recursive:!0,mode:448});let n=await lR(e).catch(a=>{if(a.code==="ENOENT")return null;throw a});if(n?.isSymbolicLink())throw new Error(`mcp_config_symlink_rejected: ${e}`);let r=`${e}.skills-layer.lock`,i=`${e}.skills-layer-stage-${process.pid}`,o=`${e}.skills-layer-backup`,s;try{s=await t6(r,"wx",384)}catch(a){throw a.code==="EEXIST"?new Error(`mcp_config_locked: ${e}`):a}try{n?.isFile()&&(await ud(o,await Qh(e),{mode:384}),await Yh(o,384)),await Ui(i,{force:!0}),await ud(i,t,{encoding:"utf8",flag:"wx",mode:384}),await n6(i,e),await Yh(e,384)}finally{await s.close(),await Promise.all([Ui(i,{force:!0}),Ui(r,{force:!0})])}}async function sy(e){if((await lR(e).catch(n=>{if(n.code==="ENOENT")return null;throw n}))?.isSymbolicLink())throw new Error(`mcp_config_symlink_rejected: ${e}`)}async function il(e,t){try{let n=JSON.parse(await Qh(e,"utf8"));return vt(n)?n:{}}catch(n){if(t.allowMissing&&n.code==="ENOENT")return null;throw n}}async function Qo(e){try{return await Qh(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Jh(e,t){try{await Yh(e,t)}catch{}}async function ay(e){await Ui(e,{force:!0})}async function ly(e,t,n=`${t}.lock`){let r=t.startsWith("\\\\.\\pipe\\")?Promise.resolve():Ui(t,{force:!0});await Promise.all([Ui(e,{force:!0}),r,Ui(n,{force:!0})])}function k6(e){return e?new Promise(t=>{let n="";e.on("data",r=>{n+=String(r);let i=n.indexOf(`
|
|
691
691
|
`);i>=0&&t({ok:!0,line:n.slice(0,i)})}),e.on("error",r=>{t({ok:!1,message:r instanceof Error?r.message:"MCP bridge stdout failed."})}),e.on("end",()=>{t({ok:!1,message:"MCP bridge exited before returning a response."})})}):Promise.resolve({ok:!1,message:"MCP bridge stdout was not available."})}function w6(e,t){let n=gR(t),r=e??process.env,i=t==="win32"?sR(r.APPDATA,r.USERPROFILE,r.HOME):sR(r.XDG_CONFIG_HOME,r.HOME?n.join(r.HOME,".skills-layer"):void 0);return i?t==="win32"||r.XDG_CONFIG_HOME?.trim()?n.join(i,"skills-layer"):i:n.join(process.cwd(),".skills-layer")}function b6(e){let t=nl(e);if(t.status==="unknown")throw new Error(`unknown MCP host: ${e}`);return t.hostId}function _6(e,t){let n=e.tokens;return vt(n)&&vt(n[t])?n[t]:e}function S6(e){if(!e)return[];let t=e.clientIds;if(Array.isArray(t))return t.filter(i=>typeof i=="string"&&i.trim().length>0);let n=e.tokens;if(vt(n))return Object.keys(n);let r=Ct(e,"clientId");return r?[r]:[]}function rl(e,...t){return gR(e).join(...t)}function gR(e){return e==="win32"?i6:r6}function sR(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Ct(e,t){let n=e?.[t];return typeof n=="string"&&n.trim().length>0?n:null}function zi(e){return aR("sha256").update(e).digest("hex")}function vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{chmod as hR,lstat as kR,mkdir as x6,open as C6,readFile as uy,rename as I6,rm as cy,writeFile as yR}from"node:fs/promises";import{dirname as P6,join as vR}from"node:path";var A6=[{hostId:"claude-code",relativePath:".mcp.json",containerKey:"mcpServers"},{hostId:"cursor",relativePath:".cursor/mcp.json",containerKey:"mcpServers"},{hostId:"cline",relativePath:".cline/mcp.json",containerKey:"mcpServers"},{hostId:"gemini-cli",relativePath:".gemini/settings.json",containerKey:"mcpServers"},{hostId:"windsurf",relativePath:".windsurf/mcp.json",containerKey:"mcpServers"}];async function wR(e){let t=vR(e.stateDir,"mcp","skills-layer-mcp-proxy.mjs"),n=[];for(let r of A6){let i=vR(e.projectRoot,r.relativePath),o=await kR(i).catch(u=>{if(u.code==="ENOENT")return null;throw u});if(!o){n.push(ol(r,i,"absent","No legacy project configuration file exists.",t,e.nodePath));continue}if(o.isSymbolicLink()||!o.isFile()){n.push(ol(r,i,"ambiguous","The legacy target is not a regular owned file and was left unchanged.",t,e.nodePath));continue}let s;try{let u=JSON.parse(await uy(i,"utf8"));if(!sl(u))throw new Error("not an object");s=u}catch{n.push(ol(r,i,"malformed","The legacy project configuration is not a JSON object and was left unchanged.",t,e.nodePath));continue}let a=s[r.containerKey],l=sl(a)?a["skills-layer"]:void 0;if(l===void 0){n.push(ol(r,i,"absent","No Skills Layer project registration exists in this file.",t,e.nodePath));continue}let c=_R(l,e.nodePath,t,r.hostId)?"owned":"ambiguous";n.push(ol(r,i,c,c==="owned"?"An exact legacy Skills Layer project registration was found.":"A Skills Layer-named entry exists but exact ownership could not be proved.",t,e.nodePath))}return n}async function bR(e){let t=new Set(e.verifiedGlobalHostIds),n=e.discovery.filter(o=>o.status==="owned"&&t.has(o.hostId)),r=e.discovery.filter(o=>o.status!=="absent"&&!n.includes(o)).map(o=>({configPath:o.configPath,hostId:o.hostId,reason:o.status==="owned"?"The replacement global registration is not verified.":o.reason}));if(!e.apply)return{applied:!1,plannedPaths:n.map(o=>o.configPath),cleanedPaths:[],skipped:r};let i=[];for(let o of n){let s=await kR(o.configPath);if(s.isSymbolicLink()||!s.isFile()){r.push({configPath:o.configPath,hostId:o.hostId,reason:"The target changed after discovery and is no longer a regular file."});continue}let a=JSON.parse(await uy(o.configPath,"utf8"));if(!sl(a)||!sl(a[o.containerKey])){r.push({configPath:o.configPath,hostId:o.hostId,reason:"The target changed after discovery and no longer has the expected container."});continue}let l=a[o.containerKey];if(!_R(l["skills-layer"],o.nodePath,o.bridgePath,o.hostId)){r.push({configPath:o.configPath,hostId:o.hostId,reason:"Ownership no longer matches the discovery receipt."});continue}let c={...l};delete c["skills-layer"],await R6(o.configPath,JSON.stringify({...a,[o.containerKey]:c},null,2)+`
|
|
692
|
-
`),i.push(o.configPath)}return{applied:!0,plannedPaths:n.map(o=>o.configPath),cleanedPaths:i,skipped:r}}function _R(e,t,n,r){return!sl(e)||e.command!==t||!Array.isArray(e.args)?!1:e.args[0]===n&&(e.args.length===1||e.args.length===3&&e.args[1]==="--client"&&e.args[2]===r)}async function R6(e,t){await x6(P6(e),{recursive:!0,mode:448});let n=e+".skills-layer-migration.lock",r=e+`.skills-layer-migration-stage-${process.pid}`,i=e+".skills-layer-migration-backup",o=await C6(n,"wx",384).catch(s=>{throw s.code==="EEXIST"?new Error(`mcp_legacy_migration_locked: ${e}`):s});try{await yR(i,await uy(e),{mode:384}),await hR(i,384),await cy(r,{force:!0}),await yR(r,t,{encoding:"utf8",flag:"wx",mode:384}),await I6(r,e),await hR(e,384)}finally{await o.close(),await Promise.all([cy(r,{force:!0}),cy(n,{force:!0})])}}function ol(e,t,n,r,i,o){return{hostId:e.hostId,configPath:t,containerKey:e.containerKey,status:n,reason:r,bridgePath:i,nodePath:o}}function sl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{createHmac as lq,sign as rue,timingSafeEqual as cq,verify as uq}from"node:crypto";import{createHash as E6}from"node:crypto";import{posix as AR,win32 as RR}from"node:path";var Qt=Object.freeze({codex:"codex-pre-tool-use-v4-2026-10-01","claude-code":"claude-code-pre-tool-use-v2-2026-10-01",cline:"cline-pre-tool-use-v2-2026-10-01","gemini-cli":"gemini-cli-before-tool-v2-2026-10-01",cursor:"cursor-pre-tool-use-v2-2026-10-01","github-copilot":"github-copilot-pre-tool-use-v2-2026-10-01",opencode:"opencode-tool-execute-before-v2-2026-10-01",windsurf:"windsurf-cascade-pre-action-v2-2026-10-01",antigravity:"antigravity-pre-tool-use-v2-2026-10-01","antigravity-cli":"antigravity-cli-pre-tool-use-v2-2026-10-01","kiro-cli":"kiro-cli-pre-tool-use-v2-2026-10-01"}),SR=256*1024,$6=16,D6=4096,T6=1024,O6=512,ll=65536,kt=4096,L6=1024,ER=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,j6=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,N6=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,F6=new Set(["__proto__","constructor","prototype"]),xR=Object.freeze({codex:Object.freeze({agentId:"codex",adapterRevision:Qt.codex,eventName:"PreToolUse",sourceUrl:"https://learn.chatgpt.com/docs/hooks",sourceCheckedAt:"2026-10-01",blockingContract:"hookSpecificOutput.permissionDecision=deny; malformed hook output fails open"}),"claude-code":Object.freeze({agentId:"claude-code",adapterRevision:Qt["claude-code"],eventName:"PreToolUse",sourceUrl:"https://code.claude.com/docs/en/hooks",sourceCheckedAt:"2026-07-16",blockingContract:"hookSpecificOutput.permissionDecision=deny or command exit 2"}),cline:Object.freeze({agentId:"cline",adapterRevision:Qt.cline,eventName:"PreToolUse",sourceUrl:"https://docs.cline.bot/customization/hooks",sourceCheckedAt:"2026-07-16",blockingContract:"cancel=true"}),"gemini-cli":Object.freeze({agentId:"gemini-cli",adapterRevision:Qt["gemini-cli"],eventName:"BeforeTool",sourceUrl:"https://geminicli.com/docs/hooks/reference/",sourceCheckedAt:"2026-09-25",blockingContract:"decision=deny or command exit 2"}),cursor:Object.freeze({agentId:"cursor",adapterRevision:Qt.cursor,eventName:"preToolUse",sourceUrl:"https://cursor.com/docs/hooks",sourceCheckedAt:"2026-09-25",blockingContract:"permission=deny with failClosed=true"}),"github-copilot":Object.freeze({agentId:"github-copilot",adapterRevision:Qt["github-copilot"],eventName:"PreToolUse",sourceUrl:"https://docs.github.com/en/copilot/reference/hooks-reference",sourceCheckedAt:"2026-09-25",blockingContract:"non-zero exit denies, but command-hook timeout fails open"}),opencode:Object.freeze({agentId:"opencode",adapterRevision:Qt.opencode,eventName:"tool.execute.before",sourceUrl:"https://opencode.ai/docs/plugins/",sourceCheckedAt:"2026-09-25",blockingContract:"plugin tool.execute.before throws before tool execution"}),windsurf:Object.freeze({agentId:"windsurf",adapterRevision:Qt.windsurf,eventName:"pre_run_command",sourceUrl:"https://docs.windsurf.com/windsurf/cascade/hooks",sourceCheckedAt:"2026-09-25",blockingContract:"exit code 2 blocks supported Cascade pre-hooks"}),antigravity:Object.freeze({agentId:"antigravity",adapterRevision:Qt.antigravity,eventName:"PreToolUse",sourceUrl:"https://antigravity.google/docs/hooks?tab=ide",sourceCheckedAt:"2026-09-25",blockingContract:"decision=deny"}),"antigravity-cli":Object.freeze({agentId:"antigravity-cli",adapterRevision:Qt["antigravity-cli"],eventName:"PreToolUse",sourceUrl:"https://antigravity.google/docs/hooks?tab=cli",sourceCheckedAt:"2026-09-25",blockingContract:"decision=deny"}),"kiro-cli":Object.freeze({agentId:"kiro-cli",adapterRevision:Qt["kiro-cli"],eventName:"preToolUse",sourceUrl:"https://kiro.dev/docs/hooks/types/",sourceCheckedAt:"2026-09-25",blockingContract:"non-zero command exit blocks"})}),B6=new Set(["bash","exec_command","shell","shell_command","execute_command","run_shell_command","run_command","execute_bash"]),M6=new Set(["read","read_file","view","glob","grep","list_files","search_files","list_code_definition_names","view_file","fs_read"]),U6=new Set(["write","write_file","edit","create","apply_patch","notebookedit","write_to_file","replace_in_file","insert_content","replace","replace_file_content","multi_replace_file_content","fs_write"]),z6=new Set(["webfetch","websearch","web_fetch","web_search","google_web_search"]),q6=new Set(["browser","browser_action","computer"]),V6=new Set(["device","device_action","computer_use"]);function Gn(e){return Object.prototype.hasOwnProperty.call(xR,e)?xR[e]:null}function vr(e){return Gn(e)!==null}function $R(e){let t=Gn(e.agentId);if(!t)throw new Error(`No strict hook adapter is implemented for ${e.agentId}.`);oq(e.platform),TR(e.hostVersion,"host version"),al(e.expectedSessionId,"expected session id");let n=nq(e.attribution),r=rq(e.payload),i=e.agentId==="cline"?H6(r,e):e.agentId==="gemini-cli"?K6(r,e):e.agentId==="cursor"?W6(r,e):e.agentId==="github-copilot"?Z6(r,e):e.agentId==="opencode"?J6(r,e):e.agentId==="windsurf"?Y6(r,e):e.agentId==="antigravity"||e.agentId==="antigravity-cli"?X6(r,e):e.agentId==="kiro-cli"?Q6(r,e):G6(r,e),o=eq({agentId:e.agentId,platform:e.platform,cwd:i.cwd,toolName:i.toolName,toolInput:i.toolInput}),s=py(aq(i.toolInput)),a=py({actionVersion:1,actionFamily:o.actionFamily,command:o.command,cwdRealPath:i.cwd,fileTargets:Object.freeze(o.fileTargets),networkTargets:Object.freeze(o.networkTargets),toolName:i.toolName,toolInput:s,toolInputSha256:IR(ts(s)),host:Object.freeze({agentId:e.agentId,hostVersion:e.hostVersion,platform:e.platform,sessionId:i.sessionId,toolUseId:i.toolUseId}),skill:Object.freeze(n)});return Object.freeze({adapterRevision:t.adapterRevision,action:a,actionSha256:IR(ts(a))})}function ns(e,t){if(!Gn(e))throw new Error(`No strict hook adapter is implemented for ${e}.`);if(t.decision!=="allow"&&t.decision!=="deny")throw new Error("Strict hook decision must be allow or deny.");if(sq(t.reason,"decision reason",L6),e==="kiro-cli"||e==="opencode"||e==="windsurf"||e==="github-copilot")return Object.freeze(t.decision==="deny"?{exitCode:2,stdout:"",stderr:t.reason}:{exitCode:0,stdout:"",stderr:""});let n=e==="cline"?t.decision==="deny"?{cancel:!0,errorMessage:t.reason}:{cancel:!1}:e==="gemini-cli"||e==="antigravity"||e==="antigravity-cli"?{decision:t.decision,reason:t.reason}:e==="cursor"?{permission:t.decision,user_message:t.reason,agent_message:t.reason}:e==="codex"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t.decision,...t.decision==="deny"?{permissionDecisionReason:t.reason}:{}}}:{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t.decision,permissionDecisionReason:t.reason}};return Object.freeze({exitCode:0,stdout:JSON.stringify(n),stderr:""})}function G6(e,t){if(e.hook_event_name!=="PreToolUse")throw new Error("Strict host hook accepts only the PreToolUse event.");let n=ne(e.session_id,"hook session id",256);if(n!==t.expectedSessionId)throw new Error("Hook session does not match the bound session.");let r=kr(ne(e.cwd,"hook cwd",kt),t.platform),i=ne(e.tool_name,"hook tool name",256),o=ne(e.tool_use_id,"hook tool use id",256),s=Mt(e.tool_input,"hook tool input");return{sessionId:n,cwd:r,toolName:i,toolUseId:o,toolInput:s}}function H6(e,t){if(e.hookName!=="PreToolUse")throw new Error("Strict Cline hook accepts only the PreToolUse event.");let n=ne(e.taskId,"Cline task id",256);if(n!==t.expectedSessionId)throw new Error("Cline task does not match the bound session.");ne(e.clineVersion,"Cline version",128);let r=ne(e.timestamp,"Cline timestamp",32);if(!/^\d{13}$/u.test(r)||!Number.isFinite(Number(r)))throw new Error("Cline timestamp must be milliseconds since epoch encoded as a string.");ne(e.userId,"Cline user id",256);let i=Mt(e.model,"Cline model");if(ne(i.provider,"Cline model provider",256),ne(i.slug,"Cline model slug",256),!Array.isArray(e.workspaceRoots)||e.workspaceRoots.length===0||e.workspaceRoots.length>64)throw new Error("Cline workspaceRoots must contain between one and 64 paths.");let o=e.workspaceRoots.map(c=>kr(ne(c,"Cline workspace root",kt),t.platform)),s=Mt(e.preToolUse,"Cline preToolUse"),a=ne(s.tool,"Cline tool name",256),l=Mt(s.parameters,"Cline tool parameters");return{sessionId:n,cwd:o[0],toolName:a,toolUseId:null,toolInput:l}}function K6(e,t){if(e.hook_event_name!=="BeforeTool")throw new Error("Strict Gemini CLI hook accepts only the BeforeTool event.");let n=ne(e.session_id,"Gemini CLI session id",256);if(n!==t.expectedSessionId)throw new Error("Gemini CLI session does not match the bound session.");let r=kr(ne(e.cwd,"Gemini CLI cwd",kt),t.platform),i=ne(e.tool_name,"Gemini CLI tool name",256),o=Mt(e.tool_input,"Gemini CLI tool input"),s=fd(e.tool_use_id,"Gemini CLI tool use id");return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function W6(e,t){if(e.hook_event_name!=="preToolUse")throw new Error("Strict Cursor hook accepts only the preToolUse event.");let n=ne(e.conversation_id,"Cursor conversation id",256);if(n!==t.expectedSessionId)throw new Error("Cursor conversation does not match the bound session.");ne(e.cursor_version,"Cursor version",128);let r=DR(e.workspace_roots,"Cursor workspace roots",t.platform),i=typeof e.cwd=="string"?e.cwd:r[0],o=kr(ne(i,"Cursor cwd",kt),t.platform),s=ne(e.tool_name,"Cursor tool name",256),a=Mt(e.tool_input,"Cursor tool input"),l=fd(e.tool_use_id,"Cursor tool use id");return{sessionId:n,cwd:o,toolName:s,toolUseId:l,toolInput:a}}function Z6(e,t){if(e.hook_event_name!=="PreToolUse")throw new Error("Guardian accepts only GitHub Copilot's PascalCase PreToolUse event.");let n=ne(e.session_id,"GitHub Copilot session id",256);if(n!==t.expectedSessionId)throw new Error("GitHub Copilot session does not match the bound session.");let r=kr(ne(e.cwd,"GitHub Copilot cwd",kt),t.platform),i=ne(e.tool_name,"GitHub Copilot tool name",256),o=Mt(e.tool_input,"GitHub Copilot tool input");return{sessionId:n,cwd:r,toolName:i,toolUseId:null,toolInput:o}}function J6(e,t){if(e.hook_event_name!=="tool.execute.before")throw new Error("Strict OpenCode plugin accepts only the tool.execute.before event.");let n=ne(e.session_id,"OpenCode session id",256);if(n!==t.expectedSessionId)throw new Error("OpenCode session does not match the bound session.");let r=kr(ne(e.cwd,"OpenCode cwd",kt),t.platform),i=ne(e.tool_name,"OpenCode tool name",256),o=Mt(e.tool_input,"OpenCode tool input"),s=ne(e.call_id,"OpenCode call id",256);return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function Y6(e,t){let n=ne(e.agent_action_name,"Windsurf action name",128);if(!new Set(["pre_read_code","pre_write_code","pre_run_command","pre_mcp_tool_use"]).has(n))throw new Error("Guardian accepts only blocking Windsurf pre-action events.");let i=ne(e.trajectory_id,"Windsurf trajectory id",256);if(i!==t.expectedSessionId)throw new Error("Windsurf trajectory does not match the bound session.");let o=ne(e.execution_id,"Windsurf execution id",256),s=Mt(e.tool_info,"Windsurf tool info"),a=n==="pre_run_command"&&typeof s.cwd=="string"?s.cwd:e.cwd,l=kr(ne(a,"Windsurf cwd",kt),t.platform);if(n==="pre_read_code"||n==="pre_write_code"){let p=ne(s.file_path,"Windsurf file path",kt);return{sessionId:i,cwd:l,toolName:n==="pre_read_code"?"read_file":"write_file",toolUseId:o,toolInput:{path:p}}}if(n==="pre_run_command")return{sessionId:i,cwd:l,toolName:"shell_command",toolUseId:o,toolInput:{command:ne(s.command_line,"Windsurf command",ll)}};let c=ne(s.mcp_server_name,"Windsurf MCP server",256),u=ne(s.mcp_tool_name,"Windsurf MCP tool",256),d=Mt(s.mcp_tool_arguments,"Windsurf MCP arguments");return{sessionId:i,cwd:l,toolName:`mcp__${c}__${u}`,toolUseId:o,toolInput:d}}function X6(e,t){if(e.hook_event_name!==void 0&&e.hook_event_name!=="PreToolUse")throw new Error("Strict Antigravity hook accepts only the PreToolUse event.");let n=ne(e.conversationId,"Antigravity conversation id",256);if(n!==t.expectedSessionId)throw new Error("Antigravity conversation does not match the bound session.");let r=DR(e.workspacePaths,"Antigravity workspace paths",t.platform),i=Mt(e.toolCall,"Antigravity tool call"),o=ne(i.name,"Antigravity tool name",256),s=Mt(i.args,"Antigravity tool arguments"),a=fd(i.id,"Antigravity tool call id");return{sessionId:n,cwd:r[0],toolName:o,toolUseId:a,toolInput:s}}function Q6(e,t){if(e.hook_event_name!=="preToolUse")throw new Error("Strict Kiro hook accepts only the preToolUse event.");let n=ne(e.session_id,"Kiro session id",256);if(n!==t.expectedSessionId)throw new Error("Kiro session does not match the bound session.");let r=kr(ne(e.cwd,"Kiro cwd",kt),t.platform),i=ne(e.tool_name,"Kiro tool name",256),o=Mt(e.tool_input,"Kiro tool input"),s=fd(e.tool_use_id,"Kiro tool use id");return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function eq(e){let t=e.toolName.toLowerCase();if(B6.has(t)){let n=e.toolInput.command??e.toolInput.cmd??e.toolInput.CommandLine,r=ne(n,`${e.toolName} command`,ll);if(r.trim().length===0)throw new Error(`${e.toolName} command cannot be empty.`);return{actionFamily:"shell_execution",command:r,fileTargets:[],networkTargets:[]}}if(M6.has(t)){let n=dy(e.toolInput,e.cwd,e.platform);return n.length===0&&n.push(e.cwd),{actionFamily:"filesystem_read",command:null,fileTargets:PR(n),networkTargets:[]}}if(U6.has(t)){let n=t==="apply_patch"?tq(e.toolInput,e.cwd,e.platform):dy(e.toolInput,e.cwd,e.platform);if(n.length===0)throw new Error(`${e.toolName} has no complete file target for strict mapping.`);return{actionFamily:"filesystem_write",command:null,fileTargets:PR(n),networkTargets:[]}}if(z6.has(t)){let n=e.toolInput.url,r=e.toolInput.query;if(t==="webfetch"||t==="web_fetch"){let i=LR(ne(n,`${e.toolName} URL`,kt));return{actionFamily:"network_access",command:null,fileTargets:[],networkTargets:[i]}}return ne(r,`${e.toolName} query`,ll),{actionFamily:"network_access",command:null,fileTargets:[],networkTargets:[]}}if(q6.has(t)||t.startsWith("browser__"))return{actionFamily:"browser_access",command:null,fileTargets:[],networkTargets:CR(e.toolInput)};if(V6.has(t))return{actionFamily:"device_control",command:null,fileTargets:[],networkTargets:[]};if(t==="use_aws"||t.startsWith("@")||t.startsWith("mcp__")||t.startsWith("mcp."))return{actionFamily:"api_access",command:null,fileTargets:dy(e.toolInput,e.cwd,e.platform),networkTargets:CR(e.toolInput)};throw new Error(`Tool ${e.toolName} has no strict mapping for ${e.agentId}.`)}function dy(e,t,n){let r=[],i=["file_path","path","notebook_path","directory","target_path","old_path","new_path","AbsolutePath"];for(let o of i)e[o]!==void 0&&r.push(ne(e[o],`${o} path`,kt));if(e.paths!==void 0){if(!Array.isArray(e.paths)||e.paths.length>64)throw new Error("Tool paths must be an array with no more than 64 entries.");for(let o of e.paths)r.push(ne(o,"tool path",kt))}return r.map(o=>OR(o,t,n))}function tq(e,t,n){let r=ne(e.patch??e.command,"apply_patch payload",ll),i=[];for(let o of r.split(/\r?\n/u)){if(!o.startsWith("*** ")||o==="*** Begin Patch"||o==="*** End Patch")continue;let s=/^(?:\*\*\* (?:Add|Update|Delete) File: |\*\*\* Move to: )(.*)$/u.exec(o);if(!s)throw new Error(`apply_patch contains an unsupported file directive: ${o}`);let a=s[1]?.trim();if(!a)throw new Error("apply_patch contains an empty file target.");i.push(OR(a,t,n))}if(i.length===0)throw new Error("apply_patch payload has no recognized file targets.");return i}function CR(e){return e.url===void 0?[]:[LR(ne(e.url,"tool URL",kt))]}function nq(e){if(!e||typeof e!="object")throw new Error("Strict hook attribution is required.");if(!N6.test(e.skillSlug))throw new Error("Strict hook attribution skill slug is invalid.");return TR(e.version,"attribution version"),al(e.generationId,"attribution generation id"),al(e.actorId,"attribution actor id"),al(e.tenantId,"attribution tenant id"),e.workspaceId!==void 0&&al(e.workspaceId,"attribution workspace id"),{skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,actorId:e.actorId,tenantId:e.tenantId,...e.workspaceId===void 0?{}:{workspaceId:e.workspaceId}}}function rq(e){let t=e;if(typeof e=="string"){if(Buffer.byteLength(e,"utf8")>SR)throw new Error("Host hook payload exceeds the maximum 256 KiB size.");try{t=JSON.parse(e)}catch{throw new Error("Host hook payload must be valid JSON.")}}iq(t);let n=ts(t);if(Buffer.byteLength(n,"utf8")>SR)throw new Error("Host hook payload exceeds the maximum 256 KiB size.");return Mt(t,"host hook payload")}function iq(e){let t=0,n=new Set,r=(i,o)=>{if(t+=1,t>D6)throw new Error("Host hook JSON contains too many values.");if(o>$6)throw new Error("Host hook JSON exceeds the maximum depth.");if(!(i===null||typeof i=="boolean")){if(typeof i=="string"){if(i.length>ll)throw new Error("Host hook JSON string is too long.");if(i.includes("\0"))throw new Error("Host hook JSON cannot contain NUL characters.");return}if(typeof i=="number"){if(!Number.isFinite(i))throw new Error("Host hook JSON numbers must be finite.");return}if(typeof i!="object")throw new Error("Host hook payload must contain JSON-compatible values only.");if(n.has(i))throw new Error("Host hook payload cannot contain cyclic objects.");if(n.add(i),Array.isArray(i)){if(i.length>T6)throw new Error("Host hook JSON array is too large.");for(let s of i)r(s,o+1)}else{let s=Object.getPrototypeOf(i);if(s!==Object.prototype&&s!==null)throw new Error("Host hook JSON objects must use a plain object prototype.");let a=Object.entries(i);if(a.length>O6)throw new Error("Host hook JSON object has too many keys.");for(let[l,c]of a){if(F6.has(l))throw new Error(`Host hook JSON contains unsafe key ${l}.`);if(l.length===0||l.length>256)throw new Error("Host hook JSON key length is invalid.");r(c,o+1)}}n.delete(i)}};r(e,0)}function Mt(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object.`);return e}function ne(e,t,n){if(typeof e!="string"||e.length===0||e.length>n||e.includes("\0"))throw new Error(`${t} must be a non-empty bounded string.`);return e}function fd(e,t){if(e==null)return null;let n=ne(e,t,256);if(!ER.test(n))throw new Error(`${t} is invalid.`);return n}function DR(e,t,n){if(!Array.isArray(e)||e.length===0||e.length>64)throw new Error(`${t} must contain between one and 64 paths.`);return e.map(r=>kr(ne(r,t,kt),n))}function al(e,t){if(typeof e!="string"||!ER.test(e))throw new Error(`${t} is invalid.`)}function TR(e,t){if(typeof e!="string"||!j6.test(e))throw new Error(`${t} is invalid.`)}function oq(e){if(e!=="darwin"&&e!=="linux"&&e!=="win32")throw new Error("Strict hook platform is unsupported.")}function sq(e,t,n){if(typeof e!="string"||e.trim().length===0||e.length>n||/[\u0000\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(e))throw new Error(`${t} is invalid.`)}function kr(e,t){if(e.length>kt||e.includes("\0"))throw new Error("Hook path is invalid.");let n=t==="win32"?RR:AR;if(!n.isAbsolute(e))throw new Error(`Hook path must be absolute for ${t}.`);return n.normalize(e)}function OR(e,t,n){let r=n==="win32"?RR:AR;if(e.length>kt||e.includes("\0"))throw new Error("Tool path is invalid.");return r.normalize(r.isAbsolute(e)?e:r.resolve(t,e))}function LR(e){let t;try{t=new URL(e)}catch{throw new Error("Network target must be a valid absolute URL.")}if(t.protocol!=="https:"&&t.protocol!=="http:"||t.username||t.password)throw new Error("Network target must be an HTTP(S) URL without embedded credentials.");return t.hash="",t.toString()}function aq(e){return JSON.parse(ts(e))}function py(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))py(t)}return e}function ts(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(n=>ts(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${ts(t[n])}`).join(",")}}`}function IR(e){return`sha256:${E6("sha256").update(e).digest("hex")}`}function PR(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}var dq=32,pq=1024,fq=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,jR=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,mq=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,gq=/^hmac-sha256:[a-f0-9]{64}$/u,hq=/^ed25519:[A-Za-z0-9_-]{86}$/u,yq=/^(?:sha256:)?[a-f0-9]{64}$/u,vq=/^[a-f0-9]{64}$/u,NR=Object.freeze({disabled:0,warning:1,enforce:2});function ul(e){let t=e.envelope;if(!t||typeof t!="object"||t.version!==1&&t.version!==2)throw new Error("Guardian attribution envelope version is invalid.");if(t.version===2){if(t.algorithm!=="ed25519"||t.issuer!=="skills-layer-cloud"||!hq.test(t.signature))throw new Error("Guardian attribution signature is invalid.");Ur(t.keyId,"Guardian attribution key id");let s=e.publicKeys?.[t.keyId];if(!s)throw new Error("Guardian attribution key is unknown.");let a=kq(t.claims),l={version:2,algorithm:"ed25519",keyId:t.keyId,issuer:t.issuer,claims:a},c=Buffer.from(t.signature.slice(8),"base64url");if(!uq(null,Buffer.from(md(l),"utf8"),s,c))throw new Error("Guardian attribution signature verification failed.");return FR(a,e)}if(!e.key)throw new Error("Guardian attribution key is required.");if(_q(e.key),Ur(t.keyId,"Guardian attribution key id"),typeof t.signature!="string"||!gq.test(t.signature))throw new Error("Guardian attribution signature is invalid.");let n=MR(t.claims),r=bq({version:1,keyId:t.keyId,claims:n},e.key),i=Buffer.from(t.signature.slice(12),"hex"),o=Buffer.from(r.slice(12),"hex");if(i.byteLength!==o.byteLength||!cq(i,o))throw new Error("Guardian attribution signature verification failed.");return FR(n,e)}async function fy(e){try{if(!e.attributionEnvelope||!e.attributionKey&&!e.attributionPublicKeys)throw new Error("Signed Guardian attribution is required.");let t=ul({...e.attributionKey?{key:e.attributionKey}:{},...e.attributionPublicKeys?{publicKeys:e.attributionPublicKeys}:{},envelope:e.attributionEnvelope,expectedAgentId:e.agentId,expectedPlatform:e.platform,now:e.now}),n=$R({agentId:e.agentId,platform:e.platform,hostVersion:e.hostVersion,expectedSessionId:t.sessionId,attribution:t,payload:e.rawPayload});if(wq(t.requestedMode,t.workspaceRequiredMode)==="disabled")return ns(e.agentId,{decision:"allow",reason:"Guardian is disabled for this personal skill session."});let i=await e.evaluate(n);return Sq(i),ns(e.agentId,{decision:i.decision,reason:UR(i.reason)})}catch{return ns(e.agentId,{decision:"deny",reason:"Guardian could not verify this action."})}}function MR(e){if(!e||typeof e!="object")throw new Error("Guardian attribution claims are required.");if(!vr(e.agentId))throw new Error("Guardian attribution agent is invalid.");if(e.platform!=="darwin"&&e.platform!=="linux"&&e.platform!=="win32")throw new Error("Guardian attribution platform is invalid.");if(!jR.test(e.hostVersion))throw new Error("Guardian attribution host version is invalid.");if(Ur(e.sessionId,"Guardian attribution session id"),!mq.test(e.skillSlug))throw new Error("Guardian attribution skill slug is invalid.");if(!jR.test(e.version))throw new Error("Guardian attribution skill version is invalid.");return Ur(e.generationId,"Guardian attribution generation id"),Ur(e.actorId,"Guardian attribution actor id"),Ur(e.tenantId,"Guardian attribution tenant id"),e.workspaceId!==void 0&&Ur(e.workspaceId,"Guardian attribution workspace id"),BR(e.requestedMode,"Guardian requested mode"),e.workspaceRequiredMode!==null&&BR(e.workspaceRequiredMode,"Guardian workspace-required mode"),cl(e.issuedAt,"Guardian attribution issuedAt"),cl(e.expiresAt,"Guardian attribution expiresAt"),my({agentId:e.agentId,platform:e.platform,hostVersion:e.hostVersion,sessionId:e.sessionId,skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,actorId:e.actorId,tenantId:e.tenantId,...e.workspaceId===void 0?{}:{workspaceId:e.workspaceId},requestedMode:e.requestedMode,workspaceRequiredMode:e.workspaceRequiredMode,issuedAt:e.issuedAt,expiresAt:e.expiresAt})}function kq(e){let t=MR(e);if(!yq.test(e.contractDigest))throw new Error("Guardian attribution contract digest is invalid.");if(!vq.test(e.archiveSha256))throw new Error("Guardian attribution archive digest is invalid.");if(!Number.isSafeInteger(e.policyRevision)||e.policyRevision<1)throw new Error("Guardian attribution policy revision is invalid.");return Ur(e.trustLedgerId,"Guardian attribution Trust Ledger id"),my({...t,contractDigest:e.contractDigest,archiveSha256:e.archiveSha256,policyRevision:e.policyRevision,trustLedgerId:e.trustLedgerId})}function FR(e,t){if(e.agentId!==t.expectedAgentId)throw new Error("Guardian attribution agent does not match this hook.");if(e.platform!==t.expectedPlatform)throw new Error("Guardian attribution platform does not match this hook.");let n=cl(t.now,"Guardian runtime timestamp"),r=cl(e.issuedAt,"Guardian attribution issuedAt"),i=cl(e.expiresAt,"Guardian attribution expiresAt");if(i.getTime()<=r.getTime())throw new Error("Guardian attribution expiry must follow issuance.");if(n.getTime()<r.getTime())throw new Error("Guardian attribution is not valid yet.");if(n.getTime()>i.getTime())throw new Error("Guardian attribution has expired.");return e}function wq(e,t){return t!==null&&NR[t]>NR[e]?t:e}function bq(e,t){return`hmac-sha256:${lq("sha256",t).update(md(e)).digest("hex")}`}function _q(e){if(!(e instanceof Uint8Array)||e.byteLength<dq||e.byteLength>pq)throw new Error("Guardian attribution key must contain between 32 and 1024 bytes.")}function Ur(e,t){if(typeof e!="string"||!fq.test(e))throw new Error(`${t} is invalid.`)}function BR(e,t){if(e!=="enforce"&&e!=="warning"&&e!=="disabled")throw new Error(`${t} is invalid.`)}function cl(e,t){let n=Date.parse(e);if(!Number.isFinite(n)||new Date(n).toISOString()!==e)throw new Error(`${t} is invalid.`);return new Date(n)}function Sq(e){if(!e||e.decision!=="allow"&&e.decision!=="deny")throw new Error("Guardian policy evaluator returned an invalid decision.");UR(e.reason)}function UR(e){if(typeof e!="string"||e.trim().length===0||e.length>900||/[\u0000\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(e))throw new Error("Guardian policy reason is invalid.");return e}function md(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(md).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${md(t[n])}`).join(",")}}`}function my(e){if(e&&typeof e=="object"){for(let t of Object.values(e))my(t);Object.freeze(e)}return e}import{createHash as zR}from"node:crypto";var qR=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,xq=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,rs=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,VR=/^sha256:[a-f0-9]{64}$/u,GR=4096;function HR(){return Object.freeze({version:2,revision:0,associations:Object.freeze({})})}function KR(e){if(!Hn(e)||e.version!==2||!Number.isSafeInteger(e.revision)||Number(e.revision)<0||!Hn(e.associations))throw new Error("Guardian session association index is invalid.");let t={};for(let[n,r]of Object.entries(e.associations)){if(!Hn(r))throw new Error("Guardian session association record is invalid.");let i=r;if(YR(i),et(i)!==n)throw new Error("Guardian session association key does not match its exact identity.");t[n]=qr({...i})}return qr({version:2,revision:Number(e.revision),associations:t})}function Vr(e){let t={targetDir:e.targetDir,generation:e.generation,archiveSha256:e.archiveSha256,manifestSha256:e.manifestSha256,files:[...e.files].map(n=>({path:n.path,sizeBytes:n.sizeBytes,sha256:n.sha256})).sort((n,r)=>gy(n.path,r.path))};return Cq(gd(t))}function et(e){return XR(e),`association_${zR("sha256").update(gd({scope:e.scope,agentId:e.agentId,sessionId:e.sessionId,skillSlug:e.skillSlug,skillVersion:e.skillVersion,generationId:e.generationId}),"utf8").digest("hex")}`}function WR(e,t,n){if(yd(e),e.revision!==n)throw new Error("Guardian association compare-and-swap revision changed.");YR(t);let r=et(t),i=e.associations[r],o=qr({...t,revision:i?i.revision+1:1,createdAt:i?.createdAt??t.createdAt});return qr({version:2,revision:e.revision+1,associations:{...e.associations,[r]:o}})}function ZR(e,t){if(yd(e),e.revision!==t.expectedIndexRevision)throw new Error("Guardian association compare-and-swap revision changed.");let n=e.associations[t.key];if(!n)throw new Error("Guardian session association was not found.");os(t.updatedAt,"Guardian association update timestamp"),t.attributionExpiresAt!==void 0&&os(t.attributionExpiresAt,"Guardian attribution expiry"),t.trustLedgerId!==void 0&&zr(t.trustLedgerId,"Guardian Trust Ledger id"),t.reasonCode!==void 0&&is(t.reasonCode,"Guardian association reason code");let r=qr({...n,revision:n.revision+1,state:t.state,updatedAt:t.updatedAt,...t.attributionExpiresAt===void 0?{}:{attributionExpiresAt:t.attributionExpiresAt},...t.trustLedgerId===void 0?{}:{trustLedgerId:t.trustLedgerId},...t.reasonCode===void 0?{}:{reasonCode:t.reasonCode}});return qr({version:2,revision:e.revision+1,associations:{...e.associations,[t.key]:r}})}function pl(e,t){yd(e),zr(t.sessionId,"Guardian host session id");let n=os(t.asOf,"Guardian association lookup timestamp"),r=Object.values(e.associations).filter(s=>s.agentId===t.agentId&&s.sessionId===t.sessionId).sort((s,a)=>gy(et(s),et(a)));if(r.length===0)return{status:"unrelated",associations:[]};let i=r.filter(s=>s.state==="active");if(i.length>1)return{status:"ambiguous",associations:i};if(i.length===1){let s=i[0],a=s.attributionExpiresAt?Date.parse(s.attributionExpiresAt):Number.NaN;return Number.isFinite(a)&&a>n?{status:"active",associations:[s]}:{status:"active_authority_stale",associations:[s]}}let o=r.filter(s=>s.state==="pending_authority"||s.state==="stale");return o.length>0?{status:"expected_missing_authority",associations:o}:{status:"terminal",associations:r}}function JR(e,t){if(yd(e),e.revision!==t.expectedIndexRevision)throw new Error("Guardian association compare-and-swap revision changed.");if(!rs.test(t.skillSlug)||!qR.test(t.generationId)||!VR.test(t.receiptSha256))throw new Error("Guardian association forget identity is invalid.");let n=Object.entries(e.associations).flatMap(([i,o])=>o.skillSlug===t.skillSlug&&o.generationId===t.generationId&&o.receiptSha256===t.receiptSha256&&(o.state==="externally_removed"||o.state==="host_detached")?[i]:[]);if(n.length===0)return{index:e,removedKeys:[]};let r=new Set(n);return{index:qr({version:2,revision:e.revision+1,associations:Object.fromEntries(Object.entries(e.associations).filter(([i])=>!r.has(i)))}),removedKeys:[...n]}}function hd(e,t){if(!Hn(t))return null;if(e==="claude-code"){let n=Rn(t.session_id);if(t.hook_event_name==="UserPromptExpansion"&&t.expansion_type==="slash_command"){let r=Rn(t.command_name);if(n&&r&&rs.test(r))return dl(n,r,"slug","claude_user_prompt_expansion",`UserPromptExpansion:${r}`)}if(t.hook_event_name==="PreToolUse"&&t.tool_name==="Skill"){let r=Hn(t.tool_input)?t.tool_input:null,i=r?Rn(r.skill)??Rn(r.name):null;if(n&&i&&rs.test(i))return dl(n,i,"slug","claude_skill_tool",`Skill:${i}`)}return null}if(e==="gemini-cli"){let n=Rn(t.session_id),r=Hn(t.tool_input)?t.tool_input:null,i=r?Rn(r.name):null;return t.hook_event_name==="BeforeTool"&&t.tool_name==="activate_skill"&&n&&i&&rs.test(i)?dl(n,i,"slug","gemini_activate_skill",`activate_skill:${i}`):null}if(e==="antigravity"||e==="antigravity-cli"){let n=Rn(t.conversationId),r=Hn(t.toolCall)?t.toolCall:null,i=r&&Hn(r.args)?r.args:null,o=i?Rn(i.AbsolutePath):null;if(r?.name==="view_file"&&i?.IsSkillFile===!0&&n&&o)return dl(n,o,"path","antigravity_skill_file",`view_file:${o}`)}if(e==="opencode"){let n=Rn(t.session_id),r=Hn(t.tool_input)?t.tool_input:null,i=r?Rn(r.name)??Rn(r.skill):null;if(t.hook_event_name==="tool.execute.before"&&t.tool_name==="skill"&&n&&i&&rs.test(i))return dl(n,i,"slug","opencode_skill_tool",`skill:${i}`)}return null}function dl(e,t,n,r,i){return zr(e,"Guardian activation session id"),is(t,"Guardian activation skill reference"),is(i,"Guardian activation evidence"),Object.freeze({sessionId:e,skillReference:t,referenceKind:n,source:r,evidence:i})}function yd(e){if(!e||e.version!==2||!Number.isSafeInteger(e.revision)||e.revision<0||!Hn(e.associations))throw new Error("Guardian session association index is invalid.")}function YR(e){if(!e||e.version!==2||!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Guardian session association version is invalid.");if(XR(e),!VR.test(e.receiptSha256))throw new Error("Guardian association receipt digest is invalid.");if(e.requestedPreference!=="enforce"&&e.requestedPreference!=="warning_only"&&e.requestedPreference!=="disabled")throw new Error("Guardian association preference is invalid.");if(!["pending_authority","active","stale","externally_removed","host_detached"].includes(e.state))throw new Error("Guardian association state is invalid.");if(!["claude_skill_tool","claude_user_prompt_expansion","gemini_activate_skill","antigravity_skill_file","opencode_skill_tool","approved_launcher","manual_recovery"].includes(e.activationSource))throw new Error("Guardian activation source is invalid.");is(e.activationEvidence,"Guardian activation evidence"),is(e.adapterRevision,"Guardian adapter revision"),os(e.createdAt,"Guardian association creation timestamp"),os(e.updatedAt,"Guardian association update timestamp"),e.attributionExpiresAt!==void 0&&os(e.attributionExpiresAt,"Guardian attribution expiry"),e.trustLedgerId!==void 0&&zr(e.trustLedgerId,"Guardian Trust Ledger id"),e.workspaceId!==void 0&&zr(e.workspaceId,"Guardian workspace id"),e.reasonCode!==void 0&&is(e.reasonCode,"Guardian association reason code")}function XR(e){if(e.scope!=="project"&&e.scope!=="global")throw new Error("Guardian association scope is invalid.");if(zr(e.agentId,"Guardian association agent id"),zr(e.sessionId,"Guardian association session id"),!rs.test(e.skillSlug))throw new Error("Guardian association skill slug is invalid.");if(!xq.test(e.skillVersion))throw new Error("Guardian association skill version is invalid.");zr(e.generationId,"Guardian association generation id")}function zr(e,t){if(typeof e!="string"||!qR.test(e))throw new Error(`${t} is invalid.`)}function is(e,t){if(typeof e!="string"||e.length===0||e.length>GR||/[\u0000-\u001f\u007f]/u.test(e))throw new Error(`${t} is invalid.`)}function os(e,t){let n=Date.parse(e);if(!Number.isFinite(n)||new Date(n).toISOString()!==e)throw new Error(`${t} is invalid.`);return n}function Rn(e){return typeof e=="string"&&e.length>0&&e.length<=GR?e:null}function Hn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Cq(e){return`sha256:${zR("sha256").update(e,"utf8").digest("hex")}`}function gd(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(gd).join(",")}]`;let t=e;return`{${Object.keys(t).sort(gy).map(n=>`${JSON.stringify(n)}:${gd(t[n])}`).join(",")}}`}function gy(e,t){return e<t?-1:e>t?1:0}function qr(e){if(e&&typeof e=="object"){for(let t of Object.values(e))qr(t);Object.freeze(e)}return e}import{constants as QR}from"node:fs";import{lstat as Iq,open as Pq}from"node:fs/promises";import{createHash as Aq}from"node:crypto";import{posix as rE,win32 as iE}from"node:path";var Rq=/^sha256:[a-f0-9]{64}$/u,eE=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,oE=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,Eq=4096,sE=6;function $q(e){return vd(fl(e))}function aE(e){let t=Oq(e.asOf,"asOf"),n=[],r=e.evidence;if(!r||typeof r!="object"||r.evidenceVersion!==1)return n.push("evidence_version_invalid"),{capability:"unverified",reasons:n};Tq(r.sourceUrl)||n.push("evidence_source_not_https");let i=ky(r.checkedAt);if(!i)n.push("evidence_checked_at_invalid");else{i.getTime()>t.getTime()&&n.push("evidence_from_future");let l=new Date(i.getTime());l.setUTCMonth(l.getUTCMonth()+sE),t.getTime()>l.getTime()&&n.push("evidence_stale")}tE(r.binding,"evidence",n),tE(e.currentBinding,"current",n);let o=r.binding&&typeof r.binding=="object"?$q(r.binding):null;(!ss(r.bindingDigest)||o===null||r.bindingDigest!==o)&&n.push("evidence_binding_digest_invalid"),(!r.binding||typeof r.binding!="object"||!e.currentBinding||typeof e.currentBinding!="object"||fl(nE(r.binding))!==fl(nE(e.currentBinding)))&&n.push("current_installation_binding_changed");let s=[r.allowCanary,r.denyCanary,r.argumentMutationCanary,r.missingAttributionCanary,r.enterpriseNonDowngradeCanary,r.handlerFailureCanary,r.handlerTimeoutCanary,r.activationCanary];Gr(r.allowCanary,"allow","allowed",!0,!1,r.bindingDigest,i,t,n),Gr(r.denyCanary,"deny","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.argumentMutationCanary,"argument_mutation","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.missingAttributionCanary,"missing_attribution","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.enterpriseNonDowngradeCanary,"enterprise_non_downgrade","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.handlerFailureCanary,"handler_failure","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.handlerTimeoutCanary,"handler_timeout","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.activationCanary,"activation_association","allowed",!1,!0,r.bindingDigest,i,t,n);let a=s.filter(l=>!!(l&&typeof l=="object"));if(new Set(a.map(l=>l.observationId)).size!==a.length&&n.push("canary_observations_not_distinct"),new Set(a.map(l=>l.fixtureId)).size!==a.length&&n.push("canary_fixtures_not_distinct"),new Set(a.map(l=>l.actionSha256)).size!==a.length&&n.push("canary_actions_not_distinct"),r.activationRoute!=="native_activation"&&r.activationRoute!=="approved_launcher"&&n.push("activation_route_invalid"),!r.qualification||typeof r.qualification!="object")n.push("qualification_missing");else{r.qualification.driver!=="skills-layer-real-host-canary-v1"&&n.push("qualification_driver_invalid");let l=r.binding?.platform;(l!=="darwin"&&l!=="linux"&&l!=="win32"||!vy(r.qualification.hostExecutablePath,l))&&n.push("qualification_host_executable_not_absolute"),ss(r.qualification.hostExecutableSha256)||n.push("qualification_host_digest_invalid"),ss(r.qualification.planSha256)||n.push("qualification_plan_digest_invalid")}return r.changedArgumentsInvalidateApproval||n.push("argument_mutation_not_verified"),r.missingAttributionFailsClosed||n.push("missing_attribution_not_fail_closed"),r.enterpriseEnforceNonDowngradeVerified||n.push("enterprise_mode_downgrade_not_blocked"),n.length===0?{capability:"strict",reasons:[]}:{capability:"unverified",reasons:[...new Set(n)]}}async function lE(e){if(!Gn(e.agentId))throw new Error(`No strict hook adapter exists for ${e.agentId}.`);if(e.adapterRevision!==Qt[e.agentId])throw new Error("Strict hook adapter revision does not match the implemented adapter.");if(!oE.test(e.hostVersion))throw new Error("Strict hook host version is invalid.");Dq(e.platform);let n=yy(e.hookConfigPath,e.platform,"hook config path"),r=yy(e.hookScriptPath,e.platform,"hook script path"),i=yy(e.absoluteCliPath,e.platform,"CLI path");if(new Set([n,r,i]).size!==3)throw new Error("Strict hook config, script, and CLI paths must be distinct.");let[o,s,a]=await Promise.all([hy(n,!1),hy(r,e.platform!=="win32"),hy(i,e.platform!=="win32")]);return Object.freeze({agentId:e.agentId,platform:e.platform,hostVersion:e.hostVersion,adapterRevision:e.adapterRevision,hookConfigPath:n,hookConfigSha256:vd(o),hookScriptPath:r,hookScriptSha256:vd(s),absoluteCliPath:i,cliSha256:vd(a)})}function tE(e,t,n){if(!e||typeof e!="object"){n.push(`${t}_binding_missing`);return}let r=Gn(e.agentId);if(r||n.push(`${t}_agent_has_no_strict_adapter`),e.platform!=="darwin"&&e.platform!=="linux"&&e.platform!=="win32"){n.push(`${t}_platform_invalid`);return}oE.test(e.hostVersion)||n.push(`${t}_host_version_invalid`),(!r||e.adapterRevision!==r.adapterRevision)&&n.push(`${t}_adapter_revision_invalid`);let i=[e.hookConfigPath,e.hookScriptPath,e.absoluteCliPath];for(let[o,s]of i.entries())vy(s,e.platform)||n.push(`${t}_path_${o}_not_absolute`);new Set(i).size!==i.length&&n.push(`${t}_paths_not_distinct`);for(let[o,s]of[e.hookConfigSha256,e.hookScriptSha256,e.cliSha256].entries())ss(s)||n.push(`${t}_digest_${o}_invalid`)}function nE(e){let{hostVersion:t,...n}=e;return n}function Gr(e,t,n,r,i,o,s,a,l){if(!e||typeof e!="object"){l.push(`${t}_canary_missing`);return}e.kind!==t&&l.push(`${t}_canary_kind_invalid`),eE.test(e.observationId)||l.push(`${t}_observation_id_invalid`),eE.test(e.fixtureId)||l.push(`${t}_fixture_id_invalid`);let c=ky(e.observedAt);if(!c)l.push(`${t}_observed_at_invalid`);else if(s&&c.getTime()>s.getTime())l.push(`${t}_observation_after_evidence`);else{let u=new Date(c.getTime());u.setUTCMonth(u.getUTCMonth()+sE),a.getTime()>u.getTime()&&l.push(`${t}_canary_stale`)}e.realHostExecution||l.push(`${t}_not_real_host_execution`),(!ss(e.bindingDigest)||e.bindingDigest!==o)&&l.push(`${t}_binding_digest_mismatch`),ss(e.actionSha256)||l.push(`${t}_action_digest_invalid`),e.hostOutcome!==n&&l.push(`${t}_host_outcome_invalid`),e.sideEffectObserved!==r&&l.push(`${t}_side_effect_invalid`),e.associationObserved!==i&&l.push(`${t}_association_invalid`)}async function hy(e,t){let n=await Iq(e);if(n.isSymbolicLink())throw new Error(`Strict hook path is a symbolic link: ${e}`);if(!n.isFile())throw new Error(`Strict hook path must be a regular file: ${e}`);let r=await Pq(e,QR.O_RDONLY|QR.O_NOFOLLOW);try{let i=await r.stat();if(!i.isFile())throw new Error(`Strict hook path must be a regular file: ${e}`);if(t&&(i.mode&73)===0)throw new Error(`Strict hook executable path has no execute bit: ${e}`);return new Uint8Array(await r.readFile())}finally{await r.close()}}function yy(e,t,n){if(!vy(e,t))throw new Error(`Strict ${n} must be absolute for ${t}.`);return(t==="win32"?iE:rE).normalize(e)}function vy(e,t){return typeof e!="string"||e.length===0||e.length>Eq||e.includes("\0")?!1:(t==="win32"?iE:rE).isAbsolute(e)}function Dq(e){if(e!=="darwin"&&e!=="linux"&&e!=="win32")throw new Error("Strict hook platform is unsupported.")}function ss(e){return typeof e=="string"&&Rq.test(e)}function Tq(e){if(typeof e!="string")return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.username.length===0&&t.password.length===0}catch{return!1}}function Oq(e,t){let n=ky(e);if(!n)throw new Error(`${t} must be a valid ISO date.`);return n}function ky(e){if(typeof e!="string"||e.length===0)return null;let t=Date.parse(e);if(!Number.isFinite(t))return null;let n=new Date(t);return n.toISOString()===e?n:null}function fl(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(fl).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${fl(t[n])}`).join(",")}}`}function vd(e){return`sha256:${Aq("sha256").update(e).digest("hex")}`}import{createHash as Lq}from"node:crypto";import{constants as Hr}from"node:fs";import{open as uE}from"node:fs/promises";import{isAbsolute as jq}from"node:path";var gl="skills-layer-real-host-canary-v1",Nq=new Set(["allow","deny","argument_mutation","missing_attribution","enterprise_non_downgrade","handler_failure","handler_timeout","activation_association"]),Fq=/^[A-Za-z0-9_-]{43}$/u,dE=/^association_[a-f0-9]{64}$/u,Bq=4096,Mq=512*1024,Uq=16*1024;function ls(e){return hl(e)?.scenario??null}async function by(e){let t=hl(e.env);if(!t||e.activationEvent&&t.scenario!=="activation_association")return!1;let n=e.reportingSource??"hook";if(n==="hook"&&(e.delegatedExecution===!0||cE(e.agentId,e.result)?.value?.includes("atomic guarded execution wrapper")||t.scenario!=="activation_association"&&t.sideEffectPath&&!zq(e.rawPayloadBase64,t.sideEffectPath)))return!1;let r="invalid";try{let i=e.rawPayloadBase64??"";if(Buffer.byteLength(i,"utf8")>Mq)throw new Error("Guardian canary payload is too large.");if(r=n==="guarded_execution"?e.result.exitCode===0?"allowed":"denied":Vq(e.agentId,e.result),t.scenario==="missing_attribution"){if(e.associationState!=="missing"||r!=="denied")throw new Error("Guardian missing attribution canary requires no active association and a denied host outcome.")}else if(e.associationState!=="active")throw new Error("Guardian canary requires an active exact skill-session association.");let o=kd(t.challenge),s=kd(`${t.scenario}\0${i}`);try{await wd(t.resultPath,{challenge:t.challenge,driver:gl,agentId:e.agentId,scenario:t.scenario,associationState:e.associationState,observationId:`guardian-canary-${t.scenario}-${o.slice(7,31)}`,fixtureId:`guardian-fixture-${e.agentId}-${t.scenario}-${s.slice(7,23)}`,actionSha256:s,hostOutcome:r})}catch(a){if(a.code==="EEXIST")return!1;throw a}return!0}catch(i){let o=cE(e.agentId,e.result);throw await wd(t.diagnosticPath,{schemaVersion:"skills-layer.guardian-canary-diagnostic.v1",challengeDigest:kd(t.challenge),driver:gl,agentId:e.agentId,scenario:t.scenario,associationState:e.associationState,activationEvent:e.activationEvent,hostOutcome:r,failureCode:qq(i),...o?{decisionReasonCode:o.code,decisionReasonSha256:kd(o.value)}:{}}).catch(()=>{}),i}}async function pE(e){let t=hl(e);return!t||t.scenario!=="activation_association"?!1:(await wd(t.associationPath,{challenge:t.challenge,associationEstablished:!0}),!0)}async function fE(e){let t=hl(e.env);if(!t)return!1;if(!dE.test(e.associationKey))throw new Error("Guardian canary delegation association key is invalid.");try{await wd(t.delegationPath,{challenge:t.challenge,driver:gl,agentId:e.agentId,scope:e.scope,skillSlug:e.skillSlug,associationKey:e.associationKey})}catch(n){if(n.code==="EEXIST")return!1;throw n}return!0}async function mE(e){let t=hl(e.env);if(!t)return null;let n;try{n=await Gq(t.delegationPath)}catch(r){if(r.code==="ENOENT")return null;throw r}if(!as(n)||n.challenge!==t.challenge||n.driver!==gl||typeof n.agentId!="string"||typeof n.scope!="string"||typeof n.skillSlug!="string"||typeof n.associationKey!="string"||!dE.test(n.associationKey))throw new Error("Guardian canary delegation receipt is invalid.");return n.agentId!==e.agentId||n.scope!==e.scope||n.skillSlug!==e.skillSlug?null:{associationKey:n.associationKey}}function hl(e){let t=e.SKILLS_LAYER_GUARDIAN_CANARY_DRIVER,n=e.SKILLS_LAYER_GUARDIAN_CANARY_SCENARIO,r=e.SKILLS_LAYER_GUARDIAN_CANARY_CHALLENGE,i=e.SKILLS_LAYER_GUARDIAN_CANARY_RESULT_PATH,o=e.SKILLS_LAYER_GUARDIAN_CANARY_ASSOCIATION_PATH,s=e.SKILLS_LAYER_GUARDIAN_CANARY_DELEGATION_PATH,a=e.SKILLS_LAYER_GUARDIAN_CANARY_DIAGNOSTIC_PATH,l=e.SKILLS_LAYER_GUARDIAN_CANARY_SIDE_EFFECT_PATH;if([t,n,r,i,o,s,a].filter(u=>u!==void 0).length===0)return null;if(t!==gl||!n||!Nq.has(n)||!r||!Fq.test(r)||!ml(i)||!ml(o)||!ml(s)||!ml(a)||l!==void 0&&!ml(l)||new Set([i,o,s,a,...l?[l]:[]]).size!==(l?5:4))throw new Error("Guardian canary context is invalid.");return{scenario:n,challenge:r,resultPath:i,associationPath:o,delegationPath:s,diagnosticPath:a,...l?{sideEffectPath:l}:{}}}function zq(e,t){if(!e)return!1;try{let n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return wy(n,t,0)}catch{return!1}}function wy(e,t,n){return n>16?!1:typeof e=="string"?e.includes(t):Array.isArray(e)?e.some(r=>wy(r,t,n+1)):as(e)?Object.values(e).some(r=>wy(r,t,n+1)):!1}function qq(e){let t=e instanceof Error?e.message:String(e);return t.includes("payload is too large")?"payload_too_large":t.includes("hook result is invalid")?"hook_result_invalid":t.includes("decision output is invalid")?"hook_decision_invalid":t.includes("missing attribution canary")?"missing_attribution_contract_mismatch":t.includes("active exact skill-session association")?"exact_association_not_active":"canary_result_rejected"}function cE(e,t){let n=t.exitCode===0?void 0:t.stderr;if(t.exitCode===0)try{let o=JSON.parse(t.stdout);as(o)&&(e==="cline"?n=o.errorMessage:e==="gemini-cli"||e==="antigravity"||e==="antigravity-cli"?n=o.reason:e==="cursor"?n=o.user_message??o.agent_message:n=(as(o.hookSpecificOutput)?o.hookSpecificOutput:null)?.permissionDecisionReason)}catch{return}if(typeof n!="string"||n.length===0)return;let r=n.slice(0,1024),i=r.match(/verified enforcement is unavailable \(([a-z][a-z0-9_]{0,127})\)/u)?.[1];return i?{code:i,value:r}:r.includes("Guardian attribution is not valid yet.")?{code:"guardian_attribution_not_valid_yet",value:r}:r.includes("could not establish exact skill-session authority")?{code:"guardian_session_authority_unavailable",value:r}:r.includes("could not safely record this exact skill-session association")?{code:"guardian_association_persistence_failed",value:r}:r.includes("managed launch no longer matches the exact installed generation")?{code:"guardian_managed_launch_generation_mismatch",value:r}:r.includes("invalid, expired, replayed, or host-mismatched managed launch token")?{code:"guardian_managed_launch_rejected",value:r}:{code:"unclassified_guardian_decision",value:r}}function Vq(e,t){if(!Number.isSafeInteger(t.exitCode)||typeof t.stdout!="string"||typeof t.stderr!="string")throw new Error("Guardian canary hook result is invalid.");if(t.exitCode!==0)return"denied";if(e==="kiro-cli"||e==="opencode"||e==="windsurf"||e==="github-copilot")return"allowed";let n;try{n=JSON.parse(t.stdout)}catch{throw new Error("Guardian canary hook decision output is invalid.")}if(!as(n))throw new Error("Guardian canary hook decision output is invalid.");if(e==="cline")return n.cancel===!0?"denied":"allowed";if(e==="gemini-cli"||e==="antigravity"||e==="antigravity-cli"){if(n.decision==="deny")return"denied";if(n.decision==="allow")return"allowed"}else if(e==="cursor"){if(n.permission==="deny")return"denied";if(n.permission==="allow")return"allowed"}else{let r=as(n.hookSpecificOutput)?n.hookSpecificOutput:null;if(r?.permissionDecision==="deny")return"denied";if(r?.permissionDecision==="allow")return"allowed"}throw new Error("Guardian canary hook decision output is invalid.")}async function wd(e,t){let n=typeof Hr.O_NOFOLLOW=="number"?Hr.O_NOFOLLOW:0,r=await uE(e,Hr.O_CREAT|Hr.O_EXCL|Hr.O_WRONLY|n,384);try{await r.writeFile(`${JSON.stringify(t)}
|
|
692
|
+
`),i.push(o.configPath)}return{applied:!0,plannedPaths:n.map(o=>o.configPath),cleanedPaths:i,skipped:r}}function _R(e,t,n,r){return!sl(e)||e.command!==t||!Array.isArray(e.args)?!1:e.args[0]===n&&(e.args.length===1||e.args.length===3&&e.args[1]==="--client"&&e.args[2]===r)}async function R6(e,t){await x6(P6(e),{recursive:!0,mode:448});let n=e+".skills-layer-migration.lock",r=e+`.skills-layer-migration-stage-${process.pid}`,i=e+".skills-layer-migration-backup",o=await C6(n,"wx",384).catch(s=>{throw s.code==="EEXIST"?new Error(`mcp_legacy_migration_locked: ${e}`):s});try{await yR(i,await uy(e),{mode:384}),await hR(i,384),await cy(r,{force:!0}),await yR(r,t,{encoding:"utf8",flag:"wx",mode:384}),await I6(r,e),await hR(e,384)}finally{await o.close(),await Promise.all([cy(r,{force:!0}),cy(n,{force:!0})])}}function ol(e,t,n,r,i,o){return{hostId:e.hostId,configPath:t,containerKey:e.containerKey,status:n,reason:r,bridgePath:i,nodePath:o}}function sl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{createHmac as lq,sign as rue,timingSafeEqual as cq,verify as uq}from"node:crypto";import{createHash as E6}from"node:crypto";import{posix as AR,win32 as RR}from"node:path";var Qt=Object.freeze({codex:"codex-pre-tool-use-v4-2026-10-01","claude-code":"claude-code-pre-tool-use-v2-2026-10-01",cline:"cline-pre-tool-use-v2-2026-10-01","gemini-cli":"gemini-cli-before-tool-v2-2026-10-01",cursor:"cursor-pre-tool-use-v2-2026-10-01","github-copilot":"github-copilot-pre-tool-use-v2-2026-10-01",opencode:"opencode-tool-execute-before-v2-2026-10-01",windsurf:"windsurf-cascade-pre-action-v2-2026-10-01",antigravity:"antigravity-pre-tool-use-v2-2026-10-01","antigravity-cli":"antigravity-cli-pre-tool-use-v2-2026-10-01","kiro-cli":"kiro-cli-pre-tool-use-v2-2026-10-01"}),SR=256*1024,$6=16,D6=4096,T6=1024,O6=512,ll=65536,kt=4096,L6=1024,ER=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,j6=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,N6=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,F6=new Set(["__proto__","constructor","prototype"]),xR=Object.freeze({codex:Object.freeze({agentId:"codex",adapterRevision:Qt.codex,eventName:"PreToolUse",sourceUrl:"https://learn.chatgpt.com/docs/hooks",sourceCheckedAt:"2026-10-01",blockingContract:"hookSpecificOutput.permissionDecision=deny; malformed hook output fails open"}),"claude-code":Object.freeze({agentId:"claude-code",adapterRevision:Qt["claude-code"],eventName:"PreToolUse",sourceUrl:"https://code.claude.com/docs/en/hooks",sourceCheckedAt:"2026-07-16",blockingContract:"hookSpecificOutput.permissionDecision=deny or command exit 2"}),cline:Object.freeze({agentId:"cline",adapterRevision:Qt.cline,eventName:"PreToolUse",sourceUrl:"https://docs.cline.bot/customization/hooks",sourceCheckedAt:"2026-07-16",blockingContract:"cancel=true"}),"gemini-cli":Object.freeze({agentId:"gemini-cli",adapterRevision:Qt["gemini-cli"],eventName:"BeforeTool",sourceUrl:"https://geminicli.com/docs/hooks/reference/",sourceCheckedAt:"2026-09-25",blockingContract:"decision=deny or command exit 2"}),cursor:Object.freeze({agentId:"cursor",adapterRevision:Qt.cursor,eventName:"preToolUse",sourceUrl:"https://cursor.com/docs/hooks",sourceCheckedAt:"2026-09-25",blockingContract:"permission=deny with failClosed=true"}),"github-copilot":Object.freeze({agentId:"github-copilot",adapterRevision:Qt["github-copilot"],eventName:"PreToolUse",sourceUrl:"https://docs.github.com/en/copilot/reference/hooks-reference",sourceCheckedAt:"2026-09-25",blockingContract:"non-zero exit denies, but command-hook timeout fails open"}),opencode:Object.freeze({agentId:"opencode",adapterRevision:Qt.opencode,eventName:"tool.execute.before",sourceUrl:"https://opencode.ai/docs/plugins/",sourceCheckedAt:"2026-09-25",blockingContract:"plugin tool.execute.before throws before tool execution"}),windsurf:Object.freeze({agentId:"windsurf",adapterRevision:Qt.windsurf,eventName:"pre_run_command",sourceUrl:"https://docs.windsurf.com/windsurf/cascade/hooks",sourceCheckedAt:"2026-09-25",blockingContract:"exit code 2 blocks supported Cascade pre-hooks"}),antigravity:Object.freeze({agentId:"antigravity",adapterRevision:Qt.antigravity,eventName:"PreToolUse",sourceUrl:"https://antigravity.google/docs/hooks?tab=ide",sourceCheckedAt:"2026-09-25",blockingContract:"decision=deny"}),"antigravity-cli":Object.freeze({agentId:"antigravity-cli",adapterRevision:Qt["antigravity-cli"],eventName:"PreToolUse",sourceUrl:"https://antigravity.google/docs/hooks?tab=cli",sourceCheckedAt:"2026-09-25",blockingContract:"decision=deny"}),"kiro-cli":Object.freeze({agentId:"kiro-cli",adapterRevision:Qt["kiro-cli"],eventName:"preToolUse",sourceUrl:"https://kiro.dev/docs/hooks/types/",sourceCheckedAt:"2026-09-25",blockingContract:"non-zero command exit blocks"})}),B6=new Set(["bash","exec_command","shell","shell_command","execute_command","run_shell_command","run_command","execute_bash"]),M6=new Set(["read","read_file","view","glob","grep","list_files","search_files","list_code_definition_names","view_file","fs_read"]),U6=new Set(["write","write_file","edit","create","apply_patch","notebookedit","write_to_file","replace_in_file","insert_content","replace","replace_file_content","multi_replace_file_content","fs_write"]),z6=new Set(["webfetch","websearch","web_fetch","web_search","google_web_search"]),q6=new Set(["browser","browser_action","computer"]),V6=new Set(["device","device_action","computer_use"]);function Gn(e){return Object.prototype.hasOwnProperty.call(xR,e)?xR[e]:null}function vr(e){return Gn(e)!==null}function $R(e){let t=Gn(e.agentId);if(!t)throw new Error(`No strict hook adapter is implemented for ${e.agentId}.`);oq(e.platform),TR(e.hostVersion,"host version"),al(e.expectedSessionId,"expected session id");let n=nq(e.attribution),r=rq(e.payload),i=e.agentId==="cline"?H6(r,e):e.agentId==="gemini-cli"?K6(r,e):e.agentId==="cursor"?W6(r,e):e.agentId==="github-copilot"?Z6(r,e):e.agentId==="opencode"?J6(r,e):e.agentId==="windsurf"?Y6(r,e):e.agentId==="antigravity"||e.agentId==="antigravity-cli"?X6(r,e):e.agentId==="kiro-cli"?Q6(r,e):G6(r,e),o=eq({agentId:e.agentId,platform:e.platform,cwd:i.cwd,toolName:i.toolName,toolInput:i.toolInput}),s=py(aq(i.toolInput)),a=py({actionVersion:1,actionFamily:o.actionFamily,command:o.command,cwdRealPath:i.cwd,fileTargets:Object.freeze(o.fileTargets),networkTargets:Object.freeze(o.networkTargets),toolName:i.toolName,toolInput:s,toolInputSha256:IR(ts(s)),host:Object.freeze({agentId:e.agentId,hostVersion:e.hostVersion,platform:e.platform,sessionId:i.sessionId,toolUseId:i.toolUseId}),skill:Object.freeze(n)});return Object.freeze({adapterRevision:t.adapterRevision,action:a,actionSha256:IR(ts(a))})}function ns(e,t){if(!Gn(e))throw new Error(`No strict hook adapter is implemented for ${e}.`);if(t.decision!=="allow"&&t.decision!=="deny")throw new Error("Strict hook decision must be allow or deny.");if(sq(t.reason,"decision reason",L6),e==="kiro-cli"||e==="opencode"||e==="windsurf"||e==="github-copilot")return Object.freeze(t.decision==="deny"?{exitCode:2,stdout:"",stderr:t.reason}:{exitCode:0,stdout:"",stderr:""});let n=e==="cline"?t.decision==="deny"?{cancel:!0,errorMessage:t.reason}:{cancel:!1}:e==="gemini-cli"||e==="antigravity"||e==="antigravity-cli"?{decision:t.decision,reason:t.reason}:e==="cursor"?{permission:t.decision,user_message:t.reason,agent_message:t.reason}:e==="codex"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t.decision,...t.decision==="deny"?{permissionDecisionReason:t.reason}:{}}}:{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:t.decision,permissionDecisionReason:t.reason}};return Object.freeze({exitCode:0,stdout:JSON.stringify(n),stderr:""})}function G6(e,t){if(e.hook_event_name!=="PreToolUse")throw new Error("Strict host hook accepts only the PreToolUse event.");let n=ne(e.session_id,"hook session id",256);if(n!==t.expectedSessionId)throw new Error("Hook session does not match the bound session.");let r=kr(ne(e.cwd,"hook cwd",kt),t.platform),i=ne(e.tool_name,"hook tool name",256),o=ne(e.tool_use_id,"hook tool use id",256),s=Mt(e.tool_input,"hook tool input");return{sessionId:n,cwd:r,toolName:i,toolUseId:o,toolInput:s}}function H6(e,t){if(e.hookName!=="PreToolUse")throw new Error("Strict Cline hook accepts only the PreToolUse event.");let n=ne(e.taskId,"Cline task id",256);if(n!==t.expectedSessionId)throw new Error("Cline task does not match the bound session.");ne(e.clineVersion,"Cline version",128);let r=ne(e.timestamp,"Cline timestamp",32);if(!/^\d{13}$/u.test(r)||!Number.isFinite(Number(r)))throw new Error("Cline timestamp must be milliseconds since epoch encoded as a string.");ne(e.userId,"Cline user id",256);let i=Mt(e.model,"Cline model");if(ne(i.provider,"Cline model provider",256),ne(i.slug,"Cline model slug",256),!Array.isArray(e.workspaceRoots)||e.workspaceRoots.length===0||e.workspaceRoots.length>64)throw new Error("Cline workspaceRoots must contain between one and 64 paths.");let o=e.workspaceRoots.map(c=>kr(ne(c,"Cline workspace root",kt),t.platform)),s=Mt(e.preToolUse,"Cline preToolUse"),a=ne(s.tool,"Cline tool name",256),l=Mt(s.parameters,"Cline tool parameters");return{sessionId:n,cwd:o[0],toolName:a,toolUseId:null,toolInput:l}}function K6(e,t){if(e.hook_event_name!=="BeforeTool")throw new Error("Strict Gemini CLI hook accepts only the BeforeTool event.");let n=ne(e.session_id,"Gemini CLI session id",256);if(n!==t.expectedSessionId)throw new Error("Gemini CLI session does not match the bound session.");let r=kr(ne(e.cwd,"Gemini CLI cwd",kt),t.platform),i=ne(e.tool_name,"Gemini CLI tool name",256),o=Mt(e.tool_input,"Gemini CLI tool input"),s=fd(e.tool_use_id,"Gemini CLI tool use id");return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function W6(e,t){if(e.hook_event_name!=="preToolUse")throw new Error("Strict Cursor hook accepts only the preToolUse event.");let n=ne(e.conversation_id,"Cursor conversation id",256);if(n!==t.expectedSessionId)throw new Error("Cursor conversation does not match the bound session.");ne(e.cursor_version,"Cursor version",128);let r=DR(e.workspace_roots,"Cursor workspace roots",t.platform),i=typeof e.cwd=="string"?e.cwd:r[0],o=kr(ne(i,"Cursor cwd",kt),t.platform),s=ne(e.tool_name,"Cursor tool name",256),a=Mt(e.tool_input,"Cursor tool input"),l=fd(e.tool_use_id,"Cursor tool use id");return{sessionId:n,cwd:o,toolName:s,toolUseId:l,toolInput:a}}function Z6(e,t){if(e.hook_event_name!=="PreToolUse")throw new Error("Guardian accepts only GitHub Copilot's PascalCase PreToolUse event.");let n=ne(e.session_id,"GitHub Copilot session id",256);if(n!==t.expectedSessionId)throw new Error("GitHub Copilot session does not match the bound session.");let r=kr(ne(e.cwd,"GitHub Copilot cwd",kt),t.platform),i=ne(e.tool_name,"GitHub Copilot tool name",256),o=Mt(e.tool_input,"GitHub Copilot tool input");return{sessionId:n,cwd:r,toolName:i,toolUseId:null,toolInput:o}}function J6(e,t){if(e.hook_event_name!=="tool.execute.before")throw new Error("Strict OpenCode plugin accepts only the tool.execute.before event.");let n=ne(e.session_id,"OpenCode session id",256);if(n!==t.expectedSessionId)throw new Error("OpenCode session does not match the bound session.");let r=kr(ne(e.cwd,"OpenCode cwd",kt),t.platform),i=ne(e.tool_name,"OpenCode tool name",256),o=Mt(e.tool_input,"OpenCode tool input"),s=ne(e.call_id,"OpenCode call id",256);return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function Y6(e,t){let n=ne(e.agent_action_name,"Windsurf action name",128);if(!new Set(["pre_read_code","pre_write_code","pre_run_command","pre_mcp_tool_use"]).has(n))throw new Error("Guardian accepts only blocking Windsurf pre-action events.");let i=ne(e.trajectory_id,"Windsurf trajectory id",256);if(i!==t.expectedSessionId)throw new Error("Windsurf trajectory does not match the bound session.");let o=ne(e.execution_id,"Windsurf execution id",256),s=Mt(e.tool_info,"Windsurf tool info"),a=n==="pre_run_command"&&typeof s.cwd=="string"?s.cwd:e.cwd,l=kr(ne(a,"Windsurf cwd",kt),t.platform);if(n==="pre_read_code"||n==="pre_write_code"){let p=ne(s.file_path,"Windsurf file path",kt);return{sessionId:i,cwd:l,toolName:n==="pre_read_code"?"read_file":"write_file",toolUseId:o,toolInput:{path:p}}}if(n==="pre_run_command")return{sessionId:i,cwd:l,toolName:"shell_command",toolUseId:o,toolInput:{command:ne(s.command_line,"Windsurf command",ll)}};let c=ne(s.mcp_server_name,"Windsurf MCP server",256),u=ne(s.mcp_tool_name,"Windsurf MCP tool",256),d=Mt(s.mcp_tool_arguments,"Windsurf MCP arguments");return{sessionId:i,cwd:l,toolName:`mcp__${c}__${u}`,toolUseId:o,toolInput:d}}function X6(e,t){if(e.hook_event_name!==void 0&&e.hook_event_name!=="PreToolUse")throw new Error("Strict Antigravity hook accepts only the PreToolUse event.");let n=ne(e.conversationId,"Antigravity conversation id",256);if(n!==t.expectedSessionId)throw new Error("Antigravity conversation does not match the bound session.");let r=DR(e.workspacePaths,"Antigravity workspace paths",t.platform),i=Mt(e.toolCall,"Antigravity tool call"),o=ne(i.name,"Antigravity tool name",256),s=Mt(i.args,"Antigravity tool arguments"),a=fd(i.id,"Antigravity tool call id");return{sessionId:n,cwd:r[0],toolName:o,toolUseId:a,toolInput:s}}function Q6(e,t){if(e.hook_event_name!=="preToolUse")throw new Error("Strict Kiro hook accepts only the preToolUse event.");let n=ne(e.session_id,"Kiro session id",256);if(n!==t.expectedSessionId)throw new Error("Kiro session does not match the bound session.");let r=kr(ne(e.cwd,"Kiro cwd",kt),t.platform),i=ne(e.tool_name,"Kiro tool name",256),o=Mt(e.tool_input,"Kiro tool input"),s=fd(e.tool_use_id,"Kiro tool use id");return{sessionId:n,cwd:r,toolName:i,toolUseId:s,toolInput:o}}function eq(e){let t=e.toolName.toLowerCase();if(B6.has(t)){let n=e.toolInput.command??e.toolInput.cmd??e.toolInput.CommandLine,r=ne(n,`${e.toolName} command`,ll);if(r.trim().length===0)throw new Error(`${e.toolName} command cannot be empty.`);return{actionFamily:"shell_execution",command:r,fileTargets:[],networkTargets:[]}}if(M6.has(t)){let n=dy(e.toolInput,e.cwd,e.platform);return n.length===0&&n.push(e.cwd),{actionFamily:"filesystem_read",command:null,fileTargets:PR(n),networkTargets:[]}}if(U6.has(t)){let n=t==="apply_patch"?tq(e.toolInput,e.cwd,e.platform):dy(e.toolInput,e.cwd,e.platform);if(n.length===0)throw new Error(`${e.toolName} has no complete file target for strict mapping.`);return{actionFamily:"filesystem_write",command:null,fileTargets:PR(n),networkTargets:[]}}if(z6.has(t)){let n=e.toolInput.url,r=e.toolInput.query;if(t==="webfetch"||t==="web_fetch"){let i=LR(ne(n,`${e.toolName} URL`,kt));return{actionFamily:"network_access",command:null,fileTargets:[],networkTargets:[i]}}return ne(r,`${e.toolName} query`,ll),{actionFamily:"network_access",command:null,fileTargets:[],networkTargets:[]}}if(q6.has(t)||t.startsWith("browser__"))return{actionFamily:"browser_access",command:null,fileTargets:[],networkTargets:CR(e.toolInput)};if(V6.has(t))return{actionFamily:"device_control",command:null,fileTargets:[],networkTargets:[]};if(t==="use_aws"||t.startsWith("@")||t.startsWith("mcp__")||t.startsWith("mcp."))return{actionFamily:"api_access",command:null,fileTargets:dy(e.toolInput,e.cwd,e.platform),networkTargets:CR(e.toolInput)};throw new Error(`Tool ${e.toolName} has no strict mapping for ${e.agentId}.`)}function dy(e,t,n){let r=[],i=["file_path","path","notebook_path","directory","target_path","old_path","new_path","AbsolutePath"];for(let o of i)e[o]!==void 0&&r.push(ne(e[o],`${o} path`,kt));if(e.paths!==void 0){if(!Array.isArray(e.paths)||e.paths.length>64)throw new Error("Tool paths must be an array with no more than 64 entries.");for(let o of e.paths)r.push(ne(o,"tool path",kt))}return r.map(o=>OR(o,t,n))}function tq(e,t,n){let r=ne(e.patch??e.command,"apply_patch payload",ll),i=[];for(let o of r.split(/\r?\n/u)){if(!o.startsWith("*** ")||o==="*** Begin Patch"||o==="*** End Patch")continue;let s=/^(?:\*\*\* (?:Add|Update|Delete) File: |\*\*\* Move to: )(.*)$/u.exec(o);if(!s)throw new Error(`apply_patch contains an unsupported file directive: ${o}`);let a=s[1]?.trim();if(!a)throw new Error("apply_patch contains an empty file target.");i.push(OR(a,t,n))}if(i.length===0)throw new Error("apply_patch payload has no recognized file targets.");return i}function CR(e){return e.url===void 0?[]:[LR(ne(e.url,"tool URL",kt))]}function nq(e){if(!e||typeof e!="object")throw new Error("Strict hook attribution is required.");if(!N6.test(e.skillSlug))throw new Error("Strict hook attribution skill slug is invalid.");return TR(e.version,"attribution version"),al(e.generationId,"attribution generation id"),al(e.actorId,"attribution actor id"),al(e.tenantId,"attribution tenant id"),e.workspaceId!==void 0&&al(e.workspaceId,"attribution workspace id"),{skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,actorId:e.actorId,tenantId:e.tenantId,...e.workspaceId===void 0?{}:{workspaceId:e.workspaceId}}}function rq(e){let t=e;if(typeof e=="string"){if(Buffer.byteLength(e,"utf8")>SR)throw new Error("Host hook payload exceeds the maximum 256 KiB size.");try{t=JSON.parse(e)}catch{throw new Error("Host hook payload must be valid JSON.")}}iq(t);let n=ts(t);if(Buffer.byteLength(n,"utf8")>SR)throw new Error("Host hook payload exceeds the maximum 256 KiB size.");return Mt(t,"host hook payload")}function iq(e){let t=0,n=new Set,r=(i,o)=>{if(t+=1,t>D6)throw new Error("Host hook JSON contains too many values.");if(o>$6)throw new Error("Host hook JSON exceeds the maximum depth.");if(!(i===null||typeof i=="boolean")){if(typeof i=="string"){if(i.length>ll)throw new Error("Host hook JSON string is too long.");if(i.includes("\0"))throw new Error("Host hook JSON cannot contain NUL characters.");return}if(typeof i=="number"){if(!Number.isFinite(i))throw new Error("Host hook JSON numbers must be finite.");return}if(typeof i!="object")throw new Error("Host hook payload must contain JSON-compatible values only.");if(n.has(i))throw new Error("Host hook payload cannot contain cyclic objects.");if(n.add(i),Array.isArray(i)){if(i.length>T6)throw new Error("Host hook JSON array is too large.");for(let s of i)r(s,o+1)}else{let s=Object.getPrototypeOf(i);if(s!==Object.prototype&&s!==null)throw new Error("Host hook JSON objects must use a plain object prototype.");let a=Object.entries(i);if(a.length>O6)throw new Error("Host hook JSON object has too many keys.");for(let[l,c]of a){if(F6.has(l))throw new Error(`Host hook JSON contains unsafe key ${l}.`);if(l.length===0||l.length>256)throw new Error("Host hook JSON key length is invalid.");r(c,o+1)}}n.delete(i)}};r(e,0)}function Mt(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object.`);return e}function ne(e,t,n){if(typeof e!="string"||e.length===0||e.length>n||e.includes("\0"))throw new Error(`${t} must be a non-empty bounded string.`);return e}function fd(e,t){if(e==null)return null;let n=ne(e,t,256);if(!ER.test(n))throw new Error(`${t} is invalid.`);return n}function DR(e,t,n){if(!Array.isArray(e)||e.length===0||e.length>64)throw new Error(`${t} must contain between one and 64 paths.`);return e.map(r=>kr(ne(r,t,kt),n))}function al(e,t){if(typeof e!="string"||!ER.test(e))throw new Error(`${t} is invalid.`)}function TR(e,t){if(typeof e!="string"||!j6.test(e))throw new Error(`${t} is invalid.`)}function oq(e){if(e!=="darwin"&&e!=="linux"&&e!=="win32")throw new Error("Strict hook platform is unsupported.")}function sq(e,t,n){if(typeof e!="string"||e.trim().length===0||e.length>n||/[\u0000\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(e))throw new Error(`${t} is invalid.`)}function kr(e,t){if(e.length>kt||e.includes("\0"))throw new Error("Hook path is invalid.");let n=t==="win32"?RR:AR;if(!n.isAbsolute(e))throw new Error(`Hook path must be absolute for ${t}.`);return n.normalize(e)}function OR(e,t,n){let r=n==="win32"?RR:AR;if(e.length>kt||e.includes("\0"))throw new Error("Tool path is invalid.");return r.normalize(r.isAbsolute(e)?e:r.resolve(t,e))}function LR(e){let t;try{t=new URL(e)}catch{throw new Error("Network target must be a valid absolute URL.")}if(t.protocol!=="https:"&&t.protocol!=="http:"||t.username||t.password)throw new Error("Network target must be an HTTP(S) URL without embedded credentials.");return t.hash="",t.toString()}function aq(e){return JSON.parse(ts(e))}function py(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))py(t)}return e}function ts(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(n=>ts(n)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${ts(t[n])}`).join(",")}}`}function IR(e){return`sha256:${E6("sha256").update(e).digest("hex")}`}function PR(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}var dq=32,pq=1024,fq=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,jR=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,mq=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,gq=/^hmac-sha256:[a-f0-9]{64}$/u,hq=/^ed25519:[A-Za-z0-9_-]{86}$/u,yq=/^(?:sha256:)?[a-f0-9]{64}$/u,vq=/^[a-f0-9]{64}$/u,NR=Object.freeze({disabled:0,warning:1,enforce:2});function ul(e){let t=e.envelope;if(!t||typeof t!="object"||t.version!==1&&t.version!==2)throw new Error("Guardian attribution envelope version is invalid.");if(t.version===2){if(t.algorithm!=="ed25519"||t.issuer!=="skills-layer-cloud"||!hq.test(t.signature))throw new Error("Guardian attribution signature is invalid.");Ur(t.keyId,"Guardian attribution key id");let s=e.publicKeys?.[t.keyId];if(!s)throw new Error("Guardian attribution key is unknown.");let a=kq(t.claims),l={version:2,algorithm:"ed25519",keyId:t.keyId,issuer:t.issuer,claims:a},c=Buffer.from(t.signature.slice(8),"base64url");if(!uq(null,Buffer.from(md(l),"utf8"),s,c))throw new Error("Guardian attribution signature verification failed.");return FR(a,e)}if(!e.key)throw new Error("Guardian attribution key is required.");if(_q(e.key),Ur(t.keyId,"Guardian attribution key id"),typeof t.signature!="string"||!gq.test(t.signature))throw new Error("Guardian attribution signature is invalid.");let n=MR(t.claims),r=bq({version:1,keyId:t.keyId,claims:n},e.key),i=Buffer.from(t.signature.slice(12),"hex"),o=Buffer.from(r.slice(12),"hex");if(i.byteLength!==o.byteLength||!cq(i,o))throw new Error("Guardian attribution signature verification failed.");return FR(n,e)}async function fy(e){try{if(!e.attributionEnvelope||!e.attributionKey&&!e.attributionPublicKeys)throw new Error("Signed Guardian attribution is required.");let t=ul({...e.attributionKey?{key:e.attributionKey}:{},...e.attributionPublicKeys?{publicKeys:e.attributionPublicKeys}:{},envelope:e.attributionEnvelope,expectedAgentId:e.agentId,expectedPlatform:e.platform,now:e.now}),n=$R({agentId:e.agentId,platform:e.platform,hostVersion:e.hostVersion,expectedSessionId:t.sessionId,attribution:t,payload:e.rawPayload});if(wq(t.requestedMode,t.workspaceRequiredMode)==="disabled")return ns(e.agentId,{decision:"allow",reason:"Guardian is disabled for this personal skill session."});let i=await e.evaluate(n);return Sq(i),ns(e.agentId,{decision:i.decision,reason:UR(i.reason)})}catch{return ns(e.agentId,{decision:"deny",reason:"Guardian could not verify this action."})}}function MR(e){if(!e||typeof e!="object")throw new Error("Guardian attribution claims are required.");if(!vr(e.agentId))throw new Error("Guardian attribution agent is invalid.");if(e.platform!=="darwin"&&e.platform!=="linux"&&e.platform!=="win32")throw new Error("Guardian attribution platform is invalid.");if(!jR.test(e.hostVersion))throw new Error("Guardian attribution host version is invalid.");if(Ur(e.sessionId,"Guardian attribution session id"),!mq.test(e.skillSlug))throw new Error("Guardian attribution skill slug is invalid.");if(!jR.test(e.version))throw new Error("Guardian attribution skill version is invalid.");return Ur(e.generationId,"Guardian attribution generation id"),Ur(e.actorId,"Guardian attribution actor id"),Ur(e.tenantId,"Guardian attribution tenant id"),e.workspaceId!==void 0&&Ur(e.workspaceId,"Guardian attribution workspace id"),BR(e.requestedMode,"Guardian requested mode"),e.workspaceRequiredMode!==null&&BR(e.workspaceRequiredMode,"Guardian workspace-required mode"),cl(e.issuedAt,"Guardian attribution issuedAt"),cl(e.expiresAt,"Guardian attribution expiresAt"),my({agentId:e.agentId,platform:e.platform,hostVersion:e.hostVersion,sessionId:e.sessionId,skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,actorId:e.actorId,tenantId:e.tenantId,...e.workspaceId===void 0?{}:{workspaceId:e.workspaceId},requestedMode:e.requestedMode,workspaceRequiredMode:e.workspaceRequiredMode,issuedAt:e.issuedAt,expiresAt:e.expiresAt})}function kq(e){let t=MR(e);if(!yq.test(e.contractDigest))throw new Error("Guardian attribution contract digest is invalid.");if(!vq.test(e.archiveSha256))throw new Error("Guardian attribution archive digest is invalid.");if(!Number.isSafeInteger(e.policyRevision)||e.policyRevision<1)throw new Error("Guardian attribution policy revision is invalid.");return Ur(e.trustLedgerId,"Guardian attribution Trust Ledger id"),my({...t,contractDigest:e.contractDigest,archiveSha256:e.archiveSha256,policyRevision:e.policyRevision,trustLedgerId:e.trustLedgerId})}function FR(e,t){if(e.agentId!==t.expectedAgentId)throw new Error("Guardian attribution agent does not match this hook.");if(e.platform!==t.expectedPlatform)throw new Error("Guardian attribution platform does not match this hook.");let n=cl(t.now,"Guardian runtime timestamp"),r=cl(e.issuedAt,"Guardian attribution issuedAt"),i=cl(e.expiresAt,"Guardian attribution expiresAt");if(i.getTime()<=r.getTime())throw new Error("Guardian attribution expiry must follow issuance.");if(n.getTime()<r.getTime())throw new Error("Guardian attribution is not valid yet.");if(n.getTime()>i.getTime())throw new Error("Guardian attribution has expired.");return e}function wq(e,t){return t!==null&&NR[t]>NR[e]?t:e}function bq(e,t){return`hmac-sha256:${lq("sha256",t).update(md(e)).digest("hex")}`}function _q(e){if(!(e instanceof Uint8Array)||e.byteLength<dq||e.byteLength>pq)throw new Error("Guardian attribution key must contain between 32 and 1024 bytes.")}function Ur(e,t){if(typeof e!="string"||!fq.test(e))throw new Error(`${t} is invalid.`)}function BR(e,t){if(e!=="enforce"&&e!=="warning"&&e!=="disabled")throw new Error(`${t} is invalid.`)}function cl(e,t){let n=Date.parse(e);if(!Number.isFinite(n)||new Date(n).toISOString()!==e)throw new Error(`${t} is invalid.`);return new Date(n)}function Sq(e){if(!e||e.decision!=="allow"&&e.decision!=="deny")throw new Error("Guardian policy evaluator returned an invalid decision.");UR(e.reason)}function UR(e){if(typeof e!="string"||e.trim().length===0||e.length>900||/[\u0000\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(e))throw new Error("Guardian policy reason is invalid.");return e}function md(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(md).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${md(t[n])}`).join(",")}}`}function my(e){if(e&&typeof e=="object"){for(let t of Object.values(e))my(t);Object.freeze(e)}return e}import{createHash as zR}from"node:crypto";var qR=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,xq=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,rs=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,VR=/^sha256:[a-f0-9]{64}$/u,GR=4096;function HR(){return Object.freeze({version:2,revision:0,associations:Object.freeze({})})}function KR(e){if(!Hn(e)||e.version!==2||!Number.isSafeInteger(e.revision)||Number(e.revision)<0||!Hn(e.associations))throw new Error("Guardian session association index is invalid.");let t={};for(let[n,r]of Object.entries(e.associations)){if(!Hn(r))throw new Error("Guardian session association record is invalid.");let i=r;if(YR(i),tt(i)!==n)throw new Error("Guardian session association key does not match its exact identity.");t[n]=qr({...i})}return qr({version:2,revision:Number(e.revision),associations:t})}function Vr(e){let t={targetDir:e.targetDir,generation:e.generation,archiveSha256:e.archiveSha256,manifestSha256:e.manifestSha256,files:[...e.files].map(n=>({path:n.path,sizeBytes:n.sizeBytes,sha256:n.sha256})).sort((n,r)=>gy(n.path,r.path))};return Cq(gd(t))}function tt(e){return XR(e),`association_${zR("sha256").update(gd({scope:e.scope,agentId:e.agentId,sessionId:e.sessionId,skillSlug:e.skillSlug,skillVersion:e.skillVersion,generationId:e.generationId}),"utf8").digest("hex")}`}function WR(e,t,n){if(yd(e),e.revision!==n)throw new Error("Guardian association compare-and-swap revision changed.");YR(t);let r=tt(t),i=e.associations[r],o=qr({...t,revision:i?i.revision+1:1,createdAt:i?.createdAt??t.createdAt});return qr({version:2,revision:e.revision+1,associations:{...e.associations,[r]:o}})}function ZR(e,t){if(yd(e),e.revision!==t.expectedIndexRevision)throw new Error("Guardian association compare-and-swap revision changed.");let n=e.associations[t.key];if(!n)throw new Error("Guardian session association was not found.");os(t.updatedAt,"Guardian association update timestamp"),t.attributionExpiresAt!==void 0&&os(t.attributionExpiresAt,"Guardian attribution expiry"),t.trustLedgerId!==void 0&&zr(t.trustLedgerId,"Guardian Trust Ledger id"),t.reasonCode!==void 0&&is(t.reasonCode,"Guardian association reason code");let r=qr({...n,revision:n.revision+1,state:t.state,updatedAt:t.updatedAt,...t.attributionExpiresAt===void 0?{}:{attributionExpiresAt:t.attributionExpiresAt},...t.trustLedgerId===void 0?{}:{trustLedgerId:t.trustLedgerId},...t.reasonCode===void 0?{}:{reasonCode:t.reasonCode}});return qr({version:2,revision:e.revision+1,associations:{...e.associations,[t.key]:r}})}function pl(e,t){yd(e),zr(t.sessionId,"Guardian host session id");let n=os(t.asOf,"Guardian association lookup timestamp"),r=Object.values(e.associations).filter(s=>s.agentId===t.agentId&&s.sessionId===t.sessionId).sort((s,a)=>gy(tt(s),tt(a)));if(r.length===0)return{status:"unrelated",associations:[]};let i=r.filter(s=>s.state==="active");if(i.length>1)return{status:"ambiguous",associations:i};if(i.length===1){let s=i[0],a=s.attributionExpiresAt?Date.parse(s.attributionExpiresAt):Number.NaN;return Number.isFinite(a)&&a>n?{status:"active",associations:[s]}:{status:"active_authority_stale",associations:[s]}}let o=r.filter(s=>s.state==="pending_authority"||s.state==="stale");return o.length>0?{status:"expected_missing_authority",associations:o}:{status:"terminal",associations:r}}function JR(e,t){if(yd(e),e.revision!==t.expectedIndexRevision)throw new Error("Guardian association compare-and-swap revision changed.");if(!rs.test(t.skillSlug)||!qR.test(t.generationId)||!VR.test(t.receiptSha256))throw new Error("Guardian association forget identity is invalid.");let n=Object.entries(e.associations).flatMap(([i,o])=>o.skillSlug===t.skillSlug&&o.generationId===t.generationId&&o.receiptSha256===t.receiptSha256&&(o.state==="externally_removed"||o.state==="host_detached")?[i]:[]);if(n.length===0)return{index:e,removedKeys:[]};let r=new Set(n);return{index:qr({version:2,revision:e.revision+1,associations:Object.fromEntries(Object.entries(e.associations).filter(([i])=>!r.has(i)))}),removedKeys:[...n]}}function hd(e,t){if(!Hn(t))return null;if(e==="claude-code"){let n=Rn(t.session_id);if(t.hook_event_name==="UserPromptExpansion"&&t.expansion_type==="slash_command"){let r=Rn(t.command_name);if(n&&r&&rs.test(r))return dl(n,r,"slug","claude_user_prompt_expansion",`UserPromptExpansion:${r}`)}if(t.hook_event_name==="PreToolUse"&&t.tool_name==="Skill"){let r=Hn(t.tool_input)?t.tool_input:null,i=r?Rn(r.skill)??Rn(r.name):null;if(n&&i&&rs.test(i))return dl(n,i,"slug","claude_skill_tool",`Skill:${i}`)}return null}if(e==="gemini-cli"){let n=Rn(t.session_id),r=Hn(t.tool_input)?t.tool_input:null,i=r?Rn(r.name):null;return t.hook_event_name==="BeforeTool"&&t.tool_name==="activate_skill"&&n&&i&&rs.test(i)?dl(n,i,"slug","gemini_activate_skill",`activate_skill:${i}`):null}if(e==="antigravity"||e==="antigravity-cli"){let n=Rn(t.conversationId),r=Hn(t.toolCall)?t.toolCall:null,i=r&&Hn(r.args)?r.args:null,o=i?Rn(i.AbsolutePath):null;if(r?.name==="view_file"&&i?.IsSkillFile===!0&&n&&o)return dl(n,o,"path","antigravity_skill_file",`view_file:${o}`)}if(e==="opencode"){let n=Rn(t.session_id),r=Hn(t.tool_input)?t.tool_input:null,i=r?Rn(r.name)??Rn(r.skill):null;if(t.hook_event_name==="tool.execute.before"&&t.tool_name==="skill"&&n&&i&&rs.test(i))return dl(n,i,"slug","opencode_skill_tool",`skill:${i}`)}return null}function dl(e,t,n,r,i){return zr(e,"Guardian activation session id"),is(t,"Guardian activation skill reference"),is(i,"Guardian activation evidence"),Object.freeze({sessionId:e,skillReference:t,referenceKind:n,source:r,evidence:i})}function yd(e){if(!e||e.version!==2||!Number.isSafeInteger(e.revision)||e.revision<0||!Hn(e.associations))throw new Error("Guardian session association index is invalid.")}function YR(e){if(!e||e.version!==2||!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Guardian session association version is invalid.");if(XR(e),!VR.test(e.receiptSha256))throw new Error("Guardian association receipt digest is invalid.");if(e.requestedPreference!=="enforce"&&e.requestedPreference!=="warning_only"&&e.requestedPreference!=="disabled")throw new Error("Guardian association preference is invalid.");if(!["pending_authority","active","stale","externally_removed","host_detached"].includes(e.state))throw new Error("Guardian association state is invalid.");if(!["claude_skill_tool","claude_user_prompt_expansion","gemini_activate_skill","antigravity_skill_file","opencode_skill_tool","approved_launcher","manual_recovery"].includes(e.activationSource))throw new Error("Guardian activation source is invalid.");is(e.activationEvidence,"Guardian activation evidence"),is(e.adapterRevision,"Guardian adapter revision"),os(e.createdAt,"Guardian association creation timestamp"),os(e.updatedAt,"Guardian association update timestamp"),e.attributionExpiresAt!==void 0&&os(e.attributionExpiresAt,"Guardian attribution expiry"),e.trustLedgerId!==void 0&&zr(e.trustLedgerId,"Guardian Trust Ledger id"),e.workspaceId!==void 0&&zr(e.workspaceId,"Guardian workspace id"),e.reasonCode!==void 0&&is(e.reasonCode,"Guardian association reason code")}function XR(e){if(e.scope!=="project"&&e.scope!=="global")throw new Error("Guardian association scope is invalid.");if(zr(e.agentId,"Guardian association agent id"),zr(e.sessionId,"Guardian association session id"),!rs.test(e.skillSlug))throw new Error("Guardian association skill slug is invalid.");if(!xq.test(e.skillVersion))throw new Error("Guardian association skill version is invalid.");zr(e.generationId,"Guardian association generation id")}function zr(e,t){if(typeof e!="string"||!qR.test(e))throw new Error(`${t} is invalid.`)}function is(e,t){if(typeof e!="string"||e.length===0||e.length>GR||/[\u0000-\u001f\u007f]/u.test(e))throw new Error(`${t} is invalid.`)}function os(e,t){let n=Date.parse(e);if(!Number.isFinite(n)||new Date(n).toISOString()!==e)throw new Error(`${t} is invalid.`);return n}function Rn(e){return typeof e=="string"&&e.length>0&&e.length<=GR?e:null}function Hn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Cq(e){return`sha256:${zR("sha256").update(e,"utf8").digest("hex")}`}function gd(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(gd).join(",")}]`;let t=e;return`{${Object.keys(t).sort(gy).map(n=>`${JSON.stringify(n)}:${gd(t[n])}`).join(",")}}`}function gy(e,t){return e<t?-1:e>t?1:0}function qr(e){if(e&&typeof e=="object"){for(let t of Object.values(e))qr(t);Object.freeze(e)}return e}import{constants as QR}from"node:fs";import{lstat as Iq,open as Pq}from"node:fs/promises";import{createHash as Aq}from"node:crypto";import{posix as rE,win32 as iE}from"node:path";var Rq=/^sha256:[a-f0-9]{64}$/u,eE=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u,oE=/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u,Eq=4096,sE=6;function $q(e){return vd(fl(e))}function aE(e){let t=Oq(e.asOf,"asOf"),n=[],r=e.evidence;if(!r||typeof r!="object"||r.evidenceVersion!==1)return n.push("evidence_version_invalid"),{capability:"unverified",reasons:n};Tq(r.sourceUrl)||n.push("evidence_source_not_https");let i=ky(r.checkedAt);if(!i)n.push("evidence_checked_at_invalid");else{i.getTime()>t.getTime()&&n.push("evidence_from_future");let l=new Date(i.getTime());l.setUTCMonth(l.getUTCMonth()+sE),t.getTime()>l.getTime()&&n.push("evidence_stale")}tE(r.binding,"evidence",n),tE(e.currentBinding,"current",n);let o=r.binding&&typeof r.binding=="object"?$q(r.binding):null;(!ss(r.bindingDigest)||o===null||r.bindingDigest!==o)&&n.push("evidence_binding_digest_invalid"),(!r.binding||typeof r.binding!="object"||!e.currentBinding||typeof e.currentBinding!="object"||fl(nE(r.binding))!==fl(nE(e.currentBinding)))&&n.push("current_installation_binding_changed");let s=[r.allowCanary,r.denyCanary,r.argumentMutationCanary,r.missingAttributionCanary,r.enterpriseNonDowngradeCanary,r.handlerFailureCanary,r.handlerTimeoutCanary,r.activationCanary];Gr(r.allowCanary,"allow","allowed",!0,!1,r.bindingDigest,i,t,n),Gr(r.denyCanary,"deny","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.argumentMutationCanary,"argument_mutation","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.missingAttributionCanary,"missing_attribution","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.enterpriseNonDowngradeCanary,"enterprise_non_downgrade","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.handlerFailureCanary,"handler_failure","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.handlerTimeoutCanary,"handler_timeout","denied",!1,!1,r.bindingDigest,i,t,n),Gr(r.activationCanary,"activation_association","allowed",!1,!0,r.bindingDigest,i,t,n);let a=s.filter(l=>!!(l&&typeof l=="object"));if(new Set(a.map(l=>l.observationId)).size!==a.length&&n.push("canary_observations_not_distinct"),new Set(a.map(l=>l.fixtureId)).size!==a.length&&n.push("canary_fixtures_not_distinct"),new Set(a.map(l=>l.actionSha256)).size!==a.length&&n.push("canary_actions_not_distinct"),r.activationRoute!=="native_activation"&&r.activationRoute!=="approved_launcher"&&n.push("activation_route_invalid"),!r.qualification||typeof r.qualification!="object")n.push("qualification_missing");else{r.qualification.driver!=="skills-layer-real-host-canary-v1"&&n.push("qualification_driver_invalid");let l=r.binding?.platform;(l!=="darwin"&&l!=="linux"&&l!=="win32"||!vy(r.qualification.hostExecutablePath,l))&&n.push("qualification_host_executable_not_absolute"),ss(r.qualification.hostExecutableSha256)||n.push("qualification_host_digest_invalid"),ss(r.qualification.planSha256)||n.push("qualification_plan_digest_invalid")}return r.changedArgumentsInvalidateApproval||n.push("argument_mutation_not_verified"),r.missingAttributionFailsClosed||n.push("missing_attribution_not_fail_closed"),r.enterpriseEnforceNonDowngradeVerified||n.push("enterprise_mode_downgrade_not_blocked"),n.length===0?{capability:"strict",reasons:[]}:{capability:"unverified",reasons:[...new Set(n)]}}async function lE(e){if(!Gn(e.agentId))throw new Error(`No strict hook adapter exists for ${e.agentId}.`);if(e.adapterRevision!==Qt[e.agentId])throw new Error("Strict hook adapter revision does not match the implemented adapter.");if(!oE.test(e.hostVersion))throw new Error("Strict hook host version is invalid.");Dq(e.platform);let n=yy(e.hookConfigPath,e.platform,"hook config path"),r=yy(e.hookScriptPath,e.platform,"hook script path"),i=yy(e.absoluteCliPath,e.platform,"CLI path");if(new Set([n,r,i]).size!==3)throw new Error("Strict hook config, script, and CLI paths must be distinct.");let[o,s,a]=await Promise.all([hy(n,!1),hy(r,e.platform!=="win32"),hy(i,e.platform!=="win32")]);return Object.freeze({agentId:e.agentId,platform:e.platform,hostVersion:e.hostVersion,adapterRevision:e.adapterRevision,hookConfigPath:n,hookConfigSha256:vd(o),hookScriptPath:r,hookScriptSha256:vd(s),absoluteCliPath:i,cliSha256:vd(a)})}function tE(e,t,n){if(!e||typeof e!="object"){n.push(`${t}_binding_missing`);return}let r=Gn(e.agentId);if(r||n.push(`${t}_agent_has_no_strict_adapter`),e.platform!=="darwin"&&e.platform!=="linux"&&e.platform!=="win32"){n.push(`${t}_platform_invalid`);return}oE.test(e.hostVersion)||n.push(`${t}_host_version_invalid`),(!r||e.adapterRevision!==r.adapterRevision)&&n.push(`${t}_adapter_revision_invalid`);let i=[e.hookConfigPath,e.hookScriptPath,e.absoluteCliPath];for(let[o,s]of i.entries())vy(s,e.platform)||n.push(`${t}_path_${o}_not_absolute`);new Set(i).size!==i.length&&n.push(`${t}_paths_not_distinct`);for(let[o,s]of[e.hookConfigSha256,e.hookScriptSha256,e.cliSha256].entries())ss(s)||n.push(`${t}_digest_${o}_invalid`)}function nE(e){let{hostVersion:t,...n}=e;return n}function Gr(e,t,n,r,i,o,s,a,l){if(!e||typeof e!="object"){l.push(`${t}_canary_missing`);return}e.kind!==t&&l.push(`${t}_canary_kind_invalid`),eE.test(e.observationId)||l.push(`${t}_observation_id_invalid`),eE.test(e.fixtureId)||l.push(`${t}_fixture_id_invalid`);let c=ky(e.observedAt);if(!c)l.push(`${t}_observed_at_invalid`);else if(s&&c.getTime()>s.getTime())l.push(`${t}_observation_after_evidence`);else{let u=new Date(c.getTime());u.setUTCMonth(u.getUTCMonth()+sE),a.getTime()>u.getTime()&&l.push(`${t}_canary_stale`)}e.realHostExecution||l.push(`${t}_not_real_host_execution`),(!ss(e.bindingDigest)||e.bindingDigest!==o)&&l.push(`${t}_binding_digest_mismatch`),ss(e.actionSha256)||l.push(`${t}_action_digest_invalid`),e.hostOutcome!==n&&l.push(`${t}_host_outcome_invalid`),e.sideEffectObserved!==r&&l.push(`${t}_side_effect_invalid`),e.associationObserved!==i&&l.push(`${t}_association_invalid`)}async function hy(e,t){let n=await Iq(e);if(n.isSymbolicLink())throw new Error(`Strict hook path is a symbolic link: ${e}`);if(!n.isFile())throw new Error(`Strict hook path must be a regular file: ${e}`);let r=await Pq(e,QR.O_RDONLY|QR.O_NOFOLLOW);try{let i=await r.stat();if(!i.isFile())throw new Error(`Strict hook path must be a regular file: ${e}`);if(t&&(i.mode&73)===0)throw new Error(`Strict hook executable path has no execute bit: ${e}`);return new Uint8Array(await r.readFile())}finally{await r.close()}}function yy(e,t,n){if(!vy(e,t))throw new Error(`Strict ${n} must be absolute for ${t}.`);return(t==="win32"?iE:rE).normalize(e)}function vy(e,t){return typeof e!="string"||e.length===0||e.length>Eq||e.includes("\0")?!1:(t==="win32"?iE:rE).isAbsolute(e)}function Dq(e){if(e!=="darwin"&&e!=="linux"&&e!=="win32")throw new Error("Strict hook platform is unsupported.")}function ss(e){return typeof e=="string"&&Rq.test(e)}function Tq(e){if(typeof e!="string")return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.username.length===0&&t.password.length===0}catch{return!1}}function Oq(e,t){let n=ky(e);if(!n)throw new Error(`${t} must be a valid ISO date.`);return n}function ky(e){if(typeof e!="string"||e.length===0)return null;let t=Date.parse(e);if(!Number.isFinite(t))return null;let n=new Date(t);return n.toISOString()===e?n:null}function fl(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(fl).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${fl(t[n])}`).join(",")}}`}function vd(e){return`sha256:${Aq("sha256").update(e).digest("hex")}`}import{createHash as Lq}from"node:crypto";import{constants as Hr}from"node:fs";import{open as uE}from"node:fs/promises";import{isAbsolute as jq}from"node:path";var gl="skills-layer-real-host-canary-v1",Nq=new Set(["allow","deny","argument_mutation","missing_attribution","enterprise_non_downgrade","handler_failure","handler_timeout","activation_association"]),Fq=/^[A-Za-z0-9_-]{43}$/u,dE=/^association_[a-f0-9]{64}$/u,Bq=4096,Mq=512*1024,Uq=16*1024;function ls(e){return hl(e)?.scenario??null}async function by(e){let t=hl(e.env);if(!t||e.activationEvent&&t.scenario!=="activation_association")return!1;let n=e.reportingSource??"hook";if(n==="hook"&&(e.delegatedExecution===!0||cE(e.agentId,e.result)?.value?.includes("atomic guarded execution wrapper")||t.scenario!=="activation_association"&&t.sideEffectPath&&!zq(e.rawPayloadBase64,t.sideEffectPath)))return!1;let r="invalid";try{let i=e.rawPayloadBase64??"";if(Buffer.byteLength(i,"utf8")>Mq)throw new Error("Guardian canary payload is too large.");if(r=n==="guarded_execution"?e.result.exitCode===0?"allowed":"denied":Vq(e.agentId,e.result),t.scenario==="missing_attribution"){if(e.associationState!=="missing"||r!=="denied")throw new Error("Guardian missing attribution canary requires no active association and a denied host outcome.")}else if(e.associationState!=="active")throw new Error("Guardian canary requires an active exact skill-session association.");let o=kd(t.challenge),s=kd(`${t.scenario}\0${i}`);try{await wd(t.resultPath,{challenge:t.challenge,driver:gl,agentId:e.agentId,scenario:t.scenario,associationState:e.associationState,observationId:`guardian-canary-${t.scenario}-${o.slice(7,31)}`,fixtureId:`guardian-fixture-${e.agentId}-${t.scenario}-${s.slice(7,23)}`,actionSha256:s,hostOutcome:r})}catch(a){if(a.code==="EEXIST")return!1;throw a}return!0}catch(i){let o=cE(e.agentId,e.result);throw await wd(t.diagnosticPath,{schemaVersion:"skills-layer.guardian-canary-diagnostic.v1",challengeDigest:kd(t.challenge),driver:gl,agentId:e.agentId,scenario:t.scenario,associationState:e.associationState,activationEvent:e.activationEvent,hostOutcome:r,failureCode:qq(i),...o?{decisionReasonCode:o.code,decisionReasonSha256:kd(o.value)}:{}}).catch(()=>{}),i}}async function pE(e){let t=hl(e);return!t||t.scenario!=="activation_association"?!1:(await wd(t.associationPath,{challenge:t.challenge,associationEstablished:!0}),!0)}async function fE(e){let t=hl(e.env);if(!t)return!1;if(!dE.test(e.associationKey))throw new Error("Guardian canary delegation association key is invalid.");try{await wd(t.delegationPath,{challenge:t.challenge,driver:gl,agentId:e.agentId,scope:e.scope,skillSlug:e.skillSlug,associationKey:e.associationKey})}catch(n){if(n.code==="EEXIST")return!1;throw n}return!0}async function mE(e){let t=hl(e.env);if(!t)return null;let n;try{n=await Gq(t.delegationPath)}catch(r){if(r.code==="ENOENT")return null;throw r}if(!as(n)||n.challenge!==t.challenge||n.driver!==gl||typeof n.agentId!="string"||typeof n.scope!="string"||typeof n.skillSlug!="string"||typeof n.associationKey!="string"||!dE.test(n.associationKey))throw new Error("Guardian canary delegation receipt is invalid.");return n.agentId!==e.agentId||n.scope!==e.scope||n.skillSlug!==e.skillSlug?null:{associationKey:n.associationKey}}function hl(e){let t=e.SKILLS_LAYER_GUARDIAN_CANARY_DRIVER,n=e.SKILLS_LAYER_GUARDIAN_CANARY_SCENARIO,r=e.SKILLS_LAYER_GUARDIAN_CANARY_CHALLENGE,i=e.SKILLS_LAYER_GUARDIAN_CANARY_RESULT_PATH,o=e.SKILLS_LAYER_GUARDIAN_CANARY_ASSOCIATION_PATH,s=e.SKILLS_LAYER_GUARDIAN_CANARY_DELEGATION_PATH,a=e.SKILLS_LAYER_GUARDIAN_CANARY_DIAGNOSTIC_PATH,l=e.SKILLS_LAYER_GUARDIAN_CANARY_SIDE_EFFECT_PATH;if([t,n,r,i,o,s,a].filter(u=>u!==void 0).length===0)return null;if(t!==gl||!n||!Nq.has(n)||!r||!Fq.test(r)||!ml(i)||!ml(o)||!ml(s)||!ml(a)||l!==void 0&&!ml(l)||new Set([i,o,s,a,...l?[l]:[]]).size!==(l?5:4))throw new Error("Guardian canary context is invalid.");return{scenario:n,challenge:r,resultPath:i,associationPath:o,delegationPath:s,diagnosticPath:a,...l?{sideEffectPath:l}:{}}}function zq(e,t){if(!e)return!1;try{let n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return wy(n,t,0)}catch{return!1}}function wy(e,t,n){return n>16?!1:typeof e=="string"?e.includes(t):Array.isArray(e)?e.some(r=>wy(r,t,n+1)):as(e)?Object.values(e).some(r=>wy(r,t,n+1)):!1}function qq(e){let t=e instanceof Error?e.message:String(e);return t.includes("payload is too large")?"payload_too_large":t.includes("hook result is invalid")?"hook_result_invalid":t.includes("decision output is invalid")?"hook_decision_invalid":t.includes("missing attribution canary")?"missing_attribution_contract_mismatch":t.includes("active exact skill-session association")?"exact_association_not_active":"canary_result_rejected"}function cE(e,t){let n=t.exitCode===0?void 0:t.stderr;if(t.exitCode===0)try{let o=JSON.parse(t.stdout);as(o)&&(e==="cline"?n=o.errorMessage:e==="gemini-cli"||e==="antigravity"||e==="antigravity-cli"?n=o.reason:e==="cursor"?n=o.user_message??o.agent_message:n=(as(o.hookSpecificOutput)?o.hookSpecificOutput:null)?.permissionDecisionReason)}catch{return}if(typeof n!="string"||n.length===0)return;let r=n.slice(0,1024),i=r.match(/verified enforcement is unavailable \(([a-z][a-z0-9_]{0,127})\)/u)?.[1];return i?{code:i,value:r}:r.includes("Guardian attribution is not valid yet.")?{code:"guardian_attribution_not_valid_yet",value:r}:r.includes("could not establish exact skill-session authority")?{code:"guardian_session_authority_unavailable",value:r}:r.includes("could not safely record this exact skill-session association")?{code:"guardian_association_persistence_failed",value:r}:r.includes("managed launch no longer matches the exact installed generation")?{code:"guardian_managed_launch_generation_mismatch",value:r}:r.includes("invalid, expired, replayed, or host-mismatched managed launch token")?{code:"guardian_managed_launch_rejected",value:r}:{code:"unclassified_guardian_decision",value:r}}function Vq(e,t){if(!Number.isSafeInteger(t.exitCode)||typeof t.stdout!="string"||typeof t.stderr!="string")throw new Error("Guardian canary hook result is invalid.");if(t.exitCode!==0)return"denied";if(e==="kiro-cli"||e==="opencode"||e==="windsurf"||e==="github-copilot")return"allowed";let n;try{n=JSON.parse(t.stdout)}catch{throw new Error("Guardian canary hook decision output is invalid.")}if(!as(n))throw new Error("Guardian canary hook decision output is invalid.");if(e==="cline")return n.cancel===!0?"denied":"allowed";if(e==="gemini-cli"||e==="antigravity"||e==="antigravity-cli"){if(n.decision==="deny")return"denied";if(n.decision==="allow")return"allowed"}else if(e==="cursor"){if(n.permission==="deny")return"denied";if(n.permission==="allow")return"allowed"}else{let r=as(n.hookSpecificOutput)?n.hookSpecificOutput:null;if(r?.permissionDecision==="deny")return"denied";if(r?.permissionDecision==="allow")return"allowed"}throw new Error("Guardian canary hook decision output is invalid.")}async function wd(e,t){let n=typeof Hr.O_NOFOLLOW=="number"?Hr.O_NOFOLLOW:0,r=await uE(e,Hr.O_CREAT|Hr.O_EXCL|Hr.O_WRONLY|n,384);try{await r.writeFile(`${JSON.stringify(t)}
|
|
693
693
|
`,"utf8"),await r.sync()}finally{await r.close()}}async function Gq(e){let t=typeof Hr.O_NOFOLLOW=="number"?Hr.O_NOFOLLOW:0,n=await uE(e,Hr.O_RDONLY|t);try{let r=await n.stat();if(!r.isFile()||r.size>Uq)throw new Error("Guardian canary delegation receipt is invalid.");return JSON.parse(await n.readFile("utf8"))}catch(r){throw r instanceof SyntaxError?new Error("Guardian canary delegation receipt is invalid."):r}finally{await n.close()}}function ml(e){return typeof e=="string"&&Buffer.byteLength(e,"utf8")<=Bq&&jq(e)}function kd(e){return`sha256:${Lq("sha256").update(e,"utf8").digest("hex")}`}function as(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}var gE=Object.freeze(["SKILLS_LAYER_GUARDIAN_CANARY_DRIVER","SKILLS_LAYER_GUARDIAN_CANARY_SIDE_EFFECT_PATH"]);function hE(e){let t=Hq(e.command,e.platform);if(!t)return!1;let n;try{n=vE(e)}catch{return!1}return t.length>n.length&&n.every((r,i)=>t[i]===r)}function yE(e){return vE(e).map(n=>Kq(n,e.platform)).join(" ")}function vE(e){let t=e.approvedEnvironmentKeys??[];if(t.length>16||new Set(t).size!==t.length||t.some(r=>!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u.test(r)))throw new Error("Strict Guardian execution route has an invalid environment key contract.");let n=e.platform==="win32"?["&",e.runtimeExecutablePath,e.cliPath,"guardian","exec",e.skillSlug]:[e.cliPath,"guardian","exec",e.skillSlug];for(let r of t)n.push("--secret-env",r);return n.push("--"),n}function Hq(e,t){if(e.length===0||e.length>65536||/[\r\n\0]/u.test(e))return null;let n=[],r="",i=!1,o=null,s=0;if(t==="win32"){let a=/^\s*/u.exec(e)[0].length;if(e[a]!=="&"||!/\s/u.test(e[a+1]??""))return null;n.push("&"),s=a+1}for(let a=s;a<e.length;a+=1){let l=e[a];if(o==="single"){l==="'"?o=null:r+=l;continue}if(o==="double"){if(l==='"')o=null;else{if(t==="win32"?l==="%"||l==="!"||l==="$"||l==="`":l==="$"||l==="`")return null;if(t!=="win32"&&l==="\\"){let u=e[++a];if(u===void 0)return null;r+=u}else r+=l}continue}if(/\s/u.test(l)){i&&(n.push(r),r="",i=!1);continue}if(l==="'"){if(t==="win32")return null;o="single",i=!0;continue}if(l==='"'){o="double",i=!0;continue}if((t==="win32"?/[;&|<>^()%!$`{}]/u:/[;&|<>()[\]{}*?~#$`]/u).test(l))return null;if(t!=="win32"&&l==="\\"){let u=e[++a];if(u===void 0)return null;r+=u}else r+=l;i=!0}return o?null:(i&&n.push(r),n)}function Kq(e,t){return t==="win32"&&e==="&"||/^[A-Za-z0-9_./:\\-]+$/u.test(e)?e:t==="win32"?`"${e.replaceAll('"','\\"')}"`:`'${e.replaceAll("'",`'"'"'`)}'`}var kE={disabled:0,warning:1,enforce:2},Wq=/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u;function wE(e){bE(e.requestedMode),e.workspacePolicy!==null&&Zq(e.workspacePolicy);let t=e.workspacePolicy?.requiredMode,n=t!==void 0&&kE[t]>kE[e.requestedMode]?t:e.requestedMode;if(n==="enforce"){if(e.strictAdapterVerified)return{status:"active",effectiveMode:"enforce",protectionLabel:"strict_enforced",countedAsEnforced:!0,activationAllowed:!0,reasonCode:t==="enforce"?"workspace_enforce_non_downgrade":"verified_strict_adapter"};if(e.verifiedGuardedWrapper)return{status:"active",effectiveMode:"enforce",protectionLabel:"strict_enforced_via_wrapper",countedAsEnforced:!0,activationAllowed:!0,reasonCode:t==="enforce"?"workspace_enforce_via_wrapper":"verified_guarded_wrapper"};let r=t==="enforce";return{status:r?"refused":"unavailable",effectiveMode:null,protectionLabel:r?"strict_required_unavailable":"strict_unavailable",countedAsEnforced:!1,activationAllowed:!1,reasonCode:r?"workspace_strict_route_unavailable":"no_verified_strict_route"}}return n==="warning"?{status:"active",effectiveMode:"warning",protectionLabel:"warning_only",countedAsEnforced:!1,activationAllowed:!0,reasonCode:t==="warning"?"workspace_warning_non_downgrade":"personal_warning"}:{status:"active",effectiveMode:"disabled",protectionLabel:"disabled",countedAsEnforced:!1,activationAllowed:!0,reasonCode:t==="disabled"?"workspace_mode_satisfied":"personal_disabled"}}function Zq(e){if(bE(e.requiredMode),!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Workspace Guardian policy revision is invalid.");if(!Wq.test(e.updatedBy))throw new Error("Workspace Guardian policy updater is invalid.");if(!Jq(e.updatedAt))throw new Error("Workspace Guardian policy timestamp is invalid.")}function bE(e){if(e!=="enforce"&&e!=="warning"&&e!=="disabled")throw new Error("Guardian host mode is invalid.")}function Jq(e){let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}var Yq=Object.freeze([En("codex",["cli"],!0,"approved_launcher_required","inspectable_local_state","strict_candidate","explicit deny","https://github.com/openai/codex","exact_activation_signal_unverified"),En("claude-code",["cli","ide"],!0,"native_activation","inspectable_local_state","strict_candidate","explicit deny or exit 2","https://code.claude.com/docs/en/hooks","live_canary_required"),En("cline",["ide"],!0,"approved_launcher_required","inspectable_local_state","strict_candidate","cancel=true","https://docs.cline.bot/customization/hooks","exact_activation_signal_unverified"),En("gemini-cli",["cli"],!0,"native_activation","inspectable_local_state","strict_candidate","explicit deny or exit 2","https://geminicli.com/docs/hooks/reference/","live_canary_required"),En("antigravity",["ide"],!0,"native_activation","inspectable_local_state","strict_candidate","explicit deny","https://antigravity.google/docs/hooks?tab=ide","failure_timeout_canary_required"),En("antigravity-cli",["cli"],!0,"native_activation","inspectable_local_state","strict_candidate","explicit deny","https://antigravity.google/docs/hooks?tab=cli","failure_timeout_canary_required"),En("cursor",["local_ide"],!0,"approved_launcher_required","inspectable_local_state","strict_candidate","permission=deny and failClosed=true","https://cursor.com/docs/hooks","exact_activation_signal_unavailable"),En("kiro-cli",["cli"],!0,"approved_launcher_required","inspectable_local_state","strict_candidate","non-zero exit blocks","https://kiro.dev/docs/hooks/types/","exact_activation_signal_unverified"),En("windsurf",["local_ide"],!0,"unavailable","best_effort","warning_audit","event-specific exit 2","https://docs.windsurf.com/windsurf/cascade/hooks","privileged_surface_incomplete"),En("github-copilot",["cli","cloud_agent"],!0,"unavailable","best_effort","warning_audit","command-hook errors deny but timeouts always fail open","https://docs.github.com/en/copilot/reference/hooks-reference","hook_timeout_fail_open"),En("opencode",["cli"],!0,"native_activation","inspectable_local_state","strict_candidate","plugin tool.execute.before throws before execution","https://opencode.ai/docs/plugins/","plugin_canary_required")]);function wr(e){return Yq.find(t=>t.agentId===e)??null}function yl(e){if(e.materializationState==="externally_removed"||e.associationState==="externally_removed")return Kr("externally_removed","exact_target_absent");if(e.materializationState==="host_detached"||e.associationState==="host_detached")return Kr("host_detached","host_registration_detached");if(e.materializationState==="unreadable"||e.materializationState==="drifted"||e.associationState==="stale")return Kr("stale_binding","exact_local_authority_stale");let t=wE({requestedMode:e.requestedMode,strictAdapterVerified:e.strictHookVerified,verifiedGuardedWrapper:e.completeWrapperVerified,workspacePolicy:e.workspacePolicy});return t.effectiveMode==="warning"?Object.freeze({label:"warning_only",countedAsEnforced:!1,activationAllowed:!0,runtimeGuardian:e.hookInstalled&&e.associationState==="active",reasonCode:e.hookInstalled&&e.associationState==="active"?t.reasonCode:"activation_scan_only"}):t.effectiveMode==="disabled"?Object.freeze({label:"disabled",countedAsEnforced:!1,activationAllowed:!0,runtimeGuardian:!1,reasonCode:t.reasonCode}):e.hostSupported?e.strictHookVerified&&!e.exactActivationVerified&&!e.completeWrapperVerified?Kr("candidate_unverified","no_verified_exact_activation_route"):e.hookInstalled&&!e.strictHookVerified&&!e.completeWrapperVerified?Kr("candidate_unverified",t.reasonCode):t.activationAllowed?e.evaluationContext==="runtime"&&!e.completeWrapperVerified&&e.associationState!=="active"?Kr("candidate_unverified",e.associationState==="pending_authority"?"exact_skill_session_authority_pending":"exact_skill_session_not_active"):Object.freeze({label:t.protectionLabel==="strict_enforced_via_wrapper"?"strict_enforced_via_wrapper":"strict_enforced",countedAsEnforced:!0,activationAllowed:!0,runtimeGuardian:!0,reasonCode:t.reasonCode}):Kr("unavailable",t.reasonCode):Kr("host_unsupported","host_has_no_supported_guardian_route")}function En(e,t,n,r,i,o,s,a,l){return Object.freeze({agentId:e,surfaces:Object.freeze([...t]),adapterImplemented:n,automaticAssociation:r,uninstallSignal:i,maximumTier:o,failureContract:s,sourceUrl:a,sourceCheckedAt:"2026-09-25",reasonCode:l})}function Kr(e,t){return Object.freeze({label:e,countedAsEnforced:!1,activationAllowed:!1,runtimeGuardian:!1,reasonCode:t})}import{createHash as Xq,randomBytes as Qq}from"node:crypto";import{constants as Ut}from"node:fs";import{chmod as _E,lstat as PE,open as kl,realpath as e4,rename as SE,unlink as vl}from"node:fs/promises";import{basename as bd,dirname as t4,isAbsolute as AE,join as _d}from"node:path";var n4=1024*1024,r4=32,i4=2e4,RE=4096,o4=/^sha256:[a-f0-9]{64}$/u,s4=new Set(["__proto__","constructor","prototype"]);function a4(e){let t=c4(e.agentId),n=u4(t,e.eventName);p4(e.absoluteScriptPath);let r=xE(e.existingJson),i=m4(r,n),o=l4(t,n,e.absoluteScriptPath),s=IE(o),a=Object.freeze({owner:"skills-layer",agentId:t,eventName:n,entrySha256:s}),l;if(e.operation==="install"){if(e.previousOwnership!==void 0)throw new Error("Install must not supply previous Skills Layer ownership evidence.");l=[...i,o]}else{let u=d4(e.previousOwnership,t,n),d=i.flatMap((m,h)=>IE(m)===u.entrySha256?[h]:[]);if(d.length===0)throw new Error("Previous Skills Layer hook ownership could not be proven; refusing to modify host config.");let p=d[0];l=[];for(let[m,h]of i.entries())m===p&&l.push(o),d.includes(m)||l.push(h)}g4(r,n,l);let c=wl(xE(e.existingJson))!==wl(r);return{json:c?`${JSON.stringify(r,null,2)}
|
|
694
694
|
`:e.existingJson,changed:c,ownership:a}}async function xd(e){if(!AE(e.configPath)||e.configPath.length>RE||e.configPath.includes("\0"))throw new Error("Host hook config path must be an absolute bounded path.");let t=t4(e.configPath),n=await PE(t);if(n.isSymbolicLink()||!n.isDirectory())throw new Error("Host hook config parent must be a real directory, not a symbolic link.");let r=await e4(t),i=_d(r,bd(e.configPath)),o=Qq(12).toString("hex"),s=_d(r,`.${bd(i)}.skills-layer.lock`),a=_d(r,`.${bd(i)}.skills-layer-stage-${o}`),l=_d(r,`.${bd(i)}.skills-layer-backup-${o}`),c=null,u=!1,d=null,p=null,m=384,h=!1,g=!1;try{c=await kl(s,Ut.O_CREAT|Ut.O_EXCL|Ut.O_WRONLY,384),u=!0,await c.writeFile(`${process.pid}
|
|
695
695
|
`,"utf8"),await c.sync();let y=await Sy(i);p=y?.bytes??null,m=y?.mode??384;let v=p===null?"{}":Buffer.from(p).toString("utf8"),b=a4({...e.update,existingJson:v});if(!b.changed)return{...b,configPath:i,configSha256:Cy(p)};let w=new TextEncoder().encode(b.json);if(d=await kl(a,Ut.O_CREAT|Ut.O_EXCL|Ut.O_WRONLY|Ut.O_NOFOLLOW,384),await d.writeFile(w),await d.sync(),await d.close(),d=null,p!==null){let P=await kl(l,Ut.O_CREAT|Ut.O_EXCL|Ut.O_WRONLY|Ut.O_NOFOLLOW,384);try{await P.writeFile(p),await P.sync()}finally{await P.close()}h=!0}await Sd(r),await e.checkpoint?.("after_backup");let _=await Sy(i);if(!h4(p,_?.bytes??null))throw new Error("Host hook config changed concurrently; refusing to overwrite it.");await SE(a,i),g=!0,await _E(i,384),await Sd(r),await e.checkpoint?.("after_replace");let C=await CE(i);if(!xy(C.bytes,w))throw new Error("Atomic host hook config verification failed after replacement.");return h&&(await vl(l),h=!1),await Sd(r),{...b,configPath:i,configSha256:Cy(C.bytes)}}catch(y){if(g)try{if(p===null)await vl(i).catch(v=>{if(v.code!=="ENOENT")throw v});else{if(!h)throw new Error("Host hook rollback backup is unavailable.");await _E(l,m&511),await SE(l,i),h=!1;let v=await CE(i);if(!xy(v.bytes,p))throw new Error("Host hook rollback verification failed.")}await Sd(r)}catch(v){throw new AggregateError([y,v],"Host hook config update and exact rollback both failed.")}throw y}finally{d&&await d.close().catch(()=>{}),c&&await c.close(),await vl(a).catch(_y),h&&await vl(l).catch(_y),u&&await vl(s).catch(_y)}}function l4(e,t,n){return e==="cursor"?{command:n,matcher:"*",failClosed:!0}:e==="windsurf"?{command:n,show_output:!0}:{matcher:e==="codex"?".*":t==="UserPromptExpansion"?"*":"",hooks:[{type:"command",command:n,timeout:10}]}}function c4(e){if(e==="cline")throw new Error("Cline uses file-based hook discovery; JSON hook configuration is not supported.");if(e!=="codex"&&e!=="claude-code"&&e!=="gemini-cli"&&e!=="cursor"&&e!=="windsurf"&&e!=="antigravity"&&e!=="antigravity-cli")throw new Error(`${e} does not use the Claude-compatible owned JSON hook configuration.`);return e}function u4(e,t){let n=e==="gemini-cli"?"BeforeTool":e==="cursor"?"preToolUse":e==="windsurf"?"pre_run_command":"PreToolUse",r=t??n;if(r==="UserPromptExpansion"&&e==="claude-code"||e==="windsurf"&&(r==="pre_read_code"||r==="pre_write_code"||r==="pre_run_command"||r==="pre_mcp_tool_use"))return r;if(r!==n)throw new Error(`Hook event ${r} is not valid for ${e}.`);return r}function d4(e,t,n){if(!e||e.owner!=="skills-layer"||e.agentId!==t||e.eventName!==n||!o4.test(e.entrySha256))throw new Error("Valid prior Skills Layer hook ownership evidence is required.");return e}function p4(e){if(!AE(e)||e.length===0||e.length>RE||e.includes("\0"))throw new Error("Guardian hook script path must be absolute and bounded.")}function xE(e){if(typeof e!="string"||Buffer.byteLength(e,"utf8")>n4)throw new Error("Host hook config exceeds the 1 MiB maximum.");let t;try{t=JSON.parse(e)}catch{throw new Error("Host hook config must be valid JSON.")}if(f4(t),!Cd(t))throw new Error("Host hook config root must be a JSON object.");return t}function f4(e){let t=0,n=(r,i)=>{if(t+=1,t>i4)throw new Error("Host hook config contains too many JSON values.");if(i>r4)throw new Error("Host hook config exceeds the maximum JSON depth.");if(!(r===null||typeof r=="string"||typeof r=="boolean")){if(typeof r=="number"){if(!Number.isFinite(r))throw new Error("Host hook config contains a non-finite number.");return}if(Array.isArray(r)){for(let o of r)n(o,i+1);return}if(!Cd(r))throw new Error("Host hook config contains a non-JSON value.");for(let[o,s]of Object.entries(r)){if(s4.has(o))throw new Error(`Host hook config contains unsafe key ${o}.`);n(s,i+1)}}};n(e,0)}function m4(e,t){if(e.hooks===void 0&&(e.hooks={}),!Cd(e.hooks))throw new Error("Host hook config hooks field must be an object.");if(e.hooks[t]===void 0&&(e.hooks[t]=[]),!Array.isArray(e.hooks[t]))throw new Error(`Host hook config hooks.${t} must be an array.`);return e.hooks[t]}function g4(e,t,n){let r=e.hooks;if(!Cd(r))throw new Error("Host hook config hooks field must be an object.");r[t]=n}function Cd(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}async function Sy(e){let t;try{t=await PE(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(t.isSymbolicLink())throw new Error(`Host hook config target is a symbolic link: ${e}`);if(!t.isFile())throw new Error(`Host hook config target must be a regular file: ${e}`);let n=await kl(e,Ut.O_RDONLY|Ut.O_NOFOLLOW);try{let r=await n.stat();if(!r.isFile())throw new Error(`Host hook config target must be a regular file: ${e}`);return{bytes:new Uint8Array(await n.readFile()),mode:r.mode}}finally{await n.close()}}async function CE(e){let t=await Sy(e);if(!t)throw new Error(`Host hook config disappeared: ${e}`);return t}async function Sd(e){let t=await kl(e,Ut.O_RDONLY);try{await t.sync()}finally{await t.close()}}function h4(e,t){return e===null||t===null?e===t:xy(e,t)}function xy(e,t){return e.byteLength===t.byteLength&&Buffer.from(e).equals(Buffer.from(t))}function _y(e){if(e.code!=="ENOENT")throw e}function IE(e){return Cy(wl(e))}function wl(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(wl).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${wl(t[n])}`).join(",")}}`}function Cy(e){return`sha256:${Xq("sha256").update(e).digest("hex")}`}import{createHash as y4,randomBytes as v4}from"node:crypto";import{constants as zt}from"node:fs";import{chmod as EE,lstat as TE,open as _l,realpath as k4,rename as $E,unlink as bl}from"node:fs/promises";import{basename as Id,dirname as w4,isAbsolute as b4,join as Pd}from"node:path";var OE=1024*1024,_4=4096,S4=/^sha256:[a-f0-9]{64}$/u;async function Py(e){C4(e.filePath);let t=I4(e.content),n=LE(t),r=Object.freeze({owner:"skills-layer",fileSha256:n}),i=w4(e.filePath),o=await TE(i);if(o.isSymbolicLink()||!o.isDirectory())throw new Error("Owned hook parent must be a real directory, not a symbolic link.");let s=await k4(i),a=Pd(s,Id(e.filePath)),l=v4(12).toString("hex"),c=Pd(s,`.${Id(a)}.skills-layer.lock`),u=Pd(s,`.${Id(a)}.skills-layer-stage-${l}`),d=Pd(s,`.${Id(a)}.skills-layer-backup-${l}`),p=null,m=null,h=null,g=!1,y=!1;try{if(p=await _l(c,zt.O_CREAT|zt.O_EXCL|zt.O_WRONLY,384),await p.writeFile(`${process.pid}
|
|
@@ -748,10 +748,10 @@ ${r}
|
|
|
748
748
|
> `)),referenceMaterialBytes:await Pk(e.promptText,"Approximate reusable reference-material size in bytes (blank if unknown):"),assetPayloadBytes:await Pk(e.promptText,"Approximate reusable asset size in bytes (blank if none/unknown):"),expectedRunsPerMonth:await Pk(e.promptText,"Expected runs per month (blank if unknown):")}}function d1(e){if(!e||typeof e!="object")return"general";let t=e.data;if(!t||typeof t!="object")return"general";let n=t.domainProfile,r=t.session,i=r&&typeof r=="object"?r.domainSuggestion:void 0,o=n&&typeof n=="object"?n.id:i&&typeof i=="object"?i.profileId:void 0;return typeof o=="string"&&Ss.includes(o)?o:"general"}function p1(e){if(!e||typeof e!="object")return null;let t=e.data;if(!t||typeof t!="object")return null;let n=t.session;if(!n||typeof n!="object")return null;let r=n.skillSlug;return typeof r=="string"&&r.trim()?r:null}async function o9(e,t){let n=Mp(await t(`Suggested domain: ${e}. Press Enter to accept, or enter one of: ${Ss.join(", ")}.
|
|
749
749
|
> `));if(!n)return e;if(!Ss.includes(n))throw new Error(`Unknown Creator domain profile: ${n}`);return n}async function xr(e,t){let n=Mp(await e(`${t}
|
|
750
750
|
> `));if(!n)throw new Error("Interactive Creator interview answers must not be empty");return n}async function Pk(e,t){let n=Mp(await e(`${t}
|
|
751
|
-
> `));if(!n)return null;let r=Number(n);if(!Number.isSafeInteger(r)||r<0)throw new Error(`${t} requires a non-negative safe integer`);return r}function ac(e){let t=xs(e);if(t.length===0)throw new Error("Interactive Creator interview answers must not be empty");return t}function xs(e){return e.split("|").map(t=>t.trim()).filter(Boolean)}function Mp(e){return e.trim().replace(/\s+/gu," ")}var $pe={domain:Jn("domain","Confirm or change the suggested domain.","The domain selects the relevant safeguards and terminology.",{type:"string",enum:Ss}),activation:Jn("activation","Give a representative request that should activate this skill.","A positive example defines when the skill is useful.",{type:"string",minLength:1}),boundaries:Jn("boundaries","Describe an out-of-scope request, a near miss, and an alternate activation phrasing.","Boundaries prevent accidental activation.",lc(["negativeExamples","nearMisses","paraphrases"])),outputs:Jn("outputs","Describe the expected output and observable success criteria.","The workflow needs a testable result.",lc(["expectedOutputs","successCriteria"])),failures:Jn("failures","Which known conditions mean the workflow cannot safely complete?","Known failure conditions make stopping behaviour explicit.",Up()),safety:Jn("safety","Describe safety constraints and operating constraints.","Authority, cost, time and scope boundaries must be explicit.",lc(["safetyConstraints","constraints"])),domain_requirements:Jn("domain_requirements","Describe domain-specific requirements and safeguards.","Domain context keeps the skill accurate without opening extra questions.",lc(["constraints","safetyConstraints"])),resources:Jn("resources","Identify reusable knowledge and approximate reference or asset sizes.","This drives the explainable resource recommendation.",{type:"object",required:["reusableKnowledge"],properties:{reusableKnowledge:Up(!0),referenceMaterialBytes:Ak(),assetPayloadBytes:Ak()},additionalProperties:!1}),repeatability:Jn("repeatability","Identify repeatable and fragile steps.","Repeated or fragile work may need scripts and deterministic validation.",lc(["repeatedSteps","fragileSteps"],!0)),confirmation:Jn("confirmation","Confirm the normalized interview and provide verified target agents and expected monthly use.","Confirmation prevents Creator from inventing missing intent.",{type:"object",required:["confirmed"],properties:{confirmed:{const:!0},targetAgents:Up(!0),expectedRunsPerMonth:Ak()},additionalProperties:!1})};function zp(e,t){let n=t.trim();if(!n)throw new Error("Creator interview answer must not be empty");if(e==="domain"||e==="activation")return n;if(n.startsWith("{")||n.startsWith("["))try{return JSON.parse(n)}catch{throw new Error("Creator interview answer must be valid JSON")}let r=s9(n);return e==="failures"?r:e==="domain_requirements"?{constraints:[r[0]],safetyConstraints:r.slice(1)}:e==="boundaries"?{negativeExamples:[r[0]],nearMisses:[r[1]],paraphrases:[r[2]]}:e==="outputs"?{expectedOutputs:[r[0]],successCriteria:[r[1]]}:e==="safety"?{safetyConstraints:[r[0]],constraints:r.slice(1)}:e==="repeatability"?{repeatedSteps:[r[0]],fragileSteps:r.slice(1)}:e==="resources"?{reusableKnowledge:r,referenceMaterialBytes:null,assetPayloadBytes:null}:{confirmed:/^(?:y|yes|confirm|confirmed)$/iu.test(n),targetAgents:[],expectedRunsPerMonth:null}}function Jn(e,t,n,r){return{id:e,prompt:t,whyAsked:n,required:!0,answerSchema:r}}function Up(e=!1){return{type:"array",minItems:e?0:1,items:{type:"string",minLength:1}}}function Ak(){return{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}function lc(e,t=!1){return{type:"object",required:e,properties:Object.fromEntries(e.map(n=>[n,Up(t)])),additionalProperties:!1}}function s9(e){let t=e.split("|").map(n=>n.trim()).filter(Boolean);if(t.length===0)throw new Error("Creator interview answer must not be empty");return t}var j9=fn(Ji(),1);import{createHash as A1}from"node:crypto";var cc=fn(Ji(),1);var a9=
|
|
751
|
+
> `));if(!n)return null;let r=Number(n);if(!Number.isSafeInteger(r)||r<0)throw new Error(`${t} requires a non-negative safe integer`);return r}function ac(e){let t=xs(e);if(t.length===0)throw new Error("Interactive Creator interview answers must not be empty");return t}function xs(e){return e.split("|").map(t=>t.trim()).filter(Boolean)}function Mp(e){return e.trim().replace(/\s+/gu," ")}var $pe={domain:Jn("domain","Confirm or change the suggested domain.","The domain selects the relevant safeguards and terminology.",{type:"string",enum:Ss}),activation:Jn("activation","Give a representative request that should activate this skill.","A positive example defines when the skill is useful.",{type:"string",minLength:1}),boundaries:Jn("boundaries","Describe an out-of-scope request, a near miss, and an alternate activation phrasing.","Boundaries prevent accidental activation.",lc(["negativeExamples","nearMisses","paraphrases"])),outputs:Jn("outputs","Describe the expected output and observable success criteria.","The workflow needs a testable result.",lc(["expectedOutputs","successCriteria"])),failures:Jn("failures","Which known conditions mean the workflow cannot safely complete?","Known failure conditions make stopping behaviour explicit.",Up()),safety:Jn("safety","Describe safety constraints and operating constraints.","Authority, cost, time and scope boundaries must be explicit.",lc(["safetyConstraints","constraints"])),domain_requirements:Jn("domain_requirements","Describe domain-specific requirements and safeguards.","Domain context keeps the skill accurate without opening extra questions.",lc(["constraints","safetyConstraints"])),resources:Jn("resources","Identify reusable knowledge and approximate reference or asset sizes.","This drives the explainable resource recommendation.",{type:"object",required:["reusableKnowledge"],properties:{reusableKnowledge:Up(!0),referenceMaterialBytes:Ak(),assetPayloadBytes:Ak()},additionalProperties:!1}),repeatability:Jn("repeatability","Identify repeatable and fragile steps.","Repeated or fragile work may need scripts and deterministic validation.",lc(["repeatedSteps","fragileSteps"],!0)),confirmation:Jn("confirmation","Confirm the normalized interview and provide verified target agents and expected monthly use.","Confirmation prevents Creator from inventing missing intent.",{type:"object",required:["confirmed"],properties:{confirmed:{const:!0},targetAgents:Up(!0),expectedRunsPerMonth:Ak()},additionalProperties:!1})};function zp(e,t){let n=t.trim();if(!n)throw new Error("Creator interview answer must not be empty");if(e==="domain"||e==="activation")return n;if(n.startsWith("{")||n.startsWith("["))try{return JSON.parse(n)}catch{throw new Error("Creator interview answer must be valid JSON")}let r=s9(n);return e==="failures"?r:e==="domain_requirements"?{constraints:[r[0]],safetyConstraints:r.slice(1)}:e==="boundaries"?{negativeExamples:[r[0]],nearMisses:[r[1]],paraphrases:[r[2]]}:e==="outputs"?{expectedOutputs:[r[0]],successCriteria:[r[1]]}:e==="safety"?{safetyConstraints:[r[0]],constraints:r.slice(1)}:e==="repeatability"?{repeatedSteps:[r[0]],fragileSteps:r.slice(1)}:e==="resources"?{reusableKnowledge:r,referenceMaterialBytes:null,assetPayloadBytes:null}:{confirmed:/^(?:y|yes|confirm|confirmed)$/iu.test(n),targetAgents:[],expectedRunsPerMonth:null}}function Jn(e,t,n,r){return{id:e,prompt:t,whyAsked:n,required:!0,answerSchema:r}}function Up(e=!1){return{type:"array",minItems:e?0:1,items:{type:"string",minLength:1}}}function Ak(){return{anyOf:[{type:"integer",minimum:0},{type:"null"}]}}function lc(e,t=!1){return{type:"object",required:e,properties:Object.fromEntries(e.map(n=>[n,Up(t)])),additionalProperties:!1}}function s9(e){let t=e.split("|").map(n=>n.trim()).filter(Boolean);if(t.length===0)throw new Error("Creator interview answer must not be empty");return t}var j9=fn(Ji(),1);import{createHash as A1}from"node:crypto";var cc=fn(Ji(),1);var a9=et({HOME:"/home/skills-layer"},"linux","/workspace").filter(e=>e.pathContracts.project.status==="supported").map(e=>e.id);var l9=[...Xt],c9=["basic_skills","allowed_tools","hooks","forked_context","local_install"];function m1(e){if(e===void 0)return;if(!f1(e))throw new Error("metadata.agent_compatibility must be an object when provided");let t={};for(let[n,r]of Object.entries(e)){if(!l9.includes(n))throw new Error(`metadata.agent_compatibility contains an unsupported agent id: ${n}`);if(!f1(r))throw new Error(`metadata.agent_compatibility.${n} must be an object`);let i=f9(r,n),o=u9(r.capabilities,`${n}.capabilities`),s=d9(r.notes,`${n}.notes`);t[n]={supported:i,capabilities:o,...s?{notes:s}:{}}}return t}function u9(e,t){if(e===void 0)return[];if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`metadata.agent_compatibility.${t} must be a string array when provided`);let n=e.map(r=>r.trim()).filter(r=>r.length>0);for(let r of n)if(!c9.includes(r))throw new Error(`metadata.agent_compatibility.${t} contains an unsupported capability: ${r}`);return[...new Set(n)]}function d9(e,t){if(e!==void 0){if(typeof e!="string"||e.trim().length===0)throw new Error(`metadata.agent_compatibility.${t} must be a non-empty string when provided`);return e.trim()}}function p9(e,t){if(typeof e!="boolean")throw new Error(`metadata.agent_compatibility.${t} must be a boolean when provided`);return e}function f9(e,t){return Object.hasOwn(e,"supported")?p9(e.supported,`${t}.supported`):!0}function f1(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Rk=["claude","anthropic"];function g1(e){let t=y1(e);return t?Rk.find(n=>t.includes(n))??null:null}function h1(e){let t=y1(e);return t?Rk.includes(t):!1}function qp(){return`name must not use reserved ${Rk.join(" or ")} terms`}function y1(e){let t=e.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").replace(/-{2,}/gu,"-");return t.length>0?t:null}var k1=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,m9=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Gp(e){let t=e.match(k1);if(!t)throw new Error("SKILL.md must start with YAML frontmatter delimited by ---");let[,n,r]=t,i=(0,cc.parse)(n);if(!Vp(i))throw new Error("Frontmatter must parse to an object");return{frontmatter:g9(i),body:r,rawFrontmatter:n}}function w1(e,t,n){let r=e.match(k1);if(!r)throw new Error("SKILL.md must start with YAML frontmatter delimited by ---");let[,i,o]=r,s=(0,cc.parse)(i);if(!Vp(s))throw new Error("Frontmatter must parse to an object");let a={...s,license:t},l=Vp(s.metadata)?{...s.metadata}:void 0;return l?(delete l.license,delete l.license_file,Object.keys(l).length===0?delete a.metadata:a.metadata=l):delete a.metadata,`---
|
|
752
752
|
${(0,cc.stringify)(a,{lineWidth:0}).trimEnd()}
|
|
753
753
|
---
|
|
754
|
-
${o}`}function Vp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function g9(e){let t=v1(e.name,"name"),n=v1(e.description,"description"),r=e.license,i=h9(e.compatibility,"compatibility"),o=y9(e.metadata,"metadata"),s=m1(o?.agent_compatibility),a=v9(e["allowed-tools"]);if(!m9.test(t))throw new Error("name must be kebab-case");if(g1(t))throw new Error(qp());if(n.length>1024)throw new Error("description must be 1024 characters or fewer");return{name:t,description:n,...r===void 0?{}:{license:r},...i===void 0?{}:{compatibility:i},...s===void 0?{}:{compatibilityMatrix:s},...o===void 0?{}:{metadata:o},...a===void 0?{}:{"allowed-tools":a}}}function v1(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e.trim()}function h9(e,t){if(e===void 0)return;if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string when provided`);let n=e.trim();if(t==="compatibility"&&n.length>500)throw new Error("compatibility must be 500 characters or fewer");return n}function y9(e,t){if(e!==void 0){if(!Vp(e))throw new Error(`${t} must be an object when provided`);return e}}function v9(e){if(e!==void 0){if(typeof e=="string")return e.trim();if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e.map(t=>t.trim());throw new Error("allowed-tools must be a string or string array when provided")}}var Dk=fn(Ji(),1);var k9="private",b1="public",_1="unlisted";function uc(e){if(typeof e!="string"||e.trim().length===0)return null;let t=e.trim().toLowerCase();return t==="private"?k9:t===b1?b1:t===_1?_1:null}var Ek="skills-layer.control.v3",Cs="skills-layer.control.v2";var w9=new Set(["private","public","unlisted"]);var b9=new Set(["schemaVersion","listing","toolContract","targets"]),_9=new Set(["visibility","priceCents","category","tags"]),S9=new Set(["visibility","category","tags"]),x9=new Set(["requestedCapabilities","requestedTools","networkDomains","fileReadScopes","fileWriteScopes"]),C9=/^[^\s\u0000-\u001f\u007f]{1,160}$/u;function x1(e){let t;try{t=(0,Dk.parse)(e,{uniqueKeys:!0})}catch(n){let r=n instanceof Error?n.message:"Invalid control YAML";throw new Error(`Invalid Creator control manifest: ${r}`)}if(!I1(t))throw new Error("Creator control manifest must be a YAML object");if($k(t,b9,"control manifest"),t.schemaVersion!==Ek&&t.schemaVersion!==Cs)throw new Error(`Creator control schemaVersion must be ${Ek} or ${Cs}`);return I9(t)}function I9(e){let t=e.schemaVersion;if(t!==Ek&&t!==Cs)throw new Error("Creator control schemaVersion is invalid");let n=e.listing===void 0?{}:S1(e.listing,"listing"),r=e.toolContract===void 0?{}:S1(e.toolContract,"toolContract");$k(n,t===Cs?_9:S9,"listing"),$k(r,x9,"toolContract");let i=n.visibility===void 0?"private":P9(n.visibility,w9,"listing.visibility"),o=n.priceCents===void 0?0:n.priceCents;if(t===Cs&&(!Number.isInteger(o)||Number(o)<0))throw new Error("listing.priceCents must be a non-negative integer");let s=n.category===void 0||n.category===null?null:C1(n.category,"listing.category",80).toLowerCase();return{schemaVersion:t,listing:{visibility:i,...t===Cs&&n.priceCents!==void 0?{priceCents:Number(o)}:{},category:s,tags:Qi(n.tags,"listing.tags",80,!0)},toolContract:{requestedCapabilities:Qi(r.requestedCapabilities,"toolContract.requestedCapabilities"),requestedTools:Qi(r.requestedTools,"toolContract.requestedTools"),networkDomains:Qi(r.networkDomains,"toolContract.networkDomains",253,!0),fileReadScopes:Qi(r.fileReadScopes,"toolContract.fileReadScopes",1024),fileWriteScopes:Qi(r.fileWriteScopes,"toolContract.fileWriteScopes",1024)},targets:Qi(e.targets,"targets",160,!0)}}function Qi(e,t,n=160,r=!1){if(e==null)return[];if(!Array.isArray(e))throw new Error(`${t} must be an array of bounded strings`);let i=e.map(o=>{let s=C1(o,t,n);if(!C9.test(s))throw new Error(`${t} contains an invalid value`);return r?s.toLowerCase():s});return[...new Set(i)].sort((o,s)=>o.localeCompare(s))}function $k(e,t,n){let r=Object.keys(e).filter(i=>!t.has(i));if(r.length>0)throw new Error(`${n} contains unsupported field(s): ${r.sort().join(", ")}`)}function S1(e,t){if(!I1(e))throw new Error(`${t} must be an object`);return e}function C1(e,t,n=200){if(typeof e!="string"||e.trim().length===0||e.trim().length>n)throw new Error(`${t} must be a non-empty string of at most ${n} characters`);if(/[\u0000-\u001f\u007f]/u.test(e))throw new Error(`${t} contains control characters`);return e.trim()}function P9(e,t,n){if(typeof e!="string"||!t.has(e))throw new Error(`${n} is not supported`);return e}function I1(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var A9=/(^|\/)SKILL\.md$/,R9=[/(^|\n)#+\s+examples?\b/i,/(^|\n)#+\s+usage examples?\b/i,/(^|\n)#+\s+\u793A\u4F8B(?=$|\s)/u,/(^|\n)#+\s+\u4F8B\u5B50(?=$|\s)/u,/(^|\n)#+\s+\u7528\u4F8B(?=$|\s)/u],E9=[/(^|\n)#+\s+troubleshooting\b/i,/(^|\n)#+\s+trouble shooting\b/i,/(^|\n)#+\s+\u6545\u969C\u6392\u9664(?=$|\s)/u,/(^|\n)#+\s+\u95EE\u9898\u6392\u67E5(?=$|\s)/u,/(^|\n)#+\s+\u6392\u9519(?=$|\s)/u],$9=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]+|[\p{L}\p{N}_-]+/gu,D9=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u;function tt(e,t={}){let n=t.profile??"legacy_v1",r=[],i=e.filter(d=>A9.test(d.path)),o=e.some(d=>d.path.includes("/references/")||d.path.startsWith("references/"));if(i.length===0)return r.push(Cr("skill-missing","Bundle must contain exactly one SKILL.md file")),Tk(n,!1,r,e.length,0,o);i.length>1&&r.push(Cr("skill-duplicate","Bundle must not contain more than one SKILL.md file"));let s=i[0];if(!s||typeof s.content!="string")return r.push(Cr("skill-content-missing","SKILL.md content must be available for validation")),Tk(n,!1,r,e.length,0,o);let a;try{a=Gp(s.content)}catch(d){let p=d instanceof Error?d.message:"Unknown frontmatter parsing error";return r.push(Cr("frontmatter-invalid",p)),n==="external_ingest_tolerant"&&r.push(li("external-normalisation-needed","The external skill is recognizable but must be normalized before release")),Tk(n,n==="external_ingest_tolerant",r,e.length,0,o)}/^Helps with [^.]+\.$/u.test(a.frontmatter.description.trim())&&r.push(li("scaffold-description-placeholder","Replace the scaffold description with the skill's concrete purpose and when to use it."));let l=T9(a.body),c=O9(a.frontmatter.metadata);c&&r.push(c);let u=Np(e,a.frontmatter);return r.push(...u.issues),r.push(...L9({files:e,skillFilePath:s.path,parsedSkill:a,profile:n})),P1(a.body,R9)||r.push(li("examples-missing","Consider adding an Examples section to improve skill usability")),P1(a.body,E9)||r.push(li("troubleshooting-missing","Consider adding a Troubleshooting section for common failure cases")),l>5e3&&r.push(li("skill-body-too-long","SKILL.md body should stay under 5000 words for progressive disclosure")),l>1200&&!o&&r.push(li("references-missing","Large skills should move detailed material into references/")),{profile:n,ingestible:i.length===1,valid:r.every(d=>d.severity!=="error"),issues:r,parsedSkill:a,license:u,stats:{fileCount:e.length,bodyWordCount:l,hasReferences:o}}}function T9(e){let t=e.trim();if(t.length===0)return 0;let n=t.match($9);return n?n.reduce((r,i)=>r+(D9.test(i)?i.length:1),0):0}function Cr(e,t){return{severity:"error",code:e,message:t}}function li(e,t){return{severity:"warning",code:e,message:t}}function P1(e,t){return t.some(n=>n.test(e))}function O9(e){return e?.price_cents===void 0?null:li("price-cents-non-authoritative","metadata.price_cents is ignored; marketplace pricing is stored in the version pricing authority")}function Tk(e,t,n,r,i,o){return{profile:e,ingestible:t,valid:!1,issues:n,stats:{fileCount:r,bodyWordCount:i,hasReferences:o}}}function L9(e){let t=[],n=YE(e.files),r=n.find(p=>p.type==="control");if(r){let p=e.files.find(m=>m.path.replaceAll("\\","/").replace(/^\.\//u,"")===r.path);try{x1(p?.content??"")}catch(m){t.push(Cr("control-manifest-invalid",m.message))}}if(e.profile==="legacy_v1")return t;let o=e.profile!=="external_ingest_tolerant"?Cr:li,s=e.parsedSkill.frontmatter.name;s.length>64&&t.push(o("portable-name-too-long","Portable skill names must be 64 characters or fewer"));let l=e.skillFilePath.replaceAll("\\","/").split("/").filter(Boolean),c=l.length>1?l.at(-2):void 0;c&&c!==s&&t.push(o("portable-directory-name-mismatch","Portable skill name must match the directory containing SKILL.md")),e.parsedSkill.frontmatter.compatibility!==void 0&&t.push(o("unverified-compatibility-claim","Compatibility claims belong in evidence-backed control data, not portable runtime frontmatter"));let u=e.parsedSkill.frontmatter.metadata,d=["agent_compatibility","category","license","license_file","price_cents","skills_layer","tags","visibility"].filter(p=>u&&Object.hasOwn(u,p));return d.length>0&&t.push(o("runtime-control-metadata",`Skills Layer control metadata must not be stored in portable runtime frontmatter: ${d.join(", ")}`)),n.some(p=>p.reasonCode==="misplaced_control_manifest")&&t.push(Cr("control-manifest-misplaced","The Skills Layer control manifest is allowed only at the skill root")),n.some(p=>p.reasonCode==="unsupported_control_material")&&t.push(Cr("control-material-unsupported","Only root .skills-layer/skill.yaml is supported as control material")),n.filter(p=>p.type==="control").length>1&&t.push(Cr("control-manifest-duplicate","A skill bundle may contain only one root control manifest")),t}function N9(e){return`sha256:${A1("sha256").update(ye(e)).digest("hex")}`}function R1(e){return`sha256:${A1("sha256").update(JSON.stringify(e.map(t=>({path:t.path,digest:N9(t)})))).digest("hex")}`}var dc=class extends Error{constructor(n,r){super(n);this.reasonCode=r}reasonCode};function E1(e,t){if(!Ok(e)||!Ok(e.workspace))throw eo("Creator materialization response is missing its workspace.");let n=B9(t??e.skillSlug);if(!n)throw new dc("Creator materialization response is missing a portable skill slug; rerun with --dir or inspect the session.","creator_materialization_slug_missing");if(!Array.isArray(e.workspace.files)||e.workspace.files.length===0)throw eo("Creator materialization response contains no files.");let r=e.workspace.files.map((s,a)=>F9(s,a)),i=e.workspace.digest;if(typeof i!="string"||!/^sha256:[a-f0-9]{64}$/u.test(i))throw eo("Creator materialization response is missing a valid workspace digest.");if(R1(r)!==i)throw new dc("Creator materialization workspace digest does not match the returned files.","creator_materialization_digest_mismatch");return{skillSlug:n,files:r,workspaceDigest:i}}function F9(e,t){if(!Ok(e)||typeof e.path!="string")throw eo(`Creator materialization file ${t+1} is malformed.`);let n=typeof e.content=="string",r=typeof e.contentBase64=="string";if(n===r)throw eo(`Creator materialization file ${e.path} must contain exactly one byte representation.`);if(e.mediaType!==void 0&&typeof e.mediaType!="string")throw eo(`Creator materialization file ${e.path} has an invalid media type.`);let i={path:e.path,...n?{content:e.content}:{contentBase64:e.contentBase64},...typeof e.mediaType=="string"?{mediaType:e.mediaType}:{}};try{ye(i)}catch(o){throw eo(o instanceof Error?o.message:`Creator materialization file ${e.path} is invalid.`)}return i}function B9(e){if(typeof e!="string")return null;let t=e.trim();return/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(t)&&t.length<=64?t:null}function eo(e){return new dc(e,"creator_materialization_snapshot_invalid")}function Ok(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomUUID as M9}from"node:crypto";import{constants as Ir}from"node:fs";import{lstat as On,mkdir as Hp,mkdtemp as U9,open as Lk,realpath as Kp,readdir as z9,rename as pc,rm as $1}from"node:fs/promises";import{basename as q9,dirname as fc,isAbsolute as V9,join as Yn,parse as jk,posix as T1,resolve as Zp,sep as Wp}from"node:path";var D1=16*1024*1024,G9=64*1024*1024,Nk=typeof Ir.O_NOFOLLOW=="number"?Ir.O_NOFOLLOW:0;async function O1(e){let t=await j1(e);await ci(t);let n=await Bk(t);return{exists:n.exists,files:n.files.map(r=>({path:r.relativePath,...en(r.bytes)}))}}async function Jp(e){let t=await K9(e);if(t.plan.confirmationRequired&&!e.confirmed)return{status:"confirmation_required",plan:t.plan};let n=t.targetDir,r=fc(n);await ci(r),await Hp(r,{recursive:!0}),await ci(r);let i=[...t.tree.files.map(c=>c.relativePath),...e.files.map(c=>c.path)].reduce((c,u)=>Math.max(c,u.length),0),o=H9({parentDir:r,longestRelativePath:i,platform:process.platform});await ci(o);let s=await U9(Yn(o,".skills-layer-stage-")),a=null,l=!0;try{t.tree.exists&&await Y9(t.tree,s);for(let c of e.files)await X9(s,c);if(await eK(n,t.tree),!t.tree.exists)return await to(()=>pc(s,n)),l=!1,{status:"created",plan:t.plan};a=Yn(o,`.skills-layer-backup-${M9()}`),await to(()=>pc(n,a));try{await to(()=>pc(s,n)),l=!1}catch(c){throw await to(()=>pc(a,n)),a=null,c}return await to(()=>$1(a,{recursive:!0,force:!0})),a=null,{status:"replaced",plan:t.plan}}finally{l&&await to(()=>$1(s,{recursive:!0,force:!0})),a&&await tK(n,a)}}function H9(e){if(e.platform!=="win32")return e.parentDir;let t=jk(e.parentDir).root,n=Wp.length+26+Wp.length+e.longestRelativePath,r=e.parentDir;for(;r!==t&&r.length+n>iK;)r=fc(r);return r}async function Fk(e,t=256*1024){let n=await N1(Zp(e));if(await ci(n),(await On(n)).isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${n}`);let i=await Kp(n);await ci(i);let o=await L1(i,t);return Buffer.from(o).toString("utf8")}async function K9(e){W9(e.files);let t=Zp(e.targetDir),n=await j1(t);await ci(n);let r=await Bk(n),i=new Map(r.files.map(l=>[l.relativePath,l])),o=new Set(r.directories.map(l=>l.relativePath)),s=e.files.map(l=>{let c=i.get(l.path);if(o.has(l.path))throw new Error(`Scaffold file ${l.path} conflicts with an existing directory.`);let u=ye(l),d=u.byteLength;if(!c)return{path:l.path,action:"create",previousBytes:null,nextBytes:d};let p=Buffer.from(c.bytes).equals(Buffer.from(u));return{path:l.path,action:p?"unchanged":"replace",previousBytes:c.bytes.byteLength,nextBytes:d}}),a=r.files.length+r.directories.length;return{tree:r,targetDir:n,plan:{targetDir:t,targetExists:r.exists,confirmationRequired:r.exists&&a>0,preservedEntryCount:a,changes:s}}}function W9(e){let t=new Set,n=new Map,r=new Set(e.map(o=>o.path));for(let o of e){if(Z9(o.path),t.has(o.path))throw new Error(`Scaffold contains duplicate generated path ${o.path}.`);t.add(o.path);let s=o.path.normalize("NFC").toLocaleLowerCase("en-US"),a=n.get(s);if(a&&a!==o.path)throw new Error(`Scaffold contains a cross-platform path collision: ${a} and ${o.path}.`);n.set(s,o.path);let l=o.path.split("/");for(let c=1;c<l.length;c+=1){let u=l.slice(0,c).join("/");if(r.has(u))throw new Error(`Scaffold file ${u} conflicts with generated descendant ${o.path}.`)}}let i=tt(e);if(!i.valid)throw new Error(`Scaffold bundle validation failed: ${i.issues.filter(o=>o.severity==="error").map(o=>`${o.code}: ${o.message}`).join("; ")}`)}function Z9(e){let t=e.split("/");if(e.length===0||e.includes("\\")||e.includes("\0")||V9(e)||T1.normalize(e)!==e||e===".."||e.startsWith("../")||e!==e.normalize("NFC")||e.length>1024||t.some(n=>!J9(n)))throw new Error(`Unsafe scaffold path: ${e}`)}function J9(e){if(!e||e.length>255||/[<>:"|?*\u0000-\u001f]/u.test(e)||/[ .]$/u.test(e))return!1;let t=e.split(".")[0].toUpperCase();return!oK.has(t)}async function Bk(e){let t;try{t=await On(e,{bigint:!0})}catch(s){if(Is(s))return{exists:!1,identity:null,files:[],directories:[]};throw s}if(t.isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${e}`);if(!t.isDirectory())throw new Error(`Scaffold target must be a directory: ${e}`);let n=[],r=[],i=0,o=async(s,a)=>{let l=await On(s,{bigint:!0});if(l.isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${s}`);if(!l.isDirectory())throw new Error(`Scaffold target changed while it was inspected: ${s}`);let c=(await z9(s,{withFileTypes:!0})).sort((d,p)=>d.name.localeCompare(p.name));for(let d of c){let p=Yn(s,d.name),m=a?T1.join(a,d.name):d.name,h=await On(p,{bigint:!0});if(h.isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${p}`);if(h.isDirectory()){r.push({relativePath:m,absolutePath:p}),await o(p,m);continue}if(!h.isFile())throw new Error(`Scaffold transaction refuses non-regular filesystem entries: ${p}`);let g=Number(h.size);if(g>D1||i+g>G9)throw new Error("Existing scaffold target exceeds the bounded transaction copy limit.");let y=await L1(p,D1);i+=y.byteLength,n.push({relativePath:m,absolutePath:p,bytes:y})}let u=await On(s,{bigint:!0});if(u.dev!==l.dev||u.ino!==l.ino||!u.isDirectory())throw new Error(`Scaffold target changed while it was inspected: ${s}`)};return await o(e,""),{exists:!0,identity:{dev:t.dev,ino:t.ino},files:n,directories:r}}async function L1(e,t){let n=await Lk(e,Ir.O_RDONLY|Nk);try{let r=await n.stat();if(!r.isFile())throw new Error(`Expected a regular file: ${e}`);if(r.size>t)throw new Error(`File exceeds the bounded read limit: ${e}`);return new Uint8Array(await n.readFile())}finally{await n.close()}}async function Y9(e,t){for(let n of e.directories)await Hp(Yn(t,...n.relativePath.split("/")),{recursive:!0});for(let n of e.files){let r=Yn(t,...n.relativePath.split("/"));await Hp(fc(r),{recursive:!0}),await Q9(r,n.bytes)}}async function X9(e,t){let n=Yn(e,...t.path.split("/"));await Hp(fc(n),{recursive:!0});let r=await Lk(n,Ir.O_WRONLY|Ir.O_CREAT|Ir.O_TRUNC|Nk,384);try{await r.writeFile(ye(t)),await r.sync()}finally{await r.close()}}async function Q9(e,t){let n=await Lk(e,Ir.O_WRONLY|Ir.O_CREAT|Ir.O_EXCL|Nk,384);try{await n.writeFile(t)}finally{await n.close()}}async function ci(e){let t=Zp(e),n=jk(t).root,r=t.slice(n.length).split(Wp).filter(Boolean),i=n;for(let o of r){i=Yn(i,o);try{if((await On(i)).isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${i}`)}catch(s){if(Is(s))return;throw s}}}async function j1(e){let t=await N1(Zp(e));await ci(t);try{if((await On(t)).isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${t}`);return await Kp(t)}catch(o){if(!Is(o))throw o}let n=[],r=t;for(;;)try{await On(r);break}catch(o){if(!Is(o))throw o;let s=fc(r);if(s===r)throw new Error(`Unable to resolve scaffold target parent: ${t}`);n.unshift(q9(r)),r=s}let i=await Kp(r);return Yn(i,...n)}async function N1(e){let t=jk(e).root,n=e.slice(t.length).split(Wp).filter(Boolean);if(n.length===0)return e;let r=Yn(t,n[0]);return(await On(r)).isSymbolicLink()?Yn(await Kp(r),...n.slice(1)):e}async function eK(e,t){let n=await Bk(e);if(n.exists!==t.exists)throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");if(!t.exists)return;if(!t.identity||!n.identity||n.identity.dev!==t.identity.dev||n.identity.ino!==t.identity.ino)throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");let r=t.directories.map(o=>o.relativePath),i=n.directories.map(o=>o.relativePath);if(r.join("\0")!==i.join("\0"))throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");if(n.files.length!==t.files.length)throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");for(let o=0;o<t.files.length;o+=1){let s=t.files[o],a=n.files[o];if(s.relativePath!==a.relativePath||!Buffer.from(s.bytes).equals(Buffer.from(a.bytes)))throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.")}}async function tK(e,t){try{await On(t)}catch(n){if(Is(n))return;throw n}try{await On(e)}catch(n){if(Is(n)){await to(()=>pc(t,e));return}throw n}throw new Error(`Scaffold backup requires manual recovery: ${t}`)}async function to(e,t={}){let n=t.maximumAttempts??5;if(!Number.isInteger(n)||n<1||n>10)throw new Error("Filesystem retry maximumAttempts must be between 1 and 10.");let r=t.wait??(i=>new Promise(o=>setTimeout(o,i)));for(let i=1;;i+=1)try{return await e()}catch(o){if(!nK(o)||i>=n)throw o;await r(Math.min(160,10*2**(i-1)))}}function nK(e){return typeof e=="object"&&e!==null&&"code"in e&&rK.has(String(e.code))}function Is(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}var rK=new Set(["EPERM","EBUSY","ENOTEMPTY","EACCES"]),iK=240,oK=new Set(["CON","PRN","AUX","NUL","CLOCK$",...Array.from({length:9},(e,t)=>`COM${t+1}`),...Array.from({length:9},(e,t)=>`LPT${t+1}`)]);var F1="skills-layer.creator.platform-telemetry.v1";function Yp(e){return e==="darwin"?"macos":e==="linux"?"linux":e==="win32"?"windows":"other"}function Xp(e){let t={schemaVersion:F1,...e};if(!B1(t))throw new Error("Creator platform telemetry event is invalid or contains unsupported fields");return t}function B1(e){return!sK(e)||Object.keys(e).sort().join("\0")!==["nodeMajor","occurredAt","operation","operationId","osFamily","outcome","schemaVersion"].sort().join("\0")?!1:e.schemaVersion===F1&&(e.osFamily==="macos"||e.osFamily==="linux"||e.osFamily==="windows"||e.osFamily==="other")&&Number.isInteger(e.nodeMajor)&&Number(e.nodeMajor)>=18&&Number(e.nodeMajor)<=99&&(e.operation==="plan"||e.operation==="materialize"||e.operation==="patch"||e.operation==="recover")&&(e.outcome==="succeeded"||e.outcome==="failed"||e.outcome==="recovered")&&typeof e.operationId=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.operationId)&&typeof e.occurredAt=="string"&&Number.isFinite(Date.parse(e.occurredAt))}async function Qp(e){if(!B1(e.event))throw new Error("Creator platform telemetry event is invalid");try{return await e.publish(e.event),"accepted"}catch{return"ignored"}}function sK(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{resolve as M1}from"node:path";async function Mk(e){if(e.skip&&(e.explicitIdentifier||e.explicitLicenseFile))throw new Error("--skip-license cannot be combined with --license or --license-file.");if(e.explicitLicenseFile&&!e.explicitIdentifier)throw new Error("--license-file requires --license <SPDX-or-LicenseRef-identifier>.");if(e.skip)return{selection:{mode:"skip"},source:"skip"};if(e.explicitIdentifier){let i=si(e.explicitIdentifier);if(e.explicitLicenseFile)return{selection:{mode:"custom",identifier:i,text:await Fk(M1(e.cwd,e.explicitLicenseFile)),filePath:"LICENSE"},source:"explicit_import"};if(!ic(i))throw new Error(`--license ${i} requires --license-file because Skills Layer will not invent or guess terms.`);return{selection:{mode:"template",identifier:i},source:"explicit_template"}}let t=aK(e.files??[]);if(t?.status==="verified"||t?.status==="recognized_template")return{selection:U1(t),source:"existing"};if(!e.interactive||!e.prompt)return{selection:{mode:"skip"},source:"skip"};let n=[];t?.status==="confirmation_required"&&t.detectedIdentifier&&t.text&&t.filePath&&n.push({value:`existing:${t.detectedIdentifier}`,label:`Confirm detected ${t.detectedIdentifier} terms`,description:`Preserve ${t.filePath} byte-for-byte and bind its detected identifier.`}),n.push({value:"template:MIT",label:"Use the approved MIT template",description:"Creator-selected immutable standard template; review and replace placeholders before publication."},{value:"import",label:"Import my exact terms",description:"Supply an SPDX/LicenseRef identifier and a local text file; Skills Layer will not alter it."},{value:"skip",label:"Skip for now",description:"Continue with a visible, non-blocking license_missing warning."});let r=await e.prompt.select("Choose optional creator licence terms:",n);if(!r||r==="skip")return{selection:{mode:"skip"},source:"skip"};if(r.startsWith("existing:")&&t?.text&&t.filePath)return{selection:U1(t),source:"existing"};if(r==="template:MIT")return{selection:{mode:"template",identifier:"MIT"},source:"interactive_template"};if(r==="import"){let i=si(await e.prompt.text("SPDX or LicenseRef-* identifier: ")),o=(await e.prompt.text("Path to the exact licence terms file: ")).trim();if(!o)throw new Error("A licence terms file path is required for import.");return{selection:{mode:"custom",identifier:i,text:await Fk(M1(e.cwd,o)),filePath:"LICENSE"},source:"interactive_import"}}throw new Error("Unsupported creator licence selection.")}function z1(e,t){let n=e.filter(o=>/(^|\/)SKILL\.md$/u.test(o.path)&&typeof o.content=="string");if(n.length!==1||!n[0]?.content)throw new Error("Licence remediation requires exactly one readable SKILL.md file.");let r=t.mode==="template"?"LICENSE":t.filePath??"LICENSE",i=t.mode==="template"?Xi(t.identifier):t.text;return[{path:n[0].path,content:w1(n[0].content,t.identifier,r)},{path:r,content:i}]}function aK(e){let t=e.filter(n=>/(^|\/)SKILL\.md$/u.test(n.path)&&typeof n.content=="string");if(t.length!==1||!t[0]?.content)return null;try{return Np(e,Gp(t[0].content).frontmatter)}catch{return null}}function U1(e){if(!e.identifier&&!e.detectedIdentifier)throw new Error("Existing licence selection requires a creator-confirmed identifier.");if(!e.text||!e.filePath)throw new Error("Existing licence selection requires exact in-bundle terms.");return{mode:"existing",identifier:e.identifier??e.detectedIdentifier,text:e.text,filePath:e.filePath}}var q1={maxPatternBytes:512,maxWildcards:8},lK=new Set(["[","]","(",")","{","}","+","?","|"]);function mc(e,t=q1){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>t.maxPatternBytes||!Number.isSafeInteger(t.maxWildcards)||t.maxWildcards<0)return Ps();let n=e.startsWith("^"),r=e.endsWith("$")&&!cK(e,e.length-1),i=n?1:0,o=r?e.length-1:e.length;if(i>=o)return Ps();let s=[""],a=0,l=!1;for(let c=i;c<o;c+=1){let u=e[c];if(l){s[s.length-1]+=u,l=!1;continue}if(u==="\\"){l=!0;continue}if(u==="*"){if(s[s.length-1]===""&&s.length>1)continue;if(a+=1,a>t.maxWildcards)return Ps();s.push("");continue}if(lK.has(u)||u==="^"||u==="$"||u.charCodeAt(0)<32||u.charCodeAt(0)===127)return Ps();s[s.length-1]+=u}return l||s.every(c=>c.length===0)?Ps():{valid:!0,anchoredStart:n,anchoredEnd:r,segments:s,wildcardCount:a}}function V1(e,t,n=q1){let r=mc(t,n);if(!r.valid)return{matched:!1,reasonCode:"unsafe_pattern"};let{segments:i,anchoredStart:o,anchoredEnd:s,wildcardCount:a}=r;if(a===0){let c=i[0];return o&&s?{matched:e===c}:o?{matched:e.startsWith(c)}:s?{matched:e.endsWith(c)}:{matched:e.includes(c)}}let l=0;for(let c=0;c<i.length;c+=1){let u=i[c];if(u.length===0)continue;let d=c===0,p=c===i.length-1;if(d&&o){if(!e.startsWith(u))return{matched:!1};l=u.length;continue}if(p&&s)return{matched:e.length-u.length>=l&&e.endsWith(u)};let m=e.indexOf(u,l);if(m<0)return{matched:!1};l=m+u.length}return{matched:!0}}function cK(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r-=1)n+=1;return n%2===1}function Ps(){return{valid:!1,reasonCode:"unsafe_pattern"}}var ui=Object.freeze({schemaVersion:"skills-layer.eval.resource-policy.v1",maxPackBytes:256*1024,maxNestingDepth:16,maxObjectKeys:4096,maxCases:64,maxAssertions:512,maxPatternBytes:512,maxPatternWildcards:8,maxPathBytes:512,maxFiles:256,maxFileBytes:1024*1024,maxScannedBytes:8*1024*1024,maxOpaqueFileBytes:20*1024*1024,maxOpaqueBytes:20*1024*1024,maxJsonDepth:32,maxJsonKeys:4096,maxDurationMs:5e3,maxResultBytes:256*1024});function ef(e,t=ui){let n=H1(e,{maxBytes:t.maxPackBytes,maxDepth:t.maxNestingDepth,maxKeys:t.maxObjectKeys,rootPath:"$"});if(!n.valid)return n;if(!Uk(e))return bt("invalid_pack","eval-pack-invalid","$","Eval pack must be an object");let r=e.cases;if(Array.isArray(r)&&r.length>t.maxCases)return bt("resource_limit","eval-pack-case-limit","$.cases","Eval case count exceeds the checked resource policy.");let i=0;if(Array.isArray(r))for(let o=0;o<r.length;o+=1){let s=r[o];if(!(!Uk(s)||!Array.isArray(s.assertions))){if(i+=s.assertions.length,i>t.maxAssertions)return bt("resource_limit","eval-pack-assertion-limit",`$.cases[${o}].assertions`,"Eval assertion count exceeds the checked resource policy.");for(let a=0;a<s.assertions.length;a+=1){let l=s.assertions[a];if(!Uk(l))continue;let c=`$.cases[${o}].assertions[${a}]`;if(l.type==="regex_match"&&!mc(l.pattern,{maxPatternBytes:t.maxPatternBytes,maxWildcards:t.maxPatternWildcards}).valid)return bt("unsafe_pattern","eval-pack-unsafe-pattern",`${c}.pattern`,"Eval pattern is outside the bounded literal/glob language.");if(l.path!==void 0&&!K1(l.path,t.maxPathBytes))return bt("invalid_pack","eval-pack-target-path-invalid",`${c}.path`,"Eval target must be a bounded portable relative path.")}}}return{valid:!0,outcome:"valid",issues:[]}}function tf(e,t=ui){if(!Array.isArray(e)||e.length>t.maxFiles)return bt("resource_limit","eval-file-count-limit","$files","Eval file count exceeds the checked resource policy.");let n=0,r=0,i=new Set;for(let o=0;o<e.length;o+=1){let s=e[o];if(!s||!K1(s.path,t.maxPathBytes)||i.has(G1(s.path)))return bt("invalid_pack","eval-file-path-invalid",`$files[${o}].path`,"Eval file paths must be unique bounded portable relative paths.");i.add(G1(s.path));let a;try{a=cs(s)}catch{return bt("invalid_pack","eval-file-content-invalid",`$files[${o}]`,"Eval file content must use one canonical byte representation.")}if(uK(s)){if(a>t.maxOpaqueFileBytes)return bt("resource_limit","eval-opaque-file-byte-limit",`$files[${o}]`,"Eval opaque asset exceeds the per-file byte limit.");if(r+=a,r>t.maxOpaqueBytes)return bt("resource_limit","eval-opaque-byte-limit","$files","Eval opaque asset bytes exceed the cumulative byte limit.")}else{if(a>t.maxFileBytes)return bt("resource_limit","eval-file-byte-limit",`$files[${o}]`,"Eval target file exceeds the per-file byte limit.");if(n+=a,n>t.maxScannedBytes)return bt("resource_limit","eval-scan-byte-limit","$files","Eval target bytes exceed the cumulative scan limit.")}}return{valid:!0,outcome:"valid",issues:[]}}function zk(e,t=ui){return H1(e,{maxBytes:t.maxFileBytes,maxDepth:t.maxJsonDepth,maxKeys:t.maxJsonKeys,rootPath:"$json"})}function H1(e,t){let n=new WeakSet,r=[{value:e,depth:0,path:t.rootPath}],i=0,o=0;for(;r.length>0;){let s=r.pop();if(s.depth>t.maxDepth)return bt("resource_limit","eval-nesting-limit",s.path,"Eval input exceeds the nesting-depth limit.");if(typeof s.value=="string")i+=Buffer.byteLength(s.value,"utf8");else if(typeof s.value=="number"||typeof s.value=="boolean")i+=String(s.value).length;else if(s.value===null)i+=4;else if(typeof s.value=="object"){if(n.has(s.value))return bt("invalid_pack","eval-cycle-invalid",s.path,"Eval input must be acyclic JSON data.");if(n.add(s.value),Array.isArray(s.value)){o+=s.value.length;for(let a=s.value.length-1;a>=0;a-=1)r.push({value:s.value[a],depth:s.depth+1,path:`${s.path}[${a}]`})}else for(let[a,l]of Object.entries(s.value))o+=1,i+=Buffer.byteLength(a,"utf8"),r.push({value:l,depth:s.depth+1,path:`${s.path}.${a}`})}else if(s.value!==void 0)return bt("invalid_pack","eval-json-type-invalid",s.path,"Eval input must contain JSON-compatible values only.");if(o>t.maxKeys||i>t.maxBytes)return bt("resource_limit","eval-byte-or-key-limit",s.path,"Eval input exceeds the checked byte or key limit.")}return{valid:!0,outcome:"valid",issues:[]}}function K1(e,t){return typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>t||e.includes("\\")||e.includes("\0")||e.startsWith("/")||/^[A-Za-z]:/u.test(e)?!1:e.split("/").every(r=>r.length>0&&r!=="."&&r!=="..")}function G1(e){return e.normalize("NFC").toLowerCase()}function uK(e){return typeof e.contentBase64=="string"&&typeof e.content!="string"}function Uk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bt(e,t,n,r){return{valid:!1,outcome:e,issues:[{code:t,path:n,message:r}]}}function W1(e={}){let t=e.maxScannedBytes??ui.maxScannedBytes;if(!Number.isSafeInteger(t)||t<0)throw new Error("Eval scan budget must be a non-negative safe integer.");return{maxScannedBytes:t,scannedBytes:0}}function rf(e,t){switch(e.type){case"file_exists":return qk(t.files,no(e.path))?As("file_exists"):yn("file_missing");case"json_valid":return dK(e,t);case"section_exists":return pK(e,t);case"regex_match":return fK(e,t);case"schema_match":return mK(e,t);case"artifact_valid":return gK(e,t);case"max_duration_ms":return tn("runner_unavailable");case"command_exit":return tn("runner_unavailable");default:return tn("assertion_type_unsupported")}}function dK(e,t){let n=qk(t.files,no(e.path));if(!n)return yn("file_missing");let r=gc(n,t);if(!r.ok)return tn(r.reasonCode);try{let i=JSON.parse(r.content);return zk(i).valid?As("json_valid"):tn("resource_limit")}catch{return yn("json_invalid")}}function pK(e,t){let n=no(e.target);if(!n)return yn("section_target_missing");for(let r of t.files){let i=gc(r,t);if(!i.ok){if(i.reasonCode==="opaque_asset_not_text")continue;return tn(i.reasonCode)}if(i.content.split(/\r?\n/u).some(o=>hK(o,n)))return As("section_exists")}return yn("section_missing")}function fK(e,t){let n=no(e.pattern);if(!n)return yn("regex_missing");if(!mc(n).valid)return tn("unsafe_pattern");let r=no(e.path),i=r?t.files.filter(s=>nf(s.path)===nf(r)):t.files,o=!1;for(let s of i){let a=gc(s,t);if(!a.ok){if(a.reasonCode==="opaque_asset_not_text"){o=!0;continue}return tn(a.reasonCode)}if(V1(a.content,n).matched)return As("regex_matched")}return r&&o?tn("opaque_asset_not_text"):yn("regex_not_matched")}function mK(e,t){let n=qk(t.files,no(e.path));if(!n)return yn("file_missing");let r=gc(n,t);if(!r.ok)return tn(r.reasonCode);let i;try{i=JSON.parse(r.content)}catch{return yn("json_invalid")}return zk(i).valid?yK(i)?(Array.isArray(e.requiredKeys)?e.requiredKeys.map(String):[]).every(s=>Object.prototype.hasOwnProperty.call(i,s))?As("schema_matched"):yn("schema_required_key_missing"):yn("schema_target_not_object"):tn("resource_limit")}function gK(e,t){let n=tf(t.files);if(!n.valid)return tn(n.outcome);for(let r of t.files){let i=gc(r,t);if(!i.ok&&i.reasonCode!=="opaque_asset_not_text")return tn(i.reasonCode)}return ct(t.files)===no(e.artifactDigest)?As("artifact_digest_matched"):yn("artifact_digest_mismatch")}function qk(e,t){if(!t)return;let n=nf(t);return e.find(r=>nf(r.path)===n)}function no(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function nf(e){return e.replaceAll("\\","/").replace(/^\.\//u,"")}function gc(e,t){if(typeof e.contentBase64=="string"&&typeof e.content!="string")return{ok:!1,reasonCode:"opaque_asset_not_text"};let n=e.content??"",r=Buffer.byteLength(n,"utf8");if(r>ui.maxFileBytes)return{ok:!1,reasonCode:"resource_limit"};if(t.scanBudget){if(t.scanBudget.scannedBytes+r>t.scanBudget.maxScannedBytes)return{ok:!1,reasonCode:"resource_limit"};t.scanBudget.scannedBytes+=r}return{ok:!0,content:n}}function hK(e,t){let n=e.trimStart(),r=0;for(;n[r]==="#";)r+=1;return r===0||n[r]!==" "?!1:n.slice(r+1).trim().localeCompare(t.trim(),void 0,{sensitivity:"accent"})===0}function yK(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function As(e){return{status:"passed",reasonCode:e}}function yn(e){return{status:"failed",reasonCode:e}}function tn(e){return{status:"skipped",reasonCode:e}}import{createHash as vK}from"node:crypto";var kK=["submitted","inferred","submitted_plus_inferred"],wK=["starter","reviewed","verified"],bK=["file_exists","json_valid","schema_match","section_exists","regex_match","command_exit","artifact_valid","max_duration_ms"],_K=new Set(kK),SK=new Set(wK),xK=new Set(bK);function sf(e){let t=ef(e);if(!t.valid)return{valid:!1,issues:t.issues};let n=[],r=e;return r.schemaVersion!=="skills-layer.eval.pack.v1"&&n.push(vn("eval-pack-schema-invalid","$.schemaVersion","Eval pack schemaVersion is unsupported")),(typeof r.artifactDigest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(r.artifactDigest))&&n.push(vn("eval-pack-artifact-digest-invalid","$.artifactDigest","Eval pack must target a sha256 artifact digest")),(typeof r.origin!="string"||!_K.has(r.origin))&&n.push(vn("eval-pack-origin-invalid","$.origin","Eval pack origin is not canonical")),(typeof r.confidence!="string"||!SK.has(r.confidence))&&n.push(vn("eval-pack-confidence-invalid","$.confidence","Eval pack confidence is not canonical")),typeof r.creatorReviewed!="boolean"&&n.push(vn("eval-pack-review-invalid","$.creatorReviewed","Eval pack must state whether the creator reviewed it")),(!of(r.redaction)||r.redaction.mode!=="content_free")&&n.push(vn("eval-pack-redaction-invalid","$.redaction.mode","Eval pack must use content_free redaction by default")),!Array.isArray(r.cases)||r.cases.length===0?n.push(vn("eval-pack-cases-invalid","$.cases","Eval pack must include at least one case")):CK(r.cases,n),{valid:n.length===0,issues:n}}function Rs(e){return`sha256:${vK("sha256").update(IK(e)).digest("hex")}`}function CK(e,t){let n=new Set;e.forEach((r,i)=>{let o=`$.cases[${i}]`;if(!of(r)){t.push(vn("eval-pack-case-invalid",o,"Eval case must be an object"));return}if(typeof r.id!="string"||r.id.trim().length===0?t.push(vn("eval-pack-case-id-invalid",`${o}.id`,"Eval case id is required")):n.has(r.id)?t.push(vn("eval-pack-case-id-duplicate",`${o}.id`,"Eval case ids must be unique")):n.add(r.id),!Array.isArray(r.assertions)||r.assertions.length===0){t.push(vn("eval-pack-assertions-invalid",`${o}.assertions`,"Eval case must include assertions"));return}r.assertions.forEach((s,a)=>{let l=`${o}.assertions[${a}]`;(!of(s)||typeof s.type!="string"||!xK.has(s.type))&&t.push(vn("eval-pack-assertion-type-invalid",`${l}.type`,"Eval assertion type is not supported"))})})}function IK(e){return JSON.stringify(Vk(e))}function Vk(e){return Array.isArray(e)?e.map(Vk).sort(PK):of(e)?Object.fromEntries(Object.entries(e).filter(([t])=>t!=="evalPackDigest").sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Vk(n)])):e}function PK(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))}function of(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vn(e,t,n){return{code:e,path:t,message:n}}function J1(e){let t=e.assertionsPassed+e.assertionsFailed,n={coverageRatio:Z1(e.evaluatedCapabilities,e.declaredCapabilities),passRate:t===0?0:Z1(e.assertionsPassed,t),freshnessFactor:RK(e),evidenceConfidence:e.evidenceConfidenceOverride===void 0?AK(e):af(hc(e.evidenceConfidenceOverride)),baselineDelta:hc(Math.max(0,e.baselineDelta??0)),telemetrySignal:hc(e.aggregationThresholdMet?e.telemetrySignal??0:0)},r=af(n.coverageRatio*.25+n.passRate*.25+n.freshnessFactor*.15+n.evidenceConfidence*.2+n.baselineDelta*.05+n.telemetrySignal*.1);return{components:n,overallScore:r,effectiveScorePercent:$K(r*100),assertionsFailed:e.assertionsFailed,executedAssertions:t,aggregationThresholdMet:e.aggregationThresholdMet}}function Y1(e){return e.executedAssertions===0&&e.components.coverageRatio===0?"unknown":e.components.freshnessFactor===0?"stale":e.assertionsFailed>0&&e.components.passRate<.8?"failing":e.overallScore>=.8&&e.components.coverageRatio>=.8&&e.components.passRate>=.9&&e.components.evidenceConfidence>=.7?"strong":e.aggregationThresholdMet&&e.components.telemetrySignal>=.7?"telemetry-backed":"limited"}function AK(e){let t=e.origin==="submitted"?.65:e.origin==="submitted_plus_inferred"?.55:.25,n=e.creatorReviewed?.15:0,r=Math.min(e.runCount*.03,.15),i=Math.min(new Set(e.runnerTypes).size*.04,.1),o=e.aggregationThresholdMet?.1:0;return af(hc(t+n+r+i+o))}function RK(e){if(e.freshnessPolicy==="never")return 1;if(!e.generatedAt||!e.now)return 0;let t=Date.parse(e.generatedAt),n=Date.parse(e.now);if(!Number.isFinite(t)||!Number.isFinite(n)||n<t)return 0;let r=EK(e.freshnessPolicy);return n-t<=r?1:0}function EK(e){return e==="3_months"?2160*60*60*1e3:e==="6_months"?4392*60*60*1e3:365*24*60*60*1e3}function Z1(e,t){return t<=0?0:af(hc(e/t))}function hc(e){return Math.max(0,Math.min(1,e))}function af(e){return Math.round(e*1e4)/1e4}function $K(e){return Math.round(e*10)/10}var Gk=["passed","failed","not_run","generated_only","policy_skipped","runner_unavailable"],zfe=new Set(Gk);function Es(e){return{schemaVersion:"skills-layer.eval.summary.v1",status:e.status,skillSlug:e.skillSlug,version:e.version,...e.generationId?{generationId:e.generationId}:{},artifactDigest:e.artifactDigest,...e.evalPackDigest?{evalPackDigest:e.evalPackDigest}:{},...e.runnerVersion?{runnerVersion:e.runnerVersion}:{},generatedAt:e.generatedAt,...e.counts?{counts:e.counts}:{},redaction:{mode:"content_free",rawContentIncluded:!1}}}function DK(e){return e==="limited"||e==="unknown"?"attention_needed":"ready"}function Hk(e){let t=ct(e),n=Ty(e),r=e.map(l=>$n(l.path,e)).filter(l=>l.type==="evidence"),i=TK(e),o=i?"submitted":"inferred",s=J1({declaredCapabilities:4,evaluatedCapabilities:i?2:1,assertionsPassed:0,assertionsFailed:0,assertionsSkipped:0,origin:o,creatorReviewed:!1,runCount:0,runnerTypes:["dry"],aggregationThresholdMet:!1,freshnessPolicy:"never"}),a=Y1(s);return{schemaVersion:"skills-layer.eval.readiness.v1",status:DK(a),label:a,artifactDigest:t,origin:o,confidence:"starter",creatorReviewed:!1,runtimeFileCount:n.length,evidenceFileCount:r.length,excludedEvidencePaths:r.map(l=>l.path),score:{overallScore:s.overallScore,effectiveScorePercent:s.effectiveScorePercent,components:s.components},summaryEnvelope:{requiredOnSubmit:!0,statuses:[...Gk]},nextAction:"creator.submit",nextStep:"Add representative Eval cases, preview trigger behavior, then submit with the mandatory redacted Eval summary.",improvements:["Add representative should-trigger, should-not-trigger, and paraphrase cases.","Review the generated assertions and cover every advertised core capability."],recommendedCommands:["skills-layer preview-trigger <path>","skills-layer validate <path>"]}}function TK(e){return e.map(t=>$n(t.path,e)).some(t=>t.type==="evidence"&&(t.relativePath.startsWith("evals/")||t.relativePath.endsWith(".eval.json")||t.relativePath.endsWith(".eval.yaml")))}function X1(e){if(e.activationState!=="inactive_staging")return lf("invalid_pack","inactive_staging_required","$activationState","Static Eval must run before activation in an inactive staging tree.");let t=ef(e.pack);if(!t.valid)return{outcome:t.outcome,reasonCode:t.issues[0]?.code??t.outcome,issues:t.issues};let n=sf(e.pack);if(!n.valid)return{outcome:"invalid_pack",reasonCode:n.issues[0]?.code??"invalid_pack",issues:n.issues};let r=tf(e.files);if(!r.valid)return{outcome:r.outcome,reasonCode:r.issues[0]?.code??r.outcome,issues:r.issues};let i=e.pack,o=ct(e.files);if(i.artifactDigest!==o)return lf("invalid_pack","artifact_digest_mismatch","$.artifactDigest","Eval pack is not bound to the staged runtime artifact.");let s=W1(),a=i.cases.map(d=>({id:d.id,assertions:d.assertions.map(p=>rf(p,{files:e.files,scanBudget:s}))})),l=a.flatMap(d=>d.assertions).find(d=>d.reasonCode==="resource_limit"||d.reasonCode==="unsafe_pattern");if(l){let d=l.reasonCode;return lf(d,d,"$cases","Static Eval stopped at the checked security boundary.")}let c=OK(a),u=Es({status:c.failed>0?"failed":c.passed>0?"passed":"not_run",skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:o,evalPackDigest:Rs(e.pack),generatedAt:e.generatedAt,runnerVersion:e.runnerVersion,counts:{cases:a.length,assertions:c.total,passed:c.passed,failed:c.failed,skipped:c.skipped}});return Buffer.byteLength(JSON.stringify(u),"utf8")>ui.maxResultBytes?lf("resource_limit","eval-result-byte-limit","$result","Static Eval result exceeds the checked byte limit."):{outcome:"completed",result:{summary:u,cases:a}}}function OK(e){let t={total:0,passed:0,failed:0,skipped:0};for(let n of e)for(let r of n.assertions)t.total+=1,r.status==="passed"?t.passed+=1:r.status==="failed"?t.failed+=1:t.skipped+=1;return t}function lf(e,t,n,r){return{outcome:e,reasonCode:t,issues:[{code:t,path:n,message:r}]}}var S={};Vn(S,{$brand:()=>cf,$input:()=>p_,$output:()=>d_,NEVER:()=>Kk,TimePrecision:()=>h_,ZodAny:()=>ox,ZodArray:()=>cx,ZodBase64:()=>jm,ZodBase64URL:()=>Nm,ZodBigInt:()=>sa,ZodBigIntFormat:()=>Mm,ZodBoolean:()=>oa,ZodCIDRv4:()=>Om,ZodCIDRv6:()=>Lm,ZodCUID:()=>Pm,ZodCUID2:()=>Am,ZodCatch:()=>$x,ZodCodec:()=>Wm,ZodCustom:()=>Wc,ZodCustomStringFormat:()=>ra,ZodDate:()=>qc,ZodDefault:()=>Cx,ZodDiscriminatedUnion:()=>dx,ZodE164:()=>Fm,ZodEmail:()=>xm,ZodEmoji:()=>Cm,ZodEnum:()=>ta,ZodError:()=>lJ,ZodExactOptional:()=>_x,ZodFile:()=>wx,ZodFirstPartyTypeKind:()=>qx,ZodFunction:()=>Mx,ZodGUID:()=>Fc,ZodIPv4:()=>Dm,ZodIPv6:()=>Tm,ZodISODate:()=>vm,ZodISODateTime:()=>ym,ZodISODuration:()=>wm,ZodISOTime:()=>km,ZodIntersection:()=>px,ZodIssueCode:()=>uJ,ZodJWT:()=>Bm,ZodKSUID:()=>$m,ZodLazy:()=>Nx,ZodLiteral:()=>kx,ZodMAC:()=>XS,ZodMap:()=>yx,ZodNaN:()=>Tx,ZodNanoID:()=>Im,ZodNever:()=>ax,ZodNonOptional:()=>Hm,ZodNull:()=>rx,ZodNullable:()=>xx,ZodNumber:()=>ia,ZodNumberFormat:()=>uo,ZodObject:()=>Gc,ZodOptional:()=>Gm,ZodPipe:()=>Km,ZodPrefault:()=>Px,ZodPromise:()=>Bx,ZodReadonly:()=>Ox,ZodRealError:()=>Kt,ZodRecord:()=>Kc,ZodSet:()=>vx,ZodString:()=>na,ZodStringFormat:()=>Se,ZodSuccess:()=>Ex,ZodSymbol:()=>tx,ZodTemplateLiteral:()=>jx,ZodTransform:()=>bx,ZodTuple:()=>mx,ZodType:()=>se,ZodULID:()=>Rm,ZodURL:()=>zc,ZodUUID:()=>tr,ZodUndefined:()=>nx,ZodUnion:()=>Hc,ZodUnknown:()=>sx,ZodVoid:()=>lx,ZodXID:()=>Em,ZodXor:()=>ux,_ZodString:()=>Sm,_default:()=>Ix,_function:()=>$L,any:()=>cL,array:()=>Vc,base64:()=>HO,base64url:()=>KO,bigint:()=>iL,boolean:()=>ex,catch:()=>Dx,check:()=>DL,cidrv4:()=>VO,cidrv6:()=>GO,clone:()=>It,codec:()=>AL,coerce:()=>Vx,config:()=>je,core:()=>Rr,cuid:()=>jO,cuid2:()=>NO,custom:()=>TL,date:()=>dL,decode:()=>GS,decodeAsync:()=>KS,describe:()=>OL,discriminatedUnion:()=>yL,e164:()=>WO,email:()=>IO,emoji:()=>OO,encode:()=>VS,encodeAsync:()=>HS,endsWith:()=>Gs,enum:()=>qm,exactOptional:()=>Sx,file:()=>xL,flattenError:()=>Cc,float32:()=>eL,float64:()=>tL,formatError:()=>Ic,fromJSONSchema:()=>UL,function:()=>$L,getErrorMap:()=>pJ,globalRegistry:()=>pt,gt:()=>Qn,gte:()=>Pt,guid:()=>PO,hash:()=>QO,hex:()=>XO,hostname:()=>YO,httpUrl:()=>TO,includes:()=>qs,instanceof:()=>jL,int:()=>_m,int32:()=>nL,int64:()=>oL,intersection:()=>fx,ipv4:()=>UO,ipv6:()=>qO,iso:()=>ea,json:()=>FL,jwt:()=>ZO,keyof:()=>pL,ksuid:()=>MO,lazy:()=>Fx,length:()=>lo,literal:()=>SL,locales:()=>Oc,looseObject:()=>gL,looseRecord:()=>kL,lowercase:()=>Us,lt:()=>Xn,lte:()=>rn,mac:()=>zO,map:()=>wL,maxLength:()=>ao,maxSize:()=>yi,meta:()=>LL,mime:()=>Hs,minLength:()=>Ar,minSize:()=>er,multipleOf:()=>hi,nan:()=>PL,nanoid:()=>LO,nativeEnum:()=>_L,negative:()=>am,never:()=>Um,nonnegative:()=>cm,nonoptional:()=>Rx,nonpositive:()=>lm,normalize:()=>Ks,null:()=>ix,nullable:()=>Mc,nullish:()=>CL,number:()=>QS,object:()=>fL,optional:()=>Bc,overwrite:()=>jn,parse:()=>MS,parseAsync:()=>US,partialRecord:()=>vL,pipe:()=>Uc,positive:()=>sm,prefault:()=>Ax,preprocess:()=>BL,prettifyError:()=>ow,promise:()=>EL,property:()=>um,readonly:()=>Lx,record:()=>hx,refine:()=>Ux,regex:()=>Ms,regexes:()=>wn,registry:()=>Bf,safeDecode:()=>ZS,safeDecodeAsync:()=>YS,safeEncode:()=>WS,safeEncodeAsync:()=>JS,safeParse:()=>zS,safeParseAsync:()=>qS,set:()=>bL,setErrorMap:()=>dJ,size:()=>so,slugify:()=>Ys,startsWith:()=>Vs,strictObject:()=>mL,string:()=>bm,stringFormat:()=>JO,stringbool:()=>NL,success:()=>IL,superRefine:()=>zx,symbol:()=>aL,templateLiteral:()=>RL,toJSONSchema:()=>mm,toLowerCase:()=>Zs,toUpperCase:()=>Js,transform:()=>Vm,treeifyError:()=>iw,trim:()=>Ws,tuple:()=>gx,uint32:()=>rL,uint64:()=>sL,ulid:()=>FO,undefined:()=>lL,union:()=>zm,unknown:()=>co,uppercase:()=>zs,url:()=>DO,util:()=>M,uuid:()=>AO,uuidv4:()=>RO,uuidv6:()=>EO,uuidv7:()=>$O,void:()=>uL,xid:()=>BO,xor:()=>hL});var Rr={};Vn(Rr,{$ZodAny:()=>Tb,$ZodArray:()=>Fb,$ZodAsyncError:()=>Ln,$ZodBase64:()=>Sb,$ZodBase64URL:()=>xb,$ZodBigInt:()=>Df,$ZodBigIntFormat:()=>Rb,$ZodBoolean:()=>Ec,$ZodCIDRv4:()=>wb,$ZodCIDRv6:()=>bb,$ZodCUID:()=>lb,$ZodCUID2:()=>cb,$ZodCatch:()=>n_,$ZodCheck:()=>Ie,$ZodCheckBigIntFormat:()=>Fw,$ZodCheckEndsWith:()=>Jw,$ZodCheckGreaterThan:()=>Cf,$ZodCheckIncludes:()=>Ww,$ZodCheckLengthEquals:()=>Vw,$ZodCheckLessThan:()=>xf,$ZodCheckLowerCase:()=>Hw,$ZodCheckMaxLength:()=>zw,$ZodCheckMaxSize:()=>Bw,$ZodCheckMimeType:()=>Xw,$ZodCheckMinLength:()=>qw,$ZodCheckMinSize:()=>Mw,$ZodCheckMultipleOf:()=>jw,$ZodCheckNumberFormat:()=>Nw,$ZodCheckOverwrite:()=>Qw,$ZodCheckProperty:()=>Yw,$ZodCheckRegex:()=>Gw,$ZodCheckSizeEquals:()=>Uw,$ZodCheckStartsWith:()=>Zw,$ZodCheckStringFormat:()=>Fs,$ZodCheckUpperCase:()=>Kw,$ZodCodec:()=>Dc,$ZodCustom:()=>u_,$ZodCustomStringFormat:()=>Pb,$ZodDate:()=>Nb,$ZodDefault:()=>Xb,$ZodDiscriminatedUnion:()=>Ub,$ZodE164:()=>Cb,$ZodEmail:()=>ib,$ZodEmoji:()=>sb,$ZodEncodeError:()=>di,$ZodEnum:()=>Hb,$ZodError:()=>xc,$ZodExactOptional:()=>Jb,$ZodFile:()=>Wb,$ZodFunction:()=>a_,$ZodGUID:()=>nb,$ZodIPv4:()=>yb,$ZodIPv6:()=>vb,$ZodISODate:()=>mb,$ZodISODateTime:()=>fb,$ZodISODuration:()=>hb,$ZodISOTime:()=>gb,$ZodIntersection:()=>zb,$ZodJWT:()=>Ib,$ZodKSUID:()=>pb,$ZodLazy:()=>c_,$ZodLiteral:()=>Kb,$ZodMAC:()=>kb,$ZodMap:()=>Vb,$ZodNaN:()=>r_,$ZodNanoID:()=>ab,$ZodNever:()=>Lb,$ZodNonOptional:()=>e_,$ZodNull:()=>Db,$ZodNullable:()=>Yb,$ZodNumber:()=>$f,$ZodNumberFormat:()=>Ab,$ZodObject:()=>CT,$ZodObjectJIT:()=>Bb,$ZodOptional:()=>Of,$ZodPipe:()=>i_,$ZodPrefault:()=>Qb,$ZodPromise:()=>l_,$ZodReadonly:()=>o_,$ZodRealError:()=>Ht,$ZodRecord:()=>qb,$ZodRegistry:()=>Ff,$ZodSet:()=>Gb,$ZodString:()=>oo,$ZodStringFormat:()=>_e,$ZodSuccess:()=>t_,$ZodSymbol:()=>Eb,$ZodTemplateLiteral:()=>s_,$ZodTransform:()=>Zb,$ZodTuple:()=>Tf,$ZodType:()=>oe,$ZodULID:()=>ub,$ZodURL:()=>ob,$ZodUUID:()=>rb,$ZodUndefined:()=>$b,$ZodUnion:()=>$c,$ZodUnknown:()=>Ob,$ZodVoid:()=>jb,$ZodXID:()=>db,$ZodXor:()=>Mb,$brand:()=>cf,$constructor:()=>I,$input:()=>p_,$output:()=>d_,Doc:()=>Rc,JSONSchema:()=>xO,JSONSchemaGenerator:()=>gm,NEVER:()=>Kk,TimePrecision:()=>h_,_any:()=>N_,_array:()=>V_,_base64:()=>nm,_base64url:()=>rm,_bigint:()=>E_,_boolean:()=>A_,_catch:()=>eJ,_check:()=>SO,_cidrv4:()=>em,_cidrv6:()=>tm,_coercedBigint:()=>$_,_coercedBoolean:()=>R_,_coercedDate:()=>z_,_coercedNumber:()=>__,_coercedString:()=>m_,_cuid:()=>Kf,_cuid2:()=>Wf,_custom:()=>H_,_date:()=>U_,_decode:()=>gf,_decodeAsync:()=>yf,_default:()=>YZ,_discriminatedUnion:()=>BZ,_e164:()=>im,_email:()=>Mf,_emoji:()=>Gf,_encode:()=>mf,_encodeAsync:()=>hf,_endsWith:()=>Gs,_enum:()=>GZ,_file:()=>G_,_float32:()=>x_,_float64:()=>C_,_gt:()=>Qn,_gte:()=>Pt,_guid:()=>Lc,_includes:()=>qs,_int:()=>S_,_int32:()=>I_,_int64:()=>D_,_intersection:()=>MZ,_ipv4:()=>Xf,_ipv6:()=>Qf,_isoDate:()=>v_,_isoDateTime:()=>y_,_isoDuration:()=>w_,_isoTime:()=>k_,_jwt:()=>om,_ksuid:()=>Yf,_lazy:()=>iJ,_length:()=>lo,_literal:()=>KZ,_lowercase:()=>Us,_lt:()=>Xn,_lte:()=>rn,_mac:()=>g_,_map:()=>qZ,_max:()=>rn,_maxLength:()=>ao,_maxSize:()=>yi,_mime:()=>Hs,_min:()=>Pt,_minLength:()=>Ar,_minSize:()=>er,_multipleOf:()=>hi,_nan:()=>q_,_nanoid:()=>Hf,_nativeEnum:()=>HZ,_negative:()=>am,_never:()=>B_,_nonnegative:()=>cm,_nonoptional:()=>XZ,_nonpositive:()=>lm,_normalize:()=>Ks,_null:()=>j_,_nullable:()=>JZ,_number:()=>b_,_optional:()=>ZZ,_overwrite:()=>jn,_parse:()=>Os,_parseAsync:()=>Ls,_pipe:()=>tJ,_positive:()=>sm,_promise:()=>oJ,_property:()=>um,_readonly:()=>nJ,_record:()=>zZ,_refine:()=>K_,_regex:()=>Ms,_safeDecode:()=>kf,_safeDecodeAsync:()=>bf,_safeEncode:()=>vf,_safeEncodeAsync:()=>wf,_safeParse:()=>js,_safeParseAsync:()=>Ns,_set:()=>VZ,_size:()=>so,_slugify:()=>Ys,_startsWith:()=>Vs,_string:()=>f_,_stringFormat:()=>Xs,_stringbool:()=>Y_,_success:()=>QZ,_superRefine:()=>W_,_symbol:()=>O_,_templateLiteral:()=>rJ,_toLowerCase:()=>Zs,_toUpperCase:()=>Js,_transform:()=>WZ,_trim:()=>Ws,_tuple:()=>UZ,_uint32:()=>P_,_uint64:()=>T_,_ulid:()=>Zf,_undefined:()=>L_,_union:()=>NZ,_unknown:()=>F_,_uppercase:()=>zs,_url:()=>jc,_uuid:()=>Uf,_uuidv4:()=>zf,_uuidv6:()=>qf,_uuidv7:()=>Vf,_void:()=>M_,_xid:()=>Jf,_xor:()=>FZ,clone:()=>It,config:()=>je,createStandardJSONSchemaMethod:()=>Qs,createToJSONSchemaMethod:()=>X_,decode:()=>lW,decodeAsync:()=>uW,describe:()=>Z_,encode:()=>aW,encodeAsync:()=>cW,extractDefs:()=>ki,finalize:()=>wi,flattenError:()=>Cc,formatError:()=>Ic,globalConfig:()=>yc,globalRegistry:()=>pt,initializeContext:()=>vi,isValidBase64:()=>_b,isValidBase64URL:()=>bT,isValidJWT:()=>_T,locales:()=>Oc,meta:()=>J_,parse:()=>pf,parseAsync:()=>ff,prettifyError:()=>ow,process:()=>be,regexes:()=>wn,registry:()=>Bf,safeDecode:()=>pW,safeDecodeAsync:()=>mW,safeEncode:()=>dW,safeEncodeAsync:()=>fW,safeParse:()=>sw,safeParseAsync:()=>aw,toDotPath:()=>rT,toJSONSchema:()=>mm,treeifyError:()=>iw,util:()=>M,version:()=>eb});var Kk=Object.freeze({status:"aborted"});function I(e,t,n){function r(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let c=s.prototype,u=Object.keys(c);for(let d=0;d<u.length;d++){let p=u[d];p in a||(a[p]=c[p].bind(a))}}let i=n?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(a){var l;let c=n?.Parent?new o:this;r(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var cf=Symbol("zod_brand"),Ln=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},di=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}},yc={};function je(e){return e&&Object.assign(yc,e),yc}var M={};Vn(M,{BIGINT_FORMAT_RANGES:()=>rw,Class:()=>Zk,NUMBER_FORMAT_RANGES:()=>nw,aborted:()=>gi,allowsEval:()=>Xk,assert:()=>BK,assertEqual:()=>LK,assertIs:()=>NK,assertNever:()=>FK,assertNotEqual:()=>jK,assignProp:()=>fi,base64ToUint8Array:()=>eT,base64urlToUint8Array:()=>nW,cached:()=>Ds,captureStackTrace:()=>df,cleanEnum:()=>tW,cleanRegex:()=>wc,clone:()=>It,cloneDef:()=>UK,createTransparentProxy:()=>KK,defineLazy:()=>de,esc:()=>uf,escapeRegex:()=>kn,extend:()=>JK,finalizeIssue:()=>Gt,floatSafeRemainder:()=>Jk,getElementAtPath:()=>zK,getEnumValues:()=>kc,getLengthableOrigin:()=>Sc,getParsedType:()=>HK,getSizableOrigin:()=>_c,hexToUint8Array:()=>iW,isObject:()=>ro,isPlainObject:()=>mi,issue:()=>Ts,joinValues:()=>$,jsonStringifyReplacer:()=>$s,merge:()=>XK,mergeDefs:()=>Pr,normalizeParams:()=>U,nullish:()=>pi,numKeys:()=>GK,objectClone:()=>MK,omit:()=>ZK,optionalKeys:()=>tw,parsedType:()=>B,partial:()=>QK,pick:()=>WK,prefixIssues:()=>nn,primitiveTypes:()=>ew,promiseAllObject:()=>qK,propertyKeyTypes:()=>bc,randomString:()=>VK,required:()=>eW,safeExtend:()=>YK,shallowClone:()=>Qk,slugify:()=>Yk,stringifyPrimitive:()=>F,uint8ArrayToBase64:()=>tT,uint8ArrayToBase64url:()=>rW,uint8ArrayToHex:()=>oW,unwrapMessage:()=>vc});function LK(e){return e}function jK(e){return e}function NK(e){}function FK(e){throw new Error("Unexpected value in exhaustive check")}function BK(e){}function kc(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function $(e,t="|"){return e.map(n=>F(n)).join(t)}function $s(e,t){return typeof t=="bigint"?t.toString():t}function Ds(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function pi(e){return e==null}function wc(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Jk(e,t){let n=(e.toString().split(".")[1]||"").length,r=t.toString(),i=(r.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(r)){let l=r.match(/\d?e-(\d?)/);l?.[1]&&(i=Number.parseInt(l[1]))}let o=n>i?n:i,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}var Q1=Symbol("evaluating");function de(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Q1)return r===void 0&&(r=Q1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function MK(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function fi(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Pr(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function UK(e){return Pr(e._zod.def)}function zK(e,t){return t?t.reduce((n,r)=>n?.[r],e):e}function qK(e){let t=Object.keys(e),n=t.map(r=>e[r]);return Promise.all(n).then(r=>{let i={};for(let o=0;o<t.length;o++)i[t[o]]=r[o];return i})}function VK(e=10){let t="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<e;r++)n+=t[Math.floor(Math.random()*t.length)];return n}function uf(e){return JSON.stringify(e)}function Yk(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var df="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ro(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Xk=Ds(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function mi(e){if(ro(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(ro(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Qk(e){return mi(e)?{...e}:Array.isArray(e)?[...e]:e}function GK(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}var HK=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},bc=new Set(["string","number","symbol"]),ew=new Set(["string","number","bigint","boolean","symbol","undefined"]);function kn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function It(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function U(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function KK(e){let t;return new Proxy({},{get(n,r,i){return t??(t=e()),Reflect.get(t,r,i)},set(n,r,i,o){return t??(t=e()),Reflect.set(t,r,i,o)},has(n,r){return t??(t=e()),Reflect.has(t,r)},deleteProperty(n,r){return t??(t=e()),Reflect.deleteProperty(t,r)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,r){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)},defineProperty(n,r,i){return t??(t=e()),Reflect.defineProperty(t,r,i)}})}function F(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function tw(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var nw={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},rw={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function WK(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let o=Pr(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=n.shape[a])}return fi(this,"shape",s),s},checks:[]});return It(e,o)}function ZK(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let o=Pr(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return fi(this,"shape",s),s},checks:[]});return It(e,o)}function JK(e,t){if(!mi(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=Pr(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return fi(this,"shape",o),o}});return It(e,i)}function YK(e,t){if(!mi(t))throw new Error("Invalid input to safeExtend: expected a plain object");let n=Pr(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return fi(this,"shape",r),r}});return It(e,n)}function XK(e,t){let n=Pr(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return fi(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return It(e,n)}function QK(e,t,n){let i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Pr(t._zod.def,{get shape(){let a=t._zod.def.shape,l={...a};if(n)for(let c in n){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);n[c]&&(l[c]=e?new e({type:"optional",innerType:a[c]}):a[c])}else for(let c in a)l[c]=e?new e({type:"optional",innerType:a[c]}):a[c];return fi(this,"shape",l),l},checks:[]});return It(t,s)}function eW(e,t,n){let r=Pr(t._zod.def,{get shape(){let i=t._zod.def.shape,o={...i};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:i[s]}))}else for(let s in i)o[s]=new e({type:"nonoptional",innerType:i[s]});return fi(this,"shape",o),o}});return It(t,r)}function gi(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function nn(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function vc(e){return typeof e=="string"?e:e?.message}function Gt(e,t,n){let r={...e,path:e.path??[]};if(!e.message){let i=vc(e.inst?._zod.def?.error?.(e))??vc(t?.error?.(e))??vc(n.customError?.(e))??vc(n.localeError?.(e))??"Invalid input";r.message=i}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function _c(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Sc(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function B(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function Ts(...e){let[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}function tW(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function eT(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function tT(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function nW(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return eT(t+n)}function rW(e){return tT(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function iW(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function oW(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Zk=class{constructor(...t){}};var nT=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,$s,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},xc=I("$ZodError",nT),Ht=I("$ZodError",nT,{Parent:Error});function Cc(e,t=n=>n.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ic(e,t=n=>n.message){let n={_errors:[]},r=i=>{for(let o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>r({issues:s}));else if(o.code==="invalid_key")r({issues:o.issues});else if(o.code==="invalid_element")r({issues:o.issues});else if(o.path.length===0)n._errors.push(t(o));else{let s=n,a=0;for(;a<o.path.length;){let l=o.path[a];a===o.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(t(o))):s[l]=s[l]||{_errors:[]},s=s[l],a++}}};return r(e),n}function iw(e,t=n=>n.message){let n={errors:[]},r=(i,o=[])=>{var s,a;for(let l of i.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(c=>r({issues:c},l.path));else if(l.code==="invalid_key")r({issues:l.issues},l.path);else if(l.code==="invalid_element")r({issues:l.issues},l.path);else{let c=[...o,...l.path];if(c.length===0){n.errors.push(t(l));continue}let u=n,d=0;for(;d<c.length;){let p=c[d],m=d===c.length-1;typeof p=="string"?(u.properties??(u.properties={}),(s=u.properties)[p]??(s[p]={errors:[]}),u=u.properties[p]):(u.items??(u.items=[]),(a=u.items)[p]??(a[p]={errors:[]}),u=u.items[p]),m&&u.errors.push(t(l)),d++}}};return r(e),n}function rT(e){let t=[],n=e.map(r=>typeof r=="object"?r.key:r);for(let r of n)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function ow(e){let t=[],n=[...e.issues].sort((r,i)=>(r.path??[]).length-(i.path??[]).length);for(let r of n)t.push(`\u2716 ${r.message}`),r.path?.length&&t.push(` \u2192 at ${rT(r.path)}`);return t.join(`
|
|
754
|
+
${o}`}function Vp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function g9(e){let t=v1(e.name,"name"),n=v1(e.description,"description"),r=e.license,i=h9(e.compatibility,"compatibility"),o=y9(e.metadata,"metadata"),s=m1(o?.agent_compatibility),a=v9(e["allowed-tools"]);if(!m9.test(t))throw new Error("name must be kebab-case");if(g1(t))throw new Error(qp());if(n.length>1024)throw new Error("description must be 1024 characters or fewer");return{name:t,description:n,...r===void 0?{}:{license:r},...i===void 0?{}:{compatibility:i},...s===void 0?{}:{compatibilityMatrix:s},...o===void 0?{}:{metadata:o},...a===void 0?{}:{"allowed-tools":a}}}function v1(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e.trim()}function h9(e,t){if(e===void 0)return;if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string when provided`);let n=e.trim();if(t==="compatibility"&&n.length>500)throw new Error("compatibility must be 500 characters or fewer");return n}function y9(e,t){if(e!==void 0){if(!Vp(e))throw new Error(`${t} must be an object when provided`);return e}}function v9(e){if(e!==void 0){if(typeof e=="string")return e.trim();if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e.map(t=>t.trim());throw new Error("allowed-tools must be a string or string array when provided")}}var Dk=fn(Ji(),1);var k9="private",b1="public",_1="unlisted";function uc(e){if(typeof e!="string"||e.trim().length===0)return null;let t=e.trim().toLowerCase();return t==="private"?k9:t===b1?b1:t===_1?_1:null}var Ek="skills-layer.control.v3",Cs="skills-layer.control.v2";var w9=new Set(["private","public","unlisted"]);var b9=new Set(["schemaVersion","listing","toolContract","targets"]),_9=new Set(["visibility","priceCents","category","tags"]),S9=new Set(["visibility","category","tags"]),x9=new Set(["requestedCapabilities","requestedTools","networkDomains","fileReadScopes","fileWriteScopes"]),C9=/^[^\s\u0000-\u001f\u007f]{1,160}$/u;function x1(e){let t;try{t=(0,Dk.parse)(e,{uniqueKeys:!0})}catch(n){let r=n instanceof Error?n.message:"Invalid control YAML";throw new Error(`Invalid Creator control manifest: ${r}`)}if(!I1(t))throw new Error("Creator control manifest must be a YAML object");if($k(t,b9,"control manifest"),t.schemaVersion!==Ek&&t.schemaVersion!==Cs)throw new Error(`Creator control schemaVersion must be ${Ek} or ${Cs}`);return I9(t)}function I9(e){let t=e.schemaVersion;if(t!==Ek&&t!==Cs)throw new Error("Creator control schemaVersion is invalid");let n=e.listing===void 0?{}:S1(e.listing,"listing"),r=e.toolContract===void 0?{}:S1(e.toolContract,"toolContract");$k(n,t===Cs?_9:S9,"listing"),$k(r,x9,"toolContract");let i=n.visibility===void 0?"private":P9(n.visibility,w9,"listing.visibility"),o=n.priceCents===void 0?0:n.priceCents;if(t===Cs&&(!Number.isInteger(o)||Number(o)<0))throw new Error("listing.priceCents must be a non-negative integer");let s=n.category===void 0||n.category===null?null:C1(n.category,"listing.category",80).toLowerCase();return{schemaVersion:t,listing:{visibility:i,...t===Cs&&n.priceCents!==void 0?{priceCents:Number(o)}:{},category:s,tags:Qi(n.tags,"listing.tags",80,!0)},toolContract:{requestedCapabilities:Qi(r.requestedCapabilities,"toolContract.requestedCapabilities"),requestedTools:Qi(r.requestedTools,"toolContract.requestedTools"),networkDomains:Qi(r.networkDomains,"toolContract.networkDomains",253,!0),fileReadScopes:Qi(r.fileReadScopes,"toolContract.fileReadScopes",1024),fileWriteScopes:Qi(r.fileWriteScopes,"toolContract.fileWriteScopes",1024)},targets:Qi(e.targets,"targets",160,!0)}}function Qi(e,t,n=160,r=!1){if(e==null)return[];if(!Array.isArray(e))throw new Error(`${t} must be an array of bounded strings`);let i=e.map(o=>{let s=C1(o,t,n);if(!C9.test(s))throw new Error(`${t} contains an invalid value`);return r?s.toLowerCase():s});return[...new Set(i)].sort((o,s)=>o.localeCompare(s))}function $k(e,t,n){let r=Object.keys(e).filter(i=>!t.has(i));if(r.length>0)throw new Error(`${n} contains unsupported field(s): ${r.sort().join(", ")}`)}function S1(e,t){if(!I1(e))throw new Error(`${t} must be an object`);return e}function C1(e,t,n=200){if(typeof e!="string"||e.trim().length===0||e.trim().length>n)throw new Error(`${t} must be a non-empty string of at most ${n} characters`);if(/[\u0000-\u001f\u007f]/u.test(e))throw new Error(`${t} contains control characters`);return e.trim()}function P9(e,t,n){if(typeof e!="string"||!t.has(e))throw new Error(`${n} is not supported`);return e}function I1(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var A9=/(^|\/)SKILL\.md$/,R9=[/(^|\n)#+\s+examples?\b/i,/(^|\n)#+\s+usage examples?\b/i,/(^|\n)#+\s+\u793A\u4F8B(?=$|\s)/u,/(^|\n)#+\s+\u4F8B\u5B50(?=$|\s)/u,/(^|\n)#+\s+\u7528\u4F8B(?=$|\s)/u],E9=[/(^|\n)#+\s+troubleshooting\b/i,/(^|\n)#+\s+trouble shooting\b/i,/(^|\n)#+\s+\u6545\u969C\u6392\u9664(?=$|\s)/u,/(^|\n)#+\s+\u95EE\u9898\u6392\u67E5(?=$|\s)/u,/(^|\n)#+\s+\u6392\u9519(?=$|\s)/u],$9=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]+|[\p{L}\p{N}_-]+/gu,D9=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u;function nt(e,t={}){let n=t.profile??"legacy_v1",r=[],i=e.filter(d=>A9.test(d.path)),o=e.some(d=>d.path.includes("/references/")||d.path.startsWith("references/"));if(i.length===0)return r.push(Cr("skill-missing","Bundle must contain exactly one SKILL.md file")),Tk(n,!1,r,e.length,0,o);i.length>1&&r.push(Cr("skill-duplicate","Bundle must not contain more than one SKILL.md file"));let s=i[0];if(!s||typeof s.content!="string")return r.push(Cr("skill-content-missing","SKILL.md content must be available for validation")),Tk(n,!1,r,e.length,0,o);let a;try{a=Gp(s.content)}catch(d){let p=d instanceof Error?d.message:"Unknown frontmatter parsing error";return r.push(Cr("frontmatter-invalid",p)),n==="external_ingest_tolerant"&&r.push(li("external-normalisation-needed","The external skill is recognizable but must be normalized before release")),Tk(n,n==="external_ingest_tolerant",r,e.length,0,o)}/^Helps with [^.]+\.$/u.test(a.frontmatter.description.trim())&&r.push(li("scaffold-description-placeholder","Replace the scaffold description with the skill's concrete purpose and when to use it."));let l=T9(a.body),c=O9(a.frontmatter.metadata);c&&r.push(c);let u=Np(e,a.frontmatter);return r.push(...u.issues),r.push(...L9({files:e,skillFilePath:s.path,parsedSkill:a,profile:n})),P1(a.body,R9)||r.push(li("examples-missing","Consider adding an Examples section to improve skill usability")),P1(a.body,E9)||r.push(li("troubleshooting-missing","Consider adding a Troubleshooting section for common failure cases")),l>5e3&&r.push(li("skill-body-too-long","SKILL.md body should stay under 5000 words for progressive disclosure")),l>1200&&!o&&r.push(li("references-missing","Large skills should move detailed material into references/")),{profile:n,ingestible:i.length===1,valid:r.every(d=>d.severity!=="error"),issues:r,parsedSkill:a,license:u,stats:{fileCount:e.length,bodyWordCount:l,hasReferences:o}}}function T9(e){let t=e.trim();if(t.length===0)return 0;let n=t.match($9);return n?n.reduce((r,i)=>r+(D9.test(i)?i.length:1),0):0}function Cr(e,t){return{severity:"error",code:e,message:t}}function li(e,t){return{severity:"warning",code:e,message:t}}function P1(e,t){return t.some(n=>n.test(e))}function O9(e){return e?.price_cents===void 0?null:li("price-cents-non-authoritative","metadata.price_cents is ignored; marketplace pricing is stored in the version pricing authority")}function Tk(e,t,n,r,i,o){return{profile:e,ingestible:t,valid:!1,issues:n,stats:{fileCount:r,bodyWordCount:i,hasReferences:o}}}function L9(e){let t=[],n=YE(e.files),r=n.find(p=>p.type==="control");if(r){let p=e.files.find(m=>m.path.replaceAll("\\","/").replace(/^\.\//u,"")===r.path);try{x1(p?.content??"")}catch(m){t.push(Cr("control-manifest-invalid",m.message))}}if(e.profile==="legacy_v1")return t;let o=e.profile!=="external_ingest_tolerant"?Cr:li,s=e.parsedSkill.frontmatter.name;s.length>64&&t.push(o("portable-name-too-long","Portable skill names must be 64 characters or fewer"));let l=e.skillFilePath.replaceAll("\\","/").split("/").filter(Boolean),c=l.length>1?l.at(-2):void 0;c&&c!==s&&t.push(o("portable-directory-name-mismatch","Portable skill name must match the directory containing SKILL.md")),e.parsedSkill.frontmatter.compatibility!==void 0&&t.push(o("unverified-compatibility-claim","Compatibility claims belong in evidence-backed control data, not portable runtime frontmatter"));let u=e.parsedSkill.frontmatter.metadata,d=["agent_compatibility","category","license","license_file","price_cents","skills_layer","tags","visibility"].filter(p=>u&&Object.hasOwn(u,p));return d.length>0&&t.push(o("runtime-control-metadata",`Skills Layer control metadata must not be stored in portable runtime frontmatter: ${d.join(", ")}`)),n.some(p=>p.reasonCode==="misplaced_control_manifest")&&t.push(Cr("control-manifest-misplaced","The Skills Layer control manifest is allowed only at the skill root")),n.some(p=>p.reasonCode==="unsupported_control_material")&&t.push(Cr("control-material-unsupported","Only root .skills-layer/skill.yaml is supported as control material")),n.filter(p=>p.type==="control").length>1&&t.push(Cr("control-manifest-duplicate","A skill bundle may contain only one root control manifest")),t}function N9(e){return`sha256:${A1("sha256").update(ye(e)).digest("hex")}`}function R1(e){return`sha256:${A1("sha256").update(JSON.stringify(e.map(t=>({path:t.path,digest:N9(t)})))).digest("hex")}`}var dc=class extends Error{constructor(n,r){super(n);this.reasonCode=r}reasonCode};function E1(e,t){if(!Ok(e)||!Ok(e.workspace))throw eo("Creator materialization response is missing its workspace.");let n=B9(t??e.skillSlug);if(!n)throw new dc("Creator materialization response is missing a portable skill slug; rerun with --dir or inspect the session.","creator_materialization_slug_missing");if(!Array.isArray(e.workspace.files)||e.workspace.files.length===0)throw eo("Creator materialization response contains no files.");let r=e.workspace.files.map((s,a)=>F9(s,a)),i=e.workspace.digest;if(typeof i!="string"||!/^sha256:[a-f0-9]{64}$/u.test(i))throw eo("Creator materialization response is missing a valid workspace digest.");if(R1(r)!==i)throw new dc("Creator materialization workspace digest does not match the returned files.","creator_materialization_digest_mismatch");return{skillSlug:n,files:r,workspaceDigest:i}}function F9(e,t){if(!Ok(e)||typeof e.path!="string")throw eo(`Creator materialization file ${t+1} is malformed.`);let n=typeof e.content=="string",r=typeof e.contentBase64=="string";if(n===r)throw eo(`Creator materialization file ${e.path} must contain exactly one byte representation.`);if(e.mediaType!==void 0&&typeof e.mediaType!="string")throw eo(`Creator materialization file ${e.path} has an invalid media type.`);let i={path:e.path,...n?{content:e.content}:{contentBase64:e.contentBase64},...typeof e.mediaType=="string"?{mediaType:e.mediaType}:{}};try{ye(i)}catch(o){throw eo(o instanceof Error?o.message:`Creator materialization file ${e.path} is invalid.`)}return i}function B9(e){if(typeof e!="string")return null;let t=e.trim();return/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(t)&&t.length<=64?t:null}function eo(e){return new dc(e,"creator_materialization_snapshot_invalid")}function Ok(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{randomUUID as M9}from"node:crypto";import{constants as Ir}from"node:fs";import{lstat as On,mkdir as Hp,mkdtemp as U9,open as Lk,realpath as Kp,readdir as z9,rename as pc,rm as $1}from"node:fs/promises";import{basename as q9,dirname as fc,isAbsolute as V9,join as Yn,parse as jk,posix as T1,resolve as Zp,sep as Wp}from"node:path";var D1=16*1024*1024,G9=64*1024*1024,Nk=typeof Ir.O_NOFOLLOW=="number"?Ir.O_NOFOLLOW:0;async function O1(e){let t=await j1(e);await ci(t);let n=await Bk(t);return{exists:n.exists,files:n.files.map(r=>({path:r.relativePath,...en(r.bytes)}))}}async function Jp(e){let t=await K9(e);if(t.plan.confirmationRequired&&!e.confirmed)return{status:"confirmation_required",plan:t.plan};let n=t.targetDir,r=fc(n);await ci(r),await Hp(r,{recursive:!0}),await ci(r);let i=[...t.tree.files.map(c=>c.relativePath),...e.files.map(c=>c.path)].reduce((c,u)=>Math.max(c,u.length),0),o=H9({parentDir:r,longestRelativePath:i,platform:process.platform});await ci(o);let s=await U9(Yn(o,".skills-layer-stage-")),a=null,l=!0;try{t.tree.exists&&await Y9(t.tree,s);for(let c of e.files)await X9(s,c);if(await eK(n,t.tree),!t.tree.exists)return await to(()=>pc(s,n)),l=!1,{status:"created",plan:t.plan};a=Yn(o,`.skills-layer-backup-${M9()}`),await to(()=>pc(n,a));try{await to(()=>pc(s,n)),l=!1}catch(c){throw await to(()=>pc(a,n)),a=null,c}return await to(()=>$1(a,{recursive:!0,force:!0})),a=null,{status:"replaced",plan:t.plan}}finally{l&&await to(()=>$1(s,{recursive:!0,force:!0})),a&&await tK(n,a)}}function H9(e){if(e.platform!=="win32")return e.parentDir;let t=jk(e.parentDir).root,n=Wp.length+26+Wp.length+e.longestRelativePath,r=e.parentDir;for(;r!==t&&r.length+n>iK;)r=fc(r);return r}async function Fk(e,t=256*1024){let n=await N1(Zp(e));if(await ci(n),(await On(n)).isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${n}`);let i=await Kp(n);await ci(i);let o=await L1(i,t);return Buffer.from(o).toString("utf8")}async function K9(e){W9(e.files);let t=Zp(e.targetDir),n=await j1(t);await ci(n);let r=await Bk(n),i=new Map(r.files.map(l=>[l.relativePath,l])),o=new Set(r.directories.map(l=>l.relativePath)),s=e.files.map(l=>{let c=i.get(l.path);if(o.has(l.path))throw new Error(`Scaffold file ${l.path} conflicts with an existing directory.`);let u=ye(l),d=u.byteLength;if(!c)return{path:l.path,action:"create",previousBytes:null,nextBytes:d};let p=Buffer.from(c.bytes).equals(Buffer.from(u));return{path:l.path,action:p?"unchanged":"replace",previousBytes:c.bytes.byteLength,nextBytes:d}}),a=r.files.length+r.directories.length;return{tree:r,targetDir:n,plan:{targetDir:t,targetExists:r.exists,confirmationRequired:r.exists&&a>0,preservedEntryCount:a,changes:s}}}function W9(e){let t=new Set,n=new Map,r=new Set(e.map(o=>o.path));for(let o of e){if(Z9(o.path),t.has(o.path))throw new Error(`Scaffold contains duplicate generated path ${o.path}.`);t.add(o.path);let s=o.path.normalize("NFC").toLocaleLowerCase("en-US"),a=n.get(s);if(a&&a!==o.path)throw new Error(`Scaffold contains a cross-platform path collision: ${a} and ${o.path}.`);n.set(s,o.path);let l=o.path.split("/");for(let c=1;c<l.length;c+=1){let u=l.slice(0,c).join("/");if(r.has(u))throw new Error(`Scaffold file ${u} conflicts with generated descendant ${o.path}.`)}}let i=nt(e);if(!i.valid)throw new Error(`Scaffold bundle validation failed: ${i.issues.filter(o=>o.severity==="error").map(o=>`${o.code}: ${o.message}`).join("; ")}`)}function Z9(e){let t=e.split("/");if(e.length===0||e.includes("\\")||e.includes("\0")||V9(e)||T1.normalize(e)!==e||e===".."||e.startsWith("../")||e!==e.normalize("NFC")||e.length>1024||t.some(n=>!J9(n)))throw new Error(`Unsafe scaffold path: ${e}`)}function J9(e){if(!e||e.length>255||/[<>:"|?*\u0000-\u001f]/u.test(e)||/[ .]$/u.test(e))return!1;let t=e.split(".")[0].toUpperCase();return!oK.has(t)}async function Bk(e){let t;try{t=await On(e,{bigint:!0})}catch(s){if(Is(s))return{exists:!1,identity:null,files:[],directories:[]};throw s}if(t.isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${e}`);if(!t.isDirectory())throw new Error(`Scaffold target must be a directory: ${e}`);let n=[],r=[],i=0,o=async(s,a)=>{let l=await On(s,{bigint:!0});if(l.isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${s}`);if(!l.isDirectory())throw new Error(`Scaffold target changed while it was inspected: ${s}`);let c=(await z9(s,{withFileTypes:!0})).sort((d,p)=>d.name.localeCompare(p.name));for(let d of c){let p=Yn(s,d.name),m=a?T1.join(a,d.name):d.name,h=await On(p,{bigint:!0});if(h.isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${p}`);if(h.isDirectory()){r.push({relativePath:m,absolutePath:p}),await o(p,m);continue}if(!h.isFile())throw new Error(`Scaffold transaction refuses non-regular filesystem entries: ${p}`);let g=Number(h.size);if(g>D1||i+g>G9)throw new Error("Existing scaffold target exceeds the bounded transaction copy limit.");let y=await L1(p,D1);i+=y.byteLength,n.push({relativePath:m,absolutePath:p,bytes:y})}let u=await On(s,{bigint:!0});if(u.dev!==l.dev||u.ino!==l.ino||!u.isDirectory())throw new Error(`Scaffold target changed while it was inspected: ${s}`)};return await o(e,""),{exists:!0,identity:{dev:t.dev,ino:t.ino},files:n,directories:r}}async function L1(e,t){let n=await Lk(e,Ir.O_RDONLY|Nk);try{let r=await n.stat();if(!r.isFile())throw new Error(`Expected a regular file: ${e}`);if(r.size>t)throw new Error(`File exceeds the bounded read limit: ${e}`);return new Uint8Array(await n.readFile())}finally{await n.close()}}async function Y9(e,t){for(let n of e.directories)await Hp(Yn(t,...n.relativePath.split("/")),{recursive:!0});for(let n of e.files){let r=Yn(t,...n.relativePath.split("/"));await Hp(fc(r),{recursive:!0}),await Q9(r,n.bytes)}}async function X9(e,t){let n=Yn(e,...t.path.split("/"));await Hp(fc(n),{recursive:!0});let r=await Lk(n,Ir.O_WRONLY|Ir.O_CREAT|Ir.O_TRUNC|Nk,384);try{await r.writeFile(ye(t)),await r.sync()}finally{await r.close()}}async function Q9(e,t){let n=await Lk(e,Ir.O_WRONLY|Ir.O_CREAT|Ir.O_EXCL|Nk,384);try{await n.writeFile(t)}finally{await n.close()}}async function ci(e){let t=Zp(e),n=jk(t).root,r=t.slice(n.length).split(Wp).filter(Boolean),i=n;for(let o of r){i=Yn(i,o);try{if((await On(i)).isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${i}`)}catch(s){if(Is(s))return;throw s}}}async function j1(e){let t=await N1(Zp(e));await ci(t);try{if((await On(t)).isSymbolicLink())throw new Error(`Scaffold transaction refuses symbolic links: ${t}`);return await Kp(t)}catch(o){if(!Is(o))throw o}let n=[],r=t;for(;;)try{await On(r);break}catch(o){if(!Is(o))throw o;let s=fc(r);if(s===r)throw new Error(`Unable to resolve scaffold target parent: ${t}`);n.unshift(q9(r)),r=s}let i=await Kp(r);return Yn(i,...n)}async function N1(e){let t=jk(e).root,n=e.slice(t.length).split(Wp).filter(Boolean);if(n.length===0)return e;let r=Yn(t,n[0]);return(await On(r)).isSymbolicLink()?Yn(await Kp(r),...n.slice(1)):e}async function eK(e,t){let n=await Bk(e);if(n.exists!==t.exists)throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");if(!t.exists)return;if(!t.identity||!n.identity||n.identity.dev!==t.identity.dev||n.identity.ino!==t.identity.ino)throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");let r=t.directories.map(o=>o.relativePath),i=n.directories.map(o=>o.relativePath);if(r.join("\0")!==i.join("\0"))throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");if(n.files.length!==t.files.length)throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.");for(let o=0;o<t.files.length;o+=1){let s=t.files[o],a=n.files[o];if(s.relativePath!==a.relativePath||!Buffer.from(s.bytes).equals(Buffer.from(a.bytes)))throw new Error("Scaffold target changed after preview; rerun creator init to review a fresh diff.")}}async function tK(e,t){try{await On(t)}catch(n){if(Is(n))return;throw n}try{await On(e)}catch(n){if(Is(n)){await to(()=>pc(t,e));return}throw n}throw new Error(`Scaffold backup requires manual recovery: ${t}`)}async function to(e,t={}){let n=t.maximumAttempts??5;if(!Number.isInteger(n)||n<1||n>10)throw new Error("Filesystem retry maximumAttempts must be between 1 and 10.");let r=t.wait??(i=>new Promise(o=>setTimeout(o,i)));for(let i=1;;i+=1)try{return await e()}catch(o){if(!nK(o)||i>=n)throw o;await r(Math.min(160,10*2**(i-1)))}}function nK(e){return typeof e=="object"&&e!==null&&"code"in e&&rK.has(String(e.code))}function Is(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}var rK=new Set(["EPERM","EBUSY","ENOTEMPTY","EACCES"]),iK=240,oK=new Set(["CON","PRN","AUX","NUL","CLOCK$",...Array.from({length:9},(e,t)=>`COM${t+1}`),...Array.from({length:9},(e,t)=>`LPT${t+1}`)]);var F1="skills-layer.creator.platform-telemetry.v1";function Yp(e){return e==="darwin"?"macos":e==="linux"?"linux":e==="win32"?"windows":"other"}function Xp(e){let t={schemaVersion:F1,...e};if(!B1(t))throw new Error("Creator platform telemetry event is invalid or contains unsupported fields");return t}function B1(e){return!sK(e)||Object.keys(e).sort().join("\0")!==["nodeMajor","occurredAt","operation","operationId","osFamily","outcome","schemaVersion"].sort().join("\0")?!1:e.schemaVersion===F1&&(e.osFamily==="macos"||e.osFamily==="linux"||e.osFamily==="windows"||e.osFamily==="other")&&Number.isInteger(e.nodeMajor)&&Number(e.nodeMajor)>=18&&Number(e.nodeMajor)<=99&&(e.operation==="plan"||e.operation==="materialize"||e.operation==="patch"||e.operation==="recover")&&(e.outcome==="succeeded"||e.outcome==="failed"||e.outcome==="recovered")&&typeof e.operationId=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.operationId)&&typeof e.occurredAt=="string"&&Number.isFinite(Date.parse(e.occurredAt))}async function Qp(e){if(!B1(e.event))throw new Error("Creator platform telemetry event is invalid");try{return await e.publish(e.event),"accepted"}catch{return"ignored"}}function sK(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{resolve as M1}from"node:path";async function Mk(e){if(e.skip&&(e.explicitIdentifier||e.explicitLicenseFile))throw new Error("--skip-license cannot be combined with --license or --license-file.");if(e.explicitLicenseFile&&!e.explicitIdentifier)throw new Error("--license-file requires --license <SPDX-or-LicenseRef-identifier>.");if(e.skip)return{selection:{mode:"skip"},source:"skip"};if(e.explicitIdentifier){let i=si(e.explicitIdentifier);if(e.explicitLicenseFile)return{selection:{mode:"custom",identifier:i,text:await Fk(M1(e.cwd,e.explicitLicenseFile)),filePath:"LICENSE"},source:"explicit_import"};if(!ic(i))throw new Error(`--license ${i} requires --license-file because Skills Layer will not invent or guess terms.`);return{selection:{mode:"template",identifier:i},source:"explicit_template"}}let t=aK(e.files??[]);if(t?.status==="verified"||t?.status==="recognized_template")return{selection:U1(t),source:"existing"};if(!e.interactive||!e.prompt)return{selection:{mode:"skip"},source:"skip"};let n=[];t?.status==="confirmation_required"&&t.detectedIdentifier&&t.text&&t.filePath&&n.push({value:`existing:${t.detectedIdentifier}`,label:`Confirm detected ${t.detectedIdentifier} terms`,description:`Preserve ${t.filePath} byte-for-byte and bind its detected identifier.`}),n.push({value:"template:MIT",label:"Use the approved MIT template",description:"Creator-selected immutable standard template; review and replace placeholders before publication."},{value:"import",label:"Import my exact terms",description:"Supply an SPDX/LicenseRef identifier and a local text file; Skills Layer will not alter it."},{value:"skip",label:"Skip for now",description:"Continue with a visible, non-blocking license_missing warning."});let r=await e.prompt.select("Choose optional creator licence terms:",n);if(!r||r==="skip")return{selection:{mode:"skip"},source:"skip"};if(r.startsWith("existing:")&&t?.text&&t.filePath)return{selection:U1(t),source:"existing"};if(r==="template:MIT")return{selection:{mode:"template",identifier:"MIT"},source:"interactive_template"};if(r==="import"){let i=si(await e.prompt.text("SPDX or LicenseRef-* identifier: ")),o=(await e.prompt.text("Path to the exact licence terms file: ")).trim();if(!o)throw new Error("A licence terms file path is required for import.");return{selection:{mode:"custom",identifier:i,text:await Fk(M1(e.cwd,o)),filePath:"LICENSE"},source:"interactive_import"}}throw new Error("Unsupported creator licence selection.")}function z1(e,t){let n=e.filter(o=>/(^|\/)SKILL\.md$/u.test(o.path)&&typeof o.content=="string");if(n.length!==1||!n[0]?.content)throw new Error("Licence remediation requires exactly one readable SKILL.md file.");let r=t.mode==="template"?"LICENSE":t.filePath??"LICENSE",i=t.mode==="template"?Xi(t.identifier):t.text;return[{path:n[0].path,content:w1(n[0].content,t.identifier,r)},{path:r,content:i}]}function aK(e){let t=e.filter(n=>/(^|\/)SKILL\.md$/u.test(n.path)&&typeof n.content=="string");if(t.length!==1||!t[0]?.content)return null;try{return Np(e,Gp(t[0].content).frontmatter)}catch{return null}}function U1(e){if(!e.identifier&&!e.detectedIdentifier)throw new Error("Existing licence selection requires a creator-confirmed identifier.");if(!e.text||!e.filePath)throw new Error("Existing licence selection requires exact in-bundle terms.");return{mode:"existing",identifier:e.identifier??e.detectedIdentifier,text:e.text,filePath:e.filePath}}var q1={maxPatternBytes:512,maxWildcards:8},lK=new Set(["[","]","(",")","{","}","+","?","|"]);function mc(e,t=q1){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>t.maxPatternBytes||!Number.isSafeInteger(t.maxWildcards)||t.maxWildcards<0)return Ps();let n=e.startsWith("^"),r=e.endsWith("$")&&!cK(e,e.length-1),i=n?1:0,o=r?e.length-1:e.length;if(i>=o)return Ps();let s=[""],a=0,l=!1;for(let c=i;c<o;c+=1){let u=e[c];if(l){s[s.length-1]+=u,l=!1;continue}if(u==="\\"){l=!0;continue}if(u==="*"){if(s[s.length-1]===""&&s.length>1)continue;if(a+=1,a>t.maxWildcards)return Ps();s.push("");continue}if(lK.has(u)||u==="^"||u==="$"||u.charCodeAt(0)<32||u.charCodeAt(0)===127)return Ps();s[s.length-1]+=u}return l||s.every(c=>c.length===0)?Ps():{valid:!0,anchoredStart:n,anchoredEnd:r,segments:s,wildcardCount:a}}function V1(e,t,n=q1){let r=mc(t,n);if(!r.valid)return{matched:!1,reasonCode:"unsafe_pattern"};let{segments:i,anchoredStart:o,anchoredEnd:s,wildcardCount:a}=r;if(a===0){let c=i[0];return o&&s?{matched:e===c}:o?{matched:e.startsWith(c)}:s?{matched:e.endsWith(c)}:{matched:e.includes(c)}}let l=0;for(let c=0;c<i.length;c+=1){let u=i[c];if(u.length===0)continue;let d=c===0,p=c===i.length-1;if(d&&o){if(!e.startsWith(u))return{matched:!1};l=u.length;continue}if(p&&s)return{matched:e.length-u.length>=l&&e.endsWith(u)};let m=e.indexOf(u,l);if(m<0)return{matched:!1};l=m+u.length}return{matched:!0}}function cK(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r-=1)n+=1;return n%2===1}function Ps(){return{valid:!1,reasonCode:"unsafe_pattern"}}var ui=Object.freeze({schemaVersion:"skills-layer.eval.resource-policy.v1",maxPackBytes:256*1024,maxNestingDepth:16,maxObjectKeys:4096,maxCases:64,maxAssertions:512,maxPatternBytes:512,maxPatternWildcards:8,maxPathBytes:512,maxFiles:256,maxFileBytes:1024*1024,maxScannedBytes:8*1024*1024,maxOpaqueFileBytes:20*1024*1024,maxOpaqueBytes:20*1024*1024,maxJsonDepth:32,maxJsonKeys:4096,maxDurationMs:5e3,maxResultBytes:256*1024});function ef(e,t=ui){let n=H1(e,{maxBytes:t.maxPackBytes,maxDepth:t.maxNestingDepth,maxKeys:t.maxObjectKeys,rootPath:"$"});if(!n.valid)return n;if(!Uk(e))return bt("invalid_pack","eval-pack-invalid","$","Eval pack must be an object");let r=e.cases;if(Array.isArray(r)&&r.length>t.maxCases)return bt("resource_limit","eval-pack-case-limit","$.cases","Eval case count exceeds the checked resource policy.");let i=0;if(Array.isArray(r))for(let o=0;o<r.length;o+=1){let s=r[o];if(!(!Uk(s)||!Array.isArray(s.assertions))){if(i+=s.assertions.length,i>t.maxAssertions)return bt("resource_limit","eval-pack-assertion-limit",`$.cases[${o}].assertions`,"Eval assertion count exceeds the checked resource policy.");for(let a=0;a<s.assertions.length;a+=1){let l=s.assertions[a];if(!Uk(l))continue;let c=`$.cases[${o}].assertions[${a}]`;if(l.type==="regex_match"&&!mc(l.pattern,{maxPatternBytes:t.maxPatternBytes,maxWildcards:t.maxPatternWildcards}).valid)return bt("unsafe_pattern","eval-pack-unsafe-pattern",`${c}.pattern`,"Eval pattern is outside the bounded literal/glob language.");if(l.path!==void 0&&!K1(l.path,t.maxPathBytes))return bt("invalid_pack","eval-pack-target-path-invalid",`${c}.path`,"Eval target must be a bounded portable relative path.")}}}return{valid:!0,outcome:"valid",issues:[]}}function tf(e,t=ui){if(!Array.isArray(e)||e.length>t.maxFiles)return bt("resource_limit","eval-file-count-limit","$files","Eval file count exceeds the checked resource policy.");let n=0,r=0,i=new Set;for(let o=0;o<e.length;o+=1){let s=e[o];if(!s||!K1(s.path,t.maxPathBytes)||i.has(G1(s.path)))return bt("invalid_pack","eval-file-path-invalid",`$files[${o}].path`,"Eval file paths must be unique bounded portable relative paths.");i.add(G1(s.path));let a;try{a=cs(s)}catch{return bt("invalid_pack","eval-file-content-invalid",`$files[${o}]`,"Eval file content must use one canonical byte representation.")}if(uK(s)){if(a>t.maxOpaqueFileBytes)return bt("resource_limit","eval-opaque-file-byte-limit",`$files[${o}]`,"Eval opaque asset exceeds the per-file byte limit.");if(r+=a,r>t.maxOpaqueBytes)return bt("resource_limit","eval-opaque-byte-limit","$files","Eval opaque asset bytes exceed the cumulative byte limit.")}else{if(a>t.maxFileBytes)return bt("resource_limit","eval-file-byte-limit",`$files[${o}]`,"Eval target file exceeds the per-file byte limit.");if(n+=a,n>t.maxScannedBytes)return bt("resource_limit","eval-scan-byte-limit","$files","Eval target bytes exceed the cumulative scan limit.")}}return{valid:!0,outcome:"valid",issues:[]}}function zk(e,t=ui){return H1(e,{maxBytes:t.maxFileBytes,maxDepth:t.maxJsonDepth,maxKeys:t.maxJsonKeys,rootPath:"$json"})}function H1(e,t){let n=new WeakSet,r=[{value:e,depth:0,path:t.rootPath}],i=0,o=0;for(;r.length>0;){let s=r.pop();if(s.depth>t.maxDepth)return bt("resource_limit","eval-nesting-limit",s.path,"Eval input exceeds the nesting-depth limit.");if(typeof s.value=="string")i+=Buffer.byteLength(s.value,"utf8");else if(typeof s.value=="number"||typeof s.value=="boolean")i+=String(s.value).length;else if(s.value===null)i+=4;else if(typeof s.value=="object"){if(n.has(s.value))return bt("invalid_pack","eval-cycle-invalid",s.path,"Eval input must be acyclic JSON data.");if(n.add(s.value),Array.isArray(s.value)){o+=s.value.length;for(let a=s.value.length-1;a>=0;a-=1)r.push({value:s.value[a],depth:s.depth+1,path:`${s.path}[${a}]`})}else for(let[a,l]of Object.entries(s.value))o+=1,i+=Buffer.byteLength(a,"utf8"),r.push({value:l,depth:s.depth+1,path:`${s.path}.${a}`})}else if(s.value!==void 0)return bt("invalid_pack","eval-json-type-invalid",s.path,"Eval input must contain JSON-compatible values only.");if(o>t.maxKeys||i>t.maxBytes)return bt("resource_limit","eval-byte-or-key-limit",s.path,"Eval input exceeds the checked byte or key limit.")}return{valid:!0,outcome:"valid",issues:[]}}function K1(e,t){return typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>t||e.includes("\\")||e.includes("\0")||e.startsWith("/")||/^[A-Za-z]:/u.test(e)?!1:e.split("/").every(r=>r.length>0&&r!=="."&&r!=="..")}function G1(e){return e.normalize("NFC").toLowerCase()}function uK(e){return typeof e.contentBase64=="string"&&typeof e.content!="string"}function Uk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bt(e,t,n,r){return{valid:!1,outcome:e,issues:[{code:t,path:n,message:r}]}}function W1(e={}){let t=e.maxScannedBytes??ui.maxScannedBytes;if(!Number.isSafeInteger(t)||t<0)throw new Error("Eval scan budget must be a non-negative safe integer.");return{maxScannedBytes:t,scannedBytes:0}}function rf(e,t){switch(e.type){case"file_exists":return qk(t.files,no(e.path))?As("file_exists"):yn("file_missing");case"json_valid":return dK(e,t);case"section_exists":return pK(e,t);case"regex_match":return fK(e,t);case"schema_match":return mK(e,t);case"artifact_valid":return gK(e,t);case"max_duration_ms":return tn("runner_unavailable");case"command_exit":return tn("runner_unavailable");default:return tn("assertion_type_unsupported")}}function dK(e,t){let n=qk(t.files,no(e.path));if(!n)return yn("file_missing");let r=gc(n,t);if(!r.ok)return tn(r.reasonCode);try{let i=JSON.parse(r.content);return zk(i).valid?As("json_valid"):tn("resource_limit")}catch{return yn("json_invalid")}}function pK(e,t){let n=no(e.target);if(!n)return yn("section_target_missing");for(let r of t.files){let i=gc(r,t);if(!i.ok){if(i.reasonCode==="opaque_asset_not_text")continue;return tn(i.reasonCode)}if(i.content.split(/\r?\n/u).some(o=>hK(o,n)))return As("section_exists")}return yn("section_missing")}function fK(e,t){let n=no(e.pattern);if(!n)return yn("regex_missing");if(!mc(n).valid)return tn("unsafe_pattern");let r=no(e.path),i=r?t.files.filter(s=>nf(s.path)===nf(r)):t.files,o=!1;for(let s of i){let a=gc(s,t);if(!a.ok){if(a.reasonCode==="opaque_asset_not_text"){o=!0;continue}return tn(a.reasonCode)}if(V1(a.content,n).matched)return As("regex_matched")}return r&&o?tn("opaque_asset_not_text"):yn("regex_not_matched")}function mK(e,t){let n=qk(t.files,no(e.path));if(!n)return yn("file_missing");let r=gc(n,t);if(!r.ok)return tn(r.reasonCode);let i;try{i=JSON.parse(r.content)}catch{return yn("json_invalid")}return zk(i).valid?yK(i)?(Array.isArray(e.requiredKeys)?e.requiredKeys.map(String):[]).every(s=>Object.prototype.hasOwnProperty.call(i,s))?As("schema_matched"):yn("schema_required_key_missing"):yn("schema_target_not_object"):tn("resource_limit")}function gK(e,t){let n=tf(t.files);if(!n.valid)return tn(n.outcome);for(let r of t.files){let i=gc(r,t);if(!i.ok&&i.reasonCode!=="opaque_asset_not_text")return tn(i.reasonCode)}return ct(t.files)===no(e.artifactDigest)?As("artifact_digest_matched"):yn("artifact_digest_mismatch")}function qk(e,t){if(!t)return;let n=nf(t);return e.find(r=>nf(r.path)===n)}function no(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function nf(e){return e.replaceAll("\\","/").replace(/^\.\//u,"")}function gc(e,t){if(typeof e.contentBase64=="string"&&typeof e.content!="string")return{ok:!1,reasonCode:"opaque_asset_not_text"};let n=e.content??"",r=Buffer.byteLength(n,"utf8");if(r>ui.maxFileBytes)return{ok:!1,reasonCode:"resource_limit"};if(t.scanBudget){if(t.scanBudget.scannedBytes+r>t.scanBudget.maxScannedBytes)return{ok:!1,reasonCode:"resource_limit"};t.scanBudget.scannedBytes+=r}return{ok:!0,content:n}}function hK(e,t){let n=e.trimStart(),r=0;for(;n[r]==="#";)r+=1;return r===0||n[r]!==" "?!1:n.slice(r+1).trim().localeCompare(t.trim(),void 0,{sensitivity:"accent"})===0}function yK(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function As(e){return{status:"passed",reasonCode:e}}function yn(e){return{status:"failed",reasonCode:e}}function tn(e){return{status:"skipped",reasonCode:e}}import{createHash as vK}from"node:crypto";var kK=["submitted","inferred","submitted_plus_inferred"],wK=["starter","reviewed","verified"],bK=["file_exists","json_valid","schema_match","section_exists","regex_match","command_exit","artifact_valid","max_duration_ms"],_K=new Set(kK),SK=new Set(wK),xK=new Set(bK);function sf(e){let t=ef(e);if(!t.valid)return{valid:!1,issues:t.issues};let n=[],r=e;return r.schemaVersion!=="skills-layer.eval.pack.v1"&&n.push(vn("eval-pack-schema-invalid","$.schemaVersion","Eval pack schemaVersion is unsupported")),(typeof r.artifactDigest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(r.artifactDigest))&&n.push(vn("eval-pack-artifact-digest-invalid","$.artifactDigest","Eval pack must target a sha256 artifact digest")),(typeof r.origin!="string"||!_K.has(r.origin))&&n.push(vn("eval-pack-origin-invalid","$.origin","Eval pack origin is not canonical")),(typeof r.confidence!="string"||!SK.has(r.confidence))&&n.push(vn("eval-pack-confidence-invalid","$.confidence","Eval pack confidence is not canonical")),typeof r.creatorReviewed!="boolean"&&n.push(vn("eval-pack-review-invalid","$.creatorReviewed","Eval pack must state whether the creator reviewed it")),(!of(r.redaction)||r.redaction.mode!=="content_free")&&n.push(vn("eval-pack-redaction-invalid","$.redaction.mode","Eval pack must use content_free redaction by default")),!Array.isArray(r.cases)||r.cases.length===0?n.push(vn("eval-pack-cases-invalid","$.cases","Eval pack must include at least one case")):CK(r.cases,n),{valid:n.length===0,issues:n}}function Rs(e){return`sha256:${vK("sha256").update(IK(e)).digest("hex")}`}function CK(e,t){let n=new Set;e.forEach((r,i)=>{let o=`$.cases[${i}]`;if(!of(r)){t.push(vn("eval-pack-case-invalid",o,"Eval case must be an object"));return}if(typeof r.id!="string"||r.id.trim().length===0?t.push(vn("eval-pack-case-id-invalid",`${o}.id`,"Eval case id is required")):n.has(r.id)?t.push(vn("eval-pack-case-id-duplicate",`${o}.id`,"Eval case ids must be unique")):n.add(r.id),!Array.isArray(r.assertions)||r.assertions.length===0){t.push(vn("eval-pack-assertions-invalid",`${o}.assertions`,"Eval case must include assertions"));return}r.assertions.forEach((s,a)=>{let l=`${o}.assertions[${a}]`;(!of(s)||typeof s.type!="string"||!xK.has(s.type))&&t.push(vn("eval-pack-assertion-type-invalid",`${l}.type`,"Eval assertion type is not supported"))})})}function IK(e){return JSON.stringify(Vk(e))}function Vk(e){return Array.isArray(e)?e.map(Vk).sort(PK):of(e)?Object.fromEntries(Object.entries(e).filter(([t])=>t!=="evalPackDigest").sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Vk(n)])):e}function PK(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))}function of(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vn(e,t,n){return{code:e,path:t,message:n}}function J1(e){let t=e.assertionsPassed+e.assertionsFailed,n={coverageRatio:Z1(e.evaluatedCapabilities,e.declaredCapabilities),passRate:t===0?0:Z1(e.assertionsPassed,t),freshnessFactor:RK(e),evidenceConfidence:e.evidenceConfidenceOverride===void 0?AK(e):af(hc(e.evidenceConfidenceOverride)),baselineDelta:hc(Math.max(0,e.baselineDelta??0)),telemetrySignal:hc(e.aggregationThresholdMet?e.telemetrySignal??0:0)},r=af(n.coverageRatio*.25+n.passRate*.25+n.freshnessFactor*.15+n.evidenceConfidence*.2+n.baselineDelta*.05+n.telemetrySignal*.1);return{components:n,overallScore:r,effectiveScorePercent:$K(r*100),assertionsFailed:e.assertionsFailed,executedAssertions:t,aggregationThresholdMet:e.aggregationThresholdMet}}function Y1(e){return e.executedAssertions===0&&e.components.coverageRatio===0?"unknown":e.components.freshnessFactor===0?"stale":e.assertionsFailed>0&&e.components.passRate<.8?"failing":e.overallScore>=.8&&e.components.coverageRatio>=.8&&e.components.passRate>=.9&&e.components.evidenceConfidence>=.7?"strong":e.aggregationThresholdMet&&e.components.telemetrySignal>=.7?"telemetry-backed":"limited"}function AK(e){let t=e.origin==="submitted"?.65:e.origin==="submitted_plus_inferred"?.55:.25,n=e.creatorReviewed?.15:0,r=Math.min(e.runCount*.03,.15),i=Math.min(new Set(e.runnerTypes).size*.04,.1),o=e.aggregationThresholdMet?.1:0;return af(hc(t+n+r+i+o))}function RK(e){if(e.freshnessPolicy==="never")return 1;if(!e.generatedAt||!e.now)return 0;let t=Date.parse(e.generatedAt),n=Date.parse(e.now);if(!Number.isFinite(t)||!Number.isFinite(n)||n<t)return 0;let r=EK(e.freshnessPolicy);return n-t<=r?1:0}function EK(e){return e==="3_months"?2160*60*60*1e3:e==="6_months"?4392*60*60*1e3:365*24*60*60*1e3}function Z1(e,t){return t<=0?0:af(hc(e/t))}function hc(e){return Math.max(0,Math.min(1,e))}function af(e){return Math.round(e*1e4)/1e4}function $K(e){return Math.round(e*10)/10}var Gk=["passed","failed","not_run","generated_only","policy_skipped","runner_unavailable"],zfe=new Set(Gk);function Es(e){return{schemaVersion:"skills-layer.eval.summary.v1",status:e.status,skillSlug:e.skillSlug,version:e.version,...e.generationId?{generationId:e.generationId}:{},artifactDigest:e.artifactDigest,...e.evalPackDigest?{evalPackDigest:e.evalPackDigest}:{},...e.runnerVersion?{runnerVersion:e.runnerVersion}:{},generatedAt:e.generatedAt,...e.counts?{counts:e.counts}:{},redaction:{mode:"content_free",rawContentIncluded:!1}}}function DK(e){return e==="limited"||e==="unknown"?"attention_needed":"ready"}function Hk(e){let t=ct(e),n=Ty(e),r=e.map(l=>$n(l.path,e)).filter(l=>l.type==="evidence"),i=TK(e),o=i?"submitted":"inferred",s=J1({declaredCapabilities:4,evaluatedCapabilities:i?2:1,assertionsPassed:0,assertionsFailed:0,assertionsSkipped:0,origin:o,creatorReviewed:!1,runCount:0,runnerTypes:["dry"],aggregationThresholdMet:!1,freshnessPolicy:"never"}),a=Y1(s);return{schemaVersion:"skills-layer.eval.readiness.v1",status:DK(a),label:a,artifactDigest:t,origin:o,confidence:"starter",creatorReviewed:!1,runtimeFileCount:n.length,evidenceFileCount:r.length,excludedEvidencePaths:r.map(l=>l.path),score:{overallScore:s.overallScore,effectiveScorePercent:s.effectiveScorePercent,components:s.components},summaryEnvelope:{requiredOnSubmit:!0,statuses:[...Gk]},nextAction:"creator.submit",nextStep:"Add representative Eval cases, preview trigger behavior, then submit with the mandatory redacted Eval summary.",improvements:["Add representative should-trigger, should-not-trigger, and paraphrase cases.","Review the generated assertions and cover every advertised core capability."],recommendedCommands:["skills-layer preview-trigger <path>","skills-layer validate <path>"]}}function TK(e){return e.map(t=>$n(t.path,e)).some(t=>t.type==="evidence"&&(t.relativePath.startsWith("evals/")||t.relativePath.endsWith(".eval.json")||t.relativePath.endsWith(".eval.yaml")))}function X1(e){if(e.activationState!=="inactive_staging")return lf("invalid_pack","inactive_staging_required","$activationState","Static Eval must run before activation in an inactive staging tree.");let t=ef(e.pack);if(!t.valid)return{outcome:t.outcome,reasonCode:t.issues[0]?.code??t.outcome,issues:t.issues};let n=sf(e.pack);if(!n.valid)return{outcome:"invalid_pack",reasonCode:n.issues[0]?.code??"invalid_pack",issues:n.issues};let r=tf(e.files);if(!r.valid)return{outcome:r.outcome,reasonCode:r.issues[0]?.code??r.outcome,issues:r.issues};let i=e.pack,o=ct(e.files);if(i.artifactDigest!==o)return lf("invalid_pack","artifact_digest_mismatch","$.artifactDigest","Eval pack is not bound to the staged runtime artifact.");let s=W1(),a=i.cases.map(d=>({id:d.id,assertions:d.assertions.map(p=>rf(p,{files:e.files,scanBudget:s}))})),l=a.flatMap(d=>d.assertions).find(d=>d.reasonCode==="resource_limit"||d.reasonCode==="unsafe_pattern");if(l){let d=l.reasonCode;return lf(d,d,"$cases","Static Eval stopped at the checked security boundary.")}let c=OK(a),u=Es({status:c.failed>0?"failed":c.passed>0?"passed":"not_run",skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:o,evalPackDigest:Rs(e.pack),generatedAt:e.generatedAt,runnerVersion:e.runnerVersion,counts:{cases:a.length,assertions:c.total,passed:c.passed,failed:c.failed,skipped:c.skipped}});return Buffer.byteLength(JSON.stringify(u),"utf8")>ui.maxResultBytes?lf("resource_limit","eval-result-byte-limit","$result","Static Eval result exceeds the checked byte limit."):{outcome:"completed",result:{summary:u,cases:a}}}function OK(e){let t={total:0,passed:0,failed:0,skipped:0};for(let n of e)for(let r of n.assertions)t.total+=1,r.status==="passed"?t.passed+=1:r.status==="failed"?t.failed+=1:t.skipped+=1;return t}function lf(e,t,n,r){return{outcome:e,reasonCode:t,issues:[{code:t,path:n,message:r}]}}var S={};Vn(S,{$brand:()=>cf,$input:()=>p_,$output:()=>d_,NEVER:()=>Kk,TimePrecision:()=>h_,ZodAny:()=>ox,ZodArray:()=>cx,ZodBase64:()=>jm,ZodBase64URL:()=>Nm,ZodBigInt:()=>sa,ZodBigIntFormat:()=>Mm,ZodBoolean:()=>oa,ZodCIDRv4:()=>Om,ZodCIDRv6:()=>Lm,ZodCUID:()=>Pm,ZodCUID2:()=>Am,ZodCatch:()=>$x,ZodCodec:()=>Wm,ZodCustom:()=>Wc,ZodCustomStringFormat:()=>ra,ZodDate:()=>qc,ZodDefault:()=>Cx,ZodDiscriminatedUnion:()=>dx,ZodE164:()=>Fm,ZodEmail:()=>xm,ZodEmoji:()=>Cm,ZodEnum:()=>ta,ZodError:()=>lJ,ZodExactOptional:()=>_x,ZodFile:()=>wx,ZodFirstPartyTypeKind:()=>qx,ZodFunction:()=>Mx,ZodGUID:()=>Fc,ZodIPv4:()=>Dm,ZodIPv6:()=>Tm,ZodISODate:()=>vm,ZodISODateTime:()=>ym,ZodISODuration:()=>wm,ZodISOTime:()=>km,ZodIntersection:()=>px,ZodIssueCode:()=>uJ,ZodJWT:()=>Bm,ZodKSUID:()=>$m,ZodLazy:()=>Nx,ZodLiteral:()=>kx,ZodMAC:()=>XS,ZodMap:()=>yx,ZodNaN:()=>Tx,ZodNanoID:()=>Im,ZodNever:()=>ax,ZodNonOptional:()=>Hm,ZodNull:()=>rx,ZodNullable:()=>xx,ZodNumber:()=>ia,ZodNumberFormat:()=>uo,ZodObject:()=>Gc,ZodOptional:()=>Gm,ZodPipe:()=>Km,ZodPrefault:()=>Px,ZodPromise:()=>Bx,ZodReadonly:()=>Ox,ZodRealError:()=>Kt,ZodRecord:()=>Kc,ZodSet:()=>vx,ZodString:()=>na,ZodStringFormat:()=>Se,ZodSuccess:()=>Ex,ZodSymbol:()=>tx,ZodTemplateLiteral:()=>jx,ZodTransform:()=>bx,ZodTuple:()=>mx,ZodType:()=>se,ZodULID:()=>Rm,ZodURL:()=>zc,ZodUUID:()=>tr,ZodUndefined:()=>nx,ZodUnion:()=>Hc,ZodUnknown:()=>sx,ZodVoid:()=>lx,ZodXID:()=>Em,ZodXor:()=>ux,_ZodString:()=>Sm,_default:()=>Ix,_function:()=>$L,any:()=>cL,array:()=>Vc,base64:()=>HO,base64url:()=>KO,bigint:()=>iL,boolean:()=>ex,catch:()=>Dx,check:()=>DL,cidrv4:()=>VO,cidrv6:()=>GO,clone:()=>It,codec:()=>AL,coerce:()=>Vx,config:()=>je,core:()=>Rr,cuid:()=>jO,cuid2:()=>NO,custom:()=>TL,date:()=>dL,decode:()=>GS,decodeAsync:()=>KS,describe:()=>OL,discriminatedUnion:()=>yL,e164:()=>WO,email:()=>IO,emoji:()=>OO,encode:()=>VS,encodeAsync:()=>HS,endsWith:()=>Gs,enum:()=>qm,exactOptional:()=>Sx,file:()=>xL,flattenError:()=>Cc,float32:()=>eL,float64:()=>tL,formatError:()=>Ic,fromJSONSchema:()=>UL,function:()=>$L,getErrorMap:()=>pJ,globalRegistry:()=>pt,gt:()=>Qn,gte:()=>Pt,guid:()=>PO,hash:()=>QO,hex:()=>XO,hostname:()=>YO,httpUrl:()=>TO,includes:()=>qs,instanceof:()=>jL,int:()=>_m,int32:()=>nL,int64:()=>oL,intersection:()=>fx,ipv4:()=>UO,ipv6:()=>qO,iso:()=>ea,json:()=>FL,jwt:()=>ZO,keyof:()=>pL,ksuid:()=>MO,lazy:()=>Fx,length:()=>lo,literal:()=>SL,locales:()=>Oc,looseObject:()=>gL,looseRecord:()=>kL,lowercase:()=>Us,lt:()=>Xn,lte:()=>rn,mac:()=>zO,map:()=>wL,maxLength:()=>ao,maxSize:()=>yi,meta:()=>LL,mime:()=>Hs,minLength:()=>Ar,minSize:()=>er,multipleOf:()=>hi,nan:()=>PL,nanoid:()=>LO,nativeEnum:()=>_L,negative:()=>am,never:()=>Um,nonnegative:()=>cm,nonoptional:()=>Rx,nonpositive:()=>lm,normalize:()=>Ks,null:()=>ix,nullable:()=>Mc,nullish:()=>CL,number:()=>QS,object:()=>fL,optional:()=>Bc,overwrite:()=>jn,parse:()=>MS,parseAsync:()=>US,partialRecord:()=>vL,pipe:()=>Uc,positive:()=>sm,prefault:()=>Ax,preprocess:()=>BL,prettifyError:()=>ow,promise:()=>EL,property:()=>um,readonly:()=>Lx,record:()=>hx,refine:()=>Ux,regex:()=>Ms,regexes:()=>wn,registry:()=>Bf,safeDecode:()=>ZS,safeDecodeAsync:()=>YS,safeEncode:()=>WS,safeEncodeAsync:()=>JS,safeParse:()=>zS,safeParseAsync:()=>qS,set:()=>bL,setErrorMap:()=>dJ,size:()=>so,slugify:()=>Ys,startsWith:()=>Vs,strictObject:()=>mL,string:()=>bm,stringFormat:()=>JO,stringbool:()=>NL,success:()=>IL,superRefine:()=>zx,symbol:()=>aL,templateLiteral:()=>RL,toJSONSchema:()=>mm,toLowerCase:()=>Zs,toUpperCase:()=>Js,transform:()=>Vm,treeifyError:()=>iw,trim:()=>Ws,tuple:()=>gx,uint32:()=>rL,uint64:()=>sL,ulid:()=>FO,undefined:()=>lL,union:()=>zm,unknown:()=>co,uppercase:()=>zs,url:()=>DO,util:()=>M,uuid:()=>AO,uuidv4:()=>RO,uuidv6:()=>EO,uuidv7:()=>$O,void:()=>uL,xid:()=>BO,xor:()=>hL});var Rr={};Vn(Rr,{$ZodAny:()=>Tb,$ZodArray:()=>Fb,$ZodAsyncError:()=>Ln,$ZodBase64:()=>Sb,$ZodBase64URL:()=>xb,$ZodBigInt:()=>Df,$ZodBigIntFormat:()=>Rb,$ZodBoolean:()=>Ec,$ZodCIDRv4:()=>wb,$ZodCIDRv6:()=>bb,$ZodCUID:()=>lb,$ZodCUID2:()=>cb,$ZodCatch:()=>n_,$ZodCheck:()=>Ie,$ZodCheckBigIntFormat:()=>Fw,$ZodCheckEndsWith:()=>Jw,$ZodCheckGreaterThan:()=>Cf,$ZodCheckIncludes:()=>Ww,$ZodCheckLengthEquals:()=>Vw,$ZodCheckLessThan:()=>xf,$ZodCheckLowerCase:()=>Hw,$ZodCheckMaxLength:()=>zw,$ZodCheckMaxSize:()=>Bw,$ZodCheckMimeType:()=>Xw,$ZodCheckMinLength:()=>qw,$ZodCheckMinSize:()=>Mw,$ZodCheckMultipleOf:()=>jw,$ZodCheckNumberFormat:()=>Nw,$ZodCheckOverwrite:()=>Qw,$ZodCheckProperty:()=>Yw,$ZodCheckRegex:()=>Gw,$ZodCheckSizeEquals:()=>Uw,$ZodCheckStartsWith:()=>Zw,$ZodCheckStringFormat:()=>Fs,$ZodCheckUpperCase:()=>Kw,$ZodCodec:()=>Dc,$ZodCustom:()=>u_,$ZodCustomStringFormat:()=>Pb,$ZodDate:()=>Nb,$ZodDefault:()=>Xb,$ZodDiscriminatedUnion:()=>Ub,$ZodE164:()=>Cb,$ZodEmail:()=>ib,$ZodEmoji:()=>sb,$ZodEncodeError:()=>di,$ZodEnum:()=>Hb,$ZodError:()=>xc,$ZodExactOptional:()=>Jb,$ZodFile:()=>Wb,$ZodFunction:()=>a_,$ZodGUID:()=>nb,$ZodIPv4:()=>yb,$ZodIPv6:()=>vb,$ZodISODate:()=>mb,$ZodISODateTime:()=>fb,$ZodISODuration:()=>hb,$ZodISOTime:()=>gb,$ZodIntersection:()=>zb,$ZodJWT:()=>Ib,$ZodKSUID:()=>pb,$ZodLazy:()=>c_,$ZodLiteral:()=>Kb,$ZodMAC:()=>kb,$ZodMap:()=>Vb,$ZodNaN:()=>r_,$ZodNanoID:()=>ab,$ZodNever:()=>Lb,$ZodNonOptional:()=>e_,$ZodNull:()=>Db,$ZodNullable:()=>Yb,$ZodNumber:()=>$f,$ZodNumberFormat:()=>Ab,$ZodObject:()=>CT,$ZodObjectJIT:()=>Bb,$ZodOptional:()=>Of,$ZodPipe:()=>i_,$ZodPrefault:()=>Qb,$ZodPromise:()=>l_,$ZodReadonly:()=>o_,$ZodRealError:()=>Ht,$ZodRecord:()=>qb,$ZodRegistry:()=>Ff,$ZodSet:()=>Gb,$ZodString:()=>oo,$ZodStringFormat:()=>_e,$ZodSuccess:()=>t_,$ZodSymbol:()=>Eb,$ZodTemplateLiteral:()=>s_,$ZodTransform:()=>Zb,$ZodTuple:()=>Tf,$ZodType:()=>oe,$ZodULID:()=>ub,$ZodURL:()=>ob,$ZodUUID:()=>rb,$ZodUndefined:()=>$b,$ZodUnion:()=>$c,$ZodUnknown:()=>Ob,$ZodVoid:()=>jb,$ZodXID:()=>db,$ZodXor:()=>Mb,$brand:()=>cf,$constructor:()=>I,$input:()=>p_,$output:()=>d_,Doc:()=>Rc,JSONSchema:()=>xO,JSONSchemaGenerator:()=>gm,NEVER:()=>Kk,TimePrecision:()=>h_,_any:()=>N_,_array:()=>V_,_base64:()=>nm,_base64url:()=>rm,_bigint:()=>E_,_boolean:()=>A_,_catch:()=>eJ,_check:()=>SO,_cidrv4:()=>em,_cidrv6:()=>tm,_coercedBigint:()=>$_,_coercedBoolean:()=>R_,_coercedDate:()=>z_,_coercedNumber:()=>__,_coercedString:()=>m_,_cuid:()=>Kf,_cuid2:()=>Wf,_custom:()=>H_,_date:()=>U_,_decode:()=>gf,_decodeAsync:()=>yf,_default:()=>YZ,_discriminatedUnion:()=>BZ,_e164:()=>im,_email:()=>Mf,_emoji:()=>Gf,_encode:()=>mf,_encodeAsync:()=>hf,_endsWith:()=>Gs,_enum:()=>GZ,_file:()=>G_,_float32:()=>x_,_float64:()=>C_,_gt:()=>Qn,_gte:()=>Pt,_guid:()=>Lc,_includes:()=>qs,_int:()=>S_,_int32:()=>I_,_int64:()=>D_,_intersection:()=>MZ,_ipv4:()=>Xf,_ipv6:()=>Qf,_isoDate:()=>v_,_isoDateTime:()=>y_,_isoDuration:()=>w_,_isoTime:()=>k_,_jwt:()=>om,_ksuid:()=>Yf,_lazy:()=>iJ,_length:()=>lo,_literal:()=>KZ,_lowercase:()=>Us,_lt:()=>Xn,_lte:()=>rn,_mac:()=>g_,_map:()=>qZ,_max:()=>rn,_maxLength:()=>ao,_maxSize:()=>yi,_mime:()=>Hs,_min:()=>Pt,_minLength:()=>Ar,_minSize:()=>er,_multipleOf:()=>hi,_nan:()=>q_,_nanoid:()=>Hf,_nativeEnum:()=>HZ,_negative:()=>am,_never:()=>B_,_nonnegative:()=>cm,_nonoptional:()=>XZ,_nonpositive:()=>lm,_normalize:()=>Ks,_null:()=>j_,_nullable:()=>JZ,_number:()=>b_,_optional:()=>ZZ,_overwrite:()=>jn,_parse:()=>Os,_parseAsync:()=>Ls,_pipe:()=>tJ,_positive:()=>sm,_promise:()=>oJ,_property:()=>um,_readonly:()=>nJ,_record:()=>zZ,_refine:()=>K_,_regex:()=>Ms,_safeDecode:()=>kf,_safeDecodeAsync:()=>bf,_safeEncode:()=>vf,_safeEncodeAsync:()=>wf,_safeParse:()=>js,_safeParseAsync:()=>Ns,_set:()=>VZ,_size:()=>so,_slugify:()=>Ys,_startsWith:()=>Vs,_string:()=>f_,_stringFormat:()=>Xs,_stringbool:()=>Y_,_success:()=>QZ,_superRefine:()=>W_,_symbol:()=>O_,_templateLiteral:()=>rJ,_toLowerCase:()=>Zs,_toUpperCase:()=>Js,_transform:()=>WZ,_trim:()=>Ws,_tuple:()=>UZ,_uint32:()=>P_,_uint64:()=>T_,_ulid:()=>Zf,_undefined:()=>L_,_union:()=>NZ,_unknown:()=>F_,_uppercase:()=>zs,_url:()=>jc,_uuid:()=>Uf,_uuidv4:()=>zf,_uuidv6:()=>qf,_uuidv7:()=>Vf,_void:()=>M_,_xid:()=>Jf,_xor:()=>FZ,clone:()=>It,config:()=>je,createStandardJSONSchemaMethod:()=>Qs,createToJSONSchemaMethod:()=>X_,decode:()=>lW,decodeAsync:()=>uW,describe:()=>Z_,encode:()=>aW,encodeAsync:()=>cW,extractDefs:()=>ki,finalize:()=>wi,flattenError:()=>Cc,formatError:()=>Ic,globalConfig:()=>yc,globalRegistry:()=>pt,initializeContext:()=>vi,isValidBase64:()=>_b,isValidBase64URL:()=>bT,isValidJWT:()=>_T,locales:()=>Oc,meta:()=>J_,parse:()=>pf,parseAsync:()=>ff,prettifyError:()=>ow,process:()=>be,regexes:()=>wn,registry:()=>Bf,safeDecode:()=>pW,safeDecodeAsync:()=>mW,safeEncode:()=>dW,safeEncodeAsync:()=>fW,safeParse:()=>sw,safeParseAsync:()=>aw,toDotPath:()=>rT,toJSONSchema:()=>mm,treeifyError:()=>iw,util:()=>M,version:()=>eb});var Kk=Object.freeze({status:"aborted"});function I(e,t,n){function r(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let c=s.prototype,u=Object.keys(c);for(let d=0;d<u.length;d++){let p=u[d];p in a||(a[p]=c[p].bind(a))}}let i=n?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(a){var l;let c=n?.Parent?new o:this;r(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var cf=Symbol("zod_brand"),Ln=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},di=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}},yc={};function je(e){return e&&Object.assign(yc,e),yc}var M={};Vn(M,{BIGINT_FORMAT_RANGES:()=>rw,Class:()=>Zk,NUMBER_FORMAT_RANGES:()=>nw,aborted:()=>gi,allowsEval:()=>Xk,assert:()=>BK,assertEqual:()=>LK,assertIs:()=>NK,assertNever:()=>FK,assertNotEqual:()=>jK,assignProp:()=>fi,base64ToUint8Array:()=>eT,base64urlToUint8Array:()=>nW,cached:()=>Ds,captureStackTrace:()=>df,cleanEnum:()=>tW,cleanRegex:()=>wc,clone:()=>It,cloneDef:()=>UK,createTransparentProxy:()=>KK,defineLazy:()=>de,esc:()=>uf,escapeRegex:()=>kn,extend:()=>JK,finalizeIssue:()=>Gt,floatSafeRemainder:()=>Jk,getElementAtPath:()=>zK,getEnumValues:()=>kc,getLengthableOrigin:()=>Sc,getParsedType:()=>HK,getSizableOrigin:()=>_c,hexToUint8Array:()=>iW,isObject:()=>ro,isPlainObject:()=>mi,issue:()=>Ts,joinValues:()=>$,jsonStringifyReplacer:()=>$s,merge:()=>XK,mergeDefs:()=>Pr,normalizeParams:()=>U,nullish:()=>pi,numKeys:()=>GK,objectClone:()=>MK,omit:()=>ZK,optionalKeys:()=>tw,parsedType:()=>B,partial:()=>QK,pick:()=>WK,prefixIssues:()=>nn,primitiveTypes:()=>ew,promiseAllObject:()=>qK,propertyKeyTypes:()=>bc,randomString:()=>VK,required:()=>eW,safeExtend:()=>YK,shallowClone:()=>Qk,slugify:()=>Yk,stringifyPrimitive:()=>F,uint8ArrayToBase64:()=>tT,uint8ArrayToBase64url:()=>rW,uint8ArrayToHex:()=>oW,unwrapMessage:()=>vc});function LK(e){return e}function jK(e){return e}function NK(e){}function FK(e){throw new Error("Unexpected value in exhaustive check")}function BK(e){}function kc(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,i])=>t.indexOf(+r)===-1).map(([r,i])=>i)}function $(e,t="|"){return e.map(n=>F(n)).join(t)}function $s(e,t){return typeof t=="bigint"?t.toString():t}function Ds(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function pi(e){return e==null}function wc(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Jk(e,t){let n=(e.toString().split(".")[1]||"").length,r=t.toString(),i=(r.split(".")[1]||"").length;if(i===0&&/\d?e-\d?/.test(r)){let l=r.match(/\d?e-(\d?)/);l?.[1]&&(i=Number.parseInt(l[1]))}let o=n>i?n:i,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}var Q1=Symbol("evaluating");function de(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Q1)return r===void 0&&(r=Q1,r=n()),r},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function MK(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function fi(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Pr(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function UK(e){return Pr(e._zod.def)}function zK(e,t){return t?t.reduce((n,r)=>n?.[r],e):e}function qK(e){let t=Object.keys(e),n=t.map(r=>e[r]);return Promise.all(n).then(r=>{let i={};for(let o=0;o<t.length;o++)i[t[o]]=r[o];return i})}function VK(e=10){let t="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<e;r++)n+=t[Math.floor(Math.random()*t.length)];return n}function uf(e){return JSON.stringify(e)}function Yk(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var df="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ro(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Xk=Ds(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function mi(e){if(ro(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(ro(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Qk(e){return mi(e)?{...e}:Array.isArray(e)?[...e]:e}function GK(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}var HK=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},bc=new Set(["string","number","symbol"]),ew=new Set(["string","number","bigint","boolean","symbol","undefined"]);function kn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function It(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function U(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function KK(e){let t;return new Proxy({},{get(n,r,i){return t??(t=e()),Reflect.get(t,r,i)},set(n,r,i,o){return t??(t=e()),Reflect.set(t,r,i,o)},has(n,r){return t??(t=e()),Reflect.has(t,r)},deleteProperty(n,r){return t??(t=e()),Reflect.deleteProperty(t,r)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,r){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)},defineProperty(n,r,i){return t??(t=e()),Reflect.defineProperty(t,r,i)}})}function F(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function tw(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var nw={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},rw={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function WK(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let o=Pr(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=n.shape[a])}return fi(this,"shape",s),s},checks:[]});return It(e,o)}function ZK(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let o=Pr(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in n.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return fi(this,"shape",s),s},checks:[]});return It(e,o)}function JK(e,t){if(!mi(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let i=Pr(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return fi(this,"shape",o),o}});return It(e,i)}function YK(e,t){if(!mi(t))throw new Error("Invalid input to safeExtend: expected a plain object");let n=Pr(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t};return fi(this,"shape",r),r}});return It(e,n)}function XK(e,t){let n=Pr(e._zod.def,{get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return fi(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return It(e,n)}function QK(e,t,n){let i=t._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Pr(t._zod.def,{get shape(){let a=t._zod.def.shape,l={...a};if(n)for(let c in n){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);n[c]&&(l[c]=e?new e({type:"optional",innerType:a[c]}):a[c])}else for(let c in a)l[c]=e?new e({type:"optional",innerType:a[c]}):a[c];return fi(this,"shape",l),l},checks:[]});return It(t,s)}function eW(e,t,n){let r=Pr(t._zod.def,{get shape(){let i=t._zod.def.shape,o={...i};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new e({type:"nonoptional",innerType:i[s]}))}else for(let s in i)o[s]=new e({type:"nonoptional",innerType:i[s]});return fi(this,"shape",o),o}});return It(t,r)}function gi(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function nn(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function vc(e){return typeof e=="string"?e:e?.message}function Gt(e,t,n){let r={...e,path:e.path??[]};if(!e.message){let i=vc(e.inst?._zod.def?.error?.(e))??vc(t?.error?.(e))??vc(n.customError?.(e))??vc(n.localeError?.(e))??"Invalid input";r.message=i}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function _c(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Sc(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function B(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function Ts(...e){let[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}function tW(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function eT(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function tT(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function nW(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return eT(t+n)}function rW(e){return tT(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function iW(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function oW(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Zk=class{constructor(...t){}};var nT=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,$s,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},xc=I("$ZodError",nT),Ht=I("$ZodError",nT,{Parent:Error});function Cc(e,t=n=>n.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ic(e,t=n=>n.message){let n={_errors:[]},r=i=>{for(let o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>r({issues:s}));else if(o.code==="invalid_key")r({issues:o.issues});else if(o.code==="invalid_element")r({issues:o.issues});else if(o.path.length===0)n._errors.push(t(o));else{let s=n,a=0;for(;a<o.path.length;){let l=o.path[a];a===o.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(t(o))):s[l]=s[l]||{_errors:[]},s=s[l],a++}}};return r(e),n}function iw(e,t=n=>n.message){let n={errors:[]},r=(i,o=[])=>{var s,a;for(let l of i.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(c=>r({issues:c},l.path));else if(l.code==="invalid_key")r({issues:l.issues},l.path);else if(l.code==="invalid_element")r({issues:l.issues},l.path);else{let c=[...o,...l.path];if(c.length===0){n.errors.push(t(l));continue}let u=n,d=0;for(;d<c.length;){let p=c[d],m=d===c.length-1;typeof p=="string"?(u.properties??(u.properties={}),(s=u.properties)[p]??(s[p]={errors:[]}),u=u.properties[p]):(u.items??(u.items=[]),(a=u.items)[p]??(a[p]={errors:[]}),u=u.items[p]),m&&u.errors.push(t(l)),d++}}};return r(e),n}function rT(e){let t=[],n=e.map(r=>typeof r=="object"?r.key:r);for(let r of n)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function ow(e){let t=[],n=[...e.issues].sort((r,i)=>(r.path??[]).length-(i.path??[]).length);for(let r of n)t.push(`\u2716 ${r.message}`),r.path?.length&&t.push(` \u2192 at ${rT(r.path)}`);return t.join(`
|
|
755
755
|
`)}var Os=e=>(t,n,r,i)=>{let o=r?Object.assign(r,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Ln;if(s.issues.length){let a=new(i?.Err??e)(s.issues.map(l=>Gt(l,o,je())));throw df(a,i?.callee),a}return s.value},pf=Os(Ht),Ls=e=>async(t,n,r,i)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??e)(s.issues.map(l=>Gt(l,o,je())));throw df(a,i?.callee),a}return s.value},ff=Ls(Ht),js=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Ln;return o.issues.length?{success:!1,error:new(e??xc)(o.issues.map(s=>Gt(s,i,je())))}:{success:!0,data:o.value}},sw=js(Ht),Ns=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>Gt(s,i,je())))}:{success:!0,data:o.value}},aw=Ns(Ht),mf=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Os(e)(t,n,i)},aW=mf(Ht),gf=e=>(t,n,r)=>Os(e)(t,n,r),lW=gf(Ht),hf=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ls(e)(t,n,i)},cW=hf(Ht),yf=e=>async(t,n,r)=>Ls(e)(t,n,r),uW=yf(Ht),vf=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return js(e)(t,n,i)},dW=vf(Ht),kf=e=>(t,n,r)=>js(e)(t,n,r),pW=kf(Ht),wf=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return Ns(e)(t,n,i)},fW=wf(Ht),bf=e=>async(t,n,r)=>Ns(e)(t,n,r),mW=bf(Ht);var wn={};Vn(wn,{base64:()=>Sw,base64url:()=>_f,bigint:()=>Rw,boolean:()=>$w,browserEmail:()=>_W,cidrv4:()=>bw,cidrv6:()=>_w,cuid:()=>lw,cuid2:()=>cw,date:()=>Cw,datetime:()=>Pw,domain:()=>CW,duration:()=>mw,e164:()=>xw,email:()=>hw,emoji:()=>yw,extendedDuration:()=>gW,guid:()=>gw,hex:()=>IW,hostname:()=>xW,html5Email:()=>kW,idnEmail:()=>bW,integer:()=>Ew,ipv4:()=>vw,ipv6:()=>kw,ksuid:()=>pw,lowercase:()=>Ow,mac:()=>ww,md5_base64:()=>AW,md5_base64url:()=>RW,md5_hex:()=>PW,nanoid:()=>fw,null:()=>Dw,number:()=>Sf,rfc5322Email:()=>wW,sha1_base64:()=>$W,sha1_base64url:()=>DW,sha1_hex:()=>EW,sha256_base64:()=>OW,sha256_base64url:()=>LW,sha256_hex:()=>TW,sha384_base64:()=>NW,sha384_base64url:()=>FW,sha384_hex:()=>jW,sha512_base64:()=>MW,sha512_base64url:()=>UW,sha512_hex:()=>BW,string:()=>Aw,time:()=>Iw,ulid:()=>uw,undefined:()=>Tw,unicodeEmail:()=>iT,uppercase:()=>Lw,uuid:()=>io,uuid4:()=>hW,uuid6:()=>yW,uuid7:()=>vW,xid:()=>dw});var lw=/^[cC][^\s-]{8,}$/,cw=/^[0-9a-z]+$/,uw=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,dw=/^[0-9a-vA-V]{20}$/,pw=/^[A-Za-z0-9]{27}$/,fw=/^[a-zA-Z0-9_-]{21}$/,mw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,gW=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,gw=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,io=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,hW=io(4),yW=io(6),vW=io(7),hw=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,kW=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,wW=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,iT=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,bW=iT,_W=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,SW="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function yw(){return new RegExp(SW,"u")}var vw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,kw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ww=e=>{let t=kn(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},bw=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,_w=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Sw=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_f=/^[A-Za-z0-9_-]*$/,xW=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,CW=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,xw=/^\+[1-9]\d{6,14}$/,oT="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Cw=new RegExp(`^${oT}$`);function sT(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Iw(e){return new RegExp(`^${sT(e)}$`)}function Pw(e){let t=sT({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${t}(?:${n.join("|")})`;return new RegExp(`^${oT}T(?:${r})$`)}var Aw=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Rw=/^-?\d+n?$/,Ew=/^-?\d+$/,Sf=/^-?\d+(?:\.\d+)?$/,$w=/^(?:true|false)$/i,Dw=/^null$/i;var Tw=/^undefined$/i;var Ow=/^[^A-Z]*$/,Lw=/^[^a-z]*$/,IW=/^[0-9a-fA-F]*$/;function Pc(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function Ac(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var PW=/^[0-9a-fA-F]{32}$/,AW=Pc(22,"=="),RW=Ac(22),EW=/^[0-9a-fA-F]{40}$/,$W=Pc(27,"="),DW=Ac(27),TW=/^[0-9a-fA-F]{64}$/,OW=Pc(43,"="),LW=Ac(43),jW=/^[0-9a-fA-F]{96}$/,NW=Pc(64,""),FW=Ac(64),BW=/^[0-9a-fA-F]{128}$/,MW=Pc(86,"=="),UW=Ac(86);var Ie=I("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),lT={number:"number",bigint:"bigint",object:"date"},xf=I("$ZodCheckLessThan",(e,t)=>{Ie.init(e,t);let n=lT[typeof t.value];e._zod.onattach.push(r=>{let i=r._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Cf=I("$ZodCheckGreaterThan",(e,t)=>{Ie.init(e,t);let n=lT[typeof t.value];e._zod.onattach.push(r=>{let i=r._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),jw=I("$ZodCheckMultipleOf",(e,t)=>{Ie.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):Jk(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Nw=I("$ZodCheckNumberFormat",(e,t)=>{Ie.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[i,o]=nw[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=i,a.maximum=o,n&&(a.pattern=Ew)}),e._zod.check=s=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Fw=I("$ZodCheckBigIntFormat",(e,t)=>{Ie.init(e,t);let[n,r]=rw[t.format];e._zod.onattach.push(i=>{let o=i._zod.bag;o.format=t.format,o.minimum=n,o.maximum=r}),e._zod.check=i=>{let o=i.value;o<n&&i.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),o>r&&i.issues.push({origin:"bigint",input:o,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),Bw=I("$ZodCheckMaxSize",(e,t)=>{var n;Ie.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!pi(i)&&i.size!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let i=r.value;i.size<=t.maximum||r.issues.push({origin:_c(i),code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Mw=I("$ZodCheckMinSize",(e,t)=>{var n;Ie.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!pi(i)&&i.size!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let i=r.value;i.size>=t.minimum||r.issues.push({origin:_c(i),code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Uw=I("$ZodCheckSizeEquals",(e,t)=>{var n;Ie.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!pi(i)&&i.size!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag;i.minimum=t.size,i.maximum=t.size,i.size=t.size}),e._zod.check=r=>{let i=r.value,o=i.size;if(o===t.size)return;let s=o>t.size;r.issues.push({origin:_c(i),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),zw=I("$ZodCheckMaxLength",(e,t)=>{var n;Ie.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!pi(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let i=r.value;if(i.length<=t.maximum)return;let s=Sc(i);r.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),qw=I("$ZodCheckMinLength",(e,t)=>{var n;Ie.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!pi(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let i=r.value;if(i.length>=t.minimum)return;let s=Sc(i);r.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Vw=I("$ZodCheckLengthEquals",(e,t)=>{var n;Ie.init(e,t),(n=e._zod.def).when??(n.when=r=>{let i=r.value;return!pi(i)&&i.length!==void 0}),e._zod.onattach.push(r=>{let i=r._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=r=>{let i=r.value,o=i.length;if(o===t.length)return;let s=Sc(i),a=o>t.length;r.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Fs=I("$ZodCheckStringFormat",(e,t)=>{var n,r;Ie.init(e,t),e._zod.onattach.push(i=>{let o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Gw=I("$ZodCheckRegex",(e,t)=>{Fs.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Hw=I("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ow),Fs.init(e,t)}),Kw=I("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Lw),Fs.init(e,t)}),Ww=I("$ZodCheckIncludes",(e,t)=>{Ie.init(e,t);let n=kn(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(i=>{let o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),Zw=I("$ZodCheckStartsWith",(e,t)=>{Ie.init(e,t);let n=new RegExp(`^${kn(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Jw=I("$ZodCheckEndsWith",(e,t)=>{Ie.init(e,t);let n=new RegExp(`.*${kn(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{let i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}});function aT(e,t,n){e.issues.length&&t.issues.push(...nn(n,e.issues))}var Yw=I("$ZodCheckProperty",(e,t)=>{Ie.init(e,t),e._zod.check=n=>{let r=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(r instanceof Promise)return r.then(i=>aT(i,n,t.property));aT(r,n,t.property)}}),Xw=I("$ZodCheckMimeType",(e,t)=>{Ie.init(e,t);let n=new Set(t.mime);e._zod.onattach.push(r=>{r._zod.bag.mime=t.mime}),e._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:t.mime,input:r.value.type,inst:e,continue:!t.abort})}}),Qw=I("$ZodCheckOverwrite",(e,t)=>{Ie.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});var Rc=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let r=t.split(`
|
|
756
756
|
`).filter(s=>s),i=Math.min(...r.map(s=>s.length-s.trimStart().length)),o=r.map(s=>s.slice(i)).map(s=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let t=Function,n=this?.args,i=[...(this?.content??[""]).map(o=>` ${o}`)];return new t(...n,i.join(`
|
|
757
757
|
`))}};var eb={major:4,minor:3,patch:6};var oe=I("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=eb;let r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let i of r)for(let o of i._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(s,a,l)=>{let c=gi(s),u;for(let d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&l?.async===!1)throw new Ln;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==p&&(c||(c=gi(s,p)))});else{if(s.issues.length===p)continue;c||(c=gi(s,p))}}return u?u.then(()=>s):s},o=(s,a,l)=>{if(gi(s))return s.aborted=!0,s;let c=i(a,r,l);if(c instanceof Promise){if(l.async===!1)throw new Ln;return c.then(u=>e._zod.parse(u,l))}return e._zod.parse(c,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let c=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(u=>o(u,s,a)):o(c,s,a)}let l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new Ln;return l.then(c=>i(c,r,a))}return i(l,r,a)}}de(e,"~standard",()=>({validate:i=>{try{let o=sw(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return aw(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),oo=I("$ZodString",(e,t)=>{oe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Aw(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),_e=I("$ZodStringFormat",(e,t)=>{Fs.init(e,t),oo.init(e,t)}),nb=I("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=gw),_e.init(e,t)}),rb=I("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=io(r))}else t.pattern??(t.pattern=io());_e.init(e,t)}),ib=I("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=hw),_e.init(e,t)}),ob=I("$ZodURL",(e,t)=>{_e.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),sb=I("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=yw()),_e.init(e,t)}),ab=I("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=fw),_e.init(e,t)}),lb=I("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=lw),_e.init(e,t)}),cb=I("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=cw),_e.init(e,t)}),ub=I("$ZodULID",(e,t)=>{t.pattern??(t.pattern=uw),_e.init(e,t)}),db=I("$ZodXID",(e,t)=>{t.pattern??(t.pattern=dw),_e.init(e,t)}),pb=I("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=pw),_e.init(e,t)}),fb=I("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Pw(t)),_e.init(e,t)}),mb=I("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Cw),_e.init(e,t)}),gb=I("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Iw(t)),_e.init(e,t)}),hb=I("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=mw),_e.init(e,t)}),yb=I("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=vw),_e.init(e,t),e._zod.bag.format="ipv4"}),vb=I("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=kw),_e.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),kb=I("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=ww(t.delimiter)),_e.init(e,t),e._zod.bag.format="mac"}),wb=I("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=bw),_e.init(e,t)}),bb=I("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=_w),_e.init(e,t),e._zod.check=n=>{let r=n.value.split("/");try{if(r.length!==2)throw new Error;let[i,o]=r;if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function _b(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Sb=I("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Sw),_e.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{_b(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function bT(e){if(!_f.test(e))return!1;let t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return _b(n)}var xb=I("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=_f),_e.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{bT(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Cb=I("$ZodE164",(e,t)=>{t.pattern??(t.pattern=xw),_e.init(e,t)});function _T(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var Ib=I("$ZodJWT",(e,t)=>{_e.init(e,t),e._zod.check=n=>{_T(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Pb=I("$ZodCustomStringFormat",(e,t)=>{_e.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),$f=I("$ZodNumber",(e,t)=>{oe.init(e,t),e._zod.pattern=e._zod.bag.pattern??Sf,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;let o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Ab=I("$ZodNumberFormat",(e,t)=>{Nw.init(e,t),$f.init(e,t)}),Ec=I("$ZodBoolean",(e,t)=>{oe.init(e,t),e._zod.pattern=$w,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),Df=I("$ZodBigInt",(e,t)=>{oe.init(e,t),e._zod.pattern=Rw,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),Rb=I("$ZodBigIntFormat",(e,t)=>{Fw.init(e,t),Df.init(e,t)}),Eb=I("$ZodSymbol",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;return typeof i=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:i,inst:e}),n}}),$b=I("$ZodUndefined",(e,t)=>{oe.init(e,t),e._zod.pattern=Tw,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,r)=>{let i=n.value;return typeof i>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:e}),n}}),Db=I("$ZodNull",(e,t)=>{oe.init(e,t),e._zod.pattern=Dw,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{let i=n.value;return i===null||n.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),n}}),Tb=I("$ZodAny",(e,t)=>{oe.init(e,t),e._zod.parse=n=>n}),Ob=I("$ZodUnknown",(e,t)=>{oe.init(e,t),e._zod.parse=n=>n}),Lb=I("$ZodNever",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),jb=I("$ZodVoid",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;return typeof i>"u"||n.issues.push({expected:"void",code:"invalid_type",input:i,inst:e}),n}}),Nb=I("$ZodDate",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}let i=n.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),n}});function uT(e,t,n){e.issues.length&&t.issues.push(...nn(n,e.issues)),t.value[n]=e.value}var Fb=I("$ZodArray",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],l=t.element._zod.run({value:a,issues:[]},r);l instanceof Promise?o.push(l.then(c=>uT(c,n,s))):uT(l,n,s)}return o.length?Promise.all(o).then(()=>n):n}});function Ef(e,t,n,r,i){if(e.issues.length){if(i&&!(n in r))return;t.issues.push(...nn(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function ST(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=tw(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function xT(e,t,n,r,i,o){let s=[],a=i.keySet,l=i.catchall._zod,c=l.def.type,u=l.optout==="optional";for(let d in t){if(a.has(d))continue;if(c==="never"){s.push(d);continue}let p=l.run({value:t[d],issues:[]},r);p instanceof Promise?e.push(p.then(m=>Ef(m,n,d,t,u))):Ef(p,n,d,t,u)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}var CT=I("$ZodObject",(e,t)=>{if(oe.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let r=Ds(()=>ST(t));de(e._zod,"propValues",()=>{let a=t.shape,l={};for(let c in a){let u=a[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(let d of u.values)l[c].add(d)}}return l});let i=ro,o=t.catchall,s;e._zod.parse=(a,l)=>{s??(s=r.value);let c=a.value;if(!i(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),a;a.value={};let u=[],d=s.shape;for(let p of s.keys){let m=d[p],h=m._zod.optout==="optional",g=m._zod.run({value:c[p],issues:[]},l);g instanceof Promise?u.push(g.then(y=>Ef(y,a,p,c,h))):Ef(g,a,p,c,h)}return o?xT(u,c,a,l,r.value,e):u.length?Promise.all(u).then(()=>a):a}}),Bb=I("$ZodObjectJIT",(e,t)=>{CT.init(e,t);let n=e._zod.parse,r=Ds(()=>ST(t)),i=p=>{let m=new Rc(["shape","payload","ctx"]),h=r.value,g=w=>{let _=uf(w);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};m.write("const input = payload.value;");let y=Object.create(null),v=0;for(let w of h.keys)y[w]=`key_${v++}`;m.write("const newResult = {};");for(let w of h.keys){let _=y[w],C=uf(w),O=p[w]?._zod?.optout==="optional";m.write(`const ${_} = ${g(w)};`),O?m.write(`
|
|
@@ -791,16 +791,16 @@ ${o}`}function Vp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}func
|
|
|
791
791
|
`)}m.write("payload.value = newResult;"),m.write("return payload;");let b=m.compile();return(w,_)=>b(p,w,_)},o,s=ro,a=!yc.jitless,c=a&&Xk.value,u=t.catchall,d;e._zod.parse=(p,m)=>{d??(d=r.value);let h=p.value;return s(h)?a&&c&&m?.async===!1&&m.jitless!==!0?(o||(o=i(t.shape)),p=o(p,m),u?xT([],h,p,m,d,e):p):n(p,m):(p.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),p)}});function dT(e,t,n,r){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let i=e.filter(o=>!gi(o));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Gt(s,r,je())))}),t)}var $c=I("$ZodUnion",(e,t)=>{oe.init(e,t),de(e._zod,"optin",()=>t.options.some(i=>i._zod.optin==="optional")?"optional":void 0),de(e._zod,"optout",()=>t.options.some(i=>i._zod.optout==="optional")?"optional":void 0),de(e._zod,"values",()=>{if(t.options.every(i=>i._zod.values))return new Set(t.options.flatMap(i=>Array.from(i._zod.values)))}),de(e._zod,"pattern",()=>{if(t.options.every(i=>i._zod.pattern)){let i=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${i.map(o=>wc(o.source)).join("|")})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return r(i,o);let s=!1,a=[];for(let l of t.options){let c=l._zod.run({value:i.value,issues:[]},o);if(c instanceof Promise)a.push(c),s=!0;else{if(c.issues.length===0)return c;a.push(c)}}return s?Promise.all(a).then(l=>dT(l,i,e,o)):dT(a,i,e,o)}});function pT(e,t,n,r){let i=e.filter(o=>o.issues.length===0);return i.length===1?(t.value=i[0].value,t):(i.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(s=>Gt(s,r,je())))}):t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:[],inclusive:!1}),t)}var Mb=I("$ZodXor",(e,t)=>{$c.init(e,t),t.inclusive=!1;let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return r(i,o);let s=!1,a=[];for(let l of t.options){let c=l._zod.run({value:i.value,issues:[]},o);c instanceof Promise?(a.push(c),s=!0):a.push(c)}return s?Promise.all(a).then(l=>pT(l,i,e,o)):pT(a,i,e,o)}}),Ub=I("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,$c.init(e,t);let n=e._zod.parse;de(e._zod,"propValues",()=>{let i={};for(let o of t.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(o)}"`);for(let[a,l]of Object.entries(s)){i[a]||(i[a]=new Set);for(let c of l)i[a].add(c)}}return i});let r=Ds(()=>{let i=t.options,o=new Map;for(let s of i){let a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let l of a){if(o.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);o.set(l,s)}}return o});e._zod.parse=(i,o)=>{let s=i.value;if(!ro(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;let a=r.value.get(s?.[t.discriminator]);return a?a._zod.run(i,o):t.unionFallback?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),i)}}),zb=I("$ZodIntersection",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{let i=n.value,o=t.left._zod.run({value:i,issues:[]},r),s=t.right._zod.run({value:i,issues:[]},r);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([l,c])=>fT(n,l,c)):fT(n,o,s)}});function tb(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(mi(e)&&mi(t)){let n=Object.keys(t),r=Object.keys(e).filter(o=>n.indexOf(o)!==-1),i={...e,...t};for(let o of r){let s=tb(e[o],t[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};i[o]=s.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],o=t[r],s=tb(i,o);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function fT(e,t,n){let r=new Map,i;for(let a of t.issues)if(a.code==="unrecognized_keys"){i??(i=a);for(let l of a.keys)r.has(l)||r.set(l,{}),r.get(l).l=!0}else e.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let l of a.keys)r.has(l)||r.set(l,{}),r.get(l).r=!0;else e.issues.push(a);let o=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(o.length&&i&&e.issues.push({...i,keys:o}),gi(e))return e;let s=tb(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var Tf=I("$ZodTuple",(e,t)=>{oe.init(e,t);let n=t.items;e._zod.parse=(r,i)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),r;r.value=[];let s=[],a=[...n].reverse().findIndex(u=>u._zod.optin!=="optional"),l=a===-1?0:n.length-a;if(!t.rest){let u=o.length>n.length,d=o.length<l-1;if(u||d)return r.issues.push({...u?{code:"too_big",maximum:n.length,inclusive:!0}:{code:"too_small",minimum:n.length},input:o,inst:e,origin:"array"}),r}let c=-1;for(let u of n){if(c++,c>=o.length&&c>=l)continue;let d=u._zod.run({value:o[c],issues:[]},i);d instanceof Promise?s.push(d.then(p=>If(p,r,c))):If(d,r,c)}if(t.rest){let u=o.slice(n.length);for(let d of u){c++;let p=t.rest._zod.run({value:d,issues:[]},i);p instanceof Promise?s.push(p.then(m=>If(m,r,c))):If(p,r,c)}}return s.length?Promise.all(s).then(()=>r):r}});function If(e,t,n){e.issues.length&&t.issues.push(...nn(n,e.issues)),t.value[n]=e.value}var qb=I("$ZodRecord",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!mi(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let o=[],s=t.keyType._zod.values;if(s){n.value={};let a=new Set;for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);let u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&n.issues.push(...nn(c,d.issues)),n.value[c]=d.value})):(u.issues.length&&n.issues.push(...nn(c,u.issues)),n.value[c]=u.value)}let l;for(let c in i)a.has(c)||(l=l??[],l.push(c));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l})}else{n.value={};for(let a of Reflect.ownKeys(i)){if(a==="__proto__")continue;let l=t.keyType._zod.run({value:a,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Sf.test(a)&&l.issues.length){let d=t.keyType._zod.run({value:Number(a),issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(l=d)}if(l.issues.length){t.mode==="loose"?n.value[a]=i[a]:n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(d=>Gt(d,r,je())),input:a,path:[a],inst:e});continue}let u=t.valueType._zod.run({value:i[a],issues:[]},r);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&n.issues.push(...nn(a,d.issues)),n.value[l.value]=d.value})):(u.issues.length&&n.issues.push(...nn(a,u.issues)),n.value[l.value]=u.value)}}return o.length?Promise.all(o).then(()=>n):n}}),Vb=I("$ZodMap",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!(i instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:i,inst:e}),n;let o=[];n.value=new Map;for(let[s,a]of i){let l=t.keyType._zod.run({value:s,issues:[]},r),c=t.valueType._zod.run({value:a,issues:[]},r);l instanceof Promise||c instanceof Promise?o.push(Promise.all([l,c]).then(([u,d])=>{mT(u,d,n,s,i,e,r)})):mT(l,c,n,s,i,e,r)}return o.length?Promise.all(o).then(()=>n):n}});function mT(e,t,n,r,i,o,s){e.issues.length&&(bc.has(typeof r)?n.issues.push(...nn(r,e.issues)):n.issues.push({code:"invalid_key",origin:"map",input:i,inst:o,issues:e.issues.map(a=>Gt(a,s,je()))})),t.issues.length&&(bc.has(typeof r)?n.issues.push(...nn(r,t.issues)):n.issues.push({origin:"map",code:"invalid_element",input:i,inst:o,key:r,issues:t.issues.map(a=>Gt(a,s,je()))})),n.value.set(e.value,t.value)}var Gb=I("$ZodSet",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!(i instanceof Set))return n.issues.push({input:i,inst:e,expected:"set",code:"invalid_type"}),n;let o=[];n.value=new Set;for(let s of i){let a=t.valueType._zod.run({value:s,issues:[]},r);a instanceof Promise?o.push(a.then(l=>gT(l,n))):gT(a,n)}return o.length?Promise.all(o).then(()=>n):n}});function gT(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}var Hb=I("$ZodEnum",(e,t)=>{oe.init(e,t);let n=kc(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>bc.has(typeof i)).map(i=>typeof i=="string"?kn(i):i.toString()).join("|")})$`),e._zod.parse=(i,o)=>{let s=i.value;return r.has(s)||i.issues.push({code:"invalid_value",values:n,input:s,inst:e}),i}}),Kb=I("$ZodLiteral",(e,t)=>{if(oe.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?kn(r):r?kn(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,i)=>{let o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),Wb=I("$ZodFile",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;return i instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:i,inst:e}),n}}),Zb=I("$ZodTransform",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new di(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(n.value=s,n));if(i instanceof Promise)throw new Ln;return n.value=i,n}});function hT(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var Of=I("$ZodOptional",(e,t)=>{oe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",de(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),de(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${wc(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>hT(o,n.value)):hT(i,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),Jb=I("$ZodExactOptional",(e,t)=>{Of.init(e,t),de(e._zod,"values",()=>t.innerType._zod.values),de(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),Yb=I("$ZodNullable",(e,t)=>{oe.init(e,t),de(e._zod,"optin",()=>t.innerType._zod.optin),de(e._zod,"optout",()=>t.innerType._zod.optout),de(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${wc(n.source)}|null)$`):void 0}),de(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),Xb=I("$ZodDefault",(e,t)=>{oe.init(e,t),e._zod.optin="optional",de(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>yT(o,t)):yT(i,t)}});function yT(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Qb=I("$ZodPrefault",(e,t)=>{oe.init(e,t),e._zod.optin="optional",de(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),e_=I("$ZodNonOptional",(e,t)=>{oe.init(e,t),de(e._zod,"values",()=>{let n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>vT(o,e)):vT(i,e)}});function vT(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var t_=I("$ZodSuccess",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new di("ZodSuccess");let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>(n.value=o.issues.length===0,n)):(n.value=i.issues.length===0,n)}}),n_=I("$ZodCatch",(e,t)=>{oe.init(e,t),de(e._zod,"optin",()=>t.innerType._zod.optin),de(e._zod,"optout",()=>t.innerType._zod.optout),de(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(s=>Gt(s,r,je()))},input:n.value}),n.issues=[]),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(o=>Gt(o,r,je()))},input:n.value}),n.issues=[]),n)}}),r_=I("$ZodNaN",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:e,expected:"nan",code:"invalid_type"}),n)}),i_=I("$ZodPipe",(e,t)=>{oe.init(e,t),de(e._zod,"values",()=>t.in._zod.values),de(e._zod,"optin",()=>t.in._zod.optin),de(e._zod,"optout",()=>t.out._zod.optout),de(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let o=t.out._zod.run(n,r);return o instanceof Promise?o.then(s=>Pf(s,t.in,r)):Pf(o,t.in,r)}let i=t.in._zod.run(n,r);return i instanceof Promise?i.then(o=>Pf(o,t.out,r)):Pf(i,t.out,r)}});function Pf(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var Dc=I("$ZodCodec",(e,t)=>{oe.init(e,t),de(e._zod,"values",()=>t.in._zod.values),de(e._zod,"optin",()=>t.in._zod.optin),de(e._zod,"optout",()=>t.out._zod.optout),de(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if((r.direction||"forward")==="forward"){let o=t.in._zod.run(n,r);return o instanceof Promise?o.then(s=>Af(s,t,r)):Af(o,t,r)}else{let o=t.out._zod.run(n,r);return o instanceof Promise?o.then(s=>Af(s,t,r)):Af(o,t,r)}}});function Af(e,t,n){if(e.issues.length)return e.aborted=!0,e;if((n.direction||"forward")==="forward"){let i=t.transform(e.value,e);return i instanceof Promise?i.then(o=>Rf(e,o,t.out,n)):Rf(e,i,t.out,n)}else{let i=t.reverseTransform(e.value,e);return i instanceof Promise?i.then(o=>Rf(e,o,t.in,n)):Rf(e,i,t.in,n)}}function Rf(e,t,n,r){return e.issues.length?(e.aborted=!0,e):n._zod.run({value:t,issues:e.issues},r)}var o_=I("$ZodReadonly",(e,t)=>{oe.init(e,t),de(e._zod,"propValues",()=>t.innerType._zod.propValues),de(e._zod,"values",()=>t.innerType._zod.values),de(e._zod,"optin",()=>t.innerType?._zod?.optin),de(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(kT):kT(i)}});function kT(e){return e.value=Object.freeze(e.value),e}var s_=I("$ZodTemplateLiteral",(e,t)=>{oe.init(e,t);let n=[];for(let r of t.parts)if(typeof r=="object"&&r!==null){if(!r._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);let i=r._zod.pattern instanceof RegExp?r._zod.pattern.source:r._zod.pattern;if(!i)throw new Error(`Invalid template literal part: ${r._zod.traits}`);let o=i.startsWith("^")?1:0,s=i.endsWith("$")?i.length-1:i.length;n.push(i.slice(o,s))}else if(r===null||ew.has(typeof r))n.push(kn(`${r}`));else throw new Error(`Invalid template literal part: ${r}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(r,i)=>typeof r.value!="string"?(r.issues.push({input:r.value,inst:e,expected:"string",code:"invalid_type"}),r):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),r)}),a_=I("$ZodFunction",(e,t)=>(oe.init(e,t),e._def=t,e._zod.def=t,e.implement=n=>{if(typeof n!="function")throw new Error("implement() must be called with a function");return function(...r){let i=e._def.input?pf(e._def.input,r):r,o=Reflect.apply(n,this,i);return e._def.output?pf(e._def.output,o):o}},e.implementAsync=n=>{if(typeof n!="function")throw new Error("implementAsync() must be called with a function");return async function(...r){let i=e._def.input?await ff(e._def.input,r):r,o=await Reflect.apply(n,this,i);return e._def.output?await ff(e._def.output,o):o}},e._zod.parse=(n,r)=>typeof n.value!="function"?(n.issues.push({code:"invalid_type",expected:"function",input:n.value,inst:e}),n):(e._def.output&&e._def.output._zod.def.type==="promise"?n.value=e.implementAsync(n.value):n.value=e.implement(n.value),n),e.input=(...n)=>{let r=e.constructor;return Array.isArray(n[0])?new r({type:"function",input:new Tf({type:"tuple",items:n[0],rest:n[1]}),output:e._def.output}):new r({type:"function",input:n[0],output:e._def.output})},e.output=n=>{let r=e.constructor;return new r({type:"function",input:e._def.input,output:n})},e)),l_=I("$ZodPromise",(e,t)=>{oe.init(e,t),e._zod.parse=(n,r)=>Promise.resolve(n.value).then(i=>t.innerType._zod.run({value:i,issues:[]},r))}),c_=I("$ZodLazy",(e,t)=>{oe.init(e,t),de(e._zod,"innerType",()=>t.getter()),de(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),de(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),de(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),de(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),u_=I("$ZodCustom",(e,t)=>{Ie.init(e,t),oe.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(o=>wT(o,n,r,e));wT(i,n,r,e)}});function wT(e,t,n,r){if(!e){let i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Ts(i))}}var Oc={};Vn(Oc,{ar:()=>IT,az:()=>PT,be:()=>RT,bg:()=>ET,ca:()=>$T,cs:()=>DT,da:()=>TT,de:()=>OT,en:()=>Lf,eo:()=>LT,es:()=>jT,fa:()=>NT,fi:()=>FT,fr:()=>BT,frCA:()=>MT,he:()=>UT,hu:()=>zT,hy:()=>VT,id:()=>GT,is:()=>HT,it:()=>KT,ja:()=>WT,ka:()=>ZT,kh:()=>JT,km:()=>jf,ko:()=>YT,lt:()=>QT,mk:()=>eO,ms:()=>tO,nl:()=>nO,no:()=>rO,ota:()=>iO,pl:()=>sO,ps:()=>oO,pt:()=>aO,ru:()=>cO,sl:()=>uO,sv:()=>dO,ta:()=>pO,th:()=>fO,tr:()=>mO,ua:()=>gO,uk:()=>Nf,ur:()=>hO,uz:()=>yO,vi:()=>vO,yo:()=>bO,zhCN:()=>kO,zhTW:()=>wO});var qW=()=>{let e={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function t(i){return e[i]??null}let n={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},r={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${i.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${a}`:`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${o}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${a}`}case"invalid_value":return i.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${F(i.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${i.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${o} ${i.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${i.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${o} ${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${i.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${o} ${i.minimum.toString()} ${s.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${i.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${o} ${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${i.prefix}"`:o.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${o.suffix}"`:o.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${o.includes}"`:o.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${o.pattern}`:`${n[o.format]??i.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${i.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${i.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${i.keys.length>1?"\u0629":""}: ${$(i.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${i.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${i.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};function IT(){return{localeError:qW()}}var VW=()=>{let e={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function t(i){return e[i]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${i.expected}, daxil olan ${a}`:`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${o}, daxil olan ${a}`}case"invalid_value":return i.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${F(i.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${i.origin??"d\u0259y\u0259r"} ${o}${i.maximum.toString()} ${s.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${i.origin??"d\u0259y\u0259r"} ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${i.origin} ${o}${i.minimum.toString()} ${s.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${i.origin} ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${o.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:o.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${o.suffix}" il\u0259 bitm\u0259lidir`:o.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${o.includes}" daxil olmal\u0131d\u0131r`:o.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${o.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${n[o.format]??i.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${i.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${i.keys.length>1?"lar":""}: ${$(i.keys,", ")}`;case"invalid_key":return`${i.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${i.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};function PT(){return{localeError:VW()}}function AT(e,t,n,r){let i=Math.abs(e),o=i%10,s=i%100;return s>=11&&s<=19?r:o===1?t:o>=2&&o<=4?n:r}var GW=()=>{let e={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function t(i){return e[i]??null}let n={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},r={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${i.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${a}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${o}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${a}`}case"invalid_value":return i.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${F(i.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);if(s){let a=Number(i.maximum),l=AT(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${o}${i.maximum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);if(s){let a=Number(i.minimum),l=AT(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${o}${i.minimum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${i.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${o.includes}"`:o.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${n[o.format]??i.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${i.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${i.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${$(i.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${i.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${i.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};function RT(){return{localeError:GW()}}var HW=()=>{let e={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function t(i){return e[i]??null}let n={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},r={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${i.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${a}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${o}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${a}`}case"invalid_value":return i.values.length===1?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${F(i.values[0])}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${i.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${o}${i.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${i.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${i.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${o}${i.minimum.toString()} ${s.unit}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${i.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;if(o.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${o.prefix}"`;if(o.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${o.suffix}"`;if(o.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${o.includes}"`;if(o.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${o.pattern}`;let s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";return o.format==="emoji"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),o.format==="datetime"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),o.format==="date"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),o.format==="time"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),o.format==="duration"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),`${s} ${n[o.format]??i.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${i.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${i.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${i.keys.length>1?"\u043E\u0432\u0435":""}: ${$(i.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${i.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${i.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}};function ET(){return{localeError:HW()}}var KW=()=>{let e={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function t(i){return e[i]??null}let n={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Tipus inv\xE0lid: s'esperava instanceof ${i.expected}, s'ha rebut ${a}`:`Tipus inv\xE0lid: s'esperava ${o}, s'ha rebut ${a}`}case"invalid_value":return i.values.length===1?`Valor inv\xE0lid: s'esperava ${F(i.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${$(i.values," o ")}`;case"too_big":{let o=i.inclusive?"com a m\xE0xim":"menys de",s=t(i.origin);return s?`Massa gran: s'esperava que ${i.origin??"el valor"} contingu\xE9s ${o} ${i.maximum.toString()} ${s.unit??"elements"}`:`Massa gran: s'esperava que ${i.origin??"el valor"} fos ${o} ${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?"com a m\xEDnim":"m\xE9s de",s=t(i.origin);return s?`Massa petit: s'esperava que ${i.origin} contingu\xE9s ${o} ${i.minimum.toString()} ${s.unit}`:`Massa petit: s'esperava que ${i.origin} fos ${o} ${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${o.prefix}"`:o.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${o.suffix}"`:o.format==="includes"?`Format inv\xE0lid: ha d'incloure "${o.includes}"`:o.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${o.pattern}`:`Format inv\xE0lid per a ${n[o.format]??i.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${i.divisor}`;case"unrecognized_keys":return`Clau${i.keys.length>1?"s":""} no reconeguda${i.keys.length>1?"s":""}: ${$(i.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${i.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${i.origin}`;default:return"Entrada inv\xE0lida"}}};function $T(){return{localeError:KW()}}var WW=()=>{let e={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function t(i){return e[i]??null}let n={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},r={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${i.expected}, obdr\u017Eeno ${a}`:`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${o}, obdr\u017Eeno ${a}`}case"invalid_value":return i.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${F(i.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${i.origin??"hodnota"} mus\xED m\xEDt ${o}${i.maximum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${i.origin??"hodnota"} mus\xED b\xFDt ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${i.origin??"hodnota"} mus\xED m\xEDt ${o}${i.minimum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${i.origin??"hodnota"} mus\xED b\xFDt ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${o.prefix}"`:o.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${o.suffix}"`:o.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${o.includes}"`:o.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${o.pattern}`:`Neplatn\xFD form\xE1t ${n[o.format]??i.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${i.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${$(i.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${i.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${i.origin}`;default:return"Neplatn\xFD vstup"}}};function DT(){return{localeError:WW()}}var ZW=()=>{let e={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function t(i){return e[i]??null}let n={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkesl\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},r={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Ugyldigt input: forventede instanceof ${i.expected}, fik ${a}`:`Ugyldigt input: forventede ${o}, fik ${a}`}case"invalid_value":return i.values.length===1?`Ugyldig v\xE6rdi: forventede ${F(i.values[0])}`:`Ugyldigt valg: forventede en af f\xF8lgende ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin),a=r[i.origin]??i.origin;return s?`For stor: forventede ${a??"value"} ${s.verb} ${o} ${i.maximum.toString()} ${s.unit??"elementer"}`:`For stor: forventede ${a??"value"} havde ${o} ${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin),a=r[i.origin]??i.origin;return s?`For lille: forventede ${a} ${s.verb} ${o} ${i.minimum.toString()} ${s.unit}`:`For lille: forventede ${a} havde ${o} ${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Ugyldig streng: skal starte med "${o.prefix}"`:o.format==="ends_with"?`Ugyldig streng: skal ende med "${o.suffix}"`:o.format==="includes"?`Ugyldig streng: skal indeholde "${o.includes}"`:o.format==="regex"?`Ugyldig streng: skal matche m\xF8nsteret ${o.pattern}`:`Ugyldig ${n[o.format]??i.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${i.divisor}`;case"unrecognized_keys":return`${i.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${$(i.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${i.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${i.origin}`;default:return"Ugyldigt input"}}};function TT(){return{localeError:ZW()}}var JW=()=>{let e={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function t(i){return e[i]??null}let n={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},r={nan:"NaN",number:"Zahl",array:"Array"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Ung\xFCltige Eingabe: erwartet instanceof ${i.expected}, erhalten ${a}`:`Ung\xFCltige Eingabe: erwartet ${o}, erhalten ${a}`}case"invalid_value":return i.values.length===1?`Ung\xFCltige Eingabe: erwartet ${F(i.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Zu gro\xDF: erwartet, dass ${i.origin??"Wert"} ${o}${i.maximum.toString()} ${s.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${i.origin??"Wert"} ${o}${i.maximum.toString()} ist`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Zu klein: erwartet, dass ${i.origin} ${o}${i.minimum.toString()} ${s.unit} hat`:`Zu klein: erwartet, dass ${i.origin} ${o}${i.minimum.toString()} ist`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Ung\xFCltiger String: muss mit "${o.prefix}" beginnen`:o.format==="ends_with"?`Ung\xFCltiger String: muss mit "${o.suffix}" enden`:o.format==="includes"?`Ung\xFCltiger String: muss "${o.includes}" enthalten`:o.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${o.pattern} entsprechen`:`Ung\xFCltig: ${n[o.format]??i.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${i.divisor} sein`;case"unrecognized_keys":return`${i.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${$(i.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${i.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${i.origin}`;default:return"Ung\xFCltige Eingabe"}}};function OT(){return{localeError:JW()}}var YW=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(i){return e[i]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return`Invalid input: expected ${o}, received ${a}`}case"invalid_value":return i.values.length===1?`Invalid input: expected ${F(i.values[0])}`:`Invalid option: expected one of ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Too big: expected ${i.origin??"value"} to have ${o}${i.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Too small: expected ${i.origin} to have ${o}${i.minimum.toString()} ${s.unit}`:`Too small: expected ${i.origin} to be ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${n[o.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${$(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function Lf(){return{localeError:YW()}}var XW=()=>{let e={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function t(i){return e[i]??null}let n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},r={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Nevalida enigo: atendi\u011Dis instanceof ${i.expected}, ricevi\u011Dis ${a}`:`Nevalida enigo: atendi\u011Dis ${o}, ricevi\u011Dis ${a}`}case"invalid_value":return i.values.length===1?`Nevalida enigo: atendi\u011Dis ${F(i.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Tro granda: atendi\u011Dis ke ${i.origin??"valoro"} havu ${o}${i.maximum.toString()} ${s.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${i.origin??"valoro"} havu ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Tro malgranda: atendi\u011Dis ke ${i.origin} havu ${o}${i.minimum.toString()} ${s.unit}`:`Tro malgranda: atendi\u011Dis ke ${i.origin} estu ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${o.prefix}"`:o.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${o.suffix}"`:o.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${o.includes}"`:o.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${o.pattern}`:`Nevalida ${n[o.format]??i.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${i.divisor}`;case"unrecognized_keys":return`Nekonata${i.keys.length>1?"j":""} \u015Dlosilo${i.keys.length>1?"j":""}: ${$(i.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${i.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${i.origin}`;default:return"Nevalida enigo"}}};function LT(){return{localeError:XW()}}var QW=()=>{let e={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function t(i){return e[i]??null}let n={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Entrada inv\xE1lida: se esperaba instanceof ${i.expected}, recibido ${a}`:`Entrada inv\xE1lida: se esperaba ${o}, recibido ${a}`}case"invalid_value":return i.values.length===1?`Entrada inv\xE1lida: se esperaba ${F(i.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin),a=r[i.origin]??i.origin;return s?`Demasiado grande: se esperaba que ${a??"valor"} tuviera ${o}${i.maximum.toString()} ${s.unit??"elementos"}`:`Demasiado grande: se esperaba que ${a??"valor"} fuera ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin),a=r[i.origin]??i.origin;return s?`Demasiado peque\xF1o: se esperaba que ${a} tuviera ${o}${i.minimum.toString()} ${s.unit}`:`Demasiado peque\xF1o: se esperaba que ${a} fuera ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${o.prefix}"`:o.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${o.suffix}"`:o.format==="includes"?`Cadena inv\xE1lida: debe incluir "${o.includes}"`:o.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${o.pattern}`:`Inv\xE1lido ${n[o.format]??i.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${i.divisor}`;case"unrecognized_keys":return`Llave${i.keys.length>1?"s":""} desconocida${i.keys.length>1?"s":""}: ${$(i.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${r[i.origin]??i.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${r[i.origin]??i.origin}`;default:return"Entrada inv\xE1lida"}}};function jT(){return{localeError:QW()}}var eZ=()=>{let e={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function t(i){return e[i]??null}let n={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},r={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${i.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${a} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`:`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${o} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${a} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":return i.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${F(i.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${$(i.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${i.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${o}${i.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${i.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${o}${i.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${i.origin} \u0628\u0627\u06CC\u062F ${o}${i.minimum.toString()} ${s.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${i.origin} \u0628\u0627\u06CC\u062F ${o}${i.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${o.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:o.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${o.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:o.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${o.includes}" \u0628\u0627\u0634\u062F`:o.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${o.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${n[o.format]??i.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${i.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${i.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${$(i.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${i.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${i.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};function NT(){return{localeError:eZ()}}var tZ=()=>{let e={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function t(i){return e[i]??null}let n={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},r={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Virheellinen tyyppi: odotettiin instanceof ${i.expected}, oli ${a}`:`Virheellinen tyyppi: odotettiin ${o}, oli ${a}`}case"invalid_value":return i.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${F(i.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Liian suuri: ${s.subject} t\xE4ytyy olla ${o}${i.maximum.toString()} ${s.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Liian pieni: ${s.subject} t\xE4ytyy olla ${o}${i.minimum.toString()} ${s.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${o.prefix}"`:o.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${o.suffix}"`:o.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${o.includes}"`:o.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${o.pattern}`:`Virheellinen ${n[o.format]??i.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${i.divisor} monikerta`;case"unrecognized_keys":return`${i.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${$(i.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}};function FT(){return{localeError:tZ()}}var nZ=()=>{let e={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function t(i){return e[i]??null}let n={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},r={nan:"NaN",number:"nombre",array:"tableau"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Entr\xE9e invalide : instanceof ${i.expected} attendu, ${a} re\xE7u`:`Entr\xE9e invalide : ${o} attendu, ${a} re\xE7u`}case"invalid_value":return i.values.length===1?`Entr\xE9e invalide : ${F(i.values[0])} attendu`:`Option invalide : une valeur parmi ${$(i.values,"|")} attendue`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Trop grand : ${i.origin??"valeur"} doit ${s.verb} ${o}${i.maximum.toString()} ${s.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${i.origin??"valeur"} doit \xEAtre ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Trop petit : ${i.origin} doit ${s.verb} ${o}${i.minimum.toString()} ${s.unit}`:`Trop petit : ${i.origin} doit \xEAtre ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Cha\xEEne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${o.pattern}`:`${n[o.format]??i.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${i.divisor}`;case"unrecognized_keys":return`Cl\xE9${i.keys.length>1?"s":""} non reconnue${i.keys.length>1?"s":""} : ${$(i.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${i.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${i.origin}`;default:return"Entr\xE9e invalide"}}};function BT(){return{localeError:nZ()}}var rZ=()=>{let e={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function t(i){return e[i]??null}let n={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},r={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Entr\xE9e invalide : attendu instanceof ${i.expected}, re\xE7u ${a}`:`Entr\xE9e invalide : attendu ${o}, re\xE7u ${a}`}case"invalid_value":return i.values.length===1?`Entr\xE9e invalide : attendu ${F(i.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"\u2264":"<",s=t(i.origin);return s?`Trop grand : attendu que ${i.origin??"la valeur"} ait ${o}${i.maximum.toString()} ${s.unit}`:`Trop grand : attendu que ${i.origin??"la valeur"} soit ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?"\u2265":">",s=t(i.origin);return s?`Trop petit : attendu que ${i.origin} ait ${o}${i.minimum.toString()} ${s.unit}`:`Trop petit : attendu que ${i.origin} soit ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Cha\xEEne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${o.pattern}`:`${n[o.format]??i.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${i.divisor}`;case"unrecognized_keys":return`Cl\xE9${i.keys.length>1?"s":""} non reconnue${i.keys.length>1?"s":""} : ${$(i.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${i.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${i.origin}`;default:return"Entr\xE9e invalide"}}};function MT(){return{localeError:rZ()}}var iZ=()=>{let e={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},t={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},n=c=>c?e[c]:void 0,r=c=>{let u=n(c);return u?u.label:c??e.unknown.label},i=c=>`\u05D4${r(c)}`,o=c=>(n(c)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA",s=c=>c?t[c]??null:null,a={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},l={nan:"NaN"};return c=>{switch(c.code){case"invalid_type":{let u=c.expected,d=l[u??""]??r(u),p=B(c.input),m=l[p]??e[p]?.label??p;return/^[A-Z]/.test(c.expected)?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${c.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${m}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${d}, \u05D4\u05EA\u05E7\u05D1\u05DC ${m}`}case"invalid_value":{if(c.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${F(c.values[0])}`;let u=c.values.map(m=>F(m));if(c.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${u[0]} \u05D0\u05D5 ${u[1]}`;let d=u[u.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${u.slice(0,-1).join(", ")} \u05D0\u05D5 ${d}`}case"too_big":{let u=s(c.origin),d=i(c.origin??"value");if(c.origin==="string")return`${u?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${c.maximum.toString()} ${u?.unit??""} ${c.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(c.origin==="number"){let h=c.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${c.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${c.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${h}`}if(c.origin==="array"||c.origin==="set"){let h=c.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",g=c.inclusive?`${c.maximum} ${u?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${c.maximum} ${u?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${d} ${h} \u05DC\u05D4\u05DB\u05D9\u05DC ${g}`.trim()}let p=c.inclusive?"<=":"<",m=o(c.origin??"value");return u?.unit?`${u.longLabel} \u05DE\u05D3\u05D9: ${d} ${m} ${p}${c.maximum.toString()} ${u.unit}`:`${u?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${d} ${m} ${p}${c.maximum.toString()}`}case"too_small":{let u=s(c.origin),d=i(c.origin??"value");if(c.origin==="string")return`${u?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${c.minimum.toString()} ${u?.unit??""} ${c.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(c.origin==="number"){let h=c.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${c.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${c.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${h}`}if(c.origin==="array"||c.origin==="set"){let h=c.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(c.minimum===1&&c.inclusive){let y=(c.origin==="set","\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3");return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} ${h} \u05DC\u05D4\u05DB\u05D9\u05DC ${y}`}let g=c.inclusive?`${c.minimum} ${u?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${c.minimum} ${u?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} ${h} \u05DC\u05D4\u05DB\u05D9\u05DC ${g}`.trim()}let p=c.inclusive?">=":">",m=o(c.origin??"value");return u?.unit?`${u.shortLabel} \u05DE\u05D3\u05D9: ${d} ${m} ${p}${c.minimum.toString()} ${u.unit}`:`${u?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${d} ${m} ${p}${c.minimum.toString()}`}case"invalid_format":{let u=c;if(u.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${u.prefix}"`;if(u.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${u.suffix}"`;if(u.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${u.includes}"`;if(u.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${u.pattern}`;let d=a[u.format],p=d?.label??u.format,h=(d?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${p} \u05DC\u05D0 ${h}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${c.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${c.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${c.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${$(c.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${i(c.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};function UT(){return{localeError:iZ()}}var oZ=()=>{let e={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function t(i){return e[i]??null}let n={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},r={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${i.expected}, a kapott \xE9rt\xE9k ${a}`:`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${o}, a kapott \xE9rt\xE9k ${a}`}case"invalid_value":return i.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${F(i.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`T\xFAl nagy: ${i.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${o}${i.maximum.toString()} ${s.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${i.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${i.origin} m\xE9rete t\xFAl kicsi ${o}${i.minimum.toString()} ${s.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${i.origin} t\xFAl kicsi ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\xC9rv\xE9nytelen string: "${o.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:o.format==="ends_with"?`\xC9rv\xE9nytelen string: "${o.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:o.format==="includes"?`\xC9rv\xE9nytelen string: "${o.includes}" \xE9rt\xE9ket kell tartalmaznia`:o.format==="regex"?`\xC9rv\xE9nytelen string: ${o.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${n[o.format]??i.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${i.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${i.keys.length>1?"s":""}: ${$(i.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${i.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${i.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};function zT(){return{localeError:oZ()}}function qT(e,t,n){return Math.abs(e)===1?t:n}function Bs(e){if(!e)return"";let t=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],n=e[e.length-1];return e+(t.includes(n)?"\u0576":"\u0568")}var sZ=()=>{let e={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function t(i){return e[i]??null}let n={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},r={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${i.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${a}`:`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${o}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${a}`}case"invalid_value":return i.values.length===1?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${F(i.values[1])}`:`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);if(s){let a=Number(i.maximum),l=qT(a,s.unit.one,s.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${Bs(i.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${o}${i.maximum.toString()} ${l}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${Bs(i.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);if(s){let a=Number(i.minimum),l=qT(a,s.unit.one,s.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${Bs(i.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${o}${i.minimum.toString()} ${l}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${Bs(i.origin)} \u056C\u056B\u0576\u056B ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${o.prefix}"-\u0578\u057E`:o.format==="ends_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${o.suffix}"-\u0578\u057E`:o.format==="includes"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${o.includes}"`:o.format==="regex"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${o.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`:`\u054D\u056D\u0561\u056C ${n[o.format]??i.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${i.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${i.keys.length>1?"\u0576\u0565\u0580":""}. ${$(i.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${Bs(i.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${Bs(i.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}};function VT(){return{localeError:sZ()}}var aZ=()=>{let e={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function t(i){return e[i]??null}let n={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Input tidak valid: diharapkan instanceof ${i.expected}, diterima ${a}`:`Input tidak valid: diharapkan ${o}, diterima ${a}`}case"invalid_value":return i.values.length===1?`Input tidak valid: diharapkan ${F(i.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Terlalu besar: diharapkan ${i.origin??"value"} memiliki ${o}${i.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: diharapkan ${i.origin??"value"} menjadi ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Terlalu kecil: diharapkan ${i.origin} memiliki ${o}${i.minimum.toString()} ${s.unit}`:`Terlalu kecil: diharapkan ${i.origin} menjadi ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`String tidak valid: harus dimulai dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak valid: harus berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak valid: harus menyertakan "${o.includes}"`:o.format==="regex"?`String tidak valid: harus sesuai pola ${o.pattern}`:`${n[o.format]??i.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${i.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${i.keys.length>1?"s":""}: ${$(i.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${i.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${i.origin}`;default:return"Input tidak valid"}}};function GT(){return{localeError:aZ()}}var lZ=()=>{let e={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function t(i){return e[i]??null}let n={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og t\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 t\xF6lugildi",jwt:"JWT",template_literal:"gildi"},r={nan:"NaN",number:"n\xFAmer",array:"fylki"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Rangt gildi: \xDE\xFA sl\xF3st inn ${a} \xFEar sem \xE1 a\xF0 vera instanceof ${i.expected}`:`Rangt gildi: \xDE\xFA sl\xF3st inn ${a} \xFEar sem \xE1 a\xF0 vera ${o}`}case"invalid_value":return i.values.length===1?`Rangt gildi: gert r\xE1\xF0 fyrir ${F(i.values[0])}`:`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${i.origin??"gildi"} hafi ${o}${i.maximum.toString()} ${s.unit??"hluti"}`:`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${i.origin??"gildi"} s\xE9 ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${i.origin} hafi ${o}${i.minimum.toString()} ${s.unit}`:`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${i.origin} s\xE9 ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${o.prefix}"`:o.format==="ends_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${o.suffix}"`:o.format==="includes"?`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${o.includes}"`:o.format==="regex"?`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${o.pattern}`:`Rangt ${n[o.format]??i.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${i.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${i.keys.length>1?"ir lyklar":"ur lykill"}: ${$(i.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${i.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${i.origin}`;default:return"Rangt gildi"}}};function HT(){return{localeError:lZ()}}var cZ=()=>{let e={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function t(i){return e[i]??null}let n={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"numero",array:"vettore"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Input non valido: atteso instanceof ${i.expected}, ricevuto ${a}`:`Input non valido: atteso ${o}, ricevuto ${a}`}case"invalid_value":return i.values.length===1?`Input non valido: atteso ${F(i.values[0])}`:`Opzione non valida: atteso uno tra ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Troppo grande: ${i.origin??"valore"} deve avere ${o}${i.maximum.toString()} ${s.unit??"elementi"}`:`Troppo grande: ${i.origin??"valore"} deve essere ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Troppo piccolo: ${i.origin} deve avere ${o}${i.minimum.toString()} ${s.unit}`:`Troppo piccolo: ${i.origin} deve essere ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Stringa non valida: deve iniziare con "${o.prefix}"`:o.format==="ends_with"?`Stringa non valida: deve terminare con "${o.suffix}"`:o.format==="includes"?`Stringa non valida: deve includere "${o.includes}"`:o.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${o.pattern}`:`Invalid ${n[o.format]??i.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${i.divisor}`;case"unrecognized_keys":return`Chiav${i.keys.length>1?"i":"e"} non riconosciut${i.keys.length>1?"e":"a"}: ${$(i.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${i.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${i.origin}`;default:return"Input non valido"}}};function KT(){return{localeError:cZ()}}var uZ=()=>{let e={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function t(i){return e[i]??null}let n={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},r={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u7121\u52B9\u306A\u5165\u529B: instanceof ${i.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${a}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u5165\u529B: ${o}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${a}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":return i.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${F(i.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${$(i.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let o=i.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",s=t(i.origin);return s?`\u5927\u304D\u3059\u304E\u308B\u5024: ${i.origin??"\u5024"}\u306F${i.maximum.toString()}${s.unit??"\u8981\u7D20"}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${i.origin??"\u5024"}\u306F${i.maximum.toString()}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let o=i.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",s=t(i.origin);return s?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${i.origin}\u306F${i.minimum.toString()}${s.unit}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${i.origin}\u306F${i.minimum.toString()}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${o.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${n[o.format]??i.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${i.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${i.keys.length>1?"\u7FA4":""}: ${$(i.keys,"\u3001")}`;case"invalid_key":return`${i.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${i.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};function WT(){return{localeError:uZ()}}var dZ=()=>{let e={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function t(i){return e[i]??null}let n={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",json_string:"JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},r={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${i.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${a}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${o}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${a}`}case"invalid_value":return i.values.length===1?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${F(i.values[0])}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${$(i.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${i.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${s.verb} ${o}${i.maximum.toString()} ${s.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${i.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${i.origin} ${s.verb} ${o}${i.minimum.toString()} ${s.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${i.origin} \u10D8\u10E7\u10DD\u10E1 ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${o.prefix}"-\u10D8\u10D7`:o.format==="ends_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${o.suffix}"-\u10D8\u10D7`:o.format==="includes"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${o.includes}"-\u10E1`:o.format==="regex"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${o.pattern}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${n[o.format]??i.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${i.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${i.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${$(i.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${i.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${i.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}};function ZT(){return{localeError:dZ()}}var pZ=()=>{let e={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function t(i){return e[i]??null}let n={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},r={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${i.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${a}`:`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${a}`}case"invalid_value":return i.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${F(i.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${o} ${i.maximum.toString()} ${s.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${o} ${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin} ${o} ${i.minimum.toString()} ${s.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${i.origin} ${o} ${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${o.prefix}"`:o.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${o.suffix}"`:o.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${o.includes}"`:o.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${o.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${n[o.format]??i.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${i.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${$(i.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${i.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${i.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};function jf(){return{localeError:pZ()}}function JT(){return jf()}var fZ=()=>{let e={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function t(i){return e[i]??null}let n={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},r={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${i.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${a}\uC785\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${o}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${a}\uC785\uB2C8\uB2E4`}case"invalid_value":return i.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${F(i.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${$(i.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let o=i.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",s=o==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=t(i.origin),l=a?.unit??"\uC694\uC18C";return a?`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${i.maximum.toString()}${l} ${o}${s}`:`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${i.maximum.toString()} ${o}${s}`}case"too_small":{let o=i.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",s=o==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=t(i.origin),l=a?.unit??"\uC694\uC18C";return a?`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${i.minimum.toString()}${l} ${o}${s}`:`${i.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${i.minimum.toString()} ${o}${s}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:o.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:o.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:o.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${o.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${n[o.format]??i.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${i.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${$(i.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${i.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${i.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};function YT(){return{localeError:fZ()}}var Tc=e=>e.charAt(0).toUpperCase()+e.slice(1);function XT(e){let t=Math.abs(e),n=t%10,r=t%100;return r>=11&&r<=19||n===0?"many":n===1?"one":"few"}var mZ=()=>{let e={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function t(i,o,s,a){let l=e[i]??null;return l===null?l:{unit:l.unit[o],verb:l.verb[a][s?"inclusive":"notInclusive"]}}let n={regex:"\u012Fvestis",email:"el. pa\u0161to adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukm\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},r={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Gautas tipas ${a}, o tik\u0117tasi - instanceof ${i.expected}`:`Gautas tipas ${a}, o tik\u0117tasi - ${o}`}case"invalid_value":return i.values.length===1?`Privalo b\u016Bti ${F(i.values[0])}`:`Privalo b\u016Bti vienas i\u0161 ${$(i.values,"|")} pasirinkim\u0173`;case"too_big":{let o=r[i.origin]??i.origin,s=t(i.origin,XT(Number(i.maximum)),i.inclusive??!1,"smaller");if(s?.verb)return`${Tc(o??i.origin??"reik\u0161m\u0117")} ${s.verb} ${i.maximum.toString()} ${s.unit??"element\u0173"}`;let a=i.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${Tc(o??i.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${i.maximum.toString()} ${s?.unit}`}case"too_small":{let o=r[i.origin]??i.origin,s=t(i.origin,XT(Number(i.minimum)),i.inclusive??!1,"bigger");if(s?.verb)return`${Tc(o??i.origin??"reik\u0161m\u0117")} ${s.verb} ${i.minimum.toString()} ${s.unit??"element\u0173"}`;let a=i.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${Tc(o??i.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${i.minimum.toString()} ${s?.unit}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Eilut\u0117 privalo prasid\u0117ti "${o.prefix}"`:o.format==="ends_with"?`Eilut\u0117 privalo pasibaigti "${o.suffix}"`:o.format==="includes"?`Eilut\u0117 privalo \u012Ftraukti "${o.includes}"`:o.format==="regex"?`Eilut\u0117 privalo atitikti ${o.pattern}`:`Neteisingas ${n[o.format]??i.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${i.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${i.keys.length>1?"i":"as"} rakt${i.keys.length>1?"ai":"as"}: ${$(i.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let o=r[i.origin]??i.origin;return`${Tc(o??i.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}};function QT(){return{localeError:mZ()}}var gZ=()=>{let e={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function t(i){return e[i]??null}let n={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},r={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${i.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${a}`:`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${a}`}case"invalid_value":return i.values.length===1?`Invalid input: expected ${F(i.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${o}${i.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin} \u0434\u0430 \u0438\u043C\u0430 ${o}${i.minimum.toString()} ${s.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${i.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${o.pattern}`:`Invalid ${n[o.format]??i.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${i.divisor}`;case"unrecognized_keys":return`${i.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${$(i.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${i.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${i.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};function eO(){return{localeError:gZ()}}var hZ=()=>{let e={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function t(i){return e[i]??null}let n={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"nombor"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Input tidak sah: dijangka instanceof ${i.expected}, diterima ${a}`:`Input tidak sah: dijangka ${o}, diterima ${a}`}case"invalid_value":return i.values.length===1?`Input tidak sah: dijangka ${F(i.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Terlalu besar: dijangka ${i.origin??"nilai"} ${s.verb} ${o}${i.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: dijangka ${i.origin??"nilai"} adalah ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Terlalu kecil: dijangka ${i.origin} ${s.verb} ${o}${i.minimum.toString()} ${s.unit}`:`Terlalu kecil: dijangka ${i.origin} adalah ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`String tidak sah: mesti bermula dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak sah: mesti mengandungi "${o.includes}"`:o.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${o.pattern}`:`${n[o.format]??i.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${i.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${$(i.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${i.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${i.origin}`;default:return"Input tidak sah"}}};function tO(){return{localeError:hZ()}}var yZ=()=>{let e={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function t(i){return e[i]??null}let n={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},r={nan:"NaN",number:"getal"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Ongeldige invoer: verwacht instanceof ${i.expected}, ontving ${a}`:`Ongeldige invoer: verwacht ${o}, ontving ${a}`}case"invalid_value":return i.values.length===1?`Ongeldige invoer: verwacht ${F(i.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin),a=i.origin==="date"?"laat":i.origin==="string"?"lang":"groot";return s?`Te ${a}: verwacht dat ${i.origin??"waarde"} ${o}${i.maximum.toString()} ${s.unit??"elementen"} ${s.verb}`:`Te ${a}: verwacht dat ${i.origin??"waarde"} ${o}${i.maximum.toString()} is`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin),a=i.origin==="date"?"vroeg":i.origin==="string"?"kort":"klein";return s?`Te ${a}: verwacht dat ${i.origin} ${o}${i.minimum.toString()} ${s.unit} ${s.verb}`:`Te ${a}: verwacht dat ${i.origin} ${o}${i.minimum.toString()} is`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Ongeldige tekst: moet met "${o.prefix}" beginnen`:o.format==="ends_with"?`Ongeldige tekst: moet op "${o.suffix}" eindigen`:o.format==="includes"?`Ongeldige tekst: moet "${o.includes}" bevatten`:o.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${o.pattern}`:`Ongeldig: ${n[o.format]??i.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${i.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${i.keys.length>1?"s":""}: ${$(i.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${i.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${i.origin}`;default:return"Ongeldige invoer"}}};function nO(){return{localeError:yZ()}}var vZ=()=>{let e={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function t(i){return e[i]??null}let n={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"tall",array:"liste"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Ugyldig input: forventet instanceof ${i.expected}, fikk ${a}`:`Ugyldig input: forventet ${o}, fikk ${a}`}case"invalid_value":return i.values.length===1?`Ugyldig verdi: forventet ${F(i.values[0])}`:`Ugyldig valg: forventet en av ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`For stor(t): forventet ${i.origin??"value"} til \xE5 ha ${o}${i.maximum.toString()} ${s.unit??"elementer"}`:`For stor(t): forventet ${i.origin??"value"} til \xE5 ha ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`For lite(n): forventet ${i.origin} til \xE5 ha ${o}${i.minimum.toString()} ${s.unit}`:`For lite(n): forventet ${i.origin} til \xE5 ha ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${o.prefix}"`:o.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${o.suffix}"`:o.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${o.includes}"`:o.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${o.pattern}`:`Ugyldig ${n[o.format]??i.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${i.divisor}`;case"unrecognized_keys":return`${i.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${$(i.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${i.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${i.origin}`;default:return"Ugyldig input"}}};function rO(){return{localeError:vZ()}}var kZ=()=>{let e={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function t(i){return e[i]??null}let n={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},r={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`F\xE2sit giren: umulan instanceof ${i.expected}, al\u0131nan ${a}`:`F\xE2sit giren: umulan ${o}, al\u0131nan ${a}`}case"invalid_value":return i.values.length===1?`F\xE2sit giren: umulan ${F(i.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Fazla b\xFCy\xFCk: ${i.origin??"value"}, ${o}${i.maximum.toString()} ${s.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${i.origin??"value"}, ${o}${i.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Fazla k\xFC\xE7\xFCk: ${i.origin}, ${o}${i.minimum.toString()} ${s.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${i.origin}, ${o}${i.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let o=i;return o.format==="starts_with"?`F\xE2sit metin: "${o.prefix}" ile ba\u015Flamal\u0131.`:o.format==="ends_with"?`F\xE2sit metin: "${o.suffix}" ile bitmeli.`:o.format==="includes"?`F\xE2sit metin: "${o.includes}" ihtiv\xE2 etmeli.`:o.format==="regex"?`F\xE2sit metin: ${o.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${n[o.format]??i.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${i.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${i.keys.length>1?"s":""}: ${$(i.keys,", ")}`;case"invalid_key":return`${i.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${i.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};function iO(){return{localeError:kZ()}}var wZ=()=>{let e={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function t(i){return e[i]??null}let n={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},r={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${i.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${a} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`:`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${o} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${a} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":return i.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${F(i.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${$(i.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${i.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${o}${i.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${i.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${o}${i.maximum.toString()} \u0648\u064A`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${i.origin} \u0628\u0627\u06CC\u062F ${o}${i.minimum.toString()} ${s.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${i.origin} \u0628\u0627\u06CC\u062F ${o}${i.minimum.toString()} \u0648\u064A`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${o.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:o.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${o.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:o.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${o.includes}" \u0648\u0644\u0631\u064A`:o.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${o.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${n[o.format]??i.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${i.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${i.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${$(i.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${i.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${i.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};function oO(){return{localeError:wZ()}}var bZ=()=>{let e={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function t(i){return e[i]??null}let n={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},r={nan:"NaN",number:"liczba",array:"tablica"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${i.expected}, otrzymano ${a}`:`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${o}, otrzymano ${a}`}case"invalid_value":return i.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${F(i.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${o}${i.maximum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${o}${i.minimum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${i.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${o.prefix}"`:o.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${o.suffix}"`:o.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${o.includes}"`:o.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${o.pattern}`:`Nieprawid\u0142ow(y/a/e) ${n[o.format]??i.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${i.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${i.keys.length>1?"s":""}: ${$(i.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${i.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${i.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};function sO(){return{localeError:bZ()}}var _Z=()=>{let e={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function t(i){return e[i]??null}let n={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},r={nan:"NaN",number:"n\xFAmero",null:"nulo"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Tipo inv\xE1lido: esperado instanceof ${i.expected}, recebido ${a}`:`Tipo inv\xE1lido: esperado ${o}, recebido ${a}`}case"invalid_value":return i.values.length===1?`Entrada inv\xE1lida: esperado ${F(i.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Muito grande: esperado que ${i.origin??"valor"} tivesse ${o}${i.maximum.toString()} ${s.unit??"elementos"}`:`Muito grande: esperado que ${i.origin??"valor"} fosse ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Muito pequeno: esperado que ${i.origin} tivesse ${o}${i.minimum.toString()} ${s.unit}`:`Muito pequeno: esperado que ${i.origin} fosse ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${o.prefix}"`:o.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${o.suffix}"`:o.format==="includes"?`Texto inv\xE1lido: deve incluir "${o.includes}"`:o.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${o.pattern}`:`${n[o.format]??i.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${i.divisor}`;case"unrecognized_keys":return`Chave${i.keys.length>1?"s":""} desconhecida${i.keys.length>1?"s":""}: ${$(i.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${i.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${i.origin}`;default:return"Campo inv\xE1lido"}}};function aO(){return{localeError:_Z()}}function lO(e,t,n,r){let i=Math.abs(e),o=i%10,s=i%100;return s>=11&&s<=19?r:o===1?t:o>=2&&o<=4?n:r}var SZ=()=>{let e={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function t(i){return e[i]??null}let n={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},r={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${i.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${a}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${o}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${a}`}case"invalid_value":return i.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${F(i.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);if(s){let a=Number(i.maximum),l=lO(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${o}${i.maximum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);if(s){let a=Number(i.minimum),l=lO(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${o}${i.minimum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${i.origin} \u0431\u0443\u0434\u0435\u0442 ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${n[o.format]??i.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${i.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${i.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${i.keys.length>1?"\u0438":""}: ${$(i.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${i.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${i.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};function cO(){return{localeError:SZ()}}var xZ=()=>{let e={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function t(i){return e[i]??null}let n={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},r={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Neveljaven vnos: pri\u010Dakovano instanceof ${i.expected}, prejeto ${a}`:`Neveljaven vnos: pri\u010Dakovano ${o}, prejeto ${a}`}case"invalid_value":return i.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${F(i.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Preveliko: pri\u010Dakovano, da bo ${i.origin??"vrednost"} imelo ${o}${i.maximum.toString()} ${s.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${i.origin??"vrednost"} ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Premajhno: pri\u010Dakovano, da bo ${i.origin} imelo ${o}${i.minimum.toString()} ${s.unit}`:`Premajhno: pri\u010Dakovano, da bo ${i.origin} ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${o.prefix}"`:o.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${o.suffix}"`:o.format==="includes"?`Neveljaven niz: mora vsebovati "${o.includes}"`:o.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${o.pattern}`:`Neveljaven ${n[o.format]??i.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${i.divisor}`;case"unrecognized_keys":return`Neprepoznan${i.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${$(i.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${i.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${i.origin}`;default:return"Neveljaven vnos"}}};function uO(){return{localeError:xZ()}}var CZ=()=>{let e={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function t(i){return e[i]??null}let n={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},r={nan:"NaN",number:"antal",array:"lista"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${i.expected}, fick ${a}`:`Ogiltig inmatning: f\xF6rv\xE4ntat ${o}, fick ${a}`}case"invalid_value":return i.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${F(i.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`F\xF6r stor(t): f\xF6rv\xE4ntade ${i.origin??"v\xE4rdet"} att ha ${o}${i.maximum.toString()} ${s.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${i.origin??"v\xE4rdet"} att ha ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`F\xF6r lite(t): f\xF6rv\xE4ntade ${i.origin??"v\xE4rdet"} att ha ${o}${i.minimum.toString()} ${s.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${i.origin??"v\xE4rdet"} att ha ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${o.prefix}"`:o.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${o.suffix}"`:o.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${o.includes}"`:o.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${o.pattern}"`:`Ogiltig(t) ${n[o.format]??i.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${i.divisor}`;case"unrecognized_keys":return`${i.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${$(i.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${i.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${i.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};function dO(){return{localeError:CZ()}}var IZ=()=>{let e={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function t(i){return e[i]??null}let n={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},r={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${i.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${a}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${a}`}case"invalid_value":return i.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${F(i.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${$(i.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${o}${i.maximum.toString()} ${s.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${o}${i.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin} ${o}${i.minimum.toString()} ${s.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${i.origin} ${o}${i.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${o.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${n[o.format]??i.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${i.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${i.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${$(i.keys,", ")}`;case"invalid_key":return`${i.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${i.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};function pO(){return{localeError:IZ()}}var PZ=()=>{let e={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function t(i){return e[i]??null}let n={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},r={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${i.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${a}`:`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${o} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${a}`}case"invalid_value":return i.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${F(i.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",s=t(i.origin);return s?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${i.maximum.toString()} ${s.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",s=t(i.origin);return s?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${i.minimum.toString()} ${s.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${i.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${o.prefix}"`:o.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${o.suffix}"`:o.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${o.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:o.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${o.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${n[o.format]??i.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${i.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${$(i.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${i.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${i.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};function fO(){return{localeError:PZ()}}var AZ=()=>{let e={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function t(i){return e[i]??null}let n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},r={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${i.expected}, al\u0131nan ${a}`:`Ge\xE7ersiz de\u011Fer: beklenen ${o}, al\u0131nan ${a}`}case"invalid_value":return i.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${F(i.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\xC7ok b\xFCy\xFCk: beklenen ${i.origin??"de\u011Fer"} ${o}${i.maximum.toString()} ${s.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${i.origin??"de\u011Fer"} ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\xC7ok k\xFC\xE7\xFCk: beklenen ${i.origin} ${o}${i.minimum.toString()} ${s.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${i.origin} ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Ge\xE7ersiz metin: "${o.prefix}" ile ba\u015Flamal\u0131`:o.format==="ends_with"?`Ge\xE7ersiz metin: "${o.suffix}" ile bitmeli`:o.format==="includes"?`Ge\xE7ersiz metin: "${o.includes}" i\xE7ermeli`:o.format==="regex"?`Ge\xE7ersiz metin: ${o.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${n[o.format]??i.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${i.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${i.keys.length>1?"lar":""}: ${$(i.keys,", ")}`;case"invalid_key":return`${i.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${i.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};function mO(){return{localeError:AZ()}}var RZ=()=>{let e={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function t(i){return e[i]??null}let n={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},r={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${i.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${a}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${o}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${a}`}case"invalid_value":return i.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${F(i.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${s.verb} ${o}${i.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin} ${s.verb} ${o}${i.minimum.toString()} ${s.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${i.origin} \u0431\u0443\u0434\u0435 ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${n[o.format]??i.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${i.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${i.keys.length>1?"\u0456":""}: ${$(i.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${i.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${i.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};function Nf(){return{localeError:RZ()}}function gO(){return Nf()}var EZ=()=>{let e={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function t(i){return e[i]??null}let n={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},r={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${i.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${a} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`:`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${o} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${a} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":return i.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${F(i.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${$(i.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${i.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${o}${i.maximum.toString()} ${s.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${i.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${o}${i.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${i.origin} \u06A9\u06D2 ${o}${i.minimum.toString()} ${s.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${i.origin} \u06A9\u0627 ${o}${i.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${o.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${n[o.format]??i.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${i.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${i.keys.length>1?"\u0632":""}: ${$(i.keys,"\u060C ")}`;case"invalid_key":return`${i.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${i.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};function hO(){return{localeError:EZ()}}var $Z=()=>{let e={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"}};function t(i){return e[i]??null}let n={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},r={nan:"NaN",number:"raqam",array:"massiv"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${i.expected}, qabul qilingan ${a}`:`Noto\u2018g\u2018ri kirish: kutilgan ${o}, qabul qilingan ${a}`}case"invalid_value":return i.values.length===1?`Noto\u2018g\u2018ri kirish: kutilgan ${F(i.values[0])}`:`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Juda katta: kutilgan ${i.origin??"qiymat"} ${o}${i.maximum.toString()} ${s.unit} ${s.verb}`:`Juda katta: kutilgan ${i.origin??"qiymat"} ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Juda kichik: kutilgan ${i.origin} ${o}${i.minimum.toString()} ${s.unit} ${s.verb}`:`Juda kichik: kutilgan ${i.origin} ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Noto\u2018g\u2018ri satr: "${o.prefix}" bilan boshlanishi kerak`:o.format==="ends_with"?`Noto\u2018g\u2018ri satr: "${o.suffix}" bilan tugashi kerak`:o.format==="includes"?`Noto\u2018g\u2018ri satr: "${o.includes}" ni o\u2018z ichiga olishi kerak`:o.format==="regex"?`Noto\u2018g\u2018ri satr: ${o.pattern} shabloniga mos kelishi kerak`:`Noto\u2018g\u2018ri ${n[o.format]??i.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${i.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${i.keys.length>1?"lar":""}: ${$(i.keys,", ")}`;case"invalid_key":return`${i.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${i.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}};function yO(){return{localeError:$Z()}}var DZ=()=>{let e={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function t(i){return e[i]??null}let n={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},r={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${i.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${a}`:`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${o}, nh\u1EADn \u0111\u01B0\u1EE3c ${a}`}case"invalid_value":return i.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${F(i.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${i.origin??"gi\xE1 tr\u1ECB"} ${s.verb} ${o}${i.maximum.toString()} ${s.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${i.origin??"gi\xE1 tr\u1ECB"} ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${i.origin} ${s.verb} ${o}${i.minimum.toString()} ${s.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${i.origin} ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${o.prefix}"`:o.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${o.suffix}"`:o.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${o.includes}"`:o.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${o.pattern}`:`${n[o.format]??i.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${i.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${$(i.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${i.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${i.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};function vO(){return{localeError:DZ()}}var TZ=()=>{let e={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function t(i){return e[i]??null}let n={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},r={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${i.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${a}`:`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${o}\uFF0C\u5B9E\u9645\u63A5\u6536 ${a}`}case"invalid_value":return i.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${F(i.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${i.origin??"\u503C"} ${o}${i.maximum.toString()} ${s.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${i.origin??"\u503C"} ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${i.origin} ${o}${i.minimum.toString()} ${s.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${i.origin} ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${o.prefix}" \u5F00\u5934`:o.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${o.suffix}" \u7ED3\u5C3E`:o.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${o.includes}"`:o.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${o.pattern}`:`\u65E0\u6548${n[o.format]??i.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${i.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${$(i.keys,", ")}`;case"invalid_key":return`${i.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${i.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};function kO(){return{localeError:TZ()}}var OZ=()=>{let e={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function t(i){return e[i]??null}let n={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},r={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${i.expected}\uFF0C\u4F46\u6536\u5230 ${a}`:`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${o}\uFF0C\u4F46\u6536\u5230 ${a}`}case"invalid_value":return i.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${F(i.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${i.origin??"\u503C"} \u61C9\u70BA ${o}${i.maximum.toString()} ${s.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${i.origin??"\u503C"} \u61C9\u70BA ${o}${i.maximum.toString()}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${i.origin} \u61C9\u70BA ${o}${i.minimum.toString()} ${s.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${i.origin} \u61C9\u70BA ${o}${i.minimum.toString()}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${o.prefix}" \u958B\u982D`:o.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${o.suffix}" \u7D50\u5C3E`:o.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${o.includes}"`:o.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${o.pattern}`:`\u7121\u6548\u7684 ${n[o.format]??i.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${i.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${i.keys.length>1?"\u5011":""}\uFF1A${$(i.keys,"\u3001")}`;case"invalid_key":return`${i.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${i.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};function wO(){return{localeError:OZ()}}var LZ=()=>{let e={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function t(i){return e[i]??null}let n={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},r={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return i=>{switch(i.code){case"invalid_type":{let o=r[i.expected]??i.expected,s=B(i.input),a=r[s]??s;return/^[A-Z]/.test(i.expected)?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${i.expected}, \xE0m\u1ECD\u0300 a r\xED ${a}`:`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${o}, \xE0m\u1ECD\u0300 a r\xED ${a}`}case"invalid_value":return i.values.length===1?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${F(i.values[0])}`:`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${$(i.values,"|")}`;case"too_big":{let o=i.inclusive?"<=":"<",s=t(i.origin);return s?`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${i.origin??"iye"} ${s.verb} ${o}${i.maximum} ${s.unit}`:`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${o}${i.maximum}`}case"too_small":{let o=i.inclusive?">=":">",s=t(i.origin);return s?`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${i.origin} ${s.verb} ${o}${i.minimum} ${s.unit}`:`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${o}${i.minimum}`}case"invalid_format":{let o=i;return o.format==="starts_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${o.prefix}"`:o.format==="ends_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${o.suffix}"`:o.format==="includes"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${o.includes}"`:o.format==="regex"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${o.pattern}`:`A\u1E63\xEC\u1E63e: ${n[o.format]??i.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${i.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${$(i.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${i.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${i.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}};function bO(){return{localeError:LZ()}}var _O,d_=Symbol("ZodOutput"),p_=Symbol("ZodInput"),Ff=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){let r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){let n=t._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function Bf(){return new Ff}(_O=globalThis).__zod_globalRegistry??(_O.__zod_globalRegistry=Bf());var pt=globalThis.__zod_globalRegistry;function f_(e,t){return new e({type:"string",...U(t)})}function m_(e,t){return new e({type:"string",coerce:!0,...U(t)})}function Mf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...U(t)})}function Lc(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...U(t)})}function Uf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...U(t)})}function zf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...U(t)})}function qf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...U(t)})}function Vf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...U(t)})}function jc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...U(t)})}function Gf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...U(t)})}function Hf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...U(t)})}function Kf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...U(t)})}function Wf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...U(t)})}function Zf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...U(t)})}function Jf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...U(t)})}function Yf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...U(t)})}function Xf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...U(t)})}function Qf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...U(t)})}function g_(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...U(t)})}function em(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...U(t)})}function tm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...U(t)})}function nm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...U(t)})}function rm(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...U(t)})}function im(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...U(t)})}function om(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...U(t)})}var h_={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function y_(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...U(t)})}function v_(e,t){return new e({type:"string",format:"date",check:"string_format",...U(t)})}function k_(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...U(t)})}function w_(e,t){return new e({type:"string",format:"duration",check:"string_format",...U(t)})}function b_(e,t){return new e({type:"number",checks:[],...U(t)})}function __(e,t){return new e({type:"number",coerce:!0,checks:[],...U(t)})}function S_(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...U(t)})}function x_(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...U(t)})}function C_(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...U(t)})}function I_(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...U(t)})}function P_(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...U(t)})}function A_(e,t){return new e({type:"boolean",...U(t)})}function R_(e,t){return new e({type:"boolean",coerce:!0,...U(t)})}function E_(e,t){return new e({type:"bigint",...U(t)})}function $_(e,t){return new e({type:"bigint",coerce:!0,...U(t)})}function D_(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...U(t)})}function T_(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...U(t)})}function O_(e,t){return new e({type:"symbol",...U(t)})}function L_(e,t){return new e({type:"undefined",...U(t)})}function j_(e,t){return new e({type:"null",...U(t)})}function N_(e){return new e({type:"any"})}function F_(e){return new e({type:"unknown"})}function B_(e,t){return new e({type:"never",...U(t)})}function M_(e,t){return new e({type:"void",...U(t)})}function U_(e,t){return new e({type:"date",...U(t)})}function z_(e,t){return new e({type:"date",coerce:!0,...U(t)})}function q_(e,t){return new e({type:"nan",...U(t)})}function Xn(e,t){return new xf({check:"less_than",...U(t),value:e,inclusive:!1})}function rn(e,t){return new xf({check:"less_than",...U(t),value:e,inclusive:!0})}function Qn(e,t){return new Cf({check:"greater_than",...U(t),value:e,inclusive:!1})}function Pt(e,t){return new Cf({check:"greater_than",...U(t),value:e,inclusive:!0})}function sm(e){return Qn(0,e)}function am(e){return Xn(0,e)}function lm(e){return rn(0,e)}function cm(e){return Pt(0,e)}function hi(e,t){return new jw({check:"multiple_of",...U(t),value:e})}function yi(e,t){return new Bw({check:"max_size",...U(t),maximum:e})}function er(e,t){return new Mw({check:"min_size",...U(t),minimum:e})}function so(e,t){return new Uw({check:"size_equals",...U(t),size:e})}function ao(e,t){return new zw({check:"max_length",...U(t),maximum:e})}function Ar(e,t){return new qw({check:"min_length",...U(t),minimum:e})}function lo(e,t){return new Vw({check:"length_equals",...U(t),length:e})}function Ms(e,t){return new Gw({check:"string_format",format:"regex",...U(t),pattern:e})}function Us(e){return new Hw({check:"string_format",format:"lowercase",...U(e)})}function zs(e){return new Kw({check:"string_format",format:"uppercase",...U(e)})}function qs(e,t){return new Ww({check:"string_format",format:"includes",...U(t),includes:e})}function Vs(e,t){return new Zw({check:"string_format",format:"starts_with",...U(t),prefix:e})}function Gs(e,t){return new Jw({check:"string_format",format:"ends_with",...U(t),suffix:e})}function um(e,t,n){return new Yw({check:"property",property:e,schema:t,...U(n)})}function Hs(e,t){return new Xw({check:"mime_type",mime:e,...U(t)})}function jn(e){return new Qw({check:"overwrite",tx:e})}function Ks(e){return jn(t=>t.normalize(e))}function Ws(){return jn(e=>e.trim())}function Zs(){return jn(e=>e.toLowerCase())}function Js(){return jn(e=>e.toUpperCase())}function Ys(){return jn(e=>Yk(e))}function V_(e,t,n){return new e({type:"array",element:t,...U(n)})}function NZ(e,t,n){return new e({type:"union",options:t,...U(n)})}function FZ(e,t,n){return new e({type:"union",options:t,inclusive:!1,...U(n)})}function BZ(e,t,n,r){return new e({type:"union",options:n,discriminator:t,...U(r)})}function MZ(e,t,n){return new e({type:"intersection",left:t,right:n})}function UZ(e,t,n,r){let i=n instanceof oe,o=i?r:n,s=i?n:null;return new e({type:"tuple",items:t,rest:s,...U(o)})}function zZ(e,t,n,r){return new e({type:"record",keyType:t,valueType:n,...U(r)})}function qZ(e,t,n,r){return new e({type:"map",keyType:t,valueType:n,...U(r)})}function VZ(e,t,n){return new e({type:"set",valueType:t,...U(n)})}function GZ(e,t,n){let r=Array.isArray(t)?Object.fromEntries(t.map(i=>[i,i])):t;return new e({type:"enum",entries:r,...U(n)})}function HZ(e,t,n){return new e({type:"enum",entries:t,...U(n)})}function KZ(e,t,n){return new e({type:"literal",values:Array.isArray(t)?t:[t],...U(n)})}function G_(e,t){return new e({type:"file",...U(t)})}function WZ(e,t){return new e({type:"transform",transform:t})}function ZZ(e,t){return new e({type:"optional",innerType:t})}function JZ(e,t){return new e({type:"nullable",innerType:t})}function YZ(e,t,n){return new e({type:"default",innerType:t,get defaultValue(){return typeof n=="function"?n():Qk(n)}})}function XZ(e,t,n){return new e({type:"nonoptional",innerType:t,...U(n)})}function QZ(e,t){return new e({type:"success",innerType:t})}function eJ(e,t,n){return new e({type:"catch",innerType:t,catchValue:typeof n=="function"?n:()=>n})}function tJ(e,t,n){return new e({type:"pipe",in:t,out:n})}function nJ(e,t){return new e({type:"readonly",innerType:t})}function rJ(e,t,n){return new e({type:"template_literal",parts:t,...U(n)})}function iJ(e,t){return new e({type:"lazy",getter:t})}function oJ(e,t){return new e({type:"promise",innerType:t})}function H_(e,t,n){let r=U(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function K_(e,t,n){return new e({type:"custom",check:"custom",fn:t,...U(n)})}function W_(e){let t=SO(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Ts(r,n.value,t._zod.def));else{let i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),n.issues.push(Ts(i))}},e(n.value,n)));return t}function SO(e,t){let n=new Ie({check:"custom",...U(t)});return n._zod.check=e,n}function Z_(e){let t=new Ie({check:"describe"});return t._zod.onattach=[n=>{let r=pt.get(n)??{};pt.add(n,{...r,description:e})}],t._zod.check=()=>{},t}function J_(e){let t=new Ie({check:"meta"});return t._zod.onattach=[n=>{let r=pt.get(n)??{};pt.add(n,{...r,...e})}],t._zod.check=()=>{},t}function Y_(e,t){let n=U(t),r=n.truthy??["true","1","yes","on","y","enabled"],i=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(r=r.map(m=>typeof m=="string"?m.toLowerCase():m),i=i.map(m=>typeof m=="string"?m.toLowerCase():m));let o=new Set(r),s=new Set(i),a=e.Codec??Dc,l=e.Boolean??Ec,c=e.String??oo,u=new c({type:"string",error:n.error}),d=new l({type:"boolean",error:n.error}),p=new a({type:"pipe",in:u,out:d,transform:((m,h)=>{let g=m;return n.case!=="sensitive"&&(g=g.toLowerCase()),o.has(g)?!0:s.has(g)?!1:(h.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:h.value,inst:p,continue:!1}),{})}),reverseTransform:((m,h)=>m===!0?r[0]||"true":i[0]||"false"),error:n.error});return p}function Xs(e,t,n,r={}){let i=U(r),o={...U(r),check:"string_format",type:"string",format:t,fn:typeof n=="function"?n:a=>n.test(a),...i};return n instanceof RegExp&&(o.pattern=n),new e(o)}function vi(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??pt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function be(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let u={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,u);else{let p=s.schema,m=t.processors[i.type];if(!m)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);m(e,t,p,u)}let d=e._zod.parent;d&&(s.ref||(s.ref=d),be(d,t,u),t.seen.get(d).isParent=!0)}let l=t.metadataRegistry.get(e);return l&&Object.assign(s.schema,l),t.io==="input"&&At(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&s.schema._prefault&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function ki(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let l=r.get(a);if(l&&l!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}let i=s=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(s[0])?.id,p=e.external.uri??(h=>h);if(d)return{ref:p(d)};let m=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=m,{defId:m,ref:`${p("__shared")}#/${a}/${m}`}}if(s[1]===n)return{ref:"#"};let c=`#/${a}/`,u=s[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:c+u}},o=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:l,defId:c}=i(s);a.def={...a.schema},c&&(a.defId=c);let u=a.schema;for(let d in u)delete u[d];u.$ref=l};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
792
792
|
|
|
793
793
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){o(s);continue}if(e.external){let c=e.external.registry.get(s[0])?.id;if(t!==s[0]&&c){o(s);continue}}if(e.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}if(a.count>1&&e.reused==="ref"){o(s);continue}}}function wi(e,t){let n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=s=>{let a=e.seen.get(s);if(a.ref===null)return;let l=a.def??a.schema,c={...l},u=a.ref;if(a.ref=null,u){r(u);let p=e.seen.get(u),m=p.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(m)):Object.assign(l,m),Object.assign(l,c),s._zod.parent===u)for(let g in l)g==="$ref"||g==="allOf"||g in c||delete l[g];if(m.$ref&&p.def)for(let g in l)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(l[g])===JSON.stringify(p.def[g])&&delete l[g]}let d=s._zod.parent;if(d&&d!==u){r(d);let p=e.seen.get(d);if(p?.schema.$ref&&(l.$ref=p.schema.$ref,p.def))for(let m in l)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(l[m])===JSON.stringify(p.def[m])&&delete l[m]}e.override({zodSchema:s,jsonSchema:l,path:a.path??[]})};for(let s of[...e.seen.entries()].reverse())r(s[0]);let i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let s=e.external.registry.get(t)?.id;if(!s)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(s)}Object.assign(i,n.def??n.schema);let o=e.external?.defs??{};for(let s of e.seen.entries()){let a=s[1];a.def&&a.defId&&(o[a.defId]=a.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?i.$defs=o:i.definitions=o);try{let s=JSON.parse(JSON.stringify(i));return Object.defineProperty(s,"~standard",{value:{...t["~standard"],jsonSchema:{input:Qs(t,"input",e.processors),output:Qs(t,"output",e.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function At(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return At(r.element,n);if(r.type==="set")return At(r.valueType,n);if(r.type==="lazy")return At(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return At(r.innerType,n);if(r.type==="intersection")return At(r.left,n)||At(r.right,n);if(r.type==="record"||r.type==="map")return At(r.keyType,n)||At(r.valueType,n);if(r.type==="pipe")return At(r.in,n)||At(r.out,n);if(r.type==="object"){for(let i in r.shape)if(At(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(let i of r.options)if(At(i,n))return!0;return!1}if(r.type==="tuple"){for(let i of r.items)if(At(i,n))return!0;return!!(r.rest&&At(r.rest,n))}return!1}var X_=(e,t={})=>n=>{let r=vi({...n,processors:t});return be(e,r),ki(r,e),wi(r,e)},Qs=(e,t,n={})=>r=>{let{libraryOptions:i,target:o}=r??{},s=vi({...i??{},target:o,io:t,processors:n});return be(e,s),ki(s,e),wi(s,e)};var sJ={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Q_=(e,t,n,r)=>{let i=n;i.type="string";let{minimum:o,maximum:s,format:a,patterns:l,contentEncoding:c}=e._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof s=="number"&&(i.maxLength=s),a&&(i.format=sJ[a]??a,i.format===""&&delete i.format,a==="time"&&delete i.format),c&&(i.contentEncoding=c),l&&l.size>0){let u=[...l];u.length===1?i.pattern=u[0].source:u.length>1&&(i.allOf=[...u.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},eS=(e,t,n,r)=>{let i=n,{minimum:o,maximum:s,format:a,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:u}=e._zod.bag;typeof a=="string"&&a.includes("int")?i.type="integer":i.type="number",typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof o=="number"&&(i.minimum=o,typeof u=="number"&&t.target!=="draft-04"&&(u>=o?delete i.minimum:delete i.exclusiveMinimum)),typeof c=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c),typeof s=="number"&&(i.maximum=s,typeof c=="number"&&t.target!=="draft-04"&&(c<=s?delete i.maximum:delete i.exclusiveMaximum)),typeof l=="number"&&(i.multipleOf=l)},tS=(e,t,n,r)=>{n.type="boolean"},nS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},rS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},iS=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},oS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},sS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},aS=(e,t,n,r)=>{n.not={}},lS=(e,t,n,r)=>{},cS=(e,t,n,r)=>{},uS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},dS=(e,t,n,r)=>{let i=e._zod.def,o=kc(i.entries);o.every(s=>typeof s=="number")&&(n.type="number"),o.every(s=>typeof s=="string")&&(n.type="string"),n.enum=o},pS=(e,t,n,r)=>{let i=e._zod.def,o=[];for(let s of i.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(s))}else o.push(s);if(o.length!==0)if(o.length===1){let s=o[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else o.every(s=>typeof s=="number")&&(n.type="number"),o.every(s=>typeof s=="string")&&(n.type="string"),o.every(s=>typeof s=="boolean")&&(n.type="boolean"),o.every(s=>s===null)&&(n.type="null"),n.enum=o},fS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},mS=(e,t,n,r)=>{let i=n,o=e._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=o.source},gS=(e,t,n,r)=>{let i=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:l}=e._zod.bag;s!==void 0&&(o.minLength=s),a!==void 0&&(o.maxLength=a),l?l.length===1?(o.contentMediaType=l[0],Object.assign(i,o)):(Object.assign(i,o),i.anyOf=l.map(c=>({contentMediaType:c}))):Object.assign(i,o)},hS=(e,t,n,r)=>{n.type="boolean"},yS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},vS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},kS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},wS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},bS=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},_S=(e,t,n,r)=>{let i=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;typeof s=="number"&&(i.minItems=s),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=be(o.element,t,{...r,path:[...r.path,"items"]})},SS=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object",i.properties={};let s=o.shape;for(let c in s)i.properties[c]=be(s[c],t,{...r,path:[...r.path,"properties",c]});let a=new Set(Object.keys(s)),l=new Set([...a].filter(c=>{let u=o.shape[c]._zod;return t.io==="input"?u.optin===void 0:u.optout===void 0}));l.size>0&&(i.required=Array.from(l)),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=be(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},pm=(e,t,n,r)=>{let i=e._zod.def,o=i.inclusive===!1,s=i.options.map((a,l)=>be(a,t,{...r,path:[...r.path,o?"oneOf":"anyOf",l]}));o?n.oneOf=s:n.anyOf=s},xS=(e,t,n,r)=>{let i=e._zod.def,o=be(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=be(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,l=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];n.allOf=l},CS=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",l=o.items.map((p,m)=>be(p,t,{...r,path:[...r.path,s,m]})),c=o.rest?be(o.rest,t,{...r,path:[...r.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null;t.target==="draft-2020-12"?(i.prefixItems=l,c&&(i.items=c)):t.target==="openapi-3.0"?(i.items={anyOf:l},c&&i.items.anyOf.push(c),i.minItems=l.length,c||(i.maxItems=l.length)):(i.items=l,c&&(i.additionalItems=c));let{minimum:u,maximum:d}=e._zod.bag;typeof u=="number"&&(i.minItems=u),typeof d=="number"&&(i.maxItems=d)},IS=(e,t,n,r)=>{let i=n,o=e._zod.def;i.type="object";let s=o.keyType,l=s._zod.bag?.patterns;if(o.mode==="loose"&&l&&l.size>0){let u=be(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(let d of l)i.patternProperties[d.source]=u}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=be(o.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=be(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]});let c=s._zod.values;if(c){let u=[...c].filter(d=>typeof d=="string"||typeof d=="number");u.length>0&&(i.required=u)}},PS=(e,t,n,r)=>{let i=e._zod.def,o=be(i.innerType,t,r),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},AS=(e,t,n,r)=>{let i=e._zod.def;be(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},RS=(e,t,n,r)=>{let i=e._zod.def;be(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},ES=(e,t,n,r)=>{let i=e._zod.def;be(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},$S=(e,t,n,r)=>{let i=e._zod.def;be(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},DS=(e,t,n,r)=>{let i=e._zod.def,o=t.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;be(o,t,r);let s=t.seen.get(e);s.ref=o},TS=(e,t,n,r)=>{let i=e._zod.def;be(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType,n.readOnly=!0},OS=(e,t,n,r)=>{let i=e._zod.def;be(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},fm=(e,t,n,r)=>{let i=e._zod.def;be(i.innerType,t,r);let o=t.seen.get(e);o.ref=i.innerType},LS=(e,t,n,r)=>{let i=e._zod.innerType;be(i,t,r);let o=t.seen.get(e);o.ref=i},dm={string:Q_,number:eS,boolean:tS,bigint:nS,symbol:rS,null:iS,undefined:oS,void:sS,never:aS,any:lS,unknown:cS,date:uS,enum:dS,literal:pS,nan:fS,template_literal:mS,file:gS,success:hS,custom:yS,function:vS,transform:kS,map:wS,set:bS,array:_S,object:SS,union:pm,intersection:xS,tuple:CS,record:IS,nullable:PS,nonoptional:AS,default:RS,prefault:ES,catch:$S,pipe:DS,readonly:TS,promise:OS,optional:fm,lazy:LS};function mm(e,t){if("_idmap"in e){let r=e,i=vi({...t,processors:dm}),o={};for(let l of r._idmap.entries()){let[c,u]=l;be(u,i)}let s={},a={registry:r,uri:t?.uri,defs:o};i.external=a;for(let l of r._idmap.entries()){let[c,u]=l;ki(i,u),s[c]=wi(i,u)}if(Object.keys(o).length>0){let l=i.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:o}}return{schemas:s}}let n=vi({...t,processors:dm});return be(e,n),ki(n,e),wi(n,e)}var gm=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(t){this.ctx.counter=t}get seen(){return this.ctx.seen}constructor(t){let n=t?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=vi({processors:dm,target:n,...t?.metadata&&{metadata:t.metadata},...t?.unrepresentable&&{unrepresentable:t.unrepresentable},...t?.override&&{override:t.override},...t?.io&&{io:t.io}})}process(t,n={path:[],schemaPath:[]}){return be(t,this.ctx,n)}emit(t,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),ki(this.ctx,t);let r=wi(this.ctx,t),{"~standard":i,...o}=r;return o}};var xO={};var Nc={};Vn(Nc,{ZodAny:()=>ox,ZodArray:()=>cx,ZodBase64:()=>jm,ZodBase64URL:()=>Nm,ZodBigInt:()=>sa,ZodBigIntFormat:()=>Mm,ZodBoolean:()=>oa,ZodCIDRv4:()=>Om,ZodCIDRv6:()=>Lm,ZodCUID:()=>Pm,ZodCUID2:()=>Am,ZodCatch:()=>$x,ZodCodec:()=>Wm,ZodCustom:()=>Wc,ZodCustomStringFormat:()=>ra,ZodDate:()=>qc,ZodDefault:()=>Cx,ZodDiscriminatedUnion:()=>dx,ZodE164:()=>Fm,ZodEmail:()=>xm,ZodEmoji:()=>Cm,ZodEnum:()=>ta,ZodExactOptional:()=>_x,ZodFile:()=>wx,ZodFunction:()=>Mx,ZodGUID:()=>Fc,ZodIPv4:()=>Dm,ZodIPv6:()=>Tm,ZodIntersection:()=>px,ZodJWT:()=>Bm,ZodKSUID:()=>$m,ZodLazy:()=>Nx,ZodLiteral:()=>kx,ZodMAC:()=>XS,ZodMap:()=>yx,ZodNaN:()=>Tx,ZodNanoID:()=>Im,ZodNever:()=>ax,ZodNonOptional:()=>Hm,ZodNull:()=>rx,ZodNullable:()=>xx,ZodNumber:()=>ia,ZodNumberFormat:()=>uo,ZodObject:()=>Gc,ZodOptional:()=>Gm,ZodPipe:()=>Km,ZodPrefault:()=>Px,ZodPromise:()=>Bx,ZodReadonly:()=>Ox,ZodRecord:()=>Kc,ZodSet:()=>vx,ZodString:()=>na,ZodStringFormat:()=>Se,ZodSuccess:()=>Ex,ZodSymbol:()=>tx,ZodTemplateLiteral:()=>jx,ZodTransform:()=>bx,ZodTuple:()=>mx,ZodType:()=>se,ZodULID:()=>Rm,ZodURL:()=>zc,ZodUUID:()=>tr,ZodUndefined:()=>nx,ZodUnion:()=>Hc,ZodUnknown:()=>sx,ZodVoid:()=>lx,ZodXID:()=>Em,ZodXor:()=>ux,_ZodString:()=>Sm,_default:()=>Ix,_function:()=>$L,any:()=>cL,array:()=>Vc,base64:()=>HO,base64url:()=>KO,bigint:()=>iL,boolean:()=>ex,catch:()=>Dx,check:()=>DL,cidrv4:()=>VO,cidrv6:()=>GO,codec:()=>AL,cuid:()=>jO,cuid2:()=>NO,custom:()=>TL,date:()=>dL,describe:()=>OL,discriminatedUnion:()=>yL,e164:()=>WO,email:()=>IO,emoji:()=>OO,enum:()=>qm,exactOptional:()=>Sx,file:()=>xL,float32:()=>eL,float64:()=>tL,function:()=>$L,guid:()=>PO,hash:()=>QO,hex:()=>XO,hostname:()=>YO,httpUrl:()=>TO,instanceof:()=>jL,int:()=>_m,int32:()=>nL,int64:()=>oL,intersection:()=>fx,ipv4:()=>UO,ipv6:()=>qO,json:()=>FL,jwt:()=>ZO,keyof:()=>pL,ksuid:()=>MO,lazy:()=>Fx,literal:()=>SL,looseObject:()=>gL,looseRecord:()=>kL,mac:()=>zO,map:()=>wL,meta:()=>LL,nan:()=>PL,nanoid:()=>LO,nativeEnum:()=>_L,never:()=>Um,nonoptional:()=>Rx,null:()=>ix,nullable:()=>Mc,nullish:()=>CL,number:()=>QS,object:()=>fL,optional:()=>Bc,partialRecord:()=>vL,pipe:()=>Uc,prefault:()=>Ax,preprocess:()=>BL,promise:()=>EL,readonly:()=>Lx,record:()=>hx,refine:()=>Ux,set:()=>bL,strictObject:()=>mL,string:()=>bm,stringFormat:()=>JO,stringbool:()=>NL,success:()=>IL,superRefine:()=>zx,symbol:()=>aL,templateLiteral:()=>RL,transform:()=>Vm,tuple:()=>gx,uint32:()=>rL,uint64:()=>sL,ulid:()=>FO,undefined:()=>lL,union:()=>zm,unknown:()=>co,url:()=>DO,uuid:()=>AO,uuidv4:()=>RO,uuidv6:()=>EO,uuidv7:()=>$O,void:()=>uL,xid:()=>BO,xor:()=>hL});var hm={};Vn(hm,{endsWith:()=>Gs,gt:()=>Qn,gte:()=>Pt,includes:()=>qs,length:()=>lo,lowercase:()=>Us,lt:()=>Xn,lte:()=>rn,maxLength:()=>ao,maxSize:()=>yi,mime:()=>Hs,minLength:()=>Ar,minSize:()=>er,multipleOf:()=>hi,negative:()=>am,nonnegative:()=>cm,nonpositive:()=>lm,normalize:()=>Ks,overwrite:()=>jn,positive:()=>sm,property:()=>um,regex:()=>Ms,size:()=>so,slugify:()=>Ys,startsWith:()=>Vs,toLowerCase:()=>Zs,toUpperCase:()=>Js,trim:()=>Ws,uppercase:()=>zs});var ea={};Vn(ea,{ZodISODate:()=>vm,ZodISODateTime:()=>ym,ZodISODuration:()=>wm,ZodISOTime:()=>km,date:()=>NS,datetime:()=>jS,duration:()=>BS,time:()=>FS});var ym=I("ZodISODateTime",(e,t)=>{fb.init(e,t),Se.init(e,t)});function jS(e){return y_(ym,e)}var vm=I("ZodISODate",(e,t)=>{mb.init(e,t),Se.init(e,t)});function NS(e){return v_(vm,e)}var km=I("ZodISOTime",(e,t)=>{gb.init(e,t),Se.init(e,t)});function FS(e){return k_(km,e)}var wm=I("ZodISODuration",(e,t)=>{hb.init(e,t),Se.init(e,t)});function BS(e){return w_(wm,e)}var CO=(e,t)=>{xc.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Ic(e,n)},flatten:{value:n=>Cc(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,$s,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,$s,2)}},isEmpty:{get(){return e.issues.length===0}}})},lJ=I("ZodError",CO),Kt=I("ZodError",CO,{Parent:Error});var MS=Os(Kt),US=Ls(Kt),zS=js(Kt),qS=Ns(Kt),VS=mf(Kt),GS=gf(Kt),HS=hf(Kt),KS=yf(Kt),WS=vf(Kt),ZS=kf(Kt),JS=wf(Kt),YS=bf(Kt);var se=I("ZodType",(e,t)=>(oe.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Qs(e,"input"),output:Qs(e,"output")}}),e.toJSONSchema=X_(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(M.mergeDefs(t,{checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0}),e.with=e.check,e.clone=(n,r)=>It(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>MS(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>zS(e,n,r),e.parseAsync=async(n,r)=>US(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>qS(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>VS(e,n,r),e.decode=(n,r)=>GS(e,n,r),e.encodeAsync=async(n,r)=>HS(e,n,r),e.decodeAsync=async(n,r)=>KS(e,n,r),e.safeEncode=(n,r)=>WS(e,n,r),e.safeDecode=(n,r)=>ZS(e,n,r),e.safeEncodeAsync=async(n,r)=>JS(e,n,r),e.safeDecodeAsync=async(n,r)=>YS(e,n,r),e.refine=(n,r)=>e.check(Ux(n,r)),e.superRefine=n=>e.check(zx(n)),e.overwrite=n=>e.check(jn(n)),e.optional=()=>Bc(e),e.exactOptional=()=>Sx(e),e.nullable=()=>Mc(e),e.nullish=()=>Bc(Mc(e)),e.nonoptional=n=>Rx(e,n),e.array=()=>Vc(e),e.or=n=>zm([e,n]),e.and=n=>fx(e,n),e.transform=n=>Uc(e,Vm(n)),e.default=n=>Ix(e,n),e.prefault=n=>Ax(e,n),e.catch=n=>Dx(e,n),e.pipe=n=>Uc(e,n),e.readonly=()=>Lx(e),e.describe=n=>{let r=e.clone();return pt.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return pt.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return pt.get(e);let r=e.clone();return pt.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),Sm=I("_ZodString",(e,t)=>{oo.init(e,t),se.init(e,t),e._zod.processJSONSchema=(r,i,o)=>Q_(e,r,i,o);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(Ms(...r)),e.includes=(...r)=>e.check(qs(...r)),e.startsWith=(...r)=>e.check(Vs(...r)),e.endsWith=(...r)=>e.check(Gs(...r)),e.min=(...r)=>e.check(Ar(...r)),e.max=(...r)=>e.check(ao(...r)),e.length=(...r)=>e.check(lo(...r)),e.nonempty=(...r)=>e.check(Ar(1,...r)),e.lowercase=r=>e.check(Us(r)),e.uppercase=r=>e.check(zs(r)),e.trim=()=>e.check(Ws()),e.normalize=(...r)=>e.check(Ks(...r)),e.toLowerCase=()=>e.check(Zs()),e.toUpperCase=()=>e.check(Js()),e.slugify=()=>e.check(Ys())}),na=I("ZodString",(e,t)=>{oo.init(e,t),Sm.init(e,t),e.email=n=>e.check(Mf(xm,n)),e.url=n=>e.check(jc(zc,n)),e.jwt=n=>e.check(om(Bm,n)),e.emoji=n=>e.check(Gf(Cm,n)),e.guid=n=>e.check(Lc(Fc,n)),e.uuid=n=>e.check(Uf(tr,n)),e.uuidv4=n=>e.check(zf(tr,n)),e.uuidv6=n=>e.check(qf(tr,n)),e.uuidv7=n=>e.check(Vf(tr,n)),e.nanoid=n=>e.check(Hf(Im,n)),e.guid=n=>e.check(Lc(Fc,n)),e.cuid=n=>e.check(Kf(Pm,n)),e.cuid2=n=>e.check(Wf(Am,n)),e.ulid=n=>e.check(Zf(Rm,n)),e.base64=n=>e.check(nm(jm,n)),e.base64url=n=>e.check(rm(Nm,n)),e.xid=n=>e.check(Jf(Em,n)),e.ksuid=n=>e.check(Yf($m,n)),e.ipv4=n=>e.check(Xf(Dm,n)),e.ipv6=n=>e.check(Qf(Tm,n)),e.cidrv4=n=>e.check(em(Om,n)),e.cidrv6=n=>e.check(tm(Lm,n)),e.e164=n=>e.check(im(Fm,n)),e.datetime=n=>e.check(jS(n)),e.date=n=>e.check(NS(n)),e.time=n=>e.check(FS(n)),e.duration=n=>e.check(BS(n))});function bm(e){return f_(na,e)}var Se=I("ZodStringFormat",(e,t)=>{_e.init(e,t),Sm.init(e,t)}),xm=I("ZodEmail",(e,t)=>{ib.init(e,t),Se.init(e,t)});function IO(e){return Mf(xm,e)}var Fc=I("ZodGUID",(e,t)=>{nb.init(e,t),Se.init(e,t)});function PO(e){return Lc(Fc,e)}var tr=I("ZodUUID",(e,t)=>{rb.init(e,t),Se.init(e,t)});function AO(e){return Uf(tr,e)}function RO(e){return zf(tr,e)}function EO(e){return qf(tr,e)}function $O(e){return Vf(tr,e)}var zc=I("ZodURL",(e,t)=>{ob.init(e,t),Se.init(e,t)});function DO(e){return jc(zc,e)}function TO(e){return jc(zc,{protocol:/^https?$/,hostname:wn.domain,...M.normalizeParams(e)})}var Cm=I("ZodEmoji",(e,t)=>{sb.init(e,t),Se.init(e,t)});function OO(e){return Gf(Cm,e)}var Im=I("ZodNanoID",(e,t)=>{ab.init(e,t),Se.init(e,t)});function LO(e){return Hf(Im,e)}var Pm=I("ZodCUID",(e,t)=>{lb.init(e,t),Se.init(e,t)});function jO(e){return Kf(Pm,e)}var Am=I("ZodCUID2",(e,t)=>{cb.init(e,t),Se.init(e,t)});function NO(e){return Wf(Am,e)}var Rm=I("ZodULID",(e,t)=>{ub.init(e,t),Se.init(e,t)});function FO(e){return Zf(Rm,e)}var Em=I("ZodXID",(e,t)=>{db.init(e,t),Se.init(e,t)});function BO(e){return Jf(Em,e)}var $m=I("ZodKSUID",(e,t)=>{pb.init(e,t),Se.init(e,t)});function MO(e){return Yf($m,e)}var Dm=I("ZodIPv4",(e,t)=>{yb.init(e,t),Se.init(e,t)});function UO(e){return Xf(Dm,e)}var XS=I("ZodMAC",(e,t)=>{kb.init(e,t),Se.init(e,t)});function zO(e){return g_(XS,e)}var Tm=I("ZodIPv6",(e,t)=>{vb.init(e,t),Se.init(e,t)});function qO(e){return Qf(Tm,e)}var Om=I("ZodCIDRv4",(e,t)=>{wb.init(e,t),Se.init(e,t)});function VO(e){return em(Om,e)}var Lm=I("ZodCIDRv6",(e,t)=>{bb.init(e,t),Se.init(e,t)});function GO(e){return tm(Lm,e)}var jm=I("ZodBase64",(e,t)=>{Sb.init(e,t),Se.init(e,t)});function HO(e){return nm(jm,e)}var Nm=I("ZodBase64URL",(e,t)=>{xb.init(e,t),Se.init(e,t)});function KO(e){return rm(Nm,e)}var Fm=I("ZodE164",(e,t)=>{Cb.init(e,t),Se.init(e,t)});function WO(e){return im(Fm,e)}var Bm=I("ZodJWT",(e,t)=>{Ib.init(e,t),Se.init(e,t)});function ZO(e){return om(Bm,e)}var ra=I("ZodCustomStringFormat",(e,t)=>{Pb.init(e,t),Se.init(e,t)});function JO(e,t,n={}){return Xs(ra,e,t,n)}function YO(e){return Xs(ra,"hostname",wn.hostname,e)}function XO(e){return Xs(ra,"hex",wn.hex,e)}function QO(e,t){let n=t?.enc??"hex",r=`${e}_${n}`,i=wn[r];if(!i)throw new Error(`Unrecognized hash format: ${r}`);return Xs(ra,r,i,t)}var ia=I("ZodNumber",(e,t)=>{$f.init(e,t),se.init(e,t),e._zod.processJSONSchema=(r,i,o)=>eS(e,r,i,o),e.gt=(r,i)=>e.check(Qn(r,i)),e.gte=(r,i)=>e.check(Pt(r,i)),e.min=(r,i)=>e.check(Pt(r,i)),e.lt=(r,i)=>e.check(Xn(r,i)),e.lte=(r,i)=>e.check(rn(r,i)),e.max=(r,i)=>e.check(rn(r,i)),e.int=r=>e.check(_m(r)),e.safe=r=>e.check(_m(r)),e.positive=r=>e.check(Qn(0,r)),e.nonnegative=r=>e.check(Pt(0,r)),e.negative=r=>e.check(Xn(0,r)),e.nonpositive=r=>e.check(rn(0,r)),e.multipleOf=(r,i)=>e.check(hi(r,i)),e.step=(r,i)=>e.check(hi(r,i)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function QS(e){return b_(ia,e)}var uo=I("ZodNumberFormat",(e,t)=>{Ab.init(e,t),ia.init(e,t)});function _m(e){return S_(uo,e)}function eL(e){return x_(uo,e)}function tL(e){return C_(uo,e)}function nL(e){return I_(uo,e)}function rL(e){return P_(uo,e)}var oa=I("ZodBoolean",(e,t)=>{Ec.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>tS(e,n,r,i)});function ex(e){return A_(oa,e)}var sa=I("ZodBigInt",(e,t)=>{Df.init(e,t),se.init(e,t),e._zod.processJSONSchema=(r,i,o)=>nS(e,r,i,o),e.gte=(r,i)=>e.check(Pt(r,i)),e.min=(r,i)=>e.check(Pt(r,i)),e.gt=(r,i)=>e.check(Qn(r,i)),e.gte=(r,i)=>e.check(Pt(r,i)),e.min=(r,i)=>e.check(Pt(r,i)),e.lt=(r,i)=>e.check(Xn(r,i)),e.lte=(r,i)=>e.check(rn(r,i)),e.max=(r,i)=>e.check(rn(r,i)),e.positive=r=>e.check(Qn(BigInt(0),r)),e.negative=r=>e.check(Xn(BigInt(0),r)),e.nonpositive=r=>e.check(rn(BigInt(0),r)),e.nonnegative=r=>e.check(Pt(BigInt(0),r)),e.multipleOf=(r,i)=>e.check(hi(r,i));let n=e._zod.bag;e.minValue=n.minimum??null,e.maxValue=n.maximum??null,e.format=n.format??null});function iL(e){return E_(sa,e)}var Mm=I("ZodBigIntFormat",(e,t)=>{Rb.init(e,t),sa.init(e,t)});function oL(e){return D_(Mm,e)}function sL(e){return T_(Mm,e)}var tx=I("ZodSymbol",(e,t)=>{Eb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>rS(e,n,r,i)});function aL(e){return O_(tx,e)}var nx=I("ZodUndefined",(e,t)=>{$b.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>oS(e,n,r,i)});function lL(e){return L_(nx,e)}var rx=I("ZodNull",(e,t)=>{Db.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>iS(e,n,r,i)});function ix(e){return j_(rx,e)}var ox=I("ZodAny",(e,t)=>{Tb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>lS(e,n,r,i)});function cL(){return N_(ox)}var sx=I("ZodUnknown",(e,t)=>{Ob.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>cS(e,n,r,i)});function co(){return F_(sx)}var ax=I("ZodNever",(e,t)=>{Lb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>aS(e,n,r,i)});function Um(e){return B_(ax,e)}var lx=I("ZodVoid",(e,t)=>{jb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>sS(e,n,r,i)});function uL(e){return M_(lx,e)}var qc=I("ZodDate",(e,t)=>{Nb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(r,i,o)=>uS(e,r,i,o),e.min=(r,i)=>e.check(Pt(r,i)),e.max=(r,i)=>e.check(rn(r,i));let n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null});function dL(e){return U_(qc,e)}var cx=I("ZodArray",(e,t)=>{Fb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_S(e,n,r,i),e.element=t.element,e.min=(n,r)=>e.check(Ar(n,r)),e.nonempty=n=>e.check(Ar(1,n)),e.max=(n,r)=>e.check(ao(n,r)),e.length=(n,r)=>e.check(lo(n,r)),e.unwrap=()=>e.element});function Vc(e,t){return V_(cx,e,t)}function pL(e){let t=e._zod.def.shape;return qm(Object.keys(t))}var Gc=I("ZodObject",(e,t)=>{Bb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SS(e,n,r,i),M.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>qm(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:co()}),e.loose=()=>e.clone({...e._zod.def,catchall:co()}),e.strict=()=>e.clone({...e._zod.def,catchall:Um()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>M.extend(e,n),e.safeExtend=n=>M.safeExtend(e,n),e.merge=n=>M.merge(e,n),e.pick=n=>M.pick(e,n),e.omit=n=>M.omit(e,n),e.partial=(...n)=>M.partial(Gm,e,n[0]),e.required=(...n)=>M.required(Hm,e,n[0])});function fL(e,t){let n={type:"object",shape:e??{},...M.normalizeParams(t)};return new Gc(n)}function mL(e,t){return new Gc({type:"object",shape:e,catchall:Um(),...M.normalizeParams(t)})}function gL(e,t){return new Gc({type:"object",shape:e,catchall:co(),...M.normalizeParams(t)})}var Hc=I("ZodUnion",(e,t)=>{$c.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pm(e,n,r,i),e.options=t.options});function zm(e,t){return new Hc({type:"union",options:e,...M.normalizeParams(t)})}var ux=I("ZodXor",(e,t)=>{Hc.init(e,t),Mb.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pm(e,n,r,i),e.options=t.options});function hL(e,t){return new ux({type:"union",options:e,inclusive:!1,...M.normalizeParams(t)})}var dx=I("ZodDiscriminatedUnion",(e,t)=>{Hc.init(e,t),Ub.init(e,t)});function yL(e,t,n){return new dx({type:"union",options:t,discriminator:e,...M.normalizeParams(n)})}var px=I("ZodIntersection",(e,t)=>{zb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xS(e,n,r,i)});function fx(e,t){return new px({type:"intersection",left:e,right:t})}var mx=I("ZodTuple",(e,t)=>{Tf.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CS(e,n,r,i),e.rest=n=>e.clone({...e._zod.def,rest:n})});function gx(e,t,n){let r=t instanceof oe,i=r?n:t,o=r?t:null;return new mx({type:"tuple",items:e,rest:o,...M.normalizeParams(i)})}var Kc=I("ZodRecord",(e,t)=>{qb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>IS(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function hx(e,t,n){return new Kc({type:"record",keyType:e,valueType:t,...M.normalizeParams(n)})}function vL(e,t,n){let r=It(e);return r._zod.values=void 0,new Kc({type:"record",keyType:r,valueType:t,...M.normalizeParams(n)})}function kL(e,t,n){return new Kc({type:"record",keyType:e,valueType:t,mode:"loose",...M.normalizeParams(n)})}var yx=I("ZodMap",(e,t)=>{Vb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wS(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...n)=>e.check(er(...n)),e.nonempty=n=>e.check(er(1,n)),e.max=(...n)=>e.check(yi(...n)),e.size=(...n)=>e.check(so(...n))});function wL(e,t,n){return new yx({type:"map",keyType:e,valueType:t,...M.normalizeParams(n)})}var vx=I("ZodSet",(e,t)=>{Gb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bS(e,n,r,i),e.min=(...n)=>e.check(er(...n)),e.nonempty=n=>e.check(er(1,n)),e.max=(...n)=>e.check(yi(...n)),e.size=(...n)=>e.check(so(...n))});function bL(e,t){return new vx({type:"set",valueType:e,...M.normalizeParams(t)})}var ta=I("ZodEnum",(e,t)=>{Hb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(r,i,o)=>dS(e,r,i,o),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{let o={};for(let s of r)if(n.has(s))o[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ta({...t,checks:[],...M.normalizeParams(i),entries:o})},e.exclude=(r,i)=>{let o={...t.entries};for(let s of r)if(n.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new ta({...t,checks:[],...M.normalizeParams(i),entries:o})}});function qm(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new ta({type:"enum",entries:n,...M.normalizeParams(t)})}function _L(e,t){return new ta({type:"enum",entries:e,...M.normalizeParams(t)})}var kx=I("ZodLiteral",(e,t)=>{Kb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pS(e,n,r,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function SL(e,t){return new kx({type:"literal",values:Array.isArray(e)?e:[e],...M.normalizeParams(t)})}var wx=I("ZodFile",(e,t)=>{Wb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gS(e,n,r,i),e.min=(n,r)=>e.check(er(n,r)),e.max=(n,r)=>e.check(yi(n,r)),e.mime=(n,r)=>e.check(Hs(Array.isArray(n)?n:[n],r))});function xL(e){return G_(wx,e)}var bx=I("ZodTransform",(e,t)=>{Zb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kS(e,n,r,i),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new di(e.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(M.issue(o,n.value,t));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(M.issue(s))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(o=>(n.value=o,n)):(n.value=i,n)}});function Vm(e){return new bx({type:"transform",transform:e})}var Gm=I("ZodOptional",(e,t)=>{Of.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>fm(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Bc(e){return new Gm({type:"optional",innerType:e})}var _x=I("ZodExactOptional",(e,t)=>{Jb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>fm(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Sx(e){return new _x({type:"optional",innerType:e})}var xx=I("ZodNullable",(e,t)=>{Yb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>PS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Mc(e){return new xx({type:"nullable",innerType:e})}function CL(e){return Bc(Mc(e))}var Cx=I("ZodDefault",(e,t)=>{Xb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ix(e,t){return new Cx({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():M.shallowClone(t)}})}var Px=I("ZodPrefault",(e,t)=>{Qb.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>ES(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Ax(e,t){return new Px({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():M.shallowClone(t)}})}var Hm=I("ZodNonOptional",(e,t)=>{e_.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>AS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Rx(e,t){return new Hm({type:"nonoptional",innerType:e,...M.normalizeParams(t)})}var Ex=I("ZodSuccess",(e,t)=>{t_.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>hS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function IL(e){return new Ex({type:"success",innerType:e})}var $x=I("ZodCatch",(e,t)=>{n_.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>$S(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Dx(e,t){return new $x({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Tx=I("ZodNaN",(e,t)=>{r_.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>fS(e,n,r,i)});function PL(e){return q_(Tx,e)}var Km=I("ZodPipe",(e,t)=>{i_.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>DS(e,n,r,i),e.in=t.in,e.out=t.out});function Uc(e,t){return new Km({type:"pipe",in:e,out:t})}var Wm=I("ZodCodec",(e,t)=>{Km.init(e,t),Dc.init(e,t)});function AL(e,t,n){return new Wm({type:"pipe",in:e,out:t,transform:n.decode,reverseTransform:n.encode})}var Ox=I("ZodReadonly",(e,t)=>{o_.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function Lx(e){return new Ox({type:"readonly",innerType:e})}var jx=I("ZodTemplateLiteral",(e,t)=>{s_.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mS(e,n,r,i)});function RL(e,t){return new jx({type:"template_literal",parts:e,...M.normalizeParams(t)})}var Nx=I("ZodLazy",(e,t)=>{c_.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>LS(e,n,r,i),e.unwrap=()=>e._zod.def.getter()});function Fx(e){return new Nx({type:"lazy",getter:e})}var Bx=I("ZodPromise",(e,t)=>{l_.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>OS(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function EL(e){return new Bx({type:"promise",innerType:e})}var Mx=I("ZodFunction",(e,t)=>{a_.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vS(e,n,r,i)});function $L(e){return new Mx({type:"function",input:Array.isArray(e?.input)?gx(e?.input):e?.input??Vc(co()),output:e?.output??co()})}var Wc=I("ZodCustom",(e,t)=>{u_.init(e,t),se.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yS(e,n,r,i)});function DL(e){let t=new Ie({check:"custom"});return t._zod.check=e,t}function TL(e,t){return H_(Wc,e??(()=>!0),t)}function Ux(e,t={}){return K_(Wc,e,t)}function zx(e){return W_(e)}var OL=Z_,LL=J_;function jL(e,t={}){let n=new Wc({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...M.normalizeParams(t)});return n._zod.bag.Class=e,n._zod.check=r=>{r.value instanceof e||r.issues.push({code:"invalid_type",expected:e.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}var NL=(...e)=>Y_({Codec:Wm,Boolean:oa,String:na},...e);function FL(e){let t=Fx(()=>zm([bm(e),QS(),ex(),ix(),Vc(t),hx(bm(),t)]));return t}function BL(e,t){return Uc(Vm(e),t)}var uJ={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function dJ(e){je({customError:e})}function pJ(){return je().customError}var qx;qx||(qx={});var q={...Nc,...hm,iso:ea},fJ=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function mJ(e,t){let n=e.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":t??"draft-2020-12"}function gJ(e,t){if(!e.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let n=e.slice(1).split("/").filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===r){let i=n[1];if(!i||!t.defs[i])throw new Error(`Reference not found: ${e}`);return t.defs[i]}throw new Error(`Reference not found: ${e}`)}function ML(e,t){if(e.not!==void 0){if(typeof e.not=="object"&&Object.keys(e.not).length===0)return q.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(e.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(e.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(e.$ref){let i=e.$ref;if(t.refs.has(i))return t.refs.get(i);if(t.processing.has(i))return q.lazy(()=>{if(!t.refs.has(i))throw new Error(`Circular reference not resolved: ${i}`);return t.refs.get(i)});t.processing.add(i);let o=gJ(i,t),s=_t(o,t);return t.refs.set(i,s),t.processing.delete(i),s}if(e.enum!==void 0){let i=e.enum;if(t.version==="openapi-3.0"&&e.nullable===!0&&i.length===1&&i[0]===null)return q.null();if(i.length===0)return q.never();if(i.length===1)return q.literal(i[0]);if(i.every(s=>typeof s=="string"))return q.enum(i);let o=i.map(s=>q.literal(s));return o.length<2?o[0]:q.union([o[0],o[1],...o.slice(2)])}if(e.const!==void 0)return q.literal(e.const);let n=e.type;if(Array.isArray(n)){let i=n.map(o=>{let s={...e,type:o};return ML(s,t)});return i.length===0?q.never():i.length===1?i[0]:q.union(i)}if(!n)return q.any();let r;switch(n){case"string":{let i=q.string();if(e.format){let o=e.format;o==="email"?i=i.check(q.email()):o==="uri"||o==="uri-reference"?i=i.check(q.url()):o==="uuid"||o==="guid"?i=i.check(q.uuid()):o==="date-time"?i=i.check(q.iso.datetime()):o==="date"?i=i.check(q.iso.date()):o==="time"?i=i.check(q.iso.time()):o==="duration"?i=i.check(q.iso.duration()):o==="ipv4"?i=i.check(q.ipv4()):o==="ipv6"?i=i.check(q.ipv6()):o==="mac"?i=i.check(q.mac()):o==="cidr"?i=i.check(q.cidrv4()):o==="cidr-v6"?i=i.check(q.cidrv6()):o==="base64"?i=i.check(q.base64()):o==="base64url"?i=i.check(q.base64url()):o==="e164"?i=i.check(q.e164()):o==="jwt"?i=i.check(q.jwt()):o==="emoji"?i=i.check(q.emoji()):o==="nanoid"?i=i.check(q.nanoid()):o==="cuid"?i=i.check(q.cuid()):o==="cuid2"?i=i.check(q.cuid2()):o==="ulid"?i=i.check(q.ulid()):o==="xid"?i=i.check(q.xid()):o==="ksuid"&&(i=i.check(q.ksuid()))}typeof e.minLength=="number"&&(i=i.min(e.minLength)),typeof e.maxLength=="number"&&(i=i.max(e.maxLength)),e.pattern&&(i=i.regex(new RegExp(e.pattern))),r=i;break}case"number":case"integer":{let i=n==="integer"?q.number().int():q.number();typeof e.minimum=="number"&&(i=i.min(e.minimum)),typeof e.maximum=="number"&&(i=i.max(e.maximum)),typeof e.exclusiveMinimum=="number"?i=i.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum=="number"&&(i=i.gt(e.minimum)),typeof e.exclusiveMaximum=="number"?i=i.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum=="number"&&(i=i.lt(e.maximum)),typeof e.multipleOf=="number"&&(i=i.multipleOf(e.multipleOf)),r=i;break}case"boolean":{r=q.boolean();break}case"null":{r=q.null();break}case"object":{let i={},o=e.properties||{},s=new Set(e.required||[]);for(let[l,c]of Object.entries(o)){let u=_t(c,t);i[l]=s.has(l)?u:u.optional()}if(e.propertyNames){let l=_t(e.propertyNames,t),c=e.additionalProperties&&typeof e.additionalProperties=="object"?_t(e.additionalProperties,t):q.any();if(Object.keys(i).length===0){r=q.record(l,c);break}let u=q.object(i).passthrough(),d=q.looseRecord(l,c);r=q.intersection(u,d);break}if(e.patternProperties){let l=e.patternProperties,c=Object.keys(l),u=[];for(let p of c){let m=_t(l[p],t),h=q.string().regex(new RegExp(p));u.push(q.looseRecord(h,m))}let d=[];if(Object.keys(i).length>0&&d.push(q.object(i).passthrough()),d.push(...u),d.length===0)r=q.object({}).passthrough();else if(d.length===1)r=d[0];else{let p=q.intersection(d[0],d[1]);for(let m=2;m<d.length;m++)p=q.intersection(p,d[m]);r=p}break}let a=q.object(i);e.additionalProperties===!1?r=a.strict():typeof e.additionalProperties=="object"?r=a.catchall(_t(e.additionalProperties,t)):r=a.passthrough();break}case"array":{let i=e.prefixItems,o=e.items;if(i&&Array.isArray(i)){let s=i.map(l=>_t(l,t)),a=o&&typeof o=="object"&&!Array.isArray(o)?_t(o,t):void 0;a?r=q.tuple(s).rest(a):r=q.tuple(s),typeof e.minItems=="number"&&(r=r.check(q.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(q.maxLength(e.maxItems)))}else if(Array.isArray(o)){let s=o.map(l=>_t(l,t)),a=e.additionalItems&&typeof e.additionalItems=="object"?_t(e.additionalItems,t):void 0;a?r=q.tuple(s).rest(a):r=q.tuple(s),typeof e.minItems=="number"&&(r=r.check(q.minLength(e.minItems))),typeof e.maxItems=="number"&&(r=r.check(q.maxLength(e.maxItems)))}else if(o!==void 0){let s=_t(o,t),a=q.array(s);typeof e.minItems=="number"&&(a=a.min(e.minItems)),typeof e.maxItems=="number"&&(a=a.max(e.maxItems)),r=a}else r=q.array(q.any());break}default:throw new Error(`Unsupported type: ${n}`)}return e.description&&(r=r.describe(e.description)),e.default!==void 0&&(r=r.default(e.default)),r}function _t(e,t){if(typeof e=="boolean")return e?q.any():q.never();let n=ML(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let a=e.anyOf.map(c=>_t(c,t)),l=q.union(a);n=r?q.intersection(n,l):l}if(e.oneOf&&Array.isArray(e.oneOf)){let a=e.oneOf.map(c=>_t(c,t)),l=q.xor(a);n=r?q.intersection(n,l):l}if(e.allOf&&Array.isArray(e.allOf))if(e.allOf.length===0)n=r?n:q.any();else{let a=r?n:_t(e.allOf[0],t),l=r?0:1;for(let c=l;c<e.allOf.length;c++)a=q.intersection(a,_t(e.allOf[c],t));n=a}e.nullable===!0&&t.version==="openapi-3.0"&&(n=q.nullable(n)),e.readOnly===!0&&(n=q.readonly(n));let i={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of o)a in e&&(i[a]=e[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in e&&(i[a]=e[a]);for(let a of Object.keys(e))fJ.has(a)||(i[a]=e[a]);return Object.keys(i).length>0&&t.registry.add(n,i),n}function UL(e,t){if(typeof e=="boolean")return e?q.any():q.never();let n=mJ(e,t?.defaultTarget),r=e.$defs||e.definitions||{},i={version:n,defs:r,refs:new Map,processing:new Set,rootSchema:e,registry:t?.registry??pt};return _t(e,i)}var Vx={};Vn(Vx,{bigint:()=>kJ,boolean:()=>vJ,date:()=>wJ,number:()=>yJ,string:()=>hJ});function hJ(e){return m_(na,e)}function yJ(e){return __(ia,e)}function vJ(e){return R_(oa,e)}function kJ(e){return $_(sa,e)}function wJ(e){return z_(qc,e)}je(Lf());import{createHash as bJ}from"node:crypto";var Wt="1.0",on=["security_safety","runtime_access_control","effectiveness_outcomes","trust_integrity"],ft={platformScore:"skills-layer-platform-score-v1",engine:"skills-layer-platform-score-engine-v1",policy:"skills-layer-platform-score-policy-v1",intake:"skills-layer-platform-intake-v1",intakeReceipt:"skills-layer-platform-intake-receipt-v1",authorityAdapter:"skills-layer-platform-authority-adapter-v1",report:"skills-layer-platform-score-report-v1",audienceProjection:"skills-layer-platform-score-projection-v1",machineReport:"skills-layer-platform-score-json-v1",parityManifest:"skills-layer-platform-score-parity-v1",securitySarif:"skills-layer-security-sarif-v1",signedPassport:"skills-layer-skill-passport-v1",signedProvenance:"skills-layer-source-process-artifact-provenance-v1",authorityReference:"skills-layer-platform-authority-reference-v1",statusRegistry:"skills-layer-platform-score-status-v1",compositionCatalogue:"skills-layer-platform-score-controls-v1",dimensionResults:{security_safety:"skills-layer-security-score-v1",runtime_access_control:"skills-layer-runtime-access-score-v1",effectiveness_outcomes:"skills-layer-effectiveness-score-v1",trust_integrity:"skills-layer-trust-integrity-score-v1"}},aa=["ready","ready_with_findings","provisional_evidence","action_required","blocked"],la=["available","withheld","unscored"],_J=["passed","passed_with_findings","pending","unavailable","failed","blocked","not_performed","not_applicable"],SJ=["mandatory","conditional","supplementary"],xJ=["applicable","conditional","not_applicable","unknown"],Zm=["current","stale","unknown","not_applicable"],CJ=["scored","evidence_only","composition_control"],Hx=["green","amber","red"];var IJ=[{controlId:"SL-PS-INPUT-001",family:"input_integrity",title:"Exact subject parity"},{controlId:"SL-PS-INPUT-002",family:"input_integrity",title:"Compatible score and policy versions"},{controlId:"SL-PS-INPUT-003",family:"input_integrity",title:"Dimension revision and digest verification"},{controlId:"SL-PS-INPUT-004",family:"input_integrity",title:"Latest eligible dimension heads"},{controlId:"SL-PS-INPUT-005",family:"input_integrity",title:"Mandatory baseline completeness"},{controlId:"SL-PS-ROUTE-001",family:"signal_routing",title:"One primary scoring owner"},{controlId:"SL-PS-ROUTE-002",family:"signal_routing",title:"Canonical signal and finding identity"},{controlId:"SL-PS-ROUTE-003",family:"signal_routing",title:"Cross-reference without duplicate deduction"},{controlId:"SL-PS-ROUTE-004",family:"signal_routing",title:"Cap linked to originating signal"},{controlId:"SL-PS-CALC-001",family:"calculation",title:"Four equal dimension weights"},{controlId:"SL-PS-CALC-002",family:"calculation",title:"Deterministic arithmetic and rounding"},{controlId:"SL-PS-CALC-003",family:"calculation",title:"Green eligibility ordering"},{controlId:"SL-PS-CALC-004",family:"calculation",title:"Safety and authority cap ordering"},{controlId:"SL-PS-CALC-005",family:"calculation",title:"Final decision and band consistency"},{controlId:"SL-PS-PUBLISH-001",family:"publication",title:"Immutable revision and supersession"},{controlId:"SL-PS-PUBLISH-002",family:"publication",title:"Canonical and audience projection digest parity"},{controlId:"SL-PS-PUBLISH-003",family:"publication",title:"Cross-surface report and revision parity"},{controlId:"SL-PS-PUBLISH-004",family:"publication",title:"Current acquisition authority"}];var PJ=[{reasonCode:"platform_score_ready",availability:"available",decision:"ready",nextActor:null},{reasonCode:"platform_score_ready_with_findings",availability:"available",decision:"ready_with_findings",nextActor:null},{reasonCode:"platform_score_required_dimension_withheld",availability:"withheld",decision:"provisional_evidence",nextActor:"platform"},{reasonCode:"score_rebuild_in_progress",availability:"withheld",decision:"provisional_evidence",nextActor:"platform"},{reasonCode:"platform_score_action_required",availability:"available",decision:"action_required",nextActor:"owner"},{reasonCode:"platform_score_blocked",availability:"withheld",decision:"blocked",nextActor:"operator"},{reasonCode:"unscored_local_source",availability:"unscored",decision:null,nextActor:null}],Zc={contractVersion:Wt,policyId:ft.policy,policyVersion:Wt,dimensionWeightsBasisPoints:{security_safety:2500,runtime_access_control:2500,effectiveness_outcomes:2500,trust_integrity:2500},rounding:"half_up",bands:{greenMinimum:90,amberMinimum:70},greenEligibility:{minimumRawScore:90,minimumSecurityScore:90,minimumRuntimeScore:90,minimumEffectivenessScore:70,minimumTrustScore:90,failedGateMaximumScore:89},compositionControlIds:IJ.map(e=>e.controlId)},Ghe=fo(Zc),bn=S.string().regex(/^sha256:[a-f0-9]{64}$/u),le=S.string().min(1),Jc=S.string().datetime({offset:!0}),po=S.number().min(0).max(100),bi=S.object({skillId:le,slug:le,skillVersionId:le,version:le,generationId:le,archiveSha256:bn,artifactDigest:bn,runtimeArtifactDigest:bn}).strict(),sn=S.object({authorityType:le,authorityId:le,revision:S.number().int().positive(),digest:bn,observedAt:Jc}).strict(),Kx=S.object({controlId:S.string().regex(/^SL-[A-Z0-9]+(?:-[A-Z0-9]+)*-[0-9]{3}$/u),title:le,status:S.enum(_J),nativeStatus:le.optional(),requirementClass:S.enum(SJ),applicability:S.enum(xJ),freshness:S.enum(Zm),freshnessDetails:S.object({verifiedAt:Jc.nullable(),validUntil:Jc.nullable(),invalidationTriggers:S.array(le).min(1),authorityRevision:S.number().int().positive(),trustRootPolicyVersion:le,staleEffect:S.enum(["withhold","cap","limitation"])}).strict().optional(),reasonCode:le,scoringRole:S.enum(CJ),signalIds:S.array(le),scoreContribution:S.number().optional(),authorityReferences:S.array(sn),limitations:S.array(le)}).strict(),Wx=S.object({policyId:le,policyVersion:le,policyDigest:bn,policyEpoch:le}).strict(),Zx=S.object({capId:le,reasonCode:le,maximumScore:po,sourceSignalId:le}).strict(),Jx=S.object({kind:S.enum(["deduction","weighted","blend"]),formula:le,rawScore:po.nullable(),rounding:le,components:S.array(S.object({key:le,label:le,value:S.number().nullable(),weight:S.number().min(0).max(1).optional()}).strict()),deductions:S.array(S.object({sourceId:le,amount:S.number().nonnegative()}).strict()),outcomes:S.object({confidence:S.enum(["platform_baseline","corroborated","strong"]).nullable(),baselineDelta:S.number().finite().nullable(),eligibleObservationCount:S.number().int().nonnegative(),effectiveSampleSize:S.number().nonnegative(),sourceConcentration:S.number().min(0).max(1).nullable(),coreClaimCount:S.number().int().nonnegative(),coreTaskCount:S.number().int().nonnegative(),unsupportedCount:S.number().int().nonnegative(),inconclusiveCount:S.number().int().nonnegative()}).strict().optional()}).strict(),AJ=S.object({contractVersion:S.literal(Wt),contractId:S.enum([ft.dimensionResults.security_safety,ft.dimensionResults.runtime_access_control,ft.dimensionResults.effectiveness_outcomes,ft.dimensionResults.trust_integrity]),dimensionId:S.enum(on),subject:bi,revision:S.number().int().positive(),generatedAt:Jc,policy:Wx,availability:S.enum(la),decision:S.enum(aa).nullable(),score:po.nullable(),reasonCode:le,freshness:S.enum(Zm),items:S.array(Kx),appliedCaps:S.array(Zx),calculation:Jx.optional(),integrity:S.object({inputDigest:bn,canonicalDigest:bn}).strict()}).strict().superRefine((e,t)=>{e.contractId!==ft.dimensionResults[e.dimensionId]&&t.addIssue({code:"custom",message:"platform_score_dimension_contract_mismatch"}),e.availability==="available"&&e.score===null&&t.addIssue({code:"custom",message:"platform_score_available_dimension_requires_score"}),e.availability!=="available"&&e.score!==null&&t.addIssue({code:"custom",message:"platform_score_non_available_dimension_forbids_score"}),e.availability==="unscored"&&e.decision!==null&&t.addIssue({code:"custom",message:"platform_score_unscored_dimension_forbids_decision"}),e.availability!=="unscored"&&e.decision===null&&t.addIssue({code:"custom",message:"platform_score_dimension_requires_decision"})}),RJ=S.discriminatedUnion("kind",[S.object({constraintId:le,kind:S.literal("ceiling"),sourceDimension:S.enum(on),sourceSignalId:le,reasonCode:le,maximumScore:po,decisionImpact:S.enum(["ready_with_findings","action_required"])}).strict(),S.object({constraintId:le,kind:S.literal("block"),sourceDimension:S.enum(on),sourceSignalId:le,reasonCode:le,decisionImpact:S.literal("blocked")}).strict()]),zL=S.enum(Hx),Jm=S.object({contractVersion:S.literal(Wt),contractId:S.literal(ft.platformScore),engineId:S.literal(ft.engine),policyId:S.literal(ft.policy),policyVersion:S.literal(Wt),policyDigest:bn,subject:bi,availability:S.enum(la),decision:S.enum(aa).nullable(),rawScore:po.nullable(),score:po.nullable(),band:zL.nullable(),badge:S.object({icon:S.literal("double_tick"),label:S.literal("Quality Assured"),tone:zL}).strict().nullable(),statusReasonCode:le,reasonCodes:S.array(le),limitingDimensions:S.array(S.enum(on)),appliedConstraints:S.array(RJ),dimensionReferences:S.array(S.object({dimensionId:S.enum(on),revision:S.number().int().positive(),canonicalDigest:bn,score:po.nullable()}).strict()).length(4)}).strict().superRefine((e,t)=>{e.availability==="available"&&(e.decision===null||e.decision==="provisional_evidence"||e.decision==="blocked"||e.rawScore===null||e.score===null||e.band===null||e.badge===null)&&t.addIssue({code:"custom",message:"platform_score_available_result_incomplete"}),e.availability==="withheld"&&(e.score!==null||e.band!==null||e.badge!==null)&&t.addIssue({code:"custom",message:"platform_score_withheld_result_exposes_numeric_band"}),e.availability==="unscored"&&e.decision!==null&&t.addIssue({code:"custom",message:"platform_score_unscored_result_forbids_decision"}),e.availability==="unscored"&&(e.rawScore!==null||e.score!==null||e.band!==null||e.badge!==null)&&t.addIssue({code:"custom",message:"platform_score_unscored_result_exposes_numeric_band"}),e.score!==null&&e.band!==null&&e.band!==EJ(e.score)&&t.addIssue({code:"custom",message:"platform_score_band_mismatch"}),(e.band===null!=(e.badge===null)||e.band!==null&&e.badge?.tone!==e.band)&&t.addIssue({code:"custom",message:"platform_score_badge_mismatch"});let n=PJ.find(r=>r.reasonCode===e.statusReasonCode);(!n||n.availability!==e.availability||n.decision!==e.decision)&&t.addIssue({code:"custom",message:"platform_score_status_reason_mismatch"})});function EJ(e){return e>=Zc.bands.greenMinimum?"green":e>=Zc.bands.amberMinimum?"amber":"red"}var Ym=S.object({passed:S.number().int().nonnegative(),passed_with_findings:S.number().int().nonnegative(),pending:S.number().int().nonnegative(),unavailable:S.number().int().nonnegative(),failed:S.number().int().nonnegative(),blocked:S.number().int().nonnegative(),not_performed:S.number().int().nonnegative(),not_applicable:S.number().int().nonnegative()}).strict(),Yx=S.object({findingId:le,dimensionId:S.enum(on),controlId:le,severity:S.enum(["note","low","medium","high","critical"]),status:S.enum(["open","resolved","accepted","false_positive"]),title:le,summary:le,remediation:le,locations:S.array(S.object({uri:S.literal("SKILL.md"),startLine:S.number().int().positive()}).strict()).optional()}).strict(),Xx=S.object({platformTrustLedger:sn,distributionAuthority:sn}).strict(),Hhe=S.object({contractVersion:S.literal(Wt),contractId:S.literal(ft.report),reportId:le,revision:S.number().int().positive(),generatedAt:Jc,subject:bi,inputDigest:bn,authorityVectorDigest:bn,finalization:Xx,dimensionResults:S.array(AJ).length(4),platformScore:Jm,statusCounts:Ym,findings:S.array(Yx),limitations:S.array(le),integrity:S.object({canonicalDigest:bn}).strict()}).strict().superRefine((e,t)=>{let n=new Set(e.dimensionResults.map(r=>r.dimensionId));(n.size!==on.length||on.some(r=>!n.has(r)))&&t.addIssue({code:"custom",message:"platform_score_report_dimension_set_invalid"}),(Nn(e.subject)!==Nn(e.platformScore.subject)||e.dimensionResults.some(r=>Nn(r.subject)!==Nn(e.subject)))&&t.addIssue({code:"custom",message:"platform_score_report_subject_mismatch"}),e.integrity.canonicalDigest!==$J(e)&&t.addIssue({code:"custom",message:"platform_score_report_digest_mismatch"})});function $J(e){let{integrity:t,...n}=e;return fo(n)}function Nn(e){return JSON.stringify(Gx(e))}function fo(e){return`sha256:${bJ("sha256").update(Nn(e),"utf8").digest("hex")}`}function Gx(e){return Array.isArray(e)?e.map(Gx):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Gx(n)])):e}var Ae=S.string().min(1),Rt=S.string().regex(/^sha256:[a-f0-9]{64}$/u),Qx=S.string().datetime({offset:!0}),eC=S.number().min(0).max(100),Xm=S.string().url(),DJ=Kx.omit({authorityReferences:!0}),TJ=S.object({dimensionId:S.enum(on),revision:S.number().int().positive(),availability:S.enum(la),decision:S.enum(aa).nullable(),score:eC.nullable(),reasonCode:Ae,freshness:S.enum(Zm),items:S.array(DJ),calculation:Jx.optional(),appliedCaps:S.array(Zx).optional(),policy:Wx.optional()}).strict(),OJ=S.object({reportId:Ae,revision:S.number().int().positive(),reportDigest:Rt,generatedAt:Qx,subject:bi,authorityVectorDigest:Rt,finalization:Xx,platformScore:Jm,dimensions:S.array(TJ).length(4),statusCounts:Ym,findings:S.array(Yx),limitations:S.array(Ae),verificationLinks:S.array(Xm)}).strict(),LJ=S.object({controlId:Ae,concern:Ae,authorityReferences:S.array(sn)}).strict(),jJ=S.object({controlId:Ae,governanceDecision:Ae,authorityReferences:S.array(sn)}).strict(),NJ=S.object({controlId:Ae,diagnosticCode:Ae,authorityReferences:S.array(sn)}).strict(),Qm={contractVersion:S.literal(Wt),contractId:S.literal(ft.audienceProjection),projectionPolicyVersion:S.literal(Wt),projectionDigest:Rt,report:OJ},FJ=S.object({...Qm,projectionProfile:S.literal("public"),profileDetails:S.object({kind:S.literal("public")}).strict()}).strict(),BJ=S.object({...Qm,projectionProfile:S.literal("owner_manager"),profileDetails:S.object({kind:S.literal("owner_manager"),remediationEvidence:S.array(LJ)}).strict()}).strict(),MJ=S.object({...Qm,projectionProfile:S.literal("tenant_admin"),profileDetails:S.object({kind:S.literal("tenant_admin"),governanceEvidence:S.array(jJ)}).strict()}).strict(),UJ=S.object({...Qm,projectionProfile:S.literal("platform_operator"),profileDetails:S.object({kind:S.literal("platform_operator"),operationalEvidence:S.array(NJ)}).strict()}).strict(),qL=S.discriminatedUnion("projectionProfile",[FJ,BJ,MJ,UJ]).superRefine((e,t)=>{let{projectionDigest:n,...r}=e;n!==VL(r)&&t.addIssue({code:"custom",message:"platform_score_projection_digest_mismatch"});let i=new Set(e.report.dimensions.map(o=>o.dimensionId));(i.size!==on.length||on.some(o=>!i.has(o)))&&t.addIssue({code:"custom",message:"platform_score_projection_dimension_set_invalid"})});function VL(e){return fo(e)}var tC=S.object({contractVersion:S.literal(Wt),contractId:S.literal(ft.machineReport),projection:qL,deterministicJsonDigest:Rt}).strict().superRefine((e,t)=>{e.deterministicJsonDigest!==fo(e.projection)&&t.addIssue({code:"custom",message:"platform_score_machine_report_digest_mismatch"})}),Yc=S.object({contractVersion:S.literal(Wt),contractId:S.literal(ft.signedPassport),passportId:Ae,issuedAt:Qx,expiresAt:Qx,subject:bi,authorityVectorDigest:Rt,report:S.object({reportId:Ae,revision:S.number().int().positive(),digest:Rt}).strict(),platformScore:S.object({availability:S.enum(la),decision:S.enum(aa).nullable(),score:eC.nullable(),band:S.enum(Hx).nullable()}).strict(),platformTrustLedger:sn,distributionAuthority:sn,sourceProvenance:sn,issuer:S.object({keyId:Ae,algorithm:S.literal("Ed25519")}).strict(),signature:Ae,verificationUrl:Xm}).strict(),zJ=S.object({id:Ae,name:Ae.optional(),shortDescription:S.object({text:Ae}).strict().optional()}).strict(),qJ=S.object({ruleId:Ae,level:S.enum(["none","note","warning","error"]),message:S.object({text:Ae}).strict(),partialFingerprints:S.object({"skills-layer/findingId":Ae}).strict(),locations:S.array(S.object({physicalLocation:S.object({artifactLocation:S.object({uri:Ae}).strict(),region:S.object({startLine:S.number().int().positive().optional()}).strict().optional()}).strict()}).strict()).optional(),properties:S.object({dimensionId:S.literal("security_safety"),findingId:Ae,severity:S.enum(["note","low","medium","high","critical"]),status:S.enum(["open","resolved","accepted","false_positive"]),remediation:Ae}).strict()}).strict(),VJ=S.object({$schema:Xm.optional(),version:S.literal("2.1.0"),runs:S.array(S.object({tool:S.object({driver:S.object({name:S.literal("Skills Layer"),informationUri:Xm,rules:S.array(zJ)}).strict()}).strict(),results:S.array(qJ),properties:S.object({contractVersion:S.literal(Wt),contractId:S.literal(ft.securitySarif),reportId:Ae,reportRevision:S.number().int().positive(),reportDigest:Rt,subject:bi}).strict()}).strict()).min(1)}).strict(),nC=S.object({contractVersion:S.literal(Wt),contractId:S.literal(ft.parityManifest),projectionProfile:S.enum(["public","owner_manager","tenant_admin","platform_operator"]),report:S.object({reportId:Ae,revision:S.number().int().positive(),digest:Rt}).strict(),factsDigest:Rt,facts:S.object({subject:bi,authorityVectorDigest:Rt,platformScore:Jm,dimensions:S.array(S.object({dimensionId:S.enum(on),revision:S.number().int().positive(),score:eC.nullable(),availability:S.enum(la),decision:S.enum(aa).nullable(),reasonCode:Ae}).strict()).length(4),statusCounts:Ym,findingIds:S.array(Ae),platformTrustLedger:sn,distributionAuthority:sn,sourceProvenance:sn}).strict(),artifacts:S.object({projectionDigest:Rt,machineReportDigest:Rt,securitySarifDigest:Rt,passportDigest:Rt,markdownDigest:Rt}).strict()}).strict().superRefine((e,t)=>{e.factsDigest!==fo(e.facts)&&t.addIssue({code:"custom",message:"platform_score_parity_facts_digest_mismatch"})});function rC(e){return tC.safeParse(e).success}function GL(e){let t=e.projection.report,n=t.platformScore,r=[`Platform Score \u2014 ${t.subject.slug} ${t.subject.version}`,`Report: ${t.reportId} revision ${t.revision}`,`Overall: ${n.score===null?"Withheld":`${n.score}/100 (${n.band}) \u2014 ${n.badge.label}`}`,`Decision: ${n.decision??"unscored"} (${n.statusReasonCode})`,...HL(n),"Dimensions:"];for(let i of t.dimensions)r.push(`- ${WL(i.dimensionId)}: ${i.score===null?"Withheld":`${i.score}/100`} \u2014 ${i.decision??i.availability}`),r.push(...KL(i).map(o=>` ${o}`));return r.push(`Checks: ${Object.entries(t.statusCounts).map(([i,o])=>`${i}=${o}`).join(", ")}`,`Report digest: ${t.reportDigest}`),r.join(`
|
|
794
|
-
`)}function HL(e){let t=Zc.greenEligibility,n=e.limitingDimensions.filter(r=>e.reasonCodes.includes(`platform_score_green_gate_failed:${r}`));return["Formula: equal-weight average of the four dimension scores (25% each).",`Policy: ${e.policyId}, version ${e.policyVersion}.`,`Canonical average before eligibility limits: ${e.rawScore===null?"Withheld":`${e.rawScore}/100`}.`,`Published Platform Score: ${e.score===null?"Withheld":`${e.score}/100`}.`,"Rounding: half-up once after eligibility limits and safety caps.",`Green requires an average of at least ${t.minimumRawScore}, Security ${t.minimumSecurityScore}, Runtime ${t.minimumRuntimeScore}, Effectiveness ${t.minimumEffectivenessScore}, Trust ${t.minimumTrustScore}, and no material cap or evidence gap.`,...n.map(r=>`Green eligibility limit: ${WL(r)}; maximum ${t.failedGateMaximumScore}/100.`),...e.appliedConstraints.map(r=>r.kind==="ceiling"?`Safety cap ${r.constraintId}: maximum ${r.maximumScore}/100; ${r.reasonCode}.`:`Safety block ${r.constraintId}: ${r.reasonCode}.`)]}function KL(e){let t=e.calculation;return t?[t.formula,`Pre-cap score: ${t.rawScore??"Withheld"}. Rounding: ${t.rounding}.`,...t.components.map(n=>`${n.label}: ${n.value??"No eligible input"}${n.weight===void 0?"":`; weight ${n.weight}`}`),...t.deductions.map(n=>`${n.sourceId}: \u2212${n.amount}`),...t.outcomes?[`Evidence confidence: ${t.outcomes.confidence??"Withheld"}.`,`Without-skill comparison delta: ${t.outcomes.baselineDelta??"Not measured"}.`,`Core coverage: ${t.outcomes.coreClaimCount} claims, ${t.outcomes.coreTaskCount} claim-linked tasks; unsupported ${t.outcomes.unsupportedCount}, inconclusive ${t.outcomes.inconclusiveCount}.`,`Eligible independent observations: ${t.outcomes.eligibleObservationCount}; effective sample ${t.outcomes.effectiveSampleSize}; source concentration ${t.outcomes.sourceConcentration??"No field evidence"}.`]:[],...(e.appliedCaps??[]).map(n=>`Cap ${n.capId}: maximum ${n.maximumScore}; ${n.reasonCode}`)]:[]}function WL(e){return e==="security_safety"?"Security & Safety":e==="runtime_access_control"?"Runtime Access & Control":e==="effectiveness_outcomes"?"Effectiveness & Outcomes":"Trust & Integrity"}import{sign as tye,verify as GJ}from"node:crypto";function HJ(e,t){let n=Yc.safeParse(e);if(!n.success)return{valid:!1,reasonCode:"passport_schema_invalid"};let{signature:r,...i}=n.data;return GJ(null,Buffer.from(Nn(i),"utf8"),t,Buffer.from(r,"base64url"))?{valid:!0,reasonCode:"passport_signature_valid"}:{valid:!1,reasonCode:"passport_signature_invalid"}}function ZL(e){let t=Yc.safeParse(e.passport);if(!t.success||!Number.isFinite(Date.parse(e.now)))return{valid:!1,reasonCode:"passport_schema_invalid"};let n=t.data,r=e.publicKeys instanceof Map?e.publicKeys.get(n.issuer.keyId):e.publicKeys[n.issuer.keyId];return r?Date.parse(n.issuedAt)>Date.parse(e.now)?{valid:!1,reasonCode:"passport_not_yet_valid"}:Date.parse(n.expiresAt)<=Date.parse(e.now)?{valid:!1,reasonCode:"passport_expired"}:e.currentPassportId&&n.passportId!==e.currentPassportId?{valid:!1,reasonCode:"passport_superseded"}:e.expectedSubject&&Nn(n.subject)!==Nn(e.expectedSubject)?{valid:!1,reasonCode:"passport_subject_mismatch"}:e.expectedReport&&Nn(n.report)!==Nn(e.expectedReport)?{valid:!1,reasonCode:"passport_report_mismatch"}:HJ(n,r).valid?{valid:!0,reasonCode:"passport_valid"}:{valid:!1,reasonCode:"passport_signature_invalid"}:{valid:!1,reasonCode:"passport_unknown_key"}}var KJ=/^github:([^/]+)\/([^/#]+)(?:\/([^#]+))?(?:#(.+))?$/,WJ=/^gitlab:([^/#]+(?:\/[^/#]+)*?)\/([^/#]+)(?:\/([^/#]+))?(?:#(.+))?$/,ZJ=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/(.+?))?(?:#([^@]+))?$/,JJ=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\/.+)?(?:#[^@]+)?$/,YJ=/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/,XJ=/^(?:ssh:\/\/)?git@github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/,QJ=/^(?:ssh:\/\/)?git@gitlab\.com[:/]([^/]+(?:\/[^/]+)*)\/([^/]+?)(?:\.git)?$/;function rr(e){let t=e.trim();if(t.length===0)throw new Error("import requires a non-empty source.");let{sourceInput:n,skillFilter:r}=t7(t),i=n.match(KJ);if(i){let[,d,p,m,h]=i;return eg({input:t,owner:d,repo:p,ref:h?.trim()||"main",subpath:m,skillFilter:r})}let o=n.match(WJ);if(o){let[,d,p,m,h]=o;return iC({input:t,host:"gitlab.com",namespace:d,repo:p,ref:h?.trim()||"main",subpath:m,skillFilter:r})}let s=n7(t);if(s)return s;let a=r7(t);if(a)return a;let l=n.match(XJ);if(l){let[,d,p]=l;return eg({input:t,owner:d,repo:nr(p),ref:"main",subpath:"SKILL.md"})}let c=n.match(QJ);if(c){let[,d,p]=c;return iC({input:t,host:"gitlab.com",namespace:d,repo:nr(p),ref:"main",subpath:"SKILL.md"})}if(/^(?:git\+)?https?:\/\//u.test(n)){if(/[?&]skill=/u.test(n)){let d=new URL(n.replace(/^git\+/u,"")),p=d.searchParams.get("skill")?.trim();return d.searchParams.delete("skill"),{kind:"url",input:t,url:d.toString(),canonicalSource:d.toString(),...p?{skillFilter:p}:{}}}return{kind:"url",input:t,url:n.replace(/^git\+/u,""),canonicalSource:n.replace(/^git\+/u,"")}}let u=n.match(ZJ);if(u&&!YJ.test(n)){let[,d,p,m,h]=u;return eg({input:t,owner:d,repo:nr(p),ref:h?.trim()||"main",subpath:m,skillFilter:r})}return/^(?:ssh:\/\/)?git@/u.test(n)||/^(?:git\+)?ssh:\/\//u.test(n)?{kind:"git",input:t,url:n.replace(/^git\+/u,""),canonicalSource:n.replace(/^git\+/u,""),...r?{skillFilter:r}:{}}:{kind:"local",input:t,location:n,canonicalSource:n,...r?{skillFilter:r}:{}}}var e7='Source references must not contain ".", ".." or empty path segments';function Er(e,t){if(t===void 0)return;let n=t;for(let r=0;r<4;r+=1){let i;try{i=decodeURIComponent(n)}catch{break}if(i===n)break;n=i}if(n.split(/[\\/]/u).some(r=>r===""||r==="."||r===".."))throw new Error(`${e7} (${e}).`)}function JL(e){let t=e.replace(/^https?:\/\/[^/?#]*/u,"").split(/[?#]/u)[0].replace(/^\//u,"").replace(/\/$/u,"");t.length>0&&Er("url path",t)}function tg(e){let t=e?.trim();return t&&t.length>0?t:"SKILL.md"}function t7(e){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("git@")||e.startsWith("ssh://"))return{sourceInput:e};let t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return{sourceInput:e};let n=e.slice(0,t),r=e.slice(t+1).trim();return r.match(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u)?n.includes("#")?{sourceInput:n,skillFilter:r}:n.startsWith("github:")||n.startsWith("gitlab:")||JJ.test(n)?{sourceInput:n,skillFilter:r}:{sourceInput:n,skillFilter:r}:{sourceInput:e}}function YL(e,t,n,r){return`${e}://${t}@${n}/${r}`}function nr(e){return e.replace(/\.git$/u,"")}function n7(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return null;let t=new URL(e);if(t.hostname!=="github.com")return null;JL(e);let n=t.pathname.split("/").filter(Boolean);if(n.length<2)throw new Error("GitHub URLs must include an owner and repository.");let r=n[0],i=nr(n[1]),o="main",s="SKILL.md";(n[2]==="tree"||n[2]==="blob")&&(o=n[3]?.trim()||"main",s=tg(n.slice(4).join("/")));let a=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),eg({input:e,owner:r,repo:i,ref:o,subpath:s,skillFilter:a})}function r7(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return null;let t=new URL(e);if(t.hostname==="github.com")return null;let n=t.pathname.split("/").filter(Boolean),r=n.indexOf("-");if(t.hostname!=="gitlab.com"&&r!==-1)throw new Error("Self-hosted GitLab sources are not supported for the public launch; use GitLab.com.");if(t.hostname!=="gitlab.com")return null;JL(e);let i=r===-1?n:n.slice(0,r);if(i.length<2)throw new Error("GitLab URLs must include a namespace and repository.");let o=nr(i[i.length-1]),s=i.slice(0,-1).join("/"),a=r===-1?void 0:n[r+1],l=r===-1?[]:n.slice(r+2),c=(a==="tree"||a==="blob")&&l[0]?.trim()||"main",u=a==="tree"||a==="blob"?tg(l.slice(1).join("/")):"SKILL.md",d=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),iC({input:e,host:t.hostname,namespace:s,repo:o,ref:c,subpath:u,skillFilter:d})}function eg(e){Er("owner",e.owner),Er("repository",e.repo),Er("ref",e.ref),Er("subpath",e.subpath?.trim()||void 0);let t=tg(e.subpath);return{kind:"github",input:e.input,owner:e.owner,repo:nr(e.repo),ref:e.ref,subpath:t,repoUrl:`https://github.com/${e.owner}/${nr(e.repo)}`,rawUrl:`https://raw.githubusercontent.com/${e.owner}/${nr(e.repo)}/${e.ref}/${t}`,canonicalSource:YL("github",`${e.owner}/${nr(e.repo)}`,e.ref,t),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}function iC(e){Er("namespace",e.namespace),Er("repository",e.repo),Er("ref",e.ref),Er("subpath",e.subpath?.trim()||void 0);let t=nr(e.repo),n=tg(e.subpath);return{kind:"gitlab",input:e.input,host:e.host,namespace:e.namespace,repo:t,ref:e.ref,subpath:n,repoUrl:`https://${e.host}/${e.namespace}/${t}`,rawUrl:`https://${e.host}/${e.namespace}/${t}/-/raw/${e.ref}/${n}`,canonicalSource:YL("gitlab",`${e.namespace}/${t}`,e.ref,n),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}import{createHash as sg}from"node:crypto";import{readdir as hj,readFile as mC,stat as yj}from"node:fs/promises";import{dirname as vj,posix as nt,win32 as S7}from"node:path";var Qc=fn(Ji(),1);import{createHash as i7}from"node:crypto";var tj=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/u,ng=/(^|\/)SKILL\.md$/u,o7=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,s7=/^#\s+(.+?)\s*$/mu,a7=/^Skill ID:\s*`?([^`\s]+)`?\s*$/imu,l7=new Set(["name must be a non-empty string","name must be kebab-case",qp()]),nj=1024,c7="description must be 1024 characters or fewer",XL=/^(description:[ \t]*)(\S[^\r\n]*)$/gmu,u7="phase131-v2";function rg(e){let t=tt(e.files);if(t.parsedSkill)return{files:e.files,validation:t,skillSlug:t.parsedSkill.frontmatter.name,description:t.parsedSkill.frontmatter.description,originalSkillName:t.parsedSkill.frontmatter.name,normalizationApplied:!1,normalizationIssues:[]};if(!e.allowNormalization)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let n=e.files,r=t,i=[],o=d7(n);o&&(n=o.files,r=o.validation,i.push(o.issue));let s=p7(n,r);if(s&&(n=s.files,r=s.validation,i.push(s.issue)),r.parsedSkill){let g=ej(r,i);return{files:n,validation:g,skillSlug:g.parsedSkill.frontmatter.name,description:g.parsedSkill.frontmatter.description,originalSkillName:g.parsedSkill.frontmatter.name,normalizationApplied:!0,normalizationIssues:i,normalizationProvenance:oC(e.files,n,i)}}if(!g7(r)){let g=f7(e.files,e.fallbackSkillSlug);return g||{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]}}let a=n.find(g=>ng.test(g.path));if(!a||typeof a.content!="string")return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let l=rj(a.content);if(!l)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let c=h7({fallbackSkillSlug:e.fallbackSkillSlug,originalSkillName:l.frontmatter.name});if(!c)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let u=y7(l,c),d=n.map(g=>g.path===a.path?{...g,content:u}:g),p=ej(tt(d),i);if(!p.parsedSkill)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let m=l.frontmatter.name||void 0,h=[...i,m?Xc("frontmatter-name-normalized","Source name was normalized to a portable skill slug for ingestion."):Xc("frontmatter-name-synthesized","Missing source name was deterministically synthesized from the immutable source directory for ingestion.")];return{files:d,validation:p,skillSlug:p.parsedSkill.frontmatter.name,description:p.parsedSkill.frontmatter.description,originalSkillName:m,normalizationApplied:!0,normalizationIssues:h,normalizationProvenance:oC(e.files,d,h)}}function d7(e){let t=e.find(h=>ng.test(h.path));if(!t||typeof t.content!="string")return null;let n=t.content.match(tj);if(!n)return null;let[,r,i]=n,o=[...r.matchAll(XL)];if(o.length!==1)return null;let[,s,a]=o[0],l=a.trim(),c=/^\[[A-Za-z0-9._-]{1,32}\][ \t]+\S/u.test(l),u=l.includes(": ");if(!c&&!u||l.startsWith('"')||l.startsWith("'"))return null;let p=`---
|
|
794
|
+
`)}function HL(e){let t=Zc.greenEligibility,n=e.limitingDimensions.filter(r=>e.reasonCodes.includes(`platform_score_green_gate_failed:${r}`));return["Formula: equal-weight average of the four dimension scores (25% each).",`Policy: ${e.policyId}, version ${e.policyVersion}.`,`Canonical average before eligibility limits: ${e.rawScore===null?"Withheld":`${e.rawScore}/100`}.`,`Published Platform Score: ${e.score===null?"Withheld":`${e.score}/100`}.`,"Rounding: half-up once after eligibility limits and safety caps.",`Green requires an average of at least ${t.minimumRawScore}, Security ${t.minimumSecurityScore}, Runtime ${t.minimumRuntimeScore}, Effectiveness ${t.minimumEffectivenessScore}, Trust ${t.minimumTrustScore}, and no material cap or evidence gap.`,...n.map(r=>`Green eligibility limit: ${WL(r)}; maximum ${t.failedGateMaximumScore}/100.`),...e.appliedConstraints.map(r=>r.kind==="ceiling"?`Safety cap ${r.constraintId}: maximum ${r.maximumScore}/100; ${r.reasonCode}.`:`Safety block ${r.constraintId}: ${r.reasonCode}.`)]}function KL(e){let t=e.calculation;return t?[t.formula,`Pre-cap score: ${t.rawScore??"Withheld"}. Rounding: ${t.rounding}.`,...t.components.map(n=>`${n.label}: ${n.value??"No eligible input"}${n.weight===void 0?"":`; weight ${n.weight}`}`),...t.deductions.map(n=>`${n.sourceId}: \u2212${n.amount}`),...t.outcomes?[`Evidence confidence: ${t.outcomes.confidence??"Withheld"}.`,`Without-skill comparison delta: ${t.outcomes.baselineDelta??"Not measured"}.`,`Core coverage: ${t.outcomes.coreClaimCount} claims, ${t.outcomes.coreTaskCount} claim-linked tasks; unsupported ${t.outcomes.unsupportedCount}, inconclusive ${t.outcomes.inconclusiveCount}.`,`Eligible independent observations: ${t.outcomes.eligibleObservationCount}; effective sample ${t.outcomes.effectiveSampleSize}; source concentration ${t.outcomes.sourceConcentration??"No field evidence"}.`]:[],...(e.appliedCaps??[]).map(n=>`Cap ${n.capId}: maximum ${n.maximumScore}; ${n.reasonCode}`)]:[]}function WL(e){return e==="security_safety"?"Security & Safety":e==="runtime_access_control"?"Runtime Access & Control":e==="effectiveness_outcomes"?"Effectiveness & Outcomes":"Trust & Integrity"}import{sign as tye,verify as GJ}from"node:crypto";function HJ(e,t){let n=Yc.safeParse(e);if(!n.success)return{valid:!1,reasonCode:"passport_schema_invalid"};let{signature:r,...i}=n.data;return GJ(null,Buffer.from(Nn(i),"utf8"),t,Buffer.from(r,"base64url"))?{valid:!0,reasonCode:"passport_signature_valid"}:{valid:!1,reasonCode:"passport_signature_invalid"}}function ZL(e){let t=Yc.safeParse(e.passport);if(!t.success||!Number.isFinite(Date.parse(e.now)))return{valid:!1,reasonCode:"passport_schema_invalid"};let n=t.data,r=e.publicKeys instanceof Map?e.publicKeys.get(n.issuer.keyId):e.publicKeys[n.issuer.keyId];return r?Date.parse(n.issuedAt)>Date.parse(e.now)?{valid:!1,reasonCode:"passport_not_yet_valid"}:Date.parse(n.expiresAt)<=Date.parse(e.now)?{valid:!1,reasonCode:"passport_expired"}:e.currentPassportId&&n.passportId!==e.currentPassportId?{valid:!1,reasonCode:"passport_superseded"}:e.expectedSubject&&Nn(n.subject)!==Nn(e.expectedSubject)?{valid:!1,reasonCode:"passport_subject_mismatch"}:e.expectedReport&&Nn(n.report)!==Nn(e.expectedReport)?{valid:!1,reasonCode:"passport_report_mismatch"}:HJ(n,r).valid?{valid:!0,reasonCode:"passport_valid"}:{valid:!1,reasonCode:"passport_signature_invalid"}:{valid:!1,reasonCode:"passport_unknown_key"}}var KJ=/^github:([^/]+)\/([^/#]+)(?:\/([^#]+))?(?:#(.+))?$/,WJ=/^gitlab:([^/#]+(?:\/[^/#]+)*?)\/([^/#]+)(?:\/([^/#]+))?(?:#(.+))?$/,ZJ=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/(.+?))?(?:#([^@]+))?$/,JJ=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\/.+)?(?:#[^@]+)?$/,YJ=/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/,XJ=/^(?:ssh:\/\/)?git@github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/,QJ=/^(?:ssh:\/\/)?git@gitlab\.com[:/]([^/]+(?:\/[^/]+)*)\/([^/]+?)(?:\.git)?$/;function rr(e){let t=e.trim();if(t.length===0)throw new Error("import requires a non-empty source.");let{sourceInput:n,skillFilter:r}=t7(t),i=n.match(KJ);if(i){let[,d,p,m,h]=i;return eg({input:t,owner:d,repo:p,ref:h?.trim()||"main",subpath:m,skillFilter:r})}let o=n.match(WJ);if(o){let[,d,p,m,h]=o;return iC({input:t,host:"gitlab.com",namespace:d,repo:p,ref:h?.trim()||"main",subpath:m,skillFilter:r})}let s=n7(t);if(s)return s;let a=r7(t);if(a)return a;let l=n.match(XJ);if(l){let[,d,p]=l;return eg({input:t,owner:d,repo:nr(p),ref:"main",subpath:"SKILL.md"})}let c=n.match(QJ);if(c){let[,d,p]=c;return iC({input:t,host:"gitlab.com",namespace:d,repo:nr(p),ref:"main",subpath:"SKILL.md"})}if(/^(?:git\+)?https?:\/\//u.test(n)){if(/[?&]skill=/u.test(n)){let d=new URL(n.replace(/^git\+/u,"")),p=d.searchParams.get("skill")?.trim();return d.searchParams.delete("skill"),{kind:"url",input:t,url:d.toString(),canonicalSource:d.toString(),...p?{skillFilter:p}:{}}}return{kind:"url",input:t,url:n.replace(/^git\+/u,""),canonicalSource:n.replace(/^git\+/u,"")}}let u=n.match(ZJ);if(u&&!YJ.test(n)){let[,d,p,m,h]=u;return eg({input:t,owner:d,repo:nr(p),ref:h?.trim()||"main",subpath:m,skillFilter:r})}return/^(?:ssh:\/\/)?git@/u.test(n)||/^(?:git\+)?ssh:\/\//u.test(n)?{kind:"git",input:t,url:n.replace(/^git\+/u,""),canonicalSource:n.replace(/^git\+/u,""),...r?{skillFilter:r}:{}}:{kind:"local",input:t,location:n,canonicalSource:n,...r?{skillFilter:r}:{}}}var e7='Source references must not contain ".", ".." or empty path segments';function Er(e,t){if(t===void 0)return;let n=t;for(let r=0;r<4;r+=1){let i;try{i=decodeURIComponent(n)}catch{break}if(i===n)break;n=i}if(n.split(/[\\/]/u).some(r=>r===""||r==="."||r===".."))throw new Error(`${e7} (${e}).`)}function JL(e){let t=e.replace(/^https?:\/\/[^/?#]*/u,"").split(/[?#]/u)[0].replace(/^\//u,"").replace(/\/$/u,"");t.length>0&&Er("url path",t)}function tg(e){let t=e?.trim();return t&&t.length>0?t:"SKILL.md"}function t7(e){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("git@")||e.startsWith("ssh://"))return{sourceInput:e};let t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return{sourceInput:e};let n=e.slice(0,t),r=e.slice(t+1).trim();return r.match(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u)?n.includes("#")?{sourceInput:n,skillFilter:r}:n.startsWith("github:")||n.startsWith("gitlab:")||JJ.test(n)?{sourceInput:n,skillFilter:r}:{sourceInput:n,skillFilter:r}:{sourceInput:e}}function YL(e,t,n,r){return`${e}://${t}@${n}/${r}`}function nr(e){return e.replace(/\.git$/u,"")}function n7(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return null;let t=new URL(e);if(t.hostname!=="github.com")return null;JL(e);let n=t.pathname.split("/").filter(Boolean);if(n.length<2)throw new Error("GitHub URLs must include an owner and repository.");let r=n[0],i=nr(n[1]),o="main",s="SKILL.md";(n[2]==="tree"||n[2]==="blob")&&(o=n[3]?.trim()||"main",s=tg(n.slice(4).join("/")));let a=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),eg({input:e,owner:r,repo:i,ref:o,subpath:s,skillFilter:a})}function r7(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return null;let t=new URL(e);if(t.hostname==="github.com")return null;let n=t.pathname.split("/").filter(Boolean),r=n.indexOf("-");if(t.hostname!=="gitlab.com"&&r!==-1)throw new Error("Self-hosted GitLab sources are not supported for the public launch; use GitLab.com.");if(t.hostname!=="gitlab.com")return null;JL(e);let i=r===-1?n:n.slice(0,r);if(i.length<2)throw new Error("GitLab URLs must include a namespace and repository.");let o=nr(i[i.length-1]),s=i.slice(0,-1).join("/"),a=r===-1?void 0:n[r+1],l=r===-1?[]:n.slice(r+2),c=(a==="tree"||a==="blob")&&l[0]?.trim()||"main",u=a==="tree"||a==="blob"?tg(l.slice(1).join("/")):"SKILL.md",d=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),iC({input:e,host:t.hostname,namespace:s,repo:o,ref:c,subpath:u,skillFilter:d})}function eg(e){Er("owner",e.owner),Er("repository",e.repo),Er("ref",e.ref),Er("subpath",e.subpath?.trim()||void 0);let t=tg(e.subpath);return{kind:"github",input:e.input,owner:e.owner,repo:nr(e.repo),ref:e.ref,subpath:t,repoUrl:`https://github.com/${e.owner}/${nr(e.repo)}`,rawUrl:`https://raw.githubusercontent.com/${e.owner}/${nr(e.repo)}/${e.ref}/${t}`,canonicalSource:YL("github",`${e.owner}/${nr(e.repo)}`,e.ref,t),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}function iC(e){Er("namespace",e.namespace),Er("repository",e.repo),Er("ref",e.ref),Er("subpath",e.subpath?.trim()||void 0);let t=nr(e.repo),n=tg(e.subpath);return{kind:"gitlab",input:e.input,host:e.host,namespace:e.namespace,repo:t,ref:e.ref,subpath:n,repoUrl:`https://${e.host}/${e.namespace}/${t}`,rawUrl:`https://${e.host}/${e.namespace}/${t}/-/raw/${e.ref}/${n}`,canonicalSource:YL("gitlab",`${e.namespace}/${t}`,e.ref,n),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}import{createHash as sg}from"node:crypto";import{readdir as hj,readFile as mC,stat as yj}from"node:fs/promises";import{dirname as vj,posix as rt,win32 as S7}from"node:path";var Qc=fn(Ji(),1);import{createHash as i7}from"node:crypto";var tj=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/u,ng=/(^|\/)SKILL\.md$/u,o7=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,s7=/^#\s+(.+?)\s*$/mu,a7=/^Skill ID:\s*`?([^`\s]+)`?\s*$/imu,l7=new Set(["name must be a non-empty string","name must be kebab-case",qp()]),nj=1024,c7="description must be 1024 characters or fewer",XL=/^(description:[ \t]*)(\S[^\r\n]*)$/gmu,u7="phase131-v2";function rg(e){let t=nt(e.files);if(t.parsedSkill)return{files:e.files,validation:t,skillSlug:t.parsedSkill.frontmatter.name,description:t.parsedSkill.frontmatter.description,originalSkillName:t.parsedSkill.frontmatter.name,normalizationApplied:!1,normalizationIssues:[]};if(!e.allowNormalization)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let n=e.files,r=t,i=[],o=d7(n);o&&(n=o.files,r=o.validation,i.push(o.issue));let s=p7(n,r);if(s&&(n=s.files,r=s.validation,i.push(s.issue)),r.parsedSkill){let g=ej(r,i);return{files:n,validation:g,skillSlug:g.parsedSkill.frontmatter.name,description:g.parsedSkill.frontmatter.description,originalSkillName:g.parsedSkill.frontmatter.name,normalizationApplied:!0,normalizationIssues:i,normalizationProvenance:oC(e.files,n,i)}}if(!g7(r)){let g=f7(e.files,e.fallbackSkillSlug);return g||{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]}}let a=n.find(g=>ng.test(g.path));if(!a||typeof a.content!="string")return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let l=rj(a.content);if(!l)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let c=h7({fallbackSkillSlug:e.fallbackSkillSlug,originalSkillName:l.frontmatter.name});if(!c)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let u=y7(l,c),d=n.map(g=>g.path===a.path?{...g,content:u}:g),p=ej(nt(d),i);if(!p.parsedSkill)return{files:e.files,validation:t,normalizationApplied:!1,normalizationIssues:[]};let m=l.frontmatter.name||void 0,h=[...i,m?Xc("frontmatter-name-normalized","Source name was normalized to a portable skill slug for ingestion."):Xc("frontmatter-name-synthesized","Missing source name was deterministically synthesized from the immutable source directory for ingestion.")];return{files:d,validation:p,skillSlug:p.parsedSkill.frontmatter.name,description:p.parsedSkill.frontmatter.description,originalSkillName:m,normalizationApplied:!0,normalizationIssues:h,normalizationProvenance:oC(e.files,d,h)}}function d7(e){let t=e.find(h=>ng.test(h.path));if(!t||typeof t.content!="string")return null;let n=t.content.match(tj);if(!n)return null;let[,r,i]=n,o=[...r.matchAll(XL)];if(o.length!==1)return null;let[,s,a]=o[0],l=a.trim(),c=/^\[[A-Za-z0-9._-]{1,32}\][ \t]+\S/u.test(l),u=l.includes(": ");if(!c&&!u||l.startsWith('"')||l.startsWith("'"))return null;let p=`---
|
|
795
795
|
${r.replace(XL,()=>`${s}${JSON.stringify(l)}`)}
|
|
796
796
|
---
|
|
797
|
-
${i}`,m=e.map(h=>h===t?{...h,content:p}:h);return{files:m,validation:
|
|
797
|
+
${i}`,m=e.map(h=>h===t?{...h,content:p}:h);return{files:m,validation:nt(m),issue:Xc("frontmatter-description-repaired","Source description used invalid YAML and was quoted automatically for ingestion.")}}function p7(e,t){if(!t.issues.some(s=>s.code==="frontmatter-invalid"&&s.message===c7))return null;let n=e.find(s=>ng.test(s.path));if(!n||typeof n.content!="string")return null;let r=rj(n.content);if(!r||r.frontmatter.description.length<=nj)return null;let i=ij(r,{description:oj(r.frontmatter.description)}),o=e.map(s=>s===n?{...s,content:i}:s);return{files:o,validation:nt(o),issue:Xc("description-truncated","Source description exceeded 1024 characters and was truncated automatically for ingestion.")}}function f7(e,t){let n=e.find(p=>ng.test(p.path));if(!n||typeof n.content!="string")return null;let r=n.content;if(r.trimStart().startsWith("---"))return null;let i=r.match(s7)?.[1]?.trim();if(!i)return null;let o=r.match(a7)?.[1]?.trim(),s=[o,t,i].map(p=>p?mo(p):null).find(p=>!!p),a=m7(r);if(!s||!a)return null;let l=`---
|
|
798
798
|
${(0,Qc.stringify)({name:s,description:a},{lineWidth:0}).trimEnd()}
|
|
799
799
|
---
|
|
800
|
-
${r}`,c=e.map(p=>p===n?{...p,content:l}:p),u=
|
|
800
|
+
${r}`,c=e.map(p=>p===n?{...p,content:l}:p),u=nt(c);if(!u.parsedSkill)return null;let d=[Xc("frontmatter-synthesized","Missing source frontmatter was synthesized from deterministic Markdown fields.")];return{files:c,validation:u,skillSlug:s,description:a,originalSkillName:o??i,normalizationApplied:!0,normalizationIssues:d,normalizationProvenance:oC(e,c,d)}}function oC(e,t,n){return{schemaVersion:"skills-layer-source-normalization-v1",rulesetVersion:u7,originalBundleSha256:QL(e),normalizedBundleSha256:QL(t),appliedRules:Array.from(new Set(n.map(r=>r.code))).sort()}}function QL(e){let t=i7("sha256");return[...e].sort((n,r)=>n.path.localeCompare(r.path)).forEach((n,r,i)=>{t.update(n.path),t.update("\0"),t.update(ye(n)),r<i.length-1&&t.update("\0")}),`sha256:${t.digest("hex")}`}function m7(e){let n=e.trim().split(/\r?\n\s*\r?\n/u).map(i=>i.trim()).filter(Boolean).filter(i=>!i.startsWith("#")&&!/^Skill ID:/iu.test(i)&&!i.startsWith("```")&&!/^[-*]\s/u.test(i)),r=n.find(i=>/^Use this skill\b/iu.test(i))??n[0];return r?oj(r.replace(/\s+/gu," ").trim()):null}function mo(e){let t=e.normalize("NFKD").replace(/[\u0300-\u036f]/gu,"").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"");if(t.length===0)return null;let n=t.split("-").filter(r=>r.length>0&&!h1(r)).join("-");return n.length===0||!o7.test(n)?null:n}function g7(e){return e.issues.length===1&&e.issues[0]?.code==="frontmatter-invalid"&&l7.has(e.issues[0].message)}function h7(e){let t=[e.fallbackSkillSlug,e.originalSkillName].map(n=>n?.trim()).filter(n=>!!n);for(let n of t){let r=mo(n);if(r)return r}return null}function rj(e){let t=e.match(tj);if(!t)return null;let[,n,r]=t,i=(0,Qc.parse)(n);if(!v7(i))return null;let o=typeof i.name=="string"?i.name.trim():"",s=typeof i.description=="string"?i.description.trim():"";return s?{frontmatter:{...i,name:o,description:s},body:r}:null}function y7(e,t){return ij(e,{name:t})}function ij(e,t){return`---
|
|
801
801
|
${(0,Qc.stringify)({...e.frontmatter,...t}).trimEnd()}
|
|
802
802
|
---
|
|
803
|
-
${e.body}`}function oj(e){let t=e.slice(0,nj),n=t.charCodeAt(t.length-1);return n>=55296&&n<=56319?t.slice(0,-1):t}function Xc(e,t){return{severity:"warning",code:e,message:t,nextAction:"review-normalized-source",nextStep:"Review the normalized frontmatter and improve the upstream SKILL.md when practical."}}function ej(e,t){if(t.length===0)return e;let n=[...e.issues,...t];return{...e,valid:e.valid&&n.every(r=>r.severity!=="error"),issues:n}}function v7(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sj(e){if(!ir(e))throw new Error("Well-known search response must be a JSON object.");if(e.version!==1)throw new Error("Well-known search response version must be 1.");let t=aC(e.provider),n=_7(e.query,"query"),r=cj(e.limit,"limit");if(!Array.isArray(e.results))throw new Error("results must be an array.");return{version:1,provider:t,query:n,limit:r,results:e.results.map((i,o)=>k7(i,`results[${o}]`))}}function aj(e){if(!ir(e))throw new Error("Well-known skill manifest must be a JSON object.");if(e.version!==1)throw new Error("Well-known skill manifest version must be 1.");let t=aC(e.provider);if(!ir(e.skill))throw new Error("skill must be an object.");if(!Array.isArray(e.skill.files))throw new Error("skill.files must be an array.");let n=e.skill.files.map((i,o)=>w7(i,`skill.files[${o}]`));if(!n.some(i=>i.path==="SKILL.md"))throw new Error("skill.files must include SKILL.md.");let r=sC(e.skill.sourceUrl,"skill.sourceUrl")??n.find(i=>i.path==="SKILL.md").url;return{version:1,provider:t,skill:{slug:_n(e.skill.slug,"skill.slug"),name:_n(e.skill.name,"skill.name"),description:_n(e.skill.description,"skill.description"),skillVersion:_n(e.skill.skillVersion,"skill.skillVersion"),compatibility:sC(e.skill.compatibility,"skill.compatibility")??"",featured:e.skill.featured===!0,tags:uj(e.skill.tags,"skill.tags"),files:n,sourceUrl:go(r,"skill.sourceUrl")}}}function lj(e){if(!ir(e))throw new Error("Well-known index must be a JSON object.");if(!ir(e.provider))throw new Error("Well-known index provider must be an object.");let t=aC(e.provider);if(e.version!==2)throw new Error("Well-known service manifest version must be 2.");if(!ir(e.capabilities))throw new Error("capabilities must be an object.");if(e.capabilities.directSkillManifest!==!0)throw new Error("capabilities.directSkillManifest must be true.");if(e.capabilities.search!==!0)throw new Error("capabilities.search must be true.");let n=cj(e.capabilities.maxSearchResults,"capabilities.maxSearchResults");if(!ir(e.routes))throw new Error("routes must be an object.");return{version:2,provider:t,capabilities:{directSkillManifest:!0,search:!0,maxSearchResults:n},routes:{search:go(e.routes.search,"routes.search"),skillManifest:go(e.routes.skillManifest,"routes.skillManifest"),skillFile:go(e.routes.skillFile,"routes.skillFile")}}}function k7(e,t){if(!ir(e))throw new Error(`${t} must be an object.`);return{slug:_n(e.slug,`${t}.slug`),name:_n(e.name,`${t}.name`),description:_n(e.description,`${t}.description`),skillVersion:_n(e.skillVersion,`${t}.skillVersion`),compatibility:sC(e.compatibility,`${t}.compatibility`)??"",featured:e.featured===!0,tags:uj(e.tags,`${t}.tags`),skillManifestUrl:go(e.skillManifestUrl,`${t}.skillManifestUrl`)}}function w7(e,t){if(!ir(e))throw new Error(`${t} must be an object.`);return{path:b7(_n(e.path,`${t}.path`)),url:go(e.url,`${t}.url`)}}function aC(e){if(!ir(e))throw new Error("Well-known index provider must be an object.");return{name:_n(e.name,"provider.name"),baseUrl:go(e.baseUrl,"provider.baseUrl")}}function b7(e){return e.trim().replaceAll("\\","/").replace(/^\/+/u,"").split("/").filter(t=>t.length>0&&t!=="."&&t!=="..").join("/")}function cj(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<1||e>5)throw new Error(`${t} must be between 1 and 5.`);return e}function _7(e,t){if(typeof e!="string")throw new Error(`${t} must be a string.`);return e.trim()}function _n(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string.`);return e.trim()}function sC(e,t){if(e!==void 0)return _n(e,t)}function go(e,t){let n=_n(e,t);if(!/^https?:\/\//u.test(n))throw new Error(`${t} must be an absolute http(s) URL.`);return n}function uj(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be a string array.`);return e.map(n=>n.trim()).filter(n=>n.length>0)}function ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ca=class extends Error{constructor(t){super(t instanceof Error?t.message:"Source files could not be read completely.",{cause:t}),this.name="SourceReadUnavailableError"}};var og=100,da=class extends Error{},x7=40;async function kj(e){if(e.source.kind==="local")return N7({source:e.source,cwd:e.cwd,platform:e.platform});if(e.source.kind==="git")return{source:e.source,results:[],issues:[{severity:"warning",code:"git-remote-not-inspectable",message:"Generic git remotes are normalized, but inspection currently requires a local checkout or GitHub/GitLab raw access."}]};if(e.source.kind==="well-known"&&Array.isArray(e.source.files)&&e.source.files.length>0)return uC({source:e.source,fetchFn:e.fetchFn});if(e.source.kind==="url"){let t=await C7({source:e.source,fetchFn:e.fetchFn,requestedSkillSlug:e.requestedSkillSlug});if(t!==null)return t}if(e.source.kind==="github"||e.source.kind==="gitlab")try{return await A7({source:e.source,fetchFn:e.fetchFn,requestedSkillSlug:e.requestedSkillSlug})}catch(t){if(t instanceof ca)throw t;let n=t instanceof ho?t:null;if(!(xj(e.source.subpath)&&(n===null||n.status===404||n.status===403))){if(n===null)throw t;let i=e.source.kind==="github"?"GitHub":"GitLab";throw new ca(new Error(`${i} source inspection failed (HTTP ${n.status}): ${n.message}. This is a source-provider failure, not a Skills Layer login failure.`))}}return I7({source:e.source,fetchFn:e.fetchFn})}async function C7(e){if(xj(e.source.url))return null;let t=await X7(e.source.url,e.fetchFn);if(t===null)return null;let n=e.source.skillFilter??e.requestedSkillSlug??tY(e.source.url),r=[],i=[];if(n){let o=mj(t.index.routes.skillManifest,{slug:n}),s=await pj(o,e.fetchFn);if(s===null)i.push({severity:"warning",code:"well-known-skill-not-found",message:`Well-known provider did not expose "${n}".`});else{let a=await uC({source:fj({inputSource:e.source,detectedIndex:t,manifest:s,manifestUrl:o,skillFilter:n}),fetchFn:e.fetchFn});r.push(...a.results),i.push(...a.issues)}}else{let o=mj(t.index.routes.search,{query:eY(e.source.url),limit:"5"}),s=await Q7(o,e.fetchFn);if(s!==null)for(let a of s.results.slice(0,t.index.capabilities.maxSearchResults)){let l=await pj(a.skillManifestUrl,e.fetchFn);if(l===null){i.push({severity:"warning",code:"well-known-manifest-not-found",message:`Well-known provider advertised "${a.slug}" but its manifest was unavailable.`});continue}let c=await uC({source:fj({inputSource:e.source,detectedIndex:t,manifest:l,manifestUrl:a.skillManifestUrl}),fetchFn:e.fetchFn});r.push(...c.results),i.push(...c.issues)}}return{source:e.source,results:r,issues:i}}async function I7(e){let t=await e.fetchFn(H7(e.source));if(!t.ok)throw await Si(t);let r=[{path:"SKILL.md",content:await t.text()}];return wj(e.source,r)}async function uC(e){let t=await j7(e.source,e.fetchFn);return wj(e.source,t)}function wj(e,t){let n=[],r=rg({files:t,allowNormalization:!0}),i=r.validation,o=r.skillSlug??iu(i,e);if(!o||!pa(e.skillFilter,o)){let s=t.find(a=>M7.test(a.path));return s&&fa(n,i,s.path),{source:e,results:[],issues:n}}return{source:e,results:[{skillSlug:o,description:r.description??(i.parsedSkill?i.parsedSkill.frontmatter.description:o),...r.originalSkillName?{originalSkillName:r.originalSkillName}:{},sourceKind:e.kind,relativeSkillRoot:".",relativeSkillFile:"SKILL.md",discoveryRoute:"remote_file",validation:{valid:i.valid,issueCount:i.issues.length},...r.normalizationIssues.length>0?{normalizationIssues:r.normalizationIssues}:{},...r.normalizationProvenance?{normalizationProvenance:r.normalizationProvenance}:{},files:r.files,losslessImport:P7(e,t)}],issues:n}}function P7(e,t){let n=sg("sha256"),r=t.slice().sort((l,c)=>l.path.localeCompare(c.path));r.forEach((l,c)=>{n.update(l.path),n.update("\0"),n.update(ye(l)),c<r.length-1&&n.update("\0")});let i=n.digest("hex"),o=e.kind==="github"||e.kind==="gitlab"?e.kind:"url",s=e.kind==="github"?`${e.owner}/${e.repo}`:e.kind==="gitlab"?`${e.namespace}/${e.repo}`:e.canonicalSource,a=e.kind==="github"||e.kind==="gitlab"?e.ref:"fetched-content";return{source:{provider:o,repository:s,ref:a,commitSha:/^[a-f0-9]{40}$/iu.test(a)?a.toLowerCase():i,treeSha:null},files:r.map(l=>({path:l.path,bytes:ye(l)}))}}async function A7(e){let t=await R7(e.source,e.fetchFn),n=[],r=e.requestedSkillSlug??e.source.skillFilter,i,o=new Map;if(r){let d=await E7({source:e.source,fetchFn:e.fetchFn,context:t});n.push(...d.issues);let p=d.results.filter(m=>pa(r,m.skillSlug));if(p.length===0)return{source:e.source,results:d.results,issues:n};i=new Set(p.map(m=>m.relativeSkillRoot));for(let m of p){let h=m.files.find(g=>g.path==="SKILL.md");h?.content!==void 0&&o.set(m.relativeSkillFile,h.content)}}let s=new Map([...o].map(([d,p])=>[d,{content:p}])),a=await F7({fileSet:t.fileSet,fetchFile:async d=>{let p=s.get(d);if(p!==void 0)return p;let m=await e.fetchFn(Sj(e.source,nu(t.sourceRoot,d)));if(!m.ok)throw await Si(m);let h=en(new Uint8Array(await m.arrayBuffer()),m.headers.get("content-type"));return s.set(d,h),h},onlySkillRoots:i},n),l=new Map;for(let d of a){let p=l.get(d.skillSlug);(!p||yC(d,p)<0)&&l.set(d.skillSlug,d)}let c=[...l.values()].filter(d=>pa(r,d.skillSlug)),u=c.length===0?{commitSha:e.source.ref,treeSha:null}:await W7(e.source,e.fetchFn,Z7(c));return{source:e.source,results:c.map(d=>({skillSlug:d.skillSlug,description:d.description,...d.originalSkillName?{originalSkillName:d.originalSkillName}:{},sourceKind:e.source.kind,relativeSkillRoot:d.relativeSkillRoot,relativeSkillFile:d.relativeSkillFile,discoveryRoute:d.discoveryRoute,...d.pluginName?{pluginName:d.pluginName}:{},...d.pluginManifestPath?{pluginManifestPath:d.pluginManifestPath}:{},validation:{valid:d.validation.valid,issueCount:d.validation.issues.length},...d.normalizationIssues&&d.normalizationIssues.length>0?{normalizationIssues:d.normalizationIssues}:{},...d.normalizationProvenance?{normalizationProvenance:d.normalizationProvenance}:{},files:d.files,providerFileAttestations:L7(d,t.providerBlobByPath),losslessImport:{source:{provider:e.source.kind,repository:e.source.kind==="github"?`${e.source.owner}/${e.source.repo}`:`${e.source.namespace}/${e.source.repo}`,ref:e.source.ref,commitSha:u.commitSha,treeSha:u.treeSha},files:d.originalFiles.map(p=>{let m=nu(d.relativeSkillRoot,p.path);return{path:m,bytes:ye(p),providerObjectId:t.providerBlobByPath.get(m)??void 0}})}})).sort((d,p)=>d.skillSlug.localeCompare(p.skillSlug)||d.relativeSkillRoot.localeCompare(p.relativeSkillRoot)),issues:n}}async function R7(e,t){let n=nY(e.subpath),i=(await K7(e,t)).map(s=>{let a=_i(s.path,n);return a===null?null:{...s,path:a}}).filter(s=>s!==null),o=i.map(s=>s.path);if(o.length===0)throw new Error(`Remote repository path "${e.subpath}" did not expose any files.`);return{sourceRoot:n,relativeFileEntries:i,fileSet:new Set(o),providerBlobByPath:new Map(i.map(s=>[s.path,s.providerBlobSha]))}}async function E7(e){let t=lY([...e.context.fileSet],".");if(t.length>x7&&!e.requestedSkillSlug&&!e.source.skillFilter)return{source:e.source,results:t.map(o=>$7({entry:o,source:e.source})).sort((o,s)=>o.skillSlug.localeCompare(s.skillSlug)||o.relativeSkillRoot.localeCompare(s.relativeSkillRoot)),issues:[{severity:"warning",code:"remote-source-large-index",message:`Found ${t.length} Skills Layer-compatible entries; listing uses repository paths to stay within source host request limits. Select a specific skill or subfolder for full validation details.`}]};let n=[],i=(await O7(t,8,async o=>T7({entry:o,source:e.source,sourceRoot:e.context.sourceRoot,fetchFn:e.fetchFn,requestedSkillSlug:e.requestedSkillSlug??e.source.skillFilter,issues:n}))).filter(o=>o!==null).sort((o,s)=>o.skillSlug.localeCompare(s.skillSlug)||o.relativeSkillRoot.localeCompare(s.relativeSkillRoot));return{source:e.source,results:i,issues:n}}function $7(e){let t=D7(e.entry),n=bj(e.entry.skillRoot);return{skillSlug:t,description:`Discovered at ${e.entry.skillRoot}. Select this skill or subfolder for full details.`,sourceKind:e.source.kind,relativeSkillRoot:e.entry.skillRoot,relativeSkillFile:e.entry.skillFilePath,discoveryRoute:n,fileCount:e.entry.bundleFileCount,validation:{valid:!0,issueCount:0},files:[]}}function D7(e){let t=e.skillRoot==="."?nt.basename(nt.dirname(e.skillFilePath)):nt.basename(e.skillRoot);return mo(t)??mo(e.skillRoot.replace(/\//gu,"-"))??`source-skill-${sg("sha256").update(e.skillRoot).digest("hex").slice(0,12)}`}async function T7(e){let t=await e.fetchFn(Sj(e.source,nu(e.sourceRoot,e.entry.skillFilePath)));if(!t.ok)return e.issues.push({severity:"warning",code:"remote-skill-unreadable",message:(await Si(t)).message,path:e.entry.skillFilePath}),null;let n=await t.text(),r=e.entry.skillRoot!=="."?mo(nt.basename(e.entry.skillRoot))??void 0:void 0,i=rg({files:[{path:"SKILL.md",content:n}],fallbackSkillSlug:r,allowNormalization:!0}),o=i.validation,s=i.skillSlug??iu(o,null);if(!s)return fa(e.issues,o,e.entry.skillFilePath),null;if(!pa(e.requestedSkillSlug,s))return null;if(!o.parsedSkill)return fa(e.issues,o,e.entry.skillFilePath),null;let a=bj(e.entry.skillRoot);return{skillSlug:s,description:i.description??o.parsedSkill.frontmatter.description,...i.originalSkillName?{originalSkillName:i.originalSkillName}:{},sourceKind:e.source.kind,relativeSkillRoot:e.entry.skillRoot,relativeSkillFile:e.entry.skillFilePath,discoveryRoute:a,fileCount:e.entry.bundleFileCount,validation:{valid:o.valid,issueCount:o.issues.length},...i.normalizationIssues.length>0?{normalizationIssues:i.normalizationIssues}:{},...i.normalizationProvenance?{normalizationProvenance:i.normalizationProvenance}:{},files:i.files}}function bj(e){return gC().find(n=>n.absolutePath===e)?.discoveryRoute??(e==="."?"root":"recursive")}async function O7(e,t,n){let r=new Array(e.length),i=0,o=Math.min(Math.max(t,1),e.length);return await Promise.all(Array.from({length:o},async()=>{for(;i<e.length;){let s=i;i+=1,r[s]=await n(e[s],s)}})),r}function L7(e,t){return e.files.map(n=>{let r=nu(e.relativeSkillRoot,n.path);return{path:n.path,providerBlobSha:t.get(r)??null,contentSha256:J7(ye(n))}})}async function j7(e,t){let n=rY(e.files);return(await Promise.all(n.map(async i=>{let o=await t(e.fileUrls?.[i]??iY(e.sourceUrl,i));if(!o.ok)throw await Si(o);return{path:i,...en(new Uint8Array(await o.arrayBuffer()),o.headers.get("content-type"))}}))).sort((i,o)=>i.path.localeCompare(o.path))}async function N7(e){let t=xi(e.platform),n=t.resolve(e.cwd,e.source.location);if(!(await yj(n)).isDirectory()){let l=[{path:t.basename(n),...en(new Uint8Array(await mC(n)))}],c=tt(l),u=iu(c,e.source);if(!u||!pa(e.source.skillFilter,u)){let d=oY(c,t.basename(n));return{source:e.source,results:[],issues:d}}return{source:e.source,results:[{skillSlug:u,description:c.parsedSkill?.frontmatter.description??u,sourceKind:"local",relativeSkillRoot:".",relativeSkillFile:t.basename(n),discoveryRoute:"remote_file",validation:{valid:c.valid,issueCount:c.issues.length},files:l}],issues:[]}}let i=[],o=await B7(n,e.platform,i),s=new Map;for(let l of o){let c=s.get(l.skillSlug);(!c||yC(l,c)<0)&&s.set(l.skillSlug,l)}let a=[...s.values()].filter(l=>pa(e.source.skillFilter,l.skillSlug)).map(l=>({skillSlug:l.skillSlug,description:l.description,sourceKind:"local",relativeSkillRoot:l.relativeSkillRoot,relativeSkillFile:l.relativeSkillFile,discoveryRoute:l.discoveryRoute,...l.pluginName?{pluginName:l.pluginName}:{},...l.pluginManifestPath?{pluginManifestPath:l.pluginManifestPath}:{},validation:{valid:l.validation.valid,issueCount:l.validation.issues.length},files:l.files})).sort((l,c)=>l.skillSlug.localeCompare(c.skillSlug)||l.relativeSkillRoot.localeCompare(c.relativeSkillRoot));return{source:e.source,results:a,issues:i}}async function F7(e,t){let n=new Map,r=new Set,i=gC();for(let s of i){let a=s.discoveryRoute==="root"?e.fileSet.has("SKILL.md")?["SKILL.md"]:[]:tu(e.fileSet,s.absolutePath,{maxDepth:5,ignoreDirNames:or});for(let l of a){if(r.has(l)||e.onlySkillRoots&&!e.onlySkillRoots.has(mt(nt.dirname(l))))continue;r.add(l);let c=await pC({allFiles:e.fileSet,fetchFile:e.fetchFile,skillFilePath:l,discoveryRoute:s.discoveryRoute,allowNormalization:e.allowNormalization,issues:t});c&&ua(n,c)}}let o=await z7(e.fileSet,e.fetchFile,t,e.allowNormalization);for(let s of o)ua(n,s);for(let s of tu(e.fileSet,".",{maxDepth:6,ignoreDirNames:or})){if(r.has(s)||e.onlySkillRoots&&!e.onlySkillRoots.has(mt(nt.dirname(s))))continue;r.add(s);let a=await pC({allFiles:e.fileSet,fetchFile:e.fetchFile,skillFilePath:s,discoveryRoute:"recursive",allowNormalization:e.allowNormalization,issues:t});a&&ua(n,a)}return[...n.values()]}async function B7(e,t,n){let r=xi(t),i=new Map,o=new Set,s=U7(e,t);for(let c of s){if(!await ru(c.absolutePath))continue;let u=c.discoveryRoute==="root"?[r.join(c.absolutePath,"SKILL.md")]:await fC(c.absolutePath,t,{maxDepth:5,ignoreDirNames:or});for(let d of u){let p=r.normalize(d);if(o.has(p)||!await ru(p))continue;o.add(p);let m=await dC({rootPath:e,skillFilePath:p,platform:t,discoveryRoute:c.discoveryRoute,issues:n});m&&ua(i,m)}}let a=await q7(e,t,n);for(let c of a)ua(i,c);let l=await fC(e,t,{maxDepth:6,ignoreDirNames:or});for(let c of l){let u=r.normalize(c);if(o.has(u))continue;o.add(u);let d=await dC({rootPath:e,skillFilePath:u,platform:t,discoveryRoute:"recursive",issues:n});d&&ua(i,d)}return[...i.values()]}var or=new Set([".git",".skills-layer","node_modules","dist","coverage"]),M7=/(^|\/)SKILL\.md$/;function gC(){let e=new Map;e.set(".","root"),e.set("skills","skills"),e.set("skills/.curated","curated"),e.set("skills/.experimental","experimental"),e.set("skills/.system","system");for(let t of Qe({},"linux","/repo")){let n=Sn(nt.relative("/repo",t.targets.projectSkillsPath));n.length===0||n==="skills"||e.set(n,"agent")}return[...e.entries()].map(([t,n])=>({absolutePath:t,discoveryRoute:n}))}function U7(e,t){let n=xi(t),r=new Map;r.set(e,"root"),r.set(n.join(e,"skills"),"skills"),r.set(n.join(e,"skills",".curated"),"curated"),r.set(n.join(e,"skills",".experimental"),"experimental"),r.set(n.join(e,"skills",".system"),"system");for(let i of Qe({},t,e)){let o=Sn(n.relative(e,i.targets.projectSkillsPath));o.length===0||o==="skills"||r.set(i.targets.projectSkillsPath,"agent")}return[...r.entries()].map(([i,o])=>({absolutePath:i,discoveryRoute:o}))}async function z7(e,t,n,r){let i=[".claude-plugin/marketplace.json",".claude-plugin/plugin.json"].filter(s=>e.has(s)),o=[];for(let s of i){let a;try{a=JSON.parse(Y7(await t(s),s))}catch{n.push({severity:"warning",code:"plugin-manifest-invalid",message:"Plugin manifest could not be parsed as JSON.",path:s});continue}let l=_j(a,nt.dirname(s));if(l.length===0){n.push({severity:"warning",code:"plugin-manifest-empty",message:"Plugin manifest did not declare a usable plugin or skills root.",path:s});continue}for(let c of l){let u=mt(c.relativeRootPath),d=tu(e,u,{maxDepth:5,ignoreDirNames:or});for(let p of d){let m=await pC({allFiles:e,fetchFile:t,skillFilePath:p,discoveryRoute:"plugin_manifest",pluginName:c.pluginName,pluginManifestPath:s,allowNormalization:r,issues:n});m&&o.push(m)}}}return o}async function q7(e,t,n){let r=xi(t),i=[r.join(e,".claude-plugin","marketplace.json"),r.join(e,".claude-plugin","plugin.json")],o=[];for(let s of i){if(!await ru(s))continue;let a;try{a=JSON.parse(await mC(s,"utf8"))}catch{n.push({severity:"warning",code:"plugin-manifest-invalid",message:"Plugin manifest could not be parsed as JSON.",path:Sn(r.relative(e,s))});continue}let l=_j(a,r.relative(e,vj(s)));if(l.length===0){n.push({severity:"warning",code:"plugin-manifest-empty",message:"Plugin manifest did not declare a usable plugin or skills root.",path:Sn(r.relative(e,s))});continue}for(let c of l){let u=r.resolve(e,...c.relativeRootPath.split("/"));if(!Pj(e,u,t)){n.push({severity:"warning",code:"plugin-root-escaped",message:"Plugin manifest resolved outside the inspected source root and was ignored.",path:Sn(r.relative(e,s))});continue}if(!await ru(u))continue;let d=await fC(u,t,{maxDepth:5,ignoreDirNames:or});for(let p of d){let m=await dC({rootPath:e,skillFilePath:p,platform:t,discoveryRoute:"plugin_manifest",pluginName:c.pluginName,pluginManifestPath:Sn(r.relative(e,s)),issues:n});m&&o.push(m)}}}return o}function _j(e,t){if(!cC(e))return[];let n=t.length===0?".":Sn(t),r=lC(e,["plugin_root","pluginRoot","skills_root","skillsRoot","root","path","directory"]),i=[];if(Array.isArray(e.plugins))for(let o of e.plugins){if(!cC(o))continue;let s=lC(o,["plugin_root","pluginRoot","skills_root","skillsRoot","root","path","directory"]),a=typeof o.name=="string"&&o.name.trim().length>0?o.name.trim():void 0,l=s??(r&&a?`${r}/${a}`:void 0);l&&i.push({pluginName:a,relativeRootPath:ig(n,l)})}if(Array.isArray(e.skills))for(let o of e.skills){if(typeof o=="string"&&o.trim().length>0){let c=r?`${r}/${o.trim()}`:o.trim();i.push({relativeRootPath:ig(n,c)});continue}if(!cC(o))continue;let s=lC(o,["root","path","directory"]),a=typeof o.name=="string"&&o.name.trim().length>0?o.name.trim():void 0,l=s??(r&&a?`${r}/${a}`:void 0);l&&i.push({pluginName:a,relativeRootPath:ig(n,l)})}return i.length>0?i:r?[{pluginName:typeof e.name=="string"?e.name.trim():void 0,relativeRootPath:ig(n,r)}]:[{pluginName:typeof e.name=="string"?e.name.trim():void 0,relativeRootPath:n}]}function ig(e,t){let n=mt(t);return e===".claude-plugin"&&!t.startsWith(".")?n:nu(e,n)}async function dC(e){let t=xi(e.platform),n=vj(e.skillFilePath);if(!Pj(e.rootPath,n,e.platform))return null;let r;try{r=await V7(n,e.platform)}catch(l){if(!(l instanceof da))throw l;let c=l.message;return e.issues.push({severity:"warning",code:"skill-too-large",message:c,path:Sn(t.relative(e.rootPath,e.skillFilePath))}),null}let i=tt(r),o=iu(i,null);if(!o||!i.parsedSkill)return fa(e.issues,i,Sn(t.relative(e.rootPath,e.skillFilePath))),null;let s=mt(t.relative(e.rootPath,n)),a=Cj(e.discoveryRoute,s);return{skillSlug:o,description:i.parsedSkill.frontmatter.description,relativeSkillRoot:s,relativeSkillFile:Sn(t.relative(e.rootPath,e.skillFilePath)),discoveryRoute:a,...e.pluginName?{pluginName:e.pluginName}:{},...e.pluginManifestPath?{pluginManifestPath:e.pluginManifestPath}:{},files:r,originalFiles:r,validation:i}}async function pC(e){let t=mt(nt.dirname(e.skillFilePath)),n;try{n=await G7(t,e.allFiles,e.fetchFile)}catch(c){if(!(c instanceof da))throw c;let u=c.message;return e.issues.push({severity:"warning",code:"skill-too-large",message:u,path:e.skillFilePath}),null}let r=t!=="."?mo(nt.basename(t))??void 0:void 0,i=rg({files:n,fallbackSkillSlug:r,allowNormalization:e.allowNormalization??!0}),o=i.validation,s=i.skillSlug??iu(o,null);if(!s||!o.parsedSkill)return fa(e.issues,o,e.skillFilePath),null;let a=mt(t),l=Cj(e.discoveryRoute,a);return{skillSlug:s,description:i.description??o.parsedSkill.frontmatter.description,...i.originalSkillName?{originalSkillName:i.originalSkillName}:{},relativeSkillRoot:a,relativeSkillFile:e.skillFilePath,discoveryRoute:l,...e.pluginName?{pluginName:e.pluginName}:{},...e.pluginManifestPath?{pluginManifestPath:e.pluginManifestPath}:{},...i.normalizationIssues.length>0?{normalizationIssues:i.normalizationIssues}:{},...i.normalizationProvenance?{normalizationProvenance:i.normalizationProvenance}:{},files:i.files,originalFiles:n,validation:o}}async function V7(e,t){let n=[],r=xi(t);async function i(o){let s=await hj(o,{withFileTypes:!0});for(let a of s){let l=r.join(o,a.name),c=Sn(r.relative(e,l));if(a.isDirectory()){if(or.has(a.name)||l!==e&&await ru(r.join(l,"SKILL.md")))continue;await i(l);continue}if(!hC(c)){if(n.length>=og)throw new da(`Skill root contains too many files. The maximum allowed is ${og}.`);n.push({path:c,...en(new Uint8Array(await mC(l)))})}}}return await i(e),n.sort((o,s)=>o.path.localeCompare(s.path))}async function G7(e,t,n){let r=new Set([...t].filter(o=>o==="SKILL.md"||o.endsWith("/SKILL.md")).map(o=>mt(nt.dirname(o)))),i=[...t].filter(o=>_i(o,e)!==null).filter(o=>!Ij(e,o,r)).filter(o=>{let s=_i(o,e);return s!==null&&!hC(s)}).sort((o,s)=>o.localeCompare(s));if(i.length>og)throw new da(`Skill root contains too many files (${i.length}). The maximum allowed is ${og}.`);return Promise.all(i.map(async o=>{let s;try{s=await n(o)}catch(a){throw new ca(a)}return{path:_i(o,e)??o,...typeof s=="string"?{content:s}:s}}))}async function fC(e,t,n){let r=xi(t),i=[];async function o(s,a){if(a>n.maxDepth)return;let l=await hj(s,{withFileTypes:!0});for(let c of l){if(c.isDirectory()){if(n.ignoreDirNames.has(c.name))continue;await o(r.join(s,c.name),a+1);continue}c.name==="SKILL.md"&&i.push(r.join(s,c.name))}}return await o(e,0),i.sort()}function tu(e,t,n){let r=[];for(let i of e){if(nt.basename(i)!=="SKILL.md")continue;let o=_i(i,t);if(o===null)continue;let s=o.split("/").filter(a=>a.length>0);s.length!==0&&(s.slice(0,-1).some(a=>n.ignoreDirNames.has(a))||s.length-1>n.maxDepth||r.push(i))}return r.sort((i,o)=>i.localeCompare(o))}function H7(e){return e.kind==="url"?e.url:e.kind==="well-known"?e.sourceUrl:e.rawUrl}function Sj(e,t){return e.kind==="github"?`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref}/${t}`:`https://${e.host}/${e.namespace}/${e.repo}/-/raw/${e.ref}/${t}`}function hC(e){let t=mt(e);if(t==="."||t.length===0)return!1;let n=t.split("/").filter(o=>o.length>0);if(n.some(o=>or.has(o)))return!0;let r=n[n.length-1]??"",i=Buffer.from([46,68,83,95,83,116,111,114,101]).toString("ascii");return r===i||r==="Thumbs.db"}async function K7(e,t){if(e.kind==="github"){let o=await t(`https://api.github.com/repos/${e.owner}/${e.repo}/git/trees/${encodeURIComponent(e.ref)}?recursive=1`,{headers:{"user-agent":"skills-layer-source-inspector"}});if(!o.ok)throw new ho(o.status,await Si(o));return((await o.json()).tree??[]).filter(a=>a.type==="blob"&&typeof a.path=="string"&&!dj(a.mode)).map(a=>({path:a.path,providerBlobSha:eu(a.sha),sizeBytes:Number.isSafeInteger(a.size)&&(a.size??-1)>=0?a.size:null})).sort((a,l)=>a.path.localeCompare(l.path))}let n=encodeURIComponent(`${e.namespace}/${e.repo}`),r=[],i=1;for(;;){let o=new URLSearchParams({recursive:"true",ref:e.ref,per_page:"100",page:String(i)}),s=await t(`https://${e.host}/api/v4/projects/${n}/repository/tree?${o.toString()}`);if(!s.ok)throw new ho(s.status,await Si(s));let a=await s.json();r.push(...a.filter(c=>c.type==="blob"&&typeof c.path=="string"&&!dj(c.mode)).map(c=>({path:c.path,providerBlobSha:eu(c.id),sizeBytes:null})));let l=s.headers.get("x-next-page");if(!l||l.trim().length===0||(i=Number.parseInt(l,10),Number.isNaN(i)||i<1))break}return r.sort((o,s)=>o.path.localeCompare(s.path))}function dj(e){return e==="120000"}async function W7(e,t,n){if(/^[a-f0-9]{40}$/iu.test(e.ref))return{commitSha:e.ref.toLowerCase(),treeSha:null};if(e.kind==="github")try{let i=await t(`https://api.github.com/repos/${e.owner}/${e.repo}/commits/${encodeURIComponent(e.ref)}`,{headers:{"user-agent":"skills-layer-source-inspector"}});if(!i.ok)throw new ho(i.status,await Si(i));let o=await i.json(),s=eu(o.sha);if(!s)throw new Error("GitHub source revision did not resolve to an immutable commit.");return{commitSha:s,treeSha:eu(o.commit?.tree?.sha)}}catch{return{commitSha:n,treeSha:null}}let r=encodeURIComponent(`${e.namespace}/${e.repo}`);try{let i=await t(`https://${e.host}/api/v4/projects/${r}/repository/commits/${encodeURIComponent(e.ref)}`);if(!i.ok)throw new ho(i.status,await Si(i));let o=await i.json(),s=eu(o.id);if(!s)throw new Error("GitLab source revision did not resolve to an immutable commit.");return{commitSha:s,treeSha:null}}catch{return{commitSha:n,treeSha:null}}}function Z7(e){let t=sg("sha256");for(let n of[...e].sort((r,i)=>r.relativeSkillRoot.localeCompare(i.relativeSkillRoot))){t.update(n.relativeSkillRoot),t.update("\0");for(let r of[...n.originalFiles].sort((i,o)=>i.path.localeCompare(o.path)))t.update(r.path),t.update("\0"),t.update(ye(r)),t.update("\0")}return`content-sha256:${t.digest("hex")}`}function eu(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function J7(e){return`sha256:${sg("sha256").update(e).digest("hex")}`}function Y7(e,t){if(typeof e=="string")return e;if(typeof e.content!="string")throw new Error(`${t} must be valid bounded UTF-8 text.`);return e.content}async function X7(e,t){let n=new URL(e),r=n.pathname.replace(/\/+$/u,""),i=r.match(/^(.*\/\.well-known\/skills)(?:\/.*)?$/iu),o=[`${n.protocol}//${n.host}${r}/.well-known/skills/index.json`];i&&o.push(`${n.protocol}//${n.host}${i[1]}/index.json`),r.length>0&&!r.includes("/.well-known/skills")&&o.push(`${n.protocol}//${n.host}/.well-known/skills/index.json`),r.endsWith("/.well-known/skills")&&o.unshift(`${n.protocol}//${n.host}${r}/index.json`),r.endsWith("/.well-known/skills/index.json")&&o.unshift(`${n.protocol}//${n.host}${r}`);for(let s of[...new Set(o)])try{let a=await t(s);if(!a.ok||!(a.headers.get("content-type")??"").includes("json"))continue;return{indexUrl:s,index:lj(await a.json())}}catch{continue}return null}async function Q7(e,t){try{let n=await t(e);return!n.ok||!(n.headers.get("content-type")??"").includes("json")?null:sj(await n.json())}catch{return null}}async function pj(e,t){try{let n=await t(e);return!n.ok||!(n.headers.get("content-type")??"").includes("json")?null:aj(await n.json())}catch{return null}}function fj(e){let t={};for(let n of e.manifest.skill.files)t[n.path]=n.url;return{kind:"well-known",input:e.skillFilter?`${e.inputSource.input}#${e.skillFilter}`:e.inputSource.input,indexUrl:e.detectedIndex.indexUrl,providerName:e.manifest.provider.name||e.detectedIndex.index.provider.name,providerUrl:e.manifest.provider.baseUrl||e.detectedIndex.index.provider.baseUrl,skillSlug:e.manifest.skill.slug,skillManifestUrl:e.manifestUrl,sourceUrl:e.manifest.skill.sourceUrl,files:e.manifest.skill.files.map(n=>n.path),fileUrls:t,canonicalSource:`${e.detectedIndex.indexUrl}#${e.manifest.skill.slug}`,...e.skillFilter?{skillFilter:e.skillFilter}:{}}}function mj(e,t){let n=e;for(let[r,i]of Object.entries(t))n=n.replaceAll(`{${r}}`,encodeURIComponent(i));return n}function eY(e){try{return new URL(e).searchParams.get("q")?.trim()??""}catch{return""}}function xj(e){let t=e.toLowerCase();return t.endsWith(".md")||t.endsWith(".txt")}function tY(e){try{let r=new URL(e).pathname.match(/\/\.well-known\/skills\/([^/]+)(?:\/.*)?$/iu)?.[1];return r&&r!=="index.json"&&r!=="search.json"?r:void 0}catch{return}}function iu(e,t){return e.parsedSkill?.frontmatter.name??(t?.kind==="well-known"?t.skillSlug:void 0)}function pa(e,t){return!e||e===t}function yC(e,t){return gj(e.discoveryRoute)-gj(t.discoveryRoute)||e.relativeSkillRoot.localeCompare(t.relativeSkillRoot)}function ua(e,t){let n=`${t.skillSlug}:${t.relativeSkillRoot}`,r=e.get(n);if(!r){e.set(n,t);return}let i=yC(t,r)<0?t:r,o=i===t?r:t;e.set(n,{...i,pluginName:i.pluginName??o.pluginName,pluginManifestPath:i.pluginManifestPath??o.pluginManifestPath})}function gj(e){switch(e){case"remote_file":return 0;case"root":return 1;case"curated":return 2;case"skills":return 3;case"system":return 4;case"experimental":return 5;case"plugin_manifest":return 6;case"agent":return 7;case"recursive":return 8}}function mt(e){let t=Sn(e);return t.length===0?".":t}function nY(e){let t=mt(e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""));return t==="SKILL.md"?".":t.endsWith("/SKILL.md")?mt(nt.dirname(t)):t}function rY(e){let t=(e??[]).map(r=>r.replaceAll("\\","/").replace(/^\/+/u,"").trim()).filter(r=>r.length>0),n=[...new Set(t)];return n.includes("SKILL.md")?n:["SKILL.md",...n]}function iY(e,t){let n=new URL(e),r=n.toString().endsWith("/SKILL.md")?n.toString().slice(0,-8):`${n.toString().replace(/\/+$/u,"")}/`;return new URL(t.replace(/^\/+/u,""),r).toString()}function Cj(e,t){return e==="skills"&&t.startsWith("skills/.curated/")?"curated":e==="skills"&&t.startsWith("skills/.system/")?"system":e==="skills"&&t.startsWith("skills/.experimental/")?"experimental":e}function xi(e){return e==="win32"?S7:nt}function Sn(e){return e.replaceAll("\\","/")}function lC(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}function cC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nu(e,t){let n=e==="."?"":e.replace(/\/+$/u,""),r=t.replace(/^\.\/+/u,"");return[n,r].filter(i=>i.length>0).join("/")||"."}function _i(e,t){let n=mt(e),r=mt(t);return r==="."?n:n===r?".":n.startsWith(`${r}/`)?n.slice(r.length+1):null}function Ij(e,t,n){let r=mt(nt.dirname(t));for(;r!=="."&&r!==e;){if(n.has(r))return!0;r=mt(nt.dirname(r))}return!1}function oY(e,t){let n=[];return fa(n,e,t),n}function fa(e,t,n){if(!t.valid)for(let r of t.issues)r.severity==="error"&&sY(e,{severity:"warning",code:r.code,message:r.message,path:n})}function sY(e,t){e.some(n=>n.code===t.code&&n.message===t.message&&n.path===t.path)||e.push(t)}function Pj(e,t,n){let r=xi(n),i=r.resolve(e),o=r.resolve(t),s=r.relative(i,o);return s.length===0||!s.startsWith("..")&&!r.isAbsolute(s)}async function ru(e){try{return await yj(e),!0}catch{return!1}}var ho=class extends Error{constructor(n,r){super(r.message);this.status=n;this.name="ApiErrorLike"}status};async function Si(e){let t=e.headers.get("content-type")??"",n=e.clone();if(t.includes("application/json"))try{let r=await e.json(),i=typeof r.error=="string"?r.error:typeof r.message=="string"?r.message:"";if(i.trim().length>0)return new Error(i.trim())}catch{}return new Error(await n.text()||`Remote source request failed with ${e.status}.`)}var aY=18;function lY(e,t){let n=e.map(c=>_i(c,t)).filter(c=>c!==null),r=new Set(n),i=new Set,o=[],s=gC();for(let c of s){let u=c.discoveryRoute==="root"?r.has("SKILL.md")?["SKILL.md"]:[]:tu(r,c.absolutePath,{maxDepth:5,ignoreDirNames:or});for(let d of u)i.has(d)||(i.add(d),o.push(d))}for(let c of tu(r,".",{maxDepth:6,ignoreDirNames:or}))i.has(c)||(i.add(c),o.push(c));let a=new Set(o.map(c=>mt(nt.dirname(c)))),l=[];for(let c of o){let u=mt(nt.dirname(c)),d=[...r].filter(p=>_i(p,u)!==null).filter(p=>!Ij(u,p,a)).filter(p=>{let m=_i(p,u);return m!==null&&!hC(m)}).sort((p,m)=>p.localeCompare(m));l.push({skillFilePath:c,skillRoot:u,bundleFilePaths:d,bundleFileCount:d.length,estimatedCost:d.length+aY})}return l.sort((c,u)=>c.skillFilePath.localeCompare(u.skillFilePath))}import{constants as Aj}from"node:fs";import{lstat as cg,open as cY,opendir as uY,realpath as $j}from"node:fs/promises";import{dirname as Dj,isAbsolute as kC,parse as Tj,relative as ou,resolve as su,sep as Oj}from"node:path";var pe=class extends Error{code;issueCodes;issues;preview;constructor(t,n=[],r){super(`Local bundle rejected (${t}).`),this.name="LocalBundleIntakeError",this.code=t,this.issueCodes=[...new Set(n)].sort((i,o)=>i.localeCompare(o)),this.issues=r?.issues??[],this.preview=r?.preview}},dY=32*1024,pY=64*1024;async function ma(e){let t=gY(e.limits),n=hY(e.maxTraversalEntries,t.maxFiles),r=su(e.cwd),i=su(r,e.sourcePath);await yY(r,e.sourcePath,i);let o=await Bj(i);wC(o);let s=await Ej(i),a=o.isDirectory()?s:await Ej(Dj(i));bC(a,s);let l={rootRealPath:a,limits:t,maxTraversalEntries:n,traversalEntries:0,fileCount:0,declaredTotalBytes:0,skillsIgnore:"",excludePath:Ay(),files:[],excluded:[],hooks:e.hooks};if(o.isFile()){let d=IY(i),p=l.excludePath(d);p?l.excluded.push({path:d,reason:p}):await Nj(i,d,o,l)}else await wY(i,o,l);let c;try{c=Zr({files:l.files,skillsIgnore:l.skillsIgnore,limits:t})}catch{let d=Wr({files:l.files,skillsIgnore:l.skillsIgnore,limits:t});throw new pe("canonical_bundle_rejected",d.issues.map(p=>p.code),fY(d))}if(c.files.length===0)throw new pe("local_bundle_empty");let u=new Map;for(let d of[...l.excluded,...c.excluded])u.set(d.path,d);return{...c,excluded:[...u.values()].sort((d,p)=>d.path.localeCompare(p.path))}}function fY(e){return{issues:e.issues.map(t=>{let n=mY(t.code),r=Rj(t.path,t.code);return{code:t.code,...r?{path:r}:{},message:t.message,...n}}),preview:{fileCount:e.preview.fileCount,totalBytes:e.preview.totalBytes,bundleSha256:e.preview.bundleSha256,files:e.preview.files.filter(t=>Rj(t.path,"preview")).map(t=>({...t}))}}}function Rj(e,t){if(!(!e||t==="pii_path"||e.startsWith("/")||/^[A-Za-z]:/u.test(e)||e.includes("\\")||e.split("/").some(n=>!n||n==="."||n==="..")||/[^\s@]+@[^\s@]+\.[^\s@]+/u.test(e)))return e}function mY(e){return e==="pii_email"||e==="pii_phone"||e==="pii_path"?{remediationId:"remove_personal_data",remediation:"Remove personal contact data from distributable skill files and validate again."}:e.startsWith("secret_")?{remediationId:"remove_secret",remediation:"Remove the secret and reference a runtime-provided credential instead."}:e.includes("path")||e==="reserved_path"||e==="binary_content"?{remediationId:"fix_bundle_entry",remediation:"Rename, remove, or convert the listed bundle entry to portable UTF-8 text."}:e.includes("exceeded")||e==="file_too_large"?{remediationId:"reduce_bundle_size",remediation:"Reduce the listed file or bundle size to the documented canonical limits."}:{remediationId:"fix_canonical_bundle",remediation:"Correct the listed canonical intake issue and run validation again."}}function gY(e){let t={...wt,...e};return Wr({files:[],limits:t,runDlp:!1}),t}function hY(e,t){let n=e??Math.max(256,t*8);if(!Number.isInteger(n)||n<=0)throw new pe("local_traversal_budget_exceeded");return n}async function yY(e,t,n){let r=kY(e,t,n);for(let i=0;i<r.length;i+=1){let o=await Bj(r[i]);if(o.isSymbolicLink()){if(vY(r[i],o,t,e,n,i))continue;throw new pe("local_entry_symlink")}if(i<r.length-1&&!o.isDirectory())throw new pe("local_entry_non_regular")}}function vY(e,t,n,r,i,o,s=process.platform){if(s==="win32"||!kC(n)||_C(ou(r,i))||o!==0||t.uid!==0n)return!1;let a=Tj(e).root;return Dj(e)===a}function kY(e,t,n){if(!kC(t))return vC(e,ou(e,n));let r=ou(e,n);if(_C(r))return vC(e,r);let i=Tj(n).root;return vC(i,ou(i,n))}function vC(e,t){let n=[],r=e;for(let i of t.split(Oj))!i||i==="."||(r=su(r,i),n.at(-1)!==r&&n.push(r));return n}async function wY(e,t,n){let r=await jj(e,t,n);if(r.includes(".skillsignore")){let i=su(e,".skillsignore"),o=await Mj(i);if(wC(o),!o.isFile())throw new pe("local_entry_non_regular");n.skillsIgnore=await _Y(i,".skillsignore",o,dY,n);try{n.excludePath=Ay(n.skillsIgnore)}catch{throw new pe("canonical_bundle_rejected",["skillsignore_invalid"])}n.files.push({path:".skillsignore",content:n.skillsIgnore})}await Lj(e,t,r,"",n)}async function bY(e,t,n,r){let i=await jj(e,n,r);await Lj(e,n,i,t,r)}async function Lj(e,t,n,r,i){for(let o of n){let s=r?`${r}/${o}`:o;if(!r&&s===".skillsignore")continue;let a=i.excludePath(s);if(a){i.excluded.push({path:s.normalize("NFC"),reason:a});continue}CY(s,i.limits);let l=su(e,o);await i.hooks?.beforeEntryInspection?.({relativePath:s});let c=await Mj(l);wC(c),await i.hooks?.afterEntryInspection?.({relativePath:s,kind:c.isDirectory()?"directory":"file"}),await ag(l,c);let u={relativePath:s,kind:c.isDirectory()?"directory":"file"};await i.hooks?.afterEntryValidation?.(u);let d=await Uj(l);bC(i.rootRealPath,d),c.isDirectory()?await bY(l,s,c,i):await Nj(l,s,c,i)}await ag(e,t)}async function jj(e,t,n){let r;try{r=await uY(e)}catch{throw new pe("local_entry_unreadable")}let i=[];try{for(;;){let o=await r.read();if(!o)break;if(n.traversalEntries+=1,n.traversalEntries>n.maxTraversalEntries)throw new pe("local_traversal_budget_exceeded");i.push(o.name)}}catch(o){throw o instanceof pe?o:new pe("local_entry_unreadable")}finally{await r.close().catch(()=>{})}return await ag(e,t),i.sort((o,s)=>o.localeCompare(s))}async function Nj(e,t,n,r){if(r.fileCount+=1,r.fileCount>r.limits.maxFiles)throw new pe("local_file_count_exceeded");let i=Ey(t,r.limits);if(n.size>BigInt(i))throw new pe("local_file_bytes_exceeded");let o=r.declaredTotalBytes+Number(n.size);if(!Number.isSafeInteger(o)||o>r.limits.maxTotalBytes)throw new pe("local_total_bytes_exceeded",["local_total_bytes_exceeded"],{issues:[{code:"local_total_bytes_exceeded",path:t,message:`Bundle exceeds the ${r.limits.maxTotalBytes}-byte upload limit.`,remediationId:"reduce_bundle_size",remediation:"Remove unnecessary files or reduce their size, then validate again."}]});let s=await Fj(e,t,n,i,r),a=en(s,Sl(t,s));if(typeof a.contentBase64=="string"&&jE(t))throw new pe("local_entry_invalid_utf8");r.declaredTotalBytes=o,r.files.push({path:t,...a})}async function _Y(e,t,n,r,i){let o=await Fj(e,t,n,r,i);try{return new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new pe("local_entry_invalid_utf8")}}async function Fj(e,t,n,r,i){await ag(e,n);let o=await Uj(e);bC(i.rootRealPath,o);let s={relativePath:t,kind:"file"};await i.hooks?.beforeFileOpen?.(s);let a;try{a=await cY(e,Aj.O_RDONLY|Aj.O_NOFOLLOW)}catch(l){throw new pe(PY(l)?"local_entry_raced":"local_entry_unreadable")}try{let l=await a.stat({bigint:!0});if(!l.isFile())throw new pe("local_entry_non_regular");if(!lg(n,l))throw new pe("local_entry_raced");await i.hooks?.afterFileOpen?.(s);let c=await SY(a,r),u=await a.stat({bigint:!0});if(!lg(l,u)||BigInt(c.byteLength)!==u.size)throw new pe("local_entry_raced");return await i.hooks?.afterFileMetadataValidation?.(s),await xY(e,u),c}catch(l){throw l instanceof pe?l:new pe("local_entry_unreadable")}finally{await a.close().catch(()=>{})}}async function SY(e,t){let n=[],r=0;for(;;){let i=t+1-r,o=Buffer.allocUnsafe(Math.min(pY,i)),{bytesRead:s}=await e.read(o,0,o.byteLength,r);if(s===0)break;if(r+=s,r>t)throw new pe("local_file_bytes_exceeded");n.push(o.subarray(0,s))}return Buffer.concat(n,r)}async function Bj(e){try{return await cg(e,{bigint:!0})}catch{throw new pe("local_entry_unreadable")}}async function Mj(e){try{return await cg(e,{bigint:!0})}catch{throw new pe("local_entry_unreadable")}}function wC(e){if(e.isSymbolicLink())throw new pe("local_entry_symlink");if(!e.isDirectory()&&!e.isFile())throw new pe("local_entry_non_regular")}async function ag(e,t){let n;try{n=await cg(e,{bigint:!0})}catch{throw new pe("local_entry_raced")}if(!lg(t,n))throw new pe("local_entry_raced")}async function xY(e,t){let n;try{n=await cg(e,{bigint:!0})}catch{throw new pe("local_entry_raced")}if(!lg(t,n))throw new pe("local_entry_raced")}function lg(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.mode===t.mode&&e.size===t.size&&e.mtimeNs===t.mtimeNs&&e.ctimeNs===t.ctimeNs}async function Ej(e){try{return await $j(e)}catch{throw new pe("local_entry_unreadable")}}async function Uj(e){try{return await $j(e)}catch{throw new pe("local_entry_raced")}}function bC(e,t){if(!_C(ou(e,t)))throw new pe("local_entry_outside_root")}function _C(e){return e===""||!e.startsWith(`..${Oj}`)&&e!==".."&&!kC(e)}function CY(e,t){if(e.split("/").length>t.maxDepth)throw new pe("local_path_depth_exceeded");if(Buffer.byteLength(e,"utf8")>t.maxPathBytes)throw new pe("local_path_length_exceeded")}function IY(e){let t=e.replaceAll("\\","/").split("/");return t[t.length-1]}function PY(e){return["ELOOP","ENOENT","ENOTDIR"].includes(String(e.code))}var AY=fn(Ji(),1);import{createHash as RY}from"node:crypto";var zj="skills-layer.commercial-rights-declaration.v1",EY="I declare that I own this skill bundle or am authorised by its rightsholder to distribute it commercially, and that charging for it does not infringe the rights of any other person.",Mye=`sha256:${RY("sha256").update(EY).digest("hex")}`;import{createHash as $Y}from"node:crypto";var DY=6,TY=1e3,OY=3e4,LY=5e3,jY=1e3,NY=12e4;function dg(e){return e.reduce((t,n)=>t+cs(n),0)>wt.maxTotalBytes}async function xC(e){let t=e.apiKey?"/api/v1/me/source-hydrations":"/api/v1/source-hydrations",n=e.baseUrl.replace(/\/+$/u,""),r=e.apiKey?{authorization:`Bearer ${e.apiKey}`}:{},i=e.sleep??MY,o=e.files.map(u=>{let d=ye(u);return{file:u,bytes:d,mediaType:u.mediaType?.trim()||Sl(u.path,d),sha256:`sha256:${$Y("sha256").update(d).digest("hex")}`}}),s=await SC(()=>e.fetchFn(`${n}${t}`,{method:"POST",headers:{"content-type":"application/json",...r},body:JSON.stringify({...e.apiKey?{}:{visibility:"public"},files:o.map(({file:u,bytes:d,mediaType:p,sha256:m})=>({path:u.path,sizeBytes:d.byteLength,sha256:m,mediaType:p}))})}),{sleep:i,retryBusy:!1}),a=ug(s,"manifestId"),l=new Map((Array.isArray(s.files)?s.files:[]).filter(u=>!!u&&typeof u=="object"&&!Array.isArray(u)).map(u=>[ug(u,"path"),ug(u,"uploadPath")]));for(let{file:u,bytes:d,mediaType:p}of o){let m=l.get(u.path);if(!m)throw new Error(`Source hydration upload path is missing for ${u.path}.`);await SC(()=>e.fetchFn(`${n}${m}`,{method:"PUT",headers:{"content-type":p,...r},body:Buffer.from(d)}),{sleep:i,retryBusy:!0})}let c=await SC(()=>e.fetchFn(`${n}${t}/${encodeURIComponent(a)}`,{headers:r}),{sleep:i,retryBusy:!1});if(c.status!=="validated")throw new Error("Source hydration upload did not reach validated state.");return{manifestId:a,candidateId:ug(c,"candidateId")}}async function SC(e,t){for(let n=1;;n+=1){let r=await e(),i=await r.text(),o=UY(i),s=n<DY?FY(r,o,n,t.retryBusy):null;if(s===null)return zY(r,i,o);await t.sleep(s)}}function FY(e,t,n,r){return e.status===429?ga(t)&&t.reasonCode==="anonymous_upload_quota_exceeded"?null:qj(e.headers.get("retry-after"))??LY:r&&e.status===409&&BY(t)?qj(e.headers.get("retry-after"))??Math.min(OY,TY*2**(n-1)):null}function BY(e){return ga(e)?e.status==="unavailable"||ga(e.data)&&e.data.status==="unavailable":!1}function qj(e){let t=e?.trim()??"";if(!t)return null;let n=/^\d+$/u.test(t)?Number(t)*1e3:Date.parse(t)-Date.now();return Number.isFinite(n)?Math.min(NY,Math.max(jY,n)):null}function MY(e){return new Promise(t=>setTimeout(t,e))}function UY(e){try{return e?JSON.parse(e):null}catch{return null}}function zY(e,t,n){if(!e.ok){let r=ga(n)&&typeof n.error=="string"?n.error:t||e.statusText||"Source hydration request failed.";throw new Error(r)}if(!ga(n))throw new Error("Source hydration returned an invalid response.");return n.schemaVersion!=="skills-layer.creator.operation.v1"&&ga(n.data)?n.data:n}function ga(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ug(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`Source hydration response is missing ${t}.`);return n}var Hye=256*1024;var Jye=26*1024*1024;var qY=1024*1024;var yo=Object.freeze({...wt,maxTotalBytes:20*qY});var ive=Array.from({length:256},(e,t)=>{let n=t;for(let r=0;r<8;r+=1)n=(n&1)!==0?3988292384^n>>>1:n>>>1;return n>>>0});import{createHash as VY,randomUUID as Kj,timingSafeEqual as GY}from"node:crypto";import{constants as Ii}from"node:fs";import{chmod as HY,lstat as Ai,mkdir as $C,mkdtemp as KY,open as mg,realpath as PC,readdir as WY,rename as Ri,rm as Wj}from"node:fs/promises";import{basename as Ci,dirname as $r,join as xn,parse as gg,posix as CC,resolve as hg,sep as au}from"node:path";var ZY=3e4,Vj=5*6e4,lu=/^sha256:[a-f0-9]{64}$/u,Zj=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,Jj=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,JY=new TextEncoder().encode("SKILLS-LAYER-MANIFEST-V1\0"),yg=typeof Ii.O_NOFOLLOW=="number"?Ii.O_NOFOLLOW:0;async function Yj(e){return Qj(e,!0)}async function Xj(e){return Qj(e,!1)}async function Qj(e,t){let n=YY(e.preActivationTimeoutMs),r=Nd({archiveBytes:e.archiveBytes,envelope:e.envelope});t&&XY(e.approval,r);let i=Cl({archiveBytes:e.archiveBytes,envelope:r});e2(i);let o=hg(e.targetDir),s=await ya(o);if(s===gg(s).root)throw new Error("Atomic install target cannot be a filesystem root.");if(Ci(s)!==r.generation.skillSlug&&Ci(s)!==Mr(r.generation.skillSlug))throw new Error("Atomic install target basename must equal the approved skill slug or its private base name.");let a=$r(s);await uu(a),await $C(a,{recursive:!0,mode:448}),await uu(a);let l=await Fn(a,"Atomic install parent"),c=await TC(s),u=await KY(xn(a,`.${Ci(s)}.skills-layer-stage-`)),d=await Fn(u,"Atomic install stage"),p=null,m=!1,h=!1;try{await vo(e.checkpoint,"after_stage_created");for(let b of i)await QY(u,b),await vo(e.checkpoint,"after_file_written");await ha(u,r.manifest.files,d);let g=await nX({callback:e.preActivate,stageDir:u,files:r.manifest.files,timeoutMs:n});if(g.status!=="passed")throw new Error(`Static pre-activation Eval failed: ${g.reasonCode}`);await ha(u,r.manifest.files,d),await Gj(u,r.manifest.files),await vo(e.checkpoint,"after_static_eval"),await ha(u,r.manifest.files,d),await Gj(u,r.manifest.files),await Pi(a,l,"Atomic install parent changed during staging."),await a2(s,c),await Zt(a),e.expectedPreviousReceipt&&await cu(s,e.expectedPreviousReceipt),c.exists&&(p=xn(a,`.${Ci(s)}.skills-layer-backup-${Kj()}`),await Ri(s,p),m=!0,await Zt(a),await vo(e.checkpoint,"after_target_backed_up"),e.expectedPreviousReceipt&&await cu(p,e.expectedPreviousReceipt)),await Ri(u,s),h=!0,await Zt(a),await vo(e.checkpoint,"after_stage_activated");let y=mX({targetDir:o,generation:r.generation,archiveSha256:r.archive.sha256,manifestSha256:r.manifest.sha256,files:r.manifest.files}),v=await iX(p,a);return p=v.backupStillExists?p:null,{status:c.exists?"replaced":"created",receipt:y,staticEvaluation:g,cleanupPending:v.backupStillExists,...v.backupStillExists&&p?{cleanupPath:p}:{}}}catch(g){throw await rX({targetDir:s,stageDir:u,parentDir:a,backupDir:p,backupMoved:m,stageActivated:h,originalError:g}),g}}function e2(e){if(e.some(t=>typeof t.path=="string"&&t.path!==t.path.normalize("NFC")))throw new Error("Portable install paths must use NFC Unicode normalization.");try{let t=Zr({files:e,runDlp:!1,limits:{maxTotalBytes:ut.maxTotalFileBytes}});if(t.excluded.length>0||t.files.length!==e.length)throw new Error("install-control or excluded paths are not deliverable files");for(let n=0;n<t.files.length;n+=1){let r=t.files[n],i=e.find(o=>o.path===r.path);if(!i||i.content!==r.content)throw new Error("portable normalization changed the approved file set")}}catch(t){throw new Error(`Portable install paths rejected: ${c2(t)}`,{cause:t})}}async function t2(e){if(!Zj.test(e.reasonCode))throw new Error("Quarantine reason code is invalid.");DC(e.receipt);let t=await ya(e.receipt.targetDir),n=$r(t);await uu(t);let r=await Fn(n,"Atomic quarantine parent"),i=await cu(t,e.receipt),o=await s2(e.discoveryRoots),s=await ya(e.quarantineRoot);AC({targetDir:t,quarantineRoot:s,discoveryRoots:o});let a=await r2({callback:e.authorizeQuarantine,context:{receipt:e.receipt,targetDir:t,quarantineRoot:s,discoveryRoots:o,reasonCode:e.reasonCode},receipt:e.receipt,allowedPurposes:["quarantine_blocked","quarantine_revoked"]});await $C(s,{recursive:!0,mode:448}),await uu(s),await HY(s,448);let l=await RC(s,"External quarantine root");AC({targetDir:t,quarantineRoot:l,discoveryRoots:o});let c=await Fn(l,"External quarantine root");if(c.dev!==r.dev)throw new Error("External quarantine root must be on the same filesystem for an atomic fail-closed move.");let u=xn(l,`${Ci(t)}.skills-layer-quarantine-${Kj()}`);await Pi(n,r,"Atomic quarantine parent changed."),await Pi(l,c,"External quarantine root changed."),await Pi(t,i,"Installed generation changed before quarantine."),await Ri(t,u);try{await Zt(n),await Zt(l),await ha(u,e.receipt.files,i),await vo(e.checkpoint,"after_quarantine_rename")}catch(d){throw await Ri(u,t),await Zt(n),await Zt(l),d}return Object.freeze({status:"quarantined",reasonCode:e.reasonCode,targetDir:e.receipt.targetDir,quarantineRoot:l,quarantineDir:u,discoveryRoots:Object.freeze([...o]),quarantineAuthorization:a,receipt:e.receipt})}async function n2(e){oX(e.quarantine);let t=await ya(e.quarantine.receipt.targetDir),n=await s2(e.quarantine.discoveryRoots),r=await RC(e.quarantine.quarantineRoot,"External quarantine root"),i=await RC(e.quarantine.quarantineDir,"Quarantine tree"),o=$r(t);if(AC({targetDir:t,quarantineRoot:r,discoveryRoots:n}),$r(i)!==r||!Ci(i).startsWith(`${Ci(t)}.skills-layer-quarantine-`))throw new Error("Quarantine generation is outside its validated external quarantine root.");let s=await Fn(o,"Atomic restore parent"),a=await Fn(r,"External quarantine root"),l=await cu(i,e.quarantine.receipt),c=await TC(t);if(c.exists)throw new Error("Cannot restore quarantine because the install target already exists.");let u={receipt:e.quarantine.receipt,targetDir:t,quarantineRoot:r,quarantineDir:i,discoveryRoots:n,reasonCode:e.quarantine.reasonCode,quarantineAuthorization:e.quarantine.quarantineAuthorization},d=await r2({callback:e.authorizeRestore,context:u,receipt:e.quarantine.receipt,allowedPurposes:["restore_fresh_approval"],forbiddenAuthorizationId:e.quarantine.quarantineAuthorization.authorizationId});await Pi(o,s,"Atomic restore parent changed."),await Pi(r,a,"External quarantine root changed."),await Pi(i,l,"Quarantine generation changed before restore."),await a2(t,c),await Ri(i,t);try{await Zt(o),await Zt(r),await ha(t,e.quarantine.receipt.files,l),await vo(e.checkpoint,"after_restore_rename"),await sX(e.finalizeRestore,{...u,restoreAuthorization:d})}catch(p){throw await Ri(t,i),await Zt(o),await Zt(r),p}return e.quarantine.receipt}function YY(e){let t=e??ZY;if(!Number.isInteger(t)||t<=0||t>Vj)throw new Error(`Static pre-activation timeout must be an integer from 1 to ${Vj} ms.`);return t}function XY(e,t){let n=e?.generation;if(e?.status!=="approved"||!n||n.skillSlug!==t.generation.skillSlug||n.semanticVersion!==t.generation.semanticVersion||n.generationId!==t.generation.generationId||!va(e.archiveSha256,t.archive.sha256)||!va(e.manifestSha256,t.manifest.sha256))throw new Error("Install denied: approved artifact identity does not match the verified deliverable.")}async function QY(e,t){let n=xn(e,...t.path.split("/"));await eX(e,$r(n));let r=await mg(n,Ii.O_WRONLY|Ii.O_CREAT|Ii.O_EXCL|yg,384);try{await r.writeFile(ye(t)),await r.sync()}finally{await r.close()}}async function eX(e,t){let n=t.slice(e.length).split(au).filter(Boolean),r=e;for(let i of n){r=xn(r,i);try{await $C(r,{mode:448})}catch(s){if(!hX(s))throw s}let o=await Ai(r);if(o.isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link in the staged tree: ${r}`);if(!o.isDirectory())throw new Error(`Atomic install staged path is not a directory: ${r}`)}}async function ha(e,t,n){let r=await Fn(e,"Install generation root");if(n&&!fg(r,n))throw new Error("Install generation root changed during staging.");let i=new Map(t.map(c=>[c.path,c])),o=new Set;for(let c of t){let u=CC.dirname(c.path);for(;u!==".";)o.add(u),u=CC.dirname(u)}let s=new Set,a=new Set,l=async(c,u)=>{let d=await Fn(c,"Install generation directory"),p=(await WY(c,{withFileTypes:!0})).sort((h,g)=>gX(h.name,g.name));for(let h of p){let g=xn(c,h.name),y=u?CC.join(u,h.name):h.name,v=await Ai(g);if(v.isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link in the generation tree: ${y}`);if(v.isDirectory()){if(!o.has(y))throw new Error(`Installed generation manifest has an unexpected directory: ${y}`);a.add(y),await l(g,y);continue}if(!v.isFile())throw new Error(`Atomic install refuses a non-regular generation entry: ${y}`);let b=i.get(y);if(!b)throw new Error(`Installed generation manifest has an unexpected file: ${y}`);let w=await tX(g,b.sizeBytes);if(w.sizeBytes!==b.sizeBytes||!va(w.sha256,b.sha256))throw new Error(`Installed generation manifest mismatch for ${y}.`);s.add(y)}let m=await Fn(c,"Install generation directory");if(!fg(d,m))throw new Error(`Install generation directory changed while verified: ${u||"."}`)};if(await l(e,""),s.size!==t.length||a.size!==o.size)throw new Error("Installed generation manifest is incomplete.");return await Pi(e,r,"Install generation root changed while verified."),r}async function tX(e,t){let n=await mg(e,Ii.O_RDONLY|yg);try{let r=await n.stat();if(!r.isFile())throw new Error(`Expected a regular installed generation file: ${e}`);if(r.size>t)throw new Error(`Installed generation file exceeds its approved size: ${e}`);let i=new Uint8Array(await n.readFile());return{sizeBytes:i.byteLength,sha256:l2(i)}}finally{await n.close()}}async function nX(e){let t=new AbortController,n,r=new Promise((i,o)=>{n=setTimeout(()=>{t.abort(),o(new Error(`Static pre-activation Eval timed out after ${e.timeoutMs} ms.`))},e.timeoutMs)});try{let i=await Promise.race([Promise.resolve().then(()=>e.callback({stageDir:e.stageDir,files:e.files,signal:t.signal})),r]);if(!i||i.status!=="passed"&&i.status!=="failed"||i.status==="passed"&&(typeof i.evidenceId!="string"||i.evidenceId.length===0)||i.status==="failed"&&(typeof i.reasonCode!="string"||i.reasonCode.length===0))throw new Error("Static pre-activation Eval returned an invalid result.");return i}finally{clearTimeout(n)}}async function Gj(e,t){for(let r of t){let i=await mg(xn(e,...r.path.split("/")),Ii.O_RDONLY|yg);try{await i.sync()}finally{await i.close()}}let n=new Set([e]);for(let r of t){let i=$r(xn(e,...r.path.split("/")));for(;i.startsWith(e)&&i!==$r(e)&&(n.add(i),i!==e);)i=$r(i)}for(let r of[...n].sort((i,o)=>o.length-i.length))await Zt(r)}async function rX(e){try{e.stageActivated&&await Ri(e.targetDir,e.stageDir),e.backupMoved&&e.backupDir&&await Ri(e.backupDir,e.targetDir),await uX(e.stageDir),await Zt(e.parentDir)}catch(t){let n=e.backupDir?` from ${e.backupDir}`:"";throw new Error(`Atomic install rollback requires manual recovery${n}.`,{cause:new AggregateError([e.originalError,t])})}}async function iX(e,t){if(!e)return{backupStillExists:!1};try{return await Wj(e,{recursive:!0,force:!1}),await Zt(t),{backupStillExists:!1}}catch(n){return ko(n)?{backupStillExists:!1}:{backupStillExists:!0}}}async function cu(e,t){DC(t);try{return await ha(e,t.files)}catch(n){throw new Error(`Installed generation manifest verification failed: ${c2(n)}`,{cause:n})}}async function Dr(e){try{return await cu(e.targetDir,e),Object.freeze({status:"verified",generation:e.generation,manifestSha256:e.manifestSha256})}catch{return Object.freeze({status:"changed",reasonCode:"installed_tree_manifest_mismatch",generation:e.generation,manifestSha256:e.manifestSha256})}}function DC(e){if(!e||typeof e.targetDir!="string"||!lu.test(e.archiveSha256)||!lu.test(e.manifestSha256)||!Array.isArray(e.files)||e.files.length===0)throw new Error("Installed generation receipt manifest is invalid.");let t=dX(e.files),n=e.files.map(r=>({path:r.path,content:""}));if(e2(n),!va(l2(t),e.manifestSha256))throw new Error("Installed generation receipt manifest digest is invalid.")}function oX(e){if(!e||e.status!=="quarantined"||!Zj.test(e.reasonCode)||typeof e.targetDir!="string"||typeof e.quarantineRoot!="string"||typeof e.quarantineDir!="string"||!Array.isArray(e.discoveryRoots)||e.discoveryRoots.length===0||!e.receipt||!i2(e.quarantineAuthorization)||e.quarantineAuthorization.purpose!=="quarantine_blocked"&&e.quarantineAuthorization.purpose!=="quarantine_revoked"||!o2(e.quarantineAuthorization,e.receipt)||e.targetDir!==e.receipt?.targetDir)throw new Error("Quarantine record is invalid.");DC(e.receipt)}async function r2(e){if(typeof e.callback!="function")throw new Error("Exact-generation authorization callback is required.");let t=await e.callback(e.context);if(t?.status==="denied")throw new Error(`Exact-generation authorization denied: ${t.reasonCode||"unspecified"}.`);if(!i2(t)||!e.allowedPurposes.includes(t.purpose)||!o2(t,e.receipt)||t.authorizationId===e.forbiddenAuthorizationId)throw new Error("Exact-generation authorization is invalid, stale, reused, or bound to different bytes.");return aX(t)}async function sX(e,t){if(typeof e!="function")throw new Error("Restore release callback is required.");let n=await e(t);if(n?.status!=="released"||!Jj.test(n.releaseId)){let r=n?.status==="denied"?n.reasonCode:"invalid_release_decision";throw new Error(`Restore release denied: ${r}.`)}}function i2(e){return typeof e=="object"&&e!==null&&"status"in e&&e.status==="authorized"&&"authorizationId"in e&&typeof e.authorizationId=="string"&&Jj.test(e.authorizationId)&&"purpose"in e&&(e.purpose==="quarantine_blocked"||e.purpose==="quarantine_revoked"||e.purpose==="restore_fresh_approval"||e.purpose==="purge_quarantined")&&"generation"in e&&typeof e.generation=="object"&&e.generation!==null&&"archiveSha256"in e&&typeof e.archiveSha256=="string"&&"manifestSha256"in e&&typeof e.manifestSha256=="string"}function o2(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&va(e.archiveSha256,t.archiveSha256)&&va(e.manifestSha256,t.manifestSha256)}function aX(e){return Object.freeze({...e,generation:Object.freeze({...e.generation})})}async function s2(e){if(!Array.isArray(e)||e.length===0||e.some(r=>typeof r!="string"||r.length===0))throw new Error("External quarantine requires the complete non-empty discovery root set.");let t=[],n=new Set;for(let r of e){let i=await ya(r),o=pg(i);n.has(o)||(t.push(i),n.add(o))}return Object.freeze(t)}function AC(e){let t=pg(e.targetDir),n=pg(e.quarantineRoot),r=e.discoveryRoots.map(pg);if(!r.some(i=>t!==i&&IC(t,i)))throw new Error("Install target is not inside the authoritative discovery root set.");for(let i of r)if(IC(n,i)||IC(i,n))throw new Error("Quarantine root must be physically outside and non-overlapping with every discovery root.")}function pg(e){let t=hg(e).normalize("NFC"),n=gg(t).root,r=t===n?t:t.replace(/[\\/]+$/u,"");return process.platform==="linux"?r:r.toLocaleLowerCase("en-US")}function IC(e,t){return e===t||e.startsWith(t.endsWith(au)?t:`${t}${au}`)}async function TC(e){try{let t=await Ai(e,{bigint:!0});if(t.isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link target: ${e}`);if(!t.isDirectory())throw new Error(`Atomic install target must be a directory: ${e}`);return{exists:!0,identity:{dev:t.dev,ino:t.ino}}}catch(t){if(ko(t))return{exists:!1,identity:null};throw t}}async function a2(e,t){let n=await TC(e);if(n.exists!==t.exists||t.identity!==null&&(n.identity===null||!fg(t.identity,n.identity)))throw new Error("Atomic install target changed while the approved generation was staged.")}async function Fn(e,t){let n=await Ai(e,{bigint:!0});if(n.isSymbolicLink())throw new Error(`${t} refuses a symbolic link: ${e}`);if(!n.isDirectory())throw new Error(`${t} must be a directory: ${e}`);return{dev:n.dev,ino:n.ino}}async function Pi(e,t,n){let r=await Fn(e,"Atomic install identity check");if(!fg(r,t))throw new Error(n)}function fg(e,t){return e.dev===t.dev&&e.ino===t.ino}async function ya(e){let t=await lX(hg(e));await uu(t);try{if((await Ai(t)).isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link: ${t}`);return await PC(t)}catch(i){if(!ko(i))throw i}let n=[],r=t;for(;;)try{await Ai(r);break}catch(i){if(!ko(i))throw i;let o=$r(r);if(o===r)throw new Error(`Unable to resolve atomic install target parent: ${t}`);n.unshift(Ci(r)),r=o}return xn(await PC(r),...n)}async function RC(e,t){let n=await ya(e);return await Fn(n,t),n}async function lX(e){let t=gg(e).root,n=e.slice(t.length).split(au).filter(Boolean);if(n.length===0)return e;let r=xn(t,n[0]),i;try{i=await Ai(r)}catch(o){if(ko(o))return e;throw o}return i.isSymbolicLink()?xn(await PC(r),...n.slice(1)):e}async function uu(e){let t=hg(e),n=gg(t).root,r=t.slice(n.length).split(au).filter(Boolean),i=n;for(let o of r){i=xn(i,o);try{if((await Ai(i)).isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link: ${i}`)}catch(s){if(ko(s))return;throw s}}}async function Zt(e){let t;try{t=await mg(e,Ii.O_RDONLY|yg),await t.sync()}catch(n){if(!cX(n))throw n}finally{await t?.close()}}function cX(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return t==="EINVAL"||t==="ENOTSUP"||t==="EOPNOTSUPP"||process.platform==="win32"&&(t==="EPERM"||t==="EISDIR"||t==="EBADF")}async function uX(e){try{await Wj(e,{recursive:!0,force:!1})}catch(t){if(!ko(t))throw t}}async function vo(e,t){await e?.(t)}function dX(e){let t=[JY,Hj(e.length)];for(let n of e){if(typeof n.path!="string"||!Number.isSafeInteger(n.sizeBytes)||n.sizeBytes<0||!lu.test(n.sha256))throw new Error("Installed generation receipt manifest entry is invalid.");let r=new TextEncoder().encode(n.path);t.push(Hj(r.byteLength),r,pX(n.sizeBytes),EC(n.sha256))}return fX(t)}function Hj(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function pX(e){let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function fX(e){let t=new Uint8Array(e.reduce((r,i)=>r+i.byteLength,0)),n=0;for(let r of e)t.set(r,n),n+=r.byteLength;return t}function mX(e){let t=Object.freeze({...e.generation}),n=Object.freeze(e.files.map(r=>Object.freeze({...r})));return Object.freeze({...e,generation:t,files:n})}function l2(e){return`sha256:${VY("sha256").update(e).digest("hex")}`}function va(e,t){return typeof e=="string"&&lu.test(e)&&lu.test(t)&&GY(EC(e),EC(t))}function EC(e){return Buffer.from(e.slice(7),"hex")}function gX(e,t){return Buffer.compare(Buffer.from(e,"utf8"),Buffer.from(t,"utf8"))}function c2(e){return e instanceof Error?e.message:String(e)}function ko(e){return u2(e)==="ENOENT"}function hX(e){return u2(e)==="EEXIST"}function u2(e){return typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function d2(e){if(e.pathState==="absent"){if(e.receiptState==="verified")throw new Error("An absent target cannot have a verified receipt observation.");return du("externally_removed","exact_target_absent")}if(e.pathState==="unreadable"){if(e.receiptState==="verified")throw new Error("An unreadable target cannot have a verified receipt observation.");return du("unreadable","exact_target_unreadable")}if(e.pathState==="replaced_type"){if(e.receiptState==="verified")throw new Error("A replaced target cannot have a verified receipt observation.");return du("drifted","exact_target_replaced")}if(e.receiptState==="unchecked")throw new Error("A present exact target receipt must be checked before reconciliation.");return e.receiptState==="changed"?du("drifted","exact_tree_changed"):e.hostState==="detached"?du("host_detached","host_registration_detached"):Object.freeze({state:"active",reasonCode:"exact_target_verified",runnable:!0,recoverable:!0})}function du(e,t){return Object.freeze({state:e,reasonCode:t,runnable:!1,recoverable:!0})}import{createHash as yX}from"node:crypto";var vX="skills-layer-signatures-v1";var kX="security/signature-packs",yve=`${kX}/source/current.json`;var p2=bX(wX({version:vX,generatedAt:"2026-06-14T00:00:00.000Z",issuer:"skills-layer-local",signatures:[{id:"SL-SIG-COMMODITY-WEBHOOK-EXFIL",ruleId:"SL-SIG-002",title:"Commodity webhook exfiltration",severity:"critical",confidence:.92,tags:["exfiltration","webhook","secret-harvest"],regexes:[`https://(?:discord(?:app)?\\.com/api/webhooks|hooks\\.slack\\.com/services|webhook\\.site)/[^\\s"']+`],explanation:"Content references a commodity webhook endpoint often used for data exfiltration."},{id:"SL-SIG-REMOTE-BOOTSTRAP",ruleId:"SL-SIG-001",title:"Remote bootstrap execution",severity:"high",confidence:.88,tags:["remote-bootstrap","shell"],regexes:["(?:curl|wget)\\s+[^\\n|]+\\|\\s*(?:bash|sh|zsh|python|node)"],explanation:"Content downloads remote code and pipes it directly into an interpreter."},{id:"SL-SIG-DESTRUCTIVE-AUTONOMY",ruleId:"SL-SIG-004",title:"Destructive autonomous action",severity:"high",confidence:.84,tags:["destructive","autonomous"],regexes:["\\b(?:rm\\s+-rf|Remove-Item\\s+-Recurse|format\\s+[A-Z]:|git\\s+push\\s+--force)\\b"],explanation:"Content includes destructive commands that can cause irreversible changes."}]}));function wX(e){return{boundary:"skills_layer_signature_pack",version:e.version,generatedAt:e.generatedAt,issuer:e.issuer??"skills-layer-cloud",...e.managedAuthorityDigest?{managedAuthorityDigest:e.managedAuthorityDigest}:{},signatures:e.signatures.map(xX).sort((t,n)=>t.id.localeCompare(n.id))}}function bX(e){let t=`sha256:${pu(ka(e))}`;return{...e,digest:t,signature:pu(ka({boundary:e.boundary,digest:t,issuer:e.issuer,version:e.version}))}}function _X(e){let{digest:t,signature:n,...r}=e;return t===`sha256:${pu(ka(r))}`&&n===pu(ka({boundary:r.boundary,digest:t,issuer:r.issuer,version:r.version}))}function f2(e,t){if(!_X(t))return[];let n=[],r=new Set;for(let i of e){let o=i.content??"";for(let s of t.signatures){if(s.filePattern&&!new RegExp(s.filePattern,"iu").test(i.path))continue;let a=SX(o,s);if(!a)continue;let l=`${s.id}:${i.path}:${a.lineNumber}:${a.tag}`;r.has(l)||(r.add(l),n.push({signatureId:s.id,ruleId:s.ruleId,title:s.title,severity:s.severity,confidence:s.confidence,filePath:i.path,lineNumber:a.lineNumber,matchedTag:a.tag,evidenceHash:`sha256:${pu(`${i.path}
|
|
803
|
+
${e.body}`}function oj(e){let t=e.slice(0,nj),n=t.charCodeAt(t.length-1);return n>=55296&&n<=56319?t.slice(0,-1):t}function Xc(e,t){return{severity:"warning",code:e,message:t,nextAction:"review-normalized-source",nextStep:"Review the normalized frontmatter and improve the upstream SKILL.md when practical."}}function ej(e,t){if(t.length===0)return e;let n=[...e.issues,...t];return{...e,valid:e.valid&&n.every(r=>r.severity!=="error"),issues:n}}function v7(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sj(e){if(!ir(e))throw new Error("Well-known search response must be a JSON object.");if(e.version!==1)throw new Error("Well-known search response version must be 1.");let t=aC(e.provider),n=_7(e.query,"query"),r=cj(e.limit,"limit");if(!Array.isArray(e.results))throw new Error("results must be an array.");return{version:1,provider:t,query:n,limit:r,results:e.results.map((i,o)=>k7(i,`results[${o}]`))}}function aj(e){if(!ir(e))throw new Error("Well-known skill manifest must be a JSON object.");if(e.version!==1)throw new Error("Well-known skill manifest version must be 1.");let t=aC(e.provider);if(!ir(e.skill))throw new Error("skill must be an object.");if(!Array.isArray(e.skill.files))throw new Error("skill.files must be an array.");let n=e.skill.files.map((i,o)=>w7(i,`skill.files[${o}]`));if(!n.some(i=>i.path==="SKILL.md"))throw new Error("skill.files must include SKILL.md.");let r=sC(e.skill.sourceUrl,"skill.sourceUrl")??n.find(i=>i.path==="SKILL.md").url;return{version:1,provider:t,skill:{slug:_n(e.skill.slug,"skill.slug"),name:_n(e.skill.name,"skill.name"),description:_n(e.skill.description,"skill.description"),skillVersion:_n(e.skill.skillVersion,"skill.skillVersion"),compatibility:sC(e.skill.compatibility,"skill.compatibility")??"",featured:e.skill.featured===!0,tags:uj(e.skill.tags,"skill.tags"),files:n,sourceUrl:go(r,"skill.sourceUrl")}}}function lj(e){if(!ir(e))throw new Error("Well-known index must be a JSON object.");if(!ir(e.provider))throw new Error("Well-known index provider must be an object.");let t=aC(e.provider);if(e.version!==2)throw new Error("Well-known service manifest version must be 2.");if(!ir(e.capabilities))throw new Error("capabilities must be an object.");if(e.capabilities.directSkillManifest!==!0)throw new Error("capabilities.directSkillManifest must be true.");if(e.capabilities.search!==!0)throw new Error("capabilities.search must be true.");let n=cj(e.capabilities.maxSearchResults,"capabilities.maxSearchResults");if(!ir(e.routes))throw new Error("routes must be an object.");return{version:2,provider:t,capabilities:{directSkillManifest:!0,search:!0,maxSearchResults:n},routes:{search:go(e.routes.search,"routes.search"),skillManifest:go(e.routes.skillManifest,"routes.skillManifest"),skillFile:go(e.routes.skillFile,"routes.skillFile")}}}function k7(e,t){if(!ir(e))throw new Error(`${t} must be an object.`);return{slug:_n(e.slug,`${t}.slug`),name:_n(e.name,`${t}.name`),description:_n(e.description,`${t}.description`),skillVersion:_n(e.skillVersion,`${t}.skillVersion`),compatibility:sC(e.compatibility,`${t}.compatibility`)??"",featured:e.featured===!0,tags:uj(e.tags,`${t}.tags`),skillManifestUrl:go(e.skillManifestUrl,`${t}.skillManifestUrl`)}}function w7(e,t){if(!ir(e))throw new Error(`${t} must be an object.`);return{path:b7(_n(e.path,`${t}.path`)),url:go(e.url,`${t}.url`)}}function aC(e){if(!ir(e))throw new Error("Well-known index provider must be an object.");return{name:_n(e.name,"provider.name"),baseUrl:go(e.baseUrl,"provider.baseUrl")}}function b7(e){return e.trim().replaceAll("\\","/").replace(/^\/+/u,"").split("/").filter(t=>t.length>0&&t!=="."&&t!=="..").join("/")}function cj(e,t){if(typeof e!="number"||!Number.isInteger(e)||e<1||e>5)throw new Error(`${t} must be between 1 and 5.`);return e}function _7(e,t){if(typeof e!="string")throw new Error(`${t} must be a string.`);return e.trim()}function _n(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string.`);return e.trim()}function sC(e,t){if(e!==void 0)return _n(e,t)}function go(e,t){let n=_n(e,t);if(!/^https?:\/\//u.test(n))throw new Error(`${t} must be an absolute http(s) URL.`);return n}function uj(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be a string array.`);return e.map(n=>n.trim()).filter(n=>n.length>0)}function ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ca=class extends Error{constructor(t){super(t instanceof Error?t.message:"Source files could not be read completely.",{cause:t}),this.name="SourceReadUnavailableError"}};var og=100,da=class extends Error{},x7=40;async function kj(e){if(e.source.kind==="local")return N7({source:e.source,cwd:e.cwd,platform:e.platform});if(e.source.kind==="git")return{source:e.source,results:[],issues:[{severity:"warning",code:"git-remote-not-inspectable",message:"Generic git remotes are normalized, but inspection currently requires a local checkout or GitHub/GitLab raw access."}]};if(e.source.kind==="well-known"&&Array.isArray(e.source.files)&&e.source.files.length>0)return uC({source:e.source,fetchFn:e.fetchFn});if(e.source.kind==="url"){let t=await C7({source:e.source,fetchFn:e.fetchFn,requestedSkillSlug:e.requestedSkillSlug});if(t!==null)return t}if(e.source.kind==="github"||e.source.kind==="gitlab")try{return await A7({source:e.source,fetchFn:e.fetchFn,requestedSkillSlug:e.requestedSkillSlug})}catch(t){if(t instanceof ca)throw t;let n=t instanceof ho?t:null;if(!(xj(e.source.subpath)&&(n===null||n.status===404||n.status===403))){if(n===null)throw t;let i=e.source.kind==="github"?"GitHub":"GitLab";throw new ca(new Error(`${i} source inspection failed (HTTP ${n.status}): ${n.message}. This is a source-provider failure, not a Skills Layer login failure.`))}}return I7({source:e.source,fetchFn:e.fetchFn})}async function C7(e){if(xj(e.source.url))return null;let t=await X7(e.source.url,e.fetchFn);if(t===null)return null;let n=e.source.skillFilter??e.requestedSkillSlug??tY(e.source.url),r=[],i=[];if(n){let o=mj(t.index.routes.skillManifest,{slug:n}),s=await pj(o,e.fetchFn);if(s===null)i.push({severity:"warning",code:"well-known-skill-not-found",message:`Well-known provider did not expose "${n}".`});else{let a=await uC({source:fj({inputSource:e.source,detectedIndex:t,manifest:s,manifestUrl:o,skillFilter:n}),fetchFn:e.fetchFn});r.push(...a.results),i.push(...a.issues)}}else{let o=mj(t.index.routes.search,{query:eY(e.source.url),limit:"5"}),s=await Q7(o,e.fetchFn);if(s!==null)for(let a of s.results.slice(0,t.index.capabilities.maxSearchResults)){let l=await pj(a.skillManifestUrl,e.fetchFn);if(l===null){i.push({severity:"warning",code:"well-known-manifest-not-found",message:`Well-known provider advertised "${a.slug}" but its manifest was unavailable.`});continue}let c=await uC({source:fj({inputSource:e.source,detectedIndex:t,manifest:l,manifestUrl:a.skillManifestUrl}),fetchFn:e.fetchFn});r.push(...c.results),i.push(...c.issues)}}return{source:e.source,results:r,issues:i}}async function I7(e){let t=await e.fetchFn(H7(e.source));if(!t.ok)throw await Si(t);let r=[{path:"SKILL.md",content:await t.text()}];return wj(e.source,r)}async function uC(e){let t=await j7(e.source,e.fetchFn);return wj(e.source,t)}function wj(e,t){let n=[],r=rg({files:t,allowNormalization:!0}),i=r.validation,o=r.skillSlug??iu(i,e);if(!o||!pa(e.skillFilter,o)){let s=t.find(a=>M7.test(a.path));return s&&fa(n,i,s.path),{source:e,results:[],issues:n}}return{source:e,results:[{skillSlug:o,description:r.description??(i.parsedSkill?i.parsedSkill.frontmatter.description:o),...r.originalSkillName?{originalSkillName:r.originalSkillName}:{},sourceKind:e.kind,relativeSkillRoot:".",relativeSkillFile:"SKILL.md",discoveryRoute:"remote_file",validation:{valid:i.valid,issueCount:i.issues.length},...r.normalizationIssues.length>0?{normalizationIssues:r.normalizationIssues}:{},...r.normalizationProvenance?{normalizationProvenance:r.normalizationProvenance}:{},files:r.files,losslessImport:P7(e,t)}],issues:n}}function P7(e,t){let n=sg("sha256"),r=t.slice().sort((l,c)=>l.path.localeCompare(c.path));r.forEach((l,c)=>{n.update(l.path),n.update("\0"),n.update(ye(l)),c<r.length-1&&n.update("\0")});let i=n.digest("hex"),o=e.kind==="github"||e.kind==="gitlab"?e.kind:"url",s=e.kind==="github"?`${e.owner}/${e.repo}`:e.kind==="gitlab"?`${e.namespace}/${e.repo}`:e.canonicalSource,a=e.kind==="github"||e.kind==="gitlab"?e.ref:"fetched-content";return{source:{provider:o,repository:s,ref:a,commitSha:/^[a-f0-9]{40}$/iu.test(a)?a.toLowerCase():i,treeSha:null},files:r.map(l=>({path:l.path,bytes:ye(l)}))}}async function A7(e){let t=await R7(e.source,e.fetchFn),n=[],r=e.requestedSkillSlug??e.source.skillFilter,i,o=new Map;if(r){let d=await E7({source:e.source,fetchFn:e.fetchFn,context:t});n.push(...d.issues);let p=d.results.filter(m=>pa(r,m.skillSlug));if(p.length===0)return{source:e.source,results:d.results,issues:n};i=new Set(p.map(m=>m.relativeSkillRoot));for(let m of p){let h=m.files.find(g=>g.path==="SKILL.md");h?.content!==void 0&&o.set(m.relativeSkillFile,h.content)}}let s=new Map([...o].map(([d,p])=>[d,{content:p}])),a=await F7({fileSet:t.fileSet,fetchFile:async d=>{let p=s.get(d);if(p!==void 0)return p;let m=await e.fetchFn(Sj(e.source,nu(t.sourceRoot,d)));if(!m.ok)throw await Si(m);let h=en(new Uint8Array(await m.arrayBuffer()),m.headers.get("content-type"));return s.set(d,h),h},onlySkillRoots:i},n),l=new Map;for(let d of a){let p=l.get(d.skillSlug);(!p||yC(d,p)<0)&&l.set(d.skillSlug,d)}let c=[...l.values()].filter(d=>pa(r,d.skillSlug)),u=c.length===0?{commitSha:e.source.ref,treeSha:null}:await W7(e.source,e.fetchFn,Z7(c));return{source:e.source,results:c.map(d=>({skillSlug:d.skillSlug,description:d.description,...d.originalSkillName?{originalSkillName:d.originalSkillName}:{},sourceKind:e.source.kind,relativeSkillRoot:d.relativeSkillRoot,relativeSkillFile:d.relativeSkillFile,discoveryRoute:d.discoveryRoute,...d.pluginName?{pluginName:d.pluginName}:{},...d.pluginManifestPath?{pluginManifestPath:d.pluginManifestPath}:{},validation:{valid:d.validation.valid,issueCount:d.validation.issues.length},...d.normalizationIssues&&d.normalizationIssues.length>0?{normalizationIssues:d.normalizationIssues}:{},...d.normalizationProvenance?{normalizationProvenance:d.normalizationProvenance}:{},files:d.files,providerFileAttestations:L7(d,t.providerBlobByPath),losslessImport:{source:{provider:e.source.kind,repository:e.source.kind==="github"?`${e.source.owner}/${e.source.repo}`:`${e.source.namespace}/${e.source.repo}`,ref:e.source.ref,commitSha:u.commitSha,treeSha:u.treeSha},files:d.originalFiles.map(p=>{let m=nu(d.relativeSkillRoot,p.path);return{path:m,bytes:ye(p),providerObjectId:t.providerBlobByPath.get(m)??void 0}})}})).sort((d,p)=>d.skillSlug.localeCompare(p.skillSlug)||d.relativeSkillRoot.localeCompare(p.relativeSkillRoot)),issues:n}}async function R7(e,t){let n=nY(e.subpath),i=(await K7(e,t)).map(s=>{let a=_i(s.path,n);return a===null?null:{...s,path:a}}).filter(s=>s!==null),o=i.map(s=>s.path);if(o.length===0)throw new Error(`Remote repository path "${e.subpath}" did not expose any files.`);return{sourceRoot:n,relativeFileEntries:i,fileSet:new Set(o),providerBlobByPath:new Map(i.map(s=>[s.path,s.providerBlobSha]))}}async function E7(e){let t=lY([...e.context.fileSet],".");if(t.length>x7&&!e.requestedSkillSlug&&!e.source.skillFilter)return{source:e.source,results:t.map(o=>$7({entry:o,source:e.source})).sort((o,s)=>o.skillSlug.localeCompare(s.skillSlug)||o.relativeSkillRoot.localeCompare(s.relativeSkillRoot)),issues:[{severity:"warning",code:"remote-source-large-index",message:`Found ${t.length} Skills Layer-compatible entries; listing uses repository paths to stay within source host request limits. Select a specific skill or subfolder for full validation details.`}]};let n=[],i=(await O7(t,8,async o=>T7({entry:o,source:e.source,sourceRoot:e.context.sourceRoot,fetchFn:e.fetchFn,requestedSkillSlug:e.requestedSkillSlug??e.source.skillFilter,issues:n}))).filter(o=>o!==null).sort((o,s)=>o.skillSlug.localeCompare(s.skillSlug)||o.relativeSkillRoot.localeCompare(s.relativeSkillRoot));return{source:e.source,results:i,issues:n}}function $7(e){let t=D7(e.entry),n=bj(e.entry.skillRoot);return{skillSlug:t,description:`Discovered at ${e.entry.skillRoot}. Select this skill or subfolder for full details.`,sourceKind:e.source.kind,relativeSkillRoot:e.entry.skillRoot,relativeSkillFile:e.entry.skillFilePath,discoveryRoute:n,fileCount:e.entry.bundleFileCount,validation:{valid:!0,issueCount:0},files:[]}}function D7(e){let t=e.skillRoot==="."?rt.basename(rt.dirname(e.skillFilePath)):rt.basename(e.skillRoot);return mo(t)??mo(e.skillRoot.replace(/\//gu,"-"))??`source-skill-${sg("sha256").update(e.skillRoot).digest("hex").slice(0,12)}`}async function T7(e){let t=await e.fetchFn(Sj(e.source,nu(e.sourceRoot,e.entry.skillFilePath)));if(!t.ok)return e.issues.push({severity:"warning",code:"remote-skill-unreadable",message:(await Si(t)).message,path:e.entry.skillFilePath}),null;let n=await t.text(),r=e.entry.skillRoot!=="."?mo(rt.basename(e.entry.skillRoot))??void 0:void 0,i=rg({files:[{path:"SKILL.md",content:n}],fallbackSkillSlug:r,allowNormalization:!0}),o=i.validation,s=i.skillSlug??iu(o,null);if(!s)return fa(e.issues,o,e.entry.skillFilePath),null;if(!pa(e.requestedSkillSlug,s))return null;if(!o.parsedSkill)return fa(e.issues,o,e.entry.skillFilePath),null;let a=bj(e.entry.skillRoot);return{skillSlug:s,description:i.description??o.parsedSkill.frontmatter.description,...i.originalSkillName?{originalSkillName:i.originalSkillName}:{},sourceKind:e.source.kind,relativeSkillRoot:e.entry.skillRoot,relativeSkillFile:e.entry.skillFilePath,discoveryRoute:a,fileCount:e.entry.bundleFileCount,validation:{valid:o.valid,issueCount:o.issues.length},...i.normalizationIssues.length>0?{normalizationIssues:i.normalizationIssues}:{},...i.normalizationProvenance?{normalizationProvenance:i.normalizationProvenance}:{},files:i.files}}function bj(e){return gC().find(n=>n.absolutePath===e)?.discoveryRoute??(e==="."?"root":"recursive")}async function O7(e,t,n){let r=new Array(e.length),i=0,o=Math.min(Math.max(t,1),e.length);return await Promise.all(Array.from({length:o},async()=>{for(;i<e.length;){let s=i;i+=1,r[s]=await n(e[s],s)}})),r}function L7(e,t){return e.files.map(n=>{let r=nu(e.relativeSkillRoot,n.path);return{path:n.path,providerBlobSha:t.get(r)??null,contentSha256:J7(ye(n))}})}async function j7(e,t){let n=rY(e.files);return(await Promise.all(n.map(async i=>{let o=await t(e.fileUrls?.[i]??iY(e.sourceUrl,i));if(!o.ok)throw await Si(o);return{path:i,...en(new Uint8Array(await o.arrayBuffer()),o.headers.get("content-type"))}}))).sort((i,o)=>i.path.localeCompare(o.path))}async function N7(e){let t=xi(e.platform),n=t.resolve(e.cwd,e.source.location);if(!(await yj(n)).isDirectory()){let l=[{path:t.basename(n),...en(new Uint8Array(await mC(n)))}],c=nt(l),u=iu(c,e.source);if(!u||!pa(e.source.skillFilter,u)){let d=oY(c,t.basename(n));return{source:e.source,results:[],issues:d}}return{source:e.source,results:[{skillSlug:u,description:c.parsedSkill?.frontmatter.description??u,sourceKind:"local",relativeSkillRoot:".",relativeSkillFile:t.basename(n),discoveryRoute:"remote_file",validation:{valid:c.valid,issueCount:c.issues.length},files:l}],issues:[]}}let i=[],o=await B7(n,e.platform,i),s=new Map;for(let l of o){let c=s.get(l.skillSlug);(!c||yC(l,c)<0)&&s.set(l.skillSlug,l)}let a=[...s.values()].filter(l=>pa(e.source.skillFilter,l.skillSlug)).map(l=>({skillSlug:l.skillSlug,description:l.description,sourceKind:"local",relativeSkillRoot:l.relativeSkillRoot,relativeSkillFile:l.relativeSkillFile,discoveryRoute:l.discoveryRoute,...l.pluginName?{pluginName:l.pluginName}:{},...l.pluginManifestPath?{pluginManifestPath:l.pluginManifestPath}:{},validation:{valid:l.validation.valid,issueCount:l.validation.issues.length},files:l.files})).sort((l,c)=>l.skillSlug.localeCompare(c.skillSlug)||l.relativeSkillRoot.localeCompare(c.relativeSkillRoot));return{source:e.source,results:a,issues:i}}async function F7(e,t){let n=new Map,r=new Set,i=gC();for(let s of i){let a=s.discoveryRoute==="root"?e.fileSet.has("SKILL.md")?["SKILL.md"]:[]:tu(e.fileSet,s.absolutePath,{maxDepth:5,ignoreDirNames:or});for(let l of a){if(r.has(l)||e.onlySkillRoots&&!e.onlySkillRoots.has(mt(rt.dirname(l))))continue;r.add(l);let c=await pC({allFiles:e.fileSet,fetchFile:e.fetchFile,skillFilePath:l,discoveryRoute:s.discoveryRoute,allowNormalization:e.allowNormalization,issues:t});c&&ua(n,c)}}let o=await z7(e.fileSet,e.fetchFile,t,e.allowNormalization);for(let s of o)ua(n,s);for(let s of tu(e.fileSet,".",{maxDepth:6,ignoreDirNames:or})){if(r.has(s)||e.onlySkillRoots&&!e.onlySkillRoots.has(mt(rt.dirname(s))))continue;r.add(s);let a=await pC({allFiles:e.fileSet,fetchFile:e.fetchFile,skillFilePath:s,discoveryRoute:"recursive",allowNormalization:e.allowNormalization,issues:t});a&&ua(n,a)}return[...n.values()]}async function B7(e,t,n){let r=xi(t),i=new Map,o=new Set,s=U7(e,t);for(let c of s){if(!await ru(c.absolutePath))continue;let u=c.discoveryRoute==="root"?[r.join(c.absolutePath,"SKILL.md")]:await fC(c.absolutePath,t,{maxDepth:5,ignoreDirNames:or});for(let d of u){let p=r.normalize(d);if(o.has(p)||!await ru(p))continue;o.add(p);let m=await dC({rootPath:e,skillFilePath:p,platform:t,discoveryRoute:c.discoveryRoute,issues:n});m&&ua(i,m)}}let a=await q7(e,t,n);for(let c of a)ua(i,c);let l=await fC(e,t,{maxDepth:6,ignoreDirNames:or});for(let c of l){let u=r.normalize(c);if(o.has(u))continue;o.add(u);let d=await dC({rootPath:e,skillFilePath:u,platform:t,discoveryRoute:"recursive",issues:n});d&&ua(i,d)}return[...i.values()]}var or=new Set([".git",".skills-layer","node_modules","dist","coverage"]),M7=/(^|\/)SKILL\.md$/;function gC(){let e=new Map;e.set(".","root"),e.set("skills","skills"),e.set("skills/.curated","curated"),e.set("skills/.experimental","experimental"),e.set("skills/.system","system");for(let t of et({},"linux","/repo")){let n=Sn(rt.relative("/repo",t.targets.projectSkillsPath));n.length===0||n==="skills"||e.set(n,"agent")}return[...e.entries()].map(([t,n])=>({absolutePath:t,discoveryRoute:n}))}function U7(e,t){let n=xi(t),r=new Map;r.set(e,"root"),r.set(n.join(e,"skills"),"skills"),r.set(n.join(e,"skills",".curated"),"curated"),r.set(n.join(e,"skills",".experimental"),"experimental"),r.set(n.join(e,"skills",".system"),"system");for(let i of et({},t,e)){let o=Sn(n.relative(e,i.targets.projectSkillsPath));o.length===0||o==="skills"||r.set(i.targets.projectSkillsPath,"agent")}return[...r.entries()].map(([i,o])=>({absolutePath:i,discoveryRoute:o}))}async function z7(e,t,n,r){let i=[".claude-plugin/marketplace.json",".claude-plugin/plugin.json"].filter(s=>e.has(s)),o=[];for(let s of i){let a;try{a=JSON.parse(Y7(await t(s),s))}catch{n.push({severity:"warning",code:"plugin-manifest-invalid",message:"Plugin manifest could not be parsed as JSON.",path:s});continue}let l=_j(a,rt.dirname(s));if(l.length===0){n.push({severity:"warning",code:"plugin-manifest-empty",message:"Plugin manifest did not declare a usable plugin or skills root.",path:s});continue}for(let c of l){let u=mt(c.relativeRootPath),d=tu(e,u,{maxDepth:5,ignoreDirNames:or});for(let p of d){let m=await pC({allFiles:e,fetchFile:t,skillFilePath:p,discoveryRoute:"plugin_manifest",pluginName:c.pluginName,pluginManifestPath:s,allowNormalization:r,issues:n});m&&o.push(m)}}}return o}async function q7(e,t,n){let r=xi(t),i=[r.join(e,".claude-plugin","marketplace.json"),r.join(e,".claude-plugin","plugin.json")],o=[];for(let s of i){if(!await ru(s))continue;let a;try{a=JSON.parse(await mC(s,"utf8"))}catch{n.push({severity:"warning",code:"plugin-manifest-invalid",message:"Plugin manifest could not be parsed as JSON.",path:Sn(r.relative(e,s))});continue}let l=_j(a,r.relative(e,vj(s)));if(l.length===0){n.push({severity:"warning",code:"plugin-manifest-empty",message:"Plugin manifest did not declare a usable plugin or skills root.",path:Sn(r.relative(e,s))});continue}for(let c of l){let u=r.resolve(e,...c.relativeRootPath.split("/"));if(!Pj(e,u,t)){n.push({severity:"warning",code:"plugin-root-escaped",message:"Plugin manifest resolved outside the inspected source root and was ignored.",path:Sn(r.relative(e,s))});continue}if(!await ru(u))continue;let d=await fC(u,t,{maxDepth:5,ignoreDirNames:or});for(let p of d){let m=await dC({rootPath:e,skillFilePath:p,platform:t,discoveryRoute:"plugin_manifest",pluginName:c.pluginName,pluginManifestPath:Sn(r.relative(e,s)),issues:n});m&&o.push(m)}}}return o}function _j(e,t){if(!cC(e))return[];let n=t.length===0?".":Sn(t),r=lC(e,["plugin_root","pluginRoot","skills_root","skillsRoot","root","path","directory"]),i=[];if(Array.isArray(e.plugins))for(let o of e.plugins){if(!cC(o))continue;let s=lC(o,["plugin_root","pluginRoot","skills_root","skillsRoot","root","path","directory"]),a=typeof o.name=="string"&&o.name.trim().length>0?o.name.trim():void 0,l=s??(r&&a?`${r}/${a}`:void 0);l&&i.push({pluginName:a,relativeRootPath:ig(n,l)})}if(Array.isArray(e.skills))for(let o of e.skills){if(typeof o=="string"&&o.trim().length>0){let c=r?`${r}/${o.trim()}`:o.trim();i.push({relativeRootPath:ig(n,c)});continue}if(!cC(o))continue;let s=lC(o,["root","path","directory"]),a=typeof o.name=="string"&&o.name.trim().length>0?o.name.trim():void 0,l=s??(r&&a?`${r}/${a}`:void 0);l&&i.push({pluginName:a,relativeRootPath:ig(n,l)})}return i.length>0?i:r?[{pluginName:typeof e.name=="string"?e.name.trim():void 0,relativeRootPath:ig(n,r)}]:[{pluginName:typeof e.name=="string"?e.name.trim():void 0,relativeRootPath:n}]}function ig(e,t){let n=mt(t);return e===".claude-plugin"&&!t.startsWith(".")?n:nu(e,n)}async function dC(e){let t=xi(e.platform),n=vj(e.skillFilePath);if(!Pj(e.rootPath,n,e.platform))return null;let r;try{r=await V7(n,e.platform)}catch(l){if(!(l instanceof da))throw l;let c=l.message;return e.issues.push({severity:"warning",code:"skill-too-large",message:c,path:Sn(t.relative(e.rootPath,e.skillFilePath))}),null}let i=nt(r),o=iu(i,null);if(!o||!i.parsedSkill)return fa(e.issues,i,Sn(t.relative(e.rootPath,e.skillFilePath))),null;let s=mt(t.relative(e.rootPath,n)),a=Cj(e.discoveryRoute,s);return{skillSlug:o,description:i.parsedSkill.frontmatter.description,relativeSkillRoot:s,relativeSkillFile:Sn(t.relative(e.rootPath,e.skillFilePath)),discoveryRoute:a,...e.pluginName?{pluginName:e.pluginName}:{},...e.pluginManifestPath?{pluginManifestPath:e.pluginManifestPath}:{},files:r,originalFiles:r,validation:i}}async function pC(e){let t=mt(rt.dirname(e.skillFilePath)),n;try{n=await G7(t,e.allFiles,e.fetchFile)}catch(c){if(!(c instanceof da))throw c;let u=c.message;return e.issues.push({severity:"warning",code:"skill-too-large",message:u,path:e.skillFilePath}),null}let r=t!=="."?mo(rt.basename(t))??void 0:void 0,i=rg({files:n,fallbackSkillSlug:r,allowNormalization:e.allowNormalization??!0}),o=i.validation,s=i.skillSlug??iu(o,null);if(!s||!o.parsedSkill)return fa(e.issues,o,e.skillFilePath),null;let a=mt(t),l=Cj(e.discoveryRoute,a);return{skillSlug:s,description:i.description??o.parsedSkill.frontmatter.description,...i.originalSkillName?{originalSkillName:i.originalSkillName}:{},relativeSkillRoot:a,relativeSkillFile:e.skillFilePath,discoveryRoute:l,...e.pluginName?{pluginName:e.pluginName}:{},...e.pluginManifestPath?{pluginManifestPath:e.pluginManifestPath}:{},...i.normalizationIssues.length>0?{normalizationIssues:i.normalizationIssues}:{},...i.normalizationProvenance?{normalizationProvenance:i.normalizationProvenance}:{},files:i.files,originalFiles:n,validation:o}}async function V7(e,t){let n=[],r=xi(t);async function i(o){let s=await hj(o,{withFileTypes:!0});for(let a of s){let l=r.join(o,a.name),c=Sn(r.relative(e,l));if(a.isDirectory()){if(or.has(a.name)||l!==e&&await ru(r.join(l,"SKILL.md")))continue;await i(l);continue}if(!hC(c)){if(n.length>=og)throw new da(`Skill root contains too many files. The maximum allowed is ${og}.`);n.push({path:c,...en(new Uint8Array(await mC(l)))})}}}return await i(e),n.sort((o,s)=>o.path.localeCompare(s.path))}async function G7(e,t,n){let r=new Set([...t].filter(o=>o==="SKILL.md"||o.endsWith("/SKILL.md")).map(o=>mt(rt.dirname(o)))),i=[...t].filter(o=>_i(o,e)!==null).filter(o=>!Ij(e,o,r)).filter(o=>{let s=_i(o,e);return s!==null&&!hC(s)}).sort((o,s)=>o.localeCompare(s));if(i.length>og)throw new da(`Skill root contains too many files (${i.length}). The maximum allowed is ${og}.`);return Promise.all(i.map(async o=>{let s;try{s=await n(o)}catch(a){throw new ca(a)}return{path:_i(o,e)??o,...typeof s=="string"?{content:s}:s}}))}async function fC(e,t,n){let r=xi(t),i=[];async function o(s,a){if(a>n.maxDepth)return;let l=await hj(s,{withFileTypes:!0});for(let c of l){if(c.isDirectory()){if(n.ignoreDirNames.has(c.name))continue;await o(r.join(s,c.name),a+1);continue}c.name==="SKILL.md"&&i.push(r.join(s,c.name))}}return await o(e,0),i.sort()}function tu(e,t,n){let r=[];for(let i of e){if(rt.basename(i)!=="SKILL.md")continue;let o=_i(i,t);if(o===null)continue;let s=o.split("/").filter(a=>a.length>0);s.length!==0&&(s.slice(0,-1).some(a=>n.ignoreDirNames.has(a))||s.length-1>n.maxDepth||r.push(i))}return r.sort((i,o)=>i.localeCompare(o))}function H7(e){return e.kind==="url"?e.url:e.kind==="well-known"?e.sourceUrl:e.rawUrl}function Sj(e,t){return e.kind==="github"?`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref}/${t}`:`https://${e.host}/${e.namespace}/${e.repo}/-/raw/${e.ref}/${t}`}function hC(e){let t=mt(e);if(t==="."||t.length===0)return!1;let n=t.split("/").filter(o=>o.length>0);if(n.some(o=>or.has(o)))return!0;let r=n[n.length-1]??"",i=Buffer.from([46,68,83,95,83,116,111,114,101]).toString("ascii");return r===i||r==="Thumbs.db"}async function K7(e,t){if(e.kind==="github"){let o=await t(`https://api.github.com/repos/${e.owner}/${e.repo}/git/trees/${encodeURIComponent(e.ref)}?recursive=1`,{headers:{"user-agent":"skills-layer-source-inspector"}});if(!o.ok)throw new ho(o.status,await Si(o));return((await o.json()).tree??[]).filter(a=>a.type==="blob"&&typeof a.path=="string"&&!dj(a.mode)).map(a=>({path:a.path,providerBlobSha:eu(a.sha),sizeBytes:Number.isSafeInteger(a.size)&&(a.size??-1)>=0?a.size:null})).sort((a,l)=>a.path.localeCompare(l.path))}let n=encodeURIComponent(`${e.namespace}/${e.repo}`),r=[],i=1;for(;;){let o=new URLSearchParams({recursive:"true",ref:e.ref,per_page:"100",page:String(i)}),s=await t(`https://${e.host}/api/v4/projects/${n}/repository/tree?${o.toString()}`);if(!s.ok)throw new ho(s.status,await Si(s));let a=await s.json();r.push(...a.filter(c=>c.type==="blob"&&typeof c.path=="string"&&!dj(c.mode)).map(c=>({path:c.path,providerBlobSha:eu(c.id),sizeBytes:null})));let l=s.headers.get("x-next-page");if(!l||l.trim().length===0||(i=Number.parseInt(l,10),Number.isNaN(i)||i<1))break}return r.sort((o,s)=>o.path.localeCompare(s.path))}function dj(e){return e==="120000"}async function W7(e,t,n){if(/^[a-f0-9]{40}$/iu.test(e.ref))return{commitSha:e.ref.toLowerCase(),treeSha:null};if(e.kind==="github")try{let i=await t(`https://api.github.com/repos/${e.owner}/${e.repo}/commits/${encodeURIComponent(e.ref)}`,{headers:{"user-agent":"skills-layer-source-inspector"}});if(!i.ok)throw new ho(i.status,await Si(i));let o=await i.json(),s=eu(o.sha);if(!s)throw new Error("GitHub source revision did not resolve to an immutable commit.");return{commitSha:s,treeSha:eu(o.commit?.tree?.sha)}}catch{return{commitSha:n,treeSha:null}}let r=encodeURIComponent(`${e.namespace}/${e.repo}`);try{let i=await t(`https://${e.host}/api/v4/projects/${r}/repository/commits/${encodeURIComponent(e.ref)}`);if(!i.ok)throw new ho(i.status,await Si(i));let o=await i.json(),s=eu(o.id);if(!s)throw new Error("GitLab source revision did not resolve to an immutable commit.");return{commitSha:s,treeSha:null}}catch{return{commitSha:n,treeSha:null}}}function Z7(e){let t=sg("sha256");for(let n of[...e].sort((r,i)=>r.relativeSkillRoot.localeCompare(i.relativeSkillRoot))){t.update(n.relativeSkillRoot),t.update("\0");for(let r of[...n.originalFiles].sort((i,o)=>i.path.localeCompare(o.path)))t.update(r.path),t.update("\0"),t.update(ye(r)),t.update("\0")}return`content-sha256:${t.digest("hex")}`}function eu(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function J7(e){return`sha256:${sg("sha256").update(e).digest("hex")}`}function Y7(e,t){if(typeof e=="string")return e;if(typeof e.content!="string")throw new Error(`${t} must be valid bounded UTF-8 text.`);return e.content}async function X7(e,t){let n=new URL(e),r=n.pathname.replace(/\/+$/u,""),i=r.match(/^(.*\/\.well-known\/skills)(?:\/.*)?$/iu),o=[`${n.protocol}//${n.host}${r}/.well-known/skills/index.json`];i&&o.push(`${n.protocol}//${n.host}${i[1]}/index.json`),r.length>0&&!r.includes("/.well-known/skills")&&o.push(`${n.protocol}//${n.host}/.well-known/skills/index.json`),r.endsWith("/.well-known/skills")&&o.unshift(`${n.protocol}//${n.host}${r}/index.json`),r.endsWith("/.well-known/skills/index.json")&&o.unshift(`${n.protocol}//${n.host}${r}`);for(let s of[...new Set(o)])try{let a=await t(s);if(!a.ok||!(a.headers.get("content-type")??"").includes("json"))continue;return{indexUrl:s,index:lj(await a.json())}}catch{continue}return null}async function Q7(e,t){try{let n=await t(e);return!n.ok||!(n.headers.get("content-type")??"").includes("json")?null:sj(await n.json())}catch{return null}}async function pj(e,t){try{let n=await t(e);return!n.ok||!(n.headers.get("content-type")??"").includes("json")?null:aj(await n.json())}catch{return null}}function fj(e){let t={};for(let n of e.manifest.skill.files)t[n.path]=n.url;return{kind:"well-known",input:e.skillFilter?`${e.inputSource.input}#${e.skillFilter}`:e.inputSource.input,indexUrl:e.detectedIndex.indexUrl,providerName:e.manifest.provider.name||e.detectedIndex.index.provider.name,providerUrl:e.manifest.provider.baseUrl||e.detectedIndex.index.provider.baseUrl,skillSlug:e.manifest.skill.slug,skillManifestUrl:e.manifestUrl,sourceUrl:e.manifest.skill.sourceUrl,files:e.manifest.skill.files.map(n=>n.path),fileUrls:t,canonicalSource:`${e.detectedIndex.indexUrl}#${e.manifest.skill.slug}`,...e.skillFilter?{skillFilter:e.skillFilter}:{}}}function mj(e,t){let n=e;for(let[r,i]of Object.entries(t))n=n.replaceAll(`{${r}}`,encodeURIComponent(i));return n}function eY(e){try{return new URL(e).searchParams.get("q")?.trim()??""}catch{return""}}function xj(e){let t=e.toLowerCase();return t.endsWith(".md")||t.endsWith(".txt")}function tY(e){try{let r=new URL(e).pathname.match(/\/\.well-known\/skills\/([^/]+)(?:\/.*)?$/iu)?.[1];return r&&r!=="index.json"&&r!=="search.json"?r:void 0}catch{return}}function iu(e,t){return e.parsedSkill?.frontmatter.name??(t?.kind==="well-known"?t.skillSlug:void 0)}function pa(e,t){return!e||e===t}function yC(e,t){return gj(e.discoveryRoute)-gj(t.discoveryRoute)||e.relativeSkillRoot.localeCompare(t.relativeSkillRoot)}function ua(e,t){let n=`${t.skillSlug}:${t.relativeSkillRoot}`,r=e.get(n);if(!r){e.set(n,t);return}let i=yC(t,r)<0?t:r,o=i===t?r:t;e.set(n,{...i,pluginName:i.pluginName??o.pluginName,pluginManifestPath:i.pluginManifestPath??o.pluginManifestPath})}function gj(e){switch(e){case"remote_file":return 0;case"root":return 1;case"curated":return 2;case"skills":return 3;case"system":return 4;case"experimental":return 5;case"plugin_manifest":return 6;case"agent":return 7;case"recursive":return 8}}function mt(e){let t=Sn(e);return t.length===0?".":t}function nY(e){let t=mt(e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""));return t==="SKILL.md"?".":t.endsWith("/SKILL.md")?mt(rt.dirname(t)):t}function rY(e){let t=(e??[]).map(r=>r.replaceAll("\\","/").replace(/^\/+/u,"").trim()).filter(r=>r.length>0),n=[...new Set(t)];return n.includes("SKILL.md")?n:["SKILL.md",...n]}function iY(e,t){let n=new URL(e),r=n.toString().endsWith("/SKILL.md")?n.toString().slice(0,-8):`${n.toString().replace(/\/+$/u,"")}/`;return new URL(t.replace(/^\/+/u,""),r).toString()}function Cj(e,t){return e==="skills"&&t.startsWith("skills/.curated/")?"curated":e==="skills"&&t.startsWith("skills/.system/")?"system":e==="skills"&&t.startsWith("skills/.experimental/")?"experimental":e}function xi(e){return e==="win32"?S7:rt}function Sn(e){return e.replaceAll("\\","/")}function lC(e,t){for(let n of t){let r=e[n];if(typeof r=="string"&&r.trim().length>0)return r.trim()}}function cC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nu(e,t){let n=e==="."?"":e.replace(/\/+$/u,""),r=t.replace(/^\.\/+/u,"");return[n,r].filter(i=>i.length>0).join("/")||"."}function _i(e,t){let n=mt(e),r=mt(t);return r==="."?n:n===r?".":n.startsWith(`${r}/`)?n.slice(r.length+1):null}function Ij(e,t,n){let r=mt(rt.dirname(t));for(;r!=="."&&r!==e;){if(n.has(r))return!0;r=mt(rt.dirname(r))}return!1}function oY(e,t){let n=[];return fa(n,e,t),n}function fa(e,t,n){if(!t.valid)for(let r of t.issues)r.severity==="error"&&sY(e,{severity:"warning",code:r.code,message:r.message,path:n})}function sY(e,t){e.some(n=>n.code===t.code&&n.message===t.message&&n.path===t.path)||e.push(t)}function Pj(e,t,n){let r=xi(n),i=r.resolve(e),o=r.resolve(t),s=r.relative(i,o);return s.length===0||!s.startsWith("..")&&!r.isAbsolute(s)}async function ru(e){try{return await yj(e),!0}catch{return!1}}var ho=class extends Error{constructor(n,r){super(r.message);this.status=n;this.name="ApiErrorLike"}status};async function Si(e){let t=e.headers.get("content-type")??"",n=e.clone();if(t.includes("application/json"))try{let r=await e.json(),i=typeof r.error=="string"?r.error:typeof r.message=="string"?r.message:"";if(i.trim().length>0)return new Error(i.trim())}catch{}return new Error(await n.text()||`Remote source request failed with ${e.status}.`)}var aY=18;function lY(e,t){let n=e.map(c=>_i(c,t)).filter(c=>c!==null),r=new Set(n),i=new Set,o=[],s=gC();for(let c of s){let u=c.discoveryRoute==="root"?r.has("SKILL.md")?["SKILL.md"]:[]:tu(r,c.absolutePath,{maxDepth:5,ignoreDirNames:or});for(let d of u)i.has(d)||(i.add(d),o.push(d))}for(let c of tu(r,".",{maxDepth:6,ignoreDirNames:or}))i.has(c)||(i.add(c),o.push(c));let a=new Set(o.map(c=>mt(rt.dirname(c)))),l=[];for(let c of o){let u=mt(rt.dirname(c)),d=[...r].filter(p=>_i(p,u)!==null).filter(p=>!Ij(u,p,a)).filter(p=>{let m=_i(p,u);return m!==null&&!hC(m)}).sort((p,m)=>p.localeCompare(m));l.push({skillFilePath:c,skillRoot:u,bundleFilePaths:d,bundleFileCount:d.length,estimatedCost:d.length+aY})}return l.sort((c,u)=>c.skillFilePath.localeCompare(u.skillFilePath))}import{constants as Aj}from"node:fs";import{lstat as cg,open as cY,opendir as uY,realpath as $j}from"node:fs/promises";import{dirname as Dj,isAbsolute as kC,parse as Tj,relative as ou,resolve as su,sep as Oj}from"node:path";var pe=class extends Error{code;issueCodes;issues;preview;constructor(t,n=[],r){super(`Local bundle rejected (${t}).`),this.name="LocalBundleIntakeError",this.code=t,this.issueCodes=[...new Set(n)].sort((i,o)=>i.localeCompare(o)),this.issues=r?.issues??[],this.preview=r?.preview}},dY=32*1024,pY=64*1024;async function ma(e){let t=gY(e.limits),n=hY(e.maxTraversalEntries,t.maxFiles),r=su(e.cwd),i=su(r,e.sourcePath);await yY(r,e.sourcePath,i);let o=await Bj(i);wC(o);let s=await Ej(i),a=o.isDirectory()?s:await Ej(Dj(i));bC(a,s);let l={rootRealPath:a,limits:t,maxTraversalEntries:n,traversalEntries:0,fileCount:0,declaredTotalBytes:0,skillsIgnore:"",excludePath:Ay(),files:[],excluded:[],hooks:e.hooks};if(o.isFile()){let d=IY(i),p=l.excludePath(d);p?l.excluded.push({path:d,reason:p}):await Nj(i,d,o,l)}else await wY(i,o,l);let c;try{c=Zr({files:l.files,skillsIgnore:l.skillsIgnore,limits:t})}catch{let d=Wr({files:l.files,skillsIgnore:l.skillsIgnore,limits:t});throw new pe("canonical_bundle_rejected",d.issues.map(p=>p.code),fY(d))}if(c.files.length===0)throw new pe("local_bundle_empty");let u=new Map;for(let d of[...l.excluded,...c.excluded])u.set(d.path,d);return{...c,excluded:[...u.values()].sort((d,p)=>d.path.localeCompare(p.path))}}function fY(e){return{issues:e.issues.map(t=>{let n=mY(t.code),r=Rj(t.path,t.code);return{code:t.code,...r?{path:r}:{},message:t.message,...n}}),preview:{fileCount:e.preview.fileCount,totalBytes:e.preview.totalBytes,bundleSha256:e.preview.bundleSha256,files:e.preview.files.filter(t=>Rj(t.path,"preview")).map(t=>({...t}))}}}function Rj(e,t){if(!(!e||t==="pii_path"||e.startsWith("/")||/^[A-Za-z]:/u.test(e)||e.includes("\\")||e.split("/").some(n=>!n||n==="."||n==="..")||/[^\s@]+@[^\s@]+\.[^\s@]+/u.test(e)))return e}function mY(e){return e==="pii_email"||e==="pii_phone"||e==="pii_path"?{remediationId:"remove_personal_data",remediation:"Remove personal contact data from distributable skill files and validate again."}:e.startsWith("secret_")?{remediationId:"remove_secret",remediation:"Remove the secret and reference a runtime-provided credential instead."}:e.includes("path")||e==="reserved_path"||e==="binary_content"?{remediationId:"fix_bundle_entry",remediation:"Rename, remove, or convert the listed bundle entry to portable UTF-8 text."}:e.includes("exceeded")||e==="file_too_large"?{remediationId:"reduce_bundle_size",remediation:"Reduce the listed file or bundle size to the documented canonical limits."}:{remediationId:"fix_canonical_bundle",remediation:"Correct the listed canonical intake issue and run validation again."}}function gY(e){let t={...wt,...e};return Wr({files:[],limits:t,runDlp:!1}),t}function hY(e,t){let n=e??Math.max(256,t*8);if(!Number.isInteger(n)||n<=0)throw new pe("local_traversal_budget_exceeded");return n}async function yY(e,t,n){let r=kY(e,t,n);for(let i=0;i<r.length;i+=1){let o=await Bj(r[i]);if(o.isSymbolicLink()){if(vY(r[i],o,t,e,n,i))continue;throw new pe("local_entry_symlink")}if(i<r.length-1&&!o.isDirectory())throw new pe("local_entry_non_regular")}}function vY(e,t,n,r,i,o,s=process.platform){if(s==="win32"||!kC(n)||_C(ou(r,i))||o!==0||t.uid!==0n)return!1;let a=Tj(e).root;return Dj(e)===a}function kY(e,t,n){if(!kC(t))return vC(e,ou(e,n));let r=ou(e,n);if(_C(r))return vC(e,r);let i=Tj(n).root;return vC(i,ou(i,n))}function vC(e,t){let n=[],r=e;for(let i of t.split(Oj))!i||i==="."||(r=su(r,i),n.at(-1)!==r&&n.push(r));return n}async function wY(e,t,n){let r=await jj(e,t,n);if(r.includes(".skillsignore")){let i=su(e,".skillsignore"),o=await Mj(i);if(wC(o),!o.isFile())throw new pe("local_entry_non_regular");n.skillsIgnore=await _Y(i,".skillsignore",o,dY,n);try{n.excludePath=Ay(n.skillsIgnore)}catch{throw new pe("canonical_bundle_rejected",["skillsignore_invalid"])}n.files.push({path:".skillsignore",content:n.skillsIgnore})}await Lj(e,t,r,"",n)}async function bY(e,t,n,r){let i=await jj(e,n,r);await Lj(e,n,i,t,r)}async function Lj(e,t,n,r,i){for(let o of n){let s=r?`${r}/${o}`:o;if(!r&&s===".skillsignore")continue;let a=i.excludePath(s);if(a){i.excluded.push({path:s.normalize("NFC"),reason:a});continue}CY(s,i.limits);let l=su(e,o);await i.hooks?.beforeEntryInspection?.({relativePath:s});let c=await Mj(l);wC(c),await i.hooks?.afterEntryInspection?.({relativePath:s,kind:c.isDirectory()?"directory":"file"}),await ag(l,c);let u={relativePath:s,kind:c.isDirectory()?"directory":"file"};await i.hooks?.afterEntryValidation?.(u);let d=await Uj(l);bC(i.rootRealPath,d),c.isDirectory()?await bY(l,s,c,i):await Nj(l,s,c,i)}await ag(e,t)}async function jj(e,t,n){let r;try{r=await uY(e)}catch{throw new pe("local_entry_unreadable")}let i=[];try{for(;;){let o=await r.read();if(!o)break;if(n.traversalEntries+=1,n.traversalEntries>n.maxTraversalEntries)throw new pe("local_traversal_budget_exceeded");i.push(o.name)}}catch(o){throw o instanceof pe?o:new pe("local_entry_unreadable")}finally{await r.close().catch(()=>{})}return await ag(e,t),i.sort((o,s)=>o.localeCompare(s))}async function Nj(e,t,n,r){if(r.fileCount+=1,r.fileCount>r.limits.maxFiles)throw new pe("local_file_count_exceeded");let i=Ey(t,r.limits);if(n.size>BigInt(i))throw new pe("local_file_bytes_exceeded");let o=r.declaredTotalBytes+Number(n.size);if(!Number.isSafeInteger(o)||o>r.limits.maxTotalBytes)throw new pe("local_total_bytes_exceeded",["local_total_bytes_exceeded"],{issues:[{code:"local_total_bytes_exceeded",path:t,message:`Bundle exceeds the ${r.limits.maxTotalBytes}-byte upload limit.`,remediationId:"reduce_bundle_size",remediation:"Remove unnecessary files or reduce their size, then validate again."}]});let s=await Fj(e,t,n,i,r),a=en(s,Sl(t,s));if(typeof a.contentBase64=="string"&&jE(t))throw new pe("local_entry_invalid_utf8");r.declaredTotalBytes=o,r.files.push({path:t,...a})}async function _Y(e,t,n,r,i){let o=await Fj(e,t,n,r,i);try{return new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new pe("local_entry_invalid_utf8")}}async function Fj(e,t,n,r,i){await ag(e,n);let o=await Uj(e);bC(i.rootRealPath,o);let s={relativePath:t,kind:"file"};await i.hooks?.beforeFileOpen?.(s);let a;try{a=await cY(e,Aj.O_RDONLY|Aj.O_NOFOLLOW)}catch(l){throw new pe(PY(l)?"local_entry_raced":"local_entry_unreadable")}try{let l=await a.stat({bigint:!0});if(!l.isFile())throw new pe("local_entry_non_regular");if(!lg(n,l))throw new pe("local_entry_raced");await i.hooks?.afterFileOpen?.(s);let c=await SY(a,r),u=await a.stat({bigint:!0});if(!lg(l,u)||BigInt(c.byteLength)!==u.size)throw new pe("local_entry_raced");return await i.hooks?.afterFileMetadataValidation?.(s),await xY(e,u),c}catch(l){throw l instanceof pe?l:new pe("local_entry_unreadable")}finally{await a.close().catch(()=>{})}}async function SY(e,t){let n=[],r=0;for(;;){let i=t+1-r,o=Buffer.allocUnsafe(Math.min(pY,i)),{bytesRead:s}=await e.read(o,0,o.byteLength,r);if(s===0)break;if(r+=s,r>t)throw new pe("local_file_bytes_exceeded");n.push(o.subarray(0,s))}return Buffer.concat(n,r)}async function Bj(e){try{return await cg(e,{bigint:!0})}catch{throw new pe("local_entry_unreadable")}}async function Mj(e){try{return await cg(e,{bigint:!0})}catch{throw new pe("local_entry_unreadable")}}function wC(e){if(e.isSymbolicLink())throw new pe("local_entry_symlink");if(!e.isDirectory()&&!e.isFile())throw new pe("local_entry_non_regular")}async function ag(e,t){let n;try{n=await cg(e,{bigint:!0})}catch{throw new pe("local_entry_raced")}if(!lg(t,n))throw new pe("local_entry_raced")}async function xY(e,t){let n;try{n=await cg(e,{bigint:!0})}catch{throw new pe("local_entry_raced")}if(!lg(t,n))throw new pe("local_entry_raced")}function lg(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.mode===t.mode&&e.size===t.size&&e.mtimeNs===t.mtimeNs&&e.ctimeNs===t.ctimeNs}async function Ej(e){try{return await $j(e)}catch{throw new pe("local_entry_unreadable")}}async function Uj(e){try{return await $j(e)}catch{throw new pe("local_entry_raced")}}function bC(e,t){if(!_C(ou(e,t)))throw new pe("local_entry_outside_root")}function _C(e){return e===""||!e.startsWith(`..${Oj}`)&&e!==".."&&!kC(e)}function CY(e,t){if(e.split("/").length>t.maxDepth)throw new pe("local_path_depth_exceeded");if(Buffer.byteLength(e,"utf8")>t.maxPathBytes)throw new pe("local_path_length_exceeded")}function IY(e){let t=e.replaceAll("\\","/").split("/");return t[t.length-1]}function PY(e){return["ELOOP","ENOENT","ENOTDIR"].includes(String(e.code))}var AY=fn(Ji(),1);import{createHash as RY}from"node:crypto";var zj="skills-layer.commercial-rights-declaration.v1",EY="I declare that I own this skill bundle or am authorised by its rightsholder to distribute it commercially, and that charging for it does not infringe the rights of any other person.",Mye=`sha256:${RY("sha256").update(EY).digest("hex")}`;import{createHash as $Y}from"node:crypto";var DY=6,TY=1e3,OY=3e4,LY=5e3,jY=1e3,NY=12e4;function dg(e){return e.reduce((t,n)=>t+cs(n),0)>wt.maxTotalBytes}async function xC(e){let t=e.apiKey?"/api/v1/me/source-hydrations":"/api/v1/source-hydrations",n=e.baseUrl.replace(/\/+$/u,""),r=e.apiKey?{authorization:`Bearer ${e.apiKey}`}:{},i=e.sleep??MY,o=e.files.map(u=>{let d=ye(u);return{file:u,bytes:d,mediaType:u.mediaType?.trim()||Sl(u.path,d),sha256:`sha256:${$Y("sha256").update(d).digest("hex")}`}}),s=await SC(()=>e.fetchFn(`${n}${t}`,{method:"POST",headers:{"content-type":"application/json",...r},body:JSON.stringify({...e.apiKey?{}:{visibility:"public"},files:o.map(({file:u,bytes:d,mediaType:p,sha256:m})=>({path:u.path,sizeBytes:d.byteLength,sha256:m,mediaType:p}))})}),{sleep:i,retryBusy:!1}),a=ug(s,"manifestId"),l=new Map((Array.isArray(s.files)?s.files:[]).filter(u=>!!u&&typeof u=="object"&&!Array.isArray(u)).map(u=>[ug(u,"path"),ug(u,"uploadPath")]));for(let{file:u,bytes:d,mediaType:p}of o){let m=l.get(u.path);if(!m)throw new Error(`Source hydration upload path is missing for ${u.path}.`);await SC(()=>e.fetchFn(`${n}${m}`,{method:"PUT",headers:{"content-type":p,...r},body:Buffer.from(d)}),{sleep:i,retryBusy:!0})}let c=await SC(()=>e.fetchFn(`${n}${t}/${encodeURIComponent(a)}`,{headers:r}),{sleep:i,retryBusy:!1});if(c.status!=="validated")throw new Error("Source hydration upload did not reach validated state.");return{manifestId:a,candidateId:ug(c,"candidateId")}}async function SC(e,t){for(let n=1;;n+=1){let r=await e(),i=await r.text(),o=UY(i),s=n<DY?FY(r,o,n,t.retryBusy):null;if(s===null)return zY(r,i,o);await t.sleep(s)}}function FY(e,t,n,r){return e.status===429?ga(t)&&t.reasonCode==="anonymous_upload_quota_exceeded"?null:qj(e.headers.get("retry-after"))??LY:r&&e.status===409&&BY(t)?qj(e.headers.get("retry-after"))??Math.min(OY,TY*2**(n-1)):null}function BY(e){return ga(e)?e.status==="unavailable"||ga(e.data)&&e.data.status==="unavailable":!1}function qj(e){let t=e?.trim()??"";if(!t)return null;let n=/^\d+$/u.test(t)?Number(t)*1e3:Date.parse(t)-Date.now();return Number.isFinite(n)?Math.min(NY,Math.max(jY,n)):null}function MY(e){return new Promise(t=>setTimeout(t,e))}function UY(e){try{return e?JSON.parse(e):null}catch{return null}}function zY(e,t,n){if(!e.ok){let r=ga(n)&&typeof n.error=="string"?n.error:t||e.statusText||"Source hydration request failed.";throw new Error(r)}if(!ga(n))throw new Error("Source hydration returned an invalid response.");return n.schemaVersion!=="skills-layer.creator.operation.v1"&&ga(n.data)?n.data:n}function ga(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ug(e,t){let n=e[t];if(typeof n!="string"||!n.trim())throw new Error(`Source hydration response is missing ${t}.`);return n}var Hye=256*1024;var Jye=26*1024*1024;var qY=1024*1024;var yo=Object.freeze({...wt,maxTotalBytes:20*qY});var ive=Array.from({length:256},(e,t)=>{let n=t;for(let r=0;r<8;r+=1)n=(n&1)!==0?3988292384^n>>>1:n>>>1;return n>>>0});import{createHash as VY,randomUUID as Kj,timingSafeEqual as GY}from"node:crypto";import{constants as Ii}from"node:fs";import{chmod as HY,lstat as Ai,mkdir as $C,mkdtemp as KY,open as mg,realpath as PC,readdir as WY,rename as Ri,rm as Wj}from"node:fs/promises";import{basename as Ci,dirname as $r,join as xn,parse as gg,posix as CC,resolve as hg,sep as au}from"node:path";var ZY=3e4,Vj=5*6e4,lu=/^sha256:[a-f0-9]{64}$/u,Zj=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,Jj=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,JY=new TextEncoder().encode("SKILLS-LAYER-MANIFEST-V1\0"),yg=typeof Ii.O_NOFOLLOW=="number"?Ii.O_NOFOLLOW:0;async function Yj(e){return Qj(e,!0)}async function Xj(e){return Qj(e,!1)}async function Qj(e,t){let n=YY(e.preActivationTimeoutMs),r=Nd({archiveBytes:e.archiveBytes,envelope:e.envelope});t&&XY(e.approval,r);let i=Cl({archiveBytes:e.archiveBytes,envelope:r});e2(i);let o=hg(e.targetDir),s=await ya(o);if(s===gg(s).root)throw new Error("Atomic install target cannot be a filesystem root.");if(Ci(s)!==r.generation.skillSlug&&Ci(s)!==Mr(r.generation.skillSlug))throw new Error("Atomic install target basename must equal the approved skill slug or its private base name.");let a=$r(s);await uu(a),await $C(a,{recursive:!0,mode:448}),await uu(a);let l=await Fn(a,"Atomic install parent"),c=await TC(s),u=await KY(xn(a,`.${Ci(s)}.skills-layer-stage-`)),d=await Fn(u,"Atomic install stage"),p=null,m=!1,h=!1;try{await vo(e.checkpoint,"after_stage_created");for(let b of i)await QY(u,b),await vo(e.checkpoint,"after_file_written");await ha(u,r.manifest.files,d);let g=await nX({callback:e.preActivate,stageDir:u,files:r.manifest.files,timeoutMs:n});if(g.status!=="passed")throw new Error(`Static pre-activation Eval failed: ${g.reasonCode}`);await ha(u,r.manifest.files,d),await Gj(u,r.manifest.files),await vo(e.checkpoint,"after_static_eval"),await ha(u,r.manifest.files,d),await Gj(u,r.manifest.files),await Pi(a,l,"Atomic install parent changed during staging."),await a2(s,c),await Zt(a),e.expectedPreviousReceipt&&await cu(s,e.expectedPreviousReceipt),c.exists&&(p=xn(a,`.${Ci(s)}.skills-layer-backup-${Kj()}`),await Ri(s,p),m=!0,await Zt(a),await vo(e.checkpoint,"after_target_backed_up"),e.expectedPreviousReceipt&&await cu(p,e.expectedPreviousReceipt)),await Ri(u,s),h=!0,await Zt(a),await vo(e.checkpoint,"after_stage_activated");let y=mX({targetDir:o,generation:r.generation,archiveSha256:r.archive.sha256,manifestSha256:r.manifest.sha256,files:r.manifest.files}),v=await iX(p,a);return p=v.backupStillExists?p:null,{status:c.exists?"replaced":"created",receipt:y,staticEvaluation:g,cleanupPending:v.backupStillExists,...v.backupStillExists&&p?{cleanupPath:p}:{}}}catch(g){throw await rX({targetDir:s,stageDir:u,parentDir:a,backupDir:p,backupMoved:m,stageActivated:h,originalError:g}),g}}function e2(e){if(e.some(t=>typeof t.path=="string"&&t.path!==t.path.normalize("NFC")))throw new Error("Portable install paths must use NFC Unicode normalization.");try{let t=Zr({files:e,runDlp:!1,limits:{maxTotalBytes:ut.maxTotalFileBytes}});if(t.excluded.length>0||t.files.length!==e.length)throw new Error("install-control or excluded paths are not deliverable files");for(let n=0;n<t.files.length;n+=1){let r=t.files[n],i=e.find(o=>o.path===r.path);if(!i||i.content!==r.content)throw new Error("portable normalization changed the approved file set")}}catch(t){throw new Error(`Portable install paths rejected: ${c2(t)}`,{cause:t})}}async function t2(e){if(!Zj.test(e.reasonCode))throw new Error("Quarantine reason code is invalid.");DC(e.receipt);let t=await ya(e.receipt.targetDir),n=$r(t);await uu(t);let r=await Fn(n,"Atomic quarantine parent"),i=await cu(t,e.receipt),o=await s2(e.discoveryRoots),s=await ya(e.quarantineRoot);AC({targetDir:t,quarantineRoot:s,discoveryRoots:o});let a=await r2({callback:e.authorizeQuarantine,context:{receipt:e.receipt,targetDir:t,quarantineRoot:s,discoveryRoots:o,reasonCode:e.reasonCode},receipt:e.receipt,allowedPurposes:["quarantine_blocked","quarantine_revoked"]});await $C(s,{recursive:!0,mode:448}),await uu(s),await HY(s,448);let l=await RC(s,"External quarantine root");AC({targetDir:t,quarantineRoot:l,discoveryRoots:o});let c=await Fn(l,"External quarantine root");if(c.dev!==r.dev)throw new Error("External quarantine root must be on the same filesystem for an atomic fail-closed move.");let u=xn(l,`${Ci(t)}.skills-layer-quarantine-${Kj()}`);await Pi(n,r,"Atomic quarantine parent changed."),await Pi(l,c,"External quarantine root changed."),await Pi(t,i,"Installed generation changed before quarantine."),await Ri(t,u);try{await Zt(n),await Zt(l),await ha(u,e.receipt.files,i),await vo(e.checkpoint,"after_quarantine_rename")}catch(d){throw await Ri(u,t),await Zt(n),await Zt(l),d}return Object.freeze({status:"quarantined",reasonCode:e.reasonCode,targetDir:e.receipt.targetDir,quarantineRoot:l,quarantineDir:u,discoveryRoots:Object.freeze([...o]),quarantineAuthorization:a,receipt:e.receipt})}async function n2(e){oX(e.quarantine);let t=await ya(e.quarantine.receipt.targetDir),n=await s2(e.quarantine.discoveryRoots),r=await RC(e.quarantine.quarantineRoot,"External quarantine root"),i=await RC(e.quarantine.quarantineDir,"Quarantine tree"),o=$r(t);if(AC({targetDir:t,quarantineRoot:r,discoveryRoots:n}),$r(i)!==r||!Ci(i).startsWith(`${Ci(t)}.skills-layer-quarantine-`))throw new Error("Quarantine generation is outside its validated external quarantine root.");let s=await Fn(o,"Atomic restore parent"),a=await Fn(r,"External quarantine root"),l=await cu(i,e.quarantine.receipt),c=await TC(t);if(c.exists)throw new Error("Cannot restore quarantine because the install target already exists.");let u={receipt:e.quarantine.receipt,targetDir:t,quarantineRoot:r,quarantineDir:i,discoveryRoots:n,reasonCode:e.quarantine.reasonCode,quarantineAuthorization:e.quarantine.quarantineAuthorization},d=await r2({callback:e.authorizeRestore,context:u,receipt:e.quarantine.receipt,allowedPurposes:["restore_fresh_approval"],forbiddenAuthorizationId:e.quarantine.quarantineAuthorization.authorizationId});await Pi(o,s,"Atomic restore parent changed."),await Pi(r,a,"External quarantine root changed."),await Pi(i,l,"Quarantine generation changed before restore."),await a2(t,c),await Ri(i,t);try{await Zt(o),await Zt(r),await ha(t,e.quarantine.receipt.files,l),await vo(e.checkpoint,"after_restore_rename"),await sX(e.finalizeRestore,{...u,restoreAuthorization:d})}catch(p){throw await Ri(t,i),await Zt(o),await Zt(r),p}return e.quarantine.receipt}function YY(e){let t=e??ZY;if(!Number.isInteger(t)||t<=0||t>Vj)throw new Error(`Static pre-activation timeout must be an integer from 1 to ${Vj} ms.`);return t}function XY(e,t){let n=e?.generation;if(e?.status!=="approved"||!n||n.skillSlug!==t.generation.skillSlug||n.semanticVersion!==t.generation.semanticVersion||n.generationId!==t.generation.generationId||!va(e.archiveSha256,t.archive.sha256)||!va(e.manifestSha256,t.manifest.sha256))throw new Error("Install denied: approved artifact identity does not match the verified deliverable.")}async function QY(e,t){let n=xn(e,...t.path.split("/"));await eX(e,$r(n));let r=await mg(n,Ii.O_WRONLY|Ii.O_CREAT|Ii.O_EXCL|yg,384);try{await r.writeFile(ye(t)),await r.sync()}finally{await r.close()}}async function eX(e,t){let n=t.slice(e.length).split(au).filter(Boolean),r=e;for(let i of n){r=xn(r,i);try{await $C(r,{mode:448})}catch(s){if(!hX(s))throw s}let o=await Ai(r);if(o.isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link in the staged tree: ${r}`);if(!o.isDirectory())throw new Error(`Atomic install staged path is not a directory: ${r}`)}}async function ha(e,t,n){let r=await Fn(e,"Install generation root");if(n&&!fg(r,n))throw new Error("Install generation root changed during staging.");let i=new Map(t.map(c=>[c.path,c])),o=new Set;for(let c of t){let u=CC.dirname(c.path);for(;u!==".";)o.add(u),u=CC.dirname(u)}let s=new Set,a=new Set,l=async(c,u)=>{let d=await Fn(c,"Install generation directory"),p=(await WY(c,{withFileTypes:!0})).sort((h,g)=>gX(h.name,g.name));for(let h of p){let g=xn(c,h.name),y=u?CC.join(u,h.name):h.name,v=await Ai(g);if(v.isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link in the generation tree: ${y}`);if(v.isDirectory()){if(!o.has(y))throw new Error(`Installed generation manifest has an unexpected directory: ${y}`);a.add(y),await l(g,y);continue}if(!v.isFile())throw new Error(`Atomic install refuses a non-regular generation entry: ${y}`);let b=i.get(y);if(!b)throw new Error(`Installed generation manifest has an unexpected file: ${y}`);let w=await tX(g,b.sizeBytes);if(w.sizeBytes!==b.sizeBytes||!va(w.sha256,b.sha256))throw new Error(`Installed generation manifest mismatch for ${y}.`);s.add(y)}let m=await Fn(c,"Install generation directory");if(!fg(d,m))throw new Error(`Install generation directory changed while verified: ${u||"."}`)};if(await l(e,""),s.size!==t.length||a.size!==o.size)throw new Error("Installed generation manifest is incomplete.");return await Pi(e,r,"Install generation root changed while verified."),r}async function tX(e,t){let n=await mg(e,Ii.O_RDONLY|yg);try{let r=await n.stat();if(!r.isFile())throw new Error(`Expected a regular installed generation file: ${e}`);if(r.size>t)throw new Error(`Installed generation file exceeds its approved size: ${e}`);let i=new Uint8Array(await n.readFile());return{sizeBytes:i.byteLength,sha256:l2(i)}}finally{await n.close()}}async function nX(e){let t=new AbortController,n,r=new Promise((i,o)=>{n=setTimeout(()=>{t.abort(),o(new Error(`Static pre-activation Eval timed out after ${e.timeoutMs} ms.`))},e.timeoutMs)});try{let i=await Promise.race([Promise.resolve().then(()=>e.callback({stageDir:e.stageDir,files:e.files,signal:t.signal})),r]);if(!i||i.status!=="passed"&&i.status!=="failed"||i.status==="passed"&&(typeof i.evidenceId!="string"||i.evidenceId.length===0)||i.status==="failed"&&(typeof i.reasonCode!="string"||i.reasonCode.length===0))throw new Error("Static pre-activation Eval returned an invalid result.");return i}finally{clearTimeout(n)}}async function Gj(e,t){for(let r of t){let i=await mg(xn(e,...r.path.split("/")),Ii.O_RDONLY|yg);try{await i.sync()}finally{await i.close()}}let n=new Set([e]);for(let r of t){let i=$r(xn(e,...r.path.split("/")));for(;i.startsWith(e)&&i!==$r(e)&&(n.add(i),i!==e);)i=$r(i)}for(let r of[...n].sort((i,o)=>o.length-i.length))await Zt(r)}async function rX(e){try{e.stageActivated&&await Ri(e.targetDir,e.stageDir),e.backupMoved&&e.backupDir&&await Ri(e.backupDir,e.targetDir),await uX(e.stageDir),await Zt(e.parentDir)}catch(t){let n=e.backupDir?` from ${e.backupDir}`:"";throw new Error(`Atomic install rollback requires manual recovery${n}.`,{cause:new AggregateError([e.originalError,t])})}}async function iX(e,t){if(!e)return{backupStillExists:!1};try{return await Wj(e,{recursive:!0,force:!1}),await Zt(t),{backupStillExists:!1}}catch(n){return ko(n)?{backupStillExists:!1}:{backupStillExists:!0}}}async function cu(e,t){DC(t);try{return await ha(e,t.files)}catch(n){throw new Error(`Installed generation manifest verification failed: ${c2(n)}`,{cause:n})}}async function Dr(e){try{return await cu(e.targetDir,e),Object.freeze({status:"verified",generation:e.generation,manifestSha256:e.manifestSha256})}catch{return Object.freeze({status:"changed",reasonCode:"installed_tree_manifest_mismatch",generation:e.generation,manifestSha256:e.manifestSha256})}}function DC(e){if(!e||typeof e.targetDir!="string"||!lu.test(e.archiveSha256)||!lu.test(e.manifestSha256)||!Array.isArray(e.files)||e.files.length===0)throw new Error("Installed generation receipt manifest is invalid.");let t=dX(e.files),n=e.files.map(r=>({path:r.path,content:""}));if(e2(n),!va(l2(t),e.manifestSha256))throw new Error("Installed generation receipt manifest digest is invalid.")}function oX(e){if(!e||e.status!=="quarantined"||!Zj.test(e.reasonCode)||typeof e.targetDir!="string"||typeof e.quarantineRoot!="string"||typeof e.quarantineDir!="string"||!Array.isArray(e.discoveryRoots)||e.discoveryRoots.length===0||!e.receipt||!i2(e.quarantineAuthorization)||e.quarantineAuthorization.purpose!=="quarantine_blocked"&&e.quarantineAuthorization.purpose!=="quarantine_revoked"||!o2(e.quarantineAuthorization,e.receipt)||e.targetDir!==e.receipt?.targetDir)throw new Error("Quarantine record is invalid.");DC(e.receipt)}async function r2(e){if(typeof e.callback!="function")throw new Error("Exact-generation authorization callback is required.");let t=await e.callback(e.context);if(t?.status==="denied")throw new Error(`Exact-generation authorization denied: ${t.reasonCode||"unspecified"}.`);if(!i2(t)||!e.allowedPurposes.includes(t.purpose)||!o2(t,e.receipt)||t.authorizationId===e.forbiddenAuthorizationId)throw new Error("Exact-generation authorization is invalid, stale, reused, or bound to different bytes.");return aX(t)}async function sX(e,t){if(typeof e!="function")throw new Error("Restore release callback is required.");let n=await e(t);if(n?.status!=="released"||!Jj.test(n.releaseId)){let r=n?.status==="denied"?n.reasonCode:"invalid_release_decision";throw new Error(`Restore release denied: ${r}.`)}}function i2(e){return typeof e=="object"&&e!==null&&"status"in e&&e.status==="authorized"&&"authorizationId"in e&&typeof e.authorizationId=="string"&&Jj.test(e.authorizationId)&&"purpose"in e&&(e.purpose==="quarantine_blocked"||e.purpose==="quarantine_revoked"||e.purpose==="restore_fresh_approval"||e.purpose==="purge_quarantined")&&"generation"in e&&typeof e.generation=="object"&&e.generation!==null&&"archiveSha256"in e&&typeof e.archiveSha256=="string"&&"manifestSha256"in e&&typeof e.manifestSha256=="string"}function o2(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&va(e.archiveSha256,t.archiveSha256)&&va(e.manifestSha256,t.manifestSha256)}function aX(e){return Object.freeze({...e,generation:Object.freeze({...e.generation})})}async function s2(e){if(!Array.isArray(e)||e.length===0||e.some(r=>typeof r!="string"||r.length===0))throw new Error("External quarantine requires the complete non-empty discovery root set.");let t=[],n=new Set;for(let r of e){let i=await ya(r),o=pg(i);n.has(o)||(t.push(i),n.add(o))}return Object.freeze(t)}function AC(e){let t=pg(e.targetDir),n=pg(e.quarantineRoot),r=e.discoveryRoots.map(pg);if(!r.some(i=>t!==i&&IC(t,i)))throw new Error("Install target is not inside the authoritative discovery root set.");for(let i of r)if(IC(n,i)||IC(i,n))throw new Error("Quarantine root must be physically outside and non-overlapping with every discovery root.")}function pg(e){let t=hg(e).normalize("NFC"),n=gg(t).root,r=t===n?t:t.replace(/[\\/]+$/u,"");return process.platform==="linux"?r:r.toLocaleLowerCase("en-US")}function IC(e,t){return e===t||e.startsWith(t.endsWith(au)?t:`${t}${au}`)}async function TC(e){try{let t=await Ai(e,{bigint:!0});if(t.isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link target: ${e}`);if(!t.isDirectory())throw new Error(`Atomic install target must be a directory: ${e}`);return{exists:!0,identity:{dev:t.dev,ino:t.ino}}}catch(t){if(ko(t))return{exists:!1,identity:null};throw t}}async function a2(e,t){let n=await TC(e);if(n.exists!==t.exists||t.identity!==null&&(n.identity===null||!fg(t.identity,n.identity)))throw new Error("Atomic install target changed while the approved generation was staged.")}async function Fn(e,t){let n=await Ai(e,{bigint:!0});if(n.isSymbolicLink())throw new Error(`${t} refuses a symbolic link: ${e}`);if(!n.isDirectory())throw new Error(`${t} must be a directory: ${e}`);return{dev:n.dev,ino:n.ino}}async function Pi(e,t,n){let r=await Fn(e,"Atomic install identity check");if(!fg(r,t))throw new Error(n)}function fg(e,t){return e.dev===t.dev&&e.ino===t.ino}async function ya(e){let t=await lX(hg(e));await uu(t);try{if((await Ai(t)).isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link: ${t}`);return await PC(t)}catch(i){if(!ko(i))throw i}let n=[],r=t;for(;;)try{await Ai(r);break}catch(i){if(!ko(i))throw i;let o=$r(r);if(o===r)throw new Error(`Unable to resolve atomic install target parent: ${t}`);n.unshift(Ci(r)),r=o}return xn(await PC(r),...n)}async function RC(e,t){let n=await ya(e);return await Fn(n,t),n}async function lX(e){let t=gg(e).root,n=e.slice(t.length).split(au).filter(Boolean);if(n.length===0)return e;let r=xn(t,n[0]),i;try{i=await Ai(r)}catch(o){if(ko(o))return e;throw o}return i.isSymbolicLink()?xn(await PC(r),...n.slice(1)):e}async function uu(e){let t=hg(e),n=gg(t).root,r=t.slice(n.length).split(au).filter(Boolean),i=n;for(let o of r){i=xn(i,o);try{if((await Ai(i)).isSymbolicLink())throw new Error(`Atomic install refuses a symbolic link: ${i}`)}catch(s){if(ko(s))return;throw s}}}async function Zt(e){let t;try{t=await mg(e,Ii.O_RDONLY|yg),await t.sync()}catch(n){if(!cX(n))throw n}finally{await t?.close()}}function cX(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return t==="EINVAL"||t==="ENOTSUP"||t==="EOPNOTSUPP"||process.platform==="win32"&&(t==="EPERM"||t==="EISDIR"||t==="EBADF")}async function uX(e){try{await Wj(e,{recursive:!0,force:!1})}catch(t){if(!ko(t))throw t}}async function vo(e,t){await e?.(t)}function dX(e){let t=[JY,Hj(e.length)];for(let n of e){if(typeof n.path!="string"||!Number.isSafeInteger(n.sizeBytes)||n.sizeBytes<0||!lu.test(n.sha256))throw new Error("Installed generation receipt manifest entry is invalid.");let r=new TextEncoder().encode(n.path);t.push(Hj(r.byteLength),r,pX(n.sizeBytes),EC(n.sha256))}return fX(t)}function Hj(e){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t}function pX(e){let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t}function fX(e){let t=new Uint8Array(e.reduce((r,i)=>r+i.byteLength,0)),n=0;for(let r of e)t.set(r,n),n+=r.byteLength;return t}function mX(e){let t=Object.freeze({...e.generation}),n=Object.freeze(e.files.map(r=>Object.freeze({...r})));return Object.freeze({...e,generation:t,files:n})}function l2(e){return`sha256:${VY("sha256").update(e).digest("hex")}`}function va(e,t){return typeof e=="string"&&lu.test(e)&&lu.test(t)&&GY(EC(e),EC(t))}function EC(e){return Buffer.from(e.slice(7),"hex")}function gX(e,t){return Buffer.compare(Buffer.from(e,"utf8"),Buffer.from(t,"utf8"))}function c2(e){return e instanceof Error?e.message:String(e)}function ko(e){return u2(e)==="ENOENT"}function hX(e){return u2(e)==="EEXIST"}function u2(e){return typeof e=="object"&&e!==null&&"code"in e?e.code:void 0}function d2(e){if(e.pathState==="absent"){if(e.receiptState==="verified")throw new Error("An absent target cannot have a verified receipt observation.");return du("externally_removed","exact_target_absent")}if(e.pathState==="unreadable"){if(e.receiptState==="verified")throw new Error("An unreadable target cannot have a verified receipt observation.");return du("unreadable","exact_target_unreadable")}if(e.pathState==="replaced_type"){if(e.receiptState==="verified")throw new Error("A replaced target cannot have a verified receipt observation.");return du("drifted","exact_target_replaced")}if(e.receiptState==="unchecked")throw new Error("A present exact target receipt must be checked before reconciliation.");return e.receiptState==="changed"?du("drifted","exact_tree_changed"):e.hostState==="detached"?du("host_detached","host_registration_detached"):Object.freeze({state:"active",reasonCode:"exact_target_verified",runnable:!0,recoverable:!0})}function du(e,t){return Object.freeze({state:e,reasonCode:t,runnable:!1,recoverable:!0})}import{createHash as yX}from"node:crypto";var vX="skills-layer-signatures-v1";var kX="security/signature-packs",yve=`${kX}/source/current.json`;var p2=bX(wX({version:vX,generatedAt:"2026-06-14T00:00:00.000Z",issuer:"skills-layer-local",signatures:[{id:"SL-SIG-COMMODITY-WEBHOOK-EXFIL",ruleId:"SL-SIG-002",title:"Commodity webhook exfiltration",severity:"critical",confidence:.92,tags:["exfiltration","webhook","secret-harvest"],regexes:[`https://(?:discord(?:app)?\\.com/api/webhooks|hooks\\.slack\\.com/services|webhook\\.site)/[^\\s"']+`],explanation:"Content references a commodity webhook endpoint often used for data exfiltration."},{id:"SL-SIG-REMOTE-BOOTSTRAP",ruleId:"SL-SIG-001",title:"Remote bootstrap execution",severity:"high",confidence:.88,tags:["remote-bootstrap","shell"],regexes:["(?:curl|wget)\\s+[^\\n|]+\\|\\s*(?:bash|sh|zsh|python|node)"],explanation:"Content downloads remote code and pipes it directly into an interpreter."},{id:"SL-SIG-DESTRUCTIVE-AUTONOMY",ruleId:"SL-SIG-004",title:"Destructive autonomous action",severity:"high",confidence:.84,tags:["destructive","autonomous"],regexes:["\\b(?:rm\\s+-rf|Remove-Item\\s+-Recurse|format\\s+[A-Z]:|git\\s+push\\s+--force)\\b"],explanation:"Content includes destructive commands that can cause irreversible changes."}]}));function wX(e){return{boundary:"skills_layer_signature_pack",version:e.version,generatedAt:e.generatedAt,issuer:e.issuer??"skills-layer-cloud",...e.managedAuthorityDigest?{managedAuthorityDigest:e.managedAuthorityDigest}:{},signatures:e.signatures.map(xX).sort((t,n)=>t.id.localeCompare(n.id))}}function bX(e){let t=`sha256:${pu(ka(e))}`;return{...e,digest:t,signature:pu(ka({boundary:e.boundary,digest:t,issuer:e.issuer,version:e.version}))}}function _X(e){let{digest:t,signature:n,...r}=e;return t===`sha256:${pu(ka(r))}`&&n===pu(ka({boundary:r.boundary,digest:t,issuer:r.issuer,version:r.version}))}function f2(e,t){if(!_X(t))return[];let n=[],r=new Set;for(let i of e){let o=i.content??"";for(let s of t.signatures){if(s.filePattern&&!new RegExp(s.filePattern,"iu").test(i.path))continue;let a=SX(o,s);if(!a)continue;let l=`${s.id}:${i.path}:${a.lineNumber}:${a.tag}`;r.has(l)||(r.add(l),n.push({signatureId:s.id,ruleId:s.ruleId,title:s.title,severity:s.severity,confidence:s.confidence,filePath:i.path,lineNumber:a.lineNumber,matchedTag:a.tag,evidenceHash:`sha256:${pu(`${i.path}
|
|
804
804
|
${a.line}`)}`,explanation:s.explanation}))}}return n}function SX(e,t){let n=e.split(/\r?\n/u);for(let r=0;r<n.length;r+=1){let i=n[r];for(let o of t.strings??[])if(i.toLowerCase().includes(o.toLowerCase()))return{line:i,lineNumber:r+1,tag:o};for(let o of t.regexes??[])if(new RegExp(o,"iu").test(i))return{line:i,lineNumber:r+1,tag:o}}return null}function xX(e){return{id:e.id.trim(),ruleId:e.ruleId.trim(),title:e.title.trim(),severity:e.severity,confidence:Math.max(0,Math.min(1,e.confidence)),tags:[...new Set(e.tags.map(t=>t.trim()).filter(Boolean))].sort(),...e.filePattern?{filePattern:e.filePattern}:{},...e.strings?{strings:e.strings.map(t=>t.trim()).filter(Boolean)}:{},...e.regexes?{regexes:e.regexes.map(t=>t.trim()).filter(Boolean)}:{},explanation:e.explanation.trim()}}function ka(e){return Array.isArray(e)?`[${e.map(ka).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${ka(n)}`).join(",")}}`:JSON.stringify(e)}function pu(e){return yX("sha256").update(e).digest("hex")}import{spawn as VX}from"node:child_process";import{createHash as b2}from"node:crypto";import{constants as _2}from"node:fs";import{chmod as jC,copyFile as S2,lstat as x2,mkdir as LC,mkdtemp as GX,open as C2,realpath as wg,rm as HX,stat as I2}from"node:fs/promises";import{tmpdir as KX}from"node:os";import{extname as P2,isAbsolute as WX,join as ba,resolve as y2}from"node:path";import{createHash as CX,randomBytes as wve}from"node:crypto";import{posix as IX,win32 as PX}from"node:path";var AX=new Set(["shell_execution","filesystem_read","filesystem_write","network_access","browser_access","device_control","api_access","generated_code_execution"]),RX=new Set(["darwin","linux","win32"]),EX=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/u,$X=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,DX=/^[0-9A-Za-z][0-9A-Za-z.+-]{0,127}$/u,OC=/^sha256:[a-f0-9]{64}$/u,TX=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u,OX=/^[^\u0000-\u001f\u007f]{1,4096}$/u;var LX=256,m2=64,jX=64,NX=64,FX=256*1024*1024;function BX(e){MX(e);let t=e.platform==="win32"?PX:IX,n={planVersion:1,actionFamily:e.actionFamily,platform:e.platform,executableRealPath:vg(e.executableRealPath,t),executableSha256:e.executableSha256,argv:Object.freeze([...e.argv]),cwdRealPath:vg(e.cwdRealPath,t),fileTargets:Object.freeze(e.fileTargets.map(r=>vg(r,t))),networkTargets:Object.freeze(e.networkTargets.map(zX)),environmentKeys:Object.freeze([...new Set(e.environmentKeys)].sort()),immutableInputs:Object.freeze([...e.immutableInputs??[]].map(r=>Object.freeze({path:vg(r.path,t),sha256:r.sha256,size:r.size,argumentIndexes:Object.freeze([...r.argumentIndexes].sort((i,o)=>i-o))})).sort((r,i)=>r.path.localeCompare(i.path))),skill:Object.freeze({slug:e.skillSlug,version:e.version,generationId:e.generationId}),subject:Object.freeze({actorId:e.actorId,...e.deviceId===void 0?{}:{deviceId:e.deviceId},tenantId:e.tenantId,...e.workspaceId===void 0?{}:{workspaceId:e.workspaceId}}),host:Object.freeze({agentId:e.agentId,hostVersion:e.hostVersion,sessionId:e.sessionId}),policy:Object.freeze({revision:e.policyRevision,digest:e.policyDigest})};return Object.freeze(n)}function h2(e){return UX(e),qX(fu(e))}function MX(e){(!RX.has(e.platform)||!AX.has(e.actionFamily)||!OC.test(e.executableSha256))&&Cn(),(!Array.isArray(e.argv)||e.argv.length>LX||e.argv.some(t=>!kg(t)))&&Cn(),(!Array.isArray(e.fileTargets)||e.fileTargets.length>m2||!Array.isArray(e.networkTargets)||e.networkTargets.length>m2||!Array.isArray(e.environmentKeys)||e.environmentKeys.length>jX||e.environmentKeys.some(t=>!TX.test(t)))&&Cn(),e.immutableInputs!==void 0&&(!Array.isArray(e.immutableInputs)||e.immutableInputs.length>NX||e.immutableInputs.some(t=>!t||typeof t!="object"||!OC.test(t.sha256)||!Number.isSafeInteger(t.size)||t.size<=0||t.size>FX||!Array.isArray(t.argumentIndexes)||t.argumentIndexes.length===0||t.argumentIndexes.some(n=>!Number.isSafeInteger(n)||n<0||n>=e.argv.length)))&&Cn(),(!$X.test(e.skillSlug)||!DX.test(e.version)||!wa(e.generationId)||!wa(e.actorId)||!g2(e.deviceId)||!wa(e.tenantId)||!g2(e.workspaceId)||!wa(e.agentId)||!kg(e.hostVersion)||!wa(e.sessionId)||!Number.isSafeInteger(e.policyRevision)||e.policyRevision<=0||!OC.test(e.policyDigest))&&Cn()}function UX(e){(typeof e!="object"||e===null||e.planVersion!==1)&&Cn();let t=BX({platform:e.platform,actionFamily:e.actionFamily,executableRealPath:e.executableRealPath,executableSha256:e.executableSha256,argv:[...e.argv],cwdRealPath:e.cwdRealPath,fileTargets:[...e.fileTargets],networkTargets:[...e.networkTargets],environmentKeys:[...e.environmentKeys],immutableInputs:e.immutableInputs.map(n=>({...n,argumentIndexes:[...n.argumentIndexes]})),skillSlug:e.skill.slug,version:e.skill.version,generationId:e.skill.generationId,actorId:e.subject.actorId,...e.subject.deviceId===void 0?{}:{deviceId:e.subject.deviceId},tenantId:e.subject.tenantId,...e.subject.workspaceId===void 0?{}:{workspaceId:e.subject.workspaceId},agentId:e.host.agentId,hostVersion:e.host.hostVersion,sessionId:e.host.sessionId,policyRevision:e.policy.revision,policyDigest:e.policy.digest});fu(t)!==fu(e)&&Cn()}function vg(e,t){(!kg(e)||!t.isAbsolute(e))&&Cn();let n=t.normalize(e);return n!==e&&Cn(),n}function zX(e){kg(e)||Cn();let t;try{t=new URL(e)}catch{Cn()}return(t.protocol!=="https:"||t.username||t.password||t.hash||t.port&&t.port!=="443")&&Cn(),t.toString()}function Cn(){throw new Error("Guardian execution plan input is invalid or unresolved.")}function kg(e){return typeof e=="string"&&OX.test(e)}function wa(e){return typeof e=="string"&&EX.test(e)}function g2(e){return e===void 0||wa(e)}function fu(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(fu).join(",")}]`:`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[r])=>n<r?-1:1).map(([n,r])=>`${JSON.stringify(n)}:${fu(r)}`).join(",")}}`}function qX(e){return`sha256:${CX("sha256").update(e,"utf8").digest("hex")}`}var ZX=3e4,JX=50,YX=3e5,XX=64*1024,QX=256,eQ=1024*1024,tQ=256*1024*1024,A2=64*1024,nQ=250,rQ="/usr/local/bin:/usr/bin:/bin",R2=new Set(["LANG","LC_ALL","LC_CTYPE","TZ","TERM","COLORTERM","NO_COLOR"]),iQ=new Set(["HOME","TMPDIR","TMP","TEMP","USERPROFILE","PATH","SystemRoot"]),oQ=new Set(["darwin","linux","win32"]),sQ=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u,$e=class extends Error{constructor(n){super(`Guardian process refused execution: ${n}.`);this.reasonCode=n;this.name="GuardianProcessError"}reasonCode};async function E2(e,t={}){let n=w2(e.timeoutMs??ZX,JX,YX,"timeout"),r=w2(e.outputLimitBytes??XX,QX,eQ,"output limit"),i=yQ(process.platform);if(e.plan.platform!==i)throw new $e("platform_mismatch");let o=h2(e.plan),s=await dQ(e.plan);await fQ(e.plan.cwdRealPath);let a=mQ(e.approvedSecrets??{},e.plan.environmentKeys),l=e.temporaryParent??KX(),c=await GX(ba(l,"skills-layer-guardian-"));await jC(c,448);let u=ba(c,"home"),d=ba(c,"tmp");await Promise.all([LC(u,{mode:448}),LC(d,{mode:448})]);try{let p=await pQ(s,e.plan.executableSha256,c),m=await aQ(e.plan,c),h=gQ({platform:i,plannedKeys:e.plan.environmentKeys,ambient:e.ambientEnvironment??process.env,approvedSecrets:a,isolatedHome:u,isolatedTemp:d});return e.signal?.aborted?$2("aborted",o):(uQ(i,e.treeTerminator),await hQ({executable:p,argv:m,cwd:e.plan.cwdRealPath,environment:h,approvedSecrets:Object.values(a),timeoutMs:n,outputLimitBytes:r,signal:e.signal,platform:i,planHash:o,treeTerminator:e.treeTerminator,spawnProcess:t.spawn??VX}))}finally{await HX(c,{recursive:!0,force:!0})}}async function aQ(e,t){let n=[...e.argv];if(e.immutableInputs.length===0)return n;let r=ba(t,"inputs");await LC(r,{mode:448});for(let[i,o]of e.immutableInputs.entries()){let s=await wg(o.path).catch(()=>"");if(s!==o.path)throw new $e("immutable_input_changed");let a=await x2(s);if(!a.isFile()||a.size!==o.size)throw new $e("immutable_input_changed");let l=ba(r,`${i}${P2(o.path)}`);await S2(s,l,_2.COPYFILE_EXCL),await jC(l,256);let c=await lQ(l),u=`sha256:${b2("sha256").update(c).digest("hex")}`;if(c.byteLength!==o.size||u!==o.sha256)throw new $e("immutable_input_changed");for(let d of o.argumentIndexes)n[d]=await cQ(n[d],o.path,e.cwdRealPath,l)}return n}async function lQ(e){let t=await C2(e,"r");try{let n=await t.readFile();return await t.sync(),n}finally{await t.close()}}async function cQ(e,t,n,r){let i=e.indexOf("="),o=i>0?e.slice(0,i+1):"",s=i>0?e.slice(i+1):e,a=WX(s)?y2(s):y2(n,s);if(await wg(a).catch(()=>"")!==t)throw new $e("immutable_input_argument_mismatch");return`${o}${r}`}function v2(e,t=[]){let n=e;for(let r of[...new Set(t)].sort((i,o)=>o.length-i.length))r.length>0&&(n=n.split(r).join("[SECRET_REDACTED]"));return n.replace(/-----BEGIN [^-\r\n]{1,64} PRIVATE KEY-----[\s\S]*?-----END [^-\r\n]{1,64} PRIVATE KEY-----/gu,"[PRIVATE_KEY_REDACTED]").replace(/\b(?:mktplace_|slg_exec_|github_pat_|gh[opusr]_|sk-)[A-Za-z0-9_-]{8,}\b/gu,"[TOKEN_REDACTED]").replace(/\bAuthorization\s*:\s*(?:Bearer|Basic)\s+[^\s,;]+/giu,"Authorization: [REDACTED]").replace(/\b(password|passwd|secret|token|api[_-]?key)\s*[=:]\s*[^\s,;]+/giu,"$1=[REDACTED]").replace(/[^\t\n\r\u0020-\u007e\u00a0-\uffff]/gu,"\uFFFD")}function uQ(e,t){if(e==="win32"&&!t)throw new $e("windows_process_tree_isolation_unavailable")}async function dQ(e){let t=await wg(e.executableRealPath).catch(()=>"");if(t!==e.executableRealPath)throw new $e("executable_path_changed");let[n,r]=await Promise.all([x2(t),I2(t)]);if(!n.isFile())throw new $e("executable_not_regular_file");if(r.size<=0||r.size>tQ)throw new $e("executable_size_invalid");if(e.platform!=="win32"&&(r.mode&73)===0)throw new $e("executable_not_executable");return t}async function pQ(e,t,n){let r=ba(n,`executable${P2(e)}`);await S2(e,r,_2.COPYFILE_EXCL),await jC(r,320);let i=await C2(r,"r");try{let o=await i.readFile();if(await i.sync(),`sha256:${b2("sha256").update(o).digest("hex")}`!==t)throw new $e("executable_digest_changed")}finally{await i.close()}return r}async function fQ(e){let t=await wg(e).catch(()=>"");if(t!==e)throw new $e("working_directory_changed");if(!(await I2(t)).isDirectory())throw new $e("working_directory_not_directory")}function mQ(e,t){let n=new Set(t),r={};for(let[i,o]of Object.entries(e)){if(!sQ.test(i)||!n.has(i)||iQ.has(i)||R2.has(i))throw new $e("secret_not_exactly_approved");if(typeof o!="string"||o.length===0||o.includes("\0")||Buffer.byteLength(o,"utf8")>A2)throw new $e("secret_value_invalid");r[i]=o}return r}function gQ(e){let t=e.platform==="win32"?{PATH:"C:\\Windows\\System32",SystemRoot:"C:\\Windows",USERPROFILE:e.isolatedHome,TEMP:e.isolatedTemp,TMP:e.isolatedTemp}:{PATH:rQ,HOME:e.isolatedHome,TMPDIR:e.isolatedTemp},n=new Set(Object.keys(t));for(let r of e.plannedKeys){if(n.has(r))continue;if(Object.hasOwn(e.approvedSecrets,r)){t[r]=e.approvedSecrets[r],n.add(r);continue}if(!R2.has(r))throw new $e("unapproved_environment_key");let i=e.ambient[r];if(typeof i!="string"||i.includes("\0")||Buffer.byteLength(i,"utf8")>A2)throw new $e("ambient_environment_value_invalid");t[r]=i,n.add(r)}if(n.size!==e.plannedKeys.length)throw new $e("environment_plan_mismatch");return t}async function hQ(e){let t;try{t=e.spawnProcess(e.executable,e.argv,{cwd:e.cwd,env:e.environment,shell:!1,windowsHide:!0,detached:e.platform!=="win32",stdio:["ignore","pipe","pipe"]})}catch{return $2("spawn_failed",e.planHash)}return await new Promise(n=>{let r=[],i=[],o=0,s="exited",a=!1,l=!1,c,u=g=>{s==="exited"&&(s=g,k2(t,!1,e.treeTerminator),c=setTimeout(()=>k2(t,!0,e.treeTerminator),nQ),c.unref?.())},d=(g,y)=>{if(a)return;let v=y,b=e.outputLimitBytes-o;if(v.byteLength<=b){g.push(v),o+=v.byteLength;return}g.push(v.subarray(0,Math.max(b,0))),o=e.outputLimitBytes,a=!0,u("output_limit")},p=(g,y)=>{if(l)return;l=!0,clearTimeout(h),c&&clearTimeout(c),e.signal?.removeEventListener("abort",m);let v=a?`
|
|
805
805
|
[output truncated; process terminated]`:"";n({reason:s,exitCode:g,signal:y,stdout:v2(Buffer.concat(r).toString("utf8")+v,e.approvedSecrets),stderr:v2(Buffer.concat(i).toString("utf8"),e.approvedSecrets),outputTruncated:a,planHash:e.planHash})},m=()=>u("aborted"),h=setTimeout(()=>u("timed_out"),e.timeoutMs);h.unref?.(),e.signal?.addEventListener("abort",m,{once:!0}),t.stdout.on("data",g=>d(r,g)),t.stderr.on("data",g=>d(i,g)),t.once("error",()=>{s="spawn_failed",p(null,null)}),t.once("close",p)})}function k2(e,t,n){if(n){n.terminate(e,t);return}let r=t?"SIGKILL":"SIGTERM";try{if(typeof e.pid!="number"){e.kill(r);return}process.kill(-e.pid,r)}catch{e.kill(r)}}function yQ(e){if(!oQ.has(e))throw new $e("unsupported_platform");return e}function w2(e,t,n,r){if(!Number.isSafeInteger(e)||e<t||e>n)throw new $e(`${r.replaceAll(" ","_")}_invalid`);return e}function $2(e,t){return{reason:e,exitCode:null,signal:null,stdout:"",stderr:"",outputTruncated:!1,planHash:t}}import{execFile as vQ}from"node:child_process";import{createHash as kQ}from"node:crypto";import{promisify as wQ}from"node:util";var NC=wQ(vQ),mu="apiKey",_a="apiKeyRef",Le="Skills Layer CLI";function FC(e=process.platform,t=process.env){let n=t.SKILLS_LAYER_CREDENTIAL_STORE?.trim().toLowerCase();return n==="local-file"||n==="local_file"||n==="disabled"||e!=="darwin"||process.env.VITEST==="true"&&n!=="macos-keychain"&&n!=="macos_keychain"?null:SQ()}async function D2(e,t){if(!(typeof e[mu]=="string"&&e[mu].length>0))return e;let r=BC(t);if(!r)return e;try{let i={...e,credentialStorage:"macos_keychain"},o=bQ(e);return await r.set(MC(t),o,e[mu]),i[_a]=o,delete i[mu],i}catch{return _Q(e)}}async function T2(e,t){if(e.credentialStorage!=="macos_keychain"||e[mu]||!e[_a])return e;let n=BC(t);if(!n)return e;let r=await n.get(MC(t),e[_a]);return r?{...e,apiKey:r}:e}async function O2(e,t){if(!e||e.credentialStorage!=="macos_keychain"||!e[_a])return;let n=BC(t);if(!n)throw new Error("OS credential storage is unavailable; retry logout on this profile\u2019s original machine.");await n.delete(MC(t),e[_a])}function bQ(e){let t=[e.baseUrl??"unknown-base-url",e.userId??e.email??e.role??"unknown-user","apiKey"].join(`
|
|
806
806
|
`);return`skills-layer-cli:api-key:${kQ("sha256").update(t).digest("base64url").slice(0,32)}`}function BC(e){return e.store!==void 0?e.store:FC(e.platform,e.env??process.env)}function MC(e){return e.service??Le}function _Q(e){let t={...e,credentialStorage:"local_file_locked"};return delete t[_a],t}function SQ(){return{kind:"macos_keychain",async set(e,t,n){await NC("/usr/bin/security",["add-generic-password","-a",t,"-s",e,"-w",n,"-U"])},async get(e,t){try{let{stdout:n}=await NC("/usr/bin/security",["find-generic-password","-a",t,"-s",e,"-w"]);return n.trim()||null}catch{return null}},async delete(e,t){try{await NC("/usr/bin/security",["delete-generic-password","-a",t,"-s",e])}catch{}}}}var L2=Object.freeze(["mcp:use","catalog:read","identity:read","identity:write","library:read","library:write","creator:read","creator:submit","eval:write","source:read","source:write","billing:read","workspace:read","workspace:write","workspace:approve","guardian:check","guardian:incident"]);function bg(e){try{return rR(new URL(e).origin)}catch{return!1}}var Sa=class extends Error{constructor(){super("Skills Layer Cloud MCP requires supported OS-secure credential storage; the bearer was not saved to a local file."),this.name="SecureMcpCredentialStorageError"}};var zC=8,UC=8,xQ=/^key_[A-Za-z0-9_-]{1,128}$/u,CQ=/^user_[A-Za-z0-9_-]{1,128}$/u,IQ=new Set([...tR.map(e=>new URL(e).hostname),"api.skills-layer.local"]);function _g(e){let t=PQ(e.baseUrl);if(!t||!CQ.test(e.userId)||!AQ(e.createdAt))throw new Error("Pending revocation identifiers are invalid.");let n=j2(e.humanKeyIds),r=j2(e.mcpKeyIds);if(e.humanKeyIds.length!==new Set(e.humanKeyIds).size||e.mcpKeyIds.length!==new Set(e.mcpKeyIds).size)throw new Error("Pending revocation credential identifiers are invalid.");if(n.length===0&&r.length===0&&!e.revokeAllMcp&&!e.revokeAdminMcp)throw new Error("Pending revocation has no server-side work.");return{version:1,baseUrl:t,userId:e.userId,humanKeyIds:n,mcpKeyIds:r,revokeAllMcp:e.revokeAllMcp,revokeAdminMcp:e.revokeAdminMcp,createdAt:e.createdAt}}function N2(e,t){let n=e.find(i=>i.baseUrl===t.baseUrl&&i.userId===t.userId),r=n?_g({baseUrl:t.baseUrl,userId:t.userId,humanKeyIds:[...new Set([...n.humanKeyIds,...t.humanKeyIds])].slice(0,UC),mcpKeyIds:[...new Set([...n.mcpKeyIds,...t.mcpKeyIds])].slice(0,UC),revokeAllMcp:n.revokeAllMcp||t.revokeAllMcp,revokeAdminMcp:n.revokeAdminMcp||t.revokeAdminMcp,createdAt:n.createdAt<t.createdAt?n.createdAt:t.createdAt}):t;return[...e.filter(i=>i.baseUrl!==t.baseUrl||i.userId!==t.userId),r].slice(-zC)}function F2(e){return{includeCurrent:!1,revokeAllMcp:e.revokeAllMcp,humanKeyIds:[...e.humanKeyIds],mcpKeyIds:[...e.mcpKeyIds]}}function qC(e){if(!B2(e)||e.version!==1||!Array.isArray(e.entries)||e.entries.length>zC)return[];let t=[];for(let n of e.entries){if(!RQ(n))return[];try{t.push(_g({baseUrl:n.baseUrl,userId:n.userId,humanKeyIds:n.humanKeyIds,mcpKeyIds:n.mcpKeyIds,revokeAllMcp:n.revokeAllMcp,revokeAdminMcp:n.revokeAdminMcp,createdAt:n.createdAt}))}catch{return[]}}return t}function VC(e){return{version:1,entries:e.slice(-zC)}}function PQ(e){try{let t=new URL(e),n=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="::1";return(t.protocol!=="https:"||!IQ.has(t.hostname))&&!(t.protocol==="http:"&&n)||t.username||t.password||t.search||t.hash||t.pathname!=="/"&&t.pathname!==""?null:t.origin}catch{return null}}function j2(e){if(!Array.isArray(e)||e.length>UC||e.some(t=>!xQ.test(t)))throw new Error("Pending revocation credential identifiers are invalid.");return[...new Set(e)]}function AQ(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))&&new Date(e).toISOString()===e}function B2(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function RQ(e){return!B2(e)||Object.keys(e).sort().join("|")!=="baseUrl|createdAt|humanKeyIds|mcpKeyIds|revokeAdminMcp|revokeAllMcp|userId|version"?!1:e.version===1&&typeof e.baseUrl=="string"&&typeof e.userId=="string"&&Array.isArray(e.humanKeyIds)&&e.humanKeyIds.every(n=>typeof n=="string")&&Array.isArray(e.mcpKeyIds)&&e.mcpKeyIds.every(n=>typeof n=="string")&&typeof e.revokeAllMcp=="boolean"&&typeof e.revokeAdminMcp=="boolean"&&typeof e.createdAt=="string"}function GC(e){let t=e.skillSlug??"<skill-slug>";return{localWork:{purpose:e.purpose,command:e.command,jsonCommand:e.jsonCommand},guardian:{checkCommand:`skills-layer guardian check --skill ${t} --json`,execCommand:`skills-layer guardian exec ${t} --json -- <command>`,mcpTools:["guardian.check","guardian.enforce","guardian.status","guardian.incident"],guidance:"Before risky shell, network, file, secret, browser, API, generated-code, or model-context actions, call MCP guardian.check/guardian.enforce or run skills-layer guardian check. Route shell actions through skills-layer guardian exec when strict local blocking is needed."},setup:{setupCommand:"skills-layer setup",hookStatusCommand:"skills-layer guardian hook status",hookInstallProjectCommand:"skills-layer guardian hook install --agent codex --scope project",hookInstallGlobalCommand:"skills-layer guardian hook install --agent codex --scope global"}}}var EQ=/\u001B\[[0-?]*[ -/]*[@-~]/gu,$Q=/\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)/gu,DQ=/\u001B[@-_]/gu,TQ=/\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)|\u001B\[[0-?]*[ -/]*[@-~]|\u001B[@-_]/gu,OQ=/[\u0000-\u0008\u000B\u000C\u000E-\u001A\u001C-\u001F\u007F-\u009F\u202A-\u202E\u2066-\u2069]/gu,LQ=/[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9-]+)+/giu,jQ=new Set([0,1,2,22,30,31,32,33,34,35,36,37,39,90,91,92,93,94,95,96,97]);function sr(e){return e.replace($Q,"").replace(EQ,"").replace(DQ,"").replace(OQ,"")}function H(e){return sr(e).replace(/\r\n?/gu,`
|
|
@@ -1020,7 +1020,7 @@ Primary commands:
|
|
|
1020
1020
|
skills-layer creator submit-version <skill-slug> [<path-or-source> | --creator-session-id <session-id>] [--source <source>] [--list] [--version <semver>] [--category <category>] [--price-cents <n>] [--confirm-free] [--yes] [--distribution-scope <public_distribution|commercial_distribution>] [--attest-rights [--rights-basis <self_authored|authorized_by_rightsholder>]] [--visibility <private|public|unlisted>] [--replace-unpublished] [--dry-run] [--json]
|
|
1021
1021
|
skills-layer creator check-slug <requested-slug> [--json]
|
|
1022
1022
|
skills-layer creator rename <skill-slug> <next-skill-slug> [--json]
|
|
1023
|
-
skills-layer creator pricing <skill-slug> [--version <semver>] [--price-cents <n>] [--confirm-free] [--attest-rights [--rights-basis <self_authored|authorized_by_rightsholder>]] [--confirm|--yes] [--idempotency-key <key>] [--json]
|
|
1023
|
+
skills-layer creator pricing <skill-slug> [--version <semver>] [--price-cents <n>] [--confirm-free] [--attest-rights [--rights-basis <self_authored|authorized_by_rightsholder>]] [--confirm|--yes] [--idempotency-key <key>] [--dry-run] [--json]
|
|
1024
1024
|
skills-layer creator update-listing <skill-slug> [--display-name <text>] [--skill-type <type>] [--listing-status <status>] [--json]
|
|
1025
1025
|
skills-layer creator visibility <skill-slug> [--version <semver>] --visibility <private|public|unlisted> [--dry-run] [--json]
|
|
1026
1026
|
skills-layer creator security-report <skill-slug> [--version <semver>] [--version-id <id>] [--format <json|sarif>] [--json]
|
|
@@ -2017,7 +2017,7 @@ Next:
|
|
|
2017
2017
|
`).trimStart().split(/\n\s*\n/u)[0].split(/\r?\n/u).map(o=>o.trim()).filter(Boolean)}function cee(e){return[...new Set([...e.matchAll(/--[a-z0-9][a-z0-9-]*/giu)].map(t=>t[0]).sort())]}var uee=Object.freeze(["--ascii","--api-key","--base-url","--color","--detail","--help","--json","--motion","--no-color","--no-interactive","--no-motion","--output-format","--screen-reader","--ui"]),dee=Object.freeze({"auth mfa recovery-codes":Object.freeze(["--code","--mfa-code"])}),pee=Object.freeze(Dg.map(e=>{let t=e.split(" "),n=_o(t[0],t.slice(1));if(!n)throw new Error(`Public command manifest could not resolve focused help for ${e}.`);let r=yee(e,n.usage),o=!Dg.some(s=>s!==e&&s.startsWith(`${e} `))&&r.length>0?"command":"help_topic";return Object.freeze({path:e,kind:o,pathSegments:Object.freeze(t),aliases:Object.freeze(gee(e)),usage:r.join(`
|
|
2018
2018
|
`)||n.usage,positionals:Object.freeze(hee(r.join(`
|
|
2019
2019
|
`)||n.usage)),options:Object.freeze([...new Set([...o==="command"?vee(r.join(`
|
|
2020
|
-
`)):n.options,...dee[e]??[],"--json"])]),inheritedOptions:uee,outputModes:Object.freeze(["human","json","stream-json"]),mutability:kee(n.sideEffects),humanInLoop:wee(n),fixturePrerequisites:Object.freeze([...n.requiresLogin?["authenticated_account"]:[],...n.requiresNetwork?["reachable_backend"]:[]]),examples:Object.freeze(n.examples),availability:"public"})})),fee=new Map(pee.map(e=>[e.path,e]));function uN(e){let t=e.map(n=>n.trim().toLowerCase()).filter(Boolean);for(let n=t.length;n>=1;n-=1){let r=fee.get(t.slice(0,n).join(" "));if(r)return r}return null}function mee(e,t){let n=new Set([...e.options,...e.inheritedOptions]),r=t.indexOf("--"),i=r===-1?t:t.slice(0,r);for(let o of i){if(!o.startsWith("--"))continue;let s=o.split("=",1)[0];if(!n.has(s))return s.slice(2)}return null}var dN=mee;function gee(e){return e==="find"?["search"]:e==="workspaces"?["workspace"]:[]}function hee(e){return[...new Set([...e.matchAll(/<([^>]+)>/gu)].map(t=>t[1]))]}function yee(e,t){let n=`skills-layer ${e}`;return t.split(/\r?\n/u).map(r=>r.trim()).filter(r=>r===n||r.startsWith(`${n} `))}function vee(e){return[...new Set([...e.matchAll(/--[a-z][a-z0-9-]*/gu)].map(t=>t[0]))]}function kee(e){let t=e.some(r=>r.includes("local")||r.includes("credential")),n=e.some(r=>r.includes("cloud_write")||r.includes("payment"));return t&&n?"mixed":n?"cloud_write":t?"local_write":"read_only"}function wee(e){return e.sideEffects.includes("payment_mutation")?"financial":e.mayOpenBrowser?"browser":e.mayPrompt?"prompt":"none"}import{posix as bee,win32 as _ee}from"node:path";function pN(e,t){let n=t==="win32"?_ee:bee;if(t==="win32"){let o=rI(e.APPDATA,e.USERPROFILE,e.HOME);if(!o)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(o,"skills-layer")}let r=rI(e.XDG_CONFIG_HOME);if(r)return n.join(r,"skills-layer");let i=rI(e.HOME);if(!i)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(i,".skills-layer")}function rI(...e){return e.map(t=>t?.trim()).find(t=>!!t)}var See=/^[\u00a0\u2007\u202f\ufeff]+|[\u00a0\u2007\u202f\ufeff]+$/gu,xee=/^\[(https?:\/\/[^\]\r\n]+)\]\((https?:\/\/[^)\r\n]+)\)$/u;function fN(e){let t=e.indexOf("--");return e.map((n,r)=>{if(t!==-1&&r>t)return n;let i=n.replace(See,""),o=xee.exec(i);return o&&o[1]===o[2]?o[1]:i})}var mN={enterprise_member_already_active:E("conflict","conflict",!1,!1,"This person is already an active Enterprise member.",[4]),local_cleanup_incomplete:E("human_action_required","error",!0,!0,"Unlock the OS credential store and retry logout to finish local cleanup.",[4,5]),admin_step_up_invalid:E("security_verification_failed","error",!1,!0,"Verify your administrator step-up key in the private operator checkout.",[4]),verification_code_locked:E("rate_limited","rate_limited",!0,!0,"This code is locked. Request a new code after the retry time.",[4]),conflicting_flags:E("invalid_input","error",!1,!0,"Choose a value or its clear flag, not both.",[4]),flag_value_missing:E("invalid_input","error",!1,!0,"Supply a value for the flag.",[4]),rights_attestation_required:E("precondition_required","error",!1,!0,"Public and unlisted releases require confirmation of distribution rights.",[4]),rights_attestation_invalid:E("invalid_input","error",!1,!0,"Supply a supported rights basis and public distribution scope.",[4]),catalogue_artifact_unavailable:E("backend_unreachable","error",!0,!0,"The catalogue artifact could not be downloaded; retry export.",[4]),admin_mfa_required:E("human_action_required","human_action_required",!1,!0,"Enable MFA with skills-layer auth mfa setup, then retry.",[4]),admin_mfa_unavailable:E("backend_unreachable","unavailable",!0,!0,"Administrator MFA is unavailable; contact the deployment operator.",[5]),source_read_unavailable:E("backend_unreachable","source_unavailable",!1,!0,"The source could not be read completely. Its package has not been assessed.",[5]),command_failed:E("internal_error","error",!1,!1,"The command could not be completed.",[5]),resource_not_found:E("not_found","not_found",!1,!0,"The requested resource was not found.",[4]),permission_denied:E("permission_denied","error",!1,!1,"This credential cannot perform the requested operation.",[4]),login_required:E("login_required","login_required",!1,!0,"Sign in is required.",[4]),unauthorized:E("login_required","login_required",!1,!0,"Sign in is required.",[4]),api_key_invalid_or_expired:E("login_required","login_required",!1,!0,"The saved API key is no longer valid. Sign in again to use account features.",[4]),confirmation_required:E("confirmation_required","human_action_required",!1,!0,"Human confirmation is required.",[4]),mfa_setup_required:E("human_action_required","human_action_required",!1,!0,"MFA setup is required.",[4]),login_mfa_required:E("human_action_required","human_action_required",!1,!0,"A second authentication factor is required.",[4]),login_mfa_input_invalid:E("invalid_input","error",!1,!0,"Provide exactly one supported MFA proof.",[4]),login_mfa_invalid:E("security_verification_failed","error",!1,!0,"The MFA proof was invalid or already used.",[4]),login_security_unavailable:E("security_verification_failed","security_unavailable",!0,!0,"Login security is unavailable.",[5]),mfa_challenge_locked:E("rate_limited","rate_limited",!0,!0,"The MFA challenge is temporarily locked.",[4]),social_secure_continuation_unavailable:E("security_verification_failed","security_unavailable",!1,!0,"Secure social continuation is unavailable.",[4,5]),social_continuation_terminal:E("security_verification_failed","error",!1,!0,"The social continuation ended without authorization.",[4]),verification_code_expired:E("human_action_required","error",!1,!0,"The verification code expired.",[4]),payout_human_confirmation_required:E("human_action_required","human_action_required",!1,!0,"Human payout confirmation is required.",[4]),security_report_requires_action:E("policy_blocked","blocked",!1,!0,"The security report requires action.",[4]),trust_report_not_actionable:E("policy_blocked","blocked",!1,!0,"The trust report does not permit this transition.",[4]),trust_report_authority_mismatch:E("security_verification_failed","blocked",!1,!0,"Trust evidence does not match the exact artifact generation.",[4,5]),trust_report_required_evidence_unavailable:E("verification_pending","action_required",!0,!0,"Required trust evidence is unavailable or incomplete.",[2,4,5]),sarif_source_mapping_required:E("precondition_required","error",!1,!0,"Repository SARIF requires verified repository-relative source locations.",[4]),sarif_security_evidence_required:E("precondition_required","error",!1,!0,"Runtime-audit SARIF requires typed security evidence.",[4]),sarif_rule_mapping_required:E("precondition_required","error",!1,!0,"Runtime-audit SARIF requires an explicit reviewed rule mapping for every actionable event.",[4]),sarif_profile_unsupported:E("invalid_input","error",!1,!0,"The requested SARIF profile is not available for this report audience.",[4]),cloud_trust_ledger_mismatch:E("security_verification_failed","blocked",!1,!0,"This exact public skill generation is temporarily unavailable because its Cloud Trust Ledger attestation does not match. A Skills Layer operator must re-attest the exact generation before install.",[4]),api_key_active_limit_reached:E("quota_exceeded","conflict",!1,!0,"The active API-key limit has been reached.",[4]),rate_limited:E("rate_limited","rate_limited",!0,!0,"The request rate limit was reached.",[4]),source_connection_already_canceled:E("unchanged","unchanged",!1,!1,"The source connection was already canceled.",[2,4]),source_connection_completed:E("conflict","conflict",!1,!1,"A completed source connection cannot be canceled.",[4]),source_connection_revoked:E("unchanged","unchanged",!1,!1,"The authorized source connection was revoked.",[0]),source_connection_already_revoked:E("unchanged","unchanged",!1,!1,"The source connection was already revoked.",[0]),source_connection_not_authorized:E("conflict","conflict",!1,!1,"Only an authorized source connection can be revoked.",[4]),reupload_required:E("precondition_required","reupload_required",!1,!0,"The stored artifact is unavailable; upload the bundle again.",[4]),artifact_finalization_failed:E("processing_action_required","partial_success",!0,!1,"The version exists but artifact finalisation is incomplete.",[0]),publication_moderation_failed:E("processing_action_required","partial_success",!1,!1,"The version exists but its moderation transition needs operator inspection.",[0]),source_connection_completion_unverified:E("verification_pending","verification_warning",!0,!0,"Source connection completion could not be verified.",[4,5]),admin_mcp_verification_warning:E("verification_pending","verification_warning",!0,!0,"Administrator MCP verification is pending.",[2,4,5]),admin_mcp_verification_rejected:E("security_verification_failed","rejected",!1,!0,"Administrator MCP verification was rejected.",[4]),authoritative_security_report_pending:E("processing_action_required","already_processing",!0,!0,"The authoritative security report is still processing.",[4]),publication_continuation_scheduled:E("processing_action_required","already_processing",!0,!1,"Publication is continuing through the durable exact-generation workflow.",[2,4]),binary_inspection_pending:E("processing_action_required","already_processing",!0,!0,"Binary asset security inspection is still processing.",[2,4]),binary_inspection_unavailable:E("verification_pending","hold",!0,!0,"Required binary asset security inspection is currently unavailable.",[2,4,5]),binary_asset_blocked:E("policy_blocked","blocked",!1,!0,"A binary asset did not satisfy the platform security policy.",[2,4]),binary_profile_suspended:E("policy_blocked","hold",!0,!0,"The required binary format profile is temporarily suspended.",[2,4]),security_adjudication_pending:E("processing_action_required","already_processing",!0,!0,"Contextual security evidence is still being evaluated.",[2,4]),content_adjudication_insufficient_evidence:E("verification_pending","hold",!0,!0,"The available evidence is insufficient to resolve the security finding.",[2,4]),content_adjudication_confirmed_risk:E("policy_blocked","blocked",!1,!0,"The exact content contains a confirmed security risk.",[2,4]),content_adjudication_source_remediation_required:E("policy_blocked","blocked",!1,!0,"The source must be changed before security review can continue.",[2,4]),content_adjudication_execution_failed:E("verification_pending","hold",!0,!0,"Content security adjudication could not complete and remains held.",[2,4,5]),content_probe_runner_unavailable:E("verification_pending","hold",!0,!0,"The isolated content security evaluator is currently unavailable.",[2,4,5]),binary_inspection_authority_invalid:E("security_verification_failed","hold",!0,!0,"Binary security evidence could not be authenticated.",[2,4,5]),managed_security_pack_stale:E("security_verification_failed","hold",!0,!0,"A required managed security definition pack is not current.",[2,4,5]),workflow_dependency_incomplete:E("precondition_required","waiting_for_dependency",!0,!0,"A required upstream workflow is incomplete.",[4]),creator_processing_sla_breached:E("processing_action_required","action_required",!1,!0,"Creator processing exceeded its platform SLA.",[4,5]),invalid_global_option:E("invalid_input","error",!1,!0,"A global CLI option is invalid.",[4]),invalid_numeric_input:E("invalid_input","error",!1,!0,"A numeric option is invalid.",[4]),unknown_flag:E("invalid_input","error",!1,!0,"The option is not supported.",[4]),unknown_command:E("invalid_input","error",!1,!0,"The command is not supported.",[4]),unknown_subcommand:E("invalid_input","error",!1,!0,"The command is not supported.",[4]),missing_required_argument:E("invalid_input","error",!1,!0,"Required information is missing.",[4]),invalid_json:E("invalid_input","error",!1,!0,"The JSON value is invalid.",[4]),canonical_bundle_rejected:E("invalid_input","error",!1,!0,"The bundle failed canonical validation.",[4]),recovery_code_invalid_or_expired:E("human_action_required","error",!1,!0,"The recovery code is invalid or expired.",[4]),social_provider_not_configured:E("precondition_required","error",!1,!0,"The selected social provider is not configured.",[4,5]),search_selection_not_found:E("not_found","not_found",!1,!0,"The selected skill is not present in these search results.",[4]),best_effort:E("unchanged","low_confidence",!1,!0,"Best-effort candidates need a more specific task for higher confidence.",[2]),unsafe_task:E("policy_blocked","policy_blocked",!1,!0,"This task is outside the recommendation safety policy.",[2]),no_confident_recommendation:E("unchanged","no_confident_recommendation",!1,!0,"No skill met the calibrated recommendation confidence policy.",[2]),clarification_required:E("human_action_required","clarification_required",!1,!0,"One public task constraint is required before a skill can be recommended.",[2]),workspace_required:E("precondition_required","error",!1,!0,"A workspace id is required for this install.",[4]),unsupported_skill_type:E("invalid_input","error",!1,!0,"The requested skill type is unsupported.",[4]),creator_resource_not_found:E("not_found","not_found",!1,!0,"The creator resource was not found.",[4]),creator_access_required:E("permission_denied","access_required",!1,!0,"Creator management access is required for this public skill.",[4]),library_access_required:E("permission_denied","access_required",!1,!0,"Library access is required to inspect issues for this public skill.",[4]),issue_not_found:E("not_found","not_found",!1,!0,"The issue was not found in the managed skill.",[4]),review_not_found:E("not_found","not_found",!1,!0,"The review was not found in the managed skill.",[4]),api_key_not_found:E("not_found","not_found",!1,!0,"The API key was not found.",[4]),approval_request_not_found:E("not_found","not_found",!1,!0,"The approval request was not found.",[4]),available:E("unchanged","available",!1,!1,"The requested capability is available.",[2]),catalog_acquisition_ready:E("unchanged","ready",!1,!1,"The catalog acquisition is ready.",[2]),catalog_artifact_unavailable:E("precondition_required","error",!0,!0,"The exact catalog artifact is temporarily unavailable.",[4,5]),compare_missing_skills:E("not_found","not_found",!1,!0,"One or more skills requested for comparison were not found.",[4]),conflicting_export_output:E("conflict","conflict",!1,!0,"The requested export output options conflict.",[4]),conflicting_mcp_client_selection:E("conflict","conflict",!1,!0,"The MCP client selection is ambiguous.",[4]),conflicting_mcp_migration_mode:E("conflict","conflict",!1,!0,"Choose either a legacy MCP migration preview or an apply operation.",[4]),needs_mcp_client_choice:E("human_action_required","needs_mcp_client_choice",!1,!0,"Choose a verified MCP host before setup can continue.",[4]),mcp_config_symlink_rejected:E("human_action_required","mcp_setup_blocked",!1,!0,"Replace the MCP config symlink with a regular user-owned config file before retrying.",[4]),mcp_registration_ownership_ambiguous:E("human_action_required","mcp_setup_blocked",!1,!0,"Review or rename the existing unowned Skills Layer MCP entry before retrying.",[4]),mcp_client_scope_required:E("human_action_required","needs_mcp_client_scope",!1,!0,"Choose one configured MCP host or explicitly select all hosts.",[4]),mcp_client_inventory_missing:E("precondition_required","mcp_needs_repair",!1,!0,"The local MCP configuration has no canonical host inventory.",[4]),mcp_legacy_project_path_required:E("precondition_required","error",!1,!0,"Choose the exact project root to inspect for legacy MCP registration.",[4]),mcp_multi_client_verify_failed:E("verification_pending","mcp_needs_repair",!0,!0,"One or more configured MCP hosts failed verification.",[4,5]),unknown_mcp_client:E("unsupported_client","error",!1,!0,"The requested MCP host is unsupported.",[4]),creator_listing_not_found_or_not_owned:E("not_found","not_found",!1,!0,"The creator listing is unavailable to this account.",[4]),creator_submission_not_found:E("not_found","not_found",!1,!0,"The creator submission was not found.",[4]),enterprise_resource_not_found:E("not_found","not_found",!1,!0,"The Enterprise resource was not found.",[4]),enterprise_checkout_completion_pending:E("processing_action_required","completion_pending",!0,!0,"Enterprise checkout completion is still being reconciled.",[2,5]),guardian_enabled:E("unchanged","enabled",!1,!1,"Guardian enforcement is enabled.",[2]),feature_already_configured:E("unchanged","unchanged",!1,!1,"The requested feature state is already configured.",[2]),guardian_exact_version_required:E("precondition_required","error",!1,!0,"Guardian requires one exact skill version.",[4]),guardian_unmanaged_atomic_execution_required:E("precondition_required","blocked",!1,!0,"Unmanaged execution cannot be authorized by a diagnostic Guardian check.",[4]),guardian_plan_resolution_failed:E("internal_error","error",!0,!0,"Guardian could not resolve a safe execution plan.",[4,5]),guardian_version_not_current:E("conflict","conflict",!1,!0,"The selected Guardian version is not current.",[4]),human_handoff_required:E("human_action_required","human_action_required",!1,!0,"A human must complete this handoff.",[2,4]),invalid_amount_cents:E("invalid_input","error",!1,!0,"The amount must be a valid non-negative number of cents.",[4]),invalid_enterprise_role:E("invalid_input","error",!1,!0,"The Enterprise role is invalid.",[4]),invalid_expiry:E("invalid_input","error",!1,!0,"The expiry value is invalid.",[4]),invalid_incident_path:E("invalid_input","error",!1,!0,"The incident path is invalid.",[4]),invalid_issue_status:E("invalid_input","error",!1,!0,"The issue status is invalid.",[4]),invalid_price_cents:E("invalid_input","error",!1,!0,"The price must be a valid non-negative number of cents.",[4]),invalid_review_status:E("invalid_input","error",!1,!0,"The review status is invalid.",[4]),invalid_scope:E("invalid_input","error",!1,!0,"The requested scope is invalid.",[4]),invalid_search_filter:E("invalid_input","error",!1,!0,"The search filter is invalid.",[4]),invalid_seats:E("invalid_input","error",!1,!0,"The Enterprise seat count is invalid.",[4]),invalid_sort:E("invalid_input","error",!1,!0,"The requested sort mode is invalid.",[4]),invalid_source:E("invalid_input","error",!1,!0,"The requested source is invalid.",[4]),invalid_version:E("invalid_input","error",!1,!0,"The semantic version is invalid.",[4]),local_install_not_found:E("not_found","not_found",!1,!0,"The local installation was not found.",[4]),local_source_requires_client_files:E("precondition_required","error",!1,!0,"This local source requires client-provided files.",[4]),ownership_claim_not_found:E("not_found","not_found",!1,!0,"The ownership claim was not found.",[4]),ownership_dispute_open:E("human_action_required","manual_review_required",!1,!0,"An ownership dispute requires human resolution.",[2,4]),ownership_already_configured:E("unchanged","unchanged",!1,!1,"The requested ownership assignments are already configured.",[2]),org_dependency_audit_incomplete:E("precondition_required","hold",!0,!0,"The organization dependency audit is incomplete.",[2,4]),purchase_not_found:E("not_found","not_found",!1,!0,"The purchase was not found.",[4]),restore_record_not_found:E("not_found","not_found",!1,!0,"No restorable installation record was found.",[4]),scaffold_overwrite_confirmation_required:E("confirmation_required","human_action_required",!1,!0,"Overwriting the scaffold requires confirmation.",[4]),security_report_requires_review:E("policy_blocked","manual_review_required",!1,!0,"The security report requires human review.",[2,4]),security_report_missing:E("not_found","not_found",!1,!0,"The security report was not found.",[4]),platform_score_subject_missing:E("not_found","not_found",!1,!0,"The exact Platform Score skill generation was not found.",[4]),security_evidence_operation_not_found:E("not_found","not_found",!1,!0,"The security evidence operation was not found.",[4]),skill_not_found:E("not_found","not_found",!1,!0,"The skill was not found.",[4]),social_browser_confirmation_required:E("human_action_required","human_action_required",!1,!0,"Social sign-in requires browser confirmation.",[4]),source_connection_not_found:E("not_found","not_found",!1,!0,"The source connection was not found.",[4]),source_not_verifiable:E("policy_blocked","manual_review_required",!1,!0,"The source cannot be verified automatically.",[2,4]),source_path_not_found:E("not_found","not_found",!1,!0,"The source path was not found.",[4]),source_reference_not_found:E("not_found","not_found",!1,!0,"The source reference was not found.",[4]),submission_not_found:E("not_found","not_found",!1,!0,"The submission was not found.",[2,4]),trust_report_not_found:E("not_found","not_found",!1,!0,"The Platform Score report was not found.",[4]),unknown_agent:E("unsupported_client","error",!1,!0,"The requested agent is unsupported.",[4]),verification_code_invalid:E("human_action_required","error",!1,!0,"The verification code is invalid or expired.",[4]),workspace_not_found_or_forbidden:E("not_found","not_found",!1,!0,"The workspace is unavailable to this account.",[4]),workspace_skill_approval_not_found:E("not_found","not_found",!1,!0,"The workspace skill approval was not found.",[4]),workspace_working_mode_not_found:E("not_found","not_found",!1,!0,"The selected workspace was not found.",[4])};function Cee(e){let t=mN[e];return t?{reasonCode:e,...t}:null}function Og(e,t={}){if(!e)return t.httpStatus===404?Ia("resource_not_found"):t.httpStatus===401?Ia("login_required"):t.httpStatus===403?Ia("permission_denied"):t.httpStatus===409?gt("conflict","conflict"):t.httpStatus===429?Ia("rate_limited"):(t.httpStatus&&t.httpStatus>=500,Ia("command_failed"));let n=Cee(e);return n||(e.includes("not_found")||e==="missing_record"?gt(e,"not_found","not_found"):e.includes("rate_limit")?gt(e,"rate_limited","rate_limited",!0):e.includes("quota")||e.includes("_limit_reached")||e.includes("_limit_exhausted")?gt(e,"quota_exceeded","conflict"):e.includes("human")||e.includes("mfa")||e.includes("browser_confirmation")?gt(e,"human_action_required","human_action_required"):e.includes("already_canceled")||e.includes("unchanged")||e.includes("already_complete")?gt(e,"unchanged","unchanged"):e.includes("dependency")||e.includes("precondition")||e.includes("required")?gt(e,"precondition_required","error"):e.includes("processing")||e.includes("pending")||e.includes("already_processing")?gt(e,"processing_action_required","already_processing",!0):e.includes("conflict")||e.includes("already_final")||e.includes("completed")?gt(e,"conflict","conflict"):e.includes("payment")||e.includes("checkout")||e.includes("purchase")?gt(e,"payment_required","human_action_required"):e.includes("source")?gt(e,"source_required","error"):e.includes("backend")||e.includes("unreachable")||e.includes("network")?gt(e,"backend_unreachable","error",!0):e.includes("agent")||e.includes("client")||e.includes("unsupported")?gt(e,"unsupported_client","error"):e.includes("blocked")||e.includes("policy")||e.includes("guardian")?gt(e,"policy_blocked","blocked"):e.includes("forbidden")||e.includes("permission_denied")?gt(e,"permission_denied","error"):e.includes("not_allowed")||e.includes("invalid_transition")?gt(e,"operation_not_allowed","error"):gt(e,"invalid_input","error"))}function E(e,t,n,r,i,o){return{family:e,defaultStatus:t,retryable:n,nextActionRequired:r,safeSummary:i,allowedHttpStatusClasses:o}}function Ia(e){return{reasonCode:e,...mN[e]}}function gt(e,t,n="error",r=!1){return{reasonCode:e,family:t,defaultStatus:n,retryable:r,nextActionRequired:!1,safeSummary:"The command could not be completed.",allowedHttpStatusClasses:[4,5]}}var gN=[["help","account"],["help","use"],["help","creator"],["help","teams"],["help","security"],["help","mcp"],["help","automation"],["help","troubleshoot"],["help","full"]],hN=[["help"],["help","topic"],["login"],["logout"],["register"],["setup"],["whoami"],["profile"],["profile","update"],["auth"],["auth","status"],["auth","repair"],["auth","verify"],["auth","recover"],["auth","recover","complete"],["auth","connect"],["auth","mfa"],["auth","mfa","status"],["auth","mfa","setup"],["auth","mfa","verify"],["auth","mfa","recovery-codes"],["auth","mfa","disable"],["api-key"],["api-key","create"],["api-key","list"],["api-key","revoke"],["mcp"],["mcp","setup"],["mcp","status"],["mcp","verify"],["mcp","repair"],["mcp","migrate"],["mcp","disconnect"],["backend"],["backend","status"],["backend","cloud"],["backend","local"],["status"],["doctor"],["search"],["find"],["featured"],["trending"],["show"],["trust"],["recommend"],["categories"],["compare"],["install"],["install","status"],["installed"],["owned"],["export"],["add-review"],["show-reviews"],["add-issue"],["show-issues"],["purchases"],["purchases","list"],["purchases","invoice"],["purchases","status"],["purchases","refund-quote"],["purchases","refund"],["purchases","spending"],["validate"],["preview-trigger"],["creator"],["creator","init"],["creator","create"],["creator","sessions"],["creator","resume"],["creator","inspect"],["creator","answer"],["creator","resources"],["creator","resource-decide"],["creator","tool-contract"],["creator","draft"],["creator","validate"],["creator","eval"],["creator","improve"],["creator","revise"],["creator","materialize"],["creator","finalize"],["creator","rules"],["creator","submissions"],["creator","spaces"],["creator","spaces","buy"],["creator","status"],["creator","source"],["creator","source","prepare"],["creator","source","publish-request"],["creator","source","release-status"],["creator","submit"],["creator","submit-version"],["creator","check-slug"],["creator","rename"],["creator","pricing"],["creator","delist"],["creator","relist"],["creator","update-listing"],["creator","visibility"],["creator","security-report"],["creator","rescan-security"],["creator","provenance"],["creator","claim"],["creator","verify"],["creator","dispute"],["creator","issues"],["creator","update-issue"],["creator","reviews"],["creator","moderate-review"],["creator","analytics"],["creator","earnings"],["creator","payout-profile"],["creator","payout-link"],["creator","payouts"],["creator","withdraw"],["source"],["source","connection"],["source","connection","start"],["source","connection","status"],["source","connection","complete"],["source","connection","cancel"],["source","connection","revoke"],["source","reference"],["source","reference","resolve"],["approval"],["approval","request"],["approval","request","status"],["approval","request","complete"],["enterprise"],["enterprise","accept-invite"],["enterprise","checkout"],["enterprise","install-authorize"],["enterprise","list"],["enterprise","member"],["enterprise","member","remove"],["enterprise","member","role"],["enterprise","members"],["enterprise","rename"],["enterprise","primary-admin"],["enterprise","primary-admin","transfer"],["enterprise","primary-admin","status"],["enterprise","primary-admin","accept"],["enterprise","primary-admin","cancel"],["enterprise","seats"],["enterprise","seats","add"],["enterprise","invite"],["enterprise","invites"],["enterprise","revoke-invite"],["enterprise","resend-invite"],["enterprise","workspace-member"],["enterprise","workspace-member","list"],["enterprise","workspace-member","add"],["enterprise","workspace-member","remove"],["enterprise","workspace"],["enterprise","workspace","create"],["enterprise","workspace","rename"],["enterprise","workspace","update"],["enterprise","workspace","archive"],["enterprise","workspaces"],["enterprise","skill"],["enterprise","skill","entitlements"],["enterprise","skill","quote"],["enterprise","skill","buy"],["workspace"],["workspace","list"],["workspace","current"],["workspace","select"],["workspace","request"],["workspace","approve"],["workspace","reject"],["workspace","skills"],["workspace","guide"],["workspaces"],["guardian"],["guardian","check"],["guardian","incident"],["guardian","enable"],["guardian","disable"],["guardian","enable-warnings-only"],["guardian","status"],["guardian","hook"],["guardian","hook","install"],["guardian","hook","status"],["guardian","launch"],["guardian","exec"],["agents"],["agents","list"],["import"],["sync"],["restore"],["check"],["update"],["remove"],["identity"],["identity","providers"],["identity","start"],["identity","continue"],["identity","status"],["identity","complete"],["identity","list"],["identity","unlink"],["library"],["buy"]],Iee=1+gN.length+hN.length;var So="0.2.13";var Pee="skills-layer-cli-event-v1";function vN(e){let t=0,n=e.now??(()=>new Date().toISOString());return(r,i)=>{let o=Ei(i.summary,"summary",512),s=i.redactedDetail===void 0?void 0:Ei(i.redactedDetail,"redacted detail",2048),a=i.next?.map(u=>({id:Ei(u.id,"next-action ID",128),kind:u.kind,label:Ei(u.label,"next-action label",512),...u.command===void 0?{}:{command:{executable:u.command.executable,args:u.command.args.map(d=>Ei(d,"next-action argument",1024))}},...u.url===void 0?{}:{url:yN(u.url)},safeToAutoRun:u.safeToAutoRun,requiresHuman:u.requiresHuman,...u.rationale===void 0?{}:{rationale:Ei(u.rationale,"next-action rationale",1024)},safety:u.safety})),l=i.links?.map(u=>{let d=yN(u.url);return{label:Ei(u.label,"link label",512),url:d}}),c=i.data===void 0?void 0:iI(i.data);return t+=1,{schemaVersion:Pee,operationId:H(e.operationId),sequence:t,timestamp:n(),type:r,command:{name:H(e.command.name)},...i,summary:o,...s===void 0?{}:{redactedDetail:s},...a===void 0?{}:{next:a},...l===void 0?{}:{links:l},...c===void 0?{}:{data:c}}}}function yN(e){let t=Ei(e,"link URL",2048);if(!/^https?:\/\//u.test(t))throw new Error("CLI event links must use http or https URLs.");return t}function Ei(e,t,n){let r=H(e);if(r.length>n)throw new Error(`CLI event ${t} exceeds ${n} characters.`);return r}function iI(e,t=""){return/^(?:accessToken|apiKey|authorization|clientSecret|handoffCode|password|refreshToken|secret)$/iu.test(t)?"[redacted-secret]":typeof e=="string"?H(e):Array.isArray(e)?e.map(n=>iI(n)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,iI(r,n)])):e}var Aee=["human","json","stream-json"],kN=["auto","always","never"],Ree=["auto","modern","classic"],Eee=["concise","standard","full"];function wN(e){let t=[],n={},r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(r){t.push(o);continue}if(o==="--"){r=!0,t.push(o);continue}let[s,a]=$ee(o);if(s==="--output-format"){let[l,c]=ku(s,a,e[i+1],Aee);n.outputFormat=l,i+=c}else if(s==="--color"){let[l,c]=ku(s,a,e[i+1],kN);n.color=l,i+=c}else if(s==="--motion"){let[l,c]=ku(s,a,e[i+1],kN);n.motion=l,i+=c}else if(s==="--ui"){let[l,c]=ku(s,a,e[i+1],Ree);n.ui=l,i+=c}else if(s==="--detail"){let[l,c]=ku(s,a,e[i+1],Eee);n.detail=l,i+=c}else o==="--no-color"?n.color="never":o==="--no-motion"?n.motion="never":o==="--screen-reader"?n.screenReader=!0:o==="--no-interactive"?n.interactive=!1:o==="--ascii"?n.unicode=!1:t.push(o)}return{args:t,options:n}}function bN(e,t,n){let r=e.outputFormat??"human",i=e.screenReader===!0,o=Lg(t.CI),s=t.TERM==="dumb",a=n.stdinIsTty&&n.stdoutIsTty&&n.stderrIsTty,l=e.ui!=="classic",c=e.ui==="classic",u=e.detail??(r==="human"?"concise":"standard"),d=a&&!o&&!s&&l&&!i&&e.interactive!==!1,p=d&&e.motion!=="never",m=d&&p,h=!i&&e.color!=="never"&&(e.color==="always"||!Lg(t.NO_COLOR)&&!c&&(Lg(t.FORCE_COLOR)||!o&&!s&&n.stdoutIsTty)),g=e.unicode!==!1&&!Lg(t.NO_UNICODE)&&!s;return r==="json"?{kind:"json-final",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:r==="stream-json"?{kind:"json-stream",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:{kind:m?"human-interactive":"human-static",color:h,motion:p,interactive:m,unicode:g,screenReader:i,classic:c,detail:u}}function $ee(e){let t=e.indexOf("=");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function ku(e,t,n,r){let i=t??n;if(i===void 0||i.startsWith("--")||!r.includes(i))throw new Error(`${e} expects one of: ${r.join(", ")}.`);return[i,t===void 0?1:0]}function Lg(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}var _N=()=>null;var xo=88,Dee=/(?:^|_)(?:blocked|cancelled|canceled|rejected|denied|expired|invalid|not_found|conflict|missing_required_argument)(?:$|_)/u,Tee=/(?:^|_)(?:required|requires_action|warning|unverified|completion_pending)(?:$|_)/u,Oee=/(?:^|_)(?:argument|field|input|parameter|protocol|value)_required(?:$|_)/u,Lee=/(?:^|_)(?:failed|failure|internal_error|network_error|service_unavailable|timed_out|timeout)(?:$|_)/u,jee=/\b(?:required information is missing|unknown (?:command|option|flag)|invalid|already used|not found|blocked|cancelled|canceled|rejected|denied|expired|missing|not supported|could not be read|cannot write)\b/iu,Nee=/\b(?:action|approval|authentication|checkout|confirmation|consent|human action|login|mfa|payment|purchase|registration|second factor|secure account connection|sign in|source connection|verification|workspace approval)\b[^.\n]*\b(?:required|needed|must be completed)\b|\b(?:complete|confirm|continue)\b[^.\n]*\b(?:browser|cli|terminal)\b/iu,Fee=/\b(?:failed|failure|service unavailable|server error|network error|timed out|timeout|could not complete)\b/iu;function xN(e){let t=SN(e.status),n=SN(e.reasonCode),r=[t,n].filter(Boolean);return r.some(i=>Dee.test(i))?"stopped":r.some(i=>Tee.test(i)&&!Oee.test(i))?"required":r.some(i=>Lee.test(i))||e.summary&&oI(e.summary)==="failed"?"failed":e.exitCode!==void 0&&e.exitCode!==0?"stopped":"completed"}function oI(e){let t=Bee(e);return jee.test(t)?"stopped":Nee.test(t)?"required":Fee.test(t)?"failed":"stopped"}function wu(e,t){let n=t?"\u2014":"-",r=e.slice(0,1).toUpperCase()+e.slice(1);return`Skills Layer ${n} Action ${r}`}function SN(e){return H(e??"").trim().toLowerCase().replace(/[^a-z0-9]+/gu,"_")}function Bee(e){return H(e).split(/\n(?:Unchanged|Why|Next|Reference)(?:\s|$)/u,1)[0]}function Co(e){return EN(sr(e)).reduce((t,n)=>t+$N(n),0)}function CN(e,t){return e.split(`
|
|
2020
|
+
`)):n.options,...dee[e]??[],"--json"])]),inheritedOptions:uee,outputModes:Object.freeze(["human","json","stream-json"]),mutability:kee(n.sideEffects),humanInLoop:wee(n),fixturePrerequisites:Object.freeze([...n.requiresLogin?["authenticated_account"]:[],...n.requiresNetwork?["reachable_backend"]:[]]),examples:Object.freeze(n.examples),availability:"public"})})),fee=new Map(pee.map(e=>[e.path,e]));function uN(e){let t=e.map(n=>n.trim().toLowerCase()).filter(Boolean);for(let n=t.length;n>=1;n-=1){let r=fee.get(t.slice(0,n).join(" "));if(r)return r}return null}function mee(e,t){let n=new Set([...e.options,...e.inheritedOptions]),r=t.indexOf("--"),i=r===-1?t:t.slice(0,r);for(let o of i){if(!o.startsWith("--"))continue;let s=o.split("=",1)[0];if(!n.has(s))return s.slice(2)}return null}var dN=mee;function gee(e){return e==="find"?["search"]:e==="workspaces"?["workspace"]:[]}function hee(e){return[...new Set([...e.matchAll(/<([^>]+)>/gu)].map(t=>t[1]))]}function yee(e,t){let n=`skills-layer ${e}`;return t.split(/\r?\n/u).map(r=>r.trim()).filter(r=>r===n||r.startsWith(`${n} `))}function vee(e){return[...new Set([...e.matchAll(/--[a-z][a-z0-9-]*/gu)].map(t=>t[0]))]}function kee(e){let t=e.some(r=>r.includes("local")||r.includes("credential")),n=e.some(r=>r.includes("cloud_write")||r.includes("payment"));return t&&n?"mixed":n?"cloud_write":t?"local_write":"read_only"}function wee(e){return e.sideEffects.includes("payment_mutation")?"financial":e.mayOpenBrowser?"browser":e.mayPrompt?"prompt":"none"}import{posix as bee,win32 as _ee}from"node:path";function pN(e,t){let n=t==="win32"?_ee:bee;if(t==="win32"){let o=rI(e.APPDATA,e.USERPROFILE,e.HOME);if(!o)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(o,"skills-layer")}let r=rI(e.XDG_CONFIG_HOME);if(r)return n.join(r,"skills-layer");let i=rI(e.HOME);if(!i)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(i,".skills-layer")}function rI(...e){return e.map(t=>t?.trim()).find(t=>!!t)}var See=/^[\u00a0\u2007\u202f\ufeff]+|[\u00a0\u2007\u202f\ufeff]+$/gu,xee=/^\[(https?:\/\/[^\]\r\n]+)\]\((https?:\/\/[^)\r\n]+)\)$/u;function fN(e){let t=e.indexOf("--");return e.map((n,r)=>{if(t!==-1&&r>t)return n;let i=n.replace(See,""),o=xee.exec(i);return o&&o[1]===o[2]?o[1]:i})}var mN={enterprise_member_already_active:E("conflict","conflict",!1,!1,"This person is already an active Enterprise member.",[4]),local_cleanup_incomplete:E("human_action_required","error",!0,!0,"Unlock the OS credential store and retry logout to finish local cleanup.",[4,5]),admin_step_up_invalid:E("security_verification_failed","error",!1,!0,"Verify your administrator step-up key in the private operator checkout.",[4]),verification_code_locked:E("rate_limited","rate_limited",!0,!0,"This code is locked. Request a new code after the retry time.",[4]),conflicting_flags:E("invalid_input","error",!1,!0,"Choose a value or its clear flag, not both.",[4]),flag_value_missing:E("invalid_input","error",!1,!0,"Supply a value for the flag.",[4]),rights_attestation_required:E("precondition_required","error",!1,!0,"Public and unlisted releases require confirmation of distribution rights.",[4]),rights_attestation_invalid:E("invalid_input","error",!1,!0,"Supply a supported rights basis and public distribution scope.",[4]),catalogue_artifact_unavailable:E("backend_unreachable","error",!0,!0,"The catalogue artifact could not be downloaded; retry export.",[4]),admin_mfa_required:E("human_action_required","human_action_required",!1,!0,"Enable MFA with skills-layer auth mfa setup, then retry.",[4]),admin_mfa_unavailable:E("backend_unreachable","unavailable",!0,!0,"Administrator MFA is unavailable; contact the deployment operator.",[5]),source_read_unavailable:E("backend_unreachable","source_unavailable",!1,!0,"The source could not be read completely. Its package has not been assessed.",[5]),command_failed:E("internal_error","error",!1,!1,"The command could not be completed.",[5]),resource_not_found:E("not_found","not_found",!1,!0,"The requested resource was not found.",[4]),permission_denied:E("permission_denied","error",!1,!1,"This credential cannot perform the requested operation.",[4]),login_required:E("login_required","login_required",!1,!0,"Sign in is required.",[4]),unauthorized:E("login_required","login_required",!1,!0,"Sign in is required.",[4]),api_key_invalid_or_expired:E("login_required","login_required",!1,!0,"The saved API key is no longer valid. Sign in again to use account features.",[4]),confirmation_required:E("confirmation_required","human_action_required",!1,!0,"Human confirmation is required.",[4]),mfa_setup_required:E("human_action_required","human_action_required",!1,!0,"MFA setup is required.",[4]),login_mfa_required:E("human_action_required","human_action_required",!1,!0,"A second authentication factor is required.",[4]),login_mfa_input_invalid:E("invalid_input","error",!1,!0,"Provide exactly one supported MFA proof.",[4]),login_mfa_invalid:E("security_verification_failed","error",!1,!0,"The MFA proof was invalid or already used.",[4]),login_security_unavailable:E("security_verification_failed","security_unavailable",!0,!0,"Login security is unavailable.",[5]),mfa_challenge_locked:E("rate_limited","rate_limited",!0,!0,"The MFA challenge is temporarily locked.",[4]),social_secure_continuation_unavailable:E("security_verification_failed","security_unavailable",!1,!0,"Secure social continuation is unavailable.",[4,5]),social_continuation_terminal:E("security_verification_failed","error",!1,!0,"The social continuation ended without authorization.",[4]),verification_code_expired:E("human_action_required","error",!1,!0,"The verification code expired.",[4]),payout_human_confirmation_required:E("human_action_required","human_action_required",!1,!0,"Human payout confirmation is required.",[4]),security_report_requires_action:E("policy_blocked","blocked",!1,!0,"The security report requires action.",[4]),trust_report_not_actionable:E("policy_blocked","blocked",!1,!0,"The trust report does not permit this transition.",[4]),trust_report_authority_mismatch:E("security_verification_failed","blocked",!1,!0,"Trust evidence does not match the exact artifact generation.",[4,5]),trust_report_required_evidence_unavailable:E("verification_pending","action_required",!0,!0,"Required trust evidence is unavailable or incomplete.",[2,4,5]),sarif_source_mapping_required:E("precondition_required","error",!1,!0,"Repository SARIF requires verified repository-relative source locations.",[4]),sarif_security_evidence_required:E("precondition_required","error",!1,!0,"Runtime-audit SARIF requires typed security evidence.",[4]),sarif_rule_mapping_required:E("precondition_required","error",!1,!0,"Runtime-audit SARIF requires an explicit reviewed rule mapping for every actionable event.",[4]),sarif_profile_unsupported:E("invalid_input","error",!1,!0,"The requested SARIF profile is not available for this report audience.",[4]),cloud_trust_ledger_mismatch:E("security_verification_failed","blocked",!1,!0,"This exact public skill generation is temporarily unavailable because its Cloud Trust Ledger attestation does not match. A Skills Layer operator must re-attest the exact generation before install.",[4]),api_key_active_limit_reached:E("quota_exceeded","conflict",!1,!0,"The active API-key limit has been reached.",[4]),rate_limited:E("rate_limited","rate_limited",!0,!0,"The request rate limit was reached.",[4]),source_connection_already_canceled:E("unchanged","unchanged",!1,!1,"The source connection was already canceled.",[2,4]),source_connection_completed:E("conflict","conflict",!1,!1,"A completed source connection cannot be canceled.",[4]),source_connection_revoked:E("unchanged","unchanged",!1,!1,"The authorized source connection was revoked.",[0]),source_connection_already_revoked:E("unchanged","unchanged",!1,!1,"The source connection was already revoked.",[0]),source_connection_not_authorized:E("conflict","conflict",!1,!1,"Only an authorized source connection can be revoked.",[4]),reupload_required:E("precondition_required","reupload_required",!1,!0,"The stored artifact is unavailable; upload the bundle again.",[4]),artifact_finalization_failed:E("processing_action_required","partial_success",!0,!1,"The version exists but artifact finalisation is incomplete.",[0]),publication_moderation_failed:E("processing_action_required","partial_success",!1,!1,"The version exists but its moderation transition needs operator inspection.",[0]),source_connection_completion_unverified:E("verification_pending","verification_warning",!0,!0,"Source connection completion could not be verified.",[4,5]),admin_mcp_verification_warning:E("verification_pending","verification_warning",!0,!0,"Administrator MCP verification is pending.",[2,4,5]),admin_mcp_verification_rejected:E("security_verification_failed","rejected",!1,!0,"Administrator MCP verification was rejected.",[4]),authoritative_security_report_pending:E("processing_action_required","already_processing",!0,!0,"The authoritative security report is still processing.",[4]),publication_continuation_scheduled:E("processing_action_required","already_processing",!0,!1,"Publication is continuing through the durable exact-generation workflow.",[2,4]),binary_inspection_pending:E("processing_action_required","already_processing",!0,!0,"Binary asset security inspection is still processing.",[2,4]),binary_inspection_unavailable:E("verification_pending","hold",!0,!0,"Required binary asset security inspection is currently unavailable.",[2,4,5]),binary_asset_blocked:E("policy_blocked","blocked",!1,!0,"A binary asset did not satisfy the platform security policy.",[2,4]),binary_profile_suspended:E("policy_blocked","hold",!0,!0,"The required binary format profile is temporarily suspended.",[2,4]),security_adjudication_pending:E("processing_action_required","already_processing",!0,!0,"Contextual security evidence is still being evaluated.",[2,4]),content_adjudication_insufficient_evidence:E("verification_pending","hold",!0,!0,"The available evidence is insufficient to resolve the security finding.",[2,4]),content_adjudication_confirmed_risk:E("policy_blocked","blocked",!1,!0,"The exact content contains a confirmed security risk.",[2,4]),content_adjudication_source_remediation_required:E("policy_blocked","blocked",!1,!0,"The source must be changed before security review can continue.",[2,4]),content_adjudication_execution_failed:E("verification_pending","hold",!0,!0,"Content security adjudication could not complete and remains held.",[2,4,5]),content_probe_runner_unavailable:E("verification_pending","hold",!0,!0,"The isolated content security evaluator is currently unavailable.",[2,4,5]),binary_inspection_authority_invalid:E("security_verification_failed","hold",!0,!0,"Binary security evidence could not be authenticated.",[2,4,5]),managed_security_pack_stale:E("security_verification_failed","hold",!0,!0,"A required managed security definition pack is not current.",[2,4,5]),workflow_dependency_incomplete:E("precondition_required","waiting_for_dependency",!0,!0,"A required upstream workflow is incomplete.",[4]),creator_processing_sla_breached:E("processing_action_required","action_required",!1,!0,"Creator processing exceeded its platform SLA.",[4,5]),invalid_global_option:E("invalid_input","error",!1,!0,"A global CLI option is invalid.",[4]),invalid_numeric_input:E("invalid_input","error",!1,!0,"A numeric option is invalid.",[4]),unknown_flag:E("invalid_input","error",!1,!0,"The option is not supported.",[4]),unknown_command:E("invalid_input","error",!1,!0,"The command is not supported.",[4]),unknown_subcommand:E("invalid_input","error",!1,!0,"The command is not supported.",[4]),missing_required_argument:E("invalid_input","error",!1,!0,"Required information is missing.",[4]),invalid_json:E("invalid_input","error",!1,!0,"The JSON value is invalid.",[4]),canonical_bundle_rejected:E("invalid_input","error",!1,!0,"The bundle failed canonical validation.",[4]),recovery_code_invalid_or_expired:E("human_action_required","error",!1,!0,"The recovery code is invalid or expired.",[4]),social_provider_not_configured:E("precondition_required","error",!1,!0,"The selected social provider is not configured.",[4,5]),search_selection_not_found:E("not_found","not_found",!1,!0,"The selected skill is not present in these search results.",[4]),best_effort:E("unchanged","low_confidence",!1,!0,"Best-effort candidates need a more specific task for higher confidence.",[2]),unsafe_task:E("policy_blocked","policy_blocked",!1,!0,"This task is outside the recommendation safety policy.",[2]),no_confident_recommendation:E("unchanged","no_confident_recommendation",!1,!0,"No skill met the calibrated recommendation confidence policy.",[2]),clarification_required:E("human_action_required","clarification_required",!1,!0,"One public task constraint is required before a skill can be recommended.",[2]),workspace_required:E("precondition_required","error",!1,!0,"A workspace id is required for this install.",[4]),unsupported_skill_type:E("invalid_input","error",!1,!0,"The requested skill type is unsupported.",[4]),creator_resource_not_found:E("not_found","not_found",!1,!0,"The creator resource was not found.",[4]),creator_access_required:E("permission_denied","access_required",!1,!0,"Creator management access is required for this public skill.",[4]),library_access_required:E("permission_denied","access_required",!1,!0,"Library access is required to inspect issues for this public skill.",[4]),issue_not_found:E("not_found","not_found",!1,!0,"The issue was not found in the managed skill.",[4]),review_not_found:E("not_found","not_found",!1,!0,"The review was not found in the managed skill.",[4]),api_key_not_found:E("not_found","not_found",!1,!0,"The API key was not found.",[4]),approval_request_not_found:E("not_found","not_found",!1,!0,"The approval request was not found.",[4]),available:E("unchanged","available",!1,!1,"The requested capability is available.",[2]),catalog_acquisition_ready:E("unchanged","ready",!1,!1,"The catalog acquisition is ready.",[2]),catalog_artifact_unavailable:E("precondition_required","error",!0,!0,"The exact catalog artifact is temporarily unavailable.",[4,5]),compare_missing_skills:E("not_found","not_found",!1,!0,"One or more skills requested for comparison were not found.",[4]),conflicting_export_output:E("conflict","conflict",!1,!0,"The requested export output options conflict.",[4]),conflicting_mcp_client_selection:E("conflict","conflict",!1,!0,"The MCP client selection is ambiguous.",[4]),conflicting_mcp_migration_mode:E("conflict","conflict",!1,!0,"Choose either a legacy MCP migration preview or an apply operation.",[4]),needs_mcp_client_choice:E("human_action_required","needs_mcp_client_choice",!1,!0,"Choose a verified MCP host before setup can continue.",[4]),mcp_config_symlink_rejected:E("human_action_required","mcp_setup_blocked",!1,!0,"Replace the MCP config symlink with a regular user-owned config file before retrying.",[4]),mcp_registration_ownership_ambiguous:E("human_action_required","mcp_setup_blocked",!1,!0,"Review or rename the existing unowned Skills Layer MCP entry before retrying.",[4]),mcp_client_scope_required:E("human_action_required","needs_mcp_client_scope",!1,!0,"Choose one configured MCP host or explicitly select all hosts.",[4]),mcp_client_inventory_missing:E("precondition_required","mcp_needs_repair",!1,!0,"The local MCP configuration has no canonical host inventory.",[4]),mcp_legacy_project_path_required:E("precondition_required","error",!1,!0,"Choose the exact project root to inspect for legacy MCP registration.",[4]),mcp_multi_client_verify_failed:E("verification_pending","mcp_needs_repair",!0,!0,"One or more configured MCP hosts failed verification.",[4,5]),unknown_mcp_client:E("unsupported_client","error",!1,!0,"The requested MCP host is unsupported.",[4]),creator_listing_not_found_or_not_owned:E("not_found","not_found",!1,!0,"The creator listing is unavailable to this account.",[4]),creator_submission_not_found:E("not_found","not_found",!1,!0,"The creator submission was not found.",[4]),enterprise_resource_not_found:E("not_found","not_found",!1,!0,"The Enterprise resource was not found.",[4]),enterprise_checkout_completion_pending:E("processing_action_required","completion_pending",!0,!0,"Enterprise checkout completion is still being reconciled.",[2,5]),guardian_enabled:E("unchanged","enabled",!1,!1,"Guardian enforcement is enabled.",[2]),feature_already_configured:E("unchanged","unchanged",!1,!1,"The requested feature state is already configured.",[2]),guardian_exact_version_required:E("precondition_required","error",!1,!0,"Guardian requires one exact skill version.",[4]),guardian_unmanaged_atomic_execution_required:E("precondition_required","blocked",!1,!0,"Unmanaged execution cannot be authorized by a diagnostic Guardian check.",[4]),guardian_plan_resolution_failed:E("internal_error","error",!0,!0,"Guardian could not resolve a safe execution plan.",[4,5]),guardian_version_not_current:E("conflict","conflict",!1,!0,"The selected Guardian version is not current.",[4]),human_handoff_required:E("human_action_required","human_action_required",!1,!0,"A human must complete this handoff.",[2,4]),invalid_amount_cents:E("invalid_input","error",!1,!0,"The amount must be a valid non-negative number of cents.",[4]),invalid_enterprise_role:E("invalid_input","error",!1,!0,"The Enterprise role is invalid.",[4]),invalid_expiry:E("invalid_input","error",!1,!0,"The expiry value is invalid.",[4]),invalid_incident_path:E("invalid_input","error",!1,!0,"The incident path is invalid.",[4]),invalid_issue_status:E("invalid_input","error",!1,!0,"The issue status is invalid.",[4]),invalid_price_cents:E("invalid_input","error",!1,!0,"The price must be a valid non-negative number of cents.",[4]),invalid_review_status:E("invalid_input","error",!1,!0,"The review status is invalid.",[4]),invalid_scope:E("invalid_input","error",!1,!0,"The requested scope is invalid.",[4]),invalid_search_filter:E("invalid_input","error",!1,!0,"The search filter is invalid.",[4]),invalid_seats:E("invalid_input","error",!1,!0,"The Enterprise seat count is invalid.",[4]),invalid_sort:E("invalid_input","error",!1,!0,"The requested sort mode is invalid.",[4]),invalid_source:E("invalid_input","error",!1,!0,"The requested source is invalid.",[4]),invalid_version:E("invalid_input","error",!1,!0,"The semantic version is invalid.",[4]),local_install_not_found:E("not_found","not_found",!1,!0,"The local installation was not found.",[4]),local_source_requires_client_files:E("precondition_required","error",!1,!0,"This local source requires client-provided files.",[4]),ownership_claim_not_found:E("not_found","not_found",!1,!0,"The ownership claim was not found.",[4]),ownership_dispute_open:E("human_action_required","manual_review_required",!1,!0,"An ownership dispute requires human resolution.",[2,4]),ownership_already_configured:E("unchanged","unchanged",!1,!1,"The requested ownership assignments are already configured.",[2]),org_dependency_audit_incomplete:E("precondition_required","hold",!0,!0,"The organization dependency audit is incomplete.",[2,4]),purchase_not_found:E("not_found","not_found",!1,!0,"The purchase was not found.",[4]),restore_record_not_found:E("not_found","not_found",!1,!0,"No restorable installation record was found.",[4]),scaffold_overwrite_confirmation_required:E("confirmation_required","human_action_required",!1,!0,"Overwriting the scaffold requires confirmation.",[4]),security_report_requires_review:E("policy_blocked","manual_review_required",!1,!0,"The security report requires human review.",[2,4]),security_report_missing:E("not_found","not_found",!1,!0,"The security report was not found.",[4]),platform_score_subject_missing:E("not_found","not_found",!1,!0,"The exact Platform Score skill generation was not found.",[4]),security_evidence_operation_not_found:E("not_found","not_found",!1,!0,"The security evidence operation was not found.",[4]),skill_not_found:E("not_found","not_found",!1,!0,"The skill was not found.",[4]),social_browser_confirmation_required:E("human_action_required","human_action_required",!1,!0,"Social sign-in requires browser confirmation.",[4]),source_connection_not_found:E("not_found","not_found",!1,!0,"The source connection was not found.",[4]),source_not_verifiable:E("policy_blocked","manual_review_required",!1,!0,"The source cannot be verified automatically.",[2,4]),source_path_not_found:E("not_found","not_found",!1,!0,"The source path was not found.",[4]),source_reference_not_found:E("not_found","not_found",!1,!0,"The source reference was not found.",[4]),submission_not_found:E("not_found","not_found",!1,!0,"The submission was not found.",[2,4]),trust_report_not_found:E("not_found","not_found",!1,!0,"The Platform Score report was not found.",[4]),unknown_agent:E("unsupported_client","error",!1,!0,"The requested agent is unsupported.",[4]),verification_code_invalid:E("human_action_required","error",!1,!0,"The verification code is invalid or expired.",[4]),workspace_not_found_or_forbidden:E("not_found","not_found",!1,!0,"The workspace is unavailable to this account.",[4]),workspace_skill_approval_not_found:E("not_found","not_found",!1,!0,"The workspace skill approval was not found.",[4]),workspace_working_mode_not_found:E("not_found","not_found",!1,!0,"The selected workspace was not found.",[4])};function Cee(e){let t=mN[e];return t?{reasonCode:e,...t}:null}function Og(e,t={}){if(!e)return t.httpStatus===404?Ia("resource_not_found"):t.httpStatus===401?Ia("login_required"):t.httpStatus===403?Ia("permission_denied"):t.httpStatus===409?gt("conflict","conflict"):t.httpStatus===429?Ia("rate_limited"):(t.httpStatus&&t.httpStatus>=500,Ia("command_failed"));let n=Cee(e);return n||(e.includes("not_found")||e==="missing_record"?gt(e,"not_found","not_found"):e.includes("rate_limit")?gt(e,"rate_limited","rate_limited",!0):e.includes("quota")||e.includes("_limit_reached")||e.includes("_limit_exhausted")?gt(e,"quota_exceeded","conflict"):e.includes("human")||e.includes("mfa")||e.includes("browser_confirmation")?gt(e,"human_action_required","human_action_required"):e.includes("already_canceled")||e.includes("unchanged")||e.includes("already_complete")?gt(e,"unchanged","unchanged"):e.includes("dependency")||e.includes("precondition")||e.includes("required")?gt(e,"precondition_required","error"):e.includes("processing")||e.includes("pending")||e.includes("already_processing")?gt(e,"processing_action_required","already_processing",!0):e.includes("conflict")||e.includes("already_final")||e.includes("completed")?gt(e,"conflict","conflict"):e.includes("payment")||e.includes("checkout")||e.includes("purchase")?gt(e,"payment_required","human_action_required"):e.includes("source")?gt(e,"source_required","error"):e.includes("backend")||e.includes("unreachable")||e.includes("network")?gt(e,"backend_unreachable","error",!0):e.includes("agent")||e.includes("client")||e.includes("unsupported")?gt(e,"unsupported_client","error"):e.includes("blocked")||e.includes("policy")||e.includes("guardian")?gt(e,"policy_blocked","blocked"):e.includes("forbidden")||e.includes("permission_denied")?gt(e,"permission_denied","error"):e.includes("not_allowed")||e.includes("invalid_transition")?gt(e,"operation_not_allowed","error"):gt(e,"invalid_input","error"))}function E(e,t,n,r,i,o){return{family:e,defaultStatus:t,retryable:n,nextActionRequired:r,safeSummary:i,allowedHttpStatusClasses:o}}function Ia(e){return{reasonCode:e,...mN[e]}}function gt(e,t,n="error",r=!1){return{reasonCode:e,family:t,defaultStatus:n,retryable:r,nextActionRequired:!1,safeSummary:"The command could not be completed.",allowedHttpStatusClasses:[4,5]}}var gN=[["help","account"],["help","use"],["help","creator"],["help","teams"],["help","security"],["help","mcp"],["help","automation"],["help","troubleshoot"],["help","full"]],hN=[["help"],["help","topic"],["login"],["logout"],["register"],["setup"],["whoami"],["profile"],["profile","update"],["auth"],["auth","status"],["auth","repair"],["auth","verify"],["auth","recover"],["auth","recover","complete"],["auth","connect"],["auth","mfa"],["auth","mfa","status"],["auth","mfa","setup"],["auth","mfa","verify"],["auth","mfa","recovery-codes"],["auth","mfa","disable"],["api-key"],["api-key","create"],["api-key","list"],["api-key","revoke"],["mcp"],["mcp","setup"],["mcp","status"],["mcp","verify"],["mcp","repair"],["mcp","migrate"],["mcp","disconnect"],["backend"],["backend","status"],["backend","cloud"],["backend","local"],["status"],["doctor"],["search"],["find"],["featured"],["trending"],["show"],["trust"],["recommend"],["categories"],["compare"],["install"],["install","status"],["installed"],["owned"],["export"],["add-review"],["show-reviews"],["add-issue"],["show-issues"],["purchases"],["purchases","list"],["purchases","invoice"],["purchases","status"],["purchases","refund-quote"],["purchases","refund"],["purchases","spending"],["validate"],["preview-trigger"],["creator"],["creator","init"],["creator","create"],["creator","sessions"],["creator","resume"],["creator","inspect"],["creator","answer"],["creator","resources"],["creator","resource-decide"],["creator","tool-contract"],["creator","draft"],["creator","validate"],["creator","eval"],["creator","improve"],["creator","revise"],["creator","materialize"],["creator","finalize"],["creator","rules"],["creator","submissions"],["creator","spaces"],["creator","spaces","buy"],["creator","status"],["creator","source"],["creator","source","prepare"],["creator","source","publish-request"],["creator","source","release-status"],["creator","submit"],["creator","submit-version"],["creator","check-slug"],["creator","rename"],["creator","pricing"],["creator","delist"],["creator","relist"],["creator","update-listing"],["creator","visibility"],["creator","security-report"],["creator","rescan-security"],["creator","provenance"],["creator","claim"],["creator","verify"],["creator","dispute"],["creator","issues"],["creator","update-issue"],["creator","reviews"],["creator","moderate-review"],["creator","analytics"],["creator","earnings"],["creator","payout-profile"],["creator","payout-link"],["creator","payouts"],["creator","withdraw"],["source"],["source","connection"],["source","connection","start"],["source","connection","status"],["source","connection","complete"],["source","connection","cancel"],["source","connection","revoke"],["source","reference"],["source","reference","resolve"],["approval"],["approval","request"],["approval","request","status"],["approval","request","complete"],["enterprise"],["enterprise","accept-invite"],["enterprise","checkout"],["enterprise","install-authorize"],["enterprise","list"],["enterprise","member"],["enterprise","member","remove"],["enterprise","member","role"],["enterprise","members"],["enterprise","rename"],["enterprise","primary-admin"],["enterprise","primary-admin","transfer"],["enterprise","primary-admin","status"],["enterprise","primary-admin","accept"],["enterprise","primary-admin","cancel"],["enterprise","seats"],["enterprise","seats","add"],["enterprise","invite"],["enterprise","invites"],["enterprise","revoke-invite"],["enterprise","resend-invite"],["enterprise","workspace-member"],["enterprise","workspace-member","list"],["enterprise","workspace-member","add"],["enterprise","workspace-member","remove"],["enterprise","workspace"],["enterprise","workspace","create"],["enterprise","workspace","rename"],["enterprise","workspace","update"],["enterprise","workspace","archive"],["enterprise","workspaces"],["enterprise","skill"],["enterprise","skill","entitlements"],["enterprise","skill","quote"],["enterprise","skill","buy"],["workspace"],["workspace","list"],["workspace","current"],["workspace","select"],["workspace","request"],["workspace","approve"],["workspace","reject"],["workspace","skills"],["workspace","guide"],["workspaces"],["guardian"],["guardian","check"],["guardian","incident"],["guardian","enable"],["guardian","disable"],["guardian","enable-warnings-only"],["guardian","status"],["guardian","hook"],["guardian","hook","install"],["guardian","hook","status"],["guardian","launch"],["guardian","exec"],["agents"],["agents","list"],["import"],["sync"],["restore"],["check"],["update"],["remove"],["identity"],["identity","providers"],["identity","start"],["identity","continue"],["identity","status"],["identity","complete"],["identity","list"],["identity","unlink"],["library"],["buy"]],Iee=1+gN.length+hN.length;var So="0.2.14";var Pee="skills-layer-cli-event-v1";function vN(e){let t=0,n=e.now??(()=>new Date().toISOString());return(r,i)=>{let o=Ei(i.summary,"summary",512),s=i.redactedDetail===void 0?void 0:Ei(i.redactedDetail,"redacted detail",2048),a=i.next?.map(u=>({id:Ei(u.id,"next-action ID",128),kind:u.kind,label:Ei(u.label,"next-action label",512),...u.command===void 0?{}:{command:{executable:u.command.executable,args:u.command.args.map(d=>Ei(d,"next-action argument",1024))}},...u.url===void 0?{}:{url:yN(u.url)},safeToAutoRun:u.safeToAutoRun,requiresHuman:u.requiresHuman,...u.rationale===void 0?{}:{rationale:Ei(u.rationale,"next-action rationale",1024)},safety:u.safety})),l=i.links?.map(u=>{let d=yN(u.url);return{label:Ei(u.label,"link label",512),url:d}}),c=i.data===void 0?void 0:iI(i.data);return t+=1,{schemaVersion:Pee,operationId:H(e.operationId),sequence:t,timestamp:n(),type:r,command:{name:H(e.command.name)},...i,summary:o,...s===void 0?{}:{redactedDetail:s},...a===void 0?{}:{next:a},...l===void 0?{}:{links:l},...c===void 0?{}:{data:c}}}}function yN(e){let t=Ei(e,"link URL",2048);if(!/^https?:\/\//u.test(t))throw new Error("CLI event links must use http or https URLs.");return t}function Ei(e,t,n){let r=H(e);if(r.length>n)throw new Error(`CLI event ${t} exceeds ${n} characters.`);return r}function iI(e,t=""){return/^(?:accessToken|apiKey|authorization|clientSecret|handoffCode|password|refreshToken|secret)$/iu.test(t)?"[redacted-secret]":typeof e=="string"?H(e):Array.isArray(e)?e.map(n=>iI(n)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,iI(r,n)])):e}var Aee=["human","json","stream-json"],kN=["auto","always","never"],Ree=["auto","modern","classic"],Eee=["concise","standard","full"];function wN(e){let t=[],n={},r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(r){t.push(o);continue}if(o==="--"){r=!0,t.push(o);continue}let[s,a]=$ee(o);if(s==="--output-format"){let[l,c]=ku(s,a,e[i+1],Aee);n.outputFormat=l,i+=c}else if(s==="--color"){let[l,c]=ku(s,a,e[i+1],kN);n.color=l,i+=c}else if(s==="--motion"){let[l,c]=ku(s,a,e[i+1],kN);n.motion=l,i+=c}else if(s==="--ui"){let[l,c]=ku(s,a,e[i+1],Ree);n.ui=l,i+=c}else if(s==="--detail"){let[l,c]=ku(s,a,e[i+1],Eee);n.detail=l,i+=c}else o==="--no-color"?n.color="never":o==="--no-motion"?n.motion="never":o==="--screen-reader"?n.screenReader=!0:o==="--no-interactive"?n.interactive=!1:o==="--ascii"?n.unicode=!1:t.push(o)}return{args:t,options:n}}function bN(e,t,n){let r=e.outputFormat??"human",i=e.screenReader===!0,o=Lg(t.CI),s=t.TERM==="dumb",a=n.stdinIsTty&&n.stdoutIsTty&&n.stderrIsTty,l=e.ui!=="classic",c=e.ui==="classic",u=e.detail??(r==="human"?"concise":"standard"),d=a&&!o&&!s&&l&&!i&&e.interactive!==!1,p=d&&e.motion!=="never",m=d&&p,h=!i&&e.color!=="never"&&(e.color==="always"||!Lg(t.NO_COLOR)&&!c&&(Lg(t.FORCE_COLOR)||!o&&!s&&n.stdoutIsTty)),g=e.unicode!==!1&&!Lg(t.NO_UNICODE)&&!s;return r==="json"?{kind:"json-final",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:r==="stream-json"?{kind:"json-stream",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:{kind:m?"human-interactive":"human-static",color:h,motion:p,interactive:m,unicode:g,screenReader:i,classic:c,detail:u}}function $ee(e){let t=e.indexOf("=");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function ku(e,t,n,r){let i=t??n;if(i===void 0||i.startsWith("--")||!r.includes(i))throw new Error(`${e} expects one of: ${r.join(", ")}.`);return[i,t===void 0?1:0]}function Lg(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}var _N=()=>null;var xo=88,Dee=/(?:^|_)(?:blocked|cancelled|canceled|rejected|denied|expired|invalid|not_found|conflict|missing_required_argument)(?:$|_)/u,Tee=/(?:^|_)(?:required|requires_action|warning|unverified|completion_pending)(?:$|_)/u,Oee=/(?:^|_)(?:argument|field|input|parameter|protocol|value)_required(?:$|_)/u,Lee=/(?:^|_)(?:failed|failure|internal_error|network_error|service_unavailable|timed_out|timeout)(?:$|_)/u,jee=/\b(?:required information is missing|unknown (?:command|option|flag)|invalid|already used|not found|blocked|cancelled|canceled|rejected|denied|expired|missing|not supported|could not be read|cannot write)\b/iu,Nee=/\b(?:action|approval|authentication|checkout|confirmation|consent|human action|login|mfa|payment|purchase|registration|second factor|secure account connection|sign in|source connection|verification|workspace approval)\b[^.\n]*\b(?:required|needed|must be completed)\b|\b(?:complete|confirm|continue)\b[^.\n]*\b(?:browser|cli|terminal)\b/iu,Fee=/\b(?:failed|failure|service unavailable|server error|network error|timed out|timeout|could not complete)\b/iu;function xN(e){let t=SN(e.status),n=SN(e.reasonCode),r=[t,n].filter(Boolean);return r.some(i=>Dee.test(i))?"stopped":r.some(i=>Tee.test(i)&&!Oee.test(i))?"required":r.some(i=>Lee.test(i))||e.summary&&oI(e.summary)==="failed"?"failed":e.exitCode!==void 0&&e.exitCode!==0?"stopped":"completed"}function oI(e){let t=Bee(e);return jee.test(t)?"stopped":Nee.test(t)?"required":Fee.test(t)?"failed":"stopped"}function wu(e,t){let n=t?"\u2014":"-",r=e.slice(0,1).toUpperCase()+e.slice(1);return`Skills Layer ${n} Action ${r}`}function SN(e){return H(e??"").trim().toLowerCase().replace(/[^a-z0-9]+/gu,"_")}function Bee(e){return H(e).split(/\n(?:Unchanged|Why|Next|Reference)(?:\s|$)/u,1)[0]}function Co(e){return EN(sr(e)).reduce((t,n)=>t+$N(n),0)}function CN(e,t){return e.split(`
|
|
2021
2021
|
`).flatMap(n=>Uee(n,t))}function jg(e,t,n){let r=H(e),i=H(t),o=n.width-2;if(n.width<12||Co(r)+4>o)return i;let s=n.unicode?{topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502"}:{topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|"},a=`${s.horizontal} ${r} `,l=n.border??(m=>m),c=l(`${s.topLeft}${a}${s.horizontal.repeat(o-Co(a))}${s.topRight}`),u=o-2,d=CN(i,u).map(m=>`${l(s.vertical)} ${aI(m,u)} ${l(s.vertical)}`),p=l(`${s.bottomLeft}${s.horizontal.repeat(o)}${s.bottomRight}`);return[c,...d,p].join(`
|
|
2022
2022
|
`)}function Xe(e,t){return`${H(e)}
|
|
2023
2023
|
${H(t)}`}function Ng(e,t){let n=t?"\u2022":"-";return e.map(r=>`${n} ${H(r)}`).join(`
|
|
@@ -2059,7 +2059,7 @@ ${e.slice(t)}`}function KF(e,t){let n=sr(e);if(qI.test(n)||VI(n))return eh(e);le
|
|
|
2059
2059
|
${r.heading("Next")}
|
|
2060
2060
|
${r.info(r.symbols.active)} ${o}`}function WF(e,t){if(/^\u001B\[[0-9;]*m(?:┌|\+)/u.test(e))return e;let n=e.split(`
|
|
2061
2061
|
`),r=sr(n[0]),i=XF(r);if(!i)return e;let o=an(t),s=QF(i,o);return n.forEach((a,l)=>{if(l===0||l===n.length-1){n[l]=s(a);return}let c=a.slice(0,1),u=a.slice(-1);(c==="\u2502"&&u==="\u2502"||c==="|"&&u==="|")&&(n[l]=`${s(c)}${a.slice(1,-1)}${s(u)}`)}),n.join(`
|
|
2062
|
-
`)}function VI(e){return/^(?:┌─ |\+- )?Skills Layer (?:—|-) Skill Details(?:\s|$)/u.test(e)||/\nUsage:\s*\n/u.test(e)||/^Skills Layer help:/u.test(e)||/^Skills Layer enterprise help(?:\n|$)/u.test(e)||/^skills-layer \d+\.\d+\.\d+\s*$/u.test(e.trim())}function ZF(e,t){if(t.detail==="full"||VI(e))return e;let n=t.detail==="concise"?14:24,r=t.detail==="concise"?6:10,i=[],o=new Set,s=0,a=0;for(let m of e.split(`
|
|
2062
|
+
`)}function VI(e){return/^(?:┌─ |\+- )?Skills Layer (?:—|-) Skill Details(?:\s|$)/u.test(e)||/(?:^|\n)[^\n]*Price reviews \([1-9]\d*\)/u.test(e)||/\nUsage:\s*\n/u.test(e)||/^Skills Layer help:/u.test(e)||/^Skills Layer enterprise help(?:\n|$)/u.test(e)||/^skills-layer \d+\.\d+\.\d+\s*$/u.test(e.trim())}function ZF(e,t){if(t.detail==="full"||VI(e))return e;let n=t.detail==="concise"?14:24,r=t.detail==="concise"?6:10,i=[],o=new Set,s=0,a=0;for(let m of e.split(`
|
|
2063
2063
|
`)){let h=/^(?<identity>[a-z0-9_-]+ \[[^\]]+\])(?:\s+(?:project|global)=.*)?$/iu.exec(m.trim())?.groups?.identity;if(h&&(s+=1,s>r)){a+=1;continue}let g=h??m,y=g.trim(),v=h!==void 0||g===g.trimStart();y&&v&&o.has(y)||(y&&v&&o.add(y),i.push(g))}if(a>0){let m=i.findIndex(g=>/^Next:?\s*$/iu.test(g.trim())),h=`\u2026 ${a} more agents hidden; rerun with --detail full.`;i.splice(m>=0?m:i.length,0,h,"")}if(i.length<=n)return i.join(`
|
|
2064
2064
|
`);let l=i.findIndex(m=>/^Next:?\s*$/iu.test(m.trim())),c=l>=0?i.slice(l):[],u=c.length>0?Math.min(c.length,5):0,d=n-u-2,p=i.length-d-u;return[...i.slice(0,d),"",`\u2026 ${p} lower-priority lines hidden; rerun with --detail full.`,...c.slice(0,u)].join(`
|
|
2065
2065
|
`)}function JF(e){let t=/^Next:\s*(?<next>.+)$/imu.exec(e)?.groups?.next?.trim();if(t)return t;let n=/`(?<command>skills-layer [^`]+)`/u.exec(e)?.groups?.command?.trim();if(n)return n;let r=/^(?<command>[a-z][a-z0-9 -]*?) requires (?:an? )?<(?<argument>[^>]+)>/iu.exec(e)?.groups;if(r)return`skills-layer ${r.command.trim()} <${r.argument.trim()}>`}function YF(e,t){let r=/(?:requires|unknown (?:flag|command)|must be|expects one of|invalid)/iu.test(e)?"No changes were made because validation stopped the command.":"No additional change is claimed; check command status before retrying.";return[e,"","Unchanged",` ${r}`,"","Next",` ${t}`].join(`
|
|
@@ -2096,7 +2096,7 @@ Did you mean:
|
|
|
2096
2096
|
|
|
2097
2097
|
Next: ${r.replace(/^Run /u,"run ")}`,t,"unknown_command")}function ure(e){let t=e.trim().toLowerCase(),n={purchase:"buy",validation:"validate",details:"show","security-report":"trust"};if(n[t])return n[t];let r=[...yh].filter(s=>!s.includes(" ")).map(s=>({candidate:s,distance:dre(t,s)})).sort((s,a)=>s.distance-a.distance||s.candidate.localeCompare(a.candidate)),i=r[0],o=r[1];return i&&i.distance<=2&&i.distance<(o?.distance??Number.POSITIVE_INFINITY)?i.candidate:void 0}function dre(e,t){let n=Array.from({length:t.length+1},(r,i)=>i);for(let r=1;r<=e.length;r+=1){let i=[r];for(let o=1;o<=t.length;o+=1)i[o]=Math.min((i[o-1]??0)+1,(n[o]??0)+1,(n[o-1]??0)+(e[r-1]===t[o-1]?0:1));n.splice(0,n.length,...i)}return n[t.length]??t.length}function Lo(e,t=!1){let n=t?yu:Eg;return`${Ag(e)}
|
|
2098
2098
|
|
|
2099
|
-
${n}`}function iP(e){let t={json:e.includes("--json"),help:!1,dryRun:!1,list:!1,all:!1,deep:!1,verbose:!1,showUrl:!1,noOpen:!1,confirmed:!1,allowUnmanagedOnce:!1,discloseSource:!1,shouldTrigger:[],shouldNotTrigger:[],paraphrase:[],grantJson:[],findingCode:[],acceptCapability:[],approvalRequestId:[]},n=[];for(let r=0;r<e.length;r+=1){let i=e[r];if(!i)continue;if(i==="--"){n.push(...e.slice(r+1));break}if(i==="-h"){t.help=!0;continue}if(!i.startsWith("--")){n.push(i);continue}let o=i.slice(2);if(o!=="install"&&!IB.has(o)&&!PB.has(o)&&!AB.has(o)&&!rP.has(o))return{flags:t,positionals:n,error:`Unknown flag --${o}.`};if(IB.has(o)){let a=oP(o);o==="confirm"||o==="yes"?t.confirmed=!0:t[a]=!0;continue}let s=e[r+1];if(!s||s.startsWith("--")){if(o==="install"){t.install="";continue}return{flags:t,positionals:n,error:`Flag --${o} requires a value.`}}if(PB.has(o)){let a=pre(e,r);if(!a.value)return{flags:t,positionals:n,error:`Flag --${o} requires a value.`};t[oP(o)]=a.value,r=a.nextIndex;continue}if(AB.has(o)||rP.has(o)){let a=oP(o);if(o==="scope"){let l=Array.isArray(t.scopeValues)?t.scopeValues:[];l.push(s),t.scopeValues=l,t.scope=s}else if(rP.has(o)){let l=Array.isArray(t[a])?t[a]:[];l.push(s),t[a]=l}else t[a]=s;r+=1;continue}return{flags:t,positionals:n,error:`Unknown flag --${o}.`}}return{flags:t,positionals:n}}function pre(e,t){let n=[],r=t;for(let i=t+1;i<e.length;i+=1){let o=e[i];if(!o||o.startsWith("--"))break;n.push(o),r=i}return{value:n.length>0?n.join(" "):null,nextIndex:r}}function oP(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function Tu(e,t){let n=fre(t.env,t.platform),[r,i]=await Promise.all([fce(n.configPath,t),ke(n.backendPreferencePath)]),o=dr(k(e.baseUrl)??Re(t.env.SKILLS_LAYER_BASE_URL)??Re(i?.preferredBaseUrl)??Re(r?.baseUrl)??YP);try{tl(o)}catch{throw new Z(400,"Invalid backend URL. Use HTTPS, or HTTP for loopback development only.",{reasonCode:"invalid_base_url",baseUrl:o.replace(/(\/\/)[^/]*@/u,"$1<redacted>@"),nextAction:"backend",nextStep:"Use an HTTPS backend URL without credentials, query parameters, or fragments."})}let s=k(e.apiKey)??Re(t.env.SKILLS_LAYER_API_KEY),a=Re(r?.apiKey),l=Re(r?.baseUrl),c=!l||Yu(l,o),u=s??(c?a:void 0),d=!s&&a&&l&&!c?`Your saved login belongs to ${dr(l)}, but the selected backend is ${o}. Run \`skills-layer backend --base-url ${dr(l)}\` to use that login, or run \`skills-layer login\` for ${o}.`:void 0;return{...t,paths:n,config:r,baseUrl:o,apiKey:u,authBlockedMessage:d}}function fre(e,t){let n=t==="win32"?ot:Lt,r=pN(e,t);return{stateDir:r,configPath:n.join(r,"config.json"),backendPreferencePath:n.join(r,"backend-preference.json"),installTargetPreferencePath:n.join(r,"install-target-preference.json"),installsPath:n.join(r,"installs.json"),importsPath:n.join(r,"imports.json"),mcpConfigPath:n.join(r,"mcp.json"),mcpPreferencePath:n.join(r,"mcp-preference.json"),pendingRevocationsPath:n.join(r,"pending-revocations.json"),bundlesDir:n.join(r,"bundles"),incidentsDir:n.join(r,"incidents")}}async function mre(e,t,n){if(e[0]!=="list")return R(`Unknown agents command "${e[0]??""}".`,t.json);let r=Qe(n.env,n.platform,n.cwd).map(i=>({id:i.id,displayName:i.displayName,capabilities:i.capabilities,projectSkillsPath:i.targets.projectSkillsPath,globalSkillsPath:i.targets.globalSkillsPath}));return A({status:"ok",results:r},`Found ${r.length} supported agent targets.`,t.json,n)}async function gre(e,t,n){let r=e[0],i=k(t.baseUrl);if(!r&&i||r==="cloud"||r==="local"){let l=dr(i??(r==="local"?nre:YP)),c=Eie(l,t);if(c)return c;if(!t.skipProbe){let m=await FA(l,n.fetchFn);if(m!=="ok")return x({status:"error",reasonCode:m,unchanged:!0,nextStep:"Check the backend address, or use --skip-probe for offline configuration."},m==="backend_unreachable"?"Backend could not be reached.":"The address did not identify a Skills Layer API.",t.json,m)}let u=Dt(l),d=n.config?.baseUrl??null,p=!n.config?.baseUrl||Yu(n.config.baseUrl,l);return await Ve(n.paths.backendPreferencePath,{version:JP,preferredBaseUrl:l,savedAt:n.now()}),A({status:"updated",selectedBackend:u,selectedBaseUrl:l,savedLoginBaseUrl:d,loginMatchesSelectedBackend:p,loggedIn:!!n.apiKey&&p,...p?{}:{warning:`Saved login belongs to ${d}; selected backend is ${l}.`}},p?`Backend set to ${u}.`:`Backend set to ${u}. Saved login is for ${d}.`,t.json,n)}if(r&&r!=="status")return R(`Unknown backend command "${r}".`,t.json);let o=Dt(n.baseUrl),s=!n.config?.baseUrl||Yu(n.config.baseUrl,n.baseUrl),a=!!n.apiKey&&s;return A({status:"ok",selectedBackend:o,selectedBaseUrl:n.baseUrl,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:s,loggedIn:a,email:a?n.config?.email??null:null,role:a?n.config?.role??null:null,identitySource:"cached_at_login"},`Backend: ${n.baseUrl}. Account details are cached from login; run skills-layer whoami to check current access.`,t.json,n)}var $h=[{value:"google",label:"Google",description:"Open browser sign-in and return here"},{value:"github",label:"GitHub",description:"Open browser sign-in and return here"},{value:"gitlab",label:"GitLab",description:"Open browser sign-in and return here"},{value:"microsoft",label:"Microsoft",description:"Open browser sign-in and return here"}];async function Dh(e,t){if(t.nonInteractive||!t.stdoutIsTty)return e.filter(n=>n.value!=="microsoft");try{let n=await D(t,"/api/v1/identity/social/providers");return Array.isArray(n.providers)?e.filter(r=>!Ko(r.value)||n.providers.includes(r.value)):e.filter(r=>r.value!=="microsoft")}catch{return e.filter(n=>n.value!=="microsoft")}}var hre=[...$h,{value:"email",label:"Continue with email",description:"Sign in or create an account with an emailed one-time code"},{value:"api_key",label:"API key (advanced)",description:"Paste an existing Skills Layer login key"}],yre=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...$h],vre=[{value:"email",label:"Email code",description:"Verify account ownership with an emailed one-time code"}];async function UM(e,t){let n=k(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",await Dh(yre,t))}catch{return R("register requires --method when interactive selection is unavailable. Try `skills-layer register --method email --email you@example.com`, `skills-layer register --method google`, `skills-layer register --method github` or `skills-layer register --method gitlab`.",!1)}let r=Mn("register","method",n,kie,e,"invalid_method");if(r)return r;if(n==="email"){let a=k(e.email);if(!a&&!e.json)try{a=await t.promptText("Enter your email address: ")}catch{return R("register --method email requires --email when interactive prompts are unavailable.",!1)}a=T(a,"register requires --email.");let l=await D(t,"/api/v1/register",{method:"POST",headers:V(),body:JSON.stringify({method:n,email:a})});if(e.json){let u=l.status==="already_registered"?WP(l):Nt({...l,nextCommand:`skills-layer auth verify --email ${a} --code <code> --json`,nextAction:"auth.verify"}),d=l.status==="already_registered"?`${a} is already registered.`:`Registration started for ${a}.`;return A(u,d,e.json,t)}if(l.status==="already_registered")return A(WP(l),`${a} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,!1,t);let c;try{c=await t.promptText(`Enter the verification code sent to ${a} (check spam/junk folder if missing): `)}catch{return A(Nt(l),`Registration started for ${a}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${a} --code <code>\`.`,!1,t)}return await vA(a,c,e,t,`Verified ${a}.`)}if(!Ko(n))return R("register --method must be email, google, github, or gitlab.",e.json);let i=Ho(),o=await wA({flags:e,backend:t,provider:n,mode:"register",credentialHandoff:i});if(fe(o))return o;let s=await D(t,"/api/v1/identity/social/start",{method:"POST",headers:V(),body:JSON.stringify({provider:n,mode:"register",createAccount:e.createAccount===!0,handoffCodeHash:i.authorizationCodeHash,handoffCodeChallenge:i.codeChallenge})});return await jh(n,s,i,e,t,"register",void 0,o)}async function zM(e,t){if(e.withMcp&&e.noMcp)return R("login cannot combine --with-mcp and --no-mcp.",e.json);let n=k(e.apiKey);if(n){let l=await Vu(t,n,{notifyLogin:!0}),c=await wh(e,{...t,config:l,apiKey:n});if(fe(c))return c;let u=await xP(e,{...t,config:l,apiKey:n});if(fe(u))return u;let d=u.data?.status==="mcp_not_configured";return A(Nt(CP({status:d?"partial_success":"verified",...l,loggedIn:!0,...c.data?{workingMode:c.data}:{},...u.data?{mcp:u.data}:{},...d?{warnings:[u.data]}:{}},u.data)),[`Logged in as ${l.email}.`,c.message??"",u.message??""].filter(Boolean).join(" "),e.json,t)}let r=k(e.method);if(!r&&!e.json)try{let l=await t.promptSelect("Choose how to sign in:",await Dh(hre,t));r=l==="api_key"?void 0:l}catch{return R("login requires --api-key or --method <email|google|github|gitlab> when interactive selection is unavailable.",!1)}let i=Mn("login","method",r,vie,e,"invalid_method");if(i)return i;if(r){if(r==="email"){let d=k(e.email);!d&&!e.json&&(d=(await t.promptText("Enter your email address: ")).trim()),d=T(d,"login --method email requires --email.");let p=await D(t,"/api/v1/register",{method:"POST",headers:V(),body:JSON.stringify({email:d})}),m=Nt({...p,nextAction:"auth.verify",nextCommand:`skills-layer auth verify --email ${d} --code <code> --json`});if(f(p,"emailDelivery")==="failed")return x({...m,status:"email_delivery_failed",reasonCode:"email_delivery_failed",nextAction:"login.retry",nextStep:"Retry email sign-in after the delivery service recovers, or choose a connected social provider."},"The email code could not be delivered. Retry later or choose another sign-in method.",e.json,"email_delivery_failed");if(f(p,"status")==="already_registered")return R("The backend did not prepare an email sign-in code. Retry later or choose another sign-in method.",e.json);if(e.json)return A(m,`Email sign-in started for ${d}.`,!0,t);let h="";try{h=(await t.promptText("Enter the email code if you received one, or press Enter to stop: ")).trim()}catch{return A(m,`Email sign-in started for ${d}. Check your email (including spam/junk folder), then run \`skills-layer auth verify --email ${d} --code <code>\` when the code arrives.`,!1,t)}return h?await vA(d,h,e,t,`Verified ${d}.`):A(m,`Email sign-in started for ${d}. No code was entered, so nothing else was changed. Run \`skills-layer auth verify --email ${d} --code <code>\` when ready.`,!1,t)}if(!Ko(r))return R("login --method must be email, google, github, or gitlab.",e.json);let l=Ho(),c=await wA({flags:e,backend:t,provider:r,mode:"login",credentialHandoff:l});if(fe(c))return c;let u=await D(t,"/api/v1/identity/social/start",{method:"POST",headers:V(),body:JSON.stringify({provider:r,mode:"login",handoffCodeHash:l.authorizationCodeHash,handoffCodeChallenge:l.codeChallenge})});return await jh(r,u,l,e,t,"login",void 0,c)}if(!e.json)try{n=(await t.promptSecret("Enter your Skills Layer API key: ")).trim()}catch{return R("login requires an API key.",e.json)}if(!n)return R("login requires --api-key or --method <email|google|github|gitlab>.",e.json);let o=await Vu(t,n,{notifyLogin:!0}),s=await wh(e,{...t,config:o,apiKey:n});if(fe(s))return s;let a=await xP(e,{...t,config:o,apiKey:n});return fe(a)?a:A(Nt(CP({status:"verified",...o,...s.data?{workingMode:s.data}:{},...a.data?{mcp:a.data}:{}},a.data)),[`Logged in as ${o.email}.`,s.message??"",a.message??""].filter(Boolean).join(" "),e.json,t)}async function qM(e,t){let n=!1,r=!1,i=await ke(t.paths.mcpConfigPath),o=i?f(i,"keyId"):void 0,s=Re(t.config?.apiKey)??t.apiKey,a=dr(Re(t.config?.baseUrl)??t.baseUrl);if(s){try{await D({...t,baseUrl:a,apiKey:s},"/api/v1/me/working-mode",{method:"DELETE",headers:re(s)}),n=!0}catch{n=!1}try{await D({...t,baseUrl:a,apiKey:s},"/api/v1/me/session/revoke",{method:"POST",headers:V(s),body:JSON.stringify({includeCurrent:!0,revokeAllMcp:!0,humanKeyIds:[],mcpKeyIds:o?[o]:[]})}),r=!0}catch{r=!1}}let l=O2(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),c=await Promise.allSettled([l,kre(t),l.then(()=>We(t.paths.configPath,{force:!0}))]),u=c.every(m=>m.status==="fulfilled");if(!u)return x({status:"logout_incomplete",reasonCode:"local_cleanup_incomplete",serverCredentialsRevoked:r,localCleanupComplete:!1,nextAction:"logout",nextStep:"Unlock the OS credential store and retry logout. Local references were retained for cleanup."},"Server revocation was attempted, but local cleanup is incomplete.",e.json,"local_cleanup_incomplete");let d=!!s&&!r,p=d&&(t.config?.userId&&(t.config.sessionCredentialId||o))?await xA(t,{baseUrl:a,userId:t.config.userId,humanKeyIds:t.config.sessionCredentialId?[t.config.sessionCredentialId]:[],mcpKeyIds:o?[o]:[],revokeAllMcp:!0,revokeAdminMcp:!0,createdAt:t.now()}):!1;return A({status:s?"logged_out":"not_logged_in",serverWorkingModeCleared:n,serverCredentialsRevoked:r,revocationPending:d,...d?{pendingRecorded:p}:{},localCleanupComplete:u,warnings:u?[]:["Some local cleanup failed. Retry logout to finish clearing local state."],mcpAuthCleared:c[1].status==="fulfilled"},d?p?"Logged out locally. Server revocation is pending and will retry after the same account authenticates again.":"Logged out locally, but server revocation could not be recorded. Reconnect promptly; credentials remain bounded by expiry.":r?"Logged out. Human and MCP credentials were revoked.":"No saved login; local state cleared.",e.json,t)}async function kre(e){let t=await ke(e.paths.mcpConfigPath);if(!t){await SP(null,e),await We(e.paths.mcpPreferencePath,{force:!0});return}let n=t?f(t,"baseUrl")??e.baseUrl:e.baseUrl,r=t?f(t,"clientId")??"codex":"codex",i=es({baseUrl:n,mcpUrl:t?f(t,"mcpUrl")??`${n}/mcp`:`${n}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:t?f(t,"environment")??Dt(n):Dt(n),now:e.now(),env:e.env,platform:e.platform,cwd:e.cwd,stateDir:e.paths.stateDir,mcpConfigPath:e.paths.mcpConfigPath,nodePath:process.execPath}),o=t&&Array.isArray(t.clientIds)?t.clientIds.filter(a=>typeof a=="string"):t?[r]:[];if((await Promise.allSettled([SP(t,e),...i.targets.filter(a=>o.includes(a.agentId)).map(a=>a.disconnect?.()),ay(i.bridgePath),ly(i.brokerPath,i.brokerSocketPath,i.brokerLockPath),We(e.paths.mcpPreferencePath,{force:!0})])).some(a=>a.status==="rejected"))throw new Error("MCP local cleanup is incomplete; retry logout.");await We(e.paths.mcpConfigPath,{force:!0})}async function wre(e,t,n){let r=e[0]??"show";if(r==="show")return await me("/api/v1/profile",t,n,"Editable profile loaded.",{authenticated:!0});if(r==="update"){let i=await bre(t,n);if(fe(i))return i;let o=await D(n,"/api/v1/profile",{method:"PATCH",headers:V(n.apiKey),body:JSON.stringify(i)});return A(o,"Profile updated.",t.json,n)}return R(`Unknown profile command "${r}".`,t.json)}async function bre(e,t){let n=Ft(e,["displayName","bio","company"]);for(let r of["displayName","bio","company"])if(e[`clear${r[0].toUpperCase()}${r.slice(1)}`]){let i=r.replace(/[A-Z]/gu,o=>`-${o.toLowerCase()}`);if(n[r]!==void 0)return x({reasonCode:"conflicting_flags",unchanged:!0},`Choose either --${i} or --clear-${i}.`,e.json,"conflicting_flags");n[r]=null}if(Object.keys(n).length>0)return n;if(e.json)return R("profile update requires at least one of --display-name, --bio, or --company.",!0);try{let r=await t.promptText("Display name (leave blank to keep unchanged): "),i=await t.promptText("Bio (leave blank to keep unchanged): "),o=await t.promptText("Company (leave blank to keep unchanged): "),s=ie({displayName:r||void 0,bio:i||void 0,company:o||void 0});return Object.keys(s).length===0?R("No profile changes entered.",!1):s}catch{return R("profile update requires at least one of --display-name, --bio, or --company.",!1)}}async function _re(e,t,n){let r=e[0];if(r==="register")return await UM({...t,method:"email"},n);if(r==="verify"){let i=T(t.email,"auth verify requires --email."),o=T(t.code,"auth verify requires --code.");return await vA(i,o,t,n,`Verified ${i}.`)}return r==="recover"?await Cre(e.slice(1),t,n):r==="connect"?await Ire(t,n):r==="mfa"?await Pre(e.slice(1),t,n):r==="login"?await zM(t,n):r==="logout"?await qM(t,n):r==="status"?Sre(t,n):r==="repair"?await xre(t,n):R(`Unknown auth command "${r??""}".`,t.json)}function Sre(e,t){let n=t.config?.baseUrl?dr(t.config.baseUrl):null,r=!!(t.apiKey&&n&&Yu(n,t.baseUrl));return A({status:"auth_status",selectedBackend:Dt(t.baseUrl),selectedBaseUrl:t.baseUrl,loggedIn:r,requiresLogin:!r,...t.config?.email?{savedLogin:{baseUrl:n,email:t.config.email,role:t.config.role??null,roles:t.config.roles??[],savedAt:t.config.savedAt??null,...t.config.credentialStorage?{credentialStorage:t.config.credentialStorage}:{},matchesSelectedBackend:r}}:{}},r&&t.config?.email?`Logged in as ${t.config.email}.`:t.config?.baseUrl?`Saved login targets ${n}; selected backend is ${t.baseUrl}. Run \`skills-layer auth repair\` or \`skills-layer login\`.`:"Not logged in. Run `skills-layer login`.",e.json,t)}async function xre(e,t){if(!t.config?.baseUrl||!t.config.apiKey||!t.config.email||!t.config.role||!t.config.savedAt)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login` to create a saved session, then use `skills-layer auth repair` only if backend/session metadata drifts."},"No saved Skills Layer login was found to repair. Run `skills-layer login`.",e.json,"login_required");let n=dr(t.config.baseUrl);return await Ve(t.paths.backendPreferencePath,{version:JP,preferredBaseUrl:n,savedAt:t.now()}),await CA(t.paths.configPath,{...t.config,baseUrl:n,savedAt:t.now()},t),A({status:"auth_repaired",baseUrl:n,loggedIn:!0,email:t.config.email,role:t.config.role,credentialStorage:t.config.credentialStorage??"local_file_locked"},`Auth repaired for ${t.config.email}. Backend preference now matches ${n}.`,e.json,t)}async function Cre(e,t,n){let r=e[0]??k(t.method);if(!r&&!t.json)try{r=await n.promptSelect("Choose how to recover access:",vre)}catch{return R("auth recover requires --method email when interactive selection is unavailable.",!1)}if(r??="email",Ko(r))return x({status:"unsupported_auth_journey",reasonCode:"unsupported_auth_journey",provider:r,nextAction:"account.connect",nextStep:`Run \`skills-layer auth connect --provider ${r}\` after signing in.`},`Social identities are connected, not used for account recovery. Sign in, then run \`skills-layer auth connect --provider ${r}\`.`,t.json,"unsupported_auth_journey");if(r!=="complete"&&r!=="email")return R("auth recover --method must be email.",t.json);let i=k(t.email);if(r==="complete"){if(!i&&!t.json)try{i=await n.promptText("Enter your email address: ")}catch{return R("auth recover complete requires --email when interactive prompts are unavailable.",!1)}i=T(i,"auth recover complete requires --email.");let l=k(t.code);if(!l&&!t.json)try{l=await n.promptText("Enter the recovery code: ")}catch{return R("auth recover complete requires --code when interactive prompts are unavailable.",!1)}return l=T(l,"auth recover complete requires --code."),await EB(i,l,t,n)}if(!i&&!t.json)try{i=await n.promptText("Enter your email address: ")}catch{return R("auth recover --method email requires --email when interactive prompts are unavailable.",!1)}i=T(i,"auth recover --method email requires --email.");let o=await D(n,"/api/v1/identity/recover/start",{method:"POST",headers:V(),body:JSON.stringify({email:i,method:r})}),s=WP(o);if(t.json)return A({...s,nextCommand:`skills-layer auth recover complete --email ${i} --code <code>`,nextAction:"auth.recover.complete",nextStep:"Check your email and complete recovery with the emailed code."},"Recovery started.",!0,n);let a="";try{a=(await n.promptText("Enter the recovery code if you received one, or press Enter to stop: ")).trim()}catch{return A(s,`If this email can continue, instructions have been sent. Check your inbox and spam folder. When you have a code, run \`skills-layer auth recover complete --email ${i} --code <code>\`.`,!1,n)}return a?await EB(i,a,t,n):A(s,`If this email can continue, instructions have been sent. When you have a code, run \`skills-layer auth recover complete --email ${i} --code <code>\`.`,!1,n)}async function Ire(e,t){let n=k(e.provider);if(!n&&!e.json)try{n=await t.promptSelect("Choose an identity to connect:",await Dh($h,t))}catch{return R("auth connect requires --provider when interactive selection is unavailable.",!1)}if(n=T(n,"auth connect requires --provider."),!Ko(n))return R("auth connect --provider must be google, github, or gitlab.",e.json);if(!t.apiKey||t.authBlockedMessage)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login`, then retry the connection."},"Sign in before connecting another login method.",e.json,"login_required");if((await D(t,"/api/v1/identity/mfa/status",{headers:V(t.apiKey,t.authBlockedMessage)})).enabled!==!0){let l=await VM(e,t);return fe(l)?l:A(l,"MFA setup is required before connecting a sign-in method. Complete setup in the browser, then run this command again.",e.json,t)}let i=k(e.mfaCode);if(!i&&!e.json)try{i=await t.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return R("auth connect requires MFA verification. Retry with an interactive terminal.",!1)}if(!i||!/^\d{6}$/u.test(i))return R("auth connect requires a 6-digit --mfa-code when interactive prompts are unavailable.",e.json);let o=await D(t,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({purpose:"identity.connect",code:i})}),s=T(f(o,"stepUpGrant"),"MFA verification did not return a step-up grant."),a=await D(t,"/api/v1/identity/connect/start",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({provider:n,stepUpGrant:s})});return await jh(n,a,void 0,e,t,"connect","/api/v1/identity/connect/status")}async function Pre(e,t,n){let r=e[0]??"status";if(!n.apiKey||n.authBlockedMessage)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login`, then retry the MFA command."},"Sign in before managing MFA.",t.json,"login_required");if(r==="status"){let i=await D(n,"/api/v1/identity/mfa/status",{headers:re(n.apiKey,n.authBlockedMessage)}),o=i.enabled===!1?{...i,nextAction:"account.mfa.setup",nextStep:"Protect this account by running `skills-layer auth mfa setup`."}:i;return A(o,"MFA status loaded.",t.json,n)}if(r==="setup"){let i=await VM(t,n);return fe(i)?i:A(i,"MFA setup started. Complete it in your browser; recovery codes are shown there once.",t.json,n)}if(r==="verify"){let i=T(k(t.purpose),"auth mfa verify requires --purpose."),o=k(t.mfaCode)??k(t.code);if(!o&&!t.json)try{o=await n.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return R("auth mfa verify requires an interactive code or --mfa-code.",!1)}if(!o||!/^\d{6}$/u.test(o))return R("auth mfa verify requires a 6-digit --mfa-code.",t.json);let s=await D(n,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({purpose:i,code:o})});return A(s,`MFA verified for ${i}.`,t.json,n)}if(r==="recovery-codes"){if(k(t.mfaCode)||k(t.code))return R("Do not pass an authenticator code on the command line. Recovery-code regeneration now requires protected browser verification.",t.json);if(t.json)return A({status:"human_action_required",reasonCode:"human_handoff_required",nextAction:"mfa.recovery_codes.browser",nextStep:"Run `skills-layer auth mfa recovery-codes` in an interactive human terminal to open the protected browser flow.",delivery:"browser_only"},"Recovery-code regeneration requires a protected human browser session.",!0,n);let i=await D(n,"/api/v1/identity/mfa/recovery-codes/regenerate",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({})}),o=T(f(i,"recoveryCodesUrl"),"Recovery-code regeneration did not return a secure browser handoff."),s=T(f(i,"operationId"),"Recovery-code regeneration did not return a secure operation identifier.");!t.noOpen&&await n.openUrl(o)||n.emitInfo(`Open this secure recovery-code link in your browser:
|
|
2099
|
+
${n}`}function iP(e){let t={json:e.includes("--json"),help:!1,dryRun:!1,list:!1,all:!1,deep:!1,verbose:!1,showUrl:!1,noOpen:!1,confirmed:!1,allowUnmanagedOnce:!1,discloseSource:!1,shouldTrigger:[],shouldNotTrigger:[],paraphrase:[],grantJson:[],findingCode:[],acceptCapability:[],approvalRequestId:[]},n=[];for(let r=0;r<e.length;r+=1){let i=e[r];if(!i)continue;if(i==="--"){n.push(...e.slice(r+1));break}if(i==="-h"){t.help=!0;continue}if(!i.startsWith("--")){n.push(i);continue}let o=i.slice(2);if(o!=="install"&&!IB.has(o)&&!PB.has(o)&&!AB.has(o)&&!rP.has(o))return{flags:t,positionals:n,error:`Unknown flag --${o}.`};if(IB.has(o)){let a=oP(o);o==="confirm"||o==="yes"?t.confirmed=!0:t[a]=!0;continue}let s=e[r+1];if(!s||s.startsWith("--")){if(o==="install"){t.install="";continue}return{flags:t,positionals:n,error:`Flag --${o} requires a value.`}}if(PB.has(o)){let a=pre(e,r);if(!a.value)return{flags:t,positionals:n,error:`Flag --${o} requires a value.`};t[oP(o)]=a.value,r=a.nextIndex;continue}if(AB.has(o)||rP.has(o)){let a=oP(o);if(o==="scope"){let l=Array.isArray(t.scopeValues)?t.scopeValues:[];l.push(s),t.scopeValues=l,t.scope=s}else if(rP.has(o)){let l=Array.isArray(t[a])?t[a]:[];l.push(s),t[a]=l}else t[a]=s;r+=1;continue}return{flags:t,positionals:n,error:`Unknown flag --${o}.`}}return{flags:t,positionals:n}}function pre(e,t){let n=[],r=t;for(let i=t+1;i<e.length;i+=1){let o=e[i];if(!o||o.startsWith("--"))break;n.push(o),r=i}return{value:n.length>0?n.join(" "):null,nextIndex:r}}function oP(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function Tu(e,t){let n=fre(t.env,t.platform),[r,i]=await Promise.all([fce(n.configPath,t),ke(n.backendPreferencePath)]),o=dr(k(e.baseUrl)??Re(t.env.SKILLS_LAYER_BASE_URL)??Re(i?.preferredBaseUrl)??Re(r?.baseUrl)??YP);try{tl(o)}catch{throw new Z(400,"Invalid backend URL. Use HTTPS, or HTTP for loopback development only.",{reasonCode:"invalid_base_url",baseUrl:o.replace(/(\/\/)[^/]*@/u,"$1<redacted>@"),nextAction:"backend",nextStep:"Use an HTTPS backend URL without credentials, query parameters, or fragments."})}let s=k(e.apiKey)??Re(t.env.SKILLS_LAYER_API_KEY),a=Re(r?.apiKey),l=Re(r?.baseUrl),c=!l||Yu(l,o),u=s??(c?a:void 0),d=!s&&a&&l&&!c?`Your saved login belongs to ${dr(l)}, but the selected backend is ${o}. Run \`skills-layer backend --base-url ${dr(l)}\` to use that login, or run \`skills-layer login\` for ${o}.`:void 0;return{...t,paths:n,config:r,baseUrl:o,apiKey:u,authBlockedMessage:d}}function fre(e,t){let n=t==="win32"?st:Lt,r=pN(e,t);return{stateDir:r,configPath:n.join(r,"config.json"),backendPreferencePath:n.join(r,"backend-preference.json"),installTargetPreferencePath:n.join(r,"install-target-preference.json"),installsPath:n.join(r,"installs.json"),importsPath:n.join(r,"imports.json"),mcpConfigPath:n.join(r,"mcp.json"),mcpPreferencePath:n.join(r,"mcp-preference.json"),pendingRevocationsPath:n.join(r,"pending-revocations.json"),bundlesDir:n.join(r,"bundles"),incidentsDir:n.join(r,"incidents")}}async function mre(e,t,n){if(e[0]!=="list")return R(`Unknown agents command "${e[0]??""}".`,t.json);let r=et(n.env,n.platform,n.cwd).map(i=>({id:i.id,displayName:i.displayName,capabilities:i.capabilities,projectSkillsPath:i.targets.projectSkillsPath,globalSkillsPath:i.targets.globalSkillsPath}));return A({status:"ok",results:r},`Found ${r.length} supported agent targets.`,t.json,n)}async function gre(e,t,n){let r=e[0],i=k(t.baseUrl);if(!r&&i||r==="cloud"||r==="local"){let l=dr(i??(r==="local"?nre:YP)),c=Eie(l,t);if(c)return c;if(!t.skipProbe){let m=await FA(l,n.fetchFn);if(m!=="ok")return x({status:"error",reasonCode:m,unchanged:!0,nextStep:"Check the backend address, or use --skip-probe for offline configuration."},m==="backend_unreachable"?"Backend could not be reached.":"The address did not identify a Skills Layer API.",t.json,m)}let u=Dt(l),d=n.config?.baseUrl??null,p=!n.config?.baseUrl||Yu(n.config.baseUrl,l);return await Ve(n.paths.backendPreferencePath,{version:JP,preferredBaseUrl:l,savedAt:n.now()}),A({status:"updated",selectedBackend:u,selectedBaseUrl:l,savedLoginBaseUrl:d,loginMatchesSelectedBackend:p,loggedIn:!!n.apiKey&&p,...p?{}:{warning:`Saved login belongs to ${d}; selected backend is ${l}.`}},p?`Backend set to ${u}.`:`Backend set to ${u}. Saved login is for ${d}.`,t.json,n)}if(r&&r!=="status")return R(`Unknown backend command "${r}".`,t.json);let o=Dt(n.baseUrl),s=!n.config?.baseUrl||Yu(n.config.baseUrl,n.baseUrl),a=!!n.apiKey&&s;return A({status:"ok",selectedBackend:o,selectedBaseUrl:n.baseUrl,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:s,loggedIn:a,email:a?n.config?.email??null:null,role:a?n.config?.role??null:null,identitySource:"cached_at_login"},`Backend: ${n.baseUrl}. Account details are cached from login; run skills-layer whoami to check current access.`,t.json,n)}var $h=[{value:"google",label:"Google",description:"Open browser sign-in and return here"},{value:"github",label:"GitHub",description:"Open browser sign-in and return here"},{value:"gitlab",label:"GitLab",description:"Open browser sign-in and return here"},{value:"microsoft",label:"Microsoft",description:"Open browser sign-in and return here"}];async function Dh(e,t){if(t.nonInteractive||!t.stdoutIsTty)return e.filter(n=>n.value!=="microsoft");try{let n=await D(t,"/api/v1/identity/social/providers");return Array.isArray(n.providers)?e.filter(r=>!Ko(r.value)||n.providers.includes(r.value)):e.filter(r=>r.value!=="microsoft")}catch{return e.filter(n=>n.value!=="microsoft")}}var hre=[...$h,{value:"email",label:"Continue with email",description:"Sign in or create an account with an emailed one-time code"},{value:"api_key",label:"API key (advanced)",description:"Paste an existing Skills Layer login key"}],yre=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...$h],vre=[{value:"email",label:"Email code",description:"Verify account ownership with an emailed one-time code"}];async function UM(e,t){let n=k(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",await Dh(yre,t))}catch{return R("register requires --method when interactive selection is unavailable. Try `skills-layer register --method email --email you@example.com`, `skills-layer register --method google`, `skills-layer register --method github` or `skills-layer register --method gitlab`.",!1)}let r=Mn("register","method",n,kie,e,"invalid_method");if(r)return r;if(n==="email"){let a=k(e.email);if(!a&&!e.json)try{a=await t.promptText("Enter your email address: ")}catch{return R("register --method email requires --email when interactive prompts are unavailable.",!1)}a=T(a,"register requires --email.");let l=await D(t,"/api/v1/register",{method:"POST",headers:V(),body:JSON.stringify({method:n,email:a})});if(e.json){let u=l.status==="already_registered"?WP(l):Nt({...l,nextCommand:`skills-layer auth verify --email ${a} --code <code> --json`,nextAction:"auth.verify"}),d=l.status==="already_registered"?`${a} is already registered.`:`Registration started for ${a}.`;return A(u,d,e.json,t)}if(l.status==="already_registered")return A(WP(l),`${a} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,!1,t);let c;try{c=await t.promptText(`Enter the verification code sent to ${a} (check spam/junk folder if missing): `)}catch{return A(Nt(l),`Registration started for ${a}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${a} --code <code>\`.`,!1,t)}return await vA(a,c,e,t,`Verified ${a}.`)}if(!Ko(n))return R("register --method must be email, google, github, or gitlab.",e.json);let i=Ho(),o=await wA({flags:e,backend:t,provider:n,mode:"register",credentialHandoff:i});if(fe(o))return o;let s=await D(t,"/api/v1/identity/social/start",{method:"POST",headers:V(),body:JSON.stringify({provider:n,mode:"register",createAccount:e.createAccount===!0,handoffCodeHash:i.authorizationCodeHash,handoffCodeChallenge:i.codeChallenge})});return await jh(n,s,i,e,t,"register",void 0,o)}async function zM(e,t){if(e.withMcp&&e.noMcp)return R("login cannot combine --with-mcp and --no-mcp.",e.json);let n=k(e.apiKey);if(n){let l=await Vu(t,n,{notifyLogin:!0}),c=await wh(e,{...t,config:l,apiKey:n});if(fe(c))return c;let u=await xP(e,{...t,config:l,apiKey:n});if(fe(u))return u;let d=u.data?.status==="mcp_not_configured";return A(Nt(CP({status:d?"partial_success":"verified",...l,loggedIn:!0,...c.data?{workingMode:c.data}:{},...u.data?{mcp:u.data}:{},...d?{warnings:[u.data]}:{}},u.data)),[`Logged in as ${l.email}.`,c.message??"",u.message??""].filter(Boolean).join(" "),e.json,t)}let r=k(e.method);if(!r&&!e.json)try{let l=await t.promptSelect("Choose how to sign in:",await Dh(hre,t));r=l==="api_key"?void 0:l}catch{return R("login requires --api-key or --method <email|google|github|gitlab> when interactive selection is unavailable.",!1)}let i=Mn("login","method",r,vie,e,"invalid_method");if(i)return i;if(r){if(r==="email"){let d=k(e.email);!d&&!e.json&&(d=(await t.promptText("Enter your email address: ")).trim()),d=T(d,"login --method email requires --email.");let p=await D(t,"/api/v1/register",{method:"POST",headers:V(),body:JSON.stringify({email:d})}),m=Nt({...p,nextAction:"auth.verify",nextCommand:`skills-layer auth verify --email ${d} --code <code> --json`});if(f(p,"emailDelivery")==="failed")return x({...m,status:"email_delivery_failed",reasonCode:"email_delivery_failed",nextAction:"login.retry",nextStep:"Retry email sign-in after the delivery service recovers, or choose a connected social provider."},"The email code could not be delivered. Retry later or choose another sign-in method.",e.json,"email_delivery_failed");if(f(p,"status")==="already_registered")return R("The backend did not prepare an email sign-in code. Retry later or choose another sign-in method.",e.json);if(e.json)return A(m,`Email sign-in started for ${d}.`,!0,t);let h="";try{h=(await t.promptText("Enter the email code if you received one, or press Enter to stop: ")).trim()}catch{return A(m,`Email sign-in started for ${d}. Check your email (including spam/junk folder), then run \`skills-layer auth verify --email ${d} --code <code>\` when the code arrives.`,!1,t)}return h?await vA(d,h,e,t,`Verified ${d}.`):A(m,`Email sign-in started for ${d}. No code was entered, so nothing else was changed. Run \`skills-layer auth verify --email ${d} --code <code>\` when ready.`,!1,t)}if(!Ko(r))return R("login --method must be email, google, github, or gitlab.",e.json);let l=Ho(),c=await wA({flags:e,backend:t,provider:r,mode:"login",credentialHandoff:l});if(fe(c))return c;let u=await D(t,"/api/v1/identity/social/start",{method:"POST",headers:V(),body:JSON.stringify({provider:r,mode:"login",handoffCodeHash:l.authorizationCodeHash,handoffCodeChallenge:l.codeChallenge})});return await jh(r,u,l,e,t,"login",void 0,c)}if(!e.json)try{n=(await t.promptSecret("Enter your Skills Layer API key: ")).trim()}catch{return R("login requires an API key.",e.json)}if(!n)return R("login requires --api-key or --method <email|google|github|gitlab>.",e.json);let o=await Vu(t,n,{notifyLogin:!0}),s=await wh(e,{...t,config:o,apiKey:n});if(fe(s))return s;let a=await xP(e,{...t,config:o,apiKey:n});return fe(a)?a:A(Nt(CP({status:"verified",...o,...s.data?{workingMode:s.data}:{},...a.data?{mcp:a.data}:{}},a.data)),[`Logged in as ${o.email}.`,s.message??"",a.message??""].filter(Boolean).join(" "),e.json,t)}async function qM(e,t){let n=!1,r=!1,i=await ke(t.paths.mcpConfigPath),o=i?f(i,"keyId"):void 0,s=Re(t.config?.apiKey)??t.apiKey,a=dr(Re(t.config?.baseUrl)??t.baseUrl);if(s){try{await D({...t,baseUrl:a,apiKey:s},"/api/v1/me/working-mode",{method:"DELETE",headers:re(s)}),n=!0}catch{n=!1}try{await D({...t,baseUrl:a,apiKey:s},"/api/v1/me/session/revoke",{method:"POST",headers:V(s),body:JSON.stringify({includeCurrent:!0,revokeAllMcp:!0,humanKeyIds:[],mcpKeyIds:o?[o]:[]})}),r=!0}catch{r=!1}}let l=O2(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),c=await Promise.allSettled([l,kre(t),l.then(()=>We(t.paths.configPath,{force:!0}))]),u=c.every(m=>m.status==="fulfilled");if(!u)return x({status:"logout_incomplete",reasonCode:"local_cleanup_incomplete",serverCredentialsRevoked:r,localCleanupComplete:!1,nextAction:"logout",nextStep:"Unlock the OS credential store and retry logout. Local references were retained for cleanup."},"Server revocation was attempted, but local cleanup is incomplete.",e.json,"local_cleanup_incomplete");let d=!!s&&!r,p=d&&(t.config?.userId&&(t.config.sessionCredentialId||o))?await xA(t,{baseUrl:a,userId:t.config.userId,humanKeyIds:t.config.sessionCredentialId?[t.config.sessionCredentialId]:[],mcpKeyIds:o?[o]:[],revokeAllMcp:!0,revokeAdminMcp:!0,createdAt:t.now()}):!1;return A({status:s?"logged_out":"not_logged_in",serverWorkingModeCleared:n,serverCredentialsRevoked:r,revocationPending:d,...d?{pendingRecorded:p}:{},localCleanupComplete:u,warnings:u?[]:["Some local cleanup failed. Retry logout to finish clearing local state."],mcpAuthCleared:c[1].status==="fulfilled"},d?p?"Logged out locally. Server revocation is pending and will retry after the same account authenticates again.":"Logged out locally, but server revocation could not be recorded. Reconnect promptly; credentials remain bounded by expiry.":r?"Logged out. Human and MCP credentials were revoked.":"No saved login; local state cleared.",e.json,t)}async function kre(e){let t=await ke(e.paths.mcpConfigPath);if(!t){await SP(null,e),await We(e.paths.mcpPreferencePath,{force:!0});return}let n=t?f(t,"baseUrl")??e.baseUrl:e.baseUrl,r=t?f(t,"clientId")??"codex":"codex",i=es({baseUrl:n,mcpUrl:t?f(t,"mcpUrl")??`${n}/mcp`:`${n}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:t?f(t,"environment")??Dt(n):Dt(n),now:e.now(),env:e.env,platform:e.platform,cwd:e.cwd,stateDir:e.paths.stateDir,mcpConfigPath:e.paths.mcpConfigPath,nodePath:process.execPath}),o=t&&Array.isArray(t.clientIds)?t.clientIds.filter(a=>typeof a=="string"):t?[r]:[];if((await Promise.allSettled([SP(t,e),...i.targets.filter(a=>o.includes(a.agentId)).map(a=>a.disconnect?.()),ay(i.bridgePath),ly(i.brokerPath,i.brokerSocketPath,i.brokerLockPath),We(e.paths.mcpPreferencePath,{force:!0})])).some(a=>a.status==="rejected"))throw new Error("MCP local cleanup is incomplete; retry logout.");await We(e.paths.mcpConfigPath,{force:!0})}async function wre(e,t,n){let r=e[0]??"show";if(r==="show")return await me("/api/v1/profile",t,n,"Editable profile loaded.",{authenticated:!0});if(r==="update"){let i=await bre(t,n);if(fe(i))return i;let o=await D(n,"/api/v1/profile",{method:"PATCH",headers:V(n.apiKey),body:JSON.stringify(i)});return A(o,"Profile updated.",t.json,n)}return R(`Unknown profile command "${r}".`,t.json)}async function bre(e,t){let n=Ft(e,["displayName","bio","company"]);for(let r of["displayName","bio","company"])if(e[`clear${r[0].toUpperCase()}${r.slice(1)}`]){let i=r.replace(/[A-Z]/gu,o=>`-${o.toLowerCase()}`);if(n[r]!==void 0)return x({reasonCode:"conflicting_flags",unchanged:!0},`Choose either --${i} or --clear-${i}.`,e.json,"conflicting_flags");n[r]=null}if(Object.keys(n).length>0)return n;if(e.json)return R("profile update requires at least one of --display-name, --bio, or --company.",!0);try{let r=await t.promptText("Display name (leave blank to keep unchanged): "),i=await t.promptText("Bio (leave blank to keep unchanged): "),o=await t.promptText("Company (leave blank to keep unchanged): "),s=ie({displayName:r||void 0,bio:i||void 0,company:o||void 0});return Object.keys(s).length===0?R("No profile changes entered.",!1):s}catch{return R("profile update requires at least one of --display-name, --bio, or --company.",!1)}}async function _re(e,t,n){let r=e[0];if(r==="register")return await UM({...t,method:"email"},n);if(r==="verify"){let i=T(t.email,"auth verify requires --email."),o=T(t.code,"auth verify requires --code.");return await vA(i,o,t,n,`Verified ${i}.`)}return r==="recover"?await Cre(e.slice(1),t,n):r==="connect"?await Ire(t,n):r==="mfa"?await Pre(e.slice(1),t,n):r==="login"?await zM(t,n):r==="logout"?await qM(t,n):r==="status"?Sre(t,n):r==="repair"?await xre(t,n):R(`Unknown auth command "${r??""}".`,t.json)}function Sre(e,t){let n=t.config?.baseUrl?dr(t.config.baseUrl):null,r=!!(t.apiKey&&n&&Yu(n,t.baseUrl));return A({status:"auth_status",selectedBackend:Dt(t.baseUrl),selectedBaseUrl:t.baseUrl,loggedIn:r,requiresLogin:!r,...t.config?.email?{savedLogin:{baseUrl:n,email:t.config.email,role:t.config.role??null,roles:t.config.roles??[],savedAt:t.config.savedAt??null,...t.config.credentialStorage?{credentialStorage:t.config.credentialStorage}:{},matchesSelectedBackend:r}}:{}},r&&t.config?.email?`Logged in as ${t.config.email}.`:t.config?.baseUrl?`Saved login targets ${n}; selected backend is ${t.baseUrl}. Run \`skills-layer auth repair\` or \`skills-layer login\`.`:"Not logged in. Run `skills-layer login`.",e.json,t)}async function xre(e,t){if(!t.config?.baseUrl||!t.config.apiKey||!t.config.email||!t.config.role||!t.config.savedAt)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login` to create a saved session, then use `skills-layer auth repair` only if backend/session metadata drifts."},"No saved Skills Layer login was found to repair. Run `skills-layer login`.",e.json,"login_required");let n=dr(t.config.baseUrl);return await Ve(t.paths.backendPreferencePath,{version:JP,preferredBaseUrl:n,savedAt:t.now()}),await CA(t.paths.configPath,{...t.config,baseUrl:n,savedAt:t.now()},t),A({status:"auth_repaired",baseUrl:n,loggedIn:!0,email:t.config.email,role:t.config.role,credentialStorage:t.config.credentialStorage??"local_file_locked"},`Auth repaired for ${t.config.email}. Backend preference now matches ${n}.`,e.json,t)}async function Cre(e,t,n){let r=e[0]??k(t.method);if(!r&&!t.json)try{r=await n.promptSelect("Choose how to recover access:",vre)}catch{return R("auth recover requires --method email when interactive selection is unavailable.",!1)}if(r??="email",Ko(r))return x({status:"unsupported_auth_journey",reasonCode:"unsupported_auth_journey",provider:r,nextAction:"account.connect",nextStep:`Run \`skills-layer auth connect --provider ${r}\` after signing in.`},`Social identities are connected, not used for account recovery. Sign in, then run \`skills-layer auth connect --provider ${r}\`.`,t.json,"unsupported_auth_journey");if(r!=="complete"&&r!=="email")return R("auth recover --method must be email.",t.json);let i=k(t.email);if(r==="complete"){if(!i&&!t.json)try{i=await n.promptText("Enter your email address: ")}catch{return R("auth recover complete requires --email when interactive prompts are unavailable.",!1)}i=T(i,"auth recover complete requires --email.");let l=k(t.code);if(!l&&!t.json)try{l=await n.promptText("Enter the recovery code: ")}catch{return R("auth recover complete requires --code when interactive prompts are unavailable.",!1)}return l=T(l,"auth recover complete requires --code."),await EB(i,l,t,n)}if(!i&&!t.json)try{i=await n.promptText("Enter your email address: ")}catch{return R("auth recover --method email requires --email when interactive prompts are unavailable.",!1)}i=T(i,"auth recover --method email requires --email.");let o=await D(n,"/api/v1/identity/recover/start",{method:"POST",headers:V(),body:JSON.stringify({email:i,method:r})}),s=WP(o);if(t.json)return A({...s,nextCommand:`skills-layer auth recover complete --email ${i} --code <code>`,nextAction:"auth.recover.complete",nextStep:"Check your email and complete recovery with the emailed code."},"Recovery started.",!0,n);let a="";try{a=(await n.promptText("Enter the recovery code if you received one, or press Enter to stop: ")).trim()}catch{return A(s,`If this email can continue, instructions have been sent. Check your inbox and spam folder. When you have a code, run \`skills-layer auth recover complete --email ${i} --code <code>\`.`,!1,n)}return a?await EB(i,a,t,n):A(s,`If this email can continue, instructions have been sent. When you have a code, run \`skills-layer auth recover complete --email ${i} --code <code>\`.`,!1,n)}async function Ire(e,t){let n=k(e.provider);if(!n&&!e.json)try{n=await t.promptSelect("Choose an identity to connect:",await Dh($h,t))}catch{return R("auth connect requires --provider when interactive selection is unavailable.",!1)}if(n=T(n,"auth connect requires --provider."),!Ko(n))return R("auth connect --provider must be google, github, or gitlab.",e.json);if(!t.apiKey||t.authBlockedMessage)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login`, then retry the connection."},"Sign in before connecting another login method.",e.json,"login_required");if((await D(t,"/api/v1/identity/mfa/status",{headers:V(t.apiKey,t.authBlockedMessage)})).enabled!==!0){let l=await VM(e,t);return fe(l)?l:A(l,"MFA setup is required before connecting a sign-in method. Complete setup in the browser, then run this command again.",e.json,t)}let i=k(e.mfaCode);if(!i&&!e.json)try{i=await t.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return R("auth connect requires MFA verification. Retry with an interactive terminal.",!1)}if(!i||!/^\d{6}$/u.test(i))return R("auth connect requires a 6-digit --mfa-code when interactive prompts are unavailable.",e.json);let o=await D(t,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({purpose:"identity.connect",code:i})}),s=T(f(o,"stepUpGrant"),"MFA verification did not return a step-up grant."),a=await D(t,"/api/v1/identity/connect/start",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({provider:n,stepUpGrant:s})});return await jh(n,a,void 0,e,t,"connect","/api/v1/identity/connect/status")}async function Pre(e,t,n){let r=e[0]??"status";if(!n.apiKey||n.authBlockedMessage)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login`, then retry the MFA command."},"Sign in before managing MFA.",t.json,"login_required");if(r==="status"){let i=await D(n,"/api/v1/identity/mfa/status",{headers:re(n.apiKey,n.authBlockedMessage)}),o=i.enabled===!1?{...i,nextAction:"account.mfa.setup",nextStep:"Protect this account by running `skills-layer auth mfa setup`."}:i;return A(o,"MFA status loaded.",t.json,n)}if(r==="setup"){let i=await VM(t,n);return fe(i)?i:A(i,"MFA setup started. Complete it in your browser; recovery codes are shown there once.",t.json,n)}if(r==="verify"){let i=T(k(t.purpose),"auth mfa verify requires --purpose."),o=k(t.mfaCode)??k(t.code);if(!o&&!t.json)try{o=await n.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return R("auth mfa verify requires an interactive code or --mfa-code.",!1)}if(!o||!/^\d{6}$/u.test(o))return R("auth mfa verify requires a 6-digit --mfa-code.",t.json);let s=await D(n,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({purpose:i,code:o})});return A(s,`MFA verified for ${i}.`,t.json,n)}if(r==="recovery-codes"){if(k(t.mfaCode)||k(t.code))return R("Do not pass an authenticator code on the command line. Recovery-code regeneration now requires protected browser verification.",t.json);if(t.json)return A({status:"human_action_required",reasonCode:"human_handoff_required",nextAction:"mfa.recovery_codes.browser",nextStep:"Run `skills-layer auth mfa recovery-codes` in an interactive human terminal to open the protected browser flow.",delivery:"browser_only"},"Recovery-code regeneration requires a protected human browser session.",!0,n);let i=await D(n,"/api/v1/identity/mfa/recovery-codes/regenerate",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({})}),o=T(f(i,"recoveryCodesUrl"),"Recovery-code regeneration did not return a secure browser handoff."),s=T(f(i,"operationId"),"Recovery-code regeneration did not return a secure operation identifier.");!t.noOpen&&await n.openUrl(o)||n.emitInfo(`Open this secure recovery-code link in your browser:
|
|
2100
2100
|
${o}`),n.emitInfo("Waiting for recovery-code verification to finish in your browser...");let l=await Gae(s,n);return fe(l)?l:A({status:"regenerated",action:"mfa.recovery_codes.completed",completedAt:f(l,"completedAt"),delivery:"browser_only",nextAction:"store_recovery_codes",nextStep:"Confirm the replacement recovery codes are saved in your password manager or secure offline location."},"Recovery codes were replaced in your browser.",!1,n)}if(r==="disable"){let i="identity.mfa.disable",o=k(t.mfaCode)??k(t.code);if(!o&&!t.json)try{o=await n.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return R(`auth mfa ${r} requires an interactive code or --mfa-code.`,!1)}if(!o||!/^\d{6}$/u.test(o))return R(`auth mfa ${r} requires a 6-digit --mfa-code.`,t.json);let s=await D(n,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({purpose:i,code:o})}),a=T(f(s,"stepUpGrant"),"MFA verification did not return a step-up grant."),l=await D(n,"/api/v1/identity/mfa/disable",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({stepUpGrant:a})});return A(l,"MFA disabled.",t.json,n)}return R(`Unknown auth mfa command "${r}".`,t.json)}async function VM(e,t){let n=await D(t,"/api/v1/identity/mfa/setup/start",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage)}),r=T(f(n,"setupUrl"),"MFA setup did not return a browser handoff."),i=e.noOpen||e.json?!1:await t.openUrl(r);return!e.json&&!i&&t.emitInfo(`Open this secure MFA setup link in your browser:
|
|
2101
2101
|
${r}`),{...n,status:"human_action_required",nextAction:"mfa.setup.browser",nextStep:"Complete authenticator setup in the browser, save the one-time recovery codes, then return to the CLI."}}async function EB(e,t,n,r){let i=Ho(),o=async(l,c)=>D(r,"/api/v1/identity/recover/complete",{method:"POST",headers:V(),body:JSON.stringify({email:e,code:t,...l?{mfaCode:l}:{},...c?{recoveryCode:c}:{},handoffCodeHash:i.authorizationCodeHash,handoffCodeChallenge:i.codeChallenge})}),s;try{s=await o(k(n.mfaCode),k(n.recoveryCode))}catch(l){if(!(l instanceof Z)||l.status!==428)throw l;if(n.json)return x({status:"human_action_required",reasonCode:"recovery_mfa_required",nextAction:"account.recover.verify_mfa",nextStep:"Retry with --mfa-code <6-digits> or --recovery-code <one-time-code>."},"Recovery needs your second factor.",!0,"recovery_mfa_required");let c=await r.promptSelect("Choose your recovery second factor:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one saved one-time recovery code"}]),u=(await r.promptSecret(c==="authenticator"?"Enter the 6-digit authenticator code: ":"Enter one unused recovery code: ")).trim();s=c==="authenticator"?await o(u,void 0):await o(void 0,u)}if(f(s,"status")!=="recovered")return R("Email recovery did not prepare a secure credential handoff. Start recovery again.",n.json);let a=await D(r,"/api/v1/identity/credential-handoff/exchange",{method:"POST",headers:V(),body:JSON.stringify({authorizationCode:i.authorizationCode,codeVerifier:i.codeVerifier})});if(f(a,"status")!=="exchanged"||!f(a,"email")||!f(a,"role")||!f(a,"apiKey"))return R("Email recovery credential handoff failed closed. Start recovery again.",n.json);if(n.json){let l=f(a,"apiKey");return l?(await Vu(r,l,{expectedEmail:e,knownEmail:f(a,"email")??e,knownRole:f(a,"role")??"user",knownRoles:Un(a,"roles"),knownUserId:f(a,"userId"),knownSessionCredentialId:f(a,"id")}),A(Nt({...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions,loggedIn:!0}),`Recovery complete. Sensitive actions are held until ${String(s.holdUntil)}.`,!0,r)):A(Nt({...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions,email:e,loggedIn:!1}),`Recovery complete. Sensitive actions are held until ${String(s.holdUntil)}.`,!0,r)}return await kA(e,{...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions},n,r,`Recovered access for ${e}. Sensitive actions are held until ${String(s.holdUntil)}.`)}async function Are(e,t,n){let r=e[0],i=1;if(r==="providers")return await me("/api/v1/identity/social/providers",t,n,"Identity providers loaded.");if(r==="start"){let o=k(t.provider);if(!o&&!t.json)try{o=await n.promptSelect("Choose identity provider:",await Dh($h,n))}catch{return R("identity start requires --provider when interactive selection is unavailable.",!1)}if(o=T(o,"identity start requires --provider."),!Ko(o))return R("identity start --provider must be google, github, or gitlab.",t.json);let s=k(t.mode)??"login";if(s!=="login"&&s!=="register")return x({status:"dedicated_auth_journey_required",reasonCode:"dedicated_auth_journey_required",nextStep:s==="recovery"?"Run `skills-layer auth recover`.":"Run `skills-layer auth connect --provider <provider>`."},"Use the dedicated recover or connect command for this account journey.",t.json,"dedicated_auth_journey_required");let a=Ho(),l=await wA({flags:t,backend:n,provider:o,mode:s,credentialHandoff:a});if(fe(l))return l;let c=await D(n,"/api/v1/identity/social/start",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({provider:o,mode:s,handoffCodeHash:a.authorizationCodeHash,handoffCodeChallenge:a.codeChallenge})});return await jh(o,c,a,t,n,s,void 0,l)}if(r==="status"){let o=k(t.state)??e[i];return o?await me(`/api/v1/identity/social/status/${encodeURIComponent(o)}`,t,n,"Social auth status loaded."):R("identity status requires --state.",t.json)}if(r==="continue"){let o=k(t.reference)??e[i];return await Rre(o,t,n)}if(r==="complete"){let o=T(t.provider,"identity complete requires --provider."),s=T(t.state,"identity complete requires --state."),a=T(t.code,"identity complete requires --code."),l=await D(n,"/api/v1/identity/social/complete",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({provider:o,state:s,code:a})});return A(Nt(l),"Social auth complete.",t.json,n)}if(r==="list")return await me("/api/v1/me/linked-identities",t,n,"Linked identities loaded.",{authenticated:!0});if(r==="unlink"){let o=T(t.provider??e[i],"identity unlink requires a provider."),s=l=>D(n,`/api/v1/me/linked-identities/${encodeURIComponent(o)}`,{method:"DELETE",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({mfaCode:l})}),a;try{a=await s(k(t.mfaCode))}catch(l){if(!(l instanceof Z)||l.details?.reasonCode!=="mfa_step_up_required"||t.json||n.nonInteractive||k(t.mfaCode))throw l;a=await s((await n.promptSecret("Enter a fresh authenticator code to unlink this identity: ")).trim())}return A(a,"Identity unlinked.",t.json,n)}return R(`Unknown identity command "${r??""}".`,t.json)}async function Rre(e,t,n){let r=T(e,"identity continue requires --reference <reference>.");if(!/^social_[A-Za-z0-9_-]{20,80}$/u.test(r)||!n.credentialStore)return No(t,n);let i=`skills-layer-social-continuation:${r}`,o;try{o=await n.credentialStore.get(Le,i)}catch{o=null}let s=Ere(o,r,n.baseUrl);if(!s)return await n.credentialStore.delete(Le,i).catch(()=>{}),No(t,n);if(Date.parse(n.now())>=Date.parse(s.expiresAt))return await n.credentialStore.delete(Le,i).catch(()=>{}),No(t,n);let a=await D(n,`/api/v1/identity/social/status/${encodeURIComponent(s.state)}`),l=f(a,"status");if(l==="pending")return A({status:"already_processing",reasonCode:"social_auth_pending",reference:r,expiresAt:s.expiresAt,nextAction:"identity.continue",nextStep:`Complete browser sign-in, then rerun \`skills-layer identity continue --reference ${r}\`.`},"Browser sign-in is still pending.",t.json,n);if(l==="mfa_required"){let c=k(t.mfaCode),u=k(t.recoveryCode);if(!c&&!u&&!t.json&&!n.nonInteractive&&n.stdoutIsTty){let p=await n.promptSelect("Complete MFA to finish login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),m=(await n.promptSecret(p==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();p==="recovery_code"?u=m:c=m}if(!c&&!u)return x({status:"human_action_required",reasonCode:"login_mfa_required",methods:["authenticator","recovery_code"],reference:r,nextAction:"identity.continue",nextStep:`Run \`skills-layer identity continue --reference ${r} --mfa-code <6-digits>\` in a human-controlled terminal.`},"MFA is required to finish the social login.",t.json,"login_mfa_required");let d=await D(n,"/api/v1/identity/login/mfa/verify",{method:"POST",headers:V(),body:JSON.stringify({state:s.state,authorizationCode:s.authorizationCode,codeVerifier:s.codeVerifier,...c?{mfaCode:c}:{},...u?{recoveryCode:u}:{}})});if(f(d,"status")!=="verified"||f(d,"credentialHandoff")!=="ready")return R("MFA verification did not authorize the stored login.",t.json)}else if(l!=="verified"&&l!=="recovered")return await n.credentialStore.delete(Le,i).catch(()=>{}),x({status:l??"failed",reasonCode:"social_continuation_terminal",unchanged:!0,nextAction:"login",nextStep:"Start a fresh social login."},"The social login cannot be continued.",t.json,"social_continuation_terminal");try{return await kh(kz(s.provider),{authorizationCode:s.authorizationCode,codeVerifier:s.codeVerifier,authorizationCodeHash:s.authorizationCodeHash,codeChallenge:s.codeChallenge},t,n,s.mode)}finally{await n.credentialStore.delete(Le,i).catch(()=>{})}}function Ere(e,t,n){if(!e)return null;try{let r=JSON.parse(e),i=f(r,"provider"),o=f(r,"mode"),s=f(r,"state"),a=f(r,"expiresAt"),l=f(r,"authorizationCode"),c=f(r,"codeVerifier"),u=f(r,"authorizationCodeHash"),d=f(r,"codeChallenge"),p=f(r,"integrityDigest"),m=f(r,"createdAt")??"";return r.version!==1||f(r,"reference")!==t||f(r,"baseUrl")!==n||!i||!Ko(i)||o!=="login"&&o!=="register"||!s||!a||!Number.isFinite(Date.parse(a))||!l?.startsWith("social_handoff_")||!c||!u||!d||!p||Me("sha256").update(l).digest("base64url")!==u||Me("sha256").update(c).digest("base64url")!==d||bA({version:1,reference:t,baseUrl:n,provider:i,mode:o,authorizationCode:l,codeVerifier:c,authorizationCodeHash:u,codeChallenge:d,createdAt:m,state:s,expiresAt:a})!==p?null:{version:1,reference:t,baseUrl:n,provider:i,mode:o,authorizationCode:l,codeVerifier:c,authorizationCodeHash:u,codeChallenge:d,integrityDigest:p,createdAt:m,state:s,expiresAt:a}}catch{return null}}async function $re(e,t,n){let r=e[0];if(!r)return R("api-key requires create, list, or revoke.",t.json);if(r==="list"){let i=Dre(t);if(i.failure)return i.failure;let o=await D(n,"/api/v1/me/api-keys",{headers:re(n.apiKey,n.authBlockedMessage)}),s=Tre(GM(o),i.filters,Date.parse(n.now()));return A({...o,filters:ie({...i.filters}),results:s},"API keys loaded.",t.json,n)}if(r==="create"){let i=k(t.name),o=_ce(Array.isArray(t.scopeValues)&&t.scopeValues.length>1?t.scopeValues:t.scope);if(!i)return R("api-key create requires --name.",t.json);if(o.length===0)return R("api-key create requires at least one --scope.",t.json);let s=o.find(p=>!UB.includes(p));if(s)return Nr("api-key.create","scope",s,UB,t,"invalid_scope");let a=Die("api-key.create",t.expires,t);if(a)return a;if(t.dryRun){let p=await D(n,"/api/v1/me/api-keys",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({name:i,scopes:o,expiresIn:k(t.expires),dryRun:!0})});return A(p,"API key create dry run passed.",t.json,n)}let l=Ho(),c=await D(n,"/api/v1/me/api-keys",{method:"POST",headers:{"content-type":"application/json",...re(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:i,scopes:o,...k(t.expires)?{expiresIn:k(t.expires)}:{},handoffCodeHash:l.authorizationCodeHash,handoffCodeChallenge:l.codeChallenge})});if(f(c,"credentialHandoff")!=="ready")return R("API key creation did not prepare a secure credential handoff.",t.json);let u=await D(n,"/api/v1/credential-handoffs/exchange",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({authorizationCode:l.authorizationCode,codeVerifier:l.codeVerifier})}),d=f(u,"apiKey");return f(u,"status")!=="exchanged"||!d?R("API key credential exchange failed closed; prepare the key again.",t.json):A({...u,secretReturned:!0,secretDelivery:"one_time_client_bound_exchange"},`Automation API key created. Copy this one-time secret now: ${d}
|
|
2102
2102
|
Run \`skills-layer api-key list\` to manage keys.`,t.json,n)}if(r==="rotate")return R(`api-key rotate is not part of normal login.
|
|
@@ -2134,7 +2134,7 @@ Run:
|
|
|
2134
2134
|
`)}function Xre(e,t){let n=Pe(t),r=j(e,"enterprise"),i=J(e,"addedSeats"),o=r?J(r,"seatCapacity"):void 0,s=r?J(r,"usedSeats"):void 0,a=r?J(r,"availableSeats"):void 0,l=[`${n.ok("OK")} ${i??"Additional"} Enterprise seat${i===1?"":"s"} added.`,"",n.section("Enterprise")];return l.push(` ${n.label("Name")}: ${r?f(r,"name")??"unknown":"unknown"}`),l.push(` ${n.label("ID")}: ${r?f(r,"enterpriseId")??"unknown":"unknown"}`),o!==void 0&&s!==void 0&&a!==void 0&&l.push(` ${n.label("Seats")}: ${s} used, ${a} available of ${o}`),l.push("",n.section("Next"),` ${n.arrow} skills-layer enterprise seats`),l.join(`
|
|
2135
2135
|
`)}function Qre(e,t){let n=e==="canceled"||e==="cancelled",r=t==="enterprise"?"Enterprise checkout":t==="enterprise_seats"?"Enterprise seat checkout":"Enterprise skill checkout",i=t==="enterprise"?"No Enterprise, workspace, or seats were created.":t==="enterprise_seats"?"No seats were added and the Enterprise capacity is unchanged.":"No Enterprise skill entitlement was created and no workspace access changed.",o=t==="enterprise"?"Enterprise checkout":t==="enterprise_seats"?"Enterprise seat purchase":"Enterprise skill purchase";return n?`${r} was cancelled. ${i} Rerun the ${o} command when you are ready.`:e==="expired"?`${r} expired. ${i} Start a new ${o} when you are ready.`:`${r} failed${e?` (${e})`:""}. ${i} Retry the ${o} command or contact support if payment was charged.`}function eie(e,t,n){let r=Pe(n),i=t==="enterprise"?"Enterprise checkout":t==="enterprise_seats"?"Enterprise seat checkout":"Enterprise skill checkout";return[`${r.muted("!")} ${i} payment or provisioning may already be in progress.`,"",r.section("Status"),` ${r.label("Checkout ID")}: ${f(e,"checkoutId")??"unknown"}`,` ${r.label("State")}: Completion pending`,"",r.section("Next"),` ${r.arrow} ${f(e,"nextStep")??"Check the same checkout status again. Do not start a second checkout."}`].join(`
|
|
2136
2136
|
`)}function jt(e){if(e==="workspace_approved_only")return"Workspace-approved only";let t=e.replace(/[_-]+/gu," ").trim().toLowerCase();return t.length>0?t[0].toUpperCase()+t.slice(1):"Unknown"}function cn(e,t,n,r,i){return r?A(e,n,!0,i):{exitCode:0,stdout:t,stderr:""}}function Ot(e){let t=nl(e);return t.status==="unknown"?null:t.hostId}function tie(e){return Ot(e)!==null}function HM(e){return Xt.includes(e)}function sP(e,t){return x({status:"error",reasonCode:"unknown_mcp_client",requestedClient:e,nextAction:"mcp.status",nextStep:"Run `skills-layer mcp setup --all --dry-run` to see verified MCP host ids."},`Unknown MCP client "${e}". MCP hosts are separate from skill-install agents; run \`skills-layer mcp setup --all --dry-run\` to inspect them.`,t.json,"unknown_mcp_client")}function ch(e){let t=e.target.instructions,n=Array.isArray(t)&&typeof t[0]=="string"?t[0]:`Install skills with \`skills-layer install <skill> --agent ${e.clientId}\`.`;return{...e,status:"skills_only",configured:!1,nextCommand:null,nextAction:"install.skills",nextStep:n}}async function XP(e,t){let n=k(e.environment)??Dt(t.baseUrl),r=[...L2],i=`${t.baseUrl}/mcp`,o=es({baseUrl:t.baseUrl,mcpUrl:i,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:"codex",environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath}),s=await nie(e,t,o);if(s.clientIds.length===0)return x({status:"needs_mcp_client_choice",reasonCode:"needs_mcp_client_choice",configured:!1,detectedClientIds:s.detectedClientIds,supportedClientIds:o.targets.filter(C=>C.status==="automatic").map(C=>C.agentId),nextAction:"mcp.setup.select_client",nextStep:"Run `skills-layer mcp setup --client <host-id>` or `skills-layer mcp setup --all`."},"No verified Tier 1 MCP host was detected, so no client was selected. Choose a host explicitly or use --all.",e.json,"needs_mcp_client_choice");let a=s.clientIds[0],l=es({baseUrl:t.baseUrl,mcpUrl:i,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:a,environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath});if(e.dryRun){let C=l.targets.filter(P=>P.status==="automatic"&&s.clientIds.includes(Ot(P.agentId)));return{status:"mcp_setup_preview",evidenceStale:l.evidenceStale,warnings:l.warnings,dryRun:!0,configured:!1,unchanged:!0,clientId:a,clientIds:s.clientIds,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,plannedWrites:C.map(P=>({clientId:P.agentId,scope:"user_global",configPath:P.configPath})),skippedClients:l.targets.filter(P=>P.status!=="automatic").map(P=>({clientId:P.agentId,reason:P.reason})),bridgePath:l.bridgePath,brokerPath:l.brokerPath,nextAction:"mcp.setup"}}let c=l.targets.filter(C=>C.status==="automatic"&&s.clientIds.includes(Ot(C.agentId)));try{for(let C of c)await C.preflight?.()}catch(C){let P=C instanceof Error&&C.message.startsWith("mcp_config_symlink_rejected")?"mcp_config_symlink_rejected":"mcp_registration_ownership_ambiguous";return x({status:"mcp_setup_blocked",configured:!1,unchanged:!0,reasonCode:P,clientIds:s.clientIds,nextAction:"mcp.config.review",nextStep:"Review the existing user-global MCP entry. Skills Layer did not mint a credential or overwrite it."},C instanceof Error?C.message:"MCP host configuration preflight failed.",e.json,P)}if(bg(t.baseUrl)&&!t.credentialStore)return x({status:"security_unavailable",reasonCode:"mcp_secure_storage_required",configured:!1,unchanged:!0,nextAction:"mcp.setup",nextStep:"Run `skills-layer mcp setup --client <host-id>` on a machine with supported OS-secure credential storage."},"Skills Layer Cloud MCP setup requires supported OS-secure credential storage. No MCP credential was created.",e.json,"mcp_secure_storage_required");let u=Ho(),d=await D(t,"/api/v1/me/mcp-tokens",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({clientId:ey,linkedClientIds:s.clientIds,environment:n,scopes:r,handoffCodeHash:u.authorizationCodeHash,handoffCodeChallenge:u.codeChallenge})});if(f(d,"credentialHandoff")!=="ready")return R("MCP setup did not prepare a secure credential handoff.",e.json);let p=await D(t,"/api/v1/credential-handoffs/exchange",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({authorizationCode:u.authorizationCode,codeVerifier:u.codeVerifier})}),m=f(p,"apiKey");if(!m)return R("MCP token credential exchange failed closed.",e.json);let h;try{h=await rie(t,{token:m,clientId:ey,environment:n})}catch(C){if(!(C instanceof Sa))throw C;let P=f(p,"id"),O=!1;if(P)try{await D(t,"/api/v1/me/session/revoke",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({includeCurrent:!1,revokeAllMcp:!1,humanKeyIds:[],mcpKeyIds:[P]})}),O=!0}catch{t.config?.userId&&await xA(t,{baseUrl:t.baseUrl,userId:t.config.userId,humanKeyIds:[],mcpKeyIds:[P],revokeAllMcp:!1,revokeAdminMcp:!1,createdAt:t.now()})}return R(O?"OS-secure credential storage failed, so the new MCP credential was revoked and no local MCP setup was written.":"OS-secure credential storage failed. No local MCP setup was written; server revocation is pending or requires prompt retry.",e.json)}let g={...h,shared:!0,keyId:f(p,"id")??null,tokenPrefix:f(p,"keyPrefix")??null,scopes:Array.isArray(p.scopes)?p.scopes:[]},y=await ke(t.paths.mcpConfigPath),v=`${t.paths.stateDir}/mcp-credential-refs.json`,b=await ke(v),w=[...Ma(b??{},Le),...Ma(y??{},Le),...Ma(g,Le)];if(await Ve(v,{tokens:Object.fromEntries(w.map(C=>[C.tokenRef,{tokenRef:C.tokenRef,credentialService:C.service,credentialStorage:"macos_keychain"}]))}),await Ve(t.paths.mcpConfigPath,{version:1,baseUrl:t.baseUrl,mcpUrl:i,clientId:a,clientIds:s.clientIds,environment:n,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,...g,brokerPath:l.brokerPath,brokerSocketPath:l.brokerSocketPath,brokerLockPath:l.brokerLockPath,brokerIntegrityProfile:"standard_v1",brokerChecksum:l.brokerChecksum,savedAt:t.now()}),t.credentialStore){let C=new Set(Ma(g,Le).map(P=>`${P.service}:${P.tokenRef}`));for(let P of w)C.has(`${P.service}:${P.tokenRef}`)||await t.credentialStore.delete(P.service,P.tokenRef);await Ve(v,{tokens:Object.fromEntries(w.filter(P=>C.has(`${P.service}:${P.tokenRef}`)).map(P=>[P.tokenRef,{tokenRef:P.tokenRef,credentialService:P.service,credentialStorage:"macos_keychain"}]))})}let _=c;for(let C of _)await C.apply?.();return await We(t.paths.mcpPreferencePath,{force:!0}),{...Nt(p),status:"mcp_configured",evidenceStale:l.evidenceStale,warnings:l.warnings,clientId:a,clientIds:s.clientIds,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,environment:n,mcpUrl:i,bridgePath:l.bridgePath,brokerPath:l.brokerPath,brokerSocketPath:l.brokerSocketPath,nodePath:l.nodePath,bridgeChecksum:l.bridgeChecksum,brokerChecksum:l.brokerChecksum,saved:!0,readiness:{status:"configured_needs_agent_reload",verifyCommand:`skills-layer mcp verify --client ${a}`,nextStep:"Open a fresh agent session so the host can load the updated MCP configuration. Run verify or repair if Skills Layer tools are still not visible."},registrations:{status:"mcp_registration_plan",automaticCount:l.automaticCount,manualCount:l.manualCount,skillsOnlyCount:l.skillsOnlyCount,unsupportedCount:l.unsupportedCount,appliedCount:_.length,appliedClients:_.map(C=>C.agentId),targets:l.targets.map(C=>({agentId:C.agentId,displayName:C.displayName,tier:C.tier,status:C.status,transport:C.transport,configPath:C.configPath,bridgePath:C.bridgePath,restartRequired:C.restartRequired,reason:C.reason,instructions:C.instructions}))}}}async function nie(e,t,n){let r=k(e.client),i=n.targets.filter(l=>l.status==="automatic").flatMap(l=>{let c=Ot(l.agentId);return c?[c]:[]});if(r){let l=Ot(r);return{clientIds:l?[l]:[],detectedClientIds:[],selectionSource:"explicit"}}if(e.all)return{clientIds:i,detectedClientIds:i,selectionSource:"all"};let o=await QA({env:t.env,platform:t.platform,cwd:t.cwd,pathExists:t.pathExists}),s=new Set(i),a=o.map(l=>l.hostId).filter(l=>s.has(l));if(a.length>0)return{clientIds:a,detectedClientIds:a,selectionSource:"detected"};if(t.stdoutIsTty&&!e.json)try{let l=await t.promptSelect("Choose the MCP host to configure globally:",n.targets.filter(u=>u.status==="automatic").map(u=>({value:String(u.agentId),label:u.displayName,description:`User-global config: ${u.configPath}`}))),c=Ot(l);if(c)return{clientIds:[c],detectedClientIds:[],selectionSource:"explicit"}}catch{}return{clientIds:[],detectedClientIds:[],selectionSource:"choice_required"}}async function rie(e,t){if(!e.credentialStore){if(bg(e.baseUrl))throw new Sa;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}let n=iie({baseUrl:e.baseUrl,userId:e.config?.userId,email:e.config?.email,clientId:t.clientId,environment:t.environment,stateDir:e.paths.stateDir});try{return await e.credentialStore.set(Le,n,t.token),{tokenRef:n,credentialStorage:"macos_keychain",credentialService:Le,tokenStorage:"macos_keychain"}}catch{if(bg(e.baseUrl))throw new Sa;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}}async function SP(e,t){let n=`${t.paths.stateDir}/mcp-credential-refs.json`,r=await ke(n),i=[...Ma(e??{},Le),...Ma(r??{},Le)];if(!t.credentialStore){if(i.length)throw new Error("OS credential storage is unavailable; retry cleanup on this profile's original machine.");return}if((await Promise.allSettled(i.map(s=>t.credentialStore.delete(s.service,s.tokenRef)))).some(s=>s.status==="rejected"))throw new Error("MCP credential cleanup is incomplete; retry logout.");await We(n,{force:!0})}function Ma(e,t){let n=new Map;jB(e,t,n);let r=e.tokens;if(L(r))for(let i of Object.values(r))L(i)&&jB(i,t,n);return[...n.values()]}function jB(e,t,n){let r=f(e,"tokenRef");if(!r||f(e,"credentialStorage")!=="macos_keychain")return;let i=f(e,"credentialService")??t;n.set(`${i}:${r}`,{service:i,tokenRef:r})}function iie(e){let t=[e.baseUrl,e.userId??e.email??"unknown-user",e.clientId,e.environment,"mcpToken"].join(`
|
|
2137
|
-
`);return`skills-layer-cli:mcp-token:${Me("sha256").update(t).digest("base64url").slice(0,32)}`}async function xP(e,t){if(e.noMcp)return{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."};let n=await ke(t.paths.mcpConfigPath),r=n?f(n,"baseUrl"):void 0,i=n?f(n,"clientId"):null;if(!e.withMcp&&r===t.baseUrl&&i)return{data:{status:"mcp_already_configured",configured:!0,clientId:i,mcpUrl:n?f(n,"mcpUrl")??`${t.baseUrl}/mcp`:`${t.baseUrl}/mcp`},message:"MCP is already configured for this machine."};let o=e.withMcp===!0;if(!o&&!e.json)try{let a=await t.promptSelect("Set up Skills Layer MCP for your AI tools on this machine?",[{value:"yes",label:"Yes, set up MCP",description:"Mint a scoped token and write local MCP configuration"},{value:"no",label:"Not now",description:"You can run skills-layer mcp setup later"}]);if(o=a==="yes",a==="no")return await We(t.paths.mcpPreferencePath,{force:!0}),{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."}}catch{return{}}if(!o)return{};let s=await XP(e,t);return fe(s)?{data:oie(s),message:"Login completed, but MCP was not configured. Choose a verified host with `skills-layer mcp setup --client <host-id>` or use `--all`."}:{data:s,message:"MCP configuration written for this machine. Open a fresh agent session so your AI tools can load it."}}function oie(e){let t="mcp_setup_failed";try{let n=JSON.parse(e.stderr);t=f(n,"reasonCode")??t}catch{e.stderr.includes("OS-secure credential storage")&&(t="mcp_secure_storage_required")}return{status:"mcp_not_configured",configured:!1,reasonCode:t,nextAction:"mcp.setup",nextCommand:"skills-layer mcp setup --client <host-id>",nextStep:"Run `skills-layer mcp setup --client <host-id>` after resolving the reported MCP prerequisite, or use `--all`."}}function CP(e,t){return t?t.status==="mcp_skipped"?{...e,nextAction:"whoami",nextStep:"Run `skills-layer whoami` to check your account."}:t.configured!==!1?{...e,nextAction:"mcp.verify",nextStep:"Open a fresh agent session so it can load Skills Layer, then run `skills-layer mcp verify` if the tools are not visible."}:t.configured===!1||t.status==="mcp_skipped"?{...e,nextAction:"mcp.setup",nextStep:"Run `skills-layer mcp setup` when you want Skills Layer available to your AI tools."}:e:e}async function wh(e,t){if(t.config?.edition==="community")return{};let n;try{n=await D(t,"/api/v1/me/working-modes",{headers:re(t.apiKey,t.authBlockedMessage)})}catch{return{}}await ji(t,n);let r=Array.isArray(n.modes)?n.modes.filter(L):[],i=f(n,"selectedModeId");if(!r.some(u=>f(u,"type")==="enterprise_workspace")){let u=r.find(p=>f(p,"modeId")===i),d=u?f(u,"label")??i:i;return i?{data:{status:"working_mode_selected",selectedModeId:i,...u?{mode:u}:{}},message:`Selected workspace: ${d}.`}:{}}let s=sie(r,i);if(s.length===0)return{};if(e.json)return x({status:"working_mode_selection_required",reasonCode:"working_mode_selection_required",selectedModeId:i??null,modes:r,nextAction:"workspace.select",nextStep:"Run `skills-layer workspace select personal` or `skills-layer workspace select <workspace-id>`."},"Select Personal or an Enterprise workspace to finish signing in.",!0,"working_mode_selection_required");let a;try{a=await t.promptSelect("Select your Skills Layer workspace:",s)}catch{return x({status:"working_mode_selection_required",reasonCode:"working_mode_selection_required",selectedModeId:f(n,"selectedModeId")??null,modes:r,nextAction:"workspace.select",nextStep:"Run `skills-layer workspace select personal` or `skills-layer workspace select <workspace-id>`."},"Select Personal or an Enterprise workspace to finish signing in.",e.json,"working_mode_selection_required")}let l=await D(t,"/api/v1/me/working-mode",{method:"PUT",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({modeId:a})});await ji(t,l);let c=s.find(u=>u.value===a)?.label??a;return{data:l,message:`Selected workspace: ${c}.`}}function sie(e,t){let n=new Map;for(let o of e){let s=f(o,"modeId"),a=f(o,"type");!s||a!=="personal"&&a!=="enterprise_workspace"||n.has(s)||n.set(s,o)}let r=[...n.values()],i=new Map;for(let o of r){let s=f(o,"modeId"),l=(f(o,"label")??s).trim().toLocaleLowerCase();i.set(l,[...i.get(l)??[],o])}return r.map(o=>{let s=f(o,"modeId"),a=f(o,"type"),l=f(o,"label")??s;if(a==="personal")return{value:s,label:l,description:s===t?"Currently selected \u2014 your personal library and public catalog":"Your personal library and public catalog"};let c=i.get(l.trim().toLocaleLowerCase())??[];if(c.length===1)return{value:s,label:l,...s===t?{description:"Currently selected"}:{}};let u=new Set(c.map(h=>f(h,"enterpriseId")).filter(Boolean)),d=u.size>1?f(o,"enterpriseId"):f(o,"workspaceId"),p=u.size>1?"Enterprise":"Workspace",m=aie(d??s);return{value:s,label:`${l} (${p} ${m})`,...s===t?{description:"Currently selected"}:{}}})}function aie(e){return e.replace(/^(?:enterprise|workspace)_/u,"").slice(0,8)}function lie(e){if(!e)return null;let t=e.mode??e.workingMode,n=L(t)?t:e,r=f(n,"modeId")??f(e,"selectedModeId"),i=f(n,"type");return!r||i!=="personal"&&i!=="enterprise_workspace"?null:{workingModeId:r,workingModeType:i,workingModeEnterpriseId:f(n,"enterpriseId"),workingModeWorkspaceId:f(n,"workspaceId"),workingModeGuardianPolicy:n.guardianPolicy==="standard"?"standard":"strict",workingModeRole:f(n,"role"),workingModeLabel:f(n,"label")}}async function ji(e,t){let n=lie(t);if(!n||!e.config)return e.config;let r={...e.config,...n,workingModeSavedAt:e.now()};return await CA(e.paths.configPath,r,e),e.config=r,r}async function NB(e,t,n){let r=[...new Set(t.map(i=>i.trim()).filter(Boolean))];for(let i of r){let o=await QP(e,i,n);if(o)return o}return null}async function QP(e,t,n){if(!e.apiKey)return null;let r=e.config?.workingModeType;if(r!=="personal"&&r!=="enterprise_workspace"){let i;try{i=await D(e,"/api/v1/me/install-policy",{headers:re(e.apiKey,e.authBlockedMessage)})}catch(o){if(o instanceof Z&&(o.status===403||o.status===409))return aP(o.details??{error:o.message},t,n.json);throw o}if(await ji(e,i),i.requiresWorkingModeSelection===!0)return x({status:"working_mode_selection_required",skillSlug:t,reasonCode:"working_mode_selection_required",nextAction:f(i,"nextAction")??"select_working_mode",nextStep:f(i,"nextStep")??"Select Personal or an Enterprise workspace before installing."},`Install blocked for ${t}. ${f(i,"nextStep")??"Select Personal or an Enterprise workspace before installing."}`,n.json,"working_mode_selection_required");r=e.config?.workingModeType}if(r!=="enterprise_workspace")return null;try{let i=await D(e,`/api/v1/skills/${encodeURIComponent(t)}/install-authorize`,{method:"POST",headers:V(e.apiKey,e.authBlockedMessage),body:JSON.stringify({})});return await ji(e,i),f(i,"status")==="authorized"?null:aP(i,t,n.json)}catch(i){if(i instanceof Z&&(i.status===403||i.status===409))return aP(i.details??{error:i.message},t,n.json);throw i}}function aP(e,t,n){let r=L(e.data)?e.data:e,i=f(e,"reasonCode")??f(r,"reasonCode"),o=f(e,"nextAction")??f(r,"nextAction"),s=f(e,"nextStep")??f(r,"nextStep"),a=f(r,"status")??"blocked";return x({...r,status:a,skillSlug:t,...i?{reasonCode:i}:{},...o?{nextAction:o}:{},...s?{nextStep:s}:{}},`Install blocked for ${t}${i?` (${i})`:""}.${s?` ${s}`:""}`,n,i)}function cie(e){let t=k(e);if(t)return t.split(",").map(n=>n.trim()).filter(Boolean)}async function uie(e,t,n){let r=e.join(" ").trim()||k(t.search)||"",i=new URLSearchParams;r&&i.set("query",r);let o=k(t.runtimeRisk);if(o&&!FB.includes(o))return cP("runtime-risk",o,FB,t);let s=k(t.agent);if(s&&!HM(s))return x({status:"error",reasonCode:"unknown_agent",filter:"agent",value:s,acceptedValues:Xt,nextAction:"search",nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown search --agent "${s}". Run \`skills-layer agents list\` to inspect supported agents.`,t.json,"unknown_agent");let a=k(t.trust);if(a&&!BB.includes(a))return cP("trust",a,BB,t);let l=k(t.securityCapability),c=xie(l);if(l&&!c)return cP("security-capability",l,KM,t);let u=wz(i,t);if(typeof u=="string")return x({status:"error",reasonCode:"invalid_limit",nextAction:"search",nextStep:"Use --limit with a positive whole number; values above 20 are clamped."},u,t.json,"invalid_limit");Ke(i,"agent",t.agent),Ke(i,"capability",t.capability),Ke(i,"trust",a),Ke(i,"runtime-risk",o),Ke(i,"security-capability",c);let d=await D(n,`/api/v1/search${at(i)}`);if(t.install!==void 0){let p=k(t.install);if(!p){if(t.json)return R("search --install requires an explicit skill slug in the public CLI package.",!0);let h=ur(d);if(h.length===0)return R("Search results do not include any installable skills. Run search again with a broader query.",!1);if(h.length===1)p=h[0].value;else try{p=await n.promptSelect("Select a search result to install:",h)}catch{return R("No search result was selected for install.",!1)}}let m=vce(d);return m.includes(p)?await Wa([p],t,n,{origin:"search_result",fallbackPolicy:"eligible_public"}):R(m.length===0?`Search results do not include "${p}". Run search again with a matching query first.`:`Search results do not include "${p}". Run search again with a matching query or choose one of: ${m.join(", ")}.`,t.json)}return A({...d,...u.length?{warnings:[...Array.isArray(d.warnings)?d.warnings:[],...u]}:{}},"Search complete.",t.json,n)}var FB=TA,BB=el,KM=["filesystem_read","filesystem_write","network_access","api_access","browser_access","device_control","generated_code_execution","secret_handling","model_context","shell_access"],die={network:"network_access",filesystem:"filesystem_read",files:"filesystem_read",file_read:"filesystem_read",file_write:"filesystem_write",shell:"shell_access",browser:"browser_access",device:"device_control",api:"api_access",secrets:"secret_handling",model:"model_context"},lP=["local","project","global","workspace"],Lu=["private","public","unlisted"],za=["private","public","unlisted"],MB=["github","gitlab","local","generic_git","domain"],pie=["owner","maintainer"],fie=["submitted","published","draft","pending_review","suspended","blocked","archived","unlisted"],mie=["open","acknowledged","fixed","closed","rejected","abusive","reopened","resolved"],gie=["visible","flagged","hidden"],hie=["bug","quality","safety","other"],yie=["approved","denied"],vie=["email","google","github","gitlab","microsoft"],kie=["email","google","github","gitlab","microsoft"],UB=["catalog:read","library:read","creator:read","creator:submit","source:read","source:write","guardian:check","guardian:incident","workspace:read","workspace:write","workspace:approve","mcp:use"],zB=["automation","mcp","agent"],qB=["active","expired","revoked","all"],VB=["created-desc","created-asc","expires-desc","expires-asc","name-asc","name-desc","last-used-desc","last-used-asc"];var WM=["json","sarif","report","passport","markdown"],uh=[...OA,"score"],wie=/^(?:card(?:_[A-Za-z0-9]+)*|pm_[A-Za-z0-9_]+)$/u,bie=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,_ie=/^[a-f0-9]{6,64}$/iu;function Sie(e,t,n,r){let i=k(t);if(!i)return{};if(!/^\d+$/u.test(i))return{failure:x({status:"error",reasonCode:"invalid_limit",command:e,value:i,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be a whole number from 1 to ${n}.`,r.json,"invalid_limit")};let o=Number.parseInt(i,10);return!Number.isInteger(o)||o<1||o>n?{failure:x({status:"error",reasonCode:"invalid_limit",command:e,value:i,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be between 1 and ${n}.`,r.json,"invalid_limit")}:{value:String(o)}}function cP(e,t,n,r){return x({status:"error",reasonCode:"invalid_search_filter",filter:e,value:t,acceptedValues:n,nextAction:"search",nextStep:e==="runtime-risk"?"Use --runtime-risk low, elevated, or high.":e==="limit"?"Use --limit with a whole number from 1 to 20.":`Use --${e} with one of: ${n.join(", ")}.`},e==="runtime-risk"?`Invalid runtime risk "${t}". Use one of: ${n.join(", ")}.`:e==="limit"?`Invalid search limit "${t}". Use a whole number from 1 to 20.`:`Invalid search --${e} "${t}". Use one of: ${n.join(", ")}.`,r.json,"invalid_search_filter")}function xie(e){if(e)return KM.includes(e)?e:die[e]}function Nr(e,t,n,r,i,o,s=t){return x({status:"error",reasonCode:o,[t]:n,acceptedValues:r,nextAction:e,nextStep:`Use --${s} with one of: ${r.join(", ")}.`},`Invalid ${e} --${s} "${n}". Use one of: ${r.join(", ")}.`,i.json,o)}function Mn(e,t,n,r,i,o,s=t){let a=k(n);if(!(!a||r.includes(a)))return Nr(e,t,a,r,i,o,s)}function Oi(e,t){let n=k(t.version);return n&&!Th(n)?eA(e,n,t):void 0}function Cie(e,t,n){return x({status:"error",reasonCode:"invalid_slug",value:t,acceptedFormat:"lowercase words separated by hyphens",nextAction:e,nextStep:"Use a lowercase skill slug such as project-planner or year9-history-study-guide."},`Invalid skill slug "${t}". Use lowercase letters, numbers, and single hyphens.`,n.json,"invalid_slug")}function ZM(e,t,n){return t&&!bie.test(t)?Cie(e,t,n):void 0}function Iie(e,t,n){return x({status:"error",reasonCode:"invalid_format",format:t,acceptedValues:WM,nextAction:e,nextStep:"Use --format json, sarif, report, passport, or markdown."},`Invalid ${e} --format "${t}". Use json, sarif, report, passport, or markdown.`,n.json,"invalid_format")}function JM(e,t){let n=k(t.format);return n&&!WM.includes(n.toLowerCase())?Iie(e,n,t):void 0}function Pie(e,t,n){return x({status:"error",reasonCode:"invalid_commit_sha",commitSha:t,nextAction:e,nextStep:"Use --commit-sha with a 6 to 64 character hexadecimal commit SHA."},`Invalid --commit-sha "${t}". Use a hexadecimal commit SHA.`,n.json,"invalid_commit_sha")}function Aie(e,t){let n=k(t.commitSha);return n&&!_ie.test(n)?Pie(e,n,t):void 0}function Rie(e,t){return x({status:"error",reasonCode:"invalid_base_url",baseUrl:e,nextAction:"backend",nextStep:"Use --base-url with HTTPS, or HTTP for loopback development only."},`Invalid backend base URL "${e}". Use HTTPS, or HTTP for loopback development only.`,t.json,"invalid_base_url")}function Eie(e,t){try{tl(e);return}catch{return Rie(e,t)}}function GB(e,t,n){return x({status:"error",reasonCode:"unexpected_argument",command:e,argument:t,nextAction:e,nextStep:`Run \`skills-layer ${e} --help\` to see supported arguments for this command.`},`Unexpected argument "${t}" for ${e}.`,n.json,"unexpected_argument")}function Qu(e,t){let n=k(t.scope);if(n&&!lP.includes(n))return{failure:x({status:"error",reasonCode:"invalid_install_filter",filter:"scope",value:n,acceptedValues:lP,nextAction:e,nextStep:"Use --scope local, project, global, or workspace."},`Invalid ${e} --scope "${n}". Use one of: ${lP.join(", ")}.`,t.json,"invalid_install_filter")};let r=k(t.agent);return r&&!(e==="install"&&r==="all")&&!HM(r)?{failure:x({status:"error",reasonCode:"unknown_agent",filter:"agent",value:r,acceptedValues:Xt,nextAction:e,nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown ${e} --agent "${r}". Run \`skills-layer agents\` to inspect supported agents.`,t.json,"unknown_agent")}:{scope:n,agent:r}}function YM(e,t){let n=Qu(e,t);if(n.failure)return n.failure;let r=k(t.version);if(e==="install"&&r&&!Th(r))return eA("install",r,t)}function eA(e,t,n){return x({status:"error",reasonCode:"invalid_version",command:e,version:t,nextAction:e,nextStep:"Use a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --version "${t}". Use a semver version or an external-<digest> version.`,n.json,"invalid_version")}function $ie(e,t,n){return x({status:"error",reasonCode:"invalid_expiry",command:e,expiresIn:t,acceptedFormat:"<positive whole number>d",maxDays:365,nextAction:e,nextStep:"Use --expires from 1d to 365d. Omit it for the 90-day default."},`Invalid --expires "${t}". Use a day duration from 1d to 365d. Omit it for the 90-day default.`,n.json,"invalid_expiry")}function Die(e,t,n){let r=k(t);if(r&&BA(r)===null)return $ie(e,r,n)}function Ni(e,t,n,r,i,o){let s=k(e);if(!s)return{};if(!/^\d+$/u.test(s))return{failure:x({status:"error",reasonCode:r,[n]:s,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`,i.json,r)};let a=Number(s);return!Number.isSafeInteger(a)||a<o.minimum?{failure:x({status:"error",reasonCode:r,[n]:s,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`,i.json,r)}:{value:a}}function HB(e,t,n,r,i,o){let s=Ni(e,t,n,`invalid_${n.replace(/[A-Z]/gu,a=>`_${a.toLowerCase()}`)}`,i,o);return s.failure?s.failure:s.value===void 0?R(`${r} requires ${t} <count>.`,i.json):s.value}function Tie(e){let t=k(e.paymentMethod)??"card";return wie.test(t)?{value:t}:{failure:x({status:"error",reasonCode:"invalid_payment_method",paymentMethod:t,acceptedValues:["card","card_<test-card>","pm_<provider-method-id>"],nextAction:"buy",nextStep:"Use --payment-method card or a provider token such as pm_<id>."},`Invalid payment method "${t}". Use card or a provider token such as pm_<id>.`,e.json,"invalid_payment_method")}}async function Oie(e,t,n){let r=new URLSearchParams,i=wz(r,t);if(typeof i=="string")return x({status:"error",reasonCode:"invalid_limit",nextAction:"search",nextStep:"Use --limit with a positive whole number; values above 20 are clamped."},i,t.json,"invalid_limit");let o=k(t.sort);if(o&&!uh.includes(o))return x({status:"error",reasonCode:"invalid_sort",sort:o,acceptedValues:uh,nextAction:e,nextStep:`Use --sort with one of: ${uh.join(", ")}.`},`${e} --sort must be one of: ${uh.join(", ")}.`,t.json,"invalid_sort");Ke(r,"search",t.search),Ke(r,"sort",o);let s=await D(n,`/api/v1/${e}${at(r)}`);return A({...s,...i.length?{warnings:[...Array.isArray(s.warnings)?s.warnings:[],...i]}:{}},e==="trending"&&typeof s.basis=="string"?DA(s.basis):`${Fh(e)} skills loaded.`,t.json,n)}async function Lie(e,t,n){let r=e.join(" ").trim();if(!r)return R("recommend requires a task.",t.json);let i=Sie("recommend",t.limit,20,t);if(i.failure)return i.failure;let o=new URLSearchParams({task:r});Ke(o,"limit",i.value);let s=await D(n,`/api/v1/recommend?${o.toString()}`,{headers:Wo(n.apiKey)});return A(s,f(s,"summary")??"Recommendations loaded.",t.json,n)}async function jie(e,t,n){if(e.length<2)return R("compare requires two or more skill slugs.",t.json);if(e.length>5)return x({status:"error",reasonCode:"too_many_compare_slugs",requestedCount:e.length,maxItems:5,nextAction:"compare",nextStep:"Compare up to 5 skills at a time."},"compare supports up to 5 skill slugs at a time.",t.json,"too_many_compare_slugs");let r=new URLSearchParams({slugs:e.join(",")}),i=await D(n,`/api/v1/skills/compare?${r.toString()}`),o=Array.isArray(i.missing)?i.missing.filter(s=>typeof s=="string"):[];return o.length>0?x({...i,status:"not_found",reasonCode:"compare_missing_skills",missing:o,nextAction:"search",nextStep:`Run \`skills-layer search ${o[0]}\` to find the correct slug, then retry compare.`},`Comparison could not find: ${o.join(", ")}.`,t.json,"compare_missing_skills"):t.json?A(i,"Comparison loaded.",!0,n):{exitCode:0,stdout:Ile(i,"Comparison loaded.",Pe(n),t.verbose),stderr:""}}async function Nie(e,t,n){let r=T(e[0],"show requires a skill slug."),i=await D(n,`/api/v1/skills/${encodeURIComponent(r)}`);return A(Gh(i),"Skill loaded.",t.json,n)}async function Fie(e,t,n){let r=T(e[0],"trust requires a skill slug."),i=JM("trust",t);if(i)return i;let o=new URLSearchParams;Ke(o,"format",t.format),Ke(o,"version",t.version),Ke(o,"versionId",t.versionId);let s=await D(n,`/api/v1/skills/${encodeURIComponent(r)}/platform-score${at(o)}`);return k(t.format)?.toLowerCase()==="sarif"?{exitCode:0,stdout:JSON.stringify(s,null,2),stderr:""}:!t.json&&rC(s)?{exitCode:0,stdout:H(GL(s)),stderr:""}:A(s,"Platform Score loaded.",t.json,n)}async function Bie(e,t,n){e.length===0&&n.renderMode.detail==="full"&&(e=["full"]);let r=e[0];if(t.json||n.renderMode.kind==="json-final"){if(r==="full")return A(aN(),"Help loaded.",!0,n);let a=e.length===1?Rg(r,bo):null;if(a)return A({status:"ok",kind:"goal_help",goal:a},"Help loaded.",!0,n);let l=r==="topic"?_o(e[1]):_o(r,e.slice(1));if(l)return A(l,"Help loaded.",!0,n);if(r!=="topic"&&!rre.has(r??""))return IP(e,!0)}if(!r){if(n.renderMode.kind==="json-stream"||!n.helpInteractive)return{exitCode:0,stdout:Lo(n.renderMode),stderr:""};let a;try{a=await n.promptSelect("What do you want to do?",nN(bo))}catch{a=void 0}if(!a)return{exitCode:0,stdout:Lo(n.renderMode),stderr:""};if(a==="full")return Ba(Lo(n.renderMode,!0),"full",t,n);let l=Rg(a,bo);return l?Ba(XC(l),l.id,t,n):{exitCode:0,stdout:Lo(n.renderMode),stderr:""}}if(r==="full")return Ba(Lo(n.renderMode,!0),"full",t,n);let o=e.length===1?Rg(r,bo):null;if(o)return Ba(XC(o),o.id,t,n);let s=vu(e[0],e.slice(1));if(s)return Ba(s,e.filter(Boolean).join(" "),t,n);if(r==="topic"){let a=vu(e[1]);if(a)return Ba(a,e[1]??"overview",t,n);let l=new URLSearchParams;return e[1]&&l.set("topic",e[1]),await me(`/api/v1/help${at(l)}`,t,n,"Help topic loaded.")}if(r==="standards")return await me("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let a=await D(n,"/api/v1/marketplace/status");return t.json?A(a,"Marketplace status loaded.",!0,n):A(Dle(a),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let a=await D(n,"/api/v1/capabilities");return A(Ole(a),"Edition capabilities loaded.",t.json,n)}if(r==="schema-plan")return R("help schema-plan is not included in the public npm CLI.",t.json);if(r==="optimize-tokens"){let a=T(t.text,"help optimize-tokens requires --text."),l=Lle(t.maxCharacters,t.json);if(fe(l))return l;let c=await D(n,"/api/v1/optimize-tokens",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({text:a,...l?{maxCharacters:l}:{}})});return A(c,"Token optimization complete.",t.json,n)}return R(`Unknown help command "${r}".`,t.json)}function Ba(e,t,n,r){return n.json?A({status:"ok",topic:t,content:e},"Help topic loaded.",!0,r):{exitCode:0,stdout:e,stderr:""}}function IP(e,t){let n=e.filter(Boolean).join(" ").trim()||"help";return x({status:"not_found",reasonCode:"help_topic_not_found",topic:n,nextAction:"help",nextStep:"Run `skills-layer --help`, `skills-layer help full`, or `skills-layer <command> --help` for a supported command."},`Help topic not found: ${n}.`,t,"help_topic_not_found")}async function Mie(e,t,n){let r=T(e[0]??t.path,"validate requires a file or directory."),i=Tt(n.cwd,r);if(!await pr(i))return IU("validate",r,t,n);let o=(await ma({cwd:n.cwd,sourcePath:r,limits:yo})).files;o=await Uie({files:o,resolvedTarget:i,flags:t,backend:n});let s=tt(o),a={files:o,sourceIntakeContext:k(t.sourceIntakeContext),publicationStatus:k(t.publicationStatus),dependencyAuditStatus:k(t.dependencyAuditStatus),category:k(t.category),discloseSource:!!t.discloseSource},l;try{l=await D(n,"/api/v1/validation/preview",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(ie(a))})}catch(d){if(d instanceof Z&&d.status===422&&d.details)l=bce(d.details);else throw d}let c=zie({...l,license:s.license,licenseIssues:s.issues.filter(d=>d.code.startsWith("license_"))},o),u=c.valid===!1||j(c,"validation")?.valid===!1;return t.json?u?x({...cz(c,n.renderMode.detail,"validate"),nextAction:"validate",nextStep:"Fix the listed issues, then run validate again."},"Validation failed.",!0,"bundle_invalid"):A(c,"Validation complete.",!0,n,"validate"):{exitCode:u?1:0,stdout:jle(c,r,n),stderr:""}}async function Uie(e){if(tt(e.files).license?.status==="verified"||e.flags.json||!e.backend.stdoutIsTty)return e.files;let n=await Mk({cwd:e.backend.cwd,files:e.files,skip:!1,interactive:!0,prompt:XM(e.backend)});if(n.selection.mode==="skip"||await e.backend.promptSelect("Apply this licence change to the local bundle?",[{value:"apply",label:"Apply the reviewed change"},{value:"cancel",label:"Cancel without changing files"}])!=="apply")return e.files;let o=(await Ja(e.resolvedTarget)).isDirectory()?e.resolvedTarget:Be(e.resolvedTarget);return await Jp({targetDir:o,files:z1(e.files,n.selection),confirmed:!0}),(await ma({cwd:e.backend.cwd,sourcePath:o})).files}function zie(e,t){return{...e,evalReadiness:Hk(t)}}function qie(e,t){let n=Vie(e);return Es({status:n?"not_run":"generated_only",skillSlug:t.skillSlug,version:t.version,artifactDigest:ct(e),...n?{evalPackDigest:n}:{},generatedAt:t.generatedAt,runnerVersion:So,counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})}function Vie(e){let t=e.find(n=>{let r=$n(n.path,e);return r.type==="evidence"&&typeof n.content=="string"&&(r.relativePath.startsWith("evals/")||r.relativePath.endsWith(".eval.json")||r.relativePath.endsWith(".eval.yaml"))});if(t?.content)try{return Rs(JSON.parse(t.content))}catch{return}}async function Gie(e,t,n){let r=T(e[0]??t.path,"preview-trigger requires a file or directory."),i=Tt(n.cwd,r);if(!await pr(i))return IU("preview-trigger",r,t,n);let o=(await ma({cwd:n.cwd,sourcePath:r,limits:yo})).files,s=await D(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({files:o,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?A(s,"Trigger preview complete.",!0,n):{exitCode:0,stdout:Nle(s,r,n),stderr:""}}async function Hie(e,t,n){let r=e[0];if(["create","sessions","resume","inspect","answer","resources","resource-decide","tool-contract","draft","validate","eval","improve","revise","materialize","finalize"].includes(r??""))return await WB(r,e.slice(1),t,n);if(r==="init")return t.quick?await WB("create",e.slice(1),{...t,mode:"quick"},n):await Wie(e.slice(1),t,n);if(r==="rules")return await me("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(r==="submissions")return await me("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(r==="status"){let i=T(e[1],"creator status requires a skill slug.");try{return await me(`/api/v1/me/submissions/${encodeURIComponent(i)}/status`,t,n,"Submission status loaded.",{authenticated:!0})}catch(o){if(o instanceof Z&&o.status===404)return roe(i,t);throw o}}if(r==="charge-status"){let i=T(e[1],"creator charge-status requires a charge id.");return await me(`/api/v1/me/private-skill-charges/${encodeURIComponent(i)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(r==="spaces")return await Yie(e.slice(1),t,n);if(r==="submit")return await AP(e.slice(1),t,n,!1);if(r==="submit-version")return await AP(e.slice(1),t,n,!0);if(r==="check-slug"){let i=T(e[1],"creator check-slug requires a slug.");return await toe(i,t,n)}if(r==="rename"){let i=T(e[1],"creator rename requires the current slug."),o=T(e[2],"creator rename requires the new slug."),s=ZM("creator.rename",o,t);return s||await Li(`/api/v1/me/submissions/${encodeURIComponent(i)}/slug`,{nextSkillSlug:o},t,n,"Skill renamed.")}if(r==="pricing")return await ooe(e,t,n);if(r==="update-listing"){let i=T(e[1],"creator update-listing requires a skill slug.");return await soe(i,t,n)}if(r==="visibility"){let i=T(e[1],"creator visibility requires a skill slug."),o=Oi("creator.visibility",t);if(o)return o;let s=k(t.visibility)??e[2],a=uc(s);if(!a||!Lu.includes(a))return x({status:"error",reasonCode:"invalid_visibility",skillSlug:i,visibility:s??null,acceptedValues:Lu,nextAction:"creator.visibility",nextStep:"Use --visibility private, public, or unlisted."},`Invalid creator visibility "${s??""}". Use one of: ${Lu.join(", ")}.`,t.json,"invalid_visibility");let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/visibility`,{method:"PATCH",headers:V(n.apiKey),body:JSON.stringify(ie({visibility:a,dryRun:t.dryRun}))});return cse(l)?x(l,use(l,i),t.json,f(l,"reasonCode")??f(l,"status")):A(l,t.dryRun?"Visibility preview loaded.":"Visibility updated.",t.json,n)}if(r==="security-report"){let i=T(e[1],"creator security-report requires a skill slug."),o=JM("creator.security-report",t);if(o)return o;let s=Oi("creator.security-report",t);if(s)return s;let a=new URLSearchParams;Ke(a,"format",t.format),Ke(a,"version",t.version),Ke(a,"versionId",t.versionId);let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security-report${at(a)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?A(l,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:ece(l,i,n),stderr:""}}if(r==="rescan-security"){let i=T(e[1],"creator rescan-security requires a skill slug."),o=Oi("creator.rescan-security",t);if(o)return o;let s=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security/rescan`,{method:"POST",headers:V(n.apiKey),body:JSON.stringify(ie(Ft(t,["version","versionId"])))});return t.json?A(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:tce(s,i,n),stderr:""}}if(r==="provenance"){let i=T(e[1],"creator provenance requires a skill slug.");return await me(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership`,t,n,"Provenance loaded.",{authenticated:!0})}if(r==="claim"||r==="verify"||r==="dispute")return await aoe(r,e,t,n);if(r==="issues"||r==="reviews"||r==="update-issue"||r==="moderate-review")return await foe(r,e,t,n);if(r==="analytics"){let i=T(e[1],"creator analytics requires a skill slug.");return await loe(i,t,n)}if(r==="delist"||r==="relist"){let i=T(e[1],`creator ${r} requires a skill slug.`),o=k(t.reason)??(r==="relist"?"Creator relisted skill":"");return o.trim().length<3?R("creator delist requires --reason (at least 3 characters).",t.json):await Li(`/api/v1/me/submissions/${encodeURIComponent(i)}`,{lifecycle:r==="delist"?"delisted":"active",reason:o},t,n,`${i} ${r==="delist"?"delisted":"relisted"}; existing buyers keep access.`)}if(r==="earnings")return await me("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0});if(r==="payout-profile")return k(t.country)?await eM(t,n):await coe(t,n);if(r==="payout-link")return await eM(t,n);if(r==="payouts")return await me("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0});if(r==="withdraw"){if(!k(t.amountCents))return R("creator withdraw requires --amount-cents.",t.json);let i=Ni(t.amountCents,"--amount-cents","amountCents","invalid_amount_cents",t,{minimum:1});if(i.failure)return i.failure;let o=k(t.idempotencyKey)??ele();if(t.json||!n.stdoutIsTty)return x({status:"blocked",reasonCode:"payout_human_confirmation_required",nextAction:"creator.withdraw",nextStep:"Use an interactive terminal. MCP returns a browser handoff, and automation credentials cannot withdraw."},"Creator withdrawal requires an interactive human confirmation. Use an interactive terminal; MCP returns a browser handoff and automation credentials cannot withdraw.",t.json,"payout_human_confirmation_required");let s=ie({amountCents:i.value,reason:k(t.reason)}),a={...V(n.apiKey),"idempotency-key":o},l=await D(n,"/api/v1/me/payouts",{method:"POST",headers:a,body:JSON.stringify(s)});if(l.status!=="confirmation_required"||typeof l.confirmationId!="string"||typeof l.confirmationToken!="string"||typeof l.confirmationPhrase!="string")throw new Error("The payout service did not return a valid action-bound confirmation challenge.");let c=l.impact&&typeof l.impact=="object"?l.impact:{};if(await n.promptText(`Withdrawal impact: ${String(c.amountCents??i.value)} ${String(c.currency??"usd").toUpperCase()}, remaining withdrawable balance ${String(c.withdrawableAfterCents??"unknown")} cents.
|
|
2137
|
+
`);return`skills-layer-cli:mcp-token:${Me("sha256").update(t).digest("base64url").slice(0,32)}`}async function xP(e,t){if(e.noMcp)return{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."};let n=await ke(t.paths.mcpConfigPath),r=n?f(n,"baseUrl"):void 0,i=n?f(n,"clientId"):null;if(!e.withMcp&&r===t.baseUrl&&i)return{data:{status:"mcp_already_configured",configured:!0,clientId:i,mcpUrl:n?f(n,"mcpUrl")??`${t.baseUrl}/mcp`:`${t.baseUrl}/mcp`},message:"MCP is already configured for this machine."};let o=e.withMcp===!0;if(!o&&!e.json)try{let a=await t.promptSelect("Set up Skills Layer MCP for your AI tools on this machine?",[{value:"yes",label:"Yes, set up MCP",description:"Mint a scoped token and write local MCP configuration"},{value:"no",label:"Not now",description:"You can run skills-layer mcp setup later"}]);if(o=a==="yes",a==="no")return await We(t.paths.mcpPreferencePath,{force:!0}),{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."}}catch{return{}}if(!o)return{};let s=await XP(e,t);return fe(s)?{data:oie(s),message:"Login completed, but MCP was not configured. Choose a verified host with `skills-layer mcp setup --client <host-id>` or use `--all`."}:{data:s,message:"MCP configuration written for this machine. Open a fresh agent session so your AI tools can load it."}}function oie(e){let t="mcp_setup_failed";try{let n=JSON.parse(e.stderr);t=f(n,"reasonCode")??t}catch{e.stderr.includes("OS-secure credential storage")&&(t="mcp_secure_storage_required")}return{status:"mcp_not_configured",configured:!1,reasonCode:t,nextAction:"mcp.setup",nextCommand:"skills-layer mcp setup --client <host-id>",nextStep:"Run `skills-layer mcp setup --client <host-id>` after resolving the reported MCP prerequisite, or use `--all`."}}function CP(e,t){return t?t.status==="mcp_skipped"?{...e,nextAction:"whoami",nextStep:"Run `skills-layer whoami` to check your account."}:t.configured!==!1?{...e,nextAction:"mcp.verify",nextStep:"Open a fresh agent session so it can load Skills Layer, then run `skills-layer mcp verify` if the tools are not visible."}:t.configured===!1||t.status==="mcp_skipped"?{...e,nextAction:"mcp.setup",nextStep:"Run `skills-layer mcp setup` when you want Skills Layer available to your AI tools."}:e:e}async function wh(e,t){if(t.config?.edition==="community")return{};let n;try{n=await D(t,"/api/v1/me/working-modes",{headers:re(t.apiKey,t.authBlockedMessage)})}catch{return{}}await ji(t,n);let r=Array.isArray(n.modes)?n.modes.filter(L):[],i=f(n,"selectedModeId");if(!r.some(u=>f(u,"type")==="enterprise_workspace")){let u=r.find(p=>f(p,"modeId")===i),d=u?f(u,"label")??i:i;return i?{data:{status:"working_mode_selected",selectedModeId:i,...u?{mode:u}:{}},message:`Selected workspace: ${d}.`}:{}}let s=sie(r,i);if(s.length===0)return{};if(e.json)return x({status:"working_mode_selection_required",reasonCode:"working_mode_selection_required",selectedModeId:i??null,modes:r,nextAction:"workspace.select",nextStep:"Run `skills-layer workspace select personal` or `skills-layer workspace select <workspace-id>`."},"Select Personal or an Enterprise workspace to finish signing in.",!0,"working_mode_selection_required");let a;try{a=await t.promptSelect("Select your Skills Layer workspace:",s)}catch{return x({status:"working_mode_selection_required",reasonCode:"working_mode_selection_required",selectedModeId:f(n,"selectedModeId")??null,modes:r,nextAction:"workspace.select",nextStep:"Run `skills-layer workspace select personal` or `skills-layer workspace select <workspace-id>`."},"Select Personal or an Enterprise workspace to finish signing in.",e.json,"working_mode_selection_required")}let l=await D(t,"/api/v1/me/working-mode",{method:"PUT",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({modeId:a})});await ji(t,l);let c=s.find(u=>u.value===a)?.label??a;return{data:l,message:`Selected workspace: ${c}.`}}function sie(e,t){let n=new Map;for(let o of e){let s=f(o,"modeId"),a=f(o,"type");!s||a!=="personal"&&a!=="enterprise_workspace"||n.has(s)||n.set(s,o)}let r=[...n.values()],i=new Map;for(let o of r){let s=f(o,"modeId"),l=(f(o,"label")??s).trim().toLocaleLowerCase();i.set(l,[...i.get(l)??[],o])}return r.map(o=>{let s=f(o,"modeId"),a=f(o,"type"),l=f(o,"label")??s;if(a==="personal")return{value:s,label:l,description:s===t?"Currently selected \u2014 your personal library and public catalog":"Your personal library and public catalog"};let c=i.get(l.trim().toLocaleLowerCase())??[];if(c.length===1)return{value:s,label:l,...s===t?{description:"Currently selected"}:{}};let u=new Set(c.map(h=>f(h,"enterpriseId")).filter(Boolean)),d=u.size>1?f(o,"enterpriseId"):f(o,"workspaceId"),p=u.size>1?"Enterprise":"Workspace",m=aie(d??s);return{value:s,label:`${l} (${p} ${m})`,...s===t?{description:"Currently selected"}:{}}})}function aie(e){return e.replace(/^(?:enterprise|workspace)_/u,"").slice(0,8)}function lie(e){if(!e)return null;let t=e.mode??e.workingMode,n=L(t)?t:e,r=f(n,"modeId")??f(e,"selectedModeId"),i=f(n,"type");return!r||i!=="personal"&&i!=="enterprise_workspace"?null:{workingModeId:r,workingModeType:i,workingModeEnterpriseId:f(n,"enterpriseId"),workingModeWorkspaceId:f(n,"workspaceId"),workingModeGuardianPolicy:n.guardianPolicy==="standard"?"standard":"strict",workingModeRole:f(n,"role"),workingModeLabel:f(n,"label")}}async function ji(e,t){let n=lie(t);if(!n||!e.config)return e.config;let r={...e.config,...n,workingModeSavedAt:e.now()};return await CA(e.paths.configPath,r,e),e.config=r,r}async function NB(e,t,n){let r=[...new Set(t.map(i=>i.trim()).filter(Boolean))];for(let i of r){let o=await QP(e,i,n);if(o)return o}return null}async function QP(e,t,n){if(!e.apiKey)return null;let r=e.config?.workingModeType;if(r!=="personal"&&r!=="enterprise_workspace"){let i;try{i=await D(e,"/api/v1/me/install-policy",{headers:re(e.apiKey,e.authBlockedMessage)})}catch(o){if(o instanceof Z&&(o.status===403||o.status===409))return aP(o.details??{error:o.message},t,n.json);throw o}if(await ji(e,i),i.requiresWorkingModeSelection===!0)return x({status:"working_mode_selection_required",skillSlug:t,reasonCode:"working_mode_selection_required",nextAction:f(i,"nextAction")??"select_working_mode",nextStep:f(i,"nextStep")??"Select Personal or an Enterprise workspace before installing."},`Install blocked for ${t}. ${f(i,"nextStep")??"Select Personal or an Enterprise workspace before installing."}`,n.json,"working_mode_selection_required");r=e.config?.workingModeType}if(r!=="enterprise_workspace")return null;try{let i=await D(e,`/api/v1/skills/${encodeURIComponent(t)}/install-authorize`,{method:"POST",headers:V(e.apiKey,e.authBlockedMessage),body:JSON.stringify({})});return await ji(e,i),f(i,"status")==="authorized"?null:aP(i,t,n.json)}catch(i){if(i instanceof Z&&(i.status===403||i.status===409))return aP(i.details??{error:i.message},t,n.json);throw i}}function aP(e,t,n){let r=L(e.data)?e.data:e,i=f(e,"reasonCode")??f(r,"reasonCode"),o=f(e,"nextAction")??f(r,"nextAction"),s=f(e,"nextStep")??f(r,"nextStep"),a=f(r,"status")??"blocked";return x({...r,status:a,skillSlug:t,...i?{reasonCode:i}:{},...o?{nextAction:o}:{},...s?{nextStep:s}:{}},`Install blocked for ${t}${i?` (${i})`:""}.${s?` ${s}`:""}`,n,i)}function cie(e){let t=k(e);if(t)return t.split(",").map(n=>n.trim()).filter(Boolean)}async function uie(e,t,n){let r=e.join(" ").trim()||k(t.search)||"",i=new URLSearchParams;r&&i.set("query",r);let o=k(t.runtimeRisk);if(o&&!FB.includes(o))return cP("runtime-risk",o,FB,t);let s=k(t.agent);if(s&&!HM(s))return x({status:"error",reasonCode:"unknown_agent",filter:"agent",value:s,acceptedValues:Xt,nextAction:"search",nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown search --agent "${s}". Run \`skills-layer agents list\` to inspect supported agents.`,t.json,"unknown_agent");let a=k(t.trust);if(a&&!BB.includes(a))return cP("trust",a,BB,t);let l=k(t.securityCapability),c=xie(l);if(l&&!c)return cP("security-capability",l,KM,t);let u=wz(i,t);if(typeof u=="string")return x({status:"error",reasonCode:"invalid_limit",nextAction:"search",nextStep:"Use --limit with a positive whole number; values above 20 are clamped."},u,t.json,"invalid_limit");Ke(i,"agent",t.agent),Ke(i,"capability",t.capability),Ke(i,"trust",a),Ke(i,"runtime-risk",o),Ke(i,"security-capability",c);let d=await D(n,`/api/v1/search${Qe(i)}`);if(t.install!==void 0){let p=k(t.install);if(!p){if(t.json)return R("search --install requires an explicit skill slug in the public CLI package.",!0);let h=ur(d);if(h.length===0)return R("Search results do not include any installable skills. Run search again with a broader query.",!1);if(h.length===1)p=h[0].value;else try{p=await n.promptSelect("Select a search result to install:",h)}catch{return R("No search result was selected for install.",!1)}}let m=vce(d);return m.includes(p)?await Wa([p],t,n,{origin:"search_result",fallbackPolicy:"eligible_public"}):R(m.length===0?`Search results do not include "${p}". Run search again with a matching query first.`:`Search results do not include "${p}". Run search again with a matching query or choose one of: ${m.join(", ")}.`,t.json)}return A({...d,...u.length?{warnings:[...Array.isArray(d.warnings)?d.warnings:[],...u]}:{}},"Search complete.",t.json,n)}var FB=TA,BB=el,KM=["filesystem_read","filesystem_write","network_access","api_access","browser_access","device_control","generated_code_execution","secret_handling","model_context","shell_access"],die={network:"network_access",filesystem:"filesystem_read",files:"filesystem_read",file_read:"filesystem_read",file_write:"filesystem_write",shell:"shell_access",browser:"browser_access",device:"device_control",api:"api_access",secrets:"secret_handling",model:"model_context"},lP=["local","project","global","workspace"],Lu=["private","public","unlisted"],za=["private","public","unlisted"],MB=["github","gitlab","local","generic_git","domain"],pie=["owner","maintainer"],fie=["submitted","published","draft","pending_review","suspended","blocked","archived","unlisted"],mie=["open","acknowledged","fixed","closed","rejected","abusive","reopened","resolved"],gie=["visible","flagged","hidden"],hie=["bug","quality","safety","other"],yie=["approved","denied"],vie=["email","google","github","gitlab","microsoft"],kie=["email","google","github","gitlab","microsoft"],UB=["catalog:read","library:read","creator:read","creator:submit","source:read","source:write","guardian:check","guardian:incident","workspace:read","workspace:write","workspace:approve","mcp:use"],zB=["automation","mcp","agent"],qB=["active","expired","revoked","all"],VB=["created-desc","created-asc","expires-desc","expires-asc","name-asc","name-desc","last-used-desc","last-used-asc"];var WM=["json","sarif","report","passport","markdown"],uh=[...OA,"score"],wie=/^(?:card(?:_[A-Za-z0-9]+)*|pm_[A-Za-z0-9_]+)$/u,bie=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,_ie=/^[a-f0-9]{6,64}$/iu;function Sie(e,t,n,r){let i=k(t);if(!i)return{};if(!/^\d+$/u.test(i))return{failure:x({status:"error",reasonCode:"invalid_limit",command:e,value:i,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be a whole number from 1 to ${n}.`,r.json,"invalid_limit")};let o=Number.parseInt(i,10);return!Number.isInteger(o)||o<1||o>n?{failure:x({status:"error",reasonCode:"invalid_limit",command:e,value:i,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be between 1 and ${n}.`,r.json,"invalid_limit")}:{value:String(o)}}function cP(e,t,n,r){return x({status:"error",reasonCode:"invalid_search_filter",filter:e,value:t,acceptedValues:n,nextAction:"search",nextStep:e==="runtime-risk"?"Use --runtime-risk low, elevated, or high.":e==="limit"?"Use --limit with a whole number from 1 to 20.":`Use --${e} with one of: ${n.join(", ")}.`},e==="runtime-risk"?`Invalid runtime risk "${t}". Use one of: ${n.join(", ")}.`:e==="limit"?`Invalid search limit "${t}". Use a whole number from 1 to 20.`:`Invalid search --${e} "${t}". Use one of: ${n.join(", ")}.`,r.json,"invalid_search_filter")}function xie(e){if(e)return KM.includes(e)?e:die[e]}function Nr(e,t,n,r,i,o,s=t){return x({status:"error",reasonCode:o,[t]:n,acceptedValues:r,nextAction:e,nextStep:`Use --${s} with one of: ${r.join(", ")}.`},`Invalid ${e} --${s} "${n}". Use one of: ${r.join(", ")}.`,i.json,o)}function Mn(e,t,n,r,i,o,s=t){let a=k(n);if(!(!a||r.includes(a)))return Nr(e,t,a,r,i,o,s)}function Oi(e,t){let n=k(t.version);return n&&!Th(n)?eA(e,n,t):void 0}function Cie(e,t,n){return x({status:"error",reasonCode:"invalid_slug",value:t,acceptedFormat:"lowercase words separated by hyphens",nextAction:e,nextStep:"Use a lowercase skill slug such as project-planner or year9-history-study-guide."},`Invalid skill slug "${t}". Use lowercase letters, numbers, and single hyphens.`,n.json,"invalid_slug")}function ZM(e,t,n){return t&&!bie.test(t)?Cie(e,t,n):void 0}function Iie(e,t,n){return x({status:"error",reasonCode:"invalid_format",format:t,acceptedValues:WM,nextAction:e,nextStep:"Use --format json, sarif, report, passport, or markdown."},`Invalid ${e} --format "${t}". Use json, sarif, report, passport, or markdown.`,n.json,"invalid_format")}function JM(e,t){let n=k(t.format);return n&&!WM.includes(n.toLowerCase())?Iie(e,n,t):void 0}function Pie(e,t,n){return x({status:"error",reasonCode:"invalid_commit_sha",commitSha:t,nextAction:e,nextStep:"Use --commit-sha with a 6 to 64 character hexadecimal commit SHA."},`Invalid --commit-sha "${t}". Use a hexadecimal commit SHA.`,n.json,"invalid_commit_sha")}function Aie(e,t){let n=k(t.commitSha);return n&&!_ie.test(n)?Pie(e,n,t):void 0}function Rie(e,t){return x({status:"error",reasonCode:"invalid_base_url",baseUrl:e,nextAction:"backend",nextStep:"Use --base-url with HTTPS, or HTTP for loopback development only."},`Invalid backend base URL "${e}". Use HTTPS, or HTTP for loopback development only.`,t.json,"invalid_base_url")}function Eie(e,t){try{tl(e);return}catch{return Rie(e,t)}}function GB(e,t,n){return x({status:"error",reasonCode:"unexpected_argument",command:e,argument:t,nextAction:e,nextStep:`Run \`skills-layer ${e} --help\` to see supported arguments for this command.`},`Unexpected argument "${t}" for ${e}.`,n.json,"unexpected_argument")}function Qu(e,t){let n=k(t.scope);if(n&&!lP.includes(n))return{failure:x({status:"error",reasonCode:"invalid_install_filter",filter:"scope",value:n,acceptedValues:lP,nextAction:e,nextStep:"Use --scope local, project, global, or workspace."},`Invalid ${e} --scope "${n}". Use one of: ${lP.join(", ")}.`,t.json,"invalid_install_filter")};let r=k(t.agent);return r&&!(e==="install"&&r==="all")&&!HM(r)?{failure:x({status:"error",reasonCode:"unknown_agent",filter:"agent",value:r,acceptedValues:Xt,nextAction:e,nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown ${e} --agent "${r}". Run \`skills-layer agents\` to inspect supported agents.`,t.json,"unknown_agent")}:{scope:n,agent:r}}function YM(e,t){let n=Qu(e,t);if(n.failure)return n.failure;let r=k(t.version);if(e==="install"&&r&&!Th(r))return eA("install",r,t)}function eA(e,t,n){return x({status:"error",reasonCode:"invalid_version",command:e,version:t,nextAction:e,nextStep:"Use a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --version "${t}". Use a semver version or an external-<digest> version.`,n.json,"invalid_version")}function $ie(e,t,n){return x({status:"error",reasonCode:"invalid_expiry",command:e,expiresIn:t,acceptedFormat:"<positive whole number>d",maxDays:365,nextAction:e,nextStep:"Use --expires from 1d to 365d. Omit it for the 90-day default."},`Invalid --expires "${t}". Use a day duration from 1d to 365d. Omit it for the 90-day default.`,n.json,"invalid_expiry")}function Die(e,t,n){let r=k(t);if(r&&BA(r)===null)return $ie(e,r,n)}function Ni(e,t,n,r,i,o){let s=k(e);if(!s)return{};if(!/^\d+$/u.test(s))return{failure:x({status:"error",reasonCode:r,[n]:s,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`,i.json,r)};let a=Number(s);return!Number.isSafeInteger(a)||a<o.minimum?{failure:x({status:"error",reasonCode:r,[n]:s,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`,i.json,r)}:{value:a}}function HB(e,t,n,r,i,o){let s=Ni(e,t,n,`invalid_${n.replace(/[A-Z]/gu,a=>`_${a.toLowerCase()}`)}`,i,o);return s.failure?s.failure:s.value===void 0?R(`${r} requires ${t} <count>.`,i.json):s.value}function Tie(e){let t=k(e.paymentMethod)??"card";return wie.test(t)?{value:t}:{failure:x({status:"error",reasonCode:"invalid_payment_method",paymentMethod:t,acceptedValues:["card","card_<test-card>","pm_<provider-method-id>"],nextAction:"buy",nextStep:"Use --payment-method card or a provider token such as pm_<id>."},`Invalid payment method "${t}". Use card or a provider token such as pm_<id>.`,e.json,"invalid_payment_method")}}async function Oie(e,t,n){let r=new URLSearchParams,i=wz(r,t);if(typeof i=="string")return x({status:"error",reasonCode:"invalid_limit",nextAction:"search",nextStep:"Use --limit with a positive whole number; values above 20 are clamped."},i,t.json,"invalid_limit");let o=k(t.sort);if(o&&!uh.includes(o))return x({status:"error",reasonCode:"invalid_sort",sort:o,acceptedValues:uh,nextAction:e,nextStep:`Use --sort with one of: ${uh.join(", ")}.`},`${e} --sort must be one of: ${uh.join(", ")}.`,t.json,"invalid_sort");Ke(r,"search",t.search),Ke(r,"sort",o);let s=await D(n,`/api/v1/${e}${Qe(r)}`);return A({...s,...i.length?{warnings:[...Array.isArray(s.warnings)?s.warnings:[],...i]}:{}},e==="trending"&&typeof s.basis=="string"?DA(s.basis):`${Fh(e)} skills loaded.`,t.json,n)}async function Lie(e,t,n){let r=e.join(" ").trim();if(!r)return R("recommend requires a task.",t.json);let i=Sie("recommend",t.limit,20,t);if(i.failure)return i.failure;let o=new URLSearchParams({task:r});Ke(o,"limit",i.value);let s=await D(n,`/api/v1/recommend?${o.toString()}`,{headers:Wo(n.apiKey)});return A(s,f(s,"summary")??"Recommendations loaded.",t.json,n)}async function jie(e,t,n){if(e.length<2)return R("compare requires two or more skill slugs.",t.json);if(e.length>5)return x({status:"error",reasonCode:"too_many_compare_slugs",requestedCount:e.length,maxItems:5,nextAction:"compare",nextStep:"Compare up to 5 skills at a time."},"compare supports up to 5 skill slugs at a time.",t.json,"too_many_compare_slugs");let r=new URLSearchParams({slugs:e.join(",")}),i=await D(n,`/api/v1/skills/compare?${r.toString()}`),o=Array.isArray(i.missing)?i.missing.filter(s=>typeof s=="string"):[];return o.length>0?x({...i,status:"not_found",reasonCode:"compare_missing_skills",missing:o,nextAction:"search",nextStep:`Run \`skills-layer search ${o[0]}\` to find the correct slug, then retry compare.`},`Comparison could not find: ${o.join(", ")}.`,t.json,"compare_missing_skills"):t.json?A(i,"Comparison loaded.",!0,n):{exitCode:0,stdout:Ile(i,"Comparison loaded.",Pe(n),t.verbose),stderr:""}}async function Nie(e,t,n){let r=T(e[0],"show requires a skill slug."),i=await D(n,`/api/v1/skills/${encodeURIComponent(r)}`);return A(Gh(i),"Skill loaded.",t.json,n)}async function Fie(e,t,n){let r=T(e[0],"trust requires a skill slug."),i=JM("trust",t);if(i)return i;let o=new URLSearchParams;Ke(o,"format",t.format),Ke(o,"version",t.version),Ke(o,"versionId",t.versionId);let s=await D(n,`/api/v1/skills/${encodeURIComponent(r)}/platform-score${Qe(o)}`);return k(t.format)?.toLowerCase()==="sarif"?{exitCode:0,stdout:JSON.stringify(s,null,2),stderr:""}:!t.json&&rC(s)?{exitCode:0,stdout:H(GL(s)),stderr:""}:A(s,"Platform Score loaded.",t.json,n)}async function Bie(e,t,n){e.length===0&&n.renderMode.detail==="full"&&(e=["full"]);let r=e[0];if(t.json||n.renderMode.kind==="json-final"){if(r==="full")return A(aN(),"Help loaded.",!0,n);let a=e.length===1?Rg(r,bo):null;if(a)return A({status:"ok",kind:"goal_help",goal:a},"Help loaded.",!0,n);let l=r==="topic"?_o(e[1]):_o(r,e.slice(1));if(l)return A(l,"Help loaded.",!0,n);if(r!=="topic"&&!rre.has(r??""))return IP(e,!0)}if(!r){if(n.renderMode.kind==="json-stream"||!n.helpInteractive)return{exitCode:0,stdout:Lo(n.renderMode),stderr:""};let a;try{a=await n.promptSelect("What do you want to do?",nN(bo))}catch{a=void 0}if(!a)return{exitCode:0,stdout:Lo(n.renderMode),stderr:""};if(a==="full")return Ba(Lo(n.renderMode,!0),"full",t,n);let l=Rg(a,bo);return l?Ba(XC(l),l.id,t,n):{exitCode:0,stdout:Lo(n.renderMode),stderr:""}}if(r==="full")return Ba(Lo(n.renderMode,!0),"full",t,n);let o=e.length===1?Rg(r,bo):null;if(o)return Ba(XC(o),o.id,t,n);let s=vu(e[0],e.slice(1));if(s)return Ba(s,e.filter(Boolean).join(" "),t,n);if(r==="topic"){let a=vu(e[1]);if(a)return Ba(a,e[1]??"overview",t,n);let l=new URLSearchParams;return e[1]&&l.set("topic",e[1]),await me(`/api/v1/help${Qe(l)}`,t,n,"Help topic loaded.")}if(r==="standards")return await me("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let a=await D(n,"/api/v1/marketplace/status");return t.json?A(a,"Marketplace status loaded.",!0,n):A(Dle(a),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let a=await D(n,"/api/v1/capabilities");return A(Ole(a),"Edition capabilities loaded.",t.json,n)}if(r==="schema-plan")return R("help schema-plan is not included in the public npm CLI.",t.json);if(r==="optimize-tokens"){let a=T(t.text,"help optimize-tokens requires --text."),l=Lle(t.maxCharacters,t.json);if(fe(l))return l;let c=await D(n,"/api/v1/optimize-tokens",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({text:a,...l?{maxCharacters:l}:{}})});return A(c,"Token optimization complete.",t.json,n)}return R(`Unknown help command "${r}".`,t.json)}function Ba(e,t,n,r){return n.json?A({status:"ok",topic:t,content:e},"Help topic loaded.",!0,r):{exitCode:0,stdout:e,stderr:""}}function IP(e,t){let n=e.filter(Boolean).join(" ").trim()||"help";return x({status:"not_found",reasonCode:"help_topic_not_found",topic:n,nextAction:"help",nextStep:"Run `skills-layer --help`, `skills-layer help full`, or `skills-layer <command> --help` for a supported command."},`Help topic not found: ${n}.`,t,"help_topic_not_found")}async function Mie(e,t,n){let r=T(e[0]??t.path,"validate requires a file or directory."),i=Tt(n.cwd,r);if(!await pr(i))return IU("validate",r,t,n);let o=(await ma({cwd:n.cwd,sourcePath:r,limits:yo})).files;o=await Uie({files:o,resolvedTarget:i,flags:t,backend:n});let s=nt(o),a={files:o,sourceIntakeContext:k(t.sourceIntakeContext),publicationStatus:k(t.publicationStatus),dependencyAuditStatus:k(t.dependencyAuditStatus),category:k(t.category),discloseSource:!!t.discloseSource},l;try{l=await D(n,"/api/v1/validation/preview",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(ie(a))})}catch(d){if(d instanceof Z&&d.status===422&&d.details)l=bce(d.details);else throw d}let c=zie({...l,license:s.license,licenseIssues:s.issues.filter(d=>d.code.startsWith("license_"))},o),u=c.valid===!1||j(c,"validation")?.valid===!1;return t.json?u?x({...cz(c,n.renderMode.detail,"validate"),nextAction:"validate",nextStep:"Fix the listed issues, then run validate again."},"Validation failed.",!0,"bundle_invalid"):A(c,"Validation complete.",!0,n,"validate"):{exitCode:u?1:0,stdout:jle(c,r,n),stderr:""}}async function Uie(e){if(nt(e.files).license?.status==="verified"||e.flags.json||!e.backend.stdoutIsTty)return e.files;let n=await Mk({cwd:e.backend.cwd,files:e.files,skip:!1,interactive:!0,prompt:XM(e.backend)});if(n.selection.mode==="skip"||await e.backend.promptSelect("Apply this licence change to the local bundle?",[{value:"apply",label:"Apply the reviewed change"},{value:"cancel",label:"Cancel without changing files"}])!=="apply")return e.files;let o=(await Ja(e.resolvedTarget)).isDirectory()?e.resolvedTarget:Be(e.resolvedTarget);return await Jp({targetDir:o,files:z1(e.files,n.selection),confirmed:!0}),(await ma({cwd:e.backend.cwd,sourcePath:o})).files}function zie(e,t){return{...e,evalReadiness:Hk(t)}}function qie(e,t){let n=Vie(e);return Es({status:n?"not_run":"generated_only",skillSlug:t.skillSlug,version:t.version,artifactDigest:ct(e),...n?{evalPackDigest:n}:{},generatedAt:t.generatedAt,runnerVersion:So,counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})}function Vie(e){let t=e.find(n=>{let r=$n(n.path,e);return r.type==="evidence"&&typeof n.content=="string"&&(r.relativePath.startsWith("evals/")||r.relativePath.endsWith(".eval.json")||r.relativePath.endsWith(".eval.yaml"))});if(t?.content)try{return Rs(JSON.parse(t.content))}catch{return}}async function Gie(e,t,n){let r=T(e[0]??t.path,"preview-trigger requires a file or directory."),i=Tt(n.cwd,r);if(!await pr(i))return IU("preview-trigger",r,t,n);let o=(await ma({cwd:n.cwd,sourcePath:r,limits:yo})).files,s=await D(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({files:o,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?A(s,"Trigger preview complete.",!0,n):{exitCode:0,stdout:Nle(s,r,n),stderr:""}}async function Hie(e,t,n){let r=e[0];if(["create","sessions","resume","inspect","answer","resources","resource-decide","tool-contract","draft","validate","eval","improve","revise","materialize","finalize"].includes(r??""))return await WB(r,e.slice(1),t,n);if(r==="init")return t.quick?await WB("create",e.slice(1),{...t,mode:"quick"},n):await Wie(e.slice(1),t,n);if(r==="rules")return await me("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(r==="submissions")return await me("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(r==="status"){let i=T(e[1],"creator status requires a skill slug.");try{return await me(`/api/v1/me/submissions/${encodeURIComponent(i)}/status`,t,n,"Submission status loaded.",{authenticated:!0})}catch(o){if(o instanceof Z&&o.status===404)return roe(i,t);throw o}}if(r==="charge-status"){let i=T(e[1],"creator charge-status requires a charge id.");return await me(`/api/v1/me/private-skill-charges/${encodeURIComponent(i)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(r==="spaces")return await Yie(e.slice(1),t,n);if(r==="submit")return await AP(e.slice(1),t,n,!1);if(r==="submit-version")return await AP(e.slice(1),t,n,!0);if(r==="check-slug"){let i=T(e[1],"creator check-slug requires a slug.");return await toe(i,t,n)}if(r==="rename"){let i=T(e[1],"creator rename requires the current slug."),o=T(e[2],"creator rename requires the new slug."),s=ZM("creator.rename",o,t);return s||await Li(`/api/v1/me/submissions/${encodeURIComponent(i)}/slug`,{nextSkillSlug:o},t,n,"Skill renamed.")}if(r==="pricing")return await ooe(e,t,n);if(r==="update-listing"){let i=T(e[1],"creator update-listing requires a skill slug.");return await soe(i,t,n)}if(r==="visibility"){let i=T(e[1],"creator visibility requires a skill slug."),o=Oi("creator.visibility",t);if(o)return o;let s=k(t.visibility)??e[2],a=uc(s);if(!a||!Lu.includes(a))return x({status:"error",reasonCode:"invalid_visibility",skillSlug:i,visibility:s??null,acceptedValues:Lu,nextAction:"creator.visibility",nextStep:"Use --visibility private, public, or unlisted."},`Invalid creator visibility "${s??""}". Use one of: ${Lu.join(", ")}.`,t.json,"invalid_visibility");let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/visibility`,{method:"PATCH",headers:V(n.apiKey),body:JSON.stringify(ie({visibility:a,dryRun:t.dryRun}))});return cse(l)?x(l,use(l,i),t.json,f(l,"reasonCode")??f(l,"status")):A(l,t.dryRun?"Visibility preview loaded.":"Visibility updated.",t.json,n)}if(r==="security-report"){let i=T(e[1],"creator security-report requires a skill slug."),o=JM("creator.security-report",t);if(o)return o;let s=Oi("creator.security-report",t);if(s)return s;let a=new URLSearchParams;Ke(a,"format",t.format),Ke(a,"version",t.version),Ke(a,"versionId",t.versionId);let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security-report${Qe(a)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?A(l,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:ece(l,i,n),stderr:""}}if(r==="rescan-security"){let i=T(e[1],"creator rescan-security requires a skill slug."),o=Oi("creator.rescan-security",t);if(o)return o;let s=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security/rescan`,{method:"POST",headers:V(n.apiKey),body:JSON.stringify(ie(Ft(t,["version","versionId"])))});return t.json?A(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:tce(s,i,n),stderr:""}}if(r==="provenance"){let i=T(e[1],"creator provenance requires a skill slug.");return await me(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership`,t,n,"Provenance loaded.",{authenticated:!0})}if(r==="claim"||r==="verify"||r==="dispute")return await aoe(r,e,t,n);if(r==="issues"||r==="reviews"||r==="update-issue"||r==="moderate-review")return await foe(r,e,t,n);if(r==="analytics"){let i=T(e[1],"creator analytics requires a skill slug.");return await loe(i,t,n)}if(r==="delist"||r==="relist"){let i=T(e[1],`creator ${r} requires a skill slug.`),o=k(t.reason)??(r==="relist"?"Creator relisted skill":"");return o.trim().length<3?R("creator delist requires --reason (at least 3 characters).",t.json):await Li(`/api/v1/me/submissions/${encodeURIComponent(i)}`,{lifecycle:r==="delist"?"delisted":"active",reason:o},t,n,`${i} ${r==="delist"?"delisted":"relisted"}; existing buyers keep access.`)}if(r==="earnings")return await me("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0});if(r==="payout-profile")return k(t.country)?await eM(t,n):await coe(t,n);if(r==="payout-link")return await eM(t,n);if(r==="payouts")return await me("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0});if(r==="withdraw"){if(!k(t.amountCents))return R("creator withdraw requires --amount-cents.",t.json);let i=Ni(t.amountCents,"--amount-cents","amountCents","invalid_amount_cents",t,{minimum:1});if(i.failure)return i.failure;let o=k(t.idempotencyKey)??ele();if(t.json||!n.stdoutIsTty)return x({status:"blocked",reasonCode:"payout_human_confirmation_required",nextAction:"creator.withdraw",nextStep:"Use an interactive terminal. MCP returns a browser handoff, and automation credentials cannot withdraw."},"Creator withdrawal requires an interactive human confirmation. Use an interactive terminal; MCP returns a browser handoff and automation credentials cannot withdraw.",t.json,"payout_human_confirmation_required");let s=ie({amountCents:i.value,reason:k(t.reason)}),a={...V(n.apiKey),"idempotency-key":o},l=await D(n,"/api/v1/me/payouts",{method:"POST",headers:a,body:JSON.stringify(s)});if(l.status!=="confirmation_required"||typeof l.confirmationId!="string"||typeof l.confirmationToken!="string"||typeof l.confirmationPhrase!="string")throw new Error("The payout service did not return a valid action-bound confirmation challenge.");let c=l.impact&&typeof l.impact=="object"?l.impact:{};if(await n.promptText(`Withdrawal impact: ${String(c.amountCents??i.value)} ${String(c.currency??"usd").toUpperCase()}, remaining withdrawable balance ${String(c.withdrawableAfterCents??"unknown")} cents.
|
|
2138
2138
|
Type exactly "${l.confirmationPhrase}" to confirm: `)!==l.confirmationPhrase)return R("Withdrawal cancelled; the confirmation phrase did not match.",!1);let d=await D(n,"/api/v1/me/payouts",{method:"POST",headers:a,body:JSON.stringify({...s,confirmationId:l.confirmationId,confirmationToken:l.confirmationToken,confirmationPhrase:l.confirmationPhrase})});return A(d,"Withdrawal requested.",!1,n)}return r==="source"?await hoe(e.slice(1),t,n):R(`Unknown creator command "${r??""}".`,t.json)}var KB="\0derived";function PP(e,t){return`${e}-${Me("sha256").update(JSON.stringify(t)).digest("hex").slice(0,32)}`}async function WB(e,t,n,r){let i=k(n.idempotencyKey)??(e==="create"?`creator-${Ge(12).toString("hex")}`:KB),o=k(n.sessionId)??t[0],s=k(n.expectedRevision),a=s===void 0?void 0:Number(s);if(s!==void 0&&(!Number.isInteger(a)||Number(a)<1))return R("--expected-revision must be a positive integer.",n.json);let l=g=>{if(!o)throw new Error(`creator ${g} requires a session id.`);if(a===void 0)throw new Error(`creator ${g} requires --expected-revision.`);return{sessionId:o,expectedRevision:a,idempotencyKey:i}},c,u="POST",d;if(e==="create"){let g=k(n.skill)??t[0],y=k(n.outcome)??k(n.description),v=k(n.mode)??"guided";v==="guided"&&!n.json&&r.stdoutIsTty&&(g||(g=(await r.promptText(`Choose a unique kebab-case skill name:
|
|
2139
2139
|
> `)).trim()),y||(y=(await r.promptText(`What outcome should this skill reliably produce?
|
|
2140
2140
|
> `)).trim())),d=ie({idempotencyKey:i,mode:v,outcome:y,skillSlug:g,description:k(n.description),license:k(n.license),importedCandidateId:k(n.importedCandidateId)}),c="/api/v1/creator/sessions"}else if(e==="sessions")c="/api/v1/creator/sessions",u="GET";else if(e==="resume"){if(!o)return R("creator resume requires a skill slug or session id.",n.json);c=`/api/v1/creator/sessions/resume/${encodeURIComponent(o)}`,u="GET"}else if(e==="inspect"){if(!o)return R("creator inspect requires a session id.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(o)}`,u="GET"}else if(e==="answer"){let g=l("answer"),y=k(n.questionId);if(y){let v;if(n.answerJson!==void 0)v=ln(n.answerJson,"answer-json");else if(!n.json&&r.stdoutIsTty){let b=await D(r,`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}`,{headers:re(r.apiKey,r.authBlockedMessage)}),w=qa(b);if(!w)throw new Error("Creator response did not include the canonical interview turn");if(!w.currentQuestion||w.currentQuestion.id!==y)return R("The requested question is not the session's current canonical question.",n.json);v=zp(y,await r.promptText(`${w.currentQuestion.prompt}
|
|
@@ -2146,27 +2146,27 @@ ${JSON.stringify(i.confirmationSummary,null,2)}
|
|
|
2146
2146
|
Suggested answer: ${i.currentQuestion.suggestedAnswer}`:"",a=r?`Previous answer was not accepted: ${r}
|
|
2147
2147
|
`:"",l;try{l=await t.promptText(`${o}${a}[${i.progress.questionNumber}/${i.progress.maximumQuestions}] ${i.currentQuestion.prompt}${s}
|
|
2148
2148
|
Why: ${i.currentQuestion.whyAsked}
|
|
2149
|
-
> `)}catch(u){throw uP(u,n)}let c;try{c=zp(i.currentQuestion.id,l)}catch(u){r=ve(u);continue}try{n=await D(t,`/api/v1/creator/sessions/${encodeURIComponent(String(n.sessionId))}/turn-answers`,{method:"POST",headers:V(t.apiKey),body:JSON.stringify({expectedRevision:n.revision,idempotencyKey:PP("creator-turn",{sessionId:n.sessionId,revision:n.revision,questionId:i.currentQuestion.id,answer:c}),questionId:i.currentQuestion.id,answer:c})}),r=null}catch(u){if(u instanceof Z&&u.status===422){r=ve(u);continue}throw uP(u,n)}}}async function ZB(e,t,n){await Ve(K(t.paths.stateDir,"creator-resume.json"),{version:1,baseUrl:t.baseUrl,sessionId:String(e.sessionId),skillSlug:qa(e,!1)?.skillSlug??null,revision:e.revision,completed:n,savedAt:t.now()})}function uP(e,t){let n=qa(t,!1)?.skillSlug||String(t.sessionId),r=e instanceof Z&&e.status===409?" The server revision is authoritative; reload it before answering again.":"";return new Error(`${ve(e)}${r} Resume with skills-layer creator resume ${n}.`)}function qa(e,t=!0){let n=e.data,r=n&&typeof n=="object"&&!Array.isArray(n)?n.turn:null;if(!r||typeof r!="object"||Array.isArray(r)){if(t)throw new Error("Creator response did not include the canonical interview turn");return null}return r}async function Wie(e,t,n){let r=k(t.skill)??e[0]??"my-skill",i=ZM("creator.init",r,t);if(i)return i;let o=k(t.dir)?Tt(n.cwd,k(t.dir)):K(n.paths.stateDir,"authoring",r),s;try{s=a1(k(t.type))}catch(y){return R(ve(y),t.json)}let a=k(t.category),l=await O1(o),c=await Mk({cwd:n.cwd,files:l.files,explicitIdentifier:k(t.license),explicitLicenseFile:k(t.licenseFile),skip:!!t.skipLicense,interactive:!t.json&&n.stdoutIsTty,prompt:XM(n)}),u=l1({skillSlug:r,description:k(t.description)??`Helps with ${r.replaceAll("-"," ")}.`,skillType:s,category:a,licenseSelection:c.selection}),d=await Jp({targetDir:o,files:u,confirmed:t.confirmed});if(d.status==="confirmation_required"){let y={status:"confirmation_required",reasonCode:"scaffold_overwrite_confirmation_required",targetDir:d.plan.targetDir,changes:d.plan.changes,preservedEntryCount:d.plan.preservedEntryCount,nextAction:"creator.init",nextStep:"Review the reported create/replace diff, then rerun with --confirm only if every replacement is intended."};return x(y,QM(d.plan),t.json,"scaffold_overwrite_confirmation_required")}let p=
|
|
2150
|
-
`)}async function pr(e){try{return await FM(e),!0}catch{return!1}}function eU(e){return e.attestRights?{attestRights:!0,rightsBasis:k(e.rightsBasis)??"self_authored",distributionScope:k(e.distributionScope)??"commercial_distribution",rightsDeclarationVersion:zj}:{}}async function AP(e,t,n,r){let i=k(t.visibility);if(i){let P=uc(i);if(!P||!Lu.includes(P))return Nr(r?"creator.submit-version":"creator.submit","visibility",i,Lu,t,"invalid_visibility")}let o=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(o.failure)return o.failure;let s=k(t.spacePack),a=s===void 0?void 0:oc(s);if(a===null)return Nr(r?"creator.submit-version":"creator.submit","spacePack",s,["5","10","20","50"],t,"invalid_private_skill_space_pack","space-pack");let l=k(t.creatorSessionId);if(l){let P=r?T(k(t.skill)??e[0],"creator submit-version with --creator-session-id requires a skill slug."):null,O=r?{creatorSessionId:l,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",...t.dryRun?{dryRun:!0}:{}}:{creatorSessionId:l,...t.dryRun?{dryRun:!0}:{},...a?{privateSkillSpacePack:a}:{}},N=r?`/api/v1/me/submissions/${encodeURIComponent(P)}/versions`:"/api/v1/me/submissions",Q=await D(n,N,{method:"POST",headers:JB(n,t.dryRun?null:{path:N,creatorSessionId:l}),body:JSON.stringify(O)});return YB(Q,t,n)??A(Q,t.dryRun?"Submission preview ready.":Q.status==="submission_incomplete"?`Creator session submission is incomplete. ${f(Q,"nextStep")??"Retry this session submission to complete finalization."}`:"Finalized Creator session submitted.",t.json,n)}let c=r?T(k(t.skill)??e[0],"creator submit-version requires a skill slug."):k(t.skill),u=T(k(t.source)??(r?e[1]:e[0])??t.path,`creator ${r?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),d=await Hu(u,n.cwd);if(t.list)return await Xie(u,d,c,t,n);let p=Oi(r?"creator.submit-version":"creator.submit",t);if(p)return p;if(!d&&!zu(u)&&(vz(u)||/^(?:github|gitlab):/iu.test(u)))return Qie(u,t);let m=d?.files??(await ma({cwd:n.cwd,sourcePath:u,limits:yo})).files;if(!r&&!t.dryRun){let P=await eoe(m,t,n);if(P)return P}if(t.dryRun&&dg(m))return Zie(m,{slug:c,flags:t,backend:n});let h=dg(m)?await xC({baseUrl:n.baseUrl,apiKey:n.apiKey,fetchFn:n.fetchFn,files:m}):null,g=ie({...h?{hydrationManifestId:h.manifestId}:{files:m},version:k(t.version),dryRun:t.dryRun,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",evalSummary:qie(m,{skillSlug:c??tA(m)??"unknown",version:k(t.version)??"0.0.0",generatedAt:n.now()}),replaceUnpublished:r&&t.replaceUnpublished===!0?!0:void 0,priceCents:o.value,privateSkillSpacePack:a,...eU(t),...d?{sourceMetadata:d.sourceMetadata}:{},...Ft(t,["displayName","skillType","category","visibility","source","skill"])}),y=r&&c?`/api/v1/me/submissions/${encodeURIComponent(c)}/versions`:"/api/v1/me/submissions",v=await D(n,y,{method:"POST",headers:JB(n,t.dryRun?null:{path:y,request:g,files:m}),body:JSON.stringify(g)});if(t.json||t.noOpen||v.status!=="checkout_required"||typeof v.checkoutUrl!="string"||typeof v.chargeId!="string")return YB(v,t,n)??A(v,t.dryRun?"Submission preview ready.":r?"Version submitted.":"Submission uploaded.",t.json,n);let b=j(v,"spacePack"),w=b?oc(b.code):null;n.emitInfo(w?`No private skill space is left. Opening checkout for ${Bp(w).label} (${Bp(w).displayPrice}); other packs: --space-pack 5|10|20|50. Complete the payment in your browser, then come back here.`:"Opening payment setup for skill submission. Complete the payment in your browser, then come back here."),await n.openUrl(v.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${v.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let C=await Wae(v.chargeId,n);return fe(C)?C:C.status!=="submitted"?A({...v,chargeStatus:C.status},`Payment is still ${C.status}. You can rerun \`skills-layer creator charge-status ${v.chargeId}\` to continue tracking it.`,t.json,n):A(C,r?"Version submitted.":"Submission uploaded.",t.json,n)}function JB(e,t){let n=V(e.apiKey);if(!t)return n;let{hydrationManifestId:r,files:i,evalSummary:o,...s}=t.request??{},a=t.files?Me("sha256").update(JSON.stringify(t.files.map(c=>[c.path,c.content??null,c.contentBase64??null]))).digest("hex"):null,l=Me("sha256").update(JSON.stringify({path:t.path,creatorSessionId:t.creatorSessionId??null,request:s,bundleDigest:a})).digest("hex");return{...n,"idempotency-key":`cli-submit-${l.slice(0,48)}`}}function YB(e,t,n){if(e.status!=="checkout_required"||typeof e.checkoutUrl!="string"||typeof e.chargeId!="string")return null;let r=`Open ${e.checkoutUrl} to complete payment, then run \`skills-layer creator charge-status ${e.chargeId}\` to confirm the submission.`;return A({...e,paymentRequired:!0,checkoutUrl:e.checkoutUrl,chargeId:e.chargeId,nextAction:"creator.charge-status",nextStep:r},`Payment required to finish: ${r}`,t.json,n)}function Zie(e,t){let n="creator.submit",r=tt(e),i=e.reduce((l,c)=>l+cs(c),0),o=t.slug??tA(e),s=["skill_name_availability","security_review","moderation","pricing_and_checkout","eval_evidence"],a=ie({status:r.valid?"ready":"blocked",reasonCode:r.valid?"local_preview_only":"invalid_bundle",dryRun:!0,previewMode:"local",operation:n,uploaded:!1,skillSlug:o,version:k(t.flags.version),bundle:{fileCount:e.length,totalBytes:i,transport:"source_hydration",artifactDigest:ct(e)},localChecks:[{check:"bundle_size",status:"passed"},{check:"paths",status:"passed"},{check:"secrets",status:"passed"},{check:"manifest",status:r.valid?"passed":"failed"}],serverChecks:{status:"not_run",checks:s},why:"The bundle exceeds the 2 MiB inline request limit, so the dry run previewed it locally and uploaded nothing.",validation:r,nextAction:r.valid?n:"validate",nextStep:r.valid?`Re-run without --dry-run to upload and submit. Server-only checks (${s.join(", ")}) run during the real submit.`:"Fix the bundle issues before submitting again."});return A(a,r.valid?`Local submission preview ready (${e.length} files, ${i} bytes; nothing uploaded). Server-only checks run on the real submit: ${s.join(", ")}.`:"Local submission preview blocked: the bundle does not satisfy the creator validation rules. Nothing was uploaded.",t.flags.json,t.backend)}var Jie="Use `skills-layer creator spaces` or `skills-layer creator spaces buy --pack 5|10|20|50`.";function XB(e){if(e.status==="community_unlimited")return"Community edition supports unlimited private skills.";let t=n=>typeof e[n]=="number"?e[n]:0;return`Private skill spaces: ${t("availablePrivateSkillSpaces")} available of ${t("totalPrivateSkillSpaces")} (${t("activePrivateSkills")} active private skills; free ${t("freePrivateSkillSpacesUsed")} used, ${t("freePrivateSkillSpacesRemaining")} left; purchased ${t("purchasedPrivateSkillSpaces")}, ${t("purchasedPrivateSkillSpacesUsed")} used). Buy more with \`skills-layer creator spaces buy --pack 5|10|20|50\`: ${sc}.`}async function Yie(e,t,n){let r=e[0];if(r===void 0||r==="status"){let u=await D(n,"/api/v1/me/private-skill-spaces",{headers:re(n.apiKey,n.authBlockedMessage)});return A(u,XB(u),t.json,n)}if(r!=="buy")return R(`Unknown creator spaces action "${r}". ${Jie}`,t.json);let i=k(t.pack)??e[1],o=i===void 0?void 0:oc(i);if(o===null)return Nr("creator.spaces.buy","pack",i,["5","10","20","50"],t,"invalid_private_skill_space_pack","pack");let s=await D(n,"/api/v1/me/private-skill-spaces/checkout",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(o?{privateSkillSpacePack:o}:{})});if(s.status!=="checkout_required"||typeof s.checkoutUrl!="string")return A(s,XB(s),t.json,n);let a=Bp(oc(j(s,"spacePack")?.code)??"spaces_5"),l=`Checkout for ${a.label} (${a.displayPrice}) is ready. Complete the payment in your browser, then run \`skills-layer creator spaces\` to see the credited spaces.`;return t.json||t.noOpen?A(s,`${l} Checkout URL: ${s.checkoutUrl}`,t.json,n):(await n.openUrl(s.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${s.checkoutUrl}`),A(s,l,t.json,n))}async function Xie(e,t,n,r,i){if(t)return A(QB(aA(e,t,n)),"Source skills loaded.",r.json,i);let o=await kU(i,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},r);return o.kind==="failure"?o.result:A(QB(o.inspection),"Source skills loaded.",r.json,i)}function QB(e){return{...e,sourceSubmissionSupported:!0}}function Qie(e,t){let r=`skills-layer source connection start --provider ${_U(e)} --source ${e} --visibility private --provenance-intent private_source_import`;return x({status:"source_connection_required",reasonCode:"source_connection_required",source:e,nextAction:"source.connection.start",nextStep:r},`Creator submit can list ${e} safely, but publishing from a remote source requires a source connection. Run \`${r}\`.`,t.json,"source_connection_required")}async function eoe(e,t,n){let r=k(t.skill)??tA(e);if(!r)return null;let i;try{i=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(r)}`,{headers:re(n.apiKey,n.authBlockedMessage)})}catch(o){if(o instanceof Z&&o.status===404)return tU(r,t);throw o}if(i.available===!1||f(i,"reasonCode")==="unavailable"||f(i,"reasonCode")==="reserved"){let o=f(i,"assignedSlug"),s=ie({status:"duplicate_candidate",reasonCode:f(i,"reasonCode")??"slug_unavailable",requestedSlug:r,assignedSlug:o,nextAction:"creator.status",nextStep:`Run \`skills-layer creator status ${r}\`, \`skills-layer creator submissions\`, or submit a new version of the existing skill instead of creating a duplicate listing.`});return x(s,`A public skill slug "${r}" already exists or is not available. Run \`skills-layer creator status ${r}\`, check your creator submissions, or submit a new version instead of creating a duplicate listing.`,t.json,f(s,"reasonCode"))}return null}async function toe(e,t,n){try{let r=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return A(noe(r),"Slug status loaded.",t.json,n)}catch(r){if(r instanceof Z&&r.status===404)return tU(e,t);throw r}}function tU(e,t){let n={status:"slug_check_unavailable",reasonCode:"slug_check_route_unavailable",requestedSlug:e,nextAction:"creator.status",nextStep:`Slug availability could not be checked on the selected backend. Run \`skills-layer creator submissions\`, \`skills-layer creator status ${e}\`, or retry after selecting a compatible Skills Layer backend.`};return x(n,`Slug availability could not be checked for ${e} on the selected backend. Run \`skills-layer creator submissions\` or retry after selecting a compatible Skills Layer backend.`,t.json,"slug_check_route_unavailable")}function noe(e){let t=e.available===!0,n=f(e,"assignedSlug");if(t)return ie({requestedSlug:f(e,"requestedSlug"),available:!0,reasonCode:f(e,"reasonCode")??"available",assignedSlug:n});let r=j(e,"slugAssignment"),i=Array.isArray(r?.candidateSlugs)?r.candidateSlugs.filter(o=>typeof o=="string").slice(0,3):void 0;return ie({...e,...r?{slugAssignment:{...r,...i?{candidateSlugs:i}:{}}}:{},...i?{candidateSlugs:i}:{}})}function roe(e,t){return x({status:"not_submitted",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submit",nextStep:"Run `skills-layer creator submit <path> --dry-run` to validate a local skill before submitting it, or run `skills-layer creator submissions` to see your existing submissions."},`No creator submission was found for ${e}. Run \`skills-layer creator submit <path> --dry-run\` before checking status.`,t.json,"creator_submission_not_found")}function tA(e){let t=e.find(r=>r.path.split("/").pop()?.toLowerCase()==="skill.md");if(!t)return;let n=/^---\s*\n(?<body>[\s\S]*?)\n---/u.exec(t.content??"")?.groups?.body?.split(/\r?\n/u).map(r=>r.match(/^name\s*:\s*(?<name>.+?)\s*$/u)?.groups?.name?.trim().replace(/^["']|["']$/gu,"")).find(r=>!!r);return ioe(n??it(Be(t.path)))}function ioe(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function ooe(e,t,n){let r=T(e[1],"creator pricing requires a skill slug."),i=Oi("creator.pricing",t);if(i)return i;let o=new URLSearchParams;if(Ke(o,"version",t.version),!t.priceCents)return await me(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${at(o)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(s.failure)return s.failure;let a=s.value??0,l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${at(o)}`,{headers:re(n.apiKey,n.authBlockedMessage)}),c=J(l,"priceCents")??0,u=J(l,"revision");if(!u||!Number.isSafeInteger(u)||u<1)return R("Pricing authority did not return a valid revision.",t.json);if(a>c&&!t.confirmed){let d=ie({status:"pending_approval",reasonCode:"price_increase_confirmation_required",skillSlug:r,version:f(l,"version"),currentPriceCents:c,requestedPriceCents:a,currency:f(l,"currency")??"usd",nextStep:"Review the old and new USD prices, then rerun with --yes."});return A(d,"Pricing change requires explicit confirmation.",t.json,n)}return await Li(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing`,{priceCents:a,confirmPriceIncrease:t.yes,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),expectedRevision:u,idempotencyKey:k(t.idempotencyKey)?.trim()||`pricing-${Ge(12).toString("hex")}`,reason:"Creator changed the version list price through CLI.",...eU(t)},t,n,"Pricing updated.")}async function soe(e,t,n){let r=Mn("creator.update-listing","listingStatus",t.listingStatus,fie,t,"invalid_listing_status","listing-status");if(r)return r;try{return await Li(`/api/v1/me/submissions/${encodeURIComponent(e)}`,Ft(t,["displayName","summary","description","category","skillType","license","listingStatus"]),t,n,"Listing updated.")}catch(i){if(i instanceof Z&&i.status===404){let o={status:"listing_not_found_or_not_editable",reasonCode:"creator_listing_not_found_or_not_owned",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see editable listings, or \`skills-layer show ${e}\` to inspect the public catalog entry.`};return x(o,`No editable creator listing was found for ${e}. Run \`skills-layer creator submissions\` to see listings you can update.`,t.json,"creator_listing_not_found_or_not_owned")}throw i}}async function aoe(e,t,n,r){let i=T(t[1],`creator ${e} requires a skill slug.`);if(e==="claim"){let o=Mn("creator.claim","requestedRole",n.requestedRole,pie,n,"invalid_requested_role","requested-role");if(o)return o}try{if(e==="claim")return await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/claim`,Ft(n,["requestedRole","message"]),n,r,"Ownership claim submitted.");if(e==="verify"){let o=T(n.claimId,"creator verify requires --claim-id.");return await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/verify`,{claimId:o},n,r,"Ownership claim verified.")}return T(n.message,"creator dispute requires --message."),await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/dispute`,Ft(n,["message"]),n,r,"Ownership dispute submitted.")}catch(o){if(o instanceof Z&&o.status===404){let s={status:"ownership_action_unavailable",reasonCode:e==="claim"?"skill_not_found_or_not_claimable":"ownership_claim_not_found",skillSlug:i,requestedRole:k(n.requestedRole),nextAction:e==="claim"?"search":"creator.claim",nextStep:e==="claim"?`Run \`skills-layer search ${i}\`, \`skills-layer show ${i}\`, or submit/source-install the skill before claiming it.`:`Run \`skills-layer creator claim ${i}\` to start a new claim if the skill is claimable.`};return x(s,e==="claim"?`No claimable skill was found for ${i}. Search or show the skill first, then claim it only when it exists and is claimable.`:`No matching ownership claim was found for ${i}. Start a new claim if the skill is claimable.`,n.json,f(s,"reasonCode")??"ownership_action_unavailable")}throw o}}async function loe(e,t,n){try{return await me(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(r){if(r instanceof Z&&r.status===404){let i={status:"no_creator_submission",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see skills you own, \`skills-layer show ${e}\` to inspect the catalog listing, or \`skills-layer creator claim ${e}\` if it is a claimable public-source skill.`};return x(i,`No creator-owned analytics submission was found for ${e}. Run \`skills-layer creator submissions\`, \`skills-layer show ${e}\`, or \`skills-layer creator claim ${e}\` if you should manage it.`,t.json,"creator_submission_not_found")}throw r}}async function coe(e,t){let n=await D(t,"/api/v1/me/payout-profile",{headers:re(t.apiKey,t.authBlockedMessage)});return A(n,"Creator payout profile loaded.",e.json,t)}async function eM(e,t){let n=uoe(k(e.mode));if(e.mode&&n===null)return R("creator payout-link --mode must be account_onboarding|account_update|onboarding|update.",e.json);let r;try{r=await D(t,"/api/v1/me/payout-profile/link",{method:"POST",headers:V(t.apiKey),body:JSON.stringify(ie({...n?{mode:n}:{},country:k(e.country)}))})}catch(o){if(o instanceof Z&&poe(o))return x({status:"payout_setup_already_submitted",reasonCode:"payout_update_link_unavailable",nextAction:"creator.payout-profile",nextStep:"Run `skills-layer creator payout-profile` to confirm readiness, then use `skills-layer creator earnings` or `skills-layer creator withdraw --amount-cents <amount>`."},"Payout setup is already submitted for this account. Run `skills-layer creator payout-profile` to confirm readiness before requesting a withdrawal.",e.json,"payout_update_link_unavailable");throw o}let i=Zae(r);return i&&doe(e)&&e.showUrl!==!0&&(t.emitInfo("Opening payout setup in your browser. Finish the flow there, then come back here."),await t.openUrl(i)||t.emitInfo(`Open this payout setup URL manually to continue: ${i}`)),A(r,"Payout setup link created.",e.json,t)}function uoe(e){if(!e)return null;let t=e.trim().toLowerCase();return t==="account_onboarding"||t==="onboarding"?"account_onboarding":t==="account_update"||t==="update"?"account_update":null}function doe(e){return!e.json&&!e.noOpen}function poe(e){let t=`${e.message} ${f(e.details??{},"error")??""}`.toLowerCase();return t.includes("account_update")&&t.includes("account_onboarding")&&t.includes("account link")}async function foe(e,t,n,r){let i=T(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await me(`/api/v1/me/skills/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await me(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews`,n,r,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let l=T(n.issueId,"creator update-issue requires --issue-id."),c=T(n.status,"creator update-issue requires --status."),u=Mn("creator.update-issue","status",c,mie,n,"invalid_issue_status");if(u)return u;let d=Oi("creator.update-issue",{...n,version:n.fixedVersion});if(d)return d;try{return await Li(`/api/v1/me/skills/${encodeURIComponent(i)}/issues/${encodeURIComponent(l)}`,Ft(n,["status","fixedVersion","note"]),n,r,"Issue updated.")}catch(p){if(p instanceof Z&&p.status===404)return moe(i,l,n);throw p}}let o=T(n.reviewId,"creator moderate-review requires --review-id."),s=T(n.status,"creator moderate-review requires --status."),a=Mn("creator.moderate-review","status",s,gie,n,"invalid_review_status");if(a)return a;try{return await Oe(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews/${encodeURIComponent(o)}/moderate`,Ft(n,["status","reason"]),n,r,"Review updated.")}catch(l){if(l instanceof Z&&l.status===404)return goe(i,o,n);throw l}}function moe(e,t,n){return x({status:"not_found",reasonCode:"issue_not_found",skillSlug:e,issueId:t,nextAction:"creator.issues",nextStep:`Run \`skills-layer creator issues ${e}\` to inspect open issues before updating one.`},`Issue ${t} was not found for ${e}. Run \`skills-layer creator issues ${e}\` first.`,n.json,"issue_not_found")}function goe(e,t,n){return x({status:"not_found",reasonCode:"review_not_found",skillSlug:e,reviewId:t,nextAction:"creator.reviews",nextStep:`Run \`skills-layer creator reviews ${e}\` to inspect review ids before moderating one.`},`Review ${t} was not found for ${e}. Run \`skills-layer creator reviews ${e}\` first.`,n.json,"review_not_found")}async function hoe(e,t,n){let r=e[0],i=T(e[1],`creator source ${r??""} requires a source connection id.`),o=k(t.skill)??e[2];if(r==="prepare"){let s=Oi("creator.source.prepare",t);if(s)return s;let a=Mn("creator.source.prepare","visibility",t.visibility,za,t,"invalid_visibility");if(a)return a;let l=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=k(t.source)??e[2],u=c?await Hu(c,n.cwd):void 0;return await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/prepare`,ie({...Ft(t,["skill","source","version","displayName","skillType","category","visibility"]),...l.value!==void 0?{priceCents:l.value}:{},source:c,...u?{files:u.files}:{}}),t,n,"Source release prepared.")}if(r==="publish-request"){let s=Oi("creator.source.publish-request",t);if(s)return s;let a=Mn("creator.source.publish-request","visibility",t.visibility,za,t,"invalid_visibility");if(a)return a;let l=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=t.approvalRequestId.length>0?t.approvalRequestId:k(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/publish-request`,ie({skillSlug:o,approvalRequestIds:c,confirmPriceIncrease:t.yes,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),...Ft(t,["visibility","license","discloseSource"]),...l.value!==void 0?{priceCents:l.value}:{}}),t,n,"Source publish requested.")}if(r==="release-status"){let s=new URLSearchParams;return o&&s.set("skill",o),await me(`/api/v1/me/source-connections/${encodeURIComponent(i)}/release-status${at(s)}`,t,n,"Source release status loaded.",{authenticated:!0})}return R(`Unknown creator source command "${r??""}".`,t.json)}function RP(e){return!e.list&&!e.dryRun}async function tM(e){if(!RP(e.flags)||k(e.flags.visibility)==="private"||k(e.flags.scope)==="workspace")return null;if(e.flags.all&&Array.isArray(e.inspection.catalogueDecisions)){let p=[];for(let m of ur(e.inspection)){let h=await Wa([],{...e.flags,all:!1,json:!0,source:f(e.inspection,"catalogueSourceInput")??e.source,skill:m.value},e.backend);if(h.exitCode!==0){let g=JSON.parse(h.stderr||h.stdout);return x({status:"source_install_batch_partial",reasonCode:g.reasonCode??"source_install_child_failed",failedSkill:m.value,results:p,failure:g.data},"Source installation stopped; earlier results are retained.",e.flags.json,g.reasonCode??"source_install_child_failed")}p.push(JSON.parse(h.stdout).data)}return A({status:"source_install_batch",results:p},"Source installation results loaded.",e.flags.json,e.backend)}let t=j(e.inspection,"catalogueMatch");if(!t&&e.selectedSkillSlug&&typeof e.inspection.catalogueSourceInput=="string"){let p=await jP(e.backend,e.source,{source:e.inspection.catalogueSourceInput,skillSlug:e.selectedSkillSlug,preferCatalogue:!0,listOnly:!0},e.flags);if(p.kind==="failure")return p.result;t=j(p.inspection,"catalogueMatch"),t&&(e.inspection=p.inspection)}if(!t)return null;let n=rr(e.source),r=f(t,"skillSlug"),i=f(t,"version"),o=f(t,"generationId"),s=n.kind==="github"?n.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,l=(Array.isArray(e.inspection.results)?e.inspection.results:[]).find(p=>L(p)&&p.skillSlug===e.selectedSkillSlug),c=L(l)?f(l,"relativeSkillRoot"):void 0,u=c&&s&&c!=="."?s==="."||c===s||c.startsWith(`${s}/`)?c:`${s}/${c}`:void 0,d=typeof t.sourceRoot=="string"&&(t.sourceRoot==="."||!t.sourceRoot.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)));return n.kind!=="github"||t.schemaVersion!=="skills-layer.source-catalogue-match.v1"||typeof t.repository!="string"||t.repository.toLowerCase()!==`${n.owner}/${n.repo}`.toLowerCase()||!d||t.sourceRoot!==s&&t.sourceRoot!==u||typeof t.commitSha!="string"||!/^[a-f0-9]{40}$/u.test(t.commitSha)||/^[a-f0-9]{40}$/iu.test(n.ref)&&n.ref.toLowerCase()!==t.commitSha||!r||!/^[a-z0-9][a-z0-9-]{0,255}$/u.test(r)||!i||!o||e.selectedSkillSlug&&e.selectedSkillSlug!==t.requestedSkillSlug?x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e.source,nextStep:"Retry after the exact source-to-catalogue identity is refreshed. No raw-source fallback was activated."},"The catalogue match did not identify this exact GitHub skill and revision.",e.flags.json,"source_catalogue_identity_invalid"):Wa([r],{...e.flags,source:void 0,skill:void 0,version:i},e.backend,{...nU,expectedSourceGeneration:{generationId:o,version:i}})}var nU={origin:"direct",fallbackPolicy:"eligible_public"};function yoe(e){return{origin:"update_existing",fallbackPolicy:f(e??{},"acquisitionMode")==="authenticated_account"?"account_required":"eligible_public"}}async function Wa(e,t,n,r=nU){if(e[0]==="status"&&e[1])return me(`/api/v1/install-receipts/${encodeURIComponent(e[1])}`,t,n,"Install progress loaded.",{authenticated:!!n.apiKey});let i=YM("install",t);if(i)return i;if(t.localOnly&&(t.visibility!==void 0||k(t.scope)==="workspace"||n.config?.workingModeType==="enterprise_workspace"))return x({status:"local_only_intent_conflict",reasonCode:"local_only_intent_conflict"},"Local-only installation requires a personal local target and cannot request platform visibility or workspace authority.",t.json,"local_only_intent_conflict");let o=k(t.source);if(o){let h=k(t.skill),g=sM(o,h,t);if(g)return g;let y=await Hu(o,n.cwd);if(y)return await rM(o,y,h,t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let v=aM(o,t);if(v)return v;let b=t.list||t.dryRun||!h&&!t.all,w=await jP(n,o,{source:o,skillSlug:h,listOnly:b,...t.all?{all:!0}:{},preferCatalogue:RP(t),visibility:k(t.visibility)},t);if(w.kind==="failure")return w.result;let _=w.inspection;if(t.list)return A(_,"Source skills loaded.",t.json,n);let C=Ih(o,_,t);if(C)return C;let P=await ju({source:o,inspection:_,requestedSkillSlug:h,mode:"install",flags:t,backend:n});if(P.kind==="failure")return P.result;if(t.dryRun)return A(LP(o,_,P.skillSlug,t),"Source install preview ready.",t.json,n);let O=t.all?ur(_).map(X=>X.value):[P.skillSlug??ur(_)[0]?.value??it(o)],N=await tM({inspection:_,source:o,selectedSkillSlug:P.skillSlug,flags:t,backend:n});if(N)return N;let Q=await NB(n,O,t);if(Q)return Q;let G=f(_,"catalogueSourceInput")??o,ee=await iM({backend:n,flags:t,source:G,skillSlug:P.skillSlug,defaultAcceptUnverifiedSource:Ti(o,t,n,w.sourceAccess)==="public"});if(fe(ee))return ee;let te;try{te=await cM({source:G,skillSlug:P.skillSlug,flags:t,backend:n,sourceAccess:w.sourceAccess})}catch(X){if(ee)return await pM({backend:n,flags:t,source:G,sourceAccess:w.sourceAccess,skillSlug:P.skillSlug??O[0],unverifiedMaterialization:ee,error:X});if(X instanceof Z)return dM(o,X,t);throw X}return await Uu({backend:n,result:te,fallbackSlug:P.skillSlug??f(te,"skillSlug")??o,source:G,sourceAccess:w.sourceAccess,flags:t,requestedVisibility:Ti(o,t,n,w.sourceAccess),...ee?{unverifiedMaterialization:ee}:{}})}let s=T(e[0]??t.install,"install requires a skill slug or --source.");if(vz(s)){let h=sM(s,k(t.skill),t);if(h)return h;let g=await Hu(s,n.cwd);if(g)return await rM(s,g,k(t.skill),t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let y=aM(s,t);if(y)return y;let v=k(t.skill),b,w="unknown",_=async X=>{if(b)return null;let Ce=await jP(n,s,{source:s,skillSlug:v,listOnly:X,...t.all?{all:!0}:{},preferCatalogue:RP(t),visibility:k(t.visibility)},t);return Ce.kind==="failure"?Ce.result:(b=Ce.inspection,w=Ce.sourceAccess,null)};if(t.list){let X=await _(!0);return X||A(b,"Source skills loaded.",t.json,n)}if(!v&&!t.all){let X=await _(!0);if(X)return X;let Ce=b,pn=Ih(s,Ce,t);if(pn)return pn;let Qa=await ju({source:s,inspection:Ce,requestedSkillSlug:v,mode:"install",flags:t,backend:n});if(Qa.kind==="failure")return Qa.result;v=Qa.skillSlug}if(t.dryRun){let X=await _(!0);if(X)return X;let Ce=b,pn=await ju({source:s,inspection:Ce,requestedSkillSlug:v,mode:"install",flags:t,backend:n});return pn.kind==="failure"?pn.result:(v=pn.skillSlug,A(LP(s,Ce,v,t),"Source install preview ready.",t.json,n))}let C=await _(!1);if(C)return C;let P=b,O=t.all?ur(P).map(X=>X.value):[v??ur(P)[0]?.value??it(s)],N=await tM({inspection:P,source:s,selectedSkillSlug:v,flags:t,backend:n});if(N)return N;let Q=await NB(n,O,t);if(Q)return Q;let G=f(P,"catalogueSourceInput")??s,ee=await iM({backend:n,flags:t,source:G,skillSlug:v,defaultAcceptUnverifiedSource:Ti(s,t,n,w)==="public"});if(fe(ee))return ee;let te;try{te=await cM({source:G,skillSlug:v,flags:t,backend:n,sourceAccess:w})}catch(X){if(ee)return await pM({backend:n,flags:t,source:G,sourceAccess:w,skillSlug:v??O[0],unverifiedMaterialization:ee,error:X});if(X instanceof Z)return dM(s,X,t);throw X}return await Uu({backend:n,result:te,fallbackSlug:v??f(te,"skillSlug")??it(s),source:G,sourceAccess:w,flags:t,requestedVisibility:Ti(s,t,n,w),...ee?{unverifiedMaterialization:ee}:{}})}if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");if(k(t.scope)==="workspace"){let h=T(t.workspace,"workspace installs require --workspace <workspace-id>."),g=await rU(n,`/api/v1/workspaces/${encodeURIComponent(h)}/skills/${encodeURIComponent(s)}/approve`,{dryRun:t.dryRun},t);return fe(g)?g:t.dryRun?await Woe(g,"Workspace approval preview ready.",t,n):A(g,"Workspace approval requested.",t.json,n)}if(!n.apiKey&&r.fallbackPolicy==="eligible_public")return await dP({target:s,flags:t,backend:n,catalogContext:r});if(!t.dryRun){let h;try{h=await QP(n,s,t)}catch(g){if(EP(r,g))return await dP({target:s,flags:t,backend:n,catalogContext:r});throw g}if(h)return h}let a=await oU(s,t,n);if("result"in a)return a.result;let l=a.flags,c=ie({skillSlug:s,version:k(l.version),scope:k(l.scope),agent:k(l.agent),dryRun:t.dryRun}),u;try{u=await nA(n,c,t)}catch(h){if(EP(r,h))return await dP({target:s,flags:t,backend:n,catalogContext:r,effectiveFlags:l});throw h}if(fe(u))return u;let d=u;if(d.status==="purchase_required")return PU(d,s,t,n);if(await ji(n,d),t.dryRun)return await SU(d,l,n);let p=await rA(n,d,s,l,{expectedSourceGeneration:r.expectedSourceGeneration});if(fe(p))return p;let m=await sA(n,{...p,acquisitionMode:"authenticated_account",acquisitionOrigin:r.origin},s,l);return await Ha(n,m,s),Va(m,l.agent?"Skill installed.":"Recorded; no agent selected \u2014 rerun with --agent <id> to write the skill files.",t.json,n)}async function dP(e){let t=e.backend.apiKey?{...e.backend,apiKey:void 0,authBlockedMessage:void 0}:e.backend,n=e.effectiveFlags;if(!n){let o=await oU(e.target,e.flags,e.backend);if("result"in o)return o.result;n=o.flags}let r=k(n.version),i={status:"anonymous_public",skillSlug:e.target,...r?{version:r}:{},scope:k(n.scope),agent:k(n.agent),acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin};if(e.flags.dryRun)try{let o=await bh(t,i,e.target,r,{exportMode:"public"});return await SU({...i,...Sh(o)},e.flags,t)}catch(o){if(o instanceof Z)return Go(o,e.flags.json);throw o}try{let o=await rA(t,i,e.target,n,{exportMode:"public",expectedSourceGeneration:e.catalogContext.expectedSourceGeneration});if(fe(o))return o;let s=await sA(t,{...o,acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin},e.target,n);return await Ha(t,s,e.target),Va(s,"Public skill installed locally without an account.",e.flags.json,t)}catch(o){if(o instanceof Z)return Go(o,e.flags.json);throw o}}function EP(e,t){return e.fallbackPolicy==="eligible_public"&&t instanceof Z&&t.status===401&&f(t.details??{},"reasonCode")==="api_key_invalid_or_expired"}async function rU(e,t,n,r){let i=o=>D(e,t,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(n)}catch(o){let s=iU(o);if(!s)throw o;return r.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before workspace approval. Interactive acknowledgement is unavailable in this mode.",r.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}).`),await e.promptSelect("Approve this exact warned generation for the workspace?",[{value:"cancel",label:"Cancel approval",description:"Do not approve or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind approval to this warning revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Workspace approval cancelled without granting value.",r.json,"distribution_warning_declined"):i({...n,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}async function nA(e,t,n,r="/api/v1/install"){let i=o=>D(e,r,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(t)}catch(o){let s=iU(o);if(!s)throw o;return n.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before install. Interactive acknowledgement is unavailable in this mode.",n.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}). Next action: ${s.posture.nextAction}.`),await e.promptSelect("Continue with this exact warned skill generation?",[{value:"cancel",label:"Cancel install",description:"Do not grant or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind consent to this warning and authority revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Install cancelled without granting value.",n.json,"distribution_warning_declined"):await i({...t,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}function iU(e){if(!(e instanceof Z)||e.status!==409||!e.details)return null;let t=L(e.details.data)?e.details.data:e.details,n=L(t.distributionPosture)?t.distributionPosture:null,r=n?.contractVersion,i=n?.warningDigest,o=n?.authorityRevision;return!n||r!=="skills-layer.distribution.v1"||typeof i!="string"||!/^sha256:[a-f0-9]{64}$/u.test(i)||typeof o!="number"||!Number.isSafeInteger(o)||o<1?null:{reasonCode:typeof t.reasonCode=="string"?t.reasonCode:"warning_acknowledgement_required",posture:{contractVersion:r,warningDigest:i,authorityRevision:o,effectiveDistributionStatus:typeof n.effectiveDistributionStatus=="string"?n.effectiveDistributionStatus:"published_with_warning",reasonCode:typeof n.reasonCode=="string"?n.reasonCode:"guardian_incident_warning",nextAction:typeof n.nextAction=="string"?n.nextAction:"review_warning_before_install"}}}async function oU(e,t,n){let r=k(t.scope),i=k(t.agent);if(t.json||t.dryRun||!n.stdoutIsTty||r==="workspace"||r==="local"||r!==void 0&&i!==void 0)return{flags:t};let o=Qe(n.env,n.platform,n.cwd),s=voe(n),a=await koe(n.paths.installTargetPreferencePath),l=a?.workingModeId===s,c=l&&a?.agent?o.find(w=>w.id===a.agent):void 0,u=c&&a?.scope?a.scope==="global"?c.targets.globalSkillsPath:c.targets.projectSkillsPath:void 0;if(i===void 0&&r===void 0&&a?.policy==="recheck_every_5"&&l&&c!==void 0&&(a.scope==="project"||a.scope==="global")&&u!==void 0&&a.usesSinceConfirmation>0&&a.usesSinceConfirmation<4)return await Ve(n.paths.installTargetPreferencePath,{...a,usesSinceConfirmation:a.usesSinceConfirmation+1,savedAt:n.now()}),{flags:{...t,agent:c.id,scope:a.scope}};let p=await VA({env:n.env,platform:n.platform,cwd:n.cwd,pathExists:pr}),m=p.filter(w=>w.detectionSources.includes("project")),h=i??Re(n.env.SKILLS_LAYER_AGENT),g=h?o.find(w=>w.id===h):void 0;if(h&&!g)return{result:R(`Unsupported agent "${h}". Run \`skills-layer agents list\` to choose a supported install target.`,t.json)};if(!g&&m.length===1&&(g=m[0]),!g){let w=Re(n.config?.lastSelectedAgent);g=w?p.find(_=>_.id===w)??o.find(_=>_.id===w):void 0}if(!g&&p.length===1&&(g=p[0]),!g&&p.length>1){let w=await n.promptSelect("Multiple supported agents were detected. Select one to install for:",p.map(_=>({value:_.id,label:`${_.displayName} (${_.detectionSources.join(", ")})`})));g=p.find(_=>_.id===w)}if(!g)return{result:R("No supported local agent was detected. Run `skills-layer agents list`, then retry with --agent <agent> and --scope <project|global>.",t.json)};let y=r;if(!y){let w=[{value:"project",label:"Project (this folder)"}];g.targets.globalSkillsPath&&w.push({value:"global",label:"Global (all projects)"}),y=w.length===1?w[0].value:await n.promptSelect(`Install ${e} for ${g.displayName} where?`,w)}let v=i!==void 0||r!==void 0,b=a?.policy==="ask_every_time"&&l;if(!v&&!b&&(y==="project"||y==="global")){let w=y==="project"?"Project":"Global",C=await n.promptSelect(`Remember ${g.displayName} / ${w} for future installs?`,[{value:"recheck_every_5",label:"Yes - recheck on every 5th install"},{value:"ask_every_time",label:"No - ask every time"}])==="recheck_every_5"?{version:1,policy:"recheck_every_5",agent:g.id,scope:y,usesSinceConfirmation:1,workingModeId:s,savedAt:n.now()}:{version:1,policy:"ask_every_time",usesSinceConfirmation:0,workingModeId:s,savedAt:n.now()};await Ve(n.paths.installTargetPreferencePath,C)}return{flags:{...t,agent:g.id,scope:y}}}function voe(e){return e.apiKey?Re(e.config?.workingModeId)??"personal":"anonymous"}async function koe(e){let t=await ke(e);return!L(t)||t.version!==1||t.policy!=="recheck_every_5"&&t.policy!=="ask_every_time"||typeof t.workingModeId!="string"||typeof t.savedAt!="string"||typeof t.usesSinceConfirmation!="number"||!Number.isInteger(t.usesSinceConfirmation)||t.usesSinceConfirmation<0||t.agent!==void 0&&typeof t.agent!="string"||t.scope!==void 0&&t.scope!=="project"&&t.scope!=="global"?null:t}async function rA(e,t,n,r,i={}){if(k(r.agent)==="all")return await woe(e,t,n,r,i);let o=iA(e,t,n,r);if(o.status==="skip")return t;if(o.status==="cache_only"){let h=await bh(e,t,o.skillSlug,o.version,i),g=await xh({backend:e,exportResult:h,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(g))return g;let v=(e.platform==="win32"?ot:Lt).join(e.paths.bundlesDir,o.skillSlug,g.envelope.generation.semanticVersion,encodeURIComponent(g.envelope.generation.generationId),"bundle.zip");return await IA(v,g.bytes),{...t,...Sh(h),version:g.envelope.generation.semanticVersion,scope:"local",archiveSha256:g.archiveSha256,archiveHashFormat:g.archiveHashFormat,manifestSha256:g.envelope.manifest.sha256,generationId:g.envelope.generation.generationId,sourceContentDigest:ct(g.files),verificationStatus:"verified",cachedArtifact:{state:"verified",bundlePath:v,generation:g.envelope.generation,archiveSha256:g.archiveSha256,manifestSha256:g.envelope.manifest.sha256,savedAt:e.now()}}}if(o.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:o.skillSlug,nextStep:o.nextStep},o.message,r.json,"materialization_target_invalid");let s=await Ya({backend:e,skillSlug:o.skillSlug,agentId:o.agent.id,scope:o.scope,flags:r});if(s)return s;let a=await bh(e,t,o.skillSlug,o.version,i),l=await xh({backend:e,exportResult:a,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(l))return l;let c=(await lt(e)).installs[o.skillSlug],u=qn(c,{scope:o.scope,installedPath:(e.platform==="win32"?ot:Lt).join(o.skillsPath,Mr(o.skillSlug)),platform:e.platform})[0]?.record,d=u?f(u,"sourceContentDigest"):void 0,p=ct(l.files);if(u?.verificationStatus==="unverified"&&!r.replaceUnverifiedSource&&(await Dr({targetDir:(e.platform==="win32"?ot:Lt).join(o.skillsPath,Mr(o.skillSlug)),generation:l.envelope.generation,archiveSha256:l.archiveSha256,manifestSha256:l.envelope.manifest.sha256,files:l.envelope.manifest.files})).status!=="verified")return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:o.skillSlug,installedArchiveSha256:u.archiveSha256,approvedArchiveSha256:l.archiveSha256,installedContentDigest:d,approvedContentDigest:p,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and retry with --replace-unverified-source to replace them with the approved catalogue generation."},"The approved catalogue artifact differs from the installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let m=await oA({backend:e,skillSlug:o.skillSlug,scope:o.scope,agent:o.agent,skillsPath:o.skillsPath,bytes:l.bytes,files:l.files,envelope:l.envelope,approval:l.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});return{...t,...Sh(a),archiveSha256:l.archiveSha256,archiveHashFormat:l.archiveHashFormat,scope:o.scope,agent:o.agent.id,targetAgent:o.agent.id,materializationPlan:{scope:o.scope,agent:o.agent.id},...Mu(e),...m,...m.guardianActivationReceipt?{warnings:[...Fe(t,"warnings")??[],...Fe(m,"warnings")??[]]}:{}}}async function woe(e,t,n,r,i){let o=j(t,"materializationPlan")??j(t,"installPlan"),s=k(r.scope)??f(t,"scope")??(o?f(o,"scope"):void 0),a=f(t,"skillSlug")??f(t,"slug")??n;if(s!=="project"&&s!=="global")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Use --agent all with --scope project or --scope global."},"Installing for all compatible agents requires project or global scope.",r.json,"materialization_target_invalid");let l=Qe(e.env,e.platform,e.cwd),c=new Map;for(let w of l){let _=s==="global"?w.targets.globalSkillsPath:w.targets.projectSkillsPath;if(!_)continue;let C=Bo(_,e.platform),P=c.get(C);P?P.agents.push(w):c.set(C,{agent:w,agents:[w],skillsPath:_})}if(c.size===0)return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Run `skills-layer agents list` and select a supported target with an available path."},`No supported agent exposes a ${s} skill path on this machine.`,r.json,"materialization_target_invalid");for(let w of c.values())for(let _ of w.agents){let C=await Ya({backend:e,skillSlug:a,agentId:_.id,scope:s,flags:r});if(C)return C}let u=f(t,"version")??f(t,"currentVersion"),d=await bh(e,t,a,u,i),p=await xh({backend:e,exportResult:d,flags:r,skillSlug:a,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(p))return p;let m=ct(p.files),h=(await lt(e)).installs[a],g;if(!r.replaceUnverifiedSource)for(let w of c.values()){let _=(e.platform==="win32"?ot:Lt).join(w.skillsPath,Mr(a)),C=qn(h,{scope:s,installedPath:_,platform:e.platform})[0];if(C?.record.verificationStatus==="unverified"&&(await Dr({targetDir:_,generation:p.envelope.generation,archiveSha256:p.archiveSha256,manifestSha256:p.envelope.manifest.sha256,files:p.envelope.manifest.files})).status!=="verified"){g=C;break}}if(g)return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:a,materializationId:g.materializationId,installedContentDigest:f(g.record,"sourceContentDigest"),approvedContentDigest:m,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and use --replace-unverified-source to replace the unverified generation."},"The approved catalogue artifact differs from an installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let y=[];for(let w of c.values()){let _=await oA({backend:e,skillSlug:a,scope:s,agent:w.agent,skillsPath:w.skillsPath,bytes:p.bytes,files:p.files,envelope:p.envelope,approval:p.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});y.push({...t,scope:s,agent:w.agent.id,targetAgent:w.agent.id,...Mu(e),..._})}let v=y[0],b=v[Ch];return{...t,...Sh(d),archiveSha256:p.archiveSha256,archiveHashFormat:p.archiveHashFormat,scope:s,agent:"all",targetAgents:l.map(w=>w.id),materializationPlan:{scope:s,agent:"all",physicalTargetCount:y.length,agentCount:l.length},materializationResults:y,materializedWrites:y.flatMap(w=>Array.isArray(w.materializedWrites)?w.materializedWrites:[]),materializedSkillRoot:f(v,"materializedSkillRoot"),...Mu(e),...lU(b)?{[Ch]:b}:{}}}async function Ya(e){let t=e.backend.config?.workingModeType==="enterprise_workspace",n=e.enforceRequired?"enforce":await rd(e.backend,e.skillSlug);if(!t&&n!=="enforce"&&n!=="enabled")return null;let r=Re(e.backend.config?.workingModeWorkspaceId);if(t&&!r)return x({status:"blocked",reasonCode:"guardian_workspace_context_unavailable",skillSlug:e.skillSlug,agent:e.agentId,scope:e.scope,nextAction:"workspace.current",nextStep:"Refresh the selected Enterprise workspace before materializing this skill."},"Enterprise materialization requires a current workspace-bound Guardian context.",e.flags.json,"guardian_workspace_context_unavailable");let i=await zn(e.backend,e.scope),o=(Fe(i,"hooks")??[]).filter(L).find(u=>f(u,"agent")===e.agentId&&f(u,"scope")===e.scope&&u.active===!0),s=wr(e.agentId),a=yl({evaluationContext:"activation_eligibility",requestedMode:"enforce",workspacePolicy:t?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:s?.maximumTier==="strict_candidate",hookInstalled:!!o,strictHookVerified:o?.strictPreActionBlocking===!0&&o.evidenceCapability==="strict",exactActivationVerified:o?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"none",materializationState:"active"}),l=a.activationAllowed&&a.countedAsEnforced,c=t&&e.backend.config.workingModeGuardianPolicy==="standard"&&o!==void 0&&o.configActive!==!1;return l||c?(t&&(e.backend.guardianActivationReceipts??={},e.backend.guardianActivationReceipts[`${e.agentId}:${e.scope}`]={policy:e.backend.config.workingModeGuardianPolicy==="standard"?"standard":"strict",agent:e.agentId,scope:e.scope,tier:l?"strict_verified":"hook_unverified",observedAt:e.backend.now()}),null):x({status:"blocked",reasonCode:"guardian_enforcement_unavailable",skillSlug:e.skillSlug,workspaceId:r,agent:e.agentId,scope:e.scope,measuredProtection:{...a,evidenceCapability:o?.evidenceCapability??"unverified",evidenceReasons:o?.evidenceReasons??[s?.reasonCode??"host_has_no_supported_guardian_route"]},nextAction:"guardian.hook.install",nextStep:!o||o.configActive===!1?`Run skills-layer guardian hook install --agent ${e.agentId} --scope ${e.scope}.`:e.backend.config?.workingModeRole==="enterprise_admin"?`This host has no current strict verification. Select a qualified host or use skills-layer enterprise workspace update ${e.backend.config?.workingModeEnterpriseId??"<enterprise-id>"} ${r??"<workspace-id>"} --guardian-policy standard. Hook installation alone does not prove strict enforcement.`:"This host has no current strict verification. Ask your Enterprise Admin to select a qualified host or review the workspace Guardian policy. Hook installation alone does not prove strict enforcement."},t&&e.backend.config.workingModeGuardianPolicy==="standard"&&(!o||o.configActive===!1)?`No active Guardian hook is installed for ${e.agentId} at ${e.scope} scope.`:`${t?"Enterprise":"Guardian-enforced"} materialization was blocked because verified Guardian enforcement is unavailable.`,e.flags.json,"guardian_enforcement_unavailable")}function $P(e,t,n){let r=e.guardianActivationReceipts?.[`${t}:${n}`];return r?{guardianEnforcement:r.tier,guardianActivationReceipt:r,...r.tier==="hook_unverified"?{warnings:[`Guardian hook installed but not strict-verified on ${t}; workspace policy allows standard enforcement.`]}:{}}:{}}function Mu(e){return e.config?.workingModeType!=="enterprise_workspace"?{}:ie({workingModeType:"enterprise_workspace",enterpriseId:e.config.workingModeEnterpriseId,workspaceId:e.config.workingModeWorkspaceId,workingModeWorkspaceId:e.config.workingModeWorkspaceId})}function iA(e,t,n,r){let i=j(t,"materializationPlan")??j(t,"installPlan"),o=k(r.scope)??f(t,"scope")??(i?f(i,"scope"):void 0),s=f(t,"skillSlug")??f(t,"slug")??n;if(o==="local")return{status:"cache_only",skillSlug:s,version:f(t,"version")??f(t,"currentVersion")};if(o!=="project"&&o!=="global")return{status:"skip"};let a=k(r.agent)??f(t,"agent")??f(t,"targetAgent")??(i?f(i,"agent")??f(i,"targetAgent"):void 0)??Re(e.config?.lastSelectedAgent)??"codex",l=Qe(e.env,e.platform,e.cwd).find(u=>u.id===a);if(!l)return{status:"failure",skillSlug:s,message:`Unsupported agent "${a}". Run \`skills-layer agents list\` to choose a supported local install target.`,nextStep:"Run `skills-layer agents list` and retry with a supported --agent value."};let c=o==="global"?l.targets.globalSkillsPath:l.targets.projectSkillsPath;return c?{status:"ok",scope:o,agent:l,skillsPath:c,skillSlug:s,version:f(t,"version")??f(t,"currentVersion")}:{status:"failure",skillSlug:s,message:`${l.displayName} does not expose a ${o} skills path on this machine.`,nextStep:"Retry with --scope project, or choose another agent from `skills-layer agents list`."}}async function bh(e,t,n,r,i={}){if(typeof t.downloadUrl=="string"&&L(t.artifactEnvelope)&&L(t.artifactApproval)&&L(t.platformScoreAuthority))return t;let o=new URLSearchParams;r&&o.set("version",r);let s=i.exportMode==="public"||!e.apiKey,a=s?`/api/v1/skills/${encodeURIComponent(n)}/export${at(o)}`:`/api/v1/me/library/${encodeURIComponent(n)}/export${at(o)}`,l=await D(e,a,{headers:s?{}:re(e.apiKey,e.authBlockedMessage)});if(!s&&!L(l.platformScoreAuthority))try{let c=await D(e,`/api/v1/skills/${encodeURIComponent(n)}/export${at(o)}`,{headers:{}});return{...l,platformScoreAuthority:c.platformScoreAuthority}}catch(c){if(!(c instanceof Z)||![401,403,404].includes(c.status))throw c}return s?{...l,downloadUrl:boe(n,f(l,"version")??r)}:l}function boe(e,t){let n=new URLSearchParams;return t&&n.set("version",t),`/api/v1/skills/${encodeURIComponent(e)}/download${at(n)}`}function _oe(e){let t=f(e,"visibility")??f(e,"versionVisibility"),n=f(e,"publicationStatus");return sU(e)&&(t==="public"||n==="clean_publishable"||n==="publishable_with_findings")}function Soe(e){return sU(e)}async function Uu(e){let t=_h(e.result),n=f(t,"skillSlug")??f(t,"slug")??e.fallbackSlug,r=e.requestedVisibility??(f(t,"visibility")==="public"||f(t,"versionVisibility")==="public"||f(t,"releaseVisibility")==="public"?"public":"private");if(!Soe(t)){let c=j(t,"publication"),u=f(t,"reasonCode")??(c?f(c,"reasonCode"):void 0)??"security_review_pending",d=!!e.unverifiedMaterialization,p=f(t,"version"),m=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"version")??f(e.unverifiedMaterialization,"currentVersion"):void 0,h=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"generationId"):void 0,g=c?f(c,"status")??f(t,"status")??"submitted":f(t,"status")??"submitted",y=g==="catalogue_submission_failed"||u==="source_ingestion_candidate_not_claimable",v=f(t,"workflowId"),b=f(t,"processingAttemptId"),w=f(t,"jobId"),_=f(t,"intakeReceiptId"),C=j(t,"progress")??{},P=!y&&t.continuationConfirmed!==!1&&!!(v||b||w)&&["queued","running","catalogue_processing_scheduled","held_for_moderation","source_install_pending_review","reused"].includes(g),O={status:y?"rejected":g==="reused"&&_?"reused":P?g==="reused"?"reused":"accepted":_?"accepted":"unconfirmed",reasonCode:u,continuationConfirmed:P,nextActor:f(C,"nextActor")??(P?"platform":u==="source_ingestion_candidate_not_claimable"?"operator":"requester")},N=ie({...e.unverifiedMaterialization,status:d?"installed_unverified":"install_pending_review",sourceItemStatus:f(t,"status")??"submitted",skillId:f(t,"skillId"),versionId:f(t,"versionId"),skillSlug:n,version:d?m:p,catalogueCandidateVersion:p,localProvisionalVersion:m,localGeneration:h,sourceContentDigest:e.unverifiedMaterialization?f(e.unverifiedMaterialization,"sourceContentDigest"):void 0,visibility:r,catalogueVisibilityRequested:r,requestedVisibility:r,catalogueStatus:g,publiclyDiscoverable:!1,intakeAdmission:O,assessmentStatus:f(C,"status")??(P?"pending":"unconfirmed"),publicationStatus:"not_published",distributionStatus:"verified_artifact_required",workflowId:v,processingAttemptId:b,jobId:w,intakeReceiptId:_,progress:t.progress,intakeReceiptIds:t.intakeReceiptIds,candidateIds:t.candidateIds,wakeStatus:t.wakeStatus,uploadIntent:t.uploadIntent,backgroundWorkStatus:P?"catalogue_review_continues_automatically":"retry_or_operator_action_required",publication:c?_h(c):void 0,activationStatus:d?"installed_unverified":"held",verificationStatus:d?"unverified":void 0,reasonCode:u,materializedWrites:d&&Array.isArray(e.unverifiedMaterialization?.materializedWrites)?e.unverifiedMaterialization.materializedWrites:[],materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex",activation:d?"unverified_install_request_authorized":"approved_artifact_only"},nextStep:d?`Local installation is complete as Unverified / Unscored. ${P?"The durable assessment job remains scheduled.":"Continued assessment is not confirmed; retry submission or inspect the candidate status."} Verified publication requires valid four-dimension evidence and current distribution authority. Valid poor effectiveness is a warning, not a security block.`:P?`Run skills-layer ${_?`install status ${_}`:`creator status ${n}`}, then retry when verified distribution is available.`:"Submission continuation is not confirmed. Inspect the intake status or retry submission before waiting for assessment."});return d&&await Ha(e.backend,N,n),Va(N,d?`External source installed locally as unverified; ${P?"catalogue review continues":"catalogue continuation is unconfirmed"}.`:P?"Source submitted; installation is pending approval.":"Source installation is held; catalogue continuation is unconfirmed.",e.flags.json,e.backend)}let i=j(j(t,"progress")??{},"subject"),o=i?f(i,"generationId"):void 0,s=i?f(i,"version"):void 0;if(i&&(!o||!s||f(i,"slug")!==n))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",skillSlug:n,intakeReceiptId:t.intakeReceiptId,nextStep:"Retry after the source receipt identifies the exact approved skill, version and generation."},"The completed source receipt does not identify this exact skill and generation.",e.flags.json,"source_catalogue_identity_invalid");let a;try{a=await rA(e.backend,t,n,e.flags,{exportMode:_oe(t)?"public":"auto",...i?{expectedSourceGeneration:{generationId:o,version:s}}:{}})}catch(c){if(!(c instanceof Z)||![404,502,503,504].includes(c.status))throw c;let u=ie({...t,...e.unverifiedMaterialization,status:e.unverifiedMaterialization?"installed_unverified":"catalogue_artifact_unavailable",activationStatus:e.unverifiedMaterialization?"installed_unverified":"not_installed",sourceItemStatus:f(t,"status"),catalogueStatus:f(t,"status"),publicationStatus:"published",continuationConfirmed:!0,reasonCode:"catalogue_artifact_unavailable",serverReasonCode:c.details?f(c.details,"reasonCode"):void 0,nextStep:"The catalogue version is published, but its approved artifact could not be downloaded. Retry the install when export is available. Any existing local source install remains unverified."});return e.unverifiedMaterialization?(await Ha(e.backend,u,n),Va(u,"Source installed locally as unverified; the published catalogue artifact is temporarily unavailable.",e.flags.json,e.backend)):x(u,"The published catalogue artifact is temporarily unavailable.",e.flags.json,"catalogue_artifact_unavailable")}if(fe(a))return a;let l=await sA(e.backend,a,n,e.flags);return await Ha(e.backend,l,n),Va(l,zoe(e.source,e.flags,e.backend,l,e.sourceAccess),e.flags.json,e.backend)}function _h(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>t==="localWrites"||t==="files"||t==="content"||t==="archiveBytes"?[]:Array.isArray(n)?[[t,n.map(r=>L(r)?_h(r):r)]]:L(n)?[[t,_h(n)]]:[[t,n]]))}function sU(e){if(aU(e.artifactApproval).status==="ok"&&e.artifactEnvelope!==void 0&&typeof e.downloadUrl=="string")return!0;let n=j(e,"publication"),r=n?f(n,"status")==="published":!1,i=f(e,"listingStatus")==="published",o=f(e,"versionStatus")==="published",s=f(e,"status");return i&&o&&(r||s==="published"||s==="reused"||s==="source_approved")}function Sh(e){return ie({version:f(e,"version"),storageKey:f(e,"storageKey"),expiresAt:f(e,"expiresAt")})}async function xh(e){let t=aU(e.exportResult.artifactApproval);if(t.status!=="ok"){let d=t.status==="missing";return $i(e,d?"artifact_v1_approval_missing":"artifact_v1_approval_invalid",d?`Export for ${e.skillSlug} did not include an authoritative approved Artifact Format v1 identity.`:`Export for ${e.skillSlug} included malformed Artifact Format v1 approval metadata.`)}let n=t.approval;if(e.expectedSourceGeneration&&(n.generation.generationId!==e.expectedSourceGeneration.generationId||n.generation.semanticVersion!==e.expectedSourceGeneration.version))return $i(e,"source_catalogue_generation_mismatch","The exported artifact does not match the exact version and generation resolved for this source.");let r=xoe({backend:e.backend,exportResult:e.exportResult,approval:n,skillSlug:e.skillSlug});if(r.status!=="ok")return $i(e,r.reasonCode,r.message);if(e.exportResult.artifactEnvelope===void 0)return $i(e,"artifact_v1_envelope_missing",`Export for ${e.skillSlug} did not include an Artifact Format v1 envelope.`);let i=f(e.exportResult,"downloadUrl");if(!i)return x({status:"export_download_unavailable",reasonCode:"export_download_unavailable",skillSlug:e.skillSlug,nextStep:"Retry after the backend returns a signed bundle download URL."},`Export for ${e.skillSlug} did not include a signed download URL.`,e.flags.json,"export_download_unavailable");let o=await e.backend.fetchFn(Ioe(e.backend.baseUrl,i));if(!o.ok)throw new Z(o.status,`Unable to download exported bundle (${o.status}).`);let s;try{s=await Poe(o)}catch(d){return $i(e,"artifact_v1_archive_bounds_failed",`Downloaded ${e.skillSlug} exceeded Artifact Format v1 archive bounds.`,{verificationError:ve(d)})}let a,l;try{a=Nd({archiveBytes:s,envelope:e.exportResult.artifactEnvelope}),l=Cl({archiveBytes:s,envelope:a})}catch(d){return $i(e,"artifact_v1_verification_failed",`Downloaded ${e.skillSlug} failed Artifact Format v1 verification.`,{verificationError:ve(d)})}if(!Coe(n,a))return $i(e,"artifact_v1_identity_mismatch",`Downloaded ${e.skillSlug} did not match the authoritative approved generation.`);let c=f(e.exportResult,"skillSlug"),u=f(e.exportResult,"version");return a.generation.skillSlug!==e.skillSlug||c!==void 0&&c!==a.generation.skillSlug||u!==void 0&&u!==a.generation.semanticVersion?$i(e,"artifact_v1_target_mismatch",`Downloaded ${e.skillSlug} was approved for a different skill or version.`):{status:"ok",bytes:s,files:l,envelope:a,approval:n,archiveSha256:a.archive.sha256,archiveBytesSha256:a.archive.sha256,archiveHashFormat:"artifact_v1_zip"}}function xoe(e){let t=j(e.exportResult,"platformScoreAuthority"),n=t?.machineReport,r=t?.passport,i=t?.parityManifest,o=t?f(t,"passportPublicKey"):void 0;if(!t||!rC(n)||!o)return{status:"invalid",reasonCode:"platform_score_authority_missing",message:`Export for ${e.skillSlug} did not include a verifiable Platform Score authority.`};let s=Yc.safeParse(r),a=nC.safeParse(i);if(!s.success||!a.success)return{status:"invalid",reasonCode:"platform_score_authority_invalid",message:`Export for ${e.skillSlug} included malformed Platform Score authority metadata.`};let l=n.projection.report;if(l.subject.slug!==e.skillSlug||l.subject.version!==e.approval.generation.semanticVersion||l.subject.generationId!==e.approval.generation.generationId||l.subject.archiveSha256!==e.approval.archiveSha256||a.data.report.reportId!==l.reportId||a.data.report.revision!==l.revision||a.data.report.digest!==l.reportDigest)return{status:"invalid",reasonCode:"platform_score_authority_subject_mismatch",message:`Export for ${e.skillSlug} did not match the exact Platform Score generation.`};try{let c=ZL({passport:s.data,publicKeys:{[s.data.issuer.keyId]:Yne(o)},now:e.backend.now(),expectedSubject:l.subject,expectedReport:{reportId:l.reportId,revision:l.revision,digest:l.reportDigest},currentPassportId:s.data.passportId});if(!c.valid)return{status:"invalid",reasonCode:`platform_score_${c.reasonCode}`,message:`Export for ${e.skillSlug} failed signed Skill Passport verification.`}}catch{return{status:"invalid",reasonCode:"platform_score_passport_key_invalid",message:`Export for ${e.skillSlug} included an invalid Skill Passport public key.`}}return{status:"ok"}}function aU(e){return e==null?{status:"missing"}:!L(e)||e.status!=="approved"||!L(e.generation)||typeof e.generation.skillSlug!="string"||typeof e.generation.semanticVersion!="string"||typeof e.generation.generationId!="string"||typeof e.archiveSha256!="string"||typeof e.manifestSha256!="string"?{status:"invalid"}:{status:"ok",approval:{status:"approved",generation:{skillSlug:e.generation.skillSlug,semanticVersion:e.generation.semanticVersion,generationId:e.generation.generationId},archiveSha256:e.archiveSha256,manifestSha256:e.manifestSha256}}}function Coe(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archive.sha256&&e.manifestSha256===t.manifest.sha256}function $i(e,t,n,r={}){return x({status:"download_integrity_failed",reasonCode:t,skillSlug:e.skillSlug,version:f(e.exportResult,"version"),archiveHashFormat:"artifact_v1_zip",...r,nextStep:"Retry after the catalog serving generation is refreshed, or contact Skills Layer support if this repeats."},n,e.flags.json,t)}function Ioe(e,t){return/^https?:\/\//iu.test(t)?t:`${dr(e)}${t.startsWith("/")?"":"/"}${t}`}async function Poe(e){let t=e.headers.get("content-length");if(t!==null){let a=Number(t);if(!Number.isSafeInteger(a)||a<0)throw new Error("Artifact response Content-Length is invalid.");if(a>ut.maxArchiveBytes)throw new Error("Artifact response exceeds the v1 archive byte limit.")}if(!e.body)throw new Error("Artifact response body is unavailable.");let n=e.body.getReader(),r=[],i=0;try{for(;;){let a=await n.read();if(a.done)break;if(i+=a.value.byteLength,i>ut.maxArchiveBytes)throw await n.cancel("Artifact response exceeds the v1 archive byte limit."),new Error("Artifact response exceeds the v1 archive byte limit.");r.push(Uint8Array.from(a.value))}}finally{n.releaseLock()}let o=new Uint8Array(i),s=0;for(let a of r)o.set(a,s),s+=a.byteLength;return o}async function oA(e){let t=e.verificationStatus??"verified";if(t==="verified"&&!e.approval)throw new Error("Verified materialization requires platform artifact approval.");let n=e.backend.platform==="win32"?ot:Lt,r=ct(e.files),i=n.join(e.backend.paths.bundlesDir,e.skillSlug,e.envelope.generation.semanticVersion,encodeURIComponent(e.envelope.generation.generationId),"bundle.zip"),o=n.join(e.skillsPath,Mr(e.skillSlug)),s=Qe(e.backend.env,e.backend.platform,e.backend.cwd).filter(G=>{let ee=e.scope==="global"?G.targets.globalSkillsPath:G.targets.projectSkillsPath;return ee!==null&&Bo(ee,e.backend.platform)===Bo(e.skillsPath,e.backend.platform)}).map(G=>G.id).sort(),a=`activation_${Ge(16).toString("hex")}`,l={targetDir:o,generation:e.envelope.generation,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,files:e.envelope.manifest.files},c=nz({scope:e.scope,targetDir:o,platform:e.backend.platform}),u=await lt(e.backend);for(let[G,ee]of Object.entries(u.installs)){let te=[ee,...An(ee).map(X=>X.record)].flatMap(X=>[Jt(X)?.receipt.targetDir,f(X,"materializedSkillRoot"),f(X,"materializedPath")]);if(G!==e.skillSlug&&te.some(X=>X&&yA(o,X,e.backend.platform)))throw new Error(`Install folder already belongs to another skill (${G}). Remove that installation or choose a different target before installing ${e.skillSlug}.`)}let d=u.installs[e.skillSlug],p=Yt(d)[c],m=JSON.stringify(p??null),h=Wu({state:"pending_activation",operationId:a,receipt:l,backend:e.backend}),g=Wu({state:"active",operationId:a,receipt:l,backend:e.backend}),y={skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,targetAgents:s.length>0?s:[e.agent.id],materializedPath:o,materializedSkillRoot:o,materializationId:c,bundlePath:i,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,...Mu(e.backend),...$P(e.backend,e.agent.id,e.scope),localLifecycle:h,savedAt:e.backend.now()};await IA(i,e.bytes);let v=e.files.find(G=>it(G.path).toLowerCase()==="skill.md"),b=v?await jae({backend:e.backend,skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,skillDocumentPath:n.join(o,...nM(v.path)),skillDocumentContent:v.content??""}):void 0,w,_=!1,C;try{let G={targetDir:o,...t==="verified"&&p?.verificationStatus==="unverified"&&!e.replaceUnverifiedSource?{expectedPreviousReceipt:l}:{},archiveBytes:e.bytes,envelope:e.envelope,preActivate:async({stageDir:ee})=>{let te=await Roe({backend:e.backend,stageDir:ee,envelope:e.envelope});return te.status==="passed"?(w=te.evalRun,{status:"passed",evidenceId:te.evidenceId}):{status:"failed",reasonCode:te.reasonCode}},checkpoint:async ee=>{if(ee==="after_static_eval"){await Br(e.backend,te=>{let X=te.installs[e.skillSlug],Ce=Yt(X)[c];if(JSON.stringify(Ce??null)!==m)throw new Error(`Local install materialization for ${e.skillSlug} changed during atomic activation.`);te.installs[e.skillSlug]=Fr({existing:X,skillSlug:e.skillSlug,materialization:y,backend:e.backend})}),_=!0;return}ee==="after_stage_activated"&&await Br(e.backend,te=>{let X=te.installs[e.skillSlug],Ce=Yt(X)[c],pn=Ce?Jt(Ce):null;if(!pn||pn.state!=="pending_activation"||pn.operationId!==a)throw new Error(`Atomic activation receipt reservation for ${e.skillSlug} was lost before commit.`);te.installs[e.skillSlug]=Fr({existing:X,skillSlug:e.skillSlug,materialization:{...y,localLifecycle:g,savedAt:e.backend.now()},backend:e.backend})})}};C=t==="verified"?await Yj({...G,approval:e.approval}):await Xj(G)}catch(G){throw _&&await cle({backend:e.backend,skillSlug:e.skillSlug,materializationId:c,operationId:a,baselineMaterialization:p}),G}if(!w)throw new Error("Static pre-activation Eval did not produce generation-bound evidence.");let P=await lt(e.backend),O=Yt(P.installs[e.skillSlug])[c],N=O?Jt(O):null;if(!N||N.state!=="active"||N.operationId!==a)throw new Error(`Atomic activation receipt for ${e.skillSlug} was not committed.`);let Q=C.receipt.files.map(G=>({path:yU(e.backend.cwd,n.join(o,...nM(G.path))),bytes:G.sizeBytes}));return{...e.backend.config?.workingModeType==="enterprise_workspace"?{status:"installed"}:{},bundlePath:i,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,...Mu(e.backend),...$P(e.backend,e.agent.id,e.scope),materializedPath:o,materializedSkillRoot:o,materializationId:c,targetAgents:s.length>0?s:[e.agent.id],archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,materializedWrites:Q,...b?{guardianRuntimeMetadata:b}:{},localLifecycle:g,atomicActivation:{status:C.status,receipt:C.receipt,generation:C.receipt.generation,archiveSha256:C.receipt.archiveSha256,manifestSha256:C.receipt.manifestSha256,staticEvaluation:C.staticEvaluation,cleanupPending:C.cleanupPending,...C.cleanupPath?{cleanupPath:C.cleanupPath}:{}},[Ch]:w}}var Ch=Symbol("skills-layer.pre-activation-eval"),Aoe=new Set(["file_exists","json_valid","schema_match","section_exists","regex_match","artifact_valid"]);async function Roe(e){let t=await cU(e.stageDir),n=ct(t),r=pU(t,n),i=l=>X1({pack:l,files:t,activationState:"inactive_staging",skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now(),runnerVersion:DP()}),o=i(r.pack);if(o.outcome!=="completed")return{status:"failed",reasonCode:o.reasonCode};let s=i(fU(t,n));if(s.outcome!=="completed")return{status:"failed",reasonCode:s.reasonCode};if(s.result.summary.status!=="passed")return{status:"failed",reasonCode:`static_eval_${s.result.summary.status}`};let a=dU({files:t,skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now()});return{status:"passed",evidenceId:`${s.result.summary.evalPackDigest??"eval-pack-unavailable"}:${s.result.summary.artifactDigest}`,evalRun:a}}async function sA(e,t,n,r){let i=f(t,"materializedSkillRoot");if(!i)return t;let o=f(t,"skillSlug")??f(t,"slug")??n,s=f(t,"version")??f(t,"currentVersion")??k(r.version)??"local";try{let a=t[Ch],l;if(lU(a))l=a;else{let u=await cU(Tt(e.cwd,i));if(u.length===0)return dh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"installed_files_unreadable"});l=dU({files:u,skillSlug:o,version:s,generatedAt:e.now()})}let c=await Foe(e,l.summary);return c.status==="recorded"?dh({...t,...c.effectiveness?{effectiveness:c.effectiveness}:{}},r,{status:"recorded",source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,evidenceRevision:c.evidenceRevision}):dh(t,r,{status:c.status,source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,reasonCode:c.reasonCode})}catch(a){return dh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"local_eval_failed",message:ve(a)})}}function lU(e){return L(e)&&(e.source==="submitted"||e.source==="inferred"||e.source==="invalid_submitted")&&L(e.summary)&&e.summary.schemaVersion==="skills-layer.eval.summary.v1"}async function cU(e){let t=[];return await uU(e,e,t),t.sort((n,r)=>n.path.localeCompare(r.path))}async function uU(e,t,n){for(let r of await ere(t,{withFileTypes:!0})){if(Eoe(r.name))continue;let i=K(t,r.name);if(r.isDirectory()){await uU(e,i,n);continue}if(!(!r.isFile()||Doe(r.name)))try{n.push({path:Bu(e,i).split("\\").join("/"),content:await Fi(i,"utf8")})}catch{continue}}}function Eoe(e){return e===".git"||e==="node_modules"||e==="coverage"||e===$oe()||e==="dist"}function $oe(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}function Doe(e){return e==="bundle.zip"||/^\.skills-layer-.*\.json$/u.test(e)}function dU(e){let t=ct(e.files),n=pU(e.files,t);if(!sf(n.pack).valid)return{source:"invalid_submitted",summary:Es({status:"runner_unavailable",skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:t,evalPackDigest:Rs(n.pack),generatedAt:e.generatedAt,runnerVersion:DP(),counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})};let i=Ooe(n.pack).map(s=>({id:s.id,assertions:s.assertions.map(a=>Loe(a,e.files))})),o=joe(i);return{source:n.source,summary:Es({status:Noe(o),skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:typeof n.pack.artifactDigest=="string"?n.pack.artifactDigest:t,evalPackDigest:Rs(n.pack),generatedAt:e.generatedAt,runnerVersion:DP(),counts:{cases:i.length,assertions:o.total,passed:o.passed,failed:o.failed,skipped:o.skipped}})}}function pU(e,t){let n=Toe(e);return n?{pack:n,source:"submitted"}:{pack:fU(e,t),source:"inferred"}}function Toe(e){for(let t of e){let n=$n(t.path,e);if(!(n.type!=="evidence"||!t.content||!n.relativePath.toLowerCase().endsWith(".eval.json")))try{let r=JSON.parse(t.content);if(L(r))return r}catch{return{schemaVersion:"invalid",artifactDigest:ct(e),origin:"submitted",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[]}}}}function fU(e,t){let r=e.find(i=>i.path.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()==="skill.md")?.path??"SKILL.md";return{schemaVersion:"skills-layer.eval.pack.v1",artifactDigest:t,origin:"inferred",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[{id:"starter-runtime-shape",assertions:[{type:"file_exists",path:r},{type:"regex_match",path:r,pattern:"name:"},{type:"artifact_valid",artifactDigest:t}]}]}}function Ooe(e){return Array.isArray(e.cases)?e.cases.flatMap(t=>!L(t)||typeof t.id!="string"||!Array.isArray(t.assertions)?[]:[{id:t.id,assertions:t.assertions.filter(L)}]):[]}function Loe(e,t){return typeof e.type=="string"&&!Aoe.has(e.type)?{status:"skipped",reasonCode:"runner_unavailable"}:rf(e,{files:t})}function joe(e){return e.reduce((t,n)=>{for(let r of n.assertions)t.total+=1,r.status==="passed"&&(t.passed+=1),r.status==="failed"&&(t.failed+=1),r.status==="skipped"&&(t.skipped+=1);return t},{total:0,passed:0,failed:0,skipped:0})}function Noe(e){return e.failed>0?"failed":e.passed>0?"passed":e.skipped>0?"runner_unavailable":"not_run"}function DP(){return`skills-layer-public-cli:${So}:local-install`}async function Foe(e,t){if(!e.apiKey)return{status:"local_only",reasonCode:"not_authenticated"};try{let n=await D(e,"/api/v1/me/evals/results",{method:"POST",headers:{"content-type":"application/json",...re(e.apiKey,e.authBlockedMessage)},body:JSON.stringify({evalSummary:t})}),r=j(n,"evalEvidence");return{status:"recorded",effectiveness:j(n,"effectiveness"),evidenceRevision:r?J(r,"revision"):void 0}}catch(n){return{status:"submit_failed",reasonCode:n instanceof Z?`http_${n.status}`:"request_failed"}}}function dh(e,t,n){return t.json?{...e,localEval:n}:e}function nM(e){let n=e.replaceAll("\\","/").replace(/^\/+/u,"").trim().split("/").filter(r=>r.length>0);if(n.length===0||n.some(r=>r==="."||r===".."))throw new Error(`Unsafe bundle path "${e}".`);return n}async function rM(e,t,n,r,i){let o=k(r.visibility)??"private";if(o!=="private"&&o!=="public")return x({status:"invalid_visibility",reasonCode:"invalid_visibility",source:e,requestedVisibility:o,nextStep:`Use \`skills-layer install ${e} --visibility private\` or \`--visibility public\`.`},"Local path install visibility must be private or public.",r.json,"invalid_visibility");let s=aA(e,t,n);if(r.list)return A(s,"Local source skills loaded.",r.json,i);let a=Ih(e,s,r);if(a)return a;let l=await ju({source:e,inspection:s,requestedSkillSlug:n,mode:"install",flags:r,backend:i});if(l.kind==="failure")return l.result;let c=l.skillSlug??ur(s)[0]?.value??hU(e),u=Boe(t.files,c),d=Wr({files:u,limits:yo}),p={mode:r.localOnly?"local_only":o==="public"?"explicit_public":"managed_private",upload:!r.localOnly,destination:r.localOnly?null:i.baseUrl,audience:r.localOnly?"local_device":o==="public"?"public_after_governed_review":"account_private",authentication:r.localOnly?"not_required":"required",files:d.preview.files.map(y=>({path:y.path,bytes:y.bytes})),totalBytes:d.preview.totalBytes};if(r.dryRun)return A({...LP(e,s,c,r),installKind:"local_source_submission",visibility:o,publicationStatus:"preview",catalogRecord:o,activationStatus:"not_started",uploadIntent:p,nextStep:r.localOnly?"Re-run without --dry-run for unverified, unscored local activation without upload.":`Re-run without --dry-run to create or reuse the ${o} central item. Local activation remains held until the exact generation completes security review and Artifact-v1 approval.`},"Local source submission preview ready.",r.json,i);if(r.localOnly){let y=await TP({backend:i,flags:r,source:e,skillSlug:c,files:u,defaultAcceptUnverifiedSource:!0});if(fe(y))return y;let v={...y,status:"installed_unverified",activationStatus:"installed_unverified",uploadIntent:p,intakeAdmission:{status:"not_requested"},assessmentStatus:"not_requested",publicationStatus:"not_requested",distributionStatus:"unverified_local",backgroundWorkStatus:"not_requested"};return await Ha(i,v,c),Va(v,"Local source installed as unverified and unscored. No files were uploaded.",r.json,i)}if(!i.apiKey)return x({reasonCode:"local_source_authentication_required",uploadIntent:p,nextStep:"Sign in for managed submission, or use --local-only for an unverified installation without upload."},"Managed local source submission requires authentication before uploading files.",r.json,"local_source_authentication_required");i.emitInfo(`Upload intent: ${p.files.length} selected files (${p.totalBytes} bytes) to ${i.baseUrl}; audience ${p.audience}; authenticated account required. Use --dry-run --json to inspect the file list or --local-only to avoid upload.`);let m=await QP(i,c,r);if(m)return m;let h;if(mU(r,i)){let y=await TP({backend:i,flags:r,source:e,skillSlug:c,files:u});if(fe(y))return y;h=y}let g;try{let y=dg(u)?await xC({baseUrl:i.baseUrl,apiKey:i.apiKey,fetchFn:i.fetchFn,files:u}):null;g=await D(i,"/api/v1/me/source-installs",{method:"POST",headers:{"content-type":"application/json",...re(i.apiKey,i.authBlockedMessage)},body:JSON.stringify(ie({...y?{hydrationManifestId:y.manifestId}:{files:u},skillSlug:c,version:k(r.version),visibility:o,category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),sourceMetadata:t.sourceMetadata}))})}catch(y){return h?await Uu({backend:i,flags:r,source:e,fallbackSlug:c,sourceAccess:"authenticated",requestedVisibility:o,unverifiedMaterialization:h,result:{status:"catalogue_submission_failed",skillSlug:c,uploadIntent:p,reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable"}}):x({status:"catalogue_submission_failed",uploadIntent:p,activationStatus:"not_started",intakeAdmission:{status:"rejected"},assessmentStatus:"not_requested",publicationStatus:"not_published",distributionStatus:"verified_artifact_required",reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable",skillSlug:c,nextStep:"Retry the source submission when catalogue service is available. No local files were written."},"The source was not installed because catalogue submission did not complete.",r.json,"catalogue_submission_failed")}return await Uu({backend:i,result:{...g,uploadIntent:p},fallbackSlug:f(g,"skillSlug")??c,source:e,sourceAccess:"authenticated",flags:r,requestedVisibility:o,...h?{unverifiedMaterialization:h}:{}})}function Boe(e,t){let n=lA(e).find(i=>i.skillSlug===t);if(!n||n.relativeSkillRoot===".")return e.map(i=>({...i}));let r=`${n.relativeSkillRoot.replace(/\/+$/u,"")}/`;return e.filter(i=>i.path.replaceAll("\\","/").startsWith(r)).map(i=>({...i,path:i.path.replaceAll("\\","/").slice(r.length)}))}async function iM(e){if(!e.flags.all&&!(!e.defaultAcceptUnverifiedSource&&!mU(e.flags,e.backend)))try{let t=rr(e.source),n=await kj({source:t,cwd:e.backend.cwd,platform:e.backend.platform,fetchFn:e.backend.fetchFn,...e.skillSlug?{requestedSkillSlug:e.skillSlug}:{}}),r=e.skillSlug?n.results.find(i=>i.skillSlug===e.skillSlug):n.results.length===1?n.results[0]:void 0;return r?await TP({backend:e.backend,flags:e.flags,source:e.source,skillSlug:r.skillSlug,files:r.files,relativeSkillRoot:r.relativeSkillRoot,defaultAcceptUnverifiedSource:e.defaultAcceptUnverifiedSource}):e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,nextStep:"Use --list to inspect the source and --skill <skill-slug> to select one exact skill before retrying."},"The CLI could not resolve one immutable external skill snapshot for local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}catch(t){return e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,error:t instanceof Error?t.message.slice(0,512):"Source snapshot could not be loaded.",nextStep:"Check source access and retry the exact source after its immutable snapshot is available."},"The CLI could not load the external source snapshot for unverified local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}}async function TP(e){let t=Wr({files:e.files,limits:yo}),n=tt(e.files,{profile:"external_ingest_tolerant"}),r=f2(e.files,p2),i=[...t.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:/^(?:secret_|pii_|sensitive_)/u.test(_.code)?"privacy":"integrity",..._.path?{path:_.path}:{}})),...n.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:"package_validity"})),...r.filter(_=>_.severity==="high"||_.severity==="critical").map(_=>({code:_.ruleId,concern:"security",path:_.filePath,..._.lineNumber?{lineNumber:_.lineNumber}:{}}))],o=i.map(_=>_.code);if(o.length>0){let _=i.some(C=>C.concern==="security")?"critical_local_preflight_blocked":"source_package_invalid";return x({status:"unverified_install_blocked",reasonCode:_,skillSlug:e.skillSlug,findingCodes:[...new Set(o)].sort((C,P)=>C.localeCompare(P)),blockingFindings:i,nextStep:"Do not activate this source. Review or remove the blocking content, then retry from a new immutable generation."},"External source did not satisfy the required local package checks and was not installed.",e.flags.json,_)}if(!(e.flags.acceptUnverifiedSource===!0||e.defaultAcceptUnverifiedSource===!0||await Moe(e)))return x({status:"unverified_install_consent_required",reasonCode:"unverified_source_consent_required",skillSlug:e.skillSlug,nextStep:"Review the source, then retry with --accept-unverified-source to install it before platform approval."},"External source was not installed because informed unverified-source consent was not provided.",e.flags.json,"unverified_source_consent_required");let a=iA(e.backend,{skillSlug:e.skillSlug,materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex"}},e.skillSlug,e.flags);if(a.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:e.skillSlug,nextStep:a.nextStep},a.message,e.flags.json,"materialization_target_invalid");if(a.status==="skip"||a.status==="cache_only")return x({status:"materialization_target_required",reasonCode:"materialization_target_required",skillSlug:e.skillSlug,nextStep:"Retry with --scope project|global and --agent <agent>."},"An explicit local target is required for an unverified external installation.",e.flags.json,"materialization_target_required");let l=await Ya({backend:e.backend,skillSlug:e.skillSlug,agentId:a.agent.id,scope:a.scope,flags:e.flags});if(l)return l;let c=ct(e.files),u=rr(e.source),d=u.kind==="github"?u.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,p=e.relativeSkillRoot,m=u.kind==="github"&&/^[a-f0-9]{40}$/u.test(u.ref)?{provider:"github",repository:`${u.owner}/${u.repo}`,commitSha:u.ref,sourceRoot:!p||p==="."?d:d==="."?p:`${d}/${p}`,sourceContentDigest:t.preview.bundleSha256}:void 0,h=c.slice(7,19),g=k(e.flags.version)??`0.0.0-external.${h}`,y=`generation_unverified_${c.slice(7,39)}`,v=e.files.filter(_=>$n(_.path,e.files).type==="runtime").map(_=>_.path),b=s0({generation:{skillSlug:e.skillSlug,semanticVersion:g,generationId:y},reviewPackageFiles:e.files,runtimeAllowlist:v});return{...await oA({backend:e.backend,skillSlug:e.skillSlug,scope:a.scope,agent:a.agent,skillsPath:a.skillsPath,bytes:b.archiveBytes,files:Cl({archiveBytes:b.archiveBytes,envelope:b.envelope}),envelope:b.envelope,verificationStatus:"unverified"}),source:e.source,sourceContentDigest:c,...m?{sourceSnapshot:{...m,runtimeDigest:c,archiveSha256:b.envelope.archive.sha256}}:{},platformScoreDecision:null,scoreAvailability:"unscored",scoreReasonCode:"unscored_local_source",localPreflight:{status:"passed",recommendation:t.issues.length+n.issues.length+r.length>0?"approved_with_notes":"approved",issueCount:t.issues.length+n.issues.length+r.length,findingCodes:[...t.issues.map(_=>_.code),...n.issues.map(_=>_.code),...r.map(_=>_.ruleId)]}}}function mU(e,t){return e.acceptUnverifiedSource===!0||!e.json&&!t.nonInteractive&&t.stdoutIsTty}async function Moe(e){if(e.flags.json||e.backend.nonInteractive)return!1;try{return await e.backend.promptSelect(`${e.skillSlug} comes from ${e.source} and has not completed Skills Layer Security/Eval. Install this immutable generation as unverified?`,[{value:"decline",label:"Do not install",description:"Keep local agent files unchanged."},{value:"accept",label:"Install unverified",description:"Use locally now while catalogue review runs in parallel."}])==="accept"}catch{return!1}}function aA(e,t,n){let r=lA(t.files),i=n?r.find(o=>o.skillSlug===n)??null:r.length===1?r[0]??null:null;return{status:"ok",source:t.sourceMetadata,selectedSkill:i,results:r,issues:[],sourceInstallSupported:!0,sourceInstallMode:"local_private",publicationStatus:"none",originalSource:e}}function lA(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=Be(t.path).replaceAll("\\","/"),r=n==="."?".":n,i=gU(t.content??"")??hU(r==="."?t.path:r),o=Uoe(t.content??"");return{skillSlug:i,name:i,...o?{description:o}:{},relativeSkillRoot:r,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function gU(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function Uoe(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function hU(e){return(e.replaceAll("\\","/").replace(/\/+$/u,"").split("/").filter(Boolean).at(-1)??"local-skill").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"local-skill"}function yU(e,t){let n=Bu(e,t);return n&&!n.startsWith("..")&&!ot.isAbsolute(n)?n.split("\\").join("/"):t}function Ti(e,t,n,r="unknown"){let i=k(t.visibility);return i==="public"||i==="private"?i:r==="anonymous"&&OP(e)?"public":r==="authenticated"?"private":!n.apiKey&&OP(e)?"public":"private"}function OP(e){try{let t=rr(e).kind;return t==="github"||t==="gitlab"}catch{return/^https:\/\/(?:github|gitlab)\.com\//iu.test(e.trim())}}function cA(e,t,n,r="unknown"){return Ti(e,t,n,r)==="private"||k(t.visibility)==="unlisted"||r==="authenticated"?"/api/v1/me/source-installs":"/api/v1/source-imports"}function vU(e,t,n,r="unknown"){return{"content-type":"application/json",...cA(e,t,n,r)==="/api/v1/me/source-installs"?re(n.apiKey,n.authBlockedMessage):{}}}function zoe(e,t,n,r,i="unknown"){let o=r?f(r,"visibility")??f(r,"versionVisibility"):void 0,s=r?f(r,"publicationStatus"):void 0,a=r?f(r,"catalogRecord"):void 0,l=r?f(r,"status"):void 0;return o==="public"||s==="clean_publishable"||s==="publishable_with_findings"||l==="published"?"Public source install planned.":o==="private"||s==="private"||a==="private"||l==="private_source_installed"?"Private source skill installed.":Ti(e,t,n,i)==="public"?"Public source install planned.":"Private source skill installed."}async function ju(e){let t=ur(e.inspection);if(e.requestedSkillSlug)return t.length>0&&!t.some(n=>n.value===e.requestedSkillSlug)?{kind:"failure",result:qoe(e.source,e.requestedSkillSlug,t.map(n=>n.value),e.flags)}:{kind:"selected",skillSlug:e.requestedSkillSlug};if(e.flags.all||e.flags.json&&e.flags.dryRun)return{kind:"selected",skillSlug:e.requestedSkillSlug};if(t.length<=1)return{kind:"selected",skillSlug:t[0]?.value};if(e.flags.json)return{kind:"failure",result:oM(e.source,t,e.flags)};try{return{kind:"selected",skillSlug:await e.backend.promptSelect(`${e.source} exposes multiple skills. Select one to ${e.mode}:`,t)}}catch{return{kind:"failure",result:oM(e.source,t,e.flags)}}}function oM(e,t,n){let r=t.map(i=>i.value);return x({status:"selection_required",reasonCode:"source_skill_selection_required",source:e,availableSkills:r,nextAction:"install.source.select",nextStep:`Re-run with --skill <skill-slug> using one of: ${r.join(", ")}. Use --all only if you intend to install every discovered skill.`},`Source "${e}" exposes multiple skills. Re-run with --list or --skill <skill-slug>. Available skills: ${r.join(", ")}.`,n.json,"source_skill_selection_required")}function sM(e,t,n){if(n.all&&t)return x({status:"error",reasonCode:"conflicting_source_selection",source:e,selectedSkillSlug:t,all:!0,nextAction:"install",nextStep:"Use either --all to install every discovered skill or --skill <skill-slug> to install one skill, not both."},"Source install cannot combine --all with --skill. Choose one selection mode before retrying.",n.json,"conflicting_source_selection")}function aM(e,t){try{if(rr(e).kind!=="local")return}catch{return}return x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"install",nextStep:zu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source URL, or run `skills-layer install --source <source> --list` with a supported source."},zu(e)?`Install source ${e} was not found or is not readable.`:`Install source "${e}" is not a supported remote source and no local path was found.`,t.json,"invalid_source")}function qoe(e,t,n,r){return x({status:"not_found",reasonCode:"source_skill_not_found",source:e,requestedSkillSlug:t,availableSkills:n,nextAction:"install.source.list",nextStep:`Run \`skills-layer install --source ${e} --list\` to inspect discovered skills, then retry with one of the listed slugs.`},`Source ${e} does not contain a discovered skill named ${t}. Run with --list to inspect available skills.`,r.json,"source_skill_not_found")}function ur(e){let t=[e.results,e.skills,e.discoveredSkills,j(e,"source")?.results,j(e,"inspection")?.results],n=new Set,r=[];for(let i of t)if(Array.isArray(i))for(let o of i){let s=Voe(o);!s||n.has(s.value)||(n.add(s.value),r.push(s))}return r}function Voe(e){if(!L(e))return;let t=f(e,"skillSlug")??f(e,"slug")??f(e,"name");if(!t)return;let n=f(e,"displayName")??f(e,"title")??f(e,"name"),r=n&&n!==t?`${t} - ${n}`:t,i=j(e,"parsedSkill"),o=j(e,"frontmatter")??(i?j(i,"frontmatter"):void 0),s=f(e,"shortDescription")??f(e,"summary")??f(e,"description")??(o?f(o,"description"):void 0)??f(e,"relativeSkillRoot")??f(e,"path")??f(e,"discoveryRoute")??f(e,"sourceKind");return s?{value:t,label:r,description:s}:{value:t,label:r}}function lM(e,t,n,r,i,o={}){return ie({...t,skillSlug:n,scope:k(r.scope),agent:k(r.agent),workspace:k(r.workspace),version:k(r.version),visibility:o.visibility??k(r.visibility),category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),all:r.all,acceptCapability:r.acceptCapability})}async function cM(e){let t=e.sourceAccess??"unknown",n=cA(e.source,e.flags,e.backend,t);try{return await D(e.backend,n,{method:"POST",headers:vU(e.source,e.flags,e.backend,t),body:JSON.stringify(lM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{sourceAccess:t,...n==="/api/v1/source-imports"?{visibility:"public"}:{}}))})}catch(r){if(r instanceof Z&&r.status===401&&k(e.flags.visibility)!=="private"&&t!=="authenticated"&&OP(e.source))return await D(e.backend,"/api/v1/source-imports",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(lM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{visibility:"public"}))});throw r}}function LP(e,t,n,r){return ie({status:"dry_run",source:e,selectedSkillSlug:n,all:r.all,scope:k(r.scope)??"local",agent:k(r.agent),workspace:k(r.workspace),acceptCapability:r.acceptCapability,candidates:ur(t).map(i=>({skillSlug:i.value,name:i.label,description:i.description})),nextStep:r.all?`Re-run without --dry-run to install every discovered skill from ${e}.`:`Re-run without --dry-run${n?"":" and add --skill <skill-slug> if needed"} to install from ${e}.`})}async function kU(e,t,n,r,i={}){try{return{kind:"ok",inspection:await D(e,"/api/v1/source-inspect",{method:"POST",headers:wU(e,i.authMode??"auto"),body:JSON.stringify(ie(n))})}}catch(o){if(o instanceof Z)return{kind:"failure",result:NP(t,o,r)};throw o}}function wU(e,t){return t==="anonymous"?{"content-type":"application/json"}:V(e.apiKey)}async function jP(e,t,n,r){try{let s=await D(e,"/api/v1/source-inspect",{method:"POST",headers:wU(e,"anonymous"),body:JSON.stringify(ie(n))}),a=uM(t,s,r);return a?{kind:"failure",result:a}:{kind:"ok",inspection:s,sourceAccess:"anonymous"}}catch(s){if(!(s instanceof Z))throw s;let a=s.details??{},l=f(a,"error")??s.message;if(!uA(s.status,l))return{kind:"failure",result:NP(t,s,r)};if(!e.apiKey)return{kind:"failure",result:NP(t,s,r)}}let i=await kU(e,t,n,r,{authMode:"authenticated"});if(i.kind==="failure")return i;let o=uM(t,i.inspection,r);return o?{kind:"failure",result:o}:{kind:"ok",inspection:i.inspection,sourceAccess:"authenticated"}}function uM(e,t,n){if(n.list||n.dryRun)return null;let r=[t.catalogueDecision,...Array.isArray(t.catalogueDecisions)?t.catalogueDecisions:[]].filter(i=>i!==void 0);for(let i of r){let o=L(i)?i.status:void 0;if(!L(i)||i.schemaVersion!=="skills-layer.source-catalogue-decision.v1"||!["approved","pending","new"].includes(String(o))){let s=["security_blocked","revoked","restricted","unavailable"].includes(String(o))?`source_catalogue_${o}`:"source_catalogue_identity_invalid";return x({status:s,reasonCode:s,source:e,catalogueDecision:i,nextStep:"Resolve the current catalogue decision before retrying this exact source."},"This source cannot be activated under its current catalogue decision.",n.json,s)}}if(t.catalogueSourceInput!==void 0){let i=rr(e),o=typeof t.catalogueSourceInput=="string"?rr(t.catalogueSourceInput):void 0,s=l=>l.replace(/(?:^|\/)SKILL\.md$/u,"")||".";if(!(i.kind==="github"&&o?.kind==="github"&&`${i.owner}/${i.repo}`.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&s(i.subpath)===s(o.subpath)&&/^[a-f0-9]{40}$/u.test(o.ref)&&(!/^[a-f0-9]{40}$/iu.test(i.ref)||i.ref.toLowerCase()===o.ref)&&r.every(l=>{let c=L(l)?j(l,"subject"):void 0,u=c?f(c,"sourceRoot"):void 0,d=s(o.subpath);return c?.commitSha===o.ref&&typeof c.repository=="string"&&c.repository.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&u&&(u==="."||!u.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)))&&(d==="."||u===d||u.startsWith(`${d}/`))})))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e},"The inspected snapshot does not identify this exact source.",n.json,"source_catalogue_identity_invalid")}return null}function Ih(e,t,n){if(ur(t).length>0)return null;let i=Goe(t);return x({status:"unsupported_source_layout",source:e,reasonCode:"source_no_discoverable_skills",issues:i,nextStep:"Run with --list to inspect the source, use a subfolder containing SKILL.md, or install from a Skills Layer-compatible source layout."},Hoe(e,i),n.json)}function Goe(e){return(Array.isArray(e.issues)?e.issues:[]).filter(L).map(n=>({...f(n,"code")?{code:f(n,"code")}:{},...f(n,"message")?{message:f(n,"message")}:{},...f(n,"path")?{path:f(n,"path")}:{}}))}function NP(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(uA(t.status,i))return bU(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Go(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_inspectable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be inspected as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}function dM(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(uA(t.status,i))return bU(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Go(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_installable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be installed as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}async function pM(e){let t=e.error instanceof Z?e.error.details??{}:{},n=e.error instanceof Z?f(t,"reasonCode")??"catalogue_submission_failed":"catalogue_submission_unavailable";return await Uu({backend:e.backend,result:{...t,status:"catalogue_submission_failed",reasonCode:n,publiclyDiscoverable:!1},fallbackSlug:e.skillSlug,source:e.source,sourceAccess:e.sourceAccess,flags:e.flags,requestedVisibility:Ti(e.source,e.flags,e.backend,e.sourceAccess),unverifiedMaterialization:e.unverifiedMaterialization})}function uA(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function bU(e,t,n,r){let i=t.details??{},o=f(i,"error")??t.message,a=`skills-layer source connection start --provider ${_U(e)} --source ${e} --visibility private --provenance-intent private_source_import`,l={status:"private_source_access_required",source:e,reasonCode:"private_source_access_required",backendStatus:t.status,backendMessage:o,nextStep:a};return x(l,`Cloud could not ${r} ${e} directly. If this is a private source, start a private source connection first:
|
|
2149
|
+
> `)}catch(u){throw uP(u,n)}let c;try{c=zp(i.currentQuestion.id,l)}catch(u){r=ve(u);continue}try{n=await D(t,`/api/v1/creator/sessions/${encodeURIComponent(String(n.sessionId))}/turn-answers`,{method:"POST",headers:V(t.apiKey),body:JSON.stringify({expectedRevision:n.revision,idempotencyKey:PP("creator-turn",{sessionId:n.sessionId,revision:n.revision,questionId:i.currentQuestion.id,answer:c}),questionId:i.currentQuestion.id,answer:c})}),r=null}catch(u){if(u instanceof Z&&u.status===422){r=ve(u);continue}throw uP(u,n)}}}async function ZB(e,t,n){await Ve(K(t.paths.stateDir,"creator-resume.json"),{version:1,baseUrl:t.baseUrl,sessionId:String(e.sessionId),skillSlug:qa(e,!1)?.skillSlug??null,revision:e.revision,completed:n,savedAt:t.now()})}function uP(e,t){let n=qa(t,!1)?.skillSlug||String(t.sessionId),r=e instanceof Z&&e.status===409?" The server revision is authoritative; reload it before answering again.":"";return new Error(`${ve(e)}${r} Resume with skills-layer creator resume ${n}.`)}function qa(e,t=!0){let n=e.data,r=n&&typeof n=="object"&&!Array.isArray(n)?n.turn:null;if(!r||typeof r!="object"||Array.isArray(r)){if(t)throw new Error("Creator response did not include the canonical interview turn");return null}return r}async function Wie(e,t,n){let r=k(t.skill)??e[0]??"my-skill",i=ZM("creator.init",r,t);if(i)return i;let o=k(t.dir)?Tt(n.cwd,k(t.dir)):K(n.paths.stateDir,"authoring",r),s;try{s=a1(k(t.type))}catch(y){return R(ve(y),t.json)}let a=k(t.category),l=await O1(o),c=await Mk({cwd:n.cwd,files:l.files,explicitIdentifier:k(t.license),explicitLicenseFile:k(t.licenseFile),skip:!!t.skipLicense,interactive:!t.json&&n.stdoutIsTty,prompt:XM(n)}),u=l1({skillSlug:r,description:k(t.description)??`Helps with ${r.replaceAll("-"," ")}.`,skillType:s,category:a,licenseSelection:c.selection}),d=await Jp({targetDir:o,files:u,confirmed:t.confirmed});if(d.status==="confirmation_required"){let y={status:"confirmation_required",reasonCode:"scaffold_overwrite_confirmation_required",targetDir:d.plan.targetDir,changes:d.plan.changes,preservedEntryCount:d.plan.preservedEntryCount,nextAction:"creator.init",nextStep:"Review the reported create/replace diff, then rerun with --confirm only if every replacement is intended."};return x(y,QM(d.plan),t.json,"scaffold_overwrite_confirmation_required")}let p=nt(u),m=Hk(u),h=K(d.plan.targetDir,"SKILL.md"),g=ie({status:d.status,path:h,skillSlug:r,skillType:s,category:a,targetDir:d.plan.targetDir,files:u.map(y=>y.path),fileCount:u.length,licenseStatus:p.license?.status??"unspecified",licenseIdentifier:p.license?.identifier??void 0,licenseSource:c.source,evaluationStatus:m.status,evalReadiness:m,warnings:[...p.issues.filter(y=>y.severity==="warning"),...m.status==="attention_needed"?[{severity:"warning",code:"evaluation_readiness_limited",message:"The scaffold is structurally valid, but its evaluation readiness needs attention before submission."}]:[]],validation:p});return t.json?A(g,`Created ${h}.`,!0,n):{exitCode:0,stdout:Vle(g,d.plan.targetDir,h,n),stderr:""}}function XM(e){return{select:(t,n)=>e.promptSelect(t,n),text:t=>e.promptText(t)}}function QM(e){let t=e.changes.map(n=>`- ${n.action} ${n.path} (${n.previousBytes??0} -> ${n.nextBytes} bytes)`);return[`Creator init target already contains files at ${e.targetDir}.`,...t,"Re-run with --confirm only after reviewing every replacement."].join(`
|
|
2150
|
+
`)}async function pr(e){try{return await FM(e),!0}catch{return!1}}function eU(e){return e.attestRights?{attestRights:!0,rightsBasis:k(e.rightsBasis)??"self_authored",distributionScope:k(e.distributionScope)??"commercial_distribution",rightsDeclarationVersion:zj}:{}}async function AP(e,t,n,r){let i=k(t.visibility);if(i){let P=uc(i);if(!P||!Lu.includes(P))return Nr(r?"creator.submit-version":"creator.submit","visibility",i,Lu,t,"invalid_visibility")}let o=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(o.failure)return o.failure;let s=k(t.spacePack),a=s===void 0?void 0:oc(s);if(a===null)return Nr(r?"creator.submit-version":"creator.submit","spacePack",s,["5","10","20","50"],t,"invalid_private_skill_space_pack","space-pack");let l=k(t.creatorSessionId);if(l){let P=r?T(k(t.skill)??e[0],"creator submit-version with --creator-session-id requires a skill slug."):null,O=r?{creatorSessionId:l,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",...t.dryRun?{dryRun:!0}:{}}:{creatorSessionId:l,...t.dryRun?{dryRun:!0}:{},...a?{privateSkillSpacePack:a}:{}},N=r?`/api/v1/me/submissions/${encodeURIComponent(P)}/versions`:"/api/v1/me/submissions",Q=await D(n,N,{method:"POST",headers:JB(n,t.dryRun?null:{path:N,creatorSessionId:l}),body:JSON.stringify(O)});return YB(Q,t,n)??A(Q,t.dryRun?"Submission preview ready.":Q.status==="submission_incomplete"?`Creator session submission is incomplete. ${f(Q,"nextStep")??"Retry this session submission to complete finalization."}`:"Finalized Creator session submitted.",t.json,n)}let c=r?T(k(t.skill)??e[0],"creator submit-version requires a skill slug."):k(t.skill),u=T(k(t.source)??(r?e[1]:e[0])??t.path,`creator ${r?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),d=await Hu(u,n.cwd);if(t.list)return await Xie(u,d,c,t,n);let p=Oi(r?"creator.submit-version":"creator.submit",t);if(p)return p;if(!d&&!zu(u)&&(vz(u)||/^(?:github|gitlab):/iu.test(u)))return Qie(u,t);let m=d?.files??(await ma({cwd:n.cwd,sourcePath:u,limits:yo})).files;if(!r&&!t.dryRun){let P=await eoe(m,t,n);if(P)return P}if(t.dryRun&&dg(m))return Zie(m,{slug:c,flags:t,backend:n});let h=dg(m)?await xC({baseUrl:n.baseUrl,apiKey:n.apiKey,fetchFn:n.fetchFn,files:m}):null,g=ie({...h?{hydrationManifestId:h.manifestId}:{files:m},version:k(t.version),dryRun:t.dryRun,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",evalSummary:qie(m,{skillSlug:c??tA(m)??"unknown",version:k(t.version)??"0.0.0",generatedAt:n.now()}),replaceUnpublished:r&&t.replaceUnpublished===!0?!0:void 0,priceCents:o.value,privateSkillSpacePack:a,...eU(t),...d?{sourceMetadata:d.sourceMetadata}:{},...Ft(t,["displayName","skillType","category","visibility","source","skill"])}),y=r&&c?`/api/v1/me/submissions/${encodeURIComponent(c)}/versions`:"/api/v1/me/submissions",v=await D(n,y,{method:"POST",headers:JB(n,t.dryRun?null:{path:y,request:g,files:m}),body:JSON.stringify(g)});if(t.json||t.noOpen||v.status!=="checkout_required"||typeof v.checkoutUrl!="string"||typeof v.chargeId!="string")return YB(v,t,n)??A(v,t.dryRun?"Submission preview ready.":r?"Version submitted.":"Submission uploaded.",t.json,n);let b=j(v,"spacePack"),w=b?oc(b.code):null;n.emitInfo(w?`No private skill space is left. Opening checkout for ${Bp(w).label} (${Bp(w).displayPrice}); other packs: --space-pack 5|10|20|50. Complete the payment in your browser, then come back here.`:"Opening payment setup for skill submission. Complete the payment in your browser, then come back here."),await n.openUrl(v.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${v.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let C=await Wae(v.chargeId,n);return fe(C)?C:C.status!=="submitted"?A({...v,chargeStatus:C.status},`Payment is still ${C.status}. You can rerun \`skills-layer creator charge-status ${v.chargeId}\` to continue tracking it.`,t.json,n):A(C,r?"Version submitted.":"Submission uploaded.",t.json,n)}function JB(e,t){let n=V(e.apiKey);if(!t)return n;let{hydrationManifestId:r,files:i,evalSummary:o,...s}=t.request??{},a=t.files?Me("sha256").update(JSON.stringify(t.files.map(c=>[c.path,c.content??null,c.contentBase64??null]))).digest("hex"):null,l=Me("sha256").update(JSON.stringify({path:t.path,creatorSessionId:t.creatorSessionId??null,request:s,bundleDigest:a})).digest("hex");return{...n,"idempotency-key":`cli-submit-${l.slice(0,48)}`}}function YB(e,t,n){if(e.status!=="checkout_required"||typeof e.checkoutUrl!="string"||typeof e.chargeId!="string")return null;let r=`Open ${e.checkoutUrl} to complete payment, then run \`skills-layer creator charge-status ${e.chargeId}\` to confirm the submission.`;return A({...e,paymentRequired:!0,checkoutUrl:e.checkoutUrl,chargeId:e.chargeId,nextAction:"creator.charge-status",nextStep:r},`Payment required to finish: ${r}`,t.json,n)}function Zie(e,t){let n="creator.submit",r=nt(e),i=e.reduce((l,c)=>l+cs(c),0),o=t.slug??tA(e),s=["skill_name_availability","security_review","moderation","pricing_and_checkout","eval_evidence"],a=ie({status:r.valid?"ready":"blocked",reasonCode:r.valid?"local_preview_only":"invalid_bundle",dryRun:!0,previewMode:"local",operation:n,uploaded:!1,skillSlug:o,version:k(t.flags.version),bundle:{fileCount:e.length,totalBytes:i,transport:"source_hydration",artifactDigest:ct(e)},localChecks:[{check:"bundle_size",status:"passed"},{check:"paths",status:"passed"},{check:"secrets",status:"passed"},{check:"manifest",status:r.valid?"passed":"failed"}],serverChecks:{status:"not_run",checks:s},why:"The bundle exceeds the 2 MiB inline request limit, so the dry run previewed it locally and uploaded nothing.",validation:r,nextAction:r.valid?n:"validate",nextStep:r.valid?`Re-run without --dry-run to upload and submit. Server-only checks (${s.join(", ")}) run during the real submit.`:"Fix the bundle issues before submitting again."});return A(a,r.valid?`Local submission preview ready (${e.length} files, ${i} bytes; nothing uploaded). Server-only checks run on the real submit: ${s.join(", ")}.`:"Local submission preview blocked: the bundle does not satisfy the creator validation rules. Nothing was uploaded.",t.flags.json,t.backend)}var Jie="Use `skills-layer creator spaces` or `skills-layer creator spaces buy --pack 5|10|20|50`.";function XB(e){if(e.status==="community_unlimited")return"Community edition supports unlimited private skills.";let t=n=>typeof e[n]=="number"?e[n]:0;return`Private skill spaces: ${t("availablePrivateSkillSpaces")} available of ${t("totalPrivateSkillSpaces")} (${t("activePrivateSkills")} active private skills; free ${t("freePrivateSkillSpacesUsed")} used, ${t("freePrivateSkillSpacesRemaining")} left; purchased ${t("purchasedPrivateSkillSpaces")}, ${t("purchasedPrivateSkillSpacesUsed")} used). Buy more with \`skills-layer creator spaces buy --pack 5|10|20|50\`: ${sc}.`}async function Yie(e,t,n){let r=e[0];if(r===void 0||r==="status"){let u=await D(n,"/api/v1/me/private-skill-spaces",{headers:re(n.apiKey,n.authBlockedMessage)});return A(u,XB(u),t.json,n)}if(r!=="buy")return R(`Unknown creator spaces action "${r}". ${Jie}`,t.json);let i=k(t.pack)??e[1],o=i===void 0?void 0:oc(i);if(o===null)return Nr("creator.spaces.buy","pack",i,["5","10","20","50"],t,"invalid_private_skill_space_pack","pack");let s=await D(n,"/api/v1/me/private-skill-spaces/checkout",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(o?{privateSkillSpacePack:o}:{})});if(s.status!=="checkout_required"||typeof s.checkoutUrl!="string")return A(s,XB(s),t.json,n);let a=Bp(oc(j(s,"spacePack")?.code)??"spaces_5"),l=`Checkout for ${a.label} (${a.displayPrice}) is ready. Complete the payment in your browser, then run \`skills-layer creator spaces\` to see the credited spaces.`;return t.json||t.noOpen?A(s,`${l} Checkout URL: ${s.checkoutUrl}`,t.json,n):(await n.openUrl(s.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${s.checkoutUrl}`),A(s,l,t.json,n))}async function Xie(e,t,n,r,i){if(t)return A(QB(aA(e,t,n)),"Source skills loaded.",r.json,i);let o=await kU(i,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},r);return o.kind==="failure"?o.result:A(QB(o.inspection),"Source skills loaded.",r.json,i)}function QB(e){return{...e,sourceSubmissionSupported:!0}}function Qie(e,t){let r=`skills-layer source connection start --provider ${_U(e)} --source ${e} --visibility private --provenance-intent private_source_import`;return x({status:"source_connection_required",reasonCode:"source_connection_required",source:e,nextAction:"source.connection.start",nextStep:r},`Creator submit can list ${e} safely, but publishing from a remote source requires a source connection. Run \`${r}\`.`,t.json,"source_connection_required")}async function eoe(e,t,n){let r=k(t.skill)??tA(e);if(!r)return null;let i;try{i=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(r)}`,{headers:re(n.apiKey,n.authBlockedMessage)})}catch(o){if(o instanceof Z&&o.status===404)return tU(r,t);throw o}if(i.available===!1||f(i,"reasonCode")==="unavailable"||f(i,"reasonCode")==="reserved"){let o=f(i,"assignedSlug"),s=ie({status:"duplicate_candidate",reasonCode:f(i,"reasonCode")??"slug_unavailable",requestedSlug:r,assignedSlug:o,nextAction:"creator.status",nextStep:`Run \`skills-layer creator status ${r}\`, \`skills-layer creator submissions\`, or submit a new version of the existing skill instead of creating a duplicate listing.`});return x(s,`A public skill slug "${r}" already exists or is not available. Run \`skills-layer creator status ${r}\`, check your creator submissions, or submit a new version instead of creating a duplicate listing.`,t.json,f(s,"reasonCode"))}return null}async function toe(e,t,n){try{let r=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return A(noe(r),"Slug status loaded.",t.json,n)}catch(r){if(r instanceof Z&&r.status===404)return tU(e,t);throw r}}function tU(e,t){let n={status:"slug_check_unavailable",reasonCode:"slug_check_route_unavailable",requestedSlug:e,nextAction:"creator.status",nextStep:`Slug availability could not be checked on the selected backend. Run \`skills-layer creator submissions\`, \`skills-layer creator status ${e}\`, or retry after selecting a compatible Skills Layer backend.`};return x(n,`Slug availability could not be checked for ${e} on the selected backend. Run \`skills-layer creator submissions\` or retry after selecting a compatible Skills Layer backend.`,t.json,"slug_check_route_unavailable")}function noe(e){let t=e.available===!0,n=f(e,"assignedSlug");if(t)return ie({requestedSlug:f(e,"requestedSlug"),available:!0,reasonCode:f(e,"reasonCode")??"available",assignedSlug:n});let r=j(e,"slugAssignment"),i=Array.isArray(r?.candidateSlugs)?r.candidateSlugs.filter(o=>typeof o=="string").slice(0,3):void 0;return ie({...e,...r?{slugAssignment:{...r,...i?{candidateSlugs:i}:{}}}:{},...i?{candidateSlugs:i}:{}})}function roe(e,t){return x({status:"not_submitted",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submit",nextStep:"Run `skills-layer creator submit <path> --dry-run` to validate a local skill before submitting it, or run `skills-layer creator submissions` to see your existing submissions."},`No creator submission was found for ${e}. Run \`skills-layer creator submit <path> --dry-run\` before checking status.`,t.json,"creator_submission_not_found")}function tA(e){let t=e.find(r=>r.path.split("/").pop()?.toLowerCase()==="skill.md");if(!t)return;let n=/^---\s*\n(?<body>[\s\S]*?)\n---/u.exec(t.content??"")?.groups?.body?.split(/\r?\n/u).map(r=>r.match(/^name\s*:\s*(?<name>.+?)\s*$/u)?.groups?.name?.trim().replace(/^["']|["']$/gu,"")).find(r=>!!r);return ioe(n??ot(Be(t.path)))}function ioe(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function ooe(e,t,n){let r=T(e[1],"creator pricing requires a skill slug."),i=Oi("creator.pricing",t);if(i)return i;let o=new URLSearchParams;if(Ke(o,"version",t.version),!t.priceCents)return await me(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(s.failure)return s.failure;let a=s.value??0;if(t.dryRun){o.set("dryRun","true"),o.set("priceCents",String(a));let d=await D(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return d.dryRun!==!0||d.status!=="preview"?R("This backend does not support read-only pricing previews. Upgrade the backend before retrying.",t.json):A(d,"Pricing preview; the live price is unchanged.",t.json,n)}let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,{headers:re(n.apiKey,n.authBlockedMessage)}),c=J(l,"priceCents")??0,u=J(l,"revision");if(!u||!Number.isSafeInteger(u)||u<1)return R("Pricing authority did not return a valid revision.",t.json);if(a>c&&!t.confirmed){let d=ie({status:"pending_approval",reasonCode:"price_increase_confirmation_required",skillSlug:r,version:f(l,"version"),currentPriceCents:c,requestedPriceCents:a,currency:f(l,"currency")??"usd",nextStep:"Review the old and new USD prices, then rerun with --yes."});return A(d,"Pricing change requires explicit confirmation.",t.json,n)}return await Li(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing`,{priceCents:a,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),expectedRevision:u,idempotencyKey:k(t.idempotencyKey)?.trim()||`pricing-${Ge(12).toString("hex")}`,reason:"Creator changed the version list price through CLI.",...eU(t)},t,n,"Pricing updated.")}async function soe(e,t,n){let r=Mn("creator.update-listing","listingStatus",t.listingStatus,fie,t,"invalid_listing_status","listing-status");if(r)return r;try{return await Li(`/api/v1/me/submissions/${encodeURIComponent(e)}`,Ft(t,["displayName","summary","description","category","skillType","license","listingStatus"]),t,n,"Listing updated.")}catch(i){if(i instanceof Z&&i.status===404){let o={status:"listing_not_found_or_not_editable",reasonCode:"creator_listing_not_found_or_not_owned",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see editable listings, or \`skills-layer show ${e}\` to inspect the public catalog entry.`};return x(o,`No editable creator listing was found for ${e}. Run \`skills-layer creator submissions\` to see listings you can update.`,t.json,"creator_listing_not_found_or_not_owned")}throw i}}async function aoe(e,t,n,r){let i=T(t[1],`creator ${e} requires a skill slug.`);if(e==="claim"){let o=Mn("creator.claim","requestedRole",n.requestedRole,pie,n,"invalid_requested_role","requested-role");if(o)return o}try{if(e==="claim")return await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/claim`,Ft(n,["requestedRole","message"]),n,r,"Ownership claim submitted.");if(e==="verify"){let o=T(n.claimId,"creator verify requires --claim-id.");return await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/verify`,{claimId:o},n,r,"Ownership claim verified.")}return T(n.message,"creator dispute requires --message."),await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/dispute`,Ft(n,["message"]),n,r,"Ownership dispute submitted.")}catch(o){if(o instanceof Z&&o.status===404){let s={status:"ownership_action_unavailable",reasonCode:e==="claim"?"skill_not_found_or_not_claimable":"ownership_claim_not_found",skillSlug:i,requestedRole:k(n.requestedRole),nextAction:e==="claim"?"search":"creator.claim",nextStep:e==="claim"?`Run \`skills-layer search ${i}\`, \`skills-layer show ${i}\`, or submit/source-install the skill before claiming it.`:`Run \`skills-layer creator claim ${i}\` to start a new claim if the skill is claimable.`};return x(s,e==="claim"?`No claimable skill was found for ${i}. Search or show the skill first, then claim it only when it exists and is claimable.`:`No matching ownership claim was found for ${i}. Start a new claim if the skill is claimable.`,n.json,f(s,"reasonCode")??"ownership_action_unavailable")}throw o}}async function loe(e,t,n){try{return await me(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(r){if(r instanceof Z&&r.status===404){let i={status:"no_creator_submission",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see skills you own, \`skills-layer show ${e}\` to inspect the catalog listing, or \`skills-layer creator claim ${e}\` if it is a claimable public-source skill.`};return x(i,`No creator-owned analytics submission was found for ${e}. Run \`skills-layer creator submissions\`, \`skills-layer show ${e}\`, or \`skills-layer creator claim ${e}\` if you should manage it.`,t.json,"creator_submission_not_found")}throw r}}async function coe(e,t){let n=await D(t,"/api/v1/me/payout-profile",{headers:re(t.apiKey,t.authBlockedMessage)});return A(n,"Creator payout profile loaded.",e.json,t)}async function eM(e,t){let n=uoe(k(e.mode));if(e.mode&&n===null)return R("creator payout-link --mode must be account_onboarding|account_update|onboarding|update.",e.json);let r;try{r=await D(t,"/api/v1/me/payout-profile/link",{method:"POST",headers:V(t.apiKey),body:JSON.stringify(ie({...n?{mode:n}:{},country:k(e.country)}))})}catch(o){if(o instanceof Z&&poe(o))return x({status:"payout_setup_already_submitted",reasonCode:"payout_update_link_unavailable",nextAction:"creator.payout-profile",nextStep:"Run `skills-layer creator payout-profile` to confirm readiness, then use `skills-layer creator earnings` or `skills-layer creator withdraw --amount-cents <amount>`."},"Payout setup is already submitted for this account. Run `skills-layer creator payout-profile` to confirm readiness before requesting a withdrawal.",e.json,"payout_update_link_unavailable");throw o}let i=Zae(r);return i&&doe(e)&&e.showUrl!==!0&&(t.emitInfo("Opening payout setup in your browser. Finish the flow there, then come back here."),await t.openUrl(i)||t.emitInfo(`Open this payout setup URL manually to continue: ${i}`)),A(r,"Payout setup link created.",e.json,t)}function uoe(e){if(!e)return null;let t=e.trim().toLowerCase();return t==="account_onboarding"||t==="onboarding"?"account_onboarding":t==="account_update"||t==="update"?"account_update":null}function doe(e){return!e.json&&!e.noOpen}function poe(e){let t=`${e.message} ${f(e.details??{},"error")??""}`.toLowerCase();return t.includes("account_update")&&t.includes("account_onboarding")&&t.includes("account link")}async function foe(e,t,n,r){let i=T(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await me(`/api/v1/me/skills/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await me(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews`,n,r,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let l=T(n.issueId,"creator update-issue requires --issue-id."),c=T(n.status,"creator update-issue requires --status."),u=Mn("creator.update-issue","status",c,mie,n,"invalid_issue_status");if(u)return u;let d=Oi("creator.update-issue",{...n,version:n.fixedVersion});if(d)return d;try{return await Li(`/api/v1/me/skills/${encodeURIComponent(i)}/issues/${encodeURIComponent(l)}`,Ft(n,["status","fixedVersion","note"]),n,r,"Issue updated.")}catch(p){if(p instanceof Z&&p.status===404)return moe(i,l,n);throw p}}let o=T(n.reviewId,"creator moderate-review requires --review-id."),s=T(n.status,"creator moderate-review requires --status."),a=Mn("creator.moderate-review","status",s,gie,n,"invalid_review_status");if(a)return a;try{return await Oe(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews/${encodeURIComponent(o)}/moderate`,Ft(n,["status","reason"]),n,r,"Review updated.")}catch(l){if(l instanceof Z&&l.status===404)return goe(i,o,n);throw l}}function moe(e,t,n){return x({status:"not_found",reasonCode:"issue_not_found",skillSlug:e,issueId:t,nextAction:"creator.issues",nextStep:`Run \`skills-layer creator issues ${e}\` to inspect open issues before updating one.`},`Issue ${t} was not found for ${e}. Run \`skills-layer creator issues ${e}\` first.`,n.json,"issue_not_found")}function goe(e,t,n){return x({status:"not_found",reasonCode:"review_not_found",skillSlug:e,reviewId:t,nextAction:"creator.reviews",nextStep:`Run \`skills-layer creator reviews ${e}\` to inspect review ids before moderating one.`},`Review ${t} was not found for ${e}. Run \`skills-layer creator reviews ${e}\` first.`,n.json,"review_not_found")}async function hoe(e,t,n){let r=e[0],i=T(e[1],`creator source ${r??""} requires a source connection id.`),o=k(t.skill)??e[2];if(r==="prepare"){let s=Oi("creator.source.prepare",t);if(s)return s;let a=Mn("creator.source.prepare","visibility",t.visibility,za,t,"invalid_visibility");if(a)return a;let l=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=k(t.source)??e[2],u=c?await Hu(c,n.cwd):void 0;return await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/prepare`,ie({...Ft(t,["skill","source","version","displayName","skillType","category","visibility"]),...l.value!==void 0?{priceCents:l.value}:{},source:c,...u?{files:u.files}:{}}),t,n,"Source release prepared.")}if(r==="publish-request"){let s=Oi("creator.source.publish-request",t);if(s)return s;let a=Mn("creator.source.publish-request","visibility",t.visibility,za,t,"invalid_visibility");if(a)return a;let l=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=t.approvalRequestId.length>0?t.approvalRequestId:k(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/publish-request`,ie({skillSlug:o,approvalRequestIds:c,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),...Ft(t,["visibility","license","discloseSource"]),...l.value!==void 0?{priceCents:l.value}:{}}),t,n,"Source publish requested.")}if(r==="release-status"){let s=new URLSearchParams;return o&&s.set("skill",o),await me(`/api/v1/me/source-connections/${encodeURIComponent(i)}/release-status${Qe(s)}`,t,n,"Source release status loaded.",{authenticated:!0})}return R(`Unknown creator source command "${r??""}".`,t.json)}function RP(e){return!e.list&&!e.dryRun}async function tM(e){if(!RP(e.flags)||k(e.flags.visibility)==="private"||k(e.flags.scope)==="workspace")return null;if(e.flags.all&&Array.isArray(e.inspection.catalogueDecisions)){let p=[];for(let m of ur(e.inspection)){let h=await Wa([],{...e.flags,all:!1,json:!0,source:f(e.inspection,"catalogueSourceInput")??e.source,skill:m.value},e.backend);if(h.exitCode!==0){let g=JSON.parse(h.stderr||h.stdout);return x({status:"source_install_batch_partial",reasonCode:g.reasonCode??"source_install_child_failed",failedSkill:m.value,results:p,failure:g.data},"Source installation stopped; earlier results are retained.",e.flags.json,g.reasonCode??"source_install_child_failed")}p.push(JSON.parse(h.stdout).data)}return A({status:"source_install_batch",results:p},"Source installation results loaded.",e.flags.json,e.backend)}let t=j(e.inspection,"catalogueMatch");if(!t&&e.selectedSkillSlug&&typeof e.inspection.catalogueSourceInput=="string"){let p=await jP(e.backend,e.source,{source:e.inspection.catalogueSourceInput,skillSlug:e.selectedSkillSlug,preferCatalogue:!0,listOnly:!0},e.flags);if(p.kind==="failure")return p.result;t=j(p.inspection,"catalogueMatch"),t&&(e.inspection=p.inspection)}if(!t)return null;let n=rr(e.source),r=f(t,"skillSlug"),i=f(t,"version"),o=f(t,"generationId"),s=n.kind==="github"?n.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,l=(Array.isArray(e.inspection.results)?e.inspection.results:[]).find(p=>L(p)&&p.skillSlug===e.selectedSkillSlug),c=L(l)?f(l,"relativeSkillRoot"):void 0,u=c&&s&&c!=="."?s==="."||c===s||c.startsWith(`${s}/`)?c:`${s}/${c}`:void 0,d=typeof t.sourceRoot=="string"&&(t.sourceRoot==="."||!t.sourceRoot.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)));return n.kind!=="github"||t.schemaVersion!=="skills-layer.source-catalogue-match.v1"||typeof t.repository!="string"||t.repository.toLowerCase()!==`${n.owner}/${n.repo}`.toLowerCase()||!d||t.sourceRoot!==s&&t.sourceRoot!==u||typeof t.commitSha!="string"||!/^[a-f0-9]{40}$/u.test(t.commitSha)||/^[a-f0-9]{40}$/iu.test(n.ref)&&n.ref.toLowerCase()!==t.commitSha||!r||!/^[a-z0-9][a-z0-9-]{0,255}$/u.test(r)||!i||!o||e.selectedSkillSlug&&e.selectedSkillSlug!==t.requestedSkillSlug?x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e.source,nextStep:"Retry after the exact source-to-catalogue identity is refreshed. No raw-source fallback was activated."},"The catalogue match did not identify this exact GitHub skill and revision.",e.flags.json,"source_catalogue_identity_invalid"):Wa([r],{...e.flags,source:void 0,skill:void 0,version:i},e.backend,{...nU,expectedSourceGeneration:{generationId:o,version:i}})}var nU={origin:"direct",fallbackPolicy:"eligible_public"};function yoe(e){return{origin:"update_existing",fallbackPolicy:f(e??{},"acquisitionMode")==="authenticated_account"?"account_required":"eligible_public"}}async function Wa(e,t,n,r=nU){if(e[0]==="status"&&e[1])return me(`/api/v1/install-receipts/${encodeURIComponent(e[1])}`,t,n,"Install progress loaded.",{authenticated:!!n.apiKey});let i=YM("install",t);if(i)return i;if(t.localOnly&&(t.visibility!==void 0||k(t.scope)==="workspace"||n.config?.workingModeType==="enterprise_workspace"))return x({status:"local_only_intent_conflict",reasonCode:"local_only_intent_conflict"},"Local-only installation requires a personal local target and cannot request platform visibility or workspace authority.",t.json,"local_only_intent_conflict");let o=k(t.source);if(o){let h=k(t.skill),g=sM(o,h,t);if(g)return g;let y=await Hu(o,n.cwd);if(y)return await rM(o,y,h,t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let v=aM(o,t);if(v)return v;let b=t.list||t.dryRun||!h&&!t.all,w=await jP(n,o,{source:o,skillSlug:h,listOnly:b,...t.all?{all:!0}:{},preferCatalogue:RP(t),visibility:k(t.visibility)},t);if(w.kind==="failure")return w.result;let _=w.inspection;if(t.list)return A(_,"Source skills loaded.",t.json,n);let C=Ih(o,_,t);if(C)return C;let P=await ju({source:o,inspection:_,requestedSkillSlug:h,mode:"install",flags:t,backend:n});if(P.kind==="failure")return P.result;if(t.dryRun)return A(LP(o,_,P.skillSlug,t),"Source install preview ready.",t.json,n);let O=t.all?ur(_).map(X=>X.value):[P.skillSlug??ur(_)[0]?.value??ot(o)],N=await tM({inspection:_,source:o,selectedSkillSlug:P.skillSlug,flags:t,backend:n});if(N)return N;let Q=await NB(n,O,t);if(Q)return Q;let G=f(_,"catalogueSourceInput")??o,ee=await iM({backend:n,flags:t,source:G,skillSlug:P.skillSlug,defaultAcceptUnverifiedSource:Ti(o,t,n,w.sourceAccess)==="public"});if(fe(ee))return ee;let te;try{te=await cM({source:G,skillSlug:P.skillSlug,flags:t,backend:n,sourceAccess:w.sourceAccess})}catch(X){if(ee)return await pM({backend:n,flags:t,source:G,sourceAccess:w.sourceAccess,skillSlug:P.skillSlug??O[0],unverifiedMaterialization:ee,error:X});if(X instanceof Z)return dM(o,X,t);throw X}return await Uu({backend:n,result:te,fallbackSlug:P.skillSlug??f(te,"skillSlug")??o,source:G,sourceAccess:w.sourceAccess,flags:t,requestedVisibility:Ti(o,t,n,w.sourceAccess),...ee?{unverifiedMaterialization:ee}:{}})}let s=T(e[0]??t.install,"install requires a skill slug or --source.");if(vz(s)){let h=sM(s,k(t.skill),t);if(h)return h;let g=await Hu(s,n.cwd);if(g)return await rM(s,g,k(t.skill),t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let y=aM(s,t);if(y)return y;let v=k(t.skill),b,w="unknown",_=async X=>{if(b)return null;let Ce=await jP(n,s,{source:s,skillSlug:v,listOnly:X,...t.all?{all:!0}:{},preferCatalogue:RP(t),visibility:k(t.visibility)},t);return Ce.kind==="failure"?Ce.result:(b=Ce.inspection,w=Ce.sourceAccess,null)};if(t.list){let X=await _(!0);return X||A(b,"Source skills loaded.",t.json,n)}if(!v&&!t.all){let X=await _(!0);if(X)return X;let Ce=b,pn=Ih(s,Ce,t);if(pn)return pn;let Qa=await ju({source:s,inspection:Ce,requestedSkillSlug:v,mode:"install",flags:t,backend:n});if(Qa.kind==="failure")return Qa.result;v=Qa.skillSlug}if(t.dryRun){let X=await _(!0);if(X)return X;let Ce=b,pn=await ju({source:s,inspection:Ce,requestedSkillSlug:v,mode:"install",flags:t,backend:n});return pn.kind==="failure"?pn.result:(v=pn.skillSlug,A(LP(s,Ce,v,t),"Source install preview ready.",t.json,n))}let C=await _(!1);if(C)return C;let P=b,O=t.all?ur(P).map(X=>X.value):[v??ur(P)[0]?.value??ot(s)],N=await tM({inspection:P,source:s,selectedSkillSlug:v,flags:t,backend:n});if(N)return N;let Q=await NB(n,O,t);if(Q)return Q;let G=f(P,"catalogueSourceInput")??s,ee=await iM({backend:n,flags:t,source:G,skillSlug:v,defaultAcceptUnverifiedSource:Ti(s,t,n,w)==="public"});if(fe(ee))return ee;let te;try{te=await cM({source:G,skillSlug:v,flags:t,backend:n,sourceAccess:w})}catch(X){if(ee)return await pM({backend:n,flags:t,source:G,sourceAccess:w,skillSlug:v??O[0],unverifiedMaterialization:ee,error:X});if(X instanceof Z)return dM(s,X,t);throw X}return await Uu({backend:n,result:te,fallbackSlug:v??f(te,"skillSlug")??ot(s),source:G,sourceAccess:w,flags:t,requestedVisibility:Ti(s,t,n,w),...ee?{unverifiedMaterialization:ee}:{}})}if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");if(k(t.scope)==="workspace"){let h=T(t.workspace,"workspace installs require --workspace <workspace-id>."),g=await rU(n,`/api/v1/workspaces/${encodeURIComponent(h)}/skills/${encodeURIComponent(s)}/approve`,{dryRun:t.dryRun},t);return fe(g)?g:t.dryRun?await Woe(g,"Workspace approval preview ready.",t,n):A(g,"Workspace approval requested.",t.json,n)}if(!n.apiKey&&r.fallbackPolicy==="eligible_public")return await dP({target:s,flags:t,backend:n,catalogContext:r});if(!t.dryRun){let h;try{h=await QP(n,s,t)}catch(g){if(EP(r,g))return await dP({target:s,flags:t,backend:n,catalogContext:r});throw g}if(h)return h}let a=await oU(s,t,n);if("result"in a)return a.result;let l=a.flags,c=ie({skillSlug:s,version:k(l.version),scope:k(l.scope),agent:k(l.agent),dryRun:t.dryRun}),u;try{u=await nA(n,c,t)}catch(h){if(EP(r,h))return await dP({target:s,flags:t,backend:n,catalogContext:r,effectiveFlags:l});throw h}if(fe(u))return u;let d=u;if(d.status==="purchase_required")return PU(d,s,t,n);if(await ji(n,d),t.dryRun)return await SU(d,l,n);let p=await rA(n,d,s,l,{expectedSourceGeneration:r.expectedSourceGeneration});if(fe(p))return p;let m=await sA(n,{...p,acquisitionMode:"authenticated_account",acquisitionOrigin:r.origin},s,l);return await Ha(n,m,s),Va(m,Array.isArray(m.materializedWrites)&&m.materializedWrites.length>0?"Skill installed.":l.agent?"Recorded; choose --scope project|global to install files.":"Recorded; no agent selected \u2014 rerun with --agent <id> to write the skill files.",t.json,n)}async function dP(e){let t=e.backend.apiKey?{...e.backend,apiKey:void 0,authBlockedMessage:void 0}:e.backend,n=e.effectiveFlags;if(!n){let o=await oU(e.target,e.flags,e.backend);if("result"in o)return o.result;n=o.flags}let r=k(n.version),i={status:"anonymous_public",skillSlug:e.target,...r?{version:r}:{},scope:k(n.scope),agent:k(n.agent),acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin};if(e.flags.dryRun)try{let o=await bh(t,i,e.target,r,{exportMode:"public"});return await SU({...i,...Sh(o)},e.flags,t)}catch(o){if(o instanceof Z)return Go(o,e.flags.json);throw o}try{let o=await rA(t,i,e.target,n,{exportMode:"public",expectedSourceGeneration:e.catalogContext.expectedSourceGeneration});if(fe(o))return o;let s=await sA(t,{...o,acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin},e.target,n);return await Ha(t,s,e.target),Va(s,"Public skill installed locally without an account.",e.flags.json,t)}catch(o){if(o instanceof Z)return Go(o,e.flags.json);throw o}}function EP(e,t){return e.fallbackPolicy==="eligible_public"&&t instanceof Z&&t.status===401&&f(t.details??{},"reasonCode")==="api_key_invalid_or_expired"}async function rU(e,t,n,r){let i=o=>D(e,t,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(n)}catch(o){let s=iU(o);if(!s)throw o;return r.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before workspace approval. Interactive acknowledgement is unavailable in this mode.",r.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}).`),await e.promptSelect("Approve this exact warned generation for the workspace?",[{value:"cancel",label:"Cancel approval",description:"Do not approve or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind approval to this warning revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Workspace approval cancelled without granting value.",r.json,"distribution_warning_declined"):i({...n,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}async function nA(e,t,n,r="/api/v1/install"){let i=o=>D(e,r,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(t)}catch(o){let s=iU(o);if(!s)throw o;return n.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before install. Interactive acknowledgement is unavailable in this mode.",n.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}). Next action: ${s.posture.nextAction}.`),await e.promptSelect("Continue with this exact warned skill generation?",[{value:"cancel",label:"Cancel install",description:"Do not grant or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind consent to this warning and authority revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Install cancelled without granting value.",n.json,"distribution_warning_declined"):await i({...t,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}function iU(e){if(!(e instanceof Z)||e.status!==409||!e.details)return null;let t=L(e.details.data)?e.details.data:e.details,n=L(t.distributionPosture)?t.distributionPosture:null,r=n?.contractVersion,i=n?.warningDigest,o=n?.authorityRevision;return!n||r!=="skills-layer.distribution.v1"||typeof i!="string"||!/^sha256:[a-f0-9]{64}$/u.test(i)||typeof o!="number"||!Number.isSafeInteger(o)||o<1?null:{reasonCode:typeof t.reasonCode=="string"?t.reasonCode:"warning_acknowledgement_required",posture:{contractVersion:r,warningDigest:i,authorityRevision:o,effectiveDistributionStatus:typeof n.effectiveDistributionStatus=="string"?n.effectiveDistributionStatus:"published_with_warning",reasonCode:typeof n.reasonCode=="string"?n.reasonCode:"guardian_incident_warning",nextAction:typeof n.nextAction=="string"?n.nextAction:"review_warning_before_install"}}}async function oU(e,t,n){let r=k(t.scope),i=k(t.agent);if(t.json||t.dryRun||!n.stdoutIsTty||r==="workspace"||r==="local"||r!==void 0&&i!==void 0)return{flags:t};let o=et(n.env,n.platform,n.cwd),s=voe(n),a=await koe(n.paths.installTargetPreferencePath),l=a?.workingModeId===s,c=l&&a?.agent?o.find(w=>w.id===a.agent):void 0,u=c&&a?.scope?a.scope==="global"?c.targets.globalSkillsPath:c.targets.projectSkillsPath:void 0;if(i===void 0&&r===void 0&&a?.policy==="recheck_every_5"&&l&&c!==void 0&&(a.scope==="project"||a.scope==="global")&&u!==void 0&&a.usesSinceConfirmation>0&&a.usesSinceConfirmation<4)return await Ve(n.paths.installTargetPreferencePath,{...a,usesSinceConfirmation:a.usesSinceConfirmation+1,savedAt:n.now()}),{flags:{...t,agent:c.id,scope:a.scope}};let p=await VA({env:n.env,platform:n.platform,cwd:n.cwd,pathExists:pr}),m=p.filter(w=>w.detectionSources.includes("project")),h=i??Re(n.env.SKILLS_LAYER_AGENT),g=h?o.find(w=>w.id===h):void 0;if(h&&!g)return{result:R(`Unsupported agent "${h}". Run \`skills-layer agents list\` to choose a supported install target.`,t.json)};if(!g&&m.length===1&&(g=m[0]),!g){let w=Re(n.config?.lastSelectedAgent);g=w?p.find(_=>_.id===w)??o.find(_=>_.id===w):void 0}if(!g&&p.length===1&&(g=p[0]),!g&&p.length>1){let w=await n.promptSelect("Multiple supported agents were detected. Select one to install for:",p.map(_=>({value:_.id,label:`${_.displayName} (${_.detectionSources.join(", ")})`})));g=p.find(_=>_.id===w)}if(!g)return{result:R("No supported local agent was detected. Run `skills-layer agents list`, then retry with --agent <agent> and --scope <project|global>.",t.json)};let y=r;if(!y){let w=[{value:"project",label:"Project (this folder)"}];g.targets.globalSkillsPath&&w.push({value:"global",label:"Global (all projects)"}),y=w.length===1?w[0].value:await n.promptSelect(`Install ${e} for ${g.displayName} where?`,w)}let v=i!==void 0||r!==void 0,b=a?.policy==="ask_every_time"&&l;if(!v&&!b&&(y==="project"||y==="global")){let w=y==="project"?"Project":"Global",C=await n.promptSelect(`Remember ${g.displayName} / ${w} for future installs?`,[{value:"recheck_every_5",label:"Yes - recheck on every 5th install"},{value:"ask_every_time",label:"No - ask every time"}])==="recheck_every_5"?{version:1,policy:"recheck_every_5",agent:g.id,scope:y,usesSinceConfirmation:1,workingModeId:s,savedAt:n.now()}:{version:1,policy:"ask_every_time",usesSinceConfirmation:0,workingModeId:s,savedAt:n.now()};await Ve(n.paths.installTargetPreferencePath,C)}return{flags:{...t,agent:g.id,scope:y}}}function voe(e){return e.apiKey?Re(e.config?.workingModeId)??"personal":"anonymous"}async function koe(e){let t=await ke(e);return!L(t)||t.version!==1||t.policy!=="recheck_every_5"&&t.policy!=="ask_every_time"||typeof t.workingModeId!="string"||typeof t.savedAt!="string"||typeof t.usesSinceConfirmation!="number"||!Number.isInteger(t.usesSinceConfirmation)||t.usesSinceConfirmation<0||t.agent!==void 0&&typeof t.agent!="string"||t.scope!==void 0&&t.scope!=="project"&&t.scope!=="global"?null:t}async function rA(e,t,n,r,i={}){if(k(r.agent)==="all")return await woe(e,t,n,r,i);let o=iA(e,t,n,r);if(o.status==="skip")return t;if(o.status==="cache_only"){let h=await bh(e,t,o.skillSlug,o.version,i),g=await xh({backend:e,exportResult:h,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(g))return g;let v=(e.platform==="win32"?st:Lt).join(e.paths.bundlesDir,o.skillSlug,g.envelope.generation.semanticVersion,encodeURIComponent(g.envelope.generation.generationId),"bundle.zip");return await IA(v,g.bytes),{...t,...Sh(h),version:g.envelope.generation.semanticVersion,scope:"local",archiveSha256:g.archiveSha256,archiveHashFormat:g.archiveHashFormat,manifestSha256:g.envelope.manifest.sha256,generationId:g.envelope.generation.generationId,sourceContentDigest:ct(g.files),verificationStatus:"verified",cachedArtifact:{state:"verified",bundlePath:v,generation:g.envelope.generation,archiveSha256:g.archiveSha256,manifestSha256:g.envelope.manifest.sha256,savedAt:e.now()}}}if(o.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:o.skillSlug,nextStep:o.nextStep},o.message,r.json,"materialization_target_invalid");let s=await Ya({backend:e,skillSlug:o.skillSlug,agentId:o.agent.id,scope:o.scope,flags:r});if(s)return s;let a=await bh(e,t,o.skillSlug,o.version,i),l=await xh({backend:e,exportResult:a,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(l))return l;let c=(await lt(e)).installs[o.skillSlug],u=qn(c,{scope:o.scope,installedPath:(e.platform==="win32"?st:Lt).join(o.skillsPath,Mr(o.skillSlug)),platform:e.platform})[0]?.record,d=u?f(u,"sourceContentDigest"):void 0,p=ct(l.files);if(u?.verificationStatus==="unverified"&&!r.replaceUnverifiedSource&&(await Dr({targetDir:(e.platform==="win32"?st:Lt).join(o.skillsPath,Mr(o.skillSlug)),generation:l.envelope.generation,archiveSha256:l.archiveSha256,manifestSha256:l.envelope.manifest.sha256,files:l.envelope.manifest.files})).status!=="verified")return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:o.skillSlug,installedArchiveSha256:u.archiveSha256,approvedArchiveSha256:l.archiveSha256,installedContentDigest:d,approvedContentDigest:p,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and retry with --replace-unverified-source to replace them with the approved catalogue generation."},"The approved catalogue artifact differs from the installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let m=await oA({backend:e,skillSlug:o.skillSlug,scope:o.scope,agent:o.agent,skillsPath:o.skillsPath,bytes:l.bytes,files:l.files,envelope:l.envelope,approval:l.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});return{...t,...Sh(a),archiveSha256:l.archiveSha256,archiveHashFormat:l.archiveHashFormat,scope:o.scope,agent:o.agent.id,targetAgent:o.agent.id,materializationPlan:{scope:o.scope,agent:o.agent.id},...Mu(e),...m,...m.guardianActivationReceipt?{warnings:[...Fe(t,"warnings")??[],...Fe(m,"warnings")??[]]}:{}}}async function woe(e,t,n,r,i){let o=j(t,"materializationPlan")??j(t,"installPlan"),s=k(r.scope)??f(t,"scope")??(o?f(o,"scope"):void 0),a=f(t,"skillSlug")??f(t,"slug")??n;if(s!=="project"&&s!=="global")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Use --agent all with --scope project or --scope global."},"Installing for all compatible agents requires project or global scope.",r.json,"materialization_target_invalid");let l=et(e.env,e.platform,e.cwd),c=new Map;for(let w of l){let _=s==="global"?w.targets.globalSkillsPath:w.targets.projectSkillsPath;if(!_)continue;let C=Bo(_,e.platform),P=c.get(C);P?P.agents.push(w):c.set(C,{agent:w,agents:[w],skillsPath:_})}if(c.size===0)return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Run `skills-layer agents list` and select a supported target with an available path."},`No supported agent exposes a ${s} skill path on this machine.`,r.json,"materialization_target_invalid");for(let w of c.values())for(let _ of w.agents){let C=await Ya({backend:e,skillSlug:a,agentId:_.id,scope:s,flags:r});if(C)return C}let u=f(t,"version")??f(t,"currentVersion"),d=await bh(e,t,a,u,i),p=await xh({backend:e,exportResult:d,flags:r,skillSlug:a,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(p))return p;let m=ct(p.files),h=(await lt(e)).installs[a],g;if(!r.replaceUnverifiedSource)for(let w of c.values()){let _=(e.platform==="win32"?st:Lt).join(w.skillsPath,Mr(a)),C=qn(h,{scope:s,installedPath:_,platform:e.platform})[0];if(C?.record.verificationStatus==="unverified"&&(await Dr({targetDir:_,generation:p.envelope.generation,archiveSha256:p.archiveSha256,manifestSha256:p.envelope.manifest.sha256,files:p.envelope.manifest.files})).status!=="verified"){g=C;break}}if(g)return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:a,materializationId:g.materializationId,installedContentDigest:f(g.record,"sourceContentDigest"),approvedContentDigest:m,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and use --replace-unverified-source to replace the unverified generation."},"The approved catalogue artifact differs from an installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let y=[];for(let w of c.values()){let _=await oA({backend:e,skillSlug:a,scope:s,agent:w.agent,skillsPath:w.skillsPath,bytes:p.bytes,files:p.files,envelope:p.envelope,approval:p.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});y.push({...t,scope:s,agent:w.agent.id,targetAgent:w.agent.id,...Mu(e),..._})}let v=y[0],b=v[Ch];return{...t,...Sh(d),archiveSha256:p.archiveSha256,archiveHashFormat:p.archiveHashFormat,scope:s,agent:"all",targetAgents:l.map(w=>w.id),materializationPlan:{scope:s,agent:"all",physicalTargetCount:y.length,agentCount:l.length},materializationResults:y,materializedWrites:y.flatMap(w=>Array.isArray(w.materializedWrites)?w.materializedWrites:[]),materializedSkillRoot:f(v,"materializedSkillRoot"),...Mu(e),...lU(b)?{[Ch]:b}:{}}}async function Ya(e){let t=e.backend.config?.workingModeType==="enterprise_workspace",n=e.enforceRequired?"enforce":await rd(e.backend,e.skillSlug);if(!t&&n!=="enforce"&&n!=="enabled")return null;let r=Re(e.backend.config?.workingModeWorkspaceId);if(t&&!r)return x({status:"blocked",reasonCode:"guardian_workspace_context_unavailable",skillSlug:e.skillSlug,agent:e.agentId,scope:e.scope,nextAction:"workspace.current",nextStep:"Refresh the selected Enterprise workspace before materializing this skill."},"Enterprise materialization requires a current workspace-bound Guardian context.",e.flags.json,"guardian_workspace_context_unavailable");let i=await zn(e.backend,e.scope),o=(Fe(i,"hooks")??[]).filter(L).find(u=>f(u,"agent")===e.agentId&&f(u,"scope")===e.scope&&u.active===!0),s=wr(e.agentId),a=yl({evaluationContext:"activation_eligibility",requestedMode:"enforce",workspacePolicy:t?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:s?.maximumTier==="strict_candidate",hookInstalled:!!o,strictHookVerified:o?.strictPreActionBlocking===!0&&o.evidenceCapability==="strict",exactActivationVerified:o?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"none",materializationState:"active"}),l=a.activationAllowed&&a.countedAsEnforced,c=t&&e.backend.config.workingModeGuardianPolicy==="standard"&&o!==void 0&&o.configActive!==!1;return l||c?(t&&(e.backend.guardianActivationReceipts??={},e.backend.guardianActivationReceipts[`${e.agentId}:${e.scope}`]={policy:e.backend.config.workingModeGuardianPolicy==="standard"?"standard":"strict",agent:e.agentId,scope:e.scope,tier:l?"strict_verified":"hook_unverified",observedAt:e.backend.now()}),null):x({status:"blocked",reasonCode:"guardian_enforcement_unavailable",skillSlug:e.skillSlug,workspaceId:r,agent:e.agentId,scope:e.scope,measuredProtection:{...a,evidenceCapability:o?.evidenceCapability??"unverified",evidenceReasons:o?.evidenceReasons??[s?.reasonCode??"host_has_no_supported_guardian_route"]},nextAction:"guardian.hook.install",nextStep:!o||o.configActive===!1?`Run skills-layer guardian hook install --agent ${e.agentId} --scope ${e.scope}.`:e.backend.config?.workingModeRole==="enterprise_admin"?`This host has no current strict verification. Select a qualified host or use skills-layer enterprise workspace update ${e.backend.config?.workingModeEnterpriseId??"<enterprise-id>"} ${r??"<workspace-id>"} --guardian-policy standard. Hook installation alone does not prove strict enforcement.`:"This host has no current strict verification. Ask your Enterprise Admin to select a qualified host or review the workspace Guardian policy. Hook installation alone does not prove strict enforcement."},t&&e.backend.config.workingModeGuardianPolicy==="standard"&&(!o||o.configActive===!1)?`No active Guardian hook is installed for ${e.agentId} at ${e.scope} scope.`:`${t?"Enterprise":"Guardian-enforced"} materialization was blocked because verified Guardian enforcement is unavailable.`,e.flags.json,"guardian_enforcement_unavailable")}function $P(e,t,n){let r=e.guardianActivationReceipts?.[`${t}:${n}`];return r?{guardianEnforcement:r.tier,guardianActivationReceipt:r,...r.tier==="hook_unverified"?{warnings:[`Guardian hook installed but not strict-verified on ${t}; workspace policy allows standard enforcement.`]}:{}}:{}}function Mu(e){return e.config?.workingModeType!=="enterprise_workspace"?{}:ie({workingModeType:"enterprise_workspace",enterpriseId:e.config.workingModeEnterpriseId,workspaceId:e.config.workingModeWorkspaceId,workingModeWorkspaceId:e.config.workingModeWorkspaceId})}function iA(e,t,n,r){let i=j(t,"materializationPlan")??j(t,"installPlan"),o=k(r.scope)??f(t,"scope")??(i?f(i,"scope"):void 0),s=f(t,"skillSlug")??f(t,"slug")??n;if(o==="local")return{status:"cache_only",skillSlug:s,version:f(t,"version")??f(t,"currentVersion")};if(o!=="project"&&o!=="global")return{status:"skip"};let a=k(r.agent)??f(t,"agent")??f(t,"targetAgent")??(i?f(i,"agent")??f(i,"targetAgent"):void 0)??Re(e.config?.lastSelectedAgent)??"codex",l=et(e.env,e.platform,e.cwd).find(u=>u.id===a);if(!l)return{status:"failure",skillSlug:s,message:`Unsupported agent "${a}". Run \`skills-layer agents list\` to choose a supported local install target.`,nextStep:"Run `skills-layer agents list` and retry with a supported --agent value."};let c=o==="global"?l.targets.globalSkillsPath:l.targets.projectSkillsPath;return c?{status:"ok",scope:o,agent:l,skillsPath:c,skillSlug:s,version:f(t,"version")??f(t,"currentVersion")}:{status:"failure",skillSlug:s,message:`${l.displayName} does not expose a ${o} skills path on this machine.`,nextStep:"Retry with --scope project, or choose another agent from `skills-layer agents list`."}}async function bh(e,t,n,r,i={}){if(typeof t.downloadUrl=="string"&&L(t.artifactEnvelope)&&L(t.artifactApproval)&&L(t.platformScoreAuthority))return t;let o=new URLSearchParams;r&&o.set("version",r);let s=i.exportMode==="public"||!e.apiKey,a=s?`/api/v1/skills/${encodeURIComponent(n)}/export${Qe(o)}`:`/api/v1/me/library/${encodeURIComponent(n)}/export${Qe(o)}`,l=await D(e,a,{headers:s?{}:re(e.apiKey,e.authBlockedMessage)});if(!s&&!L(l.platformScoreAuthority))try{let c=await D(e,`/api/v1/skills/${encodeURIComponent(n)}/export${Qe(o)}`,{headers:{}});return{...l,platformScoreAuthority:c.platformScoreAuthority}}catch(c){if(!(c instanceof Z)||![401,403,404].includes(c.status))throw c}return s?{...l,downloadUrl:boe(n,f(l,"version")??r)}:l}function boe(e,t){let n=new URLSearchParams;return t&&n.set("version",t),`/api/v1/skills/${encodeURIComponent(e)}/download${Qe(n)}`}function _oe(e){let t=f(e,"visibility")??f(e,"versionVisibility"),n=f(e,"publicationStatus");return sU(e)&&(t==="public"||n==="clean_publishable"||n==="publishable_with_findings")}function Soe(e){return sU(e)}async function Uu(e){let t=_h(e.result),n=f(t,"skillSlug")??f(t,"slug")??e.fallbackSlug,r=e.requestedVisibility??(f(t,"visibility")==="public"||f(t,"versionVisibility")==="public"||f(t,"releaseVisibility")==="public"?"public":"private");if(!Soe(t)){let c=j(t,"publication"),u=f(t,"reasonCode")??(c?f(c,"reasonCode"):void 0)??"security_review_pending",d=!!e.unverifiedMaterialization,p=f(t,"version"),m=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"version")??f(e.unverifiedMaterialization,"currentVersion"):void 0,h=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"generationId"):void 0,g=c?f(c,"status")??f(t,"status")??"submitted":f(t,"status")??"submitted",y=g==="catalogue_submission_failed"||u==="source_ingestion_candidate_not_claimable",v=f(t,"workflowId"),b=f(t,"processingAttemptId"),w=f(t,"jobId"),_=f(t,"intakeReceiptId"),C=j(t,"progress")??{},P=!y&&t.continuationConfirmed!==!1&&!!(v||b||w)&&["queued","running","catalogue_processing_scheduled","held_for_moderation","source_install_pending_review","reused"].includes(g),O={status:y?"rejected":g==="reused"&&_?"reused":P?g==="reused"?"reused":"accepted":_?"accepted":"unconfirmed",reasonCode:u,continuationConfirmed:P,nextActor:f(C,"nextActor")??(P?"platform":u==="source_ingestion_candidate_not_claimable"?"operator":"requester")},N=ie({...e.unverifiedMaterialization,status:d?"installed_unverified":"install_pending_review",sourceItemStatus:f(t,"status")??"submitted",skillId:f(t,"skillId"),versionId:f(t,"versionId"),skillSlug:n,version:d?m:p,catalogueCandidateVersion:p,localProvisionalVersion:m,localGeneration:h,sourceContentDigest:e.unverifiedMaterialization?f(e.unverifiedMaterialization,"sourceContentDigest"):void 0,visibility:r,catalogueVisibilityRequested:r,requestedVisibility:r,catalogueStatus:g,publiclyDiscoverable:!1,intakeAdmission:O,assessmentStatus:f(C,"status")??(P?"pending":"unconfirmed"),publicationStatus:"not_published",distributionStatus:"verified_artifact_required",workflowId:v,processingAttemptId:b,jobId:w,intakeReceiptId:_,progress:t.progress,intakeReceiptIds:t.intakeReceiptIds,candidateIds:t.candidateIds,wakeStatus:t.wakeStatus,uploadIntent:t.uploadIntent,backgroundWorkStatus:P?"catalogue_review_continues_automatically":"retry_or_operator_action_required",publication:c?_h(c):void 0,activationStatus:d?"installed_unverified":"held",verificationStatus:d?"unverified":void 0,reasonCode:u,materializedWrites:d&&Array.isArray(e.unverifiedMaterialization?.materializedWrites)?e.unverifiedMaterialization.materializedWrites:[],materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex",activation:d?"unverified_install_request_authorized":"approved_artifact_only"},nextStep:d?`Local installation is complete as Unverified / Unscored. ${P?"The durable assessment job remains scheduled.":"Continued assessment is not confirmed; retry submission or inspect the candidate status."} Verified publication requires valid four-dimension evidence and current distribution authority. Valid poor effectiveness is a warning, not a security block.`:P?`Run skills-layer ${_?`install status ${_}`:`creator status ${n}`}, then retry when verified distribution is available.`:"Submission continuation is not confirmed. Inspect the intake status or retry submission before waiting for assessment."});return d&&await Ha(e.backend,N,n),Va(N,d?`External source installed locally as unverified; ${P?"catalogue review continues":"catalogue continuation is unconfirmed"}.`:P?"Source submitted; installation is pending approval.":"Source installation is held; catalogue continuation is unconfirmed.",e.flags.json,e.backend)}let i=j(j(t,"progress")??{},"subject"),o=i?f(i,"generationId"):void 0,s=i?f(i,"version"):void 0;if(i&&(!o||!s||f(i,"slug")!==n))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",skillSlug:n,intakeReceiptId:t.intakeReceiptId,nextStep:"Retry after the source receipt identifies the exact approved skill, version and generation."},"The completed source receipt does not identify this exact skill and generation.",e.flags.json,"source_catalogue_identity_invalid");let a;try{a=await rA(e.backend,t,n,e.flags,{exportMode:_oe(t)?"public":"auto",...i?{expectedSourceGeneration:{generationId:o,version:s}}:{}})}catch(c){if(!(c instanceof Z)||![404,502,503,504].includes(c.status))throw c;let u=ie({...t,...e.unverifiedMaterialization,status:e.unverifiedMaterialization?"installed_unverified":"catalogue_artifact_unavailable",activationStatus:e.unverifiedMaterialization?"installed_unverified":"not_installed",sourceItemStatus:f(t,"status"),catalogueStatus:f(t,"status"),publicationStatus:"published",continuationConfirmed:!0,reasonCode:"catalogue_artifact_unavailable",serverReasonCode:c.details?f(c.details,"reasonCode"):void 0,nextStep:"The catalogue version is published, but its approved artifact could not be downloaded. Retry the install when export is available. Any existing local source install remains unverified."});return e.unverifiedMaterialization?(await Ha(e.backend,u,n),Va(u,"Source installed locally as unverified; the published catalogue artifact is temporarily unavailable.",e.flags.json,e.backend)):x(u,"The published catalogue artifact is temporarily unavailable.",e.flags.json,"catalogue_artifact_unavailable")}if(fe(a))return a;let l=await sA(e.backend,a,n,e.flags);return await Ha(e.backend,l,n),Va(l,zoe(e.source,e.flags,e.backend,l,e.sourceAccess),e.flags.json,e.backend)}function _h(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>t==="localWrites"||t==="files"||t==="content"||t==="archiveBytes"?[]:Array.isArray(n)?[[t,n.map(r=>L(r)?_h(r):r)]]:L(n)?[[t,_h(n)]]:[[t,n]]))}function sU(e){if(aU(e.artifactApproval).status==="ok"&&e.artifactEnvelope!==void 0&&typeof e.downloadUrl=="string")return!0;let n=j(e,"publication"),r=n?f(n,"status")==="published":!1,i=f(e,"listingStatus")==="published",o=f(e,"versionStatus")==="published",s=f(e,"status");return i&&o&&(r||s==="published"||s==="reused"||s==="source_approved")}function Sh(e){return ie({version:f(e,"version"),storageKey:f(e,"storageKey"),expiresAt:f(e,"expiresAt")})}async function xh(e){let t=aU(e.exportResult.artifactApproval);if(t.status!=="ok"){let d=t.status==="missing";return $i(e,d?"artifact_v1_approval_missing":"artifact_v1_approval_invalid",d?`Export for ${e.skillSlug} did not include an authoritative approved Artifact Format v1 identity.`:`Export for ${e.skillSlug} included malformed Artifact Format v1 approval metadata.`)}let n=t.approval;if(e.expectedSourceGeneration&&(n.generation.generationId!==e.expectedSourceGeneration.generationId||n.generation.semanticVersion!==e.expectedSourceGeneration.version))return $i(e,"source_catalogue_generation_mismatch","The exported artifact does not match the exact version and generation resolved for this source.");let r=xoe({backend:e.backend,exportResult:e.exportResult,approval:n,skillSlug:e.skillSlug});if(r.status!=="ok")return $i(e,r.reasonCode,r.message);if(e.exportResult.artifactEnvelope===void 0)return $i(e,"artifact_v1_envelope_missing",`Export for ${e.skillSlug} did not include an Artifact Format v1 envelope.`);let i=f(e.exportResult,"downloadUrl");if(!i)return x({status:"export_download_unavailable",reasonCode:"export_download_unavailable",skillSlug:e.skillSlug,nextStep:"Retry after the backend returns a signed bundle download URL."},`Export for ${e.skillSlug} did not include a signed download URL.`,e.flags.json,"export_download_unavailable");let o=await e.backend.fetchFn(Ioe(e.backend.baseUrl,i));if(!o.ok)throw new Z(o.status,`Unable to download exported bundle (${o.status}).`);let s;try{s=await Poe(o)}catch(d){return $i(e,"artifact_v1_archive_bounds_failed",`Downloaded ${e.skillSlug} exceeded Artifact Format v1 archive bounds.`,{verificationError:ve(d)})}let a,l;try{a=Nd({archiveBytes:s,envelope:e.exportResult.artifactEnvelope}),l=Cl({archiveBytes:s,envelope:a})}catch(d){return $i(e,"artifact_v1_verification_failed",`Downloaded ${e.skillSlug} failed Artifact Format v1 verification.`,{verificationError:ve(d)})}if(!Coe(n,a))return $i(e,"artifact_v1_identity_mismatch",`Downloaded ${e.skillSlug} did not match the authoritative approved generation.`);let c=f(e.exportResult,"skillSlug"),u=f(e.exportResult,"version");return a.generation.skillSlug!==e.skillSlug||c!==void 0&&c!==a.generation.skillSlug||u!==void 0&&u!==a.generation.semanticVersion?$i(e,"artifact_v1_target_mismatch",`Downloaded ${e.skillSlug} was approved for a different skill or version.`):{status:"ok",bytes:s,files:l,envelope:a,approval:n,archiveSha256:a.archive.sha256,archiveBytesSha256:a.archive.sha256,archiveHashFormat:"artifact_v1_zip"}}function xoe(e){let t=j(e.exportResult,"platformScoreAuthority"),n=t?.machineReport,r=t?.passport,i=t?.parityManifest,o=t?f(t,"passportPublicKey"):void 0;if(!t||!rC(n)||!o)return{status:"invalid",reasonCode:"platform_score_authority_missing",message:`Export for ${e.skillSlug} did not include a verifiable Platform Score authority.`};let s=Yc.safeParse(r),a=nC.safeParse(i);if(!s.success||!a.success)return{status:"invalid",reasonCode:"platform_score_authority_invalid",message:`Export for ${e.skillSlug} included malformed Platform Score authority metadata.`};let l=n.projection.report;if(l.subject.slug!==e.skillSlug||l.subject.version!==e.approval.generation.semanticVersion||l.subject.generationId!==e.approval.generation.generationId||l.subject.archiveSha256!==e.approval.archiveSha256||a.data.report.reportId!==l.reportId||a.data.report.revision!==l.revision||a.data.report.digest!==l.reportDigest)return{status:"invalid",reasonCode:"platform_score_authority_subject_mismatch",message:`Export for ${e.skillSlug} did not match the exact Platform Score generation.`};try{let c=ZL({passport:s.data,publicKeys:{[s.data.issuer.keyId]:Yne(o)},now:e.backend.now(),expectedSubject:l.subject,expectedReport:{reportId:l.reportId,revision:l.revision,digest:l.reportDigest},currentPassportId:s.data.passportId});if(!c.valid)return{status:"invalid",reasonCode:`platform_score_${c.reasonCode}`,message:`Export for ${e.skillSlug} failed signed Skill Passport verification.`}}catch{return{status:"invalid",reasonCode:"platform_score_passport_key_invalid",message:`Export for ${e.skillSlug} included an invalid Skill Passport public key.`}}return{status:"ok"}}function aU(e){return e==null?{status:"missing"}:!L(e)||e.status!=="approved"||!L(e.generation)||typeof e.generation.skillSlug!="string"||typeof e.generation.semanticVersion!="string"||typeof e.generation.generationId!="string"||typeof e.archiveSha256!="string"||typeof e.manifestSha256!="string"?{status:"invalid"}:{status:"ok",approval:{status:"approved",generation:{skillSlug:e.generation.skillSlug,semanticVersion:e.generation.semanticVersion,generationId:e.generation.generationId},archiveSha256:e.archiveSha256,manifestSha256:e.manifestSha256}}}function Coe(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archive.sha256&&e.manifestSha256===t.manifest.sha256}function $i(e,t,n,r={}){return x({status:"download_integrity_failed",reasonCode:t,skillSlug:e.skillSlug,version:f(e.exportResult,"version"),archiveHashFormat:"artifact_v1_zip",...r,nextStep:"Retry after the catalog serving generation is refreshed, or contact Skills Layer support if this repeats."},n,e.flags.json,t)}function Ioe(e,t){return/^https?:\/\//iu.test(t)?t:`${dr(e)}${t.startsWith("/")?"":"/"}${t}`}async function Poe(e){let t=e.headers.get("content-length");if(t!==null){let a=Number(t);if(!Number.isSafeInteger(a)||a<0)throw new Error("Artifact response Content-Length is invalid.");if(a>ut.maxArchiveBytes)throw new Error("Artifact response exceeds the v1 archive byte limit.")}if(!e.body)throw new Error("Artifact response body is unavailable.");let n=e.body.getReader(),r=[],i=0;try{for(;;){let a=await n.read();if(a.done)break;if(i+=a.value.byteLength,i>ut.maxArchiveBytes)throw await n.cancel("Artifact response exceeds the v1 archive byte limit."),new Error("Artifact response exceeds the v1 archive byte limit.");r.push(Uint8Array.from(a.value))}}finally{n.releaseLock()}let o=new Uint8Array(i),s=0;for(let a of r)o.set(a,s),s+=a.byteLength;return o}async function oA(e){let t=e.verificationStatus??"verified";if(t==="verified"&&!e.approval)throw new Error("Verified materialization requires platform artifact approval.");let n=e.backend.platform==="win32"?st:Lt,r=ct(e.files),i=n.join(e.backend.paths.bundlesDir,e.skillSlug,e.envelope.generation.semanticVersion,encodeURIComponent(e.envelope.generation.generationId),"bundle.zip"),o=n.join(e.skillsPath,Mr(e.skillSlug)),s=et(e.backend.env,e.backend.platform,e.backend.cwd).filter(G=>{let ee=e.scope==="global"?G.targets.globalSkillsPath:G.targets.projectSkillsPath;return ee!==null&&Bo(ee,e.backend.platform)===Bo(e.skillsPath,e.backend.platform)}).map(G=>G.id).sort(),a=`activation_${Ge(16).toString("hex")}`,l={targetDir:o,generation:e.envelope.generation,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,files:e.envelope.manifest.files},c=nz({scope:e.scope,targetDir:o,platform:e.backend.platform}),u=await lt(e.backend);for(let[G,ee]of Object.entries(u.installs)){let te=[ee,...An(ee).map(X=>X.record)].flatMap(X=>[Jt(X)?.receipt.targetDir,f(X,"materializedSkillRoot"),f(X,"materializedPath")]);if(G!==e.skillSlug&&te.some(X=>X&&yA(o,X,e.backend.platform)))throw new Error(`Install folder already belongs to another skill (${G}). Remove that installation or choose a different target before installing ${e.skillSlug}.`)}let d=u.installs[e.skillSlug],p=Yt(d)[c],m=JSON.stringify(p??null),h=Wu({state:"pending_activation",operationId:a,receipt:l,backend:e.backend}),g=Wu({state:"active",operationId:a,receipt:l,backend:e.backend}),y={skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,targetAgents:s.length>0?s:[e.agent.id],materializedPath:o,materializedSkillRoot:o,materializationId:c,bundlePath:i,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,...Mu(e.backend),...$P(e.backend,e.agent.id,e.scope),localLifecycle:h,savedAt:e.backend.now()};await IA(i,e.bytes);let v=e.files.find(G=>ot(G.path).toLowerCase()==="skill.md"),b=v?await jae({backend:e.backend,skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,skillDocumentPath:n.join(o,...nM(v.path)),skillDocumentContent:v.content??""}):void 0,w,_=!1,C;try{let G={targetDir:o,...t==="verified"&&p?.verificationStatus==="unverified"&&!e.replaceUnverifiedSource?{expectedPreviousReceipt:l}:{},archiveBytes:e.bytes,envelope:e.envelope,preActivate:async({stageDir:ee})=>{let te=await Roe({backend:e.backend,stageDir:ee,envelope:e.envelope});return te.status==="passed"?(w=te.evalRun,{status:"passed",evidenceId:te.evidenceId}):{status:"failed",reasonCode:te.reasonCode}},checkpoint:async ee=>{if(ee==="after_static_eval"){await Br(e.backend,te=>{let X=te.installs[e.skillSlug],Ce=Yt(X)[c];if(JSON.stringify(Ce??null)!==m)throw new Error(`Local install materialization for ${e.skillSlug} changed during atomic activation.`);te.installs[e.skillSlug]=Fr({existing:X,skillSlug:e.skillSlug,materialization:y,backend:e.backend})}),_=!0;return}ee==="after_stage_activated"&&await Br(e.backend,te=>{let X=te.installs[e.skillSlug],Ce=Yt(X)[c],pn=Ce?Jt(Ce):null;if(!pn||pn.state!=="pending_activation"||pn.operationId!==a)throw new Error(`Atomic activation receipt reservation for ${e.skillSlug} was lost before commit.`);te.installs[e.skillSlug]=Fr({existing:X,skillSlug:e.skillSlug,materialization:{...y,localLifecycle:g,savedAt:e.backend.now()},backend:e.backend})})}};C=t==="verified"?await Yj({...G,approval:e.approval}):await Xj(G)}catch(G){throw _&&await cle({backend:e.backend,skillSlug:e.skillSlug,materializationId:c,operationId:a,baselineMaterialization:p}),G}if(!w)throw new Error("Static pre-activation Eval did not produce generation-bound evidence.");let P=await lt(e.backend),O=Yt(P.installs[e.skillSlug])[c],N=O?Jt(O):null;if(!N||N.state!=="active"||N.operationId!==a)throw new Error(`Atomic activation receipt for ${e.skillSlug} was not committed.`);let Q=C.receipt.files.map(G=>({path:yU(e.backend.cwd,n.join(o,...nM(G.path))),bytes:G.sizeBytes}));return{...e.backend.config?.workingModeType==="enterprise_workspace"?{status:"installed"}:{},bundlePath:i,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,...Mu(e.backend),...$P(e.backend,e.agent.id,e.scope),materializedPath:o,materializedSkillRoot:o,materializationId:c,targetAgents:s.length>0?s:[e.agent.id],archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,materializedWrites:Q,...b?{guardianRuntimeMetadata:b}:{},localLifecycle:g,atomicActivation:{status:C.status,receipt:C.receipt,generation:C.receipt.generation,archiveSha256:C.receipt.archiveSha256,manifestSha256:C.receipt.manifestSha256,staticEvaluation:C.staticEvaluation,cleanupPending:C.cleanupPending,...C.cleanupPath?{cleanupPath:C.cleanupPath}:{}},[Ch]:w}}var Ch=Symbol("skills-layer.pre-activation-eval"),Aoe=new Set(["file_exists","json_valid","schema_match","section_exists","regex_match","artifact_valid"]);async function Roe(e){let t=await cU(e.stageDir),n=ct(t),r=pU(t,n),i=l=>X1({pack:l,files:t,activationState:"inactive_staging",skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now(),runnerVersion:DP()}),o=i(r.pack);if(o.outcome!=="completed")return{status:"failed",reasonCode:o.reasonCode};let s=i(fU(t,n));if(s.outcome!=="completed")return{status:"failed",reasonCode:s.reasonCode};if(s.result.summary.status!=="passed")return{status:"failed",reasonCode:`static_eval_${s.result.summary.status}`};let a=dU({files:t,skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now()});return{status:"passed",evidenceId:`${s.result.summary.evalPackDigest??"eval-pack-unavailable"}:${s.result.summary.artifactDigest}`,evalRun:a}}async function sA(e,t,n,r){let i=f(t,"materializedSkillRoot");if(!i)return t;let o=f(t,"skillSlug")??f(t,"slug")??n,s=f(t,"version")??f(t,"currentVersion")??k(r.version)??"local";try{let a=t[Ch],l;if(lU(a))l=a;else{let u=await cU(Tt(e.cwd,i));if(u.length===0)return dh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"installed_files_unreadable"});l=dU({files:u,skillSlug:o,version:s,generatedAt:e.now()})}let c=await Foe(e,l.summary);return c.status==="recorded"?dh({...t,...c.effectiveness?{effectiveness:c.effectiveness}:{}},r,{status:"recorded",source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,evidenceRevision:c.evidenceRevision}):dh(t,r,{status:c.status,source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,reasonCode:c.reasonCode})}catch(a){return dh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"local_eval_failed",message:ve(a)})}}function lU(e){return L(e)&&(e.source==="submitted"||e.source==="inferred"||e.source==="invalid_submitted")&&L(e.summary)&&e.summary.schemaVersion==="skills-layer.eval.summary.v1"}async function cU(e){let t=[];return await uU(e,e,t),t.sort((n,r)=>n.path.localeCompare(r.path))}async function uU(e,t,n){for(let r of await ere(t,{withFileTypes:!0})){if(Eoe(r.name))continue;let i=K(t,r.name);if(r.isDirectory()){await uU(e,i,n);continue}if(!(!r.isFile()||Doe(r.name)))try{n.push({path:Bu(e,i).split("\\").join("/"),content:await Fi(i,"utf8")})}catch{continue}}}function Eoe(e){return e===".git"||e==="node_modules"||e==="coverage"||e===$oe()||e==="dist"}function $oe(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}function Doe(e){return e==="bundle.zip"||/^\.skills-layer-.*\.json$/u.test(e)}function dU(e){let t=ct(e.files),n=pU(e.files,t);if(!sf(n.pack).valid)return{source:"invalid_submitted",summary:Es({status:"runner_unavailable",skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:t,evalPackDigest:Rs(n.pack),generatedAt:e.generatedAt,runnerVersion:DP(),counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})};let i=Ooe(n.pack).map(s=>({id:s.id,assertions:s.assertions.map(a=>Loe(a,e.files))})),o=joe(i);return{source:n.source,summary:Es({status:Noe(o),skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:typeof n.pack.artifactDigest=="string"?n.pack.artifactDigest:t,evalPackDigest:Rs(n.pack),generatedAt:e.generatedAt,runnerVersion:DP(),counts:{cases:i.length,assertions:o.total,passed:o.passed,failed:o.failed,skipped:o.skipped}})}}function pU(e,t){let n=Toe(e);return n?{pack:n,source:"submitted"}:{pack:fU(e,t),source:"inferred"}}function Toe(e){for(let t of e){let n=$n(t.path,e);if(!(n.type!=="evidence"||!t.content||!n.relativePath.toLowerCase().endsWith(".eval.json")))try{let r=JSON.parse(t.content);if(L(r))return r}catch{return{schemaVersion:"invalid",artifactDigest:ct(e),origin:"submitted",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[]}}}}function fU(e,t){let r=e.find(i=>i.path.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()==="skill.md")?.path??"SKILL.md";return{schemaVersion:"skills-layer.eval.pack.v1",artifactDigest:t,origin:"inferred",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[{id:"starter-runtime-shape",assertions:[{type:"file_exists",path:r},{type:"regex_match",path:r,pattern:"name:"},{type:"artifact_valid",artifactDigest:t}]}]}}function Ooe(e){return Array.isArray(e.cases)?e.cases.flatMap(t=>!L(t)||typeof t.id!="string"||!Array.isArray(t.assertions)?[]:[{id:t.id,assertions:t.assertions.filter(L)}]):[]}function Loe(e,t){return typeof e.type=="string"&&!Aoe.has(e.type)?{status:"skipped",reasonCode:"runner_unavailable"}:rf(e,{files:t})}function joe(e){return e.reduce((t,n)=>{for(let r of n.assertions)t.total+=1,r.status==="passed"&&(t.passed+=1),r.status==="failed"&&(t.failed+=1),r.status==="skipped"&&(t.skipped+=1);return t},{total:0,passed:0,failed:0,skipped:0})}function Noe(e){return e.failed>0?"failed":e.passed>0?"passed":e.skipped>0?"runner_unavailable":"not_run"}function DP(){return`skills-layer-public-cli:${So}:local-install`}async function Foe(e,t){if(!e.apiKey)return{status:"local_only",reasonCode:"not_authenticated"};try{let n=await D(e,"/api/v1/me/evals/results",{method:"POST",headers:{"content-type":"application/json",...re(e.apiKey,e.authBlockedMessage)},body:JSON.stringify({evalSummary:t})}),r=j(n,"evalEvidence");return{status:"recorded",effectiveness:j(n,"effectiveness"),evidenceRevision:r?J(r,"revision"):void 0}}catch(n){return{status:"submit_failed",reasonCode:n instanceof Z?`http_${n.status}`:"request_failed"}}}function dh(e,t,n){return t.json?{...e,localEval:n}:e}function nM(e){let n=e.replaceAll("\\","/").replace(/^\/+/u,"").trim().split("/").filter(r=>r.length>0);if(n.length===0||n.some(r=>r==="."||r===".."))throw new Error(`Unsafe bundle path "${e}".`);return n}async function rM(e,t,n,r,i){let o=k(r.visibility)??"private";if(o!=="private"&&o!=="public")return x({status:"invalid_visibility",reasonCode:"invalid_visibility",source:e,requestedVisibility:o,nextStep:`Use \`skills-layer install ${e} --visibility private\` or \`--visibility public\`.`},"Local path install visibility must be private or public.",r.json,"invalid_visibility");let s=aA(e,t,n);if(r.list)return A(s,"Local source skills loaded.",r.json,i);let a=Ih(e,s,r);if(a)return a;let l=await ju({source:e,inspection:s,requestedSkillSlug:n,mode:"install",flags:r,backend:i});if(l.kind==="failure")return l.result;let c=l.skillSlug??ur(s)[0]?.value??hU(e),u=Boe(t.files,c),d=Wr({files:u,limits:yo}),p={mode:r.localOnly?"local_only":o==="public"?"explicit_public":"managed_private",upload:!r.localOnly,destination:r.localOnly?null:i.baseUrl,audience:r.localOnly?"local_device":o==="public"?"public_after_governed_review":"account_private",authentication:r.localOnly?"not_required":"required",files:d.preview.files.map(y=>({path:y.path,bytes:y.bytes})),totalBytes:d.preview.totalBytes};if(r.dryRun)return A({...LP(e,s,c,r),installKind:"local_source_submission",visibility:o,publicationStatus:"preview",catalogRecord:o,activationStatus:"not_started",uploadIntent:p,nextStep:r.localOnly?"Re-run without --dry-run for unverified, unscored local activation without upload.":`Re-run without --dry-run to create or reuse the ${o} central item. Local activation remains held until the exact generation completes security review and Artifact-v1 approval.`},"Local source submission preview ready.",r.json,i);if(r.localOnly){let y=await TP({backend:i,flags:r,source:e,skillSlug:c,files:u,defaultAcceptUnverifiedSource:!0});if(fe(y))return y;let v={...y,status:"installed_unverified",activationStatus:"installed_unverified",uploadIntent:p,intakeAdmission:{status:"not_requested"},assessmentStatus:"not_requested",publicationStatus:"not_requested",distributionStatus:"unverified_local",backgroundWorkStatus:"not_requested"};return await Ha(i,v,c),Va(v,"Local source installed as unverified and unscored. No files were uploaded.",r.json,i)}if(!i.apiKey)return x({reasonCode:"local_source_authentication_required",uploadIntent:p,nextStep:"Sign in for managed submission, or use --local-only for an unverified installation without upload."},"Managed local source submission requires authentication before uploading files.",r.json,"local_source_authentication_required");i.emitInfo(`Upload intent: ${p.files.length} selected files (${p.totalBytes} bytes) to ${i.baseUrl}; audience ${p.audience}; authenticated account required. Use --dry-run --json to inspect the file list or --local-only to avoid upload.`);let m=await QP(i,c,r);if(m)return m;let h;if(mU(r,i)){let y=await TP({backend:i,flags:r,source:e,skillSlug:c,files:u});if(fe(y))return y;h=y}let g;try{let y=dg(u)?await xC({baseUrl:i.baseUrl,apiKey:i.apiKey,fetchFn:i.fetchFn,files:u}):null;g=await D(i,"/api/v1/me/source-installs",{method:"POST",headers:{"content-type":"application/json",...re(i.apiKey,i.authBlockedMessage)},body:JSON.stringify(ie({...y?{hydrationManifestId:y.manifestId}:{files:u},skillSlug:c,version:k(r.version),visibility:o,category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),sourceMetadata:t.sourceMetadata}))})}catch(y){return h?await Uu({backend:i,flags:r,source:e,fallbackSlug:c,sourceAccess:"authenticated",requestedVisibility:o,unverifiedMaterialization:h,result:{status:"catalogue_submission_failed",skillSlug:c,uploadIntent:p,reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable"}}):x({status:"catalogue_submission_failed",uploadIntent:p,activationStatus:"not_started",intakeAdmission:{status:"rejected"},assessmentStatus:"not_requested",publicationStatus:"not_published",distributionStatus:"verified_artifact_required",reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable",skillSlug:c,nextStep:"Retry the source submission when catalogue service is available. No local files were written."},"The source was not installed because catalogue submission did not complete.",r.json,"catalogue_submission_failed")}return await Uu({backend:i,result:{...g,uploadIntent:p},fallbackSlug:f(g,"skillSlug")??c,source:e,sourceAccess:"authenticated",flags:r,requestedVisibility:o,...h?{unverifiedMaterialization:h}:{}})}function Boe(e,t){let n=lA(e).find(i=>i.skillSlug===t);if(!n||n.relativeSkillRoot===".")return e.map(i=>({...i}));let r=`${n.relativeSkillRoot.replace(/\/+$/u,"")}/`;return e.filter(i=>i.path.replaceAll("\\","/").startsWith(r)).map(i=>({...i,path:i.path.replaceAll("\\","/").slice(r.length)}))}async function iM(e){if(!e.flags.all&&!(!e.defaultAcceptUnverifiedSource&&!mU(e.flags,e.backend)))try{let t=rr(e.source),n=await kj({source:t,cwd:e.backend.cwd,platform:e.backend.platform,fetchFn:e.backend.fetchFn,...e.skillSlug?{requestedSkillSlug:e.skillSlug}:{}}),r=e.skillSlug?n.results.find(i=>i.skillSlug===e.skillSlug):n.results.length===1?n.results[0]:void 0;return r?await TP({backend:e.backend,flags:e.flags,source:e.source,skillSlug:r.skillSlug,files:r.files,relativeSkillRoot:r.relativeSkillRoot,defaultAcceptUnverifiedSource:e.defaultAcceptUnverifiedSource}):e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,nextStep:"Use --list to inspect the source and --skill <skill-slug> to select one exact skill before retrying."},"The CLI could not resolve one immutable external skill snapshot for local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}catch(t){return e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,error:t instanceof Error?t.message.slice(0,512):"Source snapshot could not be loaded.",nextStep:"Check source access and retry the exact source after its immutable snapshot is available."},"The CLI could not load the external source snapshot for unverified local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}}async function TP(e){let t=Wr({files:e.files,limits:yo}),n=nt(e.files,{profile:"external_ingest_tolerant"}),r=f2(e.files,p2),i=[...t.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:/^(?:secret_|pii_|sensitive_)/u.test(_.code)?"privacy":"integrity",..._.path?{path:_.path}:{}})),...n.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:"package_validity"})),...r.filter(_=>_.severity==="high"||_.severity==="critical").map(_=>({code:_.ruleId,concern:"security",path:_.filePath,..._.lineNumber?{lineNumber:_.lineNumber}:{}}))],o=i.map(_=>_.code);if(o.length>0){let _=i.some(C=>C.concern==="security")?"critical_local_preflight_blocked":"source_package_invalid";return x({status:"unverified_install_blocked",reasonCode:_,skillSlug:e.skillSlug,findingCodes:[...new Set(o)].sort((C,P)=>C.localeCompare(P)),blockingFindings:i,nextStep:"Do not activate this source. Review or remove the blocking content, then retry from a new immutable generation."},"External source did not satisfy the required local package checks and was not installed.",e.flags.json,_)}if(!(e.flags.acceptUnverifiedSource===!0||e.defaultAcceptUnverifiedSource===!0||await Moe(e)))return x({status:"unverified_install_consent_required",reasonCode:"unverified_source_consent_required",skillSlug:e.skillSlug,nextStep:"Review the source, then retry with --accept-unverified-source to install it before platform approval."},"External source was not installed because informed unverified-source consent was not provided.",e.flags.json,"unverified_source_consent_required");let a=iA(e.backend,{skillSlug:e.skillSlug,materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex"}},e.skillSlug,e.flags);if(a.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:e.skillSlug,nextStep:a.nextStep},a.message,e.flags.json,"materialization_target_invalid");if(a.status==="skip"||a.status==="cache_only")return x({status:"materialization_target_required",reasonCode:"materialization_target_required",skillSlug:e.skillSlug,nextStep:"Retry with --scope project|global and --agent <agent>."},"An explicit local target is required for an unverified external installation.",e.flags.json,"materialization_target_required");let l=await Ya({backend:e.backend,skillSlug:e.skillSlug,agentId:a.agent.id,scope:a.scope,flags:e.flags});if(l)return l;let c=ct(e.files),u=rr(e.source),d=u.kind==="github"?u.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,p=e.relativeSkillRoot,m=u.kind==="github"&&/^[a-f0-9]{40}$/u.test(u.ref)?{provider:"github",repository:`${u.owner}/${u.repo}`,commitSha:u.ref,sourceRoot:!p||p==="."?d:d==="."?p:`${d}/${p}`,sourceContentDigest:t.preview.bundleSha256}:void 0,h=c.slice(7,19),g=k(e.flags.version)??`0.0.0-external.${h}`,y=`generation_unverified_${c.slice(7,39)}`,v=e.files.filter(_=>$n(_.path,e.files).type==="runtime").map(_=>_.path),b=s0({generation:{skillSlug:e.skillSlug,semanticVersion:g,generationId:y},reviewPackageFiles:e.files,runtimeAllowlist:v});return{...await oA({backend:e.backend,skillSlug:e.skillSlug,scope:a.scope,agent:a.agent,skillsPath:a.skillsPath,bytes:b.archiveBytes,files:Cl({archiveBytes:b.archiveBytes,envelope:b.envelope}),envelope:b.envelope,verificationStatus:"unverified"}),source:e.source,sourceContentDigest:c,...m?{sourceSnapshot:{...m,runtimeDigest:c,archiveSha256:b.envelope.archive.sha256}}:{},platformScoreDecision:null,scoreAvailability:"unscored",scoreReasonCode:"unscored_local_source",localPreflight:{status:"passed",recommendation:t.issues.length+n.issues.length+r.length>0?"approved_with_notes":"approved",issueCount:t.issues.length+n.issues.length+r.length,findingCodes:[...t.issues.map(_=>_.code),...n.issues.map(_=>_.code),...r.map(_=>_.ruleId)]}}}function mU(e,t){return e.acceptUnverifiedSource===!0||!e.json&&!t.nonInteractive&&t.stdoutIsTty}async function Moe(e){if(e.flags.json||e.backend.nonInteractive)return!1;try{return await e.backend.promptSelect(`${e.skillSlug} comes from ${e.source} and has not completed Skills Layer Security/Eval. Install this immutable generation as unverified?`,[{value:"decline",label:"Do not install",description:"Keep local agent files unchanged."},{value:"accept",label:"Install unverified",description:"Use locally now while catalogue review runs in parallel."}])==="accept"}catch{return!1}}function aA(e,t,n){let r=lA(t.files),i=n?r.find(o=>o.skillSlug===n)??null:r.length===1?r[0]??null:null;return{status:"ok",source:t.sourceMetadata,selectedSkill:i,results:r,issues:[],sourceInstallSupported:!0,sourceInstallMode:"local_private",publicationStatus:"none",originalSource:e}}function lA(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=Be(t.path).replaceAll("\\","/"),r=n==="."?".":n,i=gU(t.content??"")??hU(r==="."?t.path:r),o=Uoe(t.content??"");return{skillSlug:i,name:i,...o?{description:o}:{},relativeSkillRoot:r,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function gU(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function Uoe(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function hU(e){return(e.replaceAll("\\","/").replace(/\/+$/u,"").split("/").filter(Boolean).at(-1)??"local-skill").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"local-skill"}function yU(e,t){let n=Bu(e,t);return n&&!n.startsWith("..")&&!st.isAbsolute(n)?n.split("\\").join("/"):t}function Ti(e,t,n,r="unknown"){let i=k(t.visibility);return i==="public"||i==="private"?i:r==="anonymous"&&OP(e)?"public":r==="authenticated"?"private":!n.apiKey&&OP(e)?"public":"private"}function OP(e){try{let t=rr(e).kind;return t==="github"||t==="gitlab"}catch{return/^https:\/\/(?:github|gitlab)\.com\//iu.test(e.trim())}}function cA(e,t,n,r="unknown"){return Ti(e,t,n,r)==="private"||k(t.visibility)==="unlisted"||r==="authenticated"?"/api/v1/me/source-installs":"/api/v1/source-imports"}function vU(e,t,n,r="unknown"){return{"content-type":"application/json",...cA(e,t,n,r)==="/api/v1/me/source-installs"?re(n.apiKey,n.authBlockedMessage):{}}}function zoe(e,t,n,r,i="unknown"){let o=r?f(r,"visibility")??f(r,"versionVisibility"):void 0,s=r?f(r,"publicationStatus"):void 0,a=r?f(r,"catalogRecord"):void 0,l=r?f(r,"status"):void 0;return o==="public"||s==="clean_publishable"||s==="publishable_with_findings"||l==="published"?"Public source install planned.":o==="private"||s==="private"||a==="private"||l==="private_source_installed"?"Private source skill installed.":Ti(e,t,n,i)==="public"?"Public source install planned.":"Private source skill installed."}async function ju(e){let t=ur(e.inspection);if(e.requestedSkillSlug)return t.length>0&&!t.some(n=>n.value===e.requestedSkillSlug)?{kind:"failure",result:qoe(e.source,e.requestedSkillSlug,t.map(n=>n.value),e.flags)}:{kind:"selected",skillSlug:e.requestedSkillSlug};if(e.flags.all||e.flags.json&&e.flags.dryRun)return{kind:"selected",skillSlug:e.requestedSkillSlug};if(t.length<=1)return{kind:"selected",skillSlug:t[0]?.value};if(e.flags.json)return{kind:"failure",result:oM(e.source,t,e.flags)};try{return{kind:"selected",skillSlug:await e.backend.promptSelect(`${e.source} exposes multiple skills. Select one to ${e.mode}:`,t)}}catch{return{kind:"failure",result:oM(e.source,t,e.flags)}}}function oM(e,t,n){let r=t.map(i=>i.value);return x({status:"selection_required",reasonCode:"source_skill_selection_required",source:e,availableSkills:r,nextAction:"install.source.select",nextStep:`Re-run with --skill <skill-slug> using one of: ${r.join(", ")}. Use --all only if you intend to install every discovered skill.`},`Source "${e}" exposes multiple skills. Re-run with --list or --skill <skill-slug>. Available skills: ${r.join(", ")}.`,n.json,"source_skill_selection_required")}function sM(e,t,n){if(n.all&&t)return x({status:"error",reasonCode:"conflicting_source_selection",source:e,selectedSkillSlug:t,all:!0,nextAction:"install",nextStep:"Use either --all to install every discovered skill or --skill <skill-slug> to install one skill, not both."},"Source install cannot combine --all with --skill. Choose one selection mode before retrying.",n.json,"conflicting_source_selection")}function aM(e,t){try{if(rr(e).kind!=="local")return}catch{return}return x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"install",nextStep:zu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source URL, or run `skills-layer install --source <source> --list` with a supported source."},zu(e)?`Install source ${e} was not found or is not readable.`:`Install source "${e}" is not a supported remote source and no local path was found.`,t.json,"invalid_source")}function qoe(e,t,n,r){return x({status:"not_found",reasonCode:"source_skill_not_found",source:e,requestedSkillSlug:t,availableSkills:n,nextAction:"install.source.list",nextStep:`Run \`skills-layer install --source ${e} --list\` to inspect discovered skills, then retry with one of the listed slugs.`},`Source ${e} does not contain a discovered skill named ${t}. Run with --list to inspect available skills.`,r.json,"source_skill_not_found")}function ur(e){let t=[e.results,e.skills,e.discoveredSkills,j(e,"source")?.results,j(e,"inspection")?.results],n=new Set,r=[];for(let i of t)if(Array.isArray(i))for(let o of i){let s=Voe(o);!s||n.has(s.value)||(n.add(s.value),r.push(s))}return r}function Voe(e){if(!L(e))return;let t=f(e,"skillSlug")??f(e,"slug")??f(e,"name");if(!t)return;let n=f(e,"displayName")??f(e,"title")??f(e,"name"),r=n&&n!==t?`${t} - ${n}`:t,i=j(e,"parsedSkill"),o=j(e,"frontmatter")??(i?j(i,"frontmatter"):void 0),s=f(e,"shortDescription")??f(e,"summary")??f(e,"description")??(o?f(o,"description"):void 0)??f(e,"relativeSkillRoot")??f(e,"path")??f(e,"discoveryRoute")??f(e,"sourceKind");return s?{value:t,label:r,description:s}:{value:t,label:r}}function lM(e,t,n,r,i,o={}){return ie({...t,skillSlug:n,scope:k(r.scope),agent:k(r.agent),workspace:k(r.workspace),version:k(r.version),visibility:o.visibility??k(r.visibility),category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),all:r.all,acceptCapability:r.acceptCapability})}async function cM(e){let t=e.sourceAccess??"unknown",n=cA(e.source,e.flags,e.backend,t);try{return await D(e.backend,n,{method:"POST",headers:vU(e.source,e.flags,e.backend,t),body:JSON.stringify(lM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{sourceAccess:t,...n==="/api/v1/source-imports"?{visibility:"public"}:{}}))})}catch(r){if(r instanceof Z&&r.status===401&&k(e.flags.visibility)!=="private"&&t!=="authenticated"&&OP(e.source))return await D(e.backend,"/api/v1/source-imports",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(lM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{visibility:"public"}))});throw r}}function LP(e,t,n,r){return ie({status:"dry_run",source:e,selectedSkillSlug:n,all:r.all,scope:k(r.scope)??"local",agent:k(r.agent),workspace:k(r.workspace),acceptCapability:r.acceptCapability,candidates:ur(t).map(i=>({skillSlug:i.value,name:i.label,description:i.description})),nextStep:r.all?`Re-run without --dry-run to install every discovered skill from ${e}.`:`Re-run without --dry-run${n?"":" and add --skill <skill-slug> if needed"} to install from ${e}.`})}async function kU(e,t,n,r,i={}){try{return{kind:"ok",inspection:await D(e,"/api/v1/source-inspect",{method:"POST",headers:wU(e,i.authMode??"auto"),body:JSON.stringify(ie(n))})}}catch(o){if(o instanceof Z)return{kind:"failure",result:NP(t,o,r)};throw o}}function wU(e,t){return t==="anonymous"?{"content-type":"application/json"}:V(e.apiKey)}async function jP(e,t,n,r){try{let s=await D(e,"/api/v1/source-inspect",{method:"POST",headers:wU(e,"anonymous"),body:JSON.stringify(ie(n))}),a=uM(t,s,r);return a?{kind:"failure",result:a}:{kind:"ok",inspection:s,sourceAccess:"anonymous"}}catch(s){if(!(s instanceof Z))throw s;let a=s.details??{},l=f(a,"error")??s.message;if(!uA(s.status,l))return{kind:"failure",result:NP(t,s,r)};if(!e.apiKey)return{kind:"failure",result:NP(t,s,r)}}let i=await kU(e,t,n,r,{authMode:"authenticated"});if(i.kind==="failure")return i;let o=uM(t,i.inspection,r);return o?{kind:"failure",result:o}:{kind:"ok",inspection:i.inspection,sourceAccess:"authenticated"}}function uM(e,t,n){if(n.list||n.dryRun)return null;let r=[t.catalogueDecision,...Array.isArray(t.catalogueDecisions)?t.catalogueDecisions:[]].filter(i=>i!==void 0);for(let i of r){let o=L(i)?i.status:void 0;if(!L(i)||i.schemaVersion!=="skills-layer.source-catalogue-decision.v1"||!["approved","pending","new"].includes(String(o))){let s=["security_blocked","revoked","restricted","unavailable"].includes(String(o))?`source_catalogue_${o}`:"source_catalogue_identity_invalid";return x({status:s,reasonCode:s,source:e,catalogueDecision:i,nextStep:"Resolve the current catalogue decision before retrying this exact source."},"This source cannot be activated under its current catalogue decision.",n.json,s)}}if(t.catalogueSourceInput!==void 0){let i=rr(e),o=typeof t.catalogueSourceInput=="string"?rr(t.catalogueSourceInput):void 0,s=l=>l.replace(/(?:^|\/)SKILL\.md$/u,"")||".";if(!(i.kind==="github"&&o?.kind==="github"&&`${i.owner}/${i.repo}`.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&s(i.subpath)===s(o.subpath)&&/^[a-f0-9]{40}$/u.test(o.ref)&&(!/^[a-f0-9]{40}$/iu.test(i.ref)||i.ref.toLowerCase()===o.ref)&&r.every(l=>{let c=L(l)?j(l,"subject"):void 0,u=c?f(c,"sourceRoot"):void 0,d=s(o.subpath);return c?.commitSha===o.ref&&typeof c.repository=="string"&&c.repository.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&u&&(u==="."||!u.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)))&&(d==="."||u===d||u.startsWith(`${d}/`))})))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e},"The inspected snapshot does not identify this exact source.",n.json,"source_catalogue_identity_invalid")}return null}function Ih(e,t,n){if(ur(t).length>0)return null;let i=Goe(t);return x({status:"unsupported_source_layout",source:e,reasonCode:"source_no_discoverable_skills",issues:i,nextStep:"Run with --list to inspect the source, use a subfolder containing SKILL.md, or install from a Skills Layer-compatible source layout."},Hoe(e,i),n.json)}function Goe(e){return(Array.isArray(e.issues)?e.issues:[]).filter(L).map(n=>({...f(n,"code")?{code:f(n,"code")}:{},...f(n,"message")?{message:f(n,"message")}:{},...f(n,"path")?{path:f(n,"path")}:{}}))}function NP(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(uA(t.status,i))return bU(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Go(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_inspectable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be inspected as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}function dM(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(uA(t.status,i))return bU(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Go(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_installable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be installed as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}async function pM(e){let t=e.error instanceof Z?e.error.details??{}:{},n=e.error instanceof Z?f(t,"reasonCode")??"catalogue_submission_failed":"catalogue_submission_unavailable";return await Uu({backend:e.backend,result:{...t,status:"catalogue_submission_failed",reasonCode:n,publiclyDiscoverable:!1},fallbackSlug:e.skillSlug,source:e.source,sourceAccess:e.sourceAccess,flags:e.flags,requestedVisibility:Ti(e.source,e.flags,e.backend,e.sourceAccess),unverifiedMaterialization:e.unverifiedMaterialization})}function uA(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function bU(e,t,n,r){let i=t.details??{},o=f(i,"error")??t.message,a=`skills-layer source connection start --provider ${_U(e)} --source ${e} --visibility private --provenance-intent private_source_import`,l={status:"private_source_access_required",source:e,reasonCode:"private_source_access_required",backendStatus:t.status,backendMessage:o,nextStep:a};return x(l,`Cloud could not ${r} ${e} directly. If this is a private source, start a private source connection first:
|
|
2151
2151
|
${a}`,n.json,"private_source_access_required")}function _U(e){return/gitlab\./iu.test(e)?"gitlab":/github\./iu.test(e)||/^gh:/iu.test(e)?"github":"generic_git"}function Hoe(e,t){let n=[`No Skills Layer-compatible skills were found in ${e}.`];if(t.length>0){n.push("Detected issues:");for(let r of t.slice(0,5)){let i=r.code??"source-inspection";n.push(`- ${i}: ${r.message??"No details returned."}${r.path?` (${r.path})`:""}`)}}return n.push("Try --list, a subfolder containing SKILL.md, or a Skills Layer-compatible source layout."),n.join(`
|
|
2152
|
-
`)}async function SU(e,t,n){if(xU(e)){let l=f(e,"reasonCode")??f(e,"reason")??"install_not_ready",c=f(e,"why")??f(e,"summary")??"The requested skill is not ready to install from this backend.";return x(e,`Install preview is not ready: ${c}`,t.json,l)}let r=k(t.agent)==="all"?
|
|
2153
|
-
`)}function Zoe(e,t){let n=j(e,"trust"),r=j(e,"securityPosture"),i=j(e,"capabilityProfile"),o=n?.securityScore??n?.score??e.securityScore??r?.securityScore,s=qe(n,"runtimeRisk")??f(e,"runtimeRisk")??qe(r,"runtimeRisk")??qe(i,"runtimeRisk"),a=qe(n,"recommendation")??f(e,"recommendation")??qe(r,"recommendation"),l=qe(n,"label")??qe(n,"trust")??f(e,"trustStatus")??f(e,"trust")??qe(r,"label");if(o===void 0&&!s&&!a&&!l)return[];let c=[t.section("Trust")];return s&&c.push(` ${t.label("Runtime risk")}: ${s}`),a&&c.push(` ${t.label("Recommendation")}: ${a}`),l&&c.push(` ${t.label("Status")}: ${l}`),c.push(` ${t.label("Source")}: skills-layer trust`),c}async function ed(e,t,n){let r=[],i=[];if(!t.apiKey)return{warnings:r,revokedSlugs:i};let o=await lt(t),s=Object.entries(o.installs).filter(([l,c])=>(!n||l===n)&&c.acquisitionMode==="authenticated_account"&&(!c.acquisitionBaseUrl||c.acquisitionBaseUrl===t.baseUrl));if(!s.length)return{warnings:r,revokedSlugs:i};let a=[];try{for(let l=0;l<s.length;l+=50){let c=new URLSearchParams({slugs:s.slice(l,l+50).map(([d])=>d).join(",")}),u=await D(t,`/api/v1/me/entitlements?${c}`,{headers:re(t.apiKey,t.authBlockedMessage)});if(!Array.isArray(u.results))throw new Error("Entitlement status unavailable");a.push(...u.results.filter(L))}}catch{return{warnings:["Could not verify entitlements online; local copies were kept."],revokedSlugs:i}}for(let[l,c]of s){let u=a.find(h=>h.skillSlug===l);if(!u||u.status!=="revoked"||u.reason!=="refunded"||u.paid!==!0)continue;let d=typeof c.entitlementId=="string"&&c.entitlementId===u.entitlementId,p=typeof c.acquiredByUserId=="string"&&c.acquiredByUserId===t.config?.userId&&c.acquisitionBaseUrl===t.baseUrl;if(!d&&!p){r.push(`Kept ${l}: its receipt cannot be matched to this buyer's refunded grant.`);continue}let m=An(c);if(!m.length){r.push(`No managed agent copy found for refunded ${l}. Manually copied folders cannot be removed automatically.`);continue}for(let h of m){let g=typeof h.record.acquisitionBaseUrl=="string"?h.record:m.length===1?c:{},y=typeof g.entitlementId=="string"&&g.entitlementId===u.entitlementId,v=g.acquiredByUserId===t.config?.userId&&typeof g.acquiredByUserId=="string"&&g.acquisitionBaseUrl===t.baseUrl;if(!y&&!v){r.push(`Kept ${l}: this agent copy belongs to an unverified buyer receipt.`);continue}if(i.includes(l)||i.push(l),!(h.lifecycle?.state==="quarantined"||h.lifecycle?.state==="externally_removed")){if(!h.lifecycle||!["active","pending_activation"].includes(h.lifecycle.state)){r.push(`Kept ${l}: modified or unverifiable local copy; inspect it before removing it manually.`);continue}if(e.dryRun){r.push(`Would remove ${l} \u2014 refunded on ${String(u.revokedAt??"unknown date")}.`);continue}try{await pA({backend:t,skillSlug:l,record:gr(c,h),materializationId:h.materializationId,lifecycle:h.lifecycle,reasonCode:"refunded",purpose:"quarantine_revoked",status:"removed"}),r.push(`Removed ${l} \u2014 refunded on ${String(u.revokedAt??"unknown date")}.`)}catch{r.push(`Kept ${l}: modified or unverifiable local copy; inspect it before removing it manually.`)}}}}return{warnings:r,revokedSlugs:i}}async function Joe(e,t){let n=Qu("installed",e);if(n.failure)return n.failure;let r=await ed(e,t),i=e.dryRun?await lt(t):await Bi(t),o=iz(i).filter(s=>(!n.scope||f(s,"scope")===n.scope)&&(!n.agent||mr(s).includes(n.agent)));return A({status:"ok",results:o,warnings:r.warnings},`Found ${o.length} local install records. ${r.warnings.join(" ")}`,e.json,t,"installed")}async function Yoe(e,t,n){let r=T(e[0],"remove requires a skill slug."),i=YM("remove",t);if(i)return i;let s=(t.dryRun?await lt(n):await Bi(n,r)).installs[r];if(!s)return x({status:"not_installed",reasonCode:"local_install_not_found",skillSlug:r},`${r} is not installed locally. Run \`skills-layer installed\` or \`skills-layer sync\` to inspect local records.`,t.json,"local_install_not_found");let a=k(t.scope),l=k(t.agent),c=qn(s,{scope:a,agent:l});if(c.length>1){let g=ole({backend:n,skillSlug:r,materializations:c,scope:a,agent:l});g.length===1&&(c=g)}if(c.length===0&&An(s).length>0)return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:r,requestedScope:a,requestedAgent:l},`${r} is not installed for the requested local target.`,t.json,"local_install_target_not_found");if(c.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:r,availableTargets:c.map(g=>({materializationId:g.materializationId,scope:f(g.record,"scope"),targetAgents:mr(g.record),materializedSkillRoot:f(g.record,"materializedSkillRoot")})),nextAction:"remove",nextStep:`Run the command from the intended project folder, or retry with --scope project|global and --agent <agent> to remove one exact ${r} materialization.`},`${r} is installed in more than one local target. Select the exact target to remove.`,t.json,"local_install_target_selection_required");let u=c[0],d=u?gr(s,u):s,p=u?.lifecycle??null;if(!p){let g=oz(s);if(g){try{await Xoe({backend:n,skillSlug:r,record:s,cachedArtifact:g})}catch{return x({status:"blocked",reasonCode:"cached_artifact_remove_failed",skillSlug:r,nextAction:"install",nextStep:"The cache receipt or its immutable bundle could not be verified. Leave it unchanged and reinstall only after resolving the local cache issue."},`Skills Layer could not safely remove ${r}'s verified cache receipt.`,t.json,"cached_artifact_remove_failed")}let y={status:"removed",skillSlug:r,storageKind:"cached_artifact"};return t.json?A(y,`Removed cached ${r}.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}return x({status:"blocked",reasonCode:"exact_install_receipt_missing",skillSlug:r,nextAction:"install",nextStep:`Reinstall ${r} from an approved Artifact Format v1 export before removing or quarantining it.`},`Skills Layer cannot safely remove ${r} because its exact-generation receipt is missing or invalid.`,t.json,"exact_install_receipt_missing")}if(p.state==="quarantined"){let g={status:"removed",skillSlug:r,removedRecord:d,localLifecycle:p};return t.json?A(g,`${r} is already removed from discovery.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}if(p.state==="externally_removed"||p.state==="host_detached"){if(t.forget){let g=Vr(p.receipt),y=await tae(n,{skillSlug:r,generationId:p.receipt.generation.generationId,receiptSha256:g});return await Br(n,v=>{let b=v.installs[r];if(!b)return;let w=rz({existing:b,materializationId:u.materializationId,backend:n});w?v.installs[r]=w:delete v.installs[r]}),A({status:"forgotten",skillSlug:r,materializationId:u.materializationId,receiptSha256:g,forgottenAssociationCount:y,cloudAuthorityChanged:!1,nextAction:"installed",nextStep:"The local terminal tombstone and its terminal session evidence were removed. Cloud ownership, entitlement, workspace approval, and Trust Ledger history remain unchanged."},`${r}'s exact local tombstone was forgotten.`,t.json,n)}return A({status:p.state,skillSlug:r,tombstoneRetained:!0,localLifecycle:p,nextAction:"install",nextStep:`Reinstall ${r} to rematerialize it. Its local tombstone remains available for audit and recovery.`},`${r} is already absent from the exact local target; its recovery tombstone was retained.`,t.json,n)}if(t.forget)return x({status:"blocked",reasonCode:"guardian_forget_requires_terminal_tombstone",skillSlug:r,localLifecycle:p,nextAction:"remove",nextStep:"Use normal remove for an active installation. --forget only deletes a retained externally_removed or host_detached tombstone."},"Skills Layer only forgets an explicit terminal local tombstone.",t.json,"guardian_forget_requires_terminal_tombstone");if(p.state!=="active"&&p.state!=="pending_activation")return x({status:"blocked",reasonCode:"local_lifecycle_busy",skillSlug:r,localLifecycle:p},`${r} cannot be removed while its local lifecycle is ${p.state}.`,t.json,"local_lifecycle_busy");let m;try{m=await pA({backend:n,skillSlug:r,record:d,materializationId:u.materializationId,lifecycle:p,reasonCode:"user_removed",purpose:"quarantine_revoked",status:"removed"})}catch(g){return x({status:"blocked",reasonCode:"exact_generation_quarantine_failed",skillSlug:r,error:ve(g),nextAction:"guardian.incident.review",nextStep:"Do not run the skill. Inspect local drift or permissions, then retry removal after the exact tree is restored."},`Skills Layer could not atomically remove the exact installed generation for ${r}.`,t.json,"exact_generation_quarantine_failed")}let h={status:"removed",skillSlug:r,removedRecord:m.record,localLifecycle:m.lifecycle};return t.json?A(h,`Removed ${r}.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}async function Xoe(e){let t=e.backend.platform==="win32"?ot:Lt,n=t.join(e.backend.paths.bundlesDir,e.skillSlug,e.cachedArtifact.generation.semanticVersion,encodeURIComponent(e.cachedArtifact.generation.generationId),"bundle.zip");if(t.normalize(e.cachedArtifact.bundlePath)!==t.normalize(n))throw new Error("Cached artifact path does not match its exact generation.");let r=await Xu(n);if(!r.isFile()||r.isSymbolicLink())throw new Error("Cached artifact is not a regular file.");if(`sha256:${Me("sha256").update(await Fi(n)).digest("hex")}`!==e.cachedArtifact.archiveSha256)throw new Error("Cached artifact digest does not match its receipt.");let o=K(Be(n),`.bundle.remove-${Ge(12).toString("hex")}`);await zo(n,o);try{let s=await lt(e.backend),a=s.installs[e.skillSlug],l=a?oz(a):null;if(!a||!l||l.bundlePath!==e.cachedArtifact.bundlePath||l.archiveSha256!==e.cachedArtifact.archiveSha256)throw new Error("Cached install record changed during removal.");delete s.installs[e.skillSlug],await _A(e.backend,s)}catch(s){throw await zo(o,n).catch(()=>{}),s}await We(o,{force:!0})}async function pA(e){if(e.lifecycle.receipt.generation.skillSlug!==e.skillSlug)throw new Error("Install receipt skill identity does not match the indexed slug.");let t=`quarantine_${Ge(16).toString("hex")}`,n={status:"authorized",authorizationId:`${e.purpose}_${Ge(16).toString("hex")}`,purpose:e.purpose,generation:e.lifecycle.receipt.generation,archiveSha256:e.lifecycle.receipt.archiveSha256,manifestSha256:e.lifecycle.receipt.manifestSha256},r=await t2({receipt:e.lifecycle.receipt,reasonCode:e.reasonCode,quarantineRoot:K(e.backend.paths.stateDir,"quarantine"),discoveryRoots:Qoe(e.backend,e.lifecycle.receipt.targetDir),authorizeQuarantine:async()=>n}),i=Wu({state:"quarantined",operationId:t,receipt:e.lifecycle.receipt,quarantine:r,backend:e.backend}),o;if(await Br(e.backend,s=>{let a=s.installs[e.skillSlug],l=a?Yt(a)[e.materializationId]:void 0,c=l?Jt(l):null;if(!a||!l||!c||c.operationId!==e.lifecycle.operationId)throw new Error("Local install record changed while its exact generation was quarantined.");o={...l,status:e.status,...e.reasonCode==="refunded"?{removedReason:"refunded"}:{},localLifecycle:i,savedAt:e.backend.now()},s.installs[e.skillSlug]=Fr({existing:a,skillSlug:e.skillSlug,materialization:o,backend:e.backend})}),!o)throw new Error("Local install quarantine did not commit its exact target record.");return{record:o,lifecycle:i,quarantine:r}}function Qoe(e,t){let n=new Set([Be(t)]);for(let r of Qe(e.env,e.platform,e.cwd)){n.add(r.targets.projectSkillsPath),r.targets.globalSkillsPath&&n.add(r.targets.globalSkillsPath);for(let i of[r.pathContracts.project,r.pathContracts.global]){i.preferredPath&&n.add(i.preferredPath);for(let o of[...i.compatibleReadOnlyPaths,...i.legacyReadOnlyPaths])n.add(o.path)}}return[...n]}async function ese(e,t,n){let r=T(e[0],"update requires a skill slug."),i=Qu("update",t);if(i.failure)return i.failure;let o=new URLSearchParams,s=k(t.pin);if(s&&!Th(s))return x({status:"error",reasonCode:"invalid_pin",skillSlug:r,requestedPin:s,nextAction:"update",nextStep:"Use --pin with a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --pin "${s}". Use a semver version or an external-<digest> version.`,t.json,"invalid_pin");Ke(o,"pin",s),t.dryRun&&o.set("dryRun","true");let a=await ed(t,n,r);if(a.revokedSlugs.includes(r))return A({status:"entitlement_revoked",skillSlug:r,reasonCode:"entitlement_revoked_refunded",warnings:a.warnings,nextStep:`Buy ${r} again to restore access.`},a.warnings.join(" ")||`${r} was refunded; access is revoked.`,t.json,n);let c=(t.dryRun?await lt(n):await Bi(n,r)).installs[r],u=qn(c,i);if(u.length===0&&An(c).length>0&&(i.scope||i.agent))return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:r,requestedScope:i.scope,requestedAgent:i.agent,nextAction:"installed",nextStep:"Run `skills-layer installed --json` and select one of the recorded targets."},`${r} is not installed for the requested local target.`,t.json,"local_install_target_not_found");if(u.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:r,nextAction:"update",nextStep:"Retry with --scope and --agent to update one exact materialization."},`${r} has more than one local materialization. Select the exact target to update.`,t.json,"local_install_target_selection_required");let d=u[0]&&c?gr(c,u[0]):c,p=yoe(d),m=n,h;try{h=await D(n,`/api/v1/skills/${encodeURIComponent(r)}${at(o)}`,{headers:Wo(n.apiKey)})}catch(y){if(EP(p,y))m={...n,apiKey:void 0,authBlockedMessage:void 0},h=await D(m,`/api/v1/skills/${encodeURIComponent(r)}${at(o)}`);else{if(y instanceof Z&&y.status===404&&d){let v={status:"backend_missing",reasonCode:"local_install_backend_missing",skillSlug:r,localInstall:d,installedVersion:f(d,"version")??f(d,"currentVersion"),selectedBackend:n.baseUrl,nextStep:`This skill is installed locally, but no catalog update source was found on ${n.baseUrl}. Reinstall from its source, run \`skills-layer search ${r}\`, or run \`skills-layer remove ${r}\` if you no longer need it.`};return x(v,`${r} is installed locally, but no catalog update source was found on this backend. Reinstall from its source, search for a replacement, or remove the local install.`,t.json,"local_install_backend_missing")}if(y instanceof Z)return Go(y,t.json);throw y}}if(h.catalogRefreshPending===!0||L(h.skill)&&h.skill.catalogRefreshPending===!0)return A({status:"catalog_refresh_pending",skillSlug:r,nextStep:`Publication is still refreshing. Retry skills-layer update ${r} shortly.`,localInstall:d},"Publication is still refreshing. Your installed copy is unchanged; retry update shortly.",t.json,n);let g=rse(r,h,d,n);if(s&&!tse(g,s))return x({status:"not_found",reasonCode:"pin_not_resolved",skillSlug:r,requestedPin:s,installedVersion:f(d,"version")??f(d,"currentVersion"),currentVersion:f(g,"currentVersion"),nextAction:"update",nextStep:`Choose a version returned by \`skills-layer show ${r} --json\` or omit --pin to check the latest available version.`},`${r} does not have a resolvable version for --pin ${s}.`,t.json,"pin_not_resolved");if(!t.dryRun&&d){let y=f(d,"version")??f(d,"currentVersion"),v=f(g,"latestAvailableVersion"),b=s??v;if(!!(b&&b!==y)){let _={...t,dryRun:!1,pin:void 0,version:b,scope:k(t.scope)??f(d,"scope")??"project",agent:k(t.agent)??f(d,"agent")??f(d,"targetAgent")??"codex"};return await Wa([r],_,m,p)}}return t.json?A(g,"Update check complete.",!0,n):{exitCode:0,stdout:sse(g,n),stderr:""}}function Th(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u.test(e)||/^external-[0-9A-Za-z][0-9A-Za-z._-]*$/u.test(e)}function tse(e,t){let n=[f(e,"version"),f(e,"currentVersion"),f(e,"latestVersion"),f(e,"targetVersion"),f(e,"availableVersion")].filter(Boolean),r=j(e,"update");return r&&n.push(f(r,"version"),f(r,"currentVersion"),f(r,"latestVersion"),f(r,"targetVersion"),f(r,"availableVersion")),n.some(i=>i===t)}async function nse(e,t){let n=Qu("sync",e);if(n.failure)return n.failure;let r=await ed(e,t),i=e.dryRun?await lt(t):await Bi(t),o=iz(i).filter(l=>(!n.scope||f(l,"scope")===n.scope)&&(!n.agent||mr(l).includes(n.agent))),a={status:"synced",results:await Promise.all(o.map(async l=>ise(l,t))),warnings:r.warnings};return e.json?A(a,"Local install records synced.",!0,t):{exitCode:0,stdout:ase(a,t)+r.warnings.map(l=>`
|
|
2152
|
+
`)}async function SU(e,t,n){if(xU(e)){let l=f(e,"reasonCode")??f(e,"reason")??"install_not_ready",c=f(e,"why")??f(e,"summary")??"The requested skill is not ready to install from this backend.";return x(e,`Install preview is not ready: ${c}`,t.json,l)}let r=k(t.agent)==="all"?et(n.env,n.platform,n.cwd).map(l=>({...t,agent:l.id})):[t];for(let l of r){let c=iA(n,e,"",l);if(c.status!=="ok")continue;let u=await Ya({backend:n,skillSlug:c.skillSlug,agentId:c.agent.id,scope:c.scope,flags:t});if(u)return u}let i=Object.values(n.guardianActivationReceipts??{}).map(l=>$P(n,l.agent,l.scope)),o=i.flatMap(l=>Array.isArray(l.warnings)?l.warnings:[]),s=await CU({...e,...i[0],warnings:[...Array.isArray(e.warnings)?e.warnings:[],...o]},n),a=Array.isArray(s.warnings)&&s.warnings.length>0;return Koe(s,a?"Install preview ready with warnings.":"Install preview ready.",t,n)}function Koe(e,t,n,r){return n.json?A(e,t,!0,r):{exitCode:0,stdout:dA(e,t,r),stderr:""}}async function Woe(e,t,n,r){if(xU(e)){let o=f(e,"reasonCode")??f(e,"reason")??"workspace_approval_not_ready",s=f(e,"why")??f(e,"summary")??f(e,"nextStep")??"The requested workspace approval is not ready.";return x(e,`Workspace approval preview is not ready: ${s}`,n.json,o)}let i=await CU(e,r);return n.json?A(i,t,!0,r):{exitCode:0,stdout:dA(i,t,r),stderr:""}}function xU(e){let t=f(e,"status")?.toLowerCase(),n=f(e,"reasonCode")?.toLowerCase();return t==="not_found"||t==="missing"||t==="blocked"||t==="not_ready"||n==="skill_not_found"||n==="not_found"}async function CU(e,t){let n=o=>({...e,...o,warnings:[...new Set([...Fe(e,"warnings")??[],...Fe(o,"warnings")??[]])]}),r=fM(e);if(r)return n(r);let i=f(e,"skillSlug")??f(e,"slug");if(!i)return e;try{let o=await D(t,`/api/v1/skills/${encodeURIComponent(i)}/trust`),s=fM(o);return s?n(s):e}catch{return e}}function fM(e){let t=j(e,"securityReport")??j(e,"report")??e,n=j(e,"trust")??j(t,"trust")??t,r=j(e,"securityPosture")??j(t,"securityPosture"),i=j(e,"capabilityProfile")??j(t,"capabilityProfile"),o=ie({securityScore:J(n,"securityScore")??J(n,"score")??J(e,"securityScore")??(r?J(r,"securityScore"):void 0),runtimeRisk:f(n,"runtimeRisk")??f(e,"runtimeRisk")??(r?f(r,"runtimeRisk"):void 0)??(i?f(i,"runtimeRisk"):void 0),recommendation:f(n,"recommendation")??f(e,"recommendation")??(r?f(r,"recommendation"):void 0),detectedCapabilities:Fe(n,"detectedCapabilities")??Fe(e,"detectedCapabilities")??(i?Fe(i,"detectedCapabilities"):void 0),capabilityMismatches:Fe(n,"capabilityMismatches")??Fe(e,"capabilityMismatches")??(i?Fe(i,"capabilityMismatches"):void 0),organizationPolicyDecision:f(n,"organizationPolicyDecision")??f(n,"policyDecision")??f(e,"organizationPolicyDecision")??f(e,"policyDecision")??(r?f(r,"organizationPolicyDecision"):void 0)});if(Object.keys(o).length!==0)return ie({trust:o,effectiveness:j(e,"effectiveness")??j(t,"effectiveness"),runtimeRisk:f(o,"runtimeRisk"),detectedCapabilities:Array.isArray(o.detectedCapabilities)?o.detectedCapabilities:void 0,capabilityMismatches:Array.isArray(o.capabilityMismatches)?o.capabilityMismatches:void 0,organizationPolicyDecision:f(o,"organizationPolicyDecision"),warnings:Fe(e,"warnings")??Fe(t,"warnings")??Fe(n,"warnings")})}function Va(e,t,n,r){return n?A(e,t,!0,r):{exitCode:0,stdout:dA(e,t,r),stderr:""}}function dA(e,t,n){let r=Pe(n),i=[`${r.ok("OK")} ${t}`];for(let O of Fe(e,"warnings")??[])typeof O=="string"&&i.push(`Warning: ${O}`);if(e.verificationStatus==="unverified"&&e.publiclyDiscoverable===!1){i.push("","Local installation complete \u2014 Unverified / Unscored."),e.catalogueVisibilityRequested==="public"?i.push("This skill is not publicly listed. Catalogue admission does not guarantee publication."):i.push("This is not a public listing. Private catalogue approval is separate from local installation.");let O=f(e,"reasonCode");O&&i.push(`Catalogue review reason: ${O}`)}let o=f(e,"skillSlug")??f(e,"slug"),s=f(e,"version")??f(e,"currentVersion"),a=f(e,"catalogueCandidateVersion"),l=f(e,"localProvisionalVersion"),c=f(e,"localGeneration"),u=f(e,"sourceContentDigest");(o||s||a||l||c||u)&&(i.push("",r.section("Skill")),o&&i.push(` ${r.label("Slug")}: ${o}`),a?i.push(` ${r.label("Catalogue Candidate Version")}: ${a}`):s&&i.push(` ${r.label("Version")}: ${s}`),l&&i.push(` ${r.label("Local Provisional Version")}: ${l}`),c&&i.push(` ${r.label("Local Generation")}: ${c}`),u&&i.push(` ${r.label("Source Content Digest")}: ${u}`));let d=f(e,"visibility")??f(e,"versionVisibility"),p=f(e,"catalogueVisibilityRequested")??f(e,"requestedVisibility"),m=f(e,"catalogueStatus"),h=typeof e.publiclyDiscoverable=="boolean"?e.publiclyDiscoverable:void 0,g=f(e,"publicationStatus"),y=f(e,"catalogRecord");(d||p||m||h!==void 0||g||y)&&(i.push("",r.section("Privacy")),p?i.push(` ${r.label("Catalogue Visibility Requested")}: ${p}`):d&&i.push(` ${r.label("Visibility")}: ${d}`),m&&i.push(` ${r.label("Catalogue Status")}: ${m}`),h!==void 0&&i.push(` ${r.label("Publicly Discoverable")}: ${h?"yes":"no"}`),g&&i.push(` ${r.label("Publication")}: ${g}`),y&&i.push(` ${r.label("Catalog record")}: ${y}`));let v=j(e,"materializationPlan")??j(e,"installPlan"),b=f(e,"scope")??(v?f(v,"scope"):void 0),w=f(e,"agent")??f(e,"targetAgent")??(v?f(v,"agent")??f(v,"targetAgent"):void 0),_=Array.isArray(e.materializedWrites)?e.materializedWrites.filter(L):[];if(b||w||_.length>0)if(i.push("",r.section("Local Materialization")),b&&i.push(` ${r.label("Scope")}: ${b}`),w&&i.push(` ${r.label("Agent")}: ${w}`),_.length===0)i.push(` ${r.muted("No local files were written by this command.")}`);else for(let O of _.slice(0,at)){let N=f(O,"path");N&&i.push(` ${r.arrow} ${N}`)}let C=Jle(e,r).filter(O=>!O.includes("materialized writes:"));C.length>0&&i.push("",...C);let P=ice(e);return P.length>0&&i.push("",r.section("Next"),...P.map(O=>` ${r.arrow} ${O}`)),i.join(`
|
|
2153
|
+
`)}function Zoe(e,t){let n=j(e,"trust"),r=j(e,"securityPosture"),i=j(e,"capabilityProfile"),o=n?.securityScore??n?.score??e.securityScore??r?.securityScore,s=qe(n,"runtimeRisk")??f(e,"runtimeRisk")??qe(r,"runtimeRisk")??qe(i,"runtimeRisk"),a=qe(n,"recommendation")??f(e,"recommendation")??qe(r,"recommendation"),l=qe(n,"label")??qe(n,"trust")??f(e,"trustStatus")??f(e,"trust")??qe(r,"label");if(o===void 0&&!s&&!a&&!l)return[];let c=[t.section("Trust")];return s&&c.push(` ${t.label("Runtime risk")}: ${s}`),a&&c.push(` ${t.label("Recommendation")}: ${a}`),l&&c.push(` ${t.label("Status")}: ${l}`),c.push(` ${t.label("Source")}: skills-layer trust`),c}async function ed(e,t,n){let r=[],i=[];if(!t.apiKey)return{warnings:r,revokedSlugs:i};let o=await lt(t),s=Object.entries(o.installs).filter(([l,c])=>(!n||l===n)&&c.acquisitionMode==="authenticated_account"&&(!c.acquisitionBaseUrl||c.acquisitionBaseUrl===t.baseUrl));if(!s.length)return{warnings:r,revokedSlugs:i};let a=[];try{for(let l=0;l<s.length;l+=50){let c=new URLSearchParams({slugs:s.slice(l,l+50).map(([d])=>d).join(",")}),u=await D(t,`/api/v1/me/entitlements?${c}`,{headers:re(t.apiKey,t.authBlockedMessage)});if(!Array.isArray(u.results))throw new Error("Entitlement status unavailable");a.push(...u.results.filter(L))}}catch{return{warnings:["Could not verify entitlements online; local copies were kept."],revokedSlugs:i}}for(let[l,c]of s){let u=a.find(h=>h.skillSlug===l);if(!u||u.status!=="revoked"||u.reason!=="refunded"||u.paid!==!0)continue;let d=typeof c.entitlementId=="string"&&c.entitlementId===u.entitlementId,p=typeof c.acquiredByUserId=="string"&&c.acquiredByUserId===t.config?.userId&&c.acquisitionBaseUrl===t.baseUrl;if(!d&&!p){r.push(`Kept ${l}: its receipt cannot be matched to this buyer's refunded grant.`);continue}let m=An(c);if(!m.length){r.push(`No managed agent copy found for refunded ${l}. Manually copied folders cannot be removed automatically.`);continue}for(let h of m){let g=typeof h.record.acquisitionBaseUrl=="string"?h.record:m.length===1?c:{},y=typeof g.entitlementId=="string"&&g.entitlementId===u.entitlementId,v=g.acquiredByUserId===t.config?.userId&&typeof g.acquiredByUserId=="string"&&g.acquisitionBaseUrl===t.baseUrl;if(!y&&!v){r.push(`Kept ${l}: this agent copy belongs to an unverified buyer receipt.`);continue}if(i.includes(l)||i.push(l),!(h.lifecycle?.state==="quarantined"||h.lifecycle?.state==="externally_removed")){if(!h.lifecycle||!["active","pending_activation"].includes(h.lifecycle.state)){r.push(`Kept ${l}: modified or unverifiable local copy; inspect it before removing it manually.`);continue}if(e.dryRun){r.push(`Would remove ${l} \u2014 refunded on ${String(u.revokedAt??"unknown date")}.`);continue}try{await pA({backend:t,skillSlug:l,record:gr(c,h),materializationId:h.materializationId,lifecycle:h.lifecycle,reasonCode:"refunded",purpose:"quarantine_revoked",status:"removed"}),r.push(`Removed ${l} \u2014 refunded on ${String(u.revokedAt??"unknown date")}.`)}catch{r.push(`Kept ${l}: modified or unverifiable local copy; inspect it before removing it manually.`)}}}}return{warnings:r,revokedSlugs:i}}async function Joe(e,t){let n=Qu("installed",e);if(n.failure)return n.failure;let r=await ed(e,t),i=e.dryRun?await lt(t):await Bi(t),o=iz(i).filter(s=>(!n.scope||f(s,"scope")===n.scope)&&(!n.agent||mr(s).includes(n.agent)));return A({status:"ok",results:o,warnings:r.warnings},`Found ${o.length} local install records. ${r.warnings.join(" ")}`,e.json,t,"installed")}async function Yoe(e,t,n){let r=T(e[0],"remove requires a skill slug."),i=YM("remove",t);if(i)return i;let s=(t.dryRun?await lt(n):await Bi(n,r)).installs[r];if(!s)return x({status:"not_installed",reasonCode:"local_install_not_found",skillSlug:r},`${r} is not installed locally. Run \`skills-layer installed\` or \`skills-layer sync\` to inspect local records.`,t.json,"local_install_not_found");let a=k(t.scope),l=k(t.agent),c=qn(s,{scope:a,agent:l});if(c.length>1){let g=ole({backend:n,skillSlug:r,materializations:c,scope:a,agent:l});g.length===1&&(c=g)}if(c.length===0&&An(s).length>0)return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:r,requestedScope:a,requestedAgent:l},`${r} is not installed for the requested local target.`,t.json,"local_install_target_not_found");if(c.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:r,availableTargets:c.map(g=>({materializationId:g.materializationId,scope:f(g.record,"scope"),targetAgents:mr(g.record),materializedSkillRoot:f(g.record,"materializedSkillRoot")})),nextAction:"remove",nextStep:`Run the command from the intended project folder, or retry with --scope project|global and --agent <agent> to remove one exact ${r} materialization.`},`${r} is installed in more than one local target. Select the exact target to remove.`,t.json,"local_install_target_selection_required");let u=c[0],d=u?gr(s,u):s,p=u?.lifecycle??null;if(!p){let g=oz(s);if(g){try{await Xoe({backend:n,skillSlug:r,record:s,cachedArtifact:g})}catch{return x({status:"blocked",reasonCode:"cached_artifact_remove_failed",skillSlug:r,nextAction:"install",nextStep:"The cache receipt or its immutable bundle could not be verified. Leave it unchanged and reinstall only after resolving the local cache issue."},`Skills Layer could not safely remove ${r}'s verified cache receipt.`,t.json,"cached_artifact_remove_failed")}let y={status:"removed",skillSlug:r,storageKind:"cached_artifact"};return t.json?A(y,`Removed cached ${r}.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}return x({status:"blocked",reasonCode:"exact_install_receipt_missing",skillSlug:r,nextAction:"install",nextStep:`Reinstall ${r} from an approved Artifact Format v1 export before removing or quarantining it.`},`Skills Layer cannot safely remove ${r} because its exact-generation receipt is missing or invalid.`,t.json,"exact_install_receipt_missing")}if(p.state==="quarantined"){let g={status:"removed",skillSlug:r,removedRecord:d,localLifecycle:p};return t.json?A(g,`${r} is already removed from discovery.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}if(p.state==="externally_removed"||p.state==="host_detached"){if(t.forget){let g=Vr(p.receipt),y=await tae(n,{skillSlug:r,generationId:p.receipt.generation.generationId,receiptSha256:g});return await Br(n,v=>{let b=v.installs[r];if(!b)return;let w=rz({existing:b,materializationId:u.materializationId,backend:n});w?v.installs[r]=w:delete v.installs[r]}),A({status:"forgotten",skillSlug:r,materializationId:u.materializationId,receiptSha256:g,forgottenAssociationCount:y,cloudAuthorityChanged:!1,nextAction:"installed",nextStep:"The local terminal tombstone and its terminal session evidence were removed. Cloud ownership, entitlement, workspace approval, and Trust Ledger history remain unchanged."},`${r}'s exact local tombstone was forgotten.`,t.json,n)}return A({status:p.state,skillSlug:r,tombstoneRetained:!0,localLifecycle:p,nextAction:"install",nextStep:`Reinstall ${r} to rematerialize it. Its local tombstone remains available for audit and recovery.`},`${r} is already absent from the exact local target; its recovery tombstone was retained.`,t.json,n)}if(t.forget)return x({status:"blocked",reasonCode:"guardian_forget_requires_terminal_tombstone",skillSlug:r,localLifecycle:p,nextAction:"remove",nextStep:"Use normal remove for an active installation. --forget only deletes a retained externally_removed or host_detached tombstone."},"Skills Layer only forgets an explicit terminal local tombstone.",t.json,"guardian_forget_requires_terminal_tombstone");if(p.state!=="active"&&p.state!=="pending_activation")return x({status:"blocked",reasonCode:"local_lifecycle_busy",skillSlug:r,localLifecycle:p},`${r} cannot be removed while its local lifecycle is ${p.state}.`,t.json,"local_lifecycle_busy");let m;try{m=await pA({backend:n,skillSlug:r,record:d,materializationId:u.materializationId,lifecycle:p,reasonCode:"user_removed",purpose:"quarantine_revoked",status:"removed"})}catch(g){return x({status:"blocked",reasonCode:"exact_generation_quarantine_failed",skillSlug:r,error:ve(g),nextAction:"guardian.incident.review",nextStep:"Do not run the skill. Inspect local drift or permissions, then retry removal after the exact tree is restored."},`Skills Layer could not atomically remove the exact installed generation for ${r}.`,t.json,"exact_generation_quarantine_failed")}let h={status:"removed",skillSlug:r,removedRecord:m.record,localLifecycle:m.lifecycle};return t.json?A(h,`Removed ${r}.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}async function Xoe(e){let t=e.backend.platform==="win32"?st:Lt,n=t.join(e.backend.paths.bundlesDir,e.skillSlug,e.cachedArtifact.generation.semanticVersion,encodeURIComponent(e.cachedArtifact.generation.generationId),"bundle.zip");if(t.normalize(e.cachedArtifact.bundlePath)!==t.normalize(n))throw new Error("Cached artifact path does not match its exact generation.");let r=await Xu(n);if(!r.isFile()||r.isSymbolicLink())throw new Error("Cached artifact is not a regular file.");if(`sha256:${Me("sha256").update(await Fi(n)).digest("hex")}`!==e.cachedArtifact.archiveSha256)throw new Error("Cached artifact digest does not match its receipt.");let o=K(Be(n),`.bundle.remove-${Ge(12).toString("hex")}`);await zo(n,o);try{let s=await lt(e.backend),a=s.installs[e.skillSlug],l=a?oz(a):null;if(!a||!l||l.bundlePath!==e.cachedArtifact.bundlePath||l.archiveSha256!==e.cachedArtifact.archiveSha256)throw new Error("Cached install record changed during removal.");delete s.installs[e.skillSlug],await _A(e.backend,s)}catch(s){throw await zo(o,n).catch(()=>{}),s}await We(o,{force:!0})}async function pA(e){if(e.lifecycle.receipt.generation.skillSlug!==e.skillSlug)throw new Error("Install receipt skill identity does not match the indexed slug.");let t=`quarantine_${Ge(16).toString("hex")}`,n={status:"authorized",authorizationId:`${e.purpose}_${Ge(16).toString("hex")}`,purpose:e.purpose,generation:e.lifecycle.receipt.generation,archiveSha256:e.lifecycle.receipt.archiveSha256,manifestSha256:e.lifecycle.receipt.manifestSha256},r=await t2({receipt:e.lifecycle.receipt,reasonCode:e.reasonCode,quarantineRoot:K(e.backend.paths.stateDir,"quarantine"),discoveryRoots:Qoe(e.backend,e.lifecycle.receipt.targetDir),authorizeQuarantine:async()=>n}),i=Wu({state:"quarantined",operationId:t,receipt:e.lifecycle.receipt,quarantine:r,backend:e.backend}),o;if(await Br(e.backend,s=>{let a=s.installs[e.skillSlug],l=a?Yt(a)[e.materializationId]:void 0,c=l?Jt(l):null;if(!a||!l||!c||c.operationId!==e.lifecycle.operationId)throw new Error("Local install record changed while its exact generation was quarantined.");o={...l,status:e.status,...e.reasonCode==="refunded"?{removedReason:"refunded"}:{},localLifecycle:i,savedAt:e.backend.now()},s.installs[e.skillSlug]=Fr({existing:a,skillSlug:e.skillSlug,materialization:o,backend:e.backend})}),!o)throw new Error("Local install quarantine did not commit its exact target record.");return{record:o,lifecycle:i,quarantine:r}}function Qoe(e,t){let n=new Set([Be(t)]);for(let r of et(e.env,e.platform,e.cwd)){n.add(r.targets.projectSkillsPath),r.targets.globalSkillsPath&&n.add(r.targets.globalSkillsPath);for(let i of[r.pathContracts.project,r.pathContracts.global]){i.preferredPath&&n.add(i.preferredPath);for(let o of[...i.compatibleReadOnlyPaths,...i.legacyReadOnlyPaths])n.add(o.path)}}return[...n]}async function ese(e,t,n){let r=T(e[0],"update requires a skill slug."),i=Qu("update",t);if(i.failure)return i.failure;let o=new URLSearchParams,s=k(t.pin);if(s&&!Th(s))return x({status:"error",reasonCode:"invalid_pin",skillSlug:r,requestedPin:s,nextAction:"update",nextStep:"Use --pin with a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --pin "${s}". Use a semver version or an external-<digest> version.`,t.json,"invalid_pin");Ke(o,"pin",s),t.dryRun&&o.set("dryRun","true");let a=await ed(t,n,r);if(a.revokedSlugs.includes(r))return A({status:"entitlement_revoked",skillSlug:r,reasonCode:"entitlement_revoked_refunded",warnings:a.warnings,nextStep:`Buy ${r} again to restore access.`},a.warnings.join(" ")||`${r} was refunded; access is revoked.`,t.json,n);let c=(t.dryRun?await lt(n):await Bi(n,r)).installs[r],u=qn(c,i);if(u.length===0&&An(c).length>0&&(i.scope||i.agent))return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:r,requestedScope:i.scope,requestedAgent:i.agent,nextAction:"installed",nextStep:"Run `skills-layer installed --json` and select one of the recorded targets."},`${r} is not installed for the requested local target.`,t.json,"local_install_target_not_found");if(u.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:r,nextAction:"update",nextStep:"Retry with --scope and --agent to update one exact materialization."},`${r} has more than one local materialization. Select the exact target to update.`,t.json,"local_install_target_selection_required");let d=u[0]&&c?gr(c,u[0]):c,p=yoe(d),m=n,h;try{h=await D(n,`/api/v1/skills/${encodeURIComponent(r)}${Qe(o)}`,{headers:Wo(n.apiKey)})}catch(y){if(EP(p,y))m={...n,apiKey:void 0,authBlockedMessage:void 0},h=await D(m,`/api/v1/skills/${encodeURIComponent(r)}${Qe(o)}`);else{if(y instanceof Z&&y.status===404&&d){let v={status:"backend_missing",reasonCode:"local_install_backend_missing",skillSlug:r,localInstall:d,installedVersion:f(d,"version")??f(d,"currentVersion"),selectedBackend:n.baseUrl,nextStep:`This skill is installed locally, but no catalog update source was found on ${n.baseUrl}. Reinstall from its source, run \`skills-layer search ${r}\`, or run \`skills-layer remove ${r}\` if you no longer need it.`};return x(v,`${r} is installed locally, but no catalog update source was found on this backend. Reinstall from its source, search for a replacement, or remove the local install.`,t.json,"local_install_backend_missing")}if(y instanceof Z)return Go(y,t.json);throw y}}if(h.catalogRefreshPending===!0||L(h.skill)&&h.skill.catalogRefreshPending===!0)return A({status:"catalog_refresh_pending",skillSlug:r,nextStep:`Publication is still refreshing. Retry skills-layer update ${r} shortly.`,localInstall:d},"Publication is still refreshing. Your installed copy is unchanged; retry update shortly.",t.json,n);let g=rse(r,h,d,n);if(s&&!tse(g,s))return x({status:"not_found",reasonCode:"pin_not_resolved",skillSlug:r,requestedPin:s,installedVersion:f(d,"version")??f(d,"currentVersion"),currentVersion:f(g,"currentVersion"),nextAction:"update",nextStep:`Choose a version returned by \`skills-layer show ${r} --json\` or omit --pin to check the latest available version.`},`${r} does not have a resolvable version for --pin ${s}.`,t.json,"pin_not_resolved");if(!t.dryRun&&d){let y=f(d,"version")??f(d,"currentVersion"),v=f(g,"latestAvailableVersion"),b=s??v;if(!!(b&&b!==y)){let _={...t,dryRun:!1,pin:void 0,version:b,scope:k(t.scope)??f(d,"scope")??"project",agent:k(t.agent)??f(d,"agent")??f(d,"targetAgent")??"codex"};return await Wa([r],_,m,p)}}return t.json?A(g,"Update check complete.",!0,n):{exitCode:0,stdout:sse(g,n),stderr:""}}function Th(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u.test(e)||/^external-[0-9A-Za-z][0-9A-Za-z._-]*$/u.test(e)}function tse(e,t){let n=[f(e,"version"),f(e,"currentVersion"),f(e,"latestVersion"),f(e,"targetVersion"),f(e,"availableVersion")].filter(Boolean),r=j(e,"update");return r&&n.push(f(r,"version"),f(r,"currentVersion"),f(r,"latestVersion"),f(r,"targetVersion"),f(r,"availableVersion")),n.some(i=>i===t)}async function nse(e,t){let n=Qu("sync",e);if(n.failure)return n.failure;let r=await ed(e,t),i=e.dryRun?await lt(t):await Bi(t),o=iz(i).filter(l=>(!n.scope||f(l,"scope")===n.scope)&&(!n.agent||mr(l).includes(n.agent))),a={status:"synced",results:await Promise.all(o.map(async l=>ise(l,t))),warnings:r.warnings};return e.json?A(a,"Local install records synced.",!0,t):{exitCode:0,stdout:ase(a,t)+r.warnings.map(l=>`
|
|
2154
2154
|
${l}`).join(""),stderr:""}}function rse(e,t,n,r){let i=n?f(n,"version")??f(n,"currentVersion"):void 0,o=f(t,"currentVersion")??f(t,"version"),s=n?i&&o&&i!==o?"update_available":"up_to_date":"not_installed";return ie({...t,skillSlug:f(t,"skillSlug")??f(t,"slug")??e,updateStatus:s,installedVersion:i,latestAvailableVersion:o,selectedBackend:r.baseUrl,localInstall:n,nextStep:s==="not_installed"?`Run \`skills-layer install ${e}\` to install this skill locally.`:s==="update_available"?`Run \`skills-layer install ${e}\` to apply the latest available version.`:`No update is needed for ${e}.`})}async function ise(e,t){let n=f(e,"skillSlug")??f(e,"slug");if(!n)return{...e,syncStatus:"local_only",backendStatus:"unchecked"};try{let r=await D(t,`/api/v1/skills/${encodeURIComponent(n)}`,{headers:Wo(t.apiKey)}),o=(f(r,"claimedOrigin")??f(r,"sourceKind")??f(e,"sourceKind"))==="public_source"||f(e,"sourceKind")==="external";return{...e,syncStatus:o?"source_backed":"catalog_backed",backendStatus:"found",latestAvailableVersion:f(r,"currentVersion")??f(r,"version"),catalog:ose(r)}}catch(r){return r instanceof Z&&r.status===404?{...e,syncStatus:"backend_missing",backendStatus:"not_found",selectedBackend:t.baseUrl}:{...e,syncStatus:"unchecked",backendStatus:"error",backendError:ve(r)}}}function ose(e){return ie({slug:f(e,"slug")??f(e,"skillSlug"),currentVersion:f(e,"currentVersion")??f(e,"version"),claimedOrigin:f(e,"claimedOrigin"),trust:f(e,"trust")??f(e,"publicationStatus")})}function sse(e,t){let n=Pe(t),r=f(e,"skillSlug")??f(e,"slug")??"skill",i=f(e,"updateStatus")??"checked",o=[`${n.ok("OK")} Update check complete.`,"",n.section("Update")];o.push(` ${n.label("Skill")}: ${r}`),o.push(` ${n.label("Status")}: ${i.replaceAll("_"," ")}`);let s=f(e,"installedVersion"),a=f(e,"latestAvailableVersion");s&&o.push(` ${n.label("Installed version")}: ${s}`),a&&o.push(` ${n.label("Latest available version")}: ${a}`);let l=j(e,"localInstall"),c=l?f(l,"materializedPath")??f(l,"path"):void 0,u=l?f(l,"scope"):void 0,d=l?f(l,"targetAgent")??f(l,"agent"):void 0;l&&(o.push("",n.section("Local Install")),u&&o.push(` ${n.label("Scope")}: ${u}`),d&&o.push(` ${n.label("Agent")}: ${d}`),c&&o.push(` ${n.label("Path")}: ${c}`));let p=f(e,"nextStep");return p&&o.push("",n.section("Next"),` ${n.arrow} ${p}`),o.join(`
|
|
2155
2155
|
`)}function ase(e,t){let n=Pe(t),r=[`${n.ok("OK")} Local install records synced.`,"",n.section(`Results (${e.results.length})`)];return e.results.length===0?(r.push(` ${n.muted("No local install records found.")}`),r.join(`
|
|
2156
|
-
`)):(e.results.slice(0,
|
|
2156
|
+
`)):(e.results.slice(0,at).forEach((i,o)=>{let s=f(i,"skillSlug")??f(i,"slug")??`item-${o+1}`,a=f(i,"syncStatus")??"unchecked",l=f(i,"version")??f(i,"currentVersion");r.push(`${o+1}. ${s}`),r.push(` status: ${a.replaceAll("_"," ")}${l?`; version: ${l}`:""}`),a==="backend_missing"&&r.push(` ${n.muted("Installed locally, but missing from the selected backend catalog.")}`)}),e.results.length>at&&r.push(` ${n.muted(`... ${e.results.length-at} more`)}`),r.push("",n.section("Next")),r.push(` ${n.arrow} skills-layer installed`),r.push(` ${n.arrow} skills-layer update <skill-slug>`),r.join(`
|
|
2157
2157
|
`))}function pP(e,t){let n=Pe(t);return[`${n.ok("OK")} Removed ${e}.`,"",n.section("Local Install"),` ${n.label("Skill")}: ${e}`,` ${n.label("Status")}: removed locally`,"",n.section("Next"),` ${n.arrow} skills-layer installed`,` ${n.arrow} skills-layer sync`].join(`
|
|
2158
2158
|
`)}function lse(e,t,n){let r=Pe(n),i=f(t,"version")??f(t,"currentVersion"),o=f(t,"scope");return[`${r.ok("OK")} Restore record found for ${e}.`,"",r.section("Local Install"),` ${r.label("Skill")}: ${e}`,...i?[` ${r.label("Version")}: ${i}`]:[],...o?[` ${r.label("Scope")}: ${o}`]:[],"",r.section("Next"),` ${r.arrow} skills-layer installed`,` ${r.arrow} skills-layer sync`,` ${r.arrow} skills-layer update ${e}`].join(`
|
|
2159
2159
|
`)}function cse(e){let t=f(e,"status"),n=f(e,"reasonCode");return t==="invalid_transition"||t==="forbidden"||t==="not_found"||n==="invalid_transition"}function use(e,t){let n=f(e,"why")??f(e,"reason")??f(e,"error"),r=f(e,"currentVisibility"),i=f(e,"nextVisibility")??f(e,"visibility"),o=r||i?` Current visibility: ${r??"unknown"}; requested visibility: ${i??"unknown"}.`:"",s=f(e,"nextStep")??`Run \`skills-layer creator status ${t}\` and choose a valid visibility transition.`;return`Visibility was not changed for ${t}.${o}${n?` ${n}`:""}
|
|
2160
|
-
Next step: ${s}`}async function dse(e,t,n){let r=Qu("restore",t);if(r.failure)return r.failure;let i=await lt(n),o=T(e[0],"restore requires a skill slug."),s=i.installs[o];if(!s)return x({status:"missing_record",reasonCode:"restore_record_not_found",skillSlug:o,record:null,nextAction:"installed",nextStep:`Run \`skills-layer installed\` to see local records, \`skills-layer sync\` to refresh status, or \`skills-layer search ${o}\` if you want to find a catalog/source replacement.`},`No restorable local install record was found for ${o}. Run \`skills-layer installed\`, \`skills-layer sync\`, or \`skills-layer search ${o}\` next.`,t.json,"restore_record_not_found");if(s.removedReason==="refunded"||An(s).some(_=>_.record.removedReason==="refunded")){let _=!1;try{let C=await D(n,`/api/v1/me/entitlements?${new URLSearchParams({slugs:o})}`,{headers:re(n.apiKey,n.authBlockedMessage)});_=un(C.results).some(P=>P.skillSlug===o&&P.status==="active")}catch{}if(!_)return x({status:"blocked",reasonCode:"entitlement_revoked_refunded",skillSlug:o,nextStep:`Buy ${o} again before restoring it.`},"A refunded skill cannot be restored without active access.",t.json,"entitlement_revoked_refunded")}let a=qn(s,{scope:r.scope,agent:r.agent});if(a.length===0&&An(s).length>0)return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:o,requestedScope:r.scope,requestedAgent:r.agent,nextAction:"installed",nextStep:"Run `skills-layer installed --json` and select one of the recorded quarantined targets."},`${o} has no restorable record for the requested local target.`,t.json,"local_install_target_not_found");if(a.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:o,nextAction:"restore",nextStep:"Retry with --scope and --agent to restore one exact quarantined materialization."},`${o} has more than one local materialization. Select the exact target to restore.`,t.json,"local_install_target_selection_required");let l=a[0],c=l?gr(s,l):s,u=l?.lifecycle??null;if(!u)return x({status:"blocked",reasonCode:"exact_install_receipt_missing",skillSlug:o,nextAction:"install",nextStep:`Reinstall ${o} from the approved catalog; legacy records cannot authorize an exact-generation restore.`},`Skills Layer cannot restore ${o} because its exact-generation lifecycle record is missing or invalid.`,t.json,"exact_install_receipt_missing");if(u.state!=="quarantined"||!u.quarantine)return x({status:"blocked",reasonCode:"restore_not_quarantined",skillSlug:o,localLifecycle:u,nextAction:"installed",nextStep:"Only a physically quarantined exact generation can be restored."},`${o} does not have a quarantined exact generation to restore.`,t.json,"restore_not_quarantined");let d=new URLSearchParams({version:u.receipt.generation.semanticVersion,operation:"restore",generationId:u.receipt.generation.generationId}),p=f(c,"acquisitionMode")==="anonymous_public",m;try{m=await D(n,p?`/api/v1/skills/${encodeURIComponent(o)}/export${at(d)}`:`/api/v1/me/library/${encodeURIComponent(o)}/export${at(d)}`,{headers:p?{}:re(n.apiKey,n.authBlockedMessage)})}catch(_){if(_ instanceof Z)return Go(_,t.json);throw _}if(m.restoreAuthorization===void 0)return x({status:"blocked",reasonCode:"restore_authorization_missing",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Retry after the Skills Layer API returns a fresh restoreAuthorization bound to this exact generation."},`The backend did not authorize restoration of ${o}'s exact quarantined generation.`,t.json,"restore_authorization_missing");let h=az(m.restoreAuthorization);if(!h||h.purpose!=="restore_fresh_approval"||!pse(h,u.receipt))return x({status:"blocked",reasonCode:"restore_authorization_invalid",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Do not restore. Refresh backend approval for this exact artifact generation."},`The backend returned an invalid or mismatched restore authorization for ${o}.`,t.json,"restore_authorization_invalid");let g=`restore_${Ge(16).toString("hex")}`,y=Wu({state:"restore_pending",operationId:g,receipt:u.receipt,quarantine:u.quarantine,backend:n});await Br(n,_=>{let C=_.installs[o],P=C&&l?Yt(C)[l.materializationId]:void 0,O=P?Jt(P):null;if(!C||!P||O?.operationId!==u.operationId||O.state!=="quarantined")throw new Error("Local install record changed before its exact restore reservation was created.");_.installs[o]=Fr({existing:C,skillSlug:o,materialization:{...P,localLifecycle:y,savedAt:n.now()},backend:n})});let v;try{await n2({quarantine:u.quarantine,authorizeRestore:async()=>h,finalizeRestore:async()=>{let _=!0;return await Br(n,C=>{let P=C.installs[o],O=P&&l?Yt(P)[l.materializationId]:void 0,N=O?Jt(O):null;if(!P||!O||!N||N.state!=="restore_pending"||N.operationId!==g){_=!1;return}let Q=Wu({state:"active",operationId:g,receipt:u.receipt,backend:n});v={...O,status:"restored",localLifecycle:Q,savedAt:n.now()},C.installs[o]=Fr({existing:P,skillSlug:o,materialization:v,backend:n})}),_?{status:"released",releaseId:`local_restore_${Ge(16).toString("hex")}`}:{status:"denied",reasonCode:"restore_reservation_lost"}}})}catch(_){return await Br(n,C=>{let P=C.installs[o],O=P&&l?Yt(P)[l.materializationId]:void 0,N=O?Jt(O):null;!P||!O||N?.operationId!==g||(C.installs[o]=Fr({existing:P,skillSlug:o,materialization:{...O,localLifecycle:u,savedAt:n.now()},backend:n}))}).catch(()=>{}),x({status:"blocked",reasonCode:"exact_generation_restore_failed",skillSlug:o,error:ve(_),nextAction:"restore",nextStep:"Keep the generation quarantined. Resolve local path, drift, or permission problems before retrying."},`Skills Layer could not atomically restore ${o}.`,t.json,"exact_generation_restore_failed")}if(!v)throw new Error(`Atomic restore for ${o} completed without committing its local lifecycle record.`);let b=Jt(v),w={status:"restored",skillSlug:o,record:v,localLifecycle:b};return t.json?A(w,`Restored ${o}.`,!0,n):{exitCode:0,stdout:lse(o,v,n),stderr:""}}function pse(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archiveSha256&&e.manifestSha256===t.manifestSha256}async function fse(e,t,n){let r=T(e[0],"check requires a skill slug.");return await me(`/api/v1/skills/${encodeURIComponent(r)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function mse(e,t,n){let r=T(e[0]??t.source,"import requires a source."),i=Mn("import","visibility",t.visibility,za,t,"invalid_visibility");if(i)return i;let o=await Hu(r,n.cwd);if(o)return await gse(r,o,t,n);let s=hse(r,t);if(s)return s;let a=cA(r,t,n,n.apiKey?"authenticated":"unknown"),l=await D(n,a,{method:"POST",headers:vU(r,t,n,n.apiKey?"authenticated":"unknown"),body:JSON.stringify(ie({source:r,skillSlug:k(t.skill),visibility:k(t.visibility)??Ti(r,t,n)}))});return await Ve(n.paths.importsPath,{version:1,lastImport:l,savedAt:n.now()}),A(l,"Source import submitted.",t.json,n)}async function gse(e,t,n,r){let i=k(n.skill),o=aA(e,t,i);if(!r.apiKey)return x({status:"error",reasonCode:"local_import_sign_in_required",source:e,nextAction:"login",nextStep:`Run \`skills-layer login\`, then retry \`skills-layer import ${e}\` (the same flow as \`skills-layer creator submit ${e}\`).`},"Importing a local folder submits it through your creator account, so you must sign in first. Run `skills-layer login`, then retry. Nothing was uploaded.",n.json,"local_import_sign_in_required");let s=Ih(e,o,n);if(s)return s;let a=await ju({source:e,inspection:o,requestedSkillSlug:i,mode:"import",flags:n,backend:r});if(a.kind==="failure")return a.result;let c=lA(t.files).find(d=>d.skillSlug===a.skillSlug),u=c.relativeSkillRoot==="."?e:`${e.replace(/[\\/]+$/u,"")}/${c.relativeSkillRoot}`;return k(n.version)?await AP([u],{...n,source:void 0,path:void 0,skill:c.skillSlug},r,!1):x({status:"error",nextAction:"import",nextStep:"Pass --version <semver>, for example --version 1.0.0."},"A local import requires --version <semver>.",n.json,"version_required")}function hse(e,t){try{return rr(e).kind!=="local"?null:x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:zu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or --help for import examples."},zu(e)?`Import source ${e} was not found or is not readable.`:`Import source "${e}" is not a supported source. Use a local path, GitHub/GitLab source, or URL.`,t.json,"invalid_source")}catch(n){return x({status:"error",reasonCode:"invalid_source",source:e,error:ve(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${ve(n)}`,t.json,"invalid_source")}}function zu(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}function IU(e,t,n,r){let i=Tt(r.cwd,t);return x({status:"error",reasonCode:"source_path_not_found",path:i,nextAction:e,nextStep:`Check that ${t} exists and contains a readable SKILL.md, then retry.`},`${e} source path does not exist: ${i}`,n.json,"source_path_not_found")}async function yse(e,t,n){let r=e[0];if(r==="reference"&&e[1]==="resolve"){let i=T(e[2],"source reference resolve requires a reference."),o=await D(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(i)}`);return o.status==="not_found"?x({...o,status:"not_found",reasonCode:"source_reference_not_found",reference:i,nextAction:"source.connection.start",nextStep:"Start or complete the source connection before resolving this reference."},`Source reference ${i} was not found.`,t.json,"source_reference_not_found"):A(o,"Source reference resolved.",t.json,n)}return r==="connection"?await vse(e.slice(1),t,n):R(`Unknown source command "${e.join(" ")}".`,t.json)}async function vse(e,t,n){let r=e[0];if(r==="start"){let o=k(t.provider),s=k(t.source),a=k(t.visibility),l=o?.replace(/-/gu,"_");if(l&&!MB.includes(l))return Nr("source.connection.start","provider",o??"",MB,t,"invalid_source_provider");let c=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(c.failure)return c.failure;let u=kse(o,s,a,t);if(u)return u;let d=Ft(t,["provider","source","mode","visibility","priceCents","license","provenanceIntent","discloseSource"]),p=k(t.skill);return p&&(d.requestedSkillSlug=p),await Oe("/api/v1/me/source-connections",d,t,n,"Source connection started.")}let i=T(e[1],`source connection ${r??""} requires a connection id.`);if(r==="status")return await me(`/api/v1/me/source-connections/${encodeURIComponent(i)}`,t,n,"Source connection loaded.",{authenticated:!0});if(r==="complete"){let o=Aie("source.connection.complete",t);return o||await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/complete`,Ft(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed.")}return r==="cancel"?await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/cancel`,{},t,n,"Source connection cancelled."):r==="revoke"?await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/revoke`,{},t,n,"Source connection revoked."):R(`Unknown source connection command "${r??""}".`,t.json)}function kse(e,t,n,r){if(n){let i=uc(n);if(!i||!za.includes(i))return x({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:za,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${za.join(", ")}.`,r.json,"invalid_visibility")}if(!e||!t)return null;try{let i=rr(t);if((e==="github"||e==="gitlab")&&i.kind!==e)return fP(e,t,r);if(e==="domain"){let o=new URL(t);if(o.protocol!=="https:"||!o.hostname)return fP(e,t,r)}}catch{return fP(e,t,r)}return null}function fP(e,t,n){return x({status:"error",reasonCode:"invalid_source",provider:e,source:t,nextAction:"source.connection.start",nextStep:e==="github"?"Use a GitHub source such as https://github.com/OWNER/REPO or github:OWNER/REPO.":e==="gitlab"?"Use a GitLab source such as https://gitlab.com/GROUP/REPO or gitlab:GROUP/REPO.":"Use a valid source URL or provider-specific source."},`Invalid ${e} source "${t}".`,n.json,"invalid_source")}async function wse(e,t,n){if(e[0]!=="request")return R(`Unknown approval command "${e[0]??""}".`,t.json);let r=e[1];if(r!=="status"&&r!=="complete")return R("approval request requires `status <approval-request-id>` or `complete <approval-request-id> --decision <approved|denied>`.",t.json);let i=T(e[2],`approval request ${r??""} requires an approval id.`);if(r==="status")return await me(`/api/v1/me/approvals/${encodeURIComponent(i)}`,t,n,"Approval status loaded.",{authenticated:!0});let o=T(t.decision,"approval request complete requires --decision."),s=Mn("approval.request.complete","decision",o,yie,t,"invalid_decision");return s||await Oe(`/api/v1/me/approvals/${encodeURIComponent(i)}/complete`,ie({decision:o,evidence:ln(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed.")}async function bse(e,t,n){let r=e[0]??"list";if(r==="list"){let o=await D(n,"/api/v1/me/workspaces",{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,_se(o,n),"Available workspaces loaded.",t.json,n)}if(r==="current"){let o=await D(n,"/api/v1/me/working-mode",{headers:re(n.apiKey,n.authBlockedMessage)});return await ji(n,o),cn(o,Sse(o,n),"Selected workspace loaded.",t.json,n)}if(r==="select"||r==="use"){let o=T(e[1],"workspace select requires personal or a workspace id."),s=await D(n,"/api/v1/me/working-modes",{headers:re(n.apiKey,n.authBlockedMessage)}),a=(Array.isArray(s.modes)?s.modes:[]).filter(L),l=o.toLowerCase()==="personal",c=a.filter(m=>l?f(m,"type")==="personal"&&f(m,"modeId")==="personal":f(m,"type")==="enterprise_workspace"&&f(m,"workspaceId")===o);if(c.length===0)return x({status:"not_found_or_forbidden",reasonCode:"workspace_working_mode_not_found",...l?{selection:"personal"}:{workspaceId:o},nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list`, then select Personal or an exact workspace id shown there."},l?"Personal is not available for this account.":`Workspace ${o} was not found in your Enterprise workspace access.`,t.json,"workspace_working_mode_not_found");if(c.length>1)return x({status:"ambiguous_workspace",reasonCode:"workspace_working_mode_ambiguous",workspaceId:o,nextAction:"workspace.list",nextStep:"Workspace ids should be unique. Run `skills-layer workspace list` and use the exact workspace id shown there."},`Workspace ${o} matched more than one Enterprise workspace.`,t.json,"workspace_working_mode_ambiguous");let u=f(c[0],"modeId");if(!u)return x({status:"error",reasonCode:"workspace_working_mode_invalid",workspaceId:o,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` and retry with Personal or an exact selectable workspace id."},`Workspace ${o} is missing its selection identifier.`,t.json,"workspace_working_mode_invalid");let d=await D(n,"/api/v1/me/working-mode",{method:"PUT",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({modeId:u})});await ji(n,d);let p=f(c[0],"label");return A(d,l?"Selected workspace: Personal.":`Selected workspace: ${p?`${p} (${o})`:o}.`,t.json,n)}if(!["request","approve","reject","skills","guide"].includes(r))return R(`Unknown workspace command "${r}".`,t.json);let i=T(e[1],`workspace ${r} requires a workspace id.`);if(r==="request"||r==="approve"||r==="reject"){let o=T(e[2],`workspace ${r} requires a skill slug.`);try{if(r==="request")return await Oe(`/api/v1/workspaces/${encodeURIComponent(i)}/skill-requests`,{skillSlug:o,reason:k(t.reason)},t,n,"Workspace skill request captured.");if(r==="approve"){let s=await rU(n,`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/approve`,{},t);return fe(s)?s:A(s,"Workspace skill approval evaluated.",t.json,n)}return await Oe(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/${r}`,{},t,n,"Workspace skill rejected.")}catch(s){if(s instanceof Z&&(s.status===403||s.status===404))return r==="reject"&&gM(s)?mM(i,o,t):r==="approve"&&xse(s)?Cse(i,o,t,s):mP(i,t);throw s}}if(r==="skills")try{return await me(`/api/v1/workspaces/${encodeURIComponent(i)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0})}catch(o){if(o instanceof Z&&(o.status===403||o.status===404))return mP(i,t);throw o}if(r==="guide"){let o=T(e[2],"workspace guide requires a skill slug.");try{return await me(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}catch(s){if(s instanceof Z&&s.status===404)return gM(s)?mM(i,o,t):mP(i,t);throw s}}return R(`Unknown workspace command "${r}".`,t.json)}function _se(e,t){let n=Pe(t),r=Array.isArray(e.results)?e.results.filter(L):[],i=[`${n.ok("OK")} Available workspaces loaded.`,"",n.section(`Available workspaces (${r.length+1})`),"1. Personal",` ${n.label("Type")}: Personal`];return r.forEach((o,s)=>{i.push(`${s+2}. ${f(o,"name")??"Unnamed workspace"}`),i.push(` ${n.label("ID")}: ${f(o,"workspaceId")??"unknown"}`),i.push(` ${n.label("Enterprise ID")}: ${f(o,"enterpriseId")??"unknown"}`),i.push(` ${n.label("Status")}: ${jt(f(o,"status")??"unknown")}`)}),i.push("",n.section("Next"),` ${n.arrow} skills-layer workspace select personal`,` ${n.arrow} skills-layer workspace select <workspace-id>`),i.join(`
|
|
2160
|
+
Next step: ${s}`}async function dse(e,t,n){let r=Qu("restore",t);if(r.failure)return r.failure;let i=await lt(n),o=T(e[0],"restore requires a skill slug."),s=i.installs[o];if(!s)return x({status:"missing_record",reasonCode:"restore_record_not_found",skillSlug:o,record:null,nextAction:"installed",nextStep:`Run \`skills-layer installed\` to see local records, \`skills-layer sync\` to refresh status, or \`skills-layer search ${o}\` if you want to find a catalog/source replacement.`},`No restorable local install record was found for ${o}. Run \`skills-layer installed\`, \`skills-layer sync\`, or \`skills-layer search ${o}\` next.`,t.json,"restore_record_not_found");if(s.removedReason==="refunded"||An(s).some(_=>_.record.removedReason==="refunded")){let _=!1;try{let C=await D(n,`/api/v1/me/entitlements?${new URLSearchParams({slugs:o})}`,{headers:re(n.apiKey,n.authBlockedMessage)});_=un(C.results).some(P=>P.skillSlug===o&&P.status==="active")}catch{}if(!_)return x({status:"blocked",reasonCode:"entitlement_revoked_refunded",skillSlug:o,nextStep:`Buy ${o} again before restoring it.`},"A refunded skill cannot be restored without active access.",t.json,"entitlement_revoked_refunded")}let a=qn(s,{scope:r.scope,agent:r.agent});if(a.length===0&&An(s).length>0)return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:o,requestedScope:r.scope,requestedAgent:r.agent,nextAction:"installed",nextStep:"Run `skills-layer installed --json` and select one of the recorded quarantined targets."},`${o} has no restorable record for the requested local target.`,t.json,"local_install_target_not_found");if(a.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:o,nextAction:"restore",nextStep:"Retry with --scope and --agent to restore one exact quarantined materialization."},`${o} has more than one local materialization. Select the exact target to restore.`,t.json,"local_install_target_selection_required");let l=a[0],c=l?gr(s,l):s,u=l?.lifecycle??null;if(!u)return x({status:"blocked",reasonCode:"exact_install_receipt_missing",skillSlug:o,nextAction:"install",nextStep:`Reinstall ${o} from the approved catalog; legacy records cannot authorize an exact-generation restore.`},`Skills Layer cannot restore ${o} because its exact-generation lifecycle record is missing or invalid.`,t.json,"exact_install_receipt_missing");if(u.state!=="quarantined"||!u.quarantine)return x({status:"blocked",reasonCode:"restore_not_quarantined",skillSlug:o,localLifecycle:u,nextAction:"installed",nextStep:"Only a physically quarantined exact generation can be restored."},`${o} does not have a quarantined exact generation to restore.`,t.json,"restore_not_quarantined");let d=new URLSearchParams({version:u.receipt.generation.semanticVersion,operation:"restore",generationId:u.receipt.generation.generationId}),p=f(c,"acquisitionMode")==="anonymous_public",m;try{m=await D(n,p?`/api/v1/skills/${encodeURIComponent(o)}/export${Qe(d)}`:`/api/v1/me/library/${encodeURIComponent(o)}/export${Qe(d)}`,{headers:p?{}:re(n.apiKey,n.authBlockedMessage)})}catch(_){if(_ instanceof Z)return Go(_,t.json);throw _}if(m.restoreAuthorization===void 0)return x({status:"blocked",reasonCode:"restore_authorization_missing",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Retry after the Skills Layer API returns a fresh restoreAuthorization bound to this exact generation."},`The backend did not authorize restoration of ${o}'s exact quarantined generation.`,t.json,"restore_authorization_missing");let h=az(m.restoreAuthorization);if(!h||h.purpose!=="restore_fresh_approval"||!pse(h,u.receipt))return x({status:"blocked",reasonCode:"restore_authorization_invalid",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Do not restore. Refresh backend approval for this exact artifact generation."},`The backend returned an invalid or mismatched restore authorization for ${o}.`,t.json,"restore_authorization_invalid");let g=`restore_${Ge(16).toString("hex")}`,y=Wu({state:"restore_pending",operationId:g,receipt:u.receipt,quarantine:u.quarantine,backend:n});await Br(n,_=>{let C=_.installs[o],P=C&&l?Yt(C)[l.materializationId]:void 0,O=P?Jt(P):null;if(!C||!P||O?.operationId!==u.operationId||O.state!=="quarantined")throw new Error("Local install record changed before its exact restore reservation was created.");_.installs[o]=Fr({existing:C,skillSlug:o,materialization:{...P,localLifecycle:y,savedAt:n.now()},backend:n})});let v;try{await n2({quarantine:u.quarantine,authorizeRestore:async()=>h,finalizeRestore:async()=>{let _=!0;return await Br(n,C=>{let P=C.installs[o],O=P&&l?Yt(P)[l.materializationId]:void 0,N=O?Jt(O):null;if(!P||!O||!N||N.state!=="restore_pending"||N.operationId!==g){_=!1;return}let Q=Wu({state:"active",operationId:g,receipt:u.receipt,backend:n});v={...O,status:"restored",localLifecycle:Q,savedAt:n.now()},C.installs[o]=Fr({existing:P,skillSlug:o,materialization:v,backend:n})}),_?{status:"released",releaseId:`local_restore_${Ge(16).toString("hex")}`}:{status:"denied",reasonCode:"restore_reservation_lost"}}})}catch(_){return await Br(n,C=>{let P=C.installs[o],O=P&&l?Yt(P)[l.materializationId]:void 0,N=O?Jt(O):null;!P||!O||N?.operationId!==g||(C.installs[o]=Fr({existing:P,skillSlug:o,materialization:{...O,localLifecycle:u,savedAt:n.now()},backend:n}))}).catch(()=>{}),x({status:"blocked",reasonCode:"exact_generation_restore_failed",skillSlug:o,error:ve(_),nextAction:"restore",nextStep:"Keep the generation quarantined. Resolve local path, drift, or permission problems before retrying."},`Skills Layer could not atomically restore ${o}.`,t.json,"exact_generation_restore_failed")}if(!v)throw new Error(`Atomic restore for ${o} completed without committing its local lifecycle record.`);let b=Jt(v),w={status:"restored",skillSlug:o,record:v,localLifecycle:b};return t.json?A(w,`Restored ${o}.`,!0,n):{exitCode:0,stdout:lse(o,v,n),stderr:""}}function pse(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archiveSha256&&e.manifestSha256===t.manifestSha256}async function fse(e,t,n){let r=T(e[0],"check requires a skill slug.");return await me(`/api/v1/skills/${encodeURIComponent(r)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function mse(e,t,n){let r=T(e[0]??t.source,"import requires a source."),i=Mn("import","visibility",t.visibility,za,t,"invalid_visibility");if(i)return i;let o=await Hu(r,n.cwd);if(o)return await gse(r,o,t,n);let s=hse(r,t);if(s)return s;let a=cA(r,t,n,n.apiKey?"authenticated":"unknown"),l=await D(n,a,{method:"POST",headers:vU(r,t,n,n.apiKey?"authenticated":"unknown"),body:JSON.stringify(ie({source:r,skillSlug:k(t.skill),visibility:k(t.visibility)??Ti(r,t,n)}))});return await Ve(n.paths.importsPath,{version:1,lastImport:l,savedAt:n.now()}),A(l,"Source import submitted.",t.json,n)}async function gse(e,t,n,r){let i=k(n.skill),o=aA(e,t,i);if(!r.apiKey)return x({status:"error",reasonCode:"local_import_sign_in_required",source:e,nextAction:"login",nextStep:`Run \`skills-layer login\`, then retry \`skills-layer import ${e}\` (the same flow as \`skills-layer creator submit ${e}\`).`},"Importing a local folder submits it through your creator account, so you must sign in first. Run `skills-layer login`, then retry. Nothing was uploaded.",n.json,"local_import_sign_in_required");let s=Ih(e,o,n);if(s)return s;let a=await ju({source:e,inspection:o,requestedSkillSlug:i,mode:"import",flags:n,backend:r});if(a.kind==="failure")return a.result;let c=lA(t.files).find(d=>d.skillSlug===a.skillSlug),u=c.relativeSkillRoot==="."?e:`${e.replace(/[\\/]+$/u,"")}/${c.relativeSkillRoot}`;return k(n.version)?await AP([u],{...n,source:void 0,path:void 0,skill:c.skillSlug},r,!1):x({status:"error",nextAction:"import",nextStep:"Pass --version <semver>, for example --version 1.0.0."},"A local import requires --version <semver>.",n.json,"version_required")}function hse(e,t){try{return rr(e).kind!=="local"?null:x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:zu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or --help for import examples."},zu(e)?`Import source ${e} was not found or is not readable.`:`Import source "${e}" is not a supported source. Use a local path, GitHub/GitLab source, or URL.`,t.json,"invalid_source")}catch(n){return x({status:"error",reasonCode:"invalid_source",source:e,error:ve(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${ve(n)}`,t.json,"invalid_source")}}function zu(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}function IU(e,t,n,r){let i=Tt(r.cwd,t);return x({status:"error",reasonCode:"source_path_not_found",path:i,nextAction:e,nextStep:`Check that ${t} exists and contains a readable SKILL.md, then retry.`},`${e} source path does not exist: ${i}`,n.json,"source_path_not_found")}async function yse(e,t,n){let r=e[0];if(r==="reference"&&e[1]==="resolve"){let i=T(e[2],"source reference resolve requires a reference."),o=await D(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(i)}`);return o.status==="not_found"?x({...o,status:"not_found",reasonCode:"source_reference_not_found",reference:i,nextAction:"source.connection.start",nextStep:"Start or complete the source connection before resolving this reference."},`Source reference ${i} was not found.`,t.json,"source_reference_not_found"):A(o,"Source reference resolved.",t.json,n)}return r==="connection"?await vse(e.slice(1),t,n):R(`Unknown source command "${e.join(" ")}".`,t.json)}async function vse(e,t,n){let r=e[0];if(r==="start"){let o=k(t.provider),s=k(t.source),a=k(t.visibility),l=o?.replace(/-/gu,"_");if(l&&!MB.includes(l))return Nr("source.connection.start","provider",o??"",MB,t,"invalid_source_provider");let c=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(c.failure)return c.failure;let u=kse(o,s,a,t);if(u)return u;let d=Ft(t,["provider","source","mode","visibility","priceCents","license","provenanceIntent","discloseSource"]),p=k(t.skill);return p&&(d.requestedSkillSlug=p),await Oe("/api/v1/me/source-connections",d,t,n,"Source connection started.")}let i=T(e[1],`source connection ${r??""} requires a connection id.`);if(r==="status")return await me(`/api/v1/me/source-connections/${encodeURIComponent(i)}`,t,n,"Source connection loaded.",{authenticated:!0});if(r==="complete"){let o=Aie("source.connection.complete",t);return o||await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/complete`,Ft(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed.")}return r==="cancel"?await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/cancel`,{},t,n,"Source connection cancelled."):r==="revoke"?await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/revoke`,{},t,n,"Source connection revoked."):R(`Unknown source connection command "${r??""}".`,t.json)}function kse(e,t,n,r){if(n){let i=uc(n);if(!i||!za.includes(i))return x({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:za,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${za.join(", ")}.`,r.json,"invalid_visibility")}if(!e||!t)return null;try{let i=rr(t);if((e==="github"||e==="gitlab")&&i.kind!==e)return fP(e,t,r);if(e==="domain"){let o=new URL(t);if(o.protocol!=="https:"||!o.hostname)return fP(e,t,r)}}catch{return fP(e,t,r)}return null}function fP(e,t,n){return x({status:"error",reasonCode:"invalid_source",provider:e,source:t,nextAction:"source.connection.start",nextStep:e==="github"?"Use a GitHub source such as https://github.com/OWNER/REPO or github:OWNER/REPO.":e==="gitlab"?"Use a GitLab source such as https://gitlab.com/GROUP/REPO or gitlab:GROUP/REPO.":"Use a valid source URL or provider-specific source."},`Invalid ${e} source "${t}".`,n.json,"invalid_source")}async function wse(e,t,n){if(e[0]!=="request")return R(`Unknown approval command "${e[0]??""}".`,t.json);let r=e[1];if(r!=="status"&&r!=="complete")return R("approval request requires `status <approval-request-id>` or `complete <approval-request-id> --decision <approved|denied>`.",t.json);let i=T(e[2],`approval request ${r??""} requires an approval id.`);if(r==="status")return await me(`/api/v1/me/approvals/${encodeURIComponent(i)}`,t,n,"Approval status loaded.",{authenticated:!0});let o=T(t.decision,"approval request complete requires --decision."),s=Mn("approval.request.complete","decision",o,yie,t,"invalid_decision");return s||await Oe(`/api/v1/me/approvals/${encodeURIComponent(i)}/complete`,ie({decision:o,evidence:ln(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed.")}async function bse(e,t,n){let r=e[0]??"list";if(r==="list"){let o=await D(n,"/api/v1/me/workspaces",{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,_se(o,n),"Available workspaces loaded.",t.json,n)}if(r==="current"){let o=await D(n,"/api/v1/me/working-mode",{headers:re(n.apiKey,n.authBlockedMessage)});return await ji(n,o),cn(o,Sse(o,n),"Selected workspace loaded.",t.json,n)}if(r==="select"||r==="use"){let o=T(e[1],"workspace select requires personal or a workspace id."),s=await D(n,"/api/v1/me/working-modes",{headers:re(n.apiKey,n.authBlockedMessage)}),a=(Array.isArray(s.modes)?s.modes:[]).filter(L),l=o.toLowerCase()==="personal",c=a.filter(m=>l?f(m,"type")==="personal"&&f(m,"modeId")==="personal":f(m,"type")==="enterprise_workspace"&&f(m,"workspaceId")===o);if(c.length===0)return x({status:"not_found_or_forbidden",reasonCode:"workspace_working_mode_not_found",...l?{selection:"personal"}:{workspaceId:o},nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list`, then select Personal or an exact workspace id shown there."},l?"Personal is not available for this account.":`Workspace ${o} was not found in your Enterprise workspace access.`,t.json,"workspace_working_mode_not_found");if(c.length>1)return x({status:"ambiguous_workspace",reasonCode:"workspace_working_mode_ambiguous",workspaceId:o,nextAction:"workspace.list",nextStep:"Workspace ids should be unique. Run `skills-layer workspace list` and use the exact workspace id shown there."},`Workspace ${o} matched more than one Enterprise workspace.`,t.json,"workspace_working_mode_ambiguous");let u=f(c[0],"modeId");if(!u)return x({status:"error",reasonCode:"workspace_working_mode_invalid",workspaceId:o,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` and retry with Personal or an exact selectable workspace id."},`Workspace ${o} is missing its selection identifier.`,t.json,"workspace_working_mode_invalid");let d=await D(n,"/api/v1/me/working-mode",{method:"PUT",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({modeId:u})});await ji(n,d);let p=f(c[0],"label");return A(d,l?"Selected workspace: Personal.":`Selected workspace: ${p?`${p} (${o})`:o}.`,t.json,n)}if(!["request","approve","reject","skills","guide"].includes(r))return R(`Unknown workspace command "${r}".`,t.json);let i=T(e[1],`workspace ${r} requires a workspace id.`);if(r==="request"||r==="approve"||r==="reject"){let o=T(e[2],`workspace ${r} requires a skill slug.`);try{if(r==="request")return await Oe(`/api/v1/workspaces/${encodeURIComponent(i)}/skill-requests`,{skillSlug:o,reason:k(t.reason)},t,n,"Workspace skill request captured.");if(r==="approve"){let s=await rU(n,`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/approve`,{},t);return fe(s)?s:A(s,"Workspace skill approval evaluated.",t.json,n)}return await Oe(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/${r}`,{},t,n,"Workspace skill rejected.")}catch(s){if(s instanceof Z&&(s.status===403||s.status===404))return r==="reject"&&gM(s)?mM(i,o,t):r==="approve"&&xse(s)?Cse(i,o,t,s):mP(i,t);throw s}}if(r==="skills")try{return await me(`/api/v1/workspaces/${encodeURIComponent(i)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0})}catch(o){if(o instanceof Z&&(o.status===403||o.status===404))return mP(i,t);throw o}if(r==="guide"){let o=T(e[2],"workspace guide requires a skill slug.");try{return await me(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}catch(s){if(s instanceof Z&&s.status===404)return gM(s)?mM(i,o,t):mP(i,t);throw s}}return R(`Unknown workspace command "${r}".`,t.json)}function _se(e,t){let n=Pe(t),r=Array.isArray(e.results)?e.results.filter(L):[],i=[`${n.ok("OK")} Available workspaces loaded.`,"",n.section(`Available workspaces (${r.length+1})`),"1. Personal",` ${n.label("Type")}: Personal`];return r.forEach((o,s)=>{i.push(`${s+2}. ${f(o,"name")??"Unnamed workspace"}`),i.push(` ${n.label("ID")}: ${f(o,"workspaceId")??"unknown"}`),i.push(` ${n.label("Enterprise ID")}: ${f(o,"enterpriseId")??"unknown"}`),i.push(` ${n.label("Status")}: ${jt(f(o,"status")??"unknown")}`)}),i.push("",n.section("Next"),` ${n.arrow} skills-layer workspace select personal`,` ${n.arrow} skills-layer workspace select <workspace-id>`),i.join(`
|
|
2161
2161
|
`)}function Sse(e,t){let n=Pe(t),r=L(e.mode)?e.mode:void 0,i=r?f(r,"type"):void 0,o=f(e,"selectedModeId"),s=[`${n.ok("OK")} Selected workspace loaded.`,""];return i==="personal"||o==="personal"?(s.push(n.section("Selected workspace: Personal")),s.join(`
|
|
2162
2162
|
`)):r?(s.push(n.section(`Selected workspace: ${f(r,"label")??f(r,"name")??"Enterprise workspace"}`)),s.push(` ${n.label("Workspace ID")}: ${f(r,"workspaceId")??"unknown"}`),s.push(` ${n.label("Enterprise ID")}: ${f(r,"enterpriseId")??"unknown"}`),s.join(`
|
|
2163
2163
|
`)):(s.push(n.section("Selected workspace"),` ${n.muted("No workspace is currently selected.")}`),s.join(`
|
|
2164
|
-
`))}function mP(e,t){return x({status:"not_found_or_forbidden",reasonCode:"workspace_not_found_or_forbidden",workspaceId:e,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` to find a workspace you can access, then retry with that workspace id."},`Workspace ${e} was not found or you do not have access. Run \`skills-layer workspace list\` to inspect accessible workspaces.`,t.json,"workspace_not_found_or_forbidden")}function mM(e,t,n){let r={status:"approval_not_found",reasonCode:"workspace_skill_approval_not_found",workspaceId:e,skillSlug:t,nextAction:"workspace.approve",nextStep:`Run \`skills-layer workspace approve ${e} ${t}\` first, then run \`skills-layer workspace guide ${e} ${t}\` after the approval exists.`};return x(r,`Workspace approval not found for ${t}. Run \`skills-layer workspace approve ${e} ${t}\` first.`,n.json,"workspace_skill_approval_not_found")}function gM(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="workspace_skill_approval_not_found"||r.includes("workspace")&&r.includes("approval")&&r.includes("not found")}function xse(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="skill_not_found"||r.includes("skill")&&r.includes("not found")}function Cse(e,t,n,r){let i=r.details??{},o={status:"not_found",reasonCode:"skill_not_found",workspaceId:e,skillSlug:t,nextAction:"search",nextStep:f(i,"nextStep")??`Run \`skills-layer search ${t}\` to find the public skill before approving it for workspace ${e}.`};return x(o,`Skill ${t} was not found. Run \`skills-layer search ${t}\` before approving it for the workspace.`,n.json,"skill_not_found")}async function Ise(e,t,n){let r=T(e[0],"buy requires a skill slug."),i=Tie(t);if(i.failure)return i.failure;if(k(t.workspace))return x({reasonCode:"invalid_input"},"buy does not support --workspace; use skills-layer enterprise skill buy <enterprise-id> <skill-slug>.",t.json,"invalid_input");let o=await nA(n,{skillSlug:r,paymentMethod:i.value},t,"/api/v1/buy");if(fe(o))return o;if(o.status==="already_owned")return A(o,`You already own ${r}. Run \`skills-layer install ${r}\` to install or update it.`,t.json,n);if(t.noOpen&&o.status==="checkout_required"&&typeof o.checkoutUrl=="string")return A({...o,nextAction:"open_checkout_url",nextStep:`Open ${o.checkoutUrl} to complete payment, then run skills-layer install ${r}.`},`Payment is required for ${r}.`,t.json,n);if(t.json||t.noOpen||o.status!=="checkout_required"||typeof o.checkoutUrl!="string"||typeof o.purchaseId!="string")return A(o,`Purchase flow started for ${r}.`,t.json,n);n.emitInfo(`Opening checkout for ${r}. Complete the payment in your browser, then come back here.`),await n.openUrl(o.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${o.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let a=await Hae(o.purchaseId,n);return fe(a)?a:a.status!=="succeeded"?A({...o,purchaseStatus:a.status},`Checkout is still ${a.status} for ${r}. You can rerun install after payment reconciliation completes.`,t.json,n):(n.emitInfo("Payment confirmed. Continuing with install."),await Wa([r],t,n,{origin:"post_purchase",fallbackPolicy:"account_required"}))}async function Pse(e,t,n){let r=e[0]??"list";if(r==="list")return await me("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(r==="spending")return await me("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let i=T(e[1],`purchases ${r} requires a purchase id.`);if(r==="status")return await me(`/api/v1/purchases/${encodeURIComponent(i)}`,t,n,"Purchase status loaded.",{authenticated:!0});if(r==="invoice")return await me(`/api/v1/purchases/${encodeURIComponent(i)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0});if(r==="refund-quote"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund-quote`,{headers:re(n.apiKey,n.authBlockedMessage)}),s=L(o.quote)?o.quote:o,a=l=>typeof l=="number"?`USD ${(l/100).toFixed(2)}`:"unavailable";return A(o,`Refundable: ${a(s.refundableAmountCents)}. Non-refundable: ${a(s.nonRefundableAmountCents)}. Refund window ends: ${String(s.refundWindowEndsAt??"unavailable")}.`,t.json,n)}if(r==="refund"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund`,{method:"POST",headers:V(n.apiKey),body:JSON.stringify(Ft(t,["reason"]))}),s=o.status==="refunded"?await ed(t,n):{warnings:[]};return A({...o,warnings:[...s.warnings,"Manually copied folders cannot be removed automatically; other machines check on sync, installed or update."]},o.status==="refunded"?"Refund completed.":"Refund requested.",t.json,n)}return R(`Unknown purchases command "${r}".`,t.json)}function PU(e,t,n,r){let i=typeof e.amountCents=="number"?` (USD ${(e.amountCents/100).toFixed(2)})`:"";return A({...e,status:"action_required",reasonCode:"purchase_required",nextAction:"buy",nextStep:`skills-layer buy ${t}`},`Purchase required${i}. Run \`skills-layer buy ${t}\`.`,n.json,r)}async function Ase(e,t,n){let r=e[0];if(r==="search"){let i=new URLSearchParams;return Ke(i,"query",e.slice(1).join(" ").trim()||k(t.query)),Ke(i,"limit",k(t.limit)),await me(`/api/v1/me/search${at(i)}`,t,n,"Authenticated library search complete.",{authenticated:!0})}if(r==="add"){let i=T(e[1],"library add requires a skill slug."),o=await nA(n,{skillSlug:i},t);return fe(o)?o:o.status==="purchase_required"?PU(o,i,t,n):A(o,"Skill added to library.",t.json,n)}return R(`Unknown library command "${r}".`,t.json)}async function Rse(e,t,n){let r=T(e[0],"export requires a skill slug.");if(t.showUrl&&k(t.output))return x({status:"error",reasonCode:"conflicting_export_output",nextAction:"export",nextStep:"Use either --show-url to inspect the signed URL or --output <file> to download the bundle, not both."},"export cannot use --show-url and --output together.",t.json,"conflicting_export_output");let i=new URLSearchParams,o=k(t.version);if(o&&!Th(o))return eA("export",o,t);Ke(i,"version",o);let s=await D(n,`/api/v1/me/library/${encodeURIComponent(r)}/export${at(i)}`,{headers:re(n.apiKey,n.authBlockedMessage)}),a=k(t.output);if(a){let l=await xh({backend:n,exportResult:s,flags:t,skillSlug:r});if(fe(l))return l;let c=Tt(n.cwd,a);await IA(c,l.bytes);let u={...s};return delete u.downloadUrl,A({...u,archiveSha256:l.archiveSha256,archiveSha256Meaning:"artifact_v1_exact_zip_bytes_sha256",downloadedArchiveSha256:l.archiveBytesSha256,downloadedFileSha256:l.archiveBytesSha256,archiveHashFormat:l.archiveHashFormat,generationId:l.envelope.generation.generationId,manifestSha256:l.envelope.manifest.sha256,outputPath:c,downloaded:!0},`Exported ${r} to ${c}. Downloaded file SHA-256: ${l.archiveBytesSha256}.`,t.json,n)}return A(s,a?`Exported ${r} to ${a}.`:"Export prepared.",t.json,n)}async function hM(e,t,n,r){if(e==="show"){let a=t[0]?.trim(),l=a?`?skillSlug=${encodeURIComponent(a)}`:"";return await me(`/api/v1/me/library/reviews${l}`,n,r,"Reviews loaded.",{authenticated:!0})}let i=T(t[0],"add-review requires a skill slug."),o=T(n.rating,"add-review requires --rating.");if(!/^[1-5]$/u.test(o))return x({status:"error",reasonCode:"invalid_rating",rating:o,acceptedValues:["1","2","3","4","5"],nextAction:"add-review",nextStep:"Use --rating with a whole number from 1 to 5."},`Invalid review rating "${o}". Use a whole number from 1 to 5.`,n.json,"invalid_rating");let s=Ft(n,["rating","feedback"]);if(typeof n.evalSummary=="string"){let a=await ke(qo(r.cwd,n.evalSummary));if(a===null)return x({status:"error",reasonCode:"invalid_eval_summary_file",path:n.evalSummary,nextAction:"add-review",nextStep:"Pass --eval-summary with a readable JSON redacted eval summary envelope."},`Could not read eval summary JSON from ${n.evalSummary}.`,n.json,"invalid_eval_summary_file");s.evalSummary=a}return await Oe(`/api/v1/me/library/${encodeURIComponent(i)}/review`,s,n,r,"Review added.")}async function yM(e,t,n,r){let i=T(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);if(e==="show")return await me(`/api/v1/me/library/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});T(n.message,"add-issue requires --message.");let o=Mn("add-issue","issueType",n.issueType,hie,n,"invalid_issue_type","issue-type");return o||await Oe(`/api/v1/me/library/${encodeURIComponent(i)}/report-issue`,Ft(n,["issueType","message"]),n,r,"Issue reported.")}async function Ese(e,t,n){let r=e[0];if(r==="hook"){let i=e[1];if(i==="install")return await EU(t,n);if(i==="status")return await Mse(t,n);if(i==="run"){let o=await qse(t,n),s=k(t.agent);if(s&&vr(s)){let a=ls(n.env);await by({agentId:s,associationState:a?await Dse(s,t,n):"unreadable",activationEvent:a?await Ose(s,n):!1,delegatedExecution:o[AU]===!0,env:n.env,rawPayloadBase64:Re(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64),result:o})}return o}return R(`Unknown guardian hook command "${i??""}".`,t.json)}if(r==="session"){let i=e[1];return i==="bind"?await Use(e.slice(2),t,n):R(`Unknown guardian session command "${i??""}".`,t.json)}if(r==="enable")return e[1]||t.skill?await gP("enforce",e,t,n):R("guardian enable requires a skill slug.",t.json);if(r==="disable")return await gP("disabled",e,t,n);if(r==="enable-warnings-only")return await gP("warning_only",e,t,n);if(r==="status")return await jse(e,t,n);if(r==="launch")return await zse(e.slice(1),t,n);if(r==="exec")try{let i=await Lse(e,t,n);return await vM(i,e,t,n),i}catch(i){throw await vM({exitCode:1,stdout:"",stderr:ve(i)},e,t,n),i}if(r==="check"){let i=T(e[1]??t.skill,"guardian check requires a skill slug.");if((await ed({...t,dryRun:!0},n,i)).revokedSlugs.includes(i))return A({status:"blocked",decision:"block",reasonCode:"entitlement_revoked_refunded",skillSlug:i,nextStep:`Run skills-layer remove ${i}, or buy it again.`},"This skill was refunded; execution is blocked.",t.json,n);let s=$M(t,"check");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.approval.prepare",nextStep:"Use an authenticated one-action approval or `skills-layer guardian exec` for shell execution."},"Guardian enforcement does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let a=kce(t.cloudTrustLedger);if(a.status==="invalid")return R(a.message,t.json);let l=UP(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(l.status==="invalid")return R(l.message,t.json);let c=await zU({skillSlug:i,version:k(t.version),action:s,flags:t,backend:n,telemetryMode:l.mode});if(c.status!=="ok")return c.result;let u=c.context.installedPath,d=k(t.version)??c.context.version,p=ie({skillSlug:i,version:d,action:s,path:u,guardianPreference:await rd(n,i),unmanagedPolicy:c.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:l.mode,localPreflight:qu(c.context)}),m=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(p)});return await Ga(n,{skillSlug:i,version:d,action:s,decisionStatus:qP(m),reasonCode:Ah(m),telemetryMode:l.mode,path:u,authority:m}),A({...m,localPreflight:qu(c.context)},"Guardian check complete.",t.json,n)}if(r==="incident"){let i=T(e[1]??t.skill,"guardian incident requires a skill slug."),o=T(t.version,"guardian incident requires --version."),s=UP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return R(s.message,t.json);let a=k(t.path);if(a&&!await pr(Tt(n.cwd,a)))return x({status:"error",reasonCode:"invalid_incident_path",path:a,nextAction:"guardian.incident",nextStep:"Use --path with an installed skill directory, or omit --path so Skills Layer resolves the local install record."},`Guardian incident path does not exist: ${a}`,t.json,"invalid_incident_path");let l=a??(await qU({skillSlug:i,flags:t,backend:n})).installedPath,c=$M(t,"incident"),u=ln(t.evidenceJson,"evidence-json"),d=s.mode==="cloud_managed"&&!n.apiKey?"local_only":s.mode,p=n.now(),m=ie({skillSlug:i,version:o,action:c,evidence:u,path:l,telemetryMode:d,incident:!0,reason:k(t.reason),generatedAt:p,...d==="cloud_managed"?{incidentIdempotencyKey:tle()}:{}});if(d==="local_only"){if(!l)return R("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let v=await PM({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian local-only incident"});if(f(v,"status")!=="quarantined"){let w=f(v,"reasonCode")??"guardian_exact_quarantine_failed";return x(v,`Guardian could not physically quarantine the exact installed generation for ${i}.`,t.json,w)}await Ga(n,{skillSlug:i,version:o,action:c,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:d,path:l});let b=AM(n,i);return await LM(b,JSON.stringify({request:m,response:null,localResponse:v,savedAt:n.now()},null,2)),A({status:"written",skillSlug:i,version:o,telemetryMode:d,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:v,incidentStatePath:b,incidentPath:v.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let h=await nle(n,m),g=l?await PM({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian Cloud-managed incident"}):null;if(g&&f(g,"status")!=="quarantined"){let v=f(g,"reasonCode")??"guardian_exact_quarantine_failed";return x({...g,cloudResponse:h},`Guardian recorded the Cloud incident but could not physically quarantine the exact local generation for ${i}.`,t.json,v)}await Mo(n.paths.incidentsDir,{recursive:!0});let y=AM(n,i);return await LM(y,JSON.stringify({request:m,response:h,localResponse:g,savedAt:n.now()},null,2)),await Ga(n,{skillSlug:i,version:o,action:c,decisionStatus:qP(h),reasonCode:Ah(h),telemetryMode:s.mode,path:l,authority:h}),A({...h,telemetryMode:s.mode,localResponse:g,incidentPath:y},"Guardian incident recorded.",t.json,n)}return R(`Unknown guardian command "${r??""}".`,t.json)}var AU=Symbol("guardian-delegated-execution");async function vM(e,t,n,r){if(!ls(r.env))return;let i=r.env.SKILLS_LAYER_GUARDIAN_CANARY_AGENT_ID,o=r.env.SKILLS_LAYER_GUARDIAN_CANARY_SCOPE;if(!i||!vr(i)||o!=="project"&&o!=="global")return;let s=k(n.skill)??t[1];s&&await by({agentId:i,associationState:await $se(i,o,s,r),activationEvent:!1,env:r.env,rawPayloadBase64:Buffer.from(JSON.stringify({positionals:t,json:n.json})).toString("base64url"),reportingSource:"guarded_execution",result:e})}async function $se(e,t,n,r){let i=await mE({agentId:e,scope:t,skillSlug:n,env:r.env});if(!i)return"unreadable";try{let o=await Vo(r,t),s=o.associations[i.associationKey];if(!s||s.agentId!==e||s.scope!==t||s.skillSlug!==n)return"missing";let a=pl(o,{agentId:e,sessionId:s.sessionId,asOf:r.now()});return a.associations.some(c=>et(c)===i.associationKey)?a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="terminal"?"terminal":a.status==="ambiguous"?"ambiguous":"missing":"missing"}catch{return"unreadable"}}async function Dse(e,t,n){let r=Xa(k(t.scope));return r.status==="invalid"?"unreadable":await Tse(e,r.scope,n)}async function Tse(e,t,n){let r=Re(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!r)return"unreadable";let i;try{i=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{return"unreadable"}let o=hd(e,i)?.sessionId??DU(e,i);if(!o)return"unreadable";try{let s=await Vo(n,t),a=pl(s,{agentId:e,sessionId:o,asOf:n.now()});return a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="unrelated"||a.status==="expected_missing_authority"?"missing":a.status}catch{return"unreadable"}}async function Ose(e,t){let n=Re(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!n)return!1;try{let r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));return hd(e,r)!==null}catch{return!1}}async function Lse(e,t,n){let r=k(t.skill),i=T(r??e[1],"guardian exec requires a skill slug."),o=r?e.slice(1):e.slice(2);if(o.length===0)return R("guardian exec requires a command after --.",t.json);if(t.actionJson!==void 0)return x({status:"error",reasonCode:"caller_supplied_execution_action_rejected",nextAction:"guardian.execution.prepare",nextStep:"Guardian derives the canonical shell action from the exact command and execution plan."},"Guardian guarded execution does not accept a caller-authored action.",t.json,"caller_supplied_execution_action_rejected");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.execution.prepare",nextStep:"Use the authenticated atomic Guardian execution prepare flow."},"Guardian guarded execution does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let s=UP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return R(s.message,t.json);let a=xM(o),l=await zU({skillSlug:i,version:k(t.version),action:a,flags:t,backend:n,telemetryMode:s.mode});if(l.status!=="ok")return l.result;let c=l.context.installedPath,u=k(t.version)??l.context.version;if(!u)return x({status:"blocked",reasonCode:"guardian_exact_version_required",skillSlug:i,nextStep:"Install the skill through Skills Layer or pass its exact --version before guarded execution."},"Guardian guarded execution requires an exact installed skill version.",t.json,"guardian_exact_version_required");let d=await mae({commandArgs:o,skillSlug:i,version:u,flags:t,backend:n,localContext:l.context});if(d.status==="blocked")return d.result;let p=xM(o,d.request),m=await D(n,"/api/v1/guardian/execution/prepare",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({request:d.request,...t.dryRun?{dryRun:!0}:{}})}),h=typeof f(m,"token")=="string"&&j(m,"plan")!==void 0&&j(m,"binding")!==void 0;if(!fae(m)&&!h){let C=Ah(m);return await Ga(n,{skillSlug:i,version:u,action:p,decisionStatus:"blocked",reasonCode:C,telemetryMode:s.mode,path:c,authority:m}),x({...m,status:"blocked",reasonCode:C,skillSlug:i},"Guardian blocked guarded execution.",t.json,C)}if(await Ga(n,{skillSlug:i,version:u,action:p,decisionStatus:"allowed",reasonCode:"within_contract",telemetryMode:s.mode,path:c,authority:m}),t.dryRun)return A({status:"allowed",skillSlug:i,guardian:m,localPreflight:qu(l.context),command:{executable:it(d.request.executableRealPath),executableSha256:d.request.executableSha256,argvSha256:HU(d.request.argv),cwdRealPath:d.request.cwdRealPath,executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let g=m,y=f(g,"token"),v=j(g,"plan"),b=j(g,"binding");if(!y||!v||!b)return x({status:"blocked",reasonCode:"guardian_grant_response_invalid",skillSlug:i},"Guardian returned an invalid execution grant.",t.json,"guardian_grant_response_invalid");await D(n,"/api/v1/guardian/execution-grants/consume",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({token:y,plan:v,binding:b})});let w;try{w=await E2({plan:v,ambientEnvironment:n.env,approvedSecrets:d.approvedSecrets})}catch(C){let P=C instanceof $e?C.reasonCode:"guardian_process_failed";return x({status:"blocked",reasonCode:P,skillSlug:i,planHash:b.planHash},"Guardian refused the contained process launch.",t.json,P)}let _={executable:it(v.executableRealPath),argsCount:v.argv.length,exitCode:w.exitCode??1,reason:w.reason,signal:w.signal,stdout:w.stdout,stderr:w.stderr,outputTruncated:w.outputTruncated,planHash:w.planHash};return{exitCode:_.exitCode,stdout:t.json?JSON.stringify({status:_.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:i,guardian:m,localPreflight:qu(l.context),command:_},warnings:[],links:[],reasonCode:_.exitCode===0?null:"command_failed",handoff:null},null,2):Sae(_),stderr:_.stderr}}async function gP(e,t,n,r){let i=T(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),o=await D(r,"/api/v1/guardian/mode",{method:"POST",headers:V(r.apiKey),body:JSON.stringify({skillSlug:i,requestedPreference:e,source:"public-cli"})});if(o.preferenceAccepted===!0){if(f(o,"effectiveMode")==="enforce"){let s=(await Bi(r,i)).installs[i],a=An(s).filter(u=>u.lifecycle?.state==="active"||u.lifecycle?.state==="pending_activation"),l=Qe(r.env,r.platform,r.cwd),c=new Set;for(let u of a){let d=f(u.record,"scope"),p=mr(u.record);if(d!=="project"&&d!=="global"||p.length===0)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,scope:d,targetAgents:p,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode could not identify every supported local activation target.",n.json,"guardian_install_target_unavailable");for(let m of p){let h=l.find(v=>v.id===m);if(!h)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,agent:m,scope:d,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode found an unsupported local activation target.",n.json,"guardian_install_target_unavailable");let g=`${d}:${h.id}`;if(c.has(g))continue;c.add(g);let y=await Ya({backend:r,skillSlug:i,agentId:h.id,scope:d,flags:n,enforceRequired:!0});if(y)return y}}}await xae(r,i,o)}return A(o,o.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,r)}async function jse(e,t,n){let r=k(t.skill)??k(e[1]),i;try{i=await RU(n,r)}catch(m){i={status:"unavailable",skillSlug:r,policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ve(m),nextAction:"guardian.status",nextStep:"Cloud Guardian policy could not be loaded. Local hook and preference posture are still shown below."}}let o=await zn(n),s=r?await Cae(n,r):void 0,a=f(i,"status")==="unavailable",l=f(o,"enforcementLayer")??"not_installed",d=l!=="not_installed"&&o.strictPreActionBlocking===!0?{status:"strict_installed",reasonCode:"guardian_hook_strict",enforcementLayer:l,strictPreActionBlocking:!0,nextAction:"guardian.check",nextStep:"Cloud Guardian policy is enforced when checked, and the local host hook can block supported risky actions before execution."}:l==="native_hook_candidate"?{status:"candidate_installed",reasonCode:"guardian_hook_candidate",enforcementLayer:l,strictPreActionBlocking:!1,nextAction:"guardian.hook.status",nextStep:"A Guardian candidate hook is installed, but strict pre-action blocking is not verified. Run `skills-layer guardian hook status --scope project` to inspect the current binding."}:{status:"not_installed",reasonCode:"guardian_hook_not_installed",enforcementLayer:"not_installed",strictPreActionBlocking:!1,nextAction:"guardian.hook.install",nextStep:"Cloud Guardian policy is enforced when checked, but local pre-action blocking is not installed for this host. Run `skills-layer guardian hook install --agent codex --scope global` or `skills-layer setup`."},p=await Nse({backend:n,skillSlug:r,policy:i,hook:o,localPreference:s});return A(ie({status:a?"degraded":"ok",skillSlug:f(i,"skillSlug")??r,policy:i,localPreference:s,hook:o,cloudPolicy:{status:f(i,"effectiveMode")??f(i,"status")??"unknown",reasonCode:f(i,"reasonCode"),enforcementBoundary:"cloud_policy_when_checked",nextAction:f(i,"nextAction"),nextStep:f(i,"nextStep")},localEnforcement:d,measuredProtection:p,nextAction:f(d,"nextAction"),nextStep:f(d,"nextStep")}),a?"Guardian status loaded with limited Cloud policy data.":"Guardian status loaded.",t.json,n)}async function Nse(e){let t=f(e.policy,"effectiveMode")??(e.localPreference?f(e.localPreference,"effectiveMode")??f(e.localPreference,"requestedPreference"):void 0),n=t==="warning_only"?"warning":t==="disabled"?"disabled":"enforce",r="active",i,o,s=[];if(e.skillSlug){o=(await Bi(e.backend,e.skillSlug)).installs[e.skillSlug],s=An(o);let b=s.map(w=>w.lifecycle?.state??"unreadable");b.some(w=>w==="active"||w==="pending_activation")||(b.includes("externally_removed")?r="externally_removed":b.includes("host_detached")?r="host_detached":b.includes("drifted")?r="drifted":b.length>0&&(r="unreadable")),i=o?f(o,"workspaceId")??f(o,"workingModeWorkspaceId"):void 0}let a=[],l=new Set;for(let v of["project","global"])try{a.push(...Object.values((await Vo(e.backend,v)).associations).filter(b=>!e.skillSlug||b.skillSlug===e.skillSlug))}catch{l.add(v)}let c=kM(a,l.size>0),d=(Fe(e.hook,"hooks")?.filter(L)??[]).filter(v=>v.active===!0),p=s.flatMap(v=>{let b=f(v.record,"scope");if(b!=="project"&&b!=="global")return[];let w=o?gr(o,v):v.record,_=f(w,"workspaceId")??f(w,"workingModeWorkspaceId"),C=f(v.record,"receiptSha256"),P=v.lifecycle?.receipt.generation.generationId,O=Fse(v.lifecycle?.state);return mr(v.record).map(N=>{let Q=wr(N),G=d.find(Ce=>f(Ce,"agent")===N&&f(Ce,"scope")===b),ee=a.filter(Ce=>Ce.agentId===N&&Ce.scope===b&&(!C||Ce.receiptSha256===C)&&(!P||Ce.generationId===P)),te=kM(ee,l.has(b)),X=yl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:_?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:Q?.maximumTier==="strict_candidate",hookInstalled:!!G,strictHookVerified:G?.strictPreActionBlocking===!0,exactActivationVerified:G?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:te,materializationState:O});return{materializationId:v.materializationId,agent:N,scope:b,installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:C,generationId:P,materializationState:O,associationState:te,activeAssociationCount:ee.filter(Ce=>Ce.state==="active").length,hookState:G?f(G,"hookState")??"active":"not_installed",evidenceCapability:G?.evidenceCapability??"unverified",exactActivationVerified:G?.exactActivationVerified===!0,activationRoute:G?.activationRoute??null,workspaceRequired:!!_,...X}})}),m=yl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:i?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:d.some(v=>wr(f(v,"agent")??"")?.maximumTier==="strict_candidate"),hookInstalled:d.length>0,strictHookVerified:d.some(v=>v.strictPreActionBlocking===!0),exactActivationVerified:d.some(v=>v.strictPreActionBlocking===!0&&v.exactActivationVerified===!0),completeWrapperVerified:!1,associationState:c,materializationState:r}),h=new Set(p.map(v=>v.label)),g=p.length===0?m:{label:h.size===1?p[0].label:"mixed",countedAsEnforced:p.every(v=>v.countedAsEnforced),activationAllowed:p.every(v=>v.activationAllowed),runtimeGuardian:p.every(v=>v.runtimeGuardian),reasonCode:h.size===1?p[0].reasonCode:"mixed_target_protection"},y=s.map(v=>({materializationId:v.materializationId,scope:f(v.record,"scope"),agent:f(v.record,"agent")??f(v.record,"targetAgent"),targetAgents:mr(v.record),installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:f(v.record,"receiptSha256"),state:v.lifecycle?.state??"unreadable",protectionTargets:p.filter(b=>b.materializationId===v.materializationId)}));return{...g,requestedMode:n,workspaceRequired:!!i,associationState:c,materializationState:r,materializations:y,targets:p,targetCount:p.length,activeAssociationCount:a.filter(v=>v.state==="active").length}}function Fse(e){return e==="active"||e==="pending_activation"?"active":e==="externally_removed"||e==="host_detached"||e==="drifted"?e:"unreadable"}function kM(e,t){return t?"stale":e.some(n=>n.state==="active")?"active":e.some(n=>n.state==="externally_removed")?"externally_removed":e.some(n=>n.state==="host_detached")?"host_detached":e.some(n=>n.state==="stale")?"stale":e.some(n=>n.state==="pending_authority")?"pending_authority":"none"}async function RU(e,t){let n=t?await rd(e,t):void 0;return await D(e,"/api/v1/guardian/status",{method:"POST",headers:V(e.apiKey),body:JSON.stringify(ie({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function Bse(e){if(!e.apiKey)return{status:"unknown",policySource:"cloud",reasonCode:"login_required",nextAction:"skills-layer login",nextStep:"Sign in to read the Cloud Guardian policy that applies to your account."};try{return await RU(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ve(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function EU(e,t){let n=k(e.agent)??"codex",r=Xa(e.scope);if(r.status==="invalid")return R(r.message,e.json);let i=Qe(t.env,t.platform,t.cwd).find(m=>m.id===n);if(!i)return x({status:"error",reasonCode:"unknown_agent",agent:n,nextAction:"agents.list",nextStep:"Run `skills-layer agents list` to see supported agents, then retry Guardian hook install with a supported --agent value."},`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json,"unknown_agent");let o=Iae(i,r.scope,t,k(e.hostVersion)??i.installEvidence.hostVersion??"unverified");if(!o)return R(`Guardian ${r.scope} hooks are not available for ${i.displayName}.`,e.json);let s=ZU(t,r.scope),a=EM(Bu(t.cwd,o.hookPath)),l=EM(Bu(t.cwd,o.configPath)),c=await JU(s),u=c.hooks.find(m=>f(m,"agent")===i.id&&f(m,"scope")===r.scope),d=await Pae(o,t,u),p=[...c.hooks.filter(m=>f(m,"agent")!==i.id||f(m,"scope")!==r.scope),{hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:a.startsWith("..")?o.hookPath:a,configPath:l.startsWith("..")?o.configPath:l,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,hookFileOwnership:d.hookFileOwnership,...d.configEntryOwnership?{configEntryOwnership:d.configEntryOwnership}:{},...d.configEntryOwnerships?{configEntryOwnerships:d.configEntryOwnerships}:{},...d.activationConfigEntryOwnership?{activationConfigEntryOwnership:d.activationConfigEntryOwnership}:{},...d.configFileOwnership?{configFileOwnership:d.configFileOwnership}:{},absoluteCliPath:d.absoluteCliPath,hostVersion:o.hostVersion,adapterRevision:Gn(o.agent).adapterRevision,evidencePath:Aae(t,r.scope,o.agent,o.hostVersion),enabledAt:t.now()}];return await Ve(s,{version:1,hooks:p}),A({status:"enabled",hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:o.hookPath,configPath:o.configPath,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,agentCommandMatrix:GC({purpose:"materialize_skill",command:"skills-layer install <skill-slug>",jsonCommand:"skills-layer install <skill-slug> --json"}),nextStep:"Guardian is installed into the selected host configuration. Installed hooks route host pre-tool events through the internal Guardian hook runtime. `skills-layer guardian check` and MCP `guardian.check` remain diagnostic; use `skills-layer guardian exec` for atomic guarded shell execution, while supported hooks call MCP/Cloud `guardian.enforce` before a mapped tool action.",warnings:["This hook is installed as a candidate integration and is not counted as strict Guardian enforcement until a real agent/platform allow/deny canary proves the exact adapter, script, config, and CLI binding."]},"Guardian hook enabled.",e.json,t)}async function Mse(e,t){let n=k(e.scope),r=n?Xa(n):null;if(r?.status==="invalid")return R(r.message,e.json);let i=await zn(t,r?.status==="valid"?r.scope:void 0);return A(i,"Guardian status loaded.",e.json,t)}async function Use(e,t,n){let r=Xa(k(t.scope));if(r.status==="invalid")return R(r.message,t.json);let i=T(e[0]??t.skill,"guardian session bind requires a skill slug."),o=T(t.version,"guardian session bind requires --version."),s=k(t.agent);if(!s||!vr(s))return R("guardian session bind requires an agent with an implemented Guardian pre-tool adapter.",t.json);let a=T(t.hostVersion,"guardian session bind requires --host-version."),l=BU(k(t.guardianPreference)??k(t.mode));if(!l)return R("guardian session bind --mode must be enforce, warning-only, or disabled.",t.json);let c={version:1,scope:r.scope,skillSlug:i,skillVersion:o,...k(t.workspaceId)?{workspaceId:k(t.workspaceId)}:{},agentId:s,hostVersion:a,requestedPreference:l,boundAt:n.now()},u=FU(n,r.scope);return await Mo(Be(u),{recursive:!0,mode:448}),await Ve(u,c),await We(MP(n,r.scope),{force:!0}),A({status:"bound",binding:c,bindingPath:u,nextAction:"guardian.hook.run",nextStep:"Start the bound host session. The hook will obtain short-lived signed attribution for the exact Cloud generation."},"Guardian exact skill session bound.",t.json,n)}async function zse(e,t,n){let r=T(e[0]??t.skill,"guardian launch requires a skill slug."),i=Xa(k(t.scope));if(i.status==="invalid")return R(i.message,t.json);let o=k(t.agent);if(o!=="codex"&&o!=="kiro-cli")return x({status:"blocked",reasonCode:"guardian_approved_launcher_unavailable",skillSlug:r,agent:o,supportedLauncherAgents:["codex","kiro-cli"],nextAction:"guardian.status",nextStep:"Use a host with verified native activation, or use the managed launcher for Codex or Kiro CLI. Cline and Cursor IDE processes do not expose a trustworthy inherited-session launcher boundary."},"A trustworthy managed Guardian launcher is unavailable for this host.",t.json,"guardian_approved_launcher_unavailable");let s=e[1];if(!s)return R("guardian launch requires `-- <codex|kiro-cli> [arguments]`.",t.json);if(!(o==="codex"?new Set(["codex","codex.exe"]):new Set(["kiro","kiro-cli","kiro.exe","kiro-cli.exe"])).has(it(s).toLowerCase()))return x({status:"blocked",reasonCode:"guardian_launcher_executable_mismatch",agent:o,executable:it(s),nextAction:"guardian.launch",nextStep:`Launch the real ${o} executable after --; arbitrary commands cannot receive a Guardian launch token.`},"Guardian refused to pass managed-session authority to a different executable.",t.json,"guardian_launcher_executable_mismatch");let l=(await Bi(n,r)).installs[r],c=qn(l,{scope:i.scope,agent:o}).filter(O=>O.lifecycle?.state==="active");if(c.length!==1||!c[0].lifecycle)return x({status:"blocked",reasonCode:c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous",skillSlug:r,agent:o,scope:i.scope,matchingMaterializationCount:c.length,nextAction:"installed",nextStep:"Keep exactly one active exact materialization for this agent and scope before launching a guarded session."},"Guardian could not resolve one exact installed generation for the managed launch.",t.json,c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous");let u=c[0].lifecycle,d=await Dr(u.receipt);if(d.status!=="verified")return x({status:"blocked",reasonCode:d.reasonCode,skillSlug:r,agent:o,scope:i.scope,nextAction:"install",nextStep:"Repair or reinstall the exact generation before starting a managed Guardian session."},"Guardian refused to launch from a stale or changed local generation.",t.json,d.reasonCode);let p=await Ya({backend:n,skillSlug:r,agentId:o,scope:i.scope,flags:t,enforceRequired:!0});if(p)return p;let m=await zn(n,i.scope),h=(Fe(m,"hooks")??[]).filter(L).find(O=>f(O,"agent")===o&&f(O,"scope")===i.scope&&O.active===!0&&O.strictPreActionBlocking===!0&&O.exactActivationVerified===!0);if(!h)return x({status:"blocked",reasonCode:"guardian_launcher_route_unavailable",agent:o,nextAction:"guardian.hook.status",nextStep:"Install and verify the Guardian activation route before launching."},"Guardian refused to launch because the verified hook route is unavailable.",t.json,"guardian_launcher_route_unavailable");let g=k(t.hostVersion)??f(h,"hostVersion")??"unverified",y;try{y=await GU(s,n,fr(n.platform))}catch(O){return R(ve(O),t.json)}let v=Ge(32).toString("base64url"),b=n.now(),w={version:1,launchId:`guardian_launch_${Ge(12).toString("hex")}`,tokenSha256:`sha256:${Me("sha256").update(v,"utf8").digest("hex")}`,scope:i.scope,agentId:o,hostVersion:g,skillSlug:r,generationId:u.receipt.generation.generationId,receiptSha256:Vr(u.receipt),status:"pending",createdAt:b,expiresAt:new Date(Date.parse(b)+15*6e4).toISOString()};await Yse(n,i.scope,w);let _=await new Promise((O,N)=>{let Q=NM(y,e.slice(2),{cwd:n.cwd,env:{...n.env,SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN:v,SKILLS_LAYER_GUARDIAN_LAUNCH_SCOPE:i.scope},stdio:"inherit"});Q.once("error",N),Q.once("exit",(G,ee)=>O({exitCode:G??1,signal:ee}))}).catch(async O=>{throw await _M(n,i.scope,w.launchId).catch(()=>{}),O}),P=(await jU(n,i.scope)).launches[w.launchId]?.status==="associated";return await _M(n,i.scope,w.launchId).catch(()=>{}),A({status:P?"managed_session_completed":"host_exited_before_association",launchId:w.launchId,skillSlug:r,agent:o,scope:i.scope,generationId:w.generationId,hostExitCode:_.exitCode,hostSignal:_.signal,associationObserved:P,nextAction:"guardian.status",nextStep:P?"The one-time launch authority was consumed by the exact host session; inspect per-target Guardian status for the resulting association.":"The host exited before its hook completed an exact active Guardian association. The one-time authority was discarded and is not strict-session evidence."},P?"Managed Guardian host session completed.":"The managed host exited without an observed Guardian session association.",t.json,n)}async function qse(e,t){let n=Xa(k(e.scope)),r=k(e.agent);if(n.status==="invalid"||!r||!vr(r))return rt(r&&vr(r)?r:"codex","deny","Guardian hook configuration is invalid.");let i=Re(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!i||i.length>512*1024)return rt(r,"deny","Guardian could not read the bounded host event.");let o;try{o=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return rt(r,"deny","Guardian could not parse the host event.")}let s=hd(r,o);if(s)return await wM({agentId:r,scope:n.scope,observation:s,rawPayload:o,flags:e,backend:t});let a=DU(r,o);if(!a)return rt(r,"deny","Guardian could not bind this event to the host session.");let l=Re(t.env.SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN);if(l){let h=await Xse(t,n.scope,l,r,t.now());if(!h)return rt(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token.");let g=h.launch;if(h.disposition==="associated"){let y;try{y=await Vo(t,n.scope)}catch{return rt(r,"deny","Guardian session association evidence is unreadable.")}let v=pl(y,{agentId:r,sessionId:a,asOf:t.now()}),b=v.associations.length===1?v.associations[0]:void 0;return!b||et(b)!==g.associationKey?rt(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token."):await FP({agentId:r,scope:n.scope,lookup:v,rawPayload:o,backend:t})}return await wM({agentId:r,scope:n.scope,observation:{sessionId:a,skillReference:g.skillSlug,referenceKind:"slug",source:"approved_launcher",evidence:`approved-launcher:${g.launchId}`},expectedReceiptSha256:g.receiptSha256,expectedGenerationId:g.generationId,managedLaunchId:g.launchId,qualificationCandidate:g.qualificationOnly===!0,rawPayload:o,flags:e,backend:t})}let c;try{c=await Vo(t,n.scope)}catch{return rt(r,"deny","Guardian session association evidence is unreadable.")}let u=pl(c,{agentId:r,sessionId:a,asOf:t.now()});if(u.status!=="unrelated")return await FP({agentId:r,scope:n.scope,lookup:u,rawPayload:o,backend:t});let d=await ke(FU(t,n.scope));if(!d||d.version!==1||d.agentId!==r)return await eae(t,n.scope,r)?rt(r,"deny",`Guardian requires \`skills-layer guardian launch <skill> --agent ${r} --scope ${n.scope} -- <host>\` because this host has no trustworthy native skill-activation signal.`):rt(r,"allow","No Skills Layer skill session is bound; unrelated host activity remains outside Guardian.");let p=await ke(MP(t,n.scope));if(!Hse(p,d,a,t.now()))try{let h=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:d.skillSlug,version:d.skillVersion,...d.workspaceId?{workspaceId:d.workspaceId}:{},agentId:r,platform:t.platform,hostVersion:d.hostVersion,sessionId:a,requestedPreference:d.requestedPreference})}),g=j(h,"envelope"),y=MU(h,"publicKeys");if(!g||!y)throw new Error("Guardian session authority returned an invalid envelope.");p={version:1,envelope:g,publicKeys:y,savedAt:t.now()},await Ve(MP(t,n.scope),p)}catch{return rt(r,"deny","Guardian could not obtain current signed skill-session authority.")}await Kse({binding:d,sessionId:a,cache:p,backend:t}).catch(()=>{});let m=await fy({agentId:r,platform:t.platform==="darwin"||t.platform==="linux"||t.platform==="win32"?t.platform:"linux",hostVersion:d.hostVersion,rawPayload:o,attributionEnvelope:p.envelope,attributionPublicKeys:p.publicKeys,now:t.now(),evaluate:async h=>$U(h,d,t)});return{exitCode:m.exitCode,stdout:m.stdout,stderr:m.stderr}}async function wM(e){let t;try{t=await Wse(e.observation,e.agentId,e.backend)}catch(c){return Di(e.agentId,e.observation,"deny",ve(c))}let n=Vr(t.receipt);if(e.expectedReceiptSha256&&e.expectedReceiptSha256!==n||e.expectedGenerationId&&e.expectedGenerationId!==t.receipt.generation.generationId)return Di(e.agentId,e.observation,"deny","Guardian managed launch no longer matches the exact installed generation.");if(!t.workspaceId&&(t.requestedPreference===null||t.requestedPreference==="disabled"))return Di(e.agentId,e.observation,"allow","Guardian is not enabled for this Personal skill; no runtime association was created.");let r=t.requestedPreference??"enforce",i=Gn(e.agentId),o=Zse(e.agentId,e.rawPayload,e.flags)??"unverified",s=e.backend.now(),a={version:2,revision:1,state:"pending_authority",scope:e.scope,agentId:e.agentId,hostVersion:o,sessionId:e.observation.sessionId,skillSlug:t.skillSlug,skillVersion:t.receipt.generation.semanticVersion,generationId:t.receipt.generation.generationId,receiptSha256:n,...t.workspaceId?{workspaceId:t.workspaceId}:{},requestedPreference:r,activationSource:e.observation.source,activationEvidence:e.observation.evidence,adapterRevision:i.adapterRevision,createdAt:s,updatedAt:s},l;try{l=await NU(e.backend,e.scope,a)}catch{return Di(e.agentId,e.observation,bM(a),"Guardian could not safely record this exact skill-session association.")}try{let c=await TU(l,e.backend),u=e.backend.now(),d=ul({envelope:c.cache.envelope,publicKeys:c.cache.publicKeys,expectedAgentId:e.agentId,expectedPlatform:fr(e.backend.platform),now:u});if(d.skillSlug!==l.skillSlug||d.version!==l.skillVersion||d.generationId!==l.generationId||d.sessionId!==l.sessionId||d.workspaceId!==l.workspaceId)throw new Error("Guardian Cloud authority did not match the exact local association.");let p=await zn(e.backend,e.scope),m=Fe(p,"hooks")?.filter(L).find(_=>f(_,"agent")===e.agentId&&_.active===!0),h=l.requestedPreference==="warning_only"?"warning":l.requestedPreference,g=d.workspaceRequiredMode===null?null:{requiredMode:d.workspaceRequiredMode,revision:c.policyRevision,updatedBy:"skills-layer-cloud",updatedAt:d.issuedAt},y=Vse({enabled:e.qualificationCandidate===!0,managedLaunchId:e.managedLaunchId,agentId:e.agentId,exactHook:m,env:e.backend.env}),v=yl({evaluationContext:"activation_eligibility",requestedMode:h,workspacePolicy:g,hostSupported:wr(e.agentId)?.maximumTier==="strict_candidate",hookInstalled:!!m,strictHookVerified:y||m?.strictPreActionBlocking===!0,exactActivationVerified:y||m?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"pending_authority",materializationState:"active"});if(!v.activationAllowed)return await jo(e.backend,e.scope,et(l),{state:"stale",reasonCode:v.reasonCode,updatedAt:s}),Di(e.agentId,e.observation,"deny",`Guardian refused activation because verified enforcement is unavailable (${v.reasonCode}).`);let b=await jo(e.backend,e.scope,et(l),{state:"active",trustLedgerId:c.trustLedgerId,attributionExpiresAt:d.expiresAt,updatedAt:u}),w=et(b);return await mA(e.backend,e.scope,w,c.cache),!e.managedLaunchId&&ls(e.backend.env)==="missing_attribution"?(await jo(e.backend,e.scope,w,{state:"stale",reasonCode:"phase149_missing_attribution_canary",updatedAt:u}),await nae(e.backend,e.scope,w),Di(e.agentId,e.observation,"allow","Guardian qualification removed signed attribution after exact activation.")):(e.managedLaunchId&&await Qse(e.backend,e.scope,e.managedLaunchId,w),await pE(e.backend.env),e.managedLaunchId?await FP({agentId:e.agentId,scope:e.scope,lookup:{status:"active",associations:[b]},rawPayload:e.rawPayload,backend:e.backend}):Di(e.agentId,e.observation,"allow",v.label==="warning_only"?"Guardian warning-only activation is associated with this exact installed generation; it is not counted as strict enforcement.":"Guardian associated this host session with the exact installed generation."))}catch(c){return await jo(e.backend,e.scope,et(l),{state:"pending_authority",reasonCode:"guardian_session_authority_unavailable",updatedAt:s}).catch(()=>{}),Di(e.agentId,e.observation,BP(c)?"deny":bM(l),l.requestedPreference==="warning_only"&&!l.workspaceId&&!BP(c)?"Guardian warning-only activation continued without runtime authority; protection is diagnostic only.":`Guardian could not establish exact skill-session authority (${ve(c)}).`)}}function Vse(e){if(!e.enabled||!e.managedLaunchId?.startsWith("guardian_launch_phase149_")||wr(e.agentId)?.automaticAssociation!=="approved_launcher_required"||e.exactHook?.active!==!0||e.exactHook.configActive!==!0||e.exactHook.evidenceCapability!=="unverified")return!1;let t=Fe(e.exactHook,"evidenceReasons");return t?.length!==1||t[0]!=="live_canary_evidence_missing"?!1:ls(e.env)!==null}async function FP(e){if(e.lookup.status==="ambiguous")return rt(e.agentId,"deny","Guardian found multiple active skill associations for this host session.");let t=e.lookup.associations[0];if(!t)return rt(e.agentId,"deny","Guardian expected an exact association but could not load it.");if(e.lookup.status==="terminal")return rt(e.agentId,"deny","Guardian blocked a session whose exact skill was removed or detached.");if(e.lookup.status==="expected_missing_authority")return rt(e.agentId,t.requestedPreference==="warning_only"&&!t.workspaceId?"allow":"deny",t.requestedPreference==="warning_only"&&!t.workspaceId?"Guardian warning only: exact runtime authority is missing; this is not strict enforcement.":"Guardian blocked an expected skill session because exact runtime authority is missing.");let n=await Jse(t,e.backend);if(n.status!=="verified")return await jo(e.backend,e.scope,et(t),{state:n.state,reasonCode:n.reasonCode,updatedAt:e.backend.now()}).catch(()=>{}),rt(e.agentId,"deny","Guardian blocked this session because the exact installed generation is no longer current.");let r=await rae(e.backend,e.scope,et(t));if(e.lookup.status==="active_authority_stale"||!iae(r,t,e.backend.now()))try{let a=await TU(t,e.backend);r=a.cache;let l=ul({envelope:r.envelope,publicKeys:r.publicKeys,expectedAgentId:e.agentId,expectedPlatform:fr(e.backend.platform),now:e.backend.now()});await jo(e.backend,e.scope,et(t),{state:"active",trustLedgerId:a.trustLedgerId,attributionExpiresAt:l.expiresAt,updatedAt:e.backend.now()}),await mA(e.backend,e.scope,et(t),r)}catch(a){let l=t.requestedPreference==="warning_only"&&!t.workspaceId&&!BP(a);return rt(e.agentId,l?"allow":"deny",l?"Guardian warning only: signed runtime authority could not be refreshed.":"Guardian blocked this action because signed runtime authority could not be refreshed.")}let i={version:1,scope:t.scope,skillSlug:t.skillSlug,skillVersion:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},agentId:e.agentId,hostVersion:t.hostVersion,requestedPreference:t.requestedPreference,boundAt:t.createdAt},o=!1,s=await fy({agentId:e.agentId,platform:fr(e.backend.platform),hostVersion:t.hostVersion,rawPayload:e.rawPayload,attributionEnvelope:r.envelope,attributionPublicKeys:r.publicKeys,now:e.backend.now(),evaluate:async a=>{let l=await $U(a,i,e.backend);return o=l.delegatedExecution===!0,l}});return o&&await fE({agentId:e.agentId,scope:e.scope,skillSlug:t.skillSlug,associationKey:et(t),env:e.backend.env}),{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr,...o?{[AU]:!0}:{}}}async function $U(e,t,n){if(e.action.actionFamily==="shell_execution"||e.action.actionFamily==="generated_code_execution"){let i=await zn(n,t.scope),o=(Fe(i,"hooks")??[]).filter(L).find(c=>f(c,"agent")===t.agentId&&f(c,"scope")===t.scope&&c.active===!0&&c.configActive===!0&&typeof f(c,"absoluteCliPath")=="string"),s=o?f(o,"absoluteCliPath"):void 0,a=ls(n.env)?gE:void 0;if(s&&e.action.command&&hE({command:e.action.command,cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:fr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}))return{decision:"allow",reason:"Guardian delegated this exact shell action to the atomic guarded execution wrapper.",delegatedExecution:!0};let l=s?yE({cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:fr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}):null;return{decision:"deny",reason:l&&l.length<=800?`Use the exact guarded command prefix: ${l} <command>`:"Use the exact Skills Layer Guardian execution wrapper for one-action guarded shell or generated-code execution."}}let r=Gse(e);if(r.length===0)return{decision:"deny",reason:"Guardian has no exact action mapping for this host event."};for(let i of r){let o=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({skillSlug:t.skillSlug,version:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},guardianPreference:t.requestedPreference,telemetryMode:(t.workspaceId,"cloud_managed"),action:i})});if(j(o,"enforcement")?.canExecute!==!0)return{decision:"deny",reason:`Guardian denied this exact action (${Ah(o)}).`}}return{decision:"allow",reason:"Guardian allowed the exact attributed host action."}}function Gse(e){let t={strictActionSha256:e.actionSha256,toolInputSha256:e.action.toolInputSha256,adapterRevision:e.adapterRevision,host:e.action.host};switch(e.action.actionFamily){case"filesystem_read":case"filesystem_write":return e.action.fileTargets.map(n=>({type:e.action.actionFamily==="filesystem_read"?"file_read":"file_write",path:n,metadata:t}));case"network_access":return e.action.networkTargets.map(n=>({type:"network_request",url:n,metadata:t}));case"browser_access":return[{type:"browser_action",target:e.action.toolName,metadata:t}];case"device_control":return[{type:"device_action",target:e.action.toolName,metadata:t}];case"api_access":return[{type:"api_call",target:e.action.toolName,metadata:t}];default:return[]}}function rt(e,t,n){let r=ns(e,{decision:t,reason:n});return{exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}}function DU(e,t){if(!L(t))return null;let n=e==="cline"?t.taskId:e==="cursor"?t.conversation_id:e==="windsurf"?t.trajectory_id:e==="antigravity"||e==="antigravity-cli"?t.conversationId:t.session_id;return typeof n=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u.test(n)?n:null}function Hse(e,t,n,r){if(!e||e.version!==1||!L(e.envelope)||!L(e.envelope.claims))return!1;let i=e.envelope.claims;return i.agentId===t.agentId&&i.sessionId===n&&i.skillSlug===t.skillSlug&&i.version===t.skillVersion&&i.workspaceId===t.workspaceId&&typeof i.expiresAt=="string"&&Date.parse(i.expiresAt)>Date.parse(r)+5e3}async function Kse(e){let t=(await lt(e.backend)).installs[e.binding.skillSlug],n=qn(t,{scope:e.binding.scope,agent:e.binding.agentId}).filter(a=>a.lifecycle?.receipt.generation.semanticVersion===e.binding.skillVersion),r=n.length===1?n[0].lifecycle:null;if(!r||r.state!=="active"||r.receipt.generation.semanticVersion!==e.binding.skillVersion||(await Dr(r.receipt)).status!=="verified")return;let o=ul({envelope:e.cache.envelope,publicKeys:e.cache.publicKeys,expectedAgentId:e.binding.agentId,expectedPlatform:fr(e.backend.platform),now:e.backend.now()});if(o.sessionId!==e.sessionId||o.generationId!==r.receipt.generation.generationId||o.skillSlug!==e.binding.skillSlug||o.version!==e.binding.skillVersion)return;let s=await NU(e.backend,e.binding.scope,{version:2,revision:1,state:"active",scope:e.binding.scope,agentId:e.binding.agentId,hostVersion:e.binding.hostVersion,sessionId:e.sessionId,skillSlug:e.binding.skillSlug,skillVersion:e.binding.skillVersion,generationId:r.receipt.generation.generationId,receiptSha256:Vr(r.receipt),...e.binding.workspaceId?{workspaceId:e.binding.workspaceId}:{},requestedPreference:e.binding.requestedPreference,activationSource:"manual_recovery",activationEvidence:`legacy-bind:${e.binding.boundAt}`,adapterRevision:Gn(e.binding.agentId).adapterRevision,trustLedgerId:e.cache.envelope.version===2?e.cache.envelope.claims.trustLedgerId:"legacy_local",attributionExpiresAt:o.expiresAt,createdAt:e.binding.boundAt,updatedAt:e.backend.now()});await mA(e.backend,e.binding.scope,et(s),e.cache)}async function Wse(e,t,n){let r=await lt(n),i=Object.entries(r.installs).flatMap(([u,d])=>An(d).flatMap(p=>{let m=p.lifecycle;if(!m||m.state!=="active")return[];if(!mr(p.record).includes(t))return[];if(e.referenceKind==="slug"){if(e.skillReference!==u&&e.skillReference!==m.receipt.generation.skillSlug)return[]}else{let h=qo(m.receipt.targetDir),g=qo(e.skillReference),y=Bu(h,g);if(y.startsWith("..")||ot.isAbsolute(y)||Lt.isAbsolute(y))return[]}return[{skillSlug:u,record:gr(d,p),lifecycle:m}]}));if(i.length!==1)throw new Error(i.length===0?"Guardian activation did not resolve to an owned exact installed generation.":"Guardian activation matched more than one installed generation.");let o=i[0],s=await Dr(o.lifecycle.receipt);if(s.status!=="verified")throw new Error(`Guardian activation receipt verification failed (${s.reasonCode}).`);let a=f(o.record,"workspaceId")??f(o.record,"workingModeWorkspaceId"),l=await rd(n,o.skillSlug),c=l===void 0?a?"enforce":null:BU(l);if(l!==void 0&&c===null)throw new Error("Guardian activation preference is invalid.");return{skillSlug:o.skillSlug,record:o.record,receipt:o.lifecycle.receipt,requestedPreference:c,...a?{workspaceId:a}:{}}}async function TU(e,t){let n=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:e.skillSlug,version:e.skillVersion,...e.workspaceId?{workspaceId:e.workspaceId}:{},agentId:e.agentId,platform:fr(t.platform),hostVersion:e.hostVersion,sessionId:e.sessionId,requestedPreference:e.requestedPreference})}),r=j(n,"envelope"),i=MU(n,"publicKeys"),o=j(n,"ledger"),s=o?f(o,"ledgerId"):void 0;if(!r||!i||!s)throw new Error("Guardian session authority returned an invalid exact-generation envelope.");return{cache:{version:1,envelope:r,publicKeys:i,savedAt:t.now()},trustLedgerId:s,policyRevision:r.version===2?r.claims.policyRevision:1}}function bM(e){return e.requestedPreference==="warning_only"&&!e.workspaceId?"allow":"deny"}function BP(e){return e instanceof Z?e.status<500:!ve(e).startsWith("Unable to reach ")}function Di(e,t,n,r){return t.source==="claude_user_prompt_expansion"?n==="deny"?{exitCode:2,stdout:"",stderr:r}:{exitCode:0,stdout:"",stderr:""}:rt(e,n,r)}function Zse(e,t,n){let r=k(n.hostVersion);if(r)return r;if(!L(t))return null;let i=e==="cline"?t.clineVersion:e==="cursor"?t.cursor_version:t.host_version;return typeof i=="string"&&/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u.test(i)?i:null}function fr(e){return e==="darwin"||e==="win32"?e:"linux"}async function Jse(e,t){let n=(await lt(t)).installs[e.skillSlug],r=qn(n,{receiptSha256:e.receiptSha256}),i=r.length===1?r[0].lifecycle:null;if(!i)return{status:"invalid",state:"externally_removed",reasonCode:"exact_install_record_absent"};if(i.receipt.generation.semanticVersion!==e.skillVersion||i.receipt.generation.generationId!==e.generationId||Vr(i.receipt)!==e.receiptSha256)return{status:"invalid",state:"stale",reasonCode:"exact_generation_replaced"};try{await Xu(i.receipt.targetDir)}catch(s){return s.code==="ENOENT"?{status:"invalid",state:"externally_removed",reasonCode:"exact_target_absent"}:{status:"invalid",state:"stale",reasonCode:"exact_target_unreadable"}}let o=await Dr(i.receipt);return o.status==="verified"?{status:"verified"}:{status:"invalid",state:"stale",reasonCode:o.reasonCode}}function OU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-associations.json"):K(e.cwd,".skills-layer","guardian-session-associations.json")}function LU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-managed-launches.json"):K(e.cwd,".skills-layer","guardian-managed-launches.json")}async function jU(e,t){let n=await ke(LU(e,t));if(!L(n)||n.version!==1||!Number.isSafeInteger(n.revision)||Number(n.revision)<0||!L(n.launches))return{version:1,revision:0,launches:{}};let r=Object.fromEntries(Object.entries(n.launches).flatMap(([i,o])=>{if(!L(o))return[];let s=f(o,"agentId"),a=f(o,"scope"),l=f(o,"tokenSha256"),c=f(o,"receiptSha256"),u=f(o,"status"),d=o;return d.version!==1||d.launchId!==i||s!=="codex"&&s!=="kiro-cli"||a!==t||!l||!/^sha256:[a-f0-9]{64}$/u.test(l)||!c||!/^sha256:[a-f0-9]{64}$/u.test(c)||u!=="pending"&&u!=="claimed"&&u!=="associated"||o.qualificationOnly!==void 0&&o.qualificationOnly!==!0||!f(o,"hostVersion")||!f(o,"skillSlug")||!f(o,"generationId")||u==="associated"&&!f(o,"associationKey")||!f(o,"createdAt")||!f(o,"expiresAt")||!Number.isFinite(Date.parse(d.createdAt))||!Number.isFinite(Date.parse(d.expiresAt))?[]:[[i,d]]}));return{version:1,revision:Number(n.revision),launches:r}}async function td(e,t,n){let r=LU(e,t);await Zo(Be(r));let i=`${r}.lock`,o=null;for(let s=0;s<50&&!o;s+=1)try{o=await Uo(i,"wx",384)}catch(a){if(a.code!=="EEXIST"||s===49)throw a;await e.sleep(10)}if(!o)throw new Error("Guardian managed launch lock is unavailable.");try{let s=await jU(e,t),a=n(s);return await nd(r,a.store),a.value}finally{await o.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function Yse(e,t,n){await td(e,t,r=>({store:{version:1,revision:r.revision+1,launches:{...r.launches,[n.launchId]:n}},value:void 0}))}async function _M(e,t,n){await td(e,t,r=>{let i={...r.launches};return delete i[n],{store:{version:1,revision:r.revision+1,launches:i},value:void 0}})}async function Xse(e,t,n,r,i){if(n.length<32||n.length>256||!/^[A-Za-z0-9_-]+$/u.test(n))return null;let o=`sha256:${Me("sha256").update(n,"utf8").digest("hex")}`;return await td(e,t,s=>{let a=Object.values(s.launches).filter(d=>(d.status==="pending"||d.status==="associated")&&d.tokenSha256===o&&d.agentId===r&&(d.status==="associated"||Date.parse(d.expiresAt)>Date.parse(i))),l=a.length===1?a[0]:void 0,c=l?.status==="pending"?{...l,status:"claimed"}:l,u=Object.fromEntries(Object.entries(s.launches).flatMap(([d,p])=>p.status!=="associated"&&Date.parse(p.expiresAt)<=Date.parse(i)?[]:[[d,p.launchId===c?.launchId?c:p]]));return{store:{version:1,revision:s.revision+1,launches:u},value:c?{disposition:l?.status==="pending"?"claimed":"associated",launch:c}:null}})}async function Qse(e,t,n,r){await td(e,t,i=>{let o=i.launches[n];if(!o||o.status!=="claimed")throw new Error("Guardian managed launch is not in the claimed state.");return{store:{version:1,revision:i.revision+1,launches:{...i.launches,[n]:{...o,status:"associated",associationKey:r}}},value:void 0}})}async function eae(e,t,n){if(wr(n)?.automaticAssociation!=="approved_launcher_required")return!1;let r=await lt(e);for(let[i,o]of Object.entries(r.installs)){let s=qn(o,{scope:t,agent:n});for(let a of s){if(a.lifecycle?.state!=="active"&&a.lifecycle?.state!=="pending_activation")continue;let l=gr(o,a);if(f(l,"workspaceId")??f(l,"workingModeWorkspaceId"))return!0;let u=await rd(e,i);if(u==="enforce"||u==="enabled")return!0}}return!1}function Oh(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-authorities.json"):K(e.cwd,".skills-layer","guardian-session-authorities.json")}async function Vo(e,t){let n=await ke(OU(e,t));return n===null?HR():KR(n)}async function fA(e,t,n){let r=OU(e,t);await Zo(Be(r));let i=`${r}.lock`,o=null;try{o=await Uo(i,"wx",384);let s=await Vo(e,t),a=n(s);return await nd(r,a.index),a.value}finally{await o?.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function NU(e,t,n){return await fA(e,t,r=>{let i=WR(r,n,r.revision),o=i.associations[et(n)];return{index:i,value:o}})}async function jo(e,t,n,r){return await fA(e,t,i=>{let o=ZR(i,{key:n,expectedIndexRevision:i.revision,...r});return{index:o,value:o.associations[n]}})}async function tae(e,t){let n=0;for(let r of["project","global"]){let i=await fA(e,r,o=>{let s=JR(o,{...t,expectedIndexRevision:o.revision});return{index:s.index,value:s.removedKeys}});if(n+=i.length,i.length>0){let o=Oh(e,r),s=await Lh(e,r),a=new Set(i);await nd(o,{version:1,revision:s.revision+1,authorities:Object.fromEntries(Object.entries(s.authorities).filter(([l])=>!a.has(l)))})}await td(e,r,o=>({store:{version:1,revision:o.revision+1,launches:Object.fromEntries(Object.entries(o.launches).filter(([,s])=>s.skillSlug!==t.skillSlug||s.generationId!==t.generationId||s.receiptSha256!==t.receiptSha256))},value:void 0}))}return n}async function Lh(e,t){let n=await ke(Oh(e,t));return!L(n)||n.version!==1||!Number.isSafeInteger(n.revision)||!L(n.authorities)?{version:1,revision:0,authorities:{}}:{version:1,revision:Number(n.revision),authorities:Object.fromEntries(Object.entries(n.authorities).filter(r=>{let i=r[1];return L(i)&&i.version===1&&L(i.envelope)&&L(i.publicKeys)&&typeof i.savedAt=="string"}))}}async function mA(e,t,n,r){let i=Oh(e,t),o=await Lh(e,t);await nd(i,{version:1,revision:o.revision+1,authorities:{...o.authorities,[n]:r}})}async function nae(e,t,n){let r=Oh(e,t),i=await Lh(e,t),o={...i.authorities};delete o[n],await nd(r,{version:1,revision:i.revision+1,authorities:o})}async function rae(e,t,n){return(await Lh(e,t)).authorities[n]??null}function iae(e,t,n){if(!e||e.version!==1||!L(e.envelope)||!L(e.envelope.claims))return!1;let r=e.envelope.claims;return r.agentId===t.agentId&&r.sessionId===t.sessionId&&r.skillSlug===t.skillSlug&&r.version===t.skillVersion&&r.generationId===t.generationId&&r.workspaceId===t.workspaceId&&typeof r.expiresAt=="string"&&Date.parse(r.expiresAt)>Date.parse(n)+5e3}async function nd(e,t){let n=Be(e);await Zo(n);let r=K(n,`.${it(e)}.${Ge(12).toString("hex")}.tmp`),i=null;try{i=await Uo(r,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
|
|
2164
|
+
`))}function mP(e,t){return x({status:"not_found_or_forbidden",reasonCode:"workspace_not_found_or_forbidden",workspaceId:e,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` to find a workspace you can access, then retry with that workspace id."},`Workspace ${e} was not found or you do not have access. Run \`skills-layer workspace list\` to inspect accessible workspaces.`,t.json,"workspace_not_found_or_forbidden")}function mM(e,t,n){let r={status:"approval_not_found",reasonCode:"workspace_skill_approval_not_found",workspaceId:e,skillSlug:t,nextAction:"workspace.approve",nextStep:`Run \`skills-layer workspace approve ${e} ${t}\` first, then run \`skills-layer workspace guide ${e} ${t}\` after the approval exists.`};return x(r,`Workspace approval not found for ${t}. Run \`skills-layer workspace approve ${e} ${t}\` first.`,n.json,"workspace_skill_approval_not_found")}function gM(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="workspace_skill_approval_not_found"||r.includes("workspace")&&r.includes("approval")&&r.includes("not found")}function xse(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="skill_not_found"||r.includes("skill")&&r.includes("not found")}function Cse(e,t,n,r){let i=r.details??{},o={status:"not_found",reasonCode:"skill_not_found",workspaceId:e,skillSlug:t,nextAction:"search",nextStep:f(i,"nextStep")??`Run \`skills-layer search ${t}\` to find the public skill before approving it for workspace ${e}.`};return x(o,`Skill ${t} was not found. Run \`skills-layer search ${t}\` before approving it for the workspace.`,n.json,"skill_not_found")}async function Ise(e,t,n){let r=T(e[0],"buy requires a skill slug."),i=Tie(t);if(i.failure)return i.failure;if(k(t.workspace))return x({reasonCode:"invalid_input"},"buy does not support --workspace; use skills-layer enterprise skill buy <enterprise-id> <skill-slug>.",t.json,"invalid_input");let o=await nA(n,{skillSlug:r,paymentMethod:i.value},t,"/api/v1/buy");if(fe(o))return o;if(o.status==="already_owned")return A(o,`You already own ${r}. Run \`skills-layer install ${r}\` to install or update it.`,t.json,n);if(t.noOpen&&o.status==="checkout_required"&&typeof o.checkoutUrl=="string")return A({...o,nextAction:"open_checkout_url",nextStep:`Open ${o.checkoutUrl} to complete payment, then run skills-layer install ${r}.`},`Payment is required for ${r}.`,t.json,n);if(t.json||t.noOpen||o.status!=="checkout_required"||typeof o.checkoutUrl!="string"||typeof o.purchaseId!="string")return A(o,`Purchase flow started for ${r}.`,t.json,n);n.emitInfo(`Opening checkout for ${r}. Complete the payment in your browser, then come back here.`),await n.openUrl(o.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${o.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let a=await Hae(o.purchaseId,n);return fe(a)?a:a.status!=="succeeded"?A({...o,purchaseStatus:a.status},`Checkout is still ${a.status} for ${r}. You can rerun install after payment reconciliation completes.`,t.json,n):(n.emitInfo("Payment confirmed. Continuing with install."),await Wa([r],t,n,{origin:"post_purchase",fallbackPolicy:"account_required"}))}async function Pse(e,t,n){let r=e[0]??"list";if(r==="list")return await me("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(r==="spending")return await me("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let i=T(e[1],`purchases ${r} requires a purchase id.`);if(r==="status")return await me(`/api/v1/purchases/${encodeURIComponent(i)}`,t,n,"Purchase status loaded.",{authenticated:!0});if(r==="invoice")return await me(`/api/v1/purchases/${encodeURIComponent(i)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0});if(r==="refund-quote"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund-quote`,{headers:re(n.apiKey,n.authBlockedMessage)}),s=L(o.quote)?o.quote:o,a=l=>typeof l=="number"?`USD ${(l/100).toFixed(2)}`:"unavailable";return A(o,`Refundable: ${a(s.refundableAmountCents)}. Non-refundable: ${a(s.nonRefundableAmountCents)}. Refund window ends: ${String(s.refundWindowEndsAt??"unavailable")}.`,t.json,n)}if(r==="refund"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund`,{method:"POST",headers:V(n.apiKey),body:JSON.stringify(Ft(t,["reason"]))}),s=o.status==="refunded"?await ed(t,n):{warnings:[]};return A({...o,warnings:[...s.warnings,"Manually copied folders cannot be removed automatically; other machines check on sync, installed or update."]},o.status==="refunded"?"Refund completed.":"Refund requested.",t.json,n)}return R(`Unknown purchases command "${r}".`,t.json)}function PU(e,t,n,r){let i=typeof e.amountCents=="number"?` (USD ${(e.amountCents/100).toFixed(2)})`:"";return A({...e,status:"action_required",reasonCode:"purchase_required",nextAction:"buy",nextStep:`skills-layer buy ${t}`},`Purchase required${i}. Run \`skills-layer buy ${t}\`.`,n.json,r)}async function Ase(e,t,n){let r=e[0];if(r==="search"){let i=new URLSearchParams;return Ke(i,"query",e.slice(1).join(" ").trim()||k(t.query)),Ke(i,"limit",k(t.limit)),await me(`/api/v1/me/search${Qe(i)}`,t,n,"Authenticated library search complete.",{authenticated:!0})}if(r==="add"){let i=T(e[1],"library add requires a skill slug."),o=await nA(n,{skillSlug:i},t);return fe(o)?o:o.status==="purchase_required"?PU(o,i,t,n):A(o,"Skill added to library.",t.json,n)}return R(`Unknown library command "${r}".`,t.json)}async function Rse(e,t,n){let r=T(e[0],"export requires a skill slug.");if(t.showUrl&&k(t.output))return x({status:"error",reasonCode:"conflicting_export_output",nextAction:"export",nextStep:"Use either --show-url to inspect the signed URL or --output <file> to download the bundle, not both."},"export cannot use --show-url and --output together.",t.json,"conflicting_export_output");let i=new URLSearchParams,o=k(t.version);if(o&&!Th(o))return eA("export",o,t);Ke(i,"version",o);let s=await D(n,`/api/v1/me/library/${encodeURIComponent(r)}/export${Qe(i)}`,{headers:re(n.apiKey,n.authBlockedMessage)}),a=k(t.output);if(a){let l=await xh({backend:n,exportResult:s,flags:t,skillSlug:r});if(fe(l))return l;let c=Tt(n.cwd,a);await IA(c,l.bytes);let u={...s};return delete u.downloadUrl,A({...u,archiveSha256:l.archiveSha256,archiveSha256Meaning:"artifact_v1_exact_zip_bytes_sha256",downloadedArchiveSha256:l.archiveBytesSha256,downloadedFileSha256:l.archiveBytesSha256,archiveHashFormat:l.archiveHashFormat,generationId:l.envelope.generation.generationId,manifestSha256:l.envelope.manifest.sha256,outputPath:c,downloaded:!0},`Exported ${r} to ${c}. Downloaded file SHA-256: ${l.archiveBytesSha256}.`,t.json,n)}return A(s,a?`Exported ${r} to ${a}.`:"Export prepared.",t.json,n)}async function hM(e,t,n,r){if(e==="show"){let a=t[0]?.trim(),l=a?`?skillSlug=${encodeURIComponent(a)}`:"";return await me(`/api/v1/me/library/reviews${l}`,n,r,"Reviews loaded.",{authenticated:!0})}let i=T(t[0],"add-review requires a skill slug."),o=T(n.rating,"add-review requires --rating.");if(!/^[1-5]$/u.test(o))return x({status:"error",reasonCode:"invalid_rating",rating:o,acceptedValues:["1","2","3","4","5"],nextAction:"add-review",nextStep:"Use --rating with a whole number from 1 to 5."},`Invalid review rating "${o}". Use a whole number from 1 to 5.`,n.json,"invalid_rating");let s=Ft(n,["rating","feedback"]);if(typeof n.evalSummary=="string"){let a=await ke(qo(r.cwd,n.evalSummary));if(a===null)return x({status:"error",reasonCode:"invalid_eval_summary_file",path:n.evalSummary,nextAction:"add-review",nextStep:"Pass --eval-summary with a readable JSON redacted eval summary envelope."},`Could not read eval summary JSON from ${n.evalSummary}.`,n.json,"invalid_eval_summary_file");s.evalSummary=a}return await Oe(`/api/v1/me/library/${encodeURIComponent(i)}/review`,s,n,r,"Review added.")}async function yM(e,t,n,r){let i=T(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);if(e==="show")return await me(`/api/v1/me/library/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});T(n.message,"add-issue requires --message.");let o=Mn("add-issue","issueType",n.issueType,hie,n,"invalid_issue_type","issue-type");return o||await Oe(`/api/v1/me/library/${encodeURIComponent(i)}/report-issue`,Ft(n,["issueType","message"]),n,r,"Issue reported.")}async function Ese(e,t,n){let r=e[0];if(r==="hook"){let i=e[1];if(i==="install")return await EU(t,n);if(i==="status")return await Mse(t,n);if(i==="run"){let o=await qse(t,n),s=k(t.agent);if(s&&vr(s)){let a=ls(n.env);await by({agentId:s,associationState:a?await Dse(s,t,n):"unreadable",activationEvent:a?await Ose(s,n):!1,delegatedExecution:o[AU]===!0,env:n.env,rawPayloadBase64:Re(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64),result:o})}return o}return R(`Unknown guardian hook command "${i??""}".`,t.json)}if(r==="session"){let i=e[1];return i==="bind"?await Use(e.slice(2),t,n):R(`Unknown guardian session command "${i??""}".`,t.json)}if(r==="enable")return e[1]||t.skill?await gP("enforce",e,t,n):R("guardian enable requires a skill slug.",t.json);if(r==="disable")return await gP("disabled",e,t,n);if(r==="enable-warnings-only")return await gP("warning_only",e,t,n);if(r==="status")return await jse(e,t,n);if(r==="launch")return await zse(e.slice(1),t,n);if(r==="exec")try{let i=await Lse(e,t,n);return await vM(i,e,t,n),i}catch(i){throw await vM({exitCode:1,stdout:"",stderr:ve(i)},e,t,n),i}if(r==="check"){let i=T(e[1]??t.skill,"guardian check requires a skill slug.");if((await ed({...t,dryRun:!0},n,i)).revokedSlugs.includes(i))return A({status:"blocked",decision:"block",reasonCode:"entitlement_revoked_refunded",skillSlug:i,nextStep:`Run skills-layer remove ${i}, or buy it again.`},"This skill was refunded; execution is blocked.",t.json,n);let s=$M(t,"check");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.approval.prepare",nextStep:"Use an authenticated one-action approval or `skills-layer guardian exec` for shell execution."},"Guardian enforcement does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let a=kce(t.cloudTrustLedger);if(a.status==="invalid")return R(a.message,t.json);let l=UP(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(l.status==="invalid")return R(l.message,t.json);let c=await zU({skillSlug:i,version:k(t.version),action:s,flags:t,backend:n,telemetryMode:l.mode});if(c.status!=="ok")return c.result;let u=c.context.installedPath,d=k(t.version)??c.context.version,p=ie({skillSlug:i,version:d,action:s,path:u,guardianPreference:await rd(n,i),unmanagedPolicy:c.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:l.mode,localPreflight:qu(c.context)}),m=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(p)});return await Ga(n,{skillSlug:i,version:d,action:s,decisionStatus:qP(m),reasonCode:Ah(m),telemetryMode:l.mode,path:u,authority:m}),A({...m,localPreflight:qu(c.context)},"Guardian check complete.",t.json,n)}if(r==="incident"){let i=T(e[1]??t.skill,"guardian incident requires a skill slug."),o=T(t.version,"guardian incident requires --version."),s=UP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return R(s.message,t.json);let a=k(t.path);if(a&&!await pr(Tt(n.cwd,a)))return x({status:"error",reasonCode:"invalid_incident_path",path:a,nextAction:"guardian.incident",nextStep:"Use --path with an installed skill directory, or omit --path so Skills Layer resolves the local install record."},`Guardian incident path does not exist: ${a}`,t.json,"invalid_incident_path");let l=a??(await qU({skillSlug:i,flags:t,backend:n})).installedPath,c=$M(t,"incident"),u=ln(t.evidenceJson,"evidence-json"),d=s.mode==="cloud_managed"&&!n.apiKey?"local_only":s.mode,p=n.now(),m=ie({skillSlug:i,version:o,action:c,evidence:u,path:l,telemetryMode:d,incident:!0,reason:k(t.reason),generatedAt:p,...d==="cloud_managed"?{incidentIdempotencyKey:tle()}:{}});if(d==="local_only"){if(!l)return R("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let v=await PM({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian local-only incident"});if(f(v,"status")!=="quarantined"){let w=f(v,"reasonCode")??"guardian_exact_quarantine_failed";return x(v,`Guardian could not physically quarantine the exact installed generation for ${i}.`,t.json,w)}await Ga(n,{skillSlug:i,version:o,action:c,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:d,path:l});let b=AM(n,i);return await LM(b,JSON.stringify({request:m,response:null,localResponse:v,savedAt:n.now()},null,2)),A({status:"written",skillSlug:i,version:o,telemetryMode:d,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:v,incidentStatePath:b,incidentPath:v.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let h=await nle(n,m),g=l?await PM({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian Cloud-managed incident"}):null;if(g&&f(g,"status")!=="quarantined"){let v=f(g,"reasonCode")??"guardian_exact_quarantine_failed";return x({...g,cloudResponse:h},`Guardian recorded the Cloud incident but could not physically quarantine the exact local generation for ${i}.`,t.json,v)}await Mo(n.paths.incidentsDir,{recursive:!0});let y=AM(n,i);return await LM(y,JSON.stringify({request:m,response:h,localResponse:g,savedAt:n.now()},null,2)),await Ga(n,{skillSlug:i,version:o,action:c,decisionStatus:qP(h),reasonCode:Ah(h),telemetryMode:s.mode,path:l,authority:h}),A({...h,telemetryMode:s.mode,localResponse:g,incidentPath:y},"Guardian incident recorded.",t.json,n)}return R(`Unknown guardian command "${r??""}".`,t.json)}var AU=Symbol("guardian-delegated-execution");async function vM(e,t,n,r){if(!ls(r.env))return;let i=r.env.SKILLS_LAYER_GUARDIAN_CANARY_AGENT_ID,o=r.env.SKILLS_LAYER_GUARDIAN_CANARY_SCOPE;if(!i||!vr(i)||o!=="project"&&o!=="global")return;let s=k(n.skill)??t[1];s&&await by({agentId:i,associationState:await $se(i,o,s,r),activationEvent:!1,env:r.env,rawPayloadBase64:Buffer.from(JSON.stringify({positionals:t,json:n.json})).toString("base64url"),reportingSource:"guarded_execution",result:e})}async function $se(e,t,n,r){let i=await mE({agentId:e,scope:t,skillSlug:n,env:r.env});if(!i)return"unreadable";try{let o=await Vo(r,t),s=o.associations[i.associationKey];if(!s||s.agentId!==e||s.scope!==t||s.skillSlug!==n)return"missing";let a=pl(o,{agentId:e,sessionId:s.sessionId,asOf:r.now()});return a.associations.some(c=>tt(c)===i.associationKey)?a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="terminal"?"terminal":a.status==="ambiguous"?"ambiguous":"missing":"missing"}catch{return"unreadable"}}async function Dse(e,t,n){let r=Xa(k(t.scope));return r.status==="invalid"?"unreadable":await Tse(e,r.scope,n)}async function Tse(e,t,n){let r=Re(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!r)return"unreadable";let i;try{i=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{return"unreadable"}let o=hd(e,i)?.sessionId??DU(e,i);if(!o)return"unreadable";try{let s=await Vo(n,t),a=pl(s,{agentId:e,sessionId:o,asOf:n.now()});return a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="unrelated"||a.status==="expected_missing_authority"?"missing":a.status}catch{return"unreadable"}}async function Ose(e,t){let n=Re(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!n)return!1;try{let r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));return hd(e,r)!==null}catch{return!1}}async function Lse(e,t,n){let r=k(t.skill),i=T(r??e[1],"guardian exec requires a skill slug."),o=r?e.slice(1):e.slice(2);if(o.length===0)return R("guardian exec requires a command after --.",t.json);if(t.actionJson!==void 0)return x({status:"error",reasonCode:"caller_supplied_execution_action_rejected",nextAction:"guardian.execution.prepare",nextStep:"Guardian derives the canonical shell action from the exact command and execution plan."},"Guardian guarded execution does not accept a caller-authored action.",t.json,"caller_supplied_execution_action_rejected");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.execution.prepare",nextStep:"Use the authenticated atomic Guardian execution prepare flow."},"Guardian guarded execution does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let s=UP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return R(s.message,t.json);let a=xM(o),l=await zU({skillSlug:i,version:k(t.version),action:a,flags:t,backend:n,telemetryMode:s.mode});if(l.status!=="ok")return l.result;let c=l.context.installedPath,u=k(t.version)??l.context.version;if(!u)return x({status:"blocked",reasonCode:"guardian_exact_version_required",skillSlug:i,nextStep:"Install the skill through Skills Layer or pass its exact --version before guarded execution."},"Guardian guarded execution requires an exact installed skill version.",t.json,"guardian_exact_version_required");let d=await mae({commandArgs:o,skillSlug:i,version:u,flags:t,backend:n,localContext:l.context});if(d.status==="blocked")return d.result;let p=xM(o,d.request),m=await D(n,"/api/v1/guardian/execution/prepare",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({request:d.request,...t.dryRun?{dryRun:!0}:{}})}),h=typeof f(m,"token")=="string"&&j(m,"plan")!==void 0&&j(m,"binding")!==void 0;if(!fae(m)&&!h){let C=Ah(m);return await Ga(n,{skillSlug:i,version:u,action:p,decisionStatus:"blocked",reasonCode:C,telemetryMode:s.mode,path:c,authority:m}),x({...m,status:"blocked",reasonCode:C,skillSlug:i},"Guardian blocked guarded execution.",t.json,C)}if(await Ga(n,{skillSlug:i,version:u,action:p,decisionStatus:"allowed",reasonCode:"within_contract",telemetryMode:s.mode,path:c,authority:m}),t.dryRun)return A({status:"allowed",skillSlug:i,guardian:m,localPreflight:qu(l.context),command:{executable:ot(d.request.executableRealPath),executableSha256:d.request.executableSha256,argvSha256:HU(d.request.argv),cwdRealPath:d.request.cwdRealPath,executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let g=m,y=f(g,"token"),v=j(g,"plan"),b=j(g,"binding");if(!y||!v||!b)return x({status:"blocked",reasonCode:"guardian_grant_response_invalid",skillSlug:i},"Guardian returned an invalid execution grant.",t.json,"guardian_grant_response_invalid");await D(n,"/api/v1/guardian/execution-grants/consume",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({token:y,plan:v,binding:b})});let w;try{w=await E2({plan:v,ambientEnvironment:n.env,approvedSecrets:d.approvedSecrets})}catch(C){let P=C instanceof $e?C.reasonCode:"guardian_process_failed";return x({status:"blocked",reasonCode:P,skillSlug:i,planHash:b.planHash},"Guardian refused the contained process launch.",t.json,P)}let _={executable:ot(v.executableRealPath),argsCount:v.argv.length,exitCode:w.exitCode??1,reason:w.reason,signal:w.signal,stdout:w.stdout,stderr:w.stderr,outputTruncated:w.outputTruncated,planHash:w.planHash};return{exitCode:_.exitCode,stdout:t.json?JSON.stringify({status:_.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:i,guardian:m,localPreflight:qu(l.context),command:_},warnings:[],links:[],reasonCode:_.exitCode===0?null:"command_failed",handoff:null},null,2):Sae(_),stderr:_.stderr}}async function gP(e,t,n,r){let i=T(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),o=await D(r,"/api/v1/guardian/mode",{method:"POST",headers:V(r.apiKey),body:JSON.stringify({skillSlug:i,requestedPreference:e,source:"public-cli"})});if(o.preferenceAccepted===!0){if(f(o,"effectiveMode")==="enforce"){let s=(await Bi(r,i)).installs[i],a=An(s).filter(u=>u.lifecycle?.state==="active"||u.lifecycle?.state==="pending_activation"),l=et(r.env,r.platform,r.cwd),c=new Set;for(let u of a){let d=f(u.record,"scope"),p=mr(u.record);if(d!=="project"&&d!=="global"||p.length===0)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,scope:d,targetAgents:p,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode could not identify every supported local activation target.",n.json,"guardian_install_target_unavailable");for(let m of p){let h=l.find(v=>v.id===m);if(!h)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,agent:m,scope:d,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode found an unsupported local activation target.",n.json,"guardian_install_target_unavailable");let g=`${d}:${h.id}`;if(c.has(g))continue;c.add(g);let y=await Ya({backend:r,skillSlug:i,agentId:h.id,scope:d,flags:n,enforceRequired:!0});if(y)return y}}}await xae(r,i,o)}return A(o,o.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,r)}async function jse(e,t,n){let r=k(t.skill)??k(e[1]),i;try{i=await RU(n,r)}catch(m){i={status:"unavailable",skillSlug:r,policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ve(m),nextAction:"guardian.status",nextStep:"Cloud Guardian policy could not be loaded. Local hook and preference posture are still shown below."}}let o=await zn(n),s=r?await Cae(n,r):void 0,a=f(i,"status")==="unavailable",l=f(o,"enforcementLayer")??"not_installed",d=l!=="not_installed"&&o.strictPreActionBlocking===!0?{status:"strict_installed",reasonCode:"guardian_hook_strict",enforcementLayer:l,strictPreActionBlocking:!0,nextAction:"guardian.check",nextStep:"Cloud Guardian policy is enforced when checked, and the local host hook can block supported risky actions before execution."}:l==="native_hook_candidate"?{status:"candidate_installed",reasonCode:"guardian_hook_candidate",enforcementLayer:l,strictPreActionBlocking:!1,nextAction:"guardian.hook.status",nextStep:"A Guardian candidate hook is installed, but strict pre-action blocking is not verified. Run `skills-layer guardian hook status --scope project` to inspect the current binding."}:{status:"not_installed",reasonCode:"guardian_hook_not_installed",enforcementLayer:"not_installed",strictPreActionBlocking:!1,nextAction:"guardian.hook.install",nextStep:"Cloud Guardian policy is enforced when checked, but local pre-action blocking is not installed for this host. Run `skills-layer guardian hook install --agent codex --scope global` or `skills-layer setup`."},p=await Nse({backend:n,skillSlug:r,policy:i,hook:o,localPreference:s});return A(ie({status:a?"degraded":"ok",skillSlug:f(i,"skillSlug")??r,policy:i,localPreference:s,hook:o,cloudPolicy:{status:f(i,"effectiveMode")??f(i,"status")??"unknown",reasonCode:f(i,"reasonCode"),enforcementBoundary:"cloud_policy_when_checked",nextAction:f(i,"nextAction"),nextStep:f(i,"nextStep")},localEnforcement:d,measuredProtection:p,nextAction:f(d,"nextAction"),nextStep:f(d,"nextStep")}),a?"Guardian status loaded with limited Cloud policy data.":"Guardian status loaded.",t.json,n)}async function Nse(e){let t=f(e.policy,"effectiveMode")??(e.localPreference?f(e.localPreference,"effectiveMode")??f(e.localPreference,"requestedPreference"):void 0),n=t==="warning_only"?"warning":t==="disabled"?"disabled":"enforce",r="active",i,o,s=[];if(e.skillSlug){o=(await Bi(e.backend,e.skillSlug)).installs[e.skillSlug],s=An(o);let b=s.map(w=>w.lifecycle?.state??"unreadable");b.some(w=>w==="active"||w==="pending_activation")||(b.includes("externally_removed")?r="externally_removed":b.includes("host_detached")?r="host_detached":b.includes("drifted")?r="drifted":b.length>0&&(r="unreadable")),i=o?f(o,"workspaceId")??f(o,"workingModeWorkspaceId"):void 0}let a=[],l=new Set;for(let v of["project","global"])try{a.push(...Object.values((await Vo(e.backend,v)).associations).filter(b=>!e.skillSlug||b.skillSlug===e.skillSlug))}catch{l.add(v)}let c=kM(a,l.size>0),d=(Fe(e.hook,"hooks")?.filter(L)??[]).filter(v=>v.active===!0),p=s.flatMap(v=>{let b=f(v.record,"scope");if(b!=="project"&&b!=="global")return[];let w=o?gr(o,v):v.record,_=f(w,"workspaceId")??f(w,"workingModeWorkspaceId"),C=f(v.record,"receiptSha256"),P=v.lifecycle?.receipt.generation.generationId,O=Fse(v.lifecycle?.state);return mr(v.record).map(N=>{let Q=wr(N),G=d.find(Ce=>f(Ce,"agent")===N&&f(Ce,"scope")===b),ee=a.filter(Ce=>Ce.agentId===N&&Ce.scope===b&&(!C||Ce.receiptSha256===C)&&(!P||Ce.generationId===P)),te=kM(ee,l.has(b)),X=yl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:_?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:Q?.maximumTier==="strict_candidate",hookInstalled:!!G,strictHookVerified:G?.strictPreActionBlocking===!0,exactActivationVerified:G?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:te,materializationState:O});return{materializationId:v.materializationId,agent:N,scope:b,installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:C,generationId:P,materializationState:O,associationState:te,activeAssociationCount:ee.filter(Ce=>Ce.state==="active").length,hookState:G?f(G,"hookState")??"active":"not_installed",evidenceCapability:G?.evidenceCapability??"unverified",exactActivationVerified:G?.exactActivationVerified===!0,activationRoute:G?.activationRoute??null,workspaceRequired:!!_,...X}})}),m=yl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:i?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:d.some(v=>wr(f(v,"agent")??"")?.maximumTier==="strict_candidate"),hookInstalled:d.length>0,strictHookVerified:d.some(v=>v.strictPreActionBlocking===!0),exactActivationVerified:d.some(v=>v.strictPreActionBlocking===!0&&v.exactActivationVerified===!0),completeWrapperVerified:!1,associationState:c,materializationState:r}),h=new Set(p.map(v=>v.label)),g=p.length===0?m:{label:h.size===1?p[0].label:"mixed",countedAsEnforced:p.every(v=>v.countedAsEnforced),activationAllowed:p.every(v=>v.activationAllowed),runtimeGuardian:p.every(v=>v.runtimeGuardian),reasonCode:h.size===1?p[0].reasonCode:"mixed_target_protection"},y=s.map(v=>({materializationId:v.materializationId,scope:f(v.record,"scope"),agent:f(v.record,"agent")??f(v.record,"targetAgent"),targetAgents:mr(v.record),installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:f(v.record,"receiptSha256"),state:v.lifecycle?.state??"unreadable",protectionTargets:p.filter(b=>b.materializationId===v.materializationId)}));return{...g,requestedMode:n,workspaceRequired:!!i,associationState:c,materializationState:r,materializations:y,targets:p,targetCount:p.length,activeAssociationCount:a.filter(v=>v.state==="active").length}}function Fse(e){return e==="active"||e==="pending_activation"?"active":e==="externally_removed"||e==="host_detached"||e==="drifted"?e:"unreadable"}function kM(e,t){return t?"stale":e.some(n=>n.state==="active")?"active":e.some(n=>n.state==="externally_removed")?"externally_removed":e.some(n=>n.state==="host_detached")?"host_detached":e.some(n=>n.state==="stale")?"stale":e.some(n=>n.state==="pending_authority")?"pending_authority":"none"}async function RU(e,t){let n=t?await rd(e,t):void 0;return await D(e,"/api/v1/guardian/status",{method:"POST",headers:V(e.apiKey),body:JSON.stringify(ie({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function Bse(e){if(!e.apiKey)return{status:"unknown",policySource:"cloud",reasonCode:"login_required",nextAction:"skills-layer login",nextStep:"Sign in to read the Cloud Guardian policy that applies to your account."};try{return await RU(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ve(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function EU(e,t){let n=k(e.agent)??"codex",r=Xa(e.scope);if(r.status==="invalid")return R(r.message,e.json);let i=et(t.env,t.platform,t.cwd).find(m=>m.id===n);if(!i)return x({status:"error",reasonCode:"unknown_agent",agent:n,nextAction:"agents.list",nextStep:"Run `skills-layer agents list` to see supported agents, then retry Guardian hook install with a supported --agent value."},`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json,"unknown_agent");let o=Iae(i,r.scope,t,k(e.hostVersion)??i.installEvidence.hostVersion??"unverified");if(!o)return R(`Guardian ${r.scope} hooks are not available for ${i.displayName}.`,e.json);let s=ZU(t,r.scope),a=EM(Bu(t.cwd,o.hookPath)),l=EM(Bu(t.cwd,o.configPath)),c=await JU(s),u=c.hooks.find(m=>f(m,"agent")===i.id&&f(m,"scope")===r.scope),d=await Pae(o,t,u),p=[...c.hooks.filter(m=>f(m,"agent")!==i.id||f(m,"scope")!==r.scope),{hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:a.startsWith("..")?o.hookPath:a,configPath:l.startsWith("..")?o.configPath:l,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,hookFileOwnership:d.hookFileOwnership,...d.configEntryOwnership?{configEntryOwnership:d.configEntryOwnership}:{},...d.configEntryOwnerships?{configEntryOwnerships:d.configEntryOwnerships}:{},...d.activationConfigEntryOwnership?{activationConfigEntryOwnership:d.activationConfigEntryOwnership}:{},...d.configFileOwnership?{configFileOwnership:d.configFileOwnership}:{},absoluteCliPath:d.absoluteCliPath,hostVersion:o.hostVersion,adapterRevision:Gn(o.agent).adapterRevision,evidencePath:Aae(t,r.scope,o.agent,o.hostVersion),enabledAt:t.now()}];return await Ve(s,{version:1,hooks:p}),A({status:"enabled",hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:o.hookPath,configPath:o.configPath,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,agentCommandMatrix:GC({purpose:"materialize_skill",command:"skills-layer install <skill-slug>",jsonCommand:"skills-layer install <skill-slug> --json"}),nextStep:"Guardian is installed into the selected host configuration. Installed hooks route host pre-tool events through the internal Guardian hook runtime. `skills-layer guardian check` and MCP `guardian.check` remain diagnostic; use `skills-layer guardian exec` for atomic guarded shell execution, while supported hooks call MCP/Cloud `guardian.enforce` before a mapped tool action.",warnings:["This hook is installed as a candidate integration and is not counted as strict Guardian enforcement until a real agent/platform allow/deny canary proves the exact adapter, script, config, and CLI binding."]},"Guardian hook enabled.",e.json,t)}async function Mse(e,t){let n=k(e.scope),r=n?Xa(n):null;if(r?.status==="invalid")return R(r.message,e.json);let i=await zn(t,r?.status==="valid"?r.scope:void 0);return A(i,"Guardian status loaded.",e.json,t)}async function Use(e,t,n){let r=Xa(k(t.scope));if(r.status==="invalid")return R(r.message,t.json);let i=T(e[0]??t.skill,"guardian session bind requires a skill slug."),o=T(t.version,"guardian session bind requires --version."),s=k(t.agent);if(!s||!vr(s))return R("guardian session bind requires an agent with an implemented Guardian pre-tool adapter.",t.json);let a=T(t.hostVersion,"guardian session bind requires --host-version."),l=BU(k(t.guardianPreference)??k(t.mode));if(!l)return R("guardian session bind --mode must be enforce, warning-only, or disabled.",t.json);let c={version:1,scope:r.scope,skillSlug:i,skillVersion:o,...k(t.workspaceId)?{workspaceId:k(t.workspaceId)}:{},agentId:s,hostVersion:a,requestedPreference:l,boundAt:n.now()},u=FU(n,r.scope);return await Mo(Be(u),{recursive:!0,mode:448}),await Ve(u,c),await We(MP(n,r.scope),{force:!0}),A({status:"bound",binding:c,bindingPath:u,nextAction:"guardian.hook.run",nextStep:"Start the bound host session. The hook will obtain short-lived signed attribution for the exact Cloud generation."},"Guardian exact skill session bound.",t.json,n)}async function zse(e,t,n){let r=T(e[0]??t.skill,"guardian launch requires a skill slug."),i=Xa(k(t.scope));if(i.status==="invalid")return R(i.message,t.json);let o=k(t.agent);if(o!=="codex"&&o!=="kiro-cli")return x({status:"blocked",reasonCode:"guardian_approved_launcher_unavailable",skillSlug:r,agent:o,supportedLauncherAgents:["codex","kiro-cli"],nextAction:"guardian.status",nextStep:"Use a host with verified native activation, or use the managed launcher for Codex or Kiro CLI. Cline and Cursor IDE processes do not expose a trustworthy inherited-session launcher boundary."},"A trustworthy managed Guardian launcher is unavailable for this host.",t.json,"guardian_approved_launcher_unavailable");let s=e[1];if(!s)return R("guardian launch requires `-- <codex|kiro-cli> [arguments]`.",t.json);if(!(o==="codex"?new Set(["codex","codex.exe"]):new Set(["kiro","kiro-cli","kiro.exe","kiro-cli.exe"])).has(ot(s).toLowerCase()))return x({status:"blocked",reasonCode:"guardian_launcher_executable_mismatch",agent:o,executable:ot(s),nextAction:"guardian.launch",nextStep:`Launch the real ${o} executable after --; arbitrary commands cannot receive a Guardian launch token.`},"Guardian refused to pass managed-session authority to a different executable.",t.json,"guardian_launcher_executable_mismatch");let l=(await Bi(n,r)).installs[r],c=qn(l,{scope:i.scope,agent:o}).filter(O=>O.lifecycle?.state==="active");if(c.length!==1||!c[0].lifecycle)return x({status:"blocked",reasonCode:c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous",skillSlug:r,agent:o,scope:i.scope,matchingMaterializationCount:c.length,nextAction:"installed",nextStep:"Keep exactly one active exact materialization for this agent and scope before launching a guarded session."},"Guardian could not resolve one exact installed generation for the managed launch.",t.json,c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous");let u=c[0].lifecycle,d=await Dr(u.receipt);if(d.status!=="verified")return x({status:"blocked",reasonCode:d.reasonCode,skillSlug:r,agent:o,scope:i.scope,nextAction:"install",nextStep:"Repair or reinstall the exact generation before starting a managed Guardian session."},"Guardian refused to launch from a stale or changed local generation.",t.json,d.reasonCode);let p=await Ya({backend:n,skillSlug:r,agentId:o,scope:i.scope,flags:t,enforceRequired:!0});if(p)return p;let m=await zn(n,i.scope),h=(Fe(m,"hooks")??[]).filter(L).find(O=>f(O,"agent")===o&&f(O,"scope")===i.scope&&O.active===!0&&O.strictPreActionBlocking===!0&&O.exactActivationVerified===!0);if(!h)return x({status:"blocked",reasonCode:"guardian_launcher_route_unavailable",agent:o,nextAction:"guardian.hook.status",nextStep:"Install and verify the Guardian activation route before launching."},"Guardian refused to launch because the verified hook route is unavailable.",t.json,"guardian_launcher_route_unavailable");let g=k(t.hostVersion)??f(h,"hostVersion")??"unverified",y;try{y=await GU(s,n,fr(n.platform))}catch(O){return R(ve(O),t.json)}let v=Ge(32).toString("base64url"),b=n.now(),w={version:1,launchId:`guardian_launch_${Ge(12).toString("hex")}`,tokenSha256:`sha256:${Me("sha256").update(v,"utf8").digest("hex")}`,scope:i.scope,agentId:o,hostVersion:g,skillSlug:r,generationId:u.receipt.generation.generationId,receiptSha256:Vr(u.receipt),status:"pending",createdAt:b,expiresAt:new Date(Date.parse(b)+15*6e4).toISOString()};await Yse(n,i.scope,w);let _=await new Promise((O,N)=>{let Q=NM(y,e.slice(2),{cwd:n.cwd,env:{...n.env,SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN:v,SKILLS_LAYER_GUARDIAN_LAUNCH_SCOPE:i.scope},stdio:"inherit"});Q.once("error",N),Q.once("exit",(G,ee)=>O({exitCode:G??1,signal:ee}))}).catch(async O=>{throw await _M(n,i.scope,w.launchId).catch(()=>{}),O}),P=(await jU(n,i.scope)).launches[w.launchId]?.status==="associated";return await _M(n,i.scope,w.launchId).catch(()=>{}),A({status:P?"managed_session_completed":"host_exited_before_association",launchId:w.launchId,skillSlug:r,agent:o,scope:i.scope,generationId:w.generationId,hostExitCode:_.exitCode,hostSignal:_.signal,associationObserved:P,nextAction:"guardian.status",nextStep:P?"The one-time launch authority was consumed by the exact host session; inspect per-target Guardian status for the resulting association.":"The host exited before its hook completed an exact active Guardian association. The one-time authority was discarded and is not strict-session evidence."},P?"Managed Guardian host session completed.":"The managed host exited without an observed Guardian session association.",t.json,n)}async function qse(e,t){let n=Xa(k(e.scope)),r=k(e.agent);if(n.status==="invalid"||!r||!vr(r))return it(r&&vr(r)?r:"codex","deny","Guardian hook configuration is invalid.");let i=Re(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!i||i.length>512*1024)return it(r,"deny","Guardian could not read the bounded host event.");let o;try{o=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return it(r,"deny","Guardian could not parse the host event.")}let s=hd(r,o);if(s)return await wM({agentId:r,scope:n.scope,observation:s,rawPayload:o,flags:e,backend:t});let a=DU(r,o);if(!a)return it(r,"deny","Guardian could not bind this event to the host session.");let l=Re(t.env.SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN);if(l){let h=await Xse(t,n.scope,l,r,t.now());if(!h)return it(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token.");let g=h.launch;if(h.disposition==="associated"){let y;try{y=await Vo(t,n.scope)}catch{return it(r,"deny","Guardian session association evidence is unreadable.")}let v=pl(y,{agentId:r,sessionId:a,asOf:t.now()}),b=v.associations.length===1?v.associations[0]:void 0;return!b||tt(b)!==g.associationKey?it(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token."):await FP({agentId:r,scope:n.scope,lookup:v,rawPayload:o,backend:t})}return await wM({agentId:r,scope:n.scope,observation:{sessionId:a,skillReference:g.skillSlug,referenceKind:"slug",source:"approved_launcher",evidence:`approved-launcher:${g.launchId}`},expectedReceiptSha256:g.receiptSha256,expectedGenerationId:g.generationId,managedLaunchId:g.launchId,qualificationCandidate:g.qualificationOnly===!0,rawPayload:o,flags:e,backend:t})}let c;try{c=await Vo(t,n.scope)}catch{return it(r,"deny","Guardian session association evidence is unreadable.")}let u=pl(c,{agentId:r,sessionId:a,asOf:t.now()});if(u.status!=="unrelated")return await FP({agentId:r,scope:n.scope,lookup:u,rawPayload:o,backend:t});let d=await ke(FU(t,n.scope));if(!d||d.version!==1||d.agentId!==r)return await eae(t,n.scope,r)?it(r,"deny",`Guardian requires \`skills-layer guardian launch <skill> --agent ${r} --scope ${n.scope} -- <host>\` because this host has no trustworthy native skill-activation signal.`):it(r,"allow","No Skills Layer skill session is bound; unrelated host activity remains outside Guardian.");let p=await ke(MP(t,n.scope));if(!Hse(p,d,a,t.now()))try{let h=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:d.skillSlug,version:d.skillVersion,...d.workspaceId?{workspaceId:d.workspaceId}:{},agentId:r,platform:t.platform,hostVersion:d.hostVersion,sessionId:a,requestedPreference:d.requestedPreference})}),g=j(h,"envelope"),y=MU(h,"publicKeys");if(!g||!y)throw new Error("Guardian session authority returned an invalid envelope.");p={version:1,envelope:g,publicKeys:y,savedAt:t.now()},await Ve(MP(t,n.scope),p)}catch{return it(r,"deny","Guardian could not obtain current signed skill-session authority.")}await Kse({binding:d,sessionId:a,cache:p,backend:t}).catch(()=>{});let m=await fy({agentId:r,platform:t.platform==="darwin"||t.platform==="linux"||t.platform==="win32"?t.platform:"linux",hostVersion:d.hostVersion,rawPayload:o,attributionEnvelope:p.envelope,attributionPublicKeys:p.publicKeys,now:t.now(),evaluate:async h=>$U(h,d,t)});return{exitCode:m.exitCode,stdout:m.stdout,stderr:m.stderr}}async function wM(e){let t;try{t=await Wse(e.observation,e.agentId,e.backend)}catch(c){return Di(e.agentId,e.observation,"deny",ve(c))}let n=Vr(t.receipt);if(e.expectedReceiptSha256&&e.expectedReceiptSha256!==n||e.expectedGenerationId&&e.expectedGenerationId!==t.receipt.generation.generationId)return Di(e.agentId,e.observation,"deny","Guardian managed launch no longer matches the exact installed generation.");if(!t.workspaceId&&(t.requestedPreference===null||t.requestedPreference==="disabled"))return Di(e.agentId,e.observation,"allow","Guardian is not enabled for this Personal skill; no runtime association was created.");let r=t.requestedPreference??"enforce",i=Gn(e.agentId),o=Zse(e.agentId,e.rawPayload,e.flags)??"unverified",s=e.backend.now(),a={version:2,revision:1,state:"pending_authority",scope:e.scope,agentId:e.agentId,hostVersion:o,sessionId:e.observation.sessionId,skillSlug:t.skillSlug,skillVersion:t.receipt.generation.semanticVersion,generationId:t.receipt.generation.generationId,receiptSha256:n,...t.workspaceId?{workspaceId:t.workspaceId}:{},requestedPreference:r,activationSource:e.observation.source,activationEvidence:e.observation.evidence,adapterRevision:i.adapterRevision,createdAt:s,updatedAt:s},l;try{l=await NU(e.backend,e.scope,a)}catch{return Di(e.agentId,e.observation,bM(a),"Guardian could not safely record this exact skill-session association.")}try{let c=await TU(l,e.backend),u=e.backend.now(),d=ul({envelope:c.cache.envelope,publicKeys:c.cache.publicKeys,expectedAgentId:e.agentId,expectedPlatform:fr(e.backend.platform),now:u});if(d.skillSlug!==l.skillSlug||d.version!==l.skillVersion||d.generationId!==l.generationId||d.sessionId!==l.sessionId||d.workspaceId!==l.workspaceId)throw new Error("Guardian Cloud authority did not match the exact local association.");let p=await zn(e.backend,e.scope),m=Fe(p,"hooks")?.filter(L).find(_=>f(_,"agent")===e.agentId&&_.active===!0),h=l.requestedPreference==="warning_only"?"warning":l.requestedPreference,g=d.workspaceRequiredMode===null?null:{requiredMode:d.workspaceRequiredMode,revision:c.policyRevision,updatedBy:"skills-layer-cloud",updatedAt:d.issuedAt},y=Vse({enabled:e.qualificationCandidate===!0,managedLaunchId:e.managedLaunchId,agentId:e.agentId,exactHook:m,env:e.backend.env}),v=yl({evaluationContext:"activation_eligibility",requestedMode:h,workspacePolicy:g,hostSupported:wr(e.agentId)?.maximumTier==="strict_candidate",hookInstalled:!!m,strictHookVerified:y||m?.strictPreActionBlocking===!0,exactActivationVerified:y||m?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"pending_authority",materializationState:"active"});if(!v.activationAllowed)return await jo(e.backend,e.scope,tt(l),{state:"stale",reasonCode:v.reasonCode,updatedAt:s}),Di(e.agentId,e.observation,"deny",`Guardian refused activation because verified enforcement is unavailable (${v.reasonCode}).`);let b=await jo(e.backend,e.scope,tt(l),{state:"active",trustLedgerId:c.trustLedgerId,attributionExpiresAt:d.expiresAt,updatedAt:u}),w=tt(b);return await mA(e.backend,e.scope,w,c.cache),!e.managedLaunchId&&ls(e.backend.env)==="missing_attribution"?(await jo(e.backend,e.scope,w,{state:"stale",reasonCode:"phase149_missing_attribution_canary",updatedAt:u}),await nae(e.backend,e.scope,w),Di(e.agentId,e.observation,"allow","Guardian qualification removed signed attribution after exact activation.")):(e.managedLaunchId&&await Qse(e.backend,e.scope,e.managedLaunchId,w),await pE(e.backend.env),e.managedLaunchId?await FP({agentId:e.agentId,scope:e.scope,lookup:{status:"active",associations:[b]},rawPayload:e.rawPayload,backend:e.backend}):Di(e.agentId,e.observation,"allow",v.label==="warning_only"?"Guardian warning-only activation is associated with this exact installed generation; it is not counted as strict enforcement.":"Guardian associated this host session with the exact installed generation."))}catch(c){return await jo(e.backend,e.scope,tt(l),{state:"pending_authority",reasonCode:"guardian_session_authority_unavailable",updatedAt:s}).catch(()=>{}),Di(e.agentId,e.observation,BP(c)?"deny":bM(l),l.requestedPreference==="warning_only"&&!l.workspaceId&&!BP(c)?"Guardian warning-only activation continued without runtime authority; protection is diagnostic only.":`Guardian could not establish exact skill-session authority (${ve(c)}).`)}}function Vse(e){if(!e.enabled||!e.managedLaunchId?.startsWith("guardian_launch_phase149_")||wr(e.agentId)?.automaticAssociation!=="approved_launcher_required"||e.exactHook?.active!==!0||e.exactHook.configActive!==!0||e.exactHook.evidenceCapability!=="unverified")return!1;let t=Fe(e.exactHook,"evidenceReasons");return t?.length!==1||t[0]!=="live_canary_evidence_missing"?!1:ls(e.env)!==null}async function FP(e){if(e.lookup.status==="ambiguous")return it(e.agentId,"deny","Guardian found multiple active skill associations for this host session.");let t=e.lookup.associations[0];if(!t)return it(e.agentId,"deny","Guardian expected an exact association but could not load it.");if(e.lookup.status==="terminal")return it(e.agentId,"deny","Guardian blocked a session whose exact skill was removed or detached.");if(e.lookup.status==="expected_missing_authority")return it(e.agentId,t.requestedPreference==="warning_only"&&!t.workspaceId?"allow":"deny",t.requestedPreference==="warning_only"&&!t.workspaceId?"Guardian warning only: exact runtime authority is missing; this is not strict enforcement.":"Guardian blocked an expected skill session because exact runtime authority is missing.");let n=await Jse(t,e.backend);if(n.status!=="verified")return await jo(e.backend,e.scope,tt(t),{state:n.state,reasonCode:n.reasonCode,updatedAt:e.backend.now()}).catch(()=>{}),it(e.agentId,"deny","Guardian blocked this session because the exact installed generation is no longer current.");let r=await rae(e.backend,e.scope,tt(t));if(e.lookup.status==="active_authority_stale"||!iae(r,t,e.backend.now()))try{let a=await TU(t,e.backend);r=a.cache;let l=ul({envelope:r.envelope,publicKeys:r.publicKeys,expectedAgentId:e.agentId,expectedPlatform:fr(e.backend.platform),now:e.backend.now()});await jo(e.backend,e.scope,tt(t),{state:"active",trustLedgerId:a.trustLedgerId,attributionExpiresAt:l.expiresAt,updatedAt:e.backend.now()}),await mA(e.backend,e.scope,tt(t),r)}catch(a){let l=t.requestedPreference==="warning_only"&&!t.workspaceId&&!BP(a);return it(e.agentId,l?"allow":"deny",l?"Guardian warning only: signed runtime authority could not be refreshed.":"Guardian blocked this action because signed runtime authority could not be refreshed.")}let i={version:1,scope:t.scope,skillSlug:t.skillSlug,skillVersion:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},agentId:e.agentId,hostVersion:t.hostVersion,requestedPreference:t.requestedPreference,boundAt:t.createdAt},o=!1,s=await fy({agentId:e.agentId,platform:fr(e.backend.platform),hostVersion:t.hostVersion,rawPayload:e.rawPayload,attributionEnvelope:r.envelope,attributionPublicKeys:r.publicKeys,now:e.backend.now(),evaluate:async a=>{let l=await $U(a,i,e.backend);return o=l.delegatedExecution===!0,l}});return o&&await fE({agentId:e.agentId,scope:e.scope,skillSlug:t.skillSlug,associationKey:tt(t),env:e.backend.env}),{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr,...o?{[AU]:!0}:{}}}async function $U(e,t,n){if(e.action.actionFamily==="shell_execution"||e.action.actionFamily==="generated_code_execution"){let i=await zn(n,t.scope),o=(Fe(i,"hooks")??[]).filter(L).find(c=>f(c,"agent")===t.agentId&&f(c,"scope")===t.scope&&c.active===!0&&c.configActive===!0&&typeof f(c,"absoluteCliPath")=="string"),s=o?f(o,"absoluteCliPath"):void 0,a=ls(n.env)?gE:void 0;if(s&&e.action.command&&hE({command:e.action.command,cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:fr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}))return{decision:"allow",reason:"Guardian delegated this exact shell action to the atomic guarded execution wrapper.",delegatedExecution:!0};let l=s?yE({cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:fr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}):null;return{decision:"deny",reason:l&&l.length<=800?`Use the exact guarded command prefix: ${l} <command>`:"Use the exact Skills Layer Guardian execution wrapper for one-action guarded shell or generated-code execution."}}let r=Gse(e);if(r.length===0)return{decision:"deny",reason:"Guardian has no exact action mapping for this host event."};for(let i of r){let o=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({skillSlug:t.skillSlug,version:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},guardianPreference:t.requestedPreference,telemetryMode:(t.workspaceId,"cloud_managed"),action:i})});if(j(o,"enforcement")?.canExecute!==!0)return{decision:"deny",reason:`Guardian denied this exact action (${Ah(o)}).`}}return{decision:"allow",reason:"Guardian allowed the exact attributed host action."}}function Gse(e){let t={strictActionSha256:e.actionSha256,toolInputSha256:e.action.toolInputSha256,adapterRevision:e.adapterRevision,host:e.action.host};switch(e.action.actionFamily){case"filesystem_read":case"filesystem_write":return e.action.fileTargets.map(n=>({type:e.action.actionFamily==="filesystem_read"?"file_read":"file_write",path:n,metadata:t}));case"network_access":return e.action.networkTargets.map(n=>({type:"network_request",url:n,metadata:t}));case"browser_access":return[{type:"browser_action",target:e.action.toolName,metadata:t}];case"device_control":return[{type:"device_action",target:e.action.toolName,metadata:t}];case"api_access":return[{type:"api_call",target:e.action.toolName,metadata:t}];default:return[]}}function it(e,t,n){let r=ns(e,{decision:t,reason:n});return{exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}}function DU(e,t){if(!L(t))return null;let n=e==="cline"?t.taskId:e==="cursor"?t.conversation_id:e==="windsurf"?t.trajectory_id:e==="antigravity"||e==="antigravity-cli"?t.conversationId:t.session_id;return typeof n=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u.test(n)?n:null}function Hse(e,t,n,r){if(!e||e.version!==1||!L(e.envelope)||!L(e.envelope.claims))return!1;let i=e.envelope.claims;return i.agentId===t.agentId&&i.sessionId===n&&i.skillSlug===t.skillSlug&&i.version===t.skillVersion&&i.workspaceId===t.workspaceId&&typeof i.expiresAt=="string"&&Date.parse(i.expiresAt)>Date.parse(r)+5e3}async function Kse(e){let t=(await lt(e.backend)).installs[e.binding.skillSlug],n=qn(t,{scope:e.binding.scope,agent:e.binding.agentId}).filter(a=>a.lifecycle?.receipt.generation.semanticVersion===e.binding.skillVersion),r=n.length===1?n[0].lifecycle:null;if(!r||r.state!=="active"||r.receipt.generation.semanticVersion!==e.binding.skillVersion||(await Dr(r.receipt)).status!=="verified")return;let o=ul({envelope:e.cache.envelope,publicKeys:e.cache.publicKeys,expectedAgentId:e.binding.agentId,expectedPlatform:fr(e.backend.platform),now:e.backend.now()});if(o.sessionId!==e.sessionId||o.generationId!==r.receipt.generation.generationId||o.skillSlug!==e.binding.skillSlug||o.version!==e.binding.skillVersion)return;let s=await NU(e.backend,e.binding.scope,{version:2,revision:1,state:"active",scope:e.binding.scope,agentId:e.binding.agentId,hostVersion:e.binding.hostVersion,sessionId:e.sessionId,skillSlug:e.binding.skillSlug,skillVersion:e.binding.skillVersion,generationId:r.receipt.generation.generationId,receiptSha256:Vr(r.receipt),...e.binding.workspaceId?{workspaceId:e.binding.workspaceId}:{},requestedPreference:e.binding.requestedPreference,activationSource:"manual_recovery",activationEvidence:`legacy-bind:${e.binding.boundAt}`,adapterRevision:Gn(e.binding.agentId).adapterRevision,trustLedgerId:e.cache.envelope.version===2?e.cache.envelope.claims.trustLedgerId:"legacy_local",attributionExpiresAt:o.expiresAt,createdAt:e.binding.boundAt,updatedAt:e.backend.now()});await mA(e.backend,e.binding.scope,tt(s),e.cache)}async function Wse(e,t,n){let r=await lt(n),i=Object.entries(r.installs).flatMap(([u,d])=>An(d).flatMap(p=>{let m=p.lifecycle;if(!m||m.state!=="active")return[];if(!mr(p.record).includes(t))return[];if(e.referenceKind==="slug"){if(e.skillReference!==u&&e.skillReference!==m.receipt.generation.skillSlug)return[]}else{let h=qo(m.receipt.targetDir),g=qo(e.skillReference),y=Bu(h,g);if(y.startsWith("..")||st.isAbsolute(y)||Lt.isAbsolute(y))return[]}return[{skillSlug:u,record:gr(d,p),lifecycle:m}]}));if(i.length!==1)throw new Error(i.length===0?"Guardian activation did not resolve to an owned exact installed generation.":"Guardian activation matched more than one installed generation.");let o=i[0],s=await Dr(o.lifecycle.receipt);if(s.status!=="verified")throw new Error(`Guardian activation receipt verification failed (${s.reasonCode}).`);let a=f(o.record,"workspaceId")??f(o.record,"workingModeWorkspaceId"),l=await rd(n,o.skillSlug),c=l===void 0?a?"enforce":null:BU(l);if(l!==void 0&&c===null)throw new Error("Guardian activation preference is invalid.");return{skillSlug:o.skillSlug,record:o.record,receipt:o.lifecycle.receipt,requestedPreference:c,...a?{workspaceId:a}:{}}}async function TU(e,t){let n=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:e.skillSlug,version:e.skillVersion,...e.workspaceId?{workspaceId:e.workspaceId}:{},agentId:e.agentId,platform:fr(t.platform),hostVersion:e.hostVersion,sessionId:e.sessionId,requestedPreference:e.requestedPreference})}),r=j(n,"envelope"),i=MU(n,"publicKeys"),o=j(n,"ledger"),s=o?f(o,"ledgerId"):void 0;if(!r||!i||!s)throw new Error("Guardian session authority returned an invalid exact-generation envelope.");return{cache:{version:1,envelope:r,publicKeys:i,savedAt:t.now()},trustLedgerId:s,policyRevision:r.version===2?r.claims.policyRevision:1}}function bM(e){return e.requestedPreference==="warning_only"&&!e.workspaceId?"allow":"deny"}function BP(e){return e instanceof Z?e.status<500:!ve(e).startsWith("Unable to reach ")}function Di(e,t,n,r){return t.source==="claude_user_prompt_expansion"?n==="deny"?{exitCode:2,stdout:"",stderr:r}:{exitCode:0,stdout:"",stderr:""}:it(e,n,r)}function Zse(e,t,n){let r=k(n.hostVersion);if(r)return r;if(!L(t))return null;let i=e==="cline"?t.clineVersion:e==="cursor"?t.cursor_version:t.host_version;return typeof i=="string"&&/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u.test(i)?i:null}function fr(e){return e==="darwin"||e==="win32"?e:"linux"}async function Jse(e,t){let n=(await lt(t)).installs[e.skillSlug],r=qn(n,{receiptSha256:e.receiptSha256}),i=r.length===1?r[0].lifecycle:null;if(!i)return{status:"invalid",state:"externally_removed",reasonCode:"exact_install_record_absent"};if(i.receipt.generation.semanticVersion!==e.skillVersion||i.receipt.generation.generationId!==e.generationId||Vr(i.receipt)!==e.receiptSha256)return{status:"invalid",state:"stale",reasonCode:"exact_generation_replaced"};try{await Xu(i.receipt.targetDir)}catch(s){return s.code==="ENOENT"?{status:"invalid",state:"externally_removed",reasonCode:"exact_target_absent"}:{status:"invalid",state:"stale",reasonCode:"exact_target_unreadable"}}let o=await Dr(i.receipt);return o.status==="verified"?{status:"verified"}:{status:"invalid",state:"stale",reasonCode:o.reasonCode}}function OU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-associations.json"):K(e.cwd,".skills-layer","guardian-session-associations.json")}function LU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-managed-launches.json"):K(e.cwd,".skills-layer","guardian-managed-launches.json")}async function jU(e,t){let n=await ke(LU(e,t));if(!L(n)||n.version!==1||!Number.isSafeInteger(n.revision)||Number(n.revision)<0||!L(n.launches))return{version:1,revision:0,launches:{}};let r=Object.fromEntries(Object.entries(n.launches).flatMap(([i,o])=>{if(!L(o))return[];let s=f(o,"agentId"),a=f(o,"scope"),l=f(o,"tokenSha256"),c=f(o,"receiptSha256"),u=f(o,"status"),d=o;return d.version!==1||d.launchId!==i||s!=="codex"&&s!=="kiro-cli"||a!==t||!l||!/^sha256:[a-f0-9]{64}$/u.test(l)||!c||!/^sha256:[a-f0-9]{64}$/u.test(c)||u!=="pending"&&u!=="claimed"&&u!=="associated"||o.qualificationOnly!==void 0&&o.qualificationOnly!==!0||!f(o,"hostVersion")||!f(o,"skillSlug")||!f(o,"generationId")||u==="associated"&&!f(o,"associationKey")||!f(o,"createdAt")||!f(o,"expiresAt")||!Number.isFinite(Date.parse(d.createdAt))||!Number.isFinite(Date.parse(d.expiresAt))?[]:[[i,d]]}));return{version:1,revision:Number(n.revision),launches:r}}async function td(e,t,n){let r=LU(e,t);await Zo(Be(r));let i=`${r}.lock`,o=null;for(let s=0;s<50&&!o;s+=1)try{o=await Uo(i,"wx",384)}catch(a){if(a.code!=="EEXIST"||s===49)throw a;await e.sleep(10)}if(!o)throw new Error("Guardian managed launch lock is unavailable.");try{let s=await jU(e,t),a=n(s);return await nd(r,a.store),a.value}finally{await o.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function Yse(e,t,n){await td(e,t,r=>({store:{version:1,revision:r.revision+1,launches:{...r.launches,[n.launchId]:n}},value:void 0}))}async function _M(e,t,n){await td(e,t,r=>{let i={...r.launches};return delete i[n],{store:{version:1,revision:r.revision+1,launches:i},value:void 0}})}async function Xse(e,t,n,r,i){if(n.length<32||n.length>256||!/^[A-Za-z0-9_-]+$/u.test(n))return null;let o=`sha256:${Me("sha256").update(n,"utf8").digest("hex")}`;return await td(e,t,s=>{let a=Object.values(s.launches).filter(d=>(d.status==="pending"||d.status==="associated")&&d.tokenSha256===o&&d.agentId===r&&(d.status==="associated"||Date.parse(d.expiresAt)>Date.parse(i))),l=a.length===1?a[0]:void 0,c=l?.status==="pending"?{...l,status:"claimed"}:l,u=Object.fromEntries(Object.entries(s.launches).flatMap(([d,p])=>p.status!=="associated"&&Date.parse(p.expiresAt)<=Date.parse(i)?[]:[[d,p.launchId===c?.launchId?c:p]]));return{store:{version:1,revision:s.revision+1,launches:u},value:c?{disposition:l?.status==="pending"?"claimed":"associated",launch:c}:null}})}async function Qse(e,t,n,r){await td(e,t,i=>{let o=i.launches[n];if(!o||o.status!=="claimed")throw new Error("Guardian managed launch is not in the claimed state.");return{store:{version:1,revision:i.revision+1,launches:{...i.launches,[n]:{...o,status:"associated",associationKey:r}}},value:void 0}})}async function eae(e,t,n){if(wr(n)?.automaticAssociation!=="approved_launcher_required")return!1;let r=await lt(e);for(let[i,o]of Object.entries(r.installs)){let s=qn(o,{scope:t,agent:n});for(let a of s){if(a.lifecycle?.state!=="active"&&a.lifecycle?.state!=="pending_activation")continue;let l=gr(o,a);if(f(l,"workspaceId")??f(l,"workingModeWorkspaceId"))return!0;let u=await rd(e,i);if(u==="enforce"||u==="enabled")return!0}}return!1}function Oh(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-authorities.json"):K(e.cwd,".skills-layer","guardian-session-authorities.json")}async function Vo(e,t){let n=await ke(OU(e,t));return n===null?HR():KR(n)}async function fA(e,t,n){let r=OU(e,t);await Zo(Be(r));let i=`${r}.lock`,o=null;try{o=await Uo(i,"wx",384);let s=await Vo(e,t),a=n(s);return await nd(r,a.index),a.value}finally{await o?.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function NU(e,t,n){return await fA(e,t,r=>{let i=WR(r,n,r.revision),o=i.associations[tt(n)];return{index:i,value:o}})}async function jo(e,t,n,r){return await fA(e,t,i=>{let o=ZR(i,{key:n,expectedIndexRevision:i.revision,...r});return{index:o,value:o.associations[n]}})}async function tae(e,t){let n=0;for(let r of["project","global"]){let i=await fA(e,r,o=>{let s=JR(o,{...t,expectedIndexRevision:o.revision});return{index:s.index,value:s.removedKeys}});if(n+=i.length,i.length>0){let o=Oh(e,r),s=await Lh(e,r),a=new Set(i);await nd(o,{version:1,revision:s.revision+1,authorities:Object.fromEntries(Object.entries(s.authorities).filter(([l])=>!a.has(l)))})}await td(e,r,o=>({store:{version:1,revision:o.revision+1,launches:Object.fromEntries(Object.entries(o.launches).filter(([,s])=>s.skillSlug!==t.skillSlug||s.generationId!==t.generationId||s.receiptSha256!==t.receiptSha256))},value:void 0}))}return n}async function Lh(e,t){let n=await ke(Oh(e,t));return!L(n)||n.version!==1||!Number.isSafeInteger(n.revision)||!L(n.authorities)?{version:1,revision:0,authorities:{}}:{version:1,revision:Number(n.revision),authorities:Object.fromEntries(Object.entries(n.authorities).filter(r=>{let i=r[1];return L(i)&&i.version===1&&L(i.envelope)&&L(i.publicKeys)&&typeof i.savedAt=="string"}))}}async function mA(e,t,n,r){let i=Oh(e,t),o=await Lh(e,t);await nd(i,{version:1,revision:o.revision+1,authorities:{...o.authorities,[n]:r}})}async function nae(e,t,n){let r=Oh(e,t),i=await Lh(e,t),o={...i.authorities};delete o[n],await nd(r,{version:1,revision:i.revision+1,authorities:o})}async function rae(e,t,n){return(await Lh(e,t)).authorities[n]??null}function iae(e,t,n){if(!e||e.version!==1||!L(e.envelope)||!L(e.envelope.claims))return!1;let r=e.envelope.claims;return r.agentId===t.agentId&&r.sessionId===t.sessionId&&r.skillSlug===t.skillSlug&&r.version===t.skillVersion&&r.generationId===t.generationId&&r.workspaceId===t.workspaceId&&typeof r.expiresAt=="string"&&Date.parse(r.expiresAt)>Date.parse(n)+5e3}async function nd(e,t){let n=Be(e);await Zo(n);let r=K(n,`.${ot(e)}.${Ge(12).toString("hex")}.tmp`),i=null;try{i=await Uo(r,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
|
|
2165
2165
|
`,"utf8"),await i.sync(),await i.close(),i=null,await zo(r,e),await Jo(e,384),await SA(n)}finally{await i?.close().catch(()=>{}),await We(r,{force:!0}).catch(()=>{})}}function FU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-binding.json"):K(e.cwd,".skills-layer","guardian-session-binding.json")}function MP(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session.json"):K(e.cwd,".skills-layer","guardian-session.json")}function BU(e){return!e||e==="enforce"||e==="enabled"?"enforce":e==="warning"||e==="warning-only"||e==="warning_only"?"warning_only":e==="disabled"||e==="off"?"disabled":null}function MU(e,t){let n=e[t];if(!L(n))return null;let r=Object.entries(n);return r.every(([,i])=>typeof i=="string")?Object.fromEntries(r):null}async function zn(e,t){let n=t?[t]:["project","global"],r=[],i=new Set;for(let l of n){let c=ZU(e,l);if(i.has(c))continue;i.add(c);let u=await JU(c);for(let d of u.hooks){let p=f(d,"hookPath"),m=p?zP(e,l,p):null,h=f(d,"configPath"),g=h?zP(e,l,h):null,y=m?await pr(m):!1,v=g?await pr(g):null,b=y?v===!1?"active_missing_config":"active":"stale_missing_hook",w=await oae({backend:e,scope:l,hook:d,absoluteHookPath:m,absoluteConfigPath:g,hookActive:y,configActive:v});r.push({hookId:f(d,"hookId")??$t,hookName:f(d,"hookName")??xt,...d,scope:f(d,"scope")??l,hookPath:m??p??null,configPath:g??h??null,active:y,configActive:v,hookState:b,strictPreActionBlocking:w.capability==="strict",exactActivationVerified:w.exactActivationVerified,activationRoute:w.activationRoute,evidenceCapability:w.capability,evidenceReasons:w.reasons,nextStep:!y||v===!1?`Run skills-layer guardian hook install --agent ${String(d.agent)} --scope ${l}.`:w.capability!=="strict"?"This hook is installed but not strict-verified. Standard workspaces permit installation with a warning. For strict workspaces, ask your Admin for an adapter with current matching real-host canary evidence; hook install does not create that evidence.":"Strict host evidence is current. Install the approved skill using this exact agent and scope.",evidencePath:w.evidencePath,qualifiedHostExecutablePath:w.qualifiedHostExecutablePath,qualifiedHostExecutableSha256:w.qualifiedHostExecutableSha256})}}let o=r.filter(l=>l.active===!0).length,s=r.filter(l=>l.active===!1).length,a=o>0?0:s;return{status:"ok",enforcementLayer:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0)?"native_hook":o>0?"native_hook_candidate":"not_installed",strictPreActionBlocking:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0),exactActivationVerified:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0&&l.exactActivationVerified===!0),activeHookCount:o,missingHookCount:a,staleHookCount:s,hooks:r,setup:await hA(e),warnings:s>0?o>0?["One or more stale Guardian hook records were found, but an active Skills Layer Security Hook is installed."]:["One or more configured Guardian hooks are missing from disk. Run skills-layer guardian hook install --agent <agent> again to repair them."]:[]}}async function oae(e){let t=f(e.hook,"agent"),n=f(e.hook,"hostVersion"),r=f(e.hook,"adapterRevision"),i=f(e.hook,"absoluteCliPath"),o=f(e.hook,"evidencePath"),s=o?zP(e.backend,e.scope,o):null;if(!t||!vr(t))return{capability:"unverified",reasons:["strict_adapter_unavailable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(wr(t)?.maximumTier!=="strict_candidate")return{capability:"unverified",reasons:["host_strict_tier_unavailable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(!e.hookActive||e.configActive!==!0||!e.absoluteHookPath||!e.absoluteConfigPath)return{capability:"unverified",reasons:["hook_installation_incomplete"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(!n||!r||!i||!s)return{capability:"unverified",reasons:["hook_binding_metadata_missing"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};let a=await ke(s);if(!a)return{capability:"unverified",reasons:["live_canary_evidence_missing"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};try{let l=await lE({agentId:t,platform:fr(e.backend.platform),hostVersion:n,adapterRevision:r,hookConfigPath:e.absoluteConfigPath,hookScriptPath:e.absoluteHookPath,absoluteCliPath:i}),c=aE({evidence:a,currentBinding:l,asOf:e.backend.now()}),u=wr(t),d=c.capability==="strict"&&(u.automaticAssociation==="native_activation"?a.activationRoute==="native_activation":u.automaticAssociation==="approved_launcher_required"&&a.activationRoute==="approved_launcher");return{capability:d?c.capability:"unverified",reasons:d?c.reasons:[...c.reasons,"activation_route_does_not_match_host_capability"],evidencePath:s,exactActivationVerified:d,activationRoute:a.activationRoute,qualifiedHostExecutablePath:a.qualification.hostExecutablePath,qualifiedHostExecutableSha256:a.qualification.hostExecutableSha256}}catch{return{capability:"unverified",reasons:["current_installation_binding_unverifiable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null}}}async function UU(e,t){if(e.json){let c=await ke(t.paths.mcpConfigPath),u=c&&Array.isArray(c.clientIds)?c.clientIds.filter(p=>typeof p=="string"):c&&f(c,"clientId")?[f(c,"clientId")]:[],d=await tz(t,u);return A({setup:await hA(t),mcp:{status:c?"mcp_configured":"mcp_not_configured",configured:!!c,clientId:u[0],clientIds:u,hosts:d,mcpUrl:c?f(c,"mcpUrl"):void 0,readiness:c?{status:"configured_needs_agent_reload",verifyCommand:u.length===1?`skills-layer mcp verify --client ${u[0]}`:"skills-layer mcp verify",nextStep:"Open a fresh agent session if Skills Layer tools are not visible yet."}:void 0,nextCommand:c?"skills-layer mcp verify":"skills-layer mcp setup"},guardian:await zn(t)},"Setup status loaded.",!0,t)}if(!t.stdoutIsTty)return A({status:"setup_needs_terminal",mcp:{nextCommand:"skills-layer mcp setup"},security:{nextCommand:"skills-layer guardian hook install --agent codex --scope project"}},"Setup needs an interactive terminal. Run `skills-layer setup`, or use `skills-layer mcp setup` and `skills-layer guardian hook install --agent codex --scope project`.",!1,t);let n=await t.promptSelect("Set up Skills Layer on this machine?",[{value:"mcp",label:"Setup Skills-Layer MCP",description:"Configure Skills Layer MCP for AI tools"},{value:"security",label:"Setup Skills-Layer Security Guardian",description:"Install Guardian hooks for this workspace"},{value:"both",label:"Setup both - MCP & Security Guardian",description:"Connect supported AI tools and install Guardian hooks"},{value:"not_now",label:"Remind me Later",description:"Skip setup for now; you can run skills-layer setup later"}]);if(n==="not_now"){let c={version:1,setupChoice:"not_now",mcpChoice:"not_now",mcpPromptedAt:t.now(),guardianHookChoice:"not_now",guardianHookPromptedAt:t.now(),remindAfter:lae(t.now(),7)};return await CM(t,c),A({status:"setup_skipped",mcp:{status:"not_configured",nextCommand:"skills-layer mcp setup"},security:{status:"not_configured",nextCommand:"skills-layer guardian hook install --agent codex --scope project"}},"Skills Layer setup skipped for now. Run `skills-layer setup` when you want MCP and Security hooks on this machine.",!1,t)}if(n!=="both"&&n!=="mcp"&&n!=="security")return R(`Unknown setup option "${n}".`,e.json);let r=n==="both"||n==="mcp",i=n==="both"||n==="security",o={status:"setup_complete",setupChoice:n},s={version:1,setupChoice:n,mcpChoice:r?"configured":"not_requested",mcpPromptedAt:t.now(),guardianHookChoice:i?k(e.scope)??"project":"not_requested",guardianHookPromptedAt:t.now()};if(r)if(!t.apiKey)o.mcp={status:"login_required",configured:!1,nextCommand:"skills-layer login"},s.mcpChoice="login_required";else{let c=await XP(e,t);if(fe(c))return c;o.mcp=c}if(i){let c={...e,json:!0,scope:k(e.scope)??"project",agent:k(e.agent)??"codex"},u=await EU(c,t);if(u.exitCode!==0)return u;let d=zae(u.stdout),p=L(d)?d:{status:"enabled",agent:k(c.agent),scope:k(c.scope)};o.security=p,o.agent=f(p,"agent")??k(c.agent),o.scope=f(p,"scope")??k(c.scope),o.enforcementLayer=f(p,"enforcementLayer")??"native_hook_candidate",o.strictPreActionBlocking=p.strictPreActionBlocking===!0,o.hookPath=f(p,"hookPath"),o.configPath=f(p,"configPath"),o.nextAction="guardian.hook.status",o.nextStep=`Run \`skills-layer guardian hook status --scope ${f(p,"scope")??"project"}\` to inspect the candidate binding. Strict pre-action blocking remains unverified until real host allow/deny canaries pass.`}await CM(t,s);let l=(L(o.mcp)?f(o.mcp,"status"):void 0)==="login_required"?"Skills Layer Security setup complete. MCP setup needs login; run `skills-layer login`, then `skills-layer setup`.":n==="security"?"Skills Layer Security Guardian setup complete.":n==="mcp"?"Skills Layer MCP setup complete. Open a fresh agent session if MCP tools are not visible yet.":"Skills Layer MCP and Security Guardian setup complete. Open a fresh agent session if MCP tools are not visible yet.";return A(o,l,e.json,t)}async function sae(e,t){let n=await zn(t),r=await hA(t),i=J(n,"activeHookCount")??0;if(t.stdoutIsTty&&i===0&&!r)return await UU(e,t);let o=i>0?"Guardian host hooks are already configured. Run `skills-layer guardian hook status` to inspect them.":"Guardian is enabled for Skills Layer runtime checks. Run `skills-layer setup` when you want MCP and Security hooks on this machine.";return{exitCode:0,stdout:`${Lo(t.renderMode)}
|
|
2166
2166
|
|
|
2167
|
-
${o}`,stderr:""}}function aae(e,t){let n=J(e,"activeHookCount")??0,r=J(e,"missingHookCount")??0,i=f(t,"status")??"unknown",o=f(t,"effectiveMode"),s=f(t,"adminPolicy"),a=f(t,"nextAction"),l=f(t,"nextStep"),c=e.strictPreActionBlocking===!0;return n>0&&r===0&&c?{id:"guardian-local-hook",title:"Guardian local hook",status:"pass",summary:`Guardian native hook active count: ${n}.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook",strictPreActionBlocking:c,measuredProtection:"verified_strict",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook status"}:n>0&&r===0?{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian candidate hook active count: ${n}; live strict evidence is not current.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook_candidate",strictPreActionBlocking:!1,measuredProtection:"candidate_unverified",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook status",nextStep:"Run the agent/platform live canaries and inspect Guardian hook status before relying on enforced protection."}:{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian native hook setup needs attention. Active hooks: ${n}; missing hooks: ${r}.`,enforcementLayer:f(e,"enforcementLayer")??"not_installed",strictPreActionBlocking:c,measuredProtection:"unavailable",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook install --agent codex --scope project",nextStep:"Install a Guardian host hook for automatic checks, or route risky shell actions through `skills-layer guardian exec` for strict pre-execution blocking."}}function lae(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?e:(n.setUTCDate(n.getUTCDate()+t),n.toISOString())}async function zU(e){let t=VU(k(e.flags.unmanagedPolicy)??e.backend.env.SKILLS_LAYER_UNMANAGED_SKILL_POLICY);if(t.status==="invalid")return{status:"invalid",result:R(t.message,e.flags.json)};let n=await qU({skillSlug:e.skillSlug,flags:e.flags,backend:e.backend,unmanagedPolicy:t.policy});if(n.reasonCode==="local_install_target_selection_required")return To({...e,context:n,reasonCode:n.reasonCode,message:"Guardian needs one exact local skill target before it can make an execution decision.",why:"This skill is installed in more than one target and the command did not identify which materialization is active.",nextAction:"guardian.check",nextStep:"Repeat the command with --agent, --scope, or --path so Guardian can bind the decision to one exact installed target."});if(n.unmanaged&&(n.unmanagedPolicy==="allow"||n.allowUnmanagedOnce))return To({...e,context:n,reasonCode:"guardian_unmanaged_atomic_execution_required",message:"Guardian check cannot authorize unmanaged execution.",why:"A diagnostic check cannot safely bind a one-use decision to the exact local process that would consume it.",nextAction:"install",nextStep:"Install or import the exact skill generation, then use `skills-layer guardian exec <skill-slug> -- <command>` for atomic guarded execution."});if(n.unmanaged&&n.unmanagedPolicy==="block")return To({...e,context:n,reasonCode:"unmanaged_skill_blocked",message:"Guardian blocked unmanaged local skill execution.",why:"The skill path is not backed by a public install index or lockfile entry and unmanaged policy is block.",nextAction:"install",nextStep:"Install or import the exact skill generation before requesting a Guardian execution decision."});let r=n.record?Jt(n.record):null;if(r&&r.state!=="active"){let s=r.state==="quarantined"?"skill_quarantined":r.state==="restore_pending"?"skill_restore_pending":r.state==="externally_removed"?"skill_externally_removed":r.state==="host_detached"?"skill_host_detached":r.state==="unreadable"?"skill_target_unreadable":r.state==="drifted"?"installed_artifact_changed":"skill_activation_pending";return To({...e,context:n,reasonCode:s,message:"Guardian blocked the action because this exact local generation is not active.",why:`The atomic local lifecycle state is ${r.state}.`,nextAction:r.state==="quarantined"?"guardian.incident.review":"installed",nextStep:r.state==="quarantined"?"Review the quarantine evidence and request a fresh exact-generation restore approval before re-enabling the skill.":r.state==="externally_removed"?"Reinstall the exact skill generation, or explicitly remove the retained tombstone after reviewing it.":"Complete or repair the local lifecycle transaction before running this skill."})}if(!n.installedPath)return{status:"ok",context:n};if(await Nae(n.installedPath))return To({...e,context:n,reasonCode:"skill_disabled",message:"Guardian blocked the action because this local skill is disabled.",why:"A local Guardian incident marker is present for this skill.",nextAction:"guardian.incident.review",nextStep:"Review the local incident report before running this skill again."});if(n.unmanaged)return{status:"ok",context:n};let i=await dae(e.skillSlug,n.installedPath);if(n.identityAssessment=i,i.reattestationRequired===!0)return To({...e,context:n,reasonCode:f(i,"reasonCode")??"skill_identity_mismatch",message:"Guardian blocked the action because the installed skill identity changed.",why:"The visible SKILL.md identity no longer matches the installed skill record.",nextStep:"Reinstall or re-attest the skill before running it again."});let o=await pae(e.skillSlug,n.installedPath,e.backend,n.record);return n.driftAssessment=o,o.reattestationRequired===!0?To({...e,context:n,reasonCode:f(o,"reasonCode")??"installed_artifact_changed",message:"Guardian blocked the action because local runtime metadata detected installed artifact drift.",why:"The installed SKILL.md hash no longer matches the materialized runtime metadata.",nextStep:"Reinstall or re-attest the skill before running it again."}):{status:"ok",context:n}}async function To(e){return await Ga(e.backend,{skillSlug:e.skillSlug,version:e.version??e.context.version,action:e.action,decisionStatus:"blocked",reasonCode:e.reasonCode,telemetryMode:e.telemetryMode,path:e.context.installedPath}),{status:"blocked",result:x({status:"blocked",skillSlug:e.skillSlug,version:e.version??e.context.version,reasonCode:e.reasonCode,localPreflight:qu(e.context),unmanaged:e.context.unmanaged,unmanagedPolicy:e.context.unmanagedPolicy,allowUnmanagedOnce:e.context.allowUnmanagedOnce,why:e.why,nextAction:e.nextAction,nextStep:e.nextStep},e.message,e.flags.json,e.reasonCode)}}async function qU(e){let t=VU(k(e.flags.unmanagedPolicy)),n=e.unmanagedPolicy??(t.status==="valid"?t.policy:"warn"),r=k(e.flags.path),i=r?Tt(e.backend.cwd,r):void 0,o=await cae(e.skillSlug,e.backend,{scope:k(e.flags.scope),agent:k(e.flags.agent),installedPath:i}),s=i??o?.installedPath;return{source:r?"explicit_path":o?.source??"install_index",status:r?"ok":o?.status,reasonCode:r?void 0:o?.reasonCode,installedPath:s,archivePath:r?void 0:o?.archivePath,installedPathSource:r?"explicit_path":o?.installedPathSource,version:k(e.flags.version)??o?.version,record:o?.record,unmanaged:!!(r&&!o),unmanagedPolicy:n,allowUnmanagedOnce:e.flags.allowUnmanagedOnce}}async function cae(e,t,n={}){let i=(await Bi(t,e)).installs[e];if(i){let o=qn(i,{...n,platform:t.platform});if(o.length>1)return{source:"install_index",status:"degraded",reasonCode:"local_install_target_selection_required",version:f(i,"version"),record:i};if(o.length===0)return null;let s=gr(i,o[0]),a=SM(s,t);return{source:"install_index",installedPath:a.installedPath,archivePath:a.archivePath,installedPathSource:a.installedPathSource,status:a.status,reasonCode:a.reasonCode,version:f(s,"version"),record:s}}for(let o of uae(t)){let s=await ke(o);if(!L(s)||!L(s.installs))continue;let a=s.installs[e];if(L(a)){let l=SM(a,t);return{source:"lockfile",installedPath:l.installedPath,archivePath:l.archivePath,installedPathSource:l.installedPathSource,status:l.status,reasonCode:l.reasonCode,version:f(a,"version"),record:a}}}return null}function uae(e){return Array.from(new Set([K(e.cwd,"skills-layer-lock.json"),K(e.paths.stateDir,"skills-layer-lock.json")]))}function SM(e,t){let n=f(e,"materializedSkillRoot");if(n)return{installedPath:ph(Tt(t.cwd,n)),installedPathSource:"materializedSkillRoot",status:"ok"};let r=f(e,"canonicalPath");if(r)return{installedPath:ph(Tt(t.cwd,r)),installedPathSource:"canonicalPath",status:"ok"};let i=f(e,"path");if(i)return{installedPath:ph(Tt(t.cwd,i)),installedPathSource:"path",status:"ok"};let o=f(e,"materializedPath")??f(e,"bundlePath");if(o){let c=Tt(t.cwd,o),u=it(c).toLowerCase()==="bundle.zip"||c.toLowerCase().endsWith(".zip");return{installedPath:u?Be(Be(c)):ph(c),archivePath:u?c:void 0,installedPathSource:f(e,"materializedPath")?"materializedPath":"bundlePath",status:u?"degraded":"ok",reasonCode:u?"installed_skill_root_missing":void 0}}let a=(Array.isArray(e.materializedWrites)?e.materializedWrites.filter(L):[]).find(c=>{let u=f(c,"path");return u?.toLowerCase().endsWith("/skill.md")||u?.toLowerCase()==="skill.md"}),l=a?f(a,"path"):void 0;return{installedPath:l?Be(Tt(t.cwd,l)):void 0,installedPathSource:l?"materializedWrites":void 0,status:l?"ok":void 0}}function ph(e){return it(e).toLowerCase()==="skill.md"?Be(e):e}async function dae(e,t){let n=K(t,"SKILL.md");if(!await pr(n))return{status:"not_checked",reasonCode:"skill_document_unavailable",expectedSkillSlug:e,reattestationRequired:!1};try{let r=gU(await Fi(n,"utf8"));return r?r!==e?{status:"mismatch",reasonCode:"skill_identity_mismatch",expectedSkillSlug:e,observedSkillName:r,skillDocumentPath:n,reattestationRequired:!0}:{status:"matched",expectedSkillSlug:e,observedSkillName:r,skillDocumentPath:n,reattestationRequired:!1}:{status:"not_checked",reasonCode:"skill_identity_metadata_unavailable",expectedSkillSlug:e,skillDocumentPath:n,reattestationRequired:!1}}catch(r){return{status:"invalid",reasonCode:"skill_identity_unreadable",expectedSkillSlug:e,skillDocumentPath:n,message:ve(r),reattestationRequired:!0}}}async function pae(e,t,n,r){let i=r?Jt(r):null;if(i){let p=await Dr(i.receipt);return p.status==="verified"?{status:"unchanged",reasonCode:"installed_tree_manifest_matches",skillSlug:e,generationId:i.receipt.generation.generationId,manifestSha256:i.receipt.manifestSha256,reattestationRequired:!1}:{status:"changed",reasonCode:p.reasonCode,skillSlug:e,generationId:i.receipt.generation.generationId,manifestSha256:i.receipt.manifestSha256,reattestationRequired:!0}}let o=K(t,".skills-layer-runtime.json"),s=await ke(o),a=s?j(s,"materialization"):void 0,l=a?f(a,"skillDocumentSha256"):void 0;if(!s||!l)return{status:"not_checked",reasonCode:"runtime_metadata_unavailable",skillSlug:e,reattestationRequired:!0};let c=K(t,"SKILL.md");if(!await pr(c))return{status:"changed",reasonCode:"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:l,reattestationRequired:!0};let u=ez(await Fi(c,"utf8")),d=u===l;return{status:d?"unchanged":"changed",reasonCode:d?"installed_artifact_matches":"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:l,observedSkillDocumentSha256:u,reattestationRequired:!d}}function qu(e){return ie({source:e.source,status:e.status,reasonCode:e.reasonCode,installedPath:e.installedPath,archivePath:e.archivePath,installedPathSource:e.installedPathSource,version:e.version,unmanaged:e.unmanaged,unmanagedPolicy:e.unmanagedPolicy,allowUnmanagedOnce:e.allowUnmanagedOnce,identityAssessment:e.identityAssessment,driftAssessment:e.driftAssessment})}function VU(e){if(e===void 0||e.trim()==="")return{status:"valid",policy:"warn"};let t=e.trim().toLowerCase();return t==="allow"||t==="warn"||t==="block"?{status:"valid",policy:t}:{status:"invalid",message:"guardian check --unmanaged-policy must be one of: allow, warn, block."}}function UP(e,t){let n=k(e)??t;return n==="cloud_managed"||n==="local_only"?{status:"valid",mode:n}:{status:"invalid",message:"guardian --telemetry-mode must be one of: cloud_managed, local_only."}}function xM(e,t){return{type:"shell_command",command:it(t?.executableRealPath??e[0]??"command"),...t?{metadata:{executableRealPath:t.executableRealPath,executableSha256:t.executableSha256,argvSha256:HU(t.argv),cwdRealPath:t.cwdRealPath,fileTargets:t.fileTargets,networkTargets:t.networkTargets,environmentKeys:t.environmentKeys,callerActionJsonIgnored:!0,callerGrantJsonIgnored:!0}}:{}}}function fae(e){let t=j(e,"enforcement");return typeof t?.canExecute=="boolean"?t.canExecute:qP(e)!=="blocked"}async function mae(e){let t=gae(e.backend.platform);if(!t)return Ou(e,"guardian_platform_unsupported","Guardian guarded execution is unavailable on this platform.");if(t==="win32")return Ou(e,"windows_process_tree_isolation_unavailable","Guardian strict execution on Windows requires a verified Job Object process-tree adapter.");if(e.commandArgs.some(_ae))return Ou(e,"guardian_secret_in_argv","Guardian refuses likely credentials in command arguments; pass only explicitly brokered named environment secrets.");try{let[n,r]=await Promise.all([GU(e.commandArgs[0],e.backend,t),Fu(e.backend.cwd)]),i=await Ja(n);if(!i.isFile()||i.size<=0||i.size>256*1024*1024)return Ou(e,"guardian_executable_invalid","Guardian requires a bounded regular executable file.");let o=`sha256:${Me("sha256").update(await Fi(n)).digest("hex")}`,s=wae(e.flags,e.backend.env),a=await yae(e.commandArgs.slice(1),r,e.backend,t),l=k(e.flags.agent)??(e.localContext.record?f(e.localContext.record,"agent")??f(e.localContext.record,"targetAgent"):void 0)??Re(e.backend.config?.lastSelectedAgent)??"skills-layer-cli";return{status:"ok",approvedSecrets:s,request:{platform:t,actionFamily:"shell_execution",executableRealPath:n,executableSha256:o,argv:e.commandArgs.slice(1),cwdRealPath:r,fileTargets:a.fileTargets,networkTargets:a.networkTargets,immutableInputs:a.immutableInputs,environmentKeys:bae(t,Object.keys(s)),skillSlug:e.skillSlug,version:e.version,...k(e.flags.workspaceId)?{workspaceId:k(e.flags.workspaceId)}:{},agentId:l,hostVersion:So,sessionId:`guardian_session_${Ge(16).toString("hex")}`}}}catch(n){let r=n instanceof $e?n.reasonCode:"guardian_plan_resolution_failed";return Ou(e,r,`Guardian could not resolve the exact execution plan: ${ve(n)}`)}}function Ou(e,t,n){return{status:"blocked",result:x({status:"blocked",reasonCode:t,skillSlug:e.skillSlug},n,e.flags.json,t)}}function gae(e){return e==="darwin"||e==="linux"||e==="win32"?e:null}async function GU(e,t,n){if(!e||/[\u0000-\u001f\u007f]/u.test(e))throw new Error("Executable name is invalid.");let r=n==="win32"?ot:Lt,o=r.isAbsolute(e)||e.includes("/")||e.includes("\\")?[r.isAbsolute(e)?e:r.resolve(t.cwd,e)]:hae(e,t,n);for(let s of o.slice(0,128))try{await FM(s,n==="win32"?CB.F_OK:CB.X_OK);let a=await Fu(s);if((await Ja(a)).isFile())return a}catch{}throw new Error(`Executable ${it(e)} was not found as an accessible regular file.`)}function hae(e,t,n){let r=n==="win32"?ot:Lt,o=(Re(t.env.PATH)??(n==="win32"?"C:\\Windows\\System32":"/usr/local/bin:/usr/bin:/bin")).split(n==="win32"?";":":").filter(Boolean).slice(0,64),s=n==="win32"&&!ot.extname(e)?(Re(t.env.PATHEXT)??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean).slice(0,8):[""];return o.flatMap(a=>s.map(l=>r.join(a,`${e}${l}`)))}async function yae(e,t,n,r){let i=new Set,o=new Set,s=new Map;for(let[a,l]of e.entries()){let c=l.startsWith("--")&&l.includes("=")?l.slice(l.indexOf("=")+1):l;if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(c)){let p=new URL(c);if(p.protocol!=="https:")throw new Error("Guardian network targets must use HTTPS.");o.add(p.toString());continue}if(!vae(c,r))continue;let u=await kae(c,t,n,r);i.add(u);let d=await Ja(u).catch(()=>null);if(d?.isFile()){let p=s.get(u);p?p.argumentIndexes.push(a):s.set(u,{path:u,sha256:`sha256:${Me("sha256").update(await Fi(u)).digest("hex")}`,size:d.size,argumentIndexes:[a]})}}return{fileTargets:[...i].sort(vh),networkTargets:[...o].sort(vh),immutableInputs:[...s.values()].sort((a,l)=>vh(a.path,l.path))}}function vae(e,t){return!e||e.startsWith("-")?!1:(t==="win32"?ot:Lt).isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e.includes("/")||e.includes("\\")}async function kae(e,t,n,r){let i=r==="win32"?ot:Lt,o=r==="win32"?Re(n.env.USERPROFILE)??Re(n.env.HOME):Re(n.env.HOME),s=e.startsWith("~/")&&o?i.join(o,e.slice(2)):e,a=i.normalize(i.isAbsolute(s)?s:i.resolve(t,s));try{return await Fu(a)}catch{let l=await Fu(i.dirname(a));return i.join(l,i.basename(a))}}function wae(e,t){let n=Array.isArray(e.secretEnv)?e.secretEnv:typeof e.secretEnv=="string"?[e.secretEnv]:[],r={};for(let i of[...new Set(n)]){if(!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u.test(i))throw new Error(`Secret environment key ${i} is invalid.`);let o=t[i];if(typeof o!="string"||o.length===0)throw new Error(`Secret environment key ${i} is unavailable.`);r[i]=o}return r}function bae(e,t){let n=e==="win32"?["PATH","SystemRoot","TEMP","TMP","USERPROFILE"]:["HOME","PATH","TMPDIR"];return[...new Set([...n,...t])].sort(vh)}function _ae(e){return/(?:mktplace_|slg_exec_|github_pat_|gh[opusr]_|sk-)[A-Za-z0-9_-]{8,}/u.test(e)||/(?:password|passwd|secret|token|api[_-]?key)\s*[=:]\s*[^\s]+/iu.test(e)||/-----BEGIN [^-\r\n]{1,64} PRIVATE KEY-----/u.test(e)}function HU(e){return`sha256:${Me("sha256").update(JSON.stringify(e),"utf8").digest("hex")}`}function vh(e,t){return e<t?-1:e>t?1:0}function Sae(e){let t=[e.exitCode===0?"OK Guardian guarded execution complete.":"Guardian guarded execution finished with a command error.","","Command",` executable: ${e.executable}`,` args count: ${e.argsCount}`,` exit code: ${e.exitCode}`];return e.stdout&&t.push("","Stdout",e.stdout),e.stderr&&t.push("","Stderr",e.stderr),t.join(`
|
|
2167
|
+
${o}`,stderr:""}}function aae(e,t){let n=J(e,"activeHookCount")??0,r=J(e,"missingHookCount")??0,i=f(t,"status")??"unknown",o=f(t,"effectiveMode"),s=f(t,"adminPolicy"),a=f(t,"nextAction"),l=f(t,"nextStep"),c=e.strictPreActionBlocking===!0;return n>0&&r===0&&c?{id:"guardian-local-hook",title:"Guardian local hook",status:"pass",summary:`Guardian native hook active count: ${n}.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook",strictPreActionBlocking:c,measuredProtection:"verified_strict",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook status"}:n>0&&r===0?{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian candidate hook active count: ${n}; live strict evidence is not current.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook_candidate",strictPreActionBlocking:!1,measuredProtection:"candidate_unverified",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook status",nextStep:"Run the agent/platform live canaries and inspect Guardian hook status before relying on enforced protection."}:{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian native hook setup needs attention. Active hooks: ${n}; missing hooks: ${r}.`,enforcementLayer:f(e,"enforcementLayer")??"not_installed",strictPreActionBlocking:c,measuredProtection:"unavailable",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook install --agent codex --scope project",nextStep:"Install a Guardian host hook for automatic checks, or route risky shell actions through `skills-layer guardian exec` for strict pre-execution blocking."}}function lae(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?e:(n.setUTCDate(n.getUTCDate()+t),n.toISOString())}async function zU(e){let t=VU(k(e.flags.unmanagedPolicy)??e.backend.env.SKILLS_LAYER_UNMANAGED_SKILL_POLICY);if(t.status==="invalid")return{status:"invalid",result:R(t.message,e.flags.json)};let n=await qU({skillSlug:e.skillSlug,flags:e.flags,backend:e.backend,unmanagedPolicy:t.policy});if(n.reasonCode==="local_install_target_selection_required")return To({...e,context:n,reasonCode:n.reasonCode,message:"Guardian needs one exact local skill target before it can make an execution decision.",why:"This skill is installed in more than one target and the command did not identify which materialization is active.",nextAction:"guardian.check",nextStep:"Repeat the command with --agent, --scope, or --path so Guardian can bind the decision to one exact installed target."});if(n.unmanaged&&(n.unmanagedPolicy==="allow"||n.allowUnmanagedOnce))return To({...e,context:n,reasonCode:"guardian_unmanaged_atomic_execution_required",message:"Guardian check cannot authorize unmanaged execution.",why:"A diagnostic check cannot safely bind a one-use decision to the exact local process that would consume it.",nextAction:"install",nextStep:"Install or import the exact skill generation, then use `skills-layer guardian exec <skill-slug> -- <command>` for atomic guarded execution."});if(n.unmanaged&&n.unmanagedPolicy==="block")return To({...e,context:n,reasonCode:"unmanaged_skill_blocked",message:"Guardian blocked unmanaged local skill execution.",why:"The skill path is not backed by a public install index or lockfile entry and unmanaged policy is block.",nextAction:"install",nextStep:"Install or import the exact skill generation before requesting a Guardian execution decision."});let r=n.record?Jt(n.record):null;if(r&&r.state!=="active"){let s=r.state==="quarantined"?"skill_quarantined":r.state==="restore_pending"?"skill_restore_pending":r.state==="externally_removed"?"skill_externally_removed":r.state==="host_detached"?"skill_host_detached":r.state==="unreadable"?"skill_target_unreadable":r.state==="drifted"?"installed_artifact_changed":"skill_activation_pending";return To({...e,context:n,reasonCode:s,message:"Guardian blocked the action because this exact local generation is not active.",why:`The atomic local lifecycle state is ${r.state}.`,nextAction:r.state==="quarantined"?"guardian.incident.review":"installed",nextStep:r.state==="quarantined"?"Review the quarantine evidence and request a fresh exact-generation restore approval before re-enabling the skill.":r.state==="externally_removed"?"Reinstall the exact skill generation, or explicitly remove the retained tombstone after reviewing it.":"Complete or repair the local lifecycle transaction before running this skill."})}if(!n.installedPath)return{status:"ok",context:n};if(await Nae(n.installedPath))return To({...e,context:n,reasonCode:"skill_disabled",message:"Guardian blocked the action because this local skill is disabled.",why:"A local Guardian incident marker is present for this skill.",nextAction:"guardian.incident.review",nextStep:"Review the local incident report before running this skill again."});if(n.unmanaged)return{status:"ok",context:n};let i=await dae(e.skillSlug,n.installedPath);if(n.identityAssessment=i,i.reattestationRequired===!0)return To({...e,context:n,reasonCode:f(i,"reasonCode")??"skill_identity_mismatch",message:"Guardian blocked the action because the installed skill identity changed.",why:"The visible SKILL.md identity no longer matches the installed skill record.",nextStep:"Reinstall or re-attest the skill before running it again."});let o=await pae(e.skillSlug,n.installedPath,e.backend,n.record);return n.driftAssessment=o,o.reattestationRequired===!0?To({...e,context:n,reasonCode:f(o,"reasonCode")??"installed_artifact_changed",message:"Guardian blocked the action because local runtime metadata detected installed artifact drift.",why:"The installed SKILL.md hash no longer matches the materialized runtime metadata.",nextStep:"Reinstall or re-attest the skill before running it again."}):{status:"ok",context:n}}async function To(e){return await Ga(e.backend,{skillSlug:e.skillSlug,version:e.version??e.context.version,action:e.action,decisionStatus:"blocked",reasonCode:e.reasonCode,telemetryMode:e.telemetryMode,path:e.context.installedPath}),{status:"blocked",result:x({status:"blocked",skillSlug:e.skillSlug,version:e.version??e.context.version,reasonCode:e.reasonCode,localPreflight:qu(e.context),unmanaged:e.context.unmanaged,unmanagedPolicy:e.context.unmanagedPolicy,allowUnmanagedOnce:e.context.allowUnmanagedOnce,why:e.why,nextAction:e.nextAction,nextStep:e.nextStep},e.message,e.flags.json,e.reasonCode)}}async function qU(e){let t=VU(k(e.flags.unmanagedPolicy)),n=e.unmanagedPolicy??(t.status==="valid"?t.policy:"warn"),r=k(e.flags.path),i=r?Tt(e.backend.cwd,r):void 0,o=await cae(e.skillSlug,e.backend,{scope:k(e.flags.scope),agent:k(e.flags.agent),installedPath:i}),s=i??o?.installedPath;return{source:r?"explicit_path":o?.source??"install_index",status:r?"ok":o?.status,reasonCode:r?void 0:o?.reasonCode,installedPath:s,archivePath:r?void 0:o?.archivePath,installedPathSource:r?"explicit_path":o?.installedPathSource,version:k(e.flags.version)??o?.version,record:o?.record,unmanaged:!!(r&&!o),unmanagedPolicy:n,allowUnmanagedOnce:e.flags.allowUnmanagedOnce}}async function cae(e,t,n={}){let i=(await Bi(t,e)).installs[e];if(i){let o=qn(i,{...n,platform:t.platform});if(o.length>1)return{source:"install_index",status:"degraded",reasonCode:"local_install_target_selection_required",version:f(i,"version"),record:i};if(o.length===0)return null;let s=gr(i,o[0]),a=SM(s,t);return{source:"install_index",installedPath:a.installedPath,archivePath:a.archivePath,installedPathSource:a.installedPathSource,status:a.status,reasonCode:a.reasonCode,version:f(s,"version"),record:s}}for(let o of uae(t)){let s=await ke(o);if(!L(s)||!L(s.installs))continue;let a=s.installs[e];if(L(a)){let l=SM(a,t);return{source:"lockfile",installedPath:l.installedPath,archivePath:l.archivePath,installedPathSource:l.installedPathSource,status:l.status,reasonCode:l.reasonCode,version:f(a,"version"),record:a}}}return null}function uae(e){return Array.from(new Set([K(e.cwd,"skills-layer-lock.json"),K(e.paths.stateDir,"skills-layer-lock.json")]))}function SM(e,t){let n=f(e,"materializedSkillRoot");if(n)return{installedPath:ph(Tt(t.cwd,n)),installedPathSource:"materializedSkillRoot",status:"ok"};let r=f(e,"canonicalPath");if(r)return{installedPath:ph(Tt(t.cwd,r)),installedPathSource:"canonicalPath",status:"ok"};let i=f(e,"path");if(i)return{installedPath:ph(Tt(t.cwd,i)),installedPathSource:"path",status:"ok"};let o=f(e,"materializedPath")??f(e,"bundlePath");if(o){let c=Tt(t.cwd,o),u=ot(c).toLowerCase()==="bundle.zip"||c.toLowerCase().endsWith(".zip");return{installedPath:u?Be(Be(c)):ph(c),archivePath:u?c:void 0,installedPathSource:f(e,"materializedPath")?"materializedPath":"bundlePath",status:u?"degraded":"ok",reasonCode:u?"installed_skill_root_missing":void 0}}let a=(Array.isArray(e.materializedWrites)?e.materializedWrites.filter(L):[]).find(c=>{let u=f(c,"path");return u?.toLowerCase().endsWith("/skill.md")||u?.toLowerCase()==="skill.md"}),l=a?f(a,"path"):void 0;return{installedPath:l?Be(Tt(t.cwd,l)):void 0,installedPathSource:l?"materializedWrites":void 0,status:l?"ok":void 0}}function ph(e){return ot(e).toLowerCase()==="skill.md"?Be(e):e}async function dae(e,t){let n=K(t,"SKILL.md");if(!await pr(n))return{status:"not_checked",reasonCode:"skill_document_unavailable",expectedSkillSlug:e,reattestationRequired:!1};try{let r=gU(await Fi(n,"utf8"));return r?r!==e?{status:"mismatch",reasonCode:"skill_identity_mismatch",expectedSkillSlug:e,observedSkillName:r,skillDocumentPath:n,reattestationRequired:!0}:{status:"matched",expectedSkillSlug:e,observedSkillName:r,skillDocumentPath:n,reattestationRequired:!1}:{status:"not_checked",reasonCode:"skill_identity_metadata_unavailable",expectedSkillSlug:e,skillDocumentPath:n,reattestationRequired:!1}}catch(r){return{status:"invalid",reasonCode:"skill_identity_unreadable",expectedSkillSlug:e,skillDocumentPath:n,message:ve(r),reattestationRequired:!0}}}async function pae(e,t,n,r){let i=r?Jt(r):null;if(i){let p=await Dr(i.receipt);return p.status==="verified"?{status:"unchanged",reasonCode:"installed_tree_manifest_matches",skillSlug:e,generationId:i.receipt.generation.generationId,manifestSha256:i.receipt.manifestSha256,reattestationRequired:!1}:{status:"changed",reasonCode:p.reasonCode,skillSlug:e,generationId:i.receipt.generation.generationId,manifestSha256:i.receipt.manifestSha256,reattestationRequired:!0}}let o=K(t,".skills-layer-runtime.json"),s=await ke(o),a=s?j(s,"materialization"):void 0,l=a?f(a,"skillDocumentSha256"):void 0;if(!s||!l)return{status:"not_checked",reasonCode:"runtime_metadata_unavailable",skillSlug:e,reattestationRequired:!0};let c=K(t,"SKILL.md");if(!await pr(c))return{status:"changed",reasonCode:"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:l,reattestationRequired:!0};let u=ez(await Fi(c,"utf8")),d=u===l;return{status:d?"unchanged":"changed",reasonCode:d?"installed_artifact_matches":"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:l,observedSkillDocumentSha256:u,reattestationRequired:!d}}function qu(e){return ie({source:e.source,status:e.status,reasonCode:e.reasonCode,installedPath:e.installedPath,archivePath:e.archivePath,installedPathSource:e.installedPathSource,version:e.version,unmanaged:e.unmanaged,unmanagedPolicy:e.unmanagedPolicy,allowUnmanagedOnce:e.allowUnmanagedOnce,identityAssessment:e.identityAssessment,driftAssessment:e.driftAssessment})}function VU(e){if(e===void 0||e.trim()==="")return{status:"valid",policy:"warn"};let t=e.trim().toLowerCase();return t==="allow"||t==="warn"||t==="block"?{status:"valid",policy:t}:{status:"invalid",message:"guardian check --unmanaged-policy must be one of: allow, warn, block."}}function UP(e,t){let n=k(e)??t;return n==="cloud_managed"||n==="local_only"?{status:"valid",mode:n}:{status:"invalid",message:"guardian --telemetry-mode must be one of: cloud_managed, local_only."}}function xM(e,t){return{type:"shell_command",command:ot(t?.executableRealPath??e[0]??"command"),...t?{metadata:{executableRealPath:t.executableRealPath,executableSha256:t.executableSha256,argvSha256:HU(t.argv),cwdRealPath:t.cwdRealPath,fileTargets:t.fileTargets,networkTargets:t.networkTargets,environmentKeys:t.environmentKeys,callerActionJsonIgnored:!0,callerGrantJsonIgnored:!0}}:{}}}function fae(e){let t=j(e,"enforcement");return typeof t?.canExecute=="boolean"?t.canExecute:qP(e)!=="blocked"}async function mae(e){let t=gae(e.backend.platform);if(!t)return Ou(e,"guardian_platform_unsupported","Guardian guarded execution is unavailable on this platform.");if(t==="win32")return Ou(e,"windows_process_tree_isolation_unavailable","Guardian strict execution on Windows requires a verified Job Object process-tree adapter.");if(e.commandArgs.some(_ae))return Ou(e,"guardian_secret_in_argv","Guardian refuses likely credentials in command arguments; pass only explicitly brokered named environment secrets.");try{let[n,r]=await Promise.all([GU(e.commandArgs[0],e.backend,t),Fu(e.backend.cwd)]),i=await Ja(n);if(!i.isFile()||i.size<=0||i.size>256*1024*1024)return Ou(e,"guardian_executable_invalid","Guardian requires a bounded regular executable file.");let o=`sha256:${Me("sha256").update(await Fi(n)).digest("hex")}`,s=wae(e.flags,e.backend.env),a=await yae(e.commandArgs.slice(1),r,e.backend,t),l=k(e.flags.agent)??(e.localContext.record?f(e.localContext.record,"agent")??f(e.localContext.record,"targetAgent"):void 0)??Re(e.backend.config?.lastSelectedAgent)??"skills-layer-cli";return{status:"ok",approvedSecrets:s,request:{platform:t,actionFamily:"shell_execution",executableRealPath:n,executableSha256:o,argv:e.commandArgs.slice(1),cwdRealPath:r,fileTargets:a.fileTargets,networkTargets:a.networkTargets,immutableInputs:a.immutableInputs,environmentKeys:bae(t,Object.keys(s)),skillSlug:e.skillSlug,version:e.version,...k(e.flags.workspaceId)?{workspaceId:k(e.flags.workspaceId)}:{},agentId:l,hostVersion:So,sessionId:`guardian_session_${Ge(16).toString("hex")}`}}}catch(n){let r=n instanceof $e?n.reasonCode:"guardian_plan_resolution_failed";return Ou(e,r,`Guardian could not resolve the exact execution plan: ${ve(n)}`)}}function Ou(e,t,n){return{status:"blocked",result:x({status:"blocked",reasonCode:t,skillSlug:e.skillSlug},n,e.flags.json,t)}}function gae(e){return e==="darwin"||e==="linux"||e==="win32"?e:null}async function GU(e,t,n){if(!e||/[\u0000-\u001f\u007f]/u.test(e))throw new Error("Executable name is invalid.");let r=n==="win32"?st:Lt,o=r.isAbsolute(e)||e.includes("/")||e.includes("\\")?[r.isAbsolute(e)?e:r.resolve(t.cwd,e)]:hae(e,t,n);for(let s of o.slice(0,128))try{await FM(s,n==="win32"?CB.F_OK:CB.X_OK);let a=await Fu(s);if((await Ja(a)).isFile())return a}catch{}throw new Error(`Executable ${ot(e)} was not found as an accessible regular file.`)}function hae(e,t,n){let r=n==="win32"?st:Lt,o=(Re(t.env.PATH)??(n==="win32"?"C:\\Windows\\System32":"/usr/local/bin:/usr/bin:/bin")).split(n==="win32"?";":":").filter(Boolean).slice(0,64),s=n==="win32"&&!st.extname(e)?(Re(t.env.PATHEXT)??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean).slice(0,8):[""];return o.flatMap(a=>s.map(l=>r.join(a,`${e}${l}`)))}async function yae(e,t,n,r){let i=new Set,o=new Set,s=new Map;for(let[a,l]of e.entries()){let c=l.startsWith("--")&&l.includes("=")?l.slice(l.indexOf("=")+1):l;if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(c)){let p=new URL(c);if(p.protocol!=="https:")throw new Error("Guardian network targets must use HTTPS.");o.add(p.toString());continue}if(!vae(c,r))continue;let u=await kae(c,t,n,r);i.add(u);let d=await Ja(u).catch(()=>null);if(d?.isFile()){let p=s.get(u);p?p.argumentIndexes.push(a):s.set(u,{path:u,sha256:`sha256:${Me("sha256").update(await Fi(u)).digest("hex")}`,size:d.size,argumentIndexes:[a]})}}return{fileTargets:[...i].sort(vh),networkTargets:[...o].sort(vh),immutableInputs:[...s.values()].sort((a,l)=>vh(a.path,l.path))}}function vae(e,t){return!e||e.startsWith("-")?!1:(t==="win32"?st:Lt).isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e.includes("/")||e.includes("\\")}async function kae(e,t,n,r){let i=r==="win32"?st:Lt,o=r==="win32"?Re(n.env.USERPROFILE)??Re(n.env.HOME):Re(n.env.HOME),s=e.startsWith("~/")&&o?i.join(o,e.slice(2)):e,a=i.normalize(i.isAbsolute(s)?s:i.resolve(t,s));try{return await Fu(a)}catch{let l=await Fu(i.dirname(a));return i.join(l,i.basename(a))}}function wae(e,t){let n=Array.isArray(e.secretEnv)?e.secretEnv:typeof e.secretEnv=="string"?[e.secretEnv]:[],r={};for(let i of[...new Set(n)]){if(!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u.test(i))throw new Error(`Secret environment key ${i} is invalid.`);let o=t[i];if(typeof o!="string"||o.length===0)throw new Error(`Secret environment key ${i} is unavailable.`);r[i]=o}return r}function bae(e,t){let n=e==="win32"?["PATH","SystemRoot","TEMP","TMP","USERPROFILE"]:["HOME","PATH","TMPDIR"];return[...new Set([...n,...t])].sort(vh)}function _ae(e){return/(?:mktplace_|slg_exec_|github_pat_|gh[opusr]_|sk-)[A-Za-z0-9_-]{8,}/u.test(e)||/(?:password|passwd|secret|token|api[_-]?key)\s*[=:]\s*[^\s]+/iu.test(e)||/-----BEGIN [^-\r\n]{1,64} PRIVATE KEY-----/u.test(e)}function HU(e){return`sha256:${Me("sha256").update(JSON.stringify(e),"utf8").digest("hex")}`}function vh(e,t){return e<t?-1:e>t?1:0}function Sae(e){let t=[e.exitCode===0?"OK Guardian guarded execution complete.":"Guardian guarded execution finished with a command error.","","Command",` executable: ${e.executable}`,` args count: ${e.argsCount}`,` exit code: ${e.exitCode}`];return e.stdout&&t.push("","Stdout",e.stdout),e.stderr&&t.push("","Stderr",e.stderr),t.join(`
|
|
2168
2168
|
`)}function Xa(e){let t=k(e)??"project";return t==="project"||t==="global"?{status:"valid",scope:t}:{status:"invalid",message:"guardian hooks --scope must be one of: project, global."}}function KU(e){return K(e.paths.stateDir,"guardian-modes.json")}function WU(e){return K(e.paths.stateDir,"setup-state.json")}async function gA(e){let t=await ke(KU(e));return{version:1,skills:L(t?.skills)?t.skills:{}}}async function xae(e,t,n){let r=await gA(e);await Ve(KU(e),{version:1,skills:{...r.skills,[t]:{requestedPreference:f(n,"requestedPreference")??"enforce",effectiveMode:f(n,"effectiveMode")??"enforce",reasonCode:f(n,"reasonCode"),auditId:f(n,"auditId"),updatedAt:e.now()}}})}async function rd(e,t){let r=(await gA(e)).skills[t];return r?f(r,"requestedPreference"):void 0}async function Cae(e,t){return(await gA(e)).skills[t]}async function hA(e){let t=await ke(WU(e));return L(t)?{version:1,setupChoice:f(t,"setupChoice"),mcpChoice:f(t,"mcpChoice"),mcpPromptedAt:f(t,"mcpPromptedAt"),guardianHookChoice:f(t,"guardianHookChoice"),guardianHookPromptedAt:f(t,"guardianHookPromptedAt"),remindAfter:f(t,"remindAfter")}:null}async function CM(e,t){await Ve(WU(e),t)}function Iae(e,t,n,r){let i=t==="global"?e.targets.globalRoot:e.targets.projectRoot;if(!i)return null;if(e.id==="codex")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"hooks.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="claude-code")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"settings.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="cline")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"guardian-hooks.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="gemini-cli"){let o=t==="project"?K(n.cwd,".gemini"):i;return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(o,"settings.json"),hookPath:K(o,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}}if(e.id==="cursor")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"hooks.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="github-copilot"){let o=t==="project"?K(n.cwd,".github","hooks"):K(i,"hooks");return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(o,"skills-layer-guardian.json"),hookPath:K(o,"skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}}if(e.id==="opencode")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"skills-layer-guardian.json"),hookPath:K(i,"plugins","skills-layer-guardian.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="windsurf")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"hooks.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="antigravity"||e.id==="antigravity-cli"){let o=t==="project"?K(n.cwd,".agents"):K(Be(i),"config");return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(o,"hooks.json"),hookPath:K(o,"hooks",`skills-layer-guardian-${e.id}.mjs`),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}}return e.id==="kiro-cli"?{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"hooks","skills-layer-guardian.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}:null}async function Pae(e,t,n){await Mo(Be(e.hookPath),{recursive:!0,mode:448}),await Mo(Be(e.configPath),{recursive:!0,mode:448});let r=IM(n?.hookFileOwnership),i=await Lae(t),o=await Py({operation:r?"update":"install",filePath:e.hookPath,content:e.agent==="opencode"?Tae(e,i,process.execPath):Oae(e.agent,e.scope,i,e.hostVersion),...r?{previousOwnership:r}:{}});if(e.agent==="windsurf"){let l=e.agent,c=["pre_read_code","pre_write_code","pre_run_command","pre_mcp_tool_use"],u=Array.isArray(n?.configEntryOwnerships)?n.configEntryOwnerships.flatMap(p=>{for(let m of c){let h=hP(p,l,m);if(h)return[h]}return[]}):[],d=[];for(let p of c){let m=u.find(g=>g.eventName===p),h=await xd({configPath:e.configPath,update:{operation:m?"update":"install",agentId:l,eventName:p,absoluteScriptPath:e.hookPath,...m?{previousOwnership:m}:{}}});d.push(h.ownership)}return{hookFileOwnership:o.ownership,configEntryOwnerships:d,absoluteCliPath:i}}if(e.agent==="codex"||e.agent==="claude-code"||e.agent==="gemini-cli"||e.agent==="cursor"||e.agent==="antigravity"||e.agent==="antigravity-cli"){let l=e.agent==="gemini-cli"?"BeforeTool":e.agent==="cursor"?"preToolUse":"PreToolUse",c=hP(n?.configEntryOwnership,e.agent,l),u=await xd({configPath:e.configPath,update:{operation:c?"update":"install",agentId:e.agent,eventName:l,absoluteScriptPath:e.hookPath,...c?{previousOwnership:c}:{}}}),d;if(e.agent==="claude-code"){let p=hP(n?.activationConfigEntryOwnership,e.agent,"UserPromptExpansion");d=(await xd({configPath:e.configPath,update:{operation:p?"update":"install",agentId:e.agent,eventName:"UserPromptExpansion",absoluteScriptPath:e.hookPath,...p?{previousOwnership:p}:{}}})).ownership}return{hookFileOwnership:o.ownership,configEntryOwnership:u.ownership,...d?{activationConfigEntryOwnership:d}:{},absoluteCliPath:i}}let s=IM(n?.configFileOwnership),a=await Py({operation:s?"update":"install",filePath:e.configPath,content:`${JSON.stringify(e.agent==="kiro-cli"?Eae(e):e.agent==="github-copilot"?$ae(e,process.execPath):e.agent==="opencode"?Dae(e):Rae(e,t),null,2)}
|
|
2169
|
-
`,...s?{previousOwnership:s}:{}});return{hookFileOwnership:o.ownership,configFileOwnership:a.ownership,absoluteCliPath:i}}function ZU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-hooks.json"):K(e.cwd,".skills-layer","guardian-hooks.json")}function Aae(e,t,n,r){let i=t==="global"?e.paths.stateDir:K(e.cwd,".skills-layer");return K(i,"guardian-hook-evidence",`${n}-${r}-${fr(e.platform)}.json`)}async function JU(e){let t=await ke(e);return{version:1,hooks:Array.isArray(t?.hooks)?t.hooks.filter(L):[]}}function zP(e,t,n){return
|
|
2169
|
+
`,...s?{previousOwnership:s}:{}});return{hookFileOwnership:o.ownership,configFileOwnership:a.ownership,absoluteCliPath:i}}function ZU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-hooks.json"):K(e.cwd,".skills-layer","guardian-hooks.json")}function Aae(e,t,n,r){let i=t==="global"?e.paths.stateDir:K(e.cwd,".skills-layer");return K(i,"guardian-hook-evidence",`${n}-${r}-${fr(e.platform)}.json`)}async function JU(e){let t=await ke(e);return{version:1,hooks:Array.isArray(t?.hooks)?t.hooks.filter(L):[]}}function zP(e,t,n){return st.isAbsolute(n)||n.startsWith("/")?n:qo(t==="global"?e.paths.stateDir:e.cwd,n)}function Rae(e,t){return{version:1,hookId:$t,hookName:xt,agent:e.agent,agentName:e.agentName,scope:e.scope,enforcementLayer:e.enforcementLayer,strictPreActionBlocking:e.strictPreActionBlocking,installedAt:t.now(),hooks:[{name:xt,id:$t,event:"PreToolUse",command:`node ${YU(e.hookPath)}`,status:"candidate"}]}}function Eae(e){return{version:"v1",hooks:[{name:xt,description:"Skills Layer Guardian pre-tool authorization",trigger:"PreToolUse",matcher:".*",action:{type:"command",command:`node ${YU(e.hookPath)}`},timeout:0,enabled:!0}]}}function $ae(e,t){return{version:1,hooks:{PreToolUse:[{type:"command",matcher:"*",exec:t,args:[e.hookPath],timeoutSec:10}]}}}function Dae(e){return{version:1,agent:"opencode",scope:e.scope,hostVersion:e.hostVersion,hookEvent:"tool.execute.before",hookPath:e.hookPath,enabled:!0}}function Tae(e,t,n){return`import { spawnSync } from "node:child_process";
|
|
2170
2170
|
import { readFileSync } from "node:fs";
|
|
2171
2171
|
|
|
2172
2172
|
const configPath = ${JSON.stringify(e.configPath)};
|
|
@@ -2265,39 +2265,39 @@ process.exit(${e==="windsurf"||e==="github-copilot"?"result.status === 0 ? 0 : 2
|
|
|
2265
2265
|
`}async function Lae(e){let t=Re(e.env.SKILLS_LAYER_CLI_PATH),n=qo(t??process.argv[1]??""),r=await Xu(n);if(!r.isFile()&&!r.isSymbolicLink())throw new Error("Guardian hook CLI path must resolve to the installed Skills Layer executable.");return await Fu(n)}function IM(e){if(!(!L(e)||e.owner!=="skills-layer"||typeof e.fileSha256!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.fileSha256)))return{owner:"skills-layer",fileSha256:e.fileSha256}}function hP(e,t,n="PreToolUse"){if(!(!L(e)||e.owner!=="skills-layer"||e.agentId!==t||e.eventName!==n||typeof e.entrySha256!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.entrySha256)))return{owner:"skills-layer",agentId:t,eventName:n,entrySha256:e.entrySha256}}function YU(e){return JSON.stringify(e)}async function jae(e){let t=e.generationId??e.version??"unversioned",n=K(e.backend.paths.stateDir,"runtime",encodeURIComponent(e.skillSlug),`${encodeURIComponent(t)}.json`),r={version:1,generatedAt:e.backend.now(),skillSlug:e.skillSlug,sourceProvider:{id:"skills-layer",name:"Skills Layer",managedBy:"skills-layer-cli"},...e.version?{skillVersion:e.version}:{},...e.generationId?{generationId:e.generationId}:{},guardian:{required:!0,enforcementLayer:"cloud_guardian_with_local_preflight",strictPreActionBlocking:!1,checkCommand:`skills-layer guardian check --skill ${e.skillSlug} --json`,incidentCommand:`skills-layer guardian incident ${e.skillSlug} --path <installed-skill-path> --telemetry-mode local_only --json`,guardedExecutorCommand:`skills-layer guardian exec ${e.skillSlug} --json -- <command>`,mcpCheckTool:"guardian.check",mcpEnforceTool:"guardian.enforce",agentCommandMatrix:GC({purpose:"materialize_skill",command:`skills-layer install ${e.skillSlug}`,jsonCommand:`skills-layer install ${e.skillSlug} --json`,skillSlug:e.skillSlug}),agentGuidance:"MCP-capable agents should call guardian.check or guardian.enforce before risky tool use. Local host hooks should call skills-layer guardian check, and shell actions that need strict wrapping should use skills-layer guardian exec.",sensitiveActionFamilies:["shell_command","network_request","file_read","file_write","secret_read","browser_action","device_action","api_call","generated_code_execution","model_context_promotion"]},materialization:{skillDocumentPath:"SKILL.md",skillDocumentSha256:ez(e.skillDocumentContent)}},i=`${JSON.stringify(r,null,2)}
|
|
2266
2266
|
`;return await Ve(n,r),{path:yU(e.backend.cwd,n),bytes:new TextEncoder().encode(i).length}}async function Nae(e){return await pr(K(e,".skills-layer-disabled.json"))}async function PM(e){let t=e.backend.now(),r=(await lt(e.backend)).installs[e.skillSlug],i=qn(r,{installedPath:e.installedPath,platform:e.backend.platform}),o=i.length===1?i[0]:void 0,s=o&&r?gr(r,o):void 0,a=o?.lifecycle??null;if(!s||!a||!o)return{status:"blocked",reasonCode:"guardian_exact_install_receipt_missing",skillSlug:e.skillSlug,generatedAt:t,nextAction:"install",nextStep:"Install the approved skill through Skills Layer before using managed Guardian quarantine."};if(a.state!=="active"&&a.state!=="pending_activation")return{status:"blocked",reasonCode:"guardian_local_lifecycle_not_active",skillSlug:e.skillSlug,generatedAt:t,localLifecycle:a,nextAction:"guardian.incident.review",nextStep:"Review the existing quarantine or incomplete lifecycle before recording another incident."};if(!yA(e.installedPath,a.receipt.targetDir,e.backend.platform)||e.version!==a.receipt.generation.semanticVersion)return{status:"blocked",reasonCode:"guardian_incident_generation_mismatch",skillSlug:e.skillSlug,generatedAt:t,requestedVersion:e.version,receiptGeneration:a.receipt.generation,nextAction:"guardian.incident.review",nextStep:"Use the indexed exact path and version; Guardian will not quarantine a caller-selected mismatch."};let l;try{l=await pA({backend:e.backend,skillSlug:e.skillSlug,record:s,materializationId:o.materializationId,lifecycle:a,reasonCode:"guardian_incident",purpose:"quarantine_blocked",status:"quarantined"})}catch(h){return{status:"blocked",reasonCode:"guardian_exact_quarantine_failed",skillSlug:e.skillSlug,generatedAt:t,error:ve(h),nextAction:"guardian.incident.review",nextStep:"Keep the skill blocked. Resolve exact-tree drift or filesystem permissions before retrying quarantine."}}let c=t.replace(/[:.]/gu,"-"),u=K(e.backend.paths.incidentsDir,`${e.skillSlug}-${c}.md`),d=K(e.backend.paths.incidentsDir,`${e.skillSlug}-${c}-evidence.json`),p=f(e.action,"type")??"unknown";await Ve(d,{version:1,generatedAt:t,skillSlug:e.skillSlug,skillVersion:e.version,actionType:p,reason:VP(e.reason),localLifecycle:l.lifecycle});let m=["# Skills Layer Guardian Incident Report","",`Generated: ${t}`,`Skill: ${e.skillSlug}`,`Version: ${e.version}`,"","## Summary","",VP(e.reason),"","## Evidence","",`- ${t}: ${p} -> blocked and physically quarantined`].join(`
|
|
2267
2267
|
`);return await Zo(Be(u)),await ZP(u,`${m}
|
|
2268
|
-
`,{encoding:"utf8",mode:384}),await Jo(u,384),{status:"quarantined",generatedAt:t,incidentPath:u,evidencePath:d,quarantineDir:l.quarantine.quarantineDir,localLifecycle:l.lifecycle,writtenFiles:[u,d]}}function yA(e,t,n){let r=n==="win32"?
|
|
2268
|
+
`,{encoding:"utf8",mode:384}),await Jo(u,384),{status:"quarantined",generatedAt:t,incidentPath:u,evidencePath:d,quarantineDir:l.quarantine.quarantineDir,localLifecycle:l.lifecycle,writtenFiles:[u,d]}}function yA(e,t,n){let r=n==="win32"?st:Lt,i=r.resolve(e).normalize("NFC"),o=r.resolve(t).normalize("NFC");return n==="linux"?i===o:i.toLocaleLowerCase("en-US")===o.toLocaleLowerCase("en-US")}function AM(e,t){let n=e.now().replace(/[:.]/gu,"-");return K(e.paths.incidentsDir,`${t}-${n}.json`)}async function Ga(e,t){let n=K(e.paths.stateDir,"guardian-audit.jsonl");await Zo(Be(n));let r=await Fae(n),i=t.authority?j(t.authority,"exactGeneration"):void 0,o=t.authority?j(t.authority,"guardianMode"):void 0,s=ie({version:2,generatedAt:e.now(),skillSlug:t.skillSlug,...t.version?{skillVersion:t.version}:{},actionType:f(t.action,"type")??"unknown",actionDigest:`sha256:${Me("sha256").update(Ph(t.action)).digest("hex")}`,actionTarget:Mae(t.action),decisionStatus:t.decisionStatus,reasonCode:t.reasonCode,telemetryMode:t.telemetryMode,telemetryDelivery:t.authority?f(t.authority,"telemetryDelivery")??t.telemetryMode:t.telemetryMode,...i?{generationId:f(i,"generationId"),archiveSha256:f(i,"archiveSha256"),servingRevision:i.servingRevision}:{},...o?{effectiveMode:f(o,"effectiveMode")}:{},...r?{previousEntryHash:r}:{},...t.path?{localPath:QU(t.path)}:{}}),a=`sha256:${Me("sha256").update(Ph(s)).digest("hex")}`,l=`${JSON.stringify({...s,entryHash:a})}
|
|
2269
2269
|
`;await Bae(n,Buffer.byteLength(l)),await Xne(n,l,{encoding:"utf8",mode:384}),await Jo(n,384)}var XU=1048576,RM=3;async function Fae(e){let t=await Ja(e).catch(()=>null);if(!t?.isFile()||t.size===0||t.size>XU)return;let r=(await Fi(e,"utf8")).trimEnd().split(`
|
|
2270
|
-
`).at(-1);if(r)try{let i=JSON.parse(r),o=f(i,"entryHash");return o&&/^sha256:[a-f0-9]{64}$/u.test(o)?o:void 0}catch{return}}async function Bae(e,t){let n=await Ja(e).catch(()=>null);if(!(!n?.isFile()||n.size+t<=XU)){await We(`${e}.${RM}`,{force:!0});for(let r=RM-1;r>=1;r-=1)await zo(`${e}.${r}`,`${e}.${r+1}`).catch(i=>{if(i.code!=="ENOENT")throw i});await zo(e,`${e}.1`)}}function Ph(e){if(Array.isArray(e))return`[${e.map(Ph).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Ph(t[n])}`).join(",")}}`}return JSON.stringify(e)??"null"}function qP(e){let t=j(e,"decision"),n=j(e,"enforcement"),r=f(t??{},"status")??f(n??{},"status")??f(e,"status");return r==="allowed"||r==="advisory"?r:"blocked"}function Ah(e){let t=j(e,"decision");return f(t??{},"reasonCode")??f(e,"reasonCode")??f(e,"status")??"cloud_guardian_decision"}function Mae(e){let t=f(e,"type");if(t==="secret_read")return"redacted_secret";if(t==="shell_command")return"redacted_command";let n=f(e,"url");if(n)try{return new URL(n).origin}catch{return"redacted_url"}let r=f(e,"target");if(r)return VP(r);let i=f(e,"path");return i?QU(i):null}function QU(e){let t=
|
|
2270
|
+
`).at(-1);if(r)try{let i=JSON.parse(r),o=f(i,"entryHash");return o&&/^sha256:[a-f0-9]{64}$/u.test(o)?o:void 0}catch{return}}async function Bae(e,t){let n=await Ja(e).catch(()=>null);if(!(!n?.isFile()||n.size+t<=XU)){await We(`${e}.${RM}`,{force:!0});for(let r=RM-1;r>=1;r-=1)await zo(`${e}.${r}`,`${e}.${r+1}`).catch(i=>{if(i.code!=="ENOENT")throw i});await zo(e,`${e}.1`)}}function Ph(e){if(Array.isArray(e))return`[${e.map(Ph).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Ph(t[n])}`).join(",")}}`}return JSON.stringify(e)??"null"}function qP(e){let t=j(e,"decision"),n=j(e,"enforcement"),r=f(t??{},"status")??f(n??{},"status")??f(e,"status");return r==="allowed"||r==="advisory"?r:"blocked"}function Ah(e){let t=j(e,"decision");return f(t??{},"reasonCode")??f(e,"reasonCode")??f(e,"status")??"cloud_guardian_decision"}function Mae(e){let t=f(e,"type");if(t==="secret_read")return"redacted_secret";if(t==="shell_command")return"redacted_command";let n=f(e,"url");if(n)try{return new URL(n).origin}catch{return"redacted_url"}let r=f(e,"target");if(r)return VP(r);let i=f(e,"path");return i?QU(i):null}function QU(e){let t=ot(e.trim());return t?`<local-path>/${t}`:"<local-path>"}function VP(e){return e.replace(/sk-[A-Za-z0-9_-]+/gu,"[redacted-secret]").replace(/[A-Z0-9_]*SECRET[A-Z0-9_]*/gu,"[redacted-secret]").replace(/[A-Z0-9_]*TOKEN[A-Z0-9_]*/gu,"[redacted-token]").replace(/[A-Z0-9_]*KEY[A-Z0-9_]*/gu,"[redacted-key]")}function EM(e){return e.split(/[\\/]+/u).join("/")}function ez(e){return Me("sha256").update(e).digest("hex")}async function vA(e,t,n,r,i){let o=Ho(),s=k(n.mfaCode),a=k(n.recoveryCode),l=()=>D(r,"/api/v1/verify",{method:"POST",headers:V(),body:JSON.stringify({email:e,code:t,handoffCodeHash:o.authorizationCodeHash,handoffCodeChallenge:o.codeChallenge,...s?{mfaCode:s}:{},...a?{recoveryCode:a}:{}})}),c;try{c=await l()}catch(d){if(!(d instanceof Z)||d.details?.reasonCode!=="login_mfa_required"||n.json||r.nonInteractive||!r.stdoutIsTty)throw d;let p=await r.promptSelect("Complete MFA to finish email login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),m=(await r.promptSecret(p==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();p==="recovery_code"?a=m:s=m,c=await l()}if(f(c,"status")!=="verified")return R("Email verification did not prepare a secure credential handoff. Restart verification.",n.json);let u=await D(r,"/api/v1/identity/credential-handoff/exchange",{method:"POST",headers:V(),body:JSON.stringify({authorizationCode:o.authorizationCode,codeVerifier:o.codeVerifier})});if(f(u,"status")!=="exchanged"||!f(u,"email")||!f(u,"role")||!f(u,"apiKey"))return R("Email verification credential handoff failed closed. Restart verification.",n.json);if(n.json){let d=f(u,"apiKey");if(d){let p=await Vu(r,d,{expectedEmail:e,knownEmail:f(u,"email")??e,knownRole:f(u,"role")??"user",knownRoles:Un(u,"roles"),knownUserId:f(u,"userId"),knownSessionCredentialId:f(u,"id")}),m=await wh(n,{...r,config:p,apiKey:d});return fe(m)?m:A(Nt({...u,loggedIn:!0,...m.data?{workspaceSelection:m.data}:{}}),["Email verified and login completed.",m.message??""].filter(Boolean).join(" "),!0,r)}return A(Nt({...u,email:e,loggedIn:!1,nextCommand:`skills-layer login --method email --email ${e}`,nextAction:"login"}),"Email verified. Login still needs to be completed.",!0,r)}return await kA(e,u,n,r,i)}async function kA(e,t,n,r,i){let o=f(t,"apiKey"),s=f(t,"role")??"user",a=Un(t,"roles"),l=f(t,"userId"),c=o;if(!c&&n.json)return A(Nt({...t,email:e,role:s,...a?{roles:a}:{},loggedIn:!1}),`${i} Login still needs to be completed through a human handoff.`,!0,r);if(!c)try{c=(await r.promptSecret(`Enter the API key emailed to ${e} (check spam/junk folder if missing): `)).trim()}catch{return A(Nt({...t,email:e,role:s,...a?{roles:a}:{},loggedIn:!1}),`${i} Check your email (including spam/junk folder) for the API key, then run \`skills-layer login\` to finish signing in.`,n.json,r)}if(!c)return R("No API key was entered. Run `skills-layer login` once you have the emailed key.",n.json);let u=await Vu(r,c,{expectedEmail:e,knownEmail:e,knownRole:s,knownRoles:a,knownUserId:l,knownSessionCredentialId:f(t,"id"),forceProfileValidation:!o}),d=await wh(n,{...r,config:u,apiKey:c});if(fe(d))return d;let p=await xP(n,{...r,config:u,apiKey:c});if(fe(p))return p;let m=p.data?.status==="mcp_not_configured";return A(Nt(CP({...t,status:m?"partial_success":f(t,"status")??"verified",email:u.email,role:u.role,...u.roles?{roles:u.roles}:{},loggedIn:!0,...d.data?{workingMode:d.data}:{},...p.data?{mcp:p.data}:{},...m?{warnings:[p.data]}:{}},p.data)),[`${i} Logged in as ${u.email}.`,d.message??"",p.message??""].filter(Boolean).join(" "),n.json,r)}function Ho(){let e=`social_handoff_${Ge(32).toString("base64url")}`,t=Ge(48).toString("base64url");return{authorizationCode:e,codeVerifier:t,authorizationCodeHash:Me("sha256").update(e).digest("base64url"),codeChallenge:Me("sha256").update(t).digest("base64url")}}async function wA(e){if(!e.backend.nonInteractive)return null;if(!e.backend.credentialStore)return No(e.flags,e.backend);let t=`social_${Ge(18).toString("base64url")}`,n=`skills-layer-social-continuation:${t}`,r={version:1,reference:t,baseUrl:e.backend.baseUrl,provider:e.provider,mode:e.mode,authorizationCode:e.credentialHandoff.authorizationCode,codeVerifier:e.credentialHandoff.codeVerifier,authorizationCodeHash:e.credentialHandoff.authorizationCodeHash,codeChallenge:e.credentialHandoff.codeChallenge,createdAt:e.backend.now()},i={...r,integrityDigest:bA(r)};try{let o=JSON.stringify(i);if(await e.backend.credentialStore.set(Le,n,o),await e.backend.credentialStore.get(Le,n)!==o)return await e.backend.credentialStore.delete(Le,n),No(e.flags,e.backend)}catch{return await e.backend.credentialStore.delete(Le,n).catch(()=>{}),No(e.flags,e.backend)}return{reference:t,account:n,secret:i}}function No(e,t){return x({status:"security_unavailable",reasonCode:"social_secure_continuation_unavailable",unchanged:!0,nextAction:"login.interactive",nextStep:"Run the same command in an interactive human terminal with OS-secure credential storage available."},"Secure social continuation is unavailable. No browser login was started.",e.json,"social_secure_continuation_unavailable")}async function Uae(e,t,n){if(!n.credentialStore)return!1;let r=f(t,"state"),i=f(t,"expiresAt");if(!r||!i)return await n.credentialStore.delete(Le,e.account).catch(()=>{}),!1;let o={version:e.secret.version,reference:e.secret.reference,baseUrl:e.secret.baseUrl,provider:e.secret.provider,mode:e.secret.mode,authorizationCode:e.secret.authorizationCode,codeVerifier:e.secret.codeVerifier,authorizationCodeHash:e.secret.authorizationCodeHash,codeChallenge:e.secret.codeChallenge,createdAt:e.secret.createdAt,state:r,expiresAt:i},s={...o,integrityDigest:bA(o)};try{let a=JSON.stringify(s);return await n.credentialStore.set(Le,e.account,a),await n.credentialStore.get(Le,e.account)===a}catch{return await n.credentialStore.delete(Le,e.account).catch(()=>{}),!1}}function bA(e){return Me("sha256").update(JSON.stringify([e.version,e.reference,e.baseUrl,e.provider,e.mode,e.authorizationCode,e.codeVerifier,e.authorizationCodeHash,e.codeChallenge,e.createdAt,e.state??null,e.expiresAt??null])).digest("base64url")}async function jh(e,t,n,r,i,o,s="/api/v1/identity/social/status",a=null){let l=f(t,"authorizationUrl"),c=T(f(t,"state"),"Social auth did not return a state."),u=kz(e);if(i.nonInteractive)return!a||!await Uae(a,t,i)?No(r,i):A({status:"human_action_required",reasonCode:"social_auth_browser_handoff",provider:e,mode:o,authorizationUrl:l,reference:a.reference,expiresAt:f(t,"expiresAt"),nextAction:"identity.continue",nextStep:`Complete the browser sign-in, then run \`skills-layer identity continue --reference ${a.reference}\`.`},`${u} browser sign-in is ready. Complete it, then continue with the returned non-secret reference.`,r.json,i);if(l){let p=r.noOpen?!1:await i.openUrl(l);r.json||i.emitInfo(o==="recovery"?p?`${u} recovery started. Finish the verification in your browser, then come back here. Waiting for browser recovery to finish...`:`${u} recovery started. Open this URL in your browser, then come back here once it is done:
|
|
2271
2271
|
${l}
|
|
2272
2272
|
Waiting for browser recovery to finish...`:p?`${u} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`:`${u} sign-in started. Open this URL in your browser, then come back here once it is done:
|
|
2273
2273
|
${l}
|
|
2274
|
-
Waiting for browser sign-in to finish...`)}else r.json||i.emitInfo(o==="recovery"?`${u} recovery started. Finish the verification in your browser, then come back here. Waiting for browser recovery to finish...`:`${u} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`);let d=await Vae(c,i,s);if(fe(d))return d;if(d.status==="verified"||d.status==="recovered")return await kh(u,n,r,i,o);if(d.status==="mfa_required"){if(!n)return R("Login MFA handoff is unavailable. Start login again.",r.json);let p=k(r.mfaCode),m=k(r.recoveryCode);if(!p&&!m&&!r.json&&i.stdoutIsTty){let g=await i.promptSelect("Complete MFA to finish login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),y=(await i.promptSecret(g==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();g==="recovery_code"?m=y:p=y}if(!p&&!m)return x({status:"human_action_required",reasonCode:"login_mfa_required",methods:["authenticator","recovery_code"],nextAction:"account.login.mfa",nextStep:"Re-run login in a human terminal and complete MFA."},"MFA is required to finish login.",r.json,"login_mfa_required");let h=await D(i,"/api/v1/identity/login/mfa/verify",{method:"POST",headers:V(),body:JSON.stringify({state:c,authorizationCode:n.authorizationCode,codeVerifier:n.codeVerifier,...p?{mfaCode:p}:{},...m?{recoveryCode:m}:{}})});return f(h,"status")!=="verified"||f(h,"credentialHandoff")!=="ready"?R("MFA verification did not authorize the login credential. Start login again.",r.json):await kh(u,n,r,i,o)}if(d.status==="already_registered"||d.status==="link_required"){let p=UF(e,!!i.apiKey&&!i.authBlockedMessage);return x({...p},p.summary,r.json,"social_identity_link_required")}if(d.status==="registration_confirmation_required"){if(!r.json&&i.stdoutIsTty){let m=await i.promptSelect(`Create a new Skills Layer account using your verified ${u} identity?`,[{value:"create",label:"Yes, create my account",description:"Create one account, connect this sign-in, and log in"},{value:"cancel",label:"No",description:"Create nothing and leave Skills Layer unchanged"}])==="create",h=await D(i,"/api/v1/identity/social/registration/confirm",{method:"POST",headers:V(),body:JSON.stringify({state:c,createAccount:m})});return!m||f(h,"status")==="registration_cancelled"?A({status:"registration_cancelled",changed:!1},"Registration cancelled. No Skills Layer account was created.",!1,i):f(h,"status")!=="verified"||f(h,"credentialHandoff")!=="ready"?R("Account creation could not be confirmed safely. Start registration again.",!1):await kh(u,n,r,i,"register")}return x({status:"registration_confirmation_required",reasonCode:"registration_confirmation_required",nextAction:"account.registration.confirm",nextStep:r.createAccount?"Provider verification finished, but account creation still needs confirmation. Start registration again.":"Re-run registration with --create-account after confirming that you want to create this account."},"Account creation needs explicit confirmation.",r.json,"registration_confirmation_required")}return d.status==="linked"?A(d,`${u} sign-in is now connected.`,r.json,i):qae(d)?R(Jae(d),r.json):R("Social auth completed with an unexpected response.",r.json)}async function kh(e,t,n,r,i){if(!t)return R("Social credential handoff is unavailable. Start the login flow again.",n.json);let o=await D(r,"/api/v1/identity/social/exchange",{method:"POST",headers:V(),body:JSON.stringify({authorizationCode:t.authorizationCode,codeVerifier:t.codeVerifier})});if(f(o,"status")!=="exchanged"||!f(o,"email")||!f(o,"role")||!f(o,"apiKey"))return R("Social credential handoff failed closed. Start the login flow again.",n.json);let s=f(o,"email");return await kA(s,o,n,r,i==="recovery"?`Recovered access for ${s} through ${e}.`:`Verified ${s} through ${e}.`)}function Ko(e){return e==="google"||e==="github"||e==="gitlab"||e==="microsoft"}function fe(e){return L(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function zae(e){try{let t=JSON.parse(e);return L(t)?t.data:void 0}catch{return}}function qae(e){return e.status==="registration_required"||e.status==="state_expired"||e.status==="provider_mismatch"||e.status==="identity_conflict"||e.status==="email_required"||e.status==="failed"}async function Vae(e,t,n="/api/v1/identity/social/status"){for(let r=0;r<120;r+=1)try{let i=await D(t,`${n}/${encodeURIComponent(e)}`,n.includes("/identity/connect/")?{headers:re(t.apiKey,t.authBlockedMessage)}:void 0),o=f(i,"status")??"failed";if(o==="pending"){await t.sleep(1500);continue}return(o==="verified"||o==="recovered")&&f(i,"credentialHandoff")==="ready"?{status:o,credentialHandoff:"ready"}:o==="already_registered"||o==="link_required"?{status:o}:o==="linked"?{status:o}:o==="registration_confirmation_required"?{status:o}:o==="mfa_required"?{status:o}:o==="registration_required"||o==="state_expired"||o==="provider_mismatch"||o==="identity_conflict"||o==="email_required"||o==="failed"?{status:o,error:f(i,"error")}:R("Social auth completed with an unexpected response.",!1)}catch(i){if(i instanceof Z&&(i.status===404||i.status===429)){await t.sleep(1500);continue}return R(ve(i),!1)}return R("Timed out while waiting for social auth to complete.",!1)}async function Gae(e,t){let n=`/api/v1/identity/mfa/recovery-codes/operations/${encodeURIComponent(e)}`;for(let r=0;r<210;r+=1)try{let i=await D(t,n,{headers:re(t.apiKey,t.authBlockedMessage)}),o=f(i,"status"),s=j(i,"data");if(o==="pending"||o==="finalizing"){await t.sleep(1500);continue}if(o==="completed")return{...i,completedAt:f(i,"completedAt")??(s?f(s,"completedAt"):void 0)};if(o==="locked"){let a=f(i,"retryAt")??(s?f(s,"retryAt"):void 0);return x({status:"locked",reasonCode:"mfa_challenge_locked",retryAt:a,nextAction:"wait",nextStep:a?`Retry after ${a}.`:"Wait for the MFA verification lock to expire, then retry."},"Recovery-code verification is temporarily locked after too many invalid attempts.",!1)}return o==="failed"?x({status:"failed",reasonCode:"mfa_recovery_codes_failed",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"Recovery codes were not replaced.",!1):o==="expired"?x({status:"expired",reasonCode:"mfa_recovery_codes_expired",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"The recovery-code browser session expired before completion.",!1):R("Recovery-code verification completed with an unexpected response.",!1)}catch(i){if(i instanceof Z&&i.status===429){let o=i.details??{},s=f(o,"reasonCode"),a=f(o,"retryAt");if(s==="mfa_challenge_locked")return x({status:"locked",reasonCode:s,retryAt:a,nextAction:"wait",nextStep:a?`Retry after ${a}.`:"Wait for the MFA verification lock to expire, then retry."},"Recovery-code verification is temporarily locked after too many invalid attempts.",!1);let l=J(o,"retryAfterSeconds"),c=l===void 0?1500:Math.min(6e4,Math.max(1500,l*1e3));await t.sleep(c);continue}return R(ve(i),!1)}return x({status:"expired",reasonCode:"mfa_recovery_codes_expired",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"Timed out while waiting for recovery-code verification.",!1)}async function Hae(e,t){for(let n=0;n<120;n+=1)try{let r=await D(t,`/api/v1/purchases/${encodeURIComponent(e)}`,{headers:re(t.apiKey,t.authBlockedMessage)});if(!r?.status||r.status==="pending"||r.status==="requires_action"){await t.sleep(1500);continue}return{status:r.status,purchaseId:e}}catch(r){if(r instanceof Z&&r.status===429){await t.sleep(1500);continue}return R(ve(r),!1)}return R("Timed out while waiting for purchase confirmation.",!1)}async function Kae(e,t,n){let r=null;for(let i=0;i<120;i+=1)try{let o=await D(n,e,{headers:re(n.apiKey,n.authBlockedMessage)});r=o;let s=f(o,"status");if(!s||s==="checkout_required"||s==="pending"||s==="requires_action"||s==="payment_received"||s==="provisioning"||s==="finalizing"){await n.sleep(1500);continue}return o}catch(o){if(o instanceof Z&&o.status===429){await n.sleep(1500);continue}return R(ve(o),!1)}try{let i=await D(n,e,{headers:re(n.apiKey,n.authBlockedMessage)}),o=f(i,"status");if(o&&!["checkout_required","pending","requires_action","payment_received","provisioning","finalizing"].includes(o))return i;r=i}catch{}return{...r??{},status:"completion_pending",reasonCode:"enterprise_checkout_completion_pending",checkoutId:t,statusPath:e,retrySafe:!0,nextAction:"check_checkout_status",nextStep:"Check this checkout status again. Do not start a second checkout."}}async function Wae(e,t){for(let n=0;n<120;n+=1)try{let r=await D(t,`/api/v1/me/private-skill-charges/${encodeURIComponent(e)}`,{headers:re(t.apiKey,t.authBlockedMessage)}),i=f(r,"status");if(!i||i==="checkout_required"||i==="pending"||i==="requires_action"){await t.sleep(1500);continue}return{...r,status:i}}catch(r){if(r instanceof Z&&r.status===429){await t.sleep(1500);continue}return R(ve(r),!1)}return R("Timed out while waiting for payment confirmation.",!1)}function Zae(e){let t=j(e,"accountLink");return(t?f(t,"url"):void 0)??f(e,"url")??f(e,"setupUrl")}function Jae(e){return e.status==="registration_confirmation_required"?"Account creation requires explicit confirmation.":e.status==="registration_required"?e.error??"No verified account exists for this social identity. Use `skills-layer register` first.":e.status==="state_expired"?"Social auth expired before completion. Start the flow again.":e.status==="provider_mismatch"?"The browser completed a different social provider than the one the CLI started.":e.status==="identity_conflict"?e.error??"This social identity is already linked to another account.":e.status==="email_required"?e.error??"This social profile did not provide an email address.":e.error??"Social auth could not be completed."}async function Vu(e,t,n={}){let i=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole?await D({...e,apiKey:t},"/api/v1/me",{headers:{...re(t),...n.notifyLogin?{"x-skills-layer-session-intent":"login"}:{}}}):{userId:n.knownUserId,sessionCredentialId:n.knownSessionCredentialId,email:n.knownEmail,role:n.knownRole,roles:n.knownRoles},o=f(i,"email")??n.knownEmail??"unknown";if(n.expectedEmail&&o.toLowerCase()!==n.expectedEmail.toLowerCase())throw new Error(`The entered API key belongs to ${o}, not ${n.expectedEmail}. Use the API key emailed to ${n.expectedEmail}.`);let s=await D({...e,apiKey:t},"/api/v1/capabilities",{headers:re(t)}),a={version:tre,baseUrl:e.baseUrl,apiKey:t,edition:f(s,"edition")??f(i,"edition")??"saas",userId:f(i,"userId")??n.knownUserId,sessionCredentialId:f(i,"sessionCredentialId")??n.knownSessionCredentialId,email:o,role:f(i,"role")??n.knownRole??"user",roles:Un(i,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await CA(e.paths.configPath,a,e),await pce(e,a),await Ve(e.paths.backendPreferencePath,{version:JP,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),a}function $M(e,t){let n=ln(e.actionJson,"action-json");if(n&&typeof n=="object"&&!Array.isArray(n))return n;let r=k(e.action);return t==="incident"?{type:"file_write",path:k(e.path)??".skills-layer/incidents/guardian-incident.json"}:r==="file_read"||r==="file_write"?{type:r,path:k(e.path)??"."}:r==="shell_command"?{type:"shell_command",command:"unspecified"}:{type:"api_call",...r?{target:r}:{}}}async function me(e,t,n,r,i={}){let o=i.authenticated?re(n.apiKey,n.authBlockedMessage):Wo(n.apiKey);return await Gu(e,{headers:o},t,n,r)}async function Yae(e,t){let[n,r,i]=await Promise.all([D(t,"/api/v1/status",{headers:Wo(t.apiKey)}),zn(t),Nh(t)]),o={guardian:r,mcp:i.publicState};return A({...n,localRuntime:o},"Status loaded.",e.json,t)}async function tz(e,t){let n=new Set(t);return(await Wh({env:e.env,platform:e.platform,cwd:e.cwd,pathExists:e.pathExists})).map(r=>({...r,managedConfigured:n.has(r.hostId)}))}async function Nh(e){let t=await ke(e.paths.mcpConfigPath),n=t&&Array.isArray(t.clientIds)?t.clientIds.filter(d=>typeof d=="string"&&Ot(d)!==null):t&&f(t,"clientId")&&Ot(f(t,"clientId"))?[f(t,"clientId")]:[],r=await tz(e,n),i=r.filter(d=>d.installed),o=r.filter(d=>d.configured),s=r.filter(d=>d.managedConfigured),a=!!t,l=!a&&i.length>0,c=a?"mcp_configured":l?"mcp_hosts_detected_unmanaged":"mcp_not_configured",u=a?`Skills Layer MCP is configured for ${n.length} managed host${n.length===1?"":"s"}.`:l?"MCP-capable hosts or host configuration were detected, but the Skills Layer managed bridge is not configured.":"No MCP-capable host or Skills Layer managed bridge was detected on this machine.";return{config:t,configuredClientIds:n,hosts:r,summary:u,publicState:{status:c,configured:a,managedConfigured:a,hostDetected:i.length>0,hostConfigured:o.length>0,clientId:n[0]??null,clientIds:n,detectedHostIds:i.map(d=>d.hostId),hostConfiguredIds:o.map(d=>d.hostId),hosts:r,detectedHostCount:i.length,hostConfiguredCount:o.length,managedConfiguredHostCount:s.length,verifiedHostCount:0,configPath:e.paths.mcpConfigPath,nextCommand:a?"skills-layer mcp verify":"skills-layer mcp setup",verifyCommand:a?n.length===1?`skills-layer mcp verify --client ${n[0]}`:"skills-layer mcp verify":"skills-layer mcp setup",nextAction:a?"mcp.verify":"mcp.setup",nextStep:a?"Verify the Skills Layer managed bridge from a fresh agent session.":l?"Run `skills-layer mcp setup` to connect Skills Layer to a detected MCP-capable host.":"Run `skills-layer mcp setup` to connect Skills Layer to an AI client."}}}async function Xae(e,t){if(e.deep)return await Qae(e,t);let n=await D(t,"/api/v1/doctor",{headers:Wo(t.apiKey)}),[r,i,o]=await Promise.all([zn(t),Bse(t),Nh(t)]),s=[...pz(n),aae(r,i)];return A({...n,guardian:{...r,policy:i},mcp:o.publicState,checks:s},"Doctor checks loaded.",e.json,t)}async function Qae(e,t){let n;try{let c=await D(t,"/api/v1/status",{headers:Wo(t.apiKey)});n=cr("ok","backend_reachable","status","Backend status loaded.",{baseUrl:t.baseUrl,edition:f(c,"edition"),capabilityCount:Array.isArray(c.capabilities)?c.capabilities.length:void 0})}catch(c){n=cr("error","backend_unreachable","backend.status","Selected backend could not be reached.",{baseUrl:t.baseUrl,error:ve(c)})}let r=t.config?.credentialStorage??(t.apiKey?"local_file_locked":"none"),i=await Nh(t),o=i.config,s=await zn(t),a=Qe(t.env,t.platform,t.cwd).map(c=>({id:c.id,displayName:c.displayName,capabilities:c.capabilities})),l={backend:n,auth:t.apiKey?cr("ok","authenticated","whoami","A local session is available for the selected backend.",{email:t.config?.email,role:t.config?.role,savedLoginMatchesSelectedBackend:!0}):cr("login_required","login_required","login","No usable local session is available for the selected backend.",{savedLoginMatchesSelectedBackend:t.config?.baseUrl?Yu(t.config.baseUrl,t.baseUrl):!0}),credentialStorage:cr(r==="none"?"not_configured":"ok",r==="none"?"credential_storage_not_configured":"credential_storage_ready",r==="none"?"login":"auth.status",r==="none"?"Run `skills-layer login` to create a secure local session.":"Credential storage metadata is present.",{credentialStorage:r,configPath:t.paths.configPath}),mcp:o?cr("configured","mcp_configured","mcp.verify","MCP is configured locally; verify from a fresh agent session if tools are not visible.",{...i.publicState,mcpUrl:f(o,"mcpUrl")}):cr(i.publicState.hostDetected?"detected_unmanaged":"not_configured",i.publicState.status,"mcp.setup",i.summary,{...i.publicState}),guardianHooks:cr(f(s,"enforcementLayer")==="not_installed"?"not_installed":s.strictPreActionBlocking===!0?"ok":"warn",f(s,"enforcementLayer")==="not_installed"?"guardian_hook_not_installed":s.strictPreActionBlocking===!0?"guardian_hook_verified_strict":"guardian_hook_candidate_unverified","guardian.hook.status",f(s,"enforcementLayer")==="not_installed"?"Cloud Guardian checks work when called, but local pre-action hooks are not installed.":s.strictPreActionBlocking===!0?"At least one Skills Layer Security Hook has current matching live-canary evidence.":"A Skills Layer Security Hook is installed, but current live-canary evidence has not verified strict enforcement.",s),localPaths:cr("ok","local_paths_resolved","doctor.deep","Local Skills Layer paths resolved.",{stateDir:t.paths.stateDir,configPath:t.paths.configPath,installsPath:t.paths.installsPath,mcpConfigPath:t.paths.mcpConfigPath}),agentTargets:cr("ok","agent_targets_loaded","agents.list","Supported local agent targets loaded.",{count:a.length,results:a})};return A({status:"ok",deep:!0,sections:l,nextAction:t.apiKey?"status":"login",nextStep:t.apiKey?"Run `skills-layer status --json` for Cloud journey readiness.":"Run `skills-layer login` to sign in, then rerun `skills-layer doctor --deep --json`."},"Deep doctor diagnostics loaded.",e.json,t)}function cr(e,t,n,r,i={}){return ie({status:e,reasonCode:t,nextAction:n,nextStep:r,...i})}async function Oe(e,t,n,r,i,o={}){return await Gu(e,{method:"POST",headers:{...V(r.apiKey),...o},body:JSON.stringify(ie(t))},n,r,i)}function ele(){return`payout_request_${Ge(24).toString("base64url")}`}function tle(){return`guardian_incident_${Ge(24).toString("base64url")}`}async function nle(e,t){for(let n=0;n<2;n+=1)try{return await D(e,"/api/v1/guardian/enforce",{method:"POST",headers:V(e.apiKey),body:JSON.stringify(t)})}catch(r){if(!(r instanceof Z?[500,502,503,504].includes(r.status):r instanceof Error&&r.message.startsWith("Unable to reach "))||n===1)throw r;await e.sleep(250)}throw new Error("Guardian incident retry limit was exhausted.")}async function Li(e,t,n,r,i){return await Gu(e,{method:"PATCH",headers:V(r.apiKey),body:JSON.stringify(ie(t))},n,r,i)}async function Gu(e,t,n,r,i){let o=await D(r,e,t);return A(o,i,n.json,r)}async function D(e,t,n={}){tl(e.baseUrl);let r=await e.fetchFn(`${e.baseUrl}${t}`,{...n,redirect:"error"}).catch(s=>{throw new Error(`Unable to reach ${e.baseUrl}. ${ve(s)}`)});if(!r.ok)throw await rle(r);let i=await r.text();if(!i)return{};let o=JSON.parse(i);return o&&typeof o=="object"&&!Array.isArray(o)&&o.schemaVersion!=="skills-layer.creator.operation.v1"&&"data"in o?o.data:o}async function rle(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new Z(e.status,f(n,"error")??f(n,"summary")??(e.statusText||"Request failed"),n)}catch{return new Z(e.status,t)}return new Z(e.status,e.statusText||"Request failed")}function re(e,t){if(t)throw new Z(401,t,{error:t,nextAction:"backend.status",nextStep:t});if(!e)throw new Z(401,"Login required.",{error:"Login required.",nextAction:"login",nextStep:"Run `skills-layer login` to sign in, then retry this command."});return{authorization:`Bearer ${e}`}}function Wo(e){return e?{authorization:`Bearer ${e}`}:{}}function V(e,t){return{"content-type":"application/json",...e||t?re(e,t):{}}}async function Hu(e,t){if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(e)||/^[a-z][a-z0-9+.-]*:(?![\\/])/iu.test(e))return;let n=Tt(t,e);try{await Xu(n)}catch{return}let r=await ma({cwd:t,sourcePath:e,limits:yo});return{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:r.files}}var Ku=class extends Error{constructor(){super("Local Installation Ledger changed concurrently; retry the exact target operation."),this.name="InstallIndexRevisionConflictError"}},Fo=/^sha256:[a-f0-9]{64}$/u;function Wu(e){return{version:1,state:e.state,operationId:e.operationId,receipt:e.receipt,...e.quarantine?{quarantine:e.quarantine}:{},updatedAt:e.backend.now()}}function Jt(e){let t=j(e,"localLifecycle");if(!t||t.version!==1)return null;let n=f(t,"state"),r=f(t,"operationId"),i=f(t,"updatedAt"),o=sz(t.receipt);if(!n||!["pending_activation","active","quarantined","restore_pending","externally_removed","unreadable","drifted","host_detached"].includes(n)||!r||!i||!o)return null;let s=t.quarantine===void 0?void 0:sle(t.quarantine);return(n==="quarantined"||n==="restore_pending")&&!s?null:{version:1,state:n,operationId:r,receipt:o,...s?{quarantine:s}:{},updatedAt:i}}var ile=new Set(["agent","atomicActivation","guardianRuntimeMetadata","guardianEnforcement","guardianActivationReceipt","harnessUninstalledAt","hostRegistrationState","localLifecycle","materializationId","materializedPath","materializedSkillRoot","materializedWrites","receiptSha256","reconciliation","scope","targetAgent","targetAgents","targetGroup"]);function Zu(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!ile.has(t)))}function Bo(e,t){let r=(t==="win32"?ot:Lt).resolve(e).normalize("NFC");return t==="linux"?r:r.toLocaleLowerCase("en-US")}function nz(e){let t=`${e.scope}\0${Bo(e.targetDir,e.platform)}`;return`materialization_${Me("sha256").update(t).digest("hex").slice(0,24)}`}function Yt(e){let t=e?j(e,"materializations"):void 0;return t?Object.fromEntries(Object.entries(t).flatMap(([n,r])=>L(r)?[[n,r]]:[])):{}}function An(e){return Object.entries(Yt(e)).map(([t,n])=>({materializationId:t,record:n,lifecycle:Jt(n)}))}function mr(e){return Array.from(new Set([...Un(e,"targetAgents")??[],...[f(e,"agent"),f(e,"targetAgent")].filter(t=>!!t)])).sort()}function Fr(e){let t=Jt(e.materialization),n=f(e.materialization,"scope");if(!t||n!=="project"&&n!=="global")throw new Error("Local Installation Ledger materialization requires an exact lifecycle and project/global scope.");let r=f(e.materialization,"materializationId")??nz({scope:n,targetDir:t.receipt.targetDir,platform:e.backend.platform}),i=Yt(e.existing)[r],o=Array.from(new Set([...mr(i??{}),...mr(e.materialization)])).sort(),s={...e.materialization,materializationId:r,targetAgents:o,...o.length>1?{targetGroup:`shared:${n}:${o.join(",")}`}:{},receiptSha256:Vr(t.receipt),savedAt:e.backend.now()},a={...Yt(e.existing),[r]:s},l=Object.keys(a).length===1?s:{};return{...Zu(e.existing??{}),...l,skillSlug:e.skillSlug,materializations:a,materializationCount:Object.keys(a).length,savedAt:e.backend.now()}}function rz(e){let t=Yt(e.existing);if(delete t[e.materializationId],Object.keys(t).length===0)return;let n=Object.values(t);return{...Zu(e.existing),...n.length===1?n[0]:{},materializations:t,materializationCount:Object.keys(t).length,savedAt:e.backend.now()}}function qn(e,t={}){return An(e).filter(n=>{let r=f(n.record,"scope");if(t.scope&&r!==t.scope||t.agent&&!mr(n.record).includes(t.agent)||t.receiptSha256&&f(n.record,"receiptSha256")!==t.receiptSha256)return!1;if(t.installedPath){let i=n.lifecycle?.receipt.targetDir;if(!i||!yA(t.installedPath,i,t.platform??process.platform))return!1}return!0})}function ole(e){let t=e.backend.platform==="win32"?ot:Lt,n=new Set;for(let r of Qe(e.backend.env,e.backend.platform,e.backend.cwd))if(!(e.agent&&r.id!==e.agent))for(let i of new Set([e.skillSlug,Mr(e.skillSlug)]))(!e.scope||e.scope==="project")&&n.add(Bo(t.join(r.targets.projectSkillsPath,i),e.backend.platform)),(!e.scope||e.scope==="global")&&r.targets.globalSkillsPath&&n.add(Bo(t.join(r.targets.globalSkillsPath,i),e.backend.platform));return e.materializations.filter(r=>{let i=r.lifecycle?.receipt.targetDir;return!!(i&&n.has(Bo(i,e.backend.platform)))})}function gr(e,t){return{...Zu(e),...t.record,materializationId:t.materializationId}}function iz(e){return Object.values(e.installs).flatMap(t=>{let n=An(t);return n.length>0?n.map(r=>gr(t,r)):[t]})}function oz(e){let t=j(e,"cachedArtifact"),n=t?j(t,"generation"):void 0,r=t?f(t,"state"):void 0,i=t?f(t,"bundlePath"):void 0,o=n?f(n,"skillSlug"):void 0,s=n?f(n,"semanticVersion"):void 0,a=n?f(n,"generationId"):void 0,l=t?f(t,"archiveSha256"):void 0,c=t?f(t,"manifestSha256"):void 0,u=t?f(t,"savedAt"):void 0;return r!=="verified"||!i||!o||!s||!a||!l||!Fo.test(l)||!c||!Fo.test(c)||!u?null:{state:"verified",bundlePath:i,generation:{skillSlug:o,semanticVersion:s,generationId:a},archiveSha256:l,manifestSha256:c,savedAt:u}}function sz(e){if(!L(e))return null;let t=f(e,"targetDir"),n=j(e,"generation"),r=n?f(n,"skillSlug"):void 0,i=n?f(n,"semanticVersion"):void 0,o=n?f(n,"generationId"):void 0,s=f(e,"archiveSha256"),a=f(e,"manifestSha256"),l=Fe(e,"files");if(!t||!r||!i||!o||!s||!Fo.test(s)||!a||!Fo.test(a)||!l||l.length===0)return null;let c=l.flatMap(u=>{if(!L(u))return[];let d=f(u,"path"),p=J(u,"sizeBytes"),m=f(u,"sha256");return d&&Number.isSafeInteger(p)&&p>=0&&m&&Fo.test(m)?[{path:d,sizeBytes:p,sha256:m}]:[]});return c.length!==l.length?null:{targetDir:t,generation:{skillSlug:r,semanticVersion:i,generationId:o},archiveSha256:s,manifestSha256:a,files:c}}function az(e){if(!L(e)||e.status!=="authorized")return null;let t=f(e,"authorizationId"),n=f(e,"purpose"),r=j(e,"generation"),i=r?f(r,"skillSlug"):void 0,o=r?f(r,"semanticVersion"):void 0,s=r?f(r,"generationId"):void 0,a=f(e,"archiveSha256"),l=f(e,"manifestSha256");return!t||!n||!["quarantine_blocked","quarantine_revoked","restore_fresh_approval","purge_quarantined"].includes(n)||!i||!o||!s||!a||!Fo.test(a)||!l||!Fo.test(l)?null:{status:"authorized",authorizationId:t,purpose:n,generation:{skillSlug:i,semanticVersion:o,generationId:s},archiveSha256:a,manifestSha256:l}}function sle(e){if(!L(e)||e.status!=="quarantined")return null;let t=f(e,"reasonCode"),n=f(e,"targetDir"),r=f(e,"quarantineRoot"),i=f(e,"quarantineDir"),o=Un(e,"discoveryRoots"),s=az(e.quarantineAuthorization),a=sz(e.receipt);return!t||!n||!r||!i||!o||o.length===0||!s||!a?null:{status:"quarantined",reasonCode:t,targetDir:n,quarantineRoot:r,quarantineDir:i,discoveryRoots:o,quarantineAuthorization:s,receipt:a}}async function lt(e){let t=await ke(e.paths.installsPath);return!L(t)||t.version!==hh||!L(t.installs)?{version:hh,revision:0,installs:{}}:{version:hh,revision:Number.isSafeInteger(t.revision)&&Number(t.revision)>=0?Number(t.revision):0,installs:ule(t.installs)}}async function _A(e,t){let n=e.paths.installsPath,r=Be(n);await Zo(r);let i=`${n}.lock`,o,s=Date.now()+5e3;for(;!o;)try{o=await Uo(i,"wx",384)}catch(c){if(c.code!=="EEXIST"||Date.now()>=s)throw c;await new Promise(u=>setTimeout(u,10))}let a=K(r,`.${it(n)}.${Ge(12).toString("hex")}.tmp`),l;try{let c=await ke(n),u=L(c)&&c.version===hh&&Number.isSafeInteger(c.revision)&&Number(c.revision)>=0?Number(c.revision):0;if(u!==t.revision)throw new Ku;let d={...t,revision:u+1};l=await Uo(a,"wx",384),await l.writeFile(`${JSON.stringify(d,null,2)}
|
|
2275
|
-
`,"utf8"),await l.sync(),await l.close(),l=void 0,await zo(a,n),await Jo(n,384),await SA(r),t.revision=d.revision}catch(c){throw await l?.close().catch(()=>{}),await We(a,{force:!0}).catch(()=>{}),c}finally{await o.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function Br(e,t){for(let n=0;n<8;n+=1){let r=await lt(e);await t(r);try{return await _A(e,r),r}catch(i){if(!(i instanceof Ku)||n===7)throw i}}throw new Ku}async function Bi(e,t){let n=await lt(e),r=!1,i=[];for(let[o,s]of Object.entries(n.installs)){if(t&&o!==t)continue;let a=s;for(let l of An(s)){let c=l.lifecycle;if(!c||c.state!=="active")continue;let u=await ale(l.record,c);if(u.state==="active")continue;let d=u.state;a=Fr({existing:a,skillSlug:o,materialization:{...l.record,status:u.state,reconciliation:{version:1,state:u.state,reasonCode:u.reasonCode,observedAt:e.now(),recoverable:u.recoverable},localLifecycle:{...c,state:d,updatedAt:e.now()},savedAt:e.now()},backend:e}),r=!0,i.push({skillSlug:o,generationId:c.receipt.generation.generationId,receiptSha256:Vr(c.receipt),state:u.state==="externally_removed"?"externally_removed":u.state==="host_detached"?"host_detached":"stale",reasonCode:u.reasonCode})}n.installs[o]=a}r&&await _A(e,n);for(let o of i)await lle(e,o).catch(()=>{});return n}async function ale(e,t){let n;try{let o=await Xu(t.receipt.targetDir);n=o.isDirectory()&&!o.isSymbolicLink()?"present_directory":"replaced_type"}catch(o){n=o.code==="ENOENT"?"absent":"unreadable"}let r=n==="present_directory"?(await Dr(t.receipt)).status==="verified"?"verified":"changed":"unchecked",i=e.hostRegistrationState==="detached"||typeof e.harnessUninstalledAt=="string"?"detached":"unknown";return d2({pathState:n,receiptState:r,hostState:i})}async function lle(e,t){for(let n of["project","global"]){let r;try{r=await Vo(e,n)}catch{continue}let i=Object.entries(r.associations).filter(([,o])=>o.skillSlug===t.skillSlug&&o.generationId===t.generationId&&o.receiptSha256===t.receiptSha256&&o.state!=="externally_removed"&&o.state!=="host_detached");for(let[o]of i)await jo(e,n,o,{state:t.state,reasonCode:t.reasonCode,updatedAt:e.now()})}}async function SA(e){if(process.platform!=="win32")try{let t=await Uo(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function cle(e){await Br(e.backend,t=>{let n=t.installs[e.skillSlug];if(!n)return;let r=Yt(n)[e.materializationId],i=r?Jt(r):null;if(!i||i.operationId!==e.operationId)return;if(e.baselineMaterialization){t.installs[e.skillSlug]=Fr({existing:n,skillSlug:e.skillSlug,materialization:e.baselineMaterialization,backend:e.backend});return}let o=rz({existing:n,materializationId:e.materializationId,backend:e.backend});o?t.installs[e.skillSlug]=o:delete t.installs[e.skillSlug]})}async function Ha(e,t,n){let r=f(t,"skillSlug")??f(t,"slug")??n,i=Array.isArray(t.materializationResults)?t.materializationResults.filter(L):Jt(t)?[t]:[],o=i.length>0?Zu(t):t;await Br(e,s=>{let a={...Zu(s.installs[r]??{}),...o,...t.acquisitionMode==="authenticated_account"?{acquisitionBaseUrl:e.baseUrl,acquiredByUserId:e.config?.userId}:{},skillSlug:r,materializations:Yt(s.installs[r]),savedAt:e.now()};for(let l of i)a=Fr({existing:a,skillSlug:r,materialization:{...l,...t.acquisitionMode==="authenticated_account"?{acquisitionMode:t.acquisitionMode,acquisitionBaseUrl:e.baseUrl,acquiredByUserId:e.config?.userId,entitlementId:t.entitlementId}:{}},backend:e});s.installs[r]=a})}function ule(e){let t={};for(let[n,r]of Object.entries(e))t[n]=L(r)?r:{skillSlug:n,value:r};return t}var
|
|
2274
|
+
Waiting for browser sign-in to finish...`)}else r.json||i.emitInfo(o==="recovery"?`${u} recovery started. Finish the verification in your browser, then come back here. Waiting for browser recovery to finish...`:`${u} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`);let d=await Vae(c,i,s);if(fe(d))return d;if(d.status==="verified"||d.status==="recovered")return await kh(u,n,r,i,o);if(d.status==="mfa_required"){if(!n)return R("Login MFA handoff is unavailable. Start login again.",r.json);let p=k(r.mfaCode),m=k(r.recoveryCode);if(!p&&!m&&!r.json&&i.stdoutIsTty){let g=await i.promptSelect("Complete MFA to finish login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),y=(await i.promptSecret(g==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();g==="recovery_code"?m=y:p=y}if(!p&&!m)return x({status:"human_action_required",reasonCode:"login_mfa_required",methods:["authenticator","recovery_code"],nextAction:"account.login.mfa",nextStep:"Re-run login in a human terminal and complete MFA."},"MFA is required to finish login.",r.json,"login_mfa_required");let h=await D(i,"/api/v1/identity/login/mfa/verify",{method:"POST",headers:V(),body:JSON.stringify({state:c,authorizationCode:n.authorizationCode,codeVerifier:n.codeVerifier,...p?{mfaCode:p}:{},...m?{recoveryCode:m}:{}})});return f(h,"status")!=="verified"||f(h,"credentialHandoff")!=="ready"?R("MFA verification did not authorize the login credential. Start login again.",r.json):await kh(u,n,r,i,o)}if(d.status==="already_registered"||d.status==="link_required"){let p=UF(e,!!i.apiKey&&!i.authBlockedMessage);return x({...p},p.summary,r.json,"social_identity_link_required")}if(d.status==="registration_confirmation_required"){if(!r.json&&i.stdoutIsTty){let m=await i.promptSelect(`Create a new Skills Layer account using your verified ${u} identity?`,[{value:"create",label:"Yes, create my account",description:"Create one account, connect this sign-in, and log in"},{value:"cancel",label:"No",description:"Create nothing and leave Skills Layer unchanged"}])==="create",h=await D(i,"/api/v1/identity/social/registration/confirm",{method:"POST",headers:V(),body:JSON.stringify({state:c,createAccount:m})});return!m||f(h,"status")==="registration_cancelled"?A({status:"registration_cancelled",changed:!1},"Registration cancelled. No Skills Layer account was created.",!1,i):f(h,"status")!=="verified"||f(h,"credentialHandoff")!=="ready"?R("Account creation could not be confirmed safely. Start registration again.",!1):await kh(u,n,r,i,"register")}return x({status:"registration_confirmation_required",reasonCode:"registration_confirmation_required",nextAction:"account.registration.confirm",nextStep:r.createAccount?"Provider verification finished, but account creation still needs confirmation. Start registration again.":"Re-run registration with --create-account after confirming that you want to create this account."},"Account creation needs explicit confirmation.",r.json,"registration_confirmation_required")}return d.status==="linked"?A(d,`${u} sign-in is now connected.`,r.json,i):qae(d)?R(Jae(d),r.json):R("Social auth completed with an unexpected response.",r.json)}async function kh(e,t,n,r,i){if(!t)return R("Social credential handoff is unavailable. Start the login flow again.",n.json);let o=await D(r,"/api/v1/identity/social/exchange",{method:"POST",headers:V(),body:JSON.stringify({authorizationCode:t.authorizationCode,codeVerifier:t.codeVerifier})});if(f(o,"status")!=="exchanged"||!f(o,"email")||!f(o,"role")||!f(o,"apiKey"))return R("Social credential handoff failed closed. Start the login flow again.",n.json);let s=f(o,"email");return await kA(s,o,n,r,i==="recovery"?`Recovered access for ${s} through ${e}.`:`Verified ${s} through ${e}.`)}function Ko(e){return e==="google"||e==="github"||e==="gitlab"||e==="microsoft"}function fe(e){return L(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function zae(e){try{let t=JSON.parse(e);return L(t)?t.data:void 0}catch{return}}function qae(e){return e.status==="registration_required"||e.status==="state_expired"||e.status==="provider_mismatch"||e.status==="identity_conflict"||e.status==="email_required"||e.status==="failed"}async function Vae(e,t,n="/api/v1/identity/social/status"){for(let r=0;r<120;r+=1)try{let i=await D(t,`${n}/${encodeURIComponent(e)}`,n.includes("/identity/connect/")?{headers:re(t.apiKey,t.authBlockedMessage)}:void 0),o=f(i,"status")??"failed";if(o==="pending"){await t.sleep(1500);continue}return(o==="verified"||o==="recovered")&&f(i,"credentialHandoff")==="ready"?{status:o,credentialHandoff:"ready"}:o==="already_registered"||o==="link_required"?{status:o}:o==="linked"?{status:o}:o==="registration_confirmation_required"?{status:o}:o==="mfa_required"?{status:o}:o==="registration_required"||o==="state_expired"||o==="provider_mismatch"||o==="identity_conflict"||o==="email_required"||o==="failed"?{status:o,error:f(i,"error")}:R("Social auth completed with an unexpected response.",!1)}catch(i){if(i instanceof Z&&(i.status===404||i.status===429)){await t.sleep(1500);continue}return R(ve(i),!1)}return R("Timed out while waiting for social auth to complete.",!1)}async function Gae(e,t){let n=`/api/v1/identity/mfa/recovery-codes/operations/${encodeURIComponent(e)}`;for(let r=0;r<210;r+=1)try{let i=await D(t,n,{headers:re(t.apiKey,t.authBlockedMessage)}),o=f(i,"status"),s=j(i,"data");if(o==="pending"||o==="finalizing"){await t.sleep(1500);continue}if(o==="completed")return{...i,completedAt:f(i,"completedAt")??(s?f(s,"completedAt"):void 0)};if(o==="locked"){let a=f(i,"retryAt")??(s?f(s,"retryAt"):void 0);return x({status:"locked",reasonCode:"mfa_challenge_locked",retryAt:a,nextAction:"wait",nextStep:a?`Retry after ${a}.`:"Wait for the MFA verification lock to expire, then retry."},"Recovery-code verification is temporarily locked after too many invalid attempts.",!1)}return o==="failed"?x({status:"failed",reasonCode:"mfa_recovery_codes_failed",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"Recovery codes were not replaced.",!1):o==="expired"?x({status:"expired",reasonCode:"mfa_recovery_codes_expired",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"The recovery-code browser session expired before completion.",!1):R("Recovery-code verification completed with an unexpected response.",!1)}catch(i){if(i instanceof Z&&i.status===429){let o=i.details??{},s=f(o,"reasonCode"),a=f(o,"retryAt");if(s==="mfa_challenge_locked")return x({status:"locked",reasonCode:s,retryAt:a,nextAction:"wait",nextStep:a?`Retry after ${a}.`:"Wait for the MFA verification lock to expire, then retry."},"Recovery-code verification is temporarily locked after too many invalid attempts.",!1);let l=J(o,"retryAfterSeconds"),c=l===void 0?1500:Math.min(6e4,Math.max(1500,l*1e3));await t.sleep(c);continue}return R(ve(i),!1)}return x({status:"expired",reasonCode:"mfa_recovery_codes_expired",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"Timed out while waiting for recovery-code verification.",!1)}async function Hae(e,t){for(let n=0;n<120;n+=1)try{let r=await D(t,`/api/v1/purchases/${encodeURIComponent(e)}`,{headers:re(t.apiKey,t.authBlockedMessage)});if(!r?.status||r.status==="pending"||r.status==="requires_action"){await t.sleep(1500);continue}return{status:r.status,purchaseId:e}}catch(r){if(r instanceof Z&&r.status===429){await t.sleep(1500);continue}return R(ve(r),!1)}return R("Timed out while waiting for purchase confirmation.",!1)}async function Kae(e,t,n){let r=null;for(let i=0;i<120;i+=1)try{let o=await D(n,e,{headers:re(n.apiKey,n.authBlockedMessage)});r=o;let s=f(o,"status");if(!s||s==="checkout_required"||s==="pending"||s==="requires_action"||s==="payment_received"||s==="provisioning"||s==="finalizing"){await n.sleep(1500);continue}return o}catch(o){if(o instanceof Z&&o.status===429){await n.sleep(1500);continue}return R(ve(o),!1)}try{let i=await D(n,e,{headers:re(n.apiKey,n.authBlockedMessage)}),o=f(i,"status");if(o&&!["checkout_required","pending","requires_action","payment_received","provisioning","finalizing"].includes(o))return i;r=i}catch{}return{...r??{},status:"completion_pending",reasonCode:"enterprise_checkout_completion_pending",checkoutId:t,statusPath:e,retrySafe:!0,nextAction:"check_checkout_status",nextStep:"Check this checkout status again. Do not start a second checkout."}}async function Wae(e,t){for(let n=0;n<120;n+=1)try{let r=await D(t,`/api/v1/me/private-skill-charges/${encodeURIComponent(e)}`,{headers:re(t.apiKey,t.authBlockedMessage)}),i=f(r,"status");if(!i||i==="checkout_required"||i==="pending"||i==="requires_action"){await t.sleep(1500);continue}return{...r,status:i}}catch(r){if(r instanceof Z&&r.status===429){await t.sleep(1500);continue}return R(ve(r),!1)}return R("Timed out while waiting for payment confirmation.",!1)}function Zae(e){let t=j(e,"accountLink");return(t?f(t,"url"):void 0)??f(e,"url")??f(e,"setupUrl")}function Jae(e){return e.status==="registration_confirmation_required"?"Account creation requires explicit confirmation.":e.status==="registration_required"?e.error??"No verified account exists for this social identity. Use `skills-layer register` first.":e.status==="state_expired"?"Social auth expired before completion. Start the flow again.":e.status==="provider_mismatch"?"The browser completed a different social provider than the one the CLI started.":e.status==="identity_conflict"?e.error??"This social identity is already linked to another account.":e.status==="email_required"?e.error??"This social profile did not provide an email address.":e.error??"Social auth could not be completed."}async function Vu(e,t,n={}){let i=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole?await D({...e,apiKey:t},"/api/v1/me",{headers:{...re(t),...n.notifyLogin?{"x-skills-layer-session-intent":"login"}:{}}}):{userId:n.knownUserId,sessionCredentialId:n.knownSessionCredentialId,email:n.knownEmail,role:n.knownRole,roles:n.knownRoles},o=f(i,"email")??n.knownEmail??"unknown";if(n.expectedEmail&&o.toLowerCase()!==n.expectedEmail.toLowerCase())throw new Error(`The entered API key belongs to ${o}, not ${n.expectedEmail}. Use the API key emailed to ${n.expectedEmail}.`);let s=await D({...e,apiKey:t},"/api/v1/capabilities",{headers:re(t)}),a={version:tre,baseUrl:e.baseUrl,apiKey:t,edition:f(s,"edition")??f(i,"edition")??"saas",userId:f(i,"userId")??n.knownUserId,sessionCredentialId:f(i,"sessionCredentialId")??n.knownSessionCredentialId,email:o,role:f(i,"role")??n.knownRole??"user",roles:Un(i,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await CA(e.paths.configPath,a,e),await pce(e,a),await Ve(e.paths.backendPreferencePath,{version:JP,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),a}function $M(e,t){let n=ln(e.actionJson,"action-json");if(n&&typeof n=="object"&&!Array.isArray(n))return n;let r=k(e.action);return t==="incident"?{type:"file_write",path:k(e.path)??".skills-layer/incidents/guardian-incident.json"}:r==="file_read"||r==="file_write"?{type:r,path:k(e.path)??"."}:r==="shell_command"?{type:"shell_command",command:"unspecified"}:{type:"api_call",...r?{target:r}:{}}}async function me(e,t,n,r,i={}){let o=i.authenticated?re(n.apiKey,n.authBlockedMessage):Wo(n.apiKey);return await Gu(e,{headers:o},t,n,r)}async function Yae(e,t){let[n,r,i]=await Promise.all([D(t,"/api/v1/status",{headers:Wo(t.apiKey)}),zn(t),Nh(t)]),o={guardian:r,mcp:i.publicState};return A({...n,localRuntime:o},"Status loaded.",e.json,t)}async function tz(e,t){let n=new Set(t);return(await Wh({env:e.env,platform:e.platform,cwd:e.cwd,pathExists:e.pathExists})).map(r=>({...r,managedConfigured:n.has(r.hostId)}))}async function Nh(e){let t=await ke(e.paths.mcpConfigPath),n=t&&Array.isArray(t.clientIds)?t.clientIds.filter(d=>typeof d=="string"&&Ot(d)!==null):t&&f(t,"clientId")&&Ot(f(t,"clientId"))?[f(t,"clientId")]:[],r=await tz(e,n),i=r.filter(d=>d.installed),o=r.filter(d=>d.configured),s=r.filter(d=>d.managedConfigured),a=!!t,l=!a&&i.length>0,c=a?"mcp_configured":l?"mcp_hosts_detected_unmanaged":"mcp_not_configured",u=a?`Skills Layer MCP is configured for ${n.length} managed host${n.length===1?"":"s"}.`:l?"MCP-capable hosts or host configuration were detected, but the Skills Layer managed bridge is not configured.":"No MCP-capable host or Skills Layer managed bridge was detected on this machine.";return{config:t,configuredClientIds:n,hosts:r,summary:u,publicState:{status:c,configured:a,managedConfigured:a,hostDetected:i.length>0,hostConfigured:o.length>0,clientId:n[0]??null,clientIds:n,detectedHostIds:i.map(d=>d.hostId),hostConfiguredIds:o.map(d=>d.hostId),hosts:r,detectedHostCount:i.length,hostConfiguredCount:o.length,managedConfiguredHostCount:s.length,verifiedHostCount:0,configPath:e.paths.mcpConfigPath,nextCommand:a?"skills-layer mcp verify":"skills-layer mcp setup",verifyCommand:a?n.length===1?`skills-layer mcp verify --client ${n[0]}`:"skills-layer mcp verify":"skills-layer mcp setup",nextAction:a?"mcp.verify":"mcp.setup",nextStep:a?"Verify the Skills Layer managed bridge from a fresh agent session.":l?"Run `skills-layer mcp setup` to connect Skills Layer to a detected MCP-capable host.":"Run `skills-layer mcp setup` to connect Skills Layer to an AI client."}}}async function Xae(e,t){if(e.deep)return await Qae(e,t);let n=await D(t,"/api/v1/doctor",{headers:Wo(t.apiKey)}),[r,i,o]=await Promise.all([zn(t),Bse(t),Nh(t)]),s=[...pz(n),aae(r,i)];return A({...n,guardian:{...r,policy:i},mcp:o.publicState,checks:s},"Doctor checks loaded.",e.json,t)}async function Qae(e,t){let n;try{let c=await D(t,"/api/v1/status",{headers:Wo(t.apiKey)});n=cr("ok","backend_reachable","status","Backend status loaded.",{baseUrl:t.baseUrl,edition:f(c,"edition"),capabilityCount:Array.isArray(c.capabilities)?c.capabilities.length:void 0})}catch(c){n=cr("error","backend_unreachable","backend.status","Selected backend could not be reached.",{baseUrl:t.baseUrl,error:ve(c)})}let r=t.config?.credentialStorage??(t.apiKey?"local_file_locked":"none"),i=await Nh(t),o=i.config,s=await zn(t),a=et(t.env,t.platform,t.cwd).map(c=>({id:c.id,displayName:c.displayName,capabilities:c.capabilities})),l={backend:n,auth:t.apiKey?cr("ok","authenticated","whoami","A local session is available for the selected backend.",{email:t.config?.email,role:t.config?.role,savedLoginMatchesSelectedBackend:!0}):cr("login_required","login_required","login","No usable local session is available for the selected backend.",{savedLoginMatchesSelectedBackend:t.config?.baseUrl?Yu(t.config.baseUrl,t.baseUrl):!0}),credentialStorage:cr(r==="none"?"not_configured":"ok",r==="none"?"credential_storage_not_configured":"credential_storage_ready",r==="none"?"login":"auth.status",r==="none"?"Run `skills-layer login` to create a secure local session.":"Credential storage metadata is present.",{credentialStorage:r,configPath:t.paths.configPath}),mcp:o?cr("configured","mcp_configured","mcp.verify","MCP is configured locally; verify from a fresh agent session if tools are not visible.",{...i.publicState,mcpUrl:f(o,"mcpUrl")}):cr(i.publicState.hostDetected?"detected_unmanaged":"not_configured",i.publicState.status,"mcp.setup",i.summary,{...i.publicState}),guardianHooks:cr(f(s,"enforcementLayer")==="not_installed"?"not_installed":s.strictPreActionBlocking===!0?"ok":"warn",f(s,"enforcementLayer")==="not_installed"?"guardian_hook_not_installed":s.strictPreActionBlocking===!0?"guardian_hook_verified_strict":"guardian_hook_candidate_unverified","guardian.hook.status",f(s,"enforcementLayer")==="not_installed"?"Cloud Guardian checks work when called, but local pre-action hooks are not installed.":s.strictPreActionBlocking===!0?"At least one Skills Layer Security Hook has current matching live-canary evidence.":"A Skills Layer Security Hook is installed, but current live-canary evidence has not verified strict enforcement.",s),localPaths:cr("ok","local_paths_resolved","doctor.deep","Local Skills Layer paths resolved.",{stateDir:t.paths.stateDir,configPath:t.paths.configPath,installsPath:t.paths.installsPath,mcpConfigPath:t.paths.mcpConfigPath}),agentTargets:cr("ok","agent_targets_loaded","agents.list","Supported local agent targets loaded.",{count:a.length,results:a})};return A({status:"ok",deep:!0,sections:l,nextAction:t.apiKey?"status":"login",nextStep:t.apiKey?"Run `skills-layer status --json` for Cloud journey readiness.":"Run `skills-layer login` to sign in, then rerun `skills-layer doctor --deep --json`."},"Deep doctor diagnostics loaded.",e.json,t)}function cr(e,t,n,r,i={}){return ie({status:e,reasonCode:t,nextAction:n,nextStep:r,...i})}async function Oe(e,t,n,r,i,o={}){return await Gu(e,{method:"POST",headers:{...V(r.apiKey),...o},body:JSON.stringify(ie(t))},n,r,i)}function ele(){return`payout_request_${Ge(24).toString("base64url")}`}function tle(){return`guardian_incident_${Ge(24).toString("base64url")}`}async function nle(e,t){for(let n=0;n<2;n+=1)try{return await D(e,"/api/v1/guardian/enforce",{method:"POST",headers:V(e.apiKey),body:JSON.stringify(t)})}catch(r){if(!(r instanceof Z?[500,502,503,504].includes(r.status):r instanceof Error&&r.message.startsWith("Unable to reach "))||n===1)throw r;await e.sleep(250)}throw new Error("Guardian incident retry limit was exhausted.")}async function Li(e,t,n,r,i){return await Gu(e,{method:"PATCH",headers:V(r.apiKey),body:JSON.stringify(ie(t))},n,r,i)}async function Gu(e,t,n,r,i){let o=await D(r,e,t);return A(o,i,n.json,r)}async function D(e,t,n={}){tl(e.baseUrl);let r=await e.fetchFn(`${e.baseUrl}${t}`,{...n,redirect:"error"}).catch(s=>{throw new Error(`Unable to reach ${e.baseUrl}. ${ve(s)}`)});if(!r.ok)throw await rle(r);let i=await r.text();if(!i)return{};let o=JSON.parse(i);return o&&typeof o=="object"&&!Array.isArray(o)&&o.schemaVersion!=="skills-layer.creator.operation.v1"&&"data"in o?o.data:o}async function rle(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new Z(e.status,f(n,"error")??f(n,"summary")??(e.statusText||"Request failed"),n)}catch{return new Z(e.status,t)}return new Z(e.status,e.statusText||"Request failed")}function re(e,t){if(t)throw new Z(401,t,{error:t,nextAction:"backend.status",nextStep:t});if(!e)throw new Z(401,"Login required.",{error:"Login required.",nextAction:"login",nextStep:"Run `skills-layer login` to sign in, then retry this command."});return{authorization:`Bearer ${e}`}}function Wo(e){return e?{authorization:`Bearer ${e}`}:{}}function V(e,t){return{"content-type":"application/json",...e||t?re(e,t):{}}}async function Hu(e,t){if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(e)||/^[a-z][a-z0-9+.-]*:(?![\\/])/iu.test(e))return;let n=Tt(t,e);try{await Xu(n)}catch{return}let r=await ma({cwd:t,sourcePath:e,limits:yo});return{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:r.files}}var Ku=class extends Error{constructor(){super("Local Installation Ledger changed concurrently; retry the exact target operation."),this.name="InstallIndexRevisionConflictError"}},Fo=/^sha256:[a-f0-9]{64}$/u;function Wu(e){return{version:1,state:e.state,operationId:e.operationId,receipt:e.receipt,...e.quarantine?{quarantine:e.quarantine}:{},updatedAt:e.backend.now()}}function Jt(e){let t=j(e,"localLifecycle");if(!t||t.version!==1)return null;let n=f(t,"state"),r=f(t,"operationId"),i=f(t,"updatedAt"),o=sz(t.receipt);if(!n||!["pending_activation","active","quarantined","restore_pending","externally_removed","unreadable","drifted","host_detached"].includes(n)||!r||!i||!o)return null;let s=t.quarantine===void 0?void 0:sle(t.quarantine);return(n==="quarantined"||n==="restore_pending")&&!s?null:{version:1,state:n,operationId:r,receipt:o,...s?{quarantine:s}:{},updatedAt:i}}var ile=new Set(["agent","atomicActivation","guardianRuntimeMetadata","guardianEnforcement","guardianActivationReceipt","harnessUninstalledAt","hostRegistrationState","localLifecycle","materializationId","materializedPath","materializedSkillRoot","materializedWrites","receiptSha256","reconciliation","scope","targetAgent","targetAgents","targetGroup"]);function Zu(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!ile.has(t)))}function Bo(e,t){let r=(t==="win32"?st:Lt).resolve(e).normalize("NFC");return t==="linux"?r:r.toLocaleLowerCase("en-US")}function nz(e){let t=`${e.scope}\0${Bo(e.targetDir,e.platform)}`;return`materialization_${Me("sha256").update(t).digest("hex").slice(0,24)}`}function Yt(e){let t=e?j(e,"materializations"):void 0;return t?Object.fromEntries(Object.entries(t).flatMap(([n,r])=>L(r)?[[n,r]]:[])):{}}function An(e){return Object.entries(Yt(e)).map(([t,n])=>({materializationId:t,record:n,lifecycle:Jt(n)}))}function mr(e){return Array.from(new Set([...Un(e,"targetAgents")??[],...[f(e,"agent"),f(e,"targetAgent")].filter(t=>!!t)])).sort()}function Fr(e){let t=Jt(e.materialization),n=f(e.materialization,"scope");if(!t||n!=="project"&&n!=="global")throw new Error("Local Installation Ledger materialization requires an exact lifecycle and project/global scope.");let r=f(e.materialization,"materializationId")??nz({scope:n,targetDir:t.receipt.targetDir,platform:e.backend.platform}),i=Yt(e.existing)[r],o=Array.from(new Set([...mr(i??{}),...mr(e.materialization)])).sort(),s={...e.materialization,materializationId:r,targetAgents:o,...o.length>1?{targetGroup:`shared:${n}:${o.join(",")}`}:{},receiptSha256:Vr(t.receipt),savedAt:e.backend.now()},a={...Yt(e.existing),[r]:s},l=Object.keys(a).length===1?s:{};return{...Zu(e.existing??{}),...l,skillSlug:e.skillSlug,materializations:a,materializationCount:Object.keys(a).length,savedAt:e.backend.now()}}function rz(e){let t=Yt(e.existing);if(delete t[e.materializationId],Object.keys(t).length===0)return;let n=Object.values(t);return{...Zu(e.existing),...n.length===1?n[0]:{},materializations:t,materializationCount:Object.keys(t).length,savedAt:e.backend.now()}}function qn(e,t={}){return An(e).filter(n=>{let r=f(n.record,"scope");if(t.scope&&r!==t.scope||t.agent&&!mr(n.record).includes(t.agent)||t.receiptSha256&&f(n.record,"receiptSha256")!==t.receiptSha256)return!1;if(t.installedPath){let i=n.lifecycle?.receipt.targetDir;if(!i||!yA(t.installedPath,i,t.platform??process.platform))return!1}return!0})}function ole(e){let t=e.backend.platform==="win32"?st:Lt,n=new Set;for(let r of et(e.backend.env,e.backend.platform,e.backend.cwd))if(!(e.agent&&r.id!==e.agent))for(let i of new Set([e.skillSlug,Mr(e.skillSlug)]))(!e.scope||e.scope==="project")&&n.add(Bo(t.join(r.targets.projectSkillsPath,i),e.backend.platform)),(!e.scope||e.scope==="global")&&r.targets.globalSkillsPath&&n.add(Bo(t.join(r.targets.globalSkillsPath,i),e.backend.platform));return e.materializations.filter(r=>{let i=r.lifecycle?.receipt.targetDir;return!!(i&&n.has(Bo(i,e.backend.platform)))})}function gr(e,t){return{...Zu(e),...t.record,materializationId:t.materializationId}}function iz(e){return Object.values(e.installs).flatMap(t=>{let n=An(t);return n.length>0?n.map(r=>gr(t,r)):[t]})}function oz(e){let t=j(e,"cachedArtifact"),n=t?j(t,"generation"):void 0,r=t?f(t,"state"):void 0,i=t?f(t,"bundlePath"):void 0,o=n?f(n,"skillSlug"):void 0,s=n?f(n,"semanticVersion"):void 0,a=n?f(n,"generationId"):void 0,l=t?f(t,"archiveSha256"):void 0,c=t?f(t,"manifestSha256"):void 0,u=t?f(t,"savedAt"):void 0;return r!=="verified"||!i||!o||!s||!a||!l||!Fo.test(l)||!c||!Fo.test(c)||!u?null:{state:"verified",bundlePath:i,generation:{skillSlug:o,semanticVersion:s,generationId:a},archiveSha256:l,manifestSha256:c,savedAt:u}}function sz(e){if(!L(e))return null;let t=f(e,"targetDir"),n=j(e,"generation"),r=n?f(n,"skillSlug"):void 0,i=n?f(n,"semanticVersion"):void 0,o=n?f(n,"generationId"):void 0,s=f(e,"archiveSha256"),a=f(e,"manifestSha256"),l=Fe(e,"files");if(!t||!r||!i||!o||!s||!Fo.test(s)||!a||!Fo.test(a)||!l||l.length===0)return null;let c=l.flatMap(u=>{if(!L(u))return[];let d=f(u,"path"),p=J(u,"sizeBytes"),m=f(u,"sha256");return d&&Number.isSafeInteger(p)&&p>=0&&m&&Fo.test(m)?[{path:d,sizeBytes:p,sha256:m}]:[]});return c.length!==l.length?null:{targetDir:t,generation:{skillSlug:r,semanticVersion:i,generationId:o},archiveSha256:s,manifestSha256:a,files:c}}function az(e){if(!L(e)||e.status!=="authorized")return null;let t=f(e,"authorizationId"),n=f(e,"purpose"),r=j(e,"generation"),i=r?f(r,"skillSlug"):void 0,o=r?f(r,"semanticVersion"):void 0,s=r?f(r,"generationId"):void 0,a=f(e,"archiveSha256"),l=f(e,"manifestSha256");return!t||!n||!["quarantine_blocked","quarantine_revoked","restore_fresh_approval","purge_quarantined"].includes(n)||!i||!o||!s||!a||!Fo.test(a)||!l||!Fo.test(l)?null:{status:"authorized",authorizationId:t,purpose:n,generation:{skillSlug:i,semanticVersion:o,generationId:s},archiveSha256:a,manifestSha256:l}}function sle(e){if(!L(e)||e.status!=="quarantined")return null;let t=f(e,"reasonCode"),n=f(e,"targetDir"),r=f(e,"quarantineRoot"),i=f(e,"quarantineDir"),o=Un(e,"discoveryRoots"),s=az(e.quarantineAuthorization),a=sz(e.receipt);return!t||!n||!r||!i||!o||o.length===0||!s||!a?null:{status:"quarantined",reasonCode:t,targetDir:n,quarantineRoot:r,quarantineDir:i,discoveryRoots:o,quarantineAuthorization:s,receipt:a}}async function lt(e){let t=await ke(e.paths.installsPath);return!L(t)||t.version!==hh||!L(t.installs)?{version:hh,revision:0,installs:{}}:{version:hh,revision:Number.isSafeInteger(t.revision)&&Number(t.revision)>=0?Number(t.revision):0,installs:ule(t.installs)}}async function _A(e,t){let n=e.paths.installsPath,r=Be(n);await Zo(r);let i=`${n}.lock`,o,s=Date.now()+5e3;for(;!o;)try{o=await Uo(i,"wx",384)}catch(c){if(c.code!=="EEXIST"||Date.now()>=s)throw c;await new Promise(u=>setTimeout(u,10))}let a=K(r,`.${ot(n)}.${Ge(12).toString("hex")}.tmp`),l;try{let c=await ke(n),u=L(c)&&c.version===hh&&Number.isSafeInteger(c.revision)&&Number(c.revision)>=0?Number(c.revision):0;if(u!==t.revision)throw new Ku;let d={...t,revision:u+1};l=await Uo(a,"wx",384),await l.writeFile(`${JSON.stringify(d,null,2)}
|
|
2275
|
+
`,"utf8"),await l.sync(),await l.close(),l=void 0,await zo(a,n),await Jo(n,384),await SA(r),t.revision=d.revision}catch(c){throw await l?.close().catch(()=>{}),await We(a,{force:!0}).catch(()=>{}),c}finally{await o.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function Br(e,t){for(let n=0;n<8;n+=1){let r=await lt(e);await t(r);try{return await _A(e,r),r}catch(i){if(!(i instanceof Ku)||n===7)throw i}}throw new Ku}async function Bi(e,t){let n=await lt(e),r=!1,i=[];for(let[o,s]of Object.entries(n.installs)){if(t&&o!==t)continue;let a=s;for(let l of An(s)){let c=l.lifecycle;if(!c||c.state!=="active")continue;let u=await ale(l.record,c);if(u.state==="active")continue;let d=u.state;a=Fr({existing:a,skillSlug:o,materialization:{...l.record,status:u.state,reconciliation:{version:1,state:u.state,reasonCode:u.reasonCode,observedAt:e.now(),recoverable:u.recoverable},localLifecycle:{...c,state:d,updatedAt:e.now()},savedAt:e.now()},backend:e}),r=!0,i.push({skillSlug:o,generationId:c.receipt.generation.generationId,receiptSha256:Vr(c.receipt),state:u.state==="externally_removed"?"externally_removed":u.state==="host_detached"?"host_detached":"stale",reasonCode:u.reasonCode})}n.installs[o]=a}r&&await _A(e,n);for(let o of i)await lle(e,o).catch(()=>{});return n}async function ale(e,t){let n;try{let o=await Xu(t.receipt.targetDir);n=o.isDirectory()&&!o.isSymbolicLink()?"present_directory":"replaced_type"}catch(o){n=o.code==="ENOENT"?"absent":"unreadable"}let r=n==="present_directory"?(await Dr(t.receipt)).status==="verified"?"verified":"changed":"unchecked",i=e.hostRegistrationState==="detached"||typeof e.harnessUninstalledAt=="string"?"detached":"unknown";return d2({pathState:n,receiptState:r,hostState:i})}async function lle(e,t){for(let n of["project","global"]){let r;try{r=await Vo(e,n)}catch{continue}let i=Object.entries(r.associations).filter(([,o])=>o.skillSlug===t.skillSlug&&o.generationId===t.generationId&&o.receiptSha256===t.receiptSha256&&o.state!=="externally_removed"&&o.state!=="host_detached");for(let[o]of i)await jo(e,n,o,{state:t.state,reasonCode:t.reasonCode,updatedAt:e.now()})}}async function SA(e){if(process.platform!=="win32")try{let t=await Uo(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function cle(e){await Br(e.backend,t=>{let n=t.installs[e.skillSlug];if(!n)return;let r=Yt(n)[e.materializationId],i=r?Jt(r):null;if(!i||i.operationId!==e.operationId)return;if(e.baselineMaterialization){t.installs[e.skillSlug]=Fr({existing:n,skillSlug:e.skillSlug,materialization:e.baselineMaterialization,backend:e.backend});return}let o=rz({existing:n,materializationId:e.materializationId,backend:e.backend});o?t.installs[e.skillSlug]=o:delete t.installs[e.skillSlug]})}async function Ha(e,t,n){let r=f(t,"skillSlug")??f(t,"slug")??n,i=Array.isArray(t.materializationResults)?t.materializationResults.filter(L):Jt(t)?[t]:[],o=i.length>0?Zu(t):t;await Br(e,s=>{let a={...Zu(s.installs[r]??{}),...o,...t.acquisitionMode==="authenticated_account"?{acquisitionBaseUrl:e.baseUrl,acquiredByUserId:e.config?.userId}:{},skillSlug:r,materializations:Yt(s.installs[r]),savedAt:e.now()};for(let l of i)a=Fr({existing:a,skillSlug:r,materialization:{...l,...t.acquisitionMode==="authenticated_account"?{acquisitionMode:t.acquisitionMode,acquisitionBaseUrl:e.baseUrl,acquiredByUserId:e.config?.userId,entitlementId:t.entitlementId}:{}},backend:e});s.installs[r]=a})}function ule(e){let t={};for(let[n,r]of Object.entries(e))t[n]=L(r)?r:{skillSlug:n,value:r};return t}var at=5;function lz(e){if(!L(e))return null;let t=f(e,"reasonCode"),n=t==="commercial_rights_declaration_required"||t==="commercial_rights_declaration_invalid";if(!n&&t!=="paid_to_free_confirmation_required")return null;let r=n?"Confirm your rights to distribute this skill.":"Confirm that this paid skill should become free.";return{...e,status:"action_required",error:r,message:r,nextAction:"retry",nextStep:n?"Repeat with --attest-rights --rights-basis self_authored after confirming your rights. For submit or submit-version, also add --distribution-scope commercial_distribution.":"To make this paid skill free, repeat with --price-cents 0 --confirm-free. The generic --yes flag does not confirm this change."}}function A(e,t,n,r,i){let o=lz(e);o&&(e=o,t=String(o.message));let s=e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"?String(e.status):"ok",a=Rh(e),l=n&&i?cz(a,r?.renderMode.detail??"standard",i):a,c=L(a)?a:void 0,u={schemaVersion:MM,status:s,statusFamily:mle(s,a),summary:t,why:c?f(c,"why")??null:null,nextAction:c?f(c,"nextAction")??null:null,nextStep:c?f(c,"nextStep")??null:null,data:l,warnings:c&&Array.isArray(c.warnings)?c.warnings:[],links:c&&Array.isArray(c.links)?c.links:[],reasonCode:c?f(c,"reasonCode")??null:null,handoff:c?.handoff??null};return{exitCode:0,stdout:n?JSON.stringify(u,null,2):St(yle(a,t,r)),stderr:""}}function cz(e,t,n){return t==="full"||!L(e)?e:n==="installed"?ple(e,t):fle(e,t)}var uz=["skillSlug","version","scope","agent","status"],dle=[...uz,"targetAgent","source","sourceKind","installMode","installedAt","savedAt","updatedAt","generationId","installedPathSource","localLifecycle"];function ple(e,t){let n=un(e.results),r=t==="concise"?3:5,i=t==="concise"?uz:dle,o=n.slice(0,r).map(s=>Ua(s,i));return{status:f(e,"status")??"ok",resultCount:n.length,returnedResultCount:o.length,warnings:e.warnings,omittedResultCount:Math.max(0,n.length-o.length),results:o}}function fle(e,t){let n=t==="concise"?3:5,r=j(e,"parsedSkill"),i=r?j(r,"frontmatter"):void 0,o=j(e,"license"),s=[yP("skill.body",r?.body),yP("skill.frontmatter",r?.rawFrontmatter),yP("license.text",o?.text)].filter(d=>d!==void 0),a=DM(e.issues,n),l=DM(e.licenseIssues,n),c=j(e,"evalReadiness"),u=j(e,"aiReview");return ie({status:e.status,profile:e.profile,ingestible:e.ingestible,valid:e.valid,stats:e.stats,skill:i?Ua(i,t==="concise"?["name"]:["name","description","compatibility","license"]):void 0,license:o?Ua(o,t==="concise"?["status","identifier"]:["status","identifier","detectedIdentifier","declarationSource","filePath","textSha256"]):void 0,issueCount:Array.isArray(e.issues)?e.issues.length:0,returnedIssueCount:a.length,omittedIssueCount:Math.max(0,(Array.isArray(e.issues)?e.issues.length:0)-a.length),issues:a,licenseIssues:l.length>0?l:void 0,evalReadiness:c?Ua(c,t==="concise"?["status","label","origin","confidence","evidenceFileCount","nextAction"]:["schemaVersion","status","label","origin","confidence","creatorReviewed","evidenceFileCount","runtimeFileCount","artifactDigest","score","summaryEnvelope","improvements","recommendedCommands","nextAction"]):void 0,securityReport:e.securityReport,aiReview:u?Ua(u,["status","reasonCode","message","nextAction","nextStep"]):void 0,rawContent:s})}function DM(e,t){return Array.isArray(e)?e.slice(0,t).map(n=>L(n)?Ua(n,["severity","code","message","path","nextAction","nextStep"]):n):[]}function yP(e,t){if(typeof t=="string")return{field:e,characterCount:t.length,sha256:`sha256:${Me("sha256").update(t).digest("hex")}`}}function Ua(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function mle(e,t){let n=e.toLowerCase();return n==="pass"||n.includes("dry")?"dry_run_passed":n.includes("created")?"created":n.includes("updated")||n.includes("configured")||n.includes("synced")?"updated":n.includes("revoked")||n.includes("removed")||n.includes("disconnected")?"removed":n.includes("approval")||n.includes("handoff")||L(t)&&t.handoff?"human_handoff":"ok"}var gle="<redacted>";function Rh(e){if(typeof e=="string")return H(e);if(Array.isArray(e))return e.map(n=>Rh(n));if(!L(e))return e;let t={};for(let[n,r]of Object.entries(e))t[n]=hle(n)?gle:Rh(r);return t}function hle(e){let t=e.replace(/[^a-z0-9]/giu,"").toLowerCase();return t==="devicecode"||t==="usercode"||t==="verificationcode"||t==="recoverycode"||t==="onetimecode"||t==="password"||t==="clientsecret"||t==="privatekey"||t==="apikey"||t==="rawapikey"||t==="accesstoken"||t==="refreshtoken"||t==="bearertoken"||t==="mcptoken"||t.endsWith("secret")?!0:t.endsWith("token")&&t!=="tokenprefix"}function yle(e,t,n){let r=n?.renderMode??Aa([],{},{stdinIsTty:!1,stdoutIsTty:!1,stderrIsTty:!1}).mode,i=Pe(n);if(L(e)){if(J(e,"pendingPrice")!==void 0)return["Price change pending admin review",`Live price: ${Ue(J(e,"priceCents")??0,"usd")}`,`Pending price: ${Ue(J(e,"pendingPrice"),"usd")}`,f(e,"reasonCode"),f(e,"nextStep")].filter(Boolean).join(`
|
|
2276
2276
|
`);if(t==="Spending loaded."){let l=f(e,"currency")??"usd",c=[`Total spent: ${Ue(J(e,"totalSpentCents")??0,l)}`,`Refunded: ${Ue(J(e,"refundedCents")??0,l)} (${J(e,"refundedCount")??0})`,`Successful purchases: ${J(e,"successfulPurchaseCount")??0}`],u=j(e,"spentByCurrency"),d=Object.entries(u??{}).filter(p=>typeof p[1]=="number"&&p[1]!==0);if(d.length>1){c.push("By currency");for(let[p,m]of d)c.push(`${p.toUpperCase()}: ${Ue(m,p)}`)}return c.join(`
|
|
2277
2277
|
`)}if(["Purchases loaded.","Purchase status loaded.","Invoice loaded."].includes(t))return vle(e,t,i,r.detail==="full");if(t==="Skill loaded.")return MF(e,r);if(t==="Status loaded."&&TM(e))return xle(e,t,i);if(t==="Doctor checks loaded."&&TM(e))return Cle(e,t,i);if(t==="Creator payout profile loaded.")return Gle(e,t,i);if(t==="Creator earnings loaded."||t==="Earnings loaded.")return Hle(e,"Creator earnings loaded.",i);if(t==="Creator payouts loaded."||t==="Payouts loaded.")return Kle(e,"Creator payouts loaded.",i);if(t==="Guardian check complete.")return _le(e,t,i);if(t==="Reviews loaded.")return ble(e,t,i);if(t==="Categories loaded.")return wle(e,t,i)}let o=L(e)?f(e,"status")??"ok":"ok",s=TN({status:o,summary:t,data:e,next:L(e)?kle(e):[],links:[],warnings:L(e)&&Array.isArray(e.warnings)?e.warnings.filter(l=>typeof l=="string"):[]},r),a=L(e)?j(e,"submission")??j(e,"analytics")??e:null;return a?.listingStatus==="delisted"?`${s}
|
|
2278
2278
|
|
|
2279
2279
|
Delisted on ${f(a,"delistedAt")??"an unrecorded date"}; existing buyers keep access.`:s}function vle(e,t,n,r){let i=typeof e.purchaseId=="string"?[e]:un(e.results??e.purchases),o=[t];i.length||o.push("No purchases found.");for(let s of i){let a=f(s,"currency")??"usd",l=m=>`${a==="usd"?"US$":a==="gbp"?"\xA3":`${a.toUpperCase()} `}${(m/100).toFixed(2)}`,u=s.status==="disputed_lost"||s.chargedBack===!0?`Charged back by your bank (net ${l(0)})`:s.status==="disputed"?$A:["pending","expired"].includes(String(s.status))?"No charge":"";if(t==="Purchases loaded."&&!r){o.push(`${f(s,"purchaseId")??"unknown"} | ${f(s,"skillSlug")??"unknown"} | ${f(s,"status")??"unknown"} | ${l(J(s,"amountCents")??0)}${u?` | ${u}`:""}`);continue}o.push("",`${n.label("Purchase")}: ${f(s,"purchaseId")??"unknown"}`);for(let[m,h]of[["skillSlug","Skill"],["version","Version"],["status","Status"]]){let g=f(s,m);g&&o.push(`${n.label(h)}: ${g}`)}for(let[m,h]of[["amountCents","Amount"],["refundAmountCents",s.status==="refund_requested"?"Requested refund":"Refund"],["netAmountCents","Net amount"]]){let g=J(s,m);g!==void 0&&o.push(`${n.label(h)}: ${l(g)}`)}let d=f(s,"statementDescription");t==="Invoice loaded."&&d&&o.push(d),u&&!(t==="Invoice loaded."&&d?.includes(u))&&o.push(u),s.status==="refund_requested"&&o.push("Refund in progress");let p=f(s,"refundedAt");if(p){let m=Date.parse(p),h=Number.isFinite(m)?new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"UTC"}).format(m)+" UTC":p;o.push(`${n.label("Refunded on")}: ${h}`)}}return o.join(`
|
|
2280
2280
|
`)}function kle(e){let t=FN(e);return t.length>0?t:e.valid===!0?[{id:"creator-submit-dry-run",kind:"command",label:"Preview the submission without publishing",command:{executable:"skills-layer",args:["creator","submit","<path>","--dry-run"]},safeToAutoRun:!0,requiresHuman:!1,safety:"read-only"}]:[]}function wle(e,t,n){let r=un(e.results??e.categories??e.data),i=[`${n.ok("OK")} ${t}`,"",n.section(`Categories (${r.length})`)];return r.length===0?(i.push(` ${n.muted("No categories returned.")}`),i.join(`
|
|
2281
|
-
`)):(r.slice(0,
|
|
2281
|
+
`)):(r.slice(0,at).forEach((o,s)=>{let a=f(o,"slug")??f(o,"category")??f(o,"name")??`category-${s+1}`,l=f(o,"name")??a,c=o.count;i.push(`${s+1}. ${yz(l)}`);let u=[a?`slug: ${a}`:void 0,c!==void 0?`count: ${dn("count",c)}`:void 0].filter(d=>!!d);u.length>0&&i.push(` ${u.join("; ")}`)}),r.length>at&&i.push(` ${n.muted(`... ${r.length-at} more`)}`),i.join(`
|
|
2282
2282
|
`))}function ble(e,t,n){let r=un(e.reviews??e.results),i=[`${n.ok("OK")} ${t}`,"",n.section(`Reviews (${r.length})`)];return r.length===0&&i.push(` ${n.muted("No reviews yet.")}`),r.forEach((o,s)=>{let a=f(o,"reviewId")??f(o,"id"),c=f(o,"skillSlug")??f(o,"slug")??f(o,"skill")??a??`Review ${s+1}`,u=o.rating??o.score,d=f(o,"status"),p=f(o,"updatedAt")??f(o,"createdAt"),m=[a?`review: ${a}`:void 0,u!=null?`rating: ${dn("rating",u)}`:void 0,d?`status: ${d}`:void 0,p?`updated: ${p}`:void 0].filter(g=>!!g);i.push(`${s+1}. ${c}`),m.length>0&&i.push(` ${m.join("; ")}`);let h=f(o,"feedback")??f(o,"comment")??f(o,"message");h&&i.push(` ${n.label("feedback")}: ${Za(h)}`)}),i.join(`
|
|
2283
2283
|
`)}function _le(e,t,n){let r=j(e,"decision"),i=j(e,"enforcement"),o=j(e,"auditEvent"),s=qe(r,"status")??qe(i,"status")??"unknown",a=qe(i,"actionType")??qe(o,"actionType")??"action",l=qe(r,"capability")??qe(i,"capability")??"not specified",c=qe(r,"reasonCode")??qe(i,"reasonCode")??"not specified",u=qe(r,"message")??qe(i,"message")??"Guardian policy resolved this action.",d=qe(o,"skillSlug")??"unknown",p=qe(o,"version")??"unknown",m=Nu(i,"canExecute"),h=Nu(i,"auditRequired"),g=Nu(i,"telemetryRequired"),y=s==="blocked"?"BLOCKED":s==="allowed"?"ALLOWED":"WARNING",v=[`${n.ok("OK")} ${t}`,"",n.section(`${y} ${Sle(a)}`),` ${n.label("Skill")}: ${d}`,` ${n.label("Version")}: ${p}`,` ${n.label("Capability")}: ${l}`,` ${n.label("Reason")}: ${u}`,` ${n.label("Reason code")}: ${c}`,` ${n.label("Can execute")}: ${m===!0?"yes":"no"}`,` ${n.label("Audit required")}: ${h===!1?"no":"yes"}`,` ${n.label("Cloud telemetry")}: ${g===!0?"yes":"no"}`,"",n.section("Next")];return s==="blocked"?v.push(` ${n.arrow} Do not run this action.`,` ${n.arrow} Review \`skills-layer trust ${d}\`.`,` ${n.arrow} Run \`skills-layer guardian incident --skill ${d} --version ${p} --path <installed-skill-path> --reason "<reason>"\` if this was unexpected.`):v.push(` ${n.arrow} Continue only with the action Guardian evaluated.`,` ${n.arrow} Re-run guardian check if the action changes.`),v.join(`
|
|
2284
2284
|
`)}function Nu(e,t){if(L(e))return typeof e[t]=="boolean"?e[t]:void 0}function qe(e,t){return L(e)?f(e,t):void 0}function Sle(e){return e.split(/[_-]+/u).filter(Boolean).map(t=>`${t[0]?.toUpperCase()??""}${t.slice(1)}`).join(" ")}function TM(e){return!!(j(e,"backend")&&j(e,"auth")&&Array.isArray(e.checks))}function xle(e,t,n){let r=[`${n.ok("OK")} ${t}`,"",n.section("Readiness")],i=f(e,"summary");i&&r.push(` ${i}`);let o=j(e,"backend"),s=o?Rle(o):void 0;s&&r.push(` ${n.label("Backend")}: ${s}`);let a=j(e,"auth"),l=a?Ele(a):void 0;l&&r.push(` ${n.label("Account")}: ${l}`);let c=a?J(a,"personalModeCount"):void 0,u=a?J(a,"enterpriseWorkspaceCount")??J(a,"workspaceCount"):void 0,d=a?J(a,"availableWorkingModeCount"):void 0;c!==void 0&&r.push(` ${n.label("Personal modes")}: ${c}`),u!==void 0&&r.push(` ${n.label("Enterprise workspaces")}: ${u}`),d!==void 0&&r.push(` ${n.label("Available workspace choices")}: ${d}`);let p=a?J(a,"libraryCount"):void 0;p!==void 0&&r.push(` ${n.label("Owned skills")}: ${p}`);let m=j(e,"localRuntime"),h=m?j(m,"guardian"):void 0,g=m?j(m,"mcp"):void 0;(h||g)&&(r.push("",n.section("Local runtime")),h&&r.push(` ${n.label("Guardian")}: ${qe(h,"enforcementLayer")??"not_installed"}`,` ${n.label("Strict pre-action blocking")}: ${Nu(h,"strictPreActionBlocking")===!0?"yes":"no"}`),g&&r.push(` ${n.label("MCP")}: ${Nu(g,"configured")===!0?"configured":"not configured"}`));let y=dz(e);return y.length>0&&r.push("",n.section("Next"),...y.map(v=>` ${n.arrow} ${v}`)),r.push(` ${n.arrow} Run \`skills-layer doctor\` for diagnostics.`),r.join(`
|
|
2285
2285
|
`)}function Cle(e,t,n){let r=[`${n.ok("OK")} ${t}`,"",n.section("Diagnostics")],i=f(e,"summary");i&&r.push(` ${i}`);let o=f(e,"status");o&&r.push(` ${n.label("Status")}: ${o}`);let s=pz(e),a=s.filter(u=>$le(f(u,"status"))),l=s.filter(u=>f(u,"status")!=="pass");r.push(a.length===0?" No blocking issues found.":` ${a.length} check${a.length===1?"":"s"} need attention.`),a.length===0&&l.length>0&&r.push(` Advisory checks needing attention: ${l.length}.`),r.push("",n.section(`Checks (${s.length})`)),s.length===0&&r.push(` ${n.muted("No checks returned by the backend.")}`),s.forEach((u,d)=>{let p=f(u,"status")??"unknown",m=f(u,"title")??f(u,"id")??`Check ${d+1}`;r.push(`${d+1}. ${n.label(`[${p}] ${m}`)}`);let h=f(u,"summary");h&&r.push(` ${h}`);let g=f(u,"why");if(g&&r.push(` ${n.label("Why")}: ${g}`),p!=="pass"){let y=f(u,"nextStep");y&&r.push(` ${n.label("Fix")}: ${y}`);let v=f(u,"recommendedCommand");v&&r.push(` ${n.label("Try")}: ${v}`)}});let c=dz(e);return c.length>0&&r.push("",n.section(a.length>0?"Recommended Fix":"Next"),...c.map(u=>` ${n.arrow} ${u}`)),r.join(`
|
|
2286
2286
|
`)}function Ile(e,t,n,r){let i=[`${n.ok("OK")} ${t}`],o=Un(e,"requestedSlugs");o&&o.length>0&&i.push("",n.section("Requested"),` ${o.join(", ")}`);let s=un(e.results);i.push("",n.section(`Comparison (${s.length})`)),s.length===0&&i.push(` ${n.muted("No comparable skills returned.")}`),s.forEach((u,d)=>{let p=HP(u)??`Skill ${d+1}`;i.push(`${d+1}. ${p}`);let m=Ple(u);m&&i.push(` ${m}`);let h=hz(u);h&&i.push(` ${n.label("summary")}: ${r?h.replace(/\s+/gu," ").trim():Za(h)}`)});let a=un(e.missing);a.length>0&&(i.push("",n.section(`Missing (${a.length})`)),a.forEach((u,d)=>{let p=f(u,"slug")??f(u,"skillSlug")??HP(u)??`Entry ${d+1}`,m=f(u,"reason")??f(u,"status");i.push(`${d+1}. ${m?`${p} - ${m}`:p}`)}));let l=Un(e,"guidance")??Ka(e.guidance);l.length>0&&i.push("",n.section("Guidance"),...l.slice(0,3).map(u=>` ${n.arrow} ${Za(u)}`));let c=Ale(s);return c.length>0&&i.push("",n.section("Next"),...c.map(u=>` ${n.arrow} ${u}`)),i.join(`
|
|
2287
2287
|
`)}function Ple(e){let t=j(e,"securityPosture"),n=f(e,"trust")??f(e,"trustStatus")??f(e,"trustLabel")??(t?f(t,"label"):void 0),r=e.score??e.securityScore??(t?t.securityScore:void 0),i=f(e,"risk")??f(e,"runtimeRisk")??(t?f(t,"runtimeRisk"):void 0);return[["slug",f(e,"slug")??f(e,"skillSlug")],["version",f(e,"version")??f(e,"currentVersion")],["category",f(e,"category")],["type",f(e,"type")??f(e,"skillType")],["trust",n],["score",r],["risk",i]].flatMap(([s,a])=>a==null||a===""?[]:[`${s}: ${dn(String(s),a)}`]).join("; ")}function Ale(e){let t=[];for(let n of e.slice(0,5)){let r=f(n,"slug")??f(n,"skillSlug");r&&t.push(`skills-layer show ${r}`,`skills-layer trust ${r}`,`skills-layer install ${r}`)}return t}function Rle(e){let t=f(e,"edition"),n=f(e,"baseUrl");return t&&n?`${t} at ${n}`:t??n}function Ele(e){let t=f(e,"state");if(t&&t!=="authenticated")return t==="anonymous"?"not signed in":t;let n=f(e,"email"),r=Un(e,"roles");return n&&r&&r.length>0?`${n} (${r.join(", ")})`:n??f(e,"role")}function dz(e){let t=[],n=f(e,"recommendedCommand");n&&t.push(n);let r=f(e,"nextStep");return r&&t.push(r),t}function pz(e){return Array.isArray(e.checks)?e.checks.filter(L):[]}function $le(e){return e!==void 0&&e!=="pass"&&e!=="warn"&&e!=="advisory"}function un(e){return Array.isArray(e)?e.filter(L):[]}function Ka(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Dle(e){let t=e.commerce===!0;return{status:t?"available":"unavailable",summary:t?"Marketplace purchases, invoices, refunds, and creator commerce flows are available.":"Marketplace commerce is not available on this backend.",availableWorkflows:t?["Browse skills with `skills-layer featured` or `skills-layer search <query>`.","Start purchase handoff with `skills-layer buy <skill-slug>`.","Review account purchases with `skills-layer purchases list`."]:["Browse and install available free skills.","Use `skills-layer help topic install` for install guidance."]}}var Tle={"core.identity":"Account and sign-in","core.catalog":"Catalog discovery","core.validation":"Creator validation","core.creator":"Creator submissions","core.library":"Owned skills","core.workspace":"Workspace rollout","core.guardian":"Runtime trust checks","core.source":"Source installs","core.discovery":"Catalog discovery","marketplace.commerce":"Marketplace commerce","marketplace.reviews":"Reviews and issues","marketplace.payouts":"Creator earnings"};function Ole(e){let t=Ka(e.capabilities);return{status:"ok",edition:f(e,"edition")??"unknown",summary:"Public product capabilities available on the selected backend.",capabilities:t.map(n=>({name:Tle[n]??Fh(n.replace(/^[^.]+\./u,"").replace(/[._-]+/gu," ")),available:!0})),count:t.length}}function Lle(e,t){let n=k(e);if(!n)return;let r=Number(n);return!Number.isInteger(r)||r<=0?R("help optimize-tokens --max-characters must be a positive integer.",t):r<120||r>4e3?R("help optimize-tokens --max-characters must be between 120 and 4000.",t):r}function jle(e,t,n){let r=Pe(n),i=j(e,"validation")??e,o=j(i,"parsedSkill")??j(e,"parsedSkill"),s=o?j(o,"frontmatter"):void 0,a=f(e,"skillSlug")??(s?f(s,"name"):void 0),l=i.valid===!0||e.valid===!0,c=vP(i,e,"issues"),u=vP(i,e,"warnings"),d=vP(i,e,"advice"),p=j(i,"stats")??j(e,"stats"),m=[l?`${r.ok("OK")} Validation complete.`:"Validation failed.","",r.section("Bundle")];m.push(` ${r.label("Path")}: ${t}`),a&&m.push(` ${r.label("Skill")}: ${a}`),m.push(` ${r.label("Readiness")}: ${l?"ready for dry-run submission":"needs changes before submission"}`),m.push("",r.section("Checks")),m.push(` ${r.arrow} SKILL.md structure and frontmatter`),m.push(` ${r.arrow} Required bundle files and supported directories`),m.push(` ${r.arrow} Secret hygiene, unsafe script signals, and trust-review readiness`),m.push(` ${r.arrow} Trigger quality inputs for should-trigger / should-not-trigger testing`);let h=j(e,"evalReadiness");if(h){let v=j(h,"summaryEnvelope"),b=Array.isArray(v?.statuses)?v.statuses.map(P=>String(P)).join(", "):void 0,w=j(h,"score"),_=w?J(w,"effectiveScorePercent"):void 0,C=w?J(w,"overallScore"):void 0;m.push("",r.section("Effectiveness Eval")),m.push(` ${r.label("Posture")}: ${f(h,"label")??f(h,"status")??"limited"}`),m.push(` ${r.label("Origin")}: ${f(h,"origin")??"inferred"}`),_!==void 0?m.push(` ${r.label("Effective score")}: ${Eh(_)}`):C!==void 0&&m.push(` ${r.label("Effective score")}: ${Eh(C*100)}`),m.push(` ${r.label("Artifact digest")}: ${f(h,"artifactDigest")??"unavailable"}`),h.runtimeFileCount!==void 0&&m.push(` ${r.label("Runtime files")}: ${dn("runtimeFileCount",h.runtimeFileCount)}`),h.evidenceFileCount!==void 0&&m.push(` ${r.label("Evidence files excluded")}: ${dn("evidenceFileCount",h.evidenceFileCount)}`),m.push(` ${r.label("Submit envelope")}: mandatory${b?` (${b})`:""}`)}if(p){let v=p.fileCount??p.files??e.fileCount,b=p.bodyWordCount??p.bodyWords??e.bodyWordCount;m.push("",r.section("File Summary")),v!==void 0&&m.push(` ${r.label("File count")}: ${dn("fileCount",v)}`),b!==void 0&&m.push(` ${r.label("Body words")}: ${dn("bodyWordCount",b)}`)}let g=j(e,"securityReport");g&&(m.push("",r.section("Security")),m.push(` ${r.label("Recommendation")}: ${f(g,"recommendation")??"unknown"}`),m.push(...fh("Findings",Array.isArray(g.findings)?g.findings:[],r,"No security findings returned.")));let y=j(e,"aiReview");if(y){m.push("",r.section("AI Review")),m.push(` ${r.label("Status")}: ${f(y,"status")??"unknown"}`);let v=f(y,"message");v&&m.push(` ${v}`);let b=f(y,"nextStep");b&&m.push(` ${r.arrow} ${b}`)}return m.push("",...fh("Issues",c,r,"No blocking issues found.")),m.push("",...fh("Warnings",u,r,"No warnings returned.")),m.push("",...fh("Advice",d,r,"No extra advice returned.")),m.push("",r.section("Next")),l?(m.push(` ${r.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),m.push(` ${r.arrow} skills-layer creator submit ${t} --dry-run`)):m.push(` ${r.arrow} Fix the listed issues, then run skills-layer validate ${t}`),m.join(`
|
|
2288
|
-
`)}function vP(e,t,n){let r=Array.isArray(e[n])?e[n]:[],i=Array.isArray(t[n])?t[n]:[];return r.length>0?r:i}function fh(e,t,n,r){let i=[n.section(`${e} (${t.length})`)];return t.length===0?(i.push(` ${n.muted(r)}`),i):(t.slice(0,
|
|
2289
|
-
`)}function Fle(e){return[...un(e.promptResults),...un(e.results),...un(e.shouldTriggerResults),...un(e.shouldNotTriggerResults),...un(e.paraphraseResults)]}function Ble(e){let t=Ka(e.guidance),n=un(e.guidance).map(r=>fz(r));return[...t,...n]}function Mle(e,t){let n=f(e,"prompt")??f(e,"text")??f(e,"input")??`Prompt ${t+1}`,r=Ule(e),i=zle(e),o=qle(e),s=e.score??e.confidence,a=f(e,"reason")??f(e,"explanation")??f(e,"message");return[`"${Za(n)}"`,r?`expected: ${r}`:void 0,i?`actual: ${i}`:void 0,o,s!==void 0?`score: ${dn("score",s)}`:void 0,a?`reason: ${Za(a)}`:void 0].filter(l=>!!l).join("; ")}function Ule(e){return typeof e.shouldTrigger=="boolean"?e.shouldTrigger?"should trigger":"should not trigger":typeof e.expectedTrigger=="boolean"?e.expectedTrigger?"should trigger":"should not trigger":f(e,"expected")??f(e,"kind")??f(e,"type")}function zle(e){return typeof e.triggered=="boolean"?e.triggered?"triggered":"did not trigger":typeof e.actualTrigger=="boolean"?e.actualTrigger?"triggered":"did not trigger":f(e,"actual")??f(e,"classification")??f(e,"decision")}function qle(e){return typeof e.passed=="boolean"?e.passed?"pass":"fail":typeof e.pass=="boolean"?e.pass?"pass":"fail":f(e,"status")}function Vle(e,t,n,r){let i=Pe(r),o=f(e,"skillSlug")??
|
|
2288
|
+
`)}function vP(e,t,n){let r=Array.isArray(e[n])?e[n]:[],i=Array.isArray(t[n])?t[n]:[];return r.length>0?r:i}function fh(e,t,n,r){let i=[n.section(`${e} (${t.length})`)];return t.length===0?(i.push(` ${n.muted(r)}`),i):(t.slice(0,at).forEach((o,s)=>{i.push(`${s+1}. ${fz(o)}`)}),i)}function fz(e){return L(e)?(f(e,"message")??f(e,"title")??f(e,"code")??f(e,"path")??Ju(e))||"Details available with --json":dn("",e)}function Nle(e,t,n){let r=Pe(n),i=Fle(e),o=Ble(e),s=[`${r.ok("OK")} Trigger preview complete.`,"",r.section("Bundle"),` ${r.label("Path")}: ${t}`],a=f(e,"skillSlug")??f(e,"slug");return a&&s.push(` ${r.label("Skill")}: ${a}`),s.push("",r.section(`Prompt Results (${i.length})`)),i.length===0&&s.push(` ${r.muted("No prompt results returned. Use --json to inspect the raw backend response.")}`),i.slice(0,at).forEach((l,c)=>{s.push(`${c+1}. ${Mle(l,c)}`)}),s.push("",r.section(`Guidance (${o.length})`)),o.length===0&&s.push(` ${r.muted("No extra trigger guidance returned.")}`),o.slice(0,at).forEach((l,c)=>{s.push(`${c+1}. ${l}`)}),s.push("",r.section("Next")),s.push(` ${r.arrow} skills-layer validate ${t}`),s.push(` ${r.arrow} skills-layer creator submit ${t} --dry-run`),s.join(`
|
|
2289
|
+
`)}function Fle(e){return[...un(e.promptResults),...un(e.results),...un(e.shouldTriggerResults),...un(e.shouldNotTriggerResults),...un(e.paraphraseResults)]}function Ble(e){let t=Ka(e.guidance),n=un(e.guidance).map(r=>fz(r));return[...t,...n]}function Mle(e,t){let n=f(e,"prompt")??f(e,"text")??f(e,"input")??`Prompt ${t+1}`,r=Ule(e),i=zle(e),o=qle(e),s=e.score??e.confidence,a=f(e,"reason")??f(e,"explanation")??f(e,"message");return[`"${Za(n)}"`,r?`expected: ${r}`:void 0,i?`actual: ${i}`:void 0,o,s!==void 0?`score: ${dn("score",s)}`:void 0,a?`reason: ${Za(a)}`:void 0].filter(l=>!!l).join("; ")}function Ule(e){return typeof e.shouldTrigger=="boolean"?e.shouldTrigger?"should trigger":"should not trigger":typeof e.expectedTrigger=="boolean"?e.expectedTrigger?"should trigger":"should not trigger":f(e,"expected")??f(e,"kind")??f(e,"type")}function zle(e){return typeof e.triggered=="boolean"?e.triggered?"triggered":"did not trigger":typeof e.actualTrigger=="boolean"?e.actualTrigger?"triggered":"did not trigger":f(e,"actual")??f(e,"classification")??f(e,"decision")}function qle(e){return typeof e.passed=="boolean"?e.passed?"pass":"fail":typeof e.pass=="boolean"?e.pass?"pass":"fail":f(e,"status")}function Vle(e,t,n,r){let i=Pe(r),o=f(e,"skillSlug")??ot(t),s=[`${i.ok("OK")} Created ${n}.`,"",i.section("Local Skill")];s.push(` ${i.label("Path")}: ${n}`),s.push(` ${i.label("Skill")}: ${o}`);let a=f(e,"skillType"),l=f(e,"category");return a&&s.push(` ${i.label("Type")}: ${a}`),l&&s.push(` ${i.label("Category")}: ${l}`),s.push(` ${i.label("Evaluation")}: not run`),s.push("",i.section("Next")),s.push(` ${i.arrow} Edit ${n}`),s.push(` ${i.arrow} skills-layer validate ${t}`),s.push(` ${i.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),s.push(` ${i.arrow} skills-layer creator submit ${t} --dry-run`),s.join(`
|
|
2290
2290
|
`)}function Gle(e,t,n){let r=j(e,"profile")??e,i=kP(r,"requirementsCurrentlyDue"),o=kP(r,"requirementsPastDue"),s=kP(r,"requirementsPendingVerification"),a=["payouts","Enabled"].join(""),l=r.readyForPayouts??r[a],c=l===!0,u=[`${n.ok("OK")} ${t}`,"",n.section("Payout Profile")];return u.push(` ${n.label("Status")}: ${gh(f(r,"status"))}`),u.push(` ${n.label("Ready for payouts")}: ${OM(l)}`),u.push(` ${n.label("Account details submitted")}: ${OM(r.detailsSubmitted)}`),u.push(` ${n.label("Currency")}: ${gh(f(r,"currency")?.toUpperCase())}`),u.push(` ${n.label("Country")}: ${gh(f(r,"country")?.toUpperCase())}`),u.push(` ${n.label("Minimum withdrawal")}: ${Wle(r)}`),u.push(` ${n.label("Updated at")}: ${gh(f(r,"updatedAt"))}`),u.push("",n.section("Requirements")),u.push(` ${n.label("Currently due")}: ${wP(i)}`),u.push(` ${n.label("Past due")}: ${wP(o)}`),u.push(` ${n.label("Pending verification")}: ${wP(s)}`),u.push("",n.section("Next")),c?(u.push(` ${n.arrow} skills-layer creator earnings`),u.push(` ${n.arrow} skills-layer creator withdraw --amount-cents <amount>`),u.push(` ${n.arrow} skills-layer creator payouts`)):(u.push(` ${n.arrow} skills-layer creator payout-link`),u.push(` ${n.arrow} skills-layer creator earnings`)),u.join(`
|
|
2291
2291
|
`)}function Hle(e,t,n){let r=GP(e),i=Ne(e,"withdrawableBalanceCents"),o=[`${n.ok("OK")} ${t}`,"",n.section("Earnings Summary")];return o.push(` ${n.label("Gross sales")}: ${Ue(Ne(e,"successfulSalesCents"),r)}`),o.push(` ${n.label("Platform fees")}: ${Ue(Ne(e,"platformFeeCents"),r)}`),o.push(` ${n.label("Refunds requested")}: ${Ue(Ne(e,"refundRequestedCents"),r)}`),o.push(` ${n.label("Refunded")}: ${Ue(Ne(e,"refundedCents"),r)}`),(Ne(e,"disputedCents")>0||Oo(e,"disputedCount")>0)&&o.push(` ${n.label("Disputed (held)")}: ${Ue(Ne(e,"disputedCents"),r)} (${Oo(e,"disputedCount")})`),(Ne(e,"chargebackCents")>0||Oo(e,"chargebackCount")>0)&&o.push(` ${n.label("Charged back")}: ${Ue(Ne(e,"chargebackCents"),r)} (${Oo(e,"chargebackCount")})`),Ne(e,"reversedCreatorShareCents")>0&&o.push(` ${n.label("Creator share reversed")}: \u2212${Ue(Ne(e,"reversedCreatorShareCents"),r)}`),Ne(e,"disputeFeeDebitsCents")>0&&o.push(` ${n.label("Dispute fees charged")}: \u2212${Ue(Ne(e,"disputeFeeDebitsCents"),r)}`),Ne(e,"estimatedAvailableCents")<0&&o.push(" Negative balance: future earnings repay this debt before payouts resume."),Oo(e,"disputeFeeReviewCount")>0&&o.push(" Dispute fee reconciliation is pending; payouts are on hold."),o.push(` ${n.label("Estimated after holds clear")}: ${Ue(Ne(e,"estimatedAvailableCents"),r)}`),o.push(` ${n.label("Withdrawable now")}: ${Ue(Ne(e,"withdrawableBalanceCents"),r)}`),o.push(` ${n.label("Held balance")}: ${Ue(Ne(e,"heldBalanceCents"),r)}`),o.push(` ${n.label("Refund exposure")}: ${Ue(Ne(e,"refundExposureCents"),r)}`),o.push("",n.section("Activity")),o.push(` ${n.label("Successful purchases")}: ${Oo(e,"successfulPurchaseCount")}`),o.push(` ${n.label("Refund requests")}: ${Oo(e,"refundRequestedCount")}`),o.push(` ${n.label("Pending payouts")}: ${Ue(Ne(e,"pendingPayoutCents"),r)}`),o.push(` ${n.label("Completed payouts")}: ${Ue(Ne(e,"completedPayoutCents"),r)}`),o.push("",n.section("Guidance")),i>0?(o.push("1. You have a withdrawable balance available."),o.push("2. Confirm payout setup is ready before requesting withdrawal.")):(o.push("1. No withdrawable balance yet."),o.push("2. Sales will appear here after paid purchases settle.")),o.push("",n.section("Next")),i>0&&o.push(` ${n.arrow} skills-layer creator withdraw --amount-cents ${i}`),o.push(` ${n.arrow} skills-layer creator payout-profile`),o.push(` ${n.arrow} skills-layer creator payouts`),o.join(`
|
|
2292
|
-
`)}function Kle(e,t,n){let r=Array.isArray(e.results)?e.results:[],i=GP(e,r),o=Ne(e,"withdrawableBalanceCents"),s=[`${n.ok("OK")} ${t}`,"",n.section("Payout History")];return s.push(` ${n.label("Withdrawable now")}: ${mh(e,"withdrawableBalanceCents",i)}`),s.push(` ${n.label("Pending payouts")}: ${mh(e,"pendingPayoutCents",i)}`),s.push(` ${n.label("Completed payouts")}: ${mh(e,"completedPayoutCents",i)}`),s.push("",n.section(`Requests (${r.length})`)),r.length===0?s.push(` ${n.muted("No payout requests yet.")}`):(r.slice(0,
|
|
2293
|
-
`)}function GP(e,t,n="USD"){let r=f(e,"currency");if(r)return r.toUpperCase();let i=t?.find(L);if(i){let o=f(i,"currency");if(o)return o.toUpperCase()}return n}function Ne(e,t){return J(e,t)??0}function Oo(e,t){return J(e,t)??0}function mh(e,t,n){return Ue(Ne(e,t),n)}function kP(e,t){return(Un(e,t)??[]).map(n=>n.replace(/[._-]+/gu," "))}function wP(e){return e.length>0?e.join(", "):"none"}function OM(e){return e===!0?"yes":e===!1?"no":"unknown"}function gh(e){return e??"none"}function Wle(e){let t=J(e,"minimumWithdrawalAmountCents"),n=f(e,"currency")?.toUpperCase()??"minor units";return t===void 0?"none":`${Zle(t)} ${n}`}function Zle(e){return(e/100).toFixed(2).replace(/\.00$/u,"").replace(/(\.\d)0$/u,"$1")}function Pe(e){let t=e?.renderMode??Aa([],{},{stdinIsTty:!1,stdoutIsTty:!1,stderrIsTty:!1}).mode,n=an(t);return{ok:n.success,section:n.heading,label:n.label,muted:n.muted,arrow:n.info("->")}}function Jle(e,t){let n=[],r=Qle(e,t);r.length>0&&n.push(...r);let i=Yle(e,t);i.length>0&&n.push(...i);for(let[o,s]of nce(e))if(Array.isArray(s))n.push(...Xle(o,s,t));else if(L(s)){let a=Ju(s);a&&n.push(` ${t.label(KP(o))}: ${a}`)}else n.push(` ${t.label(KP(o))}: ${dn(o,s)}`);return n}function Yle(e,t){let n=j(e,"effectiveness");if(!n)return[];let r=f(n,"label"),i=f(n,"latestSummaryStatus"),o=J(n,"evidenceCount"),s=j(n,"score"),a=s?J(s,"overallScore"):void 0,l=s?J(s,"effectiveScorePercent"):void 0,c=s?j(s,"components"):void 0,u=c?J(c,"passRate"):void 0,d=c?J(c,"coverageRatio"):void 0;if(!r&&i===void 0&&o===void 0&&a===void 0)return[];let p=[t.section("Effectiveness")];if(r&&p.push(` ${t.label("Label")}: ${r}`),i&&p.push(` ${t.label("Latest summary")}: ${i}`),o!==void 0&&p.push(` ${t.label("Evidence count")}: ${o}`),Array.isArray(n.assessmentCoverage))for(let m of n.assessmentCoverage)L(m)&&typeof m.assessedRanges=="number"&&typeof m.availableRanges=="number"&&typeof m.untestedRanges=="number"&&p.push(` ${t.label("Assessment scope")}: ${m.assessedRanges} of ${m.availableRanges} source ranges assessed; ${m.untestedRanges} untested. Score applies to the sample.`);return l!==void 0?p.push(` ${t.label("Effective score")}: ${Eh(l)}`):a!==void 0&&p.push(` ${t.label("Effective score")}: ${Eh(a*100)}`),u!==void 0&&p.push(` ${t.label("Pass rate")}: ${u}`),d!==void 0&&p.push(` ${t.label("Coverage")}: ${d}`),p}function Eh(e){let t=Math.round(e*10)/10;return`${Number.isInteger(t)?t.toFixed(0):t.toFixed(1)}%`}function Xle(e,t,n){let r=rce(e),i=[n.section(`${r} (${t.length})`)];return t.length===0?(i.push(` ${n.muted("No entries.")}`),i):(t.slice(0,
|
|
2292
|
+
`)}function Kle(e,t,n){let r=Array.isArray(e.results)?e.results:[],i=GP(e,r),o=Ne(e,"withdrawableBalanceCents"),s=[`${n.ok("OK")} ${t}`,"",n.section("Payout History")];return s.push(` ${n.label("Withdrawable now")}: ${mh(e,"withdrawableBalanceCents",i)}`),s.push(` ${n.label("Pending payouts")}: ${mh(e,"pendingPayoutCents",i)}`),s.push(` ${n.label("Completed payouts")}: ${mh(e,"completedPayoutCents",i)}`),s.push("",n.section(`Requests (${r.length})`)),r.length===0?s.push(` ${n.muted("No payout requests yet.")}`):(r.slice(0,at).forEach((a,l)=>{if(!L(a)){s.push(`${l+1}. ${dn("",a)}`);return}let c=GP(a,void 0,i),u=f(a,"payoutId")??f(a,"id")??`Payout ${l+1}`,d=f(a,"status")??"unknown",p=mh(a,"amountCents",c),m=f(a,"requestedAt"),h=f(a,"completedAt"),g=f(a,"reason");s.push(`${l+1}. ${u}`),s.push(` ${n.label("Amount")}: ${p}; ${n.label("Status")}: ${d}`),m&&s.push(` ${n.label("Requested")}: ${m}`),h&&s.push(` ${n.label("Completed")}: ${h}`),g&&s.push(` ${n.label("Reason")}: ${g}`)}),r.length>at&&s.push(` ${n.muted(`... ${r.length-at} more`)}`)),s.push("",n.section("Guidance")),r.length===0?s.push("1. Payouts appear here after you request a withdrawal."):s.push("1. Use this history to track requested, processing, paid, or failed payouts."),s.push("2. Check payout profile if setup or verification looks incomplete."),s.push("",n.section("Next")),o>0&&s.push(` ${n.arrow} skills-layer creator withdraw --amount-cents ${o}`),s.push(` ${n.arrow} skills-layer creator earnings`),s.push(` ${n.arrow} skills-layer creator payout-profile`),s.join(`
|
|
2293
|
+
`)}function GP(e,t,n="USD"){let r=f(e,"currency");if(r)return r.toUpperCase();let i=t?.find(L);if(i){let o=f(i,"currency");if(o)return o.toUpperCase()}return n}function Ne(e,t){return J(e,t)??0}function Oo(e,t){return J(e,t)??0}function mh(e,t,n){return Ue(Ne(e,t),n)}function kP(e,t){return(Un(e,t)??[]).map(n=>n.replace(/[._-]+/gu," "))}function wP(e){return e.length>0?e.join(", "):"none"}function OM(e){return e===!0?"yes":e===!1?"no":"unknown"}function gh(e){return e??"none"}function Wle(e){let t=J(e,"minimumWithdrawalAmountCents"),n=f(e,"currency")?.toUpperCase()??"minor units";return t===void 0?"none":`${Zle(t)} ${n}`}function Zle(e){return(e/100).toFixed(2).replace(/\.00$/u,"").replace(/(\.\d)0$/u,"$1")}function Pe(e){let t=e?.renderMode??Aa([],{},{stdinIsTty:!1,stdoutIsTty:!1,stderrIsTty:!1}).mode,n=an(t);return{ok:n.success,section:n.heading,label:n.label,muted:n.muted,arrow:n.info("->")}}function Jle(e,t){let n=[],r=Qle(e,t);r.length>0&&n.push(...r);let i=Yle(e,t);i.length>0&&n.push(...i);for(let[o,s]of nce(e))if(Array.isArray(s))n.push(...Xle(o,s,t));else if(L(s)){let a=Ju(s);a&&n.push(` ${t.label(KP(o))}: ${a}`)}else n.push(` ${t.label(KP(o))}: ${dn(o,s)}`);return n}function Yle(e,t){let n=j(e,"effectiveness");if(!n)return[];let r=f(n,"label"),i=f(n,"latestSummaryStatus"),o=J(n,"evidenceCount"),s=j(n,"score"),a=s?J(s,"overallScore"):void 0,l=s?J(s,"effectiveScorePercent"):void 0,c=s?j(s,"components"):void 0,u=c?J(c,"passRate"):void 0,d=c?J(c,"coverageRatio"):void 0;if(!r&&i===void 0&&o===void 0&&a===void 0)return[];let p=[t.section("Effectiveness")];if(r&&p.push(` ${t.label("Label")}: ${r}`),i&&p.push(` ${t.label("Latest summary")}: ${i}`),o!==void 0&&p.push(` ${t.label("Evidence count")}: ${o}`),Array.isArray(n.assessmentCoverage))for(let m of n.assessmentCoverage)L(m)&&typeof m.assessedRanges=="number"&&typeof m.availableRanges=="number"&&typeof m.untestedRanges=="number"&&p.push(` ${t.label("Assessment scope")}: ${m.assessedRanges} of ${m.availableRanges} source ranges assessed; ${m.untestedRanges} untested. Score applies to the sample.`);return l!==void 0?p.push(` ${t.label("Effective score")}: ${Eh(l)}`):a!==void 0&&p.push(` ${t.label("Effective score")}: ${Eh(a*100)}`),u!==void 0&&p.push(` ${t.label("Pass rate")}: ${u}`),d!==void 0&&p.push(` ${t.label("Coverage")}: ${d}`),p}function Eh(e){let t=Math.round(e*10)/10;return`${Number.isInteger(t)?t.toFixed(0):t.toFixed(1)}%`}function Xle(e,t,n){let r=rce(e),i=[n.section(`${r} (${t.length})`)];return t.length===0?(i.push(` ${n.muted("No entries.")}`),i):(t.slice(0,at).forEach((o,s)=>{i.push(...mz(o,s,n))}),t.length>at&&i.push(` ${n.muted(`... ${t.length-at} more`)}`),i)}function mz(e,t,n){if(!L(e))return[`${t+1}. ${dn("",e)}`];let r=HP(e)??Re(Ju(e))??`Item ${t+1}`,i=[`${t+1}. ${r}`],o=hz(e);o&&i.push(` ${o}`);let s=Ju(e);return s&&i.push(` ${s}`),i}function Qle(e,t){let n=Zoe(e,t);if(n.length>0)return n;let r=j(e,"capabilityProfile"),i=r?f(r,"runtimeRisk"):void 0;return i?[t.section("Trust"),` ${t.label("Runtime risk")}: ${i}`]:[]}function ece(e,t,n){let r=Pe(n),i=f(e,"skillSlug")??t,o=f(e,"runtimeRisk")??(j(e,"capabilityProfile")?f(j(e,"capabilityProfile"),"runtimeRisk"):void 0),s=[`${r.ok("OK")} Creator security report loaded.`,"",r.section("Creator Security")];o&&s.push(` ${r.label("Runtime risk")}: ${o}`);let a=f(e,"recommendation");a&&s.push(` ${r.label("Recommendation")}: ${a}`),s.push(` ${r.label("Skill")}: ${i}`);let l=f(e,"version");l&&s.push(` ${r.label("Version")}: ${l}`);let c=["semantic","review","no","reviewable","findings"].join("_"),u=Ka(e.reviewDegradedReasons).includes(c),d=Ka(e.trustBadges).filter(h=>h==="capability-mismatch"),p=Ka(e.trustBadges).filter(h=>h!=="capability-mismatch");(u||d.length>0)&&(s.push("",r.section("Creator Notes")),u&&s.push("1. Semantic review was not needed because there were no reviewable findings."),d.forEach((h,g)=>{s.push(`${u?g+2:g+1}. ${h==="capability-mismatch"?"Capability declaration needs review.":h}`)})),p.length>0&&(s.push("",r.section(`Trust badges (${p.length})`)),p.slice(0,at).forEach((h,g)=>s.push(`${g+1}. ${h}`)));let m=Array.isArray(e.findings)?e.findings:[];return s.push("",r.section(`Findings (${m.length})`)),m.length===0?s.push(` ${r.muted("No entries.")}`):m.slice(0,at).forEach((h,g)=>{s.push(...mz(h,g,r))}),s.push("",r.section("Next")),s.push(` ${r.arrow} skills-layer creator rescan-security ${i}`),s.push(` ${r.arrow} skills-layer creator status ${i}`),s.push(` ${r.arrow} skills-layer trust ${i}`),s.join(`
|
|
2294
2294
|
`)}function tce(e,t,n){let i=j(e,"report")??e,o=Pe(n),s=i.securityScore,a=f(i,"generatedAt")??f(i,"reportGeneratedAt"),l=Array.isArray(i.findings)?i.findings:void 0,c=[`${o.ok("OK")} Security rescan requested.`,"",o.section("Creator Security")];return c.push(` ${o.label("Skill")}: ${f(i,"skillSlug")??t}`),l&&c.push(` ${o.label("Findings")}: ${l.length}`),a&&c.push(` ${o.label("Generated at")}: ${a}`),c.push("",o.section("Next")),c.push(` ${o.arrow} skills-layer creator security-report ${t}`),c.push(` ${o.arrow} skills-layer creator status ${t}`),c.join(`
|
|
2295
2295
|
`)}function nce(e){return Object.entries(e).filter(([t,n])=>gz(t,n))}function gz(e,t){let n=e.toLowerCase();return n==="status"||n==="securityscore"||n==="recommendation"||n==="capabilityprofile"||n==="securityposture"||n==="trust"||n==="effectiveness"||n.includes("apikey")||n.includes("secret")||n.includes("token")||n==="content"?!1:t!==void 0}function Ju(e){let n=[["id","id"],["name","name"],["keyPrefix","prefix"],["slug","slug"],["skillSlug","skill"],["currentVersion","version"],["version","version"],["category","category"],["skillType","type"],["type","type"],["visibility","visibility"],["status","status"],["count","count"],["email","email"],["role","role"],["selectedBackend","backend"],["selectedBaseUrl","base url"],["path","path"],["downloadUrl","download url"],["authorizationUrl","authorization url"],["checkoutUrl","checkout url"],["url","url"],["issueId","issue"],["reviewId","review"],["purchaseId","purchase"],["workspaceId","workspace"],["clientId","client"],["environment","environment"],["expiresAt","expires"],["lastUsedAt","last used on (UTC day)"],["revocable","revocable"],["revokeCommand","revoke"],["approvalId","approval"],["source","source"],["scope","scope"],["agent","agent"],["bytes","bytes"],["fileCount","file count"],["bodyWordCount","body words"]].flatMap(([i,o])=>{if(!gz(i,e[i]))return[];let s=e[i];return s===void 0?[]:[`${o}: ${dn(i,s)}`]}),r=j(e,"securityPosture");if(r){let i=f(r,"label"),o=f(r,"runtimeRisk");i&&n.push(`trust: ${i}`),o&&n.push(`risk: ${o}`)}return n.join("; ")}function hz(e){return f(e,"shortDescription")??f(e,"summary")??f(e,"description")??f(e,"message")}function HP(e){return f(e,"displayName")??f(e,"name")??f(e,"title")??f(e,"slug")??f(e,"skillSlug")??f(e,"code")??f(e,"id")}function dn(e,t){return e==="lastUsedAt"&&typeof t=="string"?t.slice(0,10):e==="downloadUrl"?"<hidden; use --json or --output>":typeof t=="string"?e.toLowerCase()==="category"?yz(t):Za(t):typeof t=="number"||typeof t=="boolean"?String(t):t===null?"none":Array.isArray(t)?`${t.length} item${t.length===1?"":"s"}`:L(t)?Ju(t)||"details available with --json":String(t)}function yz(e){return f0(e)}function Za(e){let t=e.replace(/\s+/gu," ").trim();return t.length>160?`${t.slice(0,157)}...`:t}function rce(e){return Fh(KP(e))}function KP(e){return e.replace(/([a-z0-9])([A-Z])/gu,"$1 $2").replace(/[_-]+/gu," ").toLowerCase()}function ice(e){if(e.verificationStatus==="unverified"&&e.publiclyDiscoverable===!1)return["Review the locally installed files before use; they remain Unverified / Unscored.","A public listing requires successful evaluation and final publication authority; held reviews are not automatic approval."];let t=oce(e),n=t?[`skills-layer show ${t}`,`skills-layer trust ${t}`,`skills-layer install ${t}`]:[],r=typeof e.downloadUrl=="string",i=Array.isArray(e.materializedWrites)&&e.materializedWrites.length>0;return r&&n.push("Use --output <path> to write exports without printing temporary download URLs"),i&&n.push("Review the materialized files in this workspace"),e.valid===!0&&n.push("skills-layer creator submit <path> --dry-run"),n}function oce(e){let t=f(e,"skillSlug")??f(e,"slug");if(t)return t;let n=e.results;if(Array.isArray(n)){for(let r of n)if(L(r)){let i=f(r,"skillSlug")??f(r,"slug");if(i)return i}}}function L(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function R(e,t){e=H(e);let n=sce(e);return n?x(n.payload,e,t,n.reasonCode):t?x({status:"error",reasonCode:"command_failed",error:e},e,t,"command_failed"):{exitCode:1,stdout:"",stderr:St(e)}}function sce(e){if(/Local bundle rejected \(canonical_bundle_rejected\)/iu.test(e))return{reasonCode:"canonical_bundle_rejected",payload:{status:"error",reasonCode:"canonical_bundle_rejected",nextAction:"bundle.fix",nextStep:"Correct the listed bundle issues and run `skills-layer validate <path>`."}};if(/Invalid or expired recovery code/iu.test(e))return{reasonCode:"recovery_code_invalid_or_expired",payload:{status:"error",reasonCode:"recovery_code_invalid_or_expired",nextAction:"auth.recover",nextStep:"Request a fresh recovery code and complete recovery before it expires."}};let t=/^(?<provider>google|github|gitlab|microsoft) auth is not configured$/iu.exec(e);if(t?.groups?.provider)return{reasonCode:"social_provider_not_configured",payload:{status:"error",reasonCode:"social_provider_not_configured",provider:t.groups.provider.toLowerCase(),nextAction:"login",nextStep:"Choose a configured sign-in method or ask the platform operator to configure this provider."}};if(/^Search results do not include /u.test(e))return{reasonCode:"search_selection_not_found",payload:{status:"not_found",reasonCode:"search_selection_not_found",nextAction:"search",nextStep:"Run search again with a matching query or choose one of the returned skill slugs."}};if(/^workspace installs require --workspace <workspace-id>\.$/u.test(e))return{reasonCode:"workspace_required",payload:{status:"error",error:e,reasonCode:"workspace_required",nextAction:"workspace.current",nextStep:"Pass --workspace <workspace-id> using an accessible workspace."}};let n=/^Unsupported skill type "(?<skillType>[^"]+)"\./u.exec(e);if(n?.groups?.skillType)return{reasonCode:"unsupported_skill_type",payload:{status:"error",reasonCode:"unsupported_skill_type",providedSkillType:n.groups.skillType,acceptedValues:["standalone","workflow","workflow_automation","mcp_enhanced"],nextAction:"creator.init",nextStep:"Choose one of the supported skill types."}};let r=/^(?<code>EACCES|EPERM|EROFS):\s*(?<detail>.+)$/iu.exec(e);if(r?.groups){let h=r.groups.code.toUpperCase(),g=/'(?<path>[^']+)'/u.exec(e)?.groups?.path;return{reasonCode:"local_filesystem_permission_denied",payload:{status:"error",reasonCode:"local_filesystem_permission_denied",code:h,...g?{path:g}:{},nextAction:"check_local_permissions",nextStep:"Check the local path permissions, choose a writable installed skill directory, or rerun the command from a workspace you can write to."}}}let i=/^--(?<flag>[a-z0-9-]+) must be valid JSON\.$/iu.exec(e);if(i?.groups){let h=i.groups.flag;return{reasonCode:"invalid_json",payload:{status:"error",reasonCode:"invalid_json",flag:h,nextAction:"fix_json_flag",nextStep:`Provide valid JSON for --${h}.`}}}let o=/^Unknown flag --(?<flag>[a-z0-9-]+)\.$/iu.exec(e);if(o?.groups)return{reasonCode:"unknown_flag",payload:{status:"error",reasonCode:"unknown_flag",flag:o.groups.flag,nextAction:"help",nextStep:"Run `skills-layer <command> --help` to see supported flags for that command."}};let s=/^(?<command>.+?) --(?<flag>[a-z0-9-]+) must be one of: (?<accepted>.+?)\.$/iu.exec(e);if(s?.groups){let h=s.groups.flag,g=s.groups.accepted.split(",").map(y=>y.trim()).filter(Boolean);return{reasonCode:`invalid_${h.replace(/-/gu,"_")}`,payload:{status:"error",reasonCode:`invalid_${h.replace(/-/gu,"_")}`,command:s.groups.command,flag:h,acceptedValues:g,nextAction:s.groups.command.replace(/\s+/gu,"."),nextStep:`Use --${h} with one of: ${g.join(", ")}.`}}}let a=/^Unknown (?<namespace>.+?) command "(?<subcommand>.*?)"\.$/u.exec(e);if(a?.groups){let h=a.groups.namespace.trim(),g=a.groups.subcommand;return{reasonCode:"unknown_subcommand",payload:{status:"error",reasonCode:"unknown_subcommand",namespace:h,subcommand:g,nextAction:`${h.replace(/\s+/gu,".")}.help`,nextStep:`Run \`skills-layer ${h} --help\` to see supported ${h} commands.`}}}if(e.startsWith("Flag --"))return{reasonCode:"flag_value_missing",payload:{status:"error",reasonCode:"flag_value_missing",nextStep:"Supply a value for the flag. To clear a profile field, use its --clear-<field> option."}};let l=/^(?<command>.+?) requires (?<argument>.+?)\.$/u.exec(e);if(!l?.groups)return;let c=l.groups.command.trim(),u=l.groups.argument.trim(),d=ace(u),p=/--(?<name>[a-z0-9-]+)/iu.exec(u)?.groups?.name,m=p?`--${p} <value>`:`<${d}>`;return{reasonCode:"missing_required_argument",payload:{status:"error",reasonCode:"missing_required_argument",command:c,argument:d,nextAction:c.replace(/\s+/gu,"."),nextStep:`Run \`skills-layer ${c} ${m}\`.`}}}function ace(e){let t=e.replace(/^(?:a|an|the)\s+/iu,"");if(/^two or more skill slugs$/iu.test(t))return"two-or-more-skill-slugs";let n=/--(?<name>[a-z0-9-]+)/iu.exec(t)?.groups?.name;return n||(/<(?<name>[^>]+)>/u.exec(t)?.groups?.name??t).replace(/\s+or\s+.*$/iu,"").replace(/[^a-z0-9]+/giu,"-").replace(/^-+|-+$/gu,"").toLowerCase()||"argument"}function x(e,t,n,r){let i=Rh(e),o=Og(r??f(i,"reasonCode")),s={schemaVersion:MM,status:lce(f(i,"status"),o.defaultStatus),summary:t,why:f(i,"why")??null,nextAction:f(i,"nextAction")??null,nextStep:f(i,"nextStep")??null,data:i,warnings:Array.isArray(i.warnings)?i.warnings:[],links:Array.isArray(i.links)?i.links:[],reasonCode:o.reasonCode,reasonFamily:o.family,handoff:i.handoff??null};return{exitCode:1,stdout:"",stderr:n?JSON.stringify(s,null,2):St(cce(s,t))}}function lce(e,t){return!e||!/^[a-z][a-z0-9_]*$/u.test(e)||e==="approved"||e==="published"?t:e}function cce(e,t){let n=f(e,"summary")??t,r=f(e,"reasonCode"),i=f(e,"why"),o=f(e,"nextStep"),s=j(e,"data"),a=s?f(s,"requestId")??f(s,"operationId"):void 0,l=uce(r,n),c=[l];l!==n&&c.push(n),c.push("","Unchanged"," No Skills Layer state was changed by this failed command."),i&&i!==n&&c.push("","Why",` ${i}`);let d=(s&&Array.isArray(s.blockingFindings)?s.blockingFindings:[]).flatMap(p=>{if(!L(p)||typeof p.code!="string"||!/^[A-Za-z0-9_-]{1,128}$/u.test(p.code))return[];let m=typeof p.path=="string"?p.path.replace(/[\p{Cc}\p{Cf}]/gu,"").slice(0,256):"",h=Number.isSafeInteger(p.lineNumber)&&Number(p.lineNumber)>0?`:${p.lineNumber}`:"";return[` ${p.code}${m?` \u2014 ${m}${h}`:""}`]}).slice(0,12);if(d.length>0&&c.push("","Blocking checks",...d),o){let p=/`(?<command>skills-layer(?: [^`]+)?)`/u.exec(o)?.groups?.command;c.push("","Next",` ${p??o}`)}else{let p=/`(?<command>skills-layer(?: [^`]+)?)`/u.exec(n)?.groups?.command;c.push("","Next",` ${p??"skills-layer --help"}`)}return a&&c.push("",`Reference ${a}`),c.join(`
|
|
2296
2296
|
`)}function uce(e,t){if(e==="missing_required_argument")return"Required information is missing";if(e==="unknown_flag")return"That option is not supported";if(e==="invalid_json")return"That JSON value could not be read";if(e==="local_filesystem_permission_denied")return"Skills Layer cannot write to that location";if(e==="login_required")return"Sign in required";if(e==="social_identity_link_required")return"Secure account connection required";let n=t.split(`
|
|
2297
2297
|
`,1)[0]?.trim();return n&&n.length<=72?n:"Skills Layer could not complete the command"}function Go(e,t){let n=lz(e.details);if(n)return A(n,String(n.message),t);let r=e.details??{};if(e.status===401&&!f(r,"reasonCode")){let a=f(r,"error")??"Login required.",l=f(r,"nextAction")??"login",c=f(r,"nextStep")??"Run `skills-layer login` to sign in, then retry this command.",u=/[.!?]$/u.test(a)?a:`${a}.`;return x({status:"login_required",reasonCode:"login_required",error:a,nextAction:l,nextStep:c},`${u} ${c}`,t,"login_required")}let i=f(r,"reasonCode");if(i){let a=L(r.data)?r.data:null,c=a!==null&&("summary"in r||"data"in r)?a:r,u=f(c,"error")??f(r,"error")??f(r,"summary")??e.message,d=Og(i,{httpStatus:e.status}),p=u==="Request failed"||u==="Request failed."?d.safeSummary:u;return x({...c,status:f(r,"status")??f(c,"status")??(e.status===404?"not_found":"error"),nextAction:f(c,"nextAction")??f(r,"nextAction"),nextStep:f(c,"nextStep")??f(r,"nextStep"),warnings:Array.isArray(c.warnings)?c.warnings:r.warnings,links:Array.isArray(c.links)?c.links:r.links,handoff:c.handoff??r.handoff,reasonCode:i},p,t,i)}let o=dce(e);if(o)return x(o.payload,o.message,t,o.reasonCode);let s=Og(null,{httpStatus:e.status});return x({status:s.defaultStatus,reasonCode:s.reasonCode,error:f(r,"error")??e.message,...Array.isArray(r.issues)?{issues:r.issues}:{},...L(r.validation)?{validation:r.validation}:{},nextAction:e.status===404?"help":null,nextStep:e.status===404?"Check the identifier or list the resources visible to this account.":null},f(r,"error")??e.message,t,s.reasonCode)}function dce(e){let t=f(e.details??{},"error")??e.message,n=t.toLowerCase();return n.includes("invalid or expired recovery code")?{reasonCode:"recovery_code_invalid_or_expired",message:"The recovery code is invalid or expired.",payload:{status:"error",reasonCode:"recovery_code_invalid_or_expired",nextAction:"auth.recover",nextStep:"Request a fresh recovery code and complete recovery before it expires."}}:/^(?:google|github|gitlab|microsoft) auth is not configured$/u.test(n)?{reasonCode:"social_provider_not_configured",message:"The selected social provider is not configured.",payload:{status:"error",reasonCode:"social_provider_not_configured",nextAction:"login",nextStep:"Choose a configured sign-in method or ask the platform operator to configure this provider."}}:e.status===403?{reasonCode:"permission_denied",message:"This credential cannot access the requested resource.",payload:{status:"error",reasonCode:"permission_denied",nextAction:null,nextStep:null}}:e.status===404&&n.includes("source connection")?{reasonCode:"source_connection_not_found",message:"Source connection not found.",payload:{status:"not_found",error:t,reasonCode:"source_connection_not_found",nextAction:"source.connection.start",nextStep:"Check the source connection id, or start a new source connection."}}:e.status===404&&n.includes("approval request")?{reasonCode:"approval_request_not_found",message:"Approval request not found.",payload:{status:"not_found",error:t,reasonCode:"approval_request_not_found",nextAction:"approval.request.status",nextStep:"Check the approval request id, or rerun the workflow that created the approval request."}}:e.status===404&&(n.includes("purchase")||n.includes("invoice"))?{reasonCode:"purchase_not_found",message:"Purchase not found.",payload:{status:"not_found",error:t,reasonCode:"purchase_not_found",nextAction:"purchases.list",nextStep:"Run `skills-layer purchases list` to find a valid purchase id."}}:e.status===404&&(n.includes("security report")||n.includes("trust report"))?{reasonCode:"trust_report_not_found",message:"Platform Score report not found.",payload:{status:"not_found",error:t,reasonCode:"trust_report_not_found",nextAction:"trust",nextStep:"Run `skills-layer show <skill-slug>` to confirm the skill exists, then retry trust after the Platform Score report is generated."}}:e.status===404&&n.includes("help topic")?{reasonCode:"help_topic_not_found",message:"Help topic not found.",payload:{status:"not_found",error:t,reasonCode:"help_topic_not_found",nextAction:"help",nextStep:"Run `skills-layer help full` or `skills-layer --help` to see available topics."}}:e.status===404&&n.includes("skill")?{reasonCode:"skill_not_found",message:"Skill not found.",payload:{status:"not_found",error:t,reasonCode:"skill_not_found",nextAction:"search",nextStep:"Run `skills-layer search <query>` to find a valid skill slug before retrying."}}:e.status===404?n.includes("download exported bundle")?{reasonCode:"resource_not_found",message:t,payload:{status:"not_found",error:t,reasonCode:"resource_not_found",nextAction:"export",nextStep:"Request a fresh export URL and retry the download."}}:{reasonCode:"resource_not_found",message:"The requested resource was not found.",payload:{status:"not_found",reasonCode:"resource_not_found",nextAction:"help",nextStep:"Check the identifier or list the resources visible to this account."}}:null}async function ke(e){try{return JSON.parse(await Fi(e,"utf8"))}catch{return null}}async function xA(e,t){try{let n=qC(await ke(e.paths.pendingRevocationsPath)),r=_g(t);return await Ve(e.paths.pendingRevocationsPath,VC(N2(n,r))),!0}catch{return!1}}async function pce(e,t){let n=await ke(e.paths.pendingRevocationsPath),r=qC(n);if(r.length===0)return n!==null&&await We(e.paths.pendingRevocationsPath,{force:!0}),{attempted:0,completed:0,remaining:0};let i=r.filter(a=>a.baseUrl===t.baseUrl&&a.userId===t.userId),o=r.filter(a=>a.baseUrl!==t.baseUrl||a.userId!==t.userId),s=0;for(let a of i)try{await D({...e,baseUrl:a.baseUrl,apiKey:t.apiKey},"/api/v1/me/session/revoke",{method:"POST",headers:V(t.apiKey),body:JSON.stringify(F2(a))}),s+=1}catch{o.push(a)}return o.length===0?await We(e.paths.pendingRevocationsPath,{force:!0}):await Ve(e.paths.pendingRevocationsPath,VC(o)),{attempted:i.length,completed:s,remaining:o.length}}async function fce(e,t){let n=await ke(e);return n?T2(n,{env:t.env,platform:t.platform,store:t.credentialStore}):null}async function CA(e,t,n){let r=await D2(t,{env:n.env,platform:n.platform,store:n.credentialStore});await Ve(e,r)}async function Ve(e,t){await Zo(Be(e)),await ZP(e,`${JSON.stringify(t,null,2)}
|
|
2298
|
-
`,{encoding:"utf8",mode:384}),await Jo(e,384)}async function Zo(e){await Mo(e,{recursive:!0,mode:448}),await Jo(e,448)}async function Jo(e,t){if(process.platform!=="win32")try{await Qne(e,t)}catch{}}async function LM(e,t){await Mo(Be(e),{recursive:!0}),await ZP(e,t,"utf8")}async function IA(e,t){let n=Be(e);await Mo(n,{recursive:!0});let r=K(n,`.${
|
|
2298
|
+
`,{encoding:"utf8",mode:384}),await Jo(e,384)}async function Zo(e){await Mo(e,{recursive:!0,mode:448}),await Jo(e,448)}async function Jo(e,t){if(process.platform!=="win32")try{await Qne(e,t)}catch{}}async function LM(e,t){await Mo(Be(e),{recursive:!0}),await ZP(e,t,"utf8")}async function IA(e,t){let n=Be(e);await Mo(n,{recursive:!0});let r=K(n,`.${ot(e)}.tmp-${Ge(12).toString("hex")}`),i;try{i=await Uo(r,"wx",384),await i.writeFile(t),await i.sync(),await i.close(),i=void 0,await zo(r,e),await Jo(e,384),await SA(n)}catch(o){throw await i?.close().catch(()=>{}),await We(r,{force:!0}).catch(()=>{}),o}}function mce(e=process.stdin,t=process.stdout,n=BM){return async r=>{if(!e.isTTY||!t.isTTY)throw new Error("Interactive prompt is not available in this environment.");let i=n({input:e,output:t});try{return(await i.question(r)).trim()}finally{i.close()}}}function gce(e=process.stdin,t=process.stdout,n=BM){return async r=>{if(!e.isTTY||!t.isTTY)throw new Error("Interactive secret prompt is not available in this environment.");if(typeof e.setRawMode=="function"&&typeof e.on=="function"&&typeof e.off=="function")return new Promise((o,s)=>{let a=e,l=a.isRaw===!0,c="",u=!1,d=m=>{u||(u=!0,a.off("data",p),a.setRawMode(l),a.pause?.(),t.write(`
|
|
2299
2299
|
`),m())},p=m=>{let h=typeof m=="string"?m:m.toString("utf8");for(let g of h){if(g==="\r"||g===`
|
|
2300
2300
|
`){d(()=>o(c.trim()));return}if(g===""){d(()=>s(new Error("Interactive secret prompt cancelled.")));return}if(g==="\b"||g==="\x7F"){c.length>0&&(c=c.slice(0,-1),t.write("\b \b"));continue}c+=g,t.write("*")}};t.write(r),a.resume?.(),a.on("data",p),a.setRawMode(!0)});let i=n({input:e,output:t,terminal:!0});i.stdoutMuted=!0,i._writeToOutput=function(s){if(!this.stdoutMuted){t.write(s);return}if(s==="\b"||s==="\x7F"){t.write("\b \b");return}if(s!=="\r"&&s!==`
|
|
2301
2301
|
`){let a=[...s].filter(l=>l!=="\r"&&l!==`
|
|
2302
2302
|
`).length;a>0&&t.write("*".repeat(a))}};try{t.write(r);let o=await i.question("");return t.write(`
|
|
2303
|
-
`),o.trim()}finally{i.close()}}}function hce(e=process.stdin,t=process.stdout){return async(n,r)=>{if(r.length===0)throw new Error("Interactive selection has no available options.");if(!e.isTTY||!t.isTTY)throw new Error("Interactive selection is not available in this environment.");return FF(n,r,{input:e,output:t})}}function yce(e){return async t=>{let n=e==="win32"?{file:"rundll32.exe",args:["url.dll,FileProtocolHandler",t]}:e==="darwin"?{file:"open",args:[t]}:{file:"xdg-open",args:[t]};return new Promise(r=>{try{let i=NM(n.file,n.args,{detached:!0,stdio:"ignore"});i.on("error",()=>r(!1)),i.unref(),r(!0)}catch{r(!1)}})}}function Ft(e,t){let n={};for(let r of t){let i=e[r];i!==void 0&&i!==!1&&(r.endsWith("Cents")||r==="rating"?n[r]=Number(i):n[r]=i)}return ie(n)}function vce(e){let t=e.results;return Array.isArray(t)?t.flatMap(n=>{if(!n||typeof n!="object"||Array.isArray(n))return[];let r=f(n,"slug")??f(n,"skillSlug");return r?[r]:[]}):[]}function kce(e){let t=k(e)??"auto";return t==="auto"||t==="required"||t==="optional"||t==="off"?{status:"ok",policy:t}:{status:"invalid",message:"guardian check --cloud-trust-ledger must be one of: auto, required, optional, off."}}function ie(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function ln(e,t){let n=k(e);return n?wce(n,t):void 0}function wce(e,t){try{return JSON.parse(e)}catch{throw new Error(`--${t} must be valid JSON.`)}}function Nt(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t={...e};return delete t.apiKey,delete t[["ad","min","Api","Key"].join("")],t}function WP(e){let t=Nt(e);for(let n of["role","roles","verifiedAt","expiresAt","userId","tenantId","linkedAccount","linkedIdentity","createdUser"])delete t[n];return t}function T(e,t){let n=k(e);if(!n)throw new Error(t);return n}function k(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Re(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function f(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function J(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim().length>0){let r=Number(n);return Number.isFinite(r)?r:void 0}}function j(e,t){let n=e[t];return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Un(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function Fe(e,t){let n=e[t];return Array.isArray(n)?n:void 0}function bce(e){return j(e,"data")??e}function _ce(e){let t=Array.isArray(e)?e:typeof e=="string"?[e]:[];return[...new Set(t.flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean))]}function Ke(e,t,n){let r=k(n);r&&e.set(t,r)}function
|
|
2303
|
+
`),o.trim()}finally{i.close()}}}function hce(e=process.stdin,t=process.stdout){return async(n,r)=>{if(r.length===0)throw new Error("Interactive selection has no available options.");if(!e.isTTY||!t.isTTY)throw new Error("Interactive selection is not available in this environment.");return FF(n,r,{input:e,output:t})}}function yce(e){return async t=>{let n=e==="win32"?{file:"rundll32.exe",args:["url.dll,FileProtocolHandler",t]}:e==="darwin"?{file:"open",args:[t]}:{file:"xdg-open",args:[t]};return new Promise(r=>{try{let i=NM(n.file,n.args,{detached:!0,stdio:"ignore"});i.on("error",()=>r(!1)),i.unref(),r(!0)}catch{r(!1)}})}}function Ft(e,t){let n={};for(let r of t){let i=e[r];i!==void 0&&i!==!1&&(r.endsWith("Cents")||r==="rating"?n[r]=Number(i):n[r]=i)}return ie(n)}function vce(e){let t=e.results;return Array.isArray(t)?t.flatMap(n=>{if(!n||typeof n!="object"||Array.isArray(n))return[];let r=f(n,"slug")??f(n,"skillSlug");return r?[r]:[]}):[]}function kce(e){let t=k(e)??"auto";return t==="auto"||t==="required"||t==="optional"||t==="off"?{status:"ok",policy:t}:{status:"invalid",message:"guardian check --cloud-trust-ledger must be one of: auto, required, optional, off."}}function ie(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function ln(e,t){let n=k(e);return n?wce(n,t):void 0}function wce(e,t){try{return JSON.parse(e)}catch{throw new Error(`--${t} must be valid JSON.`)}}function Nt(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t={...e};return delete t.apiKey,delete t[["ad","min","Api","Key"].join("")],t}function WP(e){let t=Nt(e);for(let n of["role","roles","verifiedAt","expiresAt","userId","tenantId","linkedAccount","linkedIdentity","createdUser"])delete t[n];return t}function T(e,t){let n=k(e);if(!n)throw new Error(t);return n}function k(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Re(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function f(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function J(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim().length>0){let r=Number(n);return Number.isFinite(r)?r:void 0}}function j(e,t){let n=e[t];return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Un(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function Fe(e,t){let n=e[t];return Array.isArray(n)?n:void 0}function bce(e){return j(e,"data")??e}function _ce(e){let t=Array.isArray(e)?e:typeof e=="string"?[e]:[];return[...new Set(t.flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean))]}function Ke(e,t,n){let r=k(n);r&&e.set(t,r)}function Qe(e){let t=e.toString();return t?`?${t}`:""}function dr(e){return e.replace(/\/+$/u,"")}function jM(e){let t=dr(e.trim());try{let n=new URL(t);if(n.protocol==="https:"&&(n.hostname==="staging.findfigg.co.uk"||n.hostname==="api.staging.findfigg.co.uk"))return"https://staging.findfigg.co.uk"}catch{return t}return t}function Yu(e,t){return jM(e)===jM(t)}function Dt(e){if(dr(e)===YP)return"cloud";try{let t=new URL(e);return t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="::1"||t.hostname==="[::1]"?"local":"custom"}catch{return"custom"}}function vz(e){return e.includes("/")||e.startsWith(".")||/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e)}function Tt(e,t){return qo(e,t)}function Fh(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var Sce={github:"GitHub",gitlab:"GitLab",google:"Google",microsoft:"Microsoft"};function kz(e){return Sce[e.toLowerCase()]??Fh(e)}function ve(e){return e instanceof Error?e.message:String(e)}function wz(e,t){let n=[],r=k(t.limit);if(r){let i=Number(r);if(!Number.isInteger(i)||i<1)return"--limit must be a positive whole number; the maximum is 20.";e.set("limit",String(Math.min(20,i))),i>20&&n.push("limit was clamped to 20; the maximum is 20.")}for(let[i,o]of[["cursor","cursor"],["category","category"],["publisher","publisher"],["price","price"],["minimumScore","minimum-score"],["minimumStars","minimum-stars"],["badge","badge"],["sort","sort"],["agent","agent"],["capability","capability"],["trust","trust"],["runtimeRisk","runtime-risk"],["securityCapability","security-capability"]])Ke(e,o,t[i]);return n}export{Iee as PUBLIC_CLI_HELP_AUDIT_CHECK_COUNT,hN as PUBLIC_CLI_HELP_BRANCH_ROUTES,gN as PUBLIC_CLI_HELP_GOAL_ROUTES,Dg as PUBLIC_CLI_HELP_PATH_NAMES,Wne as createCliProgress,nne as createRevealSkipController,oCe as executePublicCli,Aa as prepareCliPresentation,one as writeCliResult};
|