skills-layer 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +171 -6
- package/README.md +6 -3
- package/package.json +10 -3
- package/public/skills-layer-public.mjs +185 -82
- package/tests/public-cli-package.test.mjs +40 -2
|
@@ -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 qi}from"node:child_process";import{createHash as on}from"node:crypto";import{access as Ki,appendFile as zs,chmod as Gi,mkdir as Ke,readdir as Vi,readFile as Ge,rm as an,stat as Ws,writeFile as ln}from"node:fs/promises";import{basename as G,dirname as ee,join as L,posix as cn,relative as Me,resolve as Di,win32 as xe}from"node:path";import{createInterface as un}from"node:readline/promises";import{spawn as Bn}from"node:child_process";import{createHash as qr}from"node:crypto";import{chmod as Kr,mkdir as Ye,readFile as Nn,rm as kt,writeFile as ve}from"node:fs/promises";import{dirname as je,posix as Gr,win32 as Vr}from"node:path";import{posix as Nr,win32 as Mr}from"node:path";var we=["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"],In=[I("codex","Codex",".codex",{capabilities:U({allowedTools:!0})}),I("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:U({allowedTools:!0,hooks:!0,forkedContext:!0})}),I("cursor","Cursor",".cursor",{capabilities:U({allowedTools:!0})}),I("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:U({allowedTools:!0})}),le("amp","Amp",".config/agents",{capabilities:U({allowedTools:!0})}),le("kimi-cli","Kimi Code CLI",".config/agents"),le("replit","Replit",".config/agents"),le("universal","Universal",".config/agents"),le("antigravity","Antigravity",".gemini/antigravity",{capabilities:U({allowedTools:!0}),detectGlobal:!0}),I("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"]}},le("cline","Cline",".agents",{capabilities:U({allowedTools:!0,hooks:!0})}),le("warp","Warp",".agents"),I("codebuddy","CodeBuddy",".codebuddy",{capabilities:U({allowedTools:!0})}),I("command-code","Command Code",".commandcode",{capabilities:U({allowedTools:!0})}),I("continue","Continue",".continue"),I("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),I("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),le("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),I("droid","Droid",".factory"),le("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),le("github-copilot","GitHub Copilot",".copilot",{capabilities:U({allowedTools:!0}),detectGlobal:!0}),I("goose","Goose",".goose",{globalRootRelativePath:".config/goose"}),I("junie","Junie",".junie"),I("iflow-cli","iFlow CLI",".iflow"),I("kilo","Kilo Code",".kilocode"),I("kiro-cli","Kiro CLI",".kiro"),I("kode","Kode",".kode"),I("mcpjam","MCPJam",".mcpjam"),I("mistral-vibe","Mistral Vibe",".vibe"),I("mux","Mux",".mux"),I("openhands","OpenHands",".openhands",{capabilities:U({allowedTools:!0})}),I("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:U({allowedTools:!0})}),I("qoder","Qoder",".qoder",{capabilities:U({allowedTools:!0})}),I("qwen-code","Qwen Code",".qwen"),I("roo","Roo Code",".roo",{capabilities:U({allowedTools:!0})}),I("trae","Trae",".trae",{detectProject:!1}),I("trae-cn","Trae CN",".trae",{globalRootRelativePath:".trae-cn",detectProject:!1}),I("windsurf","Windsurf",".windsurf",{globalRootRelativePath:".codeium/windsurf"}),I("zencoder","Zencoder",".zencoder",{capabilities:U({allowedTools:!0})}),I("neovate","Neovate",".neovate",{capabilities:U({allowedTools:!0})}),I("pochi","Pochi",".pochi"),I("adal","AdaL",".adal")];function ge(e=process.env,t=process.platform,n=process.cwd()){let i=Ln(t),r=An(e,t);return In.map(s=>{let o=We(e[s.envVar]),l=r&&s.targets.globalRootRelativePath?$e(i,r,s.targets.globalRootRelativePath):null,c=r&&s.targets.globalSkillsRelativePath?$e(i,r,s.targets.globalSkillsRelativePath):null,u=s.targets.projectRootRelativePath?$e(i,n,s.targets.projectRootRelativePath):null,d=o??l;return{id:s.id,displayName:s.displayName,envVar:s.envVar,capabilities:s.capabilities,detectionSources:[],targets:{projectRoot:u,projectSkillsPath:$e(i,n,s.targets.projectSkillsRelativePath),globalRoot:d,globalSkillsPath:o?i.join(o,"skills"):c}}})}async function jn(e={}){let t=e.env??process.env,n=e.platform??process.platform,i=e.cwd??process.cwd(),r=Ln(n),s=An(t,n),o=ge(t,n,i),l=e.pathExists??(async()=>!1);return(await Promise.all(o.map(async c=>{let u=Fr(c.id),d=[],g=We(t[c.envVar]);return(g&&await l(g)||g&&await l(r.join(g,"skills")))&&d.push("override"),u.detection.projectProbeRelativePaths.length>0&&await _n({basePath:i,relativePaths:u.detection.projectProbeRelativePaths,pathApi:r,pathExists:l})&&d.push("project"),s&&u.detection.globalProbeRelativePaths.length>0&&await _n({basePath:s,relativePaths:u.detection.globalProbeRelativePaths,pathApi:r,pathExists:l})&&d.push("global"),d.length===0?null:{...c,detectionSources:Or(d)}}))).flatMap(c=>c?[c]:[])}function An(e,t){return t==="win32"?We(e.USERPROFILE,e.HOME):We(e.HOME)}function Ln(e){return e==="win32"?Mr:Nr}function We(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Or(e){return[...new Set(e)]}async function _n(e){for(let t of e.relativePaths)if(await e.pathExists($e(e.pathApi,e.basePath,t)))return!0;return!1}function $e(e,t,n){return e.join(t,...n.split("/"))}function I(e,t,n,i={}){let r=i.globalRootRelativePath??n,s=i.detectProject??!0;return{id:e,displayName:t,envVar:i.envVar??En(e),capabilities:i.capabilities??U(),targets:{projectRootRelativePath:n,projectSkillsRelativePath:`${n}/skills`,globalRootRelativePath:r,globalSkillsRelativePath:`${r}/skills`},detection:{projectProbeRelativePaths:s?[n,`${n}/skills`]:[],globalProbeRelativePaths:[r,`${r}/skills`]}}}function le(e,t,n,i={}){let r=i.detectGlobal??!1;return{id:e,displayName:t,envVar:i.envVar??En(e),capabilities:i.capabilities??U(),targets:{projectRootRelativePath:".agents",projectSkillsRelativePath:".agents/skills",globalRootRelativePath:n,globalSkillsRelativePath:`${n}/skills`},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:r?[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 En(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function Fr(e){return In.find(t=>t.id===e)}var fe="skills-layer",Dr="2025-06-18",Hr=["mcp","skills-layer-mcp-proxy.mjs"],zr=["mcp","skills-layer-mcp-broker.mjs"],Wr=["mcp","skills-layer-mcp-broker.sock"],Jr={codex:{tier:"tier_1",configKind:"codex_toml",resolveConfigPath(e,t,n){let i=vt(n);return i.join(e.targets.globalRoot??i.join(as({},n)??t,".codex"),"config.toml")}},cursor:_e(".cursor/mcp.json"),"claude-code":_e(".mcp.json"),cline:_e(".cline/mcp.json"),"gemini-cli":_e(".gemini/settings.json"),windsurf:_e(".windsurf/mcp.json")},Yr=new Set(["universal"]);function Le(e){let t=ge(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??os(e.env,i),o=e.mcpConfigPath??Ie(i,s,"mcp.json"),l=Ie(i,s,...Hr),c=Ie(i,s,...zr),u=Ie(i,s,...Wr),d=e.nodePath??process.execPath,g=Mn({mcpConfigPath:o}),f=On({mcpConfigPath:o,socketPath:u}),m=be(g),y=be(f),w=we.map(P=>{let _=n.get(P),N=Jr[P];if(N){let ze=N.resolveConfigPath(_,r,i);return Zr({agentId:P,displayName:_.displayName,configPath:ze,configKind:N.configKind,bridgePath:l,brokerPath:c,brokerSocketPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:m,brokerChecksum:y})}return Yr.has(P)?Tn({agentId:P,displayName:_.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 ${_.displayName} with \`skills-layer install <skill> --agent ${P}\`.`,"MCP auto-install is not claimed for this agent yet."]}):Tn({agentId:P,displayName:_.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 ${fe}.`,`Command: ${d}`,`Args: ${l}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{status:"mcp_registration_plan",serverName:fe,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:y,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 wt(e){let t=Le(e),n=ls(e.clientId),i=t.targets.find(w=>w.agentId===n),r=e.mcpConfig??await Ze(t.mcpConfigPath,{allowMissing:!0});if(!r)return Un({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 Ae(t.bridgePath),o=s!==null,l=s!==null&&be(s)===t.bridgeChecksum,c=await Ae(t.brokerPath),u=c!==null,d=c!==null&&be(c)===t.brokerChecksum,g=cs(r,i.agentId),f=ne(g,"token"),m=ne(g,"tokenRef"),y=i.status==="automatic"?await ns(i,f):{configured:!1,rawTokenLeaked:!1};return Un({plan:t,target:i,mcpConfig:r,tokenConfig:g,tokenPresent:!!f,tokenRefPresent:!!m,bridgeExists:o,checksumMatches:l,brokerExists:u,brokerChecksumMatches:d,targetConfigured:y.configured,rawTokenLeaked:y.rawTokenLeaked})}function Mn(e){return`#!/usr/bin/env node
|
|
3
|
+
import{spawn as Wi}from"node:child_process";import{createHash as cn}from"node:crypto";import{access as Ji,appendFile as io,chmod as Yi,mkdir as Ke,readdir as Zi,readFile as Ge,rm as un,stat as ro,writeFile as dn}from"node:fs/promises";import{basename as K,dirname as ee,join as L,posix as pn,relative as Fe,resolve as Qi,win32 as _e}from"node:path";import{createInterface as gn}from"node:readline/promises";import{spawn as qn}from"node:child_process";import{createHash as Zr}from"node:crypto";import{chmod as Qr,mkdir as Je,readFile as Kn,rm as St,writeFile as ve}from"node:fs/promises";import{dirname as Ae,posix as Xr,win32 as es}from"node:path";import{posix as zr,win32 as Wr}from"node:path";var be=["codex","claude-code","cursor","opencode","amp","kimi-cli","replit","universal","antigravity","augment","openclaw","cline","warp","codebuddy","command-code","continue","cortex","crush","deepagents","droid","gemini-cli","github-copilot","goose","junie","iflow-cli","kilo","kiro-cli","kode","mcpjam","mistral-vibe","mux","openhands","pi","qoder","qwen-code","roo","trae","trae-cn","windsurf","zencoder","neovate","pochi","adal"],Un=[j("codex","Codex",".codex",{capabilities:B({allowedTools:!0})}),j("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:B({allowedTools:!0,hooks:!0,forkedContext:!0})}),j("cursor","Cursor",".cursor",{capabilities:B({allowedTools:!0})}),j("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:B({allowedTools:!0})}),ce("amp","Amp",".config/agents",{capabilities:B({allowedTools:!0})}),ce("kimi-cli","Kimi Code CLI",".config/agents"),ce("replit","Replit",".config/agents"),ce("universal","Universal",".config/agents"),ce("antigravity","Antigravity",".gemini/antigravity",{capabilities:B({allowedTools:!0}),detectGlobal:!0}),j("augment","Augment",".augment"),{id:"openclaw",displayName:"OpenClaw",envVar:"OPENCLAW_HOME",capabilities:B({allowedTools:!0}),targets:{projectRootRelativePath:null,projectSkillsRelativePath:"skills",globalRootRelativePath:".openclaw",globalSkillsRelativePath:".openclaw/skills"},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:[".openclaw",".openclaw/skills"]}},ce("cline","Cline",".agents",{capabilities:B({allowedTools:!0,hooks:!0})}),ce("warp","Warp",".agents"),j("codebuddy","CodeBuddy",".codebuddy",{capabilities:B({allowedTools:!0})}),j("command-code","Command Code",".commandcode",{capabilities:B({allowedTools:!0})}),j("continue","Continue",".continue"),j("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),j("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),ce("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),j("droid","Droid",".factory"),ce("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),ce("github-copilot","GitHub Copilot",".copilot",{capabilities:B({allowedTools:!0}),detectGlobal:!0}),j("goose","Goose",".goose",{globalRootRelativePath:".config/goose"}),j("junie","Junie",".junie"),j("iflow-cli","iFlow CLI",".iflow"),j("kilo","Kilo Code",".kilocode"),j("kiro-cli","Kiro CLI",".kiro"),j("kode","Kode",".kode"),j("mcpjam","MCPJam",".mcpjam"),j("mistral-vibe","Mistral Vibe",".vibe"),j("mux","Mux",".mux"),j("openhands","OpenHands",".openhands",{capabilities:B({allowedTools:!0})}),j("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:B({allowedTools:!0})}),j("qoder","Qoder",".qoder",{capabilities:B({allowedTools:!0})}),j("qwen-code","Qwen Code",".qwen"),j("roo","Roo Code",".roo",{capabilities:B({allowedTools:!0})}),j("trae","Trae",".trae",{detectProject:!1}),j("trae-cn","Trae CN",".trae",{globalRootRelativePath:".trae-cn",detectProject:!1}),j("windsurf","Windsurf",".windsurf",{globalRootRelativePath:".codeium/windsurf"}),j("zencoder","Zencoder",".zencoder",{capabilities:B({allowedTools:!0})}),j("neovate","Neovate",".neovate",{capabilities:B({allowedTools:!0})}),j("pochi","Pochi",".pochi"),j("adal","AdaL",".adal")];function me(e=process.env,t=process.platform,n=process.cwd()){let i=Nn(t),r=Bn(e,t);return Un.map(s=>{let o=ze(e[s.envVar]),a=r&&s.targets.globalRootRelativePath?$e(i,r,s.targets.globalRootRelativePath):null,c=r&&s.targets.globalSkillsRelativePath?$e(i,r,s.targets.globalSkillsRelativePath):null,u=s.targets.projectRootRelativePath?$e(i,n,s.targets.projectRootRelativePath):null,d=o??a;return{id:s.id,displayName:s.displayName,envVar:s.envVar,capabilities:s.capabilities,detectionSources:[],targets:{projectRoot:u,projectSkillsPath:$e(i,n,s.targets.projectSkillsRelativePath),globalRoot:d,globalSkillsPath:o?i.join(o,"skills"):c}}})}async function Tn(e={}){let t=e.env??process.env,n=e.platform??process.platform,i=e.cwd??process.cwd(),r=Nn(n),s=Bn(t,n),o=me(t,n,i),a=e.pathExists??(async()=>!1);return(await Promise.all(o.map(async c=>{let u=Yr(c.id),d=[],g=ze(t[c.envVar]);return(g&&await a(g)||g&&await a(r.join(g,"skills")))&&d.push("override"),u.detection.projectProbeRelativePaths.length>0&&await En({basePath:i,relativePaths:u.detection.projectProbeRelativePaths,pathApi:r,pathExists:a})&&d.push("project"),s&&u.detection.globalProbeRelativePaths.length>0&&await En({basePath:s,relativePaths:u.detection.globalProbeRelativePaths,pathApi:r,pathExists:a})&&d.push("global"),d.length===0?null:{...c,detectionSources:Jr(d)}}))).flatMap(c=>c?[c]:[])}function Bn(e,t){return t==="win32"?ze(e.USERPROFILE,e.HOME):ze(e.HOME)}function Nn(e){return e==="win32"?Wr:zr}function ze(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Jr(e){return[...new Set(e)]}async function En(e){for(let t of e.relativePaths)if(await e.pathExists($e(e.pathApi,e.basePath,t)))return!0;return!1}function $e(e,t,n){return e.join(t,...n.split("/"))}function j(e,t,n,i={}){let r=i.globalRootRelativePath??n,s=i.detectProject??!0;return{id:e,displayName:t,envVar:i.envVar??Mn(e),capabilities:i.capabilities??B(),targets:{projectRootRelativePath:n,projectSkillsRelativePath:`${n}/skills`,globalRootRelativePath:r,globalSkillsRelativePath:`${r}/skills`},detection:{projectProbeRelativePaths:s?[n,`${n}/skills`]:[],globalProbeRelativePaths:[r,`${r}/skills`]}}}function ce(e,t,n,i={}){let r=i.detectGlobal??!1;return{id:e,displayName:t,envVar:i.envVar??Mn(e),capabilities:i.capabilities??B(),targets:{projectRootRelativePath:".agents",projectSkillsRelativePath:".agents/skills",globalRootRelativePath:n,globalSkillsRelativePath:`${n}/skills`},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:r?[n,`${n}/skills`]:[]}}}function B(e={}){let t=["basic_skills"];return e.allowedTools&&t.push("allowed_tools"),e.hooks&&t.push("hooks"),e.forkedContext&&t.push("forked_context"),t.push("local_install"),t}function Mn(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function Yr(e){return Un.find(t=>t.id===e)}var he="skills-layer",ts="2025-06-18",ns=["mcp","skills-layer-mcp-proxy.mjs"],is=["mcp","skills-layer-mcp-broker.mjs"],rs=["mcp","skills-layer-mcp-broker.sock"],ss={codex:{tier:"tier_1",configKind:"codex_toml",resolveConfigPath(e,t,n){let i=Ct(n);return i.join(e.targets.globalRoot??i.join(ys({},n)??t,".codex"),"config.toml")}},cursor:Ie(".cursor/mcp.json"),"claude-code":Ie(".mcp.json"),cline:Ie(".cline/mcp.json"),"gemini-cli":Ie(".gemini/settings.json"),windsurf:Ie(".windsurf/mcp.json")},os=new Set(["universal"]);function Ee(e){let t=me(e.env,e.platform,e.cwd),n=new Map(t.map(C=>[C.id,C])),i=e.platform??process.platform,r=e.cwd??process.cwd(),s=e.stateDir??hs(e.env,i),o=e.mcpConfigPath??je(i,s,"mcp.json"),a=je(i,s,...ns),c=je(i,s,...is),u=je(i,s,...rs),d=e.nodePath??process.execPath,g=Gn({mcpConfigPath:o}),f=Vn({mcpConfigPath:o,socketPath:u}),m=Se(g),k=Se(f),w=be.map(C=>{let x=n.get(C),E=ss[C];if(E){let le=E.resolveConfigPath(x,r,i);return as({agentId:C,displayName:x.displayName,configPath:le,configKind:E.configKind,bridgePath:a,brokerPath:c,brokerSocketPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:m,brokerChecksum:k})}return os.has(C)?On({agentId:C,displayName:x.displayName,tier:"tier_3",status:"skills_only",verification:"skills_only",reason:"This agent is currently supported through Skills Layer skill files, not MCP auto-install.",instructions:[`Install skills for ${x.displayName} with \`skills-layer install <skill> --agent ${C}\`.`,"MCP auto-install is not claimed for this agent yet."]}):On({agentId:C,displayName:x.displayName,tier:"tier_2",status:"manual_handoff",verification:"manual",reason:"MCP support or the safe writable config shape has not been verified yet.",instructions:[`Add a local stdio MCP server named ${he}.`,`Command: ${d}`,`Args: ${a}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{status:"mcp_registration_plan",serverName:he,mcpUrl:e.mcpUrl,bearerTokenEnvVar:e.bearerTokenEnvVar,clientId:e.clientId,environment:e.environment,generatedAt:e.now,bridgePath:a,brokerPath:c,brokerSocketPath:u,nodePath:d,mcpConfigPath:o,bridgeChecksum:m,brokerChecksum:k,automaticCount:w.filter(C=>C.status==="automatic").length,manualCount:w.filter(C=>C.status==="manual_handoff").length,skillsOnlyCount:w.filter(C=>C.status==="skills_only").length,unsupportedCount:w.filter(C=>C.status==="unsupported").length,targets:w}}async function Pt(e){let t=Ee(e),n=ks(e.clientId),i=t.targets.find(w=>w.agentId===n),r=e.mcpConfig??await Ye(t.mcpConfigPath,{allowMissing:!0});if(!r)return Fn({plan:t,target:i,mcpConfig:null,tokenConfig:null,tokenPresent:!1,tokenRefPresent:!1,bridgeExists:!1,checksumMatches:!1,brokerExists:!1,brokerChecksumMatches:!1,targetConfigured:!1,rawTokenLeaked:!1});let s=await Le(t.bridgePath),o=s!==null,a=s!==null&&Se(s)===t.bridgeChecksum,c=await Le(t.brokerPath),u=c!==null,d=c!==null&&Se(c)===t.brokerChecksum,g=ws(r,i.agentId),f=ne(g,"token"),m=ne(g,"tokenRef"),k=i.status==="automatic"?await ps(i,f):{configured:!1,rawTokenLeaked:!1};return Fn({plan:t,target:i,mcpConfig:r,tokenConfig:g,tokenPresent:!!f,tokenRefPresent:!!m,bridgeExists:o,checksumMatches:a,brokerExists:u,brokerChecksumMatches:d,targetConfigured:k.configured,rawTokenLeaked:k.rawTokenLeaked})}function Gn(e){return`#!/usr/bin/env node
|
|
4
4
|
import { createConnection } from "node:net";
|
|
5
5
|
import { createInterface } from "node:readline";
|
|
6
6
|
import { readFile } from "node:fs/promises";
|
|
7
7
|
|
|
8
8
|
const CONFIG_PATH = ${JSON.stringify(e.mcpConfigPath)};
|
|
9
|
-
const MCP_PROTOCOL_VERSION = ${JSON.stringify(
|
|
9
|
+
const MCP_PROTOCOL_VERSION = ${JSON.stringify(ts)};
|
|
10
10
|
|
|
11
11
|
function writeMessage(message) {
|
|
12
12
|
process.stdout.write(JSON.stringify(message) + "\\n");
|
|
@@ -148,7 +148,7 @@ for await (const line of rl) {
|
|
|
148
148
|
writeMessage(errorResponse(null, -32603, error instanceof Error ? error.message : "Skills Layer MCP bridge failed."));
|
|
149
149
|
}
|
|
150
150
|
}
|
|
151
|
-
`}function
|
|
151
|
+
`}function Vn(e){return`#!/usr/bin/env node
|
|
152
152
|
import { execFile } from "node:child_process";
|
|
153
153
|
import { createServer } from "node:net";
|
|
154
154
|
import { chmod, readFile, rm } from "node:fs/promises";
|
|
@@ -244,15 +244,15 @@ server.listen(SOCKET_PATH, async () => {
|
|
|
244
244
|
// Some platforms do not support chmod on sockets.
|
|
245
245
|
}
|
|
246
246
|
});
|
|
247
|
-
`}async function
|
|
248
|
-
`);let c=await Promise.race([s,
|
|
249
|
-
`,"utf8")}async function
|
|
250
|
-
`,"utf8")}async function
|
|
251
|
-
`),i=`${
|
|
252
|
-
|
|
253
|
-
`:""}${n}`;await
|
|
254
|
-
`).trimEnd()}function
|
|
255
|
-
`);r>=0&&t({ok:!0,line:n.slice(0,r)})}),e.on("error",i=>{t({ok:!1,message:i instanceof Error?i.message:"MCP bridge stdout failed."})}),e.on("end",()=>{t({ok:!1,message:"MCP bridge exited before returning a response."})})}):Promise.resolve({ok:!1,message:"MCP bridge stdout was not available."})}function
|
|
247
|
+
`}async function Dn(e){let t=e.requestId??1,n=e.timeoutMs??5e3,i=qn(e.nodePath,[e.bridgePath],{stdio:["pipe","pipe","pipe"]}),r="",s=fs(i.stdout);i.stderr.on("data",u=>{r+=String(u)});let o,a=new Promise(u=>{o=setTimeout(()=>u("timeout"),n)});i.stdin.write(`${JSON.stringify({jsonrpc:"2.0",id:t,method:"tools/list",params:{}})}
|
|
248
|
+
`);let c=await Promise.race([s,a]);if(clearTimeout(o),i.kill(),c==="timeout")return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!1,toolCount:null,reasonCode:"probe_timeout",message:"MCP bridge did not respond before the verification timeout."};if(!c.ok)return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!1,toolCount:null,reasonCode:"probe_failed",message:r.trim()?"MCP bridge failed before returning a response.":c.message};try{let u=JSON.parse(c.line);if(Q(u)&&Q(u.error))return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!0,toolCount:null,reasonCode:"remote_mcp_error",message:ne(u.error,"message")??"Skills Layer MCP returned an error."};let d=Q(u)&&Q(u.result)&&Array.isArray(u.result.tools)?u.result.tools:null;return{status:"ok",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!0,toolCount:d?d.length:null,reasonCode:null,message:d?`MCP bridge responded with ${d.length} tool${d.length===1?"":"s"}.`:"MCP bridge responded."}}catch{return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!0,toolCount:null,reasonCode:"invalid_probe_response",message:"MCP bridge returned a response that was not valid JSON."}}}function Fn(e){let t=e.target.status==="automatic",n=e.tokenRefPresent&&!e.tokenPresent,i=!n||e.brokerExists&&e.brokerChecksumMatches,r=(e.tokenPresent||e.tokenRefPresent)&&e.bridgeExists&&e.checksumMatches&&i&&t&&e.targetConfigured&&!e.rawTokenLeaked,s=r?"mcp_configured":e.mcpConfig?"mcp_needs_repair":"mcp_not_configured",o=`skills-layer mcp verify --client ${e.target.agentId}`;return{status:s,configured:r,clientId:e.target.agentId,environment:ne(e.tokenConfig,"environment")??ne(e.mcpConfig,"environment")??e.plan.environment,baseUrl:ne(e.mcpConfig,"baseUrl"),mcpUrl:ne(e.mcpConfig,"mcpUrl"),tokenPrefix:ne(e.tokenConfig,"tokenPrefix")??ne(e.mcpConfig,"tokenPrefix"),scopes:Array.isArray(e.tokenConfig?.scopes)?e.tokenConfig.scopes:Array.isArray(e.mcpConfig?.scopes)?e.mcpConfig.scopes:[],configuredClients:bs(e.mcpConfig),tokenPresent:e.tokenPresent||e.tokenRefPresent,tokenStorage:ne(e.tokenConfig,"credentialStorage")==="macos_keychain"?"macos_keychain":e.tokenPresent?"local_file_locked":"unknown",bridge:{path:e.plan.bridgePath,exists:e.bridgeExists,checksumMatches:e.checksumMatches},broker:{path:e.plan.brokerPath,socketPath:e.plan.brokerSocketPath,required:n,exists:e.brokerExists,checksumMatches:e.brokerChecksumMatches},target:{agentId:e.target.agentId,displayName:e.target.displayName,tier:e.target.tier,status:e.target.status,configPath:e.target.configPath,configured:e.targetConfigured,rawTokenLeaked:e.rawTokenLeaked,reason:e.target.reason,restartRequired:e.target.restartRequired,instructions:e.target.instructions},liveProbe:{status:"not_run",method:"tools/list",reasonCode:"use_mcp_verify",message:`Live MCP tools/list was not run by status. Run \`${o}\` to verify remote MCP reachability through the local bridge.`,nextCommand:o},nextCommand:r?null:`skills-layer mcp repair --client ${e.target.agentId}`}}function as(e){return{agentId:e.agentId,displayName:e.displayName,tier:"tier_1",status:"automatic",serverName:he,configPath:e.configPath,restartRequired:!0,verification:"bridge_config_written",transport:"stdio_bridge",bridgePath:e.bridgePath,nodePath:e.nodePath,configKind:e.configKind,reason:"MCP support and a safe local config shape are known.",instructions:[`Skills Layer will install the local MCP bridge at ${e.bridgePath}.`,`Skills Layer will update ${e.configPath} to launch the bridge with ${e.nodePath}.`,"The raw MCP token stays in Skills Layer local storage and is not written to the agent config.","Open a fresh agent session or restart the agent to load the MCP server."],apply:async()=>{let t=await ls({bridgePath:e.bridgePath,brokerPath:e.brokerPath,brokerSocketPath:e.brokerSocketPath,mcpConfigPath:e.mcpConfigPath,nodePath:e.nodePath});return await us({configPath:e.configPath,configKind:e.configKind,bridgePath:e.bridgePath,nodePath:e.nodePath,agentId:e.agentId}),t},disconnect:async()=>{await ds({configPath:e.configPath,configKind:e.configKind})}}}function On(e){return{agentId:e.agentId,displayName:e.displayName,tier:e.tier,status:e.status,serverName:he,configPath:null,restartRequired:!0,verification:e.verification,transport:"manual",bridgePath:null,nodePath:null,configKind:null,reason:e.reason,instructions:e.instructions}}async function ls(e){let t=Gn({mcpConfigPath:e.mcpConfigPath}),n=Vn({mcpConfigPath:e.mcpConfigPath,socketPath:e.brokerSocketPath});return await Je(Ae(e.bridgePath),{recursive:!0}),await ve(e.bridgePath,t,"utf8"),await ve(e.brokerPath,n,"utf8"),await vt(Ae(e.bridgePath),448),await vt(e.bridgePath,448),await vt(e.brokerPath,448),cs({nodePath:e.nodePath,brokerPath:e.brokerPath}),{bridgePath:e.bridgePath,brokerPath:e.brokerPath,brokerSocketPath:e.brokerSocketPath,mcpConfigPath:e.mcpConfigPath,checksum:Se(t),brokerChecksum:Se(n),nodePath:e.nodePath}}function cs(e){if(!(process.env.VITEST==="true"||process.env.SKILLS_LAYER_MCP_BROKER_AUTOSTART==="disabled"))try{qn(e.nodePath,[e.brokerPath],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function us(e){if(e.configKind==="codex_toml"){await ms(e);return}await gs(e)}async function ds(e){if(e.configKind==="codex_toml"){let i=await Le(e.configPath);if(i===null)return;await ve(e.configPath,Hn(i),"utf8");return}let t=await Ye(e.configPath,{allowMissing:!0});if(!t||!Q(t.mcpServers))return;let n={...t.mcpServers};delete n[he],await Je(Ae(e.configPath),{recursive:!0}),await ve(e.configPath,`${JSON.stringify({...t,mcpServers:n},null,2)}
|
|
249
|
+
`,"utf8")}async function ps(e,t){if(!e.configPath||!e.configKind||!e.bridgePath||!e.nodePath)return{configured:!1,rawTokenLeaked:!1};if(e.configKind==="codex_toml"){let s=await Le(e.configPath);return s===null?{configured:!1,rawTokenLeaked:!1}:{configured:s.includes("[mcp_servers.skills-layer]")&&s.includes(`command = ${JSON.stringify(e.nodePath)}`)&&(s.includes(`args = [${JSON.stringify(e.bridgePath)}, "--client", ${JSON.stringify(e.agentId)}]`)||s.includes(`args = [${JSON.stringify(e.bridgePath)}]`)),rawTokenLeaked:!!(t&&s.includes(t))}}let n=await Ye(e.configPath,{allowMissing:!0}),i=Q(n?.mcpServers)?n.mcpServers[he]:void 0;return{configured:Q(i)&&i.command===e.nodePath&&Array.isArray(i.args)&&i.args[0]===e.bridgePath&&(i.args.length===1||i.args[1]==="--client"&&i.args[2]===e.agentId),rawTokenLeaked:!!(t&&JSON.stringify(n??{}).includes(t))}}async function gs(e){let t=await Ye(e.configPath,{allowMissing:!0})??{},n=Q(t.mcpServers)?{...t.mcpServers}:{};n[he]={command:e.nodePath,args:[e.bridgePath,"--client",e.agentId]},await Je(Ae(e.configPath),{recursive:!0}),await ve(e.configPath,`${JSON.stringify({...t,mcpServers:n},null,2)}
|
|
250
|
+
`,"utf8")}async function ms(e){let t=await Le(e.configPath)??"",n=["[mcp_servers.skills-layer]",`command = ${JSON.stringify(e.nodePath)}`,`args = [${JSON.stringify(e.bridgePath)}, "--client", ${JSON.stringify(e.agentId)}]`,""].join(`
|
|
251
|
+
`),i=`${Hn(t).trimEnd()}${t.trim().length>0?`
|
|
252
|
+
|
|
253
|
+
`:""}${n}`;await Je(Ae(e.configPath),{recursive:!0}),await ve(e.configPath,i,"utf8")}function Hn(e){let t=e.split(/\r?\n/u),n=[],i=!1;for(let r of t){if(r.trim()==="[mcp_servers.skills-layer]"){i=!0;continue}i&&/^\s*\[.+\]\s*$/u.test(r)&&(i=!1),i||n.push(r)}return n.join(`
|
|
254
|
+
`).trimEnd()}function Ie(e){return{tier:"tier_1",configKind:"json_mcp_servers",resolveConfigPath(t,n,i){return je(i,n,...e.split("/"))}}}async function Ye(e,t){try{let n=JSON.parse(await Kn(e,"utf8"));return Q(n)?n:{}}catch(n){if(t.allowMissing&&n.code==="ENOENT")return null;throw n}}async function Le(e){try{return await Kn(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function vt(e,t){try{await Qr(e,t)}catch{}}async function zn(e){await St(e,{force:!0})}async function Wn(e,t){await Promise.all([St(e,{force:!0}),St(t,{force:!0})])}function fs(e){return e?new Promise(t=>{let n="";e.on("data",i=>{n+=String(i);let r=n.indexOf(`
|
|
255
|
+
`);r>=0&&t({ok:!0,line:n.slice(0,r)})}),e.on("error",i=>{t({ok:!1,message:i instanceof Error?i.message:"MCP bridge stdout failed."})}),e.on("end",()=>{t({ok:!1,message:"MCP bridge exited before returning a response."})})}):Promise.resolve({ok:!1,message:"MCP bridge stdout was not available."})}function hs(e,t){let n=Ct(t),i=e??process.env,r=t==="win32"?We(i.APPDATA,i.USERPROFILE,i.HOME):We(i.XDG_CONFIG_HOME,i.HOME?n.join(i.HOME,".skills-layer"):void 0);return r?t==="win32"||i.XDG_CONFIG_HOME?.trim()?n.join(r,"skills-layer"):r:n.join(process.cwd(),".skills-layer")}function ys(e,t){return t==="win32"?We(e.USERPROFILE,e.HOME):We(e.HOME)}function ks(e){return be.includes(e)?e:"codex"}function ws(e,t){let n=e.tokens;return Q(n)&&Q(n[t])?n[t]:e}function bs(e){if(!e)return[];let t=e.clientIds;if(Array.isArray(t))return t.filter(r=>typeof r=="string"&&r.trim().length>0);let n=e.tokens;if(Q(n))return Object.keys(n);let i=ne(e,"clientId");return i?[i]:[]}function je(e,...t){return Ct(e).join(...t)}function Ct(e){return e==="win32"?es:Xr}function We(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function ne(e,t){let n=e?.[t];return typeof n=="string"&&n.trim().length>0?n:null}function Se(e){return Zr("sha256").update(e).digest("hex")}function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vs(e){let t=Ss(e);if(t)return t;let n=Ps(e);if(n)return n;throw new Error("Unsupported bundle archive format")}function Jn(e){try{return vs(e)}catch{return null}}function Ss(e){if(e.byteLength<4)return null;let t=new TextDecoder,n=new DataView(e.buffer,e.byteOffset,e.byteLength),i=[],r=0,s=!1;for(;r+4<=e.byteLength;){let o=n.getUint32(r,!0);if(o===67324752){if(s=!0,r+30>e.byteLength)throw new Error("ZIP local header is truncated");let a=n.getUint16(r+8,!0),c=n.getUint32(r+18,!0),u=n.getUint16(r+26,!0),d=n.getUint16(r+28,!0),g=r+30,f=g+u+d,m=f+c;if(a!==0)throw new Error("Only stored ZIP entries are supported");if(m>e.byteLength)throw new Error("ZIP entry data is truncated");i.push({path:t.decode(e.slice(g,g+u)),content:t.decode(e.slice(f,m))}),r=m;continue}return o===33639248||o===101010256?s?i:null:s?(()=>{throw new Error("Unexpected ZIP signature")})():null}return i}function Ps(e){try{let t=JSON.parse(new TextDecoder().decode(e));return t.format!=="skills-layer-external-bundle-v1"||!Array.isArray(t.files)?null:t.files.filter(n=>typeof n.path=="string").map(n=>({path:n.path,...typeof n.content=="string"?{content:n.content}:{}}))}catch{return null}}import{createHash as Cs}from"node:crypto";function Yn(e){let t=Cs("sha256");for(let n of e)t.update(n.path),t.update("\0"),t.update(n.content??""),t.update("\0");return t.digest("hex")}var xt=["productivity","coding","review","testing","devops","data","documents","media","research","planning","design","security","business","education","automation","communication","email","customer-support","sales","marketing","finance","legal","operations","project-management","writing","translation","knowledge-management","hr","ai","ecommerce"],xs="productivity",Rs=new Set(xt),_s={ci:"devops","ci-cd":"devops",compliance:"security",content:"documents",crm:"customer-support",docs:"documents",frontend:"coding","customer-service":"customer-support","customer-success":"customer-support","e-commerce":"ecommerce",genai:"ai",legal:"legal",llm:"ai",ops:"operations",pm:"project-management",reporting:"business",reports:"business","team-ops":"operations",ui:"design",ux:"design","web-development":"coding"},$s={productivity:["productivity","todo","task","tasks","calendar","meeting","notes","workflow","focus"],coding:["code","coding","developer","frontend","backend","repository","typescript","javascript","react","vite","html","css","component","bundle","artifact"],review:["review","reviews","critique","audit","feedback","pr","pull","quality"],testing:["test","tests","testing","qa","coverage","regression","playwright","vitest"],devops:["deploy","deployment","ci","cd","pipeline","infra","infrastructure","docker","cloudflare","wrangler"],data:["data","dataset","sql","database","analytics","metrics","spreadsheet","csv","json"],documents:["document","documents","doc","docs","pdf","report","reports","contract","proposal","writing"],media:["media","image","video","audio","transcript","youtube","asset","thumbnail"],research:["research","search","sources","citation","citations","summarize","summaries","literature"],planning:["plan","planning","project","roadmap","milestone","sprint","delivery","schedule"],design:["design","ui","ux","layout","wireframe","prototype","figma","tailwind","shadcn"],security:["security","threat","secret","secrets","vulnerability","vulnerabilities","risk","policy"],business:["business","strategy","customer","market","stakeholder","commercial","pricing"],education:["education","teach","teaching","learn","learning","lesson","course","tutorial"],automation:["automation","automate","workflow","script","scripts","bot","trigger","orchestration"],communication:["communication","slack","message","messages","chat","reply","announcement","conversation"],email:["email","emails","gmail","googleemail","googlemail","outlook","inbox","mail","newsletter"],"customer-support":["support","ticket","tickets","helpdesk","customer","service","csat","escalation"],sales:["sales","lead","leads","prospect","pipeline","deal","deals","crm","account"],marketing:["marketing","campaign","brand","seo","content","social","audience","copy"],finance:["finance","financial","invoice","invoices","budget","forecast","accounting","revenue","tax"],legal:["legal","contract","contracts","clause","clauses","compliance","policy","terms","privacy"],operations:["operations","ops","runbook","process","sop","incident","queue","handoff"],"project-management":["project","projects","backlog","dependency","dependencies","kanban","scrum","pm"],writing:["writing","write","draft","edit","editing","blog","article","copywriting"],translation:["translation","translate","localization","locale","language","languages","i18n"],"knowledge-management":["knowledge","wiki","kb","retrieval","archive","taxonomy","knowledgebase"],hr:["hr","hiring","recruiting","interview","onboarding","employee","people","performance"],ai:["ai","llm","prompt","prompts","model","models","agent","agents","rag","embedding"],ecommerce:["ecommerce","commerce","shop","store","checkout","cart","order","orders","product"]};function Zn(e){if(typeof e!="string")return null;let t=ei(e);return Rs.has(t)?t:_s[t]??null}function Qn(e){let t=e.trim().toLowerCase().replace(/[_\s]+/gu,"-"),n={ai:"AI",hr:"HR",ecommerce:"E-commerce","e-commerce":"E-commerce"};return n[t]?n[t]:e.split(/[-_\s]+/u).filter(Boolean).map(i=>`${i.slice(0,1).toUpperCase()}${i.slice(1)}`).join(" ")}function Xn(e){let t=[{value:e.slug??"",weight:3,signal:"slug"},{value:e.name??"",weight:3,signal:"name"},{value:e.description??"",weight:2,signal:"description"},{value:e.skillType??"",weight:1,signal:"skill_type"},{value:e.compatibility??"",weight:1,signal:"compatibility"},{value:(e.tags??[]).join(" "),weight:4,signal:"tags"},{value:e.body??"",weight:1,signal:"body"}].filter(s=>s.value.trim().length>0),n=new Map;for(let s of t){let o=js(s.value);for(let[a,c]of Object.entries($s)){if(!c.some(g=>o.has(g)))continue;let d=n.get(a)??{score:0,signals:new Set};d.score+=s.weight,d.signals.add(s.signal),n.set(a,d)}}let r=[...n.entries()].sort((s,o)=>o[1].score-s[1].score||xt.indexOf(s[0])-xt.indexOf(o[0]))[0];return!r||r[1].score<2?{category:Is(e),confidence:"fallback",matchedSignals:[]}:{category:r[0],confidence:r[1].score>=5?"high":r[1].score>=3?"medium":"low",matchedSignals:[...r[1].signals].sort()}}function Is(e){let t=ei(e.skillType??"");return t.includes("automation")?"automation":t.includes("mcp")?"ai":xs}function ei(e){return e.trim().toLowerCase().replace(/[_\s]+/gu,"-")}function js(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/u).map(t=>t.trim()).filter(t=>t.length>=2).flatMap(As))}function As(e){let t=[e];return e.endsWith("ing")&&e.length>5&&t.push(e.slice(0,-3)),e.endsWith("s")&&e.length>4&&t.push(e.slice(0,-1)),t}var Ls=["standalone","workflow_automation","mcp_enhanced"];function ti(e){let t=e?.trim();if(!t)return"standalone";if(t==="workflow")return"workflow_automation";if(!Ls.includes(t))throw new Error(`Unsupported skill type "${t}". Supported types: standalone, workflow, workflow_automation, mcp_enhanced.`);return t}function ni(e){return[{path:"SKILL.md",content:Es(e)},{path:"README.md",content:Us(e)},{path:"references/guide.md",content:Bs(e)},{path:"scripts/README.md",content:Ts(e)}]}function Es(e){let t=Ns(e);return`---
|
|
256
256
|
name: ${e.skillSlug}
|
|
257
257
|
description: ${e.description}
|
|
258
258
|
compatibility: Codex, Claude Code
|
|
@@ -267,7 +267,7 @@ metadata:
|
|
|
267
267
|
- model_context
|
|
268
268
|
- filesystem_read
|
|
269
269
|
---
|
|
270
|
-
# ${
|
|
270
|
+
# ${Rt(e.skillSlug)}
|
|
271
271
|
|
|
272
272
|
Use this skill when the user needs ${e.description.toLowerCase()}
|
|
273
273
|
|
|
@@ -280,7 +280,7 @@ Use this skill when the user needs ${e.description.toLowerCase()}
|
|
|
280
280
|
|
|
281
281
|
- If the skill does not trigger, make the user request more explicit and mention the task directly.
|
|
282
282
|
- Move deeper procedures into [references/guide.md](references/guide.md) to keep this file concise.
|
|
283
|
-
`}function
|
|
283
|
+
`}function Us(e){return`# ${Rt(e.skillSlug)}
|
|
284
284
|
|
|
285
285
|
This scaffold was created for a ${e.skillType.replaceAll("_"," ")} skill.
|
|
286
286
|
|
|
@@ -303,12 +303,12 @@ Current summary:
|
|
|
303
303
|
- Slug: \`${e.skillSlug}\`
|
|
304
304
|
- Description: ${e.description}
|
|
305
305
|
- Default price: free (\`price_cents: 0\`)
|
|
306
|
-
`}function
|
|
306
|
+
`}function Ts(e){return`# Scripts
|
|
307
307
|
|
|
308
308
|
Place optional helper scripts for \`${e.skillSlug}\` here.
|
|
309
309
|
|
|
310
310
|
Only include files that are required by the skill workflow. Keep the runtime surface small so bundle packaging stays predictable.
|
|
311
|
-
`}function
|
|
311
|
+
`}function Bs(e){return`# ${Rt(e.skillSlug)} Guide
|
|
312
312
|
|
|
313
313
|
## Intent
|
|
314
314
|
|
|
@@ -320,15 +320,15 @@ Document the decision rules, expected inputs, and success criteria for this ${e.
|
|
|
320
320
|
- Example prompts that should trigger the skill
|
|
321
321
|
- Failure cases and recovery guidance
|
|
322
322
|
- Tooling or policy constraints
|
|
323
|
-
`}function
|
|
324
|
-
`);return`skills-layer-cli:api-key:${
|
|
323
|
+
`}function Rt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ns(e){let t=Zn(e.category);return t||Xn({name:e.skillSlug,slug:e.skillSlug,description:e.description,skillType:e.skillType}).category}var Ms=/^github:([^/]+)\/([^/#]+)(?:\/([^#]+))?(?:#(.+))?$/,Fs=/^gitlab:([^/#]+(?:\/[^/#]+)*?)\/([^/#]+)(?:\/([^/#]+))?(?:#(.+))?$/,Os=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/(.+?))?(?:#([^@]+))?$/,qs=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\/.+)?(?:#[^@]+)?$/,Ks=/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/,Gs=/^(?:ssh:\/\/)?git@github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/,Vs=/^(?:ssh:\/\/)?git@gitlab\.com[:/]([^/]+(?:\/[^/]+)*)\/([^/]+?)(?:\.git)?$/;function Qe(e){let t=e.trim();if(t.length===0)throw new Error("import requires a non-empty source.");let{sourceInput:n,skillFilter:i}=Ds(t),r=n.match(Ms);if(r){let[,g,f,m,k]=r;return Ze({input:t,owner:g,repo:f,ref:k?.trim()||"main",subpath:m,skillFilter:i})}let s=n.match(Fs);if(s){let[,g,f,m,k]=s;return _t({input:t,host:"gitlab.com",namespace:g,repo:f,ref:k?.trim()||"main",subpath:m,skillFilter:i})}let o=Hs(t);if(o)return o;let a=zs(t);if(a)return a;let c=n.match(Gs);if(c){let[,g,f]=c;return Ze({input:t,owner:g,repo:ue(f),ref:"main",subpath:"SKILL.md"})}let u=n.match(Vs);if(u){let[,g,f]=u;return _t({input:t,host:"gitlab.com",namespace:g,repo:ue(f),ref:"main",subpath:"SKILL.md"})}if(/^(?:git\+)?https?:\/\//u.test(n)){if(/[?&]skill=/u.test(n)){let g=new URL(n.replace(/^git\+/u,"")),f=g.searchParams.get("skill")?.trim();return g.searchParams.delete("skill"),{kind:"url",input:t,url:g.toString(),canonicalSource:g.toString(),...f?{skillFilter:f}:{}}}return{kind:"url",input:t,url:n.replace(/^git\+/u,""),canonicalSource:n.replace(/^git\+/u,"")}}let d=n.match(Os);if(d&&!Ks.test(n)){let[,g,f,m,k]=d;return Ze({input:t,owner:g,repo:ue(f),ref:k?.trim()||"main",subpath:m,skillFilter:i})}return/^(?:ssh:\/\/)?git@/u.test(n)||/^(?:git\+)?ssh:\/\//u.test(n)?{kind:"git",input:t,url:n.replace(/^git\+/u,""),canonicalSource:n.replace(/^git\+/u,""),...i?{skillFilter:i}:{}}:{kind:"local",input:t,location:n,canonicalSource:n,...i?{skillFilter:i}:{}}}function Xe(e){let t=e?.trim();return t&&t.length>0?t:"SKILL.md"}function Ds(e){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("git@")||e.startsWith("ssh://"))return{sourceInput:e};let t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return{sourceInput:e};let n=e.slice(0,t),i=e.slice(t+1).trim();return i.match(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u)?n.includes("#")?{sourceInput:n,skillFilter:i}:n.startsWith("github:")||n.startsWith("gitlab:")||qs.test(n)?{sourceInput:n,skillFilter:i}:{sourceInput:n,skillFilter:i}:{sourceInput:e}}function ii(e,t,n,i,r){return e==="gitlab"&&r&&r!=="gitlab.com"?`${e}://${r}/${t}@${n}/${i}`:`${e}://${t}@${n}/${i}`}function ue(e){return e.replace(/\.git$/u,"")}function Hs(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return null;let t=new URL(e);if(t.hostname!=="github.com")return null;let n=t.pathname.split("/").filter(Boolean);if(n.length<2)throw new Error("GitHub URLs must include an owner and repository.");let i=n[0],r=ue(n[1]),s="main",o="SKILL.md";(n[2]==="tree"||n[2]==="blob")&&(s=n[3]?.trim()||"main",o=Xe(n.slice(4).join("/")));let a=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),Ze({input:e,owner:i,repo:r,ref:s,subpath:o,skillFilter:a})}function zs(e){if(!e.startsWith("http://")&&!e.startsWith("https://"))return null;let t=new URL(e);if(t.hostname==="github.com")return null;let n=t.pathname.split("/").filter(Boolean),i=n.indexOf("-");if(t.hostname!=="gitlab.com"&&i===-1)return null;let r=i===-1?n:n.slice(0,i);if(r.length<2)throw new Error("GitLab URLs must include a namespace and repository.");let s=ue(r[r.length-1]),o=r.slice(0,-1).join("/"),a=i===-1?void 0:n[i+1],c=i===-1?[]:n.slice(i+2),u=(a==="tree"||a==="blob")&&c[0]?.trim()||"main",d=a==="tree"||a==="blob"?Xe(c.slice(1).join("/")):"SKILL.md",g=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),_t({input:e,host:t.hostname,namespace:o,repo:s,ref:u,subpath:d,skillFilter:g})}function Ze(e){let t=Xe(e.subpath);return{kind:"github",input:e.input,owner:e.owner,repo:ue(e.repo),ref:e.ref,subpath:t,repoUrl:`https://github.com/${e.owner}/${ue(e.repo)}`,rawUrl:`https://raw.githubusercontent.com/${e.owner}/${ue(e.repo)}/${e.ref}/${t}`,canonicalSource:ii("github",`${e.owner}/${ue(e.repo)}`,e.ref,t),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}function _t(e){let t=ue(e.repo),n=Xe(e.subpath);return{kind:"gitlab",input:e.input,host:e.host,namespace:e.namespace,repo:t,ref:e.ref,subpath:n,repoUrl:`https://${e.host}/${e.namespace}/${t}`,rawUrl:`https://${e.host}/${e.namespace}/${t}/-/raw/${e.ref}/${n}`,canonicalSource:ii("gitlab",`${e.namespace}/${t}`,e.ref,n,e.host),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}var Ws="private",ri="public",si="unlisted",oi="delisted";function $t(e){if(typeof e!="string"||e.trim().length===0)return null;let t=e.trim().toLowerCase();return t==="private"?Ws:t===ri?ri:t===si?si:t===oi?oi:null}import{execFile as Js}from"node:child_process";import{createHash as Ys}from"node:crypto";import{promisify as Zs}from"node:util";var It=Zs(Js),Ue="apiKey",Pe="apiKeyRef",Te="Skills Layer CLI";function jt(e=process.platform,t=process.env){let n=t.SKILLS_LAYER_CREDENTIAL_STORE?.trim().toLowerCase();return n==="local-file"||n==="local_file"||n==="disabled"||e!=="darwin"||process.env.VITEST==="true"&&n!=="macos-keychain"&&n!=="macos_keychain"?null:eo()}async function ai(e,t){if(!(typeof e[Ue]=="string"&&e[Ue].length>0))return e;let i=At(t);if(!i)return e;try{let r={...e,credentialStorage:"macos_keychain"},s=Qs(e);return await i.set(Lt(t),s,e[Ue]),r[Pe]=s,delete r[Ue],r}catch{return Xs(e)}}async function li(e,t){if(e.credentialStorage!=="macos_keychain"||e[Ue]||!e[Pe])return e;let n=At(t);if(!n)return e;let i=await n.get(Lt(t),e[Pe]);return i?{...e,apiKey:i}:e}async function ci(e,t){if(!e||e.credentialStorage!=="macos_keychain"||!e[Pe])return;let n=At(t);n&&await n.delete(Lt(t),e[Pe])}function Qs(e){let t=[e.baseUrl??"unknown-base-url",e.userId??e.email??e.role??"unknown-user","apiKey"].join(`
|
|
324
|
+
`);return`skills-layer-cli:api-key:${Ys("sha256").update(t).digest("base64url").slice(0,32)}`}function At(e){return e.store!==void 0?e.store:jt(e.platform,e.env??process.env)}function Lt(e){return e.service??Te}function Xs(e){let t={...e,credentialStorage:"local_file_locked"};return delete t[Pe],t}function eo(){return{kind:"macos_keychain",async set(e,t,n){await It("/usr/bin/security",["add-generic-password","-a",t,"-s",e,"-w",n,"-U"])},async get(e,t){try{let{stdout:n}=await It("/usr/bin/security",["find-generic-password","-a",t,"-s",e,"-w"]);return n.trim()||null}catch{return null}},async delete(e,t){try{await It("/usr/bin/security",["delete-generic-password","-a",t,"-s",e])}catch{}}}}function Et(e){let t=e.skillSlug??"<skill-slug>";return{localWork:{purpose:e.purpose,command:e.command,jsonCommand:e.jsonCommand},guardian:{checkCommand:`skills-layer guardian check --skill ${t} --json`,execCommand:`skills-layer guardian exec ${t} --json -- <command>`,mcpTools:["guardian.check","guardian.enforce","guardian.status","guardian.incident"],guidance:"Before risky shell, network, file, secret, browser, API, generated-code, or model-context actions, call MCP guardian.check/guardian.enforce or run skills-layer guardian check. Route shell actions through skills-layer guardian exec when strict local blocking is needed."},setup:{setupCommand:"skills-layer setup",hookStatusCommand:"skills-layer guardian hook status",hookInstallProjectCommand:"skills-layer guardian hook install --agent codex --scope project",hookInstallGlobalCommand:"skills-layer guardian hook install --agent codex --scope global"}}}var ui=` ____ _ _ _ _ _
|
|
325
325
|
/ ___|| | _(_) | |___ | | __ _ _ _ ___ _ __
|
|
326
326
|
\\___ \\| |/ / | | / __| | | / _\` | | | |/ _ \\ '__|
|
|
327
327
|
___) | <| | | \\__ \\ | |__| (_| | |_| | __/ |
|
|
328
328
|
|____/|_|\\_\\_|_|_|___/ |_____\\__,_|\\__, |\\___|_|
|
|
329
329
|
|___/
|
|
330
330
|
Skills-Layer
|
|
331
|
-
AI Agent first platform for Skills`;var
|
|
331
|
+
AI Agent first platform for Skills`;var di=`Skills Layer MCP
|
|
332
332
|
Configure Skills Layer for AI agents through a local stdio bridge.
|
|
333
333
|
|
|
334
334
|
Usage:
|
|
@@ -359,7 +359,7 @@ Checks:
|
|
|
359
359
|
repair rewrites the local bridge and supported target config.
|
|
360
360
|
disconnect removes Skills Layer MCP local state and the selected target config entry.
|
|
361
361
|
|
|
362
|
-
After setup or repair, open a fresh agent session or restart the agent if tools are not visible.`;var
|
|
362
|
+
After setup or repair, open a fresh agent session or restart the agent if tools are not visible.`;var to=`Skills Layer CLI
|
|
363
363
|
Agent-first skill marketplace for developers. CLI, MCP, and API share one journey model.
|
|
364
364
|
|
|
365
365
|
Usage:
|
|
@@ -550,9 +550,9 @@ Safety:
|
|
|
550
550
|
- Use guardian status [skill-slug] to see Cloud policy, stored user preference, effective mode, local hook posture, and the next Guardian action.
|
|
551
551
|
- Use guardian hook install to add native host hooks where supported; status reports the actual enforcement layer instead of overclaiming strict blocking.
|
|
552
552
|
- Use guardian exec when you need a stronger wrapper that refuses blocked shell actions before spawning the command.
|
|
553
|
-
- Use --dry-run before mutating catalog/source installs, workspace deployments, submissions, visibility, or ownership state.`,
|
|
553
|
+
- Use --dry-run before mutating catalog/source installs, workspace deployments, submissions, visibility, or ownership state.`,Be=`${ui}
|
|
554
554
|
|
|
555
|
-
${
|
|
555
|
+
${to}`;var no=new Set(["add-issue","add-review","agents","api-key","approval","auth","backend","buy","categories","check","compare","creator","doctor","export","featured","find","guardian","help","identity","import","install","installed","library","login","logout","mcp","owned","preview-trigger","profile","purchases","recommend","register","remove","restore","search","show","show-issues","show-reviews","source","status","sync","trending","trust","update","validate","whoami","workspace","workspaces"]);function et(e,t){let n=e?.trim().toLowerCase(),i=t?.trim().toLowerCase();if(!n||!no.has(n))return null;if(n==="install")return`Skills Layer install help
|
|
556
556
|
|
|
557
557
|
Usage:
|
|
558
558
|
skills-layer install <skill-slug> [--version <semver>] [--scope <local|project|global|workspace>] [--agent <agent>] [--dry-run] [--json]
|
|
@@ -578,7 +578,38 @@ Good defaults:
|
|
|
578
578
|
After install:
|
|
579
579
|
skills-layer installed
|
|
580
580
|
skills-layer sync
|
|
581
|
-
skills-layer update <skill-slug>`;if(n==="
|
|
581
|
+
skills-layer update <skill-slug>`;if(n==="api-key")return i==="create"?`Skills Layer api-key create help
|
|
582
|
+
|
|
583
|
+
Usage:
|
|
584
|
+
skills-layer api-key create --name <name> --scope <scope>[,<scope>...] [--expires <duration>] [--json]
|
|
585
|
+
|
|
586
|
+
What it does:
|
|
587
|
+
- Creates a named scoped automation key for CI or scripts.
|
|
588
|
+
- The raw key is sent to your verified email and is not printed in CLI or MCP output.
|
|
589
|
+
- --expires supports day durations such as 7d, 30d, or 90d; unsupported duration formats are rejected before creation.
|
|
590
|
+
|
|
591
|
+
Examples:
|
|
592
|
+
skills-layer api-key create --name "GitHub Actions" --scope catalog:read,creator:submit --expires 30d
|
|
593
|
+
skills-layer api-key create --name "Read-only smoke" --scope catalog:read --expires 7d --json
|
|
594
|
+
|
|
595
|
+
Next:
|
|
596
|
+
skills-layer api-key list
|
|
597
|
+
skills-layer api-key revoke --key-id <key-id>`:`Skills Layer api-key help
|
|
598
|
+
|
|
599
|
+
Usage:
|
|
600
|
+
skills-layer api-key create --name <name> --scope <scope>[,<scope>...] [--expires <duration>] [--json]
|
|
601
|
+
skills-layer api-key list [--json]
|
|
602
|
+
skills-layer api-key revoke --key-id <key-id> [--json]
|
|
603
|
+
|
|
604
|
+
What it does:
|
|
605
|
+
- Manages scoped automation credentials.
|
|
606
|
+
- Normal human CLI/MCP login uses skills-layer login; API keys are for named automation.
|
|
607
|
+
- Raw keys are shown or sent only through controlled delivery paths and should not be pasted into logs.
|
|
608
|
+
|
|
609
|
+
Examples:
|
|
610
|
+
skills-layer api-key create --name "GitHub Actions" --scope catalog:read --expires 7d
|
|
611
|
+
skills-layer api-key list
|
|
612
|
+
skills-layer api-key revoke --key-id key_123`;if(n==="buy")return`Skills Layer buy help
|
|
582
613
|
|
|
583
614
|
Usage:
|
|
584
615
|
skills-layer buy <skill-slug> [--payment-method <card|pm_id>] [--json]
|
|
@@ -596,7 +627,78 @@ Examples:
|
|
|
596
627
|
|
|
597
628
|
Next:
|
|
598
629
|
skills-layer purchases list
|
|
599
|
-
skills-layer install <skill-slug>`;if(n==="
|
|
630
|
+
skills-layer install <skill-slug>`;if(n==="add-review")return`Skills Layer add-review help
|
|
631
|
+
|
|
632
|
+
Usage:
|
|
633
|
+
skills-layer add-review <skill-slug> --rating <1-5> [--feedback <text>] [--json]
|
|
634
|
+
|
|
635
|
+
What it does:
|
|
636
|
+
- Adds or updates your review for a skill you can access.
|
|
637
|
+
- Rating is validated before submission.
|
|
638
|
+
- Use --json for agent-safe status output.
|
|
639
|
+
|
|
640
|
+
Examples:
|
|
641
|
+
skills-layer add-review project-planner --rating 5 --feedback "Useful planning workflow"
|
|
642
|
+
skills-layer show-reviews project-planner`;if(n==="add-issue")return`Skills Layer add-issue help
|
|
643
|
+
|
|
644
|
+
Usage:
|
|
645
|
+
skills-layer add-issue <skill-slug> --issue-type <bug|quality|safety|other> --message <text> [--json]
|
|
646
|
+
|
|
647
|
+
What it does:
|
|
648
|
+
- Reports a buyer-visible issue against a skill you can access.
|
|
649
|
+
- Issue type is validated before submission.
|
|
650
|
+
- Safety-related reports feed Guardian/security review signals.
|
|
651
|
+
|
|
652
|
+
Examples:
|
|
653
|
+
skills-layer add-issue project-planner --issue-type quality --message "Missing examples"
|
|
654
|
+
skills-layer show-issues project-planner`;if(n==="profile"&&i==="update")return`Skills Layer profile update help
|
|
655
|
+
|
|
656
|
+
Usage:
|
|
657
|
+
skills-layer profile update [--display-name <text>] [--bio <text>] [--company <text>] [--json]
|
|
658
|
+
|
|
659
|
+
What it does:
|
|
660
|
+
- Updates editable profile fields for the signed-in account.
|
|
661
|
+
- Email and role are identity properties and are not changed here.
|
|
662
|
+
- Use --json for machine-readable update results.
|
|
663
|
+
|
|
664
|
+
Examples:
|
|
665
|
+
skills-layer profile update --display-name "Manual Tester"
|
|
666
|
+
skills-layer profile update --company "Skills Layer" --json`;if(n==="recommend")return`Skills Layer recommend help
|
|
667
|
+
|
|
668
|
+
Usage:
|
|
669
|
+
skills-layer recommend <task> [--limit <n>] [--json]
|
|
670
|
+
|
|
671
|
+
What it does:
|
|
672
|
+
- Recommends skills for a natural-language task.
|
|
673
|
+
- --limit must be a whole number in the accepted range.
|
|
674
|
+
- Results include slugs you can inspect with show/trust/install.
|
|
675
|
+
|
|
676
|
+
Examples:
|
|
677
|
+
skills-layer recommend "choose a research plan" --limit 3
|
|
678
|
+
skills-layer recommend "summarize meeting notes" --json`;if(n==="compare")return`Skills Layer compare help
|
|
679
|
+
|
|
680
|
+
Usage:
|
|
681
|
+
skills-layer compare <skill-slug-1> <skill-slug-2> [<skill-slug-3> ... up to 5] [--json]
|
|
682
|
+
|
|
683
|
+
What it does:
|
|
684
|
+
- Compares up to 5 catalog skills side by side.
|
|
685
|
+
- Returns missing slugs separately so agents can recover cleanly.
|
|
686
|
+
- Review price, trust, compatibility, and risk before install.
|
|
687
|
+
|
|
688
|
+
Examples:
|
|
689
|
+
skills-layer compare project-planner gtm-strategy
|
|
690
|
+
skills-layer compare skill-a skill-b skill-c --json`;if(n==="categories")return`Skills Layer categories help
|
|
691
|
+
|
|
692
|
+
Usage:
|
|
693
|
+
skills-layer categories [--json]
|
|
694
|
+
|
|
695
|
+
What it does:
|
|
696
|
+
- Lists catalog categories you can use to browse or filter discovery.
|
|
697
|
+
- Category names are formatted for humans while JSON keeps stable identifiers.
|
|
698
|
+
|
|
699
|
+
Examples:
|
|
700
|
+
skills-layer categories
|
|
701
|
+
skills-layer search planning --json`;if(n==="export")return`Skills Layer export help
|
|
600
702
|
|
|
601
703
|
Usage:
|
|
602
704
|
skills-layer export <skill-slug> [--version <semver|external-id>] [--output <path>] [--show-url] [--json]
|
|
@@ -674,10 +776,11 @@ Next:
|
|
|
674
776
|
skills-layer install <skill-slug>`;if(n==="remove")return`Skills Layer remove help
|
|
675
777
|
|
|
676
778
|
Usage:
|
|
677
|
-
skills-layer remove <skill-slug> [--json]
|
|
779
|
+
skills-layer remove <skill-slug> [--scope <local|project|global|workspace>] [--agent <agent>] [--json]
|
|
678
780
|
|
|
679
781
|
What it does:
|
|
680
782
|
- Removes the local install record for one skill.
|
|
783
|
+
- Validates scope/agent filters before changing local state.
|
|
681
784
|
- Leaves catalog ownership and purchase history unchanged.
|
|
682
785
|
- Use install again when you want to materialize the skill locally.
|
|
683
786
|
|
|
@@ -909,7 +1012,7 @@ Usage:
|
|
|
909
1012
|
skills-layer guardian exec <skill-slug> [--action-json <json>] [--path <installed-skill-path>] [--dry-run] [--json] -- <command>
|
|
910
1013
|
|
|
911
1014
|
What it does:
|
|
912
|
-
- check performs public-safe local preflight, then asks Skills Layer Cloud for the security decision while keeping
|
|
1015
|
+
- check performs public-safe local preflight, then asks Skills Layer Cloud for the security decision while keeping sensitive policy evaluation server-side.
|
|
913
1016
|
- incident can write local disable/quarantine/report artifacts; local_only avoids uploading incident evidence.
|
|
914
1017
|
- enable, disable, and enable-warnings-only request one-skill Guardian mode changes; Cloud policy still decides the effective mode.
|
|
915
1018
|
- status shows the Cloud policy, the local per-skill preference if one is stored, the effective mode, hook posture, and next action.
|
|
@@ -998,11 +1101,11 @@ Examples:
|
|
|
998
1101
|
|
|
999
1102
|
Next:
|
|
1000
1103
|
skills-layer source connection status <source-connection-id>
|
|
1001
|
-
skills-layer creator source prepare <source-connection-id> <path>`;if(n==="mcp")return
|
|
1104
|
+
skills-layer creator source prepare <source-connection-id> <path>`;if(n==="mcp")return di;let r=i?` ${i}`:"";return`Skills Layer ${n}${r} help
|
|
1002
1105
|
|
|
1003
|
-
Run \`skills-layer --help\` for public CLI usage.`}var tt="0.1.
|
|
1004
|
-
`)),credentialStore:t.credentialStore!==void 0?t.credentialStore
|
|
1005
|
-
`,stderr:""};let r=
|
|
1106
|
+
Run \`skills-layer --help\` for public CLI usage.`}var tt="0.1.6";var I=class extends Error{status;details;constructor(t,n,i){super(n),this.name="ApiError",this.status=t,this.details=i}},Xi=1,mn=1,pi=1,pe="skills-layer-security-hook",te="Skills Layer Security Hook",fn="https://api.skills-layer.com",so="http://127.0.0.1:8787",oo=new Set(["json","dry-run","help","list","all","verbose","show-url","quarantine","confirm","confirmed","with-mcp","no-mcp","allow-unmanaged-once","disclose-source","allow-findings-featured"]),gi=new Set(["accept-capability","approval-request-id","grant-json","paraphrase","should-not-trigger","should-trigger"]),ao=new Set(["bio","company","description","display-name","feedback","message","note","reason","search","summary"]),lo=new Set(["action","action-json","agent","amount-cents","api-key","base-url","capability","category","claim-id","client","cloud-trust-ledger","code","commit-sha","decision","decision-evidence-json","dependency-audit-status","dir","email","environment","evidence-json","expires","fixed-version","format","install","issue-id","issue-type","key-id","kind","license","limit","listing-status","max-characters","method","mode","name","output","path","payment-method","pin","price-cents","provider","provider-installation-id","provider-owner-id","provider-project-id","provider-repo-id","provenance-intent","publication-status","rating","requested-role","review-id","runtime-risk","scope","security-capability","skill","skill-type","sort","source","source-intake-context","state","status","text","telemetry-mode","trust","type","unmanaged-policy","version","version-id","visibility","workspace"]);async function Nu(e,t={}){let n={env:t.env??process.env,platform:t.platform??process.platform,cwd:t.cwd??process.cwd(),now:t.now??(()=>new Date().toISOString()),fetchFn:t.fetch??globalThis.fetch,openUrl:t.openUrl??Bc(t.platform??process.platform),stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY,promptText:t.promptText??Lc(),promptSecret:t.promptSecret??Ec(),promptSelect:t.promptSelect??Uc(t.selectInput??process.stdin,t.selectOutput??process.stdout),sleep:t.sleep??(a=>new Promise(c=>setTimeout(c,a))),emitInfo:t.emitInfo??(a=>process.stdout.write(`${a}
|
|
1107
|
+
`)),credentialStore:t.credentialStore!==void 0?t.credentialStore:jt(t.platform??process.platform,t.env??process.env)},i=e[0];if(!i){let a=fi([]),c=await Tt(a.flags,n);return await pl(a.flags,c)}if(i==="--help"||i==="-h")return{exitCode:0,stdout:Be,stderr:""};if(i==="--version"||i==="-v")return{exitCode:0,stdout:`skills-layer ${tt}
|
|
1108
|
+
`,stderr:""};let r=fi(e.slice(1));if(r.error)return y(r.error,r.flags.json);let{flags:s,positionals:o}=r;if(i==="admin")return y("The public skills-layer package does not include internal commands.",s.json);if(i==="version"){let a=await Tt(s,n);return h({status:"ok",name:"skills-layer",version:tt},`skills-layer ${tt}`,s.json,a)}if(s.help){let a=et(i,o[0]);return a?{exitCode:0,stdout:a,stderr:""}:y(mi(i),s.json)}try{let a=await Tt(s,n);switch(i){case"agents":return await po(o,s,a);case"backend":return await go(o,s,a);case"register":return await er(s,a);case"login":return await tr(s,a);case"logout":return await nr(s,a);case"whoami":return await R("/api/v1/whoami",s,a,"Account loaded.",{authenticated:!0});case"profile":return await ho(o,s,a);case"auth":return await ko(o,s,a);case"identity":return await So(o,s,a);case"api-key":return await Po(o,s,a);case"mcp":return await Co(o,s,a);case"search":case"find":return await jo(o,s,a);case"featured":case"trending":return await To(i,s,a);case"categories":return await R("/api/v1/categories",s,a,"Categories loaded.");case"recommend":return await Bo(o,s,a);case"compare":return await No(o,s,a);case"show":return await Mo(o,s,a);case"trust":return await Fo(o,s,a);case"help":return await Oo(o,s,a);case"status":return await R("/api/v1/status",s,a,"Status loaded.");case"doctor":return await Ol(s,a);case"setup":return await wr(s,a);case"validate":return await qo(o,s,a);case"preview-trigger":return await Ko(o,s,a);case"creator":return await Go(o,s,a);case"install":return await wn(o,s,a);case"installed":return await Ua(s,a);case"remove":return await Ta(o,s,a);case"update":return await Ba(o,s,a);case"sync":return await Ma(s,a);case"restore":return await Wa(o,s,a);case"check":return await Ja(o,s,a);case"import":return await Ya(o,s,a);case"source":return await Qa(o,s,a);case"approval":return await tl(o,s,a);case"workspace":case"workspaces":return await nl(o,s,a);case"buy":return await il(o,s,a);case"purchases":return await rl(o,s,a);case"owned":return await R("/api/v1/me/library",s,a,"Owned skills loaded.",{authenticated:!0});case"export":return await ol(o,s,a);case"library":return await sl(o,s,a);case"add-review":return await Ei("add",o,s,a);case"show-reviews":return await Ei("show",o,s,a);case"add-issue":return await Ui("add",o,s,a);case"show-issues":return await Ui("show",o,s,a);case"guardian":return await al(o,s,a);default:return y(mi(i),s.json)}}catch(a){return a instanceof I?yt(a,s.json):y(ae(a),s.json)}}function mi(e){let t=e.trim().toLowerCase();return t==="purchase"?`Unknown command "${e}".
|
|
1006
1109
|
|
|
1007
1110
|
Did you mean:
|
|
1008
1111
|
skills-layer buy <skill-slug>
|
|
@@ -1015,7 +1118,7 @@ Did you mean:
|
|
|
1015
1118
|
skills-layer show <skill-slug>`:t==="security-report"?`Unknown command "${e}".
|
|
1016
1119
|
|
|
1017
1120
|
Did you mean:
|
|
1018
|
-
skills-layer trust <skill-slug>`:`Unknown command "${e}".`}function ui(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(Ys.has(s)){let l=At(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(Zs.has(s)){let l=Xs(e,i);if(!l.value)return{flags:t,positionals:n,error:`Flag --${s} requires a value.`};t[At(s)]=l.value,i=l.nextIndex;continue}if(Qs.has(s)||li.has(s)){let l=At(s);if(li.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 Xs(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 At(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function Lt(e,t){let n=eo(t.env,t.platform),[i,r]=await Promise.all([vc(n.configPath,t),Y(n.backendPreferencePath)]),s=ie(p(e.baseUrl)??X(t.env.SKILLS_LAYER_BASE_URL)??X(r?.preferredBaseUrl)??X(i?.baseUrl)??pn),o=p(e.apiKey)??X(t.env.SKILLS_LAYER_API_KEY),l=X(i?.apiKey),c=X(i?.baseUrl),u=!c||ie(c)===s,d=o??(u?l:void 0),g=!o&&l&&c&&!u?`Your saved login belongs to ${ie(c)}, but the selected backend is ${s}. Run \`skills-layer backend --base-url ${ie(c)}\` to use that login, or run \`skills-layer login\` for ${s}.`:void 0;return{...t,paths:n,config:i,baseUrl:s,apiKey:d,authBlockedMessage:g}}function eo(e,t){let n=t==="win32"?xe:cn,i=t==="win32"?X(e.USERPROFILE)??X(e.HOME):X(e.HOME),r=n.join(i??".",".skills-layer");return{stateDir:r,configPath:n.join(r,"config.json"),backendPreferencePath:n.join(r,"backend-preference.json"),installsPath:n.join(r,"installs.json"),importsPath:n.join(r,"imports.json"),mcpConfigPath:n.join(r,"mcp.json"),mcpPreferencePath:n.join(r,"mcp-preference.json"),bundlesDir:n.join(r,"bundles"),incidentsDir:n.join(r,"incidents")}}async function to(e,t,n){if(e[0]!=="list")return k(`Unknown agents command "${e[0]??""}".`,t.json);let i=ge(n.env,n.platform,n.cwd).map(r=>({id:r.id,displayName:r.displayName,capabilities:r.capabilities,projectSkillsPath:r.targets.projectSkillsPath,globalSkillsPath:r.targets.globalSkillsPath}));return h({status:"ok",results:i},`Found ${i.length} supported agent targets.`,t.json,n)}async function no(e,t,n){let i=e[0],r=p(t.baseUrl);if(!i&&r||i==="cloud"||i==="local"){let c=ie(r??(i==="local"?Js:pn)),u=ye(c),d=n.config?.baseUrl??null,g=!n.config?.baseUrl||ie(n.config.baseUrl)===c;return await D(n.paths.backendPreferencePath,{version:dn,preferredBaseUrl:c,savedAt:n.now()}),h({status:"updated",selectedBackend:u,selectedBaseUrl:c,savedLoginBaseUrl:d,loginMatchesSelectedBackend:g,loggedIn:!!n.apiKey&&g,...g?{}:{warning:`Saved login belongs to ${d}; selected backend is ${c}.`}},g?`Backend set to ${u}.`:`Backend set to ${u}. Saved login is for ${d}.`,t.json,n)}if(i&&i!=="status")return k(`Unknown backend command "${i}".`,t.json);let s=ye(n.baseUrl),o=!n.config?.baseUrl||ie(n.config.baseUrl)===n.baseUrl,l=!!n.apiKey&&o;return h({status:"ok",selectedBackend:s,selectedBaseUrl:n.baseUrl,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:o,loggedIn:l,email:l?n.config?.email??null:null,role:l?n.config?.role??null:null},`Backend: ${n.baseUrl}`,t.json,n)}var gn=[{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"}],io=[...gn,{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"}],ro=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...gn];async function zi(e,t){let n=p(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",ro)}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=p(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:j(),body:JSON.stringify({method:n,email:r})});if(e.json){let l=s.status==="already_registered"?sn(s):W({...s,nextCommand:`skills-layer auth verify --email ${r} --code <code> --json`,nextAction:"auth.verify"}),c=s.status==="already_registered"?`${r} is already registered.`:`Registration started for ${r}.`;return h(l,c,e.json,t)}if(s.status==="already_registered")return h(sn(s),`${r} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,!1,t);let o;try{o=await t.promptText(`Enter the verification code sent to ${r} (check spam/junk folder if missing): `)}catch{return h(W(s),`Registration started for ${r}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${r} --code <code>\`.`,!1,t)}return await br(r,o,e,t,`Verified ${r}.`)}let i=await b(t,"/api/v1/identity/social/start",{method:"POST",headers:j(),body:JSON.stringify({provider:n,mode:"login"})});return e.json?h(i,"Social registration started.",e.json,t):await Pn(n,i,e,t,"login")}async function Wi(e,t){if(e.withMcp&&e.noMcp)return k("login cannot combine --with-mcp and --no-mcp.",e.json);let n=p(e.apiKey);if(n){let o=await Oe(t,n,{notifyLogin:!0}),l=await zt(e,{...t,config:o,apiKey:n});return H(l)?l:h(W({status:"verified",...o,...l.data?{mcp:l.data}:{}}),[`Logged in as ${o.email}.`,l.message??""].filter(Boolean).join(" "),e.json,t)}let i=p(e.method);if(!i&&!e.json)try{let o=await t.promptSelect("Choose how to sign in:",io);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=p(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:j(),body:JSON.stringify({email:l,method:"email",intent:"login"})});if(e.json)return h(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 h(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:j(),body:JSON.stringify({email:l,code:u,intent:"login"})});return await dt(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:j(),body:JSON.stringify({provider:i,mode:"login"})});return e.json?h(o,"Social login started.",!0,t):await Pn(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 Oe(t,n,{notifyLogin:!0}),s=await zt(e,{...t,config:r,apiKey:n});return H(s)?s:h(W({status:"verified",...r,...s.data?{mcp:s.data}:{}}),[`Logged in as ${r.email}.`,s.message??""].filter(Boolean).join(" "),e.json,t)}async function Ji(e,t){return await ri(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),await an(t.paths.configPath,{force:!0}),h({status:"logged_out"},"Logged out.",e.json,t)}async function so(e,t,n){let i=e[0]??"show";if(i==="show")return await R("/api/v1/profile",t,n,"Editable profile loaded.",{authenticated:!0});if(i==="update"){let r=await oo(t,n);if(H(r))return r;let s=await b(n,"/api/v1/profile",{method:"PATCH",headers:j(n.apiKey),body:JSON.stringify(r)});return h(s,"Profile updated.",t.json,n)}return k(`Unknown profile command "${i}".`,t.json)}async function oo(e,t){let n=q(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=x({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 ao(e,t,n){let i=e[0];if(i==="register")return await zi({...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 br(r,s,t,n,`Verified ${r}.`)}return i==="recover"?await uo(e.slice(1),t,n):i==="login"?await Wi(t,n):i==="logout"?await Ji(t,n):i==="status"?lo(t,n):i==="repair"?await co(t,n):k(`Unknown auth command "${i??""}".`,t.json)}function lo(e,t){let n=t.config?.baseUrl?ie(t.config.baseUrl):null,i=!!(t.apiKey&&n===t.baseUrl);return h({status:"auth_status",selectedBackend:ye(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 co(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=ie(t.config.baseUrl);return await D(t.paths.backendPreferencePath,{version:dn,preferredBaseUrl:n,savedAt:t.now()}),await Rn(t.paths.configPath,{...t.config,baseUrl:n,savedAt:t.now()},t),h({status:"auth_repaired",baseUrl:n,loggedIn:!0,email:t.config.email,role:t.config.role,credentialStorage:t.config.credentialStorage??"local_file_locked"},`Auth repaired for ${t.config.email}. Backend preference now matches ${n}.`,e.json,t)}async function uo(e,t,n){let i=e[0]??p(t.method)??"email",r=p(t.email);if(!r&&!t.json)try{r=await n.promptText("Enter your email address: ")}catch{return k("auth recover requires --email when interactive prompts are unavailable.",!1)}if(r=v(r,"auth recover requires --email."),i==="complete"){let c=p(t.code);if(!c&&!t.json)try{c=await n.promptText("Enter the recovery code: ")}catch{return k("auth recover complete requires --code when interactive prompts are unavailable.",!1)}return c=v(c,"auth recover complete requires --code."),await di(r,c,t,n)}let s=await b(n,"/api/v1/identity/recover/start",{method:"POST",headers:j(),body:JSON.stringify({email:r,method:i})}),o=sn(s);if(t.json)return h(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 h(o,`If this email can continue, instructions have been sent. Check your inbox and spam folder. When you have a code, run \`skills-layer auth recover complete --email ${r} --code <code>\`.`,!1,n)}return l?await di(r,l,t,n):h(o,`If this email can continue, instructions have been sent. When you have a code, run \`skills-layer auth recover complete --email ${r} --code <code>\`.`,!1,n)}async function di(e,t,n,i){let r=await b(i,"/api/v1/identity/recover/complete",{method:"POST",headers:j(),body:JSON.stringify({email:e,code:t})});if(n.json){let s=a(r,"apiKey");return s?(await Oe(i,s,{expectedEmail:e,knownEmail:a(r,"email")??e,knownRole:a(r,"role")??"user",knownRoles:se(r,"roles"),knownUserId:a(r,"userId")}),h(W({...r,loggedIn:!0}),"Recovery complete.",!0,i)):h(W({...r,email:e,loggedIn:!1}),"Recovery complete.",!0,i)}return await dt(e,r,n,i,`Recovered access for ${e}.`)}async function po(e,t,n){let i=e[0],r=1;if(i==="providers")return await R("/api/v1/identity/social/providers",t,n,"Identity providers loaded.");if(i==="start"){let s=p(t.provider);if(!s&&!t.json)try{s=await n.promptSelect("Choose identity provider:",gn)}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:j(n.apiKey),body:JSON.stringify({provider:s,mode:p(t.mode)??"login"})});return t.json?h(o,"Social auth started.",!0,n):await Pn(s,o,t,n,"login")}if(i==="status"){let s=p(t.state)??e[r];return s?await R(`/api/v1/identity/social/status/${encodeURIComponent(s)}`,t,n,"Social auth status loaded."):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:j(n.apiKey),body:JSON.stringify({provider:s,state:o,code:l})});return await Ul(c,n),h(W(c),"Social auth complete.",t.json,n)}if(i==="list")return await R("/api/v1/me/linked-identities",t,n,"Linked identities loaded.",{authenticated:!0});if(i==="unlink"){let s=v(t.provider??e[r],"identity unlink requires a provider."),o=await b(n,`/api/v1/me/linked-identities/${encodeURIComponent(s)}`,{method:"DELETE",headers:B(n.apiKey,n.authBlockedMessage)});return h(o,"Identity unlinked.",t.json,n)}return k(`Unknown identity command "${i??""}".`,t.json)}async function go(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 R("/api/v1/me/api-keys",t,n,"API keys loaded.",{authenticated:!0});if(i==="create"){let r=p(t.name),s=Ic(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",...B(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:r,scopes:s,...p(t.expires)?{expiresIn:p(t.expires)}:{}})});return h(W(o),"Automation API key created. The full key was sent to your verified email. Run `skills-layer api-key list` to manage keys.",t.json,n)}if(i==="rotate")return k(`api-key rotate is not part of normal login.
|
|
1121
|
+
skills-layer trust <skill-slug>`:`Unknown command "${e}".`}function fi(e){let t={json:!1,help:!1,dryRun:!1,list:!1,all:!1,verbose:!1,showUrl:!1,quarantine:!1,confirmed:!1,allowUnmanagedOnce:!1,discloseSource:!1,allowFindingsFeatured:!1,shouldTrigger:[],shouldNotTrigger:[],paraphrase:[],grantJson:[],findingCode:[],acceptCapability:[],approvalRequestId:[]},n=[];for(let i=0;i<e.length;i+=1){let r=e[i];if(!r)continue;if(r==="--"){n.push(...e.slice(i+1));break}if(r==="-h"){t.help=!0;continue}if(!r.startsWith("--")){n.push(r);continue}let s=r.slice(2);if(oo.has(s)){let a=Ut(s);s==="confirm"?t.confirmed=!0:t[a]=!0;continue}let o=e[i+1];if(!o||o.startsWith("--")){if(s==="install"){t.install="";continue}return{flags:t,positionals:n,error:`Flag --${s} requires a value.`}}if(ao.has(s)){let a=co(e,i);if(!a.value)return{flags:t,positionals:n,error:`Flag --${s} requires a value.`};t[Ut(s)]=a.value,i=a.nextIndex;continue}if(lo.has(s)||gi.has(s)){let a=Ut(s);if(gi.has(s)){let c=Array.isArray(t[a])?t[a]:[];c.push(o),t[a]=c}else t[a]=o;i+=1;continue}return{flags:t,positionals:n,error:`Unknown flag --${s}.`}}return{flags:t,positionals:n}}function co(e,t){let n=[],i=t;for(let r=t+1;r<e.length;r+=1){let s=e[r];if(!s||s.startsWith("--"))break;n.push(s),i=r}return{value:n.length>0?n.join(" "):null,nextIndex:i}}function Ut(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function Tt(e,t){let n=uo(t.env,t.platform),[i,r]=await Promise.all([Ac(n.configPath,t),Y(n.backendPreferencePath)]),s=ie(p(e.baseUrl)??X(t.env.SKILLS_LAYER_BASE_URL)??X(r?.preferredBaseUrl)??X(i?.baseUrl)??fn),o=p(e.apiKey)??X(t.env.SKILLS_LAYER_API_KEY),a=X(i?.apiKey),c=X(i?.baseUrl),u=!c||ie(c)===s,d=o??(u?a:void 0),g=!o&&a&&c&&!u?`Your saved login belongs to ${ie(c)}, but the selected backend is ${s}. Run \`skills-layer backend --base-url ${ie(c)}\` to use that login, or run \`skills-layer login\` for ${s}.`:void 0;return{...t,paths:n,config:i,baseUrl:s,apiKey:d,authBlockedMessage:g}}function uo(e,t){let n=t==="win32"?_e:pn,i=t==="win32"?X(e.USERPROFILE)??X(e.HOME):X(e.HOME),r=n.join(i??".",".skills-layer");return{stateDir:r,configPath:n.join(r,"config.json"),backendPreferencePath:n.join(r,"backend-preference.json"),installsPath:n.join(r,"installs.json"),importsPath:n.join(r,"imports.json"),mcpConfigPath:n.join(r,"mcp.json"),mcpPreferencePath:n.join(r,"mcp-preference.json"),bundlesDir:n.join(r,"bundles"),incidentsDir:n.join(r,"incidents")}}async function po(e,t,n){if(e[0]!=="list")return y(`Unknown agents command "${e[0]??""}".`,t.json);let i=me(n.env,n.platform,n.cwd).map(r=>({id:r.id,displayName:r.displayName,capabilities:r.capabilities,projectSkillsPath:r.targets.projectSkillsPath,globalSkillsPath:r.targets.globalSkillsPath}));return h({status:"ok",results:i},`Found ${i.length} supported agent targets.`,t.json,n)}async function go(e,t,n){let i=e[0],r=p(t.baseUrl);if(!i&&r||i==="cloud"||i==="local"){let c=ie(r??(i==="local"?so:fn)),u=ke(c),d=n.config?.baseUrl??null,g=!n.config?.baseUrl||ie(n.config.baseUrl)===c;return await D(n.paths.backendPreferencePath,{version:mn,preferredBaseUrl:c,savedAt:n.now()}),h({status:"updated",selectedBackend:u,selectedBaseUrl:c,savedLoginBaseUrl:d,loginMatchesSelectedBackend:g,loggedIn:!!n.apiKey&&g,...g?{}:{warning:`Saved login belongs to ${d}; selected backend is ${c}.`}},g?`Backend set to ${u}.`:`Backend set to ${u}. Saved login is for ${d}.`,t.json,n)}if(i&&i!=="status")return y(`Unknown backend command "${i}".`,t.json);let s=ke(n.baseUrl),o=!n.config?.baseUrl||ie(n.config.baseUrl)===n.baseUrl,a=!!n.apiKey&&o;return h({status:"ok",selectedBackend:s,selectedBaseUrl:n.baseUrl,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:o,loggedIn:a,email:a?n.config?.email??null:null,role:a?n.config?.role??null:null},`Backend: ${n.baseUrl}`,t.json,n)}var hn=[{value:"google",label:"Google",description:"Open browser sign-in and return here"},{value:"github",label:"GitHub",description:"Open browser sign-in and return here"},{value:"gitlab",label:"GitLab",description:"Open browser sign-in and return here"},{value:"microsoft",label:"Microsoft",description:"Open browser sign-in and return here"}],mo=[...hn,{value:"email",label:"Email code",description:"Use an emailed one-time code"},{value:"api_key",label:"API key (advanced)",description:"Paste an existing Skills Layer login key"}],fo=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...hn];async function er(e,t){let n=p(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",fo)}catch{return y("register requires --method when interactive selection is unavailable. Try `skills-layer register --method email --email you@example.com`, `skills-layer register --method google`, `skills-layer register --method github`, `skills-layer register --method gitlab`, or `skills-layer register --method microsoft`.",!1)}if(n==="email"){let r=p(e.email);if(!r&&!e.json)try{r=await t.promptText("Enter your email address: ")}catch{return y("register --method email requires --email when interactive prompts are unavailable.",!1)}r=b(r,"register requires --email.");let s=await v(t,"/api/v1/register",{method:"POST",headers:A(),body:JSON.stringify({method:n,email:r})});if(e.json){let a=s.status==="already_registered"?ln(s):W({...s,nextCommand:`skills-layer auth verify --email ${r} --code <code> --json`,nextAction:"auth.verify"}),c=s.status==="already_registered"?`${r} is already registered.`:`Registration started for ${r}.`;return h(a,c,e.json,t)}if(s.status==="already_registered")return h(ln(s),`${r} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,!1,t);let o;try{o=await t.promptText(`Enter the verification code sent to ${r} (check spam/junk folder if missing): `)}catch{return h(W(s),`Registration started for ${r}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${r} --code <code>\`.`,!1,t)}return await Ar(r,o,e,t,`Verified ${r}.`)}let i=await v(t,"/api/v1/identity/social/start",{method:"POST",headers:A(),body:JSON.stringify({provider:n,mode:"login"})});return e.json?h(i,"Social registration started.",e.json,t):await $n(n,i,e,t,"login")}async function tr(e,t){if(e.withMcp&&e.noMcp)return y("login cannot combine --with-mcp and --no-mcp.",e.json);let n=p(e.apiKey);if(n){let o=await Oe(t,n,{notifyLogin:!0}),a=await Zt(e,{...t,config:o,apiKey:n});return H(a)?a:h(W({status:"verified",...o,...a.data?{mcp:a.data}:{}}),[`Logged in as ${o.email}.`,a.message??""].filter(Boolean).join(" "),e.json,t)}let i=p(e.method);if(!i&&!e.json)try{let o=await t.promptSelect("Choose how to sign in:",mo);i=o==="api_key"?void 0:o}catch{return y("login requires --api-key or --method <email|google|github|gitlab|microsoft> when interactive selection is unavailable.",!1)}if(i){if(i==="email"){let a=p(e.email);!a&&!e.json&&(a=(await t.promptText("Enter your email address: ")).trim()),a=b(a,"login --method email requires --email.");let c=await v(t,"/api/v1/identity/recover/start",{method:"POST",headers:A(),body:JSON.stringify({email:a,method:"email",intent:"login"})});if(e.json)return h(c,`Passwordless email login started for ${a}.`,!0,t);let u;try{u=(await t.promptText(`Enter the sign-in code sent to ${a} (check spam/junk folder if missing): `)).trim()}catch{return h(c,`Passwordless email login started for ${a}. Check your email, then run \`skills-layer login --method email --email ${a}\` again when prompts are available.`,!1,t)}let d=await v(t,"/api/v1/identity/recover/complete",{method:"POST",headers:A(),body:JSON.stringify({email:a,code:u,intent:"login"})});return await gt(a,d,e,t,`Verified ${a}.`)}if(!["google","github","gitlab","microsoft"].includes(i))return y("login --method must be email, google, github, gitlab, or microsoft.",e.json);let o=await v(t,"/api/v1/identity/social/start",{method:"POST",headers:A(),body:JSON.stringify({provider:i,mode:"login"})});return e.json?h(o,"Social login started.",!0,t):await $n(i,o,e,t,"login")}if(!e.json)try{n=(await t.promptSecret("Enter your Skills Layer API key: ")).trim()}catch{return y("login requires an API key.",e.json)}if(!n)return y("login requires --api-key or --method <email|google|github|gitlab|microsoft>.",e.json);let r=await Oe(t,n,{notifyLogin:!0}),s=await Zt(e,{...t,config:r,apiKey:n});return H(s)?s:h(W({status:"verified",...r,...s.data?{mcp:s.data}:{}}),[`Logged in as ${r.email}.`,s.message??""].filter(Boolean).join(" "),e.json,t)}async function nr(e,t){return await ci(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),await un(t.paths.configPath,{force:!0}),h({status:"logged_out"},"Logged out.",e.json,t)}async function ho(e,t,n){let i=e[0]??"show";if(i==="show")return await R("/api/v1/profile",t,n,"Editable profile loaded.",{authenticated:!0});if(i==="update"){let r=await yo(t,n);if(H(r))return r;let s=await v(n,"/api/v1/profile",{method:"PATCH",headers:A(n.apiKey),body:JSON.stringify(r)});return h(s,"Profile updated.",t.json,n)}return y(`Unknown profile command "${i}".`,t.json)}async function yo(e,t){let n=G(e,["displayName","bio","company"]);if(Object.keys(n).length>0)return n;if(e.json)return y("profile update requires at least one of --display-name, --bio, or --company.",!0);try{let i=await t.promptText("Display name (leave blank to keep unchanged): "),r=await t.promptText("Bio (leave blank to keep unchanged): "),s=await t.promptText("Company (leave blank to keep unchanged): "),o=_({displayName:i||void 0,bio:r||void 0,company:s||void 0});return Object.keys(o).length===0?y("No profile changes entered.",!1):o}catch{return y("profile update requires at least one of --display-name, --bio, or --company.",!1)}}async function ko(e,t,n){let i=e[0];if(i==="register")return await er({...t,method:"email"},n);if(i==="verify"){let r=b(t.email,"auth verify requires --email."),s=b(t.code,"auth verify requires --code.");return await Ar(r,s,t,n,`Verified ${r}.`)}return i==="recover"?await vo(e.slice(1),t,n):i==="login"?await tr(t,n):i==="logout"?await nr(t,n):i==="status"?wo(t,n):i==="repair"?await bo(t,n):y(`Unknown auth command "${i??""}".`,t.json)}function wo(e,t){let n=t.config?.baseUrl?ie(t.config.baseUrl):null,i=!!(t.apiKey&&n===t.baseUrl);return h({status:"auth_status",selectedBackend:ke(t.baseUrl),selectedBaseUrl:t.baseUrl,loggedIn:i,requiresLogin:!i,...t.config?.email?{savedLogin:{baseUrl:n,email:t.config.email,role:t.config.role??null,roles:t.config.roles??[],savedAt:t.config.savedAt??null,...t.config.credentialStorage?{credentialStorage:t.config.credentialStorage}:{},matchesSelectedBackend:i}}:{}},i&&t.config?.email?`Logged in as ${t.config.email}.`:t.config?.baseUrl?`Saved login targets ${n}; selected backend is ${t.baseUrl}. Run \`skills-layer auth repair\` or \`skills-layer login\`.`:"Not logged in. Run `skills-layer login`.",e.json,t)}async function bo(e,t){if(!t.config?.baseUrl||!t.config.apiKey||!t.config.email||!t.config.role||!t.config.savedAt)return y("No saved Skills Layer login was found to repair. Run `skills-layer login`.",e.json);let n=ie(t.config.baseUrl);return await D(t.paths.backendPreferencePath,{version:mn,preferredBaseUrl:n,savedAt:t.now()}),await jn(t.paths.configPath,{...t.config,baseUrl:n,savedAt:t.now()},t),h({status:"auth_repaired",baseUrl:n,loggedIn:!0,email:t.config.email,role:t.config.role,credentialStorage:t.config.credentialStorage??"local_file_locked"},`Auth repaired for ${t.config.email}. Backend preference now matches ${n}.`,e.json,t)}async function vo(e,t,n){let i=e[0]??p(t.method)??"email",r=p(t.email);if(!r&&!t.json)try{r=await n.promptText("Enter your email address: ")}catch{return y("auth recover requires --email when interactive prompts are unavailable.",!1)}if(r=b(r,"auth recover requires --email."),i==="complete"){let c=p(t.code);if(!c&&!t.json)try{c=await n.promptText("Enter the recovery code: ")}catch{return y("auth recover complete requires --code when interactive prompts are unavailable.",!1)}return c=b(c,"auth recover complete requires --code."),await hi(r,c,t,n)}let s=await v(n,"/api/v1/identity/recover/start",{method:"POST",headers:A(),body:JSON.stringify({email:r,method:i})}),o=ln(s);if(t.json)return h(o,"Recovery started.",!0,n);let a="";try{a=(await n.promptText("Enter the recovery code if you received one, or press Enter to stop: ")).trim()}catch{return h(o,`If this email can continue, instructions have been sent. Check your inbox and spam folder. When you have a code, run \`skills-layer auth recover complete --email ${r} --code <code>\`.`,!1,n)}return a?await hi(r,a,t,n):h(o,`If this email can continue, instructions have been sent. When you have a code, run \`skills-layer auth recover complete --email ${r} --code <code>\`.`,!1,n)}async function hi(e,t,n,i){let r=await v(i,"/api/v1/identity/recover/complete",{method:"POST",headers:A(),body:JSON.stringify({email:e,code:t})});if(n.json){let s=l(r,"apiKey");return s?(await Oe(i,s,{expectedEmail:e,knownEmail:l(r,"email")??e,knownRole:l(r,"role")??"user",knownRoles:se(r,"roles"),knownUserId:l(r,"userId")}),h(W({...r,loggedIn:!0}),"Recovery complete.",!0,i)):h(W({...r,email:e,loggedIn:!1}),"Recovery complete.",!0,i)}return await gt(e,r,n,i,`Recovered access for ${e}.`)}async function So(e,t,n){let i=e[0],r=1;if(i==="providers")return await R("/api/v1/identity/social/providers",t,n,"Identity providers loaded.");if(i==="start"){let s=p(t.provider);if(!s&&!t.json)try{s=await n.promptSelect("Choose identity provider:",hn)}catch{return y("identity start requires --provider when interactive selection is unavailable.",!1)}s=b(s,"identity start requires --provider.");let o=await v(n,"/api/v1/identity/social/start",{method:"POST",headers:A(n.apiKey),body:JSON.stringify({provider:s,mode:p(t.mode)??"login"})});return t.json?h(o,"Social auth started.",!0,n):await $n(s,o,t,n,"login")}if(i==="status"){let s=p(t.state)??e[r];return s?await R(`/api/v1/identity/social/status/${encodeURIComponent(s)}`,t,n,"Social auth status loaded."):y("identity status requires --state.",t.json)}if(i==="complete"){let s=b(t.provider,"identity complete requires --provider."),o=b(t.state,"identity complete requires --state."),a=b(t.code,"identity complete requires --code."),c=await v(n,"/api/v1/identity/social/complete",{method:"POST",headers:A(n.apiKey),body:JSON.stringify({provider:s,state:o,code:a})});return await Dl(c,n),h(W(c),"Social auth complete.",t.json,n)}if(i==="list")return await R("/api/v1/me/linked-identities",t,n,"Linked identities loaded.",{authenticated:!0});if(i==="unlink"){let s=b(t.provider??e[r],"identity unlink requires a provider."),o=await v(n,`/api/v1/me/linked-identities/${encodeURIComponent(s)}`,{method:"DELETE",headers:M(n.apiKey,n.authBlockedMessage)});return h(o,"Identity unlinked.",t.json,n)}return y(`Unknown identity command "${i??""}".`,t.json)}async function Po(e,t,n){let i=e[0];if(!i)return y("api-key requires create, list, or revoke.",t.json);if(i==="list")return await R("/api/v1/me/api-keys",t,n,"API keys loaded.",{authenticated:!0});if(i==="create"){let r=p(t.name),s=Oc(t.scope);if(!r)return y("api-key create requires --name.",t.json);if(s.length===0)return y("api-key create requires at least one --scope.",t.json);let o=Eo("api-key.create",t.expires,t);if(o)return o;let a=await v(n,"/api/v1/me/api-keys",{method:"POST",headers:{"content-type":"application/json",...M(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:r,scopes:s,...p(t.expires)?{expiresIn:p(t.expires)}:{}})});return h(W(a),"Automation API key created. The full key was sent to your verified email. Run `skills-layer api-key list` to manage keys.",t.json,n)}if(i==="rotate")return y(`api-key rotate is not part of normal login.
|
|
1019
1122
|
|
|
1020
1123
|
For CLI access:
|
|
1021
1124
|
skills-layer login
|
|
@@ -1025,26 +1128,26 @@ For automation:
|
|
|
1025
1128
|
|
|
1026
1129
|
To remove an old key:
|
|
1027
1130
|
skills-layer api-key list
|
|
1028
|
-
skills-layer api-key revoke --key-id <key-id>`,t.json);if(i==="revoke"){let r=t.keyId??e[1];if(!r)return
|
|
1131
|
+
skills-layer api-key revoke --key-id <key-id>`,t.json);if(i==="revoke"){let r=t.keyId??e[1];if(!r)return y(`api-key revoke needs a key id.
|
|
1029
1132
|
|
|
1030
1133
|
Run:
|
|
1031
1134
|
skills-layer api-key list
|
|
1032
|
-
skills-layer api-key revoke --key-id <key-id>`,t.json);let s=String(r),o=await
|
|
1033
|
-
`);return`skills-layer-cli:mcp-token:${on("sha256").update(t).digest("base64url").slice(0,32)}`}async function zt(e,t){if(e.noMcp)return{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."};let n=await Y(t.paths.mcpConfigPath),i=n?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 Y(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 D(t.paths.mcpPreferencePath,{version:1,choice:"not_now",baseUrl:t.baseUrl,clientId:"codex",savedAt:t.now()}),{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."}}catch{return{}}if(!s)return{};let o=await mn(e,t);return H(o)?o:{data:o,message:"MCP configuration written for this machine. Open a fresh agent session so your AI tools can load it."}}async function vo(e,t,n){let i=e.join(" ").trim()||p(t.search)||"",r=new URLSearchParams;i&&r.set("query",i);let s=p(t.runtimeRisk);if(s&&!mi.includes(s))return fi("runtime-risk",s,mi,t);let o=p(t.limit);if(o){let c=Number(o);if(!Number.isInteger(c)||c<1||c>100)return fi("limit",o,["1-100"],t);r.set("limit",String(c))}M(r,"agent",t.agent),M(r,"capability",t.capability),M(r,"trust",t.trust),M(r,"runtime-risk",s),M(r,"security-capability",t.securityCapability);let l=await b(n,`/api/v1/search${oe(r)}`);if(t.install!==void 0){let c=p(t.install);if(!c){if(t.json)return k("search --install requires an explicit skill slug in the public CLI package.",!0);let d=Ve(l);if(d.length===0)return k("Search results do not include any installable skills. Run search again with a broader query.",!1);if(d.length===1)c=d[0].value;else try{c=await n.promptSelect("Select a search result to install:",d)}catch{return k("No search result was selected for install.",!1)}}let u=xc(l);return u.includes(c)?await fn([c],t,n):k(u.length===0?`Search results do not include "${c}". Run search again with a matching query first.`:`Search results do not include "${c}". Run search again with a matching query or choose one of: ${u.join(", ")}.`,t.json)}return h(l,"Search complete.",t.json,n)}var mi=["low","elevated","high"],Ut=["local","project","global","workspace"],Tt=["private","public","unlisted"],Bt=["private","public","unlisted"],bo=/^(?:card(?:_[A-Za-z0-9]+)*|pm_[A-Za-z0-9_]+)$/u;function Yi(e,t,n,i){let r=p(t);if(!r)return{};if(!/^\d+$/u.test(r))return{failure:C({status:"error",reasonCode:"invalid_limit",command:e,value:r,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be a whole number from 1 to ${n}.`,i.json,"invalid_limit")};let s=Number.parseInt(r,10);return!Number.isInteger(s)||s<1||s>n?{failure:C({status:"error",reasonCode:"invalid_limit",command:e,value:r,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be between 1 and ${n}.`,i.json,"invalid_limit")}:{value:String(s)}}function fi(e,t,n,i){return C({status:"error",reasonCode:"invalid_search_filter",filter:e,value:t,acceptedValues:n,nextAction:"search",nextStep:e==="runtime-risk"?"Use --runtime-risk low, elevated, or high.":"Use --limit with a whole number from 1 to 100."},e==="runtime-risk"?`Invalid runtime risk "${t}". Use one of: ${n.join(", ")}.`:`Invalid search limit "${t}". Use a whole number from 1 to 100.`,i.json,"invalid_search_filter")}function Zi(e,t){let n=p(t.scope);if(n&&!Ut.includes(n))return{failure:C({status:"error",reasonCode:"invalid_install_filter",filter:"scope",value:n,acceptedValues:Ut,nextAction:e,nextStep:"Use --scope local, project, global, or workspace."},`Invalid ${e} --scope "${n}". Use one of: ${Ut.join(", ")}.`,t.json,"invalid_install_filter")};let i=p(t.agent);return i&&!st(i)?{failure:C({status:"error",reasonCode:"unknown_agent",filter:"agent",value:i,acceptedValues:we,nextAction:e,nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown ${e} --agent "${i}". Run \`skills-layer agents\` to inspect supported agents.`,t.json,"unknown_agent")}:{scope:n,agent:i}}function So(e,t,n){return C({status:"error",reasonCode:"invalid_version",command:e,version:t,nextAction:e,nextStep:"Use a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --version "${t}". Use a semver version or an external-<digest> version.`,n.json,"invalid_version")}function Po(e){let t=p(e.paymentMethod)??"card";return bo.test(t)?{value:t}:{failure:C({status:"error",reasonCode:"invalid_payment_method",paymentMethod:t,acceptedValues:["card","card_<test-card>","pm_<provider-method-id>"],nextAction:"buy",nextStep:"Use --payment-method card or a provider token such as pm_<id>."},`Invalid payment method "${t}". Use card or a provider token such as pm_<id>.`,e.json,"invalid_payment_method")}}async function Co(e,t,n){let i=new URLSearchParams,r=Yi(e,t.limit,20,t);return r.failure?r.failure:(M(i,"limit",r.value),M(i,"search",t.search),M(i,"sort",t.sort),await R(`/api/v1/${e}${oe(i)}`,t,n,`${ht(e)} skills loaded.`))}async function Ro(e,t,n){let i=e.join(" ").trim();if(!i)return k("recommend requires a task.",t.json);let r=Yi("recommend",t.limit,20,t);if(r.failure)return r.failure;let s=new URLSearchParams({task:i});return M(s,"limit",r.value),await R(`/api/v1/recommend?${s.toString()}`,t,n,"Recommendations loaded.")}async function xo(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?h(r,"Comparison loaded.",!0,n):{exitCode:0,stdout:Kl(r,"Comparison loaded.",Z(n),t.verbose),stderr:""}}async function $o(e,t,n){let i=v(e[0],"show requires a skill slug."),r=await b(n,`/api/v1/skills/${encodeURIComponent(i)}`);return h(wa(r),"Skill loaded.",t.json,n)}async function _o(e,t,n){let i=v(e[0],"trust requires a skill slug."),r=new URLSearchParams;M(r,"format",t.format),M(r,"version",t.version);let s=await b(n,`/api/v1/skills/${encodeURIComponent(i)}/trust${oe(r)}`);return p(t.format)?.toLowerCase()==="sarif"&&!t.json?{exitCode:0,stdout:va(s,i,n),stderr:""}:h(s,"Trust report loaded.",t.json,n)}async function Io(e,t,n){let i=et(e[0],e[1]);if(i)return Nt(i,[e[0],e[1]].filter(Boolean).join(" "),t,n);let r=e[0];if(!r)return{exitCode:0,stdout:Te,stderr:""};if(r==="full")return Nt(Te,"full",t,n);if(r==="topic"){let s=et(e[1]);if(s)return Nt(s,e[1]??"overview",t,n);let o=new URLSearchParams;return e[1]&&o.set("topic",e[1]),await R(`/api/v1/help${oe(o)}`,t,n,"Help topic loaded.")}if(r==="standards")return await R("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let s=await b(n,"/api/v1/marketplace/status");return t.json?h(s,"Marketplace status loaded.",!0,n):h(Wl(s),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let s=await b(n,"/api/v1/capabilities");return h(Yl(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=Zl(t.maxCharacters,t.json);if(H(o))return o;let l=await b(n,"/api/v1/optimize-tokens",{method:"POST",headers:j(n.apiKey),body:JSON.stringify({text:s,...o?{maxCharacters:o}:{}})});return h(l,"Token optimization complete.",t.json,n)}return k(`Unknown help command "${r}".`,t.json)}function Nt(e,t,n,i){return n.json?h({status:"ok",topic:t,content:e},"Help topic loaded.",!0,i):{exitCode:0,stdout:e,stderr:""}}async function jo(e,t,n){let i=v(e[0]??t.path,"validate requires a file or directory."),s={files:await gt(J(n.cwd,i)),sourceIntakeContext:p(t.sourceIntakeContext),publicationStatus:p(t.publicationStatus),dependencyAuditStatus:p(t.dependencyAuditStatus),category:p(t.category),discloseSource:!!t.discloseSource,allowFindingsFeatured:!!t.allowFindingsFeatured},o;try{o=await b(n,"/api/v1/validation/preview",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(x(s))})}catch(l){if(l instanceof A&&l.status===422&&l.details)o=_c(l.details);else throw l}return t.json?h(o,"Validation complete.",!0,n):{exitCode:0,stdout:Ql(o,i,n),stderr:""}}async function Ao(e,t,n){let i=v(e[0]??t.path,"preview-trigger requires a file or directory."),r=await gt(J(n.cwd,i)),s=await b(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:j(n.apiKey),body:JSON.stringify({files:r,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?h(s,"Trigger preview complete.",!0,n):{exitCode:0,stdout:Xl(s,i,n),stderr:""}}async function Lo(e,t,n){let i=e[0];if(i==="init")return await Eo(e.slice(1),t,n);if(i==="rules")return await R("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(i==="submissions")return await R("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(i==="status"){let r=v(e[1],"creator status requires a skill slug.");try{return await R(`/api/v1/me/submissions/${encodeURIComponent(r)}/status`,t,n,"Submission status loaded.",{authenticated:!0})}catch(s){if(s instanceof A&&s.status===404)return Fo(r,t);throw s}}if(i==="charge-status"){let r=v(e[1],"creator charge-status requires a charge id.");return await R(`/api/v1/me/private-skill-charges/${encodeURIComponent(r)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(i==="submit")return await hi(e.slice(1),t,n,!1);if(i==="submit-version")return await hi(e.slice(1),t,n,!0);if(i==="check-slug"){let r=v(e[1],"creator check-slug requires a slug.");return await Mo(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 Fe(`/api/v1/me/submissions/${encodeURIComponent(r)}/slug`,{nextSkillSlug:s},t,n,"Skill renamed.")}if(i==="pricing")return await Go(e,t,n);if(i==="update-listing"){let r=v(e[1],"creator update-listing requires a skill slug.");return await Vo(r,t,n)}if(i==="visibility"){let r=v(e[1],"creator visibility requires a skill slug."),s=p(t.visibility)??e[2],o=Rt(s);if(!o||!Tt.includes(o))return C({status:"error",reasonCode:"invalid_visibility",skillSlug:r,visibility:s??null,acceptedValues:Tt,nextAction:"creator.visibility",nextStep:"Use --visibility private, public, or unlisted."},`Invalid creator visibility "${s??""}". Use one of: ${Tt.join(", ")}.`,t.json,"invalid_visibility");let l=await b(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/visibility`,{method:"PATCH",headers:j(n.apiKey),body:JSON.stringify(x({visibility:o,dryRun:t.dryRun}))});return Ua(l)?C(l,Ta(l,r),t.json,a(l,"reasonCode")??a(l,"status")):h(l,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;M(s,"format",t.format),M(s,"version",t.version),M(s,"versionId",t.versionId);let o=await b(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust${oe(s)}`,{headers:B(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?h(o,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:mc(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:j(n.apiKey),body:JSON.stringify(x(q(t,["version","versionId"])))});return t.json?h(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:fc(s,r,n),stderr:""}}if(i==="provenance"){let r=v(e[1],"creator provenance requires a skill slug.");return await R(`/api/v1/me/submissions/${encodeURIComponent(r)}/provenance`,t,n,"Provenance loaded.",{authenticated:!0})}if(i==="claim"||i==="verify"||i==="dispute")return await Do(i,e,t,n);if(i==="issues"||i==="reviews"||i==="update-issue"||i==="moderate-review")return await Zo(i,e,t,n);if(i==="analytics"){let r=v(e[1],"creator analytics requires a skill slug.");return await Ho(r,t,n)}return i==="earnings"?await R("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0}):i==="payout-profile"?await zo(t,n):i==="payout-link"?await Wo(t,n):i==="payouts"?await R("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0}):i==="withdraw"?await K("/api/v1/me/payouts/withdrawals",q(t,["amountCents","reason"]),t,n,"Withdrawal requested."):i==="source"?await Qo(e.slice(1),t,n):k(`Unknown creator command "${i??""}".`,t.json)}async function Eo(e,t,n){let i=p(t.skill)??e[0]??"my-skill",r=J(n.cwd,p(t.dir)??i),s=L(r,"SKILL.md"),o;try{o=Yn(p(t.type))}catch(f){return k(ae(f),t.json)}let l=p(t.category),c=await Uo(r);if((await me(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 Ke(r,{recursive:!0});let d=Zn({skillSlug:i,description:p(t.description)??"Describe what this skill helps an agent do.",skillType:o,category:l});for(let f of d)await re(L(r,f.path),f.content);let g=x({status:"created",path:s,skillSlug:i,skillType:o,category:l,fileCount:d.length});return t.json?h(g,`Created ${s}.`,!0,n):{exitCode:0,stdout:oc(g,r,s,n),stderr:""}}async function me(e){try{return await Ki(e),!0}catch{return!1}}async function Uo(e){try{return(await Vi(e)).length>0}catch{return await me(e)}}async function hi(e,t,n,i){let r=i?v(p(t.skill)??e[0],"creator submit-version requires a skill slug."):p(t.skill),s=v(p(t.source)??(i?e[1]:e[0])??t.path,`creator ${i?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),o=await ut(s,n.cwd);if(t.list)return await To(s,o,r,t,n);if(p(t.source)&&!o&&Br(s))return Bo(s,t);let l=o?.files??await gt(J(n.cwd,s));if(!i&&!t.dryRun){let m=await No(l,t,n);if(m)return m}let c=x({files:l,version:p(t.version),dryRun:t.dryRun,allowFindingsFeatured:t.allowFindingsFeatured,pricing:p(t.priceCents)?{priceCents:Number(p(t.priceCents))}:void 0,...o?{sourceMetadata:o.sourceMetadata}:{},...q(t,["displayName","skillType","category","visibility","source","skill"])}),u=i&&r?`/api/v1/me/submissions/${encodeURIComponent(r)}/versions`:"/api/v1/me/submissions",d=await b(n,u,{method:"POST",headers:j(n.apiKey),body:JSON.stringify(c)});if(t.json||d.status!=="checkout_required"||typeof d.checkoutUrl!="string"||typeof d.chargeId!="string")return h(d,i?"Version submitted.":"Submission uploaded.",t.json,n);n.emitInfo("Opening payment setup for skill submission. Complete the payment in your browser, then come back here."),await n.openUrl(d.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${d.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let f=await xl(d.chargeId,n);return H(f)?f:f.status!=="submitted"?h({...d,chargeStatus:f.status},`Payment is still ${f.status}. You can rerun \`skills-layer creator charge-status ${d.chargeId}\` to continue tracking it.`,t.json,n):h(f,i?"Version submitted.":"Submission uploaded.",t.json,n)}async function To(e,t,n,i,r){if(t)return h(yi(er(e,t,n)),"Source skills loaded.",i.json,r);let s=await Be(r,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},i);return s.kind==="failure"?s.result:h(yi(s.inspection),"Source skills loaded.",i.json,r)}function yi(e){return{...e,sourceSubmissionSupported:!0}}function Bo(e,t){let i=`skills-layer source connection start --provider ${sr(e)} --source ${e} --visibility private --provenance-intent private_source_import`;return C({status:"source_connection_required",reasonCode:"source_connection_required",source:e,nextAction:"source.connection.start",nextStep:i},`Creator submit can list ${e} safely, but publishing from a remote source requires a source connection. Run \`${i}\`.`,t.json,"source_connection_required")}async function No(e,t,n){let i=p(t.skill)??qo(e);if(!i)return null;let r;try{r=await b(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(i)}`,{headers:B(n.apiKey,n.authBlockedMessage)})}catch(s){if(s instanceof A&&s.status===404)return Qi(i,t);throw s}if(r.available===!1||a(r,"reasonCode")==="unavailable"||a(r,"reasonCode")==="reserved"){let s=a(r,"assignedSlug"),o=x({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 C(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 Mo(e,t,n){try{let i=await b(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:B(n.apiKey,n.authBlockedMessage)});return h(Oo(i),"Slug status loaded.",t.json,n)}catch(i){if(i instanceof A&&i.status===404)return Qi(e,t);throw i}}function Qi(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 C(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 Oo(e){let t=e.available===!0,n=a(e,"assignedSlug");if(t)return x({requestedSlug:a(e,"requestedSlug"),available:!0,reasonCode:a(e,"reasonCode")??"available",assignedSlug:n});let i=S(e,"slugAssignment"),r=Array.isArray(i?.candidateSlugs)?i.candidateSlugs.filter(s=>typeof s=="string").slice(0,5):void 0;return x({...e,...i?{slugAssignment:{...i,...r?{candidateSlugs:r}:{}}}:{},...r?{candidateSlugs:r}:{}})}function Fo(e,t){return C({status:"not_submitted",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submit",nextStep:"Run `skills-layer creator submit <path> --dry-run` to validate a local skill before submitting it, or run `skills-layer creator submissions` to see your existing submissions."},`No creator submission was found for ${e}. Run \`skills-layer creator submit <path> --dry-run\` before checking status.`,t.json,"creator_submission_not_found")}function qo(e){let t=e.find(i=>i.path.split("/").pop()?.toLowerCase()==="skill.md");if(!t)return;let n=/^---\s*\n(?<body>[\s\S]*?)\n---/u.exec(t.content??"")?.groups?.body?.split(/\r?\n/u).map(i=>i.match(/^name\s*:\s*(?<name>.+?)\s*$/u)?.groups?.name?.trim().replace(/^["']|["']$/gu,"")).find(i=>!!i);return Ko(n??G(ee(t.path)))}function Ko(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function Go(e,t,n){let i=v(e[1],"creator pricing requires a skill slug."),r=new URLSearchParams;if(M(r,"version",t.version),!t.priceCents)return await R(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${oe(r)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=Number(p(t.priceCents)),o=await b(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${oe(r)}`,{headers:B(n.apiKey,n.authBlockedMessage)}),l=F(o,"priceCents")??0;if(s>l){let c=x({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 h(c,"Pricing change requires approval before it can affect buyers.",t.json,n)}return await Fe(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing`,{priceCents:s,version:p(t.version)},t,n,"Pricing updated.")}async function Vo(e,t,n){try{return await Fe(`/api/v1/me/submissions/${encodeURIComponent(e)}`,q(t,["displayName","summary","description","category","skillType","license","listingStatus"]),t,n,"Listing updated.")}catch(i){if(i instanceof A&&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 C(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 Do(e,t,n,i){let r=v(t[1],`creator ${e} requires a skill slug.`);try{if(e==="claim")return await K(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/claim`,q(n,["requestedRole","message"]),n,i,"Ownership claim submitted.");if(e==="verify"){let s=v(n.claimId,"creator verify requires --claim-id.");return await K(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/verify`,{claimId:s},n,i,"Ownership claim verified.")}return await K(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/dispute`,q(n,["message"]),n,i,"Ownership dispute submitted.")}catch(s){if(s instanceof A&&s.status===404){let o={status:"ownership_action_unavailable",reasonCode:e==="claim"?"skill_not_found_or_not_claimable":"ownership_claim_not_found",skillSlug:r,requestedRole:p(n.requestedRole),nextAction:e==="claim"?"search":"creator.claim",nextStep:e==="claim"?`Run \`skills-layer search ${r}\`, \`skills-layer show ${r}\`, or submit/source-install the skill before claiming it.`:`Run \`skills-layer creator claim ${r}\` to start a new claim if the skill is claimable.`};return C(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 Ho(e,t,n){try{return await R(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(i){if(i instanceof A&&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 C(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 zo(e,t){let n=await b(t,"/api/v1/me/payout-profile",{headers:B(t.apiKey,t.authBlockedMessage)});return h(n,"Creator payout profile loaded.",e.json,t)}async function Wo(e,t){let n=Jo(p(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:j(t.apiKey),body:JSON.stringify(n?{mode:n}:{})})}catch(s){if(s instanceof A&&Yo(s))return C({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=$l(i);return r&&!e.json&&e.showUrl!==!0&&(t.emitInfo("Opening payout setup in your browser. Finish the flow there, then come back here."),await t.openUrl(r)||t.emitInfo(`Open this payout setup URL manually to continue: ${r}`)),h(i,"Payout setup link created.",e.json,t)}function Jo(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 Yo(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 Zo(e,t,n,i){let r=v(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await R(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await R(`/api/v1/me/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 Fe(`/api/v1/me/library/${encodeURIComponent(r)}/issues/${encodeURIComponent(o)}`,q(n,["status","fixedVersion","note"]),n,i,"Issue updated.")}let s=v(n.reviewId,"creator moderate-review requires --review-id.");return await Fe(`/api/v1/me/library/${encodeURIComponent(r)}/reviews/${encodeURIComponent(s)}`,q(n,["status","reason"]),n,i,"Review updated.")}async function Qo(e,t,n){let i=e[0],r=v(e[1],`creator source ${i??""} requires a source connection id.`),s=p(t.skill)??e[2];if(i==="prepare")return await K(`/api/v1/me/source-connections/${encodeURIComponent(r)}/prepare`,x({...q(t,["skill","source","version","displayName","skillType","category","priceCents","visibility"]),source:p(t.source)??e[2]}),t,n,"Source release prepared.");if(i==="publish-request"){let o=t.approvalRequestId.length>0?t.approvalRequestId:p(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await K(`/api/v1/me/source-connections/${encodeURIComponent(r)}/publish-request`,x({skillSlug:s,approvalRequestIds:o,version:p(t.version),...q(t,["visibility","priceCents","license","discloseSource"])}),t,n,"Source publish requested.")}if(i==="release-status"){let o=new URLSearchParams;return s&&o.set("skill",s),await R(`/api/v1/me/source-connections/${encodeURIComponent(r)}/release-status${oe(o)}`,t,n,"Source release status loaded.",{authenticated:!0})}return k(`Unknown creator source command "${i??""}".`,t.json)}async function fn(e,t,n){let i=p(t.source);if(i){let c=p(t.skill),u=await ut(i,n.cwd);if(u)return await ki(i,u,c,t,n);let d=t.list||t.dryRun||!c&&!t.json&&!t.all,g=await Be(n,i,{source:i,skillSlug:c,listOnly:d},t);if(g.kind==="failure")return g.result;let f=g.inspection;if(t.list)return h(f,"Source skills loaded.",t.json,n);let m=Yt(i,f,t);if(m)return m;let y=await Wt({source:i,inspection:f,requestedSkillSlug:c,mode:"install",flags:t,backend:n});if(y.kind==="failure")return y.result;if(t.dryRun)return h(Jt(i,f,y.skillSlug,t),"Source install preview ready.",t.json,n);let w=wi(t,n),P;try{P=await b(n,w,{method:"POST",headers:vi(t,n),body:JSON.stringify(Si({source:i},y.skillSlug,t))})}catch(N){if(N instanceof A)return Pi(i,N,t);throw N}let _=await Ft(n,P);return await at(n,_,y.skillSlug??a(_,"skillSlug")??i),ot(_,bi(t),t.json,n)}let r=v(e[0]??t.install,"install requires a skill slug or --source.");if(Br(r)){let c=await ut(r,n.cwd);if(c)return await ki(r,c,p(t.skill),t,n);let u=p(t.skill),d;if(t.list){let y=await Be(n,r,{source:r,listOnly:!0},t);return y.kind==="failure"?y.result:h(y.inspection,"Source skills loaded.",t.json,n)}if(!u&&!t.json&&!t.all){let y=await Be(n,r,{source:r,listOnly:!0},t);if(y.kind==="failure")return y.result;let w=y.inspection;d=w;let P=Yt(r,w,t);if(P)return P;let _=await Wt({source:r,inspection:w,requestedSkillSlug:u,mode:"install",flags:t,backend:n});if(_.kind==="failure")return _.result;u=_.skillSlug}if(t.dryRun){if(!d){let y=await Be(n,r,{source:r,listOnly:!0},t);if(y.kind==="failure")return y.result;d=y.inspection}return h(Jt(r,d,u,t),"Source install preview ready.",t.json,n)}let g=wi(t,n),f;try{f=await b(n,g,{method:"POST",headers:vi(t,n),body:JSON.stringify(Si({source:r},u,t))})}catch(y){if(y instanceof A)return Pi(r,y,t);throw y}let m=await Ft(n,f);return await at(n,m,u??a(m,"skillSlug")??G(r)),ot(m,bi(t),t.json,n)}if(p(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:j(n.apiKey),body:JSON.stringify(x({skillSlug:r,version:p(t.version),dryRun:t.dryRun}))});return t.dryRun?or(u,"Workspace install preview ready.",t,n):h(u,"Workspace deployment requested.",t.json,n)}let s=await b(n,"/api/v1/install",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(x({skillSlug:r,version:p(t.version),scope:p(t.scope),agent:p(t.agent),dryRun:t.dryRun}))});if(t.dryRun)return await fa(s,t,n);let o=await Ft(n,s),l=await Xo(n,o,r,t);return H(l)?l:(await at(n,l,r),ot(l,"Skill installed.",t.json,n))}async function Xo(e,t,n,i){if(Array.isArray(t.materializedWrites)&&t.materializedWrites.length>0)return t;let r=ea(e,t,n,i);if(r.status==="skip")return t;if(r.status==="failure")return C({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:r.skillSlug,nextStep:r.nextStep},r.message,i.json,"materialization_target_invalid");let s=await ta(e,t,r.skillSlug,r.version),o=await Xi({backend:e,exportResult:s,flags:i,skillSlug:r.skillSlug});if(H(o))return o;let l=await sa({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,...na(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 ea(e,t,n,i){let r=S(t,"materializationPlan")??S(t,"installPlan"),s=p(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=p(i.agent)??a(t,"agent")??a(t,"targetAgent")??(r?a(r,"agent")??a(r,"targetAgent"):void 0)??X(e.config?.lastSelectedAgent)??"codex",c=ge(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 ta(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${oe(r)}`,{headers:B(e.apiKey,e.authBlockedMessage)})}function na(e){return x({version:a(e,"version"),storageKey:a(e,"storageKey"),expiresAt:a(e,"expiresAt")})}async function Xi(e){let t=a(e.exportResult,"downloadUrl");if(!t)return C({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(ia(e.backend.baseUrl,t));if(!n.ok)throw new A(n.status,`Unable to download exported bundle (${n.status}).`);let i=new Uint8Array(await n.arrayBuffer()),r=ra(i),s=a(e.exportResult,"archiveSha256")??n.headers.get("x-skills-layer-archive-sha256")?.trim()??void 0;return s&&r.archiveSha256!==s?C({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?C({status:"download_integrity_failed",reasonCode:"download_bundle_empty",skillSlug:e.skillSlug,archiveHashFormat:r.format,nextStep:"Retry after the catalog artifact is refreshed."},`Downloaded ${e.skillSlug} did not contain any skill files.`,e.flags.json,"download_bundle_empty"):{status:"ok",bytes:i,files:r.files,archiveSha256:r.archiveSha256,archiveBytesSha256:r.archiveBytesSha256,archiveHashFormat:r.format}}function ia(e,t){return/^https?:\/\//iu.test(t)?t:`${ie(e)}${t.startsWith("/")?"":"/"}${t}`}function ra(e){let t=on("sha256").update(e).digest("hex"),n=Vn(e);return n?{archiveSha256:Dn(n),archiveBytesSha256:t,format:"bundle_archive",files:n}:{archiveSha256:t,archiveBytesSha256:t,format:"raw",files:[]}}async function sa(e){let t=e.backend.platform==="win32"?xe:cn,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 rn(n,e.bytes),await an(i,{recursive:!0,force:!0}),await rn(r,e.bytes),s.push({path:lt(e.backend.cwd,r),bytes:e.bytes.byteLength});for(let o of e.files){let l=t.join(i,...oa(o.path)),c=o.content??"";if(await re(l,c),s.push({path:lt(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 oa(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 ki(e,t,n,i,r){let s=p(i.visibility)??"private";if(s!=="private")return C({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=er(e,t,n);if(i.list)return h(o,"Local source skills loaded.",i.json,r);let l=Yt(e,o,i);if(l)return l;let c=await Wt({source:e,inspection:o,requestedSkillSlug:n,mode:"install",flags:i,backend:r});if(c.kind==="failure")return c.result;let u=c.skillSlug??Ve(o)[0]?.value??nr(e);if(i.dryRun)return h({...Jt(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",...B(r.apiKey,r.authBlockedMessage)},body:JSON.stringify(x({files:t.files,version:p(i.version),visibility:"private",category:p(i.category),displayName:p(i.displayName),skillType:p(i.skillType),sourceMetadata:t.sourceMetadata}))}),g=await ca({backend:r,source:e,upload:t,skillSlug:a(d,"skillSlug")??u,flags:i,submitted:d});return await at(r,g,u),ot(g,"Private Cloud skill installed.",i.json,r)}function er(e,t,n){let i=aa(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 aa(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=ee(t.path).replaceAll("\\","/"),i=n==="."?".":n,r=tr(t.content??"")??nr(i==="."?t.path:i),s=la(t.content??"");return{skillSlug:r,name:r,...s?{description:s}:{},relativeSkillRoot:i,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function tr(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function la(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function nr(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 ca(e){let t=ua(e.backend,e.flags);if(t.status==="failure")throw new Error(t.message);let n=e.upload.files.map(r=>({path:L(t.skillsPath,e.skillSlug,Pr(r.path)),content:r.content??""})),i=[];for(let r of n)if(await re(r.path,r.content),i.push({path:lt(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")??p(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")??p(e.flags.version)??"private",scope:t.scope,agent:t.agent,visibility:"private",publicationStatus:"private",catalogRecord:"private",privacy:{publication:"private",catalogRecord:"private",message:"This local install was saved as a private Cloud skill and did not create a public catalog record."},materializationPlan:{scope:t.scope,agent:t.agent},materializedWrites:i}}function ua(e,t){let n=p(t.scope)??"project";if(!["local","project","global"].includes(n))return{status:"failure",message:"Local private installs support --scope local, project, or global. Use `skills-layer creator submit <path> --visibility private` for private creator workflows."};let i=p(t.agent)??X(e.config?.lastSelectedAgent)??"codex",r=ge(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 lt(e,t){let n=Me(e,t);return n&&!n.startsWith("..")&&!xe.isAbsolute(n)?n.split("\\").join("/"):t}function hn(e){return p(e.visibility)==="public"?"public":"private"}function wi(e,t){return hn(e)==="public"&&!t.apiKey?"/api/v1/source-imports":"/api/v1/me/source-installs"}function vi(e,t){return{"content-type":"application/json",...hn(e)==="private"?B(t.apiKey,t.authBlockedMessage):He(t.apiKey)}}function bi(e){return hn(e)==="public"?"Public source install planned.":"Private source skill installed."}async function Wt(e){if(e.requestedSkillSlug||e.flags.json||e.flags.all)return{kind:"selected",skillSlug:e.requestedSkillSlug};let t=Ve(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 Ve(e){let t=[e.results,e.skills,e.discoveredSkills,S(e,"source")?.results,S(e,"inspection")?.results],n=new Set,i=[];for(let r of t)if(Array.isArray(r))for(let s of r){let o=da(s);!o||n.has(o.value)||(n.add(o.value),i.push(o))}return i}function da(e){if(!$(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=S(e,"parsedSkill"),s=S(e,"frontmatter")??(r?S(r,"frontmatter"):void 0),o=a(e,"shortDescription")??a(e,"summary")??a(e,"description")??(s?a(s,"description"):void 0)??a(e,"relativeSkillRoot")??a(e,"path")??a(e,"discoveryRoute")??a(e,"sourceKind");return o?{value:t,label:i,description:o}:{value:t,label:i}}function Si(e,t,n){return x({...e,skillSlug:t,scope:p(n.scope),agent:p(n.agent),workspace:p(n.workspace),version:p(n.version),visibility:p(n.visibility)??"private",category:p(n.category),displayName:p(n.displayName),skillType:p(n.skillType),all:n.all,quarantine:n.quarantine,acceptCapability:n.acceptCapability})}function Jt(e,t,n,i){return x({status:"dry_run",source:e,selectedSkillSlug:n,all:i.all,scope:p(i.scope)??"local",agent:p(i.agent),workspace:p(i.workspace),quarantine:i.quarantine,acceptCapability:i.acceptCapability,candidates:Ve(t).map(r=>({skillSlug:r.value,name:r.label,description:r.description})),nextStep:i.all?`Re-run without --dry-run to install every discovered skill from ${e}.`:`Re-run without --dry-run${n?"":" and add --skill <skill-slug> if needed"} to install from ${e}.`})}async function Be(e,t,n,i){try{return{kind:"ok",inspection:await b(e,"/api/v1/source-inspect",{method:"POST",headers:j(e.apiKey),body:JSON.stringify(x(n))})}}catch(r){if(r instanceof A)return{kind:"failure",result:ga(t,r,i)};throw r}}function Yt(e,t,n){if(Ve(t).length>0)return null;let r=pa(t);return C({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."},ma(e,r),n.json)}function pa(e){return(Array.isArray(e.issues)?e.issues:[]).filter($).map(n=>({...a(n,"code")?{code:a(n,"code")}:{},...a(n,"message")?{message:a(n,"message")}:{},...a(n,"path")?{path:a(n,"path")}:{}}))}function ga(e,t,n){let i=t.details??{},r=a(i,"error")??t.message;if(ir(t.status,r))return rr(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return mt(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 C(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 Pi(e,t,n){let i=t.details??{},r=a(i,"error")??t.message;if(ir(t.status,r))return rr(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return mt(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 C(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 ir(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function rr(e,t,n,i){let r=t.details??{},s=a(r,"error")??t.message,l=`skills-layer source connection start --provider ${sr(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 C(c,`Cloud could not ${i} ${e} directly. If this is a private source, start a private source connection first:
|
|
1034
|
-
${
|
|
1035
|
-
`)}async function
|
|
1036
|
-
`)}function
|
|
1037
|
-
`)}function
|
|
1038
|
-
`)}function
|
|
1039
|
-
`)):(e.results.slice(0,
|
|
1040
|
-
`))}function
|
|
1041
|
-
`)}function
|
|
1042
|
-
`)}function
|
|
1043
|
-
Next step: ${o}`}async function Ba(e,t,n){let i=await ke(n),r=e[0];if(!r){let l=Object.values(i.installs);return h({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 C({status:"missing_record",reasonCode:"restore_record_not_found",skillSlug:r,record:null,nextAction:"installed",nextStep:`Run \`skills-layer installed\` to see local records, \`skills-layer sync\` to refresh status, or \`skills-layer search ${r}\` if you want to find a catalog/source replacement.`},`No restorable local install record was found for ${r}. Run \`skills-layer installed\`, \`skills-layer sync\`, or \`skills-layer search ${r}\` next.`,t.json,"restore_record_not_found");let o={status:"restored",skillSlug:r,record:s};return t.json?h(o,`Restore checked for ${r}.`,!0,n):{exitCode:0,stdout:Ea(r,s,n),stderr:""}}async function Na(e,t,n){let i=v(e[0],"check requires a skill slug.");return await R(`/api/v1/skills/${encodeURIComponent(i)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function Ma(e,t,n){let i=v(e[0]??t.source,"import requires a source."),r=await ut(i,n.cwd);if(!r){let o=Oa(i,t);if(o)return o}let s=await b(n,"/api/v1/source-imports",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(x({...r??{source:i},quarantine:t.quarantine,skillSlug:p(t.skill),visibility:p(t.visibility)}))});return await D(n.paths.importsPath,{version:1,lastImport:s,savedAt:n.now()}),h(s,"Source import submitted.",t.json,n)}function Oa(e,t){try{return Ct(e).kind!=="local"?null:C({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:Ri(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or --help for import examples."},Ri(e)?`Import source ${e} was not found or is not readable.`:`Import source "${e}" is not a supported source. Use a local path, GitHub/GitLab source, or URL.`,t.json,"invalid_source")}catch(n){return C({status:"error",reasonCode:"invalid_source",source:e,error:ae(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${ae(n)}`,t.json,"invalid_source")}}function Ri(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}async function Fa(e,t,n){let i=e[0];if(i==="reference"&&e[1]==="resolve"){let r=v(e[2],"source reference resolve requires a reference."),s=await b(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(r)}`);return s.status==="not_found"?C({...s,status:"not_found",reasonCode:"source_reference_not_found",reference:r,nextAction:"source.connection.start",nextStep:"Start or complete the source connection before resolving this reference."},`Source reference ${r} was not found.`,t.json,"source_reference_not_found"):h(s,"Source reference resolved.",t.json,n)}return i==="connection"?await qa(e.slice(1),t,n):k(`Unknown source command "${e.join(" ")}".`,t.json)}async function qa(e,t,n){let i=e[0];if(i==="start"){let s=p(t.provider),o=p(t.source),l=p(t.visibility),c=Ka(s,o,l,t);return c||await K("/api/v1/me/source-connections",q(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 R(`/api/v1/me/source-connections/${encodeURIComponent(r)}`,t,n,"Source connection loaded.",{authenticated:!0}):i==="complete"?await K(`/api/v1/me/source-connections/${encodeURIComponent(r)}/complete`,q(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed."):i==="cancel"?await K(`/api/v1/me/source-connections/${encodeURIComponent(r)}/cancel`,{},t,n,"Source connection cancelled."):k(`Unknown source connection command "${i??""}".`,t.json)}function Ka(e,t,n,i){if(n){let r=Rt(n);if(!r||!Bt.includes(r))return C({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:Bt,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${Bt.join(", ")}.`,i.json,"invalid_visibility")}if(!e||!t)return null;try{let r=Ct(t);if((e==="github"||e==="gitlab")&&r.kind!==e)return Mt(e,t,i);if(e==="domain"){let s=new URL(t);if(s.protocol!=="https:"||!s.hostname)return Mt(e,t,i)}}catch{return Mt(e,t,i)}return null}function Mt(e,t,n){return C({status:"error",reasonCode:"invalid_source",provider:e,source:t,nextAction:"source.connection.start",nextStep:e==="github"?"Use a GitHub source such as https://github.com/OWNER/REPO or github:OWNER/REPO.":e==="gitlab"?"Use a GitLab source such as https://gitlab.com/GROUP/REPO or gitlab:GROUP/REPO.":"Use a valid source URL or provider-specific source."},`Invalid ${e} source "${t}".`,n.json,"invalid_source")}async function Ga(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 R(`/api/v1/me/approvals/${encodeURIComponent(r)}`,t,n,"Approval status loaded.",{authenticated:!0}):i==="complete"?await K(`/api/v1/me/approvals/${encodeURIComponent(r)}/complete`,x({decision:p(t.decision),evidence:ft(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed."):k(`Unknown approval request command "${i??""}".`,t.json)}async function Va(e,t,n){let i=e[0]??"list";if(i==="list")return await R("/api/v1/me/workspaces",t,n,"Workspaces loaded.",{authenticated:!0});if(i==="create")return await K("/api/v1/workspaces",{name:e.slice(1).join(" "),kind:p(t.kind)},t,n,"Workspace created.");let r=v(e[1],`workspace ${i} requires a workspace id.`);if(i==="skills")return await R(`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0});if(i==="deploy"){let s=v(e[2],"workspace deploy requires a skill slug."),o=await b(n,`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,{method:"POST",headers:j(n.apiKey),body:JSON.stringify(x({skillSlug:s,dryRun:t.dryRun}))});return t.dryRun?or(o,"Workspace deployment preview ready.",t,n):h(o,"Workspace deployment requested.",t.json,n)}if(i==="remove"){let s=v(e[2],"workspace remove requires a skill slug.");return await pt(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}`,{method:"DELETE",headers:B(n.apiKey,n.authBlockedMessage)},t,n,"Workspace skill removed.")}if(i==="guide"){let s=v(e[2],"workspace guide requires a skill slug.");try{return await R(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}catch(o){if(o instanceof A&&o.status===404)return Da(r,s,t);throw o}}return k(`Unknown workspace command "${i}".`,t.json)}function Da(e,t,n){let i={status:"deployment_not_found",reasonCode:"workspace_deployment_not_found",workspaceId:e,skillSlug:t,nextAction:"workspace.deploy",nextStep:`Run \`skills-layer workspace deploy ${e} ${t}\` first, then run \`skills-layer workspace guide ${e} ${t}\` after the deployment exists.`};return C(i,`Workspace deployment not found for ${t}. Run \`skills-layer workspace deploy ${e} ${t}\` first.`,n.json,"workspace_deployment_not_found")}async function Ha(e,t,n){let i=v(e[0],"buy requires a skill slug."),r=Po(t);if(r.failure)return r.failure;let s=await b(n,"/api/v1/buy",{method:"POST",headers:j(n.apiKey),body:JSON.stringify({skillSlug:i,paymentMethod:r.value})});if(s.status==="already_owned")return h(s,`You already own ${i}. Run \`skills-layer install ${i}\` to install or update it.`,t.json,n);if(t.json||s.status!=="checkout_required"||typeof s.checkoutUrl!="string"||typeof s.purchaseId!="string")return h(s,`Purchase flow started for ${i}.`,t.json,n);n.emitInfo(`Opening checkout for ${i}. Complete the payment in your browser, then come back here.`),await n.openUrl(s.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${s.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let l=await Rl(s.purchaseId,n);return H(l)?l:l.status!=="succeeded"&&l.status!=="refund_requested"?h({...s,purchaseStatus:l.status},`Checkout is still ${l.status} for ${i}. You can rerun install after payment reconciliation completes.`,t.json,n):(n.emitInfo("Payment confirmed. Continuing with install."),await fn([i],t,n))}async function za(e,t,n){let i=e[0]??"list";if(i==="list")return await R("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(i==="spending")return await R("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let r=v(e[1],`purchases ${i} requires a purchase id.`);return i==="invoice"?await R(`/api/v1/purchases/${encodeURIComponent(r)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0}):i==="refund-quote"?await R(`/api/v1/purchases/${encodeURIComponent(r)}/refund-quote`,t,n,"Refund quote loaded.",{authenticated:!0}):i==="refund"?await K(`/api/v1/purchases/${encodeURIComponent(r)}/refund`,q(t,["reason"]),t,n,"Refund requested."):k(`Unknown purchases command "${i}".`,t.json)}async function Wa(e,t,n){let i=e[0];if(i==="add"){let r=v(e[1],"library add requires a skill slug.");return await K("/api/v1/install",{skillSlug:r},t,n,"Skill added to library.")}return k(`Unknown library command "${i}".`,t.json)}async function Ja(e,t,n){let i=v(e[0],"export requires a skill slug."),r=new URLSearchParams,s=p(t.version);if(s&&!ar(s))return So("export",s,t);M(r,"version",s);let o=await b(n,`/api/v1/me/library/${encodeURIComponent(i)}/export${oe(r)}`,{headers:B(n.apiKey,n.authBlockedMessage)}),l=p(t.output);if(l){let c=await Xi({backend:n,exportResult:o,flags:t,skillSlug:i});if(H(c))return c;let u=J(n.cwd,l);await rn(u,c.bytes);let d={...o};return delete d.downloadUrl,h({...d,archiveSha256:c.archiveSha256,archiveSha256Meaning:"canonical_bundle_sha256",canonicalBundleSha256:c.archiveSha256,downloadedArchiveSha256:c.archiveBytesSha256,archiveHashFormat:c.archiveHashFormat,outputPath:u,downloaded:!0},`Exported ${i} to ${u}.`,t.json,n)}return h(o,l?`Exported ${i} to ${l}.`:"Export prepared.",t.json,n)}async function xi(e,t,n,i){let r=v(t[0],`${e==="add"?"add-review":"show-reviews"} requires a skill slug.`);return e==="show"?await R(`/api/v1/me/library/reviews?skillSlug=${encodeURIComponent(r)}`,n,i,"Reviews loaded.",{authenticated:!0}):await K(`/api/v1/me/library/${encodeURIComponent(r)}/review`,q(n,["rating","feedback"]),n,i,"Review added.")}async function $i(e,t,n,i){let r=v(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);return e==="show"?await R(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0}):await K(`/api/v1/me/library/${encodeURIComponent(r)}/report-issue`,q(n,["issueType","message"]),n,i,"Issue reported.")}async function Ya(e,t,n){let i=e[0];if(i==="hook"){let r=e[1];return r==="install"?await Zt(t,n):r==="status"?await el(t,n):k(`Unknown guardian hook command "${r??""}".`,t.json)}if(i==="enable")return e[1]||t.skill?await Ot("enforce",e,t,n):await Zt(t,n);if(i==="disable")return await Ot("disabled",e,t,n);if(i==="enable-warnings-only")return await Ot("warning_only",e,t,n);if(i==="status")return await Qa(e,t,n);if(i==="exec")return await Za(e,t,n);if(i==="check"){let r=v(e[1]??t.skill,"guardian check requires a skill slug."),s=Ti(t,"check"),o=t.grantJson.map(y=>$n(y,"grant-json")),l=$c(t.cloudTrustLedger);if(l.status==="invalid")return k(l.message,t.json);let c=Qt(t.telemetryMode,l.policy==="off"?"local_only":"cloud_managed");if(c.status==="invalid")return k(c.message,t.json);let u=await ur({skillSlug:r,version:p(t.version),action:s,flags:t,backend:n,telemetryMode:c.mode});if(u.status!=="ok")return u.result;let d=u.context.installedPath,g=p(t.version)??u.context.version,f=x({skillSlug:r,version:g,action:s,authorizationGrants:o,path:d,guardianPreference:await wn(n,r),unmanagedPolicy:u.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:c.mode,localPreflight:he(u.context)}),m=await b(n,"/api/v1/guardian/enforce",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(f)});return await Ne(n,{skillSlug:r,version:g,action:s,decisionStatus:ct(m),reasonCode:Xt(m),telemetryMode:c.mode,path:d}),h({...m,localPreflight:he(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=Qt(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return k(o.message,t.json);let l=p(t.path)??(await dr({skillSlug:r,flags:t,backend:n})).installedPath,c=Ti(t,"incident"),u=ft(t.evidenceJson,"evidence-json"),d=o.mode==="cloud_managed"&&!n.apiKey?"local_only":o.mode,g=x({skillSlug:r,version:s,action:c,evidence:u,path:l,telemetryMode:d,incident:!0,reason:p(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 Li({backend:n,skillSlug:r,version:s,installedPath:l,action:c,reason:p(t.reason)??"Guardian local-only incident"});await Ne(n,{skillSlug:r,version:s,action:c,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:d,path:l});let P=Ei(n,r);return await re(P,JSON.stringify({request:g,response:null,localResponse:w,savedAt:n.now()},null,2)),h({status:"written",skillSlug:r,version:s,telemetryMode:d,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:w,incidentStatePath: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 f=await b(n,"/api/v1/guardian/enforce",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(g)}),m=l?await Li({backend:n,skillSlug:r,version:s,installedPath:l,action:c,reason:p(t.reason)??"Guardian Cloud-managed incident"}):null;await Ke(n.paths.incidentsDir,{recursive:!0});let y=Ei(n,r);return await re(y,JSON.stringify({request:g,response:f,localResponse:m,savedAt:n.now()},null,2)),await Ne(n,{skillSlug:r,version:s,action:c,decisionStatus:ct(f),reasonCode:Xt(f),telemetryMode:o.mode,path:l}),h({...f,telemetryMode:o.mode,localResponse:m,incidentPath:y},"Guardian incident recorded.",t.json,n)}return k(`Unknown guardian command "${i??""}".`,t.json)}async function Za(e,t,n){let i=p(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=Qt(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return k(o.message,t.json);let l=ll(t,s),c=await ur({skillSlug:r,version:p(t.version),action:l,flags:t,backend:n,telemetryMode:o.mode});if(c.status!=="ok")return c.result;let u=c.context.installedPath,d=p(t.version)??c.context.version,g=x({skillSlug:r,version:d,action:l,authorizationGrants:t.grantJson.map(P=>$n(P,"grant-json")),path:u,guardianPreference:await wn(n,r),telemetryMode:o.mode,localPreflight:he(c.context)}),f=await b(n,"/api/v1/guardian/enforce",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(g)}),m=ct(f),y=Xt(f);if(await Ne(n,{skillSlug:r,version:d,action:l,decisionStatus:m,reasonCode:y,telemetryMode:o.mode,path:u}),!cl(f))return C({status:"blocked",reasonCode:y,skillSlug:r,guardian:f,localPreflight:he(c.context),command:{executable:G(s[0]??""),executed:!1}},"Guardian blocked guarded execution.",t.json,y);if(t.dryRun)return h({status:"allowed",skillSlug:r,guardian:f,localPreflight:he(c.context),command:{executable:G(s[0]??""),executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let w=await ul(s,n);return{exitCode:w.exitCode,stdout:t.json?JSON.stringify({status:w.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:r,guardian:f,localPreflight:he(c.context),command:w},warnings:[],links:[],reasonCode:w.exitCode===0?null:"command_failed",handoff:null},null,2):dl(w),stderr:w.stderr}}async function Ot(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:j(i.apiKey),body:JSON.stringify({skillSlug:r,requestedPreference:e,source:"public-cli"})});return s.preferenceAccepted===!0&&await pl(i,r,s),h(s,s.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,i)}async function Qa(e,t,n){let i=p(t.skill)??p(e[1]),r=await lr(n,i),s=await De(n),o=i?await gl(n,i):void 0,c=a(s,"enforcementLayer")!=="not_installed"&&!!s.strictPreActionBlocking?{status:"installed",reasonCode:"guardian_hook_installed",strictPreActionBlocking:!0,nextAction:"guardian.check",nextStep:"Cloud Guardian policy is enforced when checked, and the local host hook can block supported risky actions before execution."}:{status:"not_installed",reasonCode:"guardian_hook_not_installed",strictPreActionBlocking:!1,nextAction:"guardian.hook.install",nextStep:"Cloud Guardian policy is enforced when checked, but local pre-action blocking is not installed for this host. Run `skills-layer guardian hook install --agent codex --scope global` or `skills-layer setup`."};return h(x({status:"ok",skillSlug:a(r,"skillSlug")??i,policy:r,localPreference:o,hook:s,cloudPolicy:{status:a(r,"effectiveMode")??a(r,"status")??"unknown",reasonCode:a(r,"reasonCode"),enforcementBoundary:"cloud_policy_when_checked",nextAction:a(r,"nextAction"),nextStep:a(r,"nextStep")},localEnforcement:c,nextAction:a(c,"nextAction"),nextStep:a(c,"nextStep")}),"Guardian status loaded.",t.json,n)}async function lr(e,t){let n=t?await wn(e,t):void 0;return await b(e,"/api/v1/guardian/status",{method:"POST",headers:j(e.apiKey),body:JSON.stringify(x({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function Xa(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 lr(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ae(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function Zt(e,t){let n=p(e.agent)??"codex",i=gr(e.scope);if(i.status==="invalid")return k(i.message,e.json);let r=ge(t.env,t.platform,t.cwd).find(g=>g.id===n);if(!r)return k(`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json);let s=ml(r,i.scope,t);if(!s)return k(`Guardian ${i.scope} hooks are not available for ${r.displayName}.`,e.json);await fl(s,t);let o=hr(t,i.scope),l=Ui(Me(t.cwd,s.hookPath)),c=Ui(Me(t.cwd,s.configPath)),d=[...(await yr(o)).hooks.filter(g=>a(g,"agent")!==r.id||a(g,"scope")!==i.scope),{hookId:de,hookName:te,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 D(o,{version:1,hooks:d}),h({status:"enabled",hookId:de,hookName:te,agent:r.id,agentName:r.displayName,scope:i.scope,hookPath:s.hookPath,configPath:s.configPath,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,agentCommandMatrix:jt({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 el(e,t){let n=p(e.scope),i=n?gr(n):null;if(i?.status==="invalid")return k(i.message,e.json);let r=await De(t,i?.status==="valid"?i.scope:void 0);return h(r,"Guardian status loaded.",e.json,t)}async function De(e,t){let n=t?[t]:["project","global"],i=[];for(let l of n){let c=hr(e,l),u=await yr(c);for(let d of u.hooks){let g=a(d,"hookPath"),f=g?Ai(e,l,g):null,m=a(d,"configPath"),y=m?Ai(e,l,m):null,w=f?await me(f):!1,P=y?await me(y):null,_=w?P===!1?"active_missing_config":"active":"stale_missing_hook";i.push({hookId:a(d,"hookId")??de,hookName:a(d,"hookName")??te,...d,scope:a(d,"scope")??l,hookPath:f??g??null,configPath:y??m??null,active:w,configActive:P,hookState:_})}}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.active===!0&&l.strictPreActionBlocking===!0),activeHookCount:r,missingHookCount:o,staleHookCount:s,hooks:i,setup:await vn(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 cr(e,t){if(e.json){let u=await Y(t.paths.mcpConfigPath);return h({setup:await vn(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 De(t)},"Setup status loaded.",!0,t)}if(!t.stdoutIsTty)return h({status:"setup_needs_terminal",mcp:{nextCommand:"skills-layer mcp setup"},security:{nextCommand:"skills-layer guardian hook install --agent codex --scope project"}},"Setup needs an interactive terminal. Run `skills-layer setup`, or use `skills-layer mcp setup` and `skills-layer guardian hook install --agent codex --scope project`.",!1,t);let n=await t.promptSelect("Set up Skills Layer on this machine?",[{value:"mcp",label:"Setup Skills-Layer MCP",description:"Configure Skills Layer MCP for AI tools"},{value:"security",label:"Setup Skills-Layer Security Guardian",description:"Install Guardian hooks for this workspace"},{value:"both",label:"Setup both - MCP & Security Guardian",description:"Connect supported AI tools and install Guardian hooks"},{value:"not_now",label:"Remind me Later",description:"Skip setup for now; you can run skills-layer setup later"}]);if(n==="not_now"){let u={version:1,setupChoice:"not_now",mcpChoice:"not_now",mcpPromptedAt:t.now(),guardianHookChoice:"not_now",guardianHookPromptedAt:t.now(),remindAfter:il(t.now(),7)};return await ji(t,u),h({status:"setup_skipped",mcp:{status:"not_configured",nextCommand:"skills-layer mcp setup"},security:{status:"not_configured",nextCommand:"skills-layer guardian hook install --agent codex --scope project"}},"Skills Layer setup skipped for now. Run `skills-layer setup` when you want MCP and Security hooks on this machine.",!1,t)}if(n!=="both"&&n!=="mcp"&&n!=="security")return 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?p(e.scope)??"project":"not_requested",guardianHookPromptedAt:t.now()};if(i)if(!t.apiKey)s.mcp={status:"login_required",configured:!1,nextCommand:"skills-layer login"},o.mcpChoice="login_required";else{let u=await mn(e,t);if(H(u))return u;s.mcp=u}if(r){let u={...e,json:!0,scope:p(e.scope)??"project",agent:p(e.agent)??"codex"},d=await Zt(u,t);if(d.exitCode!==0)return d;s.security=Sl(d.stdout)??{status:"enabled",agent:p(u.agent),scope:p(u.scope)}}await ji(t,o);let c=($(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 h(s,c,e.json,t)}async function tl(e,t){let n=await De(t),i=await vn(t),r=F(n,"activeHookCount")??0;if(t.stdoutIsTty&&r===0&&!i)return await cr(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:`${Te}
|
|
1044
|
-
|
|
1045
|
-
${s}`,stderr:""}}function
|
|
1046
|
-
[output truncated]`:e}function
|
|
1047
|
-
`)}function
|
|
1135
|
+
skills-layer api-key revoke --key-id <key-id>`,t.json);let s=String(r),o=await v(n,`/api/v1/me/api-keys/${encodeURIComponent(s)}/revoke`,{method:"POST",headers:M(n.apiKey,n.authBlockedMessage)});return h(o,"API key revoked.",t.json,n)}return y(`Unknown api-key command "${i}".`,t.json)}async function Co(e,t,n){let i=e[0]??"status";if(i==="setup"||i==="repair"){let r=p(t.client)??p(t.agent);if(r&&!st(r))return Bt(r,t);let s=await yn(t,n);return H(s)?s:h({...s},`MCP configuration written for ${s.clientId}. Open a fresh agent session to load Skills Layer tools, then run \`skills-layer mcp verify --client ${s.clientId}\` if they are not visible.`,t.json,n)}if(i==="status"||i==="verify"){let r=p(t.client)??p(t.agent);if(r&&!st(r))return Bt(r,t);let s=await Y(n.paths.mcpConfigPath);if(!s){if(r){let u=await Pt({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:ke(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:null});if(u.target.status==="skills_only"){let d=yi(u);return h(d,`${u.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}}return h({status:"mcp_not_configured",configured:!1,nextCommand:"skills-layer mcp setup"},"MCP is not configured on this machine.",t.json,n)}let o=r??l(s,"clientId")??"codex",a=l(s,"baseUrl")??n.baseUrl,c=await Pt({baseUrl:a,mcpUrl:l(s,"mcpUrl")??`${a}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:o,environment:l(s,"environment")??ke(a),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:s});if(c.target.status==="skills_only"){let u=yi(c);return h(u,`${c.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}if(i==="verify"&&c.configured){let u=await Dn({nodePath:process.execPath,bridgePath:c.bridge.path}),d={...c,verified:u.status==="ok",liveProbe:u};return u.status!=="ok"?P(d,`MCP config exists for ${c.clientId}, but live bridge verification failed: ${u.message}`,t.json,u.reasonCode??void 0):h(d,`MCP verified for ${c.clientId}. ${u.message} Open a fresh agent session or restart the agent if tools are not visible yet.`,t.json,n)}return h(c,c.configured?`MCP configuration is present for ${c.clientId}. Open a fresh agent session if tools are not visible, or run \`skills-layer mcp verify --client ${c.clientId}\` for a live check.`:`MCP needs repair for ${c.clientId}. Run \`${c.nextCommand}\`.`,t.json,n)}if(i==="disconnect"||i==="logout"){let r=p(t.client)??p(t.agent)??"codex";if(!st(r))return Bt(r,t);let s=await Y(n.paths.mcpConfigPath),o=Ee({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:ke(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath}),a=o.targets.find(c=>c.agentId===r);return await _o(s,n),await a?.disconnect?.(),await zn(o.bridgePath),await Wn(o.brokerPath,o.brokerSocketPath),await un(n.paths.mcpConfigPath,{force:!0}),h({status:"mcp_disconnected",configured:!1,clientId:r},"MCP disconnected on this machine.",t.json,n)}return y(`Unknown mcp command "${i}". Use setup, status, verify, repair, or disconnect.`,t.json)}function st(e){return be.includes(e)}function Bt(e,t){return P({status:"error",reasonCode:"unknown_mcp_client",requestedClient:e,nextAction:"mcp.status",nextStep:"Run `skills-layer agents list` to see supported client ids."},`Unknown MCP client "${e}". Run \`skills-layer agents list\` to see supported client ids.`,t.json,"unknown_mcp_client")}function yi(e){let t=e.target.instructions,n=Array.isArray(t)&&typeof t[0]=="string"?t[0]:`Install skills with \`skills-layer install <skill> --agent ${e.clientId}\`.`;return{...e,status:"skills_only",configured:!1,nextCommand:null,nextAction:"install.skills",nextStep:n}}async function yn(e,t){let n=p(e.environment)??ke(t.baseUrl),i=["mcp:use","catalog:read","library:read","guardian:check","guardian:incident","creator:read"],r=`${t.baseUrl}/mcp`,s=Ee({baseUrl:t.baseUrl,mcpUrl:r,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:"codex",environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath}),o=await xo(e,t,s),a=o.clientIds[0]??"codex",c=Ee({baseUrl:t.baseUrl,mcpUrl:r,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:a,environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath}),u={},d=null;for(let m of o.clientIds){let k=await v(t,"/api/v1/me/mcp-tokens",{method:"POST",headers:A(t.apiKey),body:JSON.stringify({clientId:m,environment:n,scopes:i})}),w=l(k,"apiKey");if(!w)return y("MCP setup did not receive a token from the backend.",e.json);let C=await Ro(t,{token:w,clientId:m,environment:n});u[m]={clientId:m,environment:n,...C,tokenPrefix:l(k,"keyPrefix")??null,scopes:Array.isArray(k.scopes)?k.scopes:[],savedAt:t.now()},d??=k}let g=u[a]??{};await D(t.paths.mcpConfigPath,{version:1,baseUrl:t.baseUrl,mcpUrl:r,clientId:a,clientIds:o.clientIds,environment:n,selectionSource:o.selectionSource,detectedClientIds:o.detectedClientIds,...g,tokens:u,brokerPath:c.brokerPath,brokerSocketPath:c.brokerSocketPath,savedAt:t.now()});let f=c.targets.filter(m=>m.status==="automatic"&&o.clientIds.includes(m.agentId));for(let m of f)await m.apply?.();return{...W(d??{}),status:"mcp_configured",clientId:a,clientIds:o.clientIds,selectionSource:o.selectionSource,detectedClientIds:o.detectedClientIds,environment:n,mcpUrl:r,bridgePath:c.bridgePath,brokerPath:c.brokerPath,brokerSocketPath:c.brokerSocketPath,nodePath:c.nodePath,bridgeChecksum:c.bridgeChecksum,brokerChecksum:c.brokerChecksum,saved:!0,readiness:{status:"configured_needs_agent_reload",verifyCommand:`skills-layer mcp verify --client ${a}`,nextStep:"Open a fresh agent session so the host can load the updated MCP configuration. Run verify or repair if Skills Layer tools are still not visible."},registrations:{status:"mcp_registration_plan",automaticCount:c.automaticCount,manualCount:c.manualCount,skillsOnlyCount:c.skillsOnlyCount,unsupportedCount:c.unsupportedCount,appliedCount:f.length,appliedClients:f.map(m=>m.agentId),targets:c.targets.map(m=>({agentId:m.agentId,displayName:m.displayName,tier:m.tier,status:m.status,transport:m.transport,configPath:m.configPath,bridgePath:m.bridgePath,restartRequired:m.restartRequired,reason:m.reason,instructions:m.instructions}))}}}async function xo(e,t,n){let i=p(e.client)??p(e.agent),r=n.targets.filter(c=>c.status==="automatic").map(c=>c.agentId);if(i)return{clientIds:[i],detectedClientIds:[],selectionSource:"explicit"};if(e.all)return{clientIds:r,detectedClientIds:r,selectionSource:"all"};let s=await Tn({env:t.env,platform:t.platform,cwd:t.cwd,pathExists:fe}),o=new Set(r),a=s.map(c=>c.id).filter(c=>o.has(c));return a.length>0?{clientIds:a,detectedClientIds:a,selectionSource:"detected"}:{clientIds:["codex"],detectedClientIds:[],selectionSource:"fallback"}}async function Ro(e,t){if(!e.credentialStore)return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"};let n=Io({baseUrl:e.baseUrl,userId:e.config?.userId,email:e.config?.email,clientId:t.clientId,environment:t.environment});try{return await e.credentialStore.set(Te,n,t.token),{tokenRef:n,credentialStorage:"macos_keychain",credentialService:Te,tokenStorage:"macos_keychain"}}catch{return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}}async function _o(e,t){if(!e||!t.credentialStore)return;let n=$o(e,Te);for(let i of n)await t.credentialStore.delete(i.service,i.tokenRef)}function $o(e,t){let n=new Map;ki(e,t,n);let i=e.tokens;if($(i))for(let r of Object.values(i))$(r)&&ki(r,t,n);return[...n.values()]}function ki(e,t,n){let i=l(e,"tokenRef");if(!i||l(e,"credentialStorage")!=="macos_keychain")return;let r=l(e,"credentialService")??t;n.set(`${r}:${i}`,{service:r,tokenRef:i})}function Io(e){let t=[e.baseUrl,e.userId??e.email??"unknown-user",e.clientId,e.environment,"mcpToken"].join(`
|
|
1136
|
+
`);return`skills-layer-cli:mcp-token:${cn("sha256").update(t).digest("base64url").slice(0,32)}`}async function Zt(e,t){if(e.noMcp)return{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."};let n=await Y(t.paths.mcpConfigPath),i=n?l(n,"baseUrl"):void 0,r=n?l(n,"clientId")??"codex":"codex";if(!e.withMcp&&i===t.baseUrl&&r)return{data:{status:"mcp_already_configured",configured:!0,clientId:r,mcpUrl:n?l(n,"mcpUrl")??`${t.baseUrl}/mcp`:`${t.baseUrl}/mcp`},message:"MCP is already configured for this machine."};if(!e.withMcp&&!e.json){let a=await Y(t.paths.mcpPreferencePath),c=a?l(a,"baseUrl"):void 0,u=a?l(a,"clientId")??"codex":void 0;if((a?l(a,"choice"):void 0)==="not_now"&&c===t.baseUrl&&u==="codex")return{data:{status:"mcp_skipped_previously",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup was skipped previously. Run `skills-layer mcp setup` when you want AI-tool access."}}let s=e.withMcp===!0;if(!s&&!e.json)try{let a=await t.promptSelect("Set up Skills Layer MCP for your AI tools on this machine?",[{value:"yes",label:"Yes, set up MCP",description:"Mint a scoped token and write local MCP configuration"},{value:"no",label:"Not now",description:"You can run skills-layer mcp setup later"}]);if(s=a==="yes",a==="no")return await D(t.paths.mcpPreferencePath,{version:1,choice:"not_now",baseUrl:t.baseUrl,clientId:"codex",savedAt:t.now()}),{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."}}catch{return{}}if(!s)return{};let o=await yn(e,t);return H(o)?o:{data:o,message:"MCP configuration written for this machine. Open a fresh agent session so your AI tools can load it."}}async function jo(e,t,n){let i=e.join(" ").trim()||p(t.search)||"",r=new URLSearchParams;i&&r.set("query",i);let s=p(t.runtimeRisk);if(s&&!wi.includes(s))return bi("runtime-risk",s,wi,t);let o=p(t.limit);if(o){let c=Number(o);if(!Number.isInteger(c)||c<1||c>100)return bi("limit",o,["1-100"],t);r.set("limit",String(c))}F(r,"agent",t.agent),F(r,"capability",t.capability),F(r,"trust",t.trust),F(r,"runtime-risk",s),F(r,"security-capability",t.securityCapability);let a=await v(n,`/api/v1/search${oe(r)}`);if(t.install!==void 0){let c=p(t.install);if(!c){if(t.json)return y("search --install requires an explicit skill slug in the public CLI package.",!0);let d=Ve(a);if(d.length===0)return y("Search results do not include any installable skills. Run search again with a broader query.",!1);if(d.length===1)c=d[0].value;else try{c=await n.promptSelect("Select a search result to install:",d)}catch{return y("No search result was selected for install.",!1)}}let u=Nc(a);return u.includes(c)?await wn([c],t,n):y(u.length===0?`Search results do not include "${c}". Run search again with a matching query first.`:`Search results do not include "${c}". Run search again with a matching query or choose one of: ${u.join(", ")}.`,t.json)}return h(a,"Search complete.",t.json,n)}var wi=["low","elevated","high"],Nt=["local","project","global","workspace"],Mt=["private","public","unlisted"],Ft=["private","public","unlisted"],Ao=/^(?:card(?:_[A-Za-z0-9]+)*|pm_[A-Za-z0-9_]+)$/u;function ir(e,t,n,i){let r=p(t);if(!r)return{};if(!/^\d+$/u.test(r))return{failure:P({status:"error",reasonCode:"invalid_limit",command:e,value:r,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be a whole number from 1 to ${n}.`,i.json,"invalid_limit")};let s=Number.parseInt(r,10);return!Number.isInteger(s)||s<1||s>n?{failure:P({status:"error",reasonCode:"invalid_limit",command:e,value:r,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be between 1 and ${n}.`,i.json,"invalid_limit")}:{value:String(s)}}function bi(e,t,n,i){return P({status:"error",reasonCode:"invalid_search_filter",filter:e,value:t,acceptedValues:n,nextAction:"search",nextStep:e==="runtime-risk"?"Use --runtime-risk low, elevated, or high.":"Use --limit with a whole number from 1 to 100."},e==="runtime-risk"?`Invalid runtime risk "${t}". Use one of: ${n.join(", ")}.`:`Invalid search limit "${t}". Use a whole number from 1 to 100.`,i.json,"invalid_search_filter")}function kn(e,t){let n=p(t.scope);if(n&&!Nt.includes(n))return{failure:P({status:"error",reasonCode:"invalid_install_filter",filter:"scope",value:n,acceptedValues:Nt,nextAction:e,nextStep:"Use --scope local, project, global, or workspace."},`Invalid ${e} --scope "${n}". Use one of: ${Nt.join(", ")}.`,t.json,"invalid_install_filter")};let i=p(t.agent);return i&&!st(i)?{failure:P({status:"error",reasonCode:"unknown_agent",filter:"agent",value:i,acceptedValues:be,nextAction:e,nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown ${e} --agent "${i}". Run \`skills-layer agents\` to inspect supported agents.`,t.json,"unknown_agent")}:{scope:n,agent:i}}function rr(e,t){let n=kn(e,t);if(n.failure)return n.failure;let i=p(t.version);if(e==="install"&&i&&!Sn(i))return sr("install",i,t)}function sr(e,t,n){return P({status:"error",reasonCode:"invalid_version",command:e,version:t,nextAction:e,nextStep:"Use a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --version "${t}". Use a semver version or an external-<digest> version.`,n.json,"invalid_version")}function Lo(e,t,n){return P({status:"error",reasonCode:"invalid_expiry",command:e,expiresIn:t,acceptedFormat:"<positive whole number>d",nextAction:e,nextStep:"Use --expires with a day duration such as 7d, 30d, or 90d."},`Invalid --expires "${t}". Use a day duration such as 7d, 30d, or 90d.`,n.json,"invalid_expiry")}function Eo(e,t,n){let i=p(t);if(i&&!/^[1-9]\d*d$/iu.test(i))return Lo(e,i,n)}function or(e,t,n,i,r,s){let o=p(e);if(!o)return{};if(!/^\d+$/u.test(o))return{failure:P({status:"error",reasonCode:i,[n]:o,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${s.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${s.minimum===0?"zero or greater":"greater than zero"}.`,r.json,i)};let a=Number(o);return!Number.isSafeInteger(a)||a<s.minimum?{failure:P({status:"error",reasonCode:i,[n]:o,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${s.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${s.minimum===0?"zero or greater":"greater than zero"}.`,r.json,i)}:{value:a}}function Uo(e){let t=p(e.paymentMethod)??"card";return Ao.test(t)?{value:t}:{failure:P({status:"error",reasonCode:"invalid_payment_method",paymentMethod:t,acceptedValues:["card","card_<test-card>","pm_<provider-method-id>"],nextAction:"buy",nextStep:"Use --payment-method card or a provider token such as pm_<id>."},`Invalid payment method "${t}". Use card or a provider token such as pm_<id>.`,e.json,"invalid_payment_method")}}async function To(e,t,n){let i=new URLSearchParams,r=ir(e,t.limit,20,t);return r.failure?r.failure:(F(i,"limit",r.value),F(i,"search",t.search),F(i,"sort",t.sort),await R(`/api/v1/${e}${oe(i)}`,t,n,`${wt(e)} skills loaded.`))}async function Bo(e,t,n){let i=e.join(" ").trim();if(!i)return y("recommend requires a task.",t.json);let r=ir("recommend",t.limit,20,t);if(r.failure)return r.failure;let s=new URLSearchParams({task:i});return F(s,"limit",r.value),await R(`/api/v1/recommend?${s.toString()}`,t,n,"Recommendations loaded.")}async function No(e,t,n){if(e.length<2)return y("compare requires two or more skill slugs.",t.json);let i=new URLSearchParams({slugs:e.join(",")}),r=await v(n,`/api/v1/skills/compare?${i.toString()}`);return t.json?h(r,"Comparison loaded.",!0,n):{exitCode:0,stdout:Xl(r,"Comparison loaded.",Z(n),t.verbose),stderr:""}}async function Mo(e,t,n){let i=b(e[0],"show requires a skill slug."),r=await v(n,`/api/v1/skills/${encodeURIComponent(i)}`);return h(Aa(r),"Skill loaded.",t.json,n)}async function Fo(e,t,n){let i=b(e[0],"trust requires a skill slug."),r=new URLSearchParams;F(r,"format",t.format),F(r,"version",t.version);let s=await v(n,`/api/v1/skills/${encodeURIComponent(i)}/trust${oe(r)}`);return p(t.format)?.toLowerCase()==="sarif"&&!t.json?{exitCode:0,stdout:La(s,i,n),stderr:""}:h(s,"Trust report loaded.",t.json,n)}async function Oo(e,t,n){let i=et(e[0],e[1]);if(i)return Ot(i,[e[0],e[1]].filter(Boolean).join(" "),t,n);let r=e[0];if(!r)return{exitCode:0,stdout:Be,stderr:""};if(r==="full")return Ot(Be,"full",t,n);if(r==="topic"){let s=et(e[1]);if(s)return Ot(s,e[1]??"overview",t,n);let o=new URLSearchParams;return e[1]&&o.set("topic",e[1]),await R(`/api/v1/help${oe(o)}`,t,n,"Help topic loaded.")}if(r==="standards")return await R("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let s=await v(n,"/api/v1/marketplace/status");return t.json?h(s,"Marketplace status loaded.",!0,n):h(sc(s),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let s=await v(n,"/api/v1/capabilities");return h(ac(s),"Edition capabilities loaded.",t.json,n)}if(r==="schema-plan")return y("help schema-plan is not included in the public npm CLI.",t.json);if(r==="optimize-tokens"){let s=b(t.text,"help optimize-tokens requires --text."),o=lc(t.maxCharacters,t.json);if(H(o))return o;let a=await v(n,"/api/v1/optimize-tokens",{method:"POST",headers:A(n.apiKey),body:JSON.stringify({text:s,...o?{maxCharacters:o}:{}})});return h(a,"Token optimization complete.",t.json,n)}return y(`Unknown help command "${r}".`,t.json)}function Ot(e,t,n,i){return n.json?h({status:"ok",topic:t,content:e},"Help topic loaded.",!0,i):{exitCode:0,stdout:e,stderr:""}}async function qo(e,t,n){let i=b(e[0]??t.path,"validate requires a file or directory."),s={files:await ht(J(n.cwd,i)),sourceIntakeContext:p(t.sourceIntakeContext),publicationStatus:p(t.publicationStatus),dependencyAuditStatus:p(t.dependencyAuditStatus),category:p(t.category),discloseSource:!!t.discloseSource,allowFindingsFeatured:!!t.allowFindingsFeatured},o;try{o=await v(n,"/api/v1/validation/preview",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_(s))})}catch(a){if(a instanceof I&&a.status===422&&a.details)o=Fc(a.details);else throw a}return t.json?h(o,"Validation complete.",!0,n):{exitCode:0,stdout:cc(o,i,n),stderr:""}}async function Ko(e,t,n){let i=b(e[0]??t.path,"preview-trigger requires a file or directory."),r=await ht(J(n.cwd,i)),s=await v(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:A(n.apiKey),body:JSON.stringify({files:r,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?h(s,"Trigger preview complete.",!0,n):{exitCode:0,stdout:uc(s,i,n),stderr:""}}async function Go(e,t,n){let i=e[0];if(i==="init")return await Vo(e.slice(1),t,n);if(i==="rules")return await R("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(i==="submissions")return await R("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(i==="status"){let r=b(e[1],"creator status requires a skill slug.");try{return await R(`/api/v1/me/submissions/${encodeURIComponent(r)}/status`,t,n,"Submission status loaded.",{authenticated:!0})}catch(s){if(s instanceof I&&s.status===404)return Zo(r,t);throw s}}if(i==="charge-status"){let r=b(e[1],"creator charge-status requires a charge id.");return await R(`/api/v1/me/private-skill-charges/${encodeURIComponent(r)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(i==="submit")return await vi(e.slice(1),t,n,!1);if(i==="submit-version")return await vi(e.slice(1),t,n,!0);if(i==="check-slug"){let r=b(e[1],"creator check-slug requires a slug.");return await Jo(r,t,n)}if(i==="rename"){let r=b(e[1],"creator rename requires the current slug."),s=b(e[2],"creator rename requires the new slug.");return await mt(`/api/v1/me/submissions/${encodeURIComponent(r)}/slug`,{nextSkillSlug:s},t,n,"Skill renamed.")}if(i==="pricing")return await ea(e,t,n);if(i==="update-listing"){let r=b(e[1],"creator update-listing requires a skill slug.");return await ta(r,t,n)}if(i==="visibility"){let r=b(e[1],"creator visibility requires a skill slug."),s=p(t.visibility)??e[2],o=$t(s);if(!o||!Mt.includes(o))return P({status:"error",reasonCode:"invalid_visibility",skillSlug:r,visibility:s??null,acceptedValues:Mt,nextAction:"creator.visibility",nextStep:"Use --visibility private, public, or unlisted."},`Invalid creator visibility "${s??""}". Use one of: ${Mt.join(", ")}.`,t.json,"invalid_visibility");let a=await v(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/visibility`,{method:"PATCH",headers:A(n.apiKey),body:JSON.stringify(_({visibility:o,dryRun:t.dryRun}))});return Ha(a)?P(a,za(a,r),t.json,l(a,"reasonCode")??l(a,"status")):h(a,t.dryRun?"Visibility preview loaded.":"Visibility updated.",t.json,n)}if(i==="security-report"){let r=b(e[1],"creator security-report requires a skill slug."),s=new URLSearchParams;F(s,"format",t.format),F(s,"version",t.version),F(s,"versionId",t.versionId);let o=await v(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust${oe(s)}`,{headers:M(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?h(o,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:xc(o,r,n),stderr:""}}if(i==="rescan-security"){let r=b(e[1],"creator rescan-security requires a skill slug."),s=await v(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust/rescan`,{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_(G(t,["version","versionId"])))});return t.json?h(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:Rc(s,r,n),stderr:""}}if(i==="provenance"){let r=b(e[1],"creator provenance requires a skill slug.");return await R(`/api/v1/me/submissions/${encodeURIComponent(r)}/provenance`,t,n,"Provenance loaded.",{authenticated:!0})}if(i==="claim"||i==="verify"||i==="dispute")return await na(i,e,t,n);if(i==="issues"||i==="reviews"||i==="update-issue"||i==="moderate-review")return await la(i,e,t,n);if(i==="analytics"){let r=b(e[1],"creator analytics requires a skill slug.");return await ia(r,t,n)}if(i==="earnings")return await R("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0});if(i==="payout-profile")return await ra(t,n);if(i==="payout-link")return await sa(t,n);if(i==="payouts")return await R("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0});if(i==="withdraw"){let r=or(t.amountCents,"--amount-cents","amountCents","invalid_amount_cents",t,{minimum:1});return r.failure?r.failure:await q("/api/v1/me/payouts/withdrawals",_({amountCents:r.value,reason:p(t.reason)}),t,n,"Withdrawal requested.")}return i==="source"?await da(e.slice(1),t,n):y(`Unknown creator command "${i??""}".`,t.json)}async function Vo(e,t,n){let i=p(t.skill)??e[0]??"my-skill",r=J(n.cwd,p(t.dir)??i),s=L(r,"SKILL.md"),o;try{o=ti(p(t.type))}catch(f){return y(ae(f),t.json)}let a=p(t.category),c=await Do(r);if((await fe(s)||c)&&!t.confirmed)return y(`Creator init target already exists at ${r}. Re-run with --confirm only if you want to overwrite ${s}.`,t.json);await Ke(r,{recursive:!0});let d=ni({skillSlug:i,description:p(t.description)??"Describe what this skill helps an agent do.",skillType:o,category:a});for(let f of d)await re(L(r,f.path),f.content);let g=_({status:"created",path:s,skillSlug:i,skillType:o,category:a,fileCount:d.length});return t.json?h(g,`Created ${s}.`,!0,n):{exitCode:0,stdout:yc(g,r,s,n),stderr:""}}async function fe(e){try{return await Ji(e),!0}catch{return!1}}async function Do(e){try{return(await Zi(e)).length>0}catch{return await fe(e)}}async function vi(e,t,n,i){let r=i?b(p(t.skill)??e[0],"creator submit-version requires a skill slug."):p(t.skill),s=b(p(t.source)??(i?e[1]:e[0])??t.path,`creator ${i?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),o=await pt(s,n.cwd);if(t.list)return await Ho(s,o,r,t,n);if(p(t.source)&&!o&&Hr(s))return zo(s,t);let a=o?.files??await ht(J(n.cwd,s));if(!i&&!t.dryRun){let m=await Wo(a,t,n);if(m)return m}let c=_({files:a,version:p(t.version),dryRun:t.dryRun,allowFindingsFeatured:t.allowFindingsFeatured,pricing:p(t.priceCents)?{priceCents:Number(p(t.priceCents))}:void 0,...o?{sourceMetadata:o.sourceMetadata}:{},...G(t,["displayName","skillType","category","visibility","source","skill"])}),u=i&&r?`/api/v1/me/submissions/${encodeURIComponent(r)}/versions`:"/api/v1/me/submissions",d=await v(n,u,{method:"POST",headers:A(n.apiKey),body:JSON.stringify(c)});if(t.json||d.status!=="checkout_required"||typeof d.checkoutUrl!="string"||typeof d.chargeId!="string")return h(d,i?"Version submitted.":"Submission uploaded.",t.json,n);n.emitInfo("Opening payment setup for skill submission. Complete the payment in your browser, then come back here."),await n.openUrl(d.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${d.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let f=await Nl(d.chargeId,n);return H(f)?f:f.status!=="submitted"?h({...d,chargeStatus:f.status},`Payment is still ${f.status}. You can rerun \`skills-layer creator charge-status ${d.chargeId}\` to continue tracking it.`,t.json,n):h(f,i?"Version submitted.":"Submission uploaded.",t.json,n)}async function Ho(e,t,n,i,r){if(t)return h(Si(cr(e,t,n)),"Source skills loaded.",i.json,r);let s=await Ne(r,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},i);return s.kind==="failure"?s.result:h(Si(s.inspection),"Source skills loaded.",i.json,r)}function Si(e){return{...e,sourceSubmissionSupported:!0}}function zo(e,t){let i=`skills-layer source connection start --provider ${mr(e)} --source ${e} --visibility private --provenance-intent private_source_import`;return P({status:"source_connection_required",reasonCode:"source_connection_required",source:e,nextAction:"source.connection.start",nextStep:i},`Creator submit can list ${e} safely, but publishing from a remote source requires a source connection. Run \`${i}\`.`,t.json,"source_connection_required")}async function Wo(e,t,n){let i=p(t.skill)??Qo(e);if(!i)return null;let r;try{r=await v(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(i)}`,{headers:M(n.apiKey,n.authBlockedMessage)})}catch(s){if(s instanceof I&&s.status===404)return ar(i,t);throw s}if(r.available===!1||l(r,"reasonCode")==="unavailable"||l(r,"reasonCode")==="reserved"){let s=l(r,"assignedSlug"),o=_({status:"duplicate_candidate",reasonCode:l(r,"reasonCode")??"slug_unavailable",requestedSlug:i,assignedSlug:s,nextAction:"creator.status",nextStep:`Run \`skills-layer creator status ${i}\`, \`skills-layer creator submissions\`, or submit a new version of the existing skill instead of creating a duplicate listing.`});return P(o,`A public skill slug "${i}" already exists or is not available. Run \`skills-layer creator status ${i}\`, check your creator submissions, or submit a new version instead of creating a duplicate listing.`,t.json,l(o,"reasonCode"))}return null}async function Jo(e,t,n){try{let i=await v(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:M(n.apiKey,n.authBlockedMessage)});return h(Yo(i),"Slug status loaded.",t.json,n)}catch(i){if(i instanceof I&&i.status===404)return ar(e,t);throw i}}function ar(e,t){let n={status:"slug_check_unavailable",reasonCode:"slug_check_route_unavailable",requestedSlug:e,nextAction:"creator.status",nextStep:`Slug availability could not be checked on the selected backend. Run \`skills-layer creator submissions\`, \`skills-layer creator status ${e}\`, or retry after selecting a compatible Skills Layer backend.`};return P(n,`Slug availability could not be checked for ${e} on the selected backend. Run \`skills-layer creator submissions\` or retry after selecting a compatible Skills Layer backend.`,t.json,"slug_check_route_unavailable")}function Yo(e){let t=e.available===!0,n=l(e,"assignedSlug");if(t)return _({requestedSlug:l(e,"requestedSlug"),available:!0,reasonCode:l(e,"reasonCode")??"available",assignedSlug:n});let i=S(e,"slugAssignment"),r=Array.isArray(i?.candidateSlugs)?i.candidateSlugs.filter(s=>typeof s=="string").slice(0,5):void 0;return _({...e,...i?{slugAssignment:{...i,...r?{candidateSlugs:r}:{}}}:{},...r?{candidateSlugs:r}:{}})}function Zo(e,t){return P({status:"not_submitted",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submit",nextStep:"Run `skills-layer creator submit <path> --dry-run` to validate a local skill before submitting it, or run `skills-layer creator submissions` to see your existing submissions."},`No creator submission was found for ${e}. Run \`skills-layer creator submit <path> --dry-run\` before checking status.`,t.json,"creator_submission_not_found")}function Qo(e){let t=e.find(i=>i.path.split("/").pop()?.toLowerCase()==="skill.md");if(!t)return;let n=/^---\s*\n(?<body>[\s\S]*?)\n---/u.exec(t.content??"")?.groups?.body?.split(/\r?\n/u).map(i=>i.match(/^name\s*:\s*(?<name>.+?)\s*$/u)?.groups?.name?.trim().replace(/^["']|["']$/gu,"")).find(i=>!!i);return Xo(n??K(ee(t.path)))}function Xo(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function ea(e,t,n){let i=b(e[1],"creator pricing requires a skill slug."),r=new URLSearchParams;if(F(r,"version",t.version),!t.priceCents)return await R(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${oe(r)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=or(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(s.failure)return s.failure;let o=s.value??0,a=await v(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${oe(r)}`,{headers:M(n.apiKey,n.authBlockedMessage)}),c=O(a,"priceCents")??0;if(o>c){let u=_({status:"pending_approval",reasonCode:c===0?"paid_activation_requires_approval":"price_increase_requires_approval",skillSlug:i,version:l(a,"version"),currentPriceCents:c,requestedPriceCents:o,currency:l(a,"currency")??"gbp",nextStep:"Pricing changes that increase buyer-facing cost require approval. Keep the current price for now, then retry after approval is available."});return h(u,"Pricing change requires approval before it can affect buyers.",t.json,n)}return await mt(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing`,{priceCents:o,version:p(t.version)},t,n,"Pricing updated.")}async function ta(e,t,n){try{return await mt(`/api/v1/me/submissions/${encodeURIComponent(e)}`,G(t,["displayName","summary","description","category","skillType","license","listingStatus"]),t,n,"Listing updated.")}catch(i){if(i instanceof I&&i.status===404){let r={status:"listing_not_found_or_not_editable",reasonCode:"creator_listing_not_found_or_not_owned",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see editable listings, or \`skills-layer show ${e}\` to inspect the public catalog entry.`};return P(r,`No editable creator listing was found for ${e}. Run \`skills-layer creator submissions\` to see listings you can update.`,t.json,"creator_listing_not_found_or_not_owned")}throw i}}async function na(e,t,n,i){let r=b(t[1],`creator ${e} requires a skill slug.`);try{if(e==="claim")return await q(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/claim`,G(n,["requestedRole","message"]),n,i,"Ownership claim submitted.");if(e==="verify"){let s=b(n.claimId,"creator verify requires --claim-id.");return await q(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/verify`,{claimId:s},n,i,"Ownership claim verified.")}return await q(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/dispute`,G(n,["message"]),n,i,"Ownership dispute submitted.")}catch(s){if(s instanceof I&&s.status===404){let o={status:"ownership_action_unavailable",reasonCode:e==="claim"?"skill_not_found_or_not_claimable":"ownership_claim_not_found",skillSlug:r,requestedRole:p(n.requestedRole),nextAction:e==="claim"?"search":"creator.claim",nextStep:e==="claim"?`Run \`skills-layer search ${r}\`, \`skills-layer show ${r}\`, or submit/source-install the skill before claiming it.`:`Run \`skills-layer creator claim ${r}\` to start a new claim if the skill is claimable.`};return P(o,e==="claim"?`No claimable skill was found for ${r}. Search or show the skill first, then claim it only when it exists and is claimable.`:`No matching ownership claim was found for ${r}. Start a new claim if the skill is claimable.`,n.json,l(o,"reasonCode")??"ownership_action_unavailable")}throw s}}async function ia(e,t,n){try{return await R(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(i){if(i instanceof I&&i.status===404){let r={status:"no_creator_submission",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see skills you own, \`skills-layer show ${e}\` to inspect the catalog listing, or \`skills-layer creator claim ${e}\` if it is a claimable public-source skill.`};return P(r,`No creator-owned analytics submission was found for ${e}. Run \`skills-layer creator submissions\`, \`skills-layer show ${e}\`, or \`skills-layer creator claim ${e}\` if you should manage it.`,t.json,"creator_submission_not_found")}throw i}}async function ra(e,t){let n=await v(t,"/api/v1/me/payout-profile",{headers:M(t.apiKey,t.authBlockedMessage)});return h(n,"Creator payout profile loaded.",e.json,t)}async function sa(e,t){let n=oa(p(e.mode));if(e.mode&&n===null)return y("creator payout-link --mode must be account_onboarding|account_update|onboarding|update.",e.json);let i;try{i=await v(t,"/api/v1/me/payout-profile/link",{method:"POST",headers:A(t.apiKey),body:JSON.stringify(n?{mode:n}:{})})}catch(s){if(s instanceof I&&aa(s))return P({status:"payout_setup_already_submitted",reasonCode:"payout_update_link_unavailable",nextAction:"creator.payout-profile",nextStep:"Run `skills-layer creator payout-profile` to confirm readiness, then use `skills-layer creator earnings` or `skills-layer creator withdraw --amount-cents <amount>`."},"Payout setup is already submitted for this account. Run `skills-layer creator payout-profile` to confirm readiness before requesting a withdrawal.",e.json,"payout_update_link_unavailable");throw s}let r=Ml(i);return r&&!e.json&&e.showUrl!==!0&&(t.emitInfo("Opening payout setup in your browser. Finish the flow there, then come back here."),await t.openUrl(r)||t.emitInfo(`Open this payout setup URL manually to continue: ${r}`)),h(i,"Payout setup link created.",e.json,t)}function oa(e){if(!e)return null;let t=e.trim().toLowerCase();return t==="account_onboarding"||t==="onboarding"?"account_onboarding":t==="account_update"||t==="update"?"account_update":null}function aa(e){let t=`${e.message} ${l(e.details??{},"error")??""}`.toLowerCase();return t.includes("account_update")&&t.includes("account_onboarding")&&t.includes("account link")}async function la(e,t,n,i){let r=b(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await R(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await R(`/api/v1/me/submissions/${encodeURIComponent(r)}/reviews`,n,i,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let o=b(n.issueId,"creator update-issue requires --issue-id.");try{return await mt(`/api/v1/me/skills/${encodeURIComponent(r)}/issues/${encodeURIComponent(o)}`,G(n,["status","fixedVersion","note"]),n,i,"Issue updated.")}catch(a){if(a instanceof I&&a.status===404)return ca(r,o,n);throw a}}let s=b(n.reviewId,"creator moderate-review requires --review-id.");try{return await q(`/api/v1/me/submissions/${encodeURIComponent(r)}/reviews/${encodeURIComponent(s)}/moderate`,G(n,["status","reason"]),n,i,"Review updated.")}catch(o){if(o instanceof I&&o.status===404)return ua(r,s,n);throw o}}function ca(e,t,n){return P({status:"not_found",reasonCode:"issue_not_found",skillSlug:e,issueId:t,nextAction:"creator.issues",nextStep:`Run \`skills-layer creator issues ${e}\` to inspect open issues before updating one.`},`Issue ${t} was not found for ${e}. Run \`skills-layer creator issues ${e}\` first.`,n.json,"issue_not_found")}function ua(e,t,n){return P({status:"not_found",reasonCode:"review_not_found",skillSlug:e,reviewId:t,nextAction:"creator.reviews",nextStep:`Run \`skills-layer creator reviews ${e}\` to inspect review ids before moderating one.`},`Review ${t} was not found for ${e}. Run \`skills-layer creator reviews ${e}\` first.`,n.json,"review_not_found")}async function da(e,t,n){let i=e[0],r=b(e[1],`creator source ${i??""} requires a source connection id.`),s=p(t.skill)??e[2];if(i==="prepare")return await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/prepare`,_({...G(t,["skill","source","version","displayName","skillType","category","priceCents","visibility"]),source:p(t.source)??e[2]}),t,n,"Source release prepared.");if(i==="publish-request"){let o=t.approvalRequestId.length>0?t.approvalRequestId:p(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/publish-request`,_({skillSlug:s,approvalRequestIds:o,version:p(t.version),...G(t,["visibility","priceCents","license","discloseSource"])}),t,n,"Source publish requested.")}if(i==="release-status"){let o=new URLSearchParams;return s&&o.set("skill",s),await R(`/api/v1/me/source-connections/${encodeURIComponent(r)}/release-status${oe(o)}`,t,n,"Source release status loaded.",{authenticated:!0})}return y(`Unknown creator source command "${i??""}".`,t.json)}async function wn(e,t,n){let i=rr("install",t);if(i)return i;let r=p(t.source);if(r){let u=p(t.skill),d=_i(r,u,t);if(d)return d;let g=await pt(r,n.cwd);if(g)return await Pi(r,g,u,t,n);let f=$i(r,t);if(f)return f;let m=t.list||t.dryRun||!u&&!t.json&&!t.all,k=await Ne(n,r,{source:r,skillSlug:u,listOnly:m},t);if(k.kind==="failure")return k.result;let w=k.inspection;if(t.list)return h(w,"Source skills loaded.",t.json,n);let C=Xt(r,w,t);if(C)return C;let x=await ot({source:r,inspection:w,requestedSkillSlug:u,mode:"install",flags:t,backend:n});if(x.kind==="failure")return x.result;if(t.dryRun)return h(Qt(r,w,x.skillSlug,t),"Source install preview ready.",t.json,n);let E=Ci(t,n),le;try{le=await v(n,E,{method:"POST",headers:xi(t,n),body:JSON.stringify(Ii({source:r},x.skillSlug,t))})}catch(bt){if(bt instanceof I)return ji(r,bt,t);throw bt}let U=await Vt(n,le);return await lt(n,U,x.skillSlug??l(U,"skillSlug")??r),at(U,Ri(t),t.json,n)}let s=b(e[0]??t.install,"install requires a skill slug or --source.");if(Hr(s)){let u=_i(s,p(t.skill),t);if(u)return u;let d=await pt(s,n.cwd);if(d)return await Pi(s,d,p(t.skill),t,n);let g=$i(s,t);if(g)return g;let f=p(t.skill),m;if(t.list){let x=await Ne(n,s,{source:s,listOnly:!0},t);return x.kind==="failure"?x.result:h(x.inspection,"Source skills loaded.",t.json,n)}if(!f&&!t.json&&!t.all){let x=await Ne(n,s,{source:s,listOnly:!0},t);if(x.kind==="failure")return x.result;let E=x.inspection;m=E;let le=Xt(s,E,t);if(le)return le;let U=await ot({source:s,inspection:E,requestedSkillSlug:f,mode:"install",flags:t,backend:n});if(U.kind==="failure")return U.result;f=U.skillSlug}if(t.dryRun){if(!m){let E=await Ne(n,s,{source:s,listOnly:!0},t);if(E.kind==="failure")return E.result;m=E.inspection}let x=await ot({source:s,inspection:m,requestedSkillSlug:f,mode:"install",flags:t,backend:n});return x.kind==="failure"?x.result:(f=x.skillSlug,h(Qt(s,m,f,t),"Source install preview ready.",t.json,n))}let k=Ci(t,n),w;try{w=await v(n,k,{method:"POST",headers:xi(t,n),body:JSON.stringify(Ii({source:s},f,t))})}catch(x){if(x instanceof I)return ji(s,x,t);throw x}let C=await Vt(n,w);return await lt(n,C,f??l(C,"skillSlug")??K(s)),at(C,Ri(t),t.json,n)}if(p(t.scope)==="workspace"){let u=b(t.workspace,"workspace installs require --workspace <workspace-id>."),d=await v(n,`/api/v1/workspaces/${encodeURIComponent(u)}/skills`,{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_({skillSlug:s,version:p(t.version),dryRun:t.dryRun}))});return t.dryRun?await fr(d,"Workspace install preview ready.",t,n):h(d,"Workspace deployment requested.",t.json,n)}let o=await v(n,"/api/v1/install",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_({skillSlug:s,version:p(t.version),scope:p(t.scope),agent:p(t.agent),dryRun:t.dryRun}))});if(t.dryRun)return await Ia(o,t,n);let a=await Vt(n,o),c=await pa(n,a,s,t);return H(c)?c:(await lt(n,c,s),at(c,"Skill installed.",t.json,n))}async function pa(e,t,n,i){if(Array.isArray(t.materializedWrites)&&t.materializedWrites.length>0)return t;let r=ga(e,t,n,i);if(r.status==="skip")return t;if(r.status==="failure")return P({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:r.skillSlug,nextStep:r.nextStep},r.message,i.json,"materialization_target_invalid");let s=await ma(e,t,r.skillSlug,r.version),o=await lr({backend:e,exportResult:s,flags:i,skillSlug:r.skillSlug});if(H(o))return o;let a=await ka({backend:e,skillSlug:r.skillSlug,version:r.version??l(s,"version")??"latest",scope:r.scope,agent:r.agent,skillsPath:r.skillsPath,bytes:o.bytes,files:o.files,archiveSha256:o.archiveSha256});return{...t,...fa(s),archiveSha256:o.archiveSha256,archiveHashFormat:o.archiveHashFormat,scope:r.scope,agent:r.agent.id,targetAgent:r.agent.id,materializationPlan:{scope:r.scope,agent:r.agent.id},...a}}function ga(e,t,n,i){let r=S(t,"materializationPlan")??S(t,"installPlan"),s=p(i.scope)??l(t,"scope")??(r?l(r,"scope"):void 0);if(s!=="project"&&s!=="global")return{status:"skip"};let o=l(t,"skillSlug")??l(t,"slug")??n,a=p(i.agent)??l(t,"agent")??l(t,"targetAgent")??(r?l(r,"agent")??l(r,"targetAgent"):void 0)??X(e.config?.lastSelectedAgent)??"codex",c=me(e.env,e.platform,e.cwd).find(d=>d.id===a);if(!c)return{status:"failure",skillSlug:o,message:`Unsupported agent "${a}". Run \`skills-layer agents list\` to choose a supported local install target.`,nextStep:"Run `skills-layer agents list` and retry with a supported --agent value."};let u=s==="global"?c.targets.globalSkillsPath:c.targets.projectSkillsPath;return u?{status:"ok",scope:s,agent:c,skillsPath:u,skillSlug:o,version:l(t,"version")??l(t,"currentVersion")}:{status:"failure",skillSlug:o,message:`${c.displayName} does not expose a ${s} skills path on this machine.`,nextStep:"Retry with --scope project, or choose another agent from `skills-layer agents list`."}}async function ma(e,t,n,i){if(typeof t.downloadUrl=="string"&&typeof t.archiveSha256=="string")return t;let r=new URLSearchParams;return i&&r.set("version",i),await v(e,`/api/v1/me/library/${encodeURIComponent(n)}/export${oe(r)}`,{headers:M(e.apiKey,e.authBlockedMessage)})}function fa(e){return _({version:l(e,"version"),storageKey:l(e,"storageKey"),expiresAt:l(e,"expiresAt")})}async function lr(e){let t=l(e.exportResult,"downloadUrl");if(!t)return P({status:"export_download_unavailable",reasonCode:"export_download_unavailable",skillSlug:e.skillSlug,nextStep:"Retry after the backend returns a signed bundle download URL."},`Export for ${e.skillSlug} did not include a signed download URL.`,e.flags.json,"export_download_unavailable");let n=await e.backend.fetchFn(ha(e.backend.baseUrl,t));if(!n.ok)throw new I(n.status,`Unable to download exported bundle (${n.status}).`);let i=new Uint8Array(await n.arrayBuffer()),r=ya(i),s=l(e.exportResult,"archiveSha256")??n.headers.get("x-skills-layer-archive-sha256")?.trim()??void 0;return s&&r.archiveSha256!==s?P({status:"download_integrity_failed",reasonCode:"download_hash_mismatch",skillSlug:e.skillSlug,version:l(e.exportResult,"version"),expectedArchiveSha256:s,observedArchiveSha256:r.archiveSha256,archiveHashFormat:r.format,nextStep:"Retry after the catalog artifact is refreshed, or contact Skills Layer support if this repeats."},`Downloaded ${e.skillSlug} did not match the catalog artifact hash.`,e.flags.json,"download_hash_mismatch"):r.files.length===0?P({status:"download_integrity_failed",reasonCode:"download_bundle_empty",skillSlug:e.skillSlug,archiveHashFormat:r.format,nextStep:"Retry after the catalog artifact is refreshed."},`Downloaded ${e.skillSlug} did not contain any skill files.`,e.flags.json,"download_bundle_empty"):{status:"ok",bytes:i,files:r.files,archiveSha256:r.archiveSha256,archiveBytesSha256:r.archiveBytesSha256,archiveHashFormat:r.format}}function ha(e,t){return/^https?:\/\//iu.test(t)?t:`${ie(e)}${t.startsWith("/")?"":"/"}${t}`}function ya(e){let t=cn("sha256").update(e).digest("hex"),n=Jn(e);return n?{archiveSha256:Yn(n),archiveBytesSha256:t,format:"bundle_archive",files:n}:{archiveSha256:t,archiveBytesSha256:t,format:"raw",files:[]}}async function ka(e){let t=e.backend.platform==="win32"?_e:pn,n=t.join(e.backend.paths.bundlesDir,e.skillSlug,e.version,"bundle.zip"),i=t.join(e.skillsPath,e.skillSlug),r=t.join(i,e.version,"bundle.zip"),s=[];await an(n,e.bytes),await un(i,{recursive:!0,force:!0}),await an(r,e.bytes),s.push({path:ct(e.backend.cwd,r),bytes:e.bytes.byteLength});for(let o of e.files){let a=t.join(i,...wa(o.path)),c=o.content??"";if(await re(a,c),s.push({path:ct(e.backend.cwd,a),bytes:new TextEncoder().encode(c).length}),K(o.path).toLowerCase()==="skill.md"){let u=await _n({backend:e.backend,skillSlug:e.skillSlug,version:e.version,skillDocumentPath:a,skillDocumentContent:c});s.push(u)}}return{bundlePath:n,materializedPath:r,materializedSkillRoot:i,archiveSha256:e.archiveSha256,materializedWrites:s}}function wa(e){let n=e.replaceAll("\\","/").replace(/^\/+/u,"").trim().split("/").filter(i=>i.length>0);if(n.length===0||n.some(i=>i==="."||i===".."))throw new Error(`Unsafe bundle path "${e}".`);return n}async function Pi(e,t,n,i,r){let s=p(i.visibility)??"private";if(s!=="private")return P({status:"local_install_visibility_not_allowed",reasonCode:"local_install_visibility_not_allowed",source:e,requestedVisibility:s,nextStep:`Use \`skills-layer creator submit ${e} --visibility ${s} --dry-run\` when you want to submit a local skill with non-private visibility.`},`Local path install creates a private Cloud skill by default. Use creator submit when you want ${s} visibility.`,i.json,"local_install_visibility_not_allowed");let o=cr(e,t,n);if(i.list)return h(o,"Local source skills loaded.",i.json,r);let a=Xt(e,o,i);if(a)return a;let c=await ot({source:e,inspection:o,requestedSkillSlug:n,mode:"install",flags:i,backend:r});if(c.kind==="failure")return c.result;let u=c.skillSlug??Ve(o)[0]?.value??dr(e);if(i.dryRun)return h({...Qt(e,o,u,i),installKind:"local_private",publicationStatus:"none",catalogRecord:"not_created",nextStep:`Re-run without --dry-run to install ${u} locally. Use \`skills-layer creator submit ${e} --visibility private --dry-run\` when you want a private creator submission.`},"Local private install preview ready.",i.json,r);let d=await v(r,"/api/v1/me/submissions",{method:"POST",headers:{"content-type":"application/json",...M(r.apiKey,r.authBlockedMessage)},body:JSON.stringify(_({files:t.files,version:p(i.version),visibility:"private",category:p(i.category),displayName:p(i.displayName),skillType:p(i.skillType),sourceMetadata:t.sourceMetadata}))}),g=await Sa({backend:r,source:e,upload:t,skillSlug:l(d,"skillSlug")??u,flags:i,submitted:d});return await lt(r,g,u),at(g,"Private Cloud skill installed.",i.json,r)}function cr(e,t,n){let i=ba(t.files),r=n?i.find(s=>s.skillSlug===n)??null:i.length===1?i[0]??null:null;return{status:"ok",source:t.sourceMetadata,selectedSkill:r,results:i,issues:[],sourceInstallSupported:!0,sourceInstallMode:"local_private",publicationStatus:"none",originalSource:e}}function ba(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=ee(t.path).replaceAll("\\","/"),i=n==="."?".":n,r=ur(t.content??"")??dr(i==="."?t.path:i),s=va(t.content??"");return{skillSlug:r,name:r,...s?{description:s}:{},relativeSkillRoot:i,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function ur(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function va(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function dr(e){return(e.replaceAll("\\","/").replace(/\/+$/u,"").split("/").filter(Boolean).at(-1)??"local-skill").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"local-skill"}async function Sa(e){let t=Pa(e.backend,e.flags);if(t.status==="failure")throw new Error(t.message);let n=e.upload.files.map(r=>({path:L(t.skillsPath,e.skillSlug,Er(r.path)),content:r.content??""})),i=[];for(let r of n)if(await re(r.path,r.content),i.push({path:ct(e.backend.cwd,r.path),bytes:new TextEncoder().encode(r.content).length}),K(r.path).toLowerCase()==="skill.md"){let s=await _n({backend:e.backend,skillSlug:e.skillSlug,version:l(e.submitted,"version")??p(e.flags.version)??"private",skillDocumentPath:r.path,skillDocumentContent:r.content});i.push(s)}return{...e.submitted,status:"installed",cloudStatus:l(e.submitted,"status")??"submitted",installKind:"cloud_private",source:e.source,sourceKind:"local",skillSlug:e.skillSlug,version:l(e.submitted,"version")??p(e.flags.version)??"private",scope:t.scope,agent:t.agent,visibility:"private",publicationStatus:"private",catalogRecord:"private",privacy:{publication:"private",catalogRecord:"private",message:"This local install was saved as a private Cloud skill and did not create a public catalog record."},materializationPlan:{scope:t.scope,agent:t.agent},materializedWrites:i}}function Pa(e,t){let n=p(t.scope)??"project";if(!["local","project","global"].includes(n))return{status:"failure",message:"Local private installs support --scope local, project, or global. Use `skills-layer creator submit <path> --visibility private` for private creator workflows."};let i=p(t.agent)??X(e.config?.lastSelectedAgent)??"codex",r=me(e.env,e.platform,e.cwd).find(o=>o.id===i);if(!r)return{status:"failure",message:`Unsupported agent "${i}". Run \`skills-layer agents list\` to choose a supported local install target.`};let s=n==="global"?r.targets.globalSkillsPath:r.targets.projectSkillsPath;return s?{status:"ok",scope:n,agent:r.id,skillsPath:s}:{status:"failure",message:`${r.displayName} does not expose a ${n} skills path on this machine.`}}function ct(e,t){let n=Fe(e,t);return n&&!n.startsWith("..")&&!_e.isAbsolute(n)?n.split("\\").join("/"):t}function bn(e){return p(e.visibility)==="public"?"public":"private"}function Ci(e,t){return bn(e)==="public"&&!t.apiKey?"/api/v1/source-imports":"/api/v1/me/source-installs"}function xi(e,t){return{"content-type":"application/json",...bn(e)==="private"?M(t.apiKey,t.authBlockedMessage):He(t.apiKey)}}function Ri(e){return bn(e)==="public"?"Public source install planned.":"Private source skill installed."}async function ot(e){let t=Ve(e.inspection);if(e.requestedSkillSlug)return t.length>0&&!t.some(n=>n.value===e.requestedSkillSlug)?{kind:"failure",result:Ca(e.source,e.requestedSkillSlug,t.map(n=>n.value),e.flags)}:{kind:"selected",skillSlug:e.requestedSkillSlug};if(e.flags.json||e.flags.all)return{kind:"selected",skillSlug:e.requestedSkillSlug};if(t.length<=1)return{kind:"selected",skillSlug:t[0]?.value};try{return{kind:"selected",skillSlug:await e.backend.promptSelect(`${e.source} exposes multiple skills. Select one to ${e.mode}:`,t)}}catch{return{kind:"failure",result:y(`Source "${e.source}" exposes multiple skills. Re-run with --list or --skill <skill-slug>. Available skills: ${t.map(n=>n.value).join(", ")}.`,e.flags.json)}}}function _i(e,t,n){if(n.all&&t)return P({status:"error",reasonCode:"conflicting_source_selection",source:e,selectedSkillSlug:t,all:!0,nextAction:"install",nextStep:"Use either --all to install every discovered skill or --skill <skill-slug> to install one skill, not both."},"Source install cannot combine --all with --skill. Choose one selection mode before retrying.",n.json,"conflicting_source_selection")}function $i(e,t){try{if(Qe(e).kind!=="local")return}catch{return}return P({status:"error",reasonCode:"invalid_source",source:e,nextAction:"install",nextStep:ut(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source URL, or run `skills-layer install --source <source> --list` with a supported source."},ut(e)?`Install source ${e} was not found or is not readable.`:`Install source "${e}" is not a supported remote source and no local path was found.`,t.json,"invalid_source")}function Ca(e,t,n,i){return P({status:"not_found",reasonCode:"source_skill_not_found",source:e,requestedSkillSlug:t,availableSkills:n,nextAction:"install.source.list",nextStep:`Run \`skills-layer install --source ${e} --list\` to inspect discovered skills, then retry with one of the listed slugs.`},`Source ${e} does not contain a discovered skill named ${t}. Run with --list to inspect available skills.`,i.json,"source_skill_not_found")}function Ve(e){let t=[e.results,e.skills,e.discoveredSkills,S(e,"source")?.results,S(e,"inspection")?.results],n=new Set,i=[];for(let r of t)if(Array.isArray(r))for(let s of r){let o=xa(s);!o||n.has(o.value)||(n.add(o.value),i.push(o))}return i}function xa(e){if(!$(e))return;let t=l(e,"skillSlug")??l(e,"slug")??l(e,"name");if(!t)return;let n=l(e,"displayName")??l(e,"title")??l(e,"name"),i=n&&n!==t?`${t} - ${n}`:t,r=S(e,"parsedSkill"),s=S(e,"frontmatter")??(r?S(r,"frontmatter"):void 0),o=l(e,"shortDescription")??l(e,"summary")??l(e,"description")??(s?l(s,"description"):void 0)??l(e,"relativeSkillRoot")??l(e,"path")??l(e,"discoveryRoute")??l(e,"sourceKind");return o?{value:t,label:i,description:o}:{value:t,label:i}}function Ii(e,t,n){return _({...e,skillSlug:t,scope:p(n.scope),agent:p(n.agent),workspace:p(n.workspace),version:p(n.version),visibility:p(n.visibility)??"private",category:p(n.category),displayName:p(n.displayName),skillType:p(n.skillType),all:n.all,quarantine:n.quarantine,acceptCapability:n.acceptCapability})}function Qt(e,t,n,i){return _({status:"dry_run",source:e,selectedSkillSlug:n,all:i.all,scope:p(i.scope)??"local",agent:p(i.agent),workspace:p(i.workspace),quarantine:i.quarantine,acceptCapability:i.acceptCapability,candidates:Ve(t).map(r=>({skillSlug:r.value,name:r.label,description:r.description})),nextStep:i.all?`Re-run without --dry-run to install every discovered skill from ${e}.`:`Re-run without --dry-run${n?"":" and add --skill <skill-slug> if needed"} to install from ${e}.`})}async function Ne(e,t,n,i){try{return{kind:"ok",inspection:await v(e,"/api/v1/source-inspect",{method:"POST",headers:A(e.apiKey),body:JSON.stringify(_(n))})}}catch(r){if(r instanceof I)return{kind:"failure",result:_a(t,r,i)};throw r}}function Xt(e,t,n){if(Ve(t).length>0)return null;let r=Ra(t);return P({status:"unsupported_source_layout",source:e,reasonCode:"source_no_discoverable_skills",issues:r,nextStep:"Run with --list to inspect the source, use a subfolder containing SKILL.md, or install from a Skills Layer-compatible source layout."},$a(e,r),n.json)}function Ra(e){return(Array.isArray(e.issues)?e.issues:[]).filter($).map(n=>({...l(n,"code")?{code:l(n,"code")}:{},...l(n,"message")?{message:l(n,"message")}:{},...l(n,"path")?{path:l(n,"path")}:{}}))}function _a(e,t,n){let i=t.details??{},r=l(i,"error")??t.message;if(pr(t.status,r))return gr(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return yt(t,n.json);let o={status:"unsupported_source_layout",source:e,reasonCode:"source_not_inspectable",backendStatus:t.status,backendMessage:r,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return P(o,`Source ${e} could not be inspected as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}function ji(e,t,n){let i=t.details??{},r=l(i,"error")??t.message;if(pr(t.status,r))return gr(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return yt(t,n.json);let o={status:"unsupported_source_layout",source:e,reasonCode:"source_not_installable",backendStatus:t.status,backendMessage:r,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return P(o,`Source ${e} could not be installed as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}function pr(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function gr(e,t,n,i){let r=t.details??{},s=l(r,"error")??t.message,a=`skills-layer source connection start --provider ${mr(e)} --source ${e} --visibility private --provenance-intent private_source_import`,c={status:"private_source_access_required",source:e,reasonCode:"private_source_access_required",backendStatus:t.status,backendMessage:s,nextStep:a};return P(c,`Cloud could not ${i} ${e} directly. If this is a private source, start a private source connection first:
|
|
1137
|
+
${a}`,n.json,"private_source_access_required")}function mr(e){return/gitlab\./iu.test(e)?"gitlab":/github\./iu.test(e)||/^gh:/iu.test(e)?"github":"generic_git"}function $a(e,t){let n=[`No Skills Layer-compatible skills were found in ${e}.`];if(t.length>0){n.push("Detected issues:");for(let i of t.slice(0,5)){let r=i.code??"source-inspection";n.push(`- ${r}: ${i.message??"No details returned."}${i.path?` (${i.path})`:""}`)}}return n.push("Try --list, a subfolder containing SKILL.md, or a Skills Layer-compatible source layout."),n.join(`
|
|
1138
|
+
`)}async function Ia(e,t,n){if(hr(e)){let s=l(e,"reasonCode")??l(e,"reason")??"install_not_ready",o=l(e,"why")??l(e,"summary")??"The requested skill is not ready to install from this backend.";return P(e,`Install preview is not ready: ${o}`,t.json,s)}let i=await yr(e,n),r=Array.isArray(i.warnings)&&i.warnings.length>0;return ja(i,r?"Install preview ready with warnings.":"Install preview ready.",t,n)}function ja(e,t,n,i){return n.json?h(e,t,!0,i):{exitCode:0,stdout:vn(e,t,i),stderr:""}}async function fr(e,t,n,i){if(hr(e)){let s=l(e,"reasonCode")??l(e,"reason")??"workspace_deploy_not_ready",o=l(e,"why")??l(e,"summary")??l(e,"nextStep")??"The requested workspace deployment is not ready.";return P(e,`Workspace deployment preview is not ready: ${o}`,n.json,s)}let r=await yr(e,i);return n.json?h(r,t,!0,i):{exitCode:0,stdout:vn(r,t,i),stderr:""}}function hr(e){let t=l(e,"status")?.toLowerCase(),n=l(e,"reasonCode")?.toLowerCase();return t==="not_found"||t==="missing"||t==="blocked"||t==="not_ready"||n==="skill_not_found"||n==="not_found"}async function yr(e,t){let n=Ai(e);if(n)return{...e,...n};let i=l(e,"skillSlug")??l(e,"slug");if(!i)return e;try{let r=await v(t,`/api/v1/skills/${encodeURIComponent(i)}/trust`),s=Ai(r);return s?{...e,...s}:e}catch{return e}}function Ai(e){let t=S(e,"securityReport")??S(e,"report")??e,n=S(e,"trust")??S(t,"trust")??t,i=S(e,"securityPosture")??S(t,"securityPosture"),r=S(e,"capabilityProfile")??S(t,"capabilityProfile"),s=_({securityScore:O(n,"securityScore")??O(n,"score")??O(e,"securityScore")??(i?O(i,"securityScore"):void 0),runtimeRisk:l(n,"runtimeRisk")??l(e,"runtimeRisk")??(i?l(i,"runtimeRisk"):void 0)??(r?l(r,"runtimeRisk"):void 0),recommendation:l(n,"recommendation")??l(e,"recommendation")??(i?l(i,"recommendation"):void 0),detectedCapabilities:ge(n,"detectedCapabilities")??ge(e,"detectedCapabilities")??(r?ge(r,"detectedCapabilities"):void 0),capabilityMismatches:ge(n,"capabilityMismatches")??ge(e,"capabilityMismatches")??(r?ge(r,"capabilityMismatches"):void 0),organizationPolicyDecision:l(n,"organizationPolicyDecision")??l(n,"policyDecision")??l(e,"organizationPolicyDecision")??l(e,"policyDecision")??(i?l(i,"organizationPolicyDecision"):void 0)});if(Object.keys(s).length!==0)return _({trust:s,runtimeRisk:l(s,"runtimeRisk"),detectedCapabilities:Array.isArray(s.detectedCapabilities)?s.detectedCapabilities:void 0,capabilityMismatches:Array.isArray(s.capabilityMismatches)?s.capabilityMismatches:void 0,organizationPolicyDecision:l(s,"organizationPolicyDecision"),warnings:ge(e,"warnings")??ge(t,"warnings")??ge(n,"warnings")})}function Aa(e){let t=S(e,"securityPosture"),n=S(e,"trust"),i=t?O(t,"securityScore"):void 0,r=n?O(n,"securityScore")??O(n,"score"):void 0;return i===void 0&&r===void 0?e:_({...e,...t?{securityPosture:{...t,scoreLabel:"published_ledger_score"}}:{},...n?{trust:{...n,scoreLabel:"effective_buyer_trust_score"}}:{},publishedLedgerScore:i,effectiveBuyerTrustScore:r})}function at(e,t,n,i){return n?h(e,t,!0,i):{exitCode:0,stdout:vn(e,t,i),stderr:""}}function La(e,t,n){let i=Z(n),r=Array.isArray(e.runs)?e.runs.filter($):[],s=r.flatMap(c=>Array.isArray(c.results)?c.results.filter($):[]),o=r.flatMap(c=>{let u=S(c,"tool"),d=u?S(u,"driver"):void 0;return d&&Array.isArray(d.rules)?d.rules.filter($):[]}),a=[`${i.ok("OK")} Trust report loaded.`,"",i.section("SARIF")];if(a.push(` ${i.label("Skill")}: ${t}`),a.push(` ${i.label("Runs")}: ${r.length}`),a.push(` ${i.label("Rules")}: ${o.length}`),a.push(` ${i.label("Results")}: ${s.length}`),s.length===0)a.push(` ${i.muted("No SARIF findings found.")}`);else{a.push("",i.section("Findings"));for(let[c,u]of s.slice(0,N).entries()){let d=l(u,"ruleId")??"unknown-rule",g=S(u,"message");a.push(`${c+1}. ${d}${g?` - ${l(g,"text")??""}`:""}`)}}return a.push("",i.section("Next")),a.push(` ${i.arrow} skills-layer trust ${t} --format sarif --json`),a.join(`
|
|
1139
|
+
`)}function vn(e,t,n){let i=Z(n),r=[`${i.ok("OK")} ${t}`],s=l(e,"skillSlug")??l(e,"slug"),o=l(e,"version")??l(e,"currentVersion");(s||o)&&(r.push("",i.section("Skill")),s&&r.push(` ${i.label("Slug")}: ${s}`),o&&r.push(` ${i.label("Version")}: ${o}`));let a=l(e,"visibility")??l(e,"versionVisibility"),c=l(e,"publicationStatus"),u=l(e,"catalogRecord");(a||c||u)&&(r.push("",i.section("Privacy")),a&&r.push(` ${i.label("Visibility")}: ${a}`),c&&r.push(` ${i.label("Publication")}: ${c}`),u&&r.push(` ${i.label("Catalog record")}: ${u}`));let d=S(e,"materializationPlan")??S(e,"installPlan"),g=l(e,"scope")??(d?l(d,"scope"):void 0),f=l(e,"agent")??l(e,"targetAgent")??(d?l(d,"agent")??l(d,"targetAgent"):void 0),m=Array.isArray(e.materializedWrites)?e.materializedWrites.filter($):[];if(g||f||m.length>0)if(r.push("",i.section("Local Materialization")),g&&r.push(` ${i.label("Scope")}: ${g}`),f&&r.push(` ${i.label("Agent")}: ${f}`),m.length===0)r.push(` ${i.muted("No local files were written by this command.")}`);else for(let C of m.slice(0,N)){let x=l(C,"path");x&&r.push(` ${i.arrow} ${x}`)}let k=Fr(e,i).filter(C=>!C.includes("materialized writes:"));k.length>0&&r.push("",...k);let w=Vr(e);return w.length>0&&r.push("",i.section("Next"),...w.map(C=>` ${i.arrow} ${C}`)),r.join(`
|
|
1140
|
+
`)}function Ea(e,t){let n=S(e,"trust"),i=S(e,"securityPosture"),r=S(e,"capabilityProfile"),s=n?.securityScore??n?.score??e.securityScore??i?.securityScore,o=T(n,"runtimeRisk")??l(e,"runtimeRisk")??T(i,"runtimeRisk")??T(r,"runtimeRisk"),a=T(n,"recommendation")??l(e,"recommendation")??T(i,"recommendation"),c=T(n,"label")??T(n,"trust")??l(e,"trustStatus")??l(e,"trust")??T(i,"label");if(s===void 0&&!o&&!a&&!c)return[];let u=[t.section("Trust")];return s!==void 0&&u.push(` ${t.label("Security score")}: ${z("securityScore",s)}`),o&&u.push(` ${t.label("Runtime risk")}: ${o}`),a&&u.push(` ${t.label("Recommendation")}: ${a}`),c&&u.push(` ${t.label("Status")}: ${c}`),u.push(` ${t.label("Source")}: skills-layer trust`),u}async function Ua(e,t){let n=kn("installed",e);if(n.failure)return n.failure;let i=await we(t),r=Object.values(i.installs).filter(s=>{let o=l(s,"scope"),a=l(s,"agent");return(!n.scope||o===n.scope)&&(!n.agent||a===n.agent)});return h({status:"ok",results:r},`Found ${r.length} local install records.`,e.json,t)}async function Ta(e,t,n){let i=b(e[0],"remove requires a skill slug."),r=rr("remove",t);if(r)return r;let s=await we(n),o=s.installs[i];if(!o)return P({status:"not_installed",reasonCode:"local_install_not_found",skillSlug:i},`${i} is not installed locally. Run \`skills-layer installed\` or \`skills-layer sync\` to inspect local records.`,t.json,"local_install_not_found");delete s.installs[i],await Ur(n,s);let a={status:"removed",skillSlug:i,removedRecord:o};return t.json?h(a,`Removed ${i}.`,!0,n):{exitCode:0,stdout:Va(i,n),stderr:""}}async function Ba(e,t,n){let i=b(e[0],"update requires a skill slug."),r=new URLSearchParams,s=p(t.pin);if(s&&!Sn(s))return P({status:"error",reasonCode:"invalid_pin",skillSlug:i,requestedPin:s,nextAction:"update",nextStep:"Use --pin with a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --pin "${s}". Use a semver version or an external-<digest> version.`,t.json,"invalid_pin");F(r,"pin",s),t.dryRun&&r.set("dryRun","true");let a=(await we(n)).installs[i],c;try{c=await v(n,`/api/v1/skills/${encodeURIComponent(i)}${oe(r)}`,{headers:M(n.apiKey,n.authBlockedMessage)})}catch(d){if(d instanceof I&&d.status===404&&a){let g={status:"backend_missing",reasonCode:"local_install_backend_missing",skillSlug:i,localInstall:a,installedVersion:l(a,"version")??l(a,"currentVersion"),selectedBackend:n.baseUrl,nextStep:`This skill is installed locally, but no catalog update source was found on ${n.baseUrl}. Reinstall from its source, run \`skills-layer search ${i}\`, or run \`skills-layer remove ${i}\` if you no longer need it.`};return P(g,`${i} is installed locally, but no catalog update source was found on this backend. Reinstall from its source, search for a replacement, or remove the local install.`,t.json,"local_install_backend_missing")}if(d instanceof I)return yt(d,t.json);throw d}let u=Fa(i,c,a,n);return s&&t.dryRun&&!Na(u,s)?P({status:"not_found",reasonCode:"pin_not_resolved",skillSlug:i,requestedPin:s,installedVersion:l(a,"version")??l(a,"currentVersion"),currentVersion:l(u,"currentVersion"),nextAction:"update",nextStep:`Choose a version returned by \`skills-layer show ${i} --json\` or omit --pin to check the latest available version.`},`${i} does not have a resolvable version for --pin ${s}.`,t.json,"pin_not_resolved"):t.json?h(u,"Update check complete.",!0,n):{exitCode:0,stdout:Ka(u,n),stderr:""}}function Sn(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u.test(e)||/^external-[0-9A-Za-z][0-9A-Za-z._-]*$/u.test(e)}function Na(e,t){let n=[l(e,"version"),l(e,"currentVersion"),l(e,"latestVersion"),l(e,"targetVersion"),l(e,"availableVersion")].filter(Boolean),i=S(e,"update");return i&&n.push(l(i,"version"),l(i,"currentVersion"),l(i,"latestVersion"),l(i,"targetVersion"),l(i,"availableVersion")),n.some(r=>r===t)}async function Ma(e,t){let n=kn("sync",e);if(n.failure)return n.failure;let i=await we(t),r=Object.values(i.installs).filter(a=>{let c=l(a,"scope"),u=l(a,"agent");return(!n.scope||c===n.scope)&&(!n.agent||u===n.agent)}),o={status:"synced",results:await Promise.all(r.map(async a=>Oa(a,t)))};return e.json?h(o,"Local install records synced.",!0,t):{exitCode:0,stdout:Ga(o,t),stderr:""}}function Fa(e,t,n,i){let r=n?l(n,"version")??l(n,"currentVersion"):void 0,s=l(t,"currentVersion")??l(t,"version"),o=n?r&&s&&r!==s?"update_available":"up_to_date":"not_installed";return _({...t,skillSlug:l(t,"skillSlug")??l(t,"slug")??e,updateStatus:o,installedVersion:r,latestAvailableVersion:s,selectedBackend:i.baseUrl,localInstall:n,nextStep:o==="not_installed"?`Run \`skills-layer install ${e}\` to install this skill locally.`:o==="update_available"?`Run \`skills-layer install ${e}\` to apply the latest available version.`:`No update is needed for ${e}.`})}async function Oa(e,t){let n=l(e,"skillSlug")??l(e,"slug");if(!n)return{...e,syncStatus:"local_only",backendStatus:"unchecked"};try{let i=await v(t,`/api/v1/skills/${encodeURIComponent(n)}`,{headers:He(t.apiKey)}),s=(l(i,"claimedOrigin")??l(i,"sourceKind")??l(e,"sourceKind"))==="public_source"||l(e,"sourceKind")==="external";return{...e,syncStatus:s?"source_backed":"catalog_backed",backendStatus:"found",latestAvailableVersion:l(i,"currentVersion")??l(i,"version"),catalog:qa(i)}}catch(i){return i instanceof I&&i.status===404?{...e,syncStatus:"backend_missing",backendStatus:"not_found",selectedBackend:t.baseUrl}:{...e,syncStatus:"unchecked",backendStatus:"error",backendError:ae(i)}}}function qa(e){return _({slug:l(e,"slug")??l(e,"skillSlug"),currentVersion:l(e,"currentVersion")??l(e,"version"),claimedOrigin:l(e,"claimedOrigin"),trust:l(e,"trust")??l(e,"publicationStatus")})}function Ka(e,t){let n=Z(t),i=l(e,"skillSlug")??l(e,"slug")??"skill",r=l(e,"updateStatus")??"checked",s=[`${n.ok("OK")} Update check complete.`,"",n.section("Update")];s.push(` ${n.label("Skill")}: ${i}`),s.push(` ${n.label("Status")}: ${r.replaceAll("_"," ")}`);let o=l(e,"installedVersion"),a=l(e,"latestAvailableVersion");o&&s.push(` ${n.label("Installed version")}: ${o}`),a&&s.push(` ${n.label("Latest available version")}: ${a}`);let c=S(e,"localInstall"),u=c?l(c,"materializedPath")??l(c,"path"):void 0,d=c?l(c,"scope"):void 0,g=c?l(c,"targetAgent")??l(c,"agent"):void 0;c&&(s.push("",n.section("Local Install")),d&&s.push(` ${n.label("Scope")}: ${d}`),g&&s.push(` ${n.label("Agent")}: ${g}`),u&&s.push(` ${n.label("Path")}: ${u}`));let f=l(e,"nextStep");return f&&s.push("",n.section("Next"),` ${n.arrow} ${f}`),s.join(`
|
|
1141
|
+
`)}function Ga(e,t){let n=Z(t),i=[`${n.ok("OK")} Local install records synced.`,"",n.section(`Results (${e.results.length})`)];return e.results.length===0?(i.push(` ${n.muted("No local install records found.")}`),i.join(`
|
|
1142
|
+
`)):(e.results.slice(0,N).forEach((r,s)=>{let o=l(r,"skillSlug")??l(r,"slug")??`item-${s+1}`,a=l(r,"syncStatus")??"unchecked",c=l(r,"version")??l(r,"currentVersion");i.push(`${s+1}. ${o}`),i.push(` status: ${a.replaceAll("_"," ")}${c?`; version: ${c}`:""}`),a==="backend_missing"&&i.push(` ${n.muted("Installed locally, but missing from the selected backend catalog.")}`)}),e.results.length>N&&i.push(` ${n.muted(`... ${e.results.length-N} more`)}`),i.push("",n.section("Next")),i.push(` ${n.arrow} skills-layer installed`),i.push(` ${n.arrow} skills-layer update <skill-slug>`),i.join(`
|
|
1143
|
+
`))}function Va(e,t){let n=Z(t);return[`${n.ok("OK")} Removed ${e}.`,"",n.section("Local Install"),` ${n.label("Skill")}: ${e}`,` ${n.label("Status")}: removed locally`,"",n.section("Next"),` ${n.arrow} skills-layer installed`,` ${n.arrow} skills-layer sync`].join(`
|
|
1144
|
+
`)}function Da(e,t,n){let i=Z(n),r=l(t,"version")??l(t,"currentVersion"),s=l(t,"scope");return[`${i.ok("OK")} Restore record found for ${e}.`,"",i.section("Local Install"),` ${i.label("Skill")}: ${e}`,...r?[` ${i.label("Version")}: ${r}`]:[],...s?[` ${i.label("Scope")}: ${s}`]:[],"",i.section("Next"),` ${i.arrow} skills-layer installed`,` ${i.arrow} skills-layer sync`,` ${i.arrow} skills-layer update ${e}`].join(`
|
|
1145
|
+
`)}function Ha(e){let t=l(e,"status"),n=l(e,"reasonCode");return t==="invalid_transition"||t==="forbidden"||t==="not_found"||n==="invalid_transition"}function za(e,t){let n=l(e,"why")??l(e,"reason")??l(e,"error"),i=l(e,"currentVisibility"),r=l(e,"nextVisibility")??l(e,"visibility"),s=i||r?` Current visibility: ${i??"unknown"}; requested visibility: ${r??"unknown"}.`:"",o=l(e,"nextStep")??`Run \`skills-layer creator status ${t}\` and choose a valid visibility transition.`;return`Visibility was not changed for ${t}.${s}${n?` ${n}`:""}
|
|
1146
|
+
Next step: ${o}`}async function Wa(e,t,n){let i=await we(n),r=e[0];if(!r){let a=Object.values(i.installs);return h({status:a.length>0?"restored":"no_op",results:a},`Restore checked ${a.length} local install record${a.length===1?"":"s"}.`,t.json,n)}let s=i.installs[r];if(!s)return P({status:"missing_record",reasonCode:"restore_record_not_found",skillSlug:r,record:null,nextAction:"installed",nextStep:`Run \`skills-layer installed\` to see local records, \`skills-layer sync\` to refresh status, or \`skills-layer search ${r}\` if you want to find a catalog/source replacement.`},`No restorable local install record was found for ${r}. Run \`skills-layer installed\`, \`skills-layer sync\`, or \`skills-layer search ${r}\` next.`,t.json,"restore_record_not_found");let o={status:"restored",skillSlug:r,record:s};return t.json?h(o,`Restore checked for ${r}.`,!0,n):{exitCode:0,stdout:Da(r,s,n),stderr:""}}async function Ja(e,t,n){let i=b(e[0],"check requires a skill slug.");return await R(`/api/v1/skills/${encodeURIComponent(i)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function Ya(e,t,n){let i=b(e[0]??t.source,"import requires a source."),r=await pt(i,n.cwd);if(!r){let o=Za(i,t);if(o)return o}let s=await v(n,"/api/v1/source-imports",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_({...r??{source:i},quarantine:t.quarantine,skillSlug:p(t.skill),visibility:p(t.visibility)}))});return await D(n.paths.importsPath,{version:1,lastImport:s,savedAt:n.now()}),h(s,"Source import submitted.",t.json,n)}function Za(e,t){try{return Qe(e).kind!=="local"?null:P({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:ut(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or --help for import examples."},ut(e)?`Import source ${e} was not found or is not readable.`:`Import source "${e}" is not a supported source. Use a local path, GitHub/GitLab source, or URL.`,t.json,"invalid_source")}catch(n){return P({status:"error",reasonCode:"invalid_source",source:e,error:ae(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${ae(n)}`,t.json,"invalid_source")}}function ut(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}async function Qa(e,t,n){let i=e[0];if(i==="reference"&&e[1]==="resolve"){let r=b(e[2],"source reference resolve requires a reference."),s=await v(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(r)}`);return s.status==="not_found"?P({...s,status:"not_found",reasonCode:"source_reference_not_found",reference:r,nextAction:"source.connection.start",nextStep:"Start or complete the source connection before resolving this reference."},`Source reference ${r} was not found.`,t.json,"source_reference_not_found"):h(s,"Source reference resolved.",t.json,n)}return i==="connection"?await Xa(e.slice(1),t,n):y(`Unknown source command "${e.join(" ")}".`,t.json)}async function Xa(e,t,n){let i=e[0];if(i==="start"){let s=p(t.provider),o=p(t.source),a=p(t.visibility),c=el(s,o,a,t);return c||await q("/api/v1/me/source-connections",G(t,["provider","source","skill","mode","visibility","priceCents","license","provenanceIntent","discloseSource"]),t,n,"Source connection started.")}let r=b(e[1],`source connection ${i??""} requires a connection id.`);return i==="status"?await R(`/api/v1/me/source-connections/${encodeURIComponent(r)}`,t,n,"Source connection loaded.",{authenticated:!0}):i==="complete"?await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/complete`,G(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed."):i==="cancel"?await q(`/api/v1/me/source-connections/${encodeURIComponent(r)}/cancel`,{},t,n,"Source connection cancelled."):y(`Unknown source connection command "${i??""}".`,t.json)}function el(e,t,n,i){if(n){let r=$t(n);if(!r||!Ft.includes(r))return P({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:Ft,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${Ft.join(", ")}.`,i.json,"invalid_visibility")}if(!e||!t)return null;try{let r=Qe(t);if((e==="github"||e==="gitlab")&&r.kind!==e)return qt(e,t,i);if(e==="domain"){let s=new URL(t);if(s.protocol!=="https:"||!s.hostname)return qt(e,t,i)}}catch{return qt(e,t,i)}return null}function qt(e,t,n){return P({status:"error",reasonCode:"invalid_source",provider:e,source:t,nextAction:"source.connection.start",nextStep:e==="github"?"Use a GitHub source such as https://github.com/OWNER/REPO or github:OWNER/REPO.":e==="gitlab"?"Use a GitLab source such as https://gitlab.com/GROUP/REPO or gitlab:GROUP/REPO.":"Use a valid source URL or provider-specific source."},`Invalid ${e} source "${t}".`,n.json,"invalid_source")}async function tl(e,t,n){if(e[0]!=="request")return y(`Unknown approval command "${e[0]??""}".`,t.json);let i=e[1],r=b(e[2],`approval request ${i??""} requires an approval id.`);return i==="status"?await R(`/api/v1/me/approvals/${encodeURIComponent(r)}`,t,n,"Approval status loaded.",{authenticated:!0}):i==="complete"?await q(`/api/v1/me/approvals/${encodeURIComponent(r)}/complete`,_({decision:p(t.decision),evidence:kt(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed."):y(`Unknown approval request command "${i??""}".`,t.json)}async function nl(e,t,n){let i=e[0]??"list";if(i==="list")return await R("/api/v1/me/workspaces",t,n,"Workspaces loaded.",{authenticated:!0});if(i==="create")return await q("/api/v1/workspaces",{name:e.slice(1).join(" "),kind:p(t.kind)},t,n,"Workspace created.");let r=b(e[1],`workspace ${i} requires a workspace id.`);if(i==="skills")try{return await R(`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0})}catch(s){if(s instanceof I&&(s.status===403||s.status===404))return Kt(r,t);throw s}if(i==="deploy"){let s=b(e[2],"workspace deploy requires a skill slug."),o;try{o=await v(n,`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,{method:"POST",headers:A(n.apiKey),body:JSON.stringify(_({skillSlug:s,dryRun:t.dryRun}))})}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return Kt(r,t);throw a}return t.dryRun?await fr(o,"Workspace deployment preview ready.",t,n):h(o,"Workspace deployment requested.",t.json,n)}if(i==="remove"){let s=b(e[2],"workspace remove requires a skill slug.");try{return await ft(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}`,{method:"DELETE",headers:M(n.apiKey,n.authBlockedMessage)},t,n,"Workspace skill removed.")}catch(o){if(o instanceof I&&o.status===404)return Li(r,s,t);if(o instanceof I&&o.status===403)return Kt(r,t);throw o}}if(i==="guide"){let s=b(e[2],"workspace guide requires a skill slug.");try{return await R(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}catch(o){if(o instanceof I&&o.status===404)return Li(r,s,t);throw o}}return y(`Unknown workspace command "${i}".`,t.json)}function Kt(e,t){return P({status:"not_found_or_forbidden",reasonCode:"workspace_not_found_or_forbidden",workspaceId:e,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` to find a workspace you can access, then retry with that workspace id."},`Workspace ${e} was not found or you do not have access. Run \`skills-layer workspace list\` to inspect accessible workspaces.`,t.json,"workspace_not_found_or_forbidden")}function Li(e,t,n){let i={status:"deployment_not_found",reasonCode:"workspace_deployment_not_found",workspaceId:e,skillSlug:t,nextAction:"workspace.deploy",nextStep:`Run \`skills-layer workspace deploy ${e} ${t}\` first, then run \`skills-layer workspace guide ${e} ${t}\` after the deployment exists.`};return P(i,`Workspace deployment not found for ${t}. Run \`skills-layer workspace deploy ${e} ${t}\` first.`,n.json,"workspace_deployment_not_found")}async function il(e,t,n){let i=b(e[0],"buy requires a skill slug."),r=Uo(t);if(r.failure)return r.failure;let s=await v(n,"/api/v1/buy",{method:"POST",headers:A(n.apiKey),body:JSON.stringify({skillSlug:i,paymentMethod:r.value})});if(s.status==="already_owned")return h(s,`You already own ${i}. Run \`skills-layer install ${i}\` to install or update it.`,t.json,n);if(t.json||s.status!=="checkout_required"||typeof s.checkoutUrl!="string"||typeof s.purchaseId!="string")return h(s,`Purchase flow started for ${i}.`,t.json,n);n.emitInfo(`Opening checkout for ${i}. Complete the payment in your browser, then come back here.`),await n.openUrl(s.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${s.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let a=await Bl(s.purchaseId,n);return H(a)?a:a.status!=="succeeded"&&a.status!=="refund_requested"?h({...s,purchaseStatus:a.status},`Checkout is still ${a.status} for ${i}. You can rerun install after payment reconciliation completes.`,t.json,n):(n.emitInfo("Payment confirmed. Continuing with install."),await wn([i],t,n))}async function rl(e,t,n){let i=e[0]??"list";if(i==="list")return await R("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(i==="spending")return await R("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let r=b(e[1],`purchases ${i} requires a purchase id.`);return i==="invoice"?await R(`/api/v1/purchases/${encodeURIComponent(r)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0}):i==="refund-quote"?await R(`/api/v1/purchases/${encodeURIComponent(r)}/refund-quote`,t,n,"Refund quote loaded.",{authenticated:!0}):i==="refund"?await q(`/api/v1/purchases/${encodeURIComponent(r)}/refund`,G(t,["reason"]),t,n,"Refund requested."):y(`Unknown purchases command "${i}".`,t.json)}async function sl(e,t,n){let i=e[0];if(i==="add"){let r=b(e[1],"library add requires a skill slug.");return await q("/api/v1/install",{skillSlug:r},t,n,"Skill added to library.")}return y(`Unknown library command "${i}".`,t.json)}async function ol(e,t,n){let i=b(e[0],"export requires a skill slug."),r=new URLSearchParams,s=p(t.version);if(s&&!Sn(s))return sr("export",s,t);F(r,"version",s);let o=await v(n,`/api/v1/me/library/${encodeURIComponent(i)}/export${oe(r)}`,{headers:M(n.apiKey,n.authBlockedMessage)}),a=p(t.output);if(a){let c=await lr({backend:n,exportResult:o,flags:t,skillSlug:i});if(H(c))return c;let u=J(n.cwd,a);await an(u,c.bytes);let d={...o};return delete d.downloadUrl,h({...d,archiveSha256:c.archiveSha256,archiveSha256Meaning:"canonical_bundle_sha256",canonicalBundleSha256:c.archiveSha256,downloadedArchiveSha256:c.archiveBytesSha256,downloadedFileSha256:c.archiveBytesSha256,archiveHashFormat:c.archiveHashFormat,outputPath:u,downloaded:!0},`Exported ${i} to ${u}. Downloaded file SHA-256: ${c.archiveBytesSha256}.`,t.json,n)}return h(o,a?`Exported ${i} to ${a}.`:"Export prepared.",t.json,n)}async function Ei(e,t,n,i){let r=b(t[0],`${e==="add"?"add-review":"show-reviews"} requires a skill slug.`);return e==="show"?await R(`/api/v1/me/library/reviews?skillSlug=${encodeURIComponent(r)}`,n,i,"Reviews loaded.",{authenticated:!0}):await q(`/api/v1/me/library/${encodeURIComponent(r)}/review`,G(n,["rating","feedback"]),n,i,"Review added.")}async function Ui(e,t,n,i){let r=b(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);return e==="show"?await R(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0}):await q(`/api/v1/me/library/${encodeURIComponent(r)}/report-issue`,G(n,["issueType","message"]),n,i,"Issue reported.")}async function al(e,t,n){let i=e[0];if(i==="hook"){let r=e[1];return r==="install"?await en(t,n):r==="status"?await dl(t,n):y(`Unknown guardian hook command "${r??""}".`,t.json)}if(i==="enable")return e[1]||t.skill?await Gt("enforce",e,t,n):await en(t,n);if(i==="disable")return await Gt("disabled",e,t,n);if(i==="enable-warnings-only")return await Gt("warning_only",e,t,n);if(i==="status")return await cl(e,t,n);if(i==="exec")return await ll(e,t,n);if(i==="check"){let r=b(e[1]??t.skill,"guardian check requires a skill slug."),s=Ki(t,"check"),o=t.grantJson.map(k=>Ln(k,"grant-json")),a=Mc(t.cloudTrustLedger);if(a.status==="invalid")return y(a.message,t.json);let c=tn(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(c.status==="invalid")return y(c.message,t.json);let u=await br({skillSlug:r,version:p(t.version),action:s,flags:t,backend:n,telemetryMode:c.mode});if(u.status!=="ok")return u.result;let d=u.context.installedPath,g=p(t.version)??u.context.version,f=_({skillSlug:r,version:g,action:s,authorizationGrants:o,path:d,guardianPreference:await Cn(n,r),unmanagedPolicy:u.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:c.mode,localPreflight:ye(u.context)}),m=await v(n,"/api/v1/guardian/enforce",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(f)});return await Me(n,{skillSlug:r,version:g,action:s,decisionStatus:dt(m),reasonCode:nn(m),telemetryMode:c.mode,path:d}),h({...m,localPreflight:ye(u.context)},"Guardian check complete.",t.json,n)}if(i==="incident"){let r=b(e[1]??t.skill,"guardian incident requires a skill slug."),s=b(t.version,"guardian incident requires --version."),o=tn(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return y(o.message,t.json);let a=p(t.path)??(await vr({skillSlug:r,flags:t,backend:n})).installedPath,c=Ki(t,"incident"),u=kt(t.evidenceJson,"evidence-json"),d=o.mode==="cloud_managed"&&!n.apiKey?"local_only":o.mode,g=_({skillSlug:r,version:s,action:c,evidence:u,path:a,telemetryMode:d,incident:!0,reason:p(t.reason)});if(d==="local_only"){if(!a)return y("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let w=await Fi({backend:n,skillSlug:r,version:s,installedPath:a,action:c,reason:p(t.reason)??"Guardian local-only incident"});await Me(n,{skillSlug:r,version:s,action:c,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:d,path:a});let C=Oi(n,r);return await re(C,JSON.stringify({request:g,response:null,localResponse:w,savedAt:n.now()},null,2)),h({status:"written",skillSlug:r,version:s,telemetryMode:d,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:w,incidentStatePath:C,incidentPath:w.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let f=await v(n,"/api/v1/guardian/enforce",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(g)}),m=a?await Fi({backend:n,skillSlug:r,version:s,installedPath:a,action:c,reason:p(t.reason)??"Guardian Cloud-managed incident"}):null;await Ke(n.paths.incidentsDir,{recursive:!0});let k=Oi(n,r);return await re(k,JSON.stringify({request:g,response:f,localResponse:m,savedAt:n.now()},null,2)),await Me(n,{skillSlug:r,version:s,action:c,decisionStatus:dt(f),reasonCode:nn(f),telemetryMode:o.mode,path:a}),h({...f,telemetryMode:o.mode,localResponse:m,incidentPath:k},"Guardian incident recorded.",t.json,n)}return y(`Unknown guardian command "${i??""}".`,t.json)}async function ll(e,t,n){let i=p(t.skill),r=b(i??e[1],"guardian exec requires a skill slug."),s=i?e.slice(1):e.slice(2);if(s.length===0)return y("guardian exec requires a command after --.",t.json);let o=tn(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return y(o.message,t.json);let a=wl(t,s),c=await br({skillSlug:r,version:p(t.version),action:a,flags:t,backend:n,telemetryMode:o.mode});if(c.status!=="ok")return c.result;let u=c.context.installedPath,d=p(t.version)??c.context.version,g=_({skillSlug:r,version:d,action:a,authorizationGrants:t.grantJson.map(C=>Ln(C,"grant-json")),path:u,guardianPreference:await Cn(n,r),telemetryMode:o.mode,localPreflight:ye(c.context)}),f=await v(n,"/api/v1/guardian/enforce",{method:"POST",headers:A(n.apiKey),body:JSON.stringify(g)}),m=dt(f),k=nn(f);if(await Me(n,{skillSlug:r,version:d,action:a,decisionStatus:m,reasonCode:k,telemetryMode:o.mode,path:u}),!bl(f))return P({status:"blocked",reasonCode:k,skillSlug:r,guardian:f,localPreflight:ye(c.context),command:{executable:K(s[0]??""),executed:!1}},"Guardian blocked guarded execution.",t.json,k);if(t.dryRun)return h({status:"allowed",skillSlug:r,guardian:f,localPreflight:ye(c.context),command:{executable:K(s[0]??""),executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let w=await vl(s,n);return{exitCode:w.exitCode,stdout:t.json?JSON.stringify({status:w.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:r,guardian:f,localPreflight:ye(c.context),command:w},warnings:[],links:[],reasonCode:w.exitCode===0?null:"command_failed",handoff:null},null,2):Sl(w),stderr:w.stderr}}async function Gt(e,t,n,i){let r=b(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),s=await v(i,"/api/v1/guardian/mode",{method:"POST",headers:A(i.apiKey),body:JSON.stringify({skillSlug:r,requestedPreference:e,source:"public-cli"})});return s.preferenceAccepted===!0&&await Pl(i,r,s),h(s,s.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,i)}async function cl(e,t,n){let i=p(t.skill)??p(e[1]),r=await kr(n,i),s=await De(n),o=i?await Cl(n,i):void 0,c=l(s,"enforcementLayer")!=="not_installed"&&!!s.strictPreActionBlocking?{status:"installed",reasonCode:"guardian_hook_installed",strictPreActionBlocking:!0,nextAction:"guardian.check",nextStep:"Cloud Guardian policy is enforced when checked, and the local host hook can block supported risky actions before execution."}:{status:"not_installed",reasonCode:"guardian_hook_not_installed",strictPreActionBlocking:!1,nextAction:"guardian.hook.install",nextStep:"Cloud Guardian policy is enforced when checked, but local pre-action blocking is not installed for this host. Run `skills-layer guardian hook install --agent codex --scope global` or `skills-layer setup`."};return h(_({status:"ok",skillSlug:l(r,"skillSlug")??i,policy:r,localPreference:o,hook:s,cloudPolicy:{status:l(r,"effectiveMode")??l(r,"status")??"unknown",reasonCode:l(r,"reasonCode"),enforcementBoundary:"cloud_policy_when_checked",nextAction:l(r,"nextAction"),nextStep:l(r,"nextStep")},localEnforcement:c,nextAction:l(c,"nextAction"),nextStep:l(c,"nextStep")}),"Guardian status loaded.",t.json,n)}async function kr(e,t){let n=t?await Cn(e,t):void 0;return await v(e,"/api/v1/guardian/status",{method:"POST",headers:A(e.apiKey),body:JSON.stringify(_({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function ul(e){if(!e.apiKey)return{status:"unknown",policySource:"cloud",reasonCode:"login_required",nextAction:"skills-layer login",nextStep:"Sign in to read the Cloud Guardian policy that applies to your account."};try{return await kr(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ae(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function en(e,t){let n=p(e.agent)??"codex",i=Pr(e.scope);if(i.status==="invalid")return y(i.message,e.json);let r=me(t.env,t.platform,t.cwd).find(g=>g.id===n);if(!r)return y(`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json);let s=xl(r,i.scope,t);if(!s)return y(`Guardian ${i.scope} hooks are not available for ${r.displayName}.`,e.json);await Rl(s,t);let o=Rr(t,i.scope),a=qi(Fe(t.cwd,s.hookPath)),c=qi(Fe(t.cwd,s.configPath)),d=[...(await _r(o)).hooks.filter(g=>l(g,"agent")!==r.id||l(g,"scope")!==i.scope),{hookId:pe,hookName:te,agent:r.id,agentName:r.displayName,scope:i.scope,hookPath:a.startsWith("..")?s.hookPath:a,configPath:c.startsWith("..")?s.configPath:c,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,enabledAt:t.now()}];return await D(o,{version:1,hooks:d}),h({status:"enabled",hookId:pe,hookName:te,agent:r.id,agentName:r.displayName,scope:i.scope,hookPath:s.hookPath,configPath:s.configPath,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,agentCommandMatrix:Et({purpose:"materialize_skill",command:"skills-layer install <skill-slug>",jsonCommand:"skills-layer install <skill-slug> --json"}),nextStep:"Guardian is installed into the selected host configuration. Local hooks call `skills-layer guardian check`; shell agents can route risky commands through `skills-layer guardian exec`; MCP-capable agents can call `guardian.check` or `guardian.enforce` before risky tool use.",warnings:s.enforcementLayer==="native_hook_candidate"?["This host does not expose the same stable native hook contract as Codex or Claude Code yet; Skills Layer records the guardrail config for host integration."]:[]},"Guardian hook enabled.",e.json,t)}async function dl(e,t){let n=p(e.scope),i=n?Pr(n):null;if(i?.status==="invalid")return y(i.message,e.json);let r=await De(t,i?.status==="valid"?i.scope:void 0);return h(r,"Guardian status loaded.",e.json,t)}async function De(e,t){let n=t?[t]:["project","global"],i=[];for(let a of n){let c=Rr(e,a),u=await _r(c);for(let d of u.hooks){let g=l(d,"hookPath"),f=g?Mi(e,a,g):null,m=l(d,"configPath"),k=m?Mi(e,a,m):null,w=f?await fe(f):!1,C=k?await fe(k):null,x=w?C===!1?"active_missing_config":"active":"stale_missing_hook";i.push({hookId:l(d,"hookId")??pe,hookName:l(d,"hookName")??te,...d,scope:l(d,"scope")??a,hookPath:f??g??null,configPath:k??m??null,active:w,configActive:C,hookState:x})}}let r=i.filter(a=>a.active===!0).length,s=i.filter(a=>a.active===!1).length,o=r>0?0:s;return{status:"ok",enforcementLayer:r>0?"native_hook":"not_installed",strictPreActionBlocking:i.some(a=>a.active===!0&&a.strictPreActionBlocking===!0),activeHookCount:r,missingHookCount:o,staleHookCount:s,hooks:i,setup:await xn(e),warnings:s>0?r>0?["One or more stale Guardian hook records were found, but an active Skills Layer Security Hook is installed."]:["One or more configured Guardian hooks are missing from disk. Run skills-layer guardian hook install --agent <agent> again to repair them."]:[]}}async function wr(e,t){if(e.json){let u=await Y(t.paths.mcpConfigPath);return h({setup:await xn(t),mcp:{status:u?"mcp_configured":"mcp_not_configured",configured:!!u,clientId:u?l(u,"clientId")??"codex":void 0,clientIds:u&&Array.isArray(u.clientIds)?u.clientIds:void 0,mcpUrl:u?l(u,"mcpUrl"):void 0,readiness:u?{status:"configured_needs_agent_reload",verifyCommand:`skills-layer mcp verify --client ${l(u,"clientId")??"codex"}`,nextStep:"Open a fresh agent session if Skills Layer tools are not visible yet."}:void 0,nextCommand:u?"skills-layer mcp verify":"skills-layer mcp setup"},guardian:await De(t)},"Setup status loaded.",!0,t)}if(!t.stdoutIsTty)return h({status:"setup_needs_terminal",mcp:{nextCommand:"skills-layer mcp setup"},security:{nextCommand:"skills-layer guardian hook install --agent codex --scope project"}},"Setup needs an interactive terminal. Run `skills-layer setup`, or use `skills-layer mcp setup` and `skills-layer guardian hook install --agent codex --scope project`.",!1,t);let n=await t.promptSelect("Set up Skills Layer on this machine?",[{value:"mcp",label:"Setup Skills-Layer MCP",description:"Configure Skills Layer MCP for AI tools"},{value:"security",label:"Setup Skills-Layer Security Guardian",description:"Install Guardian hooks for this workspace"},{value:"both",label:"Setup both - MCP & Security Guardian",description:"Connect supported AI tools and install Guardian hooks"},{value:"not_now",label:"Remind me Later",description:"Skip setup for now; you can run skills-layer setup later"}]);if(n==="not_now"){let u={version:1,setupChoice:"not_now",mcpChoice:"not_now",mcpPromptedAt:t.now(),guardianHookChoice:"not_now",guardianHookPromptedAt:t.now(),remindAfter:ml(t.now(),7)};return await Ni(t,u),h({status:"setup_skipped",mcp:{status:"not_configured",nextCommand:"skills-layer mcp setup"},security:{status:"not_configured",nextCommand:"skills-layer guardian hook install --agent codex --scope project"}},"Skills Layer setup skipped for now. Run `skills-layer setup` when you want MCP and Security hooks on this machine.",!1,t)}if(n!=="both"&&n!=="mcp"&&n!=="security")return y(`Unknown setup option "${n}".`,e.json);let i=n==="both"||n==="mcp",r=n==="both"||n==="security",s={status:"setup_complete",setupChoice:n},o={version:1,setupChoice:n,mcpChoice:i?"configured":"not_requested",mcpPromptedAt:t.now(),guardianHookChoice:r?p(e.scope)??"project":"not_requested",guardianHookPromptedAt:t.now()};if(i)if(!t.apiKey)s.mcp={status:"login_required",configured:!1,nextCommand:"skills-layer login"},o.mcpChoice="login_required";else{let u=await yn(e,t);if(H(u))return u;s.mcp=u}if(r){let u={...e,json:!0,scope:p(e.scope)??"project",agent:p(e.agent)??"codex"},d=await en(u,t);if(d.exitCode!==0)return d;s.security=El(d.stdout)??{status:"enabled",agent:p(u.agent),scope:p(u.scope)}}await Ni(t,o);let c=($(s.mcp)?l(s.mcp,"status"):void 0)==="login_required"?"Skills Layer Security setup complete. MCP setup needs login; run `skills-layer login`, then `skills-layer setup`.":"Skills Layer setup complete. Open a fresh agent session if MCP tools are not visible yet.";return h(s,c,e.json,t)}async function pl(e,t){let n=await De(t),i=await xn(t),r=O(n,"activeHookCount")??0;if(t.stdoutIsTty&&r===0&&!i)return await wr(e,t);let s=r>0?"Guardian host hooks are already configured. Run `skills-layer guardian hook status` to inspect them.":"Guardian is enabled for Skills Layer runtime checks. Run `skills-layer setup` when you want MCP and Security hooks on this machine.";return{exitCode:0,stdout:`${Be}
|
|
1147
|
+
|
|
1148
|
+
${s}`,stderr:""}}function gl(e,t){let n=O(e,"activeHookCount")??0,i=O(e,"missingHookCount")??0,r=l(t,"status")??"unknown",s=l(t,"effectiveMode"),o=l(t,"adminPolicy"),a=l(t,"nextAction"),c=l(t,"nextStep");return n>0&&i===0?{id:"guardian-local-hook",title:"Guardian local hook",status:"pass",summary:`Guardian native hook active count: ${n}.`,enforcementLayer:l(e,"enforcementLayer")??"native_hook",strictPreActionBlocking:e.strictPreActionBlocking===!0,policyStatus:r,adminPolicy:o,effectiveMode:s,policyNextAction:a,policyNextStep:c,recommendedCommand:"skills-layer guardian hook status"}:{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian native hook setup needs attention. Active hooks: ${n}; missing hooks: ${i}.`,enforcementLayer:l(e,"enforcementLayer")??"not_installed",strictPreActionBlocking:e.strictPreActionBlocking===!0,policyStatus:r,adminPolicy:o,effectiveMode:s,policyNextAction:a,policyNextStep:c,recommendedCommand:"skills-layer guardian hook install --agent codex --scope project",nextStep:"Install a Guardian host hook for automatic checks, or route risky shell actions through `skills-layer guardian exec` for strict pre-execution blocking."}}function ml(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?e:(n.setUTCDate(n.getUTCDate()+t),n.toISOString())}async function br(e){let t=Sr(p(e.flags.unmanagedPolicy)??e.backend.env.SKILLS_LAYER_UNMANAGED_SKILL_POLICY);if(t.status==="invalid")return{status:"invalid",result:y(t.message,e.flags.json)};let n=await vr({skillSlug:e.skillSlug,flags:e.flags,backend:e.backend,unmanagedPolicy:t.policy});if(n.unmanaged&&n.unmanagedPolicy==="block")return nt({...e,context:n,reasonCode:"unmanaged_skill_blocked",message:"Guardian blocked unmanaged local skill execution.",why:"The skill path is not backed by a public install index or lockfile entry and unmanaged policy is block.",nextStep:"Install the skill with `skills-layer install <path>` or choose --unmanaged-policy warn/allow for a one-off diagnostic check."});if(!n.installedPath)return{status:"ok",context:n};if(await Al(n.installedPath))return nt({...e,context:n,reasonCode:"skill_disabled",message:"Guardian blocked the action because this local skill is disabled.",why:"A local Guardian incident marker is present for this skill.",nextAction:"guardian.incident.review",nextStep:"Review the local incident report before running this skill again."});if(n.unmanaged)return{status:"ok",context:n};let i=await yl(e.skillSlug,n.installedPath);if(n.identityAssessment=i,i.reattestationRequired===!0)return nt({...e,context:n,reasonCode:l(i,"reasonCode")??"skill_identity_mismatch",message:"Guardian blocked the action because the installed skill identity changed.",why:"The visible SKILL.md identity no longer matches the installed skill record.",nextStep:"Reinstall or re-attest the skill before running it again."});let r=await kl(e.skillSlug,n.installedPath);return n.driftAssessment=r,r.reattestationRequired===!0?nt({...e,context:n,reasonCode:l(r,"reasonCode")??"installed_artifact_changed",message:"Guardian blocked the action because local runtime metadata detected installed artifact drift.",why:"The installed SKILL.md hash no longer matches the materialized runtime metadata.",nextStep:"Reinstall or re-attest the skill before running it again."}):{status:"ok",context:n}}async function nt(e){return await Me(e.backend,{skillSlug:e.skillSlug,version:e.version??e.context.version,action:e.action,decisionStatus:"blocked",reasonCode:e.reasonCode,telemetryMode:e.telemetryMode,path:e.context.installedPath}),{status:"blocked",result:P({status:"blocked",skillSlug:e.skillSlug,version:e.version??e.context.version,reasonCode:e.reasonCode,localPreflight:ye(e.context),unmanaged:e.context.unmanaged,unmanagedPolicy:e.context.unmanagedPolicy,allowUnmanagedOnce:e.context.allowUnmanagedOnce,why:e.why,nextAction:e.nextAction,nextStep:e.nextStep},e.message,e.flags.json,e.reasonCode)}}async function vr(e){let t=Sr(p(e.flags.unmanagedPolicy)),n=e.unmanagedPolicy??(t.status==="valid"?t.policy:"warn"),i=p(e.flags.path),r=await fl(e.skillSlug,e.backend),s=i?J(e.backend.cwd,i):r?.installedPath;return{source:i?"explicit_path":r?.source??"install_index",status:i?"ok":r?.status,reasonCode:i?void 0:r?.reasonCode,installedPath:s,archivePath:i?void 0:r?.archivePath,installedPathSource:i?"explicit_path":r?.installedPathSource,version:p(e.flags.version)??r?.version,record:r?.record,unmanaged:!!(i&&!r),unmanagedPolicy:n,allowUnmanagedOnce:e.flags.allowUnmanagedOnce}}async function fl(e,t){let i=(await we(t)).installs[e];if(i){let r=Ti(i,t);return{source:"install_index",installedPath:r.installedPath,archivePath:r.archivePath,installedPathSource:r.installedPathSource,status:r.status,reasonCode:r.reasonCode,version:l(i,"version"),record:i}}for(let r of hl(t)){let s=await Y(r);if(!$(s)||!$(s.installs))continue;let o=s.installs[e];if($(o)){let a=Ti(o,t);return{source:"lockfile",installedPath:a.installedPath,archivePath:a.archivePath,installedPathSource:a.installedPathSource,status:a.status,reasonCode:a.reasonCode,version:l(o,"version"),record:o}}}return null}function hl(e){return Array.from(new Set([L(e.cwd,"skills-layer-lock.json"),L(e.paths.stateDir,"skills-layer-lock.json")]))}function Ti(e,t){let n=l(e,"materializedSkillRoot");if(n)return{installedPath:it(J(t.cwd,n)),installedPathSource:"materializedSkillRoot",status:"ok"};let i=l(e,"canonicalPath");if(i)return{installedPath:it(J(t.cwd,i)),installedPathSource:"canonicalPath",status:"ok"};let r=l(e,"path");if(r)return{installedPath:it(J(t.cwd,r)),installedPathSource:"path",status:"ok"};let s=l(e,"materializedPath")??l(e,"bundlePath");if(s){let u=J(t.cwd,s),d=K(u).toLowerCase()==="bundle.zip"||u.toLowerCase().endsWith(".zip");return{installedPath:d?ee(ee(u)):it(u),archivePath:d?u:void 0,installedPathSource:l(e,"materializedPath")?"materializedPath":"bundlePath",status:d?"degraded":"ok",reasonCode:d?"installed_skill_root_missing":void 0}}let a=(Array.isArray(e.materializedWrites)?e.materializedWrites.filter($):[]).find(u=>{let d=l(u,"path");return d?.toLowerCase().endsWith("/skill.md")||d?.toLowerCase()==="skill.md"}),c=a?l(a,"path"):void 0;return{installedPath:c?ee(J(t.cwd,c)):void 0,installedPathSource:c?"materializedWrites":void 0,status:c?"ok":void 0}}function it(e){return K(e).toLowerCase()==="skill.md"?ee(e):e}async function yl(e,t){let n=L(t,"SKILL.md");if(!await fe(n))return{status:"not_checked",reasonCode:"skill_document_unavailable",expectedSkillSlug:e,reattestationRequired:!1};try{let i=ur(await Ge(n,"utf8"));return i?i!==e?{status:"mismatch",reasonCode:"skill_identity_mismatch",expectedSkillSlug:e,observedSkillName:i,skillDocumentPath:n,reattestationRequired:!0}:{status:"matched",expectedSkillSlug:e,observedSkillName:i,skillDocumentPath:n,reattestationRequired:!1}:{status:"not_checked",reasonCode:"skill_identity_metadata_unavailable",expectedSkillSlug:e,skillDocumentPath:n,reattestationRequired:!1}}catch(i){return{status:"invalid",reasonCode:"skill_identity_unreadable",expectedSkillSlug:e,skillDocumentPath:n,message:ae(i),reattestationRequired:!0}}}async function kl(e,t){let n=L(t,".skills-layer-runtime.json"),i=await Y(n),r=i?S(i,"materialization"):void 0,s=r?l(r,"skillDocumentSha256"):void 0;if(!i||!s)return{status:"not_checked",reasonCode:"runtime_metadata_unavailable",skillSlug:e,reattestationRequired:!1};let o=L(t,"SKILL.md");if(!await fe(o))return{status:"changed",reasonCode:"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:s,reattestationRequired:!0};let a=jr(await Ge(o,"utf8")),c=a===s;return{status:c?"unchanged":"changed",reasonCode:c?"installed_artifact_matches":"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:s,observedSkillDocumentSha256:a,reattestationRequired:!c}}function ye(e){return _({source:e.source,status:e.status,reasonCode:e.reasonCode,installedPath:e.installedPath,archivePath:e.archivePath,installedPathSource:e.installedPathSource,version:e.version,unmanaged:e.unmanaged,unmanagedPolicy:e.unmanagedPolicy,allowUnmanagedOnce:e.allowUnmanagedOnce,identityAssessment:e.identityAssessment,driftAssessment:e.driftAssessment})}function Sr(e){if(e===void 0||e.trim()==="")return{status:"valid",policy:"warn"};let t=e.trim().toLowerCase();return t==="allow"||t==="warn"||t==="block"?{status:"valid",policy:t}:{status:"invalid",message:"guardian check --unmanaged-policy must be one of: allow, warn, block."}}function tn(e,t){let n=p(e)??t;return n==="cloud_managed"||n==="local_only"?{status:"valid",mode:n}:{status:"invalid",message:"guardian --telemetry-mode must be one of: cloud_managed, local_only."}}function wl(e,t){let n=kt(e.actionJson,"action-json");return n&&typeof n=="object"&&!Array.isArray(n)?n:{type:"shell_command",command:K(t[0]??"command")}}function bl(e){let t=S(e,"enforcement");return typeof t?.canExecute=="boolean"?t.canExecute:dt(e)!=="blocked"}async function vl(e,t){let[n,...i]=e;return await new Promise((r,s)=>{let o=Wi(n,i,{cwd:t.cwd,env:{...process.env,...t.env},stdio:["ignore","pipe","pipe"]}),a="",c="";o.stdout?.setEncoding("utf8"),o.stderr?.setEncoding("utf8"),o.stdout?.on("data",u=>{a=Bi(`${a}${u}`)}),o.stderr?.on("data",u=>{c=Bi(`${c}${u}`)}),o.on("error",s),o.on("close",u=>{r({executable:K(n),argsCount:i.length,exitCode:typeof u=="number"?u:1,stdout:a,stderr:c})})})}function Bi(e){return e.length>2e4?`${e.slice(0,2e4)}
|
|
1149
|
+
[output truncated]`:e}function Sl(e){let t=[e.exitCode===0?"OK Guardian guarded execution complete.":"Guardian guarded execution finished with a command error.","","Command",` executable: ${e.executable}`,` args count: ${e.argsCount}`,` exit code: ${e.exitCode}`];return e.stdout&&t.push("","Stdout",e.stdout),e.stderr&&t.push("","Stderr",e.stderr),t.join(`
|
|
1150
|
+
`)}function Pr(e){let t=p(e)??"project";return t==="project"||t==="global"?{status:"valid",scope:t}:{status:"invalid",message:"guardian hooks --scope must be one of: project, global."}}function Cr(e){return L(e.paths.stateDir,"guardian-modes.json")}function xr(e){return L(e.paths.stateDir,"setup-state.json")}async function Pn(e){let t=await Y(Cr(e));return{version:1,skills:$(t?.skills)?t.skills:{}}}async function Pl(e,t,n){let i=await Pn(e);await D(Cr(e),{version:1,skills:{...i.skills,[t]:{requestedPreference:l(n,"requestedPreference")??"enforce",effectiveMode:l(n,"effectiveMode")??"enforce",reasonCode:l(n,"reasonCode"),auditId:l(n,"auditId"),updatedAt:e.now()}}})}async function Cn(e,t){let i=(await Pn(e)).skills[t];return i?l(i,"requestedPreference"):void 0}async function Cl(e,t){return(await Pn(e)).skills[t]}async function xn(e){let t=await Y(xr(e));return $(t)?{version:1,setupChoice:l(t,"setupChoice"),mcpChoice:l(t,"mcpChoice"),mcpPromptedAt:l(t,"mcpPromptedAt"),guardianHookChoice:l(t,"guardianHookChoice"),guardianHookPromptedAt:l(t,"guardianHookPromptedAt"),remindAfter:l(t,"remindAfter")}:null}async function Ni(e,t){await D(xr(e),t)}function xl(e,t,n){let i=t==="global"?e.targets.globalRoot:e.targets.projectRoot;return i?e.id==="codex"?{agent:e.id,agentName:e.displayName,scope:t,hookId:pe,hookName:te,configPath:L(i,"hooks.json"),hookPath:L(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook",strictPreActionBlocking:!0}:e.id==="claude-code"?{agent:e.id,agentName:e.displayName,scope:t,hookId:pe,hookName:te,configPath:L(i,"settings.json"),hookPath:L(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook",strictPreActionBlocking:!0}:e.id==="cline"?{agent:e.id,agentName:e.displayName,scope:t,hookId:pe,hookName:te,configPath:L(i,"guardian-hooks.json"),hookPath:L(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1}:null:null}async function Rl(e,t){if(await re(e.hookPath,jl(e.agentName)),await Yi(e.hookPath,448).catch(()=>{}),e.agent==="codex"){await D(e.configPath,_l(e.hookPath));return}if(e.agent==="claude-code"){await D(e.configPath,$l(e.hookPath));return}e.agent==="cline"&&await D(e.configPath,Il(e,t))}function Rr(e,t){return t==="global"?L(e.paths.stateDir,"guardian-hooks.json"):L(e.cwd,".skills-layer","guardian-hooks.json")}async function _r(e){let t=await Y(e);return{version:1,hooks:Array.isArray(t?.hooks)?t.hooks.filter($):[]}}function Mi(e,t,n){return _e.isAbsolute(n)||n.startsWith("/")?n:Qi(t==="global"?e.paths.stateDir:e.cwd,n)}function _l(e){return{hooks:{PreToolUse:[{name:te,id:pe,matcher:"Bash|Shell|Read|Write|Edit|apply_patch|mcp__.*",hooks:[{name:te,type:"command",command:`node ${Rn(e)}`}]}]}}}function $l(e){return{hooks:{PreToolUse:[{name:te,id:pe,matcher:"Bash|Read|Write|Edit|MultiEdit|NotebookEdit|WebFetch|WebSearch",hooks:[{name:te,type:"command",command:`node ${Rn(e)}`}]}]}}}function Il(e,t){return{version:1,hookId:pe,hookName:te,agent:e.agent,agentName:e.agentName,scope:e.scope,enforcementLayer:e.enforcementLayer,strictPreActionBlocking:e.strictPreActionBlocking,installedAt:t.now(),hooks:[{name:te,id:pe,event:"PreToolUse",command:`node ${Rn(e.hookPath)}`,status:"candidate"}]}}function jl(e){return`#!/usr/bin/env node
|
|
1048
1151
|
import { spawnSync } from "node:child_process";
|
|
1049
1152
|
import { readFileSync } from "node:fs";
|
|
1050
1153
|
|
|
@@ -1079,41 +1182,41 @@ const result = spawnSync("skills-layer", [
|
|
|
1079
1182
|
], { stdio: ["ignore", "inherit", "inherit"] });
|
|
1080
1183
|
|
|
1081
1184
|
process.exit(result.status ?? 1);
|
|
1082
|
-
`}function
|
|
1083
|
-
`;return await re(t,i),{path:
|
|
1185
|
+
`}function Rn(e){return JSON.stringify(e)}async function _n(e){let t=L(ee(e.skillDocumentPath),".skills-layer-runtime.json"),n={version:1,generatedAt:e.backend.now(),skillSlug:e.skillSlug,sourceProvider:{id:"skills-layer",name:"Skills Layer",managedBy:"skills-layer-cli"},...e.version?{skillVersion:e.version}:{},guardian:{required:!0,enforcementLayer:"cloud_guardian_with_local_preflight",strictPreActionBlocking:!1,checkCommand:`skills-layer guardian check --skill ${e.skillSlug} --json`,incidentCommand:`skills-layer guardian incident ${e.skillSlug} --path <installed-skill-path> --telemetry-mode local_only --json`,guardedExecutorCommand:`skills-layer guardian exec ${e.skillSlug} --json -- <command>`,mcpCheckTool:"guardian.check",mcpEnforceTool:"guardian.enforce",agentCommandMatrix:Et({purpose:"materialize_skill",command:`skills-layer install ${e.skillSlug}`,jsonCommand:`skills-layer install ${e.skillSlug} --json`,skillSlug:e.skillSlug}),agentGuidance:"MCP-capable agents should call guardian.check or guardian.enforce before risky tool use. Local host hooks should call skills-layer guardian check, and shell actions that need strict wrapping should use skills-layer guardian exec.",sensitiveActionFamilies:["shell_command","network_request","file_read","file_write","secret_read","browser_action","device_action","api_call","generated_code_execution","model_context_promotion"]},materialization:{skillDocumentPath:"SKILL.md",skillDocumentSha256:jr(e.skillDocumentContent)}},i=`${JSON.stringify(n,null,2)}
|
|
1186
|
+
`;return await re(t,i),{path:ct(e.backend.cwd,t),bytes:new TextEncoder().encode(i).length}}async function Al(e){return await fe(L(e,".skills-layer-disabled.json"))}async function Fi(e){let t=e.backend.now(),n=L(e.installedPath,".skills-layer-disabled.json"),i=L(e.installedPath,".skills-layer-quarantine.json"),r=L(e.installedPath,"incident.md"),s=l(e.action,"type")??"unknown";return await re(n,`${JSON.stringify({disabled:!0,generatedAt:t,skillSlug:e.skillSlug,version:e.version,reason:"Skills Layer Guardian incident response"},null,2)}
|
|
1084
1187
|
`),await re(i,`${JSON.stringify({generatedAt:t,skillSlug:e.skillSlug,version:e.version,actions:["disable_skill","quarantine_files","preserve_evidence","generate_incident_report","rescan_before_reenable"],quarantineTargets:[e.installedPath]},null,2)}
|
|
1085
|
-
`),await re(r,["# Skills Layer Guardian Incident Report","",`Generated: ${t}`,`Skill: ${e.skillSlug}`,`Version: ${e.version}`,"","## Summary","",
|
|
1086
|
-
`)),{status:"written",generatedAt:t,incidentPath:r,writtenFiles:[n,i,r]}}function
|
|
1087
|
-
`,{encoding:"utf8",mode:384}),await
|
|
1188
|
+
`),await re(r,["# Skills Layer Guardian Incident Report","",`Generated: ${t}`,`Skill: ${e.skillSlug}`,`Version: ${e.version}`,"","## Summary","",Ir(e.reason),"","## Evidence","",`- ${t}: ${s} -> blocked (incident_recorded)`].join(`
|
|
1189
|
+
`)),{status:"written",generatedAt:t,incidentPath:r,writtenFiles:[n,i,r]}}function Oi(e,t){let n=e.now().replace(/[:.]/gu,"-");return L(e.paths.incidentsDir,`${t}-${n}.json`)}async function Me(e,t){let n=L(e.paths.stateDir,"guardian-audit.jsonl");await Dr(ee(n));let i={version:1,generatedAt:e.now(),skillSlug:t.skillSlug,...t.version?{skillVersion:t.version}:{},actionType:l(t.action,"type")??"unknown",actionTarget:Ll(t.action),decisionStatus:t.decisionStatus,reasonCode:t.reasonCode,telemetryMode:t.telemetryMode,...t.path?{localPath:$r(t.path)}:{}};await io(n,`${JSON.stringify(i)}
|
|
1190
|
+
`,{encoding:"utf8",mode:384}),await An(n,384)}function dt(e){let t=S(e,"decision"),n=S(e,"enforcement"),i=l(t??{},"status")??l(n??{},"status")??l(e,"status");return i==="allowed"||i==="advisory"?i:"blocked"}function nn(e){let t=S(e,"decision");return l(t??{},"reasonCode")??l(e,"reasonCode")??l(e,"status")??"cloud_guardian_decision"}function Ll(e){let t=l(e,"type");if(t==="secret_read")return"redacted_secret";if(t==="shell_command")return"redacted_command";let n=l(e,"url");if(n)try{return new URL(n).origin}catch{return"redacted_url"}let i=l(e,"target");if(i)return Ir(i);let r=l(e,"path");return r?$r(r):null}function $r(e){let t=K(e.trim());return t?`<local-path>/${t}`:"<local-path>"}function Ir(e){return e.replace(/sk-[A-Za-z0-9_-]+/gu,"[redacted-secret]").replace(/[A-Z0-9_]*SECRET[A-Z0-9_]*/gu,"[redacted-secret]").replace(/[A-Z0-9_]*TOKEN[A-Z0-9_]*/gu,"[redacted-token]").replace(/[A-Z0-9_]*KEY[A-Z0-9_]*/gu,"[redacted-key]")}function qi(e){return e.split(/[\\/]+/u).join("/")}function jr(e){return cn("sha256").update(e).digest("hex")}async function Ar(e,t,n,i,r){let s=await v(i,"/api/v1/verify",{method:"POST",headers:A(),body:JSON.stringify({email:e,code:t,clientDelivery:"cli_secure_storage"})});if(n.json){let o=l(s,"apiKey");return o?(await Oe(i,o,{expectedEmail:e,knownEmail:l(s,"email")??e,knownRole:l(s,"role")??"user",knownRoles:se(s,"roles"),knownUserId:l(s,"userId")}),h(W({...s,loggedIn:!0}),"Email verified and login completed.",!0,i)):h(W({...s,email:e,loggedIn:!1,nextCommand:`skills-layer login --method email --email ${e}`,nextAction:"login"}),"Email verified. Login still needs to be completed.",!0,i)}return await gt(e,s,n,i,r)}async function gt(e,t,n,i,r){let s=l(t,"apiKey"),o=l(t,"role")??"user",a=se(t,"roles"),c=l(t,"userId"),u=s;if(!u)try{u=(await i.promptSecret(`Enter the API key emailed to ${e} (check spam/junk folder if missing): `)).trim()}catch{return h(W({...t,email:e,role:o,...a?{roles:a}:{},loggedIn:!1}),`${r} Check your email (including spam/junk folder) for the API key, then run \`skills-layer login\` to finish signing in.`,n.json,i)}if(!u)return y("No API key was entered. Run `skills-layer login` once you have the emailed key.",n.json);let d=await Oe(i,u,{expectedEmail:e,knownEmail:e,knownRole:o,knownRoles:a,knownUserId:c,forceProfileValidation:!s}),g=await Zt(n,{...i,config:d,apiKey:u});return H(g)?g:h(W({...t,status:l(t,"status")??"verified",email:d.email,role:d.role,...d.roles?{roles:d.roles}:{},loggedIn:!0,...g.data?{mcp:g.data}:{}}),[`${r} Logged in as ${d.email}.`,g.message??""].filter(Boolean).join(" "),n.json,i)}async function $n(e,t,n,i,r){let s=l(t,"authorizationUrl"),o=b(l(t,"state"),"Social auth did not return a state."),a=Kc(e);if(s){let u=await i.openUrl(s);i.emitInfo(u?`${a} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`:`${a} sign-in started. Open this URL in your browser, then come back here once it is done:
|
|
1088
1191
|
${s}
|
|
1089
|
-
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 Cl(o,i);return H(c)?c:c.status==="verified"||c.status==="recovered"?await dt(c.email,{...c},n,i,r==="recovery"?`Recovered access for ${c.email} through ${l}.`:`Verified ${c.email} through ${l}.`):c.status==="already_registered"?h(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"?h(c,`${l} sign-in is now connected.`,n.json,i):Pl(c)?k(_l(c),n.json):k("Social auth completed with an unexpected response.",n.json)}function H(e){return $(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function Sl(e){try{let t=JSON.parse(e);return $(t)?t.data:void 0}catch{return}}function Pl(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 Cl(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:se(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:se(i,"roles"),linkedAccount:typeof i.linkedAccount=="boolean"?i.linkedAccount:void 0}:r==="linked"?{status:r}:r==="registration_required"||r==="state_expired"||r==="provider_mismatch"||r==="identity_conflict"||r==="email_required"||r==="failed"?{status:r,error:a(i,"error")}:k("Social auth completed with an unexpected response.",!1)}catch(i){if(i instanceof A&&(i.status===404||i.status===429)){await t.sleep(1500);continue}return k(ae(i),!1)}return k("Timed out while waiting for social auth to complete.",!1)}async function Rl(e,t){for(let n=0;n<120;n+=1)try{let r=(await b(t,"/api/v1/purchases",{headers:B(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 A&&i.status===429){await t.sleep(1500);continue}return k(ae(i),!1)}return k("Timed out while waiting for purchase confirmation.",!1)}async function xl(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:B(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 A&&i.status===429){await t.sleep(1500);continue}return k(ae(i),!1)}return k("Timed out while waiting for payment confirmation.",!1)}function $l(e){let t=S(e,"accountLink");return(t?a(t,"url"):void 0)??a(e,"url")??a(e,"setupUrl")}function _l(e){return e.status==="registration_required"?e.error??"No verified account exists for this social identity. Use `skills-layer register` first.":e.status==="state_expired"?"Social auth expired before completion. Start the flow again.":e.status==="provider_mismatch"?"The browser completed a different social provider than the one the CLI started.":e.status==="identity_conflict"?e.error??"This social identity is already linked to another account.":e.status==="email_required"?e.error??"This social profile did not provide an email address.":e.error??"Social auth could not be completed."}async function Oe(e,t,n={}){let r=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole?await b({...e,apiKey:t},"/api/v1/me",{headers:{...B(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:B(t)}),l={version:Hi,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:se(r,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await Rn(e.paths.configPath,l,e),await D(e.paths.backendPreferencePath,{version:dn,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),l}function Ti(e,t){let n=ft(e.actionJson,"action-json");if(n&&typeof n=="object"&&!Array.isArray(n))return n;let i=p(e.action);return t==="incident"?{type:"file_write",path:p(e.path)??".skills-layer/incidents/guardian-incident.json"}:i==="file_read"||i==="file_write"?{type:i,path:p(e.path)??"."}:i==="shell_command"?{type:"shell_command",command:"unspecified"}:{type:"api_call",...i?{target:i}:{}}}async function R(e,t,n,i,r={}){let s=r.authenticated?B(n.apiKey,n.authBlockedMessage):He(n.apiKey);return await pt(e,{headers:s},t,n,i)}async function Il(e,t){let n=await b(t,"/api/v1/doctor",{headers:He(t.apiKey)}),i=await De(t),r=await Xa(t),s=[...xr(n),nl(i,r)];return h({...n,guardian:{...i,policy:r},checks:s},"Doctor checks loaded.",e.json,t)}async function K(e,t,n,i,r){return await pt(e,{method:"POST",headers:j(i.apiKey),body:JSON.stringify(x(t))},n,i,r)}async function Fe(e,t,n,i,r){return await pt(e,{method:"PATCH",headers:j(i.apiKey),body:JSON.stringify(x(t))},n,i,r)}async function pt(e,t,n,i,r){let s=await b(i,e,t);return h(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}. ${ae(o)}`)});if(!i.ok)throw await jl(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 jl(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new A(e.status,a(n,"error")??(e.statusText||"Request failed"),n)}catch{return new A(e.status,t)}return new A(e.status,e.statusText||"Request failed")}function B(e,t){if(t)throw new A(401,t,{error:t,nextAction:"backend.status",nextStep:t});if(!e)throw new A(401,"Login required.",{error:"Login required.",nextAction:"login",nextStep:"Run `skills-layer login` to sign in, then retry this command."});return{authorization:`Bearer ${e}`}}function He(e){return e?{authorization:`Bearer ${e}`}:{}}function j(e){return{"content-type":"application/json",...He(e)}}async function gt(e){let t=await Ws(e);if(t.isFile())return[{path:G(e),content:await Ge(e,"utf8")}];if(!t.isDirectory())throw new Error(`Unsupported path: ${e}`);let n=[];if(await Sr(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 Sr(e,t,n){for(let i of await Vi(t,{withFileTypes:!0})){if(Al(i.name))continue;let r=L(t,i.name);if(i.isDirectory()){await Sr(e,r,n);continue}if(!i.isFile())continue;let s=Me(e,r).split("\\").join("/");try{n.push({path:s,content:await Ge(r,"utf8")})}catch{continue}}}function Al(e){return e===".git"||e==="node_modules"||e==="coverage"||e===Ll()||e==="dist"}function Ll(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}async function ut(e,t){if(/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e))return;let n=J(t,e);try{return await Ki(n),{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:await gt(n)}}catch{return}}async function Ft(e,t){let n=El(t);if(n.length===0)return t;let i=[];for(let r of n){let s=Pr(r.path),o=J(e.cwd,s),l=Me(e.cwd,o);if(!l||l.startsWith("..")||xe.isAbsolute(l))throw new Error(`Cloud install plan attempted to write outside the current workspace: ${r.path}`);if(await re(o,r.content),i.push({path:s,bytes:new TextEncoder().encode(r.content).length}),G(s).toLowerCase()==="skill.md"){let c=a(t,"skillSlug")??a(t,"slug")??G(ee(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 El(e){return[...qt(e.localWrites),...qt(S(e,"installPlan")?.localWrites),...qt(S(e,"materializationPlan")?.localWrites)]}function qt(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];let n=t,i=p(n.path),r=typeof n.content=="string"?n.content:void 0;return i&&r!==void 0?[{path:i,content:r}]:[]}):[]}function Pr(e){let t=e.replaceAll("\\","/").replace(/^\.\/+/u,"");if(!t||t.includes("\0")||cn.isAbsolute(t)||xe.isAbsolute(e)||t.split("/").includes(".."))throw new Error(`Cloud install plan returned an unsafe local write path: ${e}`);return t}async function Ul(e,t){let n=a(e,"apiKey");if(!n)return;let i={version:Hi,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:se(e,"roles")??t.config?.roles,lastSelectedAgent:t.config?.lastSelectedAgent,savedAt:t.now()};await Rn(t.paths.configPath,i,t)}async function ke(e){let t=await Y(e.paths.installsPath);if(!$(t))return{version:ai,installs:{}};let n=$(t.installs)?Bi(t.installs):$(t.skills)?Bi(t.skills):{};return{version:typeof t.version=="number"?t.version:ai,installs:n}}async function Cr(e,t){await D(e.paths.installsPath,t)}async function at(e,t,n){let i=a(t,"skillSlug")??a(t,"slug")??n,r=await ke(e);r.installs[i]={skillSlug:i,...t,savedAt:e.now()},await Cr(e,r)}function Bi(e){let t={};for(let[n,i]of Object.entries(e))t[n]=$(i)?i:{skillSlug:n,value:i};return t}var T=5;function h(e,t,n,i){let s={status:e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"?String(e.status):"ok",summary:t,why:null,nextAction:null,nextStep:null,data:e,warnings:[],links:[],reasonCode:null,handoff:null};return{exitCode:0,stdout:n?JSON.stringify(s,null,2):Tl(e,t,i),stderr:""}}function Tl(e,t,n){let i=Z(n);if($(e)){if(t==="Status loaded."&&Ni(e))return Fl(e,t,i);if(t==="Doctor checks loaded."&&Ni(e))return ql(e,t,i);if(t==="Creator payout profile loaded.")return ac(e,t,i);if(t==="Creator earnings loaded."||t==="Earnings loaded.")return lc(e,"Creator earnings loaded.",i);if(t==="Creator payouts loaded."||t==="Payouts loaded.")return cc(e,"Creator payouts loaded.",i);if(t==="Guardian check complete.")return Ml(e,t,i);if(t==="Reviews loaded.")return Nl(e,t,i);if(t==="Categories loaded.")return Bl(e,t,i)}let r=[`${i.ok("OK")} ${t}`];if($(e)){let s=Ir(e,i);s.length>0&&r.push("",...s);let o=Ur(e);o.length>0&&r.push("",i.section("Next"),...o.map(l=>` ${i.arrow} ${l}`))}return r.join(`
|
|
1090
|
-
`)}function
|
|
1091
|
-
`)):(i.slice(0,
|
|
1092
|
-
`))}function
|
|
1093
|
-
`)}function
|
|
1094
|
-
`)}function
|
|
1095
|
-
`)}function
|
|
1096
|
-
`)}function
|
|
1097
|
-
`)}function
|
|
1098
|
-
`)}function
|
|
1099
|
-
`)}function
|
|
1100
|
-
`)}function
|
|
1101
|
-
`)}function
|
|
1102
|
-
`)}function
|
|
1103
|
-
`)}function
|
|
1104
|
-
`)}function
|
|
1105
|
-
`)}function
|
|
1106
|
-
`,{encoding:"utf8",mode:384}),await
|
|
1107
|
-
`),m())},f=m=>{let
|
|
1108
|
-
`){g(()=>s(u.trim()));return}if(w===""){g(()=>o(new Error("Interactive secret prompt cancelled.")));return}if(w==="\b"||w==="\x7F"){u.length>0&&(u=u.slice(0,-1),t.write("\b \b"));continue}u+=w,t.write("*")}};t.write(i),
|
|
1109
|
-
`){let
|
|
1110
|
-
`).length;
|
|
1111
|
-
`),s.trim()}finally{r.close()}}}function
|
|
1112
|
-
`);for(let[
|
|
1192
|
+
Waiting for browser sign-in to finish...`)}else i.emitInfo(`${a} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`);let c=await Tl(o,i);return H(c)?c:c.status==="verified"||c.status==="recovered"?await gt(c.email,{...c},n,i,r==="recovery"?`Recovered access for ${c.email} through ${a}.`:`Verified ${c.email} through ${a}.`):c.status==="already_registered"?h(c,c.linkedAccount===!0?`${a} is now linked to ${c.email}. Run \`skills-layer login\` to sign in.`:`${c.email} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,n.json,i):c.status==="linked"?h(c,`${a} sign-in is now connected.`,n.json,i):Ul(c)?y(Fl(c),n.json):y("Social auth completed with an unexpected response.",n.json)}function H(e){return $(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function El(e){try{let t=JSON.parse(e);return $(t)?t.data:void 0}catch{return}}function Ul(e){return e.status==="registration_required"||e.status==="state_expired"||e.status==="provider_mismatch"||e.status==="identity_conflict"||e.status==="email_required"||e.status==="failed"}async function Tl(e,t){for(let n=0;n<120;n+=1)try{let i=await v(t,`/api/v1/identity/social/status/${encodeURIComponent(e)}`),r=l(i,"status")??"failed";if(r==="pending"){await t.sleep(1500);continue}return(r==="verified"||r==="recovered")&&l(i,"email")&&l(i,"role")?{status:r,email:l(i,"email"),role:l(i,"role"),roles:se(i,"roles"),userId:l(i,"userId"),apiKey:l(i,"apiKey"),keyPrefix:l(i,"keyPrefix"),emailDelivery:l(i,"emailDelivery")}:r==="already_registered"&&l(i,"email")&&l(i,"role")?{status:r,email:l(i,"email"),role:l(i,"role"),roles:se(i,"roles"),linkedAccount:typeof i.linkedAccount=="boolean"?i.linkedAccount:void 0}:r==="linked"?{status:r}:r==="registration_required"||r==="state_expired"||r==="provider_mismatch"||r==="identity_conflict"||r==="email_required"||r==="failed"?{status:r,error:l(i,"error")}:y("Social auth completed with an unexpected response.",!1)}catch(i){if(i instanceof I&&(i.status===404||i.status===429)){await t.sleep(1500);continue}return y(ae(i),!1)}return y("Timed out while waiting for social auth to complete.",!1)}async function Bl(e,t){for(let n=0;n<120;n+=1)try{let r=(await v(t,"/api/v1/purchases",{headers:M(t.apiKey,t.authBlockedMessage)})).results?.find(s=>s.purchaseId===e);if(!r?.status||r.status==="pending"||r.status==="requires_action"){await t.sleep(1500);continue}return{status:r.status,purchaseId:e}}catch(i){if(i instanceof I&&i.status===429){await t.sleep(1500);continue}return y(ae(i),!1)}return y("Timed out while waiting for purchase confirmation.",!1)}async function Nl(e,t){for(let n=0;n<120;n+=1)try{let i=await v(t,`/api/v1/me/private-skill-charges/${encodeURIComponent(e)}`,{headers:M(t.apiKey,t.authBlockedMessage)}),r=l(i,"status");if(!r||r==="checkout_required"||r==="pending"||r==="requires_action"){await t.sleep(1500);continue}return{...i,status:r}}catch(i){if(i instanceof I&&i.status===429){await t.sleep(1500);continue}return y(ae(i),!1)}return y("Timed out while waiting for payment confirmation.",!1)}function Ml(e){let t=S(e,"accountLink");return(t?l(t,"url"):void 0)??l(e,"url")??l(e,"setupUrl")}function Fl(e){return e.status==="registration_required"?e.error??"No verified account exists for this social identity. Use `skills-layer register` first.":e.status==="state_expired"?"Social auth expired before completion. Start the flow again.":e.status==="provider_mismatch"?"The browser completed a different social provider than the one the CLI started.":e.status==="identity_conflict"?e.error??"This social identity is already linked to another account.":e.status==="email_required"?e.error??"This social profile did not provide an email address.":e.error??"Social auth could not be completed."}async function Oe(e,t,n={}){let r=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole?await v({...e,apiKey:t},"/api/v1/me",{headers:{...M(t),...n.notifyLogin?{"x-skills-layer-session-intent":"login"}:{}}}):{userId:n.knownUserId,email:n.knownEmail,role:n.knownRole,roles:n.knownRoles},s=l(r,"email")??n.knownEmail??"unknown";if(n.expectedEmail&&s.toLowerCase()!==n.expectedEmail.toLowerCase())throw new Error(`The entered API key belongs to ${s}, not ${n.expectedEmail}. Use the API key emailed to ${n.expectedEmail}.`);let o=await v({...e,apiKey:t},"/api/v1/capabilities",{headers:M(t)}),a={version:Xi,baseUrl:e.baseUrl,apiKey:t,edition:l(o,"edition")??l(r,"edition")??"saas",userId:l(r,"userId")??n.knownUserId,email:s,role:l(r,"role")??n.knownRole??"user",roles:se(r,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await jn(e.paths.configPath,a,e),await D(e.paths.backendPreferencePath,{version:mn,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),a}function Ki(e,t){let n=kt(e.actionJson,"action-json");if(n&&typeof n=="object"&&!Array.isArray(n))return n;let i=p(e.action);return t==="incident"?{type:"file_write",path:p(e.path)??".skills-layer/incidents/guardian-incident.json"}:i==="file_read"||i==="file_write"?{type:i,path:p(e.path)??"."}:i==="shell_command"?{type:"shell_command",command:"unspecified"}:{type:"api_call",...i?{target:i}:{}}}async function R(e,t,n,i,r={}){let s=r.authenticated?M(n.apiKey,n.authBlockedMessage):He(n.apiKey);return await ft(e,{headers:s},t,n,i)}async function Ol(e,t){let n=await v(t,"/api/v1/doctor",{headers:He(t.apiKey)}),i=await De(t),r=await ul(t),s=[...Br(n),gl(i,r)];return h({...n,guardian:{...i,policy:r},checks:s},"Doctor checks loaded.",e.json,t)}async function q(e,t,n,i,r){return await ft(e,{method:"POST",headers:A(i.apiKey),body:JSON.stringify(_(t))},n,i,r)}async function mt(e,t,n,i,r){return await ft(e,{method:"PATCH",headers:A(i.apiKey),body:JSON.stringify(_(t))},n,i,r)}async function ft(e,t,n,i,r){let s=await v(i,e,t);return h(s,r,n.json,i)}async function v(e,t,n={}){let i=await e.fetchFn(`${e.baseUrl}${t}`,n).catch(o=>{throw new Error(`Unable to reach ${e.baseUrl}. ${ae(o)}`)});if(!i.ok)throw await ql(i);let r=await i.text();if(!r)return{};let s=JSON.parse(r);return s&&typeof s=="object"&&!Array.isArray(s)&&"data"in s?s.data:s}async function ql(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new I(e.status,l(n,"error")??(e.statusText||"Request failed"),n)}catch{return new I(e.status,t)}return new I(e.status,e.statusText||"Request failed")}function M(e,t){if(t)throw new I(401,t,{error:t,nextAction:"backend.status",nextStep:t});if(!e)throw new I(401,"Login required.",{error:"Login required.",nextAction:"login",nextStep:"Run `skills-layer login` to sign in, then retry this command."});return{authorization:`Bearer ${e}`}}function He(e){return e?{authorization:`Bearer ${e}`}:{}}function A(e){return{"content-type":"application/json",...He(e)}}async function ht(e){let t=await ro(e);if(t.isFile())return[{path:K(e),content:await Ge(e,"utf8")}];if(!t.isDirectory())throw new Error(`Unsupported path: ${e}`);let n=[];if(await Lr(e,e,n),n.length===0)throw new Error(`No readable files found in ${e}.`);return n.sort((i,r)=>i.path.localeCompare(r.path))}async function Lr(e,t,n){for(let i of await Zi(t,{withFileTypes:!0})){if(Kl(i.name))continue;let r=L(t,i.name);if(i.isDirectory()){await Lr(e,r,n);continue}if(!i.isFile())continue;let s=Fe(e,r).split("\\").join("/");try{n.push({path:s,content:await Ge(r,"utf8")})}catch{continue}}}function Kl(e){return e===".git"||e==="node_modules"||e==="coverage"||e===Gl()||e==="dist"}function Gl(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}async function pt(e,t){if(/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e))return;let n=J(t,e);try{return await Ji(n),{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:await ht(n)}}catch{return}}async function Vt(e,t){let n=Vl(t);if(n.length===0)return t;let i=[];for(let r of n){let s=Er(r.path),o=J(e.cwd,s),a=Fe(e.cwd,o);if(!a||a.startsWith("..")||_e.isAbsolute(a))throw new Error(`Cloud install plan attempted to write outside the current workspace: ${r.path}`);if(await re(o,r.content),i.push({path:s,bytes:new TextEncoder().encode(r.content).length}),K(s).toLowerCase()==="skill.md"){let c=l(t,"skillSlug")??l(t,"slug")??K(ee(s)),u=await _n({backend:e,skillSlug:c,version:l(t,"version"),skillDocumentPath:o,skillDocumentContent:r.content});i.push(u)}}return{...t,materializedWrites:i}}function Vl(e){return[...Dt(e.localWrites),...Dt(S(e,"installPlan")?.localWrites),...Dt(S(e,"materializationPlan")?.localWrites)]}function Dt(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];let n=t,i=p(n.path),r=typeof n.content=="string"?n.content:void 0;return i&&r!==void 0?[{path:i,content:r}]:[]}):[]}function Er(e){let t=e.replaceAll("\\","/").replace(/^\.\/+/u,"");if(!t||t.includes("\0")||pn.isAbsolute(t)||_e.isAbsolute(e)||t.split("/").includes(".."))throw new Error(`Cloud install plan returned an unsafe local write path: ${e}`);return t}async function Dl(e,t){let n=l(e,"apiKey");if(!n)return;let i={version:Xi,baseUrl:t.baseUrl,apiKey:n,edition:l(e,"edition")??t.config?.edition??"saas",userId:l(e,"userId")??t.config?.userId,email:l(e,"email")??t.config?.email??"unknown",role:l(e,"role")??t.config?.role??"user",roles:se(e,"roles")??t.config?.roles,lastSelectedAgent:t.config?.lastSelectedAgent,savedAt:t.now()};await jn(t.paths.configPath,i,t)}async function we(e){let t=await Y(e.paths.installsPath);if(!$(t))return{version:pi,installs:{}};let n=$(t.installs)?Gi(t.installs):$(t.skills)?Gi(t.skills):{};return{version:typeof t.version=="number"?t.version:pi,installs:n}}async function Ur(e,t){await D(e.paths.installsPath,t)}async function lt(e,t,n){let i=l(t,"skillSlug")??l(t,"slug")??n,r=await we(e);r.installs[i]={skillSlug:i,...t,savedAt:e.now()},await Ur(e,r)}function Gi(e){let t={};for(let[n,i]of Object.entries(e))t[n]=$(i)?i:{skillSlug:n,value:i};return t}var N=5;function h(e,t,n,i){let s={status:e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"?String(e.status):"ok",summary:t,why:null,nextAction:null,nextStep:null,data:e,warnings:[],links:[],reasonCode:null,handoff:null};return{exitCode:0,stdout:n?JSON.stringify(s,null,2):Hl(e,t,i),stderr:""}}function Hl(e,t,n){let i=Z(n);if($(e)){if(t==="Status loaded."&&Vi(e))return Zl(e,t,i);if(t==="Doctor checks loaded."&&Vi(e))return Ql(e,t,i);if(t==="Creator payout profile loaded.")return kc(e,t,i);if(t==="Creator earnings loaded."||t==="Earnings loaded.")return wc(e,"Creator earnings loaded.",i);if(t==="Creator payouts loaded."||t==="Payouts loaded.")return bc(e,"Creator payouts loaded.",i);if(t==="Guardian check complete.")return Jl(e,t,i);if(t==="Reviews loaded.")return Wl(e,t,i);if(t==="Categories loaded.")return zl(e,t,i)}let r=[`${i.ok("OK")} ${t}`];if($(e)){let s=Fr(e,i);s.length>0&&r.push("",...s);let o=Vr(e);o.length>0&&r.push("",i.section("Next"),...o.map(a=>` ${i.arrow} ${a}`))}return r.join(`
|
|
1193
|
+
`)}function zl(e,t,n){let i=de(e.results??e.categories??e.data),r=[`${n.ok("OK")} ${t}`,"",n.section(`Categories (${i.length})`)];return i.length===0?(r.push(` ${n.muted("No categories returned.")}`),r.join(`
|
|
1194
|
+
`)):(i.slice(0,N).forEach((s,o)=>{let a=l(s,"slug")??l(s,"category")??l(s,"name")??`category-${o+1}`,c=l(s,"name")??a,u=s.count;r.push(`${o+1}. ${Gr(c)}`);let d=[a?`slug: ${a}`:void 0,u!==void 0?`count: ${z("count",u)}`:void 0].filter(g=>!!g);d.length>0&&r.push(` ${d.join("; ")}`)}),i.length>N&&r.push(` ${n.muted(`... ${i.length-N} more`)}`),r.join(`
|
|
1195
|
+
`))}function Wl(e,t,n){let i=de(e.reviews??e.results),r=[`${n.ok("OK")} ${t}`,"",n.section(`Reviews (${i.length})`)];return i.length===0&&r.push(` ${n.muted("No reviews yet.")}`),i.forEach((s,o)=>{let a=l(s,"reviewId")??l(s,"id"),u=l(s,"skillSlug")??l(s,"slug")??l(s,"skill")??a??`Review ${o+1}`,d=s.rating??s.score,g=l(s,"status"),f=l(s,"updatedAt")??l(s,"createdAt"),m=[a?`review: ${a}`:void 0,d!=null?`rating: ${z("rating",d)}`:void 0,g?`status: ${g}`:void 0,f?`updated: ${f}`:void 0].filter(w=>!!w);r.push(`${o+1}. ${u}`),m.length>0&&r.push(` ${m.join("; ")}`);let k=l(s,"feedback")??l(s,"comment")??l(s,"message");k&&r.push(` ${n.label("feedback")}: ${Re(k)}`)}),r.join(`
|
|
1196
|
+
`)}function Jl(e,t,n){let i=S(e,"decision"),r=S(e,"enforcement"),s=S(e,"auditEvent"),o=T(i,"status")??T(r,"status")??"unknown",a=T(r,"actionType")??T(s,"actionType")??"action",c=T(i,"capability")??T(r,"capability")??"not specified",u=T(i,"reasonCode")??T(r,"reasonCode")??"not specified",d=T(i,"message")??T(r,"message")??"Guardian policy resolved this action.",g=T(s,"skillSlug")??"unknown",f=T(s,"version")??"unknown",m=Ht(r,"canExecute"),k=Ht(r,"auditRequired"),w=Ht(r,"telemetryRequired"),C=o==="blocked"?"BLOCKED":o==="allowed"?"ALLOWED":"WARNING",x=[`${n.ok("OK")} ${t}`,"",n.section(`${C} ${Yl(a)}`),` ${n.label("Skill")}: ${g}`,` ${n.label("Version")}: ${f}`,` ${n.label("Capability")}: ${c}`,` ${n.label("Reason")}: ${d}`,` ${n.label("Reason code")}: ${u}`,` ${n.label("Can execute")}: ${m===!0?"yes":"no"}`,` ${n.label("Audit required")}: ${k===!1?"no":"yes"}`,` ${n.label("Cloud telemetry")}: ${w===!0?"yes":"no"}`,"",n.section("Next")];return o==="blocked"?x.push(` ${n.arrow} Do not run this action.`,` ${n.arrow} Review \`skills-layer trust ${g}\`.`,` ${n.arrow} Run \`skills-layer guardian incident --skill ${g} --version ${f} --path <installed-skill-path> --reason "<reason>"\` if this was unexpected.`):x.push(` ${n.arrow} Continue only with the action Guardian evaluated.`,` ${n.arrow} Re-run guardian check if the action changes.`),x.join(`
|
|
1197
|
+
`)}function Ht(e,t){if($(e))return typeof e[t]=="boolean"?e[t]:void 0}function T(e,t){return $(e)?l(e,t):void 0}function Yl(e){return e.split(/[_-]+/u).filter(Boolean).map(t=>`${t[0]?.toUpperCase()??""}${t.slice(1)}`).join(" ")}function Vi(e){return!!(S(e,"backend")&&S(e,"auth")&&Array.isArray(e.checks))}function Zl(e,t,n){let i=[`${n.ok("OK")} ${t}`,"",n.section("Readiness")],r=l(e,"summary");r&&i.push(` ${r}`);let s=S(e,"backend"),o=s?nc(s):void 0;o&&i.push(` ${n.label("Backend")}: ${o}`);let a=S(e,"auth"),c=a?ic(a):void 0;c&&i.push(` ${n.label("Account")}: ${c}`);let u=a?O(a,"workspaceCount"):void 0;u!==void 0&&i.push(` ${n.label("Workspaces")}: ${u}`);let d=a?O(a,"libraryCount"):void 0;d!==void 0&&i.push(` ${n.label("Owned skills")}: ${d}`);let g=Tr(e);return g.length>0&&i.push("",n.section("Next"),...g.map(f=>` ${n.arrow} ${f}`)),i.push(` ${n.arrow} Run \`skills-layer doctor\` for diagnostics.`),i.join(`
|
|
1198
|
+
`)}function Ql(e,t,n){let i=[`${n.ok("OK")} ${t}`,"",n.section("Diagnostics")],r=l(e,"summary");r&&i.push(` ${r}`);let s=l(e,"status");s&&i.push(` ${n.label("Status")}: ${s}`);let o=Br(e),a=o.filter(d=>rc(l(d,"status"))),c=o.filter(d=>l(d,"status")!=="pass");i.push(a.length===0?" No blocking issues found.":` ${a.length} check${a.length===1?"":"s"} need attention.`),a.length===0&&c.length>0&&i.push(` Advisory checks needing attention: ${c.length}.`),i.push("",n.section(`Checks (${o.length})`)),o.length===0&&i.push(` ${n.muted("No checks returned by the backend.")}`),o.forEach((d,g)=>{let f=l(d,"status")??"unknown",m=l(d,"title")??l(d,"id")??`Check ${g+1}`;i.push(`${g+1}. ${n.label(`[${f}] ${m}`)}`);let k=l(d,"summary");k&&i.push(` ${k}`);let w=l(d,"why");if(w&&i.push(` ${n.label("Why")}: ${w}`),f!=="pass"){let C=l(d,"nextStep");C&&i.push(` ${n.label("Fix")}: ${C}`);let x=l(d,"recommendedCommand");x&&i.push(` ${n.label("Try")}: ${x}`)}});let u=Tr(e);return u.length>0&&i.push("",n.section(a.length>0?"Recommended Fix":"Next"),...u.map(d=>` ${n.arrow} ${d}`)),i.join(`
|
|
1199
|
+
`)}function Xl(e,t,n,i){let r=[`${n.ok("OK")} ${t}`],s=se(e,"requestedSlugs");s&&s.length>0&&r.push("",n.section("Requested"),` ${s.join(", ")}`);let o=de(e.results);r.push("",n.section(`Comparison (${o.length})`)),o.length===0&&r.push(` ${n.muted("No comparable skills returned.")}`),o.forEach((d,g)=>{let f=sn(d)??`Skill ${g+1}`;r.push(`${g+1}. ${f}`);let m=ec(d);m&&r.push(` ${m}`);let k=Kr(d);k&&r.push(` ${n.label("summary")}: ${i?k.replace(/\s+/gu," ").trim():Re(k)}`)});let a=de(e.missing);a.length>0&&(r.push("",n.section(`Missing (${a.length})`)),a.forEach((d,g)=>{let f=l(d,"slug")??l(d,"skillSlug")??sn(d)??`Entry ${g+1}`,m=l(d,"reason")??l(d,"status");r.push(`${g+1}. ${m?`${f} - ${m}`:f}`)}));let c=se(e,"guidance")??xe(e.guidance);c.length>0&&r.push("",n.section("Guidance"),...c.slice(0,3).map(d=>` ${n.arrow} ${Re(d)}`));let u=tc(o);return u.length>0&&r.push("",n.section("Next"),...u.map(d=>` ${n.arrow} ${d}`)),r.join(`
|
|
1200
|
+
`)}function ec(e){let t=S(e,"securityPosture"),n=l(e,"trust")??l(e,"trustStatus")??l(e,"trustLabel")??(t?l(t,"label"):void 0),i=e.score??e.securityScore??(t?t.securityScore:void 0),r=l(e,"risk")??l(e,"runtimeRisk")??(t?l(t,"runtimeRisk"):void 0);return[["slug",l(e,"slug")??l(e,"skillSlug")],["version",l(e,"version")??l(e,"currentVersion")],["category",l(e,"category")],["type",l(e,"type")??l(e,"skillType")],["trust",n],["score",i],["risk",r]].flatMap(([o,a])=>a==null||a===""?[]:[`${o}: ${z(String(o),a)}`]).join("; ")}function tc(e){let t=[];for(let n of e.slice(0,5)){let i=l(n,"slug")??l(n,"skillSlug");i&&t.push(`skills-layer show ${i}`,`skills-layer trust ${i}`,`skills-layer install ${i}`)}return t}function nc(e){let t=l(e,"edition"),n=l(e,"baseUrl");return t&&n?`${t} at ${n}`:t??n}function ic(e){let t=l(e,"state");if(t&&t!=="authenticated")return t==="anonymous"?"not signed in":t;let n=l(e,"email"),i=se(e,"roles");return n&&i&&i.length>0?`${n} (${i.join(", ")})`:n??l(e,"role")}function Tr(e){let t=[],n=l(e,"recommendedCommand");n&&t.push(n);let i=l(e,"nextStep");return i&&t.push(i),t}function Br(e){return Array.isArray(e.checks)?e.checks.filter($):[]}function rc(e){return e!==void 0&&e!=="pass"&&e!=="warn"&&e!=="advisory"}function de(e){return Array.isArray(e)?e.filter($):[]}function xe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function sc(e){let t=e.commerce===!0;return{status:t?"available":"unavailable",summary:t?"Marketplace purchases, invoices, refunds, and creator commerce flows are available.":"Marketplace commerce is not available on this backend.",availableWorkflows:t?["Browse skills with `skills-layer featured` or `skills-layer search <query>`.","Start purchase handoff with `skills-layer buy <skill-slug>`.","Review account purchases with `skills-layer purchases list`."]:["Browse and install available free skills.","Use `skills-layer help topic install` for install guidance."]}}var oc={"core.identity":"Account and sign-in","core.catalog":"Catalog discovery","core.validation":"Creator validation","core.creator":"Creator submissions","core.library":"Owned skills","core.workspace":"Workspace rollout","core.guardian":"Runtime trust checks","core.source":"Source installs","core.discovery":"Catalog discovery","marketplace.commerce":"Marketplace commerce","marketplace.reviews":"Reviews and issues","marketplace.payouts":"Creator earnings"};function ac(e){let t=xe(e.capabilities);return{status:"ok",edition:l(e,"edition")??"unknown",summary:"Public product capabilities available on the selected backend.",capabilities:t.map(n=>({name:oc[n]??wt(n.replace(/^[^.]+\./u,"").replace(/[._-]+/gu," ")),available:!0})),count:t.length}}function lc(e,t){let n=p(e);if(!n)return;let i=Number(n);return!Number.isInteger(i)||i<=0?y("help optimize-tokens --max-characters must be a positive integer.",t):i<120||i>4e3?y("help optimize-tokens --max-characters must be between 120 and 4000.",t):i}function cc(e,t,n){let i=Z(n),r=S(e,"validation")??e,s=S(r,"parsedSkill")??S(e,"parsedSkill"),o=s?S(s,"frontmatter"):void 0,a=l(e,"skillSlug")??(o?l(o,"name"):void 0),c=r.valid===!0||e.valid===!0,u=zt(r,e,"issues"),d=zt(r,e,"warnings"),g=zt(r,e,"advice"),f=S(r,"stats")??S(e,"stats"),m=[`${i.ok("OK")} Validation complete.`,"",i.section("Bundle")];if(m.push(` ${i.label("Path")}: ${t}`),a&&m.push(` ${i.label("Skill")}: ${a}`),m.push(` ${i.label("Readiness")}: ${c?"ready for dry-run submission":"needs changes before submission"}`),m.push("",i.section("Checks")),m.push(` ${i.arrow} SKILL.md structure and frontmatter`),m.push(` ${i.arrow} Required bundle files and supported directories`),m.push(` ${i.arrow} Secret hygiene, unsafe script signals, and trust-review readiness`),m.push(` ${i.arrow} Trigger quality inputs for should-trigger / should-not-trigger testing`),f){let k=f.fileCount??f.files??e.fileCount,w=f.bodyWordCount??f.bodyWords??e.bodyWordCount;m.push("",i.section("File Summary")),k!==void 0&&m.push(` ${i.label("File count")}: ${z("fileCount",k)}`),w!==void 0&&m.push(` ${i.label("Body words")}: ${z("bodyWordCount",w)}`)}return m.push("",...Wt("Issues",u,i,"No blocking issues found.")),m.push("",...Wt("Warnings",d,i,"No warnings returned.")),m.push("",...Wt("Advice",g,i,"No extra advice returned.")),m.push("",i.section("Next")),m.push(` ${i.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),m.push(` ${i.arrow} skills-layer creator submit ${t} --dry-run`),m.join(`
|
|
1201
|
+
`)}function zt(e,t,n){let i=Array.isArray(e[n])?e[n]:[],r=Array.isArray(t[n])?t[n]:[];return i.length>0?i:r}function Wt(e,t,n,i){let r=[n.section(`${e} (${t.length})`)];return t.length===0?(r.push(` ${n.muted(i)}`),r):(t.slice(0,N).forEach((s,o)=>{r.push(`${o+1}. ${Nr(s)}`)}),r)}function Nr(e){return $(e)?(l(e,"message")??l(e,"title")??l(e,"code")??l(e,"path")??qe(e))||"Details available with --json":z("",e)}function uc(e,t,n){let i=Z(n),r=dc(e),s=pc(e),o=[`${i.ok("OK")} Trigger preview complete.`,"",i.section("Bundle"),` ${i.label("Path")}: ${t}`],a=l(e,"skillSlug")??l(e,"slug");return a&&o.push(` ${i.label("Skill")}: ${a}`),o.push("",i.section(`Prompt Results (${r.length})`)),r.length===0&&o.push(` ${i.muted("No prompt results returned. Use --json to inspect the raw backend response.")}`),r.slice(0,N).forEach((c,u)=>{o.push(`${u+1}. ${gc(c,u)}`)}),o.push("",i.section(`Guidance (${s.length})`)),s.length===0&&o.push(` ${i.muted("No extra trigger guidance returned.")}`),s.slice(0,N).forEach((c,u)=>{o.push(`${u+1}. ${c}`)}),o.push("",i.section("Next")),o.push(` ${i.arrow} skills-layer validate ${t}`),o.push(` ${i.arrow} skills-layer creator submit ${t} --dry-run`),o.join(`
|
|
1202
|
+
`)}function dc(e){return[...de(e.promptResults),...de(e.results),...de(e.shouldTriggerResults),...de(e.shouldNotTriggerResults),...de(e.paraphraseResults)]}function pc(e){let t=xe(e.guidance),n=de(e.guidance).map(i=>Nr(i));return[...t,...n]}function gc(e,t){let n=l(e,"prompt")??l(e,"text")??l(e,"input")??`Prompt ${t+1}`,i=mc(e),r=fc(e),s=hc(e),o=e.score??e.confidence,a=l(e,"reason")??l(e,"explanation")??l(e,"message");return[`"${Re(n)}"`,i?`expected: ${i}`:void 0,r?`actual: ${r}`:void 0,s,o!==void 0?`score: ${z("score",o)}`:void 0,a?`reason: ${Re(a)}`:void 0].filter(c=>!!c).join("; ")}function mc(e){return typeof e.shouldTrigger=="boolean"?e.shouldTrigger?"should trigger":"should not trigger":typeof e.expectedTrigger=="boolean"?e.expectedTrigger?"should trigger":"should not trigger":l(e,"expected")??l(e,"kind")??l(e,"type")}function fc(e){return typeof e.triggered=="boolean"?e.triggered?"triggered":"did not trigger":typeof e.actualTrigger=="boolean"?e.actualTrigger?"triggered":"did not trigger":l(e,"actual")??l(e,"classification")??l(e,"decision")}function hc(e){return typeof e.passed=="boolean"?e.passed?"pass":"fail":typeof e.pass=="boolean"?e.pass?"pass":"fail":l(e,"status")}function yc(e,t,n,i){let r=Z(i),s=l(e,"skillSlug")??K(t),o=[`${r.ok("OK")} Created ${n}.`,"",r.section("Local Skill")];o.push(` ${r.label("Path")}: ${n}`),o.push(` ${r.label("Skill")}: ${s}`);let a=l(e,"skillType"),c=l(e,"category");return a&&o.push(` ${r.label("Type")}: ${a}`),c&&o.push(` ${r.label("Category")}: ${c}`),o.push("",r.section("Next")),o.push(` ${r.arrow} Edit ${n}`),o.push(` ${r.arrow} skills-layer validate ${t}`),o.push(` ${r.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),o.push(` ${r.arrow} skills-layer creator submit ${t} --dry-run`),o.join(`
|
|
1203
|
+
`)}function kc(e,t,n){let i=S(e,"profile")??e,r=Jt(i,"requirementsCurrentlyDue"),s=Jt(i,"requirementsPastDue"),o=Jt(i,"requirementsPendingVerification"),a=["payouts","Enabled"].join(""),c=i.readyForPayouts??i[a],u=c===!0,d=[`${n.ok("OK")} ${t}`,"",n.section("Payout Profile")];return d.push(` ${n.label("Status")}: ${rt(l(i,"status"))}`),d.push(` ${n.label("Ready for payouts")}: ${Hi(c)}`),d.push(` ${n.label("Account details submitted")}: ${Hi(i.detailsSubmitted)}`),d.push(` ${n.label("Currency")}: ${rt(l(i,"currency")?.toUpperCase())}`),d.push(` ${n.label("Country")}: ${rt(l(i,"country")?.toUpperCase())}`),d.push(` ${n.label("Minimum withdrawal")}: ${vc(i)}`),d.push(` ${n.label("Updated at")}: ${rt(l(i,"updatedAt"))}`),d.push("",n.section("Requirements")),d.push(` ${n.label("Currently due")}: ${Yt(r)}`),d.push(` ${n.label("Past due")}: ${Yt(s)}`),d.push(` ${n.label("Pending verification")}: ${Yt(o)}`),d.push("",n.section("Next")),u?(d.push(` ${n.arrow} skills-layer creator earnings`),d.push(` ${n.arrow} skills-layer creator withdraw --amount-cents <amount>`),d.push(` ${n.arrow} skills-layer creator payouts`)):(d.push(` ${n.arrow} skills-layer creator payout-link`),d.push(` ${n.arrow} skills-layer creator earnings`)),d.join(`
|
|
1204
|
+
`)}function wc(e,t,n){let i=rn(e),r=In(e,"withdrawableBalanceCents"),s=[`${n.ok("OK")} ${t}`,"",n.section("Earnings Summary")];return s.push(` ${n.label("Gross sales")}: ${V(e,"successfulSalesCents",i)}`),s.push(` ${n.label("Platform fees")}: ${V(e,"platformFeeCents",i)}`),s.push(` ${n.label("Refunds requested")}: ${V(e,"refundRequestedCents",i)}`),s.push(` ${n.label("Refunded")}: ${V(e,"refundedCents",i)}`),s.push(` ${n.label("Estimated available")}: ${V(e,"estimatedAvailableCents",i)}`),s.push(` ${n.label("Withdrawable now")}: ${V(e,"withdrawableBalanceCents",i)}`),s.push(` ${n.label("Held balance")}: ${V(e,"heldBalanceCents",i)}`),s.push(` ${n.label("Refund exposure")}: ${V(e,"refundExposureCents",i)}`),s.push("",n.section("Activity")),s.push(` ${n.label("Successful purchases")}: ${Di(e,"successfulPurchaseCount")}`),s.push(` ${n.label("Refund requests")}: ${Di(e,"refundRequestedCount")}`),s.push(` ${n.label("Pending payouts")}: ${V(e,"pendingPayoutCents",i)}`),s.push(` ${n.label("Completed payouts")}: ${V(e,"completedPayoutCents",i)}`),s.push("",n.section("Guidance")),r>0?(s.push("1. You have a withdrawable balance available."),s.push("2. Confirm payout setup is ready before requesting withdrawal.")):(s.push("1. No withdrawable balance yet."),s.push("2. Sales will appear here after paid purchases settle.")),s.push("",n.section("Next")),r>0&&s.push(` ${n.arrow} skills-layer creator withdraw --amount-cents ${r}`),s.push(` ${n.arrow} skills-layer creator payout-profile`),s.push(` ${n.arrow} skills-layer creator payouts`),s.join(`
|
|
1205
|
+
`)}function bc(e,t,n){let i=Array.isArray(e.results)?e.results:[],r=rn(e,i),s=In(e,"withdrawableBalanceCents"),o=[`${n.ok("OK")} ${t}`,"",n.section("Payout History")];return o.push(` ${n.label("Withdrawable now")}: ${V(e,"withdrawableBalanceCents",r)}`),o.push(` ${n.label("Pending payouts")}: ${V(e,"pendingPayoutCents",r)}`),o.push(` ${n.label("Completed payouts")}: ${V(e,"completedPayoutCents",r)}`),o.push("",n.section(`Requests (${i.length})`)),i.length===0?o.push(` ${n.muted("No payout requests yet.")}`):(i.slice(0,N).forEach((a,c)=>{if(!$(a)){o.push(`${c+1}. ${z("",a)}`);return}let u=rn(a,void 0,r),d=l(a,"payoutId")??l(a,"id")??`Payout ${c+1}`,g=l(a,"status")??"unknown",f=V(a,"amountCents",u),m=l(a,"requestedAt"),k=l(a,"completedAt"),w=l(a,"reason");o.push(`${c+1}. ${d}`),o.push(` ${n.label("Amount")}: ${f}; ${n.label("Status")}: ${g}`),m&&o.push(` ${n.label("Requested")}: ${m}`),k&&o.push(` ${n.label("Completed")}: ${k}`),w&&o.push(` ${n.label("Reason")}: ${w}`)}),i.length>N&&o.push(` ${n.muted(`... ${i.length-N} more`)}`)),o.push("",n.section("Guidance")),i.length===0?o.push("1. Payouts appear here after you request a withdrawal."):o.push("1. Use this history to track requested, processing, paid, or failed payouts."),o.push("2. Check payout profile if setup or verification looks incomplete."),o.push("",n.section("Next")),s>0&&o.push(` ${n.arrow} skills-layer creator withdraw --amount-cents ${s}`),o.push(` ${n.arrow} skills-layer creator earnings`),o.push(` ${n.arrow} skills-layer creator payout-profile`),o.join(`
|
|
1206
|
+
`)}function rn(e,t,n="GBP"){let i=l(e,"currency");if(i)return i.toUpperCase();let r=t?.find($);if(r){let s=l(r,"currency");if(s)return s.toUpperCase()}return n}function In(e,t){return O(e,t)??0}function Di(e,t){return O(e,t)??0}function V(e,t,n){return`${Mr(In(e,t))} ${n}`}function Jt(e,t){return(se(e,t)??[]).map(n=>n.replace(/[._-]+/gu," "))}function Yt(e){return e.length>0?e.join(", "):"none"}function Hi(e){return e===!0?"yes":e===!1?"no":"unknown"}function rt(e){return e??"none"}function vc(e){let t=O(e,"minimumWithdrawalAmountCents"),n=l(e,"currency")?.toUpperCase()??"minor units";return t===void 0?"none":`${Mr(t)} ${n}`}function Mr(e){return(e/100).toFixed(2).replace(/\.00$/u,"").replace(/(\.\d)0$/u,"$1")}function Z(e){let t=Sc(e);return{ok:n=>t?Ce(32,n):n,section:n=>t?Ce(1,Ce(36,n)):n,label:n=>t?Ce(1,n):n,muted:n=>t?Ce(2,n):n,arrow:t?Ce(36,"->"):"->"}}function Sc(e){let t=e?.env??{};if(t.NO_COLOR)return!1;let n=t.FORCE_COLOR;return n&&n!=="0"?!0:!!e?.stdoutIsTty&&t.TERM!=="dumb"&&n!=="0"}function Ce(e,t){return`\x1B[${e}m${t}\x1B[0m`}function Fr(e,t){let n=[],i=Cc(e,t);i.length>0&&n.push(...i);for(let[r,s]of _c(e))if(Array.isArray(s))n.push(...Pc(r,s,t));else if($(s)){let o=qe(s);o&&n.push(` ${t.label(on(r))}: ${o}`)}else n.push(` ${t.label(on(r))}: ${z(r,s)}`);return n}function Pc(e,t,n){let i=$c(e),r=[n.section(`${i} (${t.length})`)];return t.length===0?(r.push(` ${n.muted("No entries.")}`),r):(t.slice(0,N).forEach((s,o)=>{r.push(...Or(s,o,n))}),t.length>N&&r.push(` ${n.muted(`... ${t.length-N} more`)}`),r)}function Or(e,t,n){if(!$(e))return[`${t+1}. ${z("",e)}`];let i=sn(e)??X(qe(e))??`Item ${t+1}`,r=[`${t+1}. ${i}`],s=Kr(e);s&&r.push(` ${s}`);let o=qe(e);return o&&r.push(` ${o}`),r}function Cc(e,t){let n=Ea(e,t);if(n.length>0)return n;let i=S(e,"capabilityProfile"),r=i?l(i,"runtimeRisk"):void 0;return r?[t.section("Trust"),` ${t.label("Runtime risk")}: ${r}`]:[]}function xc(e,t,n){let i=Z(n),r=l(e,"skillSlug")??t,s=l(e,"runtimeRisk")??(S(e,"capabilityProfile")?l(S(e,"capabilityProfile"),"runtimeRisk"):void 0),o=[`${i.ok("OK")} Creator security report loaded.`,"",i.section("Creator Security")];e.securityScore!==void 0&&o.push(` ${i.label("Security score")}: ${z("securityScore",e.securityScore)}`),s&&o.push(` ${i.label("Runtime risk")}: ${s}`);let a=l(e,"recommendation");a&&o.push(` ${i.label("Recommendation")}: ${a}`),o.push(` ${i.label("Skill")}: ${r}`);let c=l(e,"version");c&&o.push(` ${i.label("Version")}: ${c}`);let u=["semantic","review","no","reviewable","findings"].join("_"),d=xe(e.reviewDegradedReasons).includes(u),g=xe(e.trustBadges).filter(k=>k==="capability-mismatch"),f=xe(e.trustBadges).filter(k=>k!=="capability-mismatch");(d||g.length>0)&&(o.push("",i.section("Creator Notes")),d&&o.push("1. Semantic review was not needed because there were no reviewable findings."),g.forEach((k,w)=>{o.push(`${d?w+2:w+1}. ${k==="capability-mismatch"?"Capability declaration needs review.":k}`)})),f.length>0&&(o.push("",i.section(`Trust badges (${f.length})`)),f.slice(0,N).forEach((k,w)=>o.push(`${w+1}. ${k}`)));let m=Array.isArray(e.findings)?e.findings:[];return o.push("",i.section(`Findings (${m.length})`)),m.length===0?o.push(` ${i.muted("No entries.")}`):m.slice(0,N).forEach((k,w)=>{o.push(...Or(k,w,i))}),o.push("",i.section("Next")),o.push(` ${i.arrow} skills-layer creator rescan-security ${r}`),o.push(` ${i.arrow} skills-layer creator status ${r}`),o.push(` ${i.arrow} skills-layer trust ${r}`),o.join(`
|
|
1207
|
+
`)}function Rc(e,t,n){let r=S(e,"report")??e,s=Z(n),o=r.securityScore,a=l(r,"generatedAt")??l(r,"reportGeneratedAt"),c=Array.isArray(r.findings)?r.findings:void 0,u=[`${s.ok("OK")} Security rescan requested.`,"",s.section("Creator Security")];return u.push(` ${s.label("Skill")}: ${l(r,"skillSlug")??t}`),o!==void 0&&u.push(` ${s.label("Security score")}: ${z("securityScore",o)}`),c&&u.push(` ${s.label("Findings")}: ${c.length}`),a&&u.push(` ${s.label("Generated at")}: ${a}`),u.push("",s.section("Next")),u.push(` ${s.arrow} skills-layer creator security-report ${t}`),u.push(` ${s.arrow} skills-layer creator status ${t}`),u.join(`
|
|
1208
|
+
`)}function _c(e){return Object.entries(e).filter(([t,n])=>qr(t,n))}function qr(e,t){let n=e.toLowerCase();return n==="status"||n==="securityscore"||n==="recommendation"||n==="capabilityprofile"||n==="securityposture"||n==="trust"||n.includes("apikey")||n.includes("secret")||n.includes("token")||n==="content"?!1:t!==void 0}function qe(e){let n=[["id","id"],["name","name"],["keyPrefix","prefix"],["slug","slug"],["skillSlug","skill"],["currentVersion","version"],["version","version"],["category","category"],["skillType","type"],["type","type"],["visibility","visibility"],["status","status"],["count","count"],["email","email"],["role","role"],["selectedBackend","backend"],["selectedBaseUrl","base url"],["path","path"],["downloadUrl","download url"],["authorizationUrl","authorization url"],["checkoutUrl","checkout url"],["url","url"],["issueId","issue"],["reviewId","review"],["purchaseId","purchase"],["workspaceId","workspace"],["clientId","client"],["environment","environment"],["expiresAt","expires"],["lastUsedAt","last used"],["revocable","revocable"],["revokeCommand","revoke"],["deploymentId","deployment"],["source","source"],["scope","scope"],["agent","agent"],["bytes","bytes"],["fileCount","file count"],["bodyWordCount","body words"]].flatMap(([r,s])=>{if(!qr(r,e[r]))return[];let o=e[r];return o===void 0?[]:[`${s}: ${z(r,o)}`]}),i=S(e,"securityPosture");if(i){let r=l(i,"label"),s=l(i,"runtimeRisk");r&&n.push(`trust: ${r}`),s&&n.push(`risk: ${s}`)}return n.join("; ")}function Kr(e){return l(e,"shortDescription")??l(e,"summary")??l(e,"description")??l(e,"message")}function sn(e){return l(e,"displayName")??l(e,"name")??l(e,"title")??l(e,"slug")??l(e,"skillSlug")??l(e,"code")??l(e,"id")}function z(e,t){return e==="downloadUrl"?"<hidden; use --json or --output>":typeof t=="string"?e.toLowerCase()==="category"?Gr(t):Re(t):typeof t=="number"||typeof t=="boolean"?String(t):t===null?"none":Array.isArray(t)?`${t.length} item${t.length===1?"":"s"}`:$(t)?qe(t)||"details available with --json":String(t)}function Gr(e){return Qn(e)}function Re(e){let t=e.replace(/\s+/gu," ").trim();return t.length>160?`${t.slice(0,157)}...`:t}function $c(e){return wt(on(e))}function on(e){return e.replace(/([a-z0-9])([A-Z])/gu,"$1 $2").replace(/[_-]+/gu," ").toLowerCase()}function Vr(e){let t=Ic(e),n=t?[`skills-layer show ${t}`,`skills-layer trust ${t}`,`skills-layer install ${t}`]:[],i=typeof e.downloadUrl=="string",r=Array.isArray(e.materializedWrites)&&e.materializedWrites.length>0;return i&&n.push("Use --output <path> to write exports without printing temporary download URLs"),r&&n.push("Review the materialized files in this workspace"),e.valid===!0&&n.push("skills-layer creator submit <path> --dry-run"),n}function Ic(e){let t=l(e,"skillSlug")??l(e,"slug");if(t)return t;let n=e.results;if(Array.isArray(n)){for(let i of n)if($(i)){let r=l(i,"skillSlug")??l(i,"slug");if(r)return r}}}function $(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function y(e,t){return{exitCode:1,stdout:"",stderr:t?JSON.stringify({status:"error",summary:e,why:null,nextAction:null,nextStep:null,data:{error:e},warnings:[],links:[],reasonCode:null,handoff:null},null,2):e}}function P(e,t,n,i){let r={status:l(e,"status")??"error",summary:t,why:l(e,"why")??null,nextAction:l(e,"nextAction")??null,nextStep:l(e,"nextStep")??null,data:e,warnings:Array.isArray(e.warnings)?e.warnings:[],links:Array.isArray(e.links)?e.links:[],reasonCode:i??l(e,"reasonCode")??null,handoff:e.handoff??null};return{exitCode:1,stdout:"",stderr:n?JSON.stringify(r,null,2):t}}function yt(e,t){let n=e.details??{};if(e.status===401){let s=l(n,"error")??"Login required.",o=l(n,"nextAction")??"login",a=l(n,"nextStep")??"Run `skills-layer login` to sign in, then retry this command.";return P({status:"login_required",reasonCode:"login_required",error:s,nextAction:o,nextStep:a},`${s==="Login required."?"Login required":s}. ${a}`,t,"login_required")}let i=l(n,"reasonCode");if(i){let s=l(n,"error")??e.message;return P({status:l(n,"status")??(e.status===404?"not_found":"error"),...n,reasonCode:i},s,t,i)}let r=jc(e);return r?P(r.payload,r.message,t,r.reasonCode):y(l(n,"error")??e.message,t)}function jc(e){let t=l(e.details??{},"error")??e.message,n=t.toLowerCase();return e.status===404&&n.includes("source connection")?{reasonCode:"source_connection_not_found",message:"Source connection not found.",payload:{status:"not_found",error:t,reasonCode:"source_connection_not_found",nextAction:"source.connection.start",nextStep:"Check the source connection id, or start a new source connection."}}:e.status===404&&n.includes("approval request")?{reasonCode:"approval_request_not_found",message:"Approval request not found.",payload:{status:"not_found",error:t,reasonCode:"approval_request_not_found",nextAction:"approval.request.status",nextStep:"Check the approval request id, or rerun the workflow that created the approval request."}}:e.status===404&&(n.includes("purchase")||n.includes("invoice"))?{reasonCode:"purchase_not_found",message:"Purchase not found.",payload:{status:"not_found",error:t,reasonCode:"purchase_not_found",nextAction:"purchases.list",nextStep:"Run `skills-layer purchases list` to find a valid purchase id."}}:e.status===404&&n.includes("skill")?{reasonCode:"skill_not_found",message:"Skill not found.",payload:{status:"not_found",error:t,reasonCode:"skill_not_found",nextAction:"search",nextStep:"Run `skills-layer search <query>` to find a valid skill slug before retrying."}}:null}async function Y(e){try{return JSON.parse(await Ge(e,"utf8"))}catch{return null}}async function Ac(e,t){let n=await Y(e);return n?li(n,{env:t.env,platform:t.platform,store:t.credentialStore}):null}async function jn(e,t,n){let i=await ai(t,{env:n.env,platform:n.platform,store:n.credentialStore});await D(e,i)}async function D(e,t){await Dr(ee(e)),await dn(e,`${JSON.stringify(t,null,2)}
|
|
1209
|
+
`,{encoding:"utf8",mode:384}),await An(e,384)}async function Dr(e){await Ke(e,{recursive:!0,mode:448}),await An(e,448)}async function An(e,t){if(process.platform!=="win32")try{await Yi(e,t)}catch{}}async function re(e,t){await Ke(ee(e),{recursive:!0}),await dn(e,t,"utf8")}async function an(e,t){await Ke(ee(e),{recursive:!0}),await dn(e,t)}function Lc(e=process.stdin,t=process.stdout,n=gn){return async i=>{if(!e.isTTY||!t.isTTY)throw new Error("Interactive prompt is not available in this environment.");let r=n({input:e,output:t});try{return(await r.question(i)).trim()}finally{r.close()}}}function Ec(e=process.stdin,t=process.stdout,n=gn){return async i=>{if(!e.isTTY||!t.isTTY)throw new Error("Interactive secret prompt is not available in this environment.");if(typeof e.setRawMode=="function"&&typeof e.on=="function"&&typeof e.off=="function")return new Promise((s,o)=>{let a=e,c=a.isRaw===!0,u="",d=!1,g=m=>{d||(d=!0,a.off("data",f),a.setRawMode(c),a.pause?.(),t.write(`
|
|
1210
|
+
`),m())},f=m=>{let k=typeof m=="string"?m:m.toString("utf8");for(let w of k){if(w==="\r"||w===`
|
|
1211
|
+
`){g(()=>s(u.trim()));return}if(w===""){g(()=>o(new Error("Interactive secret prompt cancelled.")));return}if(w==="\b"||w==="\x7F"){u.length>0&&(u=u.slice(0,-1),t.write("\b \b"));continue}u+=w,t.write("*")}};t.write(i),a.resume?.(),a.on("data",f),a.setRawMode(!0)});let r=n({input:e,output:t,terminal:!0});r.stdoutMuted=!0,r._writeToOutput=function(o){if(!this.stdoutMuted){t.write(o);return}if(o==="\b"||o==="\x7F"){t.write("\b \b");return}if(o!=="\r"&&o!==`
|
|
1212
|
+
`){let a=[...o].filter(c=>c!=="\r"&&c!==`
|
|
1213
|
+
`).length;a>0&&t.write("*".repeat(a))}};try{t.write(i);let s=await r.question("");return t.write(`
|
|
1214
|
+
`),s.trim()}finally{r.close()}}}function Uc(e=process.stdin,t=process.stdout,n=gn){return async(i,r)=>{if(r.length===0)throw new Error("Interactive selection has no available options.");if(!e.isTTY||!t.isTTY)throw new Error("Interactive selection is not available in this environment.");let s=e;if(typeof s.setRawMode=="function"&&typeof s.on=="function"&&typeof s.off=="function")return new Promise((a,c)=>{let u=0,d="",g=0,f=!1,m=s.isRaw===!0,k=()=>{g>0&&t.write(`\x1B[${g}F\x1B[J`),t.write(`${i}
|
|
1215
|
+
`);for(let[x,E]of r.entries())t.write(`${Tc(x===u)} ${x+1}. ${zi(E)}
|
|
1113
1216
|
`);t.write(`Choice: ${d}
|
|
1114
1217
|
`),t.write(`Use up/down arrows, type a number, then press Enter.
|
|
1115
|
-
`),g=r.length+3},w=
|
|
1116
|
-
`),
|
|
1117
|
-
`)){if(d){let
|
|
1118
|
-
`);for(let[u,d]of r.entries())t.write(`${u+1}. ${
|
|
1119
|
-
`);let
|
|
1218
|
+
`),g=r.length+3},w=x=>{f||(f=!0,s.off?.("data",C),s.setRawMode?.(m),s.pause?.(),t.write(`
|
|
1219
|
+
`),x())},C=x=>{let E=typeof x=="string"?x:x.toString("utf8");if(E.includes("")){w(()=>c(new Error("Interactive selection cancelled.")));return}if(E.includes("\x1B[A")){d="",u=(u-1+r.length)%r.length,k();return}if(E.includes("\x1B[B")){d="",u=(u+1)%r.length,k();return}if(E.includes("\r")||E.includes(`
|
|
1220
|
+
`)){if(d){let U=Number.parseInt(d,10)-1;if(Number.isNaN(U)||U<0||U>=r.length){d="",t.write("\x07"),k();return}u=U}w(()=>a(r[u]?.value??r[0].value));return}if(E.includes("\b")||E.includes("\x7F")){d=d.slice(0,-1);let U=Number.parseInt(d,10)-1;!Number.isNaN(U)&&U>=0&&U<r.length&&(u=U),k();return}let le=[...E].filter(U=>/[0-9]/u.test(U));if(le.length>0){d=`${d}${le.join("")}`;let U=Number.parseInt(d,10)-1;!Number.isNaN(U)&&U>=0&&U<r.length&&(u=U),k()}};k(),s.resume?.(),s.on("data",C),s.setRawMode(!0)});let o=n({input:e,output:t});try{t.write(`${i}
|
|
1221
|
+
`);for(let[u,d]of r.entries())t.write(`${u+1}. ${zi(d)}
|
|
1222
|
+
`);let a=(await o.question("Choose a number and press enter: ")).trim(),c=Number.parseInt(a,10)-1;if(Number.isNaN(c)||c<0||c>=r.length)throw new Error("No valid option selected.");return r[c].value}finally{o.close()}}}function Tc(e){return e?"\x1B[36m>\x1B[0m":" "}function zi(e){return e.description?`${e.label} (${e.description})`:e.label}function Bc(e){return async t=>{let n=e==="win32"?{file:"rundll32.exe",args:["url.dll,FileProtocolHandler",t]}:e==="darwin"?{file:"open",args:[t]}:{file:"xdg-open",args:[t]};return new Promise(i=>{try{let r=Wi(n.file,n.args,{detached:!0,stdio:"ignore"});r.on("error",()=>i(!1)),r.unref(),i(!0)}catch{i(!1)}})}}function G(e,t){let n={};for(let i of t){let r=e[i];r!==void 0&&r!==!1&&(i.endsWith("Cents")||i==="rating"?n[i]=Number(r):n[i]=r)}return _(n)}function Nc(e){let t=e.results;return Array.isArray(t)?t.flatMap(n=>{if(!n||typeof n!="object"||Array.isArray(n))return[];let i=l(n,"slug")??l(n,"skillSlug");return i?[i]:[]}):[]}function Mc(e){let t=p(e)??"auto";return t==="auto"||t==="required"||t==="optional"||t==="off"?{status:"ok",policy:t}:{status:"invalid",message:"guardian check --cloud-trust-ledger must be one of: auto, required, optional, off."}}function _(e){let t={};for(let[n,i]of Object.entries(e))i!==void 0&&(t[n]=i);return t}function kt(e,t){let n=p(e);return n?Ln(n,t):void 0}function Ln(e,t){try{return JSON.parse(e)}catch{throw new Error(`--${t} must be valid JSON.`)}}function W(e){if(!e||typeof e!="object"||Array.isArray(e))return e;let t={...e};return delete t.apiKey,delete t[["ad","min","Api","Key"].join("")],t}function ln(e){let t=W(e);for(let n of["role","roles","verifiedAt","expiresAt","userId","tenantId","linkedAccount","linkedIdentity","createdUser"])delete t[n];return t}function b(e,t){let n=p(e);if(!n)throw new Error(t);return n}function p(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function X(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function l(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n.trim():void 0}function O(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim().length>0){let i=Number(n);return Number.isFinite(i)?i:void 0}}function S(e,t){let n=e[t];return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function se(e,t){let n=e[t];return Array.isArray(n)?n.filter(i=>typeof i=="string"):void 0}function ge(e,t){let n=e[t];return Array.isArray(n)?n:void 0}function Fc(e){return S(e,"data")??e}function Oc(e){let t=Array.isArray(e)?e:typeof e=="string"?[e]:[];return[...new Set(t.flatMap(n=>n.split(",")).map(n=>n.trim()).filter(Boolean))]}function F(e,t,n){let i=p(n);i&&e.set(t,i)}function oe(e){let t=e.toString();return t?`?${t}`:""}function ie(e){return e.replace(/\/+$/u,"")}function ke(e){if(ie(e)===fn)return"cloud";try{let t=new URL(e);return t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="::1"||t.hostname==="[::1]"?"local":"custom"}catch{return"custom"}}function Hr(e){return e.includes("/")||e.startsWith(".")||/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e)}function J(e,t){return Qi(e,t)}function wt(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var qc={github:"GitHub",gitlab:"GitLab",google:"Google",microsoft:"Microsoft"};function Kc(e){return qc[e.toLowerCase()]??wt(e)}function ae(e){return e instanceof Error?e.message:String(e)}export{Nu as executePublicCli};
|