skills-layer 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -4
- package/public/skills-layer-public.mjs +239 -71
- package/tests/public-cli-package.test.mjs +169 -0
- package/scripts/postinstall.mjs +0 -92
|
@@ -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 ir}from"node:child_process";import{createHash as Nt}from"node:crypto";import{access as sr,appendFile as Ei,chmod as or,mkdir as Te,readdir as ar,readFile as Be,rm as Ot,stat as Ui,writeFile as et}from"node:fs/promises";import{basename as G,dirname as ie,join as I,posix as Ft,relative as Ie,resolve as lr,win32 as ve}from"node:path";import{createInterface as qt}from"node:readline/promises";import{spawn as pn}from"node:child_process";import{createHash as Yr}from"node:crypto";import{chmod as Qr,mkdir as Ge,readFile as mn,rm as ct,writeFile as me}from"node:fs/promises";import{dirname as Ce,posix as Zr,win32 as Xr}from"node:path";import{posix as Jr,win32 as zr}from"node:path";var at=["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"],on=[$("codex","Codex",".codex",{capabilities:U({allowedTools:!0})}),$("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:U({allowedTools:!0,hooks:!0,forkedContext:!0})}),$("cursor","Cursor",".cursor",{capabilities:U({allowedTools:!0})}),$("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:U({allowedTools:!0})}),ne("amp","Amp",".config/agents",{capabilities:U({allowedTools:!0})}),ne("kimi-cli","Kimi Code CLI",".config/agents"),ne("replit","Replit",".config/agents"),ne("universal","Universal",".config/agents"),ne("antigravity","Antigravity",".gemini/antigravity",{capabilities:U({allowedTools:!0}),detectGlobal:!0}),$("augment","Augment",".augment"),{id:"openclaw",displayName:"OpenClaw",envVar:"OPENCLAW_HOME",capabilities:U({allowedTools:!0}),targets:{projectRootRelativePath:null,projectSkillsRelativePath:"skills",globalRootRelativePath:".openclaw",globalSkillsRelativePath:".openclaw/skills"},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:[".openclaw",".openclaw/skills"]}},ne("cline","Cline",".agents",{capabilities:U({allowedTools:!0,hooks:!0})}),ne("warp","Warp",".agents"),$("codebuddy","CodeBuddy",".codebuddy",{capabilities:U({allowedTools:!0})}),$("command-code","Command Code",".commandcode",{capabilities:U({allowedTools:!0})}),$("continue","Continue",".continue"),$("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),$("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),ne("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),$("droid","Droid",".factory"),ne("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),ne("github-copilot","GitHub Copilot",".copilot",{capabilities:U({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:U({allowedTools:!0})}),$("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:U({allowedTools:!0})}),$("qoder","Qoder",".qoder",{capabilities:U({allowedTools:!0})}),$("qwen-code","Qwen Code",".qwen"),$("roo","Roo Code",".roo",{capabilities:U({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:U({allowedTools:!0})}),$("neovate","Neovate",".neovate",{capabilities:U({allowedTools:!0})}),$("pochi","Pochi",".pochi"),$("adal","AdaL",".adal")];function ae(e=process.env,t=process.platform,n=process.cwd()){let r=cn(t),i=ln(e,t);return on.map(s=>{let o=qe(e[s.envVar]),l=i&&s.targets.globalRootRelativePath?Pe(r,i,s.targets.globalRootRelativePath):null,c=i&&s.targets.globalSkillsRelativePath?Pe(r,i,s.targets.globalSkillsRelativePath):null,u=s.targets.projectRootRelativePath?Pe(r,n,s.targets.projectRootRelativePath):null,d=o??l;return{id:s.id,displayName:s.displayName,envVar:s.envVar,capabilities:s.capabilities,detectionSources:[],targets:{projectRoot:u,projectSkillsPath:Pe(r,n,s.targets.projectSkillsRelativePath),globalRoot:d,globalSkillsPath:o?r.join(o,"skills"):c}}})}async function an(e={}){let t=e.env??process.env,n=e.platform??process.platform,r=e.cwd??process.cwd(),i=cn(n),s=ln(t,n),o=ae(t,n,r),l=e.pathExists??(async()=>!1);return(await Promise.all(o.map(async c=>{let u=Wr(c.id),d=[],m=qe(t[c.envVar]);return(m&&await l(m)||m&&await l(i.join(m,"skills")))&&d.push("override"),u.detection.projectProbeRelativePaths.length>0&&await sn({basePath:r,relativePaths:u.detection.projectProbeRelativePaths,pathApi:i,pathExists:l})&&d.push("project"),s&&u.detection.globalProbeRelativePaths.length>0&&await sn({basePath:s,relativePaths:u.detection.globalProbeRelativePaths,pathApi:i,pathExists:l})&&d.push("global"),d.length===0?null:{...c,detectionSources:Vr(d)}}))).flatMap(c=>c?[c]:[])}function ln(e,t){return t==="win32"?qe(e.USERPROFILE,e.HOME):qe(e.HOME)}function cn(e){return e==="win32"?zr:Jr}function qe(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Vr(e){return[...new Set(e)]}async function sn(e){for(let t of e.relativePaths)if(await e.pathExists(Pe(e.pathApi,e.basePath,t)))return!0;return!1}function Pe(e,t,n){return e.join(t,...n.split("/"))}function $(e,t,n,r={}){let i=r.globalRootRelativePath??n,s=r.detectProject??!0;return{id:e,displayName:t,envVar:r.envVar??un(e),capabilities:r.capabilities??U(),targets:{projectRootRelativePath:n,projectSkillsRelativePath:`${n}/skills`,globalRootRelativePath:i,globalSkillsRelativePath:`${i}/skills`},detection:{projectProbeRelativePaths:s?[n,`${n}/skills`]:[],globalProbeRelativePaths:[i,`${i}/skills`]}}}function ne(e,t,n,r={}){let i=r.detectGlobal??!1;return{id:e,displayName:t,envVar:r.envVar??un(e),capabilities:r.capabilities??U(),targets:{projectRootRelativePath:".agents",projectSkillsRelativePath:".agents/skills",globalRootRelativePath:n,globalSkillsRelativePath:`${n}/skills`},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:i?[n,`${n}/skills`]:[]}}}function U(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 un(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function Wr(e){return on.find(t=>t.id===e)}var de="skills-layer",ei="2025-06-18",ti=["mcp","skills-layer-mcp-proxy.mjs"],ni=["mcp","skills-layer-mcp-broker.mjs"],ri=["mcp","skills-layer-mcp-broker.sock"],ii={codex:{tier:"tier_1",configKind:"codex_toml",resolveConfigPath(e,t,n){let r=ut(n);return r.join(e.targets.globalRoot??r.join(hi({},n)??t,".codex"),"config.toml")}},cursor:be(".cursor/mcp.json"),"claude-code":be(".mcp.json"),cline:be(".cline/mcp.json"),"gemini-cli":be(".gemini/settings.json"),windsurf:be(".windsurf/mcp.json")},si=new Set(["universal"]);function xe(e){let t=ae(e.env,e.platform,e.cwd),n=new Map(t.map(b=>[b.id,b])),r=e.platform??process.platform,i=e.cwd??process.cwd(),s=e.stateDir??fi(e.env,r),o=e.mcpConfigPath??Se(r,s,"mcp.json"),l=Se(r,s,...ti),c=Se(r,s,...ni),u=Se(r,s,...ri),d=e.nodePath??process.execPath,m=hn({mcpConfigPath:o}),k=yn({mcpConfigPath:o,socketPath:u}),p=fe(m),h=fe(k),v=at.map(b=>{let x=n.get(b),L=ii[b];if(L){let Fe=L.resolveConfigPath(x,i,r);return oi({agentId:b,displayName:x.displayName,configPath:Fe,configKind:L.configKind,bridgePath:l,brokerPath:c,brokerSocketPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:p,brokerChecksum:h})}return si.has(b)?gn({agentId:b,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 ${b}\`.`,"MCP auto-install is not claimed for this agent yet."]}):gn({agentId:b,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 ${de}.`,`Command: ${d}`,`Args: ${l}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{status:"mcp_registration_plan",serverName:de,mcpUrl:e.mcpUrl,bearerTokenEnvVar:e.bearerTokenEnvVar,clientId:e.clientId,environment:e.environment,generatedAt:e.now,bridgePath:l,brokerPath:c,brokerSocketPath:u,nodePath:d,mcpConfigPath:o,bridgeChecksum:p,brokerChecksum:h,automaticCount:v.filter(b=>b.status==="automatic").length,manualCount:v.filter(b=>b.status==="manual_handoff").length,skillsOnlyCount:v.filter(b=>b.status==="skills_only").length,unsupportedCount:v.filter(b=>b.status==="unsupported").length,targets:v}}async function fn(e){let t=xe(e),n=yi(e.clientId),r=t.targets.find(v=>v.agentId===n),i=e.mcpConfig??await De(t.mcpConfigPath,{allowMissing:!0});if(!i)return dn({plan:t,target:r,mcpConfig:null,tokenConfig:null,tokenPresent:!1,tokenRefPresent:!1,bridgeExists:!1,checksumMatches:!1,brokerExists:!1,brokerChecksumMatches:!1,targetConfigured:!1,rawTokenLeaked:!1});let s=await Re(t.bridgePath),o=s!==null,l=s!==null&&fe(s)===t.bridgeChecksum,c=await Re(t.brokerPath),u=c!==null,d=c!==null&&fe(c)===t.brokerChecksum,m=ki(i,r.agentId),k=Z(m,"token"),p=Z(m,"tokenRef"),h=r.status==="automatic"?await di(r,k):{configured:!1,rawTokenLeaked:!1};return dn({plan:t,target:r,mcpConfig:i,tokenConfig:m,tokenPresent:!!k,tokenRefPresent:!!p,bridgeExists:o,checksumMatches:l,brokerExists:u,brokerChecksumMatches:d,targetConfigured:h.configured,rawTokenLeaked:h.rawTokenLeaked})}function hn(e){return`#!/usr/bin/env node
|
|
3
|
+
import{spawn as mi}from"node:child_process";import{createHash as Gt}from"node:crypto";import{access as fi,appendFile as ts,chmod as hi,mkdir as Ne,readdir as yi,readFile as Oe,rm as Dt,stat as ns,writeFile as Ht}from"node:fs/promises";import{basename as G,dirname as oe,join as A,posix as Jt,relative as Te,resolve as ki,win32 as Se}from"node:path";import{createInterface as zt}from"node:readline/promises";import{spawn as wn}from"node:child_process";import{createHash as or}from"node:crypto";import{chmod as ar,mkdir as Je,readFile as vn,rm as dt,writeFile as he}from"node:fs/promises";import{dirname as $e,posix as lr,win32 as cr}from"node:path";import{posix as nr,win32 as ir}from"node:path";var ct=["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"],gn=[$("codex","Codex",".codex",{capabilities:L({allowedTools:!0})}),$("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:L({allowedTools:!0,hooks:!0,forkedContext:!0})}),$("cursor","Cursor",".cursor",{capabilities:L({allowedTools:!0})}),$("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:L({allowedTools:!0})}),re("amp","Amp",".config/agents",{capabilities:L({allowedTools:!0})}),re("kimi-cli","Kimi Code CLI",".config/agents"),re("replit","Replit",".config/agents"),re("universal","Universal",".config/agents"),re("antigravity","Antigravity",".gemini/antigravity",{capabilities:L({allowedTools:!0}),detectGlobal:!0}),$("augment","Augment",".augment"),{id:"openclaw",displayName:"OpenClaw",envVar:"OPENCLAW_HOME",capabilities:L({allowedTools:!0}),targets:{projectRootRelativePath:null,projectSkillsRelativePath:"skills",globalRootRelativePath:".openclaw",globalSkillsRelativePath:".openclaw/skills"},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:[".openclaw",".openclaw/skills"]}},re("cline","Cline",".agents",{capabilities:L({allowedTools:!0,hooks:!0})}),re("warp","Warp",".agents"),$("codebuddy","CodeBuddy",".codebuddy",{capabilities:L({allowedTools:!0})}),$("command-code","Command Code",".commandcode",{capabilities:L({allowedTools:!0})}),$("continue","Continue",".continue"),$("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),$("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),re("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),$("droid","Droid",".factory"),re("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),re("github-copilot","GitHub Copilot",".copilot",{capabilities:L({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:L({allowedTools:!0})}),$("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:L({allowedTools:!0})}),$("qoder","Qoder",".qoder",{capabilities:L({allowedTools:!0})}),$("qwen-code","Qwen Code",".qwen"),$("roo","Roo Code",".roo",{capabilities:L({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:L({allowedTools:!0})}),$("neovate","Neovate",".neovate",{capabilities:L({allowedTools:!0})}),$("pochi","Pochi",".pochi"),$("adal","AdaL",".adal")];function de(e=process.env,t=process.platform,n=process.cwd()){let i=fn(t),r=mn(e,t);return gn.map(s=>{let o=De(e[s.envVar]),l=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??l;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 pn(e={}){let t=e.env??process.env,n=e.platform??process.platform,i=e.cwd??process.cwd(),r=fn(n),s=mn(t,n),o=de(t,n,i),l=e.pathExists??(async()=>!1);return(await Promise.all(o.map(async c=>{let u=sr(c.id),d=[],p=De(t[c.envVar]);return(p&&await l(p)||p&&await l(r.join(p,"skills")))&&d.push("override"),u.detection.projectProbeRelativePaths.length>0&&await dn({basePath:i,relativePaths:u.detection.projectProbeRelativePaths,pathApi:r,pathExists:l})&&d.push("project"),s&&u.detection.globalProbeRelativePaths.length>0&&await dn({basePath:s,relativePaths:u.detection.globalProbeRelativePaths,pathApi:r,pathExists:l})&&d.push("global"),d.length===0?null:{...c,detectionSources:rr(d)}}))).flatMap(c=>c?[c]:[])}function mn(e,t){return t==="win32"?De(e.USERPROFILE,e.HOME):De(e.HOME)}function fn(e){return e==="win32"?ir:nr}function De(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function rr(e){return[...new Set(e)]}async function dn(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??hn(e),capabilities:i.capabilities??L(),targets:{projectRootRelativePath:n,projectSkillsRelativePath:`${n}/skills`,globalRootRelativePath:r,globalSkillsRelativePath:`${r}/skills`},detection:{projectProbeRelativePaths:s?[n,`${n}/skills`]:[],globalProbeRelativePaths:[r,`${r}/skills`]}}}function re(e,t,n,i={}){let r=i.detectGlobal??!1;return{id:e,displayName:t,envVar:i.envVar??hn(e),capabilities:i.capabilities??L(),targets:{projectRootRelativePath:".agents",projectSkillsRelativePath:".agents/skills",globalRootRelativePath:n,globalSkillsRelativePath:`${n}/skills`},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:r?[n,`${n}/skills`]:[]}}}function L(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 hn(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function sr(e){return gn.find(t=>t.id===e)}var pe="skills-layer",ur="2025-06-18",dr=["mcp","skills-layer-mcp-proxy.mjs"],gr=["mcp","skills-layer-mcp-broker.mjs"],pr=["mcp","skills-layer-mcp-broker.sock"],mr={codex:{tier:"tier_1",configKind:"codex_toml",resolveConfigPath(e,t,n){let i=gt(n);return i.join(e.targets.globalRoot??i.join(xr({},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")},fr=new Set(["universal"]);function Ie(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??Rr(e.env,i),o=e.mcpConfigPath??xe(i,s,"mcp.json"),l=xe(i,s,...dr),c=xe(i,s,...gr),u=xe(i,s,...pr),d=e.nodePath??process.execPath,p=Pn({mcpConfigPath:o}),y=Sn({mcpConfigPath:o,socketPath:u}),m=ye(p),h=ye(y),w=ct.map(P=>{let x=n.get(P),T=mr[P];if(T){let Ge=T.resolveConfigPath(x,r,i);return hr({agentId:P,displayName:x.displayName,configPath:Ge,configKind:T.configKind,bridgePath:l,brokerPath:c,brokerSocketPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:m,brokerChecksum:h})}return fr.has(P)?kn({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."]}):kn({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: ${l}`,"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:l,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 bn(e){let t=Ie(e),n=$r(e.clientId),i=t.targets.find(w=>w.agentId===n),r=e.mcpConfig??await ze(t.mcpConfigPath,{allowMissing:!0});if(!r)return yn({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,l=s!==null&&ye(s)===t.bridgeChecksum,c=await _e(t.brokerPath),u=c!==null,d=c!==null&&ye(c)===t.brokerChecksum,p=_r(r,i.agentId),y=X(p,"token"),m=X(p,"tokenRef"),h=i.status==="automatic"?await br(i,y):{configured:!1,rawTokenLeaked:!1};return yn({plan:t,target:i,mcpConfig:r,tokenConfig:p,tokenPresent:!!y,tokenRefPresent:!!m,bridgeExists:o,checksumMatches:l,brokerExists:u,brokerChecksumMatches:d,targetConfigured:h.configured,rawTokenLeaked:h.rawTokenLeaked})}function Pn(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(ur)};
|
|
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 Sn(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,23 +244,91 @@ 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,l]);if(clearTimeout(o),
|
|
249
|
-
`,"utf8")}async function
|
|
250
|
-
`,"utf8")}async function
|
|
251
|
-
`),
|
|
252
|
-
|
|
253
|
-
`:""}${n}`;await
|
|
254
|
-
`).trimEnd()}function
|
|
255
|
-
`);
|
|
256
|
-
|
|
247
|
+
`}async function Cn(e){let t=e.requestId??1,n=e.timeoutMs??5e3,i=wn(e.nodePath,[e.bridgePath],{stdio:["pipe","pipe","pipe"]}),r="",s=Cr(i.stdout);i.stderr.on("data",u=>{r+=String(u)});let o,l=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,l]);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(V(u)&&V(u.error))return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!0,toolCount:null,reasonCode:"remote_mcp_error",message:X(u.error,"message")??"Skills Layer MCP returned an error."};let d=V(u)&&V(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 yn(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:X(e.tokenConfig,"environment")??X(e.mcpConfig,"environment")??e.plan.environment,baseUrl:X(e.mcpConfig,"baseUrl"),mcpUrl:X(e.mcpConfig,"mcpUrl"),tokenPrefix:X(e.tokenConfig,"tokenPrefix")??X(e.mcpConfig,"tokenPrefix"),scopes:Array.isArray(e.tokenConfig?.scopes)?e.tokenConfig.scopes:Array.isArray(e.mcpConfig?.scopes)?e.mcpConfig.scopes:[],configuredClients:Ir(e.mcpConfig),tokenPresent:e.tokenPresent||e.tokenRefPresent,tokenStorage:X(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 hr(e){return{agentId:e.agentId,displayName:e.displayName,tier:"tier_1",status:"automatic",serverName:pe,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 yr({bridgePath:e.bridgePath,brokerPath:e.brokerPath,brokerSocketPath:e.brokerSocketPath,mcpConfigPath:e.mcpConfigPath,nodePath:e.nodePath});return await wr({configPath:e.configPath,configKind:e.configKind,bridgePath:e.bridgePath,nodePath:e.nodePath,agentId:e.agentId}),t},disconnect:async()=>{await vr({configPath:e.configPath,configKind:e.configKind})}}}function kn(e){return{agentId:e.agentId,displayName:e.displayName,tier:e.tier,status:e.status,serverName:pe,configPath:null,restartRequired:!0,verification:e.verification,transport:"manual",bridgePath:null,nodePath:null,configKind:null,reason:e.reason,instructions:e.instructions}}async function yr(e){let t=Pn({mcpConfigPath:e.mcpConfigPath}),n=Sn({mcpConfigPath:e.mcpConfigPath,socketPath:e.brokerSocketPath});return await Je($e(e.bridgePath),{recursive:!0}),await he(e.bridgePath,t,"utf8"),await he(e.brokerPath,n,"utf8"),await ut($e(e.bridgePath),448),await ut(e.bridgePath,448),await ut(e.brokerPath,448),kr({nodePath:e.nodePath,brokerPath:e.brokerPath}),{bridgePath:e.bridgePath,brokerPath:e.brokerPath,brokerSocketPath:e.brokerSocketPath,mcpConfigPath:e.mcpConfigPath,checksum:ye(t),brokerChecksum:ye(n),nodePath:e.nodePath}}function kr(e){if(!(process.env.VITEST==="true"||process.env.SKILLS_LAYER_MCP_BROKER_AUTOSTART==="disabled"))try{wn(e.nodePath,[e.brokerPath],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function wr(e){if(e.configKind==="codex_toml"){await Sr(e);return}await Pr(e)}async function vr(e){if(e.configKind==="codex_toml"){let i=await _e(e.configPath);if(i===null)return;await he(e.configPath,Rn(i),"utf8");return}let t=await ze(e.configPath,{allowMissing:!0});if(!t||!V(t.mcpServers))return;let n={...t.mcpServers};delete n[pe],await Je($e(e.configPath),{recursive:!0}),await he(e.configPath,`${JSON.stringify({...t,mcpServers:n},null,2)}
|
|
249
|
+
`,"utf8")}async function br(e,t){if(!e.configPath||!e.configKind||!e.bridgePath||!e.nodePath)return{configured:!1,rawTokenLeaked:!1};if(e.configKind==="codex_toml"){let s=await _e(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 ze(e.configPath,{allowMissing:!0}),i=V(n?.mcpServers)?n.mcpServers[pe]:void 0;return{configured:V(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 Pr(e){let t=await ze(e.configPath,{allowMissing:!0})??{},n=V(t.mcpServers)?{...t.mcpServers}:{};n[pe]={command:e.nodePath,args:[e.bridgePath,"--client",e.agentId]},await Je($e(e.configPath),{recursive:!0}),await he(e.configPath,`${JSON.stringify({...t,mcpServers:n},null,2)}
|
|
250
|
+
`,"utf8")}async function Sr(e){let t=await _e(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=`${Rn(t).trimEnd()}${t.trim().length>0?`
|
|
252
|
+
|
|
253
|
+
`:""}${n}`;await Je($e(e.configPath),{recursive:!0}),await he(e.configPath,i,"utf8")}function Rn(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 Re(e){return{tier:"tier_1",configKind:"json_mcp_servers",resolveConfigPath(t,n,i){return xe(i,n,...e.split("/"))}}}async function ze(e,t){try{let n=JSON.parse(await vn(e,"utf8"));return V(n)?n:{}}catch(n){if(t.allowMissing&&n.code==="ENOENT")return null;throw n}}async function _e(e){try{return await vn(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function ut(e,t){try{await ar(e,t)}catch{}}async function xn(e){await dt(e,{force:!0})}async function $n(e,t){await Promise.all([dt(e,{force:!0}),dt(t,{force:!0})])}function Cr(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 Rr(e,t){let n=gt(t),i=e??process.env,r=t==="win32"?He(i.APPDATA,i.USERPROFILE,i.HOME):He(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 xr(e,t){return t==="win32"?He(e.USERPROFILE,e.HOME):He(e.HOME)}function $r(e){return ct.includes(e)?e:"codex"}function _r(e,t){let n=e.tokens;return V(n)&&V(n[t])?n[t]:e}function Ir(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(V(n))return Object.keys(n);let i=X(e,"clientId");return i?[i]:[]}function xe(e,...t){return gt(e).join(...t)}function gt(e){return e==="win32"?cr:lr}function He(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function X(e,t){let n=e?.[t];return typeof n=="string"&&n.trim().length>0?n:null}function ye(e){return or("sha256").update(e).digest("hex")}function V(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ar(e){let t=jr(e);if(t)return t;let n=Er(e);if(n)return n;throw new Error("Unsupported bundle archive format")}function _n(e){try{return Ar(e)}catch{return null}}function jr(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 l=n.getUint16(r+8,!0),c=n.getUint32(r+18,!0),u=n.getUint16(r+26,!0),d=n.getUint16(r+28,!0),p=r+30,y=p+u+d,m=y+c;if(l!==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(p,p+u)),content:t.decode(e.slice(y,m))}),r=m;continue}return o===33639248||o===101010256?s?i:null:s?(()=>{throw new Error("Unexpected ZIP signature")})():null}return i}function Er(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 Lr}from"node:crypto";function In(e){let t=Lr("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 pt=["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"],Tr="productivity",Ur=new Set(pt),Br={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"},Mr={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 An(e){if(typeof e!="string")return null;let t=En(e);return Ur.has(t)?t:Br[t]??null}function jn(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=Or(s.value);for(let[l,c]of Object.entries(Mr)){if(!c.some(p=>o.has(p)))continue;let d=n.get(l)??{score:0,signals:new Set};d.score+=s.weight,d.signals.add(s.signal),n.set(l,d)}}let r=[...n.entries()].sort((s,o)=>o[1].score-s[1].score||pt.indexOf(s[0])-pt.indexOf(o[0]))[0];return!r||r[1].score<2?{category:Nr(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 Nr(e){let t=En(e.skillType??"");return t.includes("automation")?"automation":t.includes("mcp")?"ai":Tr}function En(e){return e.trim().toLowerCase().replace(/[_\s]+/gu,"-")}function Or(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/u).map(t=>t.trim()).filter(t=>t.length>=2).flatMap(Fr))}function Fr(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 qr=["standalone","workflow_automation","mcp_enhanced"];function Ln(e){let t=e?.trim();if(!t)return"standalone";if(t==="workflow")return"workflow_automation";if(!qr.includes(t))throw new Error(`Unsupported skill type "${t}". Supported types: standalone, workflow, workflow_automation, mcp_enhanced.`);return t}function Tn(e){return[{path:"SKILL.md",content:Kr(e)},{path:"README.md",content:Gr(e)},{path:"references/guide.md",content:Hr(e)},{path:"scripts/README.md",content:Dr(e)}]}function Kr(e){let t=Jr(e);return`---
|
|
256
|
+
name: ${e.skillSlug}
|
|
257
|
+
description: ${e.description}
|
|
258
|
+
compatibility: Codex, Claude Code
|
|
259
|
+
metadata:
|
|
260
|
+
category: ${t}
|
|
261
|
+
price_cents: 0
|
|
262
|
+
tags:
|
|
263
|
+
- ${t}
|
|
264
|
+
- ${e.skillType}
|
|
265
|
+
skills_layer:
|
|
266
|
+
capabilities:
|
|
267
|
+
- model_context
|
|
268
|
+
- filesystem_read
|
|
269
|
+
---
|
|
270
|
+
# ${mt(e.skillSlug)}
|
|
271
|
+
|
|
272
|
+
Use this skill when the user needs ${e.description.toLowerCase()}
|
|
273
|
+
|
|
274
|
+
## Examples
|
|
275
|
+
|
|
276
|
+
- Help me with ${e.skillSlug.replaceAll("-"," ")}
|
|
277
|
+
- Apply this skill to a realistic ${e.skillType.replaceAll("_"," ")} task
|
|
278
|
+
|
|
279
|
+
## Troubleshooting
|
|
280
|
+
|
|
281
|
+
- If the skill does not trigger, make the user request more explicit and mention the task directly.
|
|
282
|
+
- Move deeper procedures into [references/guide.md](references/guide.md) to keep this file concise.
|
|
283
|
+
`}function Gr(e){return`# ${mt(e.skillSlug)}
|
|
284
|
+
|
|
285
|
+
This scaffold was created for a ${e.skillType.replaceAll("_"," ")} skill.
|
|
286
|
+
|
|
287
|
+
Suggested next steps:
|
|
288
|
+
|
|
289
|
+
1. Refine the frontmatter and body in [SKILL.md](SKILL.md).
|
|
290
|
+
2. Review the generated capability declaration and add shell, network, file write, secrets, browser/device/API, or generated-code capabilities only when the workflow truly needs them.
|
|
291
|
+
3. Move detailed procedures into [references/guide.md](references/guide.md).
|
|
292
|
+
4. Add helper scripts or assets only when the workflow truly needs them.
|
|
293
|
+
|
|
294
|
+
Capability declaration checklist:
|
|
295
|
+
|
|
296
|
+
- Use \`network_access\` only when the workflow needs specific external domains, and document those domains near the instruction that uses them.
|
|
297
|
+
- Use \`filesystem_write\` only when the skill creates or modifies files, and describe the intended paths or workspace scope.
|
|
298
|
+
- Use \`secret_handling\` only when a named credential is required, and never put real secret values in the bundle.
|
|
299
|
+
- Use \`shell_execution\`, \`browser_access\`, \`device_control\`, \`api_access\`, or \`generated_code_execution\` only when the workflow genuinely cannot work through normal model instructions.
|
|
300
|
+
|
|
301
|
+
Current summary:
|
|
302
|
+
|
|
303
|
+
- Slug: \`${e.skillSlug}\`
|
|
304
|
+
- Description: ${e.description}
|
|
305
|
+
- Default price: free (\`price_cents: 0\`)
|
|
306
|
+
`}function Dr(e){return`# Scripts
|
|
307
|
+
|
|
308
|
+
Place optional helper scripts for \`${e.skillSlug}\` here.
|
|
309
|
+
|
|
310
|
+
Only include files that are required by the skill workflow. Keep the runtime surface small so bundle packaging stays predictable.
|
|
311
|
+
`}function Hr(e){return`# ${mt(e.skillSlug)} Guide
|
|
312
|
+
|
|
313
|
+
## Intent
|
|
314
|
+
|
|
315
|
+
Document the decision rules, expected inputs, and success criteria for this ${e.skillType.replaceAll("_"," ")} skill.
|
|
316
|
+
|
|
317
|
+
## Suggested Sections
|
|
318
|
+
|
|
319
|
+
- Step-by-step operating procedure
|
|
320
|
+
- Example prompts that should trigger the skill
|
|
321
|
+
- Failure cases and recovery guidance
|
|
322
|
+
- Tooling or policy constraints
|
|
323
|
+
`}function mt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Jr(e){let t=An(e.category);return t||jn({name:e.skillSlug,slug:e.skillSlug,description:e.description,skillType:e.skillType}).category}import{execFile as zr}from"node:child_process";import{createHash as Wr}from"node:crypto";import{promisify as Vr}from"node:util";var ft=Vr(zr),Ae="apiKey",ke="apiKeyRef",je="Skills Layer CLI";function ht(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:Zr()}async function Un(e,t){if(!(typeof e[Ae]=="string"&&e[Ae].length>0))return e;let i=yt(t);if(!i)return e;try{let r={...e,credentialStorage:"macos_keychain"},s=Yr(e);return await i.set(kt(t),s,e[Ae]),r[ke]=s,delete r[Ae],r}catch{return Qr(e)}}async function Bn(e,t){if(e.credentialStorage!=="macos_keychain"||e[Ae]||!e[ke])return e;let n=yt(t);if(!n)return e;let i=await n.get(kt(t),e[ke]);return i?{...e,apiKey:i}:e}async function Mn(e,t){if(!e||e.credentialStorage!=="macos_keychain"||!e[ke])return;let n=yt(t);n&&await n.delete(kt(t),e[ke])}function Yr(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:${Wr("sha256").update(t).digest("base64url").slice(0,32)}`}function yt(e){return e.store!==void 0?e.store:ht(e.platform,e.env??process.env)}function kt(e){return e.service??je}function Qr(e){let t={...e,credentialStorage:"local_file_locked"};return delete t[ke],t}function Zr(){return{kind:"macos_keychain",async set(e,t,n){await ft("/usr/bin/security",["add-generic-password","-a",t,"-s",e,"-w",n,"-U"])},async get(e,t){try{let{stdout:n}=await ft("/usr/bin/security",["find-generic-password","-a",t,"-s",e,"-w"]);return n.trim()||null}catch{return null}},async delete(e,t){try{await ft("/usr/bin/security",["delete-generic-password","-a",t,"-s",e])}catch{}}}}function wt(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 Nn=` ____ _ _ _ _ _
|
|
257
325
|
/ ___|| | _(_) | |___ | | __ _ _ _ ___ _ __
|
|
258
326
|
\\___ \\| |/ / | | / __| | | / _\` | | | |/ _ \\ '__|
|
|
259
327
|
___) | <| | | \\__ \\ | |__| (_| | |_| | __/ |
|
|
260
328
|
|____/|_|\\_\\_|_|_|___/ |_____\\__,_|\\__, |\\___|_|
|
|
261
329
|
|___/
|
|
262
330
|
Skills-Layer
|
|
263
|
-
AI Agent first platform for Skills`;var
|
|
331
|
+
AI Agent first platform for Skills`;var On=`Skills Layer MCP
|
|
264
332
|
Configure Skills Layer for AI agents through a local stdio bridge.
|
|
265
333
|
|
|
266
334
|
Usage:
|
|
@@ -291,15 +359,26 @@ Checks:
|
|
|
291
359
|
repair rewrites the local bridge and supported target config.
|
|
292
360
|
disconnect removes Skills Layer MCP local state and the selected target config entry.
|
|
293
361
|
|
|
294
|
-
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 Xr=`Skills Layer CLI
|
|
295
363
|
Agent-first skill marketplace for developers. CLI, MCP, and API share one journey model.
|
|
296
364
|
|
|
297
365
|
Usage:
|
|
298
366
|
skills-layer <command> [options]
|
|
299
367
|
skills-layer <command> --help
|
|
300
368
|
skills-layer <namespace> --help
|
|
369
|
+
skills-layer help full
|
|
301
370
|
skills-layer help topic [topic] [--base-url <url>] [--json]
|
|
302
371
|
|
|
372
|
+
Start here:
|
|
373
|
+
1. Sign in:
|
|
374
|
+
skills-layer login
|
|
375
|
+
2. Connect AI tools and Security Guardian:
|
|
376
|
+
skills-layer setup
|
|
377
|
+
3. Install a skill:
|
|
378
|
+
skills-layer search "project planning"
|
|
379
|
+
skills-layer install project-planner --dry-run
|
|
380
|
+
skills-layer install project-planner
|
|
381
|
+
|
|
303
382
|
Fast paths:
|
|
304
383
|
Set up an account:
|
|
305
384
|
skills-layer register --method email --email you@example.com
|
|
@@ -471,9 +550,9 @@ Safety:
|
|
|
471
550
|
- Use guardian status [skill-slug] to see Cloud policy, stored user preference, effective mode, local hook posture, and the next Guardian action.
|
|
472
551
|
- Use guardian hook install to add native host hooks where supported; status reports the actual enforcement layer instead of overclaiming strict blocking.
|
|
473
552
|
- Use guardian exec when you need a stronger wrapper that refuses blocked shell actions before spawning the command.
|
|
474
|
-
- 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.`,Ee=`${Nn}
|
|
475
554
|
|
|
476
|
-
${
|
|
555
|
+
${Xr}`;var es=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 We(e,t){let n=e?.trim().toLowerCase(),i=t?.trim().toLowerCase();if(!n||!es.has(n))return null;if(n==="install")return`Skills Layer install help
|
|
477
556
|
|
|
478
557
|
Usage:
|
|
479
558
|
skills-layer install <skill-slug> [--version <semver>] [--scope <local|project|global|workspace>] [--agent <agent>] [--dry-run] [--json]
|
|
@@ -499,7 +578,95 @@ Good defaults:
|
|
|
499
578
|
After install:
|
|
500
579
|
skills-layer installed
|
|
501
580
|
skills-layer sync
|
|
502
|
-
skills-layer update <skill-slug>`;if(n==="
|
|
581
|
+
skills-layer update <skill-slug>`;if(n==="login")return`Skills Layer login help
|
|
582
|
+
|
|
583
|
+
Usage:
|
|
584
|
+
skills-layer login
|
|
585
|
+
skills-layer login --method <google|github|gitlab|microsoft|email> [--email <email>] [--with-mcp|--no-mcp] [--json]
|
|
586
|
+
skills-layer login --api-key <key> [--with-mcp|--no-mcp] [--json]
|
|
587
|
+
|
|
588
|
+
What it does:
|
|
589
|
+
- Starts a browser-first sign-in for humans, then stores the CLI session securely.
|
|
590
|
+
- Email sign-in sends a one-time code and then waits for the code in interactive terminals.
|
|
591
|
+
- After sign-in, the CLI can set up Skills Layer MCP once for detected AI tools.
|
|
592
|
+
- --json is agent-safe: it returns structured status and never prints raw secrets.
|
|
593
|
+
- API key login is an advanced fallback for staging, repair, or automation setup.
|
|
594
|
+
|
|
595
|
+
Examples:
|
|
596
|
+
skills-layer login
|
|
597
|
+
skills-layer login --method google
|
|
598
|
+
skills-layer login --method email --email you@example.com
|
|
599
|
+
skills-layer login --with-mcp
|
|
600
|
+
skills-layer login --no-mcp
|
|
601
|
+
|
|
602
|
+
Related:
|
|
603
|
+
skills-layer auth status
|
|
604
|
+
skills-layer auth repair
|
|
605
|
+
skills-layer mcp setup
|
|
606
|
+
skills-layer mcp status`;if(n==="register")return`Skills Layer register help
|
|
607
|
+
|
|
608
|
+
Usage:
|
|
609
|
+
skills-layer register
|
|
610
|
+
skills-layer register --method email --email <email> [--json]
|
|
611
|
+
skills-layer register --method <google|github|gitlab|microsoft> [--json]
|
|
612
|
+
|
|
613
|
+
What it does:
|
|
614
|
+
- Creates or links a Skills Layer account.
|
|
615
|
+
- Email registration sends a verification code; interactive terminals prompt for it immediately.
|
|
616
|
+
- In --json mode, use the returned nextCommand to complete verification.
|
|
617
|
+
- Existing accounts get generic safe guidance without exposing roles before sign-in.
|
|
618
|
+
|
|
619
|
+
Email flow:
|
|
620
|
+
skills-layer register --method email --email you@example.com
|
|
621
|
+
skills-layer auth verify --email you@example.com --code <code>
|
|
622
|
+
|
|
623
|
+
After verification:
|
|
624
|
+
skills-layer whoami
|
|
625
|
+
skills-layer setup`;if(n==="auth")return i==="recover"?`Skills Layer auth recover help
|
|
626
|
+
|
|
627
|
+
Usage:
|
|
628
|
+
skills-layer auth recover
|
|
629
|
+
skills-layer auth recover --email <email>
|
|
630
|
+
skills-layer auth recover complete --email <email> --code <code> [--json]
|
|
631
|
+
|
|
632
|
+
What it does:
|
|
633
|
+
- Starts account recovery or passwordless email sign-in without revealing whether an address exists.
|
|
634
|
+
- Interactive terminals prompt for the code and complete login in one flow.
|
|
635
|
+
- JSON mode returns structured next steps and never prints raw secrets.
|
|
636
|
+
|
|
637
|
+
Examples:
|
|
638
|
+
skills-layer auth recover
|
|
639
|
+
skills-layer auth recover --email you@example.com
|
|
640
|
+
skills-layer auth recover complete --email you@example.com --code <code> --json`:i==="verify"?`Skills Layer auth verify help
|
|
641
|
+
|
|
642
|
+
Usage:
|
|
643
|
+
skills-layer auth verify --email <email> --code <code> [--json]
|
|
644
|
+
|
|
645
|
+
What it does:
|
|
646
|
+
- Completes email registration.
|
|
647
|
+
- On success, the CLI stores the session securely and marks you logged in.
|
|
648
|
+
- JSON output redacts secrets while still reporting loggedIn.
|
|
649
|
+
|
|
650
|
+
Example:
|
|
651
|
+
skills-layer auth verify --email you@example.com --code <code> --json`:`Skills Layer auth help
|
|
652
|
+
|
|
653
|
+
Usage:
|
|
654
|
+
skills-layer auth status [--json]
|
|
655
|
+
skills-layer auth repair [--json]
|
|
656
|
+
skills-layer auth verify --email <email> --code <code> [--json]
|
|
657
|
+
skills-layer auth recover [--email <email>] [--json]
|
|
658
|
+
skills-layer auth recover complete --email <email> --code <code> [--json]
|
|
659
|
+
skills-layer auth logout [--json]
|
|
660
|
+
|
|
661
|
+
Common flows:
|
|
662
|
+
skills-layer login
|
|
663
|
+
skills-layer register --method email --email you@example.com
|
|
664
|
+
skills-layer auth verify --email you@example.com --code <code>
|
|
665
|
+
|
|
666
|
+
Notes:
|
|
667
|
+
- Prefer skills-layer login for normal sign-in.
|
|
668
|
+
- Use auth status to inspect the local session without printing secrets.
|
|
669
|
+
- Use auth repair when saved backend metadata and selected backend drift apart.`;if(n==="guardian")return`Skills Layer Guardian help
|
|
503
670
|
|
|
504
671
|
Usage:
|
|
505
672
|
skills-layer guardian check --skill <skill-slug> --action-json <json> [--version <semver>] [--path <installed-skill-path>] [--grant-json <json>] [--cloud-trust-ledger <auto|required|optional|off>] [--telemetry-mode <cloud_managed|local_only>] [--json]
|
|
@@ -527,10 +694,11 @@ Enforcement:
|
|
|
527
694
|
- native_hook means the selected host has a concrete pre-action hook configuration installed.
|
|
528
695
|
- native_hook_candidate means Skills Layer wrote integration metadata but does not yet claim strict host blocking.
|
|
529
696
|
- strict pre-action blocking still requires a host agent or wrapper that calls Guardian before tool execution.
|
|
530
|
-
- Cloud-managed decisions should receive only minimal action metadata, not raw files, secrets, or terminal output.`;if(n==="mcp")return
|
|
697
|
+
- Cloud-managed decisions should receive only minimal action metadata, not raw files, secrets, or terminal output.`;if(n==="mcp")return On;let r=i?` ${i}`:"";return`Skills Layer ${n}${r} help
|
|
531
698
|
|
|
532
|
-
Run \`skills-layer --help\` for public CLI usage.`}var E=class extends Error{status;details;constructor(t,n,
|
|
533
|
-
`)),credentialStore:t.credentialStore!==void 0?t.credentialStore:
|
|
699
|
+
Run \`skills-layer --help\` for public CLI usage.`}var Ve="0.1.2";var E=class extends Error{status;details;constructor(t,n,i){super(n),this.name="ApiError",this.status=t,this.details=i}},wi=1,Wt=1,Fn=1,se="skills-layer-security-hook",Z="Skills Layer Security Hook",Vt="https://api.skills-layer.com",is="http://127.0.0.1:8787",rs=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"]),qn=new Set(["accept-capability","approval-request-id","grant-json","paraphrase","should-not-trigger","should-trigger"]),ss=new Set(["bio","company","description","display-name","feedback","message","note","reason","search","summary"]),os=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 mc(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??kl(t.platform??process.platform),stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY,promptText:t.promptText??ml(),promptSecret:t.promptSecret??fl(),promptSelect:t.promptSelect??hl(t.selectInput??process.stdin,t.selectOutput??process.stdout),sleep:t.sleep??(l=>new Promise(c=>setTimeout(c,l))),emitInfo:t.emitInfo??(l=>process.stdout.write(`${l}
|
|
700
|
+
`)),credentialStore:t.credentialStore!==void 0?t.credentialStore:ht(t.platform??process.platform,t.env??process.env)},i=e[0];if(!i){let l=Gn([]),c=await bt(l.flags,n);return await Yo(l.flags,c)}if(i==="--help"||i==="-h")return{exitCode:0,stdout:Ee,stderr:""};if(i==="--version"||i==="-v")return{exitCode:0,stdout:`skills-layer ${Ve}
|
|
701
|
+
`,stderr:""};let r=Gn(e.slice(1));if(r.error)return k(r.error,r.flags.json);let{flags:s,positionals:o}=r;if(i==="admin")return k("The public skills-layer package does not include internal commands.",s.json);if(i==="version"){let l=await bt(s,n);return f({status:"ok",name:"skills-layer",version:Ve},`skills-layer ${Ve}`,s.json,l)}if(s.help){let l=We(i,o[0]);return l?{exitCode:0,stdout:l,stderr:""}:k(Kn(i),s.json)}try{let l=await bt(s,n);switch(i){case"agents":return await cs(o,s,l);case"backend":return await us(o,s,l);case"register":return await vi(s,l);case"login":return await bi(s,l);case"logout":return await Pi(s,l);case"whoami":return await S("/api/v1/whoami",s,l,"Account loaded.",{authenticated:!0});case"profile":return await ps(o,s,l);case"auth":return await fs(o,s,l);case"identity":return await ws(o,s,l);case"api-key":return await vs(o,s,l);case"mcp":return await bs(o,s,l);case"search":case"find":return await $s(o,s,l);case"featured":case"trending":return await _s(i,s,l);case"categories":return await S("/api/v1/categories",s,l,"Categories loaded.");case"recommend":return await Is(o,s,l);case"compare":return await As(o,s,l);case"show":return await js(o,s,l);case"trust":return await Es(o,s,l);case"help":return await Ls(o,s,l);case"status":return await S("/api/v1/status",s,l,"Status loaded.");case"doctor":return await Ca(s,l);case"setup":return await Ai(s,l);case"validate":return await Ts(o,s,l);case"preview-trigger":return await Us(o,s,l);case"creator":return await Bs(o,s,l);case"install":return await Zt(o,s,l);case"installed":return await bo(s,l);case"remove":return await Po(o,s,l);case"update":return await So(o,s,l);case"sync":return await Co(s,l);case"restore":return await To(o,s,l);case"check":return await Uo(o,s,l);case"import":return await Bo(o,s,l);case"source":return await Mo(o,s,l);case"approval":return await Oo(o,s,l);case"workspace":case"workspaces":return await Fo(o,s,l);case"buy":return await qo(o,s,l);case"purchases":return await Ko(o,s,l);case"owned":return await S("/api/v1/me/library",s,l,"Owned skills loaded.",{authenticated:!0});case"export":return await Do(o,s,l);case"library":return await Go(o,s,l);case"add-review":return await Xn("add",o,s,l);case"show-reviews":return await Xn("show",o,s,l);case"add-issue":return await ei("add",o,s,l);case"show-issues":return await ei("show",o,s,l);case"guardian":return await Ho(o,s,l);default:return k(Kn(i),s.json)}}catch(l){return l instanceof E?ot(l,s.json):k(ue(l),s.json)}}function Kn(e){let t=e.trim().toLowerCase();return t==="purchase"?`Unknown command "${e}".
|
|
534
702
|
|
|
535
703
|
Did you mean:
|
|
536
704
|
skills-layer buy <skill-slug>
|
|
@@ -543,7 +711,7 @@ Did you mean:
|
|
|
543
711
|
skills-layer show <skill-slug>`:t==="security-report"?`Unknown command "${e}".
|
|
544
712
|
|
|
545
713
|
Did you mean:
|
|
546
|
-
skills-layer trust <skill-slug>`:`Unknown command "${e}".`}function En(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 r=0;r<e.length;r+=1){let i=e[r];if(!i)continue;if(i==="--"){n.push(...e.slice(r+1));break}if(i==="-h"){t.help=!0;continue}if(!i.startsWith("--")){n.push(i);continue}let s=i.slice(2);if(Ti.has(s)){let l=ht(s);s==="confirm"?t.confirmed=!0:t[l]=!0;continue}let o=e[r+1];if(!o||o.startsWith("--")){if(s==="install"){t.install="";continue}return{flags:t,positionals:n,error:`Flag --${s} requires a value.`}}if(Bi.has(s)){let l=Ni(e,r);if(!l.value)return{flags:t,positionals:n,error:`Flag --${s} requires a value.`};t[ht(s)]=l.value,r=l.nextIndex;continue}if(Mi.has(s)||In.has(s)){let l=ht(s);if(In.has(s)){let c=Array.isArray(t[l])?t[l]:[];c.push(o),t[l]=c}else t[l]=o;r+=1;continue}return{flags:t,positionals:n,error:`Unknown flag --${s}.`}}return{flags:t,positionals:n}}function Ni(e,t){let n=[],r=t;for(let i=t+1;i<e.length;i+=1){let s=e[i];if(!s||s.startsWith("--"))break;n.push(s),r=i}return{value:n.length>0?n.join(" "):null,nextIndex:r}}function ht(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function Un(e,t){let n=Oi(t.env,t.platform),[r,i]=await Promise.all([Ga(n.configPath,t),z(n.backendPreferencePath)]),s=X(g(e.baseUrl)??Q(t.env.SKILLS_LAYER_BASE_URL)??Q(i?.preferredBaseUrl)??Q(r?.baseUrl)??Gt),o=g(e.apiKey)??Q(t.env.SKILLS_LAYER_API_KEY),l=Q(r?.apiKey),c=Q(r?.baseUrl),u=!c||X(c)===s,d=o??(u?l:void 0),m=!o&&l&&c&&!u?`Your saved login belongs to ${X(c)}, but the selected backend is ${s}. Run \`skills-layer backend --base-url ${X(c)}\` to use that login, or run \`skills-layer login\` for ${s}.`:void 0;return{...t,paths:n,config:r,baseUrl:s,apiKey:d,authBlockedMessage:m}}function Oi(e,t){let n=t==="win32"?ve:Ft,r=t==="win32"?Q(e.USERPROFILE)??Q(e.HOME):Q(e.HOME),i=n.join(r??".",".skills-layer");return{stateDir:i,configPath:n.join(i,"config.json"),backendPreferencePath:n.join(i,"backend-preference.json"),installsPath:n.join(i,"installs.json"),importsPath:n.join(i,"imports.json"),mcpConfigPath:n.join(i,"mcp.json"),mcpPreferencePath:n.join(i,"mcp-preference.json"),bundlesDir:n.join(i,"bundles"),incidentsDir:n.join(i,"incidents")}}async function Fi(e,t,n){if(e[0]!=="list")return y(`Unknown agents command "${e[0]??""}".`,t.json);let r=ae(n.env,n.platform,n.cwd).map(i=>({id:i.id,displayName:i.displayName,capabilities:i.capabilities,projectSkillsPath:i.targets.projectSkillsPath,globalSkillsPath:i.targets.globalSkillsPath}));return f({status:"ok",results:r},`Found ${r.length} supported agent targets.`,t.json,n)}async function qi(e,t,n){let r=e[0],i=g(t.baseUrl);if(!r&&i||r==="cloud"||r==="local"){let o=X(i??(r==="local"?Li:Gt)),l=we(o);return await K(n.paths.backendPreferencePath,{version:Kt,preferredBaseUrl:o,savedAt:n.now()}),f({status:"updated",selectedBackend:l,selectedBaseUrl:o,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:!n.config?.baseUrl||X(n.config.baseUrl)===o},`Backend set to ${l}.`,t.json,n)}if(r&&r!=="status")return y(`Unknown backend command "${r}".`,t.json);let s=we(n.baseUrl);return f({status:"ok",selectedBackend:s,selectedBaseUrl:n.baseUrl,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:!n.config?.baseUrl||X(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 Dt=[{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"}],Ki=[...Dt,{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"}],Gi=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...Dt];async function ur(e,t){let n=g(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",Gi)}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 i=g(e.email);if(!i&&!e.json)try{i=await t.promptText("Enter your email address: ")}catch{return y("register --method email requires --email when interactive prompts are unavailable.",!1)}i=w(i,"register requires --email.");let s=await P(t,"/api/v1/register",{method:"POST",headers:_(),body:JSON.stringify({method:n,email:i})});if(e.json)return f(s.status==="already_registered"?Mt(s):H(s),"Registration started.",e.json,t);if(s.status==="already_registered")return f(Mt(s),`${i} 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 ${i} (check spam/junk folder if missing): `)}catch{return f(H(s),`Registration started for ${i}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${i} --code <code>\`.`,!1,t)}return await Er(i,o,e,t,`Verified ${i}.`)}let r=await P(t,"/api/v1/identity/social/start",{method:"POST",headers:_(),body:JSON.stringify({provider:n,mode:"login"})});return e.json?f(r,"Social registration started.",e.json,t):await Xt(n,r,e,t,"login")}async function dr(e,t){if(e.withMcp&&e.noMcp)return y("login cannot combine --with-mcp and --no-mcp.",e.json);let n=g(e.apiKey);if(n){let o=await je(t,n,{notifyLogin:!0}),l=await Rt(e,{...t,config:o,apiKey:n});return D(l)?l:f(H({status:"verified",...o,...l.data?{mcp:l.data}:{}}),[`Logged in as ${o.email}.`,l.message??""].filter(Boolean).join(" "),e.json,t)}let r=g(e.method);if(!r&&!e.json)try{let o=await t.promptSelect("Choose how to sign in:",Ki);r=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(r){if(r==="email"){let l=g(e.email);!l&&!e.json&&(l=(await t.promptText("Enter your email address: ")).trim()),l=w(l,"login --method email requires --email.");let c=await P(t,"/api/v1/identity/recover/start",{method:"POST",headers:_(),body:JSON.stringify({email:l,method:"email",intent:"login"})});if(e.json)return f(c,`Passwordless email login started for ${l}.`,!0,t);let u;try{u=(await t.promptText(`Enter the sign-in code sent to ${l} (check spam/junk folder if missing): `)).trim()}catch{return f(c,`Passwordless email login started for ${l}. Check your email, then run \`skills-layer login --method email --email ${l}\` again when prompts are available.`,!1,t)}let d=await P(t,"/api/v1/identity/recover/complete",{method:"POST",headers:_(),body:JSON.stringify({email:l,code:u,intent:"login"})});return await tt(l,d,e,t,`Verified ${l}.`)}if(!["google","github","gitlab","microsoft"].includes(r))return y("login --method must be email, google, github, gitlab, or microsoft.",e.json);let o=await P(t,"/api/v1/identity/social/start",{method:"POST",headers:_(),body:JSON.stringify({provider:r,mode:"login"})});return e.json?f(o,"Social login started.",!0,t):await Xt(r,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 i=await je(t,n,{notifyLogin:!0}),s=await Rt(e,{...t,config:i,apiKey:n});return D(s)?s:f(H({status:"verified",...i,...s.data?{mcp:s.data}:{}}),[`Logged in as ${i.email}.`,s.message??""].filter(Boolean).join(" "),e.json,t)}async function gr(e,t){return await xn(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),await Ot(t.paths.configPath,{force:!0}),f({status:"logged_out"},"Logged out.",e.json,t)}async function Di(e,t,n){let r=e[0]??"show";if(r==="show")return await S("/api/v1/profile",t,n,"Profile loaded.",{authenticated:!0});if(r==="update"){let i=await Hi(t,n);if(D(i))return i;let s=await P(n,"/api/v1/profile",{method:"PATCH",headers:_(n.apiKey),body:JSON.stringify(i)});return f(s,"Profile updated.",t.json,n)}return y(`Unknown profile command "${r}".`,t.json)}async function Hi(e,t){let n=F(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 r=await t.promptText("Display name (leave blank to keep unchanged): "),i=await t.promptText("Bio (leave blank to keep unchanged): "),s=await t.promptText("Company (leave blank to keep unchanged): "),o=A({displayName:r||void 0,bio:i||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 Ji(e,t,n){let r=e[0];if(r==="register")return await ur({...t,method:"email"},n);if(r==="verify"){let i=w(t.email,"auth verify requires --email."),s=w(t.code,"auth verify requires --code.");return await Er(i,s,t,n,`Verified ${i}.`)}return r==="recover"?await Wi(e.slice(1),t,n):r==="login"?await dr(t,n):r==="logout"?await gr(t,n):r==="status"?zi(t,n):r==="repair"?await Vi(t,n):y(`Unknown auth command "${r??""}".`,t.json)}function zi(e,t){let n=t.config?.baseUrl?X(t.config.baseUrl):null,r=!!(t.apiKey&&n===t.baseUrl);return f({status:"auth_status",selectedBackend:we(t.baseUrl),selectedBaseUrl:t.baseUrl,loggedIn:r,requiresLogin:!r,...t.config?.email?{savedLogin:{baseUrl:n,email:t.config.email,role:t.config.role??null,roles:t.config.roles??[],savedAt:t.config.savedAt??null,...t.config.credentialStorage?{credentialStorage:t.config.credentialStorage}:{},matchesSelectedBackend:r}}:{}},r&&t.config?.email?`Logged in as ${t.config.email}.`:t.config?.baseUrl?`Saved login targets ${n}; selected backend is ${t.baseUrl}. Run \`skills-layer auth repair\` or \`skills-layer login\`.`:"Not logged in. Run `skills-layer login`.",e.json,t)}async function Vi(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=X(t.config.baseUrl);return await K(t.paths.backendPreferencePath,{version:Kt,preferredBaseUrl:n,savedAt:t.now()}),await tn(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 Wi(e,t,n){let r=e[0]??g(t.method)??"email",i=g(t.email);if(!i&&!t.json)try{i=await n.promptText("Enter your email address: ")}catch{return y("auth recover requires --email when interactive prompts are unavailable.",!1)}if(i=w(i,"auth recover requires --email."),r==="complete"){let c=g(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=w(c,"auth recover complete requires --code."),await Ln(i,c,t,n)}let s=await P(n,"/api/v1/identity/recover/start",{method:"POST",headers:_(),body:JSON.stringify({email:i,method:r})}),o=Mt(s);if(t.json)return f(o,"Recovery started.",!0,n);let l="";try{l=(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 ${i} --code <code>\`.`,!1,n)}return l?await Ln(i,l,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 ${i} --code <code>\`.`,!1,n)}async function Ln(e,t,n,r){let i=await P(r,"/api/v1/identity/recover/complete",{method:"POST",headers:_(),body:JSON.stringify({email:e,code:t})});if(n.json){let s=a(i,"apiKey");return s?(await je(r,s,{expectedEmail:e,knownEmail:a(i,"email")??e,knownRole:a(i,"role")??"user",knownRoles:ee(i,"roles"),knownUserId:a(i,"userId")}),f(H({...i,loggedIn:!0}),"Recovery complete.",!0,r)):f(H({...i,email:e,loggedIn:!1}),"Recovery complete.",!0,r)}return await tt(e,i,n,r,`Recovered access for ${e}.`)}async function Yi(e,t,n){let r=e[0],i=1;if(r==="providers")return await S("/api/v1/identity/social/providers",t,n,"Identity providers loaded.");if(r==="start"){let s=g(t.provider);if(!s&&!t.json)try{s=await n.promptSelect("Choose identity provider:",Dt)}catch{return y("identity start requires --provider when interactive selection is unavailable.",!1)}s=w(s,"identity start requires --provider.");let o=await P(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 Xt(s,o,t,n,"login")}if(r==="status"){let s=g(t.state)??e[i];return s?await S(`/api/v1/identity/social/status/${encodeURIComponent(s)}`,t,n,"Social auth status loaded."):y("identity status requires --state.",t.json)}if(r==="complete"){let s=w(t.provider,"identity complete requires --provider."),o=w(t.state,"identity complete requires --state."),l=w(t.code,"identity complete requires --code."),c=await P(n,"/api/v1/identity/social/complete",{method:"POST",headers:_(n.apiKey),body:JSON.stringify({provider:s,state:o,code:l})});return await oa(c,n),f(H(c),"Social auth complete.",t.json,n)}if(r==="list")return await S("/api/v1/me/linked-identities",t,n,"Linked identities loaded.",{authenticated:!0});if(r==="unlink"){let s=w(t.provider??e[i],"identity unlink requires a provider."),o=await P(n,`/api/v1/me/linked-identities/${encodeURIComponent(s)}`,{method:"DELETE",headers:T(n.apiKey,n.authBlockedMessage)});return f(o,"Identity unlinked.",t.json,n)}return y(`Unknown identity command "${r??""}".`,t.json)}async function Qi(e,t,n){let r=e[0];if(!r)return y("api-key requires create, list, or revoke.",t.json);if(r==="list")return await S("/api/v1/me/api-keys",t,n,"API keys loaded.",{authenticated:!0});if(r==="create"){let i=g(t.name),s=Qa(t.scope);if(!i)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=await P(n,"/api/v1/me/api-keys",{method:"POST",headers:{"content-type":"application/json",...T(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:i,scopes:s,...g(t.expires)?{expiresIn:g(t.expires)}:{}})});return f(H(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(r==="rotate")return y(`api-key rotate is not part of normal login.
|
|
714
|
+
skills-layer trust <skill-slug>`:`Unknown command "${e}".`}function Gn(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(rs.has(s)){let l=vt(s);s==="confirm"?t.confirmed=!0:t[l]=!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(ss.has(s)){let l=as(e,i);if(!l.value)return{flags:t,positionals:n,error:`Flag --${s} requires a value.`};t[vt(s)]=l.value,i=l.nextIndex;continue}if(os.has(s)||qn.has(s)){let l=vt(s);if(qn.has(s)){let c=Array.isArray(t[l])?t[l]:[];c.push(o),t[l]=c}else t[l]=o;i+=1;continue}return{flags:t,positionals:n,error:`Unknown flag --${s}.`}}return{flags:t,positionals:n}}function as(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 vt(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function bt(e,t){let n=ls(t.env,t.platform),[i,r]=await Promise.all([pl(n.configPath,t),z(n.backendPreferencePath)]),s=ee(g(e.baseUrl)??Q(t.env.SKILLS_LAYER_BASE_URL)??Q(r?.preferredBaseUrl)??Q(i?.baseUrl)??Vt),o=g(e.apiKey)??Q(t.env.SKILLS_LAYER_API_KEY),l=Q(i?.apiKey),c=Q(i?.baseUrl),u=!c||ee(c)===s,d=o??(u?l:void 0),p=!o&&l&&c&&!u?`Your saved login belongs to ${ee(c)}, but the selected backend is ${s}. Run \`skills-layer backend --base-url ${ee(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 ls(e,t){let n=t==="win32"?Se:Jt,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 cs(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 us(e,t,n){let i=e[0],r=g(t.baseUrl);if(!i&&r||i==="cloud"||i==="local"){let o=ee(r??(i==="local"?is:Vt)),l=Pe(o);return await K(n.paths.backendPreferencePath,{version:Wt,preferredBaseUrl:o,savedAt:n.now()}),f({status:"updated",selectedBackend:l,selectedBaseUrl:o,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:!n.config?.baseUrl||ee(n.config.baseUrl)===o},`Backend set to ${l}.`,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||ee(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 Yt=[{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"}],ds=[...Yt,{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"}],gs=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...Yt];async function vi(e,t){let n=g(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",gs)}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 l=s.status==="already_registered"?Kt(s):J({...s,nextCommand:`skills-layer auth verify --email ${r} --code <code> --json`,nextAction:"auth.verify"});return f(l,"Registration started.",e.json,t)}if(s.status==="already_registered")return f(Kt(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(J(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 Ki(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 on(n,i,e,t,"login")}async function bi(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}),l=await At(e,{...t,config:o,apiKey:n});return D(l)?l:f(J({status:"verified",...o,...l.data?{mcp:l.data}:{}}),[`Logged in as ${o.email}.`,l.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:",ds);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 l=g(e.email);!l&&!e.json&&(l=(await t.promptText("Enter your email address: ")).trim()),l=v(l,"login --method email requires --email.");let c=await b(t,"/api/v1/identity/recover/start",{method:"POST",headers:_(),body:JSON.stringify({email:l,method:"email",intent:"login"})});if(e.json)return f(c,`Passwordless email login started for ${l}.`,!0,t);let u;try{u=(await t.promptText(`Enter the sign-in code sent to ${l} (check spam/junk folder if missing): `)).trim()}catch{return f(c,`Passwordless email login started for ${l}. Check your email, then run \`skills-layer login --method email --email ${l}\` again when prompts are available.`,!1,t)}let d=await b(t,"/api/v1/identity/recover/complete",{method:"POST",headers:_(),body:JSON.stringify({email:l,code:u,intent:"login"})});return await it(l,d,e,t,`Verified ${l}.`)}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 on(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 At(e,{...t,config:r,apiKey:n});return D(s)?s:f(J({status:"verified",...r,...s.data?{mcp:s.data}:{}}),[`Logged in as ${r.email}.`,s.message??""].filter(Boolean).join(" "),e.json,t)}async function Pi(e,t){return await Mn(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),await Dt(t.paths.configPath,{force:!0}),f({status:"logged_out"},"Logged out.",e.json,t)}async function ps(e,t,n){let i=e[0]??"show";if(i==="show")return await S("/api/v1/profile",t,n,"Profile loaded.",{authenticated:!0});if(i==="update"){let r=await ms(t,n);if(D(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 ms(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=I({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 fs(e,t,n){let i=e[0];if(i==="register")return await vi({...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 Ki(r,s,t,n,`Verified ${r}.`)}return i==="recover"?await ks(e.slice(1),t,n):i==="login"?await bi(t,n):i==="logout"?await Pi(t,n):i==="status"?hs(t,n):i==="repair"?await ys(t,n):k(`Unknown auth command "${i??""}".`,t.json)}function hs(e,t){let n=t.config?.baseUrl?ee(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 ys(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=ee(t.config.baseUrl);return await K(t.paths.backendPreferencePath,{version:Wt,preferredBaseUrl:n,savedAt:t.now()}),await ln(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 ks(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 Dn(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=Kt(s);if(t.json)return f(o,"Recovery started.",!0,n);let l="";try{l=(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 l?await Dn(r,l,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 Dn(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=a(r,"apiKey");return s?(await Ue(i,s,{expectedEmail:e,knownEmail:a(r,"email")??e,knownRole:a(r,"role")??"user",knownRoles:ne(r,"roles"),knownUserId:a(r,"userId")}),f(J({...r,loggedIn:!0}),"Recovery complete.",!0,i)):f(J({...r,email:e,loggedIn:!1}),"Recovery complete.",!0,i)}return await it(e,r,n,i,`Recovered access for ${e}.`)}async function ws(e,t,n){let i=e[0],r=1;if(i==="providers")return await S("/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:",Yt)}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 on(s,o,t,n,"login")}if(i==="status"){let s=g(t.state)??e[r];return s?await S(`/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."),l=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:l})});return await Ia(c,n),f(J(c),"Social auth complete.",t.json,n)}if(i==="list")return await S("/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:U(n.apiKey,n.authBlockedMessage)});return f(o,"Identity unlinked.",t.json,n)}return k(`Unknown identity command "${i??""}".`,t.json)}async function vs(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 S("/api/v1/me/api-keys",t,n,"API keys loaded.",{authenticated:!0});if(i==="create"){let r=g(t.name),s=bl(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",...U(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:r,scopes:s,...g(t.expires)?{expiresIn:g(t.expires)}:{}})});return f(J(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.
|
|
547
715
|
|
|
548
716
|
For CLI access:
|
|
549
717
|
skills-layer login
|
|
@@ -553,27 +721,26 @@ For automation:
|
|
|
553
721
|
|
|
554
722
|
To remove an old key:
|
|
555
723
|
skills-layer api-key list
|
|
556
|
-
skills-layer api-key revoke --key-id <key-id>`,t.json);if(
|
|
724
|
+
skills-layer api-key revoke --key-id <key-id>`,t.json);if(i==="revoke"){let r=t.keyId??e[1];if(!r)return k(`api-key revoke needs a key id.
|
|
557
725
|
|
|
558
726
|
Run:
|
|
559
727
|
skills-layer api-key list
|
|
560
|
-
skills-layer api-key revoke --key-id <key-id>`,t.json);let s=String(
|
|
561
|
-
`);return`skills-layer-cli:mcp-token:${Nt("sha256").update(t).digest("base64url").slice(0,32)}`}async function Rt(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 z(t.paths.mcpConfigPath),r=n?a(n,"baseUrl"):void 0,i=n?a(n,"clientId")??"codex":"codex";if(!e.withMcp&&r===t.baseUrl&&i)return{data:{status:"mcp_already_configured",configured:!0,clientId:i,mcpUrl:n?a(n,"mcpUrl")??`${t.baseUrl}/mcp`:`${t.baseUrl}/mcp`},message:"MCP is already configured for this machine."};if(!e.withMcp&&!e.json){let l=await z(t.paths.mcpPreferencePath),c=l?a(l,"baseUrl"):void 0,u=l?a(l,"clientId")??"codex":void 0;if((l?a(l,"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 l=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=l==="yes",l==="no")return await K(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 Ht(e,t);return D(o)?o:{data:o,message:"MCP configured for this machine."}}async function is(e,t,n){let r=e.join(" ").trim()||g(t.search)||"",i=new URLSearchParams;r&&i.set("query",r),B(i,"agent",t.agent),B(i,"capability",t.capability),B(i,"trust",t.trust),B(i,"runtime-risk",t.runtimeRisk),B(i,"security-capability",t.securityCapability);let s=await P(n,`/api/v1/search${te(i)}`);if(t.install!==void 0){let o=g(t.install);if(!o){if(t.json)return y("search --install requires an explicit skill slug in the public CLI package.",!0);let c=Me(s);if(c.length===0)return y("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 y("No search result was selected for install.",!1)}}let l=Wa(s);return l.includes(o)?await Jt([o],t,n):y(l.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: ${l.join(", ")}.`,t.json)}return f(s,"Search complete.",t.json,n)}async function ss(e,t,n){let r=new URLSearchParams;return B(r,"limit",t.limit),B(r,"search",t.search),B(r,"sort",t.sort),await S(`/api/v1/${e}${te(r)}`,t,n,`${ot(e)} skills loaded.`)}async function os(e,t,n){let r=e.join(" ").trim();if(!r)return y("recommend requires a task.",t.json);let i=new URLSearchParams({task:r});return B(i,"limit",t.limit),await S(`/api/v1/recommend?${i.toString()}`,t,n,"Recommendations loaded.")}async function as(e,t,n){if(e.length<2)return y("compare requires two or more skill slugs.",t.json);let r=new URLSearchParams({slugs:e.join(",")}),i=await P(n,`/api/v1/skills/compare?${r.toString()}`);return t.json?f(i,"Comparison loaded.",!0,n):{exitCode:0,stdout:ga(i,"Comparison loaded.",V(n),t.verbose),stderr:""}}async function ls(e,t,n){let r=w(e[0],"show requires a skill slug.");return await S(`/api/v1/skills/${encodeURIComponent(r)}`,t,n,"Skill loaded.")}async function cs(e,t,n){let r=w(e[0],"trust requires a skill slug."),i=new URLSearchParams;B(i,"format",t.format),B(i,"version",t.version);let s=await P(n,`/api/v1/skills/${encodeURIComponent(r)}/trust${te(i)}`);return g(t.format)?.toLowerCase()==="sarif"&&!t.json?{exitCode:0,stdout:Ws(s,r,n),stderr:""}:f(s,"Trust report loaded.",t.json,n)}async function us(e,t,n){let r=Je(e[0],e[1]);if(r)return{exitCode:0,stdout:r,stderr:""};let i=e[0];if(!i)return{exitCode:0,stdout:He,stderr:""};if(i==="topic"){let s=Je(e[1]);if(s)return{exitCode:0,stdout:s,stderr:""};let o=new URLSearchParams;return e[1]&&o.set("topic",e[1]),await S(`/api/v1/help${te(o)}`,t,n,"Help topic loaded.")}if(i==="standards")return await S("/api/v1/standards",t,n,"Marketplace standards loaded.");if(i==="marketplace-status"){let s=await P(n,"/api/v1/marketplace/status");return t.json?f(s,"Marketplace status loaded.",!0,n):f(ka(s),"Marketplace status loaded.",!1,n)}if(i==="capabilities"){let s=await P(n,"/api/v1/capabilities");return f(va(s),"Edition capabilities loaded.",t.json,n)}if(i==="schema-plan")return y("help schema-plan is not included in the public npm CLI.",t.json);if(i==="optimize-tokens"){let s=w(t.text,"help optimize-tokens requires --text."),o=Pa(t.maxCharacters,t.json);if(D(o))return o;let l=await P(n,"/api/v1/optimize-tokens",{method:"POST",headers:_(n.apiKey),body:JSON.stringify({text:s,...o?{maxCharacters:o}:{}})});return f(l,"Token optimization complete.",t.json,n)}return y(`Unknown help command "${i}".`,t.json)}async function ds(e,t,n){let r=w(e[0]??t.path,"validate requires a file or directory."),s={files:await rt(se(n.cwd,r)),sourceIntakeContext:g(t.sourceIntakeContext),publicationStatus:g(t.publicationStatus),dependencyAuditStatus:g(t.dependencyAuditStatus),category:g(t.category),discloseSource:!!t.discloseSource,allowFindingsFeatured:!!t.allowFindingsFeatured},o=await P(n,"/api/v1/validation/preview",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(A(s))});return t.json?f(o,"Validation complete.",!0,n):{exitCode:0,stdout:ba(o,r,n),stderr:""}}async function gs(e,t,n){let r=w(e[0]??t.path,"preview-trigger requires a file or directory."),i=await rt(se(n.cwd,r)),s=await P(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:_(n.apiKey),body:JSON.stringify({files:i,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?f(s,"Trigger preview complete.",!0,n):{exitCode:0,stdout:Sa(s,r,n),stderr:""}}async function ps(e,t,n){let r=e[0];if(r==="init")return await ms(e.slice(1),t,n);if(r==="rules")return await S("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(r==="submissions")return await S("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(r==="status"){let i=w(e[1],"creator status requires a skill slug.");return await S(`/api/v1/me/submissions/${encodeURIComponent(i)}`,t,n,"Submission status loaded.",{authenticated:!0})}if(r==="charge-status"){let i=w(e[1],"creator charge-status requires a charge id.");return await S(`/api/v1/me/private-skill-charges/${encodeURIComponent(i)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(r==="submit")return await Bn(e.slice(1),t,n,!1);if(r==="submit-version")return await Bn(e.slice(1),t,n,!0);if(r==="check-slug"){let i=w(e[1],"creator check-slug requires a slug.");return await ys(i,t,n)}if(r==="rename"){let i=w(e[1],"creator rename requires the current slug."),s=w(e[2],"creator rename requires the new slug.");return await Ee(`/api/v1/me/submissions/${encodeURIComponent(i)}/slug`,{nextSkillSlug:s},t,n,"Skill renamed.")}if(r==="pricing")return await vs(e,t,n);if(r==="update-listing"){let i=w(e[1],"creator update-listing requires a skill slug.");return await Ps(i,t,n)}if(r==="visibility"){let i=w(e[1],"creator visibility requires a skill slug."),s=await P(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/visibility`,{method:"PATCH",headers:_(n.apiKey),body:JSON.stringify(A({visibility:g(t.visibility)??e[2],dryRun:t.dryRun}))});return lo(s)?j(s,co(s,i),t.json,a(s,"reasonCode")??a(s,"status")):f(s,t.dryRun?"Visibility preview loaded.":"Visibility updated.",t.json,n)}if(r==="security-report"){let i=w(e[1],"creator security-report requires a skill slug."),s=new URLSearchParams;B(s,"format",t.format),B(s,"version",t.version),B(s,"versionId",t.versionId);let o=await P(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/trust${te(s)}`,{headers:T(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?f(o,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:Na(o,i,n),stderr:""}}if(r==="rescan-security"){let i=w(e[1],"creator rescan-security requires a skill slug."),s=await P(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/trust/rescan`,{method:"POST",headers:_(n.apiKey),body:JSON.stringify(A(F(t,["version","versionId"])))});return t.json?f(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:Oa(s,i,n),stderr:""}}if(r==="provenance"){let i=w(e[1],"creator provenance requires a skill slug.");return await S(`/api/v1/me/submissions/${encodeURIComponent(i)}/provenance`,t,n,"Provenance loaded.",{authenticated:!0})}if(r==="claim"||r==="verify"||r==="dispute")return await bs(r,e,t,n);if(r==="issues"||r==="reviews"||r==="update-issue"||r==="moderate-review")return await _s(r,e,t,n);if(r==="analytics"){let i=w(e[1],"creator analytics requires a skill slug.");return await Ss(i,t,n)}return r==="earnings"?await S("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0}):r==="payout-profile"?await Cs(t,n):r==="payout-link"?await Rs(t,n):r==="payouts"?await S("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0}):r==="withdraw"?await N("/api/v1/me/payouts/withdrawals",F(t,["amountCents","reason"]),t,n,"Withdrawal requested."):r==="source"?await As(e.slice(1),t,n):y(`Unknown creator command "${r??""}".`,t.json)}async function ms(e,t,n){let r=g(t.skill)??e[0]??"my-skill",i=se(n.cwd,g(t.dir)??r),s=I(i,"SKILL.md"),o=g(t.type),l=g(t.category),c=await fs(i);if((await ce(s)||c)&&!t.confirmed)return y(`Creator init target already exists at ${i}. Re-run with --confirm only if you want to overwrite ${s}.`,t.json);await Te(i,{recursive:!0}),await et(s,["---",`name: ${r}`,`description: ${g(t.description)??"Describe what this skill helps an agent do."}`,...o?[`type: ${o}`]:[],...l?[`category: ${l}`]:[],"---","","# Overview","","Explain when this skill should be used.","","# Steps","","1. Add clear operating instructions.","2. Add examples and troubleshooting notes.",""].join(`
|
|
562
|
-
`),"utf8");let d=A({status:"created",path:s,skillSlug:r,skillType:o,category:l});return t.json?f(d,`Created ${s}.`,!0,n):{exitCode:0,stdout:Ia(d,i,s,n),stderr:""}}async function ce(e){try{return await sr(e),!0}catch{return!1}}async function fs(e){try{return(await ar(e)).length>0}catch{return await ce(e)}}async function Bn(e,t,n,r){let i=w(e[0]??t.path,`creator ${r?"submit-version":"submit"} requires a path.`),s=await rt(se(n.cwd,i));if(!r&&!t.dryRun){let k=await hs(s,t,n);if(k)return k}let o=A({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"])}),l=g(t.skill)??e[1],c=r&&l?`/api/v1/me/submissions/${encodeURIComponent(l)}/versions`:"/api/v1/me/submissions",u=await P(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,r?"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 m=await Zo(u.chargeId,n);return D(m)?m:m.status!=="submitted"?f({...u,chargeStatus:m.status},`Payment is still ${m.status}. You can rerun \`skills-layer creator charge-status ${u.chargeId}\` to continue tracking it.`,t.json,n):f(m,r?"Version submitted.":"Submission uploaded.",t.json,n)}async function hs(e,t,n){let r=g(t.skill)??ks(e);if(!r)return null;let i;try{i=await P(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(r)}`,{headers:T(n.apiKey,n.authBlockedMessage)})}catch(s){if(s instanceof E&&s.status===404)return pr(r,t);throw s}if(i.available===!1||a(i,"reasonCode")==="unavailable"||a(i,"reasonCode")==="reserved"){let s=a(i,"assignedSlug"),o=A({status:"duplicate_candidate",reasonCode:a(i,"reasonCode")??"slug_unavailable",requestedSlug:r,assignedSlug:s,nextAction:"creator.status",nextStep:`Run \`skills-layer creator status ${r}\`, \`skills-layer creator submissions\`, or submit a new version of the existing skill instead of creating a duplicate listing.`});return j(o,`A public skill slug "${r}" already exists or is not available. Run \`skills-layer creator status ${r}\`, check your creator submissions, or submit a new version instead of creating a duplicate listing.`,t.json,a(o,"reasonCode"))}return null}async function ys(e,t,n){try{return await S(`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,t,n,"Slug status loaded.",{authenticated:!0})}catch(r){if(r instanceof E&&r.status===404)return pr(e,t);throw r}}function pr(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 j(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 ks(e){let t=e.find(r=>r.path.split("/").pop()?.toLowerCase()==="skill.md");if(!t)return;let n=/^---\s*\n(?<body>[\s\S]*?)\n---/u.exec(t.content??"")?.groups?.body?.split(/\r?\n/u).map(r=>r.match(/^name\s*:\s*(?<name>.+?)\s*$/u)?.groups?.name?.trim().replace(/^["']|["']$/gu,"")).find(r=>!!r);return ws(n??G(ie(t.path)))}function ws(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function vs(e,t,n){let r=w(e[1],"creator pricing requires a skill slug."),i=new URLSearchParams;if(B(i,"version",t.version),!t.priceCents)return await S(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${te(i)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=Number(g(t.priceCents)),o=await P(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${te(i)}`,{headers:T(n.apiKey,n.authBlockedMessage)}),l=oe(o,"priceCents")??0;if(s>l){let c=A({status:"pending_approval",reasonCode:l===0?"paid_activation_requires_approval":"price_increase_requires_approval",skillSlug:r,version:a(o,"version"),currentPriceCents:l,requestedPriceCents:s,currency:a(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 Ee(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing`,{priceCents:s,version:g(t.version)},t,n,"Pricing updated.")}async function Ps(e,t,n){try{return await Ee(`/api/v1/me/submissions/${encodeURIComponent(e)}`,F(t,["displayName","summary","description","category","skillType","license","listingStatus"]),t,n,"Listing updated.")}catch(r){if(r instanceof E&&r.status===404){let i={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 j(i,`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 r}}async function bs(e,t,n,r){let i=w(t[1],`creator ${e} requires a skill slug.`);try{if(e==="claim")return await N(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/claim`,F(n,["requestedRole","message"]),n,r,"Ownership claim submitted.");if(e==="verify"){let s=w(n.claimId,"creator verify requires --claim-id.");return await N(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/verify`,{claimId:s},n,r,"Ownership claim verified.")}return await N(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/dispute`,F(n,["message"]),n,r,"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:i,requestedRole:g(n.requestedRole),nextAction:e==="claim"?"search":"creator.claim",nextStep:e==="claim"?`Run \`skills-layer search ${i}\`, \`skills-layer show ${i}\`, or submit/source-install the skill before claiming it.`:`Run \`skills-layer creator claim ${i}\` to start a new claim if the skill is claimable.`};return j(o,e==="claim"?`No claimable skill was found for ${i}. Search or show the skill first, then claim it only when it exists and is claimable.`:`No matching ownership claim was found for ${i}. Start a new claim if the skill is claimable.`,n.json,a(o,"reasonCode")??"ownership_action_unavailable")}throw s}}async function Ss(e,t,n){try{return await S(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(r){if(r instanceof E&&r.status===404){let i={status:"no_creator_submission",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see skills you own, \`skills-layer show ${e}\` to inspect the catalog listing, or \`skills-layer creator claim ${e}\` if it is a claimable public-source skill.`};return j(i,`No creator-owned analytics submission was found for ${e}. Run \`skills-layer creator submissions\`, \`skills-layer show ${e}\`, or \`skills-layer creator claim ${e}\` if you should manage it.`,t.json,"creator_submission_not_found")}throw r}}async function Cs(e,t){let n=await P(t,"/api/v1/me/payout-profile",{headers:T(t.apiKey,t.authBlockedMessage)});return f(n,"Creator payout profile loaded.",e.json,t)}async function Rs(e,t){let n=xs(g(e.mode));if(e.mode&&n===null)return y("creator payout-link --mode must be account_onboarding|account_update|onboarding|update.",e.json);let r;try{r=await P(t,"/api/v1/me/payout-profile/link",{method:"POST",headers:_(t.apiKey),body:JSON.stringify(n?{mode:n}:{})})}catch(s){if(s instanceof E&&$s(s))return j({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 i=Xo(r);return i&&!e.json&&e.showUrl!==!0&&(t.emitInfo("Opening payout setup in your browser. Finish the flow there, then come back here."),await t.openUrl(i)||t.emitInfo(`Open this payout setup URL manually to continue: ${i}`)),f(r,"Payout setup link created.",e.json,t)}function xs(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 $s(e){let t=`${e.message} ${a(e.details??{},"error")??""}`.toLowerCase();return t.includes("account_update")&&t.includes("account_onboarding")&&t.includes("account link")}async function _s(e,t,n,r){let i=w(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await S(`/api/v1/me/library/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await S(`/api/v1/me/library/${encodeURIComponent(i)}/reviews`,n,r,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let o=w(n.issueId,"creator update-issue requires --issue-id.");return await Ee(`/api/v1/me/library/${encodeURIComponent(i)}/issues/${encodeURIComponent(o)}`,F(n,["status","fixedVersion","note"]),n,r,"Issue updated.")}let s=w(n.reviewId,"creator moderate-review requires --review-id.");return await Ee(`/api/v1/me/library/${encodeURIComponent(i)}/reviews/${encodeURIComponent(s)}`,F(n,["status","reason"]),n,r,"Review updated.")}async function As(e,t,n){let r=e[0],i=w(e[1],`creator source ${r??""} requires a source connection id.`),s=g(t.skill)??e[2];if(r==="prepare")return await N(`/api/v1/me/source-connections/${encodeURIComponent(i)}/prepare`,A({...F(t,["skill","source","version","displayName","skillType","category","priceCents","visibility"]),source:g(t.source)??e[2]}),t,n,"Source release prepared.");if(r==="publish-request"){let o=t.approvalRequestId.length>0?t.approvalRequestId:g(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await N(`/api/v1/me/source-connections/${encodeURIComponent(i)}/publish-request`,A({skillSlug:s,approvalRequestIds:o,version:g(t.version),...F(t,["visibility","priceCents","license","discloseSource"])}),t,n,"Source publish requested.")}if(r==="release-status"){let o=new URLSearchParams;return s&&o.set("skill",s),await S(`/api/v1/me/source-connections/${encodeURIComponent(i)}/release-status${te(o)}`,t,n,"Source release status loaded.",{authenticated:!0})}return y(`Unknown creator source command "${r??""}".`,t.json)}async function Jt(e,t,n){let r=g(t.source);if(r){let c=g(t.skill),u=await Et(r,n.cwd);if(u)return await Mn(r,u,c,t,n);let d=t.list||t.dryRun||!c&&!t.json&&!t.all,m=await ze(n,r,{source:r,skillSlug:c,listOnly:d},t);if(m.kind==="failure")return m.result;let k=m.inspection;if(t.list)return f(k,"Source skills loaded.",t.json,n);let p=_t(r,k,t);if(p)return p;let h=await xt({source:r,inspection:k,requestedSkillSlug:c,mode:"install",flags:t,backend:n});if(h.kind==="failure")return h.result;if(t.dryRun)return f($t(r,k,h.skillSlug,t),"Source install preview ready.",t.json,n);let v=Nn(t,n),b;try{b=await P(n,v,{method:"POST",headers:On(t,n),body:JSON.stringify(qn({source:r},h.skillSlug,t))})}catch(L){if(L instanceof E)return Kn(r,L,t);throw L}let x=await kt(n,b);return await Qe(n,x,h.skillSlug??a(x,"skillSlug")??r),Ye(x,Fn(t),t.json,n)}let i=w(e[0]??t.install,"install requires a skill slug or --source.");if(Za(i)){let c=await Et(i,n.cwd);if(c)return await Mn(i,c,g(t.skill),t,n);let u=g(t.skill),d;if(t.list){let h=await ze(n,i,{source:i,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 ze(n,i,{source:i,listOnly:!0},t);if(h.kind==="failure")return h.result;let v=h.inspection;d=v;let b=_t(i,v,t);if(b)return b;let x=await xt({source:i,inspection:v,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 ze(n,i,{source:i,listOnly:!0},t);if(h.kind==="failure")return h.result;d=h.inspection}return f($t(i,d,u,t),"Source install preview ready.",t.json,n)}let m=Nn(t,n),k;try{k=await P(n,m,{method:"POST",headers:On(t,n),body:JSON.stringify(qn({source:i},u,t))})}catch(h){if(h instanceof E)return Kn(i,h,t);throw h}let p=await kt(n,k);return await Qe(n,p,u??a(p,"skillSlug")??G(i)),Ye(p,Fn(t),t.json,n)}if(g(t.scope)==="workspace"){let c=w(t.workspace,"workspace installs require --workspace <workspace-id>."),u=await P(n,`/api/v1/workspaces/${encodeURIComponent(c)}/skills`,{method:"POST",headers:_(n.apiKey),body:JSON.stringify(A({skillSlug:i,version:g(t.version),dryRun:t.dryRun}))});return f(u,t.dryRun?"Workspace install preview ready.":"Workspace deployment requested.",t.json,n)}let s=await P(n,"/api/v1/install",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(A({skillSlug:i,version:g(t.version),scope:g(t.scope),agent:g(t.agent),dryRun:t.dryRun}))});if(t.dryRun)return zs(s,t,n);let o=await kt(n,s),l=await Is(n,o,i,t);return D(l)?l:(await Qe(n,l,i),Ye(l,"Skill installed.",t.json,n))}async function Is(e,t,n,r){if(Array.isArray(t.materializedWrites)&&t.materializedWrites.length>0)return t;let i=js(e,t,n,r);if(i.status==="skip")return t;if(i.status==="failure")return j({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:i.skillSlug,nextStep:i.nextStep},i.message,r.json,"materialization_target_invalid");let s=await Es(e,t,i.skillSlug,i.version),o=await mr({backend:e,exportResult:s,flags:r,skillSlug:i.skillSlug});if(D(o))return o;let l=await Bs({backend:e,skillSlug:i.skillSlug,version:i.version??a(s,"version")??"latest",scope:i.scope,agent:i.agent,skillsPath:i.skillsPath,bytes:o.bytes,files:o.files,archiveSha256:o.archiveSha256});return{...t,...Us(s),archiveSha256:o.archiveSha256,archiveHashFormat:o.archiveHashFormat,scope:i.scope,agent:i.agent.id,targetAgent:i.agent.id,materializationPlan:{scope:i.scope,agent:i.agent.id},...l}}function js(e,t,n,r){let i=C(t,"materializationPlan")??C(t,"installPlan"),s=g(r.scope)??a(t,"scope")??(i?a(i,"scope"):void 0);if(s!=="project"&&s!=="global")return{status:"skip"};let o=a(t,"skillSlug")??a(t,"slug")??n,l=g(r.agent)??a(t,"agent")??a(t,"targetAgent")??(i?a(i,"agent")??a(i,"targetAgent"):void 0)??Q(e.config?.lastSelectedAgent)??"codex",c=ae(e.env,e.platform,e.cwd).find(d=>d.id===l);if(!c)return{status:"failure",skillSlug:o,message:`Unsupported agent "${l}". 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:a(t,"version")??a(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 Es(e,t,n,r){if(typeof t.downloadUrl=="string"&&typeof t.archiveSha256=="string")return t;let i=new URLSearchParams;return r&&i.set("version",r),await P(e,`/api/v1/me/library/${encodeURIComponent(n)}/export${te(i)}`,{headers:T(e.apiKey,e.authBlockedMessage)})}function Us(e){return A({version:a(e,"version"),storageKey:a(e,"storageKey"),expiresAt:a(e,"expiresAt")})}async function mr(e){let t=a(e.exportResult,"downloadUrl");if(!t)return j({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(Ls(e.backend.baseUrl,t));if(!n.ok)throw new E(n.status,`Unable to download exported bundle (${n.status}).`);let r=new Uint8Array(await n.arrayBuffer()),i=Ts(r),s=a(e.exportResult,"archiveSha256")??n.headers.get("x-skills-layer-archive-sha256")?.trim()??void 0;return s&&i.archiveSha256!==s?j({status:"download_integrity_failed",reasonCode:"download_hash_mismatch",skillSlug:e.skillSlug,version:a(e.exportResult,"version"),expectedArchiveSha256:s,observedArchiveSha256:i.archiveSha256,archiveHashFormat:i.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"):i.files.length===0?j({status:"download_integrity_failed",reasonCode:"download_bundle_empty",skillSlug:e.skillSlug,archiveHashFormat:i.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:r,files:i.files,archiveSha256:i.archiveSha256,archiveHashFormat:i.format}}function Ls(e,t){return/^https?:\/\//iu.test(t)?t:`${X(e)}${t.startsWith("/")?"":"/"}${t}`}function Ts(e){let t=bn(e);return t?{archiveSha256:Sn(t),format:"bundle_archive",files:t}:{archiveSha256:Nt("sha256").update(e).digest("hex"),format:"raw",files:[]}}async function Bs(e){let t=e.backend.platform==="win32"?ve:Ft,n=t.join(e.backend.paths.bundlesDir,e.skillSlug,e.version,"bundle.zip"),r=t.join(e.skillsPath,e.skillSlug),i=t.join(r,e.version,"bundle.zip"),s=[];await Bt(n,e.bytes),await Ot(r,{recursive:!0,force:!0}),await Bt(i,e.bytes),s.push({path:Ze(e.backend.cwd,i),bytes:e.bytes.byteLength});for(let o of e.files){let l=t.join(r,...Ms(o.path)),c=o.content??"";if(await re(l,c),s.push({path:Ze(e.backend.cwd,l),bytes:new TextEncoder().encode(c).length}),G(o.path).toLowerCase()==="skill.md"){let u=await Zt({backend:e.backend,skillSlug:e.skillSlug,version:e.version,skillDocumentPath:l,skillDocumentContent:c});s.push(u)}}return{bundlePath:n,materializedPath:i,materializedSkillRoot:r,archiveSha256:e.archiveSha256,materializedWrites:s}}function Ms(e){let n=e.replaceAll("\\","/").replace(/^\/+/u,"").trim().split("/").filter(r=>r.length>0);if(n.length===0||n.some(r=>r==="."||r===".."))throw new Error(`Unsafe bundle path "${e}".`);return n}async function Mn(e,t,n,r,i){let s=g(r.visibility)??"private";if(s!=="private")return j({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.`,r.json,"local_install_visibility_not_allowed");let o=Ns(e,t,n);if(r.list)return f(o,"Local source skills loaded.",r.json,i);let l=_t(e,o,r);if(l)return l;let c=await xt({source:e,inspection:o,requestedSkillSlug:n,mode:"install",flags:r,backend:i});if(c.kind==="failure")return c.result;let u=c.skillSlug??Me(o)[0]?.value??hr(e);if(r.dryRun)return f({...$t(e,o,u,r),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.",r.json,i);let d=await P(i,"/api/v1/me/submissions",{method:"POST",headers:{"content-type":"application/json",...T(i.apiKey,i.authBlockedMessage)},body:JSON.stringify(A({files:t.files,version:g(r.version),visibility:"private",category:g(r.category),displayName:g(r.displayName),skillType:g(r.skillType),sourceMetadata:t.sourceMetadata}))}),m=await Fs({backend:i,source:e,upload:t,skillSlug:a(d,"skillSlug")??u,flags:r,submitted:d});return await Qe(i,m,u),Ye(m,"Private Cloud skill installed.",r.json,i)}function Ns(e,t,n){let r=Os(t.files),i=n?r.find(s=>s.skillSlug===n)??null:r.length===1?r[0]??null:null;return{status:"ok",source:t.sourceMetadata,selectedSkill:i,results:r,issues:[],sourceInstallSupported:!0,sourceInstallMode:"local_private",publicationStatus:"none",originalSource:e}}function Os(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=ie(t.path).replaceAll("\\","/"),r=n==="."?".":n,i=fr(t.content??"")??hr(r==="."?t.path:r);return{skillSlug:i,name:i,relativeSkillRoot:r,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function fr(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function hr(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 Fs(e){let t=qs(e.backend,e.flags);if(t.status==="failure")throw new Error(t.message);let n=e.upload.files.map(i=>({path:I(t.skillsPath,e.skillSlug,Lr(i.path)),content:i.content??""})),r=[];for(let i of n)if(await re(i.path,i.content),r.push({path:Ze(e.backend.cwd,i.path),bytes:new TextEncoder().encode(i.content).length}),G(i.path).toLowerCase()==="skill.md"){let s=await Zt({backend:e.backend,skillSlug:e.skillSlug,version:a(e.submitted,"version")??g(e.flags.version)??"private",skillDocumentPath:i.path,skillDocumentContent:i.content});r.push(s)}return{...e.submitted,status:"installed",cloudStatus:a(e.submitted,"status")??"submitted",installKind:"cloud_private",source:e.source,sourceKind:"local",skillSlug:e.skillSlug,version:a(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:r}}function qs(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 r=g(t.agent)??Q(e.config?.lastSelectedAgent)??"codex",i=ae(e.env,e.platform,e.cwd).find(o=>o.id===r);if(!i)return{status:"failure",message:`Unsupported agent "${r}". Run \`skills-layer agents list\` to choose a supported local install target.`};let s=n==="global"?i.targets.globalSkillsPath:i.targets.projectSkillsPath;return s?{status:"ok",scope:n,agent:i.id,skillsPath:s}:{status:"failure",message:`${i.displayName} does not expose a ${n} skills path on this machine.`}}function Ze(e,t){let n=Ie(e,t);return n&&!n.startsWith("..")&&!ve.isAbsolute(n)?n.split("\\").join("/"):t}function zt(e){return g(e.visibility)==="public"?"public":"private"}function Nn(e,t){return zt(e)==="public"&&!t.apiKey?"/api/v1/source-imports":"/api/v1/me/source-installs"}function On(e,t){return{"content-type":"application/json",...zt(e)==="private"?T(t.apiKey,t.authBlockedMessage):Oe(t.apiKey)}}function Fn(e){return zt(e)==="public"?"Public source install planned.":"Private source skill installed."}async function xt(e){if(e.requestedSkillSlug||e.flags.json||e.flags.all)return{kind:"selected",skillSlug:e.requestedSkillSlug};let t=Me(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: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 Me(e){let t=[e.results,e.skills,e.discoveredSkills,C(e,"source")?.results,C(e,"inspection")?.results],n=new Set,r=[];for(let i of t)if(Array.isArray(i))for(let s of i){let o=Ks(s);!o||n.has(o.value)||(n.add(o.value),r.push(o))}return r}function Ks(e){if(!R(e))return;let t=a(e,"skillSlug")??a(e,"slug")??a(e,"name");if(!t)return;let n=a(e,"displayName")??a(e,"title")??a(e,"name"),r=n&&n!==t?`${t} - ${n}`:t,i=a(e,"shortDescription")??a(e,"summary")??a(e,"description")??a(e,"relativeSkillRoot")??a(e,"path")??a(e,"discoveryRoute")??a(e,"sourceKind");return i?{value:t,label:r,description:i}:{value:t,label:r}}function qn(e,t,n){return A({...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 $t(e,t,n,r){return A({status:"dry_run",source:e,selectedSkillSlug:n,all:r.all,scope:g(r.scope)??"local",agent:g(r.agent),workspace:g(r.workspace),quarantine:r.quarantine,acceptCapability:r.acceptCapability,candidates:Me(t).map(i=>({skillSlug:i.value,name:i.label,description:i.description})),nextStep:r.all?`Re-run without --dry-run to install every discovered skill from ${e}.`:`Re-run without --dry-run${n?"":" and add --skill <skill-slug> if needed"} to install from ${e}.`})}async function ze(e,t,n,r){try{return{kind:"ok",inspection:await P(e,"/api/v1/source-inspect",{method:"POST",headers:_(e.apiKey),body:JSON.stringify(A(n))})}}catch(i){if(i instanceof E)return{kind:"failure",result:Ds(t,i,r)};throw i}}function _t(e,t,n){if(Me(t).length>0)return null;let i=Gs(t);return j({status:"unsupported_source_layout",source:e,reasonCode:"source_no_discoverable_skills",issues:i,nextStep:"Run with --list to inspect the source, use a subfolder containing SKILL.md, or install from a Skills Layer-compatible source layout."},Js(e,i),n.json)}function Gs(e){return(Array.isArray(e.issues)?e.issues:[]).filter(R).map(n=>({...a(n,"code")?{code:a(n,"code")}:{},...a(n,"message")?{message:a(n,"message")}:{},...a(n,"path")?{path:a(n,"path")}:{}}))}function Ds(e,t,n){let r=t.details??{},i=a(r,"error")??t.message;if(yr(t.status,i))return kr(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return it(t,n.json);let o={status:"unsupported_source_layout",source:e,reasonCode:"source_not_inspectable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return j(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 Kn(e,t,n){let r=t.details??{},i=a(r,"error")??t.message;if(yr(t.status,i))return kr(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return it(t,n.json);let o={status:"unsupported_source_layout",source:e,reasonCode:"source_not_installable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return j(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 yr(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function kr(e,t,n,r){let i=t.details??{},s=a(i,"error")??t.message,l=`skills-layer source connection start --provider ${Hs(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:l};return j(c,`Cloud could not ${r} ${e} directly. If this is a private source, start a private source connection first:
|
|
563
|
-
${
|
|
564
|
-
`)}function
|
|
565
|
-
`)}function
|
|
566
|
-
`)}
|
|
567
|
-
`)
|
|
568
|
-
`))
|
|
569
|
-
`)
|
|
570
|
-
`)}function
|
|
571
|
-
`)}function lo(e){let t=a(e,"status"),n=a(e,"reasonCode");return t==="invalid_transition"||t==="forbidden"||t==="not_found"||n==="invalid_transition"}function co(e,t){let n=a(e,"why")??a(e,"reason")??a(e,"error"),r=a(e,"currentVisibility"),i=a(e,"nextVisibility")??a(e,"visibility"),s=r||i?` Current visibility: ${r??"unknown"}; requested visibility: ${i??"unknown"}.`:"",o=a(e,"nextStep")??`Run \`skills-layer creator status ${t}\` and choose a valid visibility transition.`;return`Visibility was not changed for ${t}.${s}${n?` ${n}`:""}
|
|
572
|
-
Next step: ${o}`}async function uo(e,t,n){let r=await pe(n),i=e[0];if(!i){let l=Object.values(r.installs);return f({status:l.length>0?"restored":"no_op",results:l},`Restore checked ${l.length} local install record${l.length===1?"":"s"}.`,t.json,n)}let s=r.installs[i];if(!s)return j({status:"missing_record",reasonCode:"restore_record_not_found",skillSlug:i,record:null,nextAction:"installed",nextStep:`Run \`skills-layer installed\` to see local records, \`skills-layer sync\` to refresh status, or \`skills-layer search ${i}\` if you want to find a catalog/source replacement.`},`No restorable local install record was found for ${i}. Run \`skills-layer installed\`, \`skills-layer sync\`, or \`skills-layer search ${i}\` next.`,t.json,"restore_record_not_found");let o={status:"restored",skillSlug:i,record:s};return t.json?f(o,`Restore checked for ${i}.`,!0,n):{exitCode:0,stdout:ao(i,s,n),stderr:""}}async function go(e,t,n){let r=w(e[0],"check requires a skill slug.");return await S(`/api/v1/skills/${encodeURIComponent(r)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function po(e,t,n){let r=w(e[0]??t.source,"import requires a source."),i=await Et(r,n.cwd),s=await P(n,"/api/v1/source-imports",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(A({...i??{source:r},quarantine:t.quarantine,skillSlug:g(t.skill),visibility:g(t.visibility)}))});return await K(n.paths.importsPath,{version:1,lastImport:s,savedAt:n.now()}),f(s,"Source import submitted.",t.json,n)}async function mo(e,t,n){let r=e[0];if(r==="reference"&&e[1]==="resolve"){let i=w(e[2],"source reference resolve requires a reference.");return await S(`/api/v1/source-references/resolve?reference=${encodeURIComponent(i)}`,t,n,"Source reference resolved.")}return r==="connection"?await fo(e.slice(1),t,n):y(`Unknown source command "${e.join(" ")}".`,t.json)}async function fo(e,t,n){let r=e[0];if(r==="start")return await N("/api/v1/me/source-connections",F(t,["provider","source","skill","mode","visibility","priceCents","license","provenanceIntent","discloseSource"]),t,n,"Source connection started.");let i=w(e[1],`source connection ${r??""} requires a connection id.`);return r==="status"?await S(`/api/v1/me/source-connections/${encodeURIComponent(i)}`,t,n,"Source connection loaded.",{authenticated:!0}):r==="complete"?await N(`/api/v1/me/source-connections/${encodeURIComponent(i)}/complete`,F(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed."):r==="cancel"?await N(`/api/v1/me/source-connections/${encodeURIComponent(i)}/cancel`,{},t,n,"Source connection cancelled."):y(`Unknown source connection command "${r??""}".`,t.json)}async function ho(e,t,n){if(e[0]!=="request")return y(`Unknown approval command "${e[0]??""}".`,t.json);let r=e[1],i=w(e[2],`approval request ${r??""} requires an approval id.`);return r==="status"?await S(`/api/v1/me/approvals/${encodeURIComponent(i)}`,t,n,"Approval status loaded.",{authenticated:!0}):r==="complete"?await N(`/api/v1/me/approvals/${encodeURIComponent(i)}/complete`,A({decision:g(t.decision),evidence:st(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed."):y(`Unknown approval request command "${r??""}".`,t.json)}async function yo(e,t,n){let r=e[0]??"list";if(r==="list")return await S("/api/v1/me/workspaces",t,n,"Workspaces loaded.",{authenticated:!0});if(r==="create")return await N("/api/v1/workspaces",{name:e.slice(1).join(" "),kind:g(t.kind)},t,n,"Workspace created.");let i=w(e[1],`workspace ${r} requires a workspace id.`);if(r==="skills")return await S(`/api/v1/workspaces/${encodeURIComponent(i)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0});if(r==="deploy"){let s=w(e[2],"workspace deploy requires a skill slug.");return await N(`/api/v1/workspaces/${encodeURIComponent(i)}/skills`,{skillSlug:s,dryRun:t.dryRun},t,n,"Workspace deployment requested.")}if(r==="remove"){let s=w(e[2],"workspace remove requires a skill slug.");return await nt(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(s)}`,{method:"DELETE",headers:T(n.apiKey,n.authBlockedMessage)},t,n,"Workspace skill removed.")}if(r==="guide"){let s=w(e[2],"workspace guide requires a skill slug.");return await S(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(s)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}return y(`Unknown workspace command "${r}".`,t.json)}async function ko(e,t,n){let r=w(e[0],"buy requires a skill slug."),i=await P(n,"/api/v1/buy",{method:"POST",headers:_(n.apiKey),body:JSON.stringify({skillSlug:r,paymentMethod:g(t.paymentMethod)??"card"})});if(i.status==="already_owned")return f(i,`You already own ${r}. Run \`skills-layer install ${r}\` to install or update it.`,t.json,n);if(t.json||i.status!=="checkout_required"||typeof i.checkoutUrl!="string"||typeof i.purchaseId!="string")return f(i,`Purchase flow started for ${r}.`,t.json,n);n.emitInfo(`Opening checkout for ${r}. Complete the payment in your browser, then come back here.`),await n.openUrl(i.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${i.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let o=await Qo(i.purchaseId,n);return D(o)?o:o.status!=="succeeded"&&o.status!=="refund_requested"?f({...i,purchaseStatus:o.status},`Checkout is still ${o.status} for ${r}. You can rerun install after payment reconciliation completes.`,t.json,n):(n.emitInfo("Payment confirmed. Continuing with install."),await Jt([r],t,n))}async function wo(e,t,n){let r=e[0]??"list";if(r==="list")return await S("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(r==="spending")return await S("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let i=w(e[1],`purchases ${r} requires a purchase id.`);return r==="invoice"?await S(`/api/v1/purchases/${encodeURIComponent(i)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0}):r==="refund-quote"?await S(`/api/v1/purchases/${encodeURIComponent(i)}/refund-quote`,t,n,"Refund quote loaded.",{authenticated:!0}):r==="refund"?await N(`/api/v1/purchases/${encodeURIComponent(i)}/refund`,F(t,["reason"]),t,n,"Refund requested."):y(`Unknown purchases command "${r}".`,t.json)}async function vo(e,t,n){let r=e[0];if(r==="add"){let i=w(e[1],"library add requires a skill slug.");return await N("/api/v1/install",{skillSlug:i},t,n,"Skill added to library.")}return y(`Unknown library command "${r}".`,t.json)}async function Po(e,t,n){let r=w(e[0],"export requires a skill slug."),i=new URLSearchParams;B(i,"version",t.version);let s=await P(n,`/api/v1/me/library/${encodeURIComponent(r)}/export${te(i)}`,{headers:T(n.apiKey,n.authBlockedMessage)}),o=g(t.output);if(o){let l=await mr({backend:n,exportResult:s,flags:t,skillSlug:r});if(D(l))return l;let c=se(n.cwd,o);await Bt(c,l.bytes);let u={...s};return delete u.downloadUrl,f({...u,archiveSha256:l.archiveSha256,archiveHashFormat:l.archiveHashFormat,outputPath:c,downloaded:!0},`Exported ${r} to ${c}.`,t.json,n)}return f(s,o?`Exported ${r} to ${o}.`:"Export prepared.",t.json,n)}async function Gn(e,t,n,r){let i=w(t[0],`${e==="add"?"add-review":"show-reviews"} requires a skill slug.`);return e==="show"?await S(`/api/v1/me/library/${encodeURIComponent(i)}/reviews`,n,r,"Reviews loaded.",{authenticated:!0}):await N(`/api/v1/me/library/${encodeURIComponent(i)}/review`,F(n,["rating","feedback"]),n,r,"Review added.")}async function Dn(e,t,n,r){let i=w(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);return e==="show"?await S(`/api/v1/me/library/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0}):await N(`/api/v1/me/library/${encodeURIComponent(i)}/report-issue`,F(n,["issueType","message"]),n,r,"Issue reported.")}async function bo(e,t,n){let r=e[0];if(r==="hook"){let i=e[1];return i==="install"?await At(t,n):i==="status"?await xo(t,n):y(`Unknown guardian hook command "${i??""}".`,t.json)}if(r==="enable")return e[1]||t.skill?await yt("enforce",e,t,n):await At(t,n);if(r==="disable")return await yt("disabled",e,t,n);if(r==="enable-warnings-only")return await yt("warning_only",e,t,n);if(r==="status")return await Co(e,t,n);if(r==="exec")return await So(e,t,n);if(r==="check"){let i=w(e[1]??t.skill,"guardian check requires a skill slug."),s=Zn(t,"check"),o=t.grantJson.map(h=>rn(h,"grant-json")),l=Ya(t.cloudTrustLedger);if(l.status==="invalid")return y(l.message,t.json);let c=It(t.telemetryMode,l.policy==="off"?"local_only":"cloud_managed");if(c.status==="invalid")return y(c.message,t.json);let u=await Pr({skillSlug:i,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,m=g(t.version)??u.context.version,k=A({skillSlug:i,version:m,action:s,authorizationGrants:o,path:d,guardianPreference:await Wt(n,i),unmanagedPolicy:u.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:c.mode,localPreflight:ge(u.context)}),p=await P(n,"/api/v1/guardian/enforce",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(k)});return await Ae(n,{skillSlug:i,version:m,action:s,decisionStatus:Xe(p),reasonCode:jt(p),telemetryMode:c.mode,path:d}),f({...p,localPreflight:ge(u.context)},"Guardian check complete.",t.json,n)}if(r==="incident"){let i=w(e[1]??t.skill,"guardian incident requires a skill slug."),s=w(t.version,"guardian incident requires --version."),o=It(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return y(o.message,t.json);let l=g(t.path)??(await br({skillSlug:i,flags:t,backend:n})).installedPath,c=Zn(t,"incident"),u=st(t.evidenceJson,"evidence-json"),d=o.mode==="cloud_managed"&&!n.apiKey?"local_only":o.mode,m=A({skillSlug:i,version:s,action:c,evidence:u,path:l,telemetryMode:d,incident:!0,reason:g(t.reason)});if(d==="local_only"){if(!l)return y("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let v=await Wn({backend:n,skillSlug:i,version:s,installedPath:l,action:c,reason:g(t.reason)??"Guardian local-only incident"});await Ae(n,{skillSlug:i,version:s,action:c,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:d,path:l});let b=Yn(n,i);return await re(b,JSON.stringify({request:m,response:null,localResponse:v,savedAt:n.now()},null,2)),f({status:"written",skillSlug:i,version:s,telemetryMode:d,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:v,incidentStatePath:b,incidentPath:v.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let k=await P(n,"/api/v1/guardian/enforce",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(m)}),p=l?await Wn({backend:n,skillSlug:i,version:s,installedPath:l,action:c,reason:g(t.reason)??"Guardian Cloud-managed incident"}):null;await Te(n.paths.incidentsDir,{recursive:!0});let h=Yn(n,i);return await re(h,JSON.stringify({request:m,response:k,localResponse:p,savedAt:n.now()},null,2)),await Ae(n,{skillSlug:i,version:s,action:c,decisionStatus:Xe(k),reasonCode:jt(k),telemetryMode:o.mode,path:l}),f({...k,telemetryMode:o.mode,localResponse:p,incidentPath:h},"Guardian incident recorded.",t.json,n)}return y(`Unknown guardian command "${r??""}".`,t.json)}async function So(e,t,n){let r=g(t.skill),i=w(r??e[1],"guardian exec requires a skill slug."),s=r?e.slice(1):e.slice(2);if(s.length===0)return y("guardian exec requires a command after --.",t.json);let o=It(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return y(o.message,t.json);let l=Lo(t,s),c=await Pr({skillSlug:i,version:g(t.version),action:l,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,m=A({skillSlug:i,version:d,action:l,authorizationGrants:t.grantJson.map(b=>rn(b,"grant-json")),path:u,guardianPreference:await Wt(n,i),telemetryMode:o.mode,localPreflight:ge(c.context)}),k=await P(n,"/api/v1/guardian/enforce",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(m)}),p=Xe(k),h=jt(k);if(await Ae(n,{skillSlug:i,version:d,action:l,decisionStatus:p,reasonCode:h,telemetryMode:o.mode,path:u}),!To(k))return j({status:"blocked",reasonCode:h,skillSlug:i,guardian:k,localPreflight:ge(c.context),command:{executable:G(s[0]??""),executed:!1}},"Guardian blocked guarded execution.",t.json,h);if(t.dryRun)return f({status:"allowed",skillSlug:i,guardian:k,localPreflight:ge(c.context),command:{executable:G(s[0]??""),executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let v=await Bo(s,n);return{exitCode:v.exitCode,stdout:t.json?JSON.stringify({status:v.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:i,guardian:k,localPreflight:ge(c.context),command:v},warnings:[],links:[],reasonCode:v.exitCode===0?null:"command_failed",handoff:null},null,2):Mo(v),stderr:v.stderr}}async function yt(e,t,n,r){let i=w(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),s=await P(r,"/api/v1/guardian/mode",{method:"POST",headers:_(r.apiKey),body:JSON.stringify({skillSlug:i,requestedPreference:e,source:"public-cli"})});return s.preferenceAccepted===!0&&await No(r,i,s),f(s,s.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,r)}async function Co(e,t,n){let r=g(t.skill)??g(e[1]),i=await wr(n,r),s=await Ne(n),o=r?await Oo(n,r):void 0;return f(A({status:"ok",skillSlug:a(i,"skillSlug")??r,policy:i,localPreference:o,hook:s,nextAction:a(i,"nextAction"),nextStep:a(i,"nextStep")}),"Guardian status loaded.",t.json,n)}async function wr(e,t){let n=t?await Wt(e,t):void 0;return await P(e,"/api/v1/guardian/status",{method:"POST",headers:_(e.apiKey),body:JSON.stringify(A({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function Ro(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 wr(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 At(e,t){let n=g(e.agent)??"codex",r=Cr(e.scope);if(r.status==="invalid")return y(r.message,e.json);let i=ae(t.env,t.platform,t.cwd).find(m=>m.id===n);if(!i)return y(`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json);let s=Fo(i,r.scope,t);if(!s)return y(`Guardian ${r.scope} hooks are not available for ${i.displayName}.`,e.json);await qo(s,t);let o=$r(t,r.scope),l=Qn(Ie(t.cwd,s.hookPath)),c=Qn(Ie(t.cwd,s.configPath)),d=[...(await _r(o)).hooks.filter(m=>a(m,"agent")!==i.id||a(m,"scope")!==r.scope),{agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:l.startsWith("..")?s.hookPath:l,configPath:c.startsWith("..")?s.configPath:c,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,enabledAt:t.now()}];return await K(o,{version:1,hooks:d}),f({status:"enabled",agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:s.hookPath,configPath:s.configPath,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,agentCommandMatrix:ft({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 xo(e,t){let n=g(e.scope),r=n?Cr(n):null;if(r?.status==="invalid")return y(r.message,e.json);let i=await Ne(t,r?.status==="valid"?r.scope:void 0);return f(i,"Guardian status loaded.",e.json,t)}async function Ne(e,t){let n=t?[t]:["project","global"],r=[];for(let o of n){let l=$r(e,o),c=await _r(l);for(let u of c.hooks){let d=a(u,"hookPath"),m=d?Vn(e,o,d):null,k=a(u,"configPath"),p=k?Vn(e,o,k):null;r.push({...u,scope:a(u,"scope")??o,hookPath:m??d??null,configPath:p??k??null,active:m?await ce(m):!1,configActive:p?await ce(p):!1})}}let i=r.filter(o=>o.active===!0).length,s=r.filter(o=>o.active===!1).length;return{status:"ok",enforcementLayer:i>0?"native_hook":"not_installed",strictPreActionBlocking:r.some(o=>o.strictPreActionBlocking===!0),activeHookCount:i,missingHookCount:s,hooks:r,setup:await Yt(e),warnings:r.some(o=>o.active===!1)?["One or more configured Guardian hooks are missing from disk. Run skills-layer guardian hook install --agent <agent> again to repair them."]:[]}}async function vr(e,t){if(e.json){let u=await z(t.paths.mcpConfigPath);return f({setup:await Yt(t),mcp:{status:u?"mcp_configured":"mcp_not_configured",configured:!!u,clientId:u?a(u,"clientId")??"codex":void 0,clientIds:u&&Array.isArray(u.clientIds)?u.clientIds:void 0,mcpUrl:u?a(u,"mcpUrl"):void 0,nextCommand:u?"skills-layer mcp status":"skills-layer mcp setup"},guardian:await Ne(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:Ao(t.now(),7)};return await zn(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 y(`Unknown setup option "${n}".`,e.json);let r=n==="both"||n==="mcp",i=n==="both"||n==="security",s={status:"setup_complete",setupChoice:n},o={version:1,setupChoice:n,mcpChoice:r?"configured":"not_requested",mcpPromptedAt:t.now(),guardianHookChoice:i?g(e.scope)??"project":"not_requested",guardianHookPromptedAt:t.now()};if(r)if(!t.apiKey)s.mcp={status:"login_required",configured:!1,nextCommand:"skills-layer login"},o.mcpChoice="login_required";else{let u=await Ht(e,t);if(D(u))return u;s.mcp=u}if(i){let u={...e,json:!0,scope:g(e.scope)??"project",agent:g(e.agent)??"codex"},d=await At(u,t);if(d.exitCode!==0)return d;s.security=Vo(d.stdout)??{status:"enabled",agent:g(u.agent),scope:g(u.scope)}}await zn(t,o);let c=(R(s.mcp)?a(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.";return f(s,c,e.json,t)}async function $o(e,t){let n=await Ne(t),r=await Yt(t),i=oe(n,"activeHookCount")??0;if(t.stdoutIsTty&&i===0&&!r)return await vr(e,t);let s=i>0?"Guardian host hooks are already configured. Run `skills-layer guardian hook status` to inspect them.":"Guardian is enabled for Skills Layer runtime checks. Run `skills-layer setup` when you want MCP and Security hooks on this machine.";return{exitCode:0,stdout:`${He}
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
`)}function Cr(e){let t=g(e)??"project";return t==="project"||t==="global"?{status:"valid",scope:t}:{status:"invalid",message:"guardian hooks --scope must be one of: project, global."}}function Rr(e){return I(e.paths.stateDir,"guardian-modes.json")}function xr(e){return I(e.paths.stateDir,"setup-state.json")}async function Vt(e){let t=await z(Rr(e));return{version:1,skills:R(t?.skills)?t.skills:{}}}async function No(e,t,n){let r=await Vt(e);await K(Rr(e),{version:1,skills:{...r.skills,[t]:{requestedPreference:a(n,"requestedPreference")??"enforce",effectiveMode:a(n,"effectiveMode")??"enforce",reasonCode:a(n,"reasonCode"),auditId:a(n,"auditId"),updatedAt:e.now()}}})}async function Wt(e,t){let r=(await Vt(e)).skills[t];return r?a(r,"requestedPreference"):void 0}async function Oo(e,t){return(await Vt(e)).skills[t]}async function Yt(e){let t=await z(xr(e));return R(t)?{version:1,setupChoice:a(t,"setupChoice"),mcpChoice:a(t,"mcpChoice"),mcpPromptedAt:a(t,"mcpPromptedAt"),guardianHookChoice:a(t,"guardianHookChoice"),guardianHookPromptedAt:a(t,"guardianHookPromptedAt"),remindAfter:a(t,"remindAfter")}:null}async function zn(e,t){await K(xr(e),t)}function Fo(e,t,n){let r=t==="global"?e.targets.globalRoot:e.targets.projectRoot;return r?e.id==="codex"?{agent:e.id,agentName:e.displayName,scope:t,configPath:I(r,"hooks.json"),hookPath:I(r,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook",strictPreActionBlocking:!0}:e.id==="claude-code"?{agent:e.id,agentName:e.displayName,scope:t,configPath:I(r,"settings.json"),hookPath:I(r,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook",strictPreActionBlocking:!0}:e.id==="cline"?{agent:e.id,agentName:e.displayName,scope:t,configPath:I(r,"guardian-hooks.json"),hookPath:I(r,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1}:null:null}async function qo(e,t){if(await re(e.hookPath,Ho(e.agentName)),await or(e.hookPath,448).catch(()=>{}),e.agent==="codex"){await K(e.configPath,Ko(e.hookPath));return}if(e.agent==="claude-code"){await K(e.configPath,Go(e.hookPath));return}e.agent==="cline"&&await K(e.configPath,Do(e,t))}function $r(e,t){return t==="global"?I(e.paths.stateDir,"guardian-hooks.json"):I(e.cwd,".skills-layer","guardian-hooks.json")}async function _r(e){let t=await z(e);return{version:1,hooks:Array.isArray(t?.hooks)?t.hooks.filter(R):[]}}function Vn(e,t,n){return ve.isAbsolute(n)||n.startsWith("/")?n:lr(t==="global"?e.paths.stateDir:e.cwd,n)}function Ko(e){return{hooks:{PreToolUse:[{matcher:"Bash|Shell|Read|Write|Edit|apply_patch|mcp__.*",hooks:[{type:"command",command:`node ${Qt(e)}`}]}]}}}function Go(e){return{hooks:{PreToolUse:[{matcher:"Bash|Read|Write|Edit|MultiEdit|NotebookEdit|WebFetch|WebSearch",hooks:[{type:"command",command:`node ${Qt(e)}`}]}]}}}function Do(e,t){return{version:1,agent:e.agent,agentName:e.agentName,scope:e.scope,enforcementLayer:e.enforcementLayer,strictPreActionBlocking:e.strictPreActionBlocking,installedAt:t.now(),hooks:[{event:"PreToolUse",command:`node ${Qt(e.hookPath)}`,status:"candidate"}]}}function Ho(e){return`#!/usr/bin/env node
|
|
728
|
+
skills-layer api-key revoke --key-id <key-id>`,t.json);let s=String(r),o=await b(n,`/api/v1/me/api-keys/${encodeURIComponent(s)}/revoke`,{method:"POST",headers:U(n.apiKey,n.authBlockedMessage)});return f(o,"API key revoked.",t.json,n)}return k(`Unknown api-key command "${i}".`,t.json)}async function bs(e,t,n){let i=e[0]??"status";if(i==="setup"||i==="repair"){let r=await Qt(t,n);return D(r)?r:f({...r},`MCP configuration written for ${r.clientId}. Open a fresh agent session to load Skills Layer tools, then run \`skills-layer mcp verify --client ${r.clientId}\` if they are not visible.`,t.json,n)}if(i==="status"||i==="verify"){let r=await z(n.paths.mcpConfigPath);if(!r)return f({status:"mcp_not_configured",configured:!1,nextCommand:"skills-layer mcp setup"},"MCP is not configured on this machine.",t.json,n);let s=g(t.client)??g(t.agent)??a(r,"clientId")??"codex",o=a(r,"baseUrl")??n.baseUrl,l=await bn({baseUrl:o,mcpUrl:a(r,"mcpUrl")??`${o}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:s,environment:a(r,"environment")??Pe(o),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:r});if(i==="verify"&&l.configured){let c=await Cn({nodePath:process.execPath,bridgePath:l.bridge.path}),u={...l,verified:c.status==="ok",liveProbe:c};return c.status!=="ok"?j(u,`MCP config exists for ${l.clientId}, but live bridge verification failed: ${c.message}`,t.json,c.reasonCode??void 0):f(u,`MCP verified for ${l.clientId}. ${c.message} Open a fresh agent session or restart the agent if tools are not visible yet.`,t.json,n)}return f(l,l.configured?`MCP configuration is present for ${l.clientId}. Open a fresh agent session if tools are not visible, or run \`skills-layer mcp verify --client ${l.clientId}\` for a live check.`:`MCP needs repair for ${l.clientId}. Run \`${l.nextCommand}\`.`,t.json,n)}if(i==="disconnect"||i==="logout"){let r=g(t.client)??g(t.agent)??"codex",s=await z(n.paths.mcpConfigPath),o=Ie({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:Pe(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}),l=o.targets.find(c=>c.agentId===r);return await Cs(s,n),await l?.disconnect?.(),await xn(o.bridgePath),await $n(o.brokerPath,o.brokerSocketPath),await Dt(n.paths.mcpConfigPath,{force:!0}),f({status:"mcp_disconnected",configured:!1,clientId:r},"MCP disconnected on this machine.",t.json,n)}return k(`Unknown mcp command "${i}". Use setup, status, verify, repair, or disconnect.`,t.json)}async function Qt(e,t){let n=g(e.environment)??Pe(t.baseUrl),i=["mcp:use","catalog:read","library:read","guardian:check","guardian:incident","creator:read"],r=`${t.baseUrl}/mcp`,s=Ie({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 Ps(e,t,s),l=o.clientIds[0]??"codex",c=Ie({baseUrl:t.baseUrl,mcpUrl:r,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:l,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 h=await b(t,"/api/v1/me/mcp-tokens",{method:"POST",headers:_(t.apiKey),body:JSON.stringify({clientId:m,environment:n,scopes:i})}),w=a(h,"apiKey");if(!w)return k("MCP setup did not receive a token from the backend.",e.json);let P=await Ss(t,{token:w,clientId:m,environment:n});u[m]={clientId:m,environment:n,...P,tokenPrefix:a(h,"keyPrefix")??null,scopes:Array.isArray(h.scopes)?h.scopes:[],savedAt:t.now()},d??=h}let p=u[l]??{};await K(t.paths.mcpConfigPath,{version:1,baseUrl:t.baseUrl,mcpUrl:r,clientId:l,clientIds:o.clientIds,environment:n,selectionSource:o.selectionSource,detectedClientIds:o.detectedClientIds,...p,tokens:u,brokerPath:c.brokerPath,brokerSocketPath:c.brokerSocketPath,savedAt:t.now()});let y=c.targets.filter(m=>m.status==="automatic"&&o.clientIds.includes(m.agentId));for(let m of y)await m.apply?.();return{...J(d??{}),status:"mcp_configured",clientId:l,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 ${l}`,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:y.length,appliedClients:y.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 Ps(e,t,n){let i=g(e.client)??g(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 pn({env:t.env,platform:t.platform,cwd:t.cwd,pathExists:ge}),o=new Set(r),l=s.map(c=>c.id).filter(c=>o.has(c));return l.length>0?{clientIds:l,detectedClientIds:l,selectionSource:"detected"}:{clientIds:["codex"],detectedClientIds:[],selectionSource:"fallback"}}async function Ss(e,t){if(!e.credentialStore)return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"};let n=xs({baseUrl:e.baseUrl,userId:e.config?.userId,email:e.config?.email,clientId:t.clientId,environment:t.environment});try{return await e.credentialStore.set(je,n,t.token),{tokenRef:n,credentialStorage:"macos_keychain",credentialService:je,tokenStorage:"macos_keychain"}}catch{return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}}async function Cs(e,t){if(!e||!t.credentialStore)return;let n=Rs(e,je);for(let i of n)await t.credentialStore.delete(i.service,i.tokenRef)}function Rs(e,t){let n=new Map;Hn(e,t,n);let i=e.tokens;if(R(i))for(let r of Object.values(i))R(r)&&Hn(r,t,n);return[...n.values()]}function Hn(e,t,n){let i=a(e,"tokenRef");if(!i||a(e,"credentialStorage")!=="macos_keychain")return;let r=a(e,"credentialService")??t;n.set(`${r}:${i}`,{service:r,tokenRef:i})}function xs(e){let t=[e.baseUrl,e.userId??e.email??"unknown-user",e.clientId,e.environment,"mcpToken"].join(`
|
|
729
|
+
`);return`skills-layer-cli:mcp-token:${Gt("sha256").update(t).digest("base64url").slice(0,32)}`}async function At(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 z(t.paths.mcpConfigPath),i=n?a(n,"baseUrl"):void 0,r=n?a(n,"clientId")??"codex":"codex";if(!e.withMcp&&i===t.baseUrl&&r)return{data:{status:"mcp_already_configured",configured:!0,clientId:r,mcpUrl:n?a(n,"mcpUrl")??`${t.baseUrl}/mcp`:`${t.baseUrl}/mcp`},message:"MCP is already configured for this machine."};if(!e.withMcp&&!e.json){let l=await z(t.paths.mcpPreferencePath),c=l?a(l,"baseUrl"):void 0,u=l?a(l,"clientId")??"codex":void 0;if((l?a(l,"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 l=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=l==="yes",l==="no")return await K(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 D(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 $s(e,t,n){let i=e.join(" ").trim()||g(t.search)||"",r=new URLSearchParams;i&&r.set("query",i),B(r,"agent",t.agent),B(r,"capability",t.capability),B(r,"trust",t.trust),B(r,"runtime-risk",t.runtimeRisk),B(r,"security-capability",t.securityCapability);let s=await b(n,`/api/v1/search${ie(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 l=wl(s);return l.includes(o)?await Zt([o],t,n):k(l.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: ${l.join(", ")}.`,t.json)}return f(s,"Search complete.",t.json,n)}async function _s(e,t,n){let i=new URLSearchParams;return B(i,"limit",t.limit),B(i,"search",t.search),B(i,"sort",t.sort),await S(`/api/v1/${e}${ie(i)}`,t,n,`${lt(e)} skills loaded.`)}async function Is(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 B(r,"limit",t.limit),await S(`/api/v1/recommend?${r.toString()}`,t,n,"Recommendations loaded.")}async function As(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:Ba(r,"Comparison loaded.",W(n),t.verbose),stderr:""}}async function js(e,t,n){let i=v(e[0],"show requires a skill slug.");return await S(`/api/v1/skills/${encodeURIComponent(i)}`,t,n,"Skill loaded.")}async function Es(e,t,n){let i=v(e[0],"trust requires a skill slug."),r=new URLSearchParams;B(r,"format",t.format),B(r,"version",t.version);let s=await b(n,`/api/v1/skills/${encodeURIComponent(i)}/trust${ie(r)}`);return g(t.format)?.toLowerCase()==="sarif"&&!t.json?{exitCode:0,stdout:wo(s,i,n),stderr:""}:f(s,"Trust report loaded.",t.json,n)}async function Ls(e,t,n){let i=We(e[0],e[1]);if(i)return{exitCode:0,stdout:i,stderr:""};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{exitCode:0,stdout:s,stderr:""};let o=new URLSearchParams;return e[1]&&o.set("topic",e[1]),await S(`/api/v1/help${ie(o)}`,t,n,"Help topic loaded.")}if(r==="standards")return await S("/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(Ka(s),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let s=await b(n,"/api/v1/capabilities");return f(Da(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=Ha(t.maxCharacters,t.json);if(D(o))return o;let l=await b(n,"/api/v1/optimize-tokens",{method:"POST",headers:_(n.apiKey),body:JSON.stringify({text:s,...o?{maxCharacters:o}:{}})});return f(l,"Token optimization complete.",t.json,n)}return k(`Unknown help command "${r}".`,t.json)}async function Ts(e,t,n){let i=v(e[0]??t.path,"validate requires a file or directory."),s={files:await st(ae(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(I(s))});return t.json?f(o,"Validation complete.",!0,n):{exitCode:0,stdout:Ja(o,i,n),stderr:""}}async function Us(e,t,n){let i=v(e[0]??t.path,"preview-trigger requires a file or directory."),r=await st(ae(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:za(s,i,n),stderr:""}}async function Bs(e,t,n){let i=e[0];if(i==="init")return await Ms(e.slice(1),t,n);if(i==="rules")return await S("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(i==="submissions")return await S("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(i==="status"){let r=v(e[1],"creator status requires a skill slug.");return await S(`/api/v1/me/submissions/${encodeURIComponent(r)}`,t,n,"Submission status loaded.",{authenticated:!0})}if(i==="charge-status"){let r=v(e[1],"creator charge-status requires a charge id.");return await S(`/api/v1/me/private-skill-charges/${encodeURIComponent(r)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(i==="submit")return await Jn(e.slice(1),t,n,!1);if(i==="submit-version")return await Jn(e.slice(1),t,n,!0);if(i==="check-slug"){let r=v(e[1],"creator check-slug requires a slug.");return await Fs(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 Gs(e,t,n);if(i==="update-listing"){let r=v(e[1],"creator update-listing requires a skill slug.");return await Ds(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(I({visibility:g(t.visibility)??e[2],dryRun:t.dryRun}))});return Eo(s)?j(s,Lo(s,r),t.json,a(s,"reasonCode")??a(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;B(s,"format",t.format),B(s,"version",t.version),B(s,"versionId",t.versionId);let o=await b(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust${ie(s)}`,{headers:U(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?f(o,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:ll(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(I(F(t,["version","versionId"])))});return t.json?f(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:cl(s,r,n),stderr:""}}if(i==="provenance"){let r=v(e[1],"creator provenance requires a skill slug.");return await S(`/api/v1/me/submissions/${encodeURIComponent(r)}/provenance`,t,n,"Provenance loaded.",{authenticated:!0})}if(i==="claim"||i==="verify"||i==="dispute")return await Hs(i,e,t,n);if(i==="issues"||i==="reviews"||i==="update-issue"||i==="moderate-review")return await Qs(i,e,t,n);if(i==="analytics"){let r=v(e[1],"creator analytics requires a skill slug.");return await Js(r,t,n)}return i==="earnings"?await S("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0}):i==="payout-profile"?await zs(t,n):i==="payout-link"?await Ws(t,n):i==="payouts"?await S("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0}):i==="withdraw"?await N("/api/v1/me/payouts/withdrawals",F(t,["amountCents","reason"]),t,n,"Withdrawal requested."):i==="source"?await Zs(e.slice(1),t,n):k(`Unknown creator command "${i??""}".`,t.json)}async function Ms(e,t,n){let i=g(t.skill)??e[0]??"my-skill",r=ae(n.cwd,g(t.dir)??i),s=A(r,"SKILL.md"),o;try{o=Ln(g(t.type))}catch(y){return k(ue(y),t.json)}let l=g(t.category),c=await Ns(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=Tn({skillSlug:i,description:g(t.description)??"Describe what this skill helps an agent do.",skillType:o,category:l});for(let y of d)await te(A(r,y.path),y.content);let p=I({status:"created",path:s,skillSlug:i,skillType:o,category:l,fileCount:d.length});return t.json?f(p,`Created ${s}.`,!0,n):{exitCode:0,stdout:el(p,r,s,n),stderr:""}}async function ge(e){try{return await fi(e),!0}catch{return!1}}async function Ns(e){try{return(await yi(e)).length>0}catch{return await ge(e)}}async function Jn(e,t,n,i){let r=v(e[0]??t.path,`creator ${i?"submit-version":"submit"} requires a path.`),s=await st(ae(n.cwd,r));if(!i&&!t.dryRun){let y=await Os(s,t,n);if(y)return y}let o=I({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"])}),l=g(t.skill)??e[1],c=i&&l?`/api/v1/me/submissions/${encodeURIComponent(l)}/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 ba(u.chargeId,n);return D(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 Os(e,t,n){let i=g(t.skill)??qs(e);if(!i)return null;let r;try{r=await b(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(i)}`,{headers:U(n.apiKey,n.authBlockedMessage)})}catch(s){if(s instanceof E&&s.status===404)return Si(i,t);throw s}if(r.available===!1||a(r,"reasonCode")==="unavailable"||a(r,"reasonCode")==="reserved"){let s=a(r,"assignedSlug"),o=I({status:"duplicate_candidate",reasonCode:a(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 j(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,a(o,"reasonCode"))}return null}async function Fs(e,t,n){try{return await S(`/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 Si(e,t);throw i}}function Si(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 j(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 qs(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 Ks(n??G(oe(t.path)))}function Ks(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function Gs(e,t,n){let i=v(e[1],"creator pricing requires a skill slug."),r=new URLSearchParams;if(B(r,"version",t.version),!t.priceCents)return await S(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${ie(r)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=Number(g(t.priceCents)),o=await b(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${ie(r)}`,{headers:U(n.apiKey,n.authBlockedMessage)}),l=ce(o,"priceCents")??0;if(s>l){let c=I({status:"pending_approval",reasonCode:l===0?"paid_activation_requires_approval":"price_increase_requires_approval",skillSlug:i,version:a(o,"version"),currentPriceCents:l,requestedPriceCents:s,currency:a(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 Ds(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 j(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 Hs(e,t,n,i){let r=v(t[1],`creator ${e} requires a skill slug.`);try{if(e==="claim")return await N(`/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 N(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/verify`,{claimId:s},n,i,"Ownership claim verified.")}return await N(`/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 j(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,a(o,"reasonCode")??"ownership_action_unavailable")}throw s}}async function Js(e,t,n){try{return await S(`/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 j(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 zs(e,t){let n=await b(t,"/api/v1/me/payout-profile",{headers:U(t.apiKey,t.authBlockedMessage)});return f(n,"Creator payout profile loaded.",e.json,t)}async function Ws(e,t){let n=Vs(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&&Ys(s))return j({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=Pa(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 Vs(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 Ys(e){let t=`${e.message} ${a(e.details??{},"error")??""}`.toLowerCase();return t.includes("account_update")&&t.includes("account_onboarding")&&t.includes("account link")}async function Qs(e,t,n,i){let r=v(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await S(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await S(`/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 Zs(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 N(`/api/v1/me/source-connections/${encodeURIComponent(r)}/prepare`,I({...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 N(`/api/v1/me/source-connections/${encodeURIComponent(r)}/publish-request`,I({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 S(`/api/v1/me/source-connections/${encodeURIComponent(r)}/release-status${ie(o)}`,t,n,"Source release status loaded.",{authenticated:!0})}return k(`Unknown creator source command "${i??""}".`,t.json)}async function Zt(e,t,n){let i=g(t.source);if(i){let c=g(t.skill),u=await Mt(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=Lt(i,y,t);if(m)return m;let h=await jt({source:i,inspection:y,requestedSkillSlug:c,mode:"install",flags:t,backend:n});if(h.kind==="failure")return h.result;if(t.dryRun)return f(Et(i,y,h.skillSlug,t),"Source install preview ready.",t.json,n);let w=Wn(t,n),P;try{P=await b(n,w,{method:"POST",headers:Vn(t,n),body:JSON.stringify(Qn({source:i},h.skillSlug,t))})}catch(T){if(T instanceof E)return Zn(i,T,t);throw T}let x=await St(n,P);return await et(n,x,h.skillSlug??a(x,"skillSlug")??i),Xe(x,Yn(t),t.json,n)}let r=v(e[0]??t.install,"install requires a skill slug or --source.");if(Pl(r)){let c=await Mt(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=Lt(r,w,t);if(P)return P;let x=await jt({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(Et(r,d,u,t),"Source install preview ready.",t.json,n)}let p=Wn(t,n),y;try{y=await b(n,p,{method:"POST",headers:Vn(t,n),body:JSON.stringify(Qn({source:r},u,t))})}catch(h){if(h instanceof E)return Zn(r,h,t);throw h}let m=await St(n,y);return await et(n,m,u??a(m,"skillSlug")??G(r)),Xe(m,Yn(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(I({skillSlug:r,version:g(t.version),dryRun:t.dryRun}))});return f(u,t.dryRun?"Workspace install preview ready.":"Workspace deployment requested.",t.json,n)}let s=await b(n,"/api/v1/install",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(I({skillSlug:r,version:g(t.version),scope:g(t.scope),agent:g(t.agent),dryRun:t.dryRun}))});if(t.dryRun)return yo(s,t,n);let o=await St(n,s),l=await Xs(n,o,r,t);return D(l)?l:(await et(n,l,r),Xe(l,"Skill installed.",t.json,n))}async function Xs(e,t,n,i){if(Array.isArray(t.materializedWrites)&&t.materializedWrites.length>0)return t;let r=eo(e,t,n,i);if(r.status==="skip")return t;if(r.status==="failure")return j({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:r.skillSlug,nextStep:r.nextStep},r.message,i.json,"materialization_target_invalid");let s=await to(e,t,r.skillSlug,r.version),o=await Ci({backend:e,exportResult:s,flags:i,skillSlug:r.skillSlug});if(D(o))return o;let l=await so({backend:e,skillSlug:r.skillSlug,version:r.version??a(s,"version")??"latest",scope:r.scope,agent:r.agent,skillsPath:r.skillsPath,bytes:o.bytes,files:o.files,archiveSha256:o.archiveSha256});return{...t,...no(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},...l}}function eo(e,t,n,i){let r=C(t,"materializationPlan")??C(t,"installPlan"),s=g(i.scope)??a(t,"scope")??(r?a(r,"scope"):void 0);if(s!=="project"&&s!=="global")return{status:"skip"};let o=a(t,"skillSlug")??a(t,"slug")??n,l=g(i.agent)??a(t,"agent")??a(t,"targetAgent")??(r?a(r,"agent")??a(r,"targetAgent"):void 0)??Q(e.config?.lastSelectedAgent)??"codex",c=de(e.env,e.platform,e.cwd).find(d=>d.id===l);if(!c)return{status:"failure",skillSlug:o,message:`Unsupported agent "${l}". 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:a(t,"version")??a(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 to(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${ie(r)}`,{headers:U(e.apiKey,e.authBlockedMessage)})}function no(e){return I({version:a(e,"version"),storageKey:a(e,"storageKey"),expiresAt:a(e,"expiresAt")})}async function Ci(e){let t=a(e.exportResult,"downloadUrl");if(!t)return j({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(io(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=ro(i),s=a(e.exportResult,"archiveSha256")??n.headers.get("x-skills-layer-archive-sha256")?.trim()??void 0;return s&&r.archiveSha256!==s?j({status:"download_integrity_failed",reasonCode:"download_hash_mismatch",skillSlug:e.skillSlug,version:a(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?j({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,archiveHashFormat:r.format}}function io(e,t){return/^https?:\/\//iu.test(t)?t:`${ee(e)}${t.startsWith("/")?"":"/"}${t}`}function ro(e){let t=_n(e);return t?{archiveSha256:In(t),format:"bundle_archive",files:t}:{archiveSha256:Gt("sha256").update(e).digest("hex"),format:"raw",files:[]}}async function so(e){let t=e.backend.platform==="win32"?Se:Jt,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 qt(n,e.bytes),await Dt(i,{recursive:!0,force:!0}),await qt(r,e.bytes),s.push({path:tt(e.backend.cwd,r),bytes:e.bytes.byteLength});for(let o of e.files){let l=t.join(i,...oo(o.path)),c=o.content??"";if(await te(l,c),s.push({path:tt(e.backend.cwd,l),bytes:new TextEncoder().encode(c).length}),G(o.path).toLowerCase()==="skill.md"){let u=await sn({backend:e.backend,skillSlug:e.skillSlug,version:e.version,skillDocumentPath:l,skillDocumentContent:c});s.push(u)}}return{bundlePath:n,materializedPath:r,materializedSkillRoot:i,archiveSha256:e.archiveSha256,materializedWrites:s}}function oo(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 j({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=ao(e,t,n);if(i.list)return f(o,"Local source skills loaded.",i.json,r);let l=Lt(e,o,i);if(l)return l;let c=await jt({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??xi(e);if(i.dryRun)return f({...Et(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",...U(r.apiKey,r.authBlockedMessage)},body:JSON.stringify(I({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 co({backend:r,source:e,upload:t,skillSlug:a(d,"skillSlug")??u,flags:i,submitted:d});return await et(r,p,u),Xe(p,"Private Cloud skill installed.",i.json,r)}function ao(e,t,n){let i=lo(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 lo(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=oe(t.path).replaceAll("\\","/"),i=n==="."?".":n,r=Ri(t.content??"")??xi(i==="."?t.path:i);return{skillSlug:r,name:r,relativeSkillRoot:i,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function Ri(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function xi(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 co(e){let t=uo(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,Di(r.path)),content:r.content??""})),i=[];for(let r of n)if(await te(r.path,r.content),i.push({path:tt(e.backend.cwd,r.path),bytes:new TextEncoder().encode(r.content).length}),G(r.path).toLowerCase()==="skill.md"){let s=await sn({backend:e.backend,skillSlug:e.skillSlug,version:a(e.submitted,"version")??g(e.flags.version)??"private",skillDocumentPath:r.path,skillDocumentContent:r.content});i.push(s)}return{...e.submitted,status:"installed",cloudStatus:a(e.submitted,"status")??"submitted",installKind:"cloud_private",source:e.source,sourceKind:"local",skillSlug:e.skillSlug,version:a(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 uo(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 tt(e,t){let n=Te(e,t);return n&&!n.startsWith("..")&&!Se.isAbsolute(n)?n.split("\\").join("/"):t}function Xt(e){return g(e.visibility)==="public"?"public":"private"}function Wn(e,t){return Xt(e)==="public"&&!t.apiKey?"/api/v1/source-imports":"/api/v1/me/source-installs"}function Vn(e,t){return{"content-type":"application/json",...Xt(e)==="private"?U(t.apiKey,t.authBlockedMessage):Ke(t.apiKey)}}function Yn(e){return Xt(e)==="public"?"Public source install planned.":"Private source skill installed."}async function jt(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,C(e,"source")?.results,C(e,"inspection")?.results],n=new Set,i=[];for(let r of t)if(Array.isArray(r))for(let s of r){let o=go(s);!o||n.has(o.value)||(n.add(o.value),i.push(o))}return i}function go(e){if(!R(e))return;let t=a(e,"skillSlug")??a(e,"slug")??a(e,"name");if(!t)return;let n=a(e,"displayName")??a(e,"title")??a(e,"name"),i=n&&n!==t?`${t} - ${n}`:t,r=a(e,"shortDescription")??a(e,"summary")??a(e,"description")??a(e,"relativeSkillRoot")??a(e,"path")??a(e,"discoveryRoute")??a(e,"sourceKind");return r?{value:t,label:i,description:r}:{value:t,label:i}}function Qn(e,t,n){return I({...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 Et(e,t,n,i){return I({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(I(n))})}}catch(r){if(r instanceof E)return{kind:"failure",result:mo(t,r,i)};throw r}}function Lt(e,t,n){if(Fe(t).length>0)return null;let r=po(t);return j({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."},ho(e,r),n.json)}function po(e){return(Array.isArray(e.issues)?e.issues:[]).filter(R).map(n=>({...a(n,"code")?{code:a(n,"code")}:{},...a(n,"message")?{message:a(n,"message")}:{},...a(n,"path")?{path:a(n,"path")}:{}}))}function mo(e,t,n){let i=t.details??{},r=a(i,"error")??t.message;if($i(t.status,r))return _i(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return ot(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 j(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 Zn(e,t,n){let i=t.details??{},r=a(i,"error")??t.message;if($i(t.status,r))return _i(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return ot(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 j(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 $i(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function _i(e,t,n,i){let r=t.details??{},s=a(r,"error")??t.message,l=`skills-layer source connection start --provider ${fo(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:l};return j(c,`Cloud could not ${i} ${e} directly. If this is a private source, start a private source connection first:
|
|
730
|
+
${l}`,n.json,"private_source_access_required")}function fo(e){return/gitlab\./iu.test(e)?"gitlab":/github\./iu.test(e)||/^gh:/iu.test(e)?"github":"generic_git"}function ho(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(`
|
|
731
|
+
`)}function yo(e,t,n){if(ko(e)){let r=a(e,"reasonCode")??a(e,"reason")??"install_not_ready",s=a(e,"why")??a(e,"summary")??"The requested skill is not ready to install from this backend.";return j(e,`Install preview is not ready: ${s}`,t.json,r)}let i=Array.isArray(e.warnings)&&e.warnings.length>0;return f(e,i?"Install preview ready with warnings.":"Install preview ready.",t.json,n)}function ko(e){let t=a(e,"status")?.toLowerCase(),n=a(e,"reasonCode")?.toLowerCase();return t==="not_found"||t==="missing"||t==="blocked"||t==="not_ready"||n==="skill_not_found"||n==="not_found"}function Xe(e,t,n,i){return n?f(e,t,!0,i):{exitCode:0,stdout:vo(e,t,i),stderr:""}}function wo(e,t,n){let i=W(n),r=Array.isArray(e.runs)?e.runs.filter(R):[],s=r.flatMap(c=>Array.isArray(c.results)?c.results.filter(R):[]),o=r.flatMap(c=>{let u=C(c,"tool"),d=u?C(u,"driver"):void 0;return d&&Array.isArray(d.rules)?d.rules.filter(R):[]}),l=[`${i.ok("OK")} Trust report loaded.`,"",i.section("SARIF")];if(l.push(` ${i.label("Skill")}: ${t}`),l.push(` ${i.label("Runs")}: ${r.length}`),l.push(` ${i.label("Rules")}: ${o.length}`),l.push(` ${i.label("Results")}: ${s.length}`),s.length===0)l.push(` ${i.muted("No SARIF findings found.")}`);else{l.push("",i.section("Findings"));for(let[c,u]of s.slice(0,O).entries()){let d=a(u,"ruleId")??"unknown-rule",p=C(u,"message");l.push(`${c+1}. ${d}${p?` - ${a(p,"text")??""}`:""}`)}}return l.push("",i.section("Next")),l.push(` ${i.arrow} skills-layer trust ${t} --format sarif --json`),l.join(`
|
|
732
|
+
`)}function vo(e,t,n){let i=W(n),r=[`${i.ok("OK")} ${t}`],s=a(e,"skillSlug")??a(e,"slug"),o=a(e,"version")??a(e,"currentVersion");(s||o)&&(r.push("",i.section("Skill")),s&&r.push(` ${i.label("Slug")}: ${s}`),o&&r.push(` ${i.label("Version")}: ${o}`));let l=a(e,"visibility")??a(e,"versionVisibility"),c=a(e,"publicationStatus"),u=a(e,"catalogRecord");(l||c||u)&&(r.push("",i.section("Privacy")),l&&r.push(` ${i.label("Visibility")}: ${l}`),c&&r.push(` ${i.label("Publication")}: ${c}`),u&&r.push(` ${i.label("Catalog record")}: ${u}`));let d=C(e,"materializationPlan")??C(e,"installPlan"),p=a(e,"scope")??(d?a(d,"scope"):void 0),y=a(e,"agent")??a(e,"targetAgent")??(d?a(d,"agent")??a(d,"targetAgent"):void 0),m=Array.isArray(e.materializedWrites)?e.materializedWrites.filter(R):[];if(p||y||m.length>0)if(r.push("",i.section("Local Materialization")),p&&r.push(` ${i.label("Scope")}: ${p}`),y&&r.push(` ${i.label("Agent")}: ${y}`),m.length===0)r.push(` ${i.muted("No local files were written by this command.")}`);else for(let P of m.slice(0,O)){let x=a(P,"path");x&&r.push(` ${i.arrow} ${x}`)}let h=Yi(e,i).filter(P=>!P.includes("materialized writes:"));h.length>0&&r.push("",...h);let w=er(e);return w.length>0&&r.push("",i.section("Next"),...w.map(P=>` ${i.arrow} ${P}`)),r.join(`
|
|
733
|
+
`)}async function bo(e,t){let n=await fe(t),i=Object.values(n.installs);return f({status:"ok",results:i},`Found ${i.length} local install records.`,e.json,t)}async function Po(e,t,n){let i=v(e[0],"remove requires a skill slug."),r=await fe(n),s=r.installs[i];if(!s)return j({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 r.installs[i],await Hi(n,r);let o={status:"removed",skillSlug:i,removedRecord:s};return t.json?f(o,`Removed ${i}.`,!0,n):{exitCode:0,stdout:Ao(i,n),stderr:""}}async function So(e,t,n){let i=v(e[0],"update requires a skill slug."),r=new URLSearchParams;B(r,"pin",t.pin),t.dryRun&&r.set("dryRun","true");let o=(await fe(n)).installs[i],l;try{l=await b(n,`/api/v1/skills/${encodeURIComponent(i)}${ie(r)}`,{headers:U(n.apiKey,n.authBlockedMessage)})}catch(u){if(u instanceof E&&u.status===404&&o){let d={status:"backend_missing",reasonCode:"local_install_backend_missing",skillSlug:i,localInstall:o,installedVersion:a(o,"version")??a(o,"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 j(d,`${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(u instanceof E)return ot(u,t.json);throw u}let c=Ro(i,l,o,n);return t.json?f(c,"Update check complete.",!0,n):{exitCode:0,stdout:_o(c,n),stderr:""}}async function Co(e,t){let n=await fe(t),r={status:"synced",results:await Promise.all(Object.values(n.installs).map(async s=>xo(s,t)))};return e.json?f(r,"Local install records synced.",!0,t):{exitCode:0,stdout:Io(r,t),stderr:""}}function Ro(e,t,n,i){let r=n?a(n,"version")??a(n,"currentVersion"):void 0,s=a(t,"currentVersion")??a(t,"version"),o=n?r&&s&&r!==s?"update_available":"up_to_date":"not_installed";return I({...t,skillSlug:a(t,"skillSlug")??a(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 xo(e,t){let n=a(e,"skillSlug")??a(e,"slug");if(!n)return{...e,syncStatus:"local_only",backendStatus:"unchecked"};try{let i=await b(t,`/api/v1/skills/${encodeURIComponent(n)}`,{headers:Ke(t.apiKey)}),s=(a(i,"claimedOrigin")??a(i,"sourceKind")??a(e,"sourceKind"))==="public_source"||a(e,"sourceKind")==="external";return{...e,syncStatus:s?"source_backed":"catalog_backed",backendStatus:"found",latestAvailableVersion:a(i,"currentVersion")??a(i,"version"),catalog:$o(i)}}catch(i){return i instanceof E&&i.status===404?{...e,syncStatus:"backend_missing",backendStatus:"not_found",selectedBackend:t.baseUrl}:{...e,syncStatus:"unchecked",backendStatus:"error",backendError:ue(i)}}}function $o(e){return I({slug:a(e,"slug")??a(e,"skillSlug"),currentVersion:a(e,"currentVersion")??a(e,"version"),claimedOrigin:a(e,"claimedOrigin"),trust:a(e,"trust")??a(e,"publicationStatus")})}function _o(e,t){let n=W(t),i=a(e,"skillSlug")??a(e,"slug")??"skill",r=a(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=a(e,"installedVersion"),l=a(e,"latestAvailableVersion");o&&s.push(` ${n.label("Installed version")}: ${o}`),l&&s.push(` ${n.label("Latest available version")}: ${l}`);let c=C(e,"localInstall"),u=c?a(c,"materializedPath")??a(c,"path"):void 0,d=c?a(c,"scope"):void 0,p=c?a(c,"targetAgent")??a(c,"agent"):void 0;c&&(s.push("",n.section("Local Install")),d&&s.push(` ${n.label("Scope")}: ${d}`),p&&s.push(` ${n.label("Agent")}: ${p}`),u&&s.push(` ${n.label("Path")}: ${u}`));let y=a(e,"nextStep");return y&&s.push("",n.section("Next"),` ${n.arrow} ${y}`),s.join(`
|
|
734
|
+
`)}function Io(e,t){let n=W(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(`
|
|
735
|
+
`)):(e.results.slice(0,O).forEach((r,s)=>{let o=a(r,"skillSlug")??a(r,"slug")??`item-${s+1}`,l=a(r,"syncStatus")??"unchecked",c=a(r,"version")??a(r,"currentVersion");i.push(`${s+1}. ${o}`),i.push(` status: ${l.replaceAll("_"," ")}${c?`; version: ${c}`:""}`),l==="backend_missing"&&i.push(` ${n.muted("Installed locally, but missing from the selected backend catalog.")}`)}),e.results.length>O&&i.push(` ${n.muted(`... ${e.results.length-O} more`)}`),i.push("",n.section("Next")),i.push(` ${n.arrow} skills-layer installed`),i.push(` ${n.arrow} skills-layer update <skill-slug>`),i.join(`
|
|
736
|
+
`))}function Ao(e,t){let n=W(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(`
|
|
737
|
+
`)}function jo(e,t,n){let i=W(n),r=a(t,"version")??a(t,"currentVersion"),s=a(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(`
|
|
738
|
+
`)}function Eo(e){let t=a(e,"status"),n=a(e,"reasonCode");return t==="invalid_transition"||t==="forbidden"||t==="not_found"||n==="invalid_transition"}function Lo(e,t){let n=a(e,"why")??a(e,"reason")??a(e,"error"),i=a(e,"currentVisibility"),r=a(e,"nextVisibility")??a(e,"visibility"),s=i||r?` Current visibility: ${i??"unknown"}; requested visibility: ${r??"unknown"}.`:"",o=a(e,"nextStep")??`Run \`skills-layer creator status ${t}\` and choose a valid visibility transition.`;return`Visibility was not changed for ${t}.${s}${n?` ${n}`:""}
|
|
739
|
+
Next step: ${o}`}async function To(e,t,n){let i=await fe(n),r=e[0];if(!r){let l=Object.values(i.installs);return f({status:l.length>0?"restored":"no_op",results:l},`Restore checked ${l.length} local install record${l.length===1?"":"s"}.`,t.json,n)}let s=i.installs[r];if(!s)return j({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:jo(r,s,n),stderr:""}}async function Uo(e,t,n){let i=v(e[0],"check requires a skill slug.");return await S(`/api/v1/skills/${encodeURIComponent(i)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function Bo(e,t,n){let i=v(e[0]??t.source,"import requires a source."),r=await Mt(i,n.cwd),s=await b(n,"/api/v1/source-imports",{method:"POST",headers:_(n.apiKey),body:JSON.stringify(I({...r??{source:i},quarantine:t.quarantine,skillSlug:g(t.skill),visibility:g(t.visibility)}))});return await K(n.paths.importsPath,{version:1,lastImport:s,savedAt:n.now()}),f(s,"Source import submitted.",t.json,n)}async function Mo(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 S(`/api/v1/source-references/resolve?reference=${encodeURIComponent(r)}`,t,n,"Source reference resolved.")}return i==="connection"?await No(e.slice(1),t,n):k(`Unknown source command "${e.join(" ")}".`,t.json)}async function No(e,t,n){let i=e[0];if(i==="start")return await N("/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 S(`/api/v1/me/source-connections/${encodeURIComponent(r)}`,t,n,"Source connection loaded.",{authenticated:!0}):i==="complete"?await N(`/api/v1/me/source-connections/${encodeURIComponent(r)}/complete`,F(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed."):i==="cancel"?await N(`/api/v1/me/source-connections/${encodeURIComponent(r)}/cancel`,{},t,n,"Source connection cancelled."):k(`Unknown source connection command "${i??""}".`,t.json)}async function Oo(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 S(`/api/v1/me/approvals/${encodeURIComponent(r)}`,t,n,"Approval status loaded.",{authenticated:!0}):i==="complete"?await N(`/api/v1/me/approvals/${encodeURIComponent(r)}/complete`,I({decision:g(t.decision),evidence:at(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed."):k(`Unknown approval request command "${i??""}".`,t.json)}async function Fo(e,t,n){let i=e[0]??"list";if(i==="list")return await S("/api/v1/me/workspaces",t,n,"Workspaces loaded.",{authenticated:!0});if(i==="create")return await N("/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 S(`/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.");return await N(`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,{skillSlug:s,dryRun:t.dryRun},t,n,"Workspace deployment requested.")}if(i==="remove"){let s=v(e[2],"workspace remove requires a skill slug.");return await rt(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}`,{method:"DELETE",headers:U(n.apiKey,n.authBlockedMessage)},t,n,"Workspace skill removed.")}if(i==="guide"){let s=v(e[2],"workspace guide requires a skill slug.");return await S(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}return k(`Unknown workspace command "${i}".`,t.json)}async function qo(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 va(r.purchaseId,n);return D(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 Zt([i],t,n))}async function Ko(e,t,n){let i=e[0]??"list";if(i==="list")return await S("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(i==="spending")return await S("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let r=v(e[1],`purchases ${i} requires a purchase id.`);return i==="invoice"?await S(`/api/v1/purchases/${encodeURIComponent(r)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0}):i==="refund-quote"?await S(`/api/v1/purchases/${encodeURIComponent(r)}/refund-quote`,t,n,"Refund quote loaded.",{authenticated:!0}):i==="refund"?await N(`/api/v1/purchases/${encodeURIComponent(r)}/refund`,F(t,["reason"]),t,n,"Refund requested."):k(`Unknown purchases command "${i}".`,t.json)}async function Go(e,t,n){let i=e[0];if(i==="add"){let r=v(e[1],"library add requires a skill slug.");return await N("/api/v1/install",{skillSlug:r},t,n,"Skill added to library.")}return k(`Unknown library command "${i}".`,t.json)}async function Do(e,t,n){let i=v(e[0],"export requires a skill slug."),r=new URLSearchParams;B(r,"version",t.version);let s=await b(n,`/api/v1/me/library/${encodeURIComponent(i)}/export${ie(r)}`,{headers:U(n.apiKey,n.authBlockedMessage)}),o=g(t.output);if(o){let l=await Ci({backend:n,exportResult:s,flags:t,skillSlug:i});if(D(l))return l;let c=ae(n.cwd,o);await qt(c,l.bytes);let u={...s};return delete u.downloadUrl,f({...u,archiveSha256:l.archiveSha256,archiveHashFormat:l.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 Xn(e,t,n,i){let r=v(t[0],`${e==="add"?"add-review":"show-reviews"} requires a skill slug.`);return e==="show"?await S(`/api/v1/me/library/reviews?skillSlug=${encodeURIComponent(r)}`,n,i,"Reviews loaded.",{authenticated:!0}):await N(`/api/v1/me/library/${encodeURIComponent(r)}/review`,F(n,["rating","feedback"]),n,i,"Review added.")}async function ei(e,t,n,i){let r=v(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);return e==="show"?await S(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0}):await N(`/api/v1/me/library/${encodeURIComponent(r)}/report-issue`,F(n,["issueType","message"]),n,i,"Issue reported.")}async function Ho(e,t,n){let i=e[0];if(i==="hook"){let r=e[1];return r==="install"?await Tt(t,n):r==="status"?await Vo(t,n):k(`Unknown guardian hook command "${r??""}".`,t.json)}if(i==="enable")return e[1]||t.skill?await Pt("enforce",e,t,n):await Tt(t,n);if(i==="disable")return await Pt("disabled",e,t,n);if(i==="enable-warnings-only")return await Pt("warning_only",e,t,n);if(i==="status")return await zo(e,t,n);if(i==="exec")return await Jo(e,t,n);if(i==="check"){let r=v(e[1]??t.skill,"guardian check requires a skill slug."),s=li(t,"check"),o=t.grantJson.map(h=>un(h,"grant-json")),l=vl(t.cloudTrustLedger);if(l.status==="invalid")return k(l.message,t.json);let c=Ut(t.telemetryMode,l.policy==="off"?"local_only":"cloud_managed");if(c.status==="invalid")return k(c.message,t.json);let u=await ji({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=I({skillSlug:r,version:p,action:s,authorizationGrants:o,path:d,guardianPreference:await tn(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:nt(m),reasonCode:Bt(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=Ut(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return k(o.message,t.json);let l=g(t.path)??(await Ei({skillSlug:r,flags:t,backend:n})).installedPath,c=li(t,"incident"),u=at(t.evidenceJson,"evidence-json"),d=o.mode==="cloud_managed"&&!n.apiKey?"local_only":o.mode,p=I({skillSlug:r,version:s,action:c,evidence:u,path:l,telemetryMode:d,incident:!0,reason:g(t.reason)});if(d==="local_only"){if(!l)return k("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let w=await si({backend:n,skillSlug:r,version:s,installedPath:l,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:l});let P=oi(n,r);return await te(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=l?await si({backend:n,skillSlug:r,version:s,installedPath:l,action:c,reason:g(t.reason)??"Guardian Cloud-managed incident"}):null;await Ne(n.paths.incidentsDir,{recursive:!0});let h=oi(n,r);return await te(h,JSON.stringify({request:p,response:y,localResponse:m,savedAt:n.now()},null,2)),await Le(n,{skillSlug:r,version:s,action:c,decisionStatus:nt(y),reasonCode:Bt(y),telemetryMode:o.mode,path:l}),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 Jo(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=Ut(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return k(o.message,t.json);let l=ia(t,s),c=await ji({skillSlug:r,version:g(t.version),action:l,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=I({skillSlug:r,version:d,action:l,authorizationGrants:t.grantJson.map(P=>un(P,"grant-json")),path:u,guardianPreference:await tn(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=nt(y),h=Bt(y);if(await Le(n,{skillSlug:r,version:d,action:l,decisionStatus:m,reasonCode:h,telemetryMode:o.mode,path:u}),!ra(y))return j({status:"blocked",reasonCode:h,skillSlug:r,guardian:y,localPreflight:me(c.context),command:{executable:G(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:G(s[0]??""),executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let w=await sa(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):oa(w),stderr:w.stderr}}async function Pt(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 aa(i,r,s),f(s,s.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,i)}async function zo(e,t,n){let i=g(t.skill)??g(e[1]),r=await Ii(n,i),s=await qe(n),o=i?await la(n,i):void 0;return f(I({status:"ok",skillSlug:a(r,"skillSlug")??i,policy:r,localPreference:o,hook:s,nextAction:a(r,"nextAction"),nextStep:a(r,"nextStep")}),"Guardian status loaded.",t.json,n)}async function Ii(e,t){let n=t?await tn(e,t):void 0;return await b(e,"/api/v1/guardian/status",{method:"POST",headers:_(e.apiKey),body:JSON.stringify(I({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function Wo(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 Ii(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 Tt(e,t){let n=g(e.agent)??"codex",i=Ti(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=ca(r,i.scope,t);if(!s)return k(`Guardian ${i.scope} hooks are not available for ${r.displayName}.`,e.json);await ua(s,t);let o=Mi(t,i.scope),l=ai(Te(t.cwd,s.hookPath)),c=ai(Te(t.cwd,s.configPath)),d=[...(await Ni(o)).hooks.filter(p=>a(p,"agent")!==r.id||a(p,"scope")!==i.scope),{hookId:se,hookName:Z,agent:r.id,agentName:r.displayName,scope:i.scope,hookPath:l.startsWith("..")?s.hookPath:l,configPath:c.startsWith("..")?s.configPath:c,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,enabledAt:t.now()}];return await K(o,{version:1,hooks:d}),f({status:"enabled",hookId:se,hookName:Z,agent:r.id,agentName:r.displayName,scope:i.scope,hookPath:s.hookPath,configPath:s.configPath,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,agentCommandMatrix:wt({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 Vo(e,t){let n=g(e.scope),i=n?Ti(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 l of n){let c=Mi(e,l),u=await Ni(c);for(let d of u.hooks){let p=a(d,"hookPath"),y=p?ri(e,l,p):null,m=a(d,"configPath"),h=m?ri(e,l,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:a(d,"hookId")??se,hookName:a(d,"hookName")??Z,...d,scope:a(d,"scope")??l,hookPath:y??p??null,configPath:h??m??null,active:w,configActive:P,hookState:x})}}let r=i.filter(l=>l.active===!0).length,s=i.filter(l=>l.active===!1).length,o=r>0?0:s;return{status:"ok",enforcementLayer:r>0?"native_hook":"not_installed",strictPreActionBlocking:i.some(l=>l.strictPreActionBlocking===!0),activeHookCount:r,missingHookCount:o,staleHookCount:s,hooks:i,setup:await nn(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 Ai(e,t){if(e.json){let u=await z(t.paths.mcpConfigPath);return f({setup:await nn(t),mcp:{status:u?"mcp_configured":"mcp_not_configured",configured:!!u,clientId:u?a(u,"clientId")??"codex":void 0,clientIds:u&&Array.isArray(u.clientIds)?u.clientIds:void 0,mcpUrl:u?a(u,"mcpUrl"):void 0,readiness:u?{status:"configured_needs_agent_reload",verifyCommand:`skills-layer mcp verify --client ${a(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:Zo(t.now(),7)};return await ii(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(D(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 Tt(u,t);if(d.exitCode!==0)return d;s.security=ya(d.stdout)??{status:"enabled",agent:g(u.agent),scope:g(u.scope)}}await ii(t,o);let c=(R(s.mcp)?a(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 Yo(e,t){let n=await qe(t),i=await nn(t),r=ce(n,"activeHookCount")??0;if(t.stdoutIsTty&&r===0&&!i)return await Ai(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}
|
|
740
|
+
|
|
741
|
+
${s}`,stderr:""}}function Qo(e,t){let n=ce(e,"activeHookCount")??0,i=ce(e,"missingHookCount")??0,r=a(t,"status")??"unknown",s=a(t,"effectiveMode"),o=a(t,"adminPolicy"),l=a(t,"nextAction"),c=a(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:a(e,"enforcementLayer")??"native_hook",strictPreActionBlocking:e.strictPreActionBlocking===!0,policyStatus:r,adminPolicy:o,effectiveMode:s,policyNextAction:l,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:a(e,"enforcementLayer")??"not_installed",strictPreActionBlocking:e.strictPreActionBlocking===!0,policyStatus:r,adminPolicy:o,effectiveMode:s,policyNextAction:l,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 Zo(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?e:(n.setUTCDate(n.getUTCDate()+t),n.toISOString())}async function ji(e){let t=Li(g(e.flags.unmanagedPolicy)??e.backend.env.SKILLS_LAYER_UNMANAGED_SKILL_POLICY);if(t.status==="invalid")return{status:"invalid",result:k(t.message,e.flags.json)};let n=await Ei({skillSlug:e.skillSlug,flags:e.flags,backend:e.backend,unmanagedPolicy:t.policy});if(n.unmanaged&&n.unmanagedPolicy==="block")return Qe({...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 fa(n.installedPath))return Qe({...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 ta(e.skillSlug,n.installedPath);if(n.identityAssessment=i,i.reattestationRequired===!0)return Qe({...e,context:n,reasonCode:a(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 na(e.skillSlug,n.installedPath);return n.driftAssessment=r,r.reattestationRequired===!0?Qe({...e,context:n,reasonCode:a(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 Qe(e){return await Le(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:j({status:"blocked",skillSlug:e.skillSlug,version:e.version??e.context.version,reasonCode:e.reasonCode,localPreflight:me(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 Ei(e){let t=Li(g(e.flags.unmanagedPolicy)),n=e.unmanagedPolicy??(t.status==="valid"?t.policy:"warn"),i=g(e.flags.path),r=await Xo(e.skillSlug,e.backend),s=i?ae(e.backend.cwd,i):r?.installedPath;return{source:i?"explicit_path":r?.source??"install_index",installedPath:s,version:g(e.flags.version)??r?.version,record:r?.record,unmanaged:!!(i&&!r),unmanagedPolicy:n,allowUnmanagedOnce:e.flags.allowUnmanagedOnce}}async function Xo(e,t){let i=(await fe(t)).installs[e];if(i)return{source:"install_index",installedPath:ti(i,t),version:a(i,"version"),record:i};for(let r of ea(t)){let s=await z(r);if(!R(s)||!R(s.installs))continue;let o=s.installs[e];if(R(o))return{source:"lockfile",installedPath:ti(o,t),version:a(o,"version"),record:o}}return null}function ea(e){return Array.from(new Set([A(e.cwd,"skills-layer-lock.json"),A(e.paths.stateDir,"skills-layer-lock.json")]))}function ti(e,t){let n=a(e,"canonicalPath")??a(e,"materializedPath")??a(e,"bundlePath")??a(e,"path");if(n){let o=ae(t.cwd,n);return G(o).toLowerCase()==="skill.md"?oe(o):o}let r=(Array.isArray(e.materializedWrites)?e.materializedWrites.filter(R):[]).find(o=>{let l=a(o,"path");return l?.toLowerCase().endsWith("/skill.md")||l?.toLowerCase()==="skill.md"}),s=r?a(r,"path"):void 0;return s?oe(ae(t.cwd,s)):void 0}async function ta(e,t){let n=A(t,"SKILL.md");if(!await ge(n))return{status:"not_checked",reasonCode:"skill_document_unavailable",expectedSkillSlug:e,reattestationRequired:!1};try{let i=Ri(await Oe(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:ue(i),reattestationRequired:!0}}}async function na(e,t){let n=A(t,".skills-layer-runtime.json"),i=await z(n),r=i?C(i,"materialization"):void 0,s=r?a(r,"skillDocumentSha256"):void 0;if(!i||!s)return{status:"not_checked",reasonCode:"runtime_metadata_unavailable",skillSlug:e,reattestationRequired:!1};let o=A(t,"SKILL.md");if(!await ge(o))return{status:"changed",reasonCode:"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:s,reattestationRequired:!0};let l=qi(await Oe(o,"utf8")),c=l===s;return{status:c?"unchanged":"changed",reasonCode:c?"installed_artifact_matches":"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:s,observedSkillDocumentSha256:l,reattestationRequired:!c}}function me(e){return I({source:e.source,installedPath:e.installedPath,version:e.version,unmanaged:e.unmanaged,unmanagedPolicy:e.unmanagedPolicy,allowUnmanagedOnce:e.allowUnmanagedOnce,identityAssessment:e.identityAssessment,driftAssessment:e.driftAssessment})}function Li(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 Ut(e,t){let n=g(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 ia(e,t){let n=at(e.actionJson,"action-json");return n&&typeof n=="object"&&!Array.isArray(n)?n:{type:"shell_command",command:G(t[0]??"command")}}function ra(e){let t=C(e,"enforcement");return typeof t?.canExecute=="boolean"?t.canExecute:nt(e)!=="blocked"}async function sa(e,t){let[n,...i]=e;return await new Promise((r,s)=>{let o=mi(n,i,{cwd:t.cwd,env:{...process.env,...t.env},stdio:["ignore","pipe","pipe"]}),l="",c="";o.stdout?.setEncoding("utf8"),o.stderr?.setEncoding("utf8"),o.stdout?.on("data",u=>{l=ni(`${l}${u}`)}),o.stderr?.on("data",u=>{c=ni(`${c}${u}`)}),o.on("error",s),o.on("close",u=>{r({executable:G(n),argsCount:i.length,exitCode:typeof u=="number"?u:1,stdout:l,stderr:c})})})}function ni(e){return e.length>2e4?`${e.slice(0,2e4)}
|
|
742
|
+
[output truncated]`:e}function oa(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(`
|
|
743
|
+
`)}function Ti(e){let t=g(e)??"project";return t==="project"||t==="global"?{status:"valid",scope:t}:{status:"invalid",message:"guardian hooks --scope must be one of: project, global."}}function Ui(e){return A(e.paths.stateDir,"guardian-modes.json")}function Bi(e){return A(e.paths.stateDir,"setup-state.json")}async function en(e){let t=await z(Ui(e));return{version:1,skills:R(t?.skills)?t.skills:{}}}async function aa(e,t,n){let i=await en(e);await K(Ui(e),{version:1,skills:{...i.skills,[t]:{requestedPreference:a(n,"requestedPreference")??"enforce",effectiveMode:a(n,"effectiveMode")??"enforce",reasonCode:a(n,"reasonCode"),auditId:a(n,"auditId"),updatedAt:e.now()}}})}async function tn(e,t){let i=(await en(e)).skills[t];return i?a(i,"requestedPreference"):void 0}async function la(e,t){return(await en(e)).skills[t]}async function nn(e){let t=await z(Bi(e));return R(t)?{version:1,setupChoice:a(t,"setupChoice"),mcpChoice:a(t,"mcpChoice"),mcpPromptedAt:a(t,"mcpPromptedAt"),guardianHookChoice:a(t,"guardianHookChoice"),guardianHookPromptedAt:a(t,"guardianHookPromptedAt"),remindAfter:a(t,"remindAfter")}:null}async function ii(e,t){await K(Bi(e),t)}function ca(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:se,hookName:Z,configPath:A(i,"hooks.json"),hookPath:A(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:se,hookName:Z,configPath:A(i,"settings.json"),hookPath:A(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook",strictPreActionBlocking:!0}:e.id==="cline"?{agent:e.id,agentName:e.displayName,scope:t,hookId:se,hookName:Z,configPath:A(i,"guardian-hooks.json"),hookPath:A(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1}:null:null}async function ua(e,t){if(await te(e.hookPath,ma(e.agentName)),await hi(e.hookPath,448).catch(()=>{}),e.agent==="codex"){await K(e.configPath,da(e.hookPath));return}if(e.agent==="claude-code"){await K(e.configPath,ga(e.hookPath));return}e.agent==="cline"&&await K(e.configPath,pa(e,t))}function Mi(e,t){return t==="global"?A(e.paths.stateDir,"guardian-hooks.json"):A(e.cwd,".skills-layer","guardian-hooks.json")}async function Ni(e){let t=await z(e);return{version:1,hooks:Array.isArray(t?.hooks)?t.hooks.filter(R):[]}}function ri(e,t,n){return Se.isAbsolute(n)||n.startsWith("/")?n:ki(t==="global"?e.paths.stateDir:e.cwd,n)}function da(e){return{hooks:{PreToolUse:[{name:Z,id:se,matcher:"Bash|Shell|Read|Write|Edit|apply_patch|mcp__.*",hooks:[{name:Z,type:"command",command:`node ${rn(e)}`}]}]}}}function ga(e){return{hooks:{PreToolUse:[{name:Z,id:se,matcher:"Bash|Read|Write|Edit|MultiEdit|NotebookEdit|WebFetch|WebSearch",hooks:[{name:Z,type:"command",command:`node ${rn(e)}`}]}]}}}function pa(e,t){return{version:1,hookId:se,hookName:Z,agent:e.agent,agentName:e.agentName,scope:e.scope,enforcementLayer:e.enforcementLayer,strictPreActionBlocking:e.strictPreActionBlocking,installedAt:t.now(),hooks:[{name:Z,id:se,event:"PreToolUse",command:`node ${rn(e.hookPath)}`,status:"candidate"}]}}function ma(e){return`#!/usr/bin/env node
|
|
577
744
|
import { spawnSync } from "node:child_process";
|
|
578
745
|
import { readFileSync } from "node:fs";
|
|
579
746
|
|
|
@@ -608,38 +775,39 @@ const result = spawnSync("skills-layer", [
|
|
|
608
775
|
], { stdio: ["ignore", "inherit", "inherit"] });
|
|
609
776
|
|
|
610
777
|
process.exit(result.status ?? 1);
|
|
611
|
-
`}function
|
|
612
|
-
`;return await
|
|
613
|
-
`),await
|
|
614
|
-
`),await
|
|
615
|
-
`)),{status:"written",generatedAt:t,incidentPath:
|
|
616
|
-
`,{encoding:"utf8",mode:384}),await
|
|
778
|
+
`}function rn(e){return JSON.stringify(e)}async function sn(e){let t=A(oe(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:wt({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:qi(e.skillDocumentContent)}},i=`${JSON.stringify(n,null,2)}
|
|
779
|
+
`;return await te(t,i),{path:tt(e.backend.cwd,t),bytes:new TextEncoder().encode(i).length}}async function fa(e){return await ge(A(e,".skills-layer-disabled.json"))}async function si(e){let t=e.backend.now(),n=A(e.installedPath,".skills-layer-disabled.json"),i=A(e.installedPath,".skills-layer-quarantine.json"),r=A(e.installedPath,"incident.md"),s=a(e.action,"type")??"unknown";return await te(n,`${JSON.stringify({disabled:!0,generatedAt:t,skillSlug:e.skillSlug,version:e.version,reason:"Skills Layer Guardian incident response"},null,2)}
|
|
780
|
+
`),await te(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)}
|
|
781
|
+
`),await te(r,["# Skills Layer Guardian Incident Report","",`Generated: ${t}`,`Skill: ${e.skillSlug}`,`Version: ${e.version}`,"","## Summary","",Fi(e.reason),"","## Evidence","",`- ${t}: ${s} -> blocked (incident_recorded)`].join(`
|
|
782
|
+
`)),{status:"written",generatedAt:t,incidentPath:r,writtenFiles:[n,i,r]}}function oi(e,t){let n=e.now().replace(/[:.]/gu,"-");return A(e.paths.incidentsDir,`${t}-${n}.json`)}async function Le(e,t){let n=A(e.paths.stateDir,"guardian-audit.jsonl");await tr(oe(n));let i={version:1,generatedAt:e.now(),skillSlug:t.skillSlug,...t.version?{skillVersion:t.version}:{},actionType:a(t.action,"type")??"unknown",actionTarget:ha(t.action),decisionStatus:t.decisionStatus,reasonCode:t.reasonCode,telemetryMode:t.telemetryMode,...t.path?{localPath:Oi(t.path)}:{}};await ts(n,`${JSON.stringify(i)}
|
|
783
|
+
`,{encoding:"utf8",mode:384}),await cn(n,384)}function nt(e){let t=C(e,"decision"),n=C(e,"enforcement"),i=a(t??{},"status")??a(n??{},"status")??a(e,"status");return i==="allowed"||i==="advisory"?i:"blocked"}function Bt(e){let t=C(e,"decision");return a(t??{},"reasonCode")??a(e,"reasonCode")??a(e,"status")??"cloud_guardian_decision"}function ha(e){let t=a(e,"type");if(t==="secret_read")return"redacted_secret";if(t==="shell_command")return"redacted_command";let n=a(e,"url");if(n)try{return new URL(n).origin}catch{return"redacted_url"}let i=a(e,"target");if(i)return Fi(i);let r=a(e,"path");return r?Oi(r):null}function Oi(e){let t=G(e.trim());return t?`<local-path>/${t}`:"<local-path>"}function Fi(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 ai(e){return e.split(/[\\/]+/u).join("/")}function qi(e){return Gt("sha256").update(e).digest("hex")}async function Ki(e,t,n,i,r){let s=await b(i,"/api/v1/verify",{method:"POST",headers:_(),body:JSON.stringify({email:e,code:t,clientDelivery:"cli_secure_storage"})});if(n.json){let o=a(s,"apiKey");return o?(await Ue(i,o,{expectedEmail:e,knownEmail:a(s,"email")??e,knownRole:a(s,"role")??"user",knownRoles:ne(s,"roles"),knownUserId:a(s,"userId")}),f(J({...s,loggedIn:!0}),"Email verified and login completed.",!0,i)):f(J({...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 it(e,s,n,i,r)}async function it(e,t,n,i,r){let s=a(t,"apiKey"),o=a(t,"role")??"user",l=ne(t,"roles"),c=a(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 f(J({...t,email:e,role:o,...l?{roles:l}:{},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 k("No API key was entered. Run `skills-layer login` once you have the emailed key.",n.json);let d=await Ue(i,u,{expectedEmail:e,knownEmail:e,knownRole:o,knownRoles:l,knownUserId:c,forceProfileValidation:!s}),p=await At(n,{...i,config:d,apiKey:u});return D(p)?p:f(J({...t,status:a(t,"status")??"verified",email:d.email,role:d.role,...d.roles?{roles:d.roles}:{},loggedIn:!0,...p.data?{mcp:p.data}:{}}),[`${r} Logged in as ${d.email}.`,p.message??""].filter(Boolean).join(" "),n.json,i)}async function on(e,t,n,i,r){let s=a(t,"authorizationUrl"),o=v(a(t,"state"),"Social auth did not return a state."),l=Cl(e);if(s){let u=await i.openUrl(s);i.emitInfo(u?`${l} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`:`${l} sign-in started. Open this URL in your browser, then come back here once it is done:
|
|
617
784
|
${s}
|
|
618
|
-
Waiting for browser sign-in to finish...`)}else r.emitInfo(`${l} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`);let c=await Yo(o,r);return D(c)?c:c.status==="verified"||c.status==="recovered"?await tt(c.email,{...c},n,r,i==="recovery"?`Recovered access for ${c.email} through ${l}.`:`Verified ${c.email} through ${l}.`):c.status==="already_registered"?f(c,c.linkedAccount===!0?`${l} 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,r):c.status==="linked"?f(c,`${l} sign-in is now connected.`,n.json,r):Wo(c)?y(ea(c),n.json):y("Social auth completed with an unexpected response.",n.json)}function D(e){return R(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function Vo(e){try{let t=JSON.parse(e);return R(t)?t.data:void 0}catch{return}}function Wo(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 Yo(e,t){for(let n=0;n<120;n+=1)try{let r=await P(t,`/api/v1/identity/social/status/${encodeURIComponent(e)}`),i=a(r,"status")??"failed";if(i==="pending"){await t.sleep(1500);continue}return(i==="verified"||i==="recovered")&&a(r,"email")&&a(r,"role")?{status:i,email:a(r,"email"),role:a(r,"role"),roles:ee(r,"roles"),userId:a(r,"userId"),apiKey:a(r,"apiKey"),keyPrefix:a(r,"keyPrefix"),emailDelivery:a(r,"emailDelivery")}:i==="already_registered"&&a(r,"email")&&a(r,"role")?{status:i,email:a(r,"email"),role:a(r,"role"),roles:ee(r,"roles"),linkedAccount:typeof r.linkedAccount=="boolean"?r.linkedAccount:void 0}:i==="linked"?{status:i}:i==="registration_required"||i==="state_expired"||i==="provider_mismatch"||i==="identity_conflict"||i==="email_required"||i==="failed"?{status:i,error:a(r,"error")}:y("Social auth completed with an unexpected response.",!1)}catch(r){if(r instanceof E&&(r.status===404||r.status===429)){await t.sleep(1500);continue}return y(ue(r),!1)}return y("Timed out while waiting for social auth to complete.",!1)}async function Qo(e,t){for(let n=0;n<120;n+=1)try{let i=(await P(t,"/api/v1/purchases",{headers:T(t.apiKey,t.authBlockedMessage)})).results?.find(s=>s.purchaseId===e);if(!i?.status||i.status==="pending"||i.status==="requires_action"){await t.sleep(1500);continue}return{status:i.status,purchaseId:e}}catch(r){if(r instanceof E&&r.status===429){await t.sleep(1500);continue}return y(ue(r),!1)}return y("Timed out while waiting for purchase confirmation.",!1)}async function Zo(e,t){for(let n=0;n<120;n+=1)try{let r=await P(t,`/api/v1/me/private-skill-charges/${encodeURIComponent(e)}`,{headers:T(t.apiKey,t.authBlockedMessage)}),i=a(r,"status");if(!i||i==="checkout_required"||i==="pending"||i==="requires_action"){await t.sleep(1500);continue}return{...r,status:i}}catch(r){if(r instanceof E&&r.status===429){await t.sleep(1500);continue}return y(ue(r),!1)}return y("Timed out while waiting for payment confirmation.",!1)}function Xo(e){let t=C(e,"accountLink");return(t?a(t,"url"):void 0)??a(e,"url")??a(e,"setupUrl")}function ea(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 je(e,t,n={}){let i=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole?await P({...e,apiKey:t},"/api/v1/me",{headers:{...T(t),...n.notifyLogin?{"x-skills-layer-session-intent":"login"}:{}}}):{userId:n.knownUserId,email:n.knownEmail,role:n.knownRole,roles:n.knownRoles},s=a(i,"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 P({...e,apiKey:t},"/api/v1/capabilities",{headers:T(t)}),l={version:cr,baseUrl:e.baseUrl,apiKey:t,edition:a(o,"edition")??a(i,"edition")??"saas",userId:a(i,"userId")??n.knownUserId,email:s,role:a(i,"role")??n.knownRole??"user",roles:ee(i,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await tn(e.paths.configPath,l,e),await K(e.paths.backendPreferencePath,{version:Kt,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),l}function Zn(e,t){let n=st(e.actionJson,"action-json");if(n&&typeof n=="object"&&!Array.isArray(n))return n;let r=g(e.action);return t==="incident"?{type:"file_write",path:g(e.path)??".skills-layer/incidents/guardian-incident.json"}:r==="file_read"||r==="file_write"?{type:r,path:g(e.path)??"."}:r==="shell_command"?{type:"shell_command",command:"unspecified"}:{type:"api_call",...r?{target:r}:{}}}async function S(e,t,n,r,i={}){let s=i.authenticated?T(n.apiKey,n.authBlockedMessage):Oe(n.apiKey);return await nt(e,{headers:s},t,n,r)}async function ta(e,t){let n=await P(t,"/api/v1/doctor",{headers:Oe(t.apiKey)}),r=await Ne(t),i=await Ro(t),s=[...Mr(n),_o(r,i)];return f({...n,guardian:{...r,policy:i},checks:s},"Doctor checks loaded.",e.json,t)}async function N(e,t,n,r,i){return await nt(e,{method:"POST",headers:_(r.apiKey),body:JSON.stringify(A(t))},n,r,i)}async function Ee(e,t,n,r,i){return await nt(e,{method:"PATCH",headers:_(r.apiKey),body:JSON.stringify(A(t))},n,r,i)}async function nt(e,t,n,r,i){let s=await P(r,e,t);return f(s,i,n.json,r)}async function P(e,t,n={}){let r=await e.fetchFn(`${e.baseUrl}${t}`,n).catch(o=>{throw new Error(`Unable to reach ${e.baseUrl}. ${ue(o)}`)});if(!r.ok)throw await na(r);let i=await r.text();if(!i)return{};let s=JSON.parse(i);return s&&typeof s=="object"&&!Array.isArray(s)&&"data"in s?s.data:s}async function na(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new E(e.status,a(n,"error")??(e.statusText||"Request failed"),n)}catch{return new E(e.status,t)}return new E(e.status,e.statusText||"Request failed")}function T(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 Oe(e){return e?{authorization:`Bearer ${e}`}:{}}function _(e){return{"content-type":"application/json",...Oe(e)}}async function rt(e){let t=await Ui(e);if(t.isFile())return[{path:G(e),content:await Be(e,"utf8")}];if(!t.isDirectory())throw new Error(`Unsupported path: ${e}`);let n=[];if(await Ur(e,e,n),n.length===0)throw new Error(`No readable files found in ${e}.`);return n.sort((r,i)=>r.path.localeCompare(i.path))}async function Ur(e,t,n){for(let r of await ar(t,{withFileTypes:!0})){if(ra(r.name))continue;let i=I(t,r.name);if(r.isDirectory()){await Ur(e,i,n);continue}if(!r.isFile())continue;let s=Ie(e,i).split("\\").join("/");try{n.push({path:s,content:await Be(i,"utf8")})}catch{continue}}}function ra(e){return e===".git"||e==="node_modules"||e==="coverage"||e===ia()||e==="dist"}function ia(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}async function Et(e,t){if(/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e))return;let n=se(t,e);try{return await sr(n),{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:await rt(n)}}catch{return}}async function kt(e,t){let n=sa(t);if(n.length===0)return t;let r=[];for(let i of n){let s=Lr(i.path),o=se(e.cwd,s),l=Ie(e.cwd,o);if(!l||l.startsWith("..")||ve.isAbsolute(l))throw new Error(`Cloud install plan attempted to write outside the current workspace: ${i.path}`);if(await re(o,i.content),r.push({path:s,bytes:new TextEncoder().encode(i.content).length}),G(s).toLowerCase()==="skill.md"){let c=a(t,"skillSlug")??a(t,"slug")??G(ie(s)),u=await Zt({backend:e,skillSlug:c,version:a(t,"version"),skillDocumentPath:o,skillDocumentContent:i.content});r.push(u)}}return{...t,materializedWrites:r}}function sa(e){return[...wt(e.localWrites),...wt(C(e,"installPlan")?.localWrites),...wt(C(e,"materializationPlan")?.localWrites)]}function wt(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];let n=t,r=g(n.path),i=typeof n.content=="string"?n.content:void 0;return r&&i!==void 0?[{path:r,content:i}]:[]}):[]}function Lr(e){let t=e.replaceAll("\\","/").replace(/^\.\/+/u,"");if(!t||t.includes("\0")||Ft.isAbsolute(t)||ve.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=a(e,"apiKey");if(!n)return;let r={version:cr,baseUrl:t.baseUrl,apiKey:n,edition:a(e,"edition")??t.config?.edition??"saas",userId:a(e,"userId")??t.config?.userId,email:a(e,"email")??t.config?.email??"unknown",role:a(e,"role")??t.config?.role??"user",roles:ee(e,"roles")??t.config?.roles,lastSelectedAgent:t.config?.lastSelectedAgent,savedAt:t.now()};await tn(t.paths.configPath,r,t)}async function pe(e){let t=await z(e.paths.installsPath);if(!R(t))return{version:An,installs:{}};let n=R(t.installs)?Xn(t.installs):R(t.skills)?Xn(t.skills):{};return{version:typeof t.version=="number"?t.version:An,installs:n}}async function Tr(e,t){await K(e.paths.installsPath,t)}async function Qe(e,t,n){let r=a(t,"skillSlug")??a(t,"slug")??n,i=await pe(e);i.installs[r]={skillSlug:r,...t,savedAt:e.now()},await Tr(e,i)}function Xn(e){let t={};for(let[n,r]of Object.entries(e))t[n]=R(r)?r:{skillSlug:n,value:r};return t}var O=5;function f(e,t,n,r){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):aa(e,t,r),stderr:""}}function aa(e,t,n){let r=V(n);if(R(e)){if(t==="Status loaded."&&er(e))return ua(e,t,r);if(t==="Doctor checks loaded."&&er(e))return da(e,t,r);if(t==="Creator payout profile loaded.")return ja(e,t,r);if(t==="Creator earnings loaded."||t==="Earnings loaded.")return Ea(e,"Creator earnings loaded.",r);if(t==="Creator payouts loaded."||t==="Payouts loaded.")return Ua(e,"Creator payouts loaded.",r);if(t==="Guardian check complete.")return la(e,t,r)}let i=[`${r.ok("OK")} ${t}`];if(R(e)){let s=Fr(e,r);s.length>0&&i.push("",...s);let o=Dr(e);o.length>0&&i.push("",r.section("Next"),...o.map(l=>` ${r.arrow} ${l}`))}return i.join(`
|
|
619
|
-
`)}function
|
|
620
|
-
`)}function
|
|
621
|
-
`)}function
|
|
622
|
-
`)}function
|
|
623
|
-
`)}function
|
|
624
|
-
`)}function
|
|
625
|
-
`)}function
|
|
626
|
-
`)}function
|
|
627
|
-
`)}function
|
|
628
|
-
`)}function
|
|
629
|
-
`)}function
|
|
630
|
-
`)}function
|
|
631
|
-
`)}function
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
`)
|
|
785
|
+
Waiting for browser sign-in to finish...`)}else i.emitInfo(`${l} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`);let c=await wa(o,i);return D(c)?c:c.status==="verified"||c.status==="recovered"?await it(c.email,{...c},n,i,r==="recovery"?`Recovered access for ${c.email} through ${l}.`:`Verified ${c.email} through ${l}.`):c.status==="already_registered"?f(c,c.linkedAccount===!0?`${l} 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,`${l} sign-in is now connected.`,n.json,i):ka(c)?k(Sa(c),n.json):k("Social auth completed with an unexpected response.",n.json)}function D(e){return R(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function ya(e){try{let t=JSON.parse(e);return R(t)?t.data:void 0}catch{return}}function ka(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 wa(e,t){for(let n=0;n<120;n+=1)try{let i=await b(t,`/api/v1/identity/social/status/${encodeURIComponent(e)}`),r=a(i,"status")??"failed";if(r==="pending"){await t.sleep(1500);continue}return(r==="verified"||r==="recovered")&&a(i,"email")&&a(i,"role")?{status:r,email:a(i,"email"),role:a(i,"role"),roles:ne(i,"roles"),userId:a(i,"userId"),apiKey:a(i,"apiKey"),keyPrefix:a(i,"keyPrefix"),emailDelivery:a(i,"emailDelivery")}:r==="already_registered"&&a(i,"email")&&a(i,"role")?{status:r,email:a(i,"email"),role:a(i,"role"),roles:ne(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:a(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 va(e,t){for(let n=0;n<120;n+=1)try{let r=(await b(t,"/api/v1/purchases",{headers:U(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 ba(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:U(t.apiKey,t.authBlockedMessage)}),r=a(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 Pa(e){let t=C(e,"accountLink");return(t?a(t,"url"):void 0)??a(e,"url")??a(e,"setupUrl")}function Sa(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:{...U(t),...n.notifyLogin?{"x-skills-layer-session-intent":"login"}:{}}}):{userId:n.knownUserId,email:n.knownEmail,role:n.knownRole,roles:n.knownRoles},s=a(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:U(t)}),l={version:wi,baseUrl:e.baseUrl,apiKey:t,edition:a(o,"edition")??a(r,"edition")??"saas",userId:a(r,"userId")??n.knownUserId,email:s,role:a(r,"role")??n.knownRole??"user",roles:ne(r,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await ln(e.paths.configPath,l,e),await K(e.paths.backendPreferencePath,{version:Wt,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),l}function li(e,t){let n=at(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 S(e,t,n,i,r={}){let s=r.authenticated?U(n.apiKey,n.authBlockedMessage):Ke(n.apiKey);return await rt(e,{headers:s},t,n,i)}async function Ca(e,t){let n=await b(t,"/api/v1/doctor",{headers:Ke(t.apiKey)}),i=await qe(t),r=await Wo(t),s=[...zi(n),Qo(i,r)];return f({...n,guardian:{...i,policy:r},checks:s},"Doctor checks loaded.",e.json,t)}async function N(e,t,n,i,r){return await rt(e,{method:"POST",headers:_(i.apiKey),body:JSON.stringify(I(t))},n,i,r)}async function Be(e,t,n,i,r){return await rt(e,{method:"PATCH",headers:_(i.apiKey),body:JSON.stringify(I(t))},n,i,r)}async function rt(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 Ra(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 Ra(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new E(e.status,a(n,"error")??(e.statusText||"Request failed"),n)}catch{return new E(e.status,t)}return new E(e.status,e.statusText||"Request failed")}function U(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 st(e){let t=await ns(e);if(t.isFile())return[{path:G(e),content:await Oe(e,"utf8")}];if(!t.isDirectory())throw new Error(`Unsupported path: ${e}`);let n=[];if(await Gi(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 Gi(e,t,n){for(let i of await yi(t,{withFileTypes:!0})){if(xa(i.name))continue;let r=A(t,i.name);if(i.isDirectory()){await Gi(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 xa(e){return e===".git"||e==="node_modules"||e==="coverage"||e===$a()||e==="dist"}function $a(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}async function Mt(e,t){if(/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e))return;let n=ae(t,e);try{return await fi(n),{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:await st(n)}}catch{return}}async function St(e,t){let n=_a(t);if(n.length===0)return t;let i=[];for(let r of n){let s=Di(r.path),o=ae(e.cwd,s),l=Te(e.cwd,o);if(!l||l.startsWith("..")||Se.isAbsolute(l))throw new Error(`Cloud install plan attempted to write outside the current workspace: ${r.path}`);if(await te(o,r.content),i.push({path:s,bytes:new TextEncoder().encode(r.content).length}),G(s).toLowerCase()==="skill.md"){let c=a(t,"skillSlug")??a(t,"slug")??G(oe(s)),u=await sn({backend:e,skillSlug:c,version:a(t,"version"),skillDocumentPath:o,skillDocumentContent:r.content});i.push(u)}}return{...t,materializedWrites:i}}function _a(e){return[...Ct(e.localWrites),...Ct(C(e,"installPlan")?.localWrites),...Ct(C(e,"materializationPlan")?.localWrites)]}function Ct(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 Di(e){let t=e.replaceAll("\\","/").replace(/^\.\/+/u,"");if(!t||t.includes("\0")||Jt.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 Ia(e,t){let n=a(e,"apiKey");if(!n)return;let i={version:wi,baseUrl:t.baseUrl,apiKey:n,edition:a(e,"edition")??t.config?.edition??"saas",userId:a(e,"userId")??t.config?.userId,email:a(e,"email")??t.config?.email??"unknown",role:a(e,"role")??t.config?.role??"user",roles:ne(e,"roles")??t.config?.roles,lastSelectedAgent:t.config?.lastSelectedAgent,savedAt:t.now()};await ln(t.paths.configPath,i,t)}async function fe(e){let t=await z(e.paths.installsPath);if(!R(t))return{version:Fn,installs:{}};let n=R(t.installs)?ci(t.installs):R(t.skills)?ci(t.skills):{};return{version:typeof t.version=="number"?t.version:Fn,installs:n}}async function Hi(e,t){await K(e.paths.installsPath,t)}async function et(e,t,n){let i=a(t,"skillSlug")??a(t,"slug")??n,r=await fe(e);r.installs[i]={skillSlug:i,...t,savedAt:e.now()},await Hi(e,r)}function ci(e){let t={};for(let[n,i]of Object.entries(e))t[n]=R(i)?i:{skillSlug:n,value:i};return t}var O=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):Aa(e,t,i),stderr:""}}function Aa(e,t,n){let i=W(n);if(R(e)){if(t==="Status loaded."&&ui(e))return Ta(e,t,i);if(t==="Doctor checks loaded."&&ui(e))return Ua(e,t,i);if(t==="Creator payout profile loaded.")return tl(e,t,i);if(t==="Creator earnings loaded."||t==="Earnings loaded.")return nl(e,"Creator earnings loaded.",i);if(t==="Creator payouts loaded."||t==="Payouts loaded.")return il(e,"Creator payouts loaded.",i);if(t==="Guardian check complete.")return Ea(e,t,i);if(t==="Reviews loaded.")return ja(e,t,i)}let r=[`${i.ok("OK")} ${t}`];if(R(e)){let s=Yi(e,i);s.length>0&&r.push("",...s);let o=er(e);o.length>0&&r.push("",i.section("Next"),...o.map(l=>` ${i.arrow} ${l}`))}return r.join(`
|
|
786
|
+
`)}function ja(e,t,n){let i=le(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 l=a(s,"reviewId")??a(s,"id"),u=a(s,"skillSlug")??a(s,"slug")??a(s,"skill")??l??`Review ${o+1}`,d=s.rating??s.score,p=a(s,"status"),y=a(s,"updatedAt")??a(s,"createdAt"),m=[l?`review: ${l}`:void 0,d!=null?`rating: ${H("rating",d)}`:void 0,p?`status: ${p}`:void 0,y?`updated: ${y}`:void 0].filter(w=>!!w);r.push(`${o+1}. ${u}`),m.length>0&&r.push(` ${m.join("; ")}`);let h=a(s,"feedback")??a(s,"comment")??a(s,"message");h&&r.push(` ${n.label("feedback")}: ${be(h)}`)}),r.join(`
|
|
787
|
+
`)}function Ea(e,t,n){let i=C(e,"decision"),r=C(e,"enforcement"),s=C(e,"auditEvent"),o=Y(i,"status")??Y(r,"status")??"unknown",l=Y(r,"actionType")??Y(s,"actionType")??"action",c=Y(i,"capability")??Y(r,"capability")??"not specified",u=Y(i,"reasonCode")??Y(r,"reasonCode")??"not specified",d=Y(i,"message")??Y(r,"message")??"Guardian policy resolved this action.",p=Y(s,"skillSlug")??"unknown",y=Y(s,"version")??"unknown",m=Rt(r,"canExecute"),h=Rt(r,"auditRequired"),w=Rt(r,"telemetryRequired"),P=o==="blocked"?"BLOCKED":o==="allowed"?"ALLOWED":"WARNING",x=[`${n.ok("OK")} ${t}`,"",n.section(`${P} ${La(l)}`),` ${n.label("Skill")}: ${p}`,` ${n.label("Version")}: ${y}`,` ${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")}: ${h===!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 ${p}\`.`,` ${n.arrow} Run \`skills-layer guardian incident --skill ${p} --version ${y} --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(`
|
|
788
|
+
`)}function Rt(e,t){if(R(e))return typeof e[t]=="boolean"?e[t]:void 0}function Y(e,t){return R(e)?a(e,t):void 0}function La(e){return e.split(/[_-]+/u).filter(Boolean).map(t=>`${t[0]?.toUpperCase()??""}${t.slice(1)}`).join(" ")}function ui(e){return!!(C(e,"backend")&&C(e,"auth")&&Array.isArray(e.checks))}function Ta(e,t,n){let i=[`${n.ok("OK")} ${t}`,"",n.section("Readiness")],r=a(e,"summary");r&&i.push(` ${r}`);let s=C(e,"backend"),o=s?Oa(s):void 0;o&&i.push(` ${n.label("Backend")}: ${o}`);let l=C(e,"auth"),c=l?Fa(l):void 0;c&&i.push(` ${n.label("Account")}: ${c}`);let u=l?ce(l,"workspaceCount"):void 0;u!==void 0&&i.push(` ${n.label("Workspaces")}: ${u}`);let d=l?ce(l,"libraryCount"):void 0;d!==void 0&&i.push(` ${n.label("Owned skills")}: ${d}`);let p=Ji(e);return p.length>0&&i.push("",n.section("Next"),...p.map(y=>` ${n.arrow} ${y}`)),i.push(` ${n.arrow} Run \`skills-layer doctor\` for diagnostics.`),i.join(`
|
|
789
|
+
`)}function Ua(e,t,n){let i=[`${n.ok("OK")} ${t}`,"",n.section("Diagnostics")],r=a(e,"summary");r&&i.push(` ${r}`);let s=a(e,"status");s&&i.push(` ${n.label("Status")}: ${s}`);let o=zi(e),l=o.filter(d=>qa(a(d,"status"))),c=o.filter(d=>a(d,"status")!=="pass");i.push(l.length===0?" No blocking issues found.":` ${l.length} check${l.length===1?"":"s"} need attention.`),l.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,p)=>{let y=a(d,"status")??"unknown",m=a(d,"title")??a(d,"id")??`Check ${p+1}`;i.push(`${p+1}. ${n.label(`[${y}] ${m}`)}`);let h=a(d,"summary");h&&i.push(` ${h}`);let w=a(d,"why");if(w&&i.push(` ${n.label("Why")}: ${w}`),y!=="pass"){let P=a(d,"nextStep");P&&i.push(` ${n.label("Fix")}: ${P}`);let x=a(d,"recommendedCommand");x&&i.push(` ${n.label("Try")}: ${x}`)}});let u=Ji(e);return u.length>0&&i.push("",n.section(l.length>0?"Recommended Fix":"Next"),...u.map(d=>` ${n.arrow} ${d}`)),i.join(`
|
|
790
|
+
`)}function Ba(e,t,n,i){let r=[`${n.ok("OK")} ${t}`],s=ne(e,"requestedSlugs");s&&s.length>0&&r.push("",n.section("Requested"),` ${s.join(", ")}`);let o=le(e.results);r.push("",n.section(`Comparison (${o.length})`)),o.length===0&&r.push(` ${n.muted("No comparable skills returned.")}`),o.forEach((d,p)=>{let y=Ot(d)??`Skill ${p+1}`;r.push(`${p+1}. ${y}`);let m=Ma(d);m&&r.push(` ${m}`);let h=Xi(d);h&&r.push(` ${n.label("summary")}: ${i?h.replace(/\s+/gu," ").trim():be(h)}`)});let l=le(e.missing);l.length>0&&(r.push("",n.section(`Missing (${l.length})`)),l.forEach((d,p)=>{let y=a(d,"slug")??a(d,"skillSlug")??Ot(d)??`Entry ${p+1}`,m=a(d,"reason")??a(d,"status");r.push(`${p+1}. ${m?`${y} - ${m}`:y}`)}));let c=ne(e,"guidance")??ve(e.guidance);c.length>0&&r.push("",n.section("Guidance"),...c.slice(0,3).map(d=>` ${n.arrow} ${be(d)}`));let u=Na(o);return u.length>0&&r.push("",n.section("Next"),...u.map(d=>` ${n.arrow} ${d}`)),r.join(`
|
|
791
|
+
`)}function Ma(e){let t=C(e,"securityPosture"),n=a(e,"trust")??a(e,"trustStatus")??a(e,"trustLabel")??(t?a(t,"label"):void 0),i=e.score??e.securityScore??(t?t.securityScore:void 0),r=a(e,"risk")??a(e,"runtimeRisk")??(t?a(t,"runtimeRisk"):void 0);return[["slug",a(e,"slug")??a(e,"skillSlug")],["version",a(e,"version")??a(e,"currentVersion")],["category",a(e,"category")],["type",a(e,"type")??a(e,"skillType")],["trust",n],["score",i],["risk",r]].flatMap(([o,l])=>l==null||l===""?[]:[`${o}: ${H(String(o),l)}`]).join("; ")}function Na(e){let t=[];for(let n of e.slice(0,5)){let i=a(n,"slug")??a(n,"skillSlug");i&&t.push(`skills-layer show ${i}`,`skills-layer trust ${i}`,`skills-layer install ${i}`)}return t}function Oa(e){let t=a(e,"edition"),n=a(e,"baseUrl");return t&&n?`${t} at ${n}`:t??n}function Fa(e){let t=a(e,"state");if(t&&t!=="authenticated")return t==="anonymous"?"not signed in":t;let n=a(e,"email"),i=ne(e,"roles");return n&&i&&i.length>0?`${n} (${i.join(", ")})`:n??a(e,"role")}function Ji(e){let t=[],n=a(e,"recommendedCommand");n&&t.push(n);let i=a(e,"nextStep");return i&&t.push(i),t}function zi(e){return Array.isArray(e.checks)?e.checks.filter(R):[]}function qa(e){return e!==void 0&&e!=="pass"&&e!=="warn"&&e!=="advisory"}function le(e){return Array.isArray(e)?e.filter(R):[]}function ve(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Ka(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 Ga={"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 Da(e){let t=ve(e.capabilities);return{status:"ok",edition:a(e,"edition")??"unknown",summary:"Public product capabilities available on the selected backend.",capabilities:t.map(n=>({name:Ga[n]??lt(n.replace(/^[^.]+\./u,"").replace(/[._-]+/gu," ")),available:!0})),count:t.length}}function Ha(e,t){let n=g(e);if(!n)return;let i=Number(n);return!Number.isInteger(i)||i<=0?k("help optimize-tokens --max-characters must be a positive integer.",t):i<120||i>4e3?k("help optimize-tokens --max-characters must be between 120 and 4000.",t):i}function Ja(e,t,n){let i=W(n),r=C(e,"validation")??e,s=C(r,"parsedSkill")??C(e,"parsedSkill"),o=s?C(s,"frontmatter"):void 0,l=a(e,"skillSlug")??(o?a(o,"name"):void 0),c=r.valid===!0||e.valid===!0,u=xt(r,e,"issues"),d=xt(r,e,"warnings"),p=xt(r,e,"advice"),y=C(r,"stats")??C(e,"stats"),m=[`${i.ok("OK")} Validation complete.`,"",i.section("Bundle")];if(m.push(` ${i.label("Path")}: ${t}`),l&&m.push(` ${i.label("Skill")}: ${l}`),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`),y){let h=y.fileCount??y.files??e.fileCount,w=y.bodyWordCount??y.bodyWords??e.bodyWordCount;m.push("",i.section("File Summary")),h!==void 0&&m.push(` ${i.label("File count")}: ${H("fileCount",h)}`),w!==void 0&&m.push(` ${i.label("Body words")}: ${H("bodyWordCount",w)}`)}return m.push("",...$t("Issues",u,i,"No blocking issues found.")),m.push("",...$t("Warnings",d,i,"No warnings returned.")),m.push("",...$t("Advice",p,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(`
|
|
792
|
+
`)}function xt(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 $t(e,t,n,i){let r=[n.section(`${e} (${t.length})`)];return t.length===0?(r.push(` ${n.muted(i)}`),r):(t.slice(0,O).forEach((s,o)=>{r.push(`${o+1}. ${Wi(s)}`)}),r)}function Wi(e){return R(e)?(a(e,"message")??a(e,"title")??a(e,"code")??a(e,"path")??Me(e))||"Details available with --json":H("",e)}function za(e,t,n){let i=W(n),r=Wa(e),s=Va(e),o=[`${i.ok("OK")} Trigger preview complete.`,"",i.section("Bundle"),` ${i.label("Path")}: ${t}`],l=a(e,"skillSlug")??a(e,"slug");return l&&o.push(` ${i.label("Skill")}: ${l}`),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,O).forEach((c,u)=>{o.push(`${u+1}. ${Ya(c,u)}`)}),o.push("",i.section(`Guidance (${s.length})`)),s.length===0&&o.push(` ${i.muted("No extra trigger guidance returned.")}`),s.slice(0,O).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(`
|
|
793
|
+
`)}function Wa(e){return[...le(e.promptResults),...le(e.results),...le(e.shouldTriggerResults),...le(e.shouldNotTriggerResults),...le(e.paraphraseResults)]}function Va(e){let t=ve(e.guidance),n=le(e.guidance).map(i=>Wi(i));return[...t,...n]}function Ya(e,t){let n=a(e,"prompt")??a(e,"text")??a(e,"input")??`Prompt ${t+1}`,i=Qa(e),r=Za(e),s=Xa(e),o=e.score??e.confidence,l=a(e,"reason")??a(e,"explanation")??a(e,"message");return[`"${be(n)}"`,i?`expected: ${i}`:void 0,r?`actual: ${r}`:void 0,s,o!==void 0?`score: ${H("score",o)}`:void 0,l?`reason: ${be(l)}`:void 0].filter(c=>!!c).join("; ")}function Qa(e){return typeof e.shouldTrigger=="boolean"?e.shouldTrigger?"should trigger":"should not trigger":typeof e.expectedTrigger=="boolean"?e.expectedTrigger?"should trigger":"should not trigger":a(e,"expected")??a(e,"kind")??a(e,"type")}function Za(e){return typeof e.triggered=="boolean"?e.triggered?"triggered":"did not trigger":typeof e.actualTrigger=="boolean"?e.actualTrigger?"triggered":"did not trigger":a(e,"actual")??a(e,"classification")??a(e,"decision")}function Xa(e){return typeof e.passed=="boolean"?e.passed?"pass":"fail":typeof e.pass=="boolean"?e.pass?"pass":"fail":a(e,"status")}function el(e,t,n,i){let r=W(i),s=a(e,"skillSlug")??G(t),o=[`${r.ok("OK")} Created ${n}.`,"",r.section("Local Skill")];o.push(` ${r.label("Path")}: ${n}`),o.push(` ${r.label("Skill")}: ${s}`);let l=a(e,"skillType"),c=a(e,"category");return l&&o.push(` ${r.label("Type")}: ${l}`),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(`
|
|
794
|
+
`)}function tl(e,t,n){let i=C(e,"profile")??e,r=_t(i,"requirementsCurrentlyDue"),s=_t(i,"requirementsPastDue"),o=_t(i,"requirementsPendingVerification"),l=["payouts","Enabled"].join(""),c=i.readyForPayouts??i[l],u=c===!0,d=[`${n.ok("OK")} ${t}`,"",n.section("Payout Profile")];return d.push(` ${n.label("Status")}: ${Ze(a(i,"status"))}`),d.push(` ${n.label("Ready for payouts")}: ${gi(c)}`),d.push(` ${n.label("Account details submitted")}: ${gi(i.detailsSubmitted)}`),d.push(` ${n.label("Currency")}: ${Ze(a(i,"currency")?.toUpperCase())}`),d.push(` ${n.label("Country")}: ${Ze(a(i,"country")?.toUpperCase())}`),d.push(` ${n.label("Minimum withdrawal")}: ${rl(i)}`),d.push(` ${n.label("Updated at")}: ${Ze(a(i,"updatedAt"))}`),d.push("",n.section("Requirements")),d.push(` ${n.label("Currently due")}: ${It(r)}`),d.push(` ${n.label("Past due")}: ${It(s)}`),d.push(` ${n.label("Pending verification")}: ${It(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(`
|
|
795
|
+
`)}function nl(e,t,n){let i=Nt(e),r=an(e,"withdrawableBalanceCents"),s=[`${n.ok("OK")} ${t}`,"",n.section("Earnings Summary")];return s.push(` ${n.label("Gross sales")}: ${q(e,"successfulSalesCents",i)}`),s.push(` ${n.label("Platform fees")}: ${q(e,"platformFeeCents",i)}`),s.push(` ${n.label("Refunds requested")}: ${q(e,"refundRequestedCents",i)}`),s.push(` ${n.label("Refunded")}: ${q(e,"refundedCents",i)}`),s.push(` ${n.label("Estimated available")}: ${q(e,"estimatedAvailableCents",i)}`),s.push(` ${n.label("Withdrawable now")}: ${q(e,"withdrawableBalanceCents",i)}`),s.push(` ${n.label("Held balance")}: ${q(e,"heldBalanceCents",i)}`),s.push(` ${n.label("Refund exposure")}: ${q(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")}: ${q(e,"pendingPayoutCents",i)}`),s.push(` ${n.label("Completed payouts")}: ${q(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(`
|
|
796
|
+
`)}function il(e,t,n){let i=Array.isArray(e.results)?e.results:[],r=Nt(e,i),s=an(e,"withdrawableBalanceCents"),o=[`${n.ok("OK")} ${t}`,"",n.section("Payout History")];return o.push(` ${n.label("Withdrawable now")}: ${q(e,"withdrawableBalanceCents",r)}`),o.push(` ${n.label("Pending payouts")}: ${q(e,"pendingPayoutCents",r)}`),o.push(` ${n.label("Completed payouts")}: ${q(e,"completedPayoutCents",r)}`),o.push("",n.section(`Requests (${i.length})`)),i.length===0?o.push(` ${n.muted("No payout requests yet.")}`):(i.slice(0,O).forEach((l,c)=>{if(!R(l)){o.push(`${c+1}. ${H("",l)}`);return}let u=Nt(l,void 0,r),d=a(l,"payoutId")??a(l,"id")??`Payout ${c+1}`,p=a(l,"status")??"unknown",y=q(l,"amountCents",u),m=a(l,"requestedAt"),h=a(l,"completedAt"),w=a(l,"reason");o.push(`${c+1}. ${d}`),o.push(` ${n.label("Amount")}: ${y}; ${n.label("Status")}: ${p}`),m&&o.push(` ${n.label("Requested")}: ${m}`),h&&o.push(` ${n.label("Completed")}: ${h}`),w&&o.push(` ${n.label("Reason")}: ${w}`)}),i.length>O&&o.push(` ${n.muted(`... ${i.length-O} 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(`
|
|
797
|
+
`)}function Nt(e,t,n="GBP"){let i=a(e,"currency");if(i)return i.toUpperCase();let r=t?.find(R);if(r){let s=a(r,"currency");if(s)return s.toUpperCase()}return n}function an(e,t){return ce(e,t)??0}function di(e,t){return ce(e,t)??0}function q(e,t,n){return`${Vi(an(e,t))} ${n}`}function _t(e,t){return(ne(e,t)??[]).map(n=>n.replace(/[._-]+/gu," "))}function It(e){return e.length>0?e.join(", "):"none"}function gi(e){return e===!0?"yes":e===!1?"no":"unknown"}function Ze(e){return e??"none"}function rl(e){let t=ce(e,"minimumWithdrawalAmountCents"),n=a(e,"currency")?.toUpperCase()??"minor units";return t===void 0?"none":`${Vi(t)} ${n}`}function Vi(e){return(e/100).toFixed(2).replace(/\.00$/u,"").replace(/(\.\d)0$/u,"$1")}function W(e){let t=sl(e);return{ok:n=>t?we(32,n):n,section:n=>t?we(1,we(36,n)):n,label:n=>t?we(1,n):n,muted:n=>t?we(2,n):n,arrow:t?we(36,"->"):"->"}}function sl(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 we(e,t){return`\x1B[${e}m${t}\x1B[0m`}function Yi(e,t){let n=[],i=al(e,t);i.length>0&&n.push(...i);for(let[r,s]of ul(e))if(Array.isArray(s))n.push(...ol(r,s,t));else if(R(s)){let o=Me(s);o&&n.push(` ${t.label(Ft(r))}: ${o}`)}else n.push(` ${t.label(Ft(r))}: ${H(r,s)}`);return n}function ol(e,t,n){let i=dl(e),r=[n.section(`${i} (${t.length})`)];return t.length===0?(r.push(` ${n.muted("No entries.")}`),r):(t.slice(0,O).forEach((s,o)=>{r.push(...Qi(s,o,n))}),t.length>O&&r.push(` ${n.muted(`... ${t.length-O} more`)}`),r)}function Qi(e,t,n){if(!R(e))return[`${t+1}. ${H("",e)}`];let i=Ot(e)??Q(Me(e))??`Item ${t+1}`,r=[`${t+1}. ${i}`],s=Xi(e);s&&r.push(` ${s}`);let o=Me(e);return o&&r.push(` ${o}`),r}function al(e,t){let n=[],i=e.securityScore,r=a(e,"recommendation"),s=C(e,"capabilityProfile"),o=s?a(s,"runtimeRisk"):void 0;return(i!==void 0||r||o)&&(n.push(t.section("Trust")),i!==void 0&&n.push(` ${t.label("Security score")}: ${H("securityScore",i)}`),o&&n.push(` ${t.label("Runtime risk")}: ${o}`),r&&n.push(` ${t.label("Recommendation")}: ${r}`)),n}function ll(e,t,n){let i=W(n),r=a(e,"skillSlug")??t,s=a(e,"runtimeRisk")??(C(e,"capabilityProfile")?a(C(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")}: ${H("securityScore",e.securityScore)}`),s&&o.push(` ${i.label("Runtime risk")}: ${s}`);let l=a(e,"recommendation");l&&o.push(` ${i.label("Recommendation")}: ${l}`),o.push(` ${i.label("Skill")}: ${r}`);let c=a(e,"version");c&&o.push(` ${i.label("Version")}: ${c}`);let u=["semantic","review","no","reviewable","findings"].join("_"),d=ve(e.reviewDegradedReasons).includes(u),p=ve(e.trustBadges).filter(h=>h==="capability-mismatch"),y=ve(e.trustBadges).filter(h=>h!=="capability-mismatch");(d||p.length>0)&&(o.push("",i.section("Creator Notes")),d&&o.push("1. Semantic review was not needed because there were no reviewable findings."),p.forEach((h,w)=>{o.push(`${d?w+2:w+1}. ${h==="capability-mismatch"?"Capability declaration needs review.":h}`)})),y.length>0&&(o.push("",i.section(`Trust badges (${y.length})`)),y.slice(0,O).forEach((h,w)=>o.push(`${w+1}. ${h}`)));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,O).forEach((h,w)=>{o.push(...Qi(h,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(`
|
|
798
|
+
`)}function cl(e,t,n){let r=C(e,"report")??e,s=W(n),o=r.securityScore,l=a(r,"generatedAt")??a(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")}: ${a(r,"skillSlug")??t}`),o!==void 0&&u.push(` ${s.label("Security score")}: ${H("securityScore",o)}`),c&&u.push(` ${s.label("Findings")}: ${c.length}`),l&&u.push(` ${s.label("Generated at")}: ${l}`),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(`
|
|
799
|
+
`)}function ul(e){return Object.entries(e).filter(([t,n])=>Zi(t,n))}function Zi(e,t){let n=e.toLowerCase();return n==="status"||n==="securityscore"||n==="recommendation"||n==="capabilityprofile"||n.includes("apikey")||n.includes("secret")||n.includes("token")||n==="content"?!1:t!==void 0}function Me(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(!Zi(r,e[r]))return[];let o=e[r];return o===void 0?[]:[`${s}: ${H(r,o)}`]}),i=C(e,"securityPosture");if(i){let r=a(i,"label"),s=i.securityScore,o=a(i,"runtimeRisk");r&&n.push(`trust: ${r}`),s!==void 0&&n.push(`score: ${H("securityScore",s)}`),o&&n.push(`risk: ${o}`)}return n.join("; ")}function Xi(e){return a(e,"shortDescription")??a(e,"summary")??a(e,"description")??a(e,"message")}function Ot(e){return a(e,"displayName")??a(e,"name")??a(e,"title")??a(e,"slug")??a(e,"skillSlug")??a(e,"code")??a(e,"id")}function H(e,t){return e==="downloadUrl"?"<hidden; use --json or --output>":typeof t=="string"?be(t):typeof t=="number"||typeof t=="boolean"?String(t):t===null?"none":Array.isArray(t)?`${t.length} item${t.length===1?"":"s"}`:R(t)?Me(t)||"details available with --json":String(t)}function be(e){let t=e.replace(/\s+/gu," ").trim();return t.length>160?`${t.slice(0,157)}...`:t}function dl(e){return lt(Ft(e))}function Ft(e){return e.replace(/([a-z0-9])([A-Z])/gu,"$1 $2").replace(/[_-]+/gu," ").toLowerCase()}function er(e){let t=gl(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 gl(e){let t=a(e,"skillSlug")??a(e,"slug");if(t)return t;let n=e.results;if(Array.isArray(n)){for(let i of n)if(R(i)){let r=a(i,"skillSlug")??a(i,"slug");if(r)return r}}}function R(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function k(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 j(e,t,n,i){let r={status:a(e,"status")??"error",summary:t,why:a(e,"why")??null,nextAction:a(e,"nextAction")??null,nextStep:a(e,"nextStep")??null,data:e,warnings:Array.isArray(e.warnings)?e.warnings:[],links:Array.isArray(e.links)?e.links:[],reasonCode:i??a(e,"reasonCode")??null,handoff:e.handoff??null};return{exitCode:1,stdout:"",stderr:n?JSON.stringify(r,null,2):t}}function ot(e,t){let n=e.details??{};return e.status===401?j({status:"login_required",error:"Login required.",nextAction:"login",nextStep:"Run `skills-layer login` to sign in, then retry this command."},"Login required. Run `skills-layer login` to sign in, then retry this command.",t,"login_required"):k(a(n,"error")??e.message,t)}async function z(e){try{return JSON.parse(await Oe(e,"utf8"))}catch{return null}}async function pl(e,t){let n=await z(e);return n?Bn(n,{env:t.env,platform:t.platform,store:t.credentialStore}):null}async function ln(e,t,n){let i=await Un(t,{env:n.env,platform:n.platform,store:n.credentialStore});await K(e,i)}async function K(e,t){await tr(oe(e)),await Ht(e,`${JSON.stringify(t,null,2)}
|
|
800
|
+
`,{encoding:"utf8",mode:384}),await cn(e,384)}async function tr(e){await Ne(e,{recursive:!0,mode:448}),await cn(e,448)}async function cn(e,t){if(process.platform!=="win32")try{await hi(e,t)}catch{}}async function te(e,t){await Ne(oe(e),{recursive:!0}),await Ht(e,t,"utf8")}async function qt(e,t){await Ne(oe(e),{recursive:!0}),await Ht(e,t)}function ml(e=process.stdin,t=process.stdout,n=zt){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 fl(e=process.stdin,t=process.stdout,n=zt){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 l=e,c=l.isRaw===!0,u="",d=!1,p=m=>{d||(d=!0,l.off("data",y),l.setRawMode(c),l.pause?.(),t.write(`
|
|
801
|
+
`),m())},y=m=>{let h=typeof m=="string"?m:m.toString("utf8");for(let w of h){if(w==="\r"||w===`
|
|
802
|
+
`){p(()=>s(u.trim()));return}if(w===""){p(()=>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),l.resume?.(),l.on("data",y),l.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!==`
|
|
635
803
|
`){let l=[...o].filter(c=>c!=="\r"&&c!==`
|
|
636
|
-
`).length;l>0&&t.write("*".repeat(l))}};try{t.write(
|
|
637
|
-
`),s.trim()}finally{
|
|
638
|
-
`);for(let[x,
|
|
804
|
+
`).length;l>0&&t.write("*".repeat(l))}};try{t.write(i);let s=await r.question("");return t.write(`
|
|
805
|
+
`),s.trim()}finally{r.close()}}}function hl(e=process.stdin,t=process.stdout,n=zt){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((l,c)=>{let u=0,d="",p=0,y=!1,m=s.isRaw===!0,h=()=>{p>0&&t.write(`\x1B[${p}F\x1B[J`),t.write(`${i}
|
|
806
|
+
`);for(let[x,T]of r.entries())t.write(`${yl(x===u)} ${x+1}. ${pi(T)}
|
|
639
807
|
`);t.write(`Choice: ${d}
|
|
640
808
|
`),t.write(`Use up/down arrows, type a number, then press Enter.
|
|
641
|
-
`),
|
|
642
|
-
`),x())},
|
|
643
|
-
`)){if(d){let M=Number.parseInt(d,10)-1;if(Number.isNaN(M)||M<0||M>=
|
|
644
|
-
`);for(let[u,d]of
|
|
645
|
-
`);let l=(await o.question("Choose a number and press enter: ")).trim(),c=Number.parseInt(l,10)-1;if(Number.isNaN(c)||c<0||c>=
|
|
809
|
+
`),p=r.length+3},w=x=>{y||(y=!0,s.off?.("data",P),s.setRawMode?.(m),s.pause?.(),t.write(`
|
|
810
|
+
`),x())},P=x=>{let T=typeof x=="string"?x:x.toString("utf8");if(T.includes("")){w(()=>c(new Error("Interactive selection cancelled.")));return}if(T.includes("\x1B[A")){d="",u=(u-1+r.length)%r.length,h();return}if(T.includes("\x1B[B")){d="",u=(u+1)%r.length,h();return}if(T.includes("\r")||T.includes(`
|
|
811
|
+
`)){if(d){let M=Number.parseInt(d,10)-1;if(Number.isNaN(M)||M<0||M>=r.length){d="",t.write("\x07"),h();return}u=M}w(()=>l(r[u]?.value??r[0].value));return}if(T.includes("\b")||T.includes("\x7F")){d=d.slice(0,-1);let M=Number.parseInt(d,10)-1;!Number.isNaN(M)&&M>=0&&M<r.length&&(u=M),h();return}let Ge=[...T].filter(M=>/[0-9]/u.test(M));if(Ge.length>0){d=`${d}${Ge.join("")}`;let M=Number.parseInt(d,10)-1;!Number.isNaN(M)&&M>=0&&M<r.length&&(u=M),h()}};h(),s.resume?.(),s.on("data",P),s.setRawMode(!0)});let o=n({input:e,output:t});try{t.write(`${i}
|
|
812
|
+
`);for(let[u,d]of r.entries())t.write(`${u+1}. ${pi(d)}
|
|
813
|
+
`);let l=(await o.question("Choose a number and press enter: ")).trim(),c=Number.parseInt(l,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 yl(e){return e?"\x1B[36m>\x1B[0m":" "}function pi(e){return e.description?`${e.label} (${e.description})`:e.label}function kl(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=mi(n.file,n.args,{detached:!0,stdio:"ignore"});r.on("error",()=>i(!1)),r.unref(),i(!0)}catch{i(!1)}})}}function F(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 I(n)}function wl(e){let t=e.results;return Array.isArray(t)?t.flatMap(n=>{if(!n||typeof n!="object"||Array.isArray(n))return[];let i=a(n,"slug")??a(n,"skillSlug");return i?[i]:[]}):[]}function vl(e){let t=g(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 I(e){let t={};for(let[n,i]of Object.entries(e))i!==void 0&&(t[n]=i);return t}function at(e,t){let n=g(e);return n?un(n,t):void 0}function un(e,t){try{return JSON.parse(e)}catch{throw new Error(`--${t} must be valid JSON.`)}}function J(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 Kt(e){let t=J(e);for(let n of["role","roles","verifiedAt","expiresAt","userId","tenantId","linkedAccount","linkedIdentity","createdUser"])delete t[n];return t}function v(e,t){let n=g(e);if(!n)throw new Error(t);return n}function g(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Q(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function a(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function ce(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 C(e,t){let n=e[t];return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function ne(e,t){let n=e[t];return Array.isArray(n)?n.filter(i=>typeof i=="string"):void 0}function bl(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 B(e,t,n){let i=g(n);i&&e.set(t,i)}function ie(e){let t=e.toString();return t?`?${t}`:""}function ee(e){return e.replace(/\/+$/u,"")}function Pe(e){if(ee(e)===Vt)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 Pl(e){return e.includes("/")||e.startsWith(".")||/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e)}function ae(e,t){return ki(e,t)}function lt(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var Sl={github:"GitHub",gitlab:"GitLab",google:"Google",microsoft:"Microsoft"};function Cl(e){return Sl[e.toLowerCase()]??lt(e)}function ue(e){return e instanceof Error?e.message:String(e)}export{mc as executePublicCli};
|