skills-layer 0.1.4 → 0.1.6
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/LICENSE +171 -6
- package/README.md +6 -3
- package/package.json +10 -3
- package/public/skills-layer-public.mjs +364 -82
- package/tests/public-cli-package.test.mjs +44 -4
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/* istanbul ignore file -- generated npm bundle is verified by boundary and tarball smoke tests. */
|
|
2
2
|
import { createRequire as __skillsLayerCreateRequire } from "node:module"; const require = __skillsLayerCreateRequire(import.meta.url);
|
|
3
|
-
import{spawn as ki}from"node:child_process";import{createHash as Dt}from"node:crypto";import{access as wi,appendFile as as,chmod as vi,mkdir as Ne,readdir as bi,readFile as Oe,rm as Ht,stat as ls,writeFile as Jt}from"node:fs/promises";import{basename as K,dirname as X,join as A,posix as zt,relative as Te,resolve as Pi,win32 as Se}from"node:path";import{createInterface as Wt}from"node:readline/promises";import{spawn as bn}from"node:child_process";import{createHash as gr}from"node:crypto";import{chmod as pr,mkdir as Je,readFile as Pn,rm as gt,writeFile as he}from"node:fs/promises";import{dirname as $e,posix as mr,win32 as fr}from"node:path";import{posix as lr,win32 as cr}from"node:path";var ut=["codex","claude-code","cursor","opencode","amp","kimi-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"],mn=[$("codex","Codex",".codex",{capabilities:T({allowedTools:!0})}),$("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:T({allowedTools:!0,hooks:!0,forkedContext:!0})}),$("cursor","Cursor",".cursor",{capabilities:T({allowedTools:!0})}),$("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:T({allowedTools:!0})}),oe("amp","Amp",".config/agents",{capabilities:T({allowedTools:!0})}),oe("kimi-cli","Kimi Code CLI",".config/agents"),oe("replit","Replit",".config/agents"),oe("universal","Universal",".config/agents"),oe("antigravity","Antigravity",".gemini/antigravity",{capabilities:T({allowedTools:!0}),detectGlobal:!0}),$("augment","Augment",".augment"),{id:"openclaw",displayName:"OpenClaw",envVar:"OPENCLAW_HOME",capabilities:T({allowedTools:!0}),targets:{projectRootRelativePath:null,projectSkillsRelativePath:"skills",globalRootRelativePath:".openclaw",globalSkillsRelativePath:".openclaw/skills"},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:[".openclaw",".openclaw/skills"]}},oe("cline","Cline",".agents",{capabilities:T({allowedTools:!0,hooks:!0})}),oe("warp","Warp",".agents"),$("codebuddy","CodeBuddy",".codebuddy",{capabilities:T({allowedTools:!0})}),$("command-code","Command Code",".commandcode",{capabilities:T({allowedTools:!0})}),$("continue","Continue",".continue"),$("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),$("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),oe("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),$("droid","Droid",".factory"),oe("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),oe("github-copilot","GitHub Copilot",".copilot",{capabilities:T({allowedTools:!0}),detectGlobal:!0}),$("goose","Goose",".goose",{globalRootRelativePath:".config/goose"}),$("junie","Junie",".junie"),$("iflow-cli","iFlow CLI",".iflow"),$("kilo","Kilo Code",".kilocode"),$("kiro-cli","Kiro CLI",".kiro"),$("kode","Kode",".kode"),$("mcpjam","MCPJam",".mcpjam"),$("mistral-vibe","Mistral Vibe",".vibe"),$("mux","Mux",".mux"),$("openhands","OpenHands",".openhands",{capabilities:T({allowedTools:!0})}),$("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:T({allowedTools:!0})}),$("qoder","Qoder",".qoder",{capabilities:T({allowedTools:!0})}),$("qwen-code","Qwen Code",".qwen"),$("roo","Roo Code",".roo",{capabilities:T({allowedTools:!0})}),$("trae","Trae",".trae",{detectProject:!1}),$("trae-cn","Trae CN",".trae",{globalRootRelativePath:".trae-cn",detectProject:!1}),$("windsurf","Windsurf",".windsurf",{globalRootRelativePath:".codeium/windsurf"}),$("zencoder","Zencoder",".zencoder",{capabilities:T({allowedTools:!0})}),$("neovate","Neovate",".neovate",{capabilities:T({allowedTools:!0})}),$("pochi","Pochi",".pochi"),$("adal","AdaL",".adal")];function de(e=process.env,t=process.platform,n=process.cwd()){let i=yn(t),r=hn(e,t);return mn.map(s=>{let o=De(e[s.envVar]),a=r&&s.targets.globalRootRelativePath?Ce(i,r,s.targets.globalRootRelativePath):null,c=r&&s.targets.globalSkillsRelativePath?Ce(i,r,s.targets.globalSkillsRelativePath):null,u=s.targets.projectRootRelativePath?Ce(i,n,s.targets.projectRootRelativePath):null,d=o??a;return{id:s.id,displayName:s.displayName,envVar:s.envVar,capabilities:s.capabilities,detectionSources:[],targets:{projectRoot:u,projectSkillsPath:Ce(i,n,s.targets.projectSkillsRelativePath),globalRoot:d,globalSkillsPath:o?i.join(o,"skills"):c}}})}async function fn(e={}){let t=e.env??process.env,n=e.platform??process.platform,i=e.cwd??process.cwd(),r=yn(n),s=hn(t,n),o=de(t,n,i),a=e.pathExists??(async()=>!1);return(await Promise.all(o.map(async c=>{let u=dr(c.id),d=[],p=De(t[c.envVar]);return(p&&await a(p)||p&&await a(r.join(p,"skills")))&&d.push("override"),u.detection.projectProbeRelativePaths.length>0&&await pn({basePath:i,relativePaths:u.detection.projectProbeRelativePaths,pathApi:r,pathExists:a})&&d.push("project"),s&&u.detection.globalProbeRelativePaths.length>0&&await pn({basePath:s,relativePaths:u.detection.globalProbeRelativePaths,pathApi:r,pathExists:a})&&d.push("global"),d.length===0?null:{...c,detectionSources:ur(d)}}))).flatMap(c=>c?[c]:[])}function hn(e,t){return t==="win32"?De(e.USERPROFILE,e.HOME):De(e.HOME)}function yn(e){return e==="win32"?cr:lr}function De(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function ur(e){return[...new Set(e)]}async function pn(e){for(let t of e.relativePaths)if(await e.pathExists(Ce(e.pathApi,e.basePath,t)))return!0;return!1}function Ce(e,t,n){return e.join(t,...n.split("/"))}function $(e,t,n,i={}){let r=i.globalRootRelativePath??n,s=i.detectProject??!0;return{id:e,displayName:t,envVar:i.envVar??kn(e),capabilities:i.capabilities??T(),targets:{projectRootRelativePath:n,projectSkillsRelativePath:`${n}/skills`,globalRootRelativePath:r,globalSkillsRelativePath:`${r}/skills`},detection:{projectProbeRelativePaths:s?[n,`${n}/skills`]:[],globalProbeRelativePaths:[r,`${r}/skills`]}}}function oe(e,t,n,i={}){let r=i.detectGlobal??!1;return{id:e,displayName:t,envVar:i.envVar??kn(e),capabilities:i.capabilities??T(),targets:{projectRootRelativePath:".agents",projectSkillsRelativePath:".agents/skills",globalRootRelativePath:n,globalSkillsRelativePath:`${n}/skills`},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:r?[n,`${n}/skills`]:[]}}}function T(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 kn(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function dr(e){return mn.find(t=>t.id===e)}var pe="skills-layer",hr="2025-06-18",yr=["mcp","skills-layer-mcp-proxy.mjs"],kr=["mcp","skills-layer-mcp-broker.mjs"],wr=["mcp","skills-layer-mcp-broker.sock"],vr={codex:{tier:"tier_1",configKind:"codex_toml",resolveConfigPath(e,t,n){let i=pt(n);return i.join(e.targets.globalRoot??i.join(Er({},n)??t,".codex"),"config.toml")}},cursor:Re(".cursor/mcp.json"),"claude-code":Re(".mcp.json"),cline:Re(".cline/mcp.json"),"gemini-cli":Re(".gemini/settings.json"),windsurf:Re(".windsurf/mcp.json")},br=new Set(["universal"]);function je(e){let t=de(e.env,e.platform,e.cwd),n=new Map(t.map(P=>[P.id,P])),i=e.platform??process.platform,r=e.cwd??process.cwd(),s=e.stateDir??Ir(e.env,i),o=e.mcpConfigPath??xe(i,s,"mcp.json"),a=xe(i,s,...yr),c=xe(i,s,...kr),u=xe(i,s,...wr),d=e.nodePath??process.execPath,p=Cn({mcpConfigPath:o}),y=Rn({mcpConfigPath:o,socketPath:u}),m=ye(p),h=ye(y),w=ut.map(P=>{let x=n.get(P),B=vr[P];if(B){let Ge=B.resolveConfigPath(x,r,i);return Pr({agentId:P,displayName:x.displayName,configPath:Ge,configKind:B.configKind,bridgePath:a,brokerPath:c,brokerSocketPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:m,brokerChecksum:h})}return br.has(P)?vn({agentId:P,displayName:x.displayName,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 ${x.displayName} with \`skills-layer install <skill> --agent ${P}\`.`,"MCP auto-install is not claimed for this agent yet."]}):vn({agentId:P,displayName:x.displayName,tier:"tier_2",status:"manual_handoff",verification:"manual",reason:"MCP support or the safe writable config shape has not been verified yet.",instructions:[`Add a local stdio MCP server named ${pe}.`,`Command: ${d}`,`Args: ${a}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{status:"mcp_registration_plan",serverName:pe,mcpUrl:e.mcpUrl,bearerTokenEnvVar:e.bearerTokenEnvVar,clientId:e.clientId,environment:e.environment,generatedAt:e.now,bridgePath:a,brokerPath:c,brokerSocketPath:u,nodePath:d,mcpConfigPath:o,bridgeChecksum:m,brokerChecksum:h,automaticCount:w.filter(P=>P.status==="automatic").length,manualCount:w.filter(P=>P.status==="manual_handoff").length,skillsOnlyCount:w.filter(P=>P.status==="skills_only").length,unsupportedCount:w.filter(P=>P.status==="unsupported").length,targets:w}}async function Sn(e){let t=je(e),n=Lr(e.clientId),i=t.targets.find(w=>w.agentId===n),r=e.mcpConfig??await ze(t.mcpConfigPath,{allowMissing:!0});if(!r)return wn({plan:t,target:i,mcpConfig:null,tokenConfig:null,tokenPresent:!1,tokenRefPresent:!1,bridgeExists:!1,checksumMatches:!1,brokerExists:!1,brokerChecksumMatches:!1,targetConfigured:!1,rawTokenLeaked:!1});let s=await _e(t.bridgePath),o=s!==null,a=s!==null&&ye(s)===t.bridgeChecksum,c=await _e(t.brokerPath),u=c!==null,d=c!==null&&ye(c)===t.brokerChecksum,p=Tr(r,i.agentId),y=te(p,"token"),m=te(p,"tokenRef"),h=i.status==="automatic"?await $r(i,y):{configured:!1,rawTokenLeaked:!1};return wn({plan:t,target:i,mcpConfig:r,tokenConfig:p,tokenPresent:!!y,tokenRefPresent:!!m,bridgeExists:o,checksumMatches:a,brokerExists:u,brokerChecksumMatches:d,targetConfigured:h.configured,rawTokenLeaked:h.rawTokenLeaked})}function Cn(e){return`#!/usr/bin/env node
|
|
3
|
+
import{spawn as Wi}from"node:child_process";import{createHash as cn}from"node:crypto";import{access as Ji,appendFile as io,chmod as Yi,mkdir as Ke,readdir as Zi,readFile as Ge,rm as un,stat as ro,writeFile as dn}from"node:fs/promises";import{basename as K,dirname as ee,join as L,posix as pn,relative as Fe,resolve as Qi,win32 as _e}from"node:path";import{createInterface as gn}from"node:readline/promises";import{spawn as qn}from"node:child_process";import{createHash as Zr}from"node:crypto";import{chmod as Qr,mkdir as Je,readFile as Kn,rm as St,writeFile as ve}from"node:fs/promises";import{dirname as Ae,posix as Xr,win32 as es}from"node:path";import{posix as zr,win32 as Wr}from"node:path";var be=["codex","claude-code","cursor","opencode","amp","kimi-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"],Un=[j("codex","Codex",".codex",{capabilities:B({allowedTools:!0})}),j("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:B({allowedTools:!0,hooks:!0,forkedContext:!0})}),j("cursor","Cursor",".cursor",{capabilities:B({allowedTools:!0})}),j("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:B({allowedTools:!0})}),ce("amp","Amp",".config/agents",{capabilities:B({allowedTools:!0})}),ce("kimi-cli","Kimi Code CLI",".config/agents"),ce("replit","Replit",".config/agents"),ce("universal","Universal",".config/agents"),ce("antigravity","Antigravity",".gemini/antigravity",{capabilities:B({allowedTools:!0}),detectGlobal:!0}),j("augment","Augment",".augment"),{id:"openclaw",displayName:"OpenClaw",envVar:"OPENCLAW_HOME",capabilities:B({allowedTools:!0}),targets:{projectRootRelativePath:null,projectSkillsRelativePath:"skills",globalRootRelativePath:".openclaw",globalSkillsRelativePath:".openclaw/skills"},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:[".openclaw",".openclaw/skills"]}},ce("cline","Cline",".agents",{capabilities:B({allowedTools:!0,hooks:!0})}),ce("warp","Warp",".agents"),j("codebuddy","CodeBuddy",".codebuddy",{capabilities:B({allowedTools:!0})}),j("command-code","Command Code",".commandcode",{capabilities:B({allowedTools:!0})}),j("continue","Continue",".continue"),j("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),j("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),ce("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),j("droid","Droid",".factory"),ce("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),ce("github-copilot","GitHub Copilot",".copilot",{capabilities:B({allowedTools:!0}),detectGlobal:!0}),j("goose","Goose",".goose",{globalRootRelativePath:".config/goose"}),j("junie","Junie",".junie"),j("iflow-cli","iFlow CLI",".iflow"),j("kilo","Kilo Code",".kilocode"),j("kiro-cli","Kiro CLI",".kiro"),j("kode","Kode",".kode"),j("mcpjam","MCPJam",".mcpjam"),j("mistral-vibe","Mistral Vibe",".vibe"),j("mux","Mux",".mux"),j("openhands","OpenHands",".openhands",{capabilities:B({allowedTools:!0})}),j("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:B({allowedTools:!0})}),j("qoder","Qoder",".qoder",{capabilities:B({allowedTools:!0})}),j("qwen-code","Qwen Code",".qwen"),j("roo","Roo Code",".roo",{capabilities:B({allowedTools:!0})}),j("trae","Trae",".trae",{detectProject:!1}),j("trae-cn","Trae CN",".trae",{globalRootRelativePath:".trae-cn",detectProject:!1}),j("windsurf","Windsurf",".windsurf",{globalRootRelativePath:".codeium/windsurf"}),j("zencoder","Zencoder",".zencoder",{capabilities:B({allowedTools:!0})}),j("neovate","Neovate",".neovate",{capabilities:B({allowedTools:!0})}),j("pochi","Pochi",".pochi"),j("adal","AdaL",".adal")];function me(e=process.env,t=process.platform,n=process.cwd()){let i=Nn(t),r=Bn(e,t);return Un.map(s=>{let o=ze(e[s.envVar]),a=r&&s.targets.globalRootRelativePath?$e(i,r,s.targets.globalRootRelativePath):null,c=r&&s.targets.globalSkillsRelativePath?$e(i,r,s.targets.globalSkillsRelativePath):null,u=s.targets.projectRootRelativePath?$e(i,n,s.targets.projectRootRelativePath):null,d=o??a;return{id:s.id,displayName:s.displayName,envVar:s.envVar,capabilities:s.capabilities,detectionSources:[],targets:{projectRoot:u,projectSkillsPath:$e(i,n,s.targets.projectSkillsRelativePath),globalRoot:d,globalSkillsPath:o?i.join(o,"skills"):c}}})}async function Tn(e={}){let t=e.env??process.env,n=e.platform??process.platform,i=e.cwd??process.cwd(),r=Nn(n),s=Bn(t,n),o=me(t,n,i),a=e.pathExists??(async()=>!1);return(await Promise.all(o.map(async c=>{let u=Yr(c.id),d=[],g=ze(t[c.envVar]);return(g&&await a(g)||g&&await a(r.join(g,"skills")))&&d.push("override"),u.detection.projectProbeRelativePaths.length>0&&await En({basePath:i,relativePaths:u.detection.projectProbeRelativePaths,pathApi:r,pathExists:a})&&d.push("project"),s&&u.detection.globalProbeRelativePaths.length>0&&await En({basePath:s,relativePaths:u.detection.globalProbeRelativePaths,pathApi:r,pathExists:a})&&d.push("global"),d.length===0?null:{...c,detectionSources:Jr(d)}}))).flatMap(c=>c?[c]:[])}function Bn(e,t){return t==="win32"?ze(e.USERPROFILE,e.HOME):ze(e.HOME)}function Nn(e){return e==="win32"?Wr:zr}function ze(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Jr(e){return[...new Set(e)]}async function En(e){for(let t of e.relativePaths)if(await e.pathExists($e(e.pathApi,e.basePath,t)))return!0;return!1}function $e(e,t,n){return e.join(t,...n.split("/"))}function j(e,t,n,i={}){let r=i.globalRootRelativePath??n,s=i.detectProject??!0;return{id:e,displayName:t,envVar:i.envVar??Mn(e),capabilities:i.capabilities??B(),targets:{projectRootRelativePath:n,projectSkillsRelativePath:`${n}/skills`,globalRootRelativePath:r,globalSkillsRelativePath:`${r}/skills`},detection:{projectProbeRelativePaths:s?[n,`${n}/skills`]:[],globalProbeRelativePaths:[r,`${r}/skills`]}}}function ce(e,t,n,i={}){let r=i.detectGlobal??!1;return{id:e,displayName:t,envVar:i.envVar??Mn(e),capabilities:i.capabilities??B(),targets:{projectRootRelativePath:".agents",projectSkillsRelativePath:".agents/skills",globalRootRelativePath:n,globalSkillsRelativePath:`${n}/skills`},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:r?[n,`${n}/skills`]:[]}}}function B(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 Mn(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function Yr(e){return Un.find(t=>t.id===e)}var he="skills-layer",ts="2025-06-18",ns=["mcp","skills-layer-mcp-proxy.mjs"],is=["mcp","skills-layer-mcp-broker.mjs"],rs=["mcp","skills-layer-mcp-broker.sock"],ss={codex:{tier:"tier_1",configKind:"codex_toml",resolveConfigPath(e,t,n){let i=Ct(n);return i.join(e.targets.globalRoot??i.join(ys({},n)??t,".codex"),"config.toml")}},cursor:Ie(".cursor/mcp.json"),"claude-code":Ie(".mcp.json"),cline:Ie(".cline/mcp.json"),"gemini-cli":Ie(".gemini/settings.json"),windsurf:Ie(".windsurf/mcp.json")},os=new Set(["universal"]);function Ee(e){let t=me(e.env,e.platform,e.cwd),n=new Map(t.map(C=>[C.id,C])),i=e.platform??process.platform,r=e.cwd??process.cwd(),s=e.stateDir??hs(e.env,i),o=e.mcpConfigPath??je(i,s,"mcp.json"),a=je(i,s,...ns),c=je(i,s,...is),u=je(i,s,...rs),d=e.nodePath??process.execPath,g=Gn({mcpConfigPath:o}),f=Vn({mcpConfigPath:o,socketPath:u}),m=Se(g),k=Se(f),w=be.map(C=>{let x=n.get(C),E=ss[C];if(E){let le=E.resolveConfigPath(x,r,i);return as({agentId:C,displayName:x.displayName,configPath:le,configKind:E.configKind,bridgePath:a,brokerPath:c,brokerSocketPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:m,brokerChecksum:k})}return os.has(C)?On({agentId:C,displayName:x.displayName,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 ${x.displayName} with \`skills-layer install <skill> --agent ${C}\`.`,"MCP auto-install is not claimed for this agent yet."]}):On({agentId:C,displayName:x.displayName,tier:"tier_2",status:"manual_handoff",verification:"manual",reason:"MCP support or the safe writable config shape has not been verified yet.",instructions:[`Add a local stdio MCP server named ${he}.`,`Command: ${d}`,`Args: ${a}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{status:"mcp_registration_plan",serverName:he,mcpUrl:e.mcpUrl,bearerTokenEnvVar:e.bearerTokenEnvVar,clientId:e.clientId,environment:e.environment,generatedAt:e.now,bridgePath:a,brokerPath:c,brokerSocketPath:u,nodePath:d,mcpConfigPath:o,bridgeChecksum:m,brokerChecksum:k,automaticCount:w.filter(C=>C.status==="automatic").length,manualCount:w.filter(C=>C.status==="manual_handoff").length,skillsOnlyCount:w.filter(C=>C.status==="skills_only").length,unsupportedCount:w.filter(C=>C.status==="unsupported").length,targets:w}}async function Pt(e){let t=Ee(e),n=ks(e.clientId),i=t.targets.find(w=>w.agentId===n),r=e.mcpConfig??await Ye(t.mcpConfigPath,{allowMissing:!0});if(!r)return Fn({plan:t,target:i,mcpConfig:null,tokenConfig:null,tokenPresent:!1,tokenRefPresent:!1,bridgeExists:!1,checksumMatches:!1,brokerExists:!1,brokerChecksumMatches:!1,targetConfigured:!1,rawTokenLeaked:!1});let s=await Le(t.bridgePath),o=s!==null,a=s!==null&&Se(s)===t.bridgeChecksum,c=await Le(t.brokerPath),u=c!==null,d=c!==null&&Se(c)===t.brokerChecksum,g=ws(r,i.agentId),f=ne(g,"token"),m=ne(g,"tokenRef"),k=i.status==="automatic"?await ps(i,f):{configured:!1,rawTokenLeaked:!1};return Fn({plan:t,target:i,mcpConfig:r,tokenConfig:g,tokenPresent:!!f,tokenRefPresent:!!m,bridgeExists:o,checksumMatches:a,brokerExists:u,brokerChecksumMatches:d,targetConfigured:k.configured,rawTokenLeaked:k.rawTokenLeaked})}function Gn(e){return`#!/usr/bin/env node
|
|
4
4
|
import { createConnection } from "node:net";
|
|
5
5
|
import { createInterface } from "node:readline";
|
|
6
6
|
import { readFile } from "node:fs/promises";
|
|
7
7
|
|
|
8
8
|
const CONFIG_PATH = ${JSON.stringify(e.mcpConfigPath)};
|
|
9
|
-
const MCP_PROTOCOL_VERSION = ${JSON.stringify(
|
|
9
|
+
const MCP_PROTOCOL_VERSION = ${JSON.stringify(ts)};
|
|
10
10
|
|
|
11
11
|
function writeMessage(message) {
|
|
12
12
|
process.stdout.write(JSON.stringify(message) + "\\n");
|
|
@@ -148,7 +148,7 @@ for await (const line of rl) {
|
|
|
148
148
|
writeMessage(errorResponse(null, -32603, error instanceof Error ? error.message : "Skills Layer MCP bridge failed."));
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
|
-
`}function
|
|
151
|
+
`}function Vn(e){return`#!/usr/bin/env node
|
|
152
152
|
import { execFile } from "node:child_process";
|
|
153
153
|
import { createServer } from "node:net";
|
|
154
154
|
import { chmod, readFile, rm } from "node:fs/promises";
|
|
@@ -244,15 +244,15 @@ server.listen(SOCKET_PATH, async () => {
|
|
|
244
244
|
// Some platforms do not support chmod on sockets.
|
|
245
245
|
}
|
|
246
246
|
});
|
|
247
|
-
`}async function
|
|
248
|
-
`);let c=await Promise.race([s,a]);if(clearTimeout(o),i.kill(),c==="timeout")return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!1,toolCount:null,reasonCode:"probe_timeout",message:"MCP bridge did not respond before the verification timeout."};if(!c.ok)return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!1,toolCount:null,reasonCode:"probe_failed",message:r.trim()?"MCP bridge failed before returning a response.":c.message};try{let u=JSON.parse(c.line);if(
|
|
249
|
-
`,"utf8")}async function
|
|
250
|
-
`,"utf8")}async function
|
|
251
|
-
`),i=`${
|
|
252
|
-
|
|
253
|
-
`:""}${n}`;await Je(
|
|
254
|
-
`).trimEnd()}function
|
|
255
|
-
`);r>=0&&t({ok:!0,line:n.slice(0,r)})}),e.on("error",i=>{t({ok:!1,message:i instanceof Error?i.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
|
|
247
|
+
`}async function Dn(e){let t=e.requestId??1,n=e.timeoutMs??5e3,i=qn(e.nodePath,[e.bridgePath],{stdio:["pipe","pipe","pipe"]}),r="",s=fs(i.stdout);i.stderr.on("data",u=>{r+=String(u)});let o,a=new Promise(u=>{o=setTimeout(()=>u("timeout"),n)});i.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:t,method:"tools/list",params:{}})}
|
|
248
|
+
`);let c=await Promise.race([s,a]);if(clearTimeout(o),i.kill(),c==="timeout")return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!1,toolCount:null,reasonCode:"probe_timeout",message:"MCP bridge did not respond before the verification timeout."};if(!c.ok)return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!1,toolCount:null,reasonCode:"probe_failed",message:r.trim()?"MCP bridge failed before returning a response.":c.message};try{let u=JSON.parse(c.line);if(Q(u)&&Q(u.error))return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!0,toolCount:null,reasonCode:"remote_mcp_error",message:ne(u.error,"message")??"Skills Layer MCP returned an error."};let d=Q(u)&&Q(u.result)&&Array.isArray(u.result.tools)?u.result.tools:null;return{status:"ok",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!0,toolCount:d?d.length:null,reasonCode:null,message:d?`MCP bridge responded with ${d.length} tool${d.length===1?"":"s"}.`:"MCP bridge responded."}}catch{return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!0,toolCount:null,reasonCode:"invalid_probe_response",message:"MCP bridge returned a response that was not valid JSON."}}}function Fn(e){let t=e.target.status==="automatic",n=e.tokenRefPresent&&!e.tokenPresent,i=!n||e.brokerExists&&e.brokerChecksumMatches,r=(e.tokenPresent||e.tokenRefPresent)&&e.bridgeExists&&e.checksumMatches&&i&&t&&e.targetConfigured&&!e.rawTokenLeaked,s=r?"mcp_configured":e.mcpConfig?"mcp_needs_repair":"mcp_not_configured",o=`skills-layer mcp verify --client ${e.target.agentId}`;return{status:s,configured:r,clientId:e.target.agentId,environment:ne(e.tokenConfig,"environment")??ne(e.mcpConfig,"environment")??e.plan.environment,baseUrl:ne(e.mcpConfig,"baseUrl"),mcpUrl:ne(e.mcpConfig,"mcpUrl"),tokenPrefix:ne(e.tokenConfig,"tokenPrefix")??ne(e.mcpConfig,"tokenPrefix"),scopes:Array.isArray(e.tokenConfig?.scopes)?e.tokenConfig.scopes:Array.isArray(e.mcpConfig?.scopes)?e.mcpConfig.scopes:[],configuredClients:bs(e.mcpConfig),tokenPresent:e.tokenPresent||e.tokenRefPresent,tokenStorage:ne(e.tokenConfig,"credentialStorage")==="macos_keychain"?"macos_keychain":e.tokenPresent?"local_file_locked":"unknown",bridge:{path:e.plan.bridgePath,exists:e.bridgeExists,checksumMatches:e.checksumMatches},broker:{path:e.plan.brokerPath,socketPath:e.plan.brokerSocketPath,required:n,exists:e.brokerExists,checksumMatches:e.brokerChecksumMatches},target:{agentId:e.target.agentId,displayName:e.target.displayName,tier:e.target.tier,status:e.target.status,configPath:e.target.configPath,configured:e.targetConfigured,rawTokenLeaked:e.rawTokenLeaked,reason:e.target.reason,restartRequired:e.target.restartRequired,instructions:e.target.instructions},liveProbe:{status:"not_run",method:"tools/list",reasonCode:"use_mcp_verify",message:`Live MCP tools/list was not run by status. Run \`${o}\` to verify remote MCP reachability through the local bridge.`,nextCommand:o},nextCommand:r?null:`skills-layer mcp repair --client ${e.target.agentId}`}}function as(e){return{agentId:e.agentId,displayName:e.displayName,tier:"tier_1",status:"automatic",serverName:he,configPath:e.configPath,restartRequired:!0,verification:"bridge_config_written",transport:"stdio_bridge",bridgePath:e.bridgePath,nodePath:e.nodePath,configKind:e.configKind,reason:"MCP support and a safe local config shape are known.",instructions:[`Skills Layer will install the local MCP bridge at ${e.bridgePath}.`,`Skills Layer will update ${e.configPath} to launch the bridge with ${e.nodePath}.`,"The raw MCP token stays in Skills Layer local storage and is not written to the agent config.","Open a fresh agent session or restart the agent to load the MCP server."],apply:async()=>{let t=await ls({bridgePath:e.bridgePath,brokerPath:e.brokerPath,brokerSocketPath:e.brokerSocketPath,mcpConfigPath:e.mcpConfigPath,nodePath:e.nodePath});return await us({configPath:e.configPath,configKind:e.configKind,bridgePath:e.bridgePath,nodePath:e.nodePath,agentId:e.agentId}),t},disconnect:async()=>{await ds({configPath:e.configPath,configKind:e.configKind})}}}function On(e){return{agentId:e.agentId,displayName:e.displayName,tier:e.tier,status:e.status,serverName:he,configPath:null,restartRequired:!0,verification:e.verification,transport:"manual",bridgePath:null,nodePath:null,configKind:null,reason:e.reason,instructions:e.instructions}}async function ls(e){let t=Gn({mcpConfigPath:e.mcpConfigPath}),n=Vn({mcpConfigPath:e.mcpConfigPath,socketPath:e.brokerSocketPath});return await Je(Ae(e.bridgePath),{recursive:!0}),await ve(e.bridgePath,t,"utf8"),await ve(e.brokerPath,n,"utf8"),await vt(Ae(e.bridgePath),448),await vt(e.bridgePath,448),await vt(e.brokerPath,448),cs({nodePath:e.nodePath,brokerPath:e.brokerPath}),{bridgePath:e.bridgePath,brokerPath:e.brokerPath,brokerSocketPath:e.brokerSocketPath,mcpConfigPath:e.mcpConfigPath,checksum:Se(t),brokerChecksum:Se(n),nodePath:e.nodePath}}function cs(e){if(!(process.env.VITEST==="true"||process.env.SKILLS_LAYER_MCP_BROKER_AUTOSTART==="disabled"))try{qn(e.nodePath,[e.brokerPath],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function us(e){if(e.configKind==="codex_toml"){await ms(e);return}await gs(e)}async function ds(e){if(e.configKind==="codex_toml"){let i=await Le(e.configPath);if(i===null)return;await ve(e.configPath,Hn(i),"utf8");return}let t=await Ye(e.configPath,{allowMissing:!0});if(!t||!Q(t.mcpServers))return;let n={...t.mcpServers};delete n[he],await Je(Ae(e.configPath),{recursive:!0}),await ve(e.configPath,`${JSON.stringify({...t,mcpServers:n},null,2)}
|
|
249
|
+
`,"utf8")}async function ps(e,t){if(!e.configPath||!e.configKind||!e.bridgePath||!e.nodePath)return{configured:!1,rawTokenLeaked:!1};if(e.configKind==="codex_toml"){let s=await Le(e.configPath);return s===null?{configured:!1,rawTokenLeaked:!1}:{configured:s.includes("[mcp_servers.skills-layer]")&&s.includes(`command = ${JSON.stringify(e.nodePath)}`)&&(s.includes(`args = [${JSON.stringify(e.bridgePath)}, "--client", ${JSON.stringify(e.agentId)}]`)||s.includes(`args = [${JSON.stringify(e.bridgePath)}]`)),rawTokenLeaked:!!(t&&s.includes(t))}}let n=await Ye(e.configPath,{allowMissing:!0}),i=Q(n?.mcpServers)?n.mcpServers[he]:void 0;return{configured:Q(i)&&i.command===e.nodePath&&Array.isArray(i.args)&&i.args[0]===e.bridgePath&&(i.args.length===1||i.args[1]==="--client"&&i.args[2]===e.agentId),rawTokenLeaked:!!(t&&JSON.stringify(n??{}).includes(t))}}async function gs(e){let t=await Ye(e.configPath,{allowMissing:!0})??{},n=Q(t.mcpServers)?{...t.mcpServers}:{};n[he]={command:e.nodePath,args:[e.bridgePath,"--client",e.agentId]},await Je(Ae(e.configPath),{recursive:!0}),await ve(e.configPath,`${JSON.stringify({...t,mcpServers:n},null,2)}
|
|
250
|
+
`,"utf8")}async function ms(e){let t=await Le(e.configPath)??"",n=["[mcp_servers.skills-layer]",`command = ${JSON.stringify(e.nodePath)}`,`args = [${JSON.stringify(e.bridgePath)}, "--client", ${JSON.stringify(e.agentId)}]`,""].join(`
|
|
251
|
+
`),i=`${Hn(t).trimEnd()}${t.trim().length>0?`
|
|
252
|
+
|
|
253
|
+
`:""}${n}`;await Je(Ae(e.configPath),{recursive:!0}),await ve(e.configPath,i,"utf8")}function Hn(e){let t=e.split(/\r?\n/u),n=[],i=!1;for(let r of t){if(r.trim()==="[mcp_servers.skills-layer]"){i=!0;continue}i&&/^\s*\[.+\]\s*$/u.test(r)&&(i=!1),i||n.push(r)}return n.join(`
|
|
254
|
+
`).trimEnd()}function Ie(e){return{tier:"tier_1",configKind:"json_mcp_servers",resolveConfigPath(t,n,i){return je(i,n,...e.split("/"))}}}async function Ye(e,t){try{let n=JSON.parse(await Kn(e,"utf8"));return Q(n)?n:{}}catch(n){if(t.allowMissing&&n.code==="ENOENT")return null;throw n}}async function Le(e){try{return await Kn(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function vt(e,t){try{await Qr(e,t)}catch{}}async function zn(e){await St(e,{force:!0})}async function Wn(e,t){await Promise.all([St(e,{force:!0}),St(t,{force:!0})])}function fs(e){return e?new Promise(t=>{let n="";e.on("data",i=>{n+=String(i);let r=n.indexOf(`
|
|
255
|
+
`);r>=0&&t({ok:!0,line:n.slice(0,r)})}),e.on("error",i=>{t({ok:!1,message:i instanceof Error?i.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 hs(e,t){let n=Ct(t),i=e??process.env,r=t==="win32"?We(i.APPDATA,i.USERPROFILE,i.HOME):We(i.XDG_CONFIG_HOME,i.HOME?n.join(i.HOME,".skills-layer"):void 0);return r?t==="win32"||i.XDG_CONFIG_HOME?.trim()?n.join(r,"skills-layer"):r:n.join(process.cwd(),".skills-layer")}function ys(e,t){return t==="win32"?We(e.USERPROFILE,e.HOME):We(e.HOME)}function ks(e){return be.includes(e)?e:"codex"}function ws(e,t){let n=e.tokens;return Q(n)&&Q(n[t])?n[t]:e}function bs(e){if(!e)return[];let t=e.clientIds;if(Array.isArray(t))return t.filter(r=>typeof r=="string"&&r.trim().length>0);let n=e.tokens;if(Q(n))return Object.keys(n);let i=ne(e,"clientId");return i?[i]:[]}function je(e,...t){return Ct(e).join(...t)}function Ct(e){return e==="win32"?es:Xr}function We(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function ne(e,t){let n=e?.[t];return typeof n=="string"&&n.trim().length>0?n:null}function Se(e){return Zr("sha256").update(e).digest("hex")}function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vs(e){let t=Ss(e);if(t)return t;let n=Ps(e);if(n)return n;throw new Error("Unsupported bundle archive format")}function Jn(e){try{return vs(e)}catch{return null}}function Ss(e){if(e.byteLength<4)return null;let t=new TextDecoder,n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=[],r=0,s=!1;for(;r+4<=e.byteLength;){let o=n.getUint32(r,!0);if(o===67324752){if(s=!0,r+30>e.byteLength)throw new Error("ZIP local header is truncated");let a=n.getUint16(r+8,!0),c=n.getUint32(r+18,!0),u=n.getUint16(r+26,!0),d=n.getUint16(r+28,!0),g=r+30,f=g+u+d,m=f+c;if(a!==0)throw new Error("Only stored ZIP entries are supported");if(m>e.byteLength)throw new Error("ZIP entry data is truncated");i.push({path:t.decode(e.slice(g,g+u)),content:t.decode(e.slice(f,m))}),r=m;continue}return o===33639248||o===101010256?s?i:null:s?(()=>{throw new Error("Unexpected ZIP signature")})():null}return i}function Ps(e){try{let t=JSON.parse(new TextDecoder().decode(e));return t.format!=="skills-layer-external-bundle-v1"||!Array.isArray(t.files)?null:t.files.filter(n=>typeof n.path=="string").map(n=>({path:n.path,...typeof n.content=="string"?{content:n.content}:{}}))}catch{return null}}import{createHash as Cs}from"node:crypto";function Yn(e){let t=Cs("sha256");for(let n of e)t.update(n.path),t.update("\0"),t.update(n.content??""),t.update("\0");return t.digest("hex")}var xt=["productivity","coding","review","testing","devops","data","documents","media","research","planning","design","security","business","education","automation","communication","email","customer-support","sales","marketing","finance","legal","operations","project-management","writing","translation","knowledge-management","hr","ai","ecommerce"],xs="productivity",Rs=new Set(xt),_s={ci:"devops","ci-cd":"devops",compliance:"security",content:"documents",crm:"customer-support",docs:"documents",frontend:"coding","customer-service":"customer-support","customer-success":"customer-support","e-commerce":"ecommerce",genai:"ai",legal:"legal",llm:"ai",ops:"operations",pm:"project-management",reporting:"business",reports:"business","team-ops":"operations",ui:"design",ux:"design","web-development":"coding"},$s={productivity:["productivity","todo","task","tasks","calendar","meeting","notes","workflow","focus"],coding:["code","coding","developer","frontend","backend","repository","typescript","javascript","react","vite","html","css","component","bundle","artifact"],review:["review","reviews","critique","audit","feedback","pr","pull","quality"],testing:["test","tests","testing","qa","coverage","regression","playwright","vitest"],devops:["deploy","deployment","ci","cd","pipeline","infra","infrastructure","docker","cloudflare","wrangler"],data:["data","dataset","sql","database","analytics","metrics","spreadsheet","csv","json"],documents:["document","documents","doc","docs","pdf","report","reports","contract","proposal","writing"],media:["media","image","video","audio","transcript","youtube","asset","thumbnail"],research:["research","search","sources","citation","citations","summarize","summaries","literature"],planning:["plan","planning","project","roadmap","milestone","sprint","delivery","schedule"],design:["design","ui","ux","layout","wireframe","prototype","figma","tailwind","shadcn"],security:["security","threat","secret","secrets","vulnerability","vulnerabilities","risk","policy"],business:["business","strategy","customer","market","stakeholder","commercial","pricing"],education:["education","teach","teaching","learn","learning","lesson","course","tutorial"],automation:["automation","automate","workflow","script","scripts","bot","trigger","orchestration"],communication:["communication","slack","message","messages","chat","reply","announcement","conversation"],email:["email","emails","gmail","googleemail","googlemail","outlook","inbox","mail","newsletter"],"customer-support":["support","ticket","tickets","helpdesk","customer","service","csat","escalation"],sales:["sales","lead","leads","prospect","pipeline","deal","deals","crm","account"],marketing:["marketing","campaign","brand","seo","content","social","audience","copy"],finance:["finance","financial","invoice","invoices","budget","forecast","accounting","revenue","tax"],legal:["legal","contract","contracts","clause","clauses","compliance","policy","terms","privacy"],operations:["operations","ops","runbook","process","sop","incident","queue","handoff"],"project-management":["project","projects","backlog","dependency","dependencies","kanban","scrum","pm"],writing:["writing","write","draft","edit","editing","blog","article","copywriting"],translation:["translation","translate","localization","locale","language","languages","i18n"],"knowledge-management":["knowledge","wiki","kb","retrieval","archive","taxonomy","knowledgebase"],hr:["hr","hiring","recruiting","interview","onboarding","employee","people","performance"],ai:["ai","llm","prompt","prompts","model","models","agent","agents","rag","embedding"],ecommerce:["ecommerce","commerce","shop","store","checkout","cart","order","orders","product"]};function Zn(e){if(typeof e!="string")return null;let t=ei(e);return Rs.has(t)?t:_s[t]??null}function Qn(e){let t=e.trim().toLowerCase().replace(/[_\s]+/gu,"-"),n={ai:"AI",hr:"HR",ecommerce:"E-commerce","e-commerce":"E-commerce"};return n[t]?n[t]:e.split(/[-_\s]+/u).filter(Boolean).map(i=>`${i.slice(0,1).toUpperCase()}${i.slice(1)}`).join(" ")}function Xn(e){let t=[{value:e.slug??"",weight:3,signal:"slug"},{value:e.name??"",weight:3,signal:"name"},{value:e.description??"",weight:2,signal:"description"},{value:e.skillType??"",weight:1,signal:"skill_type"},{value:e.compatibility??"",weight:1,signal:"compatibility"},{value:(e.tags??[]).join(" "),weight:4,signal:"tags"},{value:e.body??"",weight:1,signal:"body"}].filter(s=>s.value.trim().length>0),n=new Map;for(let s of t){let o=js(s.value);for(let[a,c]of Object.entries($s)){if(!c.some(g=>o.has(g)))continue;let d=n.get(a)??{score:0,signals:new Set};d.score+=s.weight,d.signals.add(s.signal),n.set(a,d)}}let r=[...n.entries()].sort((s,o)=>o[1].score-s[1].score||xt.indexOf(s[0])-xt.indexOf(o[0]))[0];return!r||r[1].score<2?{category:Is(e),confidence:"fallback",matchedSignals:[]}:{category:r[0],confidence:r[1].score>=5?"high":r[1].score>=3?"medium":"low",matchedSignals:[...r[1].signals].sort()}}function Is(e){let t=ei(e.skillType??"");return t.includes("automation")?"automation":t.includes("mcp")?"ai":xs}function ei(e){return e.trim().toLowerCase().replace(/[_\s]+/gu,"-")}function js(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/u).map(t=>t.trim()).filter(t=>t.length>=2).flatMap(As))}function As(e){let t=[e];return e.endsWith("ing")&&e.length>5&&t.push(e.slice(0,-3)),e.endsWith("s")&&e.length>4&&t.push(e.slice(0,-1)),t}var Ls=["standalone","workflow_automation","mcp_enhanced"];function ti(e){let t=e?.trim();if(!t)return"standalone";if(t==="workflow")return"workflow_automation";if(!Ls.includes(t))throw new Error(`Unsupported skill type "${t}". Supported types: standalone, workflow, workflow_automation, mcp_enhanced.`);return t}function ni(e){return[{path:"SKILL.md",content:Es(e)},{path:"README.md",content:Us(e)},{path:"references/guide.md",content:Bs(e)},{path:"scripts/README.md",content:Ts(e)}]}function Es(e){let t=Ns(e);return`---
|
|
256
256
|
name: ${e.skillSlug}
|
|
257
257
|
description: ${e.description}
|
|
258
258
|
compatibility: Codex, Claude Code
|
|
@@ -267,7 +267,7 @@ metadata:
|
|
|
267
267
|
- model_context
|
|
268
268
|
- filesystem_read
|
|
269
269
|
---
|
|
270
|
-
# ${
|
|
270
|
+
# ${Rt(e.skillSlug)}
|
|
271
271
|
|
|
272
272
|
Use this skill when the user needs ${e.description.toLowerCase()}
|
|
273
273
|
|
|
@@ -280,7 +280,7 @@ Use this skill when the user needs ${e.description.toLowerCase()}
|
|
|
280
280
|
|
|
281
281
|
- If the skill does not trigger, make the user request more explicit and mention the task directly.
|
|
282
282
|
- Move deeper procedures into [references/guide.md](references/guide.md) to keep this file concise.
|
|
283
|
-
`}function
|
|
283
|
+
`}function Us(e){return`# ${Rt(e.skillSlug)}
|
|
284
284
|
|
|
285
285
|
This scaffold was created for a ${e.skillType.replaceAll("_"," ")} skill.
|
|
286
286
|
|
|
@@ -303,12 +303,12 @@ Current summary:
|
|
|
303
303
|
- Slug: \`${e.skillSlug}\`
|
|
304
304
|
- Description: ${e.description}
|
|
305
305
|
- Default price: free (\`price_cents: 0\`)
|
|
306
|
-
`}function
|
|
306
|
+
`}function Ts(e){return`# Scripts
|
|
307
307
|
|
|
308
308
|
Place optional helper scripts for \`${e.skillSlug}\` here.
|
|
309
309
|
|
|
310
310
|
Only include files that are required by the skill workflow. Keep the runtime surface small so bundle packaging stays predictable.
|
|
311
|
-
`}function
|
|
311
|
+
`}function Bs(e){return`# ${Rt(e.skillSlug)} Guide
|
|
312
312
|
|
|
313
313
|
## Intent
|
|
314
314
|
|
|
@@ -320,15 +320,15 @@ Document the decision rules, expected inputs, and success criteria for this ${e.
|
|
|
320
320
|
- Example prompts that should trigger the skill
|
|
321
321
|
- Failure cases and recovery guidance
|
|
322
322
|
- Tooling or policy constraints
|
|
323
|
-
`}function
|
|
324
|
-
`);return`skills-layer-cli:api-key:${
|
|
323
|
+
`}function Rt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ns(e){let t=Zn(e.category);return t||Xn({name:e.skillSlug,slug:e.skillSlug,description:e.description,skillType:e.skillType}).category}var Ms=/^github:([^/]+)\/([^/#]+)(?:\/([^#]+))?(?:#(.+))?$/,Fs=/^gitlab:([^/#]+(?:\/[^/#]+)*?)\/([^/#]+)(?:\/([^/#]+))?(?:#(.+))?$/,Os=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/(.+?))?(?:#([^@]+))?$/,qs=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\/.+)?(?:#[^@]+)?$/,Ks=/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/,Gs=/^(?:ssh:\/\/)?git@github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/,Vs=/^(?:ssh:\/\/)?git@gitlab\.com[:/]([^/]+(?:\/[^/]+)*)\/([^/]+?)(?:\.git)?$/;function Qe(e){let t=e.trim();if(t.length===0)throw new Error("import requires a non-empty source.");let{sourceInput:n,skillFilter:i}=Ds(t),r=n.match(Ms);if(r){let[,g,f,m,k]=r;return Ze({input:t,owner:g,repo:f,ref:k?.trim()||"main",subpath:m,skillFilter:i})}let s=n.match(Fs);if(s){let[,g,f,m,k]=s;return _t({input:t,host:"gitlab.com",namespace:g,repo:f,ref:k?.trim()||"main",subpath:m,skillFilter:i})}let o=Hs(t);if(o)return o;let a=zs(t);if(a)return a;let c=n.match(Gs);if(c){let[,g,f]=c;return Ze({input:t,owner:g,repo:ue(f),ref:"main",subpath:"SKILL.md"})}let u=n.match(Vs);if(u){let[,g,f]=u;return _t({input:t,host:"gitlab.com",namespace:g,repo:ue(f),ref:"main",subpath:"SKILL.md"})}if(/^(?:git\+)?https?:\/\//u.test(n)){if(/[?&]skill=/u.test(n)){let g=new URL(n.replace(/^git\+/u,"")),f=g.searchParams.get("skill")?.trim();return g.searchParams.delete("skill"),{kind:"url",input:t,url:g.toString(),canonicalSource:g.toString(),...f?{skillFilter:f}:{}}}return{kind:"url",input:t,url:n.replace(/^git\+/u,""),canonicalSource:n.replace(/^git\+/u,"")}}let d=n.match(Os);if(d&&!Ks.test(n)){let[,g,f,m,k]=d;return Ze({input:t,owner:g,repo:ue(f),ref:k?.trim()||"main",subpath:m,skillFilter:i})}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,""),...i?{skillFilter:i}:{}}:{kind:"local",input:t,location:n,canonicalSource:n,...i?{skillFilter:i}:{}}}function Xe(e){let t=e?.trim();return t&&t.length>0?t:"SKILL.md"}function Ds(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),i=e.slice(t+1).trim();return i.match(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u)?n.includes("#")?{sourceInput:n,skillFilter:i}:n.startsWith("github:")||n.startsWith("gitlab:")||qs.test(n)?{sourceInput:n,skillFilter:i}:{sourceInput:n,skillFilter:i}:{sourceInput:e}}function ii(e,t,n,i,r){return e==="gitlab"&&r&&r!=="gitlab.com"?`${e}://${r}/${t}@${n}/${i}`:`${e}://${t}@${n}/${i}`}function ue(e){return e.replace(/\.git$/u,"")}function Hs(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);if(n.length<2)throw new Error("GitHub URLs must include an owner and repository.");let i=n[0],r=ue(n[1]),s="main",o="SKILL.md";(n[2]==="tree"||n[2]==="blob")&&(s=n[3]?.trim()||"main",o=Xe(n.slice(4).join("/")));let a=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),Ze({input:e,owner:i,repo:r,ref:s,subpath:o,skillFilter:a})}function zs(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),i=n.indexOf("-");if(t.hostname!=="gitlab.com"&&i===-1)return null;let r=i===-1?n:n.slice(0,i);if(r.length<2)throw new Error("GitLab URLs must include a namespace and repository.");let s=ue(r[r.length-1]),o=r.slice(0,-1).join("/"),a=i===-1?void 0:n[i+1],c=i===-1?[]:n.slice(i+2),u=(a==="tree"||a==="blob")&&c[0]?.trim()||"main",d=a==="tree"||a==="blob"?Xe(c.slice(1).join("/")):"SKILL.md",g=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),_t({input:e,host:t.hostname,namespace:o,repo:s,ref:u,subpath:d,skillFilter:g})}function Ze(e){let t=Xe(e.subpath);return{kind:"github",input:e.input,owner:e.owner,repo:ue(e.repo),ref:e.ref,subpath:t,repoUrl:`https://github.com/${e.owner}/${ue(e.repo)}`,rawUrl:`https://raw.githubusercontent.com/${e.owner}/${ue(e.repo)}/${e.ref}/${t}`,canonicalSource:ii("github",`${e.owner}/${ue(e.repo)}`,e.ref,t),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}function _t(e){let t=ue(e.repo),n=Xe(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:ii("gitlab",`${e.namespace}/${t}`,e.ref,n,e.host),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}var Ws="private",ri="public",si="unlisted",oi="delisted";function $t(e){if(typeof e!="string"||e.trim().length===0)return null;let t=e.trim().toLowerCase();return t==="private"?Ws:t===ri?ri:t===si?si:t===oi?oi:null}import{execFile as Js}from"node:child_process";import{createHash as Ys}from"node:crypto";import{promisify as Zs}from"node:util";var It=Zs(Js),Ue="apiKey",Pe="apiKeyRef",Te="Skills Layer CLI";function jt(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:eo()}async function ai(e,t){if(!(typeof e[Ue]=="string"&&e[Ue].length>0))return e;let i=At(t);if(!i)return e;try{let r={...e,credentialStorage:"macos_keychain"},s=Qs(e);return await i.set(Lt(t),s,e[Ue]),r[Pe]=s,delete r[Ue],r}catch{return Xs(e)}}async function li(e,t){if(e.credentialStorage!=="macos_keychain"||e[Ue]||!e[Pe])return e;let n=At(t);if(!n)return e;let i=await n.get(Lt(t),e[Pe]);return i?{...e,apiKey:i}:e}async function ci(e,t){if(!e||e.credentialStorage!=="macos_keychain"||!e[Pe])return;let n=At(t);n&&await n.delete(Lt(t),e[Pe])}function Qs(e){let t=[e.baseUrl??"unknown-base-url",e.userId??e.email??e.role??"unknown-user","apiKey"].join(`
|
|
324
|
+
`);return`skills-layer-cli:api-key:${Ys("sha256").update(t).digest("base64url").slice(0,32)}`}function At(e){return e.store!==void 0?e.store:jt(e.platform,e.env??process.env)}function Lt(e){return e.service??Te}function Xs(e){let t={...e,credentialStorage:"local_file_locked"};return delete t[Pe],t}function eo(){return{kind:"macos_keychain",async set(e,t,n){await It("/usr/bin/security",["add-generic-password","-a",t,"-s",e,"-w",n,"-U"])},async get(e,t){try{let{stdout:n}=await It("/usr/bin/security",["find-generic-password","-a",t,"-s",e,"-w"]);return n.trim()||null}catch{return null}},async delete(e,t){try{await It("/usr/bin/security",["delete-generic-password","-a",t,"-s",e])}catch{}}}}function Et(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 ui=` ____ _ _ _ _ _
|
|
325
325
|
/ ___|| | _(_) | |___ | | __ _ _ _ ___ _ __
|
|
326
326
|
\\___ \\| |/ / | | / __| | | / _\` | | | |/ _ \\ '__|
|
|
327
327
|
___) | <| | | \\__ \\ | |__| (_| | |_| | __/ |
|
|
328
328
|
|____/|_|\\_\\_|_|_|___/ |_____\\__,_|\\__, |\\___|_|
|
|
329
329
|
|___/
|
|
330
330
|
Skills-Layer
|
|
331
|
-
AI Agent first platform for Skills`;var
|
|
331
|
+
AI Agent first platform for Skills`;var di=`Skills Layer MCP
|
|
332
332
|
Configure Skills Layer for AI agents through a local stdio bridge.
|
|
333
333
|
|
|
334
334
|
Usage:
|
|
@@ -359,7 +359,7 @@ Checks:
|
|
|
359
359
|
repair rewrites the local bridge and supported target config.
|
|
360
360
|
disconnect removes Skills Layer MCP local state and the selected target config entry.
|
|
361
361
|
|
|
362
|
-
After setup or repair, open a fresh agent session or restart the agent if tools are not visible.`;var
|
|
362
|
+
After setup or repair, open a fresh agent session or restart the agent if tools are not visible.`;var to=`Skills Layer CLI
|
|
363
363
|
Agent-first skill marketplace for developers. CLI, MCP, and API share one journey model.
|
|
364
364
|
|
|
365
365
|
Usage:
|
|
@@ -438,7 +438,7 @@ Primary commands:
|
|
|
438
438
|
skills-layer doctor [--base-url <url>] [--json]
|
|
439
439
|
|
|
440
440
|
Discovery and trust:
|
|
441
|
-
skills-layer search [query] [--base-url <url>] [--agent <agent>] [--capability <capability>] [--trust <label>] [--runtime-risk <low|elevated|high>] [--security-capability <capability>] [--install [<skill-slug>]] [--json]
|
|
441
|
+
skills-layer search [query] [--base-url <url>] [--agent <agent>] [--capability <capability>] [--trust <label>] [--runtime-risk <low|elevated|high>] [--security-capability <capability>] [--limit <n>] [--install [<skill-slug>]] [--json]
|
|
442
442
|
skills-layer featured [--limit <n>] [--search <text>] [--sort <featured|trending|newest|name|relevance>] [--base-url <url>] [--json]
|
|
443
443
|
skills-layer trending [--limit <n>] [--search <text>] [--sort <featured|trending|newest|name|relevance>] [--base-url <url>] [--json]
|
|
444
444
|
skills-layer show <skill-slug> [--base-url <url>] [--json]
|
|
@@ -521,7 +521,7 @@ Primary commands:
|
|
|
521
521
|
skills-layer import ...
|
|
522
522
|
skills-layer sync [--scope <scope>] [--agent <agent>] [--json]
|
|
523
523
|
skills-layer restore [skill-slug] [--scope <scope>] [--workspace <workspace-id>] [--json]
|
|
524
|
-
skills-layer check
|
|
524
|
+
skills-layer check <skill-slug> [--json]
|
|
525
525
|
skills-layer update [<skill-slug>] [--dry-run] [--pin <version>] [--json]
|
|
526
526
|
skills-layer installed [--scope <scope>] [--agent <agent>] [--verbose] [--json]
|
|
527
527
|
skills-layer remove [skill-slug] [--scope <scope>] [--agent <agent>] [--workspace <workspace-id>] [--json]
|
|
@@ -550,9 +550,9 @@ Safety:
|
|
|
550
550
|
- Use guardian status [skill-slug] to see Cloud policy, stored user preference, effective mode, local hook posture, and the next Guardian action.
|
|
551
551
|
- Use guardian hook install to add native host hooks where supported; status reports the actual enforcement layer instead of overclaiming strict blocking.
|
|
552
552
|
- Use guardian exec when you need a stronger wrapper that refuses blocked shell actions before spawning the command.
|
|
553
|
-
- Use --dry-run before mutating catalog/source installs, workspace deployments, submissions, visibility, or ownership state.`,
|
|
553
|
+
- Use --dry-run before mutating catalog/source installs, workspace deployments, submissions, visibility, or ownership state.`,Be=`${ui}
|
|
554
554
|
|
|
555
|
-
${
|
|
555
|
+
${to}`;var no=new Set(["add-issue","add-review","agents","api-key","approval","auth","backend","buy","categories","check","compare","creator","doctor","export","featured","find","guardian","help","identity","import","install","installed","library","login","logout","mcp","owned","preview-trigger","profile","purchases","recommend","register","remove","restore","search","show","show-issues","show-reviews","source","status","sync","trending","trust","update","validate","whoami","workspace","workspaces"]);function et(e,t){let n=e?.trim().toLowerCase(),i=t?.trim().toLowerCase();if(!n||!no.has(n))return null;if(n==="install")return`Skills Layer install help
|
|
556
556
|
|
|
557
557
|
Usage:
|
|
558
558
|
skills-layer install <skill-slug> [--version <semver>] [--scope <local|project|global|workspace>] [--agent <agent>] [--dry-run] [--json]
|
|
@@ -578,7 +578,219 @@ Good defaults:
|
|
|
578
578
|
After install:
|
|
579
579
|
skills-layer installed
|
|
580
580
|
skills-layer sync
|
|
581
|
-
skills-layer update <skill-slug>`;if(n==="
|
|
581
|
+
skills-layer update <skill-slug>`;if(n==="api-key")return i==="create"?`Skills Layer api-key create help
|
|
582
|
+
|
|
583
|
+
Usage:
|
|
584
|
+
skills-layer api-key create --name <name> --scope <scope>[,<scope>...] [--expires <duration>] [--json]
|
|
585
|
+
|
|
586
|
+
What it does:
|
|
587
|
+
- Creates a named scoped automation key for CI or scripts.
|
|
588
|
+
- The raw key is sent to your verified email and is not printed in CLI or MCP output.
|
|
589
|
+
- --expires supports day durations such as 7d, 30d, or 90d; unsupported duration formats are rejected before creation.
|
|
590
|
+
|
|
591
|
+
Examples:
|
|
592
|
+
skills-layer api-key create --name "GitHub Actions" --scope catalog:read,creator:submit --expires 30d
|
|
593
|
+
skills-layer api-key create --name "Read-only smoke" --scope catalog:read --expires 7d --json
|
|
594
|
+
|
|
595
|
+
Next:
|
|
596
|
+
skills-layer api-key list
|
|
597
|
+
skills-layer api-key revoke --key-id <key-id>`:`Skills Layer api-key help
|
|
598
|
+
|
|
599
|
+
Usage:
|
|
600
|
+
skills-layer api-key create --name <name> --scope <scope>[,<scope>...] [--expires <duration>] [--json]
|
|
601
|
+
skills-layer api-key list [--json]
|
|
602
|
+
skills-layer api-key revoke --key-id <key-id> [--json]
|
|
603
|
+
|
|
604
|
+
What it does:
|
|
605
|
+
- Manages scoped automation credentials.
|
|
606
|
+
- Normal human CLI/MCP login uses skills-layer login; API keys are for named automation.
|
|
607
|
+
- Raw keys are shown or sent only through controlled delivery paths and should not be pasted into logs.
|
|
608
|
+
|
|
609
|
+
Examples:
|
|
610
|
+
skills-layer api-key create --name "GitHub Actions" --scope catalog:read --expires 7d
|
|
611
|
+
skills-layer api-key list
|
|
612
|
+
skills-layer api-key revoke --key-id key_123`;if(n==="buy")return`Skills Layer buy help
|
|
613
|
+
|
|
614
|
+
Usage:
|
|
615
|
+
skills-layer buy <skill-slug> [--payment-method <card|pm_id>] [--json]
|
|
616
|
+
|
|
617
|
+
What it does:
|
|
618
|
+
- Starts a buyer purchase or checkout flow for one catalog skill.
|
|
619
|
+
- Validates payment method input before creating a purchase.
|
|
620
|
+
- In human mode, opens checkout when payment confirmation is required.
|
|
621
|
+
- In --json mode, returns an agent-safe handoff/status envelope without interactive prompts.
|
|
622
|
+
|
|
623
|
+
Examples:
|
|
624
|
+
skills-layer buy project-planner
|
|
625
|
+
skills-layer buy project-planner --payment-method card
|
|
626
|
+
skills-layer buy project-planner --json
|
|
627
|
+
|
|
628
|
+
Next:
|
|
629
|
+
skills-layer purchases list
|
|
630
|
+
skills-layer install <skill-slug>`;if(n==="add-review")return`Skills Layer add-review help
|
|
631
|
+
|
|
632
|
+
Usage:
|
|
633
|
+
skills-layer add-review <skill-slug> --rating <1-5> [--feedback <text>] [--json]
|
|
634
|
+
|
|
635
|
+
What it does:
|
|
636
|
+
- Adds or updates your review for a skill you can access.
|
|
637
|
+
- Rating is validated before submission.
|
|
638
|
+
- Use --json for agent-safe status output.
|
|
639
|
+
|
|
640
|
+
Examples:
|
|
641
|
+
skills-layer add-review project-planner --rating 5 --feedback "Useful planning workflow"
|
|
642
|
+
skills-layer show-reviews project-planner`;if(n==="add-issue")return`Skills Layer add-issue help
|
|
643
|
+
|
|
644
|
+
Usage:
|
|
645
|
+
skills-layer add-issue <skill-slug> --issue-type <bug|quality|safety|other> --message <text> [--json]
|
|
646
|
+
|
|
647
|
+
What it does:
|
|
648
|
+
- Reports a buyer-visible issue against a skill you can access.
|
|
649
|
+
- Issue type is validated before submission.
|
|
650
|
+
- Safety-related reports feed Guardian/security review signals.
|
|
651
|
+
|
|
652
|
+
Examples:
|
|
653
|
+
skills-layer add-issue project-planner --issue-type quality --message "Missing examples"
|
|
654
|
+
skills-layer show-issues project-planner`;if(n==="profile"&&i==="update")return`Skills Layer profile update help
|
|
655
|
+
|
|
656
|
+
Usage:
|
|
657
|
+
skills-layer profile update [--display-name <text>] [--bio <text>] [--company <text>] [--json]
|
|
658
|
+
|
|
659
|
+
What it does:
|
|
660
|
+
- Updates editable profile fields for the signed-in account.
|
|
661
|
+
- Email and role are identity properties and are not changed here.
|
|
662
|
+
- Use --json for machine-readable update results.
|
|
663
|
+
|
|
664
|
+
Examples:
|
|
665
|
+
skills-layer profile update --display-name "Manual Tester"
|
|
666
|
+
skills-layer profile update --company "Skills Layer" --json`;if(n==="recommend")return`Skills Layer recommend help
|
|
667
|
+
|
|
668
|
+
Usage:
|
|
669
|
+
skills-layer recommend <task> [--limit <n>] [--json]
|
|
670
|
+
|
|
671
|
+
What it does:
|
|
672
|
+
- Recommends skills for a natural-language task.
|
|
673
|
+
- --limit must be a whole number in the accepted range.
|
|
674
|
+
- Results include slugs you can inspect with show/trust/install.
|
|
675
|
+
|
|
676
|
+
Examples:
|
|
677
|
+
skills-layer recommend "choose a research plan" --limit 3
|
|
678
|
+
skills-layer recommend "summarize meeting notes" --json`;if(n==="compare")return`Skills Layer compare help
|
|
679
|
+
|
|
680
|
+
Usage:
|
|
681
|
+
skills-layer compare <skill-slug-1> <skill-slug-2> [<skill-slug-3> ... up to 5] [--json]
|
|
682
|
+
|
|
683
|
+
What it does:
|
|
684
|
+
- Compares up to 5 catalog skills side by side.
|
|
685
|
+
- Returns missing slugs separately so agents can recover cleanly.
|
|
686
|
+
- Review price, trust, compatibility, and risk before install.
|
|
687
|
+
|
|
688
|
+
Examples:
|
|
689
|
+
skills-layer compare project-planner gtm-strategy
|
|
690
|
+
skills-layer compare skill-a skill-b skill-c --json`;if(n==="categories")return`Skills Layer categories help
|
|
691
|
+
|
|
692
|
+
Usage:
|
|
693
|
+
skills-layer categories [--json]
|
|
694
|
+
|
|
695
|
+
What it does:
|
|
696
|
+
- Lists catalog categories you can use to browse or filter discovery.
|
|
697
|
+
- Category names are formatted for humans while JSON keeps stable identifiers.
|
|
698
|
+
|
|
699
|
+
Examples:
|
|
700
|
+
skills-layer categories
|
|
701
|
+
skills-layer search planning --json`;if(n==="export")return`Skills Layer export help
|
|
702
|
+
|
|
703
|
+
Usage:
|
|
704
|
+
skills-layer export <skill-slug> [--version <semver|external-id>] [--output <path>] [--show-url] [--json]
|
|
705
|
+
|
|
706
|
+
What it does:
|
|
707
|
+
- Creates a signed export/download handoff for a skill you own.
|
|
708
|
+
- Validates --version before requesting export policy checks.
|
|
709
|
+
- With --output, downloads and verifies the archive before writing it locally.
|
|
710
|
+
- Without --output, returns export metadata or a download handoff.
|
|
711
|
+
|
|
712
|
+
Examples:
|
|
713
|
+
skills-layer export project-planner --show-url
|
|
714
|
+
skills-layer export project-planner --version 1.2.3 --json
|
|
715
|
+
skills-layer export project-planner --output ./project-planner.zip
|
|
716
|
+
|
|
717
|
+
Next:
|
|
718
|
+
skills-layer owned
|
|
719
|
+
skills-layer trust <skill-slug>`;if(n==="import")return`Skills Layer import help
|
|
720
|
+
|
|
721
|
+
Usage:
|
|
722
|
+
skills-layer import <source> [--skill <skill-slug>] [--visibility <private|public|unlisted>] [--quarantine] [--json]
|
|
723
|
+
|
|
724
|
+
Supported sources:
|
|
725
|
+
./local-skill
|
|
726
|
+
https://github.com/OWNER/REPO
|
|
727
|
+
github:OWNER/REPO
|
|
728
|
+
https://gitlab.com/GROUP/REPO
|
|
729
|
+
gitlab:GROUP/REPO
|
|
730
|
+
|
|
731
|
+
What it does:
|
|
732
|
+
- Imports a Skills Layer-compatible source through Cloud.
|
|
733
|
+
- Local paths must exist before the import request is sent.
|
|
734
|
+
- Use --visibility public only when you explicitly want public-source publication.
|
|
735
|
+
|
|
736
|
+
Examples:
|
|
737
|
+
skills-layer import ./my-skill --visibility private
|
|
738
|
+
skills-layer import github:OWNER/REPO --skill project-planner --visibility public
|
|
739
|
+
skills-layer import https://gitlab.com/GROUP/REPO --json
|
|
740
|
+
|
|
741
|
+
Next:
|
|
742
|
+
skills-layer source connection start --provider github --source <url> --visibility private
|
|
743
|
+
skills-layer install <skill-slug>`;if(n==="sync")return`Skills Layer sync help
|
|
744
|
+
|
|
745
|
+
Usage:
|
|
746
|
+
skills-layer sync [--scope <local|project|global|workspace>] [--agent <agent>] [--json]
|
|
747
|
+
|
|
748
|
+
What it does:
|
|
749
|
+
- Reconciles local install records with the selected backend catalog.
|
|
750
|
+
- Shows whether each local skill is catalog-backed, source-backed, or missing on the selected backend.
|
|
751
|
+
- Filters are validated before records are read so typos do not silently change the result.
|
|
752
|
+
|
|
753
|
+
Examples:
|
|
754
|
+
skills-layer sync
|
|
755
|
+
skills-layer sync --scope project
|
|
756
|
+
skills-layer sync --agent codex --json
|
|
757
|
+
|
|
758
|
+
Next:
|
|
759
|
+
skills-layer installed
|
|
760
|
+
skills-layer update <skill-slug>`;if(n==="restore")return`Skills Layer restore help
|
|
761
|
+
|
|
762
|
+
Usage:
|
|
763
|
+
skills-layer restore <skill-slug> [--json]
|
|
764
|
+
|
|
765
|
+
What it does:
|
|
766
|
+
- Restores a local install record when Skills Layer still has enough local metadata.
|
|
767
|
+
- Does not bypass Guardian disabled/quarantine markers.
|
|
768
|
+
- If no local record exists, returns a structured missing-record response with next steps.
|
|
769
|
+
|
|
770
|
+
Examples:
|
|
771
|
+
skills-layer restore project-planner
|
|
772
|
+
skills-layer restore project-planner --json
|
|
773
|
+
|
|
774
|
+
Next:
|
|
775
|
+
skills-layer installed
|
|
776
|
+
skills-layer install <skill-slug>`;if(n==="remove")return`Skills Layer remove help
|
|
777
|
+
|
|
778
|
+
Usage:
|
|
779
|
+
skills-layer remove <skill-slug> [--scope <local|project|global|workspace>] [--agent <agent>] [--json]
|
|
780
|
+
|
|
781
|
+
What it does:
|
|
782
|
+
- Removes the local install record for one skill.
|
|
783
|
+
- Validates scope/agent filters before changing local state.
|
|
784
|
+
- Leaves catalog ownership and purchase history unchanged.
|
|
785
|
+
- Use install again when you want to materialize the skill locally.
|
|
786
|
+
|
|
787
|
+
Examples:
|
|
788
|
+
skills-layer remove project-planner
|
|
789
|
+
skills-layer remove project-planner --json
|
|
790
|
+
|
|
791
|
+
Next:
|
|
792
|
+
skills-layer installed
|
|
793
|
+
skills-layer install <skill-slug>`;if(n==="login")return`Skills Layer login help
|
|
582
794
|
|
|
583
795
|
Usage:
|
|
584
796
|
skills-layer login
|
|
@@ -622,7 +834,59 @@ Email flow:
|
|
|
622
834
|
|
|
623
835
|
After verification:
|
|
624
836
|
skills-layer whoami
|
|
625
|
-
skills-layer setup`;if(n==="
|
|
837
|
+
skills-layer setup`;if(n==="search"||n==="find"){if(n==="find"&&i==="examples")return`Skills Layer find examples help
|
|
838
|
+
|
|
839
|
+
Examples:
|
|
840
|
+
skills-layer find planning
|
|
841
|
+
skills-layer find planning --runtime-risk low --limit 3 --json
|
|
842
|
+
skills-layer find "research plan" --agent codex
|
|
843
|
+
skills-layer find planning --install project-planner
|
|
844
|
+
|
|
845
|
+
Related:
|
|
846
|
+
skills-layer search planning
|
|
847
|
+
skills-layer show <skill-slug>
|
|
848
|
+
skills-layer install <skill-slug>`;let s=n==="find"?"find":"search";return`${n==="find"?"Skills Layer find help":"Skills Layer search help"}
|
|
849
|
+
|
|
850
|
+
Usage:
|
|
851
|
+
skills-layer ${s} [query] [--agent <agent>] [--capability <capability>] [--trust <label>] [--runtime-risk <low|elevated|high>] [--security-capability <capability>] [--limit <n>] [--json]
|
|
852
|
+
skills-layer ${s} [query] --install <skill-slug>
|
|
853
|
+
|
|
854
|
+
What it does:
|
|
855
|
+
- Searches the Skills Layer catalog and returns installable, trust-aware skill matches.
|
|
856
|
+
- Filters are explicit so humans and agents can tell exactly why a result set changed.
|
|
857
|
+
- --limit is supported and must be a whole number from 1 to 100.
|
|
858
|
+
|
|
859
|
+
Accepted values:
|
|
860
|
+
--runtime-risk low|elevated|high
|
|
861
|
+
--trust high|medium|low|published|published_with_findings|high_risk
|
|
862
|
+
|
|
863
|
+
Examples:
|
|
864
|
+
skills-layer ${s} planning
|
|
865
|
+
skills-layer ${s} planning --runtime-risk low --limit 3 --json
|
|
866
|
+
skills-layer ${s} "research plan" --agent codex --json
|
|
867
|
+
skills-layer ${s} planning --install project-planner
|
|
868
|
+
|
|
869
|
+
Next:
|
|
870
|
+
skills-layer show <skill-slug>
|
|
871
|
+
skills-layer trust <skill-slug>
|
|
872
|
+
skills-layer install <skill-slug>`}if(n==="check")return`Skills Layer check help
|
|
873
|
+
|
|
874
|
+
Usage:
|
|
875
|
+
skills-layer check <skill-slug> [--json]
|
|
876
|
+
|
|
877
|
+
What it does:
|
|
878
|
+
- Checks one locally installed skill by slug.
|
|
879
|
+
- Reports local install state, cached metadata, and update/trust guidance when available.
|
|
880
|
+
- The skill slug is required; use skills-layer installed to list local slugs.
|
|
881
|
+
|
|
882
|
+
Examples:
|
|
883
|
+
skills-layer installed
|
|
884
|
+
skills-layer check project-planner
|
|
885
|
+
skills-layer check project-planner --json
|
|
886
|
+
|
|
887
|
+
Next:
|
|
888
|
+
skills-layer update <skill-slug> --dry-run
|
|
889
|
+
skills-layer trust <skill-slug>`;if(n==="creator")return i==="init"?`Skills Layer creator init help
|
|
626
890
|
|
|
627
891
|
Usage:
|
|
628
892
|
skills-layer creator init <skill-slug> [--type <standalone|workflow|workflow_automation|mcp_enhanced>] [--dir <target-dir>] [--description <text>] [--category <category>] [--json]
|
|
@@ -748,7 +1012,7 @@ Usage:
|
|
|
748
1012
|
skills-layer guardian exec <skill-slug> [--action-json <json>] [--path <installed-skill-path>] [--dry-run] [--json] -- <command>
|
|
749
1013
|
|
|
750
1014
|
What it does:
|
|
751
|
-
- check performs public-safe local preflight, then asks Skills Layer Cloud for the security decision while keeping
|
|
1015
|
+
- check performs public-safe local preflight, then asks Skills Layer Cloud for the security decision while keeping sensitive policy evaluation server-side.
|
|
752
1016
|
- incident can write local disable/quarantine/report artifacts; local_only avoids uploading incident evidence.
|
|
753
1017
|
- enable, disable, and enable-warnings-only request one-skill Guardian mode changes; Cloud policy still decides the effective mode.
|
|
754
1018
|
- status shows the Cloud policy, the local per-skill preference if one is stored, the effective mode, hook posture, and next action.
|
|
@@ -819,11 +1083,29 @@ What it does:
|
|
|
819
1083
|
Examples:
|
|
820
1084
|
skills-layer purchases list
|
|
821
1085
|
skills-layer purchases invoice purchase_123
|
|
822
|
-
skills-layer purchases refund-quote purchase_123`;if(n==="
|
|
1086
|
+
skills-layer purchases refund-quote purchase_123`;if(n==="approval")return`Skills Layer approval help
|
|
1087
|
+
|
|
1088
|
+
Usage:
|
|
1089
|
+
skills-layer approval request status <approval-request-id> [--json]
|
|
1090
|
+
skills-layer approval request complete <approval-request-id> --decision <approved|denied> [--decision-evidence-json <json>] [--json]
|
|
1091
|
+
|
|
1092
|
+
What it does:
|
|
1093
|
+
- Reads and completes human-in-loop approval requests created by source, publishing, or payout-sensitive workflows.
|
|
1094
|
+
- status is read-only and safe for humans or agents.
|
|
1095
|
+
- complete records the explicit human decision; use --decision-evidence-json only for non-secret rationale or review metadata.
|
|
1096
|
+
|
|
1097
|
+
Examples:
|
|
1098
|
+
skills-layer approval request status approval_123
|
|
1099
|
+
skills-layer approval request complete approval_123 --decision approved
|
|
1100
|
+
skills-layer approval request complete approval_123 --decision denied --decision-evidence-json '{"reason":"not my source"}'
|
|
1101
|
+
|
|
1102
|
+
Next:
|
|
1103
|
+
skills-layer source connection status <source-connection-id>
|
|
1104
|
+
skills-layer creator source prepare <source-connection-id> <path>`;if(n==="mcp")return di;let r=i?` ${i}`:"";return`Skills Layer ${n}${r} help
|
|
823
1105
|
|
|
824
|
-
Run \`skills-layer --help\` for public CLI usage.`}var
|
|
825
|
-
`)),credentialStore:t.credentialStore!==void 0?t.credentialStore:
|
|
826
|
-
`,stderr:""};let r=
|
|
1106
|
+
Run \`skills-layer --help\` for public CLI usage.`}var tt="0.1.6";var I=class extends Error{status;details;constructor(t,n,i){super(n),this.name="ApiError",this.status=t,this.details=i}},Xi=1,mn=1,pi=1,pe="skills-layer-security-hook",te="Skills Layer Security Hook",fn="https://api.skills-layer.com",so="http://127.0.0.1:8787",oo=new Set(["json","dry-run","help","list","all","verbose","show-url","quarantine","confirm","confirmed","with-mcp","no-mcp","allow-unmanaged-once","disclose-source","allow-findings-featured"]),gi=new Set(["accept-capability","approval-request-id","grant-json","paraphrase","should-not-trigger","should-trigger"]),ao=new Set(["bio","company","description","display-name","feedback","message","note","reason","search","summary"]),lo=new Set(["action","action-json","agent","amount-cents","api-key","base-url","capability","category","claim-id","client","cloud-trust-ledger","code","commit-sha","decision","decision-evidence-json","dependency-audit-status","dir","email","environment","evidence-json","expires","fixed-version","format","install","issue-id","issue-type","key-id","kind","license","limit","listing-status","max-characters","method","mode","name","output","path","payment-method","pin","price-cents","provider","provider-installation-id","provider-owner-id","provider-project-id","provider-repo-id","provenance-intent","publication-status","rating","requested-role","review-id","runtime-risk","scope","security-capability","skill","skill-type","sort","source","source-intake-context","state","status","text","telemetry-mode","trust","type","unmanaged-policy","version","version-id","visibility","workspace"]);async function Nu(e,t={}){let n={env:t.env??process.env,platform:t.platform??process.platform,cwd:t.cwd??process.cwd(),now:t.now??(()=>new Date().toISOString()),fetchFn:t.fetch??globalThis.fetch,openUrl:t.openUrl??Bc(t.platform??process.platform),stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY,promptText:t.promptText??Lc(),promptSecret:t.promptSecret??Ec(),promptSelect:t.promptSelect??Uc(t.selectInput??process.stdin,t.selectOutput??process.stdout),sleep:t.sleep??(a=>new Promise(c=>setTimeout(c,a))),emitInfo:t.emitInfo??(a=>process.stdout.write(`${a}
|
|
1107
|
+
`)),credentialStore:t.credentialStore!==void 0?t.credentialStore:jt(t.platform??process.platform,t.env??process.env)},i=e[0];if(!i){let a=fi([]),c=await Tt(a.flags,n);return await pl(a.flags,c)}if(i==="--help"||i==="-h")return{exitCode:0,stdout:Be,stderr:""};if(i==="--version"||i==="-v")return{exitCode:0,stdout:`skills-layer ${tt}
|
|
1108
|
+
`,stderr:""};let r=fi(e.slice(1));if(r.error)return y(r.error,r.flags.json);let{flags:s,positionals:o}=r;if(i==="admin")return y("The public skills-layer package does not include internal commands.",s.json);if(i==="version"){let a=await Tt(s,n);return h({status:"ok",name:"skills-layer",version:tt},`skills-layer ${tt}`,s.json,a)}if(s.help){let a=et(i,o[0]);return a?{exitCode:0,stdout:a,stderr:""}:y(mi(i),s.json)}try{let a=await Tt(s,n);switch(i){case"agents":return await po(o,s,a);case"backend":return await go(o,s,a);case"register":return await er(s,a);case"login":return await tr(s,a);case"logout":return await nr(s,a);case"whoami":return await R("/api/v1/whoami",s,a,"Account loaded.",{authenticated:!0});case"profile":return await ho(o,s,a);case"auth":return await ko(o,s,a);case"identity":return await So(o,s,a);case"api-key":return await Po(o,s,a);case"mcp":return await Co(o,s,a);case"search":case"find":return await jo(o,s,a);case"featured":case"trending":return await To(i,s,a);case"categories":return await R("/api/v1/categories",s,a,"Categories loaded.");case"recommend":return await Bo(o,s,a);case"compare":return await No(o,s,a);case"show":return await Mo(o,s,a);case"trust":return await Fo(o,s,a);case"help":return await Oo(o,s,a);case"status":return await R("/api/v1/status",s,a,"Status loaded.");case"doctor":return await Ol(s,a);case"setup":return await wr(s,a);case"validate":return await qo(o,s,a);case"preview-trigger":return await Ko(o,s,a);case"creator":return await Go(o,s,a);case"install":return await wn(o,s,a);case"installed":return await Ua(s,a);case"remove":return await Ta(o,s,a);case"update":return await Ba(o,s,a);case"sync":return await Ma(s,a);case"restore":return await Wa(o,s,a);case"check":return await Ja(o,s,a);case"import":return await Ya(o,s,a);case"source":return await Qa(o,s,a);case"approval":return await tl(o,s,a);case"workspace":case"workspaces":return await nl(o,s,a);case"buy":return await il(o,s,a);case"purchases":return await rl(o,s,a);case"owned":return await R("/api/v1/me/library",s,a,"Owned skills loaded.",{authenticated:!0});case"export":return await ol(o,s,a);case"library":return await sl(o,s,a);case"add-review":return await Ei("add",o,s,a);case"show-reviews":return await Ei("show",o,s,a);case"add-issue":return await Ui("add",o,s,a);case"show-issues":return await Ui("show",o,s,a);case"guardian":return await al(o,s,a);default:return y(mi(i),s.json)}}catch(a){return a instanceof I?yt(a,s.json):y(ae(a),s.json)}}function mi(e){let t=e.trim().toLowerCase();return t==="purchase"?`Unknown command "${e}".
|
|
827
1109
|
|
|
828
1110
|
Did you mean:
|
|
829
1111
|
skills-layer buy <skill-slug>
|
|
@@ -836,7 +1118,7 @@ Did you mean:
|
|
|
836
1118
|
skills-layer show <skill-slug>`:t==="security-report"?`Unknown command "${e}".
|
|
837
1119
|
|
|
838
1120
|
Did you mean:
|
|
839
|
-
skills-layer trust <skill-slug>`:`Unknown command "${e}".`}function Jn(e){let t={json:!1,help:!1,dryRun:!1,list:!1,all:!1,verbose:!1,showUrl:!1,quarantine:!1,confirmed:!1,allowUnmanagedOnce:!1,discloseSource:!1,allowFindingsFeatured:!1,shouldTrigger:[],shouldNotTrigger:[],paraphrase:[],grantJson:[],findingCode:[],acceptCapability:[],approvalRequestId:[]},n=[];for(let i=0;i<e.length;i+=1){let r=e[i];if(!r)continue;if(r==="--"){n.push(...e.slice(i+1));break}if(r==="-h"){t.help=!0;continue}if(!r.startsWith("--")){n.push(r);continue}let s=r.slice(2);if(us.has(s)){let a=bt(s);s==="confirm"?t.confirmed=!0:t[a]=!0;continue}let o=e[i+1];if(!o||o.startsWith("--")){if(s==="install"){t.install="";continue}return{flags:t,positionals:n,error:`Flag --${s} requires a value.`}}if(ds.has(s)){let a=ps(e,i);if(!a.value)return{flags:t,positionals:n,error:`Flag --${s} requires a value.`};t[bt(s)]=a.value,i=a.nextIndex;continue}if(gs.has(s)||Dn.has(s)){let a=bt(s);if(Dn.has(s)){let c=Array.isArray(t[a])?t[a]:[];c.push(o),t[a]=c}else t[a]=o;i+=1;continue}return{flags:t,positionals:n,error:`Unknown flag --${s}.`}}return{flags:t,positionals:n}}function ps(e,t){let n=[],i=t;for(let r=t+1;r<e.length;r+=1){let s=e[r];if(!s||s.startsWith("--"))break;n.push(s),i=r}return{value:n.length>0?n.join(" "):null,nextIndex:i}}function bt(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function Pt(e,t){let n=ms(t.env,t.platform),[i,r]=await Promise.all([Cl(n.configPath,t),V(n.backendPreferencePath)]),s=ne(g(e.baseUrl)??Q(t.env.SKILLS_LAYER_BASE_URL)??Q(r?.preferredBaseUrl)??Q(i?.baseUrl)??Yt),o=g(e.apiKey)??Q(t.env.SKILLS_LAYER_API_KEY),a=Q(i?.apiKey),c=Q(i?.baseUrl),u=!c||ne(c)===s,d=o??(u?a:void 0),p=!o&&a&&c&&!u?`Your saved login belongs to ${ne(c)}, but the selected backend is ${s}. Run \`skills-layer backend --base-url ${ne(c)}\` to use that login, or run \`skills-layer login\` for ${s}.`:void 0;return{...t,paths:n,config:i,baseUrl:s,apiKey:d,authBlockedMessage:p}}function ms(e,t){let n=t==="win32"?Se:zt,i=t==="win32"?Q(e.USERPROFILE)??Q(e.HOME):Q(e.HOME),r=n.join(i??".",".skills-layer");return{stateDir:r,configPath:n.join(r,"config.json"),backendPreferencePath:n.join(r,"backend-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"),bundlesDir:n.join(r,"bundles"),incidentsDir:n.join(r,"incidents")}}async function fs(e,t,n){if(e[0]!=="list")return k(`Unknown agents command "${e[0]??""}".`,t.json);let i=de(n.env,n.platform,n.cwd).map(r=>({id:r.id,displayName:r.displayName,capabilities:r.capabilities,projectSkillsPath:r.targets.projectSkillsPath,globalSkillsPath:r.targets.globalSkillsPath}));return f({status:"ok",results:i},`Found ${i.length} supported agent targets.`,t.json,n)}async function hs(e,t,n){let i=e[0],r=g(t.baseUrl);if(!i&&r||i==="cloud"||i==="local"){let o=ne(r??(i==="local"?cs:Yt)),a=Pe(o);return await D(n.paths.backendPreferencePath,{version:Vt,preferredBaseUrl:o,savedAt:n.now()}),f({status:"updated",selectedBackend:a,selectedBaseUrl:o,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:!n.config?.baseUrl||ne(n.config.baseUrl)===o},`Backend set to ${a}.`,t.json,n)}if(i&&i!=="status")return k(`Unknown backend command "${i}".`,t.json);let s=Pe(n.baseUrl);return f({status:"ok",selectedBackend:s,selectedBaseUrl:n.baseUrl,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:!n.config?.baseUrl||ne(n.config.baseUrl)===n.baseUrl,loggedIn:!!n.apiKey,email:n.config?.email??null,role:n.config?.role??null},`Backend: ${n.baseUrl}`,t.json,n)}var Zt=[{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"}],ys=[...Zt,{value:"email",label:"Email code",description:"Use an emailed one-time code"},{value:"api_key",label:"API key (advanced)",description:"Paste an existing Skills Layer login key"}],ks=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...Zt];async function Ci(e,t){let n=g(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",ks)}catch{return k("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`, `skills-layer register --method gitlab`, or `skills-layer register --method microsoft`.",!1)}if(n==="email"){let r=g(e.email);if(!r&&!e.json)try{r=await t.promptText("Enter your email address: ")}catch{return k("register --method email requires --email when interactive prompts are unavailable.",!1)}r=v(r,"register requires --email.");let s=await b(t,"/api/v1/register",{method:"POST",headers:_(),body:JSON.stringify({method:n,email:r})});if(e.json){let a=s.status==="already_registered"?Gt(s):z({...s,nextCommand:`skills-layer auth verify --email ${r} --code <code> --json`,nextAction:"auth.verify"}),c=s.status==="already_registered"?`${r} is already registered.`:`Registration started for ${r}.`;return f(a,c,e.json,t)}if(s.status==="already_registered")return f(Gt(s),`${r} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,!1,t);let o;try{o=await t.promptText(`Enter the verification code sent to ${r} (check spam/junk folder if missing): `)}catch{return f(z(s),`Registration started for ${r}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${r} --code <code>\`.`,!1,t)}return await zi(r,o,e,t,`Verified ${r}.`)}let i=await b(t,"/api/v1/identity/social/start",{method:"POST",headers:_(),body:JSON.stringify({provider:n,mode:"login"})});return e.json?f(i,"Social registration started.",e.json,t):await ln(n,i,e,t,"login")}async function Ri(e,t){if(e.withMcp&&e.noMcp)return k("login cannot combine --with-mcp and --no-mcp.",e.json);let n=g(e.apiKey);if(n){let o=await Ue(t,n,{notifyLogin:!0}),a=await It(e,{...t,config:o,apiKey:n});return H(a)?a:f(z({status:"verified",...o,...a.data?{mcp:a.data}:{}}),[`Logged in as ${o.email}.`,a.message??""].filter(Boolean).join(" "),e.json,t)}let i=g(e.method);if(!i&&!e.json)try{let o=await t.promptSelect("Choose how to sign in:",ys);i=o==="api_key"?void 0:o}catch{return k("login requires --api-key or --method <email|google|github|gitlab|microsoft> when interactive selection is unavailable.",!1)}if(i){if(i==="email"){let a=g(e.email);!a&&!e.json&&(a=(await t.promptText("Enter your email address: ")).trim()),a=v(a,"login --method email requires --email.");let c=await b(t,"/api/v1/identity/recover/start",{method:"POST",headers:_(),body:JSON.stringify({email:a,method:"email",intent:"login"})});if(e.json)return f(c,`Passwordless email login started for ${a}.`,!0,t);let u;try{u=(await t.promptText(`Enter the sign-in code sent to ${a} (check spam/junk folder if missing): `)).trim()}catch{return f(c,`Passwordless email login started for ${a}. Check your email, then run \`skills-layer login --method email --email ${a}\` again when prompts are available.`,!1,t)}let d=await b(t,"/api/v1/identity/recover/complete",{method:"POST",headers:_(),body:JSON.stringify({email:a,code:u,intent:"login"})});return await rt(a,d,e,t,`Verified ${a}.`)}if(!["google","github","gitlab","microsoft"].includes(i))return k("login --method must be email, google, github, gitlab, or microsoft.",e.json);let o=await b(t,"/api/v1/identity/social/start",{method:"POST",headers:_(),body:JSON.stringify({provider:i,mode:"login"})});return e.json?f(o,"Social login started.",!0,t):await ln(i,o,e,t,"login")}if(!e.json)try{n=(await t.promptSecret("Enter your Skills Layer API key: ")).trim()}catch{return k("login requires an API key.",e.json)}if(!n)return k("login requires --api-key or --method <email|google|github|gitlab|microsoft>.",e.json);let r=await Ue(t,n,{notifyLogin:!0}),s=await It(e,{...t,config:r,apiKey:n});return H(s)?s:f(z({status:"verified",...r,...s.data?{mcp:s.data}:{}}),[`Logged in as ${r.email}.`,s.message??""].filter(Boolean).join(" "),e.json,t)}async function xi(e,t){return await Fn(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),await Ht(t.paths.configPath,{force:!0}),f({status:"logged_out"},"Logged out.",e.json,t)}async function ws(e,t,n){let i=e[0]??"show";if(i==="show")return await C("/api/v1/profile",t,n,"Profile loaded.",{authenticated:!0});if(i==="update"){let r=await vs(t,n);if(H(r))return r;let s=await b(n,"/api/v1/profile",{method:"PATCH",headers:_(n.apiKey),body:JSON.stringify(r)});return f(s,"Profile updated.",t.json,n)}return k(`Unknown profile command "${i}".`,t.json)}async function vs(e,t){let n=F(e,["displayName","bio","company"]);if(Object.keys(n).length>0)return n;if(e.json)return k("profile update requires at least one of --display-name, --bio, or --company.",!0);try{let i=await t.promptText("Display name (leave blank to keep unchanged): "),r=await t.promptText("Bio (leave blank to keep unchanged): "),s=await t.promptText("Company (leave blank to keep unchanged): "),o=j({displayName:i||void 0,bio:r||void 0,company:s||void 0});return Object.keys(o).length===0?k("No profile changes entered.",!1):o}catch{return k("profile update requires at least one of --display-name, --bio, or --company.",!1)}}async function bs(e,t,n){let i=e[0];if(i==="register")return await Ci({...t,method:"email"},n);if(i==="verify"){let r=v(t.email,"auth verify requires --email."),s=v(t.code,"auth verify requires --code.");return await zi(r,s,t,n,`Verified ${r}.`)}return i==="recover"?await Cs(e.slice(1),t,n):i==="login"?await Ri(t,n):i==="logout"?await xi(t,n):i==="status"?Ps(t,n):i==="repair"?await Ss(t,n):k(`Unknown auth command "${i??""}".`,t.json)}function Ps(e,t){let n=t.config?.baseUrl?ne(t.config.baseUrl):null,i=!!(t.apiKey&&n===t.baseUrl);return f({status:"auth_status",selectedBackend:Pe(t.baseUrl),selectedBaseUrl:t.baseUrl,loggedIn:i,requiresLogin:!i,...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:i}}:{}},i&&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 Ss(e,t){if(!t.config?.baseUrl||!t.config.apiKey||!t.config.email||!t.config.role||!t.config.savedAt)return k("No saved Skills Layer login was found to repair. Run `skills-layer login`.",e.json);let n=ne(t.config.baseUrl);return await D(t.paths.backendPreferencePath,{version:Vt,preferredBaseUrl:n,savedAt:t.now()}),await un(t.paths.configPath,{...t.config,baseUrl:n,savedAt:t.now()},t),f({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 Cs(e,t,n){let i=e[0]??g(t.method)??"email",r=g(t.email);if(!r&&!t.json)try{r=await n.promptText("Enter your email address: ")}catch{return k("auth recover requires --email when interactive prompts are unavailable.",!1)}if(r=v(r,"auth recover requires --email."),i==="complete"){let c=g(t.code);if(!c&&!t.json)try{c=await n.promptText("Enter the recovery code: ")}catch{return k("auth recover complete requires --code when interactive prompts are unavailable.",!1)}return c=v(c,"auth recover complete requires --code."),await zn(r,c,t,n)}let s=await b(n,"/api/v1/identity/recover/start",{method:"POST",headers:_(),body:JSON.stringify({email:r,method:i})}),o=Gt(s);if(t.json)return f(o,"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 f(o,`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 ${r} --code <code>\`.`,!1,n)}return a?await zn(r,a,t,n):f(o,`If this email can continue, instructions have been sent. When you have a code, run \`skills-layer auth recover complete --email ${r} --code <code>\`.`,!1,n)}async function zn(e,t,n,i){let r=await b(i,"/api/v1/identity/recover/complete",{method:"POST",headers:_(),body:JSON.stringify({email:e,code:t})});if(n.json){let s=l(r,"apiKey");return s?(await Ue(i,s,{expectedEmail:e,knownEmail:l(r,"email")??e,knownRole:l(r,"role")??"user",knownRoles:re(r,"roles"),knownUserId:l(r,"userId")}),f(z({...r,loggedIn:!0}),"Recovery complete.",!0,i)):f(z({...r,email:e,loggedIn:!1}),"Recovery complete.",!0,i)}return await rt(e,r,n,i,`Recovered access for ${e}.`)}async function Rs(e,t,n){let i=e[0],r=1;if(i==="providers")return await C("/api/v1/identity/social/providers",t,n,"Identity providers loaded.");if(i==="start"){let s=g(t.provider);if(!s&&!t.json)try{s=await n.promptSelect("Choose identity provider:",Zt)}catch{return k("identity start requires --provider when interactive selection is unavailable.",!1)}s=v(s,"identity start requires --provider.");let o=await b(n,"/api/v1/identity/social/start",{method:"POST",headers:_(n.apiKey),body:JSON.stringify({provider:s,mode:g(t.mode)??"login"})});return t.json?f(o,"Social auth started.",!0,n):await ln(s,o,t,n,"login")}if(i==="status"){let s=g(t.state)??e[r];return s?await C(`/api/v1/identity/social/status/${encodeURIComponent(s)}`,t,n,"Social auth status loaded."):k("identity status requires --state.",t.json)}if(i==="complete"){let s=v(t.provider,"identity complete requires --provider."),o=v(t.state,"identity complete requires --state."),a=v(t.code,"identity complete requires --code."),c=await b(n,"/api/v1/identity/social/complete",{method:"POST",headers:_(n.apiKey),body:JSON.stringify({provider:s,state:o,code:a})});return await Oa(c,n),f(z(c),"Social auth complete.",t.json,n)}if(i==="list")return await C("/api/v1/me/linked-identities",t,n,"Linked identities loaded.",{authenticated:!0});if(i==="unlink"){let s=v(t.provider??e[r],"identity unlink requires a provider."),o=await b(n,`/api/v1/me/linked-identities/${encodeURIComponent(s)}`,{method:"DELETE",headers:M(n.apiKey,n.authBlockedMessage)});return f(o,"Identity unlinked.",t.json,n)}return k(`Unknown identity command "${i??""}".`,t.json)}async function xs(e,t,n){let i=e[0];if(!i)return k("api-key requires create, list, or revoke.",t.json);if(i==="list")return await C("/api/v1/me/api-keys",t,n,"API keys loaded.",{authenticated:!0});if(i==="create"){let r=g(t.name),s=El(t.scope);if(!r)return k("api-key create requires --name.",t.json);if(s.length===0)return k("api-key create requires at least one --scope.",t.json);let o=await b(n,"/api/v1/me/api-keys",{method:"POST",headers:{"content-type":"application/json",...M(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:r,scopes:s,...g(t.expires)?{expiresIn:g(t.expires)}:{}})});return f(z(o),"Automation API key created. The full key was sent to your verified email. Run `skills-layer api-key list` to manage keys.",t.json,n)}if(i==="rotate")return k(`api-key rotate is not part of normal login.
|
|
1121
|
+
skills-layer trust <skill-slug>`:`Unknown command "${e}".`}function fi(e){let t={json:!1,help:!1,dryRun:!1,list:!1,all:!1,verbose:!1,showUrl:!1,quarantine:!1,confirmed:!1,allowUnmanagedOnce:!1,discloseSource:!1,allowFindingsFeatured:!1,shouldTrigger:[],shouldNotTrigger:[],paraphrase:[],grantJson:[],findingCode:[],acceptCapability:[],approvalRequestId:[]},n=[];for(let i=0;i<e.length;i+=1){let r=e[i];if(!r)continue;if(r==="--"){n.push(...e.slice(i+1));break}if(r==="-h"){t.help=!0;continue}if(!r.startsWith("--")){n.push(r);continue}let s=r.slice(2);if(oo.has(s)){let a=Ut(s);s==="confirm"?t.confirmed=!0:t[a]=!0;continue}let o=e[i+1];if(!o||o.startsWith("--")){if(s==="install"){t.install="";continue}return{flags:t,positionals:n,error:`Flag --${s} requires a value.`}}if(ao.has(s)){let a=co(e,i);if(!a.value)return{flags:t,positionals:n,error:`Flag --${s} requires a value.`};t[Ut(s)]=a.value,i=a.nextIndex;continue}if(lo.has(s)||gi.has(s)){let a=Ut(s);if(gi.has(s)){let c=Array.isArray(t[a])?t[a]:[];c.push(o),t[a]=c}else t[a]=o;i+=1;continue}return{flags:t,positionals:n,error:`Unknown flag --${s}.`}}return{flags:t,positionals:n}}function co(e,t){let n=[],i=t;for(let r=t+1;r<e.length;r+=1){let s=e[r];if(!s||s.startsWith("--"))break;n.push(s),i=r}return{value:n.length>0?n.join(" "):null,nextIndex:i}}function Ut(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function Tt(e,t){let n=uo(t.env,t.platform),[i,r]=await Promise.all([Ac(n.configPath,t),Y(n.backendPreferencePath)]),s=ie(p(e.baseUrl)??X(t.env.SKILLS_LAYER_BASE_URL)??X(r?.preferredBaseUrl)??X(i?.baseUrl)??fn),o=p(e.apiKey)??X(t.env.SKILLS_LAYER_API_KEY),a=X(i?.apiKey),c=X(i?.baseUrl),u=!c||ie(c)===s,d=o??(u?a:void 0),g=!o&&a&&c&&!u?`Your saved login belongs to ${ie(c)}, but the selected backend is ${s}. Run \`skills-layer backend --base-url ${ie(c)}\` to use that login, or run \`skills-layer login\` for ${s}.`:void 0;return{...t,paths:n,config:i,baseUrl:s,apiKey:d,authBlockedMessage:g}}function uo(e,t){let n=t==="win32"?_e:pn,i=t==="win32"?X(e.USERPROFILE)??X(e.HOME):X(e.HOME),r=n.join(i??".",".skills-layer");return{stateDir:r,configPath:n.join(r,"config.json"),backendPreferencePath:n.join(r,"backend-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"),bundlesDir:n.join(r,"bundles"),incidentsDir:n.join(r,"incidents")}}async function po(e,t,n){if(e[0]!=="list")return y(`Unknown agents command "${e[0]??""}".`,t.json);let i=me(n.env,n.platform,n.cwd).map(r=>({id:r.id,displayName:r.displayName,capabilities:r.capabilities,projectSkillsPath:r.targets.projectSkillsPath,globalSkillsPath:r.targets.globalSkillsPath}));return h({status:"ok",results:i},`Found ${i.length} supported agent targets.`,t.json,n)}async function go(e,t,n){let i=e[0],r=p(t.baseUrl);if(!i&&r||i==="cloud"||i==="local"){let c=ie(r??(i==="local"?so:fn)),u=ke(c),d=n.config?.baseUrl??null,g=!n.config?.baseUrl||ie(n.config.baseUrl)===c;return await D(n.paths.backendPreferencePath,{version:mn,preferredBaseUrl:c,savedAt:n.now()}),h({status:"updated",selectedBackend:u,selectedBaseUrl:c,savedLoginBaseUrl:d,loginMatchesSelectedBackend:g,loggedIn:!!n.apiKey&&g,...g?{}:{warning:`Saved login belongs to ${d}; selected backend is ${c}.`}},g?`Backend set to ${u}.`:`Backend set to ${u}. Saved login is for ${d}.`,t.json,n)}if(i&&i!=="status")return y(`Unknown backend command "${i}".`,t.json);let s=ke(n.baseUrl),o=!n.config?.baseUrl||ie(n.config.baseUrl)===n.baseUrl,a=!!n.apiKey&&o;return h({status:"ok",selectedBackend:s,selectedBaseUrl:n.baseUrl,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:o,loggedIn:a,email:a?n.config?.email??null:null,role:a?n.config?.role??null:null},`Backend: ${n.baseUrl}`,t.json,n)}var hn=[{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"}],mo=[...hn,{value:"email",label:"Email code",description:"Use an emailed one-time code"},{value:"api_key",label:"API key (advanced)",description:"Paste an existing Skills Layer login key"}],fo=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...hn];async function er(e,t){let n=p(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",fo)}catch{return y("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`, `skills-layer register --method gitlab`, or `skills-layer register --method microsoft`.",!1)}if(n==="email"){let r=p(e.email);if(!r&&!e.json)try{r=await t.promptText("Enter your email address: ")}catch{return y("register --method email requires --email when interactive prompts are unavailable.",!1)}r=b(r,"register requires --email.");let s=await v(t,"/api/v1/register",{method:"POST",headers:A(),body:JSON.stringify({method:n,email:r})});if(e.json){let a=s.status==="already_registered"?ln(s):W({...s,nextCommand:`skills-layer auth verify --email ${r} --code <code> --json`,nextAction:"auth.verify"}),c=s.status==="already_registered"?`${r} is already registered.`:`Registration started for ${r}.`;return h(a,c,e.json,t)}if(s.status==="already_registered")return h(ln(s),`${r} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,!1,t);let o;try{o=await t.promptText(`Enter the verification code sent to ${r} (check spam/junk folder if missing): `)}catch{return h(W(s),`Registration started for ${r}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${r} --code <code>\`.`,!1,t)}return await Ar(r,o,e,t,`Verified ${r}.`)}let i=await v(t,"/api/v1/identity/social/start",{method:"POST",headers:A(),body:JSON.stringify({provider:n,mode:"login"})});return e.json?h(i,"Social registration started.",e.json,t):await $n(n,i,e,t,"login")}async function tr(e,t){if(e.withMcp&&e.noMcp)return y("login cannot combine --with-mcp and --no-mcp.",e.json);let n=p(e.apiKey);if(n){let o=await Oe(t,n,{notifyLogin:!0}),a=await Zt(e,{...t,config:o,apiKey:n});return H(a)?a:h(W({status:"verified",...o,...a.data?{mcp:a.data}:{}}),[`Logged in as ${o.email}.`,a.message??""].filter(Boolean).join(" "),e.json,t)}let i=p(e.method);if(!i&&!e.json)try{let o=await t.promptSelect("Choose how to sign in:",mo);i=o==="api_key"?void 0:o}catch{return y("login requires --api-key or --method <email|google|github|gitlab|microsoft> when interactive selection is unavailable.",!1)}if(i){if(i==="email"){let a=p(e.email);!a&&!e.json&&(a=(await t.promptText("Enter your email address: ")).trim()),a=b(a,"login --method email requires --email.");let c=await v(t,"/api/v1/identity/recover/start",{method:"POST",headers:A(),body:JSON.stringify({email:a,method:"email",intent:"login"})});if(e.json)return h(c,`Passwordless email login started for ${a}.`,!0,t);let u;try{u=(await t.promptText(`Enter the sign-in code sent to ${a} (check spam/junk folder if missing): `)).trim()}catch{return h(c,`Passwordless email login started for ${a}. Check your email, then run \`skills-layer login --method email --email ${a}\` again when prompts are available.`,!1,t)}let d=await v(t,"/api/v1/identity/recover/complete",{method:"POST",headers:A(),body:JSON.stringify({email:a,code:u,intent:"login"})});return await gt(a,d,e,t,`Verified ${a}.`)}if(!["google","github","gitlab","microsoft"].includes(i))return y("login --method must be email, google, github, gitlab, or microsoft.",e.json);let o=await v(t,"/api/v1/identity/social/start",{method:"POST",headers:A(),body:JSON.stringify({provider:i,mode:"login"})});return e.json?h(o,"Social login started.",!0,t):await $n(i,o,e,t,"login")}if(!e.json)try{n=(await t.promptSecret("Enter your Skills Layer API key: ")).trim()}catch{return y("login requires an API key.",e.json)}if(!n)return y("login requires --api-key or --method <email|google|github|gitlab|microsoft>.",e.json);let r=await Oe(t,n,{notifyLogin:!0}),s=await Zt(e,{...t,config:r,apiKey:n});return H(s)?s:h(W({status:"verified",...r,...s.data?{mcp:s.data}:{}}),[`Logged in as ${r.email}.`,s.message??""].filter(Boolean).join(" "),e.json,t)}async function nr(e,t){return await ci(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),await un(t.paths.configPath,{force:!0}),h({status:"logged_out"},"Logged out.",e.json,t)}async function ho(e,t,n){let i=e[0]??"show";if(i==="show")return await R("/api/v1/profile",t,n,"Editable profile loaded.",{authenticated:!0});if(i==="update"){let r=await yo(t,n);if(H(r))return r;let s=await v(n,"/api/v1/profile",{method:"PATCH",headers:A(n.apiKey),body:JSON.stringify(r)});return h(s,"Profile updated.",t.json,n)}return y(`Unknown profile command "${i}".`,t.json)}async function yo(e,t){let n=G(e,["displayName","bio","company"]);if(Object.keys(n).length>0)return n;if(e.json)return y("profile update requires at least one of --display-name, --bio, or --company.",!0);try{let i=await t.promptText("Display name (leave blank to keep unchanged): "),r=await t.promptText("Bio (leave blank to keep unchanged): "),s=await t.promptText("Company (leave blank to keep unchanged): "),o=_({displayName:i||void 0,bio:r||void 0,company:s||void 0});return Object.keys(o).length===0?y("No profile changes entered.",!1):o}catch{return y("profile update requires at least one of --display-name, --bio, or --company.",!1)}}async function ko(e,t,n){let i=e[0];if(i==="register")return await er({...t,method:"email"},n);if(i==="verify"){let r=b(t.email,"auth verify requires --email."),s=b(t.code,"auth verify requires --code.");return await Ar(r,s,t,n,`Verified ${r}.`)}return i==="recover"?await vo(e.slice(1),t,n):i==="login"?await tr(t,n):i==="logout"?await nr(t,n):i==="status"?wo(t,n):i==="repair"?await bo(t,n):y(`Unknown auth command "${i??""}".`,t.json)}function wo(e,t){let n=t.config?.baseUrl?ie(t.config.baseUrl):null,i=!!(t.apiKey&&n===t.baseUrl);return h({status:"auth_status",selectedBackend:ke(t.baseUrl),selectedBaseUrl:t.baseUrl,loggedIn:i,requiresLogin:!i,...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:i}}:{}},i&&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 bo(e,t){if(!t.config?.baseUrl||!t.config.apiKey||!t.config.email||!t.config.role||!t.config.savedAt)return y("No saved Skills Layer login was found to repair. Run `skills-layer login`.",e.json);let n=ie(t.config.baseUrl);return await D(t.paths.backendPreferencePath,{version:mn,preferredBaseUrl:n,savedAt:t.now()}),await jn(t.paths.configPath,{...t.config,baseUrl:n,savedAt:t.now()},t),h({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 vo(e,t,n){let i=e[0]??p(t.method)??"email",r=p(t.email);if(!r&&!t.json)try{r=await n.promptText("Enter your email address: ")}catch{return y("auth recover requires --email when interactive prompts are unavailable.",!1)}if(r=b(r,"auth recover requires --email."),i==="complete"){let c=p(t.code);if(!c&&!t.json)try{c=await n.promptText("Enter the recovery code: ")}catch{return y("auth recover complete requires --code when interactive prompts are unavailable.",!1)}return c=b(c,"auth recover complete requires --code."),await hi(r,c,t,n)}let s=await v(n,"/api/v1/identity/recover/start",{method:"POST",headers:A(),body:JSON.stringify({email:r,method:i})}),o=ln(s);if(t.json)return h(o,"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 h(o,`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 ${r} --code <code>\`.`,!1,n)}return a?await hi(r,a,t,n):h(o,`If this email can continue, instructions have been sent. When you have a code, run \`skills-layer auth recover complete --email ${r} --code <code>\`.`,!1,n)}async function hi(e,t,n,i){let r=await v(i,"/api/v1/identity/recover/complete",{method:"POST",headers:A(),body:JSON.stringify({email:e,code:t})});if(n.json){let s=l(r,"apiKey");return s?(await Oe(i,s,{expectedEmail:e,knownEmail:l(r,"email")??e,knownRole:l(r,"role")??"user",knownRoles:se(r,"roles"),knownUserId:l(r,"userId")}),h(W({...r,loggedIn:!0}),"Recovery complete.",!0,i)):h(W({...r,email:e,loggedIn:!1}),"Recovery complete.",!0,i)}return await gt(e,r,n,i,`Recovered access for ${e}.`)}async function So(e,t,n){let i=e[0],r=1;if(i==="providers")return await R("/api/v1/identity/social/providers",t,n,"Identity providers loaded.");if(i==="start"){let s=p(t.provider);if(!s&&!t.json)try{s=await n.promptSelect("Choose identity provider:",hn)}catch{return y("identity start requires --provider when interactive selection is unavailable.",!1)}s=b(s,"identity start requires --provider.");let o=await v(n,"/api/v1/identity/social/start",{method:"POST",headers:A(n.apiKey),body:JSON.stringify({provider:s,mode:p(t.mode)??"login"})});return t.json?h(o,"Social auth started.",!0,n):await $n(s,o,t,n,"login")}if(i==="status"){let s=p(t.state)??e[r];return s?await R(`/api/v1/identity/social/status/${encodeURIComponent(s)}`,t,n,"Social auth status loaded."):y("identity status requires --state.",t.json)}if(i==="complete"){let s=b(t.provider,"identity complete requires --provider."),o=b(t.state,"identity complete requires --state."),a=b(t.code,"identity complete requires --code."),c=await v(n,"/api/v1/identity/social/complete",{method:"POST",headers:A(n.apiKey),body:JSON.stringify({provider:s,state:o,code:a})});return await Dl(c,n),h(W(c),"Social auth complete.",t.json,n)}if(i==="list")return await R("/api/v1/me/linked-identities",t,n,"Linked identities loaded.",{authenticated:!0});if(i==="unlink"){let s=b(t.provider??e[r],"identity unlink requires a provider."),o=await v(n,`/api/v1/me/linked-identities/${encodeURIComponent(s)}`,{method:"DELETE",headers:M(n.apiKey,n.authBlockedMessage)});return h(o,"Identity unlinked.",t.json,n)}return y(`Unknown identity command "${i??""}".`,t.json)}async function Po(e,t,n){let i=e[0];if(!i)return y("api-key requires create, list, or revoke.",t.json);if(i==="list")return await R("/api/v1/me/api-keys",t,n,"API keys loaded.",{authenticated:!0});if(i==="create"){let r=p(t.name),s=Oc(t.scope);if(!r)return y("api-key create requires --name.",t.json);if(s.length===0)return y("api-key create requires at least one --scope.",t.json);let o=Eo("api-key.create",t.expires,t);if(o)return o;let a=await v(n,"/api/v1/me/api-keys",{method:"POST",headers:{"content-type":"application/json",...M(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:r,scopes:s,...p(t.expires)?{expiresIn:p(t.expires)}:{}})});return h(W(a),"Automation API key created. The full key was sent to your verified email. Run `skills-layer api-key list` to manage keys.",t.json,n)}if(i==="rotate")return y(`api-key rotate is not part of normal login.
|
|
840
1122
|
|
|
841
1123
|
For CLI access:
|
|
842
1124
|
skills-layer login
|
|
@@ -846,26 +1128,26 @@ For automation:
|
|
|
846
1128
|
|
|
847
1129
|
To remove an old key:
|
|
848
1130
|
skills-layer api-key list
|
|
849
|
-
skills-layer api-key revoke --key-id <key-id>`,t.json);if(i==="revoke"){let r=t.keyId??e[1];if(!r)return
|
|
1131
|
+
skills-layer api-key revoke --key-id <key-id>`,t.json);if(i==="revoke"){let r=t.keyId??e[1];if(!r)return y(`api-key revoke needs a key id.
|
|
850
1132
|
|
|
851
1133
|
Run:
|
|
852
1134
|
skills-layer api-key list
|
|
853
|
-
skills-layer api-key revoke --key-id <key-id>`,t.json);let s=String(r),o=await
|
|
854
|
-
`);return`skills-layer-cli:mcp-token:${Dt("sha256").update(t).digest("base64url").slice(0,32)}`}async function It(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 V(t.paths.mcpConfigPath),i=n?l(n,"baseUrl"):void 0,r=n?l(n,"clientId")??"codex":"codex";if(!e.withMcp&&i===t.baseUrl&&r)return{data:{status:"mcp_already_configured",configured:!0,clientId:r,mcpUrl:n?l(n,"mcpUrl")??`${t.baseUrl}/mcp`:`${t.baseUrl}/mcp`},message:"MCP is already configured for this machine."};if(!e.withMcp&&!e.json){let a=await V(t.paths.mcpPreferencePath),c=a?l(a,"baseUrl"):void 0,u=a?l(a,"clientId")??"codex":void 0;if((a?l(a,"choice"):void 0)==="not_now"&&c===t.baseUrl&&u==="codex")return{data:{status:"mcp_skipped_previously",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup was skipped previously. Run `skills-layer mcp setup` when you want AI-tool access."}}let s=e.withMcp===!0;if(!s&&!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(s=a==="yes",a==="no")return await D(t.paths.mcpPreferencePath,{version:1,choice:"not_now",baseUrl:t.baseUrl,clientId:"codex",savedAt:t.now()}),{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(!s)return{};let o=await Qt(e,t);return H(o)?o:{data:o,message:"MCP configuration written for this machine. Open a fresh agent session so your AI tools can load it."}}async function Ls(e,t,n){let i=e.join(" ").trim()||g(t.search)||"",r=new URLSearchParams;i&&r.set("query",i),N(r,"agent",t.agent),N(r,"capability",t.capability),N(r,"trust",t.trust),N(r,"runtime-risk",t.runtimeRisk),N(r,"security-capability",t.securityCapability);let s=await b(n,`/api/v1/search${se(r)}`);if(t.install!==void 0){let o=g(t.install);if(!o){if(t.json)return k("search --install requires an explicit skill slug in the public CLI package.",!0);let c=Fe(s);if(c.length===0)return k("Search results do not include any installable skills. Run search again with a broader query.",!1);if(c.length===1)o=c[0].value;else try{o=await n.promptSelect("Select a search result to install:",c)}catch{return k("No search result was selected for install.",!1)}}let a=Al(s);return a.includes(o)?await Xt([o],t,n):k(a.length===0?`Search results do not include "${o}". Run search again with a matching query first.`:`Search results do not include "${o}". Run search again with a matching query or choose one of: ${a.join(", ")}.`,t.json)}return f(s,"Search complete.",t.json,n)}async function Ts(e,t,n){let i=new URLSearchParams;return N(i,"limit",t.limit),N(i,"search",t.search),N(i,"sort",t.sort),await C(`/api/v1/${e}${se(i)}`,t,n,`${ct(e)} skills loaded.`)}async function Us(e,t,n){let i=e.join(" ").trim();if(!i)return k("recommend requires a task.",t.json);let r=new URLSearchParams({task:i});return N(r,"limit",t.limit),await C(`/api/v1/recommend?${r.toString()}`,t,n,"Recommendations loaded.")}async function Bs(e,t,n){if(e.length<2)return k("compare requires two or more skill slugs.",t.json);let i=new URLSearchParams({slugs:e.join(",")}),r=await b(n,`/api/v1/skills/compare?${i.toString()}`);return t.json?f(r,"Comparison loaded.",!0,n):{exitCode:0,stdout:za(r,"Comparison loaded.",Y(n),t.verbose),stderr:""}}async function Ms(e,t,n){let i=v(e[0],"show requires a skill slug.");return await C(`/api/v1/skills/${encodeURIComponent(i)}`,t,n,"Skill loaded.")}async function Ns(e,t,n){let i=v(e[0],"trust requires a skill slug."),r=new URLSearchParams;N(r,"format",t.format),N(r,"version",t.version);let s=await b(n,`/api/v1/skills/${encodeURIComponent(i)}/trust${se(r)}`);return g(t.format)?.toLowerCase()==="sarif"&&!t.json?{exitCode:0,stdout:_o(s,i,n),stderr:""}:f(s,"Trust report loaded.",t.json,n)}async function Os(e,t,n){let i=We(e[0],e[1]);if(i)return Vn(i,[e[0],e[1]].filter(Boolean).join(" "),t,n);let r=e[0];if(!r)return{exitCode:0,stdout:Ee,stderr:""};if(r==="full")return{exitCode:0,stdout:Ee,stderr:""};if(r==="topic"){let s=We(e[1]);if(s)return Vn(s,e[1]??"overview",t,n);let o=new URLSearchParams;return e[1]&&o.set("topic",e[1]),await C(`/api/v1/help${se(o)}`,t,n,"Help topic loaded.")}if(r==="standards")return await C("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let s=await b(n,"/api/v1/marketplace/status");return t.json?f(s,"Marketplace status loaded.",!0,n):f(Xa(s),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let s=await b(n,"/api/v1/capabilities");return f(tl(s),"Edition capabilities loaded.",t.json,n)}if(r==="schema-plan")return k("help schema-plan is not included in the public npm CLI.",t.json);if(r==="optimize-tokens"){let s=v(t.text,"help optimize-tokens requires --text."),o=nl(t.maxCharacters,t.json);if(H(o))return o;let a=await b(n,"/api/v1/optimize-tokens",{method:"POST",headers:_(n.apiKey),body:JSON.stringify({text:s,...o?{maxCharacters:o}:{}})});return f(a,"Token optimization complete.",t.json,n)}return k(`Unknown help command "${r}".`,t.json)}function Vn(e,t,n,i){return n.json?f({status:"ok",topic:t,content:e},"Help topic loaded.",!0,i):{exitCode:0,stdout:e,stderr:""}}async function Fs(e,t,n){let i=v(e[0]??t.path,"validate requires a file or directory."),s={files:await ot(W(n.cwd,i)),sourceIntakeContext:g(t.sourceIntakeContext),publicationStatus:g(t.publicationStatus),dependencyAuditStatus:g(t.dependencyAuditStatus),category:g(t.category),discloseSource:!!t.discloseSource,allowFindingsFeatured:!!t.allowFindingsFeatured},o=await b(n,"/api/v1/validation/preview",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(j(s))});return t.json?f(o,"Validation complete.",!0,n):{exitCode:0,stdout:il(o,i,n),stderr:""}}async function qs(e,t,n){let i=v(e[0]??t.path,"preview-trigger requires a file or directory."),r=await ot(W(n.cwd,i)),s=await b(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:_(n.apiKey),body:JSON.stringify({files:r,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?f(s,"Trigger preview complete.",!0,n):{exitCode:0,stdout:rl(s,i,n),stderr:""}}async function Ks(e,t,n){let i=e[0];if(i==="init")return await Gs(e.slice(1),t,n);if(i==="rules")return await C("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(i==="submissions")return await C("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(i==="status"){let r=v(e[1],"creator status requires a skill slug.");try{return await C(`/api/v1/me/submissions/${encodeURIComponent(r)}`,t,n,"Submission status loaded.",{authenticated:!0})}catch(s){if(s instanceof E&&s.status===404)return zs(r,t);throw s}}if(i==="charge-status"){let r=v(e[1],"creator charge-status requires a charge id.");return await C(`/api/v1/me/private-skill-charges/${encodeURIComponent(r)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(i==="submit")return await Yn(e.slice(1),t,n,!1);if(i==="submit-version")return await Yn(e.slice(1),t,n,!0);if(i==="check-slug"){let r=v(e[1],"creator check-slug requires a slug.");return await Js(r,t,n)}if(i==="rename"){let r=v(e[1],"creator rename requires the current slug."),s=v(e[2],"creator rename requires the new slug.");return await Be(`/api/v1/me/submissions/${encodeURIComponent(r)}/slug`,{nextSkillSlug:s},t,n,"Skill renamed.")}if(i==="pricing")return await Ys(e,t,n);if(i==="update-listing"){let r=v(e[1],"creator update-listing requires a skill slug.");return await Zs(r,t,n)}if(i==="visibility"){let r=v(e[1],"creator visibility requires a skill slug."),s=await b(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/visibility`,{method:"PATCH",headers:_(n.apiKey),body:JSON.stringify(j({visibility:g(t.visibility)??e[2],dryRun:t.dryRun}))});return qo(s)?I(s,Ko(s,r),t.json,l(s,"reasonCode")??l(s,"status")):f(s,t.dryRun?"Visibility preview loaded.":"Visibility updated.",t.json,n)}if(i==="security-report"){let r=v(e[1],"creator security-report requires a skill slug."),s=new URLSearchParams;N(s,"format",t.format),N(s,"version",t.version),N(s,"versionId",t.versionId);let o=await b(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust${se(s)}`,{headers:M(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?f(o,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:wl(o,r,n),stderr:""}}if(i==="rescan-security"){let r=v(e[1],"creator rescan-security requires a skill slug."),s=await b(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust/rescan`,{method:"POST",headers:_(n.apiKey),body:JSON.stringify(j(F(t,["version","versionId"])))});return t.json?f(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:vl(s,r,n),stderr:""}}if(i==="provenance"){let r=v(e[1],"creator provenance requires a skill slug.");return await C(`/api/v1/me/submissions/${encodeURIComponent(r)}/provenance`,t,n,"Provenance loaded.",{authenticated:!0})}if(i==="claim"||i==="verify"||i==="dispute")return await Qs(i,e,t,n);if(i==="issues"||i==="reviews"||i==="update-issue"||i==="moderate-review")return await ro(i,e,t,n);if(i==="analytics"){let r=v(e[1],"creator analytics requires a skill slug.");return await Xs(r,t,n)}return i==="earnings"?await C("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0}):i==="payout-profile"?await eo(t,n):i==="payout-link"?await to(t,n):i==="payouts"?await C("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0}):i==="withdraw"?await q("/api/v1/me/payouts/withdrawals",F(t,["amountCents","reason"]),t,n,"Withdrawal requested."):i==="source"?await so(e.slice(1),t,n):k(`Unknown creator command "${i??""}".`,t.json)}async function Gs(e,t,n){let i=g(t.skill)??e[0]??"my-skill",r=W(n.cwd,g(t.dir)??i),s=A(r,"SKILL.md"),o;try{o=Bn(g(t.type))}catch(y){return k(ue(y),t.json)}let a=g(t.category),c=await Ds(r);if((await ge(s)||c)&&!t.confirmed)return k(`Creator init target already exists at ${r}. Re-run with --confirm only if you want to overwrite ${s}.`,t.json);await Ne(r,{recursive:!0});let d=Mn({skillSlug:i,description:g(t.description)??"Describe what this skill helps an agent do.",skillType:o,category:a});for(let y of d)await ie(A(r,y.path),y.content);let p=j({status:"created",path:s,skillSlug:i,skillType:o,category:a,fileCount:d.length});return t.json?f(p,`Created ${s}.`,!0,n):{exitCode:0,stdout:dl(p,r,s,n),stderr:""}}async function ge(e){try{return await wi(e),!0}catch{return!1}}async function Ds(e){try{return(await bi(e)).length>0}catch{return await ge(e)}}async function Yn(e,t,n,i){let r=v(e[0]??t.path,`creator ${i?"submit-version":"submit"} requires a path.`),s=await ot(W(n.cwd,r));if(!i&&!t.dryRun){let y=await Hs(s,t,n);if(y)return y}let o=j({files:s,version:g(t.version),dryRun:t.dryRun,allowFindingsFeatured:t.allowFindingsFeatured,pricing:g(t.priceCents)?{priceCents:Number(g(t.priceCents))}:void 0,...F(t,["displayName","skillType","category","visibility","source","skill"])}),a=g(t.skill)??e[1],c=i&&a?`/api/v1/me/submissions/${encodeURIComponent(a)}/versions`:"/api/v1/me/submissions",u=await b(n,c,{method:"POST",headers:_(n.apiKey),body:JSON.stringify(o)});if(t.json||u.status!=="checkout_required"||typeof u.checkoutUrl!="string"||typeof u.chargeId!="string")return f(u,i?"Version submitted.":"Submission uploaded.",t.json,n);n.emitInfo("Opening payment setup for skill submission. Complete the payment in your browser, then come back here."),await n.openUrl(u.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${u.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let p=await Ia(u.chargeId,n);return H(p)?p:p.status!=="submitted"?f({...u,chargeStatus:p.status},`Payment is still ${p.status}. You can rerun \`skills-layer creator charge-status ${u.chargeId}\` to continue tracking it.`,t.json,n):f(p,i?"Version submitted.":"Submission uploaded.",t.json,n)}async function Hs(e,t,n){let i=g(t.skill)??Ws(e);if(!i)return null;let r;try{r=await b(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(i)}`,{headers:M(n.apiKey,n.authBlockedMessage)})}catch(s){if(s instanceof E&&s.status===404)return $i(i,t);throw s}if(r.available===!1||l(r,"reasonCode")==="unavailable"||l(r,"reasonCode")==="reserved"){let s=l(r,"assignedSlug"),o=j({status:"duplicate_candidate",reasonCode:l(r,"reasonCode")??"slug_unavailable",requestedSlug:i,assignedSlug:s,nextAction:"creator.status",nextStep:`Run \`skills-layer creator status ${i}\`, \`skills-layer creator submissions\`, or submit a new version of the existing skill instead of creating a duplicate listing.`});return I(o,`A public skill slug "${i}" already exists or is not available. Run \`skills-layer creator status ${i}\`, check your creator submissions, or submit a new version instead of creating a duplicate listing.`,t.json,l(o,"reasonCode"))}return null}async function Js(e,t,n){try{return await C(`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,t,n,"Slug status loaded.",{authenticated:!0})}catch(i){if(i instanceof E&&i.status===404)return $i(e,t);throw i}}function $i(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 I(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 zs(e,t){return I({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 Ws(e){let t=e.find(i=>i.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(i=>i.match(/^name\s*:\s*(?<name>.+?)\s*$/u)?.groups?.name?.trim().replace(/^["']|["']$/gu,"")).find(i=>!!i);return Vs(n??K(X(t.path)))}function Vs(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function Ys(e,t,n){let i=v(e[1],"creator pricing requires a skill slug."),r=new URLSearchParams;if(N(r,"version",t.version),!t.priceCents)return await C(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${se(r)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=Number(g(t.priceCents)),o=await b(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${se(r)}`,{headers:M(n.apiKey,n.authBlockedMessage)}),a=ce(o,"priceCents")??0;if(s>a){let c=j({status:"pending_approval",reasonCode:a===0?"paid_activation_requires_approval":"price_increase_requires_approval",skillSlug:i,version:l(o,"version"),currentPriceCents:a,requestedPriceCents:s,currency:l(o,"currency")??"gbp",nextStep:"Pricing changes that increase buyer-facing cost require approval. Keep the current price for now, then retry after approval is available."});return f(c,"Pricing change requires approval before it can affect buyers.",t.json,n)}return await Be(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing`,{priceCents:s,version:g(t.version)},t,n,"Pricing updated.")}async function Zs(e,t,n){try{return await Be(`/api/v1/me/submissions/${encodeURIComponent(e)}`,F(t,["displayName","summary","description","category","skillType","license","listingStatus"]),t,n,"Listing updated.")}catch(i){if(i instanceof E&&i.status===404){let r={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 I(r,`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 Qs(e,t,n,i){let r=v(t[1],`creator ${e} requires a skill slug.`);try{if(e==="claim")return await q(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/claim`,F(n,["requestedRole","message"]),n,i,"Ownership claim submitted.");if(e==="verify"){let s=v(n.claimId,"creator verify requires --claim-id.");return await q(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/verify`,{claimId:s},n,i,"Ownership claim verified.")}return await q(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/dispute`,F(n,["message"]),n,i,"Ownership dispute submitted.")}catch(s){if(s instanceof E&&s.status===404){let o={status:"ownership_action_unavailable",reasonCode:e==="claim"?"skill_not_found_or_not_claimable":"ownership_claim_not_found",skillSlug:r,requestedRole:g(n.requestedRole),nextAction:e==="claim"?"search":"creator.claim",nextStep:e==="claim"?`Run \`skills-layer search ${r}\`, \`skills-layer show ${r}\`, or submit/source-install the skill before claiming it.`:`Run \`skills-layer creator claim ${r}\` to start a new claim if the skill is claimable.`};return I(o,e==="claim"?`No claimable skill was found for ${r}. Search or show the skill first, then claim it only when it exists and is claimable.`:`No matching ownership claim was found for ${r}. Start a new claim if the skill is claimable.`,n.json,l(o,"reasonCode")??"ownership_action_unavailable")}throw s}}async function Xs(e,t,n){try{return await C(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(i){if(i instanceof E&&i.status===404){let r={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 I(r,`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 i}}async function eo(e,t){let n=await b(t,"/api/v1/me/payout-profile",{headers:M(t.apiKey,t.authBlockedMessage)});return f(n,"Creator payout profile loaded.",e.json,t)}async function to(e,t){let n=no(g(e.mode));if(e.mode&&n===null)return k("creator payout-link --mode must be account_onboarding|account_update|onboarding|update.",e.json);let i;try{i=await b(t,"/api/v1/me/payout-profile/link",{method:"POST",headers:_(t.apiKey),body:JSON.stringify(n?{mode:n}:{})})}catch(s){if(s instanceof E&&io(s))return I({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 s}let r=Ea(i);return r&&!e.json&&e.showUrl!==!0&&(t.emitInfo("Opening payout setup in your browser. Finish the flow there, then come back here."),await t.openUrl(r)||t.emitInfo(`Open this payout setup URL manually to continue: ${r}`)),f(i,"Payout setup link created.",e.json,t)}function no(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 io(e){let t=`${e.message} ${l(e.details??{},"error")??""}`.toLowerCase();return t.includes("account_update")&&t.includes("account_onboarding")&&t.includes("account link")}async function ro(e,t,n,i){let r=v(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await C(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await C(`/api/v1/me/library/${encodeURIComponent(r)}/reviews`,n,i,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let o=v(n.issueId,"creator update-issue requires --issue-id.");return await Be(`/api/v1/me/library/${encodeURIComponent(r)}/issues/${encodeURIComponent(o)}`,F(n,["status","fixedVersion","note"]),n,i,"Issue updated.")}let s=v(n.reviewId,"creator moderate-review requires --review-id.");return await Be(`/api/v1/me/library/${encodeURIComponent(r)}/reviews/${encodeURIComponent(s)}`,F(n,["status","reason"]),n,i,"Review updated.")}async function so(e,t,n){let i=e[0],r=v(e[1],`creator source ${i??""} requires a source connection id.`),s=g(t.skill)??e[2];if(i==="prepare")return await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/prepare`,j({...F(t,["skill","source","version","displayName","skillType","category","priceCents","visibility"]),source:g(t.source)??e[2]}),t,n,"Source release prepared.");if(i==="publish-request"){let o=t.approvalRequestId.length>0?t.approvalRequestId:g(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/publish-request`,j({skillSlug:s,approvalRequestIds:o,version:g(t.version),...F(t,["visibility","priceCents","license","discloseSource"])}),t,n,"Source publish requested.")}if(i==="release-status"){let o=new URLSearchParams;return s&&o.set("skill",s),await C(`/api/v1/me/source-connections/${encodeURIComponent(r)}/release-status${se(o)}`,t,n,"Source release status loaded.",{authenticated:!0})}return k(`Unknown creator source command "${i??""}".`,t.json)}async function Xt(e,t,n){let i=g(t.source);if(i){let c=g(t.skill),u=await Nt(i,n.cwd);if(u)return await Zn(i,u,c,t,n);let d=t.list||t.dryRun||!c&&!t.json&&!t.all,p=await Ye(n,i,{source:i,skillSlug:c,listOnly:d},t);if(p.kind==="failure")return p.result;let y=p.inspection;if(t.list)return f(y,"Source skills loaded.",t.json,n);let m=Tt(i,y,t);if(m)return m;let h=await Et({source:i,inspection:y,requestedSkillSlug:c,mode:"install",flags:t,backend:n});if(h.kind==="failure")return h.result;if(t.dryRun)return f(Lt(i,y,h.skillSlug,t),"Source install preview ready.",t.json,n);let w=Qn(t,n),P;try{P=await b(n,w,{method:"POST",headers:Xn(t,n),body:JSON.stringify(ti({source:i},h.skillSlug,t))})}catch(B){if(B instanceof E)return ni(i,B,t);throw B}let x=await Ct(n,P);return await tt(n,x,h.skillSlug??l(x,"skillSlug")??i),et(x,ei(t),t.json,n)}let r=v(e[0]??t.install,"install requires a skill slug or --source.");if(Ll(r)){let c=await Nt(r,n.cwd);if(c)return await Zn(r,c,g(t.skill),t,n);let u=g(t.skill),d;if(t.list){let h=await Ye(n,r,{source:r,listOnly:!0},t);return h.kind==="failure"?h.result:f(h.inspection,"Source skills loaded.",t.json,n)}if(!u&&!t.json&&!t.all){let h=await Ye(n,r,{source:r,listOnly:!0},t);if(h.kind==="failure")return h.result;let w=h.inspection;d=w;let P=Tt(r,w,t);if(P)return P;let x=await Et({source:r,inspection:w,requestedSkillSlug:u,mode:"install",flags:t,backend:n});if(x.kind==="failure")return x.result;u=x.skillSlug}if(t.dryRun){if(!d){let h=await Ye(n,r,{source:r,listOnly:!0},t);if(h.kind==="failure")return h.result;d=h.inspection}return f(Lt(r,d,u,t),"Source install preview ready.",t.json,n)}let p=Qn(t,n),y;try{y=await b(n,p,{method:"POST",headers:Xn(t,n),body:JSON.stringify(ti({source:r},u,t))})}catch(h){if(h instanceof E)return ni(r,h,t);throw h}let m=await Ct(n,y);return await tt(n,m,u??l(m,"skillSlug")??K(r)),et(m,ei(t),t.json,n)}if(g(t.scope)==="workspace"){let c=v(t.workspace,"workspace installs require --workspace <workspace-id>."),u=await b(n,`/api/v1/workspaces/${encodeURIComponent(c)}/skills`,{method:"POST",headers:_(n.apiKey),body:JSON.stringify(j({skillSlug:r,version:g(t.version),dryRun:t.dryRun}))});return t.dryRun?Li(u,"Workspace install preview ready.",t,n):f(u,"Workspace deployment requested.",t.json,n)}let s=await b(n,"/api/v1/install",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(j({skillSlug:r,version:g(t.version),scope:g(t.scope),agent:g(t.agent),dryRun:t.dryRun}))});if(t.dryRun)return Ro(s,t,n);let o=await Ct(n,s),a=await oo(n,o,r,t);return H(a)?a:(await tt(n,a,r),et(a,"Skill installed.",t.json,n))}async function oo(e,t,n,i){if(Array.isArray(t.materializedWrites)&&t.materializedWrites.length>0)return t;let r=ao(e,t,n,i);if(r.status==="skip")return t;if(r.status==="failure")return I({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:r.skillSlug,nextStep:r.nextStep},r.message,i.json,"materialization_target_invalid");let s=await lo(e,t,r.skillSlug,r.version),o=await _i({backend:e,exportResult:s,flags:i,skillSlug:r.skillSlug});if(H(o))return o;let a=await po({backend:e,skillSlug:r.skillSlug,version:r.version??l(s,"version")??"latest",scope:r.scope,agent:r.agent,skillsPath:r.skillsPath,bytes:o.bytes,files:o.files,archiveSha256:o.archiveSha256});return{...t,...co(s),archiveSha256:o.archiveSha256,archiveHashFormat:o.archiveHashFormat,scope:r.scope,agent:r.agent.id,targetAgent:r.agent.id,materializationPlan:{scope:r.scope,agent:r.agent.id},...a}}function ao(e,t,n,i){let r=S(t,"materializationPlan")??S(t,"installPlan"),s=g(i.scope)??l(t,"scope")??(r?l(r,"scope"):void 0);if(s!=="project"&&s!=="global")return{status:"skip"};let o=l(t,"skillSlug")??l(t,"slug")??n,a=g(i.agent)??l(t,"agent")??l(t,"targetAgent")??(r?l(r,"agent")??l(r,"targetAgent"):void 0)??Q(e.config?.lastSelectedAgent)??"codex",c=de(e.env,e.platform,e.cwd).find(d=>d.id===a);if(!c)return{status:"failure",skillSlug:o,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 u=s==="global"?c.targets.globalSkillsPath:c.targets.projectSkillsPath;return u?{status:"ok",scope:s,agent:c,skillsPath:u,skillSlug:o,version:l(t,"version")??l(t,"currentVersion")}:{status:"failure",skillSlug:o,message:`${c.displayName} does not expose a ${s} skills path on this machine.`,nextStep:"Retry with --scope project, or choose another agent from `skills-layer agents list`."}}async function lo(e,t,n,i){if(typeof t.downloadUrl=="string"&&typeof t.archiveSha256=="string")return t;let r=new URLSearchParams;return i&&r.set("version",i),await b(e,`/api/v1/me/library/${encodeURIComponent(n)}/export${se(r)}`,{headers:M(e.apiKey,e.authBlockedMessage)})}function co(e){return j({version:l(e,"version"),storageKey:l(e,"storageKey"),expiresAt:l(e,"expiresAt")})}async function _i(e){let t=l(e.exportResult,"downloadUrl");if(!t)return I({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 n=await e.backend.fetchFn(uo(e.backend.baseUrl,t));if(!n.ok)throw new E(n.status,`Unable to download exported bundle (${n.status}).`);let i=new Uint8Array(await n.arrayBuffer()),r=go(i),s=l(e.exportResult,"archiveSha256")??n.headers.get("x-skills-layer-archive-sha256")?.trim()??void 0;return s&&r.archiveSha256!==s?I({status:"download_integrity_failed",reasonCode:"download_hash_mismatch",skillSlug:e.skillSlug,version:l(e.exportResult,"version"),expectedArchiveSha256:s,observedArchiveSha256:r.archiveSha256,archiveHashFormat:r.format,nextStep:"Retry after the catalog artifact is refreshed, or contact Skills Layer support if this repeats."},`Downloaded ${e.skillSlug} did not match the catalog artifact hash.`,e.flags.json,"download_hash_mismatch"):r.files.length===0?I({status:"download_integrity_failed",reasonCode:"download_bundle_empty",skillSlug:e.skillSlug,archiveHashFormat:r.format,nextStep:"Retry after the catalog artifact is refreshed."},`Downloaded ${e.skillSlug} did not contain any skill files.`,e.flags.json,"download_bundle_empty"):{status:"ok",bytes:i,files:r.files,archiveSha256:r.archiveSha256,archiveBytesSha256:r.archiveBytesSha256,archiveHashFormat:r.format}}function uo(e,t){return/^https?:\/\//iu.test(t)?t:`${ne(e)}${t.startsWith("/")?"":"/"}${t}`}function go(e){let t=Dt("sha256").update(e).digest("hex"),n=An(e);return n?{archiveSha256:In(n),archiveBytesSha256:t,format:"bundle_archive",files:n}:{archiveSha256:t,archiveBytesSha256:t,format:"raw",files:[]}}async function po(e){let t=e.backend.platform==="win32"?Se:zt,n=t.join(e.backend.paths.bundlesDir,e.skillSlug,e.version,"bundle.zip"),i=t.join(e.skillsPath,e.skillSlug),r=t.join(i,e.version,"bundle.zip"),s=[];await Kt(n,e.bytes),await Ht(i,{recursive:!0,force:!0}),await Kt(r,e.bytes),s.push({path:nt(e.backend.cwd,r),bytes:e.bytes.byteLength});for(let o of e.files){let a=t.join(i,...mo(o.path)),c=o.content??"";if(await ie(a,c),s.push({path:nt(e.backend.cwd,a),bytes:new TextEncoder().encode(c).length}),K(o.path).toLowerCase()==="skill.md"){let u=await an({backend:e.backend,skillSlug:e.skillSlug,version:e.version,skillDocumentPath:a,skillDocumentContent:c});s.push(u)}}return{bundlePath:n,materializedPath:r,materializedSkillRoot:i,archiveSha256:e.archiveSha256,materializedWrites:s}}function mo(e){let n=e.replaceAll("\\","/").replace(/^\/+/u,"").trim().split("/").filter(i=>i.length>0);if(n.length===0||n.some(i=>i==="."||i===".."))throw new Error(`Unsafe bundle path "${e}".`);return n}async function Zn(e,t,n,i,r){let s=g(i.visibility)??"private";if(s!=="private")return I({status:"local_install_visibility_not_allowed",reasonCode:"local_install_visibility_not_allowed",source:e,requestedVisibility:s,nextStep:`Use \`skills-layer creator submit ${e} --visibility ${s} --dry-run\` when you want to submit a local skill with non-private visibility.`},`Local path install creates a private Cloud skill by default. Use creator submit when you want ${s} visibility.`,i.json,"local_install_visibility_not_allowed");let o=fo(e,t,n);if(i.list)return f(o,"Local source skills loaded.",i.json,r);let a=Tt(e,o,i);if(a)return a;let c=await Et({source:e,inspection:o,requestedSkillSlug:n,mode:"install",flags:i,backend:r});if(c.kind==="failure")return c.result;let u=c.skillSlug??Fe(o)[0]?.value??Ai(e);if(i.dryRun)return f({...Lt(e,o,u,i),installKind:"local_private",publicationStatus:"none",catalogRecord:"not_created",nextStep:`Re-run without --dry-run to install ${u} locally. Use \`skills-layer creator submit ${e} --visibility private --dry-run\` when you want a private creator submission.`},"Local private install preview ready.",i.json,r);let d=await b(r,"/api/v1/me/submissions",{method:"POST",headers:{"content-type":"application/json",...M(r.apiKey,r.authBlockedMessage)},body:JSON.stringify(j({files:t.files,version:g(i.version),visibility:"private",category:g(i.category),displayName:g(i.displayName),skillType:g(i.skillType),sourceMetadata:t.sourceMetadata}))}),p=await ko({backend:r,source:e,upload:t,skillSlug:l(d,"skillSlug")??u,flags:i,submitted:d});return await tt(r,p,u),et(p,"Private Cloud skill installed.",i.json,r)}function fo(e,t,n){let i=ho(t.files),r=n?i.find(s=>s.skillSlug===n)??null:i.length===1?i[0]??null:null;return{status:"ok",source:t.sourceMetadata,selectedSkill:r,results:i,issues:[],sourceInstallSupported:!0,sourceInstallMode:"local_private",publicationStatus:"none",originalSource:e}}function ho(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=X(t.path).replaceAll("\\","/"),i=n==="."?".":n,r=ji(t.content??"")??Ai(i==="."?t.path:i),s=yo(t.content??"");return{skillSlug:r,name:r,...s?{description:s}:{},relativeSkillRoot:i,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function ji(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function yo(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function Ai(e){return(e.replaceAll("\\","/").replace(/\/+$/u,"").split("/").filter(Boolean).at(-1)??"local-skill").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"local-skill"}async function ko(e){let t=wo(e.backend,e.flags);if(t.status==="failure")throw new Error(t.message);let n=e.upload.files.map(r=>({path:A(t.skillsPath,e.skillSlug,Vi(r.path)),content:r.content??""})),i=[];for(let r of n)if(await ie(r.path,r.content),i.push({path:nt(e.backend.cwd,r.path),bytes:new TextEncoder().encode(r.content).length}),K(r.path).toLowerCase()==="skill.md"){let s=await an({backend:e.backend,skillSlug:e.skillSlug,version:l(e.submitted,"version")??g(e.flags.version)??"private",skillDocumentPath:r.path,skillDocumentContent:r.content});i.push(s)}return{...e.submitted,status:"installed",cloudStatus:l(e.submitted,"status")??"submitted",installKind:"cloud_private",source:e.source,sourceKind:"local",skillSlug:e.skillSlug,version:l(e.submitted,"version")??g(e.flags.version)??"private",scope:t.scope,agent:t.agent,visibility:"private",publicationStatus:"private",catalogRecord:"private",privacy:{publication:"private",catalogRecord:"private",message:"This local install was saved as a private Cloud skill and did not create a public catalog record."},materializationPlan:{scope:t.scope,agent:t.agent},materializedWrites:i}}function wo(e,t){let n=g(t.scope)??"project";if(!["local","project","global"].includes(n))return{status:"failure",message:"Local private installs support --scope local, project, or global. Use `skills-layer creator submit <path> --visibility private` for private creator workflows."};let i=g(t.agent)??Q(e.config?.lastSelectedAgent)??"codex",r=de(e.env,e.platform,e.cwd).find(o=>o.id===i);if(!r)return{status:"failure",message:`Unsupported agent "${i}". Run \`skills-layer agents list\` to choose a supported local install target.`};let s=n==="global"?r.targets.globalSkillsPath:r.targets.projectSkillsPath;return s?{status:"ok",scope:n,agent:r.id,skillsPath:s}:{status:"failure",message:`${r.displayName} does not expose a ${n} skills path on this machine.`}}function nt(e,t){let n=Te(e,t);return n&&!n.startsWith("..")&&!Se.isAbsolute(n)?n.split("\\").join("/"):t}function en(e){return g(e.visibility)==="public"?"public":"private"}function Qn(e,t){return en(e)==="public"&&!t.apiKey?"/api/v1/source-imports":"/api/v1/me/source-installs"}function Xn(e,t){return{"content-type":"application/json",...en(e)==="private"?M(t.apiKey,t.authBlockedMessage):Ke(t.apiKey)}}function ei(e){return en(e)==="public"?"Public source install planned.":"Private source skill installed."}async function Et(e){if(e.requestedSkillSlug||e.flags.json||e.flags.all)return{kind:"selected",skillSlug:e.requestedSkillSlug};let t=Fe(e.inspection);if(t.length<=1)return{kind:"selected",skillSlug:t[0]?.value};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:k(`Source "${e.source}" exposes multiple skills. Re-run with --list or --skill <skill-slug>. Available skills: ${t.map(n=>n.value).join(", ")}.`,e.flags.json)}}}function Fe(e){let t=[e.results,e.skills,e.discoveredSkills,S(e,"source")?.results,S(e,"inspection")?.results],n=new Set,i=[];for(let r of t)if(Array.isArray(r))for(let s of r){let o=vo(s);!o||n.has(o.value)||(n.add(o.value),i.push(o))}return i}function vo(e){if(!R(e))return;let t=l(e,"skillSlug")??l(e,"slug")??l(e,"name");if(!t)return;let n=l(e,"displayName")??l(e,"title")??l(e,"name"),i=n&&n!==t?`${t} - ${n}`:t,r=S(e,"parsedSkill"),s=S(e,"frontmatter")??(r?S(r,"frontmatter"):void 0),o=l(e,"shortDescription")??l(e,"summary")??l(e,"description")??(s?l(s,"description"):void 0)??l(e,"relativeSkillRoot")??l(e,"path")??l(e,"discoveryRoute")??l(e,"sourceKind");return o?{value:t,label:i,description:o}:{value:t,label:i}}function ti(e,t,n){return j({...e,skillSlug:t,scope:g(n.scope),agent:g(n.agent),workspace:g(n.workspace),version:g(n.version),visibility:g(n.visibility)??"private",category:g(n.category),displayName:g(n.displayName),skillType:g(n.skillType),all:n.all,quarantine:n.quarantine,acceptCapability:n.acceptCapability})}function Lt(e,t,n,i){return j({status:"dry_run",source:e,selectedSkillSlug:n,all:i.all,scope:g(i.scope)??"local",agent:g(i.agent),workspace:g(i.workspace),quarantine:i.quarantine,acceptCapability:i.acceptCapability,candidates:Fe(t).map(r=>({skillSlug:r.value,name:r.label,description:r.description})),nextStep:i.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 Ye(e,t,n,i){try{return{kind:"ok",inspection:await b(e,"/api/v1/source-inspect",{method:"POST",headers:_(e.apiKey),body:JSON.stringify(j(n))})}}catch(r){if(r instanceof E)return{kind:"failure",result:Po(t,r,i)};throw r}}function Tt(e,t,n){if(Fe(t).length>0)return null;let r=bo(t);return I({status:"unsupported_source_layout",source:e,reasonCode:"source_no_discoverable_skills",issues:r,nextStep:"Run with --list to inspect the source, use a subfolder containing SKILL.md, or install from a Skills Layer-compatible source layout."},Co(e,r),n.json)}function bo(e){return(Array.isArray(e.issues)?e.issues:[]).filter(R).map(n=>({...l(n,"code")?{code:l(n,"code")}:{},...l(n,"message")?{message:l(n,"message")}:{},...l(n,"path")?{path:l(n,"path")}:{}}))}function Po(e,t,n){let i=t.details??{},r=l(i,"error")??t.message;if(Ii(t.status,r))return Ei(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return at(t,n.json);let o={status:"unsupported_source_layout",source:e,reasonCode:"source_not_inspectable",backendStatus:t.status,backendMessage:r,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return I(o,`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 ni(e,t,n){let i=t.details??{},r=l(i,"error")??t.message;if(Ii(t.status,r))return Ei(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return at(t,n.json);let o={status:"unsupported_source_layout",source:e,reasonCode:"source_not_installable",backendStatus:t.status,backendMessage:r,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return I(o,`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)}function Ii(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function Ei(e,t,n,i){let r=t.details??{},s=l(r,"error")??t.message,a=`skills-layer source connection start --provider ${So(e)} --source ${e} --visibility private --provenance-intent private_source_import`,c={status:"private_source_access_required",source:e,reasonCode:"private_source_access_required",backendStatus:t.status,backendMessage:s,nextStep:a};return I(c,`Cloud could not ${i} ${e} directly. If this is a private source, start a private source connection first:
|
|
855
|
-
${a}`,n.json,"private_source_access_required")}function
|
|
856
|
-
`)}function
|
|
857
|
-
`)}function
|
|
858
|
-
`)}function
|
|
859
|
-
`)}function
|
|
860
|
-
`)):(e.results.slice(0,
|
|
861
|
-
`))}function
|
|
862
|
-
`)}function
|
|
863
|
-
`)}function
|
|
864
|
-
Next step: ${o}`}async function Go(e,t,n){let i=await fe(n),r=e[0];if(!r){let a=Object.values(i.installs);return f({status:a.length>0?"restored":"no_op",results:a},`Restore checked ${a.length} local install record${a.length===1?"":"s"}.`,t.json,n)}let s=i.installs[r];if(!s)return I({status:"missing_record",reasonCode:"restore_record_not_found",skillSlug:r,record:null,nextAction:"installed",nextStep:`Run \`skills-layer installed\` to see local records, \`skills-layer sync\` to refresh status, or \`skills-layer search ${r}\` if you want to find a catalog/source replacement.`},`No restorable local install record was found for ${r}. Run \`skills-layer installed\`, \`skills-layer sync\`, or \`skills-layer search ${r}\` next.`,t.json,"restore_record_not_found");let o={status:"restored",skillSlug:r,record:s};return t.json?f(o,`Restore checked for ${r}.`,!0,n):{exitCode:0,stdout:Fo(r,s,n),stderr:""}}async function Do(e,t,n){let i=v(e[0],"check requires a skill slug.");return await C(`/api/v1/skills/${encodeURIComponent(i)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function Ho(e,t,n){let i=v(e[0]??t.source,"import requires a source."),r=await Nt(i,n.cwd),s=await b(n,"/api/v1/source-imports",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(j({...r??{source:i},quarantine:t.quarantine,skillSlug:g(t.skill),visibility:g(t.visibility)}))});return await D(n.paths.importsPath,{version:1,lastImport:s,savedAt:n.now()}),f(s,"Source import submitted.",t.json,n)}async function Jo(e,t,n){let i=e[0];if(i==="reference"&&e[1]==="resolve"){let r=v(e[2],"source reference resolve requires a reference.");return await C(`/api/v1/source-references/resolve?reference=${encodeURIComponent(r)}`,t,n,"Source reference resolved.")}return i==="connection"?await zo(e.slice(1),t,n):k(`Unknown source command "${e.join(" ")}".`,t.json)}async function zo(e,t,n){let i=e[0];if(i==="start")return await q("/api/v1/me/source-connections",F(t,["provider","source","skill","mode","visibility","priceCents","license","provenanceIntent","discloseSource"]),t,n,"Source connection started.");let r=v(e[1],`source connection ${i??""} requires a connection id.`);return i==="status"?await C(`/api/v1/me/source-connections/${encodeURIComponent(r)}`,t,n,"Source connection loaded.",{authenticated:!0}):i==="complete"?await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/complete`,F(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed."):i==="cancel"?await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/cancel`,{},t,n,"Source connection cancelled."):k(`Unknown source connection command "${i??""}".`,t.json)}async function Wo(e,t,n){if(e[0]!=="request")return k(`Unknown approval command "${e[0]??""}".`,t.json);let i=e[1],r=v(e[2],`approval request ${i??""} requires an approval id.`);return i==="status"?await C(`/api/v1/me/approvals/${encodeURIComponent(r)}`,t,n,"Approval status loaded.",{authenticated:!0}):i==="complete"?await q(`/api/v1/me/approvals/${encodeURIComponent(r)}/complete`,j({decision:g(t.decision),evidence:lt(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed."):k(`Unknown approval request command "${i??""}".`,t.json)}async function Vo(e,t,n){let i=e[0]??"list";if(i==="list")return await C("/api/v1/me/workspaces",t,n,"Workspaces loaded.",{authenticated:!0});if(i==="create")return await q("/api/v1/workspaces",{name:e.slice(1).join(" "),kind:g(t.kind)},t,n,"Workspace created.");let r=v(e[1],`workspace ${i} requires a workspace id.`);if(i==="skills")return await C(`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0});if(i==="deploy"){let s=v(e[2],"workspace deploy requires a skill slug."),o=await b(n,`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,{method:"POST",headers:_(n.apiKey),body:JSON.stringify(j({skillSlug:s,dryRun:t.dryRun}))});return t.dryRun?Li(o,"Workspace deployment preview ready.",t,n):f(o,"Workspace deployment requested.",t.json,n)}if(i==="remove"){let s=v(e[2],"workspace remove requires a skill slug.");return await st(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}`,{method:"DELETE",headers:M(n.apiKey,n.authBlockedMessage)},t,n,"Workspace skill removed.")}if(i==="guide"){let s=v(e[2],"workspace guide requires a skill slug.");try{return await C(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}catch(o){if(o instanceof E&&o.status===404)return Yo(r,s,t);throw o}}return k(`Unknown workspace command "${i}".`,t.json)}function Yo(e,t,n){let i={status:"deployment_not_found",reasonCode:"workspace_deployment_not_found",workspaceId:e,skillSlug:t,nextAction:"workspace.deploy",nextStep:`Run \`skills-layer workspace deploy ${e} ${t}\` first, then run \`skills-layer workspace guide ${e} ${t}\` after the deployment exists.`};return I(i,`Workspace deployment not found for ${t}. Run \`skills-layer workspace deploy ${e} ${t}\` first.`,n.json,"workspace_deployment_not_found")}async function Zo(e,t,n){let i=v(e[0],"buy requires a skill slug."),r=await b(n,"/api/v1/buy",{method:"POST",headers:_(n.apiKey),body:JSON.stringify({skillSlug:i,paymentMethod:g(t.paymentMethod)??"card"})});if(r.status==="already_owned")return f(r,`You already own ${i}. Run \`skills-layer install ${i}\` to install or update it.`,t.json,n);if(t.json||r.status!=="checkout_required"||typeof r.checkoutUrl!="string"||typeof r.purchaseId!="string")return f(r,`Purchase flow started for ${i}.`,t.json,n);n.emitInfo(`Opening checkout for ${i}. Complete the payment in your browser, then come back here.`),await n.openUrl(r.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${r.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let o=await Aa(r.purchaseId,n);return H(o)?o:o.status!=="succeeded"&&o.status!=="refund_requested"?f({...r,purchaseStatus:o.status},`Checkout is still ${o.status} for ${i}. You can rerun install after payment reconciliation completes.`,t.json,n):(n.emitInfo("Payment confirmed. Continuing with install."),await Xt([i],t,n))}async function Qo(e,t,n){let i=e[0]??"list";if(i==="list")return await C("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(i==="spending")return await C("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let r=v(e[1],`purchases ${i} requires a purchase id.`);return i==="invoice"?await C(`/api/v1/purchases/${encodeURIComponent(r)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0}):i==="refund-quote"?await C(`/api/v1/purchases/${encodeURIComponent(r)}/refund-quote`,t,n,"Refund quote loaded.",{authenticated:!0}):i==="refund"?await q(`/api/v1/purchases/${encodeURIComponent(r)}/refund`,F(t,["reason"]),t,n,"Refund requested."):k(`Unknown purchases command "${i}".`,t.json)}async function Xo(e,t,n){let i=e[0];if(i==="add"){let r=v(e[1],"library add requires a skill slug.");return await q("/api/v1/install",{skillSlug:r},t,n,"Skill added to library.")}return k(`Unknown library command "${i}".`,t.json)}async function ea(e,t,n){let i=v(e[0],"export requires a skill slug."),r=new URLSearchParams;N(r,"version",t.version);let s=await b(n,`/api/v1/me/library/${encodeURIComponent(i)}/export${se(r)}`,{headers:M(n.apiKey,n.authBlockedMessage)}),o=g(t.output);if(o){let a=await _i({backend:n,exportResult:s,flags:t,skillSlug:i});if(H(a))return a;let c=W(n.cwd,o);await Kt(c,a.bytes);let u={...s};return delete u.downloadUrl,f({...u,archiveSha256:a.archiveSha256,archiveSha256Meaning:"canonical_bundle_sha256",canonicalBundleSha256:a.archiveSha256,downloadedArchiveSha256:a.archiveBytesSha256,archiveHashFormat:a.archiveHashFormat,outputPath:c,downloaded:!0},`Exported ${i} to ${c}.`,t.json,n)}return f(s,o?`Exported ${i} to ${o}.`:"Export prepared.",t.json,n)}async function ii(e,t,n,i){let r=v(t[0],`${e==="add"?"add-review":"show-reviews"} requires a skill slug.`);return e==="show"?await C(`/api/v1/me/library/reviews?skillSlug=${encodeURIComponent(r)}`,n,i,"Reviews loaded.",{authenticated:!0}):await q(`/api/v1/me/library/${encodeURIComponent(r)}/review`,F(n,["rating","feedback"]),n,i,"Review added.")}async function ri(e,t,n,i){let r=v(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);return e==="show"?await C(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0}):await q(`/api/v1/me/library/${encodeURIComponent(r)}/report-issue`,F(n,["issueType","message"]),n,i,"Issue reported.")}async function ta(e,t,n){let i=e[0];if(i==="hook"){let r=e[1];return r==="install"?await Ut(t,n):r==="status"?await sa(t,n):k(`Unknown guardian hook command "${r??""}".`,t.json)}if(i==="enable")return e[1]||t.skill?await St("enforce",e,t,n):await Ut(t,n);if(i==="disable")return await St("disabled",e,t,n);if(i==="enable-warnings-only")return await St("warning_only",e,t,n);if(i==="status")return await ia(e,t,n);if(i==="exec")return await na(e,t,n);if(i==="check"){let r=v(e[1]??t.skill,"guardian check requires a skill slug."),s=gi(t,"check"),o=t.grantJson.map(h=>gn(h,"grant-json")),a=Il(t.cloudTrustLedger);if(a.status==="invalid")return k(a.message,t.json);let c=Bt(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(c.status==="invalid")return k(c.message,t.json);let u=await Bi({skillSlug:r,version:g(t.version),action:s,flags:t,backend:n,telemetryMode:c.mode});if(u.status!=="ok")return u.result;let d=u.context.installedPath,p=g(t.version)??u.context.version,y=j({skillSlug:r,version:p,action:s,authorizationGrants:o,path:d,guardianPreference:await rn(n,r),unmanagedPolicy:u.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:c.mode,localPreflight:me(u.context)}),m=await b(n,"/api/v1/guardian/enforce",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(y)});return await Le(n,{skillSlug:r,version:p,action:s,decisionStatus:it(m),reasonCode:Mt(m),telemetryMode:c.mode,path:d}),f({...m,localPreflight:me(u.context)},"Guardian check complete.",t.json,n)}if(i==="incident"){let r=v(e[1]??t.skill,"guardian incident requires a skill slug."),s=v(t.version,"guardian incident requires --version."),o=Bt(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return k(o.message,t.json);let a=g(t.path)??(await Mi({skillSlug:r,flags:t,backend:n})).installedPath,c=gi(t,"incident"),u=lt(t.evidenceJson,"evidence-json"),d=o.mode==="cloud_managed"&&!n.apiKey?"local_only":o.mode,p=j({skillSlug:r,version:s,action:c,evidence:u,path:a,telemetryMode:d,incident:!0,reason:g(t.reason)});if(d==="local_only"){if(!a)return k("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let w=await ci({backend:n,skillSlug:r,version:s,installedPath:a,action:c,reason:g(t.reason)??"Guardian local-only incident"});await Le(n,{skillSlug:r,version:s,action:c,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:d,path:a});let P=ui(n,r);return await ie(P,JSON.stringify({request:p,response:null,localResponse:w,savedAt:n.now()},null,2)),f({status:"written",skillSlug:r,version:s,telemetryMode:d,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:w,incidentStatePath:P,incidentPath:w.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let y=await b(n,"/api/v1/guardian/enforce",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(p)}),m=a?await ci({backend:n,skillSlug:r,version:s,installedPath:a,action:c,reason:g(t.reason)??"Guardian Cloud-managed incident"}):null;await Ne(n.paths.incidentsDir,{recursive:!0});let h=ui(n,r);return await ie(h,JSON.stringify({request:p,response:y,localResponse:m,savedAt:n.now()},null,2)),await Le(n,{skillSlug:r,version:s,action:c,decisionStatus:it(y),reasonCode:Mt(y),telemetryMode:o.mode,path:a}),f({...y,telemetryMode:o.mode,localResponse:m,incidentPath:h},"Guardian incident recorded.",t.json,n)}return k(`Unknown guardian command "${i??""}".`,t.json)}async function na(e,t,n){let i=g(t.skill),r=v(i??e[1],"guardian exec requires a skill slug."),s=i?e.slice(1):e.slice(2);if(s.length===0)return k("guardian exec requires a command after --.",t.json);let o=Bt(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return k(o.message,t.json);let a=pa(t,s),c=await Bi({skillSlug:r,version:g(t.version),action:a,flags:t,backend:n,telemetryMode:o.mode});if(c.status!=="ok")return c.result;let u=c.context.installedPath,d=g(t.version)??c.context.version,p=j({skillSlug:r,version:d,action:a,authorizationGrants:t.grantJson.map(P=>gn(P,"grant-json")),path:u,guardianPreference:await rn(n,r),telemetryMode:o.mode,localPreflight:me(c.context)}),y=await b(n,"/api/v1/guardian/enforce",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(p)}),m=it(y),h=Mt(y);if(await Le(n,{skillSlug:r,version:d,action:a,decisionStatus:m,reasonCode:h,telemetryMode:o.mode,path:u}),!ma(y))return I({status:"blocked",reasonCode:h,skillSlug:r,guardian:y,localPreflight:me(c.context),command:{executable:K(s[0]??""),executed:!1}},"Guardian blocked guarded execution.",t.json,h);if(t.dryRun)return f({status:"allowed",skillSlug:r,guardian:y,localPreflight:me(c.context),command:{executable:K(s[0]??""),executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let w=await fa(s,n);return{exitCode:w.exitCode,stdout:t.json?JSON.stringify({status:w.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:r,guardian:y,localPreflight:me(c.context),command:w},warnings:[],links:[],reasonCode:w.exitCode===0?null:"command_failed",handoff:null},null,2):ha(w),stderr:w.stderr}}async function St(e,t,n,i){let r=v(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),s=await b(i,"/api/v1/guardian/mode",{method:"POST",headers:_(i.apiKey),body:JSON.stringify({skillSlug:r,requestedPreference:e,source:"public-cli"})});return s.preferenceAccepted===!0&&await ya(i,r,s),f(s,s.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,i)}async function ia(e,t,n){let i=g(t.skill)??g(e[1]),r=await Ti(n,i),s=await qe(n),o=i?await ka(n,i):void 0;return f(j({status:"ok",skillSlug:l(r,"skillSlug")??i,policy:r,localPreference:o,hook:s,nextAction:l(r,"nextAction"),nextStep:l(r,"nextStep")}),"Guardian status loaded.",t.json,n)}async function Ti(e,t){let n=t?await rn(e,t):void 0;return await b(e,"/api/v1/guardian/status",{method:"POST",headers:_(e.apiKey),body:JSON.stringify(j({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function ra(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 Ti(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ue(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function Ut(e,t){let n=g(e.agent)??"codex",i=Oi(e.scope);if(i.status==="invalid")return k(i.message,e.json);let r=de(t.env,t.platform,t.cwd).find(p=>p.id===n);if(!r)return k(`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json);let s=wa(r,i.scope,t);if(!s)return k(`Guardian ${i.scope} hooks are not available for ${r.displayName}.`,e.json);await va(s,t);let o=Ki(t,i.scope),a=di(Te(t.cwd,s.hookPath)),c=di(Te(t.cwd,s.configPath)),d=[...(await Gi(o)).hooks.filter(p=>l(p,"agent")!==r.id||l(p,"scope")!==i.scope),{hookId:le,hookName:ee,agent:r.id,agentName:r.displayName,scope:i.scope,hookPath:a.startsWith("..")?s.hookPath:a,configPath:c.startsWith("..")?s.configPath:c,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,enabledAt:t.now()}];return await D(o,{version:1,hooks:d}),f({status:"enabled",hookId:le,hookName:ee,agent:r.id,agentName:r.displayName,scope:i.scope,hookPath:s.hookPath,configPath:s.configPath,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,agentCommandMatrix:vt({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. Local hooks call `skills-layer guardian check`; shell agents can route risky commands through `skills-layer guardian exec`; MCP-capable agents can call `guardian.check` or `guardian.enforce` before risky tool use.",warnings:s.enforcementLayer==="native_hook_candidate"?["This host does not expose the same stable native hook contract as Codex or Claude Code yet; Skills Layer records the guardrail config for host integration."]:[]},"Guardian hook enabled.",e.json,t)}async function sa(e,t){let n=g(e.scope),i=n?Oi(n):null;if(i?.status==="invalid")return k(i.message,e.json);let r=await qe(t,i?.status==="valid"?i.scope:void 0);return f(r,"Guardian status loaded.",e.json,t)}async function qe(e,t){let n=t?[t]:["project","global"],i=[];for(let a of n){let c=Ki(e,a),u=await Gi(c);for(let d of u.hooks){let p=l(d,"hookPath"),y=p?li(e,a,p):null,m=l(d,"configPath"),h=m?li(e,a,m):null,w=y?await ge(y):!1,P=h?await ge(h):null,x=w?P===!1?"active_missing_config":"active":"stale_missing_hook";i.push({hookId:l(d,"hookId")??le,hookName:l(d,"hookName")??ee,...d,scope:l(d,"scope")??a,hookPath:y??p??null,configPath:h??m??null,active:w,configActive:P,hookState:x})}}let r=i.filter(a=>a.active===!0).length,s=i.filter(a=>a.active===!1).length,o=r>0?0:s;return{status:"ok",enforcementLayer:r>0?"native_hook":"not_installed",strictPreActionBlocking:i.some(a=>a.strictPreActionBlocking===!0),activeHookCount:r,missingHookCount:o,staleHookCount:s,hooks:i,setup:await sn(e),warnings:s>0?r>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 Ui(e,t){if(e.json){let u=await V(t.paths.mcpConfigPath);return f({setup:await sn(t),mcp:{status:u?"mcp_configured":"mcp_not_configured",configured:!!u,clientId:u?l(u,"clientId")??"codex":void 0,clientIds:u&&Array.isArray(u.clientIds)?u.clientIds:void 0,mcpUrl:u?l(u,"mcpUrl"):void 0,readiness:u?{status:"configured_needs_agent_reload",verifyCommand:`skills-layer mcp verify --client ${l(u,"clientId")??"codex"}`,nextStep:"Open a fresh agent session if Skills Layer tools are not visible yet."}:void 0,nextCommand:u?"skills-layer mcp verify":"skills-layer mcp setup"},guardian:await qe(t)},"Setup status loaded.",!0,t)}if(!t.stdoutIsTty)return f({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 u={version:1,setupChoice:"not_now",mcpChoice:"not_now",mcpPromptedAt:t.now(),guardianHookChoice:"not_now",guardianHookPromptedAt:t.now(),remindAfter:la(t.now(),7)};return await ai(t,u),f({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 k(`Unknown setup option "${n}".`,e.json);let i=n==="both"||n==="mcp",r=n==="both"||n==="security",s={status:"setup_complete",setupChoice:n},o={version:1,setupChoice:n,mcpChoice:i?"configured":"not_requested",mcpPromptedAt:t.now(),guardianHookChoice:r?g(e.scope)??"project":"not_requested",guardianHookPromptedAt:t.now()};if(i)if(!t.apiKey)s.mcp={status:"login_required",configured:!1,nextCommand:"skills-layer login"},o.mcpChoice="login_required";else{let u=await Qt(e,t);if(H(u))return u;s.mcp=u}if(r){let u={...e,json:!0,scope:g(e.scope)??"project",agent:g(e.agent)??"codex"},d=await Ut(u,t);if(d.exitCode!==0)return d;s.security=$a(d.stdout)??{status:"enabled",agent:g(u.agent),scope:g(u.scope)}}await ai(t,o);let c=(R(s.mcp)?l(s.mcp,"status"):void 0)==="login_required"?"Skills Layer Security setup complete. MCP setup needs login; run `skills-layer login`, then `skills-layer setup`.":"Skills Layer setup complete. Open a fresh agent session if MCP tools are not visible yet.";return f(s,c,e.json,t)}async function oa(e,t){let n=await qe(t),i=await sn(t),r=ce(n,"activeHookCount")??0;if(t.stdoutIsTty&&r===0&&!i)return await Ui(e,t);let s=r>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:`${Ee}
|
|
865
|
-
|
|
866
|
-
${s}`,stderr:""}}function
|
|
867
|
-
[output truncated]`:e}function
|
|
868
|
-
`)}function
|
|
1135
|
+
skills-layer api-key revoke --key-id <key-id>`,t.json);let s=String(r),o=await v(n,`/api/v1/me/api-keys/${encodeURIComponent(s)}/revoke`,{method:"POST",headers:M(n.apiKey,n.authBlockedMessage)});return h(o,"API key revoked.",t.json,n)}return y(`Unknown api-key command "${i}".`,t.json)}async function Co(e,t,n){let i=e[0]??"status";if(i==="setup"||i==="repair"){let r=p(t.client)??p(t.agent);if(r&&!st(r))return Bt(r,t);let s=await yn(t,n);return H(s)?s:h({...s},`MCP configuration written for ${s.clientId}. Open a fresh agent session to load Skills Layer tools, then run \`skills-layer mcp verify --client ${s.clientId}\` if they are not visible.`,t.json,n)}if(i==="status"||i==="verify"){let r=p(t.client)??p(t.agent);if(r&&!st(r))return Bt(r,t);let s=await Y(n.paths.mcpConfigPath);if(!s){if(r){let u=await Pt({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:ke(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:null});if(u.target.status==="skills_only"){let d=yi(u);return h(d,`${u.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}}return h({status:"mcp_not_configured",configured:!1,nextCommand:"skills-layer mcp setup"},"MCP is not configured on this machine.",t.json,n)}let o=r??l(s,"clientId")??"codex",a=l(s,"baseUrl")??n.baseUrl,c=await Pt({baseUrl:a,mcpUrl:l(s,"mcpUrl")??`${a}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:o,environment:l(s,"environment")??ke(a),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:s});if(c.target.status==="skills_only"){let u=yi(c);return h(u,`${c.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}if(i==="verify"&&c.configured){let u=await Dn({nodePath:process.execPath,bridgePath:c.bridge.path}),d={...c,verified:u.status==="ok",liveProbe:u};return u.status!=="ok"?P(d,`MCP config exists for ${c.clientId}, but live bridge verification failed: ${u.message}`,t.json,u.reasonCode??void 0):h(d,`MCP verified for ${c.clientId}. ${u.message} Open a fresh agent session or restart the agent if tools are not visible yet.`,t.json,n)}return h(c,c.configured?`MCP configuration is present for ${c.clientId}. Open a fresh agent session if tools are not visible, or run \`skills-layer mcp verify --client ${c.clientId}\` for a live check.`:`MCP needs repair for ${c.clientId}. Run \`${c.nextCommand}\`.`,t.json,n)}if(i==="disconnect"||i==="logout"){let r=p(t.client)??p(t.agent)??"codex";if(!st(r))return Bt(r,t);let s=await Y(n.paths.mcpConfigPath),o=Ee({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:ke(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath}),a=o.targets.find(c=>c.agentId===r);return await _o(s,n),await a?.disconnect?.(),await zn(o.bridgePath),await Wn(o.brokerPath,o.brokerSocketPath),await un(n.paths.mcpConfigPath,{force:!0}),h({status:"mcp_disconnected",configured:!1,clientId:r},"MCP disconnected on this machine.",t.json,n)}return y(`Unknown mcp command "${i}". Use setup, status, verify, repair, or disconnect.`,t.json)}function st(e){return be.includes(e)}function Bt(e,t){return P({status:"error",reasonCode:"unknown_mcp_client",requestedClient:e,nextAction:"mcp.status",nextStep:"Run `skills-layer agents list` to see supported client ids."},`Unknown MCP client "${e}". Run \`skills-layer agents list\` to see supported client ids.`,t.json,"unknown_mcp_client")}function yi(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 yn(e,t){let n=p(e.environment)??ke(t.baseUrl),i=["mcp:use","catalog:read","library:read","guardian:check","guardian:incident","creator:read"],r=`${t.baseUrl}/mcp`,s=Ee({baseUrl:t.baseUrl,mcpUrl:r,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}),o=await xo(e,t,s),a=o.clientIds[0]??"codex",c=Ee({baseUrl:t.baseUrl,mcpUrl:r,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}),u={},d=null;for(let m of o.clientIds){let k=await v(t,"/api/v1/me/mcp-tokens",{method:"POST",headers:A(t.apiKey),body:JSON.stringify({clientId:m,environment:n,scopes:i})}),w=l(k,"apiKey");if(!w)return y("MCP setup did not receive a token from the backend.",e.json);let C=await Ro(t,{token:w,clientId:m,environment:n});u[m]={clientId:m,environment:n,...C,tokenPrefix:l(k,"keyPrefix")??null,scopes:Array.isArray(k.scopes)?k.scopes:[],savedAt:t.now()},d??=k}let g=u[a]??{};await D(t.paths.mcpConfigPath,{version:1,baseUrl:t.baseUrl,mcpUrl:r,clientId:a,clientIds:o.clientIds,environment:n,selectionSource:o.selectionSource,detectedClientIds:o.detectedClientIds,...g,tokens:u,brokerPath:c.brokerPath,brokerSocketPath:c.brokerSocketPath,savedAt:t.now()});let f=c.targets.filter(m=>m.status==="automatic"&&o.clientIds.includes(m.agentId));for(let m of f)await m.apply?.();return{...W(d??{}),status:"mcp_configured",clientId:a,clientIds:o.clientIds,selectionSource:o.selectionSource,detectedClientIds:o.detectedClientIds,environment:n,mcpUrl:r,bridgePath:c.bridgePath,brokerPath:c.brokerPath,brokerSocketPath:c.brokerSocketPath,nodePath:c.nodePath,bridgeChecksum:c.bridgeChecksum,brokerChecksum:c.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:c.automaticCount,manualCount:c.manualCount,skillsOnlyCount:c.skillsOnlyCount,unsupportedCount:c.unsupportedCount,appliedCount:f.length,appliedClients:f.map(m=>m.agentId),targets:c.targets.map(m=>({agentId:m.agentId,displayName:m.displayName,tier:m.tier,status:m.status,transport:m.transport,configPath:m.configPath,bridgePath:m.bridgePath,restartRequired:m.restartRequired,reason:m.reason,instructions:m.instructions}))}}}async function xo(e,t,n){let i=p(e.client)??p(e.agent),r=n.targets.filter(c=>c.status==="automatic").map(c=>c.agentId);if(i)return{clientIds:[i],detectedClientIds:[],selectionSource:"explicit"};if(e.all)return{clientIds:r,detectedClientIds:r,selectionSource:"all"};let s=await Tn({env:t.env,platform:t.platform,cwd:t.cwd,pathExists:fe}),o=new Set(r),a=s.map(c=>c.id).filter(c=>o.has(c));return a.length>0?{clientIds:a,detectedClientIds:a,selectionSource:"detected"}:{clientIds:["codex"],detectedClientIds:[],selectionSource:"fallback"}}async function Ro(e,t){if(!e.credentialStore)return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"};let n=Io({baseUrl:e.baseUrl,userId:e.config?.userId,email:e.config?.email,clientId:t.clientId,environment:t.environment});try{return await e.credentialStore.set(Te,n,t.token),{tokenRef:n,credentialStorage:"macos_keychain",credentialService:Te,tokenStorage:"macos_keychain"}}catch{return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}}async function _o(e,t){if(!e||!t.credentialStore)return;let n=$o(e,Te);for(let i of n)await t.credentialStore.delete(i.service,i.tokenRef)}function $o(e,t){let n=new Map;ki(e,t,n);let i=e.tokens;if($(i))for(let r of Object.values(i))$(r)&&ki(r,t,n);return[...n.values()]}function ki(e,t,n){let i=l(e,"tokenRef");if(!i||l(e,"credentialStorage")!=="macos_keychain")return;let r=l(e,"credentialService")??t;n.set(`${r}:${i}`,{service:r,tokenRef:i})}function Io(e){let t=[e.baseUrl,e.userId??e.email??"unknown-user",e.clientId,e.environment,"mcpToken"].join(`
|
|
1136
|
+
`);return`skills-layer-cli:mcp-token:${cn("sha256").update(t).digest("base64url").slice(0,32)}`}async function Zt(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 Y(t.paths.mcpConfigPath),i=n?l(n,"baseUrl"):void 0,r=n?l(n,"clientId")??"codex":"codex";if(!e.withMcp&&i===t.baseUrl&&r)return{data:{status:"mcp_already_configured",configured:!0,clientId:r,mcpUrl:n?l(n,"mcpUrl")??`${t.baseUrl}/mcp`:`${t.baseUrl}/mcp`},message:"MCP is already configured for this machine."};if(!e.withMcp&&!e.json){let a=await Y(t.paths.mcpPreferencePath),c=a?l(a,"baseUrl"):void 0,u=a?l(a,"clientId")??"codex":void 0;if((a?l(a,"choice"):void 0)==="not_now"&&c===t.baseUrl&&u==="codex")return{data:{status:"mcp_skipped_previously",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup was skipped previously. Run `skills-layer mcp setup` when you want AI-tool access."}}let s=e.withMcp===!0;if(!s&&!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(s=a==="yes",a==="no")return await D(t.paths.mcpPreferencePath,{version:1,choice:"not_now",baseUrl:t.baseUrl,clientId:"codex",savedAt:t.now()}),{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(!s)return{};let o=await yn(e,t);return H(o)?o:{data:o,message:"MCP configuration written for this machine. Open a fresh agent session so your AI tools can load it."}}async function jo(e,t,n){let i=e.join(" ").trim()||p(t.search)||"",r=new URLSearchParams;i&&r.set("query",i);let s=p(t.runtimeRisk);if(s&&!wi.includes(s))return bi("runtime-risk",s,wi,t);let o=p(t.limit);if(o){let c=Number(o);if(!Number.isInteger(c)||c<1||c>100)return bi("limit",o,["1-100"],t);r.set("limit",String(c))}F(r,"agent",t.agent),F(r,"capability",t.capability),F(r,"trust",t.trust),F(r,"runtime-risk",s),F(r,"security-capability",t.securityCapability);let a=await v(n,`/api/v1/search${oe(r)}`);if(t.install!==void 0){let c=p(t.install);if(!c){if(t.json)return y("search --install requires an explicit skill slug in the public CLI package.",!0);let d=Ve(a);if(d.length===0)return y("Search results do not include any installable skills. Run search again with a broader query.",!1);if(d.length===1)c=d[0].value;else try{c=await n.promptSelect("Select a search result to install:",d)}catch{return y("No search result was selected for install.",!1)}}let u=Nc(a);return u.includes(c)?await wn([c],t,n):y(u.length===0?`Search results do not include "${c}". Run search again with a matching query first.`:`Search results do not include "${c}". Run search again with a matching query or choose one of: ${u.join(", ")}.`,t.json)}return h(a,"Search complete.",t.json,n)}var wi=["low","elevated","high"],Nt=["local","project","global","workspace"],Mt=["private","public","unlisted"],Ft=["private","public","unlisted"],Ao=/^(?:card(?:_[A-Za-z0-9]+)*|pm_[A-Za-z0-9_]+)$/u;function ir(e,t,n,i){let r=p(t);if(!r)return{};if(!/^\d+$/u.test(r))return{failure:P({status:"error",reasonCode:"invalid_limit",command:e,value:r,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}.`,i.json,"invalid_limit")};let s=Number.parseInt(r,10);return!Number.isInteger(s)||s<1||s>n?{failure:P({status:"error",reasonCode:"invalid_limit",command:e,value:r,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be between 1 and ${n}.`,i.json,"invalid_limit")}:{value:String(s)}}function bi(e,t,n,i){return P({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.":"Use --limit with a whole number from 1 to 100."},e==="runtime-risk"?`Invalid runtime risk "${t}". Use one of: ${n.join(", ")}.`:`Invalid search limit "${t}". Use a whole number from 1 to 100.`,i.json,"invalid_search_filter")}function kn(e,t){let n=p(t.scope);if(n&&!Nt.includes(n))return{failure:P({status:"error",reasonCode:"invalid_install_filter",filter:"scope",value:n,acceptedValues:Nt,nextAction:e,nextStep:"Use --scope local, project, global, or workspace."},`Invalid ${e} --scope "${n}". Use one of: ${Nt.join(", ")}.`,t.json,"invalid_install_filter")};let i=p(t.agent);return i&&!st(i)?{failure:P({status:"error",reasonCode:"unknown_agent",filter:"agent",value:i,acceptedValues:be,nextAction:e,nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown ${e} --agent "${i}". Run \`skills-layer agents\` to inspect supported agents.`,t.json,"unknown_agent")}:{scope:n,agent:i}}function rr(e,t){let n=kn(e,t);if(n.failure)return n.failure;let i=p(t.version);if(e==="install"&&i&&!Sn(i))return sr("install",i,t)}function sr(e,t,n){return P({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 Lo(e,t,n){return P({status:"error",reasonCode:"invalid_expiry",command:e,expiresIn:t,acceptedFormat:"<positive whole number>d",nextAction:e,nextStep:"Use --expires with a day duration such as 7d, 30d, or 90d."},`Invalid --expires "${t}". Use a day duration such as 7d, 30d, or 90d.`,n.json,"invalid_expiry")}function Eo(e,t,n){let i=p(t);if(i&&!/^[1-9]\d*d$/iu.test(i))return Lo(e,i,n)}function or(e,t,n,i,r,s){let o=p(e);if(!o)return{};if(!/^\d+$/u.test(o))return{failure:P({status:"error",reasonCode:i,[n]:o,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${s.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${s.minimum===0?"zero or greater":"greater than zero"}.`,r.json,i)};let a=Number(o);return!Number.isSafeInteger(a)||a<s.minimum?{failure:P({status:"error",reasonCode:i,[n]:o,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${s.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${s.minimum===0?"zero or greater":"greater than zero"}.`,r.json,i)}:{value:a}}function Uo(e){let t=p(e.paymentMethod)??"card";return Ao.test(t)?{value:t}:{failure:P({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 To(e,t,n){let i=new URLSearchParams,r=ir(e,t.limit,20,t);return r.failure?r.failure:(F(i,"limit",r.value),F(i,"search",t.search),F(i,"sort",t.sort),await R(`/api/v1/${e}${oe(i)}`,t,n,`${wt(e)} skills loaded.`))}async function Bo(e,t,n){let i=e.join(" ").trim();if(!i)return y("recommend requires a task.",t.json);let r=ir("recommend",t.limit,20,t);if(r.failure)return r.failure;let s=new URLSearchParams({task:i});return F(s,"limit",r.value),await R(`/api/v1/recommend?${s.toString()}`,t,n,"Recommendations loaded.")}async function No(e,t,n){if(e.length<2)return y("compare requires two or more skill slugs.",t.json);let i=new URLSearchParams({slugs:e.join(",")}),r=await v(n,`/api/v1/skills/compare?${i.toString()}`);return t.json?h(r,"Comparison loaded.",!0,n):{exitCode:0,stdout:Xl(r,"Comparison loaded.",Z(n),t.verbose),stderr:""}}async function Mo(e,t,n){let i=b(e[0],"show requires a skill slug."),r=await v(n,`/api/v1/skills/${encodeURIComponent(i)}`);return h(Aa(r),"Skill loaded.",t.json,n)}async function Fo(e,t,n){let i=b(e[0],"trust requires a skill slug."),r=new URLSearchParams;F(r,"format",t.format),F(r,"version",t.version);let s=await v(n,`/api/v1/skills/${encodeURIComponent(i)}/trust${oe(r)}`);return p(t.format)?.toLowerCase()==="sarif"&&!t.json?{exitCode:0,stdout:La(s,i,n),stderr:""}:h(s,"Trust report loaded.",t.json,n)}async function Oo(e,t,n){let i=et(e[0],e[1]);if(i)return Ot(i,[e[0],e[1]].filter(Boolean).join(" "),t,n);let r=e[0];if(!r)return{exitCode:0,stdout:Be,stderr:""};if(r==="full")return Ot(Be,"full",t,n);if(r==="topic"){let s=et(e[1]);if(s)return Ot(s,e[1]??"overview",t,n);let o=new URLSearchParams;return e[1]&&o.set("topic",e[1]),await R(`/api/v1/help${oe(o)}`,t,n,"Help topic loaded.")}if(r==="standards")return await R("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let s=await v(n,"/api/v1/marketplace/status");return t.json?h(s,"Marketplace status loaded.",!0,n):h(sc(s),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let s=await v(n,"/api/v1/capabilities");return h(ac(s),"Edition capabilities loaded.",t.json,n)}if(r==="schema-plan")return y("help schema-plan is not included in the public npm CLI.",t.json);if(r==="optimize-tokens"){let s=b(t.text,"help optimize-tokens requires --text."),o=lc(t.maxCharacters,t.json);if(H(o))return o;let a=await v(n,"/api/v1/optimize-tokens",{method:"POST",headers:A(n.apiKey),body:JSON.stringify({text:s,...o?{maxCharacters:o}:{}})});return h(a,"Token optimization complete.",t.json,n)}return y(`Unknown help command "${r}".`,t.json)}function Ot(e,t,n,i){return n.json?h({status:"ok",topic:t,content:e},"Help topic loaded.",!0,i):{exitCode:0,stdout:e,stderr:""}}async function qo(e,t,n){let i=b(e[0]??t.path,"validate requires a file or directory."),s={files:await ht(J(n.cwd,i)),sourceIntakeContext:p(t.sourceIntakeContext),publicationStatus:p(t.publicationStatus),dependencyAuditStatus:p(t.dependencyAuditStatus),category:p(t.category),discloseSource:!!t.discloseSource,allowFindingsFeatured:!!t.allowFindingsFeatured},o;try{o=await v(n,"/api/v1/validation/preview",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_(s))})}catch(a){if(a instanceof I&&a.status===422&&a.details)o=Fc(a.details);else throw a}return t.json?h(o,"Validation complete.",!0,n):{exitCode:0,stdout:cc(o,i,n),stderr:""}}async function Ko(e,t,n){let i=b(e[0]??t.path,"preview-trigger requires a file or directory."),r=await ht(J(n.cwd,i)),s=await v(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:A(n.apiKey),body:JSON.stringify({files:r,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?h(s,"Trigger preview complete.",!0,n):{exitCode:0,stdout:uc(s,i,n),stderr:""}}async function Go(e,t,n){let i=e[0];if(i==="init")return await Vo(e.slice(1),t,n);if(i==="rules")return await R("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(i==="submissions")return await R("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(i==="status"){let r=b(e[1],"creator status requires a skill slug.");try{return await R(`/api/v1/me/submissions/${encodeURIComponent(r)}/status`,t,n,"Submission status loaded.",{authenticated:!0})}catch(s){if(s instanceof I&&s.status===404)return Zo(r,t);throw s}}if(i==="charge-status"){let r=b(e[1],"creator charge-status requires a charge id.");return await R(`/api/v1/me/private-skill-charges/${encodeURIComponent(r)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(i==="submit")return await vi(e.slice(1),t,n,!1);if(i==="submit-version")return await vi(e.slice(1),t,n,!0);if(i==="check-slug"){let r=b(e[1],"creator check-slug requires a slug.");return await Jo(r,t,n)}if(i==="rename"){let r=b(e[1],"creator rename requires the current slug."),s=b(e[2],"creator rename requires the new slug.");return await mt(`/api/v1/me/submissions/${encodeURIComponent(r)}/slug`,{nextSkillSlug:s},t,n,"Skill renamed.")}if(i==="pricing")return await ea(e,t,n);if(i==="update-listing"){let r=b(e[1],"creator update-listing requires a skill slug.");return await ta(r,t,n)}if(i==="visibility"){let r=b(e[1],"creator visibility requires a skill slug."),s=p(t.visibility)??e[2],o=$t(s);if(!o||!Mt.includes(o))return P({status:"error",reasonCode:"invalid_visibility",skillSlug:r,visibility:s??null,acceptedValues:Mt,nextAction:"creator.visibility",nextStep:"Use --visibility private, public, or unlisted."},`Invalid creator visibility "${s??""}". Use one of: ${Mt.join(", ")}.`,t.json,"invalid_visibility");let a=await v(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/visibility`,{method:"PATCH",headers:A(n.apiKey),body:JSON.stringify(_({visibility:o,dryRun:t.dryRun}))});return Ha(a)?P(a,za(a,r),t.json,l(a,"reasonCode")??l(a,"status")):h(a,t.dryRun?"Visibility preview loaded.":"Visibility updated.",t.json,n)}if(i==="security-report"){let r=b(e[1],"creator security-report requires a skill slug."),s=new URLSearchParams;F(s,"format",t.format),F(s,"version",t.version),F(s,"versionId",t.versionId);let o=await v(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust${oe(s)}`,{headers:M(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?h(o,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:xc(o,r,n),stderr:""}}if(i==="rescan-security"){let r=b(e[1],"creator rescan-security requires a skill slug."),s=await v(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust/rescan`,{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_(G(t,["version","versionId"])))});return t.json?h(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:Rc(s,r,n),stderr:""}}if(i==="provenance"){let r=b(e[1],"creator provenance requires a skill slug.");return await R(`/api/v1/me/submissions/${encodeURIComponent(r)}/provenance`,t,n,"Provenance loaded.",{authenticated:!0})}if(i==="claim"||i==="verify"||i==="dispute")return await na(i,e,t,n);if(i==="issues"||i==="reviews"||i==="update-issue"||i==="moderate-review")return await la(i,e,t,n);if(i==="analytics"){let r=b(e[1],"creator analytics requires a skill slug.");return await ia(r,t,n)}if(i==="earnings")return await R("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0});if(i==="payout-profile")return await ra(t,n);if(i==="payout-link")return await sa(t,n);if(i==="payouts")return await R("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0});if(i==="withdraw"){let r=or(t.amountCents,"--amount-cents","amountCents","invalid_amount_cents",t,{minimum:1});return r.failure?r.failure:await q("/api/v1/me/payouts/withdrawals",_({amountCents:r.value,reason:p(t.reason)}),t,n,"Withdrawal requested.")}return i==="source"?await da(e.slice(1),t,n):y(`Unknown creator command "${i??""}".`,t.json)}async function Vo(e,t,n){let i=p(t.skill)??e[0]??"my-skill",r=J(n.cwd,p(t.dir)??i),s=L(r,"SKILL.md"),o;try{o=ti(p(t.type))}catch(f){return y(ae(f),t.json)}let a=p(t.category),c=await Do(r);if((await fe(s)||c)&&!t.confirmed)return y(`Creator init target already exists at ${r}. Re-run with --confirm only if you want to overwrite ${s}.`,t.json);await Ke(r,{recursive:!0});let d=ni({skillSlug:i,description:p(t.description)??"Describe what this skill helps an agent do.",skillType:o,category:a});for(let f of d)await re(L(r,f.path),f.content);let g=_({status:"created",path:s,skillSlug:i,skillType:o,category:a,fileCount:d.length});return t.json?h(g,`Created ${s}.`,!0,n):{exitCode:0,stdout:yc(g,r,s,n),stderr:""}}async function fe(e){try{return await Ji(e),!0}catch{return!1}}async function Do(e){try{return(await Zi(e)).length>0}catch{return await fe(e)}}async function vi(e,t,n,i){let r=i?b(p(t.skill)??e[0],"creator submit-version requires a skill slug."):p(t.skill),s=b(p(t.source)??(i?e[1]:e[0])??t.path,`creator ${i?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),o=await pt(s,n.cwd);if(t.list)return await Ho(s,o,r,t,n);if(p(t.source)&&!o&&Hr(s))return zo(s,t);let a=o?.files??await ht(J(n.cwd,s));if(!i&&!t.dryRun){let m=await Wo(a,t,n);if(m)return m}let c=_({files:a,version:p(t.version),dryRun:t.dryRun,allowFindingsFeatured:t.allowFindingsFeatured,pricing:p(t.priceCents)?{priceCents:Number(p(t.priceCents))}:void 0,...o?{sourceMetadata:o.sourceMetadata}:{},...G(t,["displayName","skillType","category","visibility","source","skill"])}),u=i&&r?`/api/v1/me/submissions/${encodeURIComponent(r)}/versions`:"/api/v1/me/submissions",d=await v(n,u,{method:"POST",headers:A(n.apiKey),body:JSON.stringify(c)});if(t.json||d.status!=="checkout_required"||typeof d.checkoutUrl!="string"||typeof d.chargeId!="string")return h(d,i?"Version submitted.":"Submission uploaded.",t.json,n);n.emitInfo("Opening payment setup for skill submission. Complete the payment in your browser, then come back here."),await n.openUrl(d.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${d.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let f=await Nl(d.chargeId,n);return H(f)?f:f.status!=="submitted"?h({...d,chargeStatus:f.status},`Payment is still ${f.status}. You can rerun \`skills-layer creator charge-status ${d.chargeId}\` to continue tracking it.`,t.json,n):h(f,i?"Version submitted.":"Submission uploaded.",t.json,n)}async function Ho(e,t,n,i,r){if(t)return h(Si(cr(e,t,n)),"Source skills loaded.",i.json,r);let s=await Ne(r,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},i);return s.kind==="failure"?s.result:h(Si(s.inspection),"Source skills loaded.",i.json,r)}function Si(e){return{...e,sourceSubmissionSupported:!0}}function zo(e,t){let i=`skills-layer source connection start --provider ${mr(e)} --source ${e} --visibility private --provenance-intent private_source_import`;return P({status:"source_connection_required",reasonCode:"source_connection_required",source:e,nextAction:"source.connection.start",nextStep:i},`Creator submit can list ${e} safely, but publishing from a remote source requires a source connection. Run \`${i}\`.`,t.json,"source_connection_required")}async function Wo(e,t,n){let i=p(t.skill)??Qo(e);if(!i)return null;let r;try{r=await v(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(i)}`,{headers:M(n.apiKey,n.authBlockedMessage)})}catch(s){if(s instanceof I&&s.status===404)return ar(i,t);throw s}if(r.available===!1||l(r,"reasonCode")==="unavailable"||l(r,"reasonCode")==="reserved"){let s=l(r,"assignedSlug"),o=_({status:"duplicate_candidate",reasonCode:l(r,"reasonCode")??"slug_unavailable",requestedSlug:i,assignedSlug:s,nextAction:"creator.status",nextStep:`Run \`skills-layer creator status ${i}\`, \`skills-layer creator submissions\`, or submit a new version of the existing skill instead of creating a duplicate listing.`});return P(o,`A public skill slug "${i}" already exists or is not available. Run \`skills-layer creator status ${i}\`, check your creator submissions, or submit a new version instead of creating a duplicate listing.`,t.json,l(o,"reasonCode"))}return null}async function Jo(e,t,n){try{let i=await v(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:M(n.apiKey,n.authBlockedMessage)});return h(Yo(i),"Slug status loaded.",t.json,n)}catch(i){if(i instanceof I&&i.status===404)return ar(e,t);throw i}}function ar(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 P(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 Yo(e){let t=e.available===!0,n=l(e,"assignedSlug");if(t)return _({requestedSlug:l(e,"requestedSlug"),available:!0,reasonCode:l(e,"reasonCode")??"available",assignedSlug:n});let i=S(e,"slugAssignment"),r=Array.isArray(i?.candidateSlugs)?i.candidateSlugs.filter(s=>typeof s=="string").slice(0,5):void 0;return _({...e,...i?{slugAssignment:{...i,...r?{candidateSlugs:r}:{}}}:{},...r?{candidateSlugs:r}:{}})}function Zo(e,t){return P({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 Qo(e){let t=e.find(i=>i.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(i=>i.match(/^name\s*:\s*(?<name>.+?)\s*$/u)?.groups?.name?.trim().replace(/^["']|["']$/gu,"")).find(i=>!!i);return Xo(n??K(ee(t.path)))}function Xo(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function ea(e,t,n){let i=b(e[1],"creator pricing requires a skill slug."),r=new URLSearchParams;if(F(r,"version",t.version),!t.priceCents)return await R(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${oe(r)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=or(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(s.failure)return s.failure;let o=s.value??0,a=await v(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${oe(r)}`,{headers:M(n.apiKey,n.authBlockedMessage)}),c=O(a,"priceCents")??0;if(o>c){let u=_({status:"pending_approval",reasonCode:c===0?"paid_activation_requires_approval":"price_increase_requires_approval",skillSlug:i,version:l(a,"version"),currentPriceCents:c,requestedPriceCents:o,currency:l(a,"currency")??"gbp",nextStep:"Pricing changes that increase buyer-facing cost require approval. Keep the current price for now, then retry after approval is available."});return h(u,"Pricing change requires approval before it can affect buyers.",t.json,n)}return await mt(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing`,{priceCents:o,version:p(t.version)},t,n,"Pricing updated.")}async function ta(e,t,n){try{return await mt(`/api/v1/me/submissions/${encodeURIComponent(e)}`,G(t,["displayName","summary","description","category","skillType","license","listingStatus"]),t,n,"Listing updated.")}catch(i){if(i instanceof I&&i.status===404){let r={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 P(r,`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 na(e,t,n,i){let r=b(t[1],`creator ${e} requires a skill slug.`);try{if(e==="claim")return await q(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/claim`,G(n,["requestedRole","message"]),n,i,"Ownership claim submitted.");if(e==="verify"){let s=b(n.claimId,"creator verify requires --claim-id.");return await q(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/verify`,{claimId:s},n,i,"Ownership claim verified.")}return await q(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/dispute`,G(n,["message"]),n,i,"Ownership dispute submitted.")}catch(s){if(s instanceof I&&s.status===404){let o={status:"ownership_action_unavailable",reasonCode:e==="claim"?"skill_not_found_or_not_claimable":"ownership_claim_not_found",skillSlug:r,requestedRole:p(n.requestedRole),nextAction:e==="claim"?"search":"creator.claim",nextStep:e==="claim"?`Run \`skills-layer search ${r}\`, \`skills-layer show ${r}\`, or submit/source-install the skill before claiming it.`:`Run \`skills-layer creator claim ${r}\` to start a new claim if the skill is claimable.`};return P(o,e==="claim"?`No claimable skill was found for ${r}. Search or show the skill first, then claim it only when it exists and is claimable.`:`No matching ownership claim was found for ${r}. Start a new claim if the skill is claimable.`,n.json,l(o,"reasonCode")??"ownership_action_unavailable")}throw s}}async function ia(e,t,n){try{return await R(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(i){if(i instanceof I&&i.status===404){let r={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 P(r,`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 i}}async function ra(e,t){let n=await v(t,"/api/v1/me/payout-profile",{headers:M(t.apiKey,t.authBlockedMessage)});return h(n,"Creator payout profile loaded.",e.json,t)}async function sa(e,t){let n=oa(p(e.mode));if(e.mode&&n===null)return y("creator payout-link --mode must be account_onboarding|account_update|onboarding|update.",e.json);let i;try{i=await v(t,"/api/v1/me/payout-profile/link",{method:"POST",headers:A(t.apiKey),body:JSON.stringify(n?{mode:n}:{})})}catch(s){if(s instanceof I&&aa(s))return P({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 s}let r=Ml(i);return r&&!e.json&&e.showUrl!==!0&&(t.emitInfo("Opening payout setup in your browser. Finish the flow there, then come back here."),await t.openUrl(r)||t.emitInfo(`Open this payout setup URL manually to continue: ${r}`)),h(i,"Payout setup link created.",e.json,t)}function oa(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 aa(e){let t=`${e.message} ${l(e.details??{},"error")??""}`.toLowerCase();return t.includes("account_update")&&t.includes("account_onboarding")&&t.includes("account link")}async function la(e,t,n,i){let r=b(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await R(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await R(`/api/v1/me/submissions/${encodeURIComponent(r)}/reviews`,n,i,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let o=b(n.issueId,"creator update-issue requires --issue-id.");try{return await mt(`/api/v1/me/skills/${encodeURIComponent(r)}/issues/${encodeURIComponent(o)}`,G(n,["status","fixedVersion","note"]),n,i,"Issue updated.")}catch(a){if(a instanceof I&&a.status===404)return ca(r,o,n);throw a}}let s=b(n.reviewId,"creator moderate-review requires --review-id.");try{return await q(`/api/v1/me/submissions/${encodeURIComponent(r)}/reviews/${encodeURIComponent(s)}/moderate`,G(n,["status","reason"]),n,i,"Review updated.")}catch(o){if(o instanceof I&&o.status===404)return ua(r,s,n);throw o}}function ca(e,t,n){return P({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 ua(e,t,n){return P({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 da(e,t,n){let i=e[0],r=b(e[1],`creator source ${i??""} requires a source connection id.`),s=p(t.skill)??e[2];if(i==="prepare")return await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/prepare`,_({...G(t,["skill","source","version","displayName","skillType","category","priceCents","visibility"]),source:p(t.source)??e[2]}),t,n,"Source release prepared.");if(i==="publish-request"){let o=t.approvalRequestId.length>0?t.approvalRequestId:p(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/publish-request`,_({skillSlug:s,approvalRequestIds:o,version:p(t.version),...G(t,["visibility","priceCents","license","discloseSource"])}),t,n,"Source publish requested.")}if(i==="release-status"){let o=new URLSearchParams;return s&&o.set("skill",s),await R(`/api/v1/me/source-connections/${encodeURIComponent(r)}/release-status${oe(o)}`,t,n,"Source release status loaded.",{authenticated:!0})}return y(`Unknown creator source command "${i??""}".`,t.json)}async function wn(e,t,n){let i=rr("install",t);if(i)return i;let r=p(t.source);if(r){let u=p(t.skill),d=_i(r,u,t);if(d)return d;let g=await pt(r,n.cwd);if(g)return await Pi(r,g,u,t,n);let f=$i(r,t);if(f)return f;let m=t.list||t.dryRun||!u&&!t.json&&!t.all,k=await Ne(n,r,{source:r,skillSlug:u,listOnly:m},t);if(k.kind==="failure")return k.result;let w=k.inspection;if(t.list)return h(w,"Source skills loaded.",t.json,n);let C=Xt(r,w,t);if(C)return C;let x=await ot({source:r,inspection:w,requestedSkillSlug:u,mode:"install",flags:t,backend:n});if(x.kind==="failure")return x.result;if(t.dryRun)return h(Qt(r,w,x.skillSlug,t),"Source install preview ready.",t.json,n);let E=Ci(t,n),le;try{le=await v(n,E,{method:"POST",headers:xi(t,n),body:JSON.stringify(Ii({source:r},x.skillSlug,t))})}catch(bt){if(bt instanceof I)return ji(r,bt,t);throw bt}let U=await Vt(n,le);return await lt(n,U,x.skillSlug??l(U,"skillSlug")??r),at(U,Ri(t),t.json,n)}let s=b(e[0]??t.install,"install requires a skill slug or --source.");if(Hr(s)){let u=_i(s,p(t.skill),t);if(u)return u;let d=await pt(s,n.cwd);if(d)return await Pi(s,d,p(t.skill),t,n);let g=$i(s,t);if(g)return g;let f=p(t.skill),m;if(t.list){let x=await Ne(n,s,{source:s,listOnly:!0},t);return x.kind==="failure"?x.result:h(x.inspection,"Source skills loaded.",t.json,n)}if(!f&&!t.json&&!t.all){let x=await Ne(n,s,{source:s,listOnly:!0},t);if(x.kind==="failure")return x.result;let E=x.inspection;m=E;let le=Xt(s,E,t);if(le)return le;let U=await ot({source:s,inspection:E,requestedSkillSlug:f,mode:"install",flags:t,backend:n});if(U.kind==="failure")return U.result;f=U.skillSlug}if(t.dryRun){if(!m){let E=await Ne(n,s,{source:s,listOnly:!0},t);if(E.kind==="failure")return E.result;m=E.inspection}let x=await ot({source:s,inspection:m,requestedSkillSlug:f,mode:"install",flags:t,backend:n});return x.kind==="failure"?x.result:(f=x.skillSlug,h(Qt(s,m,f,t),"Source install preview ready.",t.json,n))}let k=Ci(t,n),w;try{w=await v(n,k,{method:"POST",headers:xi(t,n),body:JSON.stringify(Ii({source:s},f,t))})}catch(x){if(x instanceof I)return ji(s,x,t);throw x}let C=await Vt(n,w);return await lt(n,C,f??l(C,"skillSlug")??K(s)),at(C,Ri(t),t.json,n)}if(p(t.scope)==="workspace"){let u=b(t.workspace,"workspace installs require --workspace <workspace-id>."),d=await v(n,`/api/v1/workspaces/${encodeURIComponent(u)}/skills`,{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_({skillSlug:s,version:p(t.version),dryRun:t.dryRun}))});return t.dryRun?await fr(d,"Workspace install preview ready.",t,n):h(d,"Workspace deployment requested.",t.json,n)}let o=await v(n,"/api/v1/install",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_({skillSlug:s,version:p(t.version),scope:p(t.scope),agent:p(t.agent),dryRun:t.dryRun}))});if(t.dryRun)return await Ia(o,t,n);let a=await Vt(n,o),c=await pa(n,a,s,t);return H(c)?c:(await lt(n,c,s),at(c,"Skill installed.",t.json,n))}async function pa(e,t,n,i){if(Array.isArray(t.materializedWrites)&&t.materializedWrites.length>0)return t;let r=ga(e,t,n,i);if(r.status==="skip")return t;if(r.status==="failure")return P({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:r.skillSlug,nextStep:r.nextStep},r.message,i.json,"materialization_target_invalid");let s=await ma(e,t,r.skillSlug,r.version),o=await lr({backend:e,exportResult:s,flags:i,skillSlug:r.skillSlug});if(H(o))return o;let a=await ka({backend:e,skillSlug:r.skillSlug,version:r.version??l(s,"version")??"latest",scope:r.scope,agent:r.agent,skillsPath:r.skillsPath,bytes:o.bytes,files:o.files,archiveSha256:o.archiveSha256});return{...t,...fa(s),archiveSha256:o.archiveSha256,archiveHashFormat:o.archiveHashFormat,scope:r.scope,agent:r.agent.id,targetAgent:r.agent.id,materializationPlan:{scope:r.scope,agent:r.agent.id},...a}}function ga(e,t,n,i){let r=S(t,"materializationPlan")??S(t,"installPlan"),s=p(i.scope)??l(t,"scope")??(r?l(r,"scope"):void 0);if(s!=="project"&&s!=="global")return{status:"skip"};let o=l(t,"skillSlug")??l(t,"slug")??n,a=p(i.agent)??l(t,"agent")??l(t,"targetAgent")??(r?l(r,"agent")??l(r,"targetAgent"):void 0)??X(e.config?.lastSelectedAgent)??"codex",c=me(e.env,e.platform,e.cwd).find(d=>d.id===a);if(!c)return{status:"failure",skillSlug:o,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 u=s==="global"?c.targets.globalSkillsPath:c.targets.projectSkillsPath;return u?{status:"ok",scope:s,agent:c,skillsPath:u,skillSlug:o,version:l(t,"version")??l(t,"currentVersion")}:{status:"failure",skillSlug:o,message:`${c.displayName} does not expose a ${s} skills path on this machine.`,nextStep:"Retry with --scope project, or choose another agent from `skills-layer agents list`."}}async function ma(e,t,n,i){if(typeof t.downloadUrl=="string"&&typeof t.archiveSha256=="string")return t;let r=new URLSearchParams;return i&&r.set("version",i),await v(e,`/api/v1/me/library/${encodeURIComponent(n)}/export${oe(r)}`,{headers:M(e.apiKey,e.authBlockedMessage)})}function fa(e){return _({version:l(e,"version"),storageKey:l(e,"storageKey"),expiresAt:l(e,"expiresAt")})}async function lr(e){let t=l(e.exportResult,"downloadUrl");if(!t)return P({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 n=await e.backend.fetchFn(ha(e.backend.baseUrl,t));if(!n.ok)throw new I(n.status,`Unable to download exported bundle (${n.status}).`);let i=new Uint8Array(await n.arrayBuffer()),r=ya(i),s=l(e.exportResult,"archiveSha256")??n.headers.get("x-skills-layer-archive-sha256")?.trim()??void 0;return s&&r.archiveSha256!==s?P({status:"download_integrity_failed",reasonCode:"download_hash_mismatch",skillSlug:e.skillSlug,version:l(e.exportResult,"version"),expectedArchiveSha256:s,observedArchiveSha256:r.archiveSha256,archiveHashFormat:r.format,nextStep:"Retry after the catalog artifact is refreshed, or contact Skills Layer support if this repeats."},`Downloaded ${e.skillSlug} did not match the catalog artifact hash.`,e.flags.json,"download_hash_mismatch"):r.files.length===0?P({status:"download_integrity_failed",reasonCode:"download_bundle_empty",skillSlug:e.skillSlug,archiveHashFormat:r.format,nextStep:"Retry after the catalog artifact is refreshed."},`Downloaded ${e.skillSlug} did not contain any skill files.`,e.flags.json,"download_bundle_empty"):{status:"ok",bytes:i,files:r.files,archiveSha256:r.archiveSha256,archiveBytesSha256:r.archiveBytesSha256,archiveHashFormat:r.format}}function ha(e,t){return/^https?:\/\//iu.test(t)?t:`${ie(e)}${t.startsWith("/")?"":"/"}${t}`}function ya(e){let t=cn("sha256").update(e).digest("hex"),n=Jn(e);return n?{archiveSha256:Yn(n),archiveBytesSha256:t,format:"bundle_archive",files:n}:{archiveSha256:t,archiveBytesSha256:t,format:"raw",files:[]}}async function ka(e){let t=e.backend.platform==="win32"?_e:pn,n=t.join(e.backend.paths.bundlesDir,e.skillSlug,e.version,"bundle.zip"),i=t.join(e.skillsPath,e.skillSlug),r=t.join(i,e.version,"bundle.zip"),s=[];await an(n,e.bytes),await un(i,{recursive:!0,force:!0}),await an(r,e.bytes),s.push({path:ct(e.backend.cwd,r),bytes:e.bytes.byteLength});for(let o of e.files){let a=t.join(i,...wa(o.path)),c=o.content??"";if(await re(a,c),s.push({path:ct(e.backend.cwd,a),bytes:new TextEncoder().encode(c).length}),K(o.path).toLowerCase()==="skill.md"){let u=await _n({backend:e.backend,skillSlug:e.skillSlug,version:e.version,skillDocumentPath:a,skillDocumentContent:c});s.push(u)}}return{bundlePath:n,materializedPath:r,materializedSkillRoot:i,archiveSha256:e.archiveSha256,materializedWrites:s}}function wa(e){let n=e.replaceAll("\\","/").replace(/^\/+/u,"").trim().split("/").filter(i=>i.length>0);if(n.length===0||n.some(i=>i==="."||i===".."))throw new Error(`Unsafe bundle path "${e}".`);return n}async function Pi(e,t,n,i,r){let s=p(i.visibility)??"private";if(s!=="private")return P({status:"local_install_visibility_not_allowed",reasonCode:"local_install_visibility_not_allowed",source:e,requestedVisibility:s,nextStep:`Use \`skills-layer creator submit ${e} --visibility ${s} --dry-run\` when you want to submit a local skill with non-private visibility.`},`Local path install creates a private Cloud skill by default. Use creator submit when you want ${s} visibility.`,i.json,"local_install_visibility_not_allowed");let o=cr(e,t,n);if(i.list)return h(o,"Local source skills loaded.",i.json,r);let a=Xt(e,o,i);if(a)return a;let c=await ot({source:e,inspection:o,requestedSkillSlug:n,mode:"install",flags:i,backend:r});if(c.kind==="failure")return c.result;let u=c.skillSlug??Ve(o)[0]?.value??dr(e);if(i.dryRun)return h({...Qt(e,o,u,i),installKind:"local_private",publicationStatus:"none",catalogRecord:"not_created",nextStep:`Re-run without --dry-run to install ${u} locally. Use \`skills-layer creator submit ${e} --visibility private --dry-run\` when you want a private creator submission.`},"Local private install preview ready.",i.json,r);let d=await v(r,"/api/v1/me/submissions",{method:"POST",headers:{"content-type":"application/json",...M(r.apiKey,r.authBlockedMessage)},body:JSON.stringify(_({files:t.files,version:p(i.version),visibility:"private",category:p(i.category),displayName:p(i.displayName),skillType:p(i.skillType),sourceMetadata:t.sourceMetadata}))}),g=await Sa({backend:r,source:e,upload:t,skillSlug:l(d,"skillSlug")??u,flags:i,submitted:d});return await lt(r,g,u),at(g,"Private Cloud skill installed.",i.json,r)}function cr(e,t,n){let i=ba(t.files),r=n?i.find(s=>s.skillSlug===n)??null:i.length===1?i[0]??null:null;return{status:"ok",source:t.sourceMetadata,selectedSkill:r,results:i,issues:[],sourceInstallSupported:!0,sourceInstallMode:"local_private",publicationStatus:"none",originalSource:e}}function ba(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=ee(t.path).replaceAll("\\","/"),i=n==="."?".":n,r=ur(t.content??"")??dr(i==="."?t.path:i),s=va(t.content??"");return{skillSlug:r,name:r,...s?{description:s}:{},relativeSkillRoot:i,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function ur(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function va(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function dr(e){return(e.replaceAll("\\","/").replace(/\/+$/u,"").split("/").filter(Boolean).at(-1)??"local-skill").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"local-skill"}async function Sa(e){let t=Pa(e.backend,e.flags);if(t.status==="failure")throw new Error(t.message);let n=e.upload.files.map(r=>({path:L(t.skillsPath,e.skillSlug,Er(r.path)),content:r.content??""})),i=[];for(let r of n)if(await re(r.path,r.content),i.push({path:ct(e.backend.cwd,r.path),bytes:new TextEncoder().encode(r.content).length}),K(r.path).toLowerCase()==="skill.md"){let s=await _n({backend:e.backend,skillSlug:e.skillSlug,version:l(e.submitted,"version")??p(e.flags.version)??"private",skillDocumentPath:r.path,skillDocumentContent:r.content});i.push(s)}return{...e.submitted,status:"installed",cloudStatus:l(e.submitted,"status")??"submitted",installKind:"cloud_private",source:e.source,sourceKind:"local",skillSlug:e.skillSlug,version:l(e.submitted,"version")??p(e.flags.version)??"private",scope:t.scope,agent:t.agent,visibility:"private",publicationStatus:"private",catalogRecord:"private",privacy:{publication:"private",catalogRecord:"private",message:"This local install was saved as a private Cloud skill and did not create a public catalog record."},materializationPlan:{scope:t.scope,agent:t.agent},materializedWrites:i}}function Pa(e,t){let n=p(t.scope)??"project";if(!["local","project","global"].includes(n))return{status:"failure",message:"Local private installs support --scope local, project, or global. Use `skills-layer creator submit <path> --visibility private` for private creator workflows."};let i=p(t.agent)??X(e.config?.lastSelectedAgent)??"codex",r=me(e.env,e.platform,e.cwd).find(o=>o.id===i);if(!r)return{status:"failure",message:`Unsupported agent "${i}". Run \`skills-layer agents list\` to choose a supported local install target.`};let s=n==="global"?r.targets.globalSkillsPath:r.targets.projectSkillsPath;return s?{status:"ok",scope:n,agent:r.id,skillsPath:s}:{status:"failure",message:`${r.displayName} does not expose a ${n} skills path on this machine.`}}function ct(e,t){let n=Fe(e,t);return n&&!n.startsWith("..")&&!_e.isAbsolute(n)?n.split("\\").join("/"):t}function bn(e){return p(e.visibility)==="public"?"public":"private"}function Ci(e,t){return bn(e)==="public"&&!t.apiKey?"/api/v1/source-imports":"/api/v1/me/source-installs"}function xi(e,t){return{"content-type":"application/json",...bn(e)==="private"?M(t.apiKey,t.authBlockedMessage):He(t.apiKey)}}function Ri(e){return bn(e)==="public"?"Public source install planned.":"Private source skill installed."}async function ot(e){let t=Ve(e.inspection);if(e.requestedSkillSlug)return t.length>0&&!t.some(n=>n.value===e.requestedSkillSlug)?{kind:"failure",result:Ca(e.source,e.requestedSkillSlug,t.map(n=>n.value),e.flags)}:{kind:"selected",skillSlug:e.requestedSkillSlug};if(e.flags.json||e.flags.all)return{kind:"selected",skillSlug:e.requestedSkillSlug};if(t.length<=1)return{kind:"selected",skillSlug:t[0]?.value};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:y(`Source "${e.source}" exposes multiple skills. Re-run with --list or --skill <skill-slug>. Available skills: ${t.map(n=>n.value).join(", ")}.`,e.flags.json)}}}function _i(e,t,n){if(n.all&&t)return P({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 $i(e,t){try{if(Qe(e).kind!=="local")return}catch{return}return P({status:"error",reasonCode:"invalid_source",source:e,nextAction:"install",nextStep:ut(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."},ut(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 Ca(e,t,n,i){return P({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.`,i.json,"source_skill_not_found")}function Ve(e){let t=[e.results,e.skills,e.discoveredSkills,S(e,"source")?.results,S(e,"inspection")?.results],n=new Set,i=[];for(let r of t)if(Array.isArray(r))for(let s of r){let o=xa(s);!o||n.has(o.value)||(n.add(o.value),i.push(o))}return i}function xa(e){if(!$(e))return;let t=l(e,"skillSlug")??l(e,"slug")??l(e,"name");if(!t)return;let n=l(e,"displayName")??l(e,"title")??l(e,"name"),i=n&&n!==t?`${t} - ${n}`:t,r=S(e,"parsedSkill"),s=S(e,"frontmatter")??(r?S(r,"frontmatter"):void 0),o=l(e,"shortDescription")??l(e,"summary")??l(e,"description")??(s?l(s,"description"):void 0)??l(e,"relativeSkillRoot")??l(e,"path")??l(e,"discoveryRoute")??l(e,"sourceKind");return o?{value:t,label:i,description:o}:{value:t,label:i}}function Ii(e,t,n){return _({...e,skillSlug:t,scope:p(n.scope),agent:p(n.agent),workspace:p(n.workspace),version:p(n.version),visibility:p(n.visibility)??"private",category:p(n.category),displayName:p(n.displayName),skillType:p(n.skillType),all:n.all,quarantine:n.quarantine,acceptCapability:n.acceptCapability})}function Qt(e,t,n,i){return _({status:"dry_run",source:e,selectedSkillSlug:n,all:i.all,scope:p(i.scope)??"local",agent:p(i.agent),workspace:p(i.workspace),quarantine:i.quarantine,acceptCapability:i.acceptCapability,candidates:Ve(t).map(r=>({skillSlug:r.value,name:r.label,description:r.description})),nextStep:i.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 Ne(e,t,n,i){try{return{kind:"ok",inspection:await v(e,"/api/v1/source-inspect",{method:"POST",headers:A(e.apiKey),body:JSON.stringify(_(n))})}}catch(r){if(r instanceof I)return{kind:"failure",result:_a(t,r,i)};throw r}}function Xt(e,t,n){if(Ve(t).length>0)return null;let r=Ra(t);return P({status:"unsupported_source_layout",source:e,reasonCode:"source_no_discoverable_skills",issues:r,nextStep:"Run with --list to inspect the source, use a subfolder containing SKILL.md, or install from a Skills Layer-compatible source layout."},$a(e,r),n.json)}function Ra(e){return(Array.isArray(e.issues)?e.issues:[]).filter($).map(n=>({...l(n,"code")?{code:l(n,"code")}:{},...l(n,"message")?{message:l(n,"message")}:{},...l(n,"path")?{path:l(n,"path")}:{}}))}function _a(e,t,n){let i=t.details??{},r=l(i,"error")??t.message;if(pr(t.status,r))return gr(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return yt(t,n.json);let o={status:"unsupported_source_layout",source:e,reasonCode:"source_not_inspectable",backendStatus:t.status,backendMessage:r,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return P(o,`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 ji(e,t,n){let i=t.details??{},r=l(i,"error")??t.message;if(pr(t.status,r))return gr(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return yt(t,n.json);let o={status:"unsupported_source_layout",source:e,reasonCode:"source_not_installable",backendStatus:t.status,backendMessage:r,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return P(o,`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)}function pr(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function gr(e,t,n,i){let r=t.details??{},s=l(r,"error")??t.message,a=`skills-layer source connection start --provider ${mr(e)} --source ${e} --visibility private --provenance-intent private_source_import`,c={status:"private_source_access_required",source:e,reasonCode:"private_source_access_required",backendStatus:t.status,backendMessage:s,nextStep:a};return P(c,`Cloud could not ${i} ${e} directly. If this is a private source, start a private source connection first:
|
|
1137
|
+
${a}`,n.json,"private_source_access_required")}function mr(e){return/gitlab\./iu.test(e)?"gitlab":/github\./iu.test(e)||/^gh:/iu.test(e)?"github":"generic_git"}function $a(e,t){let n=[`No Skills Layer-compatible skills were found in ${e}.`];if(t.length>0){n.push("Detected issues:");for(let i of t.slice(0,5)){let r=i.code??"source-inspection";n.push(`- ${r}: ${i.message??"No details returned."}${i.path?` (${i.path})`:""}`)}}return n.push("Try --list, a subfolder containing SKILL.md, or a Skills Layer-compatible source layout."),n.join(`
|
|
1138
|
+
`)}async function Ia(e,t,n){if(hr(e)){let s=l(e,"reasonCode")??l(e,"reason")??"install_not_ready",o=l(e,"why")??l(e,"summary")??"The requested skill is not ready to install from this backend.";return P(e,`Install preview is not ready: ${o}`,t.json,s)}let i=await yr(e,n),r=Array.isArray(i.warnings)&&i.warnings.length>0;return ja(i,r?"Install preview ready with warnings.":"Install preview ready.",t,n)}function ja(e,t,n,i){return n.json?h(e,t,!0,i):{exitCode:0,stdout:vn(e,t,i),stderr:""}}async function fr(e,t,n,i){if(hr(e)){let s=l(e,"reasonCode")??l(e,"reason")??"workspace_deploy_not_ready",o=l(e,"why")??l(e,"summary")??l(e,"nextStep")??"The requested workspace deployment is not ready.";return P(e,`Workspace deployment preview is not ready: ${o}`,n.json,s)}let r=await yr(e,i);return n.json?h(r,t,!0,i):{exitCode:0,stdout:vn(r,t,i),stderr:""}}function hr(e){let t=l(e,"status")?.toLowerCase(),n=l(e,"reasonCode")?.toLowerCase();return t==="not_found"||t==="missing"||t==="blocked"||t==="not_ready"||n==="skill_not_found"||n==="not_found"}async function yr(e,t){let n=Ai(e);if(n)return{...e,...n};let i=l(e,"skillSlug")??l(e,"slug");if(!i)return e;try{let r=await v(t,`/api/v1/skills/${encodeURIComponent(i)}/trust`),s=Ai(r);return s?{...e,...s}:e}catch{return e}}function Ai(e){let t=S(e,"securityReport")??S(e,"report")??e,n=S(e,"trust")??S(t,"trust")??t,i=S(e,"securityPosture")??S(t,"securityPosture"),r=S(e,"capabilityProfile")??S(t,"capabilityProfile"),s=_({securityScore:O(n,"securityScore")??O(n,"score")??O(e,"securityScore")??(i?O(i,"securityScore"):void 0),runtimeRisk:l(n,"runtimeRisk")??l(e,"runtimeRisk")??(i?l(i,"runtimeRisk"):void 0)??(r?l(r,"runtimeRisk"):void 0),recommendation:l(n,"recommendation")??l(e,"recommendation")??(i?l(i,"recommendation"):void 0),detectedCapabilities:ge(n,"detectedCapabilities")??ge(e,"detectedCapabilities")??(r?ge(r,"detectedCapabilities"):void 0),capabilityMismatches:ge(n,"capabilityMismatches")??ge(e,"capabilityMismatches")??(r?ge(r,"capabilityMismatches"):void 0),organizationPolicyDecision:l(n,"organizationPolicyDecision")??l(n,"policyDecision")??l(e,"organizationPolicyDecision")??l(e,"policyDecision")??(i?l(i,"organizationPolicyDecision"):void 0)});if(Object.keys(s).length!==0)return _({trust:s,runtimeRisk:l(s,"runtimeRisk"),detectedCapabilities:Array.isArray(s.detectedCapabilities)?s.detectedCapabilities:void 0,capabilityMismatches:Array.isArray(s.capabilityMismatches)?s.capabilityMismatches:void 0,organizationPolicyDecision:l(s,"organizationPolicyDecision"),warnings:ge(e,"warnings")??ge(t,"warnings")??ge(n,"warnings")})}function Aa(e){let t=S(e,"securityPosture"),n=S(e,"trust"),i=t?O(t,"securityScore"):void 0,r=n?O(n,"securityScore")??O(n,"score"):void 0;return i===void 0&&r===void 0?e:_({...e,...t?{securityPosture:{...t,scoreLabel:"published_ledger_score"}}:{},...n?{trust:{...n,scoreLabel:"effective_buyer_trust_score"}}:{},publishedLedgerScore:i,effectiveBuyerTrustScore:r})}function at(e,t,n,i){return n?h(e,t,!0,i):{exitCode:0,stdout:vn(e,t,i),stderr:""}}function La(e,t,n){let i=Z(n),r=Array.isArray(e.runs)?e.runs.filter($):[],s=r.flatMap(c=>Array.isArray(c.results)?c.results.filter($):[]),o=r.flatMap(c=>{let u=S(c,"tool"),d=u?S(u,"driver"):void 0;return d&&Array.isArray(d.rules)?d.rules.filter($):[]}),a=[`${i.ok("OK")} Trust report loaded.`,"",i.section("SARIF")];if(a.push(` ${i.label("Skill")}: ${t}`),a.push(` ${i.label("Runs")}: ${r.length}`),a.push(` ${i.label("Rules")}: ${o.length}`),a.push(` ${i.label("Results")}: ${s.length}`),s.length===0)a.push(` ${i.muted("No SARIF findings found.")}`);else{a.push("",i.section("Findings"));for(let[c,u]of s.slice(0,N).entries()){let d=l(u,"ruleId")??"unknown-rule",g=S(u,"message");a.push(`${c+1}. ${d}${g?` - ${l(g,"text")??""}`:""}`)}}return a.push("",i.section("Next")),a.push(` ${i.arrow} skills-layer trust ${t} --format sarif --json`),a.join(`
|
|
1139
|
+
`)}function vn(e,t,n){let i=Z(n),r=[`${i.ok("OK")} ${t}`],s=l(e,"skillSlug")??l(e,"slug"),o=l(e,"version")??l(e,"currentVersion");(s||o)&&(r.push("",i.section("Skill")),s&&r.push(` ${i.label("Slug")}: ${s}`),o&&r.push(` ${i.label("Version")}: ${o}`));let a=l(e,"visibility")??l(e,"versionVisibility"),c=l(e,"publicationStatus"),u=l(e,"catalogRecord");(a||c||u)&&(r.push("",i.section("Privacy")),a&&r.push(` ${i.label("Visibility")}: ${a}`),c&&r.push(` ${i.label("Publication")}: ${c}`),u&&r.push(` ${i.label("Catalog record")}: ${u}`));let d=S(e,"materializationPlan")??S(e,"installPlan"),g=l(e,"scope")??(d?l(d,"scope"):void 0),f=l(e,"agent")??l(e,"targetAgent")??(d?l(d,"agent")??l(d,"targetAgent"):void 0),m=Array.isArray(e.materializedWrites)?e.materializedWrites.filter($):[];if(g||f||m.length>0)if(r.push("",i.section("Local Materialization")),g&&r.push(` ${i.label("Scope")}: ${g}`),f&&r.push(` ${i.label("Agent")}: ${f}`),m.length===0)r.push(` ${i.muted("No local files were written by this command.")}`);else for(let C of m.slice(0,N)){let x=l(C,"path");x&&r.push(` ${i.arrow} ${x}`)}let k=Fr(e,i).filter(C=>!C.includes("materialized writes:"));k.length>0&&r.push("",...k);let w=Vr(e);return w.length>0&&r.push("",i.section("Next"),...w.map(C=>` ${i.arrow} ${C}`)),r.join(`
|
|
1140
|
+
`)}function Ea(e,t){let n=S(e,"trust"),i=S(e,"securityPosture"),r=S(e,"capabilityProfile"),s=n?.securityScore??n?.score??e.securityScore??i?.securityScore,o=T(n,"runtimeRisk")??l(e,"runtimeRisk")??T(i,"runtimeRisk")??T(r,"runtimeRisk"),a=T(n,"recommendation")??l(e,"recommendation")??T(i,"recommendation"),c=T(n,"label")??T(n,"trust")??l(e,"trustStatus")??l(e,"trust")??T(i,"label");if(s===void 0&&!o&&!a&&!c)return[];let u=[t.section("Trust")];return s!==void 0&&u.push(` ${t.label("Security score")}: ${z("securityScore",s)}`),o&&u.push(` ${t.label("Runtime risk")}: ${o}`),a&&u.push(` ${t.label("Recommendation")}: ${a}`),c&&u.push(` ${t.label("Status")}: ${c}`),u.push(` ${t.label("Source")}: skills-layer trust`),u}async function Ua(e,t){let n=kn("installed",e);if(n.failure)return n.failure;let i=await we(t),r=Object.values(i.installs).filter(s=>{let o=l(s,"scope"),a=l(s,"agent");return(!n.scope||o===n.scope)&&(!n.agent||a===n.agent)});return h({status:"ok",results:r},`Found ${r.length} local install records.`,e.json,t)}async function Ta(e,t,n){let i=b(e[0],"remove requires a skill slug."),r=rr("remove",t);if(r)return r;let s=await we(n),o=s.installs[i];if(!o)return P({status:"not_installed",reasonCode:"local_install_not_found",skillSlug:i},`${i} is not installed locally. Run \`skills-layer installed\` or \`skills-layer sync\` to inspect local records.`,t.json,"local_install_not_found");delete s.installs[i],await Ur(n,s);let a={status:"removed",skillSlug:i,removedRecord:o};return t.json?h(a,`Removed ${i}.`,!0,n):{exitCode:0,stdout:Va(i,n),stderr:""}}async function Ba(e,t,n){let i=b(e[0],"update requires a skill slug."),r=new URLSearchParams,s=p(t.pin);if(s&&!Sn(s))return P({status:"error",reasonCode:"invalid_pin",skillSlug:i,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");F(r,"pin",s),t.dryRun&&r.set("dryRun","true");let a=(await we(n)).installs[i],c;try{c=await v(n,`/api/v1/skills/${encodeURIComponent(i)}${oe(r)}`,{headers:M(n.apiKey,n.authBlockedMessage)})}catch(d){if(d instanceof I&&d.status===404&&a){let g={status:"backend_missing",reasonCode:"local_install_backend_missing",skillSlug:i,localInstall:a,installedVersion:l(a,"version")??l(a,"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 ${i}\`, or run \`skills-layer remove ${i}\` if you no longer need it.`};return P(g,`${i} 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(d instanceof I)return yt(d,t.json);throw d}let u=Fa(i,c,a,n);return s&&t.dryRun&&!Na(u,s)?P({status:"not_found",reasonCode:"pin_not_resolved",skillSlug:i,requestedPin:s,installedVersion:l(a,"version")??l(a,"currentVersion"),currentVersion:l(u,"currentVersion"),nextAction:"update",nextStep:`Choose a version returned by \`skills-layer show ${i} --json\` or omit --pin to check the latest available version.`},`${i} does not have a resolvable version for --pin ${s}.`,t.json,"pin_not_resolved"):t.json?h(u,"Update check complete.",!0,n):{exitCode:0,stdout:Ka(u,n),stderr:""}}function Sn(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 Na(e,t){let n=[l(e,"version"),l(e,"currentVersion"),l(e,"latestVersion"),l(e,"targetVersion"),l(e,"availableVersion")].filter(Boolean),i=S(e,"update");return i&&n.push(l(i,"version"),l(i,"currentVersion"),l(i,"latestVersion"),l(i,"targetVersion"),l(i,"availableVersion")),n.some(r=>r===t)}async function Ma(e,t){let n=kn("sync",e);if(n.failure)return n.failure;let i=await we(t),r=Object.values(i.installs).filter(a=>{let c=l(a,"scope"),u=l(a,"agent");return(!n.scope||c===n.scope)&&(!n.agent||u===n.agent)}),o={status:"synced",results:await Promise.all(r.map(async a=>Oa(a,t)))};return e.json?h(o,"Local install records synced.",!0,t):{exitCode:0,stdout:Ga(o,t),stderr:""}}function Fa(e,t,n,i){let r=n?l(n,"version")??l(n,"currentVersion"):void 0,s=l(t,"currentVersion")??l(t,"version"),o=n?r&&s&&r!==s?"update_available":"up_to_date":"not_installed";return _({...t,skillSlug:l(t,"skillSlug")??l(t,"slug")??e,updateStatus:o,installedVersion:r,latestAvailableVersion:s,selectedBackend:i.baseUrl,localInstall:n,nextStep:o==="not_installed"?`Run \`skills-layer install ${e}\` to install this skill locally.`:o==="update_available"?`Run \`skills-layer install ${e}\` to apply the latest available version.`:`No update is needed for ${e}.`})}async function Oa(e,t){let n=l(e,"skillSlug")??l(e,"slug");if(!n)return{...e,syncStatus:"local_only",backendStatus:"unchecked"};try{let i=await v(t,`/api/v1/skills/${encodeURIComponent(n)}`,{headers:He(t.apiKey)}),s=(l(i,"claimedOrigin")??l(i,"sourceKind")??l(e,"sourceKind"))==="public_source"||l(e,"sourceKind")==="external";return{...e,syncStatus:s?"source_backed":"catalog_backed",backendStatus:"found",latestAvailableVersion:l(i,"currentVersion")??l(i,"version"),catalog:qa(i)}}catch(i){return i instanceof I&&i.status===404?{...e,syncStatus:"backend_missing",backendStatus:"not_found",selectedBackend:t.baseUrl}:{...e,syncStatus:"unchecked",backendStatus:"error",backendError:ae(i)}}}function qa(e){return _({slug:l(e,"slug")??l(e,"skillSlug"),currentVersion:l(e,"currentVersion")??l(e,"version"),claimedOrigin:l(e,"claimedOrigin"),trust:l(e,"trust")??l(e,"publicationStatus")})}function Ka(e,t){let n=Z(t),i=l(e,"skillSlug")??l(e,"slug")??"skill",r=l(e,"updateStatus")??"checked",s=[`${n.ok("OK")} Update check complete.`,"",n.section("Update")];s.push(` ${n.label("Skill")}: ${i}`),s.push(` ${n.label("Status")}: ${r.replaceAll("_"," ")}`);let o=l(e,"installedVersion"),a=l(e,"latestAvailableVersion");o&&s.push(` ${n.label("Installed version")}: ${o}`),a&&s.push(` ${n.label("Latest available version")}: ${a}`);let c=S(e,"localInstall"),u=c?l(c,"materializedPath")??l(c,"path"):void 0,d=c?l(c,"scope"):void 0,g=c?l(c,"targetAgent")??l(c,"agent"):void 0;c&&(s.push("",n.section("Local Install")),d&&s.push(` ${n.label("Scope")}: ${d}`),g&&s.push(` ${n.label("Agent")}: ${g}`),u&&s.push(` ${n.label("Path")}: ${u}`));let f=l(e,"nextStep");return f&&s.push("",n.section("Next"),` ${n.arrow} ${f}`),s.join(`
|
|
1141
|
+
`)}function Ga(e,t){let n=Z(t),i=[`${n.ok("OK")} Local install records synced.`,"",n.section(`Results (${e.results.length})`)];return e.results.length===0?(i.push(` ${n.muted("No local install records found.")}`),i.join(`
|
|
1142
|
+
`)):(e.results.slice(0,N).forEach((r,s)=>{let o=l(r,"skillSlug")??l(r,"slug")??`item-${s+1}`,a=l(r,"syncStatus")??"unchecked",c=l(r,"version")??l(r,"currentVersion");i.push(`${s+1}. ${o}`),i.push(` status: ${a.replaceAll("_"," ")}${c?`; version: ${c}`:""}`),a==="backend_missing"&&i.push(` ${n.muted("Installed locally, but missing from the selected backend catalog.")}`)}),e.results.length>N&&i.push(` ${n.muted(`... ${e.results.length-N} more`)}`),i.push("",n.section("Next")),i.push(` ${n.arrow} skills-layer installed`),i.push(` ${n.arrow} skills-layer update <skill-slug>`),i.join(`
|
|
1143
|
+
`))}function Va(e,t){let n=Z(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(`
|
|
1144
|
+
`)}function Da(e,t,n){let i=Z(n),r=l(t,"version")??l(t,"currentVersion"),s=l(t,"scope");return[`${i.ok("OK")} Restore record found for ${e}.`,"",i.section("Local Install"),` ${i.label("Skill")}: ${e}`,...r?[` ${i.label("Version")}: ${r}`]:[],...s?[` ${i.label("Scope")}: ${s}`]:[],"",i.section("Next"),` ${i.arrow} skills-layer installed`,` ${i.arrow} skills-layer sync`,` ${i.arrow} skills-layer update ${e}`].join(`
|
|
1145
|
+
`)}function Ha(e){let t=l(e,"status"),n=l(e,"reasonCode");return t==="invalid_transition"||t==="forbidden"||t==="not_found"||n==="invalid_transition"}function za(e,t){let n=l(e,"why")??l(e,"reason")??l(e,"error"),i=l(e,"currentVisibility"),r=l(e,"nextVisibility")??l(e,"visibility"),s=i||r?` Current visibility: ${i??"unknown"}; requested visibility: ${r??"unknown"}.`:"",o=l(e,"nextStep")??`Run \`skills-layer creator status ${t}\` and choose a valid visibility transition.`;return`Visibility was not changed for ${t}.${s}${n?` ${n}`:""}
|
|
1146
|
+
Next step: ${o}`}async function Wa(e,t,n){let i=await we(n),r=e[0];if(!r){let a=Object.values(i.installs);return h({status:a.length>0?"restored":"no_op",results:a},`Restore checked ${a.length} local install record${a.length===1?"":"s"}.`,t.json,n)}let s=i.installs[r];if(!s)return P({status:"missing_record",reasonCode:"restore_record_not_found",skillSlug:r,record:null,nextAction:"installed",nextStep:`Run \`skills-layer installed\` to see local records, \`skills-layer sync\` to refresh status, or \`skills-layer search ${r}\` if you want to find a catalog/source replacement.`},`No restorable local install record was found for ${r}. Run \`skills-layer installed\`, \`skills-layer sync\`, or \`skills-layer search ${r}\` next.`,t.json,"restore_record_not_found");let o={status:"restored",skillSlug:r,record:s};return t.json?h(o,`Restore checked for ${r}.`,!0,n):{exitCode:0,stdout:Da(r,s,n),stderr:""}}async function Ja(e,t,n){let i=b(e[0],"check requires a skill slug.");return await R(`/api/v1/skills/${encodeURIComponent(i)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function Ya(e,t,n){let i=b(e[0]??t.source,"import requires a source."),r=await pt(i,n.cwd);if(!r){let o=Za(i,t);if(o)return o}let s=await v(n,"/api/v1/source-imports",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_({...r??{source:i},quarantine:t.quarantine,skillSlug:p(t.skill),visibility:p(t.visibility)}))});return await D(n.paths.importsPath,{version:1,lastImport:s,savedAt:n.now()}),h(s,"Source import submitted.",t.json,n)}function Za(e,t){try{return Qe(e).kind!=="local"?null:P({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:ut(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."},ut(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 P({status:"error",reasonCode:"invalid_source",source:e,error:ae(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${ae(n)}`,t.json,"invalid_source")}}function ut(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}async function Qa(e,t,n){let i=e[0];if(i==="reference"&&e[1]==="resolve"){let r=b(e[2],"source reference resolve requires a reference."),s=await v(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(r)}`);return s.status==="not_found"?P({...s,status:"not_found",reasonCode:"source_reference_not_found",reference:r,nextAction:"source.connection.start",nextStep:"Start or complete the source connection before resolving this reference."},`Source reference ${r} was not found.`,t.json,"source_reference_not_found"):h(s,"Source reference resolved.",t.json,n)}return i==="connection"?await Xa(e.slice(1),t,n):y(`Unknown source command "${e.join(" ")}".`,t.json)}async function Xa(e,t,n){let i=e[0];if(i==="start"){let s=p(t.provider),o=p(t.source),a=p(t.visibility),c=el(s,o,a,t);return c||await q("/api/v1/me/source-connections",G(t,["provider","source","skill","mode","visibility","priceCents","license","provenanceIntent","discloseSource"]),t,n,"Source connection started.")}let r=b(e[1],`source connection ${i??""} requires a connection id.`);return i==="status"?await R(`/api/v1/me/source-connections/${encodeURIComponent(r)}`,t,n,"Source connection loaded.",{authenticated:!0}):i==="complete"?await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/complete`,G(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed."):i==="cancel"?await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/cancel`,{},t,n,"Source connection cancelled."):y(`Unknown source connection command "${i??""}".`,t.json)}function el(e,t,n,i){if(n){let r=$t(n);if(!r||!Ft.includes(r))return P({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:Ft,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${Ft.join(", ")}.`,i.json,"invalid_visibility")}if(!e||!t)return null;try{let r=Qe(t);if((e==="github"||e==="gitlab")&&r.kind!==e)return qt(e,t,i);if(e==="domain"){let s=new URL(t);if(s.protocol!=="https:"||!s.hostname)return qt(e,t,i)}}catch{return qt(e,t,i)}return null}function qt(e,t,n){return P({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 tl(e,t,n){if(e[0]!=="request")return y(`Unknown approval command "${e[0]??""}".`,t.json);let i=e[1],r=b(e[2],`approval request ${i??""} requires an approval id.`);return i==="status"?await R(`/api/v1/me/approvals/${encodeURIComponent(r)}`,t,n,"Approval status loaded.",{authenticated:!0}):i==="complete"?await q(`/api/v1/me/approvals/${encodeURIComponent(r)}/complete`,_({decision:p(t.decision),evidence:kt(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed."):y(`Unknown approval request command "${i??""}".`,t.json)}async function nl(e,t,n){let i=e[0]??"list";if(i==="list")return await R("/api/v1/me/workspaces",t,n,"Workspaces loaded.",{authenticated:!0});if(i==="create")return await q("/api/v1/workspaces",{name:e.slice(1).join(" "),kind:p(t.kind)},t,n,"Workspace created.");let r=b(e[1],`workspace ${i} requires a workspace id.`);if(i==="skills")try{return await R(`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0})}catch(s){if(s instanceof I&&(s.status===403||s.status===404))return Kt(r,t);throw s}if(i==="deploy"){let s=b(e[2],"workspace deploy requires a skill slug."),o;try{o=await v(n,`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_({skillSlug:s,dryRun:t.dryRun}))})}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return Kt(r,t);throw a}return t.dryRun?await fr(o,"Workspace deployment preview ready.",t,n):h(o,"Workspace deployment requested.",t.json,n)}if(i==="remove"){let s=b(e[2],"workspace remove requires a skill slug.");try{return await ft(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}`,{method:"DELETE",headers:M(n.apiKey,n.authBlockedMessage)},t,n,"Workspace skill removed.")}catch(o){if(o instanceof I&&o.status===404)return Li(r,s,t);if(o instanceof I&&o.status===403)return Kt(r,t);throw o}}if(i==="guide"){let s=b(e[2],"workspace guide requires a skill slug.");try{return await R(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}catch(o){if(o instanceof I&&o.status===404)return Li(r,s,t);throw o}}return y(`Unknown workspace command "${i}".`,t.json)}function Kt(e,t){return P({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 Li(e,t,n){let i={status:"deployment_not_found",reasonCode:"workspace_deployment_not_found",workspaceId:e,skillSlug:t,nextAction:"workspace.deploy",nextStep:`Run \`skills-layer workspace deploy ${e} ${t}\` first, then run \`skills-layer workspace guide ${e} ${t}\` after the deployment exists.`};return P(i,`Workspace deployment not found for ${t}. Run \`skills-layer workspace deploy ${e} ${t}\` first.`,n.json,"workspace_deployment_not_found")}async function il(e,t,n){let i=b(e[0],"buy requires a skill slug."),r=Uo(t);if(r.failure)return r.failure;let s=await v(n,"/api/v1/buy",{method:"POST",headers:A(n.apiKey),body:JSON.stringify({skillSlug:i,paymentMethod:r.value})});if(s.status==="already_owned")return h(s,`You already own ${i}. Run \`skills-layer install ${i}\` to install or update it.`,t.json,n);if(t.json||s.status!=="checkout_required"||typeof s.checkoutUrl!="string"||typeof s.purchaseId!="string")return h(s,`Purchase flow started for ${i}.`,t.json,n);n.emitInfo(`Opening checkout for ${i}. Complete the payment in your browser, then come back here.`),await n.openUrl(s.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${s.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let a=await Bl(s.purchaseId,n);return H(a)?a:a.status!=="succeeded"&&a.status!=="refund_requested"?h({...s,purchaseStatus:a.status},`Checkout is still ${a.status} for ${i}. You can rerun install after payment reconciliation completes.`,t.json,n):(n.emitInfo("Payment confirmed. Continuing with install."),await wn([i],t,n))}async function rl(e,t,n){let i=e[0]??"list";if(i==="list")return await R("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(i==="spending")return await R("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let r=b(e[1],`purchases ${i} requires a purchase id.`);return i==="invoice"?await R(`/api/v1/purchases/${encodeURIComponent(r)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0}):i==="refund-quote"?await R(`/api/v1/purchases/${encodeURIComponent(r)}/refund-quote`,t,n,"Refund quote loaded.",{authenticated:!0}):i==="refund"?await q(`/api/v1/purchases/${encodeURIComponent(r)}/refund`,G(t,["reason"]),t,n,"Refund requested."):y(`Unknown purchases command "${i}".`,t.json)}async function sl(e,t,n){let i=e[0];if(i==="add"){let r=b(e[1],"library add requires a skill slug.");return await q("/api/v1/install",{skillSlug:r},t,n,"Skill added to library.")}return y(`Unknown library command "${i}".`,t.json)}async function ol(e,t,n){let i=b(e[0],"export requires a skill slug."),r=new URLSearchParams,s=p(t.version);if(s&&!Sn(s))return sr("export",s,t);F(r,"version",s);let o=await v(n,`/api/v1/me/library/${encodeURIComponent(i)}/export${oe(r)}`,{headers:M(n.apiKey,n.authBlockedMessage)}),a=p(t.output);if(a){let c=await lr({backend:n,exportResult:o,flags:t,skillSlug:i});if(H(c))return c;let u=J(n.cwd,a);await an(u,c.bytes);let d={...o};return delete d.downloadUrl,h({...d,archiveSha256:c.archiveSha256,archiveSha256Meaning:"canonical_bundle_sha256",canonicalBundleSha256:c.archiveSha256,downloadedArchiveSha256:c.archiveBytesSha256,downloadedFileSha256:c.archiveBytesSha256,archiveHashFormat:c.archiveHashFormat,outputPath:u,downloaded:!0},`Exported ${i} to ${u}. Downloaded file SHA-256: ${c.archiveBytesSha256}.`,t.json,n)}return h(o,a?`Exported ${i} to ${a}.`:"Export prepared.",t.json,n)}async function Ei(e,t,n,i){let r=b(t[0],`${e==="add"?"add-review":"show-reviews"} requires a skill slug.`);return e==="show"?await R(`/api/v1/me/library/reviews?skillSlug=${encodeURIComponent(r)}`,n,i,"Reviews loaded.",{authenticated:!0}):await q(`/api/v1/me/library/${encodeURIComponent(r)}/review`,G(n,["rating","feedback"]),n,i,"Review added.")}async function Ui(e,t,n,i){let r=b(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);return e==="show"?await R(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0}):await q(`/api/v1/me/library/${encodeURIComponent(r)}/report-issue`,G(n,["issueType","message"]),n,i,"Issue reported.")}async function al(e,t,n){let i=e[0];if(i==="hook"){let r=e[1];return r==="install"?await en(t,n):r==="status"?await dl(t,n):y(`Unknown guardian hook command "${r??""}".`,t.json)}if(i==="enable")return e[1]||t.skill?await Gt("enforce",e,t,n):await en(t,n);if(i==="disable")return await Gt("disabled",e,t,n);if(i==="enable-warnings-only")return await Gt("warning_only",e,t,n);if(i==="status")return await cl(e,t,n);if(i==="exec")return await ll(e,t,n);if(i==="check"){let r=b(e[1]??t.skill,"guardian check requires a skill slug."),s=Ki(t,"check"),o=t.grantJson.map(k=>Ln(k,"grant-json")),a=Mc(t.cloudTrustLedger);if(a.status==="invalid")return y(a.message,t.json);let c=tn(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(c.status==="invalid")return y(c.message,t.json);let u=await br({skillSlug:r,version:p(t.version),action:s,flags:t,backend:n,telemetryMode:c.mode});if(u.status!=="ok")return u.result;let d=u.context.installedPath,g=p(t.version)??u.context.version,f=_({skillSlug:r,version:g,action:s,authorizationGrants:o,path:d,guardianPreference:await Cn(n,r),unmanagedPolicy:u.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:c.mode,localPreflight:ye(u.context)}),m=await v(n,"/api/v1/guardian/enforce",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(f)});return await Me(n,{skillSlug:r,version:g,action:s,decisionStatus:dt(m),reasonCode:nn(m),telemetryMode:c.mode,path:d}),h({...m,localPreflight:ye(u.context)},"Guardian check complete.",t.json,n)}if(i==="incident"){let r=b(e[1]??t.skill,"guardian incident requires a skill slug."),s=b(t.version,"guardian incident requires --version."),o=tn(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return y(o.message,t.json);let a=p(t.path)??(await vr({skillSlug:r,flags:t,backend:n})).installedPath,c=Ki(t,"incident"),u=kt(t.evidenceJson,"evidence-json"),d=o.mode==="cloud_managed"&&!n.apiKey?"local_only":o.mode,g=_({skillSlug:r,version:s,action:c,evidence:u,path:a,telemetryMode:d,incident:!0,reason:p(t.reason)});if(d==="local_only"){if(!a)return y("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let w=await Fi({backend:n,skillSlug:r,version:s,installedPath:a,action:c,reason:p(t.reason)??"Guardian local-only incident"});await Me(n,{skillSlug:r,version:s,action:c,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:d,path:a});let C=Oi(n,r);return await re(C,JSON.stringify({request:g,response:null,localResponse:w,savedAt:n.now()},null,2)),h({status:"written",skillSlug:r,version:s,telemetryMode:d,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:w,incidentStatePath:C,incidentPath:w.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let f=await v(n,"/api/v1/guardian/enforce",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(g)}),m=a?await Fi({backend:n,skillSlug:r,version:s,installedPath:a,action:c,reason:p(t.reason)??"Guardian Cloud-managed incident"}):null;await Ke(n.paths.incidentsDir,{recursive:!0});let k=Oi(n,r);return await re(k,JSON.stringify({request:g,response:f,localResponse:m,savedAt:n.now()},null,2)),await Me(n,{skillSlug:r,version:s,action:c,decisionStatus:dt(f),reasonCode:nn(f),telemetryMode:o.mode,path:a}),h({...f,telemetryMode:o.mode,localResponse:m,incidentPath:k},"Guardian incident recorded.",t.json,n)}return y(`Unknown guardian command "${i??""}".`,t.json)}async function ll(e,t,n){let i=p(t.skill),r=b(i??e[1],"guardian exec requires a skill slug."),s=i?e.slice(1):e.slice(2);if(s.length===0)return y("guardian exec requires a command after --.",t.json);let o=tn(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return y(o.message,t.json);let a=wl(t,s),c=await br({skillSlug:r,version:p(t.version),action:a,flags:t,backend:n,telemetryMode:o.mode});if(c.status!=="ok")return c.result;let u=c.context.installedPath,d=p(t.version)??c.context.version,g=_({skillSlug:r,version:d,action:a,authorizationGrants:t.grantJson.map(C=>Ln(C,"grant-json")),path:u,guardianPreference:await Cn(n,r),telemetryMode:o.mode,localPreflight:ye(c.context)}),f=await v(n,"/api/v1/guardian/enforce",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(g)}),m=dt(f),k=nn(f);if(await Me(n,{skillSlug:r,version:d,action:a,decisionStatus:m,reasonCode:k,telemetryMode:o.mode,path:u}),!bl(f))return P({status:"blocked",reasonCode:k,skillSlug:r,guardian:f,localPreflight:ye(c.context),command:{executable:K(s[0]??""),executed:!1}},"Guardian blocked guarded execution.",t.json,k);if(t.dryRun)return h({status:"allowed",skillSlug:r,guardian:f,localPreflight:ye(c.context),command:{executable:K(s[0]??""),executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let w=await vl(s,n);return{exitCode:w.exitCode,stdout:t.json?JSON.stringify({status:w.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:r,guardian:f,localPreflight:ye(c.context),command:w},warnings:[],links:[],reasonCode:w.exitCode===0?null:"command_failed",handoff:null},null,2):Sl(w),stderr:w.stderr}}async function Gt(e,t,n,i){let r=b(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),s=await v(i,"/api/v1/guardian/mode",{method:"POST",headers:A(i.apiKey),body:JSON.stringify({skillSlug:r,requestedPreference:e,source:"public-cli"})});return s.preferenceAccepted===!0&&await Pl(i,r,s),h(s,s.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,i)}async function cl(e,t,n){let i=p(t.skill)??p(e[1]),r=await kr(n,i),s=await De(n),o=i?await Cl(n,i):void 0,c=l(s,"enforcementLayer")!=="not_installed"&&!!s.strictPreActionBlocking?{status:"installed",reasonCode:"guardian_hook_installed",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."}:{status:"not_installed",reasonCode:"guardian_hook_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`."};return h(_({status:"ok",skillSlug:l(r,"skillSlug")??i,policy:r,localPreference:o,hook:s,cloudPolicy:{status:l(r,"effectiveMode")??l(r,"status")??"unknown",reasonCode:l(r,"reasonCode"),enforcementBoundary:"cloud_policy_when_checked",nextAction:l(r,"nextAction"),nextStep:l(r,"nextStep")},localEnforcement:c,nextAction:l(c,"nextAction"),nextStep:l(c,"nextStep")}),"Guardian status loaded.",t.json,n)}async function kr(e,t){let n=t?await Cn(e,t):void 0;return await v(e,"/api/v1/guardian/status",{method:"POST",headers:A(e.apiKey),body:JSON.stringify(_({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function ul(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 kr(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ae(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function en(e,t){let n=p(e.agent)??"codex",i=Pr(e.scope);if(i.status==="invalid")return y(i.message,e.json);let r=me(t.env,t.platform,t.cwd).find(g=>g.id===n);if(!r)return y(`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json);let s=xl(r,i.scope,t);if(!s)return y(`Guardian ${i.scope} hooks are not available for ${r.displayName}.`,e.json);await Rl(s,t);let o=Rr(t,i.scope),a=qi(Fe(t.cwd,s.hookPath)),c=qi(Fe(t.cwd,s.configPath)),d=[...(await _r(o)).hooks.filter(g=>l(g,"agent")!==r.id||l(g,"scope")!==i.scope),{hookId:pe,hookName:te,agent:r.id,agentName:r.displayName,scope:i.scope,hookPath:a.startsWith("..")?s.hookPath:a,configPath:c.startsWith("..")?s.configPath:c,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,enabledAt:t.now()}];return await D(o,{version:1,hooks:d}),h({status:"enabled",hookId:pe,hookName:te,agent:r.id,agentName:r.displayName,scope:i.scope,hookPath:s.hookPath,configPath:s.configPath,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,agentCommandMatrix:Et({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. Local hooks call `skills-layer guardian check`; shell agents can route risky commands through `skills-layer guardian exec`; MCP-capable agents can call `guardian.check` or `guardian.enforce` before risky tool use.",warnings:s.enforcementLayer==="native_hook_candidate"?["This host does not expose the same stable native hook contract as Codex or Claude Code yet; Skills Layer records the guardrail config for host integration."]:[]},"Guardian hook enabled.",e.json,t)}async function dl(e,t){let n=p(e.scope),i=n?Pr(n):null;if(i?.status==="invalid")return y(i.message,e.json);let r=await De(t,i?.status==="valid"?i.scope:void 0);return h(r,"Guardian status loaded.",e.json,t)}async function De(e,t){let n=t?[t]:["project","global"],i=[];for(let a of n){let c=Rr(e,a),u=await _r(c);for(let d of u.hooks){let g=l(d,"hookPath"),f=g?Mi(e,a,g):null,m=l(d,"configPath"),k=m?Mi(e,a,m):null,w=f?await fe(f):!1,C=k?await fe(k):null,x=w?C===!1?"active_missing_config":"active":"stale_missing_hook";i.push({hookId:l(d,"hookId")??pe,hookName:l(d,"hookName")??te,...d,scope:l(d,"scope")??a,hookPath:f??g??null,configPath:k??m??null,active:w,configActive:C,hookState:x})}}let r=i.filter(a=>a.active===!0).length,s=i.filter(a=>a.active===!1).length,o=r>0?0:s;return{status:"ok",enforcementLayer:r>0?"native_hook":"not_installed",strictPreActionBlocking:i.some(a=>a.active===!0&&a.strictPreActionBlocking===!0),activeHookCount:r,missingHookCount:o,staleHookCount:s,hooks:i,setup:await xn(e),warnings:s>0?r>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 wr(e,t){if(e.json){let u=await Y(t.paths.mcpConfigPath);return h({setup:await xn(t),mcp:{status:u?"mcp_configured":"mcp_not_configured",configured:!!u,clientId:u?l(u,"clientId")??"codex":void 0,clientIds:u&&Array.isArray(u.clientIds)?u.clientIds:void 0,mcpUrl:u?l(u,"mcpUrl"):void 0,readiness:u?{status:"configured_needs_agent_reload",verifyCommand:`skills-layer mcp verify --client ${l(u,"clientId")??"codex"}`,nextStep:"Open a fresh agent session if Skills Layer tools are not visible yet."}:void 0,nextCommand:u?"skills-layer mcp verify":"skills-layer mcp setup"},guardian:await De(t)},"Setup status loaded.",!0,t)}if(!t.stdoutIsTty)return h({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 u={version:1,setupChoice:"not_now",mcpChoice:"not_now",mcpPromptedAt:t.now(),guardianHookChoice:"not_now",guardianHookPromptedAt:t.now(),remindAfter:ml(t.now(),7)};return await Ni(t,u),h({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 y(`Unknown setup option "${n}".`,e.json);let i=n==="both"||n==="mcp",r=n==="both"||n==="security",s={status:"setup_complete",setupChoice:n},o={version:1,setupChoice:n,mcpChoice:i?"configured":"not_requested",mcpPromptedAt:t.now(),guardianHookChoice:r?p(e.scope)??"project":"not_requested",guardianHookPromptedAt:t.now()};if(i)if(!t.apiKey)s.mcp={status:"login_required",configured:!1,nextCommand:"skills-layer login"},o.mcpChoice="login_required";else{let u=await yn(e,t);if(H(u))return u;s.mcp=u}if(r){let u={...e,json:!0,scope:p(e.scope)??"project",agent:p(e.agent)??"codex"},d=await en(u,t);if(d.exitCode!==0)return d;s.security=El(d.stdout)??{status:"enabled",agent:p(u.agent),scope:p(u.scope)}}await Ni(t,o);let c=($(s.mcp)?l(s.mcp,"status"):void 0)==="login_required"?"Skills Layer Security setup complete. MCP setup needs login; run `skills-layer login`, then `skills-layer setup`.":"Skills Layer setup complete. Open a fresh agent session if MCP tools are not visible yet.";return h(s,c,e.json,t)}async function pl(e,t){let n=await De(t),i=await xn(t),r=O(n,"activeHookCount")??0;if(t.stdoutIsTty&&r===0&&!i)return await wr(e,t);let s=r>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:`${Be}
|
|
1147
|
+
|
|
1148
|
+
${s}`,stderr:""}}function gl(e,t){let n=O(e,"activeHookCount")??0,i=O(e,"missingHookCount")??0,r=l(t,"status")??"unknown",s=l(t,"effectiveMode"),o=l(t,"adminPolicy"),a=l(t,"nextAction"),c=l(t,"nextStep");return n>0&&i===0?{id:"guardian-local-hook",title:"Guardian local hook",status:"pass",summary:`Guardian native hook active count: ${n}.`,enforcementLayer:l(e,"enforcementLayer")??"native_hook",strictPreActionBlocking:e.strictPreActionBlocking===!0,policyStatus:r,adminPolicy:o,effectiveMode:s,policyNextAction:a,policyNextStep:c,recommendedCommand:"skills-layer guardian hook status"}:{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian native hook setup needs attention. Active hooks: ${n}; missing hooks: ${i}.`,enforcementLayer:l(e,"enforcementLayer")??"not_installed",strictPreActionBlocking:e.strictPreActionBlocking===!0,policyStatus:r,adminPolicy:o,effectiveMode:s,policyNextAction:a,policyNextStep:c,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 ml(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?e:(n.setUTCDate(n.getUTCDate()+t),n.toISOString())}async function br(e){let t=Sr(p(e.flags.unmanagedPolicy)??e.backend.env.SKILLS_LAYER_UNMANAGED_SKILL_POLICY);if(t.status==="invalid")return{status:"invalid",result:y(t.message,e.flags.json)};let n=await vr({skillSlug:e.skillSlug,flags:e.flags,backend:e.backend,unmanagedPolicy:t.policy});if(n.unmanaged&&n.unmanagedPolicy==="block")return nt({...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.",nextStep:"Install the skill with `skills-layer install <path>` or choose --unmanaged-policy warn/allow for a one-off diagnostic check."});if(!n.installedPath)return{status:"ok",context:n};if(await Al(n.installedPath))return nt({...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 yl(e.skillSlug,n.installedPath);if(n.identityAssessment=i,i.reattestationRequired===!0)return nt({...e,context:n,reasonCode:l(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 r=await kl(e.skillSlug,n.installedPath);return n.driftAssessment=r,r.reattestationRequired===!0?nt({...e,context:n,reasonCode:l(r,"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 nt(e){return await Me(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:P({status:"blocked",skillSlug:e.skillSlug,version:e.version??e.context.version,reasonCode:e.reasonCode,localPreflight:ye(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 vr(e){let t=Sr(p(e.flags.unmanagedPolicy)),n=e.unmanagedPolicy??(t.status==="valid"?t.policy:"warn"),i=p(e.flags.path),r=await fl(e.skillSlug,e.backend),s=i?J(e.backend.cwd,i):r?.installedPath;return{source:i?"explicit_path":r?.source??"install_index",status:i?"ok":r?.status,reasonCode:i?void 0:r?.reasonCode,installedPath:s,archivePath:i?void 0:r?.archivePath,installedPathSource:i?"explicit_path":r?.installedPathSource,version:p(e.flags.version)??r?.version,record:r?.record,unmanaged:!!(i&&!r),unmanagedPolicy:n,allowUnmanagedOnce:e.flags.allowUnmanagedOnce}}async function fl(e,t){let i=(await we(t)).installs[e];if(i){let r=Ti(i,t);return{source:"install_index",installedPath:r.installedPath,archivePath:r.archivePath,installedPathSource:r.installedPathSource,status:r.status,reasonCode:r.reasonCode,version:l(i,"version"),record:i}}for(let r of hl(t)){let s=await Y(r);if(!$(s)||!$(s.installs))continue;let o=s.installs[e];if($(o)){let a=Ti(o,t);return{source:"lockfile",installedPath:a.installedPath,archivePath:a.archivePath,installedPathSource:a.installedPathSource,status:a.status,reasonCode:a.reasonCode,version:l(o,"version"),record:o}}}return null}function hl(e){return Array.from(new Set([L(e.cwd,"skills-layer-lock.json"),L(e.paths.stateDir,"skills-layer-lock.json")]))}function Ti(e,t){let n=l(e,"materializedSkillRoot");if(n)return{installedPath:it(J(t.cwd,n)),installedPathSource:"materializedSkillRoot",status:"ok"};let i=l(e,"canonicalPath");if(i)return{installedPath:it(J(t.cwd,i)),installedPathSource:"canonicalPath",status:"ok"};let r=l(e,"path");if(r)return{installedPath:it(J(t.cwd,r)),installedPathSource:"path",status:"ok"};let s=l(e,"materializedPath")??l(e,"bundlePath");if(s){let u=J(t.cwd,s),d=K(u).toLowerCase()==="bundle.zip"||u.toLowerCase().endsWith(".zip");return{installedPath:d?ee(ee(u)):it(u),archivePath:d?u:void 0,installedPathSource:l(e,"materializedPath")?"materializedPath":"bundlePath",status:d?"degraded":"ok",reasonCode:d?"installed_skill_root_missing":void 0}}let a=(Array.isArray(e.materializedWrites)?e.materializedWrites.filter($):[]).find(u=>{let d=l(u,"path");return d?.toLowerCase().endsWith("/skill.md")||d?.toLowerCase()==="skill.md"}),c=a?l(a,"path"):void 0;return{installedPath:c?ee(J(t.cwd,c)):void 0,installedPathSource:c?"materializedWrites":void 0,status:c?"ok":void 0}}function it(e){return K(e).toLowerCase()==="skill.md"?ee(e):e}async function yl(e,t){let n=L(t,"SKILL.md");if(!await fe(n))return{status:"not_checked",reasonCode:"skill_document_unavailable",expectedSkillSlug:e,reattestationRequired:!1};try{let i=ur(await Ge(n,"utf8"));return i?i!==e?{status:"mismatch",reasonCode:"skill_identity_mismatch",expectedSkillSlug:e,observedSkillName:i,skillDocumentPath:n,reattestationRequired:!0}:{status:"matched",expectedSkillSlug:e,observedSkillName:i,skillDocumentPath:n,reattestationRequired:!1}:{status:"not_checked",reasonCode:"skill_identity_metadata_unavailable",expectedSkillSlug:e,skillDocumentPath:n,reattestationRequired:!1}}catch(i){return{status:"invalid",reasonCode:"skill_identity_unreadable",expectedSkillSlug:e,skillDocumentPath:n,message:ae(i),reattestationRequired:!0}}}async function kl(e,t){let n=L(t,".skills-layer-runtime.json"),i=await Y(n),r=i?S(i,"materialization"):void 0,s=r?l(r,"skillDocumentSha256"):void 0;if(!i||!s)return{status:"not_checked",reasonCode:"runtime_metadata_unavailable",skillSlug:e,reattestationRequired:!1};let o=L(t,"SKILL.md");if(!await fe(o))return{status:"changed",reasonCode:"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:s,reattestationRequired:!0};let a=jr(await Ge(o,"utf8")),c=a===s;return{status:c?"unchanged":"changed",reasonCode:c?"installed_artifact_matches":"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:s,observedSkillDocumentSha256:a,reattestationRequired:!c}}function ye(e){return _({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 Sr(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 tn(e,t){let n=p(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 wl(e,t){let n=kt(e.actionJson,"action-json");return n&&typeof n=="object"&&!Array.isArray(n)?n:{type:"shell_command",command:K(t[0]??"command")}}function bl(e){let t=S(e,"enforcement");return typeof t?.canExecute=="boolean"?t.canExecute:dt(e)!=="blocked"}async function vl(e,t){let[n,...i]=e;return await new Promise((r,s)=>{let o=Wi(n,i,{cwd:t.cwd,env:{...process.env,...t.env},stdio:["ignore","pipe","pipe"]}),a="",c="";o.stdout?.setEncoding("utf8"),o.stderr?.setEncoding("utf8"),o.stdout?.on("data",u=>{a=Bi(`${a}${u}`)}),o.stderr?.on("data",u=>{c=Bi(`${c}${u}`)}),o.on("error",s),o.on("close",u=>{r({executable:K(n),argsCount:i.length,exitCode:typeof u=="number"?u:1,stdout:a,stderr:c})})})}function Bi(e){return e.length>2e4?`${e.slice(0,2e4)}
|
|
1149
|
+
[output truncated]`:e}function Sl(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(`
|
|
1150
|
+
`)}function Pr(e){let t=p(e)??"project";return t==="project"||t==="global"?{status:"valid",scope:t}:{status:"invalid",message:"guardian hooks --scope must be one of: project, global."}}function Cr(e){return L(e.paths.stateDir,"guardian-modes.json")}function xr(e){return L(e.paths.stateDir,"setup-state.json")}async function Pn(e){let t=await Y(Cr(e));return{version:1,skills:$(t?.skills)?t.skills:{}}}async function Pl(e,t,n){let i=await Pn(e);await D(Cr(e),{version:1,skills:{...i.skills,[t]:{requestedPreference:l(n,"requestedPreference")??"enforce",effectiveMode:l(n,"effectiveMode")??"enforce",reasonCode:l(n,"reasonCode"),auditId:l(n,"auditId"),updatedAt:e.now()}}})}async function Cn(e,t){let i=(await Pn(e)).skills[t];return i?l(i,"requestedPreference"):void 0}async function Cl(e,t){return(await Pn(e)).skills[t]}async function xn(e){let t=await Y(xr(e));return $(t)?{version:1,setupChoice:l(t,"setupChoice"),mcpChoice:l(t,"mcpChoice"),mcpPromptedAt:l(t,"mcpPromptedAt"),guardianHookChoice:l(t,"guardianHookChoice"),guardianHookPromptedAt:l(t,"guardianHookPromptedAt"),remindAfter:l(t,"remindAfter")}:null}async function Ni(e,t){await D(xr(e),t)}function xl(e,t,n){let i=t==="global"?e.targets.globalRoot:e.targets.projectRoot;return i?e.id==="codex"?{agent:e.id,agentName:e.displayName,scope:t,hookId:pe,hookName:te,configPath:L(i,"hooks.json"),hookPath:L(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook",strictPreActionBlocking:!0}:e.id==="claude-code"?{agent:e.id,agentName:e.displayName,scope:t,hookId:pe,hookName:te,configPath:L(i,"settings.json"),hookPath:L(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook",strictPreActionBlocking:!0}:e.id==="cline"?{agent:e.id,agentName:e.displayName,scope:t,hookId:pe,hookName:te,configPath:L(i,"guardian-hooks.json"),hookPath:L(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1}:null:null}async function Rl(e,t){if(await re(e.hookPath,jl(e.agentName)),await Yi(e.hookPath,448).catch(()=>{}),e.agent==="codex"){await D(e.configPath,_l(e.hookPath));return}if(e.agent==="claude-code"){await D(e.configPath,$l(e.hookPath));return}e.agent==="cline"&&await D(e.configPath,Il(e,t))}function Rr(e,t){return t==="global"?L(e.paths.stateDir,"guardian-hooks.json"):L(e.cwd,".skills-layer","guardian-hooks.json")}async function _r(e){let t=await Y(e);return{version:1,hooks:Array.isArray(t?.hooks)?t.hooks.filter($):[]}}function Mi(e,t,n){return _e.isAbsolute(n)||n.startsWith("/")?n:Qi(t==="global"?e.paths.stateDir:e.cwd,n)}function _l(e){return{hooks:{PreToolUse:[{name:te,id:pe,matcher:"Bash|Shell|Read|Write|Edit|apply_patch|mcp__.*",hooks:[{name:te,type:"command",command:`node ${Rn(e)}`}]}]}}}function $l(e){return{hooks:{PreToolUse:[{name:te,id:pe,matcher:"Bash|Read|Write|Edit|MultiEdit|NotebookEdit|WebFetch|WebSearch",hooks:[{name:te,type:"command",command:`node ${Rn(e)}`}]}]}}}function Il(e,t){return{version:1,hookId:pe,hookName:te,agent:e.agent,agentName:e.agentName,scope:e.scope,enforcementLayer:e.enforcementLayer,strictPreActionBlocking:e.strictPreActionBlocking,installedAt:t.now(),hooks:[{name:te,id:pe,event:"PreToolUse",command:`node ${Rn(e.hookPath)}`,status:"candidate"}]}}function jl(e){return`#!/usr/bin/env node
|
|
869
1151
|
import { spawnSync } from "node:child_process";
|
|
870
1152
|
import { readFileSync } from "node:fs";
|
|
871
1153
|
|
|
@@ -900,41 +1182,41 @@ const result = spawnSync("skills-layer", [
|
|
|
900
1182
|
], { stdio: ["ignore", "inherit", "inherit"] });
|
|
901
1183
|
|
|
902
1184
|
process.exit(result.status ?? 1);
|
|
903
|
-
`}function
|
|
904
|
-
`;return await
|
|
905
|
-
`),await
|
|
906
|
-
`),await
|
|
907
|
-
`)),{status:"written",generatedAt:t,incidentPath:r,writtenFiles:[n,i,r]}}function
|
|
908
|
-
`,{encoding:"utf8",mode:384}),await
|
|
1185
|
+
`}function Rn(e){return JSON.stringify(e)}async function _n(e){let t=L(ee(e.skillDocumentPath),".skills-layer-runtime.json"),n={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}:{},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:Et({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:jr(e.skillDocumentContent)}},i=`${JSON.stringify(n,null,2)}
|
|
1186
|
+
`;return await re(t,i),{path:ct(e.backend.cwd,t),bytes:new TextEncoder().encode(i).length}}async function Al(e){return await fe(L(e,".skills-layer-disabled.json"))}async function Fi(e){let t=e.backend.now(),n=L(e.installedPath,".skills-layer-disabled.json"),i=L(e.installedPath,".skills-layer-quarantine.json"),r=L(e.installedPath,"incident.md"),s=l(e.action,"type")??"unknown";return await re(n,`${JSON.stringify({disabled:!0,generatedAt:t,skillSlug:e.skillSlug,version:e.version,reason:"Skills Layer Guardian incident response"},null,2)}
|
|
1187
|
+
`),await re(i,`${JSON.stringify({generatedAt:t,skillSlug:e.skillSlug,version:e.version,actions:["disable_skill","quarantine_files","preserve_evidence","generate_incident_report","rescan_before_reenable"],quarantineTargets:[e.installedPath]},null,2)}
|
|
1188
|
+
`),await re(r,["# Skills Layer Guardian Incident Report","",`Generated: ${t}`,`Skill: ${e.skillSlug}`,`Version: ${e.version}`,"","## Summary","",Ir(e.reason),"","## Evidence","",`- ${t}: ${s} -> blocked (incident_recorded)`].join(`
|
|
1189
|
+
`)),{status:"written",generatedAt:t,incidentPath:r,writtenFiles:[n,i,r]}}function Oi(e,t){let n=e.now().replace(/[:.]/gu,"-");return L(e.paths.incidentsDir,`${t}-${n}.json`)}async function Me(e,t){let n=L(e.paths.stateDir,"guardian-audit.jsonl");await Dr(ee(n));let i={version:1,generatedAt:e.now(),skillSlug:t.skillSlug,...t.version?{skillVersion:t.version}:{},actionType:l(t.action,"type")??"unknown",actionTarget:Ll(t.action),decisionStatus:t.decisionStatus,reasonCode:t.reasonCode,telemetryMode:t.telemetryMode,...t.path?{localPath:$r(t.path)}:{}};await io(n,`${JSON.stringify(i)}
|
|
1190
|
+
`,{encoding:"utf8",mode:384}),await An(n,384)}function dt(e){let t=S(e,"decision"),n=S(e,"enforcement"),i=l(t??{},"status")??l(n??{},"status")??l(e,"status");return i==="allowed"||i==="advisory"?i:"blocked"}function nn(e){let t=S(e,"decision");return l(t??{},"reasonCode")??l(e,"reasonCode")??l(e,"status")??"cloud_guardian_decision"}function Ll(e){let t=l(e,"type");if(t==="secret_read")return"redacted_secret";if(t==="shell_command")return"redacted_command";let n=l(e,"url");if(n)try{return new URL(n).origin}catch{return"redacted_url"}let i=l(e,"target");if(i)return Ir(i);let r=l(e,"path");return r?$r(r):null}function $r(e){let t=K(e.trim());return t?`<local-path>/${t}`:"<local-path>"}function Ir(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 qi(e){return e.split(/[\\/]+/u).join("/")}function jr(e){return cn("sha256").update(e).digest("hex")}async function Ar(e,t,n,i,r){let s=await v(i,"/api/v1/verify",{method:"POST",headers:A(),body:JSON.stringify({email:e,code:t,clientDelivery:"cli_secure_storage"})});if(n.json){let o=l(s,"apiKey");return o?(await Oe(i,o,{expectedEmail:e,knownEmail:l(s,"email")??e,knownRole:l(s,"role")??"user",knownRoles:se(s,"roles"),knownUserId:l(s,"userId")}),h(W({...s,loggedIn:!0}),"Email verified and login completed.",!0,i)):h(W({...s,email:e,loggedIn:!1,nextCommand:`skills-layer login --method email --email ${e}`,nextAction:"login"}),"Email verified. Login still needs to be completed.",!0,i)}return await gt(e,s,n,i,r)}async function gt(e,t,n,i,r){let s=l(t,"apiKey"),o=l(t,"role")??"user",a=se(t,"roles"),c=l(t,"userId"),u=s;if(!u)try{u=(await i.promptSecret(`Enter the API key emailed to ${e} (check spam/junk folder if missing): `)).trim()}catch{return h(W({...t,email:e,role:o,...a?{roles:a}:{},loggedIn:!1}),`${r} Check your email (including spam/junk folder) for the API key, then run \`skills-layer login\` to finish signing in.`,n.json,i)}if(!u)return y("No API key was entered. Run `skills-layer login` once you have the emailed key.",n.json);let d=await Oe(i,u,{expectedEmail:e,knownEmail:e,knownRole:o,knownRoles:a,knownUserId:c,forceProfileValidation:!s}),g=await Zt(n,{...i,config:d,apiKey:u});return H(g)?g:h(W({...t,status:l(t,"status")??"verified",email:d.email,role:d.role,...d.roles?{roles:d.roles}:{},loggedIn:!0,...g.data?{mcp:g.data}:{}}),[`${r} Logged in as ${d.email}.`,g.message??""].filter(Boolean).join(" "),n.json,i)}async function $n(e,t,n,i,r){let s=l(t,"authorizationUrl"),o=b(l(t,"state"),"Social auth did not return a state."),a=Kc(e);if(s){let u=await i.openUrl(s);i.emitInfo(u?`${a} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`:`${a} sign-in started. Open this URL in your browser, then come back here once it is done:
|
|
909
1191
|
${s}
|
|
910
|
-
Waiting for browser sign-in to finish...`)}else i.emitInfo(`${a} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`);let c=await ja(o,i);return H(c)?c:c.status==="verified"||c.status==="recovered"?await rt(c.email,{...c},n,i,r==="recovery"?`Recovered access for ${c.email} through ${a}.`:`Verified ${c.email} through ${a}.`):c.status==="already_registered"?f(c,c.linkedAccount===!0?`${a} is now linked to ${c.email}. Run \`skills-layer login\` to sign in.`:`${c.email} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,n.json,i):c.status==="linked"?f(c,`${a} sign-in is now connected.`,n.json,i):_a(c)?k(La(c),n.json):k("Social auth completed with an unexpected response.",n.json)}function H(e){return R(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function $a(e){try{let t=JSON.parse(e);return R(t)?t.data:void 0}catch{return}}function _a(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 ja(e,t){for(let n=0;n<120;n+=1)try{let i=await b(t,`/api/v1/identity/social/status/${encodeURIComponent(e)}`),r=l(i,"status")??"failed";if(r==="pending"){await t.sleep(1500);continue}return(r==="verified"||r==="recovered")&&l(i,"email")&&l(i,"role")?{status:r,email:l(i,"email"),role:l(i,"role"),roles:re(i,"roles"),userId:l(i,"userId"),apiKey:l(i,"apiKey"),keyPrefix:l(i,"keyPrefix"),emailDelivery:l(i,"emailDelivery")}:r==="already_registered"&&l(i,"email")&&l(i,"role")?{status:r,email:l(i,"email"),role:l(i,"role"),roles:re(i,"roles"),linkedAccount:typeof i.linkedAccount=="boolean"?i.linkedAccount:void 0}:r==="linked"?{status:r}:r==="registration_required"||r==="state_expired"||r==="provider_mismatch"||r==="identity_conflict"||r==="email_required"||r==="failed"?{status:r,error:l(i,"error")}:k("Social auth completed with an unexpected response.",!1)}catch(i){if(i instanceof E&&(i.status===404||i.status===429)){await t.sleep(1500);continue}return k(ue(i),!1)}return k("Timed out while waiting for social auth to complete.",!1)}async function Aa(e,t){for(let n=0;n<120;n+=1)try{let r=(await b(t,"/api/v1/purchases",{headers:M(t.apiKey,t.authBlockedMessage)})).results?.find(s=>s.purchaseId===e);if(!r?.status||r.status==="pending"||r.status==="requires_action"){await t.sleep(1500);continue}return{status:r.status,purchaseId:e}}catch(i){if(i instanceof E&&i.status===429){await t.sleep(1500);continue}return k(ue(i),!1)}return k("Timed out while waiting for purchase confirmation.",!1)}async function Ia(e,t){for(let n=0;n<120;n+=1)try{let i=await b(t,`/api/v1/me/private-skill-charges/${encodeURIComponent(e)}`,{headers:M(t.apiKey,t.authBlockedMessage)}),r=l(i,"status");if(!r||r==="checkout_required"||r==="pending"||r==="requires_action"){await t.sleep(1500);continue}return{...i,status:r}}catch(i){if(i instanceof E&&i.status===429){await t.sleep(1500);continue}return k(ue(i),!1)}return k("Timed out while waiting for payment confirmation.",!1)}function Ea(e){let t=S(e,"accountLink");return(t?l(t,"url"):void 0)??l(e,"url")??l(e,"setupUrl")}function La(e){return 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 Ue(e,t,n={}){let r=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole?await b({...e,apiKey:t},"/api/v1/me",{headers:{...M(t),...n.notifyLogin?{"x-skills-layer-session-intent":"login"}:{}}}):{userId:n.knownUserId,email:n.knownEmail,role:n.knownRole,roles:n.knownRoles},s=l(r,"email")??n.knownEmail??"unknown";if(n.expectedEmail&&s.toLowerCase()!==n.expectedEmail.toLowerCase())throw new Error(`The entered API key belongs to ${s}, not ${n.expectedEmail}. Use the API key emailed to ${n.expectedEmail}.`);let o=await b({...e,apiKey:t},"/api/v1/capabilities",{headers:M(t)}),a={version:Si,baseUrl:e.baseUrl,apiKey:t,edition:l(o,"edition")??l(r,"edition")??"saas",userId:l(r,"userId")??n.knownUserId,email:s,role:l(r,"role")??n.knownRole??"user",roles:re(r,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await un(e.paths.configPath,a,e),await D(e.paths.backendPreferencePath,{version:Vt,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),a}function gi(e,t){let n=lt(e.actionJson,"action-json");if(n&&typeof n=="object"&&!Array.isArray(n))return n;let i=g(e.action);return t==="incident"?{type:"file_write",path:g(e.path)??".skills-layer/incidents/guardian-incident.json"}:i==="file_read"||i==="file_write"?{type:i,path:g(e.path)??"."}:i==="shell_command"?{type:"shell_command",command:"unspecified"}:{type:"api_call",...i?{target:i}:{}}}async function C(e,t,n,i,r={}){let s=r.authenticated?M(n.apiKey,n.authBlockedMessage):Ke(n.apiKey);return await st(e,{headers:s},t,n,i)}async function Ta(e,t){let n=await b(t,"/api/v1/doctor",{headers:Ke(t.apiKey)}),i=await qe(t),r=await ra(t),s=[...Qi(n),aa(i,r)];return f({...n,guardian:{...i,policy:r},checks:s},"Doctor checks loaded.",e.json,t)}async function q(e,t,n,i,r){return await st(e,{method:"POST",headers:_(i.apiKey),body:JSON.stringify(j(t))},n,i,r)}async function Be(e,t,n,i,r){return await st(e,{method:"PATCH",headers:_(i.apiKey),body:JSON.stringify(j(t))},n,i,r)}async function st(e,t,n,i,r){let s=await b(i,e,t);return f(s,r,n.json,i)}async function b(e,t,n={}){let i=await e.fetchFn(`${e.baseUrl}${t}`,n).catch(o=>{throw new Error(`Unable to reach ${e.baseUrl}. ${ue(o)}`)});if(!i.ok)throw await Ua(i);let r=await i.text();if(!r)return{};let s=JSON.parse(r);return s&&typeof s=="object"&&!Array.isArray(s)&&"data"in s?s.data:s}async function Ua(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new E(e.status,l(n,"error")??(e.statusText||"Request failed"),n)}catch{return new E(e.status,t)}return new E(e.status,e.statusText||"Request failed")}function M(e,t){if(t)throw new Error(t);if(!e)throw new Error("This command requires login. Run `skills-layer login` first.");return{authorization:`Bearer ${e}`}}function Ke(e){return e?{authorization:`Bearer ${e}`}:{}}function _(e){return{"content-type":"application/json",...Ke(e)}}async function ot(e){let t=await ls(e);if(t.isFile())return[{path:K(e),content:await Oe(e,"utf8")}];if(!t.isDirectory())throw new Error(`Unsupported path: ${e}`);let n=[];if(await Wi(e,e,n),n.length===0)throw new Error(`No readable files found in ${e}.`);return n.sort((i,r)=>i.path.localeCompare(r.path))}async function Wi(e,t,n){for(let i of await bi(t,{withFileTypes:!0})){if(Ba(i.name))continue;let r=A(t,i.name);if(i.isDirectory()){await Wi(e,r,n);continue}if(!i.isFile())continue;let s=Te(e,r).split("\\").join("/");try{n.push({path:s,content:await Oe(r,"utf8")})}catch{continue}}}function Ba(e){return e===".git"||e==="node_modules"||e==="coverage"||e===Ma()||e==="dist"}function Ma(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}async function Nt(e,t){if(/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e))return;let n=W(t,e);try{return await wi(n),{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:await ot(n)}}catch{return}}async function Ct(e,t){let n=Na(t);if(n.length===0)return t;let i=[];for(let r of n){let s=Vi(r.path),o=W(e.cwd,s),a=Te(e.cwd,o);if(!a||a.startsWith("..")||Se.isAbsolute(a))throw new Error(`Cloud install plan attempted to write outside the current workspace: ${r.path}`);if(await ie(o,r.content),i.push({path:s,bytes:new TextEncoder().encode(r.content).length}),K(s).toLowerCase()==="skill.md"){let c=l(t,"skillSlug")??l(t,"slug")??K(X(s)),u=await an({backend:e,skillSlug:c,version:l(t,"version"),skillDocumentPath:o,skillDocumentContent:r.content});i.push(u)}}return{...t,materializedWrites:i}}function Na(e){return[...Rt(e.localWrites),...Rt(S(e,"installPlan")?.localWrites),...Rt(S(e,"materializationPlan")?.localWrites)]}function Rt(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];let n=t,i=g(n.path),r=typeof n.content=="string"?n.content:void 0;return i&&r!==void 0?[{path:i,content:r}]:[]}):[]}function Vi(e){let t=e.replaceAll("\\","/").replace(/^\.\/+/u,"");if(!t||t.includes("\0")||zt.isAbsolute(t)||Se.isAbsolute(e)||t.split("/").includes(".."))throw new Error(`Cloud install plan returned an unsafe local write path: ${e}`);return t}async function Oa(e,t){let n=l(e,"apiKey");if(!n)return;let i={version:Si,baseUrl:t.baseUrl,apiKey:n,edition:l(e,"edition")??t.config?.edition??"saas",userId:l(e,"userId")??t.config?.userId,email:l(e,"email")??t.config?.email??"unknown",role:l(e,"role")??t.config?.role??"user",roles:re(e,"roles")??t.config?.roles,lastSelectedAgent:t.config?.lastSelectedAgent,savedAt:t.now()};await un(t.paths.configPath,i,t)}async function fe(e){let t=await V(e.paths.installsPath);if(!R(t))return{version:Gn,installs:{}};let n=R(t.installs)?pi(t.installs):R(t.skills)?pi(t.skills):{};return{version:typeof t.version=="number"?t.version:Gn,installs:n}}async function Yi(e,t){await D(e.paths.installsPath,t)}async function tt(e,t,n){let i=l(t,"skillSlug")??l(t,"slug")??n,r=await fe(e);r.installs[i]={skillSlug:i,...t,savedAt:e.now()},await Yi(e,r)}function pi(e){let t={};for(let[n,i]of Object.entries(e))t[n]=R(i)?i:{skillSlug:n,value:i};return t}var U=5;function f(e,t,n,i){let s={status:e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"?String(e.status):"ok",summary:t,why:null,nextAction:null,nextStep:null,data:e,warnings:[],links:[],reasonCode:null,handoff:null};return{exitCode:0,stdout:n?JSON.stringify(s,null,2):Fa(e,t,i),stderr:""}}function Fa(e,t,n){let i=Y(n);if(R(e)){if(t==="Status loaded."&&mi(e))return Ha(e,t,i);if(t==="Doctor checks loaded."&&mi(e))return Ja(e,t,i);if(t==="Creator payout profile loaded.")return gl(e,t,i);if(t==="Creator earnings loaded."||t==="Earnings loaded.")return pl(e,"Creator earnings loaded.",i);if(t==="Creator payouts loaded."||t==="Payouts loaded.")return ml(e,"Creator payouts loaded.",i);if(t==="Guardian check complete.")return Ga(e,t,i);if(t==="Reviews loaded.")return Ka(e,t,i);if(t==="Categories loaded.")return qa(e,t,i)}let r=[`${i.ok("OK")} ${t}`];if(R(e)){let s=tr(e,i);s.length>0&&r.push("",...s);let o=or(e);o.length>0&&r.push("",i.section("Next"),...o.map(a=>` ${i.arrow} ${a}`))}return r.join(`
|
|
911
|
-
`)}function
|
|
912
|
-
`)):(i.slice(0,
|
|
913
|
-
`))}function
|
|
914
|
-
`)}function
|
|
915
|
-
`)}function
|
|
916
|
-
`)}function
|
|
917
|
-
`)}function
|
|
918
|
-
`)}function
|
|
919
|
-
`)}function
|
|
920
|
-
`)}function
|
|
921
|
-
`)}function
|
|
922
|
-
`)}function
|
|
923
|
-
`)}function
|
|
924
|
-
`)}function
|
|
925
|
-
`)}function
|
|
926
|
-
`)}function
|
|
927
|
-
`,{encoding:"utf8",mode:384}),await
|
|
928
|
-
`),m())},
|
|
929
|
-
`){
|
|
1192
|
+
Waiting for browser sign-in to finish...`)}else i.emitInfo(`${a} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`);let c=await Tl(o,i);return H(c)?c:c.status==="verified"||c.status==="recovered"?await gt(c.email,{...c},n,i,r==="recovery"?`Recovered access for ${c.email} through ${a}.`:`Verified ${c.email} through ${a}.`):c.status==="already_registered"?h(c,c.linkedAccount===!0?`${a} is now linked to ${c.email}. Run \`skills-layer login\` to sign in.`:`${c.email} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,n.json,i):c.status==="linked"?h(c,`${a} sign-in is now connected.`,n.json,i):Ul(c)?y(Fl(c),n.json):y("Social auth completed with an unexpected response.",n.json)}function H(e){return $(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function El(e){try{let t=JSON.parse(e);return $(t)?t.data:void 0}catch{return}}function Ul(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 Tl(e,t){for(let n=0;n<120;n+=1)try{let i=await v(t,`/api/v1/identity/social/status/${encodeURIComponent(e)}`),r=l(i,"status")??"failed";if(r==="pending"){await t.sleep(1500);continue}return(r==="verified"||r==="recovered")&&l(i,"email")&&l(i,"role")?{status:r,email:l(i,"email"),role:l(i,"role"),roles:se(i,"roles"),userId:l(i,"userId"),apiKey:l(i,"apiKey"),keyPrefix:l(i,"keyPrefix"),emailDelivery:l(i,"emailDelivery")}:r==="already_registered"&&l(i,"email")&&l(i,"role")?{status:r,email:l(i,"email"),role:l(i,"role"),roles:se(i,"roles"),linkedAccount:typeof i.linkedAccount=="boolean"?i.linkedAccount:void 0}:r==="linked"?{status:r}:r==="registration_required"||r==="state_expired"||r==="provider_mismatch"||r==="identity_conflict"||r==="email_required"||r==="failed"?{status:r,error:l(i,"error")}:y("Social auth completed with an unexpected response.",!1)}catch(i){if(i instanceof I&&(i.status===404||i.status===429)){await t.sleep(1500);continue}return y(ae(i),!1)}return y("Timed out while waiting for social auth to complete.",!1)}async function Bl(e,t){for(let n=0;n<120;n+=1)try{let r=(await v(t,"/api/v1/purchases",{headers:M(t.apiKey,t.authBlockedMessage)})).results?.find(s=>s.purchaseId===e);if(!r?.status||r.status==="pending"||r.status==="requires_action"){await t.sleep(1500);continue}return{status:r.status,purchaseId:e}}catch(i){if(i instanceof I&&i.status===429){await t.sleep(1500);continue}return y(ae(i),!1)}return y("Timed out while waiting for purchase confirmation.",!1)}async function Nl(e,t){for(let n=0;n<120;n+=1)try{let i=await v(t,`/api/v1/me/private-skill-charges/${encodeURIComponent(e)}`,{headers:M(t.apiKey,t.authBlockedMessage)}),r=l(i,"status");if(!r||r==="checkout_required"||r==="pending"||r==="requires_action"){await t.sleep(1500);continue}return{...i,status:r}}catch(i){if(i instanceof I&&i.status===429){await t.sleep(1500);continue}return y(ae(i),!1)}return y("Timed out while waiting for payment confirmation.",!1)}function Ml(e){let t=S(e,"accountLink");return(t?l(t,"url"):void 0)??l(e,"url")??l(e,"setupUrl")}function Fl(e){return 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 Oe(e,t,n={}){let r=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole?await v({...e,apiKey:t},"/api/v1/me",{headers:{...M(t),...n.notifyLogin?{"x-skills-layer-session-intent":"login"}:{}}}):{userId:n.knownUserId,email:n.knownEmail,role:n.knownRole,roles:n.knownRoles},s=l(r,"email")??n.knownEmail??"unknown";if(n.expectedEmail&&s.toLowerCase()!==n.expectedEmail.toLowerCase())throw new Error(`The entered API key belongs to ${s}, not ${n.expectedEmail}. Use the API key emailed to ${n.expectedEmail}.`);let o=await v({...e,apiKey:t},"/api/v1/capabilities",{headers:M(t)}),a={version:Xi,baseUrl:e.baseUrl,apiKey:t,edition:l(o,"edition")??l(r,"edition")??"saas",userId:l(r,"userId")??n.knownUserId,email:s,role:l(r,"role")??n.knownRole??"user",roles:se(r,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await jn(e.paths.configPath,a,e),await D(e.paths.backendPreferencePath,{version:mn,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),a}function Ki(e,t){let n=kt(e.actionJson,"action-json");if(n&&typeof n=="object"&&!Array.isArray(n))return n;let i=p(e.action);return t==="incident"?{type:"file_write",path:p(e.path)??".skills-layer/incidents/guardian-incident.json"}:i==="file_read"||i==="file_write"?{type:i,path:p(e.path)??"."}:i==="shell_command"?{type:"shell_command",command:"unspecified"}:{type:"api_call",...i?{target:i}:{}}}async function R(e,t,n,i,r={}){let s=r.authenticated?M(n.apiKey,n.authBlockedMessage):He(n.apiKey);return await ft(e,{headers:s},t,n,i)}async function Ol(e,t){let n=await v(t,"/api/v1/doctor",{headers:He(t.apiKey)}),i=await De(t),r=await ul(t),s=[...Br(n),gl(i,r)];return h({...n,guardian:{...i,policy:r},checks:s},"Doctor checks loaded.",e.json,t)}async function q(e,t,n,i,r){return await ft(e,{method:"POST",headers:A(i.apiKey),body:JSON.stringify(_(t))},n,i,r)}async function mt(e,t,n,i,r){return await ft(e,{method:"PATCH",headers:A(i.apiKey),body:JSON.stringify(_(t))},n,i,r)}async function ft(e,t,n,i,r){let s=await v(i,e,t);return h(s,r,n.json,i)}async function v(e,t,n={}){let i=await e.fetchFn(`${e.baseUrl}${t}`,n).catch(o=>{throw new Error(`Unable to reach ${e.baseUrl}. ${ae(o)}`)});if(!i.ok)throw await ql(i);let r=await i.text();if(!r)return{};let s=JSON.parse(r);return s&&typeof s=="object"&&!Array.isArray(s)&&"data"in s?s.data:s}async function ql(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new I(e.status,l(n,"error")??(e.statusText||"Request failed"),n)}catch{return new I(e.status,t)}return new I(e.status,e.statusText||"Request failed")}function M(e,t){if(t)throw new I(401,t,{error:t,nextAction:"backend.status",nextStep:t});if(!e)throw new I(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 He(e){return e?{authorization:`Bearer ${e}`}:{}}function A(e){return{"content-type":"application/json",...He(e)}}async function ht(e){let t=await ro(e);if(t.isFile())return[{path:K(e),content:await Ge(e,"utf8")}];if(!t.isDirectory())throw new Error(`Unsupported path: ${e}`);let n=[];if(await Lr(e,e,n),n.length===0)throw new Error(`No readable files found in ${e}.`);return n.sort((i,r)=>i.path.localeCompare(r.path))}async function Lr(e,t,n){for(let i of await Zi(t,{withFileTypes:!0})){if(Kl(i.name))continue;let r=L(t,i.name);if(i.isDirectory()){await Lr(e,r,n);continue}if(!i.isFile())continue;let s=Fe(e,r).split("\\").join("/");try{n.push({path:s,content:await Ge(r,"utf8")})}catch{continue}}}function Kl(e){return e===".git"||e==="node_modules"||e==="coverage"||e===Gl()||e==="dist"}function Gl(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}async function pt(e,t){if(/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e))return;let n=J(t,e);try{return await Ji(n),{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:await ht(n)}}catch{return}}async function Vt(e,t){let n=Vl(t);if(n.length===0)return t;let i=[];for(let r of n){let s=Er(r.path),o=J(e.cwd,s),a=Fe(e.cwd,o);if(!a||a.startsWith("..")||_e.isAbsolute(a))throw new Error(`Cloud install plan attempted to write outside the current workspace: ${r.path}`);if(await re(o,r.content),i.push({path:s,bytes:new TextEncoder().encode(r.content).length}),K(s).toLowerCase()==="skill.md"){let c=l(t,"skillSlug")??l(t,"slug")??K(ee(s)),u=await _n({backend:e,skillSlug:c,version:l(t,"version"),skillDocumentPath:o,skillDocumentContent:r.content});i.push(u)}}return{...t,materializedWrites:i}}function Vl(e){return[...Dt(e.localWrites),...Dt(S(e,"installPlan")?.localWrites),...Dt(S(e,"materializationPlan")?.localWrites)]}function Dt(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];let n=t,i=p(n.path),r=typeof n.content=="string"?n.content:void 0;return i&&r!==void 0?[{path:i,content:r}]:[]}):[]}function Er(e){let t=e.replaceAll("\\","/").replace(/^\.\/+/u,"");if(!t||t.includes("\0")||pn.isAbsolute(t)||_e.isAbsolute(e)||t.split("/").includes(".."))throw new Error(`Cloud install plan returned an unsafe local write path: ${e}`);return t}async function Dl(e,t){let n=l(e,"apiKey");if(!n)return;let i={version:Xi,baseUrl:t.baseUrl,apiKey:n,edition:l(e,"edition")??t.config?.edition??"saas",userId:l(e,"userId")??t.config?.userId,email:l(e,"email")??t.config?.email??"unknown",role:l(e,"role")??t.config?.role??"user",roles:se(e,"roles")??t.config?.roles,lastSelectedAgent:t.config?.lastSelectedAgent,savedAt:t.now()};await jn(t.paths.configPath,i,t)}async function we(e){let t=await Y(e.paths.installsPath);if(!$(t))return{version:pi,installs:{}};let n=$(t.installs)?Gi(t.installs):$(t.skills)?Gi(t.skills):{};return{version:typeof t.version=="number"?t.version:pi,installs:n}}async function Ur(e,t){await D(e.paths.installsPath,t)}async function lt(e,t,n){let i=l(t,"skillSlug")??l(t,"slug")??n,r=await we(e);r.installs[i]={skillSlug:i,...t,savedAt:e.now()},await Ur(e,r)}function Gi(e){let t={};for(let[n,i]of Object.entries(e))t[n]=$(i)?i:{skillSlug:n,value:i};return t}var N=5;function h(e,t,n,i){let s={status:e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"?String(e.status):"ok",summary:t,why:null,nextAction:null,nextStep:null,data:e,warnings:[],links:[],reasonCode:null,handoff:null};return{exitCode:0,stdout:n?JSON.stringify(s,null,2):Hl(e,t,i),stderr:""}}function Hl(e,t,n){let i=Z(n);if($(e)){if(t==="Status loaded."&&Vi(e))return Zl(e,t,i);if(t==="Doctor checks loaded."&&Vi(e))return Ql(e,t,i);if(t==="Creator payout profile loaded.")return kc(e,t,i);if(t==="Creator earnings loaded."||t==="Earnings loaded.")return wc(e,"Creator earnings loaded.",i);if(t==="Creator payouts loaded."||t==="Payouts loaded.")return bc(e,"Creator payouts loaded.",i);if(t==="Guardian check complete.")return Jl(e,t,i);if(t==="Reviews loaded.")return Wl(e,t,i);if(t==="Categories loaded.")return zl(e,t,i)}let r=[`${i.ok("OK")} ${t}`];if($(e)){let s=Fr(e,i);s.length>0&&r.push("",...s);let o=Vr(e);o.length>0&&r.push("",i.section("Next"),...o.map(a=>` ${i.arrow} ${a}`))}return r.join(`
|
|
1193
|
+
`)}function zl(e,t,n){let i=de(e.results??e.categories??e.data),r=[`${n.ok("OK")} ${t}`,"",n.section(`Categories (${i.length})`)];return i.length===0?(r.push(` ${n.muted("No categories returned.")}`),r.join(`
|
|
1194
|
+
`)):(i.slice(0,N).forEach((s,o)=>{let a=l(s,"slug")??l(s,"category")??l(s,"name")??`category-${o+1}`,c=l(s,"name")??a,u=s.count;r.push(`${o+1}. ${Gr(c)}`);let d=[a?`slug: ${a}`:void 0,u!==void 0?`count: ${z("count",u)}`:void 0].filter(g=>!!g);d.length>0&&r.push(` ${d.join("; ")}`)}),i.length>N&&r.push(` ${n.muted(`... ${i.length-N} more`)}`),r.join(`
|
|
1195
|
+
`))}function Wl(e,t,n){let i=de(e.reviews??e.results),r=[`${n.ok("OK")} ${t}`,"",n.section(`Reviews (${i.length})`)];return i.length===0&&r.push(` ${n.muted("No reviews yet.")}`),i.forEach((s,o)=>{let a=l(s,"reviewId")??l(s,"id"),u=l(s,"skillSlug")??l(s,"slug")??l(s,"skill")??a??`Review ${o+1}`,d=s.rating??s.score,g=l(s,"status"),f=l(s,"updatedAt")??l(s,"createdAt"),m=[a?`review: ${a}`:void 0,d!=null?`rating: ${z("rating",d)}`:void 0,g?`status: ${g}`:void 0,f?`updated: ${f}`:void 0].filter(w=>!!w);r.push(`${o+1}. ${u}`),m.length>0&&r.push(` ${m.join("; ")}`);let k=l(s,"feedback")??l(s,"comment")??l(s,"message");k&&r.push(` ${n.label("feedback")}: ${Re(k)}`)}),r.join(`
|
|
1196
|
+
`)}function Jl(e,t,n){let i=S(e,"decision"),r=S(e,"enforcement"),s=S(e,"auditEvent"),o=T(i,"status")??T(r,"status")??"unknown",a=T(r,"actionType")??T(s,"actionType")??"action",c=T(i,"capability")??T(r,"capability")??"not specified",u=T(i,"reasonCode")??T(r,"reasonCode")??"not specified",d=T(i,"message")??T(r,"message")??"Guardian policy resolved this action.",g=T(s,"skillSlug")??"unknown",f=T(s,"version")??"unknown",m=Ht(r,"canExecute"),k=Ht(r,"auditRequired"),w=Ht(r,"telemetryRequired"),C=o==="blocked"?"BLOCKED":o==="allowed"?"ALLOWED":"WARNING",x=[`${n.ok("OK")} ${t}`,"",n.section(`${C} ${Yl(a)}`),` ${n.label("Skill")}: ${g}`,` ${n.label("Version")}: ${f}`,` ${n.label("Capability")}: ${c}`,` ${n.label("Reason")}: ${d}`,` ${n.label("Reason code")}: ${u}`,` ${n.label("Can execute")}: ${m===!0?"yes":"no"}`,` ${n.label("Audit required")}: ${k===!1?"no":"yes"}`,` ${n.label("Cloud telemetry")}: ${w===!0?"yes":"no"}`,"",n.section("Next")];return o==="blocked"?x.push(` ${n.arrow} Do not run this action.`,` ${n.arrow} Review \`skills-layer trust ${g}\`.`,` ${n.arrow} Run \`skills-layer guardian incident --skill ${g} --version ${f} --path <installed-skill-path> --reason "<reason>"\` if this was unexpected.`):x.push(` ${n.arrow} Continue only with the action Guardian evaluated.`,` ${n.arrow} Re-run guardian check if the action changes.`),x.join(`
|
|
1197
|
+
`)}function Ht(e,t){if($(e))return typeof e[t]=="boolean"?e[t]:void 0}function T(e,t){return $(e)?l(e,t):void 0}function Yl(e){return e.split(/[_-]+/u).filter(Boolean).map(t=>`${t[0]?.toUpperCase()??""}${t.slice(1)}`).join(" ")}function Vi(e){return!!(S(e,"backend")&&S(e,"auth")&&Array.isArray(e.checks))}function Zl(e,t,n){let i=[`${n.ok("OK")} ${t}`,"",n.section("Readiness")],r=l(e,"summary");r&&i.push(` ${r}`);let s=S(e,"backend"),o=s?nc(s):void 0;o&&i.push(` ${n.label("Backend")}: ${o}`);let a=S(e,"auth"),c=a?ic(a):void 0;c&&i.push(` ${n.label("Account")}: ${c}`);let u=a?O(a,"workspaceCount"):void 0;u!==void 0&&i.push(` ${n.label("Workspaces")}: ${u}`);let d=a?O(a,"libraryCount"):void 0;d!==void 0&&i.push(` ${n.label("Owned skills")}: ${d}`);let g=Tr(e);return g.length>0&&i.push("",n.section("Next"),...g.map(f=>` ${n.arrow} ${f}`)),i.push(` ${n.arrow} Run \`skills-layer doctor\` for diagnostics.`),i.join(`
|
|
1198
|
+
`)}function Ql(e,t,n){let i=[`${n.ok("OK")} ${t}`,"",n.section("Diagnostics")],r=l(e,"summary");r&&i.push(` ${r}`);let s=l(e,"status");s&&i.push(` ${n.label("Status")}: ${s}`);let o=Br(e),a=o.filter(d=>rc(l(d,"status"))),c=o.filter(d=>l(d,"status")!=="pass");i.push(a.length===0?" No blocking issues found.":` ${a.length} check${a.length===1?"":"s"} need attention.`),a.length===0&&c.length>0&&i.push(` Advisory checks needing attention: ${c.length}.`),i.push("",n.section(`Checks (${o.length})`)),o.length===0&&i.push(` ${n.muted("No checks returned by the backend.")}`),o.forEach((d,g)=>{let f=l(d,"status")??"unknown",m=l(d,"title")??l(d,"id")??`Check ${g+1}`;i.push(`${g+1}. ${n.label(`[${f}] ${m}`)}`);let k=l(d,"summary");k&&i.push(` ${k}`);let w=l(d,"why");if(w&&i.push(` ${n.label("Why")}: ${w}`),f!=="pass"){let C=l(d,"nextStep");C&&i.push(` ${n.label("Fix")}: ${C}`);let x=l(d,"recommendedCommand");x&&i.push(` ${n.label("Try")}: ${x}`)}});let u=Tr(e);return u.length>0&&i.push("",n.section(a.length>0?"Recommended Fix":"Next"),...u.map(d=>` ${n.arrow} ${d}`)),i.join(`
|
|
1199
|
+
`)}function Xl(e,t,n,i){let r=[`${n.ok("OK")} ${t}`],s=se(e,"requestedSlugs");s&&s.length>0&&r.push("",n.section("Requested"),` ${s.join(", ")}`);let o=de(e.results);r.push("",n.section(`Comparison (${o.length})`)),o.length===0&&r.push(` ${n.muted("No comparable skills returned.")}`),o.forEach((d,g)=>{let f=sn(d)??`Skill ${g+1}`;r.push(`${g+1}. ${f}`);let m=ec(d);m&&r.push(` ${m}`);let k=Kr(d);k&&r.push(` ${n.label("summary")}: ${i?k.replace(/\s+/gu," ").trim():Re(k)}`)});let a=de(e.missing);a.length>0&&(r.push("",n.section(`Missing (${a.length})`)),a.forEach((d,g)=>{let f=l(d,"slug")??l(d,"skillSlug")??sn(d)??`Entry ${g+1}`,m=l(d,"reason")??l(d,"status");r.push(`${g+1}. ${m?`${f} - ${m}`:f}`)}));let c=se(e,"guidance")??xe(e.guidance);c.length>0&&r.push("",n.section("Guidance"),...c.slice(0,3).map(d=>` ${n.arrow} ${Re(d)}`));let u=tc(o);return u.length>0&&r.push("",n.section("Next"),...u.map(d=>` ${n.arrow} ${d}`)),r.join(`
|
|
1200
|
+
`)}function ec(e){let t=S(e,"securityPosture"),n=l(e,"trust")??l(e,"trustStatus")??l(e,"trustLabel")??(t?l(t,"label"):void 0),i=e.score??e.securityScore??(t?t.securityScore:void 0),r=l(e,"risk")??l(e,"runtimeRisk")??(t?l(t,"runtimeRisk"):void 0);return[["slug",l(e,"slug")??l(e,"skillSlug")],["version",l(e,"version")??l(e,"currentVersion")],["category",l(e,"category")],["type",l(e,"type")??l(e,"skillType")],["trust",n],["score",i],["risk",r]].flatMap(([o,a])=>a==null||a===""?[]:[`${o}: ${z(String(o),a)}`]).join("; ")}function tc(e){let t=[];for(let n of e.slice(0,5)){let i=l(n,"slug")??l(n,"skillSlug");i&&t.push(`skills-layer show ${i}`,`skills-layer trust ${i}`,`skills-layer install ${i}`)}return t}function nc(e){let t=l(e,"edition"),n=l(e,"baseUrl");return t&&n?`${t} at ${n}`:t??n}function ic(e){let t=l(e,"state");if(t&&t!=="authenticated")return t==="anonymous"?"not signed in":t;let n=l(e,"email"),i=se(e,"roles");return n&&i&&i.length>0?`${n} (${i.join(", ")})`:n??l(e,"role")}function Tr(e){let t=[],n=l(e,"recommendedCommand");n&&t.push(n);let i=l(e,"nextStep");return i&&t.push(i),t}function Br(e){return Array.isArray(e.checks)?e.checks.filter($):[]}function rc(e){return e!==void 0&&e!=="pass"&&e!=="warn"&&e!=="advisory"}function de(e){return Array.isArray(e)?e.filter($):[]}function xe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function sc(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 oc={"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 ac(e){let t=xe(e.capabilities);return{status:"ok",edition:l(e,"edition")??"unknown",summary:"Public product capabilities available on the selected backend.",capabilities:t.map(n=>({name:oc[n]??wt(n.replace(/^[^.]+\./u,"").replace(/[._-]+/gu," ")),available:!0})),count:t.length}}function lc(e,t){let n=p(e);if(!n)return;let i=Number(n);return!Number.isInteger(i)||i<=0?y("help optimize-tokens --max-characters must be a positive integer.",t):i<120||i>4e3?y("help optimize-tokens --max-characters must be between 120 and 4000.",t):i}function cc(e,t,n){let i=Z(n),r=S(e,"validation")??e,s=S(r,"parsedSkill")??S(e,"parsedSkill"),o=s?S(s,"frontmatter"):void 0,a=l(e,"skillSlug")??(o?l(o,"name"):void 0),c=r.valid===!0||e.valid===!0,u=zt(r,e,"issues"),d=zt(r,e,"warnings"),g=zt(r,e,"advice"),f=S(r,"stats")??S(e,"stats"),m=[`${i.ok("OK")} Validation complete.`,"",i.section("Bundle")];if(m.push(` ${i.label("Path")}: ${t}`),a&&m.push(` ${i.label("Skill")}: ${a}`),m.push(` ${i.label("Readiness")}: ${c?"ready for dry-run submission":"needs changes before submission"}`),m.push("",i.section("Checks")),m.push(` ${i.arrow} SKILL.md structure and frontmatter`),m.push(` ${i.arrow} Required bundle files and supported directories`),m.push(` ${i.arrow} Secret hygiene, unsafe script signals, and trust-review readiness`),m.push(` ${i.arrow} Trigger quality inputs for should-trigger / should-not-trigger testing`),f){let k=f.fileCount??f.files??e.fileCount,w=f.bodyWordCount??f.bodyWords??e.bodyWordCount;m.push("",i.section("File Summary")),k!==void 0&&m.push(` ${i.label("File count")}: ${z("fileCount",k)}`),w!==void 0&&m.push(` ${i.label("Body words")}: ${z("bodyWordCount",w)}`)}return m.push("",...Wt("Issues",u,i,"No blocking issues found.")),m.push("",...Wt("Warnings",d,i,"No warnings returned.")),m.push("",...Wt("Advice",g,i,"No extra advice returned.")),m.push("",i.section("Next")),m.push(` ${i.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),m.push(` ${i.arrow} skills-layer creator submit ${t} --dry-run`),m.join(`
|
|
1201
|
+
`)}function zt(e,t,n){let i=Array.isArray(e[n])?e[n]:[],r=Array.isArray(t[n])?t[n]:[];return i.length>0?i:r}function Wt(e,t,n,i){let r=[n.section(`${e} (${t.length})`)];return t.length===0?(r.push(` ${n.muted(i)}`),r):(t.slice(0,N).forEach((s,o)=>{r.push(`${o+1}. ${Nr(s)}`)}),r)}function Nr(e){return $(e)?(l(e,"message")??l(e,"title")??l(e,"code")??l(e,"path")??qe(e))||"Details available with --json":z("",e)}function uc(e,t,n){let i=Z(n),r=dc(e),s=pc(e),o=[`${i.ok("OK")} Trigger preview complete.`,"",i.section("Bundle"),` ${i.label("Path")}: ${t}`],a=l(e,"skillSlug")??l(e,"slug");return a&&o.push(` ${i.label("Skill")}: ${a}`),o.push("",i.section(`Prompt Results (${r.length})`)),r.length===0&&o.push(` ${i.muted("No prompt results returned. Use --json to inspect the raw backend response.")}`),r.slice(0,N).forEach((c,u)=>{o.push(`${u+1}. ${gc(c,u)}`)}),o.push("",i.section(`Guidance (${s.length})`)),s.length===0&&o.push(` ${i.muted("No extra trigger guidance returned.")}`),s.slice(0,N).forEach((c,u)=>{o.push(`${u+1}. ${c}`)}),o.push("",i.section("Next")),o.push(` ${i.arrow} skills-layer validate ${t}`),o.push(` ${i.arrow} skills-layer creator submit ${t} --dry-run`),o.join(`
|
|
1202
|
+
`)}function dc(e){return[...de(e.promptResults),...de(e.results),...de(e.shouldTriggerResults),...de(e.shouldNotTriggerResults),...de(e.paraphraseResults)]}function pc(e){let t=xe(e.guidance),n=de(e.guidance).map(i=>Nr(i));return[...t,...n]}function gc(e,t){let n=l(e,"prompt")??l(e,"text")??l(e,"input")??`Prompt ${t+1}`,i=mc(e),r=fc(e),s=hc(e),o=e.score??e.confidence,a=l(e,"reason")??l(e,"explanation")??l(e,"message");return[`"${Re(n)}"`,i?`expected: ${i}`:void 0,r?`actual: ${r}`:void 0,s,o!==void 0?`score: ${z("score",o)}`:void 0,a?`reason: ${Re(a)}`:void 0].filter(c=>!!c).join("; ")}function mc(e){return typeof e.shouldTrigger=="boolean"?e.shouldTrigger?"should trigger":"should not trigger":typeof e.expectedTrigger=="boolean"?e.expectedTrigger?"should trigger":"should not trigger":l(e,"expected")??l(e,"kind")??l(e,"type")}function fc(e){return typeof e.triggered=="boolean"?e.triggered?"triggered":"did not trigger":typeof e.actualTrigger=="boolean"?e.actualTrigger?"triggered":"did not trigger":l(e,"actual")??l(e,"classification")??l(e,"decision")}function hc(e){return typeof e.passed=="boolean"?e.passed?"pass":"fail":typeof e.pass=="boolean"?e.pass?"pass":"fail":l(e,"status")}function yc(e,t,n,i){let r=Z(i),s=l(e,"skillSlug")??K(t),o=[`${r.ok("OK")} Created ${n}.`,"",r.section("Local Skill")];o.push(` ${r.label("Path")}: ${n}`),o.push(` ${r.label("Skill")}: ${s}`);let a=l(e,"skillType"),c=l(e,"category");return a&&o.push(` ${r.label("Type")}: ${a}`),c&&o.push(` ${r.label("Category")}: ${c}`),o.push("",r.section("Next")),o.push(` ${r.arrow} Edit ${n}`),o.push(` ${r.arrow} skills-layer validate ${t}`),o.push(` ${r.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),o.push(` ${r.arrow} skills-layer creator submit ${t} --dry-run`),o.join(`
|
|
1203
|
+
`)}function kc(e,t,n){let i=S(e,"profile")??e,r=Jt(i,"requirementsCurrentlyDue"),s=Jt(i,"requirementsPastDue"),o=Jt(i,"requirementsPendingVerification"),a=["payouts","Enabled"].join(""),c=i.readyForPayouts??i[a],u=c===!0,d=[`${n.ok("OK")} ${t}`,"",n.section("Payout Profile")];return d.push(` ${n.label("Status")}: ${rt(l(i,"status"))}`),d.push(` ${n.label("Ready for payouts")}: ${Hi(c)}`),d.push(` ${n.label("Account details submitted")}: ${Hi(i.detailsSubmitted)}`),d.push(` ${n.label("Currency")}: ${rt(l(i,"currency")?.toUpperCase())}`),d.push(` ${n.label("Country")}: ${rt(l(i,"country")?.toUpperCase())}`),d.push(` ${n.label("Minimum withdrawal")}: ${vc(i)}`),d.push(` ${n.label("Updated at")}: ${rt(l(i,"updatedAt"))}`),d.push("",n.section("Requirements")),d.push(` ${n.label("Currently due")}: ${Yt(r)}`),d.push(` ${n.label("Past due")}: ${Yt(s)}`),d.push(` ${n.label("Pending verification")}: ${Yt(o)}`),d.push("",n.section("Next")),u?(d.push(` ${n.arrow} skills-layer creator earnings`),d.push(` ${n.arrow} skills-layer creator withdraw --amount-cents <amount>`),d.push(` ${n.arrow} skills-layer creator payouts`)):(d.push(` ${n.arrow} skills-layer creator payout-link`),d.push(` ${n.arrow} skills-layer creator earnings`)),d.join(`
|
|
1204
|
+
`)}function wc(e,t,n){let i=rn(e),r=In(e,"withdrawableBalanceCents"),s=[`${n.ok("OK")} ${t}`,"",n.section("Earnings Summary")];return s.push(` ${n.label("Gross sales")}: ${V(e,"successfulSalesCents",i)}`),s.push(` ${n.label("Platform fees")}: ${V(e,"platformFeeCents",i)}`),s.push(` ${n.label("Refunds requested")}: ${V(e,"refundRequestedCents",i)}`),s.push(` ${n.label("Refunded")}: ${V(e,"refundedCents",i)}`),s.push(` ${n.label("Estimated available")}: ${V(e,"estimatedAvailableCents",i)}`),s.push(` ${n.label("Withdrawable now")}: ${V(e,"withdrawableBalanceCents",i)}`),s.push(` ${n.label("Held balance")}: ${V(e,"heldBalanceCents",i)}`),s.push(` ${n.label("Refund exposure")}: ${V(e,"refundExposureCents",i)}`),s.push("",n.section("Activity")),s.push(` ${n.label("Successful purchases")}: ${Di(e,"successfulPurchaseCount")}`),s.push(` ${n.label("Refund requests")}: ${Di(e,"refundRequestedCount")}`),s.push(` ${n.label("Pending payouts")}: ${V(e,"pendingPayoutCents",i)}`),s.push(` ${n.label("Completed payouts")}: ${V(e,"completedPayoutCents",i)}`),s.push("",n.section("Guidance")),r>0?(s.push("1. You have a withdrawable balance available."),s.push("2. Confirm payout setup is ready before requesting withdrawal.")):(s.push("1. No withdrawable balance yet."),s.push("2. Sales will appear here after paid purchases settle.")),s.push("",n.section("Next")),r>0&&s.push(` ${n.arrow} skills-layer creator withdraw --amount-cents ${r}`),s.push(` ${n.arrow} skills-layer creator payout-profile`),s.push(` ${n.arrow} skills-layer creator payouts`),s.join(`
|
|
1205
|
+
`)}function bc(e,t,n){let i=Array.isArray(e.results)?e.results:[],r=rn(e,i),s=In(e,"withdrawableBalanceCents"),o=[`${n.ok("OK")} ${t}`,"",n.section("Payout History")];return o.push(` ${n.label("Withdrawable now")}: ${V(e,"withdrawableBalanceCents",r)}`),o.push(` ${n.label("Pending payouts")}: ${V(e,"pendingPayoutCents",r)}`),o.push(` ${n.label("Completed payouts")}: ${V(e,"completedPayoutCents",r)}`),o.push("",n.section(`Requests (${i.length})`)),i.length===0?o.push(` ${n.muted("No payout requests yet.")}`):(i.slice(0,N).forEach((a,c)=>{if(!$(a)){o.push(`${c+1}. ${z("",a)}`);return}let u=rn(a,void 0,r),d=l(a,"payoutId")??l(a,"id")??`Payout ${c+1}`,g=l(a,"status")??"unknown",f=V(a,"amountCents",u),m=l(a,"requestedAt"),k=l(a,"completedAt"),w=l(a,"reason");o.push(`${c+1}. ${d}`),o.push(` ${n.label("Amount")}: ${f}; ${n.label("Status")}: ${g}`),m&&o.push(` ${n.label("Requested")}: ${m}`),k&&o.push(` ${n.label("Completed")}: ${k}`),w&&o.push(` ${n.label("Reason")}: ${w}`)}),i.length>N&&o.push(` ${n.muted(`... ${i.length-N} more`)}`)),o.push("",n.section("Guidance")),i.length===0?o.push("1. Payouts appear here after you request a withdrawal."):o.push("1. Use this history to track requested, processing, paid, or failed payouts."),o.push("2. Check payout profile if setup or verification looks incomplete."),o.push("",n.section("Next")),s>0&&o.push(` ${n.arrow} skills-layer creator withdraw --amount-cents ${s}`),o.push(` ${n.arrow} skills-layer creator earnings`),o.push(` ${n.arrow} skills-layer creator payout-profile`),o.join(`
|
|
1206
|
+
`)}function rn(e,t,n="GBP"){let i=l(e,"currency");if(i)return i.toUpperCase();let r=t?.find($);if(r){let s=l(r,"currency");if(s)return s.toUpperCase()}return n}function In(e,t){return O(e,t)??0}function Di(e,t){return O(e,t)??0}function V(e,t,n){return`${Mr(In(e,t))} ${n}`}function Jt(e,t){return(se(e,t)??[]).map(n=>n.replace(/[._-]+/gu," "))}function Yt(e){return e.length>0?e.join(", "):"none"}function Hi(e){return e===!0?"yes":e===!1?"no":"unknown"}function rt(e){return e??"none"}function vc(e){let t=O(e,"minimumWithdrawalAmountCents"),n=l(e,"currency")?.toUpperCase()??"minor units";return t===void 0?"none":`${Mr(t)} ${n}`}function Mr(e){return(e/100).toFixed(2).replace(/\.00$/u,"").replace(/(\.\d)0$/u,"$1")}function Z(e){let t=Sc(e);return{ok:n=>t?Ce(32,n):n,section:n=>t?Ce(1,Ce(36,n)):n,label:n=>t?Ce(1,n):n,muted:n=>t?Ce(2,n):n,arrow:t?Ce(36,"->"):"->"}}function Sc(e){let t=e?.env??{};if(t.NO_COLOR)return!1;let n=t.FORCE_COLOR;return n&&n!=="0"?!0:!!e?.stdoutIsTty&&t.TERM!=="dumb"&&n!=="0"}function Ce(e,t){return`\x1B[${e}m${t}\x1B[0m`}function Fr(e,t){let n=[],i=Cc(e,t);i.length>0&&n.push(...i);for(let[r,s]of _c(e))if(Array.isArray(s))n.push(...Pc(r,s,t));else if($(s)){let o=qe(s);o&&n.push(` ${t.label(on(r))}: ${o}`)}else n.push(` ${t.label(on(r))}: ${z(r,s)}`);return n}function Pc(e,t,n){let i=$c(e),r=[n.section(`${i} (${t.length})`)];return t.length===0?(r.push(` ${n.muted("No entries.")}`),r):(t.slice(0,N).forEach((s,o)=>{r.push(...Or(s,o,n))}),t.length>N&&r.push(` ${n.muted(`... ${t.length-N} more`)}`),r)}function Or(e,t,n){if(!$(e))return[`${t+1}. ${z("",e)}`];let i=sn(e)??X(qe(e))??`Item ${t+1}`,r=[`${t+1}. ${i}`],s=Kr(e);s&&r.push(` ${s}`);let o=qe(e);return o&&r.push(` ${o}`),r}function Cc(e,t){let n=Ea(e,t);if(n.length>0)return n;let i=S(e,"capabilityProfile"),r=i?l(i,"runtimeRisk"):void 0;return r?[t.section("Trust"),` ${t.label("Runtime risk")}: ${r}`]:[]}function xc(e,t,n){let i=Z(n),r=l(e,"skillSlug")??t,s=l(e,"runtimeRisk")??(S(e,"capabilityProfile")?l(S(e,"capabilityProfile"),"runtimeRisk"):void 0),o=[`${i.ok("OK")} Creator security report loaded.`,"",i.section("Creator Security")];e.securityScore!==void 0&&o.push(` ${i.label("Security score")}: ${z("securityScore",e.securityScore)}`),s&&o.push(` ${i.label("Runtime risk")}: ${s}`);let a=l(e,"recommendation");a&&o.push(` ${i.label("Recommendation")}: ${a}`),o.push(` ${i.label("Skill")}: ${r}`);let c=l(e,"version");c&&o.push(` ${i.label("Version")}: ${c}`);let u=["semantic","review","no","reviewable","findings"].join("_"),d=xe(e.reviewDegradedReasons).includes(u),g=xe(e.trustBadges).filter(k=>k==="capability-mismatch"),f=xe(e.trustBadges).filter(k=>k!=="capability-mismatch");(d||g.length>0)&&(o.push("",i.section("Creator Notes")),d&&o.push("1. Semantic review was not needed because there were no reviewable findings."),g.forEach((k,w)=>{o.push(`${d?w+2:w+1}. ${k==="capability-mismatch"?"Capability declaration needs review.":k}`)})),f.length>0&&(o.push("",i.section(`Trust badges (${f.length})`)),f.slice(0,N).forEach((k,w)=>o.push(`${w+1}. ${k}`)));let m=Array.isArray(e.findings)?e.findings:[];return o.push("",i.section(`Findings (${m.length})`)),m.length===0?o.push(` ${i.muted("No entries.")}`):m.slice(0,N).forEach((k,w)=>{o.push(...Or(k,w,i))}),o.push("",i.section("Next")),o.push(` ${i.arrow} skills-layer creator rescan-security ${r}`),o.push(` ${i.arrow} skills-layer creator status ${r}`),o.push(` ${i.arrow} skills-layer trust ${r}`),o.join(`
|
|
1207
|
+
`)}function Rc(e,t,n){let r=S(e,"report")??e,s=Z(n),o=r.securityScore,a=l(r,"generatedAt")??l(r,"reportGeneratedAt"),c=Array.isArray(r.findings)?r.findings:void 0,u=[`${s.ok("OK")} Security rescan requested.`,"",s.section("Creator Security")];return u.push(` ${s.label("Skill")}: ${l(r,"skillSlug")??t}`),o!==void 0&&u.push(` ${s.label("Security score")}: ${z("securityScore",o)}`),c&&u.push(` ${s.label("Findings")}: ${c.length}`),a&&u.push(` ${s.label("Generated at")}: ${a}`),u.push("",s.section("Next")),u.push(` ${s.arrow} skills-layer creator security-report ${t}`),u.push(` ${s.arrow} skills-layer creator status ${t}`),u.join(`
|
|
1208
|
+
`)}function _c(e){return Object.entries(e).filter(([t,n])=>qr(t,n))}function qr(e,t){let n=e.toLowerCase();return n==="status"||n==="securityscore"||n==="recommendation"||n==="capabilityprofile"||n==="securityposture"||n==="trust"||n.includes("apikey")||n.includes("secret")||n.includes("token")||n==="content"?!1:t!==void 0}function qe(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"],["revocable","revocable"],["revokeCommand","revoke"],["deploymentId","deployment"],["source","source"],["scope","scope"],["agent","agent"],["bytes","bytes"],["fileCount","file count"],["bodyWordCount","body words"]].flatMap(([r,s])=>{if(!qr(r,e[r]))return[];let o=e[r];return o===void 0?[]:[`${s}: ${z(r,o)}`]}),i=S(e,"securityPosture");if(i){let r=l(i,"label"),s=l(i,"runtimeRisk");r&&n.push(`trust: ${r}`),s&&n.push(`risk: ${s}`)}return n.join("; ")}function Kr(e){return l(e,"shortDescription")??l(e,"summary")??l(e,"description")??l(e,"message")}function sn(e){return l(e,"displayName")??l(e,"name")??l(e,"title")??l(e,"slug")??l(e,"skillSlug")??l(e,"code")??l(e,"id")}function z(e,t){return e==="downloadUrl"?"<hidden; use --json or --output>":typeof t=="string"?e.toLowerCase()==="category"?Gr(t):Re(t):typeof t=="number"||typeof t=="boolean"?String(t):t===null?"none":Array.isArray(t)?`${t.length} item${t.length===1?"":"s"}`:$(t)?qe(t)||"details available with --json":String(t)}function Gr(e){return Qn(e)}function Re(e){let t=e.replace(/\s+/gu," ").trim();return t.length>160?`${t.slice(0,157)}...`:t}function $c(e){return wt(on(e))}function on(e){return e.replace(/([a-z0-9])([A-Z])/gu,"$1 $2").replace(/[_-]+/gu," ").toLowerCase()}function Vr(e){let t=Ic(e),n=t?[`skills-layer show ${t}`,`skills-layer trust ${t}`,`skills-layer install ${t}`]:[],i=typeof e.downloadUrl=="string",r=Array.isArray(e.materializedWrites)&&e.materializedWrites.length>0;return i&&n.push("Use --output <path> to write exports without printing temporary download URLs"),r&&n.push("Review the materialized files in this workspace"),e.valid===!0&&n.push("skills-layer creator submit <path> --dry-run"),n}function Ic(e){let t=l(e,"skillSlug")??l(e,"slug");if(t)return t;let n=e.results;if(Array.isArray(n)){for(let i of n)if($(i)){let r=l(i,"skillSlug")??l(i,"slug");if(r)return r}}}function $(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function y(e,t){return{exitCode:1,stdout:"",stderr:t?JSON.stringify({status:"error",summary:e,why:null,nextAction:null,nextStep:null,data:{error:e},warnings:[],links:[],reasonCode:null,handoff:null},null,2):e}}function P(e,t,n,i){let r={status:l(e,"status")??"error",summary:t,why:l(e,"why")??null,nextAction:l(e,"nextAction")??null,nextStep:l(e,"nextStep")??null,data:e,warnings:Array.isArray(e.warnings)?e.warnings:[],links:Array.isArray(e.links)?e.links:[],reasonCode:i??l(e,"reasonCode")??null,handoff:e.handoff??null};return{exitCode:1,stdout:"",stderr:n?JSON.stringify(r,null,2):t}}function yt(e,t){let n=e.details??{};if(e.status===401){let s=l(n,"error")??"Login required.",o=l(n,"nextAction")??"login",a=l(n,"nextStep")??"Run `skills-layer login` to sign in, then retry this command.";return P({status:"login_required",reasonCode:"login_required",error:s,nextAction:o,nextStep:a},`${s==="Login required."?"Login required":s}. ${a}`,t,"login_required")}let i=l(n,"reasonCode");if(i){let s=l(n,"error")??e.message;return P({status:l(n,"status")??(e.status===404?"not_found":"error"),...n,reasonCode:i},s,t,i)}let r=jc(e);return r?P(r.payload,r.message,t,r.reasonCode):y(l(n,"error")??e.message,t)}function jc(e){let t=l(e.details??{},"error")??e.message,n=t.toLowerCase();return 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("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."}}:null}async function Y(e){try{return JSON.parse(await Ge(e,"utf8"))}catch{return null}}async function Ac(e,t){let n=await Y(e);return n?li(n,{env:t.env,platform:t.platform,store:t.credentialStore}):null}async function jn(e,t,n){let i=await ai(t,{env:n.env,platform:n.platform,store:n.credentialStore});await D(e,i)}async function D(e,t){await Dr(ee(e)),await dn(e,`${JSON.stringify(t,null,2)}
|
|
1209
|
+
`,{encoding:"utf8",mode:384}),await An(e,384)}async function Dr(e){await Ke(e,{recursive:!0,mode:448}),await An(e,448)}async function An(e,t){if(process.platform!=="win32")try{await Yi(e,t)}catch{}}async function re(e,t){await Ke(ee(e),{recursive:!0}),await dn(e,t,"utf8")}async function an(e,t){await Ke(ee(e),{recursive:!0}),await dn(e,t)}function Lc(e=process.stdin,t=process.stdout,n=gn){return async i=>{if(!e.isTTY||!t.isTTY)throw new Error("Interactive prompt is not available in this environment.");let r=n({input:e,output:t});try{return(await r.question(i)).trim()}finally{r.close()}}}function Ec(e=process.stdin,t=process.stdout,n=gn){return async i=>{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((s,o)=>{let a=e,c=a.isRaw===!0,u="",d=!1,g=m=>{d||(d=!0,a.off("data",f),a.setRawMode(c),a.pause?.(),t.write(`
|
|
1210
|
+
`),m())},f=m=>{let k=typeof m=="string"?m:m.toString("utf8");for(let w of k){if(w==="\r"||w===`
|
|
1211
|
+
`){g(()=>s(u.trim()));return}if(w===""){g(()=>o(new Error("Interactive secret prompt cancelled.")));return}if(w==="\b"||w==="\x7F"){u.length>0&&(u=u.slice(0,-1),t.write("\b \b"));continue}u+=w,t.write("*")}};t.write(i),a.resume?.(),a.on("data",f),a.setRawMode(!0)});let r=n({input:e,output:t,terminal:!0});r.stdoutMuted=!0,r._writeToOutput=function(o){if(!this.stdoutMuted){t.write(o);return}if(o==="\b"||o==="\x7F"){t.write("\b \b");return}if(o!=="\r"&&o!==`
|
|
930
1212
|
`){let a=[...o].filter(c=>c!=="\r"&&c!==`
|
|
931
1213
|
`).length;a>0&&t.write("*".repeat(a))}};try{t.write(i);let s=await r.question("");return t.write(`
|
|
932
|
-
`),s.trim()}finally{r.close()}}}function
|
|
933
|
-
`);for(let[x,
|
|
1214
|
+
`),s.trim()}finally{r.close()}}}function Uc(e=process.stdin,t=process.stdout,n=gn){return async(i,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.");let s=e;if(typeof s.setRawMode=="function"&&typeof s.on=="function"&&typeof s.off=="function")return new Promise((a,c)=>{let u=0,d="",g=0,f=!1,m=s.isRaw===!0,k=()=>{g>0&&t.write(`\x1B[${g}F\x1B[J`),t.write(`${i}
|
|
1215
|
+
`);for(let[x,E]of r.entries())t.write(`${Tc(x===u)} ${x+1}. ${zi(E)}
|
|
934
1216
|
`);t.write(`Choice: ${d}
|
|
935
1217
|
`),t.write(`Use up/down arrows, type a number, then press Enter.
|
|
936
|
-
`),
|
|
937
|
-
`),x())},
|
|
938
|
-
`)){if(d){let
|
|
939
|
-
`);for(let[u,d]of r.entries())t.write(`${u+1}. ${
|
|
940
|
-
`);let a=(await o.question("Choose a number and press enter: ")).trim(),c=Number.parseInt(a,10)-1;if(Number.isNaN(c)||c<0||c>=r.length)throw new Error("No valid option selected.");return r[c].value}finally{o.close()}}}function
|
|
1218
|
+
`),g=r.length+3},w=x=>{f||(f=!0,s.off?.("data",C),s.setRawMode?.(m),s.pause?.(),t.write(`
|
|
1219
|
+
`),x())},C=x=>{let E=typeof x=="string"?x:x.toString("utf8");if(E.includes("")){w(()=>c(new Error("Interactive selection cancelled.")));return}if(E.includes("\x1B[A")){d="",u=(u-1+r.length)%r.length,k();return}if(E.includes("\x1B[B")){d="",u=(u+1)%r.length,k();return}if(E.includes("\r")||E.includes(`
|
|
1220
|
+
`)){if(d){let U=Number.parseInt(d,10)-1;if(Number.isNaN(U)||U<0||U>=r.length){d="",t.write("\x07"),k();return}u=U}w(()=>a(r[u]?.value??r[0].value));return}if(E.includes("\b")||E.includes("\x7F")){d=d.slice(0,-1);let U=Number.parseInt(d,10)-1;!Number.isNaN(U)&&U>=0&&U<r.length&&(u=U),k();return}let le=[...E].filter(U=>/[0-9]/u.test(U));if(le.length>0){d=`${d}${le.join("")}`;let U=Number.parseInt(d,10)-1;!Number.isNaN(U)&&U>=0&&U<r.length&&(u=U),k()}};k(),s.resume?.(),s.on("data",C),s.setRawMode(!0)});let o=n({input:e,output:t});try{t.write(`${i}
|
|
1221
|
+
`);for(let[u,d]of r.entries())t.write(`${u+1}. ${zi(d)}
|
|
1222
|
+
`);let a=(await o.question("Choose a number and press enter: ")).trim(),c=Number.parseInt(a,10)-1;if(Number.isNaN(c)||c<0||c>=r.length)throw new Error("No valid option selected.");return r[c].value}finally{o.close()}}}function Tc(e){return e?"\x1B[36m>\x1B[0m":" "}function zi(e){return e.description?`${e.label} (${e.description})`:e.label}function Bc(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(i=>{try{let r=Wi(n.file,n.args,{detached:!0,stdio:"ignore"});r.on("error",()=>i(!1)),r.unref(),i(!0)}catch{i(!1)}})}}function G(e,t){let n={};for(let i of t){let r=e[i];r!==void 0&&r!==!1&&(i.endsWith("Cents")||i==="rating"?n[i]=Number(r):n[i]=r)}return _(n)}function Nc(e){let t=e.results;return Array.isArray(t)?t.flatMap(n=>{if(!n||typeof n!="object"||Array.isArray(n))return[];let i=l(n,"slug")??l(n,"skillSlug");return i?[i]:[]}):[]}function Mc(e){let t=p(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 _(e){let t={};for(let[n,i]of Object.entries(e))i!==void 0&&(t[n]=i);return t}function kt(e,t){let n=p(e);return n?Ln(n,t):void 0}function Ln(e,t){try{return JSON.parse(e)}catch{throw new Error(`--${t} must be valid JSON.`)}}function W(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 ln(e){let t=W(e);for(let n of["role","roles","verifiedAt","expiresAt","userId","tenantId","linkedAccount","linkedIdentity","createdUser"])delete t[n];return t}function b(e,t){let n=p(e);if(!n)throw new Error(t);return n}function p(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function X(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function l(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function O(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim().length>0){let i=Number(n);return Number.isFinite(i)?i:void 0}}function S(e,t){let n=e[t];return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function se(e,t){let n=e[t];return Array.isArray(n)?n.filter(i=>typeof i=="string"):void 0}function ge(e,t){let n=e[t];return Array.isArray(n)?n:void 0}function Fc(e){return S(e,"data")??e}function Oc(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 F(e,t,n){let i=p(n);i&&e.set(t,i)}function oe(e){let t=e.toString();return t?`?${t}`:""}function ie(e){return e.replace(/\/+$/u,"")}function ke(e){if(ie(e)===fn)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 Hr(e){return e.includes("/")||e.startsWith(".")||/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e)}function J(e,t){return Qi(e,t)}function wt(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var qc={github:"GitHub",gitlab:"GitLab",google:"Google",microsoft:"Microsoft"};function Kc(e){return qc[e.toLowerCase()]??wt(e)}function ae(e){return e instanceof Error?e.message:String(e)}export{Nu as executePublicCli};
|