skills-layer 0.1.7 → 0.1.8
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/.github/dependabot.yml +7 -0
- package/.github/workflows/ci.yml +22 -0
- package/.github/workflows/publish.yml +24 -0
- package/CODE_OF_CONDUCT.md +18 -0
- package/CONTRIBUTING.md +24 -0
- package/SECURITY.md +18 -0
- package/package.json +6 -1
- package/public/skills-layer-public.mjs +87 -82
- package/tests/public-cli-package.test.mjs +96 -1
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/* istanbul ignore file -- generated npm bundle is verified by boundary and tarball smoke tests. */
|
|
2
2
|
import { createRequire as __skillsLayerCreateRequire } from "node:module"; const require = __skillsLayerCreateRequire(import.meta.url);
|
|
3
|
-
import{spawn as Ir}from"node:child_process";import{createHash as $n}from"node:crypto";import{access as jr,appendFile as Wo,chmod as Er,mkdir as nt,readdir as Lr,readFile as it,rm as An,stat as Jo,writeFile as In}from"node:fs/promises";import{basename as V,dirname as ne,join as E,posix as jn,relative as Xe,resolve as Ur,win32 as Ue}from"node:path";import{createInterface as En}from"node:readline/promises";import{spawn as ai}from"node:child_process";import{createHash as Bs}from"node:crypto";import{chmod as Ms,mkdir as at,readFile as li,rm as Mt,writeFile as _e}from"node:fs/promises";import{dirname as qe,posix as qs,win32 as Os}from"node:path";import{posix as Us,win32 as Ts}from"node:path";var ve=["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"],ei=[I("codex","Codex",".codex",{capabilities:F({allowedTools:!0})}),I("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:F({allowedTools:!0,hooks:!0,forkedContext:!0})}),I("cursor","Cursor",".cursor",{capabilities:F({allowedTools:!0})}),I("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:F({allowedTools:!0})}),pe("amp","Amp",".config/agents",{capabilities:F({allowedTools:!0})}),pe("kimi-cli","Kimi Code CLI",".config/agents"),pe("replit","Replit",".config/agents"),pe("universal","Universal",".config/agents"),pe("antigravity","Antigravity",".gemini/antigravity",{capabilities:F({allowedTools:!0}),detectGlobal:!0}),I("augment","Augment",".augment"),{id:"openclaw",displayName:"OpenClaw",envVar:"OPENCLAW_HOME",capabilities:F({allowedTools:!0}),targets:{projectRootRelativePath:null,projectSkillsRelativePath:"skills",globalRootRelativePath:".openclaw",globalSkillsRelativePath:".openclaw/skills"},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:[".openclaw",".openclaw/skills"]}},pe("cline","Cline",".agents",{capabilities:F({allowedTools:!0,hooks:!0})}),pe("warp","Warp",".agents"),I("codebuddy","CodeBuddy",".codebuddy",{capabilities:F({allowedTools:!0})}),I("command-code","Command Code",".commandcode",{capabilities:F({allowedTools:!0})}),I("continue","Continue",".continue"),I("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),I("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),pe("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),I("droid","Droid",".factory"),pe("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),pe("github-copilot","GitHub Copilot",".copilot",{capabilities:F({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:F({allowedTools:!0})}),I("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:F({allowedTools:!0})}),I("qoder","Qoder",".qoder",{capabilities:F({allowedTools:!0})}),I("qwen-code","Qwen Code",".qwen"),I("roo","Roo Code",".roo",{capabilities:F({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:F({allowedTools:!0})}),I("neovate","Neovate",".neovate",{capabilities:F({allowedTools:!0})}),I("pochi","Pochi",".pochi"),I("adal","AdaL",".adal")];function ke(e=process.env,t=process.platform,n=process.cwd()){let i=ii(t),r=ni(e,t);return ei.map(s=>{let o=st(e[s.envVar]),a=r&&s.targets.globalRootRelativePath?Fe(i,r,s.targets.globalRootRelativePath):null,c=r&&s.targets.globalSkillsRelativePath?Fe(i,r,s.targets.globalSkillsRelativePath):null,u=s.targets.projectRootRelativePath?Fe(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:Fe(i,n,s.targets.projectSkillsRelativePath),globalRoot:d,globalSkillsPath:o?i.join(o,"skills"):c}}})}async function ti(e={}){let t=e.env??process.env,n=e.platform??process.platform,i=e.cwd??process.cwd(),r=ii(n),s=ni(t,n),o=ke(t,n,i),a=e.pathExists??(async()=>!1);return(await Promise.all(o.map(async c=>{let u=Fs(c.id),d=[],g=st(t[c.envVar]);return(g&&await a(g)||g&&await a(r.join(g,"skills")))&&d.push("override"),u.detection.projectProbeRelativePaths.length>0&&await Xn({basePath:i,relativePaths:u.detection.projectProbeRelativePaths,pathApi:r,pathExists:a})&&d.push("project"),s&&u.detection.globalProbeRelativePaths.length>0&&await Xn({basePath:s,relativePaths:u.detection.globalProbeRelativePaths,pathApi:r,pathExists:a})&&d.push("global"),d.length===0?null:{...c,detectionSources:Ns(d)}}))).flatMap(c=>c?[c]:[])}function ni(e,t){return t==="win32"?st(e.USERPROFILE,e.HOME):st(e.HOME)}function ii(e){return e==="win32"?Ts:Us}function st(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Ns(e){return[...new Set(e)]}async function Xn(e){for(let t of e.relativePaths)if(await e.pathExists(Fe(e.pathApi,e.basePath,t)))return!0;return!1}function Fe(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??ri(e),capabilities:i.capabilities??F(),targets:{projectRootRelativePath:n,projectSkillsRelativePath:`${n}/skills`,globalRootRelativePath:r,globalSkillsRelativePath:`${r}/skills`},detection:{projectProbeRelativePaths:s?[n,`${n}/skills`]:[],globalProbeRelativePaths:[r,`${r}/skills`]}}}function pe(e,t,n,i={}){let r=i.detectGlobal??!1;return{id:e,displayName:t,envVar:i.envVar??ri(e),capabilities:i.capabilities??F(),targets:{projectRootRelativePath:".agents",projectSkillsRelativePath:".agents/skills",globalRootRelativePath:n,globalSkillsRelativePath:`${n}/skills`},detection:{projectProbeRelativePaths:[],globalProbeRelativePaths:r?[n,`${n}/skills`]:[]}}}function F(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 ri(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function Fs(e){return ei.find(t=>t.id===e)}var be="skills-layer",Ks="2025-06-18",Ds=["mcp","skills-layer-mcp-proxy.mjs"],Gs=["mcp","skills-layer-mcp-broker.mjs"],Vs=["mcp","skills-layer-mcp-broker.sock"],Hs={codex:{tier:"tier_1",configKind:"codex_toml",resolveConfigPath(e,t,n){let i=qt(n);return i.join(e.targets.globalRoot??i.join(ro({},n)??t,".codex"),"config.toml")}},cursor:Be(".cursor/mcp.json"),"claude-code":Be(".mcp.json"),cline:Be(".cline/mcp.json"),"gemini-cli":Be(".gemini/settings.json"),windsurf:Be(".windsurf/mcp.json")},zs=new Set(["universal"]);function Ke(e){let t=ke(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??io(e.env,i),o=e.mcpConfigPath??Me(i,s,"mcp.json"),a=Me(i,s,...Ds),c=Me(i,s,...Gs),u=Me(i,s,...Vs),d=e.nodePath??process.execPath,g=ci({mcpConfigPath:o}),f=ui({mcpConfigPath:o,socketPath:u}),m=xe(g),y=xe(f),v=ve.map(C=>{let _=n.get(C),L=Hs[C];if(L){let de=L.resolveConfigPath(_,r,i);return Ws({agentId:C,displayName:_.displayName,configPath:de,configKind:L.configKind,bridgePath:a,brokerPath:c,brokerSocketPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:m,brokerChecksum:y})}return zs.has(C)?oi({agentId:C,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 ${C}\`.`,"MCP auto-install is not claimed for this agent yet."]}):oi({agentId:C,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 ${be}.`,`Command: ${d}`,`Args: ${a}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{status:"mcp_registration_plan",serverName:be,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:y,automaticCount:v.filter(C=>C.status==="automatic").length,manualCount:v.filter(C=>C.status==="manual_handoff").length,skillsOnlyCount:v.filter(C=>C.status==="skills_only").length,unsupportedCount:v.filter(C=>C.status==="unsupported").length,targets:v}}async function De(e){let t=Ke(e),n=so(e.clientId),i=t.targets.find(v=>v.agentId===n),r=e.mcpConfig??await lt(t.mcpConfigPath,{allowMissing:!0});if(!r)return si({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 Oe(t.bridgePath),o=s!==null,a=s!==null&&xe(s)===t.bridgeChecksum,c=await Oe(t.brokerPath),u=c!==null,d=c!==null&&xe(c)===t.brokerChecksum,g=oo(r,i.agentId),f=oe(g,"token"),m=oe(g,"tokenRef"),y=i.status==="automatic"?await Xs(i,f):{configured:!1,rawTokenLeaked:!1};return si({plan:t,target:i,mcpConfig:r,tokenConfig:g,tokenPresent:!!f,tokenRefPresent:!!m,bridgeExists:o,checksumMatches:a,brokerExists:u,brokerChecksumMatches:d,targetConfigured:y.configured,rawTokenLeaked:y.rawTokenLeaked})}function ci(e){return`#!/usr/bin/env node
|
|
3
|
+
import{spawn as ks}from"node:child_process";import{createHash as ni}from"node:crypto";import{access as ws,appendFile as hl,chmod as vs,mkdir as ft,readdir as ii,readFile as He,rm as ri,stat as yl,writeFile as si}from"node:fs/promises";import{basename as D,dirname as ae,join as U,posix as oi,relative as Ke,resolve as ai,win32 as ze}from"node:path";import{createInterface as li}from"node:readline/promises";import{spawn as Mi}from"node:child_process";import{createHash as Io}from"node:crypto";import{chmod as jo,mkdir as vt,readFile as Bi,rm as rn,writeFile as Te}from"node:fs/promises";import{dirname as Qe,posix as Lo,win32 as Uo}from"node:path";import{posix as Ro,win32 as $o}from"node:path";var Re=["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"],Ii=[E("codex","Codex",".codex",{capabilities:B({allowedTools:!0})}),E("claude-code","Claude Code",".claude",{envVar:"CLAUDE_CODE_HOME",capabilities:B({allowedTools:!0,hooks:!0,forkedContext:!0})}),E("cursor","Cursor",".cursor",{capabilities:B({allowedTools:!0})}),E("opencode","OpenCode",".opencode",{globalRootRelativePath:".config/opencode",capabilities:B({allowedTools:!0})}),fe("amp","Amp",".config/agents",{capabilities:B({allowedTools:!0})}),fe("kimi-cli","Kimi Code CLI",".config/agents"),fe("replit","Replit",".config/agents"),fe("universal","Universal",".config/agents"),fe("antigravity","Antigravity",".gemini/antigravity",{capabilities:B({allowedTools:!0}),detectGlobal:!0}),E("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"]}},fe("cline","Cline",".agents",{capabilities:B({allowedTools:!0,hooks:!0})}),fe("warp","Warp",".agents"),E("codebuddy","CodeBuddy",".codebuddy",{capabilities:B({allowedTools:!0})}),E("command-code","Command Code",".commandcode",{capabilities:B({allowedTools:!0})}),E("continue","Continue",".continue"),E("cortex","Cortex Code",".cortex",{globalRootRelativePath:".snowflake/cortex"}),E("crush","Crush",".crush",{globalRootRelativePath:".config/crush"}),fe("deepagents","Deep Agents",".deepagents/agent",{detectGlobal:!0}),E("droid","Droid",".factory"),fe("gemini-cli","Gemini CLI",".gemini",{detectGlobal:!0}),fe("github-copilot","GitHub Copilot",".copilot",{capabilities:B({allowedTools:!0}),detectGlobal:!0}),E("goose","Goose",".goose",{globalRootRelativePath:".config/goose"}),E("junie","Junie",".junie"),E("iflow-cli","iFlow CLI",".iflow"),E("kilo","Kilo Code",".kilocode"),E("kiro-cli","Kiro CLI",".kiro"),E("kode","Kode",".kode"),E("mcpjam","MCPJam",".mcpjam"),E("mistral-vibe","Mistral Vibe",".vibe"),E("mux","Mux",".mux"),E("openhands","OpenHands",".openhands",{capabilities:B({allowedTools:!0})}),E("pi","Pi",".pi",{globalRootRelativePath:".pi/agent",capabilities:B({allowedTools:!0})}),E("qoder","Qoder",".qoder",{capabilities:B({allowedTools:!0})}),E("qwen-code","Qwen Code",".qwen"),E("roo","Roo Code",".roo",{capabilities:B({allowedTools:!0})}),E("trae","Trae",".trae",{detectProject:!1}),E("trae-cn","Trae CN",".trae",{globalRootRelativePath:".trae-cn",detectProject:!1}),E("windsurf","Windsurf",".windsurf",{globalRootRelativePath:".codeium/windsurf"}),E("zencoder","Zencoder",".zencoder",{capabilities:B({allowedTools:!0})}),E("neovate","Neovate",".neovate",{capabilities:B({allowedTools:!0})}),E("pochi","Pochi",".pochi"),E("adal","AdaL",".adal")];function Pe(e=process.env,t=process.platform,n=process.cwd()){let i=Ui(t),r=Li(e,t);return Ii.map(s=>{let o=kt(e[s.envVar]),a=r&&s.targets.globalRootRelativePath?Je(i,r,s.targets.globalRootRelativePath):null,c=r&&s.targets.globalSkillsRelativePath?Je(i,r,s.targets.globalSkillsRelativePath):null,u=s.targets.projectRootRelativePath?Je(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:Je(i,n,s.targets.projectSkillsRelativePath),globalRoot:d,globalSkillsPath:o?i.join(o,"skills"):c}}})}async function ji(e={}){let t=e.env??process.env,n=e.platform??process.platform,i=e.cwd??process.cwd(),r=Ui(n),s=Li(t,n),o=Pe(t,n,i),a=e.pathExists??(async()=>!1);return(await Promise.all(o.map(async c=>{let u=Eo(c.id),d=[],g=kt(t[c.envVar]);return(g&&await a(g)||g&&await a(r.join(g,"skills")))&&d.push("override"),u.detection.projectProbeRelativePaths.length>0&&await Ei({basePath:i,relativePaths:u.detection.projectProbeRelativePaths,pathApi:r,pathExists:a})&&d.push("project"),s&&u.detection.globalProbeRelativePaths.length>0&&await Ei({basePath:s,relativePaths:u.detection.globalProbeRelativePaths,pathApi:r,pathExists:a})&&d.push("global"),d.length===0?null:{...c,detectionSources:Ao(d)}}))).flatMap(c=>c?[c]:[])}function Li(e,t){return t==="win32"?kt(e.USERPROFILE,e.HOME):kt(e.HOME)}function Ui(e){return e==="win32"?$o:Ro}function kt(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function Ao(e){return[...new Set(e)]}async function Ei(e){for(let t of e.relativePaths)if(await e.pathExists(Je(e.pathApi,e.basePath,t)))return!0;return!1}function Je(e,t,n){return e.join(t,...n.split("/"))}function E(e,t,n,i={}){let r=i.globalRootRelativePath??n,s=i.detectProject??!0;return{id:e,displayName:t,envVar:i.envVar??Ti(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 fe(e,t,n,i={}){let r=i.detectGlobal??!1;return{id:e,displayName:t,envVar:i.envVar??Ti(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 Ti(e){return`${e.replaceAll("-","_").toUpperCase()}_HOME`}function Eo(e){return Ii.find(t=>t.id===e)}var $e="skills-layer",To="2025-06-18",Fo=["mcp","skills-layer-mcp-proxy.mjs"],No=["mcp","skills-layer-mcp-broker.mjs"],Mo=["mcp","skills-layer-mcp-broker.sock"],Bo={codex:{tier:"tier_1",configKind:"codex_toml",resolveConfigPath(e,t,n){let i=sn(n);return i.join(e.targets.globalRoot??i.join(Zo({},n)??t,".codex"),"config.toml")}},cursor:Ye(".cursor/mcp.json"),"claude-code":Ye(".mcp.json"),cline:Ye(".cline/mcp.json"),"gemini-cli":Ye(".gemini/settings.json"),windsurf:Ye(".windsurf/mcp.json")},Oo=new Set(["universal"]);function et(e){let t=Pe(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??Yo(e.env,i),o=e.mcpConfigPath??Ze(i,s,"mcp.json"),a=Ze(i,s,...Fo),c=Ze(i,s,...No),u=Ze(i,s,...Mo),d=e.nodePath??process.execPath,g=Oi({mcpConfigPath:o}),f=qi({mcpConfigPath:o,socketPath:u}),m=Fe(g),y=Fe(f),v=Re.map(P=>{let R=n.get(P),L=Bo[P];if(L){let K=L.resolveConfigPath(R,r,i);return qo({agentId:P,displayName:R.displayName,configPath:K,configKind:L.configKind,bridgePath:a,brokerPath:c,brokerSocketPath:u,mcpConfigPath:o,nodePath:d,bridgeChecksum:m,brokerChecksum:y})}return Oo.has(P)?Ni({agentId:P,displayName:R.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 ${R.displayName} with \`skills-layer install <skill> --agent ${P}\`.`,"MCP auto-install is not claimed for this agent yet."]}):Ni({agentId:P,displayName:R.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 ${$e}.`,`Command: ${d}`,`Args: ${a}`,"Restart or reload the agent if it does not reconnect automatically."]})});return{status:"mcp_registration_plan",serverName:$e,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:y,automaticCount:v.filter(P=>P.status==="automatic").length,manualCount:v.filter(P=>P.status==="manual_handoff").length,skillsOnlyCount:v.filter(P=>P.status==="skills_only").length,unsupportedCount:v.filter(P=>P.status==="unsupported").length,targets:v}}async function tt(e){let t=et(e),n=Qo(e.clientId),i=t.targets.find(v=>v.agentId===n),r=e.mcpConfig??await bt(t.mcpConfigPath,{allowMissing:!0});if(!r)return Fi({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 Xe(t.bridgePath),o=s!==null,a=s!==null&&Fe(s)===t.bridgeChecksum,c=await Xe(t.brokerPath),u=c!==null,d=c!==null&&Fe(c)===t.brokerChecksum,g=Xo(r,i.agentId),f=de(g,"token"),m=de(g,"tokenRef"),y=i.status==="automatic"?await Ho(i,f):{configured:!1,rawTokenLeaked:!1};return Fi({plan:t,target:i,mcpConfig:r,tokenConfig:g,tokenPresent:!!f,tokenRefPresent:!!m,bridgeExists:o,checksumMatches:a,brokerExists:u,brokerChecksumMatches:d,targetConfigured:y.configured,rawTokenLeaked:y.rawTokenLeaked})}function Oi(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(To)};
|
|
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 qi(e){return`#!/usr/bin/env node
|
|
152
152
|
import { execFile } from "node:child_process";
|
|
153
153
|
import { createServer } from "node:net";
|
|
154
154
|
import { chmod, readFile, rm } from "node:fs/promises";
|
|
@@ -244,15 +244,15 @@ server.listen(SOCKET_PATH, async () => {
|
|
|
244
244
|
// Some platforms do not support chmod on sockets.
|
|
245
245
|
}
|
|
246
246
|
});
|
|
247
|
-
`}async function
|
|
248
|
-
`);let c=await Promise.race([s,a]);if(clearTimeout(o),i.kill(),c==="timeout")return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!1,toolCount:null,reasonCode:"probe_timeout",message:"MCP bridge did not respond before the verification timeout."};if(!c.ok)return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!1,toolCount:null,reasonCode:"probe_failed",message:r.trim()?"MCP bridge failed before returning a response.":c.message};try{let u=JSON.parse(c.line);if(
|
|
249
|
-
`,"utf8")}async function
|
|
250
|
-
`,"utf8")}async function
|
|
251
|
-
`),i=`${
|
|
252
|
-
|
|
253
|
-
`:""}${n}`;await
|
|
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 io(e,t){let n=qt(t),i=e??process.env,r=t==="win32"?ot(i.APPDATA,i.USERPROFILE,i.HOME):ot(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 ro(e,t){return t==="win32"?ot(e.USERPROFILE,e.HOME):ot(e.HOME)}function so(e){return ve.includes(e)?e:"codex"}function oo(e,t){let n=e.tokens;return X(n)&&X(n[t])?n[t]:e}function ao(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(X(n))return Object.keys(n);let i=oe(e,"clientId");return i?[i]:[]}function Me(e,...t){return qt(e).join(...t)}function qt(e){return e==="win32"?Os:qs}function ot(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function oe(e,t){let n=e?.[t];return typeof n=="string"&&n.trim().length>0?n:null}function xe(e){return Bs("sha256").update(e).digest("hex")}function X(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lo(e){let t=co(e);if(t)return t;let n=uo(e);if(n)return n;throw new Error("Unsupported bundle archive format")}function fi(e){try{return lo(e)}catch{return null}}function co(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 uo(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 po}from"node:crypto";function hi(e){let t=po("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 Ot=["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"],go="productivity",mo=new Set(Ot),fo={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"},ho={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 yi(e){if(typeof e!="string")return null;let t=vi(e);return mo.has(t)?t:fo[t]??null}function ki(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 wi(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=ko(s.value);for(let[a,c]of Object.entries(ho)){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||Ot.indexOf(s[0])-Ot.indexOf(o[0]))[0];return!r||r[1].score<2?{category:yo(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 yo(e){let t=vi(e.skillType??"");return t.includes("automation")?"automation":t.includes("mcp")?"ai":go}function vi(e){return e.trim().toLowerCase().replace(/[_\s]+/gu,"-")}function ko(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/u).map(t=>t.trim()).filter(t=>t.length>=2).flatMap(wo))}function wo(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 vo=["standalone","workflow_automation","mcp_enhanced"];function bi(e){let t=e?.trim();if(!t)return"standalone";if(t==="workflow")return"workflow_automation";if(!vo.includes(t))throw new Error(`Unsupported skill type "${t}". Supported types: standalone, workflow, workflow_automation, mcp_enhanced.`);return t}function Si(e){return[{path:"SKILL.md",content:bo(e)},{path:"README.md",content:So(e)},{path:"references/guide.md",content:Co(e)},{path:"scripts/README.md",content:Po(e)}]}function bo(e){let t=_o(e);return`---
|
|
247
|
+
`}async function Di(e){let t=e.requestId??1,n=e.timeoutMs??5e3,i=Mi(e.nodePath,[e.bridgePath],{stdio:["pipe","pipe","pipe"]}),r="",s=Jo(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(se(u)&&se(u.error))return{status:"error",method:"tools/list",bridgePath:e.bridgePath,nodePath:e.nodePath,responseReceived:!0,toolCount:null,reasonCode:"remote_mcp_error",message:de(u.error,"message")??"Skills Layer MCP returned an error."};let d=se(u)&&se(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 Fi(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:de(e.tokenConfig,"environment")??de(e.mcpConfig,"environment")??e.plan.environment,baseUrl:de(e.mcpConfig,"baseUrl"),mcpUrl:de(e.mcpConfig,"mcpUrl"),tokenPrefix:de(e.tokenConfig,"tokenPrefix")??de(e.mcpConfig,"tokenPrefix"),scopes:Array.isArray(e.tokenConfig?.scopes)?e.tokenConfig.scopes:Array.isArray(e.mcpConfig?.scopes)?e.mcpConfig.scopes:[],configuredClients:ea(e.mcpConfig),tokenPresent:e.tokenPresent||e.tokenRefPresent,tokenStorage:de(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 qo(e){return{agentId:e.agentId,displayName:e.displayName,tier:"tier_1",status:"automatic",serverName:$e,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 Do({bridgePath:e.bridgePath,brokerPath:e.brokerPath,brokerSocketPath:e.brokerSocketPath,mcpConfigPath:e.mcpConfigPath,nodePath:e.nodePath});return await Vo({configPath:e.configPath,configKind:e.configKind,bridgePath:e.bridgePath,nodePath:e.nodePath,agentId:e.agentId}),t},disconnect:async()=>{await Go({configPath:e.configPath,configKind:e.configKind})}}}function Ni(e){return{agentId:e.agentId,displayName:e.displayName,tier:e.tier,status:e.status,serverName:$e,configPath:null,restartRequired:!0,verification:e.verification,transport:"manual",bridgePath:null,nodePath:null,configKind:null,reason:e.reason,instructions:e.instructions}}async function Do(e){let t=Oi({mcpConfigPath:e.mcpConfigPath}),n=qi({mcpConfigPath:e.mcpConfigPath,socketPath:e.brokerSocketPath});return await vt(Qe(e.bridgePath),{recursive:!0}),await Te(e.bridgePath,t,"utf8"),await Te(e.brokerPath,n,"utf8"),await nn(Qe(e.bridgePath),448),await nn(e.bridgePath,448),await nn(e.brokerPath,448),Ko({nodePath:e.nodePath,brokerPath:e.brokerPath}),{bridgePath:e.bridgePath,brokerPath:e.brokerPath,brokerSocketPath:e.brokerSocketPath,mcpConfigPath:e.mcpConfigPath,checksum:Fe(t),brokerChecksum:Fe(n),nodePath:e.nodePath}}function Ko(e){if(!(process.env.VITEST==="true"||process.env.SKILLS_LAYER_MCP_BROKER_AUTOSTART==="disabled"))try{Mi(e.nodePath,[e.brokerPath],{detached:!0,stdio:"ignore"}).unref()}catch{}}async function Vo(e){if(e.configKind==="codex_toml"){await Wo(e);return}await zo(e)}async function Go(e){if(e.configKind==="codex_toml"){let i=await Xe(e.configPath);if(i===null)return;await Te(e.configPath,Ki(i),"utf8");return}let t=await bt(e.configPath,{allowMissing:!0});if(!t||!se(t.mcpServers))return;let n={...t.mcpServers};delete n[$e],await vt(Qe(e.configPath),{recursive:!0}),await Te(e.configPath,`${JSON.stringify({...t,mcpServers:n},null,2)}
|
|
249
|
+
`,"utf8")}async function Ho(e,t){if(!e.configPath||!e.configKind||!e.bridgePath||!e.nodePath)return{configured:!1,rawTokenLeaked:!1};if(e.configKind==="codex_toml"){let s=await Xe(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 bt(e.configPath,{allowMissing:!0}),i=se(n?.mcpServers)?n.mcpServers[$e]:void 0;return{configured:se(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 zo(e){let t=await bt(e.configPath,{allowMissing:!0})??{},n=se(t.mcpServers)?{...t.mcpServers}:{};n[$e]={command:e.nodePath,args:[e.bridgePath,"--client",e.agentId]},await vt(Qe(e.configPath),{recursive:!0}),await Te(e.configPath,`${JSON.stringify({...t,mcpServers:n},null,2)}
|
|
250
|
+
`,"utf8")}async function Wo(e){let t=await Xe(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=`${Ki(t).trimEnd()}${t.trim().length>0?`
|
|
252
|
+
|
|
253
|
+
`:""}${n}`;await vt(Qe(e.configPath),{recursive:!0}),await Te(e.configPath,i,"utf8")}function Ki(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 Ye(e){return{tier:"tier_1",configKind:"json_mcp_servers",resolveConfigPath(t,n,i){return Ze(i,n,...e.split("/"))}}}async function bt(e,t){try{let n=JSON.parse(await Bi(e,"utf8"));return se(n)?n:{}}catch(n){if(t.allowMissing&&n.code==="ENOENT")return null;throw n}}async function Xe(e){try{return await Bi(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function nn(e,t){try{await jo(e,t)}catch{}}async function Vi(e){await rn(e,{force:!0})}async function Gi(e,t){await Promise.all([rn(e,{force:!0}),rn(t,{force:!0})])}function Jo(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 Yo(e,t){let n=sn(t),i=e??process.env,r=t==="win32"?wt(i.APPDATA,i.USERPROFILE,i.HOME):wt(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 Zo(e,t){return t==="win32"?wt(e.USERPROFILE,e.HOME):wt(e.HOME)}function Qo(e){return Re.includes(e)?e:"codex"}function Xo(e,t){let n=e.tokens;return se(n)&&se(n[t])?n[t]:e}function ea(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(se(n))return Object.keys(n);let i=de(e,"clientId");return i?[i]:[]}function Ze(e,...t){return sn(e).join(...t)}function sn(e){return e==="win32"?Uo:Lo}function wt(...e){return e.find(t=>typeof t=="string"&&t.trim().length>0)?.trim()}function de(e,t){let n=e?.[t];return typeof n=="string"&&n.trim().length>0?n:null}function Fe(e){return Io("sha256").update(e).digest("hex")}function se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ta(e){let t=na(e);if(t)return t;let n=ia(e);if(n)return n;throw new Error("Unsupported bundle archive format")}function Hi(e){try{return ta(e)}catch{return null}}function na(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 ia(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 ra}from"node:crypto";function zi(e){let t=ra("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 on=["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"],sa="productivity",oa=new Set(on),aa={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"},la={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 Wi(e){if(typeof e!="string")return null;let t=Zi(e);return oa.has(t)?t:aa[t]??null}function Ji(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 Yi(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=ua(s.value);for(let[a,c]of Object.entries(la)){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||on.indexOf(s[0])-on.indexOf(o[0]))[0];return!r||r[1].score<2?{category:ca(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 ca(e){let t=Zi(e.skillType??"");return t.includes("automation")?"automation":t.includes("mcp")?"ai":sa}function Zi(e){return e.trim().toLowerCase().replace(/[_\s]+/gu,"-")}function ua(e){return new Set(e.toLowerCase().split(/[^a-z0-9]+/u).map(t=>t.trim()).filter(t=>t.length>=2).flatMap(da))}function da(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}import{createHash as pa}from"node:crypto";var ga=new Set(["evals","tests","test","fixtures","examples","golden","goldens","snapshots","__snapshots__",".github",".circleci","coverage"]),ma=new Set([".gitlab-ci.yml","azure-pipelines.yml"]),fa=[".eval.json",".eval.yaml"],ha=[".golden.",".snapshot."];function Ae(e,t){let n=cn(e),i=Qi(t),r=an(n,i),[s]=r.split("/");return s&&ga.has(s)?{path:n,relativePath:r,root:i,type:"evidence",reasonCode:"top_level_evidence_folder"}:ya(r)?{path:n,relativePath:r,root:i,type:"evidence",reasonCode:"top_level_evidence_file"}:{path:n,relativePath:r,root:i,type:"runtime",reasonCode:"runtime_material"}}function ln(e){let t=Qi(e);return e.map(n=>({...n,path:cn(n.path)})).filter(n=>Ae(n.path,e).type==="runtime").sort((n,i)=>ka(n.path,i.path,t))}function he(e){let t=pa("sha256");for(let n of ln(e))t.update(n.path),t.update("\0"),t.update(n.content??""),t.update("\0");return`sha256:${t.digest("hex")}`}function ya(e){return e.includes("/")?!1:ma.has(e)||fa.some(t=>e.endsWith(t))||ha.some(t=>e.includes(t))}function Qi(e){let t=e.map(n=>cn(n.path)).find(n=>n==="SKILL.md"||n.endsWith("/SKILL.md"));return!t||t==="SKILL.md"?"":t.slice(0,-9)}function an(e,t){return t?e===t?"":e.startsWith(`${t}/`)?e.slice(t.length+1):e:e}function ka(e,t,n){let i=an(e,n),r=an(t,n);return i==="SKILL.md"?r==="SKILL.md"?0:-1:r==="SKILL.md"?1:e.localeCompare(t)}function cn(e){return e.replaceAll("\\","/").split("/").filter(t=>t.length>0&&t!==".").join("/")}var wa=["standalone","workflow_automation","mcp_enhanced"];function Xi(e){let t=e?.trim();if(!t)return"standalone";if(t==="workflow")return"workflow_automation";if(!wa.includes(t))throw new Error(`Unsupported skill type "${t}". Supported types: standalone, workflow, workflow_automation, mcp_enhanced.`);return t}function er(e){let t=[{path:"SKILL.md",content:va(e)},{path:"README.md",content:ba(e)},{path:"references/guide.md",content:Pa(e)},{path:"scripts/README.md",content:Sa(e)}],n=he(t);return[...t,{path:"evals/skills-layer.eval.json",content:Ca(e,n)}]}function va(e){let t=_a(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
|
+
# ${un(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 ba(e){return`# ${un(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 Sa(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 Pa(e){return`# ${un(e.skillSlug)} Guide
|
|
312
312
|
|
|
313
313
|
## Intent
|
|
314
314
|
|
|
@@ -320,15 +320,16 @@ 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:${Bo("sha256").update(t).digest("base64url").slice(0,32)}`}function Ht(e){return e.store!==void 0?e.store:Vt(e.platform,e.env??process.env)}function zt(e){return e.service??Ve}function Oo(e){let t={...e,credentialStorage:"local_file_locked"};return delete t[Re],t}function Ko(){return{kind:"macos_keychain",async set(e,t,n){await Gt("/usr/bin/security",["add-generic-password","-a",t,"-s",e,"-w",n,"-U"])},async get(e,t){try{let{stdout:n}=await Gt("/usr/bin/security",["find-generic-password","-a",t,"-s",e,"-w"]);return n.trim()||null}catch{return null}},async delete(e,t){try{await Gt("/usr/bin/security",["delete-generic-password","-a",t,"-s",e])}catch{}}}}function Wt(e){let t=e.skillSlug??"<skill-slug>";return{localWork:{purpose:e.purpose,command:e.command,jsonCommand:e.jsonCommand},guardian:{checkCommand:`skills-layer guardian check --skill ${t} --json`,execCommand:`skills-layer guardian exec ${t} --json -- <command>`,mcpTools:["guardian.check","guardian.enforce","guardian.status","guardian.incident"],guidance:"Before risky shell, network, file, secret, browser, API, generated-code, or model-context actions, call MCP guardian.check/guardian.enforce or run skills-layer guardian check. Route shell actions through skills-layer guardian exec when strict local blocking is needed."},setup:{setupCommand:"skills-layer setup",hookStatusCommand:"skills-layer guardian hook status",hookInstallProjectCommand:"skills-layer guardian hook install --agent codex --scope project",hookInstallGlobalCommand:"skills-layer guardian hook install --agent codex --scope global"}}}var Ii=` ____ _ _ _ _ _
|
|
323
|
+
`}function Ca(e,t){return`${JSON.stringify({schemaVersion:"skills-layer.eval.pack.v1",artifactDigest:t,origin:"inferred",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[{id:"starter-trigger-fit",title:"Skill has a clear trigger and usage path",assertions:[{type:"section_exists",target:"Examples"},{type:"section_exists",target:"Troubleshooting"},{type:"max_duration_ms",value:3e4}]}],notes:[`Review and expand this starter eval pack before submitting ${e.skillSlug}.`,"Keep prompts, fixtures, and expected private outputs out of cloud summaries."]},null,2)}
|
|
324
|
+
`}function un(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function _a(e){let t=Wi(e.category);return t||Yi({name:e.skillSlug,slug:e.skillSlug,description:e.description,skillType:e.skillType}).category}function nr(e,t){switch(e.type){case"file_exists":return dn(t.files,Ee(e.path))?_e("file_exists"):J("file_missing");case"json_valid":return xa(e,t);case"section_exists":return Ra(e,t);case"regex_match":return $a(e,t);case"schema_match":return Aa(e,t);case"artifact_valid":return he(t.files)===Ee(e.artifactDigest)?_e("artifact_digest_matched"):J("artifact_digest_mismatch");case"max_duration_ms":return typeof t.durationMs=="number"&&t.durationMs<=tr(e.value)?_e("duration_within_limit"):J("duration_exceeded");case"command_exit":return typeof t.commandExitCode=="number"&&t.commandExitCode===tr(e.value)?_e("command_exit_matched"):J("command_exit_mismatch");default:return ja("assertion_type_unsupported")}}function xa(e,t){let n=dn(t.files,Ee(e.path));if(!n)return J("file_missing");try{return JSON.parse(n.content??""),_e("json_valid")}catch{return J("json_invalid")}}function Ra(e,t){let n=Ee(e.target);if(!n)return J("section_target_missing");let i=new RegExp(`(^|\\n)#+\\s+${Ea(n)}(?=$|\\s)`,"iu");return t.files.some(r=>i.test(r.content??""))?_e("section_exists"):J("section_missing")}function $a(e,t){let n=Ee(e.pattern);if(!n)return J("regex_missing");let i;try{i=new RegExp(n,"u")}catch{return J("regex_invalid")}let r=Ee(e.path);return(r?t.files.filter(o=>St(o.path)===St(r)):t.files).some(o=>i.test(o.content??""))?_e("regex_matched"):J("regex_not_matched")}function Aa(e,t){let n=dn(t.files,Ee(e.path));if(!n)return J("file_missing");let i;try{i=JSON.parse(n.content??"")}catch{return J("json_invalid")}return Ia(i)?(Array.isArray(e.requiredKeys)?e.requiredKeys.map(String):[]).every(s=>Object.prototype.hasOwnProperty.call(i,s))?_e("schema_matched"):J("schema_required_key_missing"):J("schema_target_not_object")}function dn(e,t){if(!t)return;let n=St(t);return e.find(i=>St(i.path)===n)}function Ee(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function tr(e){return typeof e=="number"&&Number.isFinite(e)?e:Number.NaN}function St(e){return e.replaceAll("\\","/").replace(/^\.\//u,"")}function Ea(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function Ia(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _e(e){return{status:"passed",reasonCode:e}}function J(e){return{status:"failed",reasonCode:e}}function ja(e){return{status:"skipped",reasonCode:e}}import{createHash as La}from"node:crypto";var Ua=["submitted","inferred","submitted_plus_inferred"],Ta=["starter","reviewed","verified"],Fa=["file_exists","json_valid","schema_match","section_exists","regex_match","command_exit","artifact_valid","max_duration_ms"],Na=new Set(Ua),Ma=new Set(Ta),Ba=new Set(Fa);function ir(e){let t=[];return nt(e)?(e.schemaVersion!=="skills-layer.eval.pack.v1"&&t.push(ne("eval-pack-schema-invalid","$.schemaVersion","Eval pack schemaVersion is unsupported")),(typeof e.artifactDigest!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.artifactDigest))&&t.push(ne("eval-pack-artifact-digest-invalid","$.artifactDigest","Eval pack must target a sha256 artifact digest")),(typeof e.origin!="string"||!Na.has(e.origin))&&t.push(ne("eval-pack-origin-invalid","$.origin","Eval pack origin is not canonical")),(typeof e.confidence!="string"||!Ma.has(e.confidence))&&t.push(ne("eval-pack-confidence-invalid","$.confidence","Eval pack confidence is not canonical")),typeof e.creatorReviewed!="boolean"&&t.push(ne("eval-pack-review-invalid","$.creatorReviewed","Eval pack must state whether the creator reviewed it")),(!nt(e.redaction)||e.redaction.mode!=="content_free")&&t.push(ne("eval-pack-redaction-invalid","$.redaction.mode","Eval pack must use content_free redaction by default")),!Array.isArray(e.cases)||e.cases.length===0?t.push(ne("eval-pack-cases-invalid","$.cases","Eval pack must include at least one case")):Oa(e.cases,t),{valid:t.length===0,issues:t}):{valid:!1,issues:[ne("eval-pack-invalid","$","Eval pack must be an object")]}}function Pt(e){return`sha256:${La("sha256").update(qa(e)).digest("hex")}`}function Oa(e,t){let n=new Set;e.forEach((i,r)=>{let s=`$.cases[${r}]`;if(!nt(i)){t.push(ne("eval-pack-case-invalid",s,"Eval case must be an object"));return}if(typeof i.id!="string"||i.id.trim().length===0?t.push(ne("eval-pack-case-id-invalid",`${s}.id`,"Eval case id is required")):n.has(i.id)?t.push(ne("eval-pack-case-id-duplicate",`${s}.id`,"Eval case ids must be unique")):n.add(i.id),!Array.isArray(i.assertions)||i.assertions.length===0){t.push(ne("eval-pack-assertions-invalid",`${s}.assertions`,"Eval case must include assertions"));return}i.assertions.forEach((o,a)=>{let c=`${s}.assertions[${a}]`;(!nt(o)||typeof o.type!="string"||!Ba.has(o.type))&&t.push(ne("eval-pack-assertion-type-invalid",`${c}.type`,"Eval assertion type is not supported"))})})}function qa(e){return JSON.stringify(pn(e))}function pn(e){return Array.isArray(e)?e.map(pn).sort(Da):nt(e)?Object.fromEntries(Object.entries(e).filter(([t])=>t!=="evalPackDigest").sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,pn(n)])):e}function Da(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))}function nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ne(e,t,n){return{code:e,path:t,message:n}}function sr(e){let t=e.assertionsPassed+e.assertionsFailed,n={coverageRatio:rr(e.evaluatedCapabilities,e.declaredCapabilities),passRate:t===0?0:rr(e.assertionsPassed,t),freshnessFactor:Va(e),evidenceConfidence:Ka(e),baselineDelta:Ct(Math.max(0,e.baselineDelta??0)),telemetrySignal:Ct(e.aggregationThresholdMet?e.telemetrySignal??0:0)},i=gn(n.coverageRatio*.25+n.passRate*.25+n.freshnessFactor*.15+n.evidenceConfidence*.2+n.baselineDelta*.05+n.telemetrySignal*.1);return{components:n,overallScore:i,effectiveScorePercent:Ha(i*100),assertionsFailed:e.assertionsFailed,executedAssertions:t,aggregationThresholdMet:e.aggregationThresholdMet}}function or(e){return e.executedAssertions===0&&e.components.coverageRatio===0?"unknown":e.components.freshnessFactor===0?"stale":e.assertionsFailed>0&&e.components.passRate<.8?"failing":e.overallScore>=.8&&e.components.coverageRatio>=.8&&e.components.passRate>=.9&&e.components.evidenceConfidence>=.7?"strong":e.aggregationThresholdMet&&e.components.telemetrySignal>=.7?"telemetry-backed":"limited"}function Ka(e){let t=e.origin==="submitted"?.65:e.origin==="submitted_plus_inferred"?.55:.25,n=e.creatorReviewed?.15:0,i=Math.min(e.runCount*.03,.15),r=Math.min(new Set(e.runnerTypes).size*.04,.1),s=e.aggregationThresholdMet?.1:0;return gn(Ct(t+n+i+r+s))}function Va(e){if(e.freshnessPolicy==="never")return 1;if(!e.generatedAt||!e.now)return 0;let t=Date.parse(e.generatedAt),n=Date.parse(e.now);if(!Number.isFinite(t)||!Number.isFinite(n)||n<t)return 0;let i=Ga(e.freshnessPolicy);return n-t<=i?1:0}function Ga(e){return e==="3_months"?2160*60*60*1e3:e==="6_months"?4392*60*60*1e3:365*24*60*60*1e3}function rr(e,t){return t<=0?0:gn(Ct(e/t))}function Ct(e){return Math.max(0,Math.min(1,e))}function gn(e){return Math.round(e*1e4)/1e4}function Ha(e){return Math.round(e*10)/10}var mn=["passed","failed","not_run","generated_only","policy_skipped","runner_unavailable"],hg=new Set(mn);function _t(e){return{schemaVersion:"skills-layer.eval.summary.v1",status:e.status,skillSlug:e.skillSlug,version:e.version,artifactDigest:e.artifactDigest,...e.evalPackDigest?{evalPackDigest:e.evalPackDigest}:{},...e.runnerVersion?{runnerVersion:e.runnerVersion}:{},generatedAt:e.generatedAt,...e.counts?{counts:e.counts}:{},redaction:{mode:"content_free",rawContentIncluded:!1}}}function ar(e){let t=he(e),n=ln(e),i=e.map(c=>Ae(c.path,e)).filter(c=>c.type==="evidence"),r=za(e),s=r?"submitted":"inferred",o=sr({declaredCapabilities:4,evaluatedCapabilities:r?2:1,assertionsPassed:0,assertionsFailed:0,assertionsSkipped:0,origin:s,creatorReviewed:!1,runCount:0,runnerTypes:["dry"],aggregationThresholdMet:!1,freshnessPolicy:"never"}),a=or(o);return{schemaVersion:"skills-layer.eval.readiness.v1",status:a,label:a,artifactDigest:t,origin:s,confidence:"starter",creatorReviewed:!1,runtimeFileCount:n.length,evidenceFileCount:i.length,excludedEvidencePaths:i.map(c=>c.path),score:{overallScore:o.overallScore,effectiveScorePercent:o.effectiveScorePercent,components:o.components},summaryEnvelope:{requiredOnSubmit:!0,statuses:[...mn]},nextAction:"creator.submit",nextStep:"creator submit must attach a mandatory redacted eval summary envelope."}}function za(e){return e.map(t=>Ae(t.path,e)).some(t=>t.type==="evidence"&&(t.relativePath.startsWith("evals/")||t.relativePath.endsWith(".eval.json")||t.relativePath.endsWith(".eval.yaml")))}var Wa=/^github:([^/]+)\/([^/#]+)(?:\/([^#]+))?(?:#(.+))?$/,Ja=/^gitlab:([^/#]+(?:\/[^/#]+)*?)\/([^/#]+)(?:\/([^/#]+))?(?:#(.+))?$/,Ya=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/(.+?))?(?:#([^@]+))?$/,Za=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\/.+)?(?:#[^@]+)?$/,Qa=/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/,Xa=/^(?:ssh:\/\/)?git@github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/,el=/^(?:ssh:\/\/)?git@gitlab\.com[:/]([^/]+(?:\/[^/]+)*)\/([^/]+?)(?:\.git)?$/;function it(e){let t=e.trim();if(t.length===0)throw new Error("import requires a non-empty source.");let{sourceInput:n,skillFilter:i}=tl(t),r=n.match(Wa);if(r){let[,g,f,m,y]=r;return xt({input:t,owner:g,repo:f,ref:y?.trim()||"main",subpath:m,skillFilter:i})}let s=n.match(Ja);if(s){let[,g,f,m,y]=s;return fn({input:t,host:"gitlab.com",namespace:g,repo:f,ref:y?.trim()||"main",subpath:m,skillFilter:i})}let o=nl(t);if(o)return o;let a=il(t);if(a)return a;let c=n.match(Xa);if(c){let[,g,f]=c;return xt({input:t,owner:g,repo:ye(f),ref:"main",subpath:"SKILL.md"})}let u=n.match(el);if(u){let[,g,f]=u;return fn({input:t,host:"gitlab.com",namespace:g,repo:ye(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(Ya);if(d&&!Qa.test(n)){let[,g,f,m,y]=d;return xt({input:t,owner:g,repo:ye(f),ref:y?.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 Rt(e){let t=e?.trim();return t&&t.length>0?t:"SKILL.md"}function tl(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:")||Za.test(n)?{sourceInput:n,skillFilter:i}:{sourceInput:n,skillFilter:i}:{sourceInput:e}}function lr(e,t,n,i,r){return e==="gitlab"&&r&&r!=="gitlab.com"?`${e}://${r}/${t}@${n}/${i}`:`${e}://${t}@${n}/${i}`}function ye(e){return e.replace(/\.git$/u,"")}function nl(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=ye(n[1]),s="main",o="SKILL.md";(n[2]==="tree"||n[2]==="blob")&&(s=n[3]?.trim()||"main",o=Rt(n.slice(4).join("/")));let a=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),xt({input:e,owner:i,repo:r,ref:s,subpath:o,skillFilter:a})}function il(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=ye(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"?Rt(c.slice(1).join("/")):"SKILL.md",g=t.searchParams.get("skill")?.trim()||void 0;return t.searchParams.delete("skill"),fn({input:e,host:t.hostname,namespace:o,repo:s,ref:u,subpath:d,skillFilter:g})}function xt(e){let t=Rt(e.subpath);return{kind:"github",input:e.input,owner:e.owner,repo:ye(e.repo),ref:e.ref,subpath:t,repoUrl:`https://github.com/${e.owner}/${ye(e.repo)}`,rawUrl:`https://raw.githubusercontent.com/${e.owner}/${ye(e.repo)}/${e.ref}/${t}`,canonicalSource:lr("github",`${e.owner}/${ye(e.repo)}`,e.ref,t),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}function fn(e){let t=ye(e.repo),n=Rt(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:lr("gitlab",`${e.namespace}/${t}`,e.ref,n,e.host),...e.skillFilter?{skillFilter:e.skillFilter}:{}}}var rl="private",cr="public",ur="unlisted",dr="delisted";function $t(e){if(typeof e!="string"||e.trim().length===0)return null;let t=e.trim().toLowerCase();return t==="private"?rl:t===cr?cr:t===ur?ur:t===dr?dr:null}import{execFile as sl}from"node:child_process";import{createHash as ol}from"node:crypto";import{promisify as al}from"node:util";var hn=al(sl),rt="apiKey",Ne="apiKeyRef",st="Skills Layer CLI";function yn(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:ul()}async function pr(e,t){if(!(typeof e[rt]=="string"&&e[rt].length>0))return e;let i=kn(t);if(!i)return e;try{let r={...e,credentialStorage:"macos_keychain"},s=ll(e);return await i.set(wn(t),s,e[rt]),r[Ne]=s,delete r[rt],r}catch{return cl(e)}}async function gr(e,t){if(e.credentialStorage!=="macos_keychain"||e[rt]||!e[Ne])return e;let n=kn(t);if(!n)return e;let i=await n.get(wn(t),e[Ne]);return i?{...e,apiKey:i}:e}async function mr(e,t){if(!e||e.credentialStorage!=="macos_keychain"||!e[Ne])return;let n=kn(t);n&&await n.delete(wn(t),e[Ne])}function ll(e){let t=[e.baseUrl??"unknown-base-url",e.userId??e.email??e.role??"unknown-user","apiKey"].join(`
|
|
325
|
+
`);return`skills-layer-cli:api-key:${ol("sha256").update(t).digest("base64url").slice(0,32)}`}function kn(e){return e.store!==void 0?e.store:yn(e.platform,e.env??process.env)}function wn(e){return e.service??st}function cl(e){let t={...e,credentialStorage:"local_file_locked"};return delete t[Ne],t}function ul(){return{kind:"macos_keychain",async set(e,t,n){await hn("/usr/bin/security",["add-generic-password","-a",t,"-s",e,"-w",n,"-U"])},async get(e,t){try{let{stdout:n}=await hn("/usr/bin/security",["find-generic-password","-a",t,"-s",e,"-w"]);return n.trim()||null}catch{return null}},async delete(e,t){try{await hn("/usr/bin/security",["delete-generic-password","-a",t,"-s",e])}catch{}}}}function vn(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 fr=` ____ _ _ _ _ _
|
|
325
326
|
/ ___|| | _(_) | |___ | | __ _ _ _ ___ _ __
|
|
326
327
|
\\___ \\| |/ / | | / __| | | / _\` | | | |/ _ \\ '__|
|
|
327
328
|
___) | <| | | \\__ \\ | |__| (_| | |_| | __/ |
|
|
328
329
|
|____/|_|\\_\\_|_|_|___/ |_____\\__,_|\\__, |\\___|_|
|
|
329
330
|
|___/
|
|
330
331
|
Skills-Layer
|
|
331
|
-
AI Agent first platform for Skills`;var
|
|
332
|
+
AI Agent first platform for Skills`;var hr=`Skills Layer MCP
|
|
332
333
|
Configure Skills Layer for AI agents through a local stdio bridge.
|
|
333
334
|
|
|
334
335
|
Usage:
|
|
@@ -359,7 +360,7 @@ Checks:
|
|
|
359
360
|
repair rewrites the local bridge and supported target config.
|
|
360
361
|
disconnect removes Skills Layer MCP local state and the selected target config entry.
|
|
361
362
|
|
|
362
|
-
After setup or repair, open a fresh agent session or restart the agent if tools are not visible.`;var
|
|
363
|
+
After setup or repair, open a fresh agent session or restart the agent if tools are not visible.`;var wr=`Skills Layer CLI
|
|
363
364
|
Agent-first skill marketplace for developers. CLI, MCP, and API share one journey model.
|
|
364
365
|
|
|
365
366
|
Usage:
|
|
@@ -459,7 +460,7 @@ Primary commands:
|
|
|
459
460
|
skills-layer buy <skill-slug> [--payment-method <method>] [--no-open] [--json]
|
|
460
461
|
skills-layer owned [--json]
|
|
461
462
|
skills-layer export <skill-slug> [--version <semver>] [--output <path>] [--show-url] [--json]
|
|
462
|
-
skills-layer add-review <skill-slug> --rating <1-5> [--feedback <text>] [--json]
|
|
463
|
+
skills-layer add-review <skill-slug> --rating <1-5> [--feedback <text>] [--eval-summary <json-file>] [--json]
|
|
463
464
|
skills-layer show-reviews [skill-slug] [--json]
|
|
464
465
|
skills-layer add-issue <skill-slug> --issue-type <bug|quality|safety|other> --message <text> [--json]
|
|
465
466
|
skills-layer show-issues <skill-slug> [--json]
|
|
@@ -550,9 +551,9 @@ Safety:
|
|
|
550
551
|
- Use guardian status [skill-slug] to see Cloud policy, stored user preference, effective mode, local hook posture, and the next Guardian action.
|
|
551
552
|
- Use guardian hook install to add native host hooks where supported; status reports the actual enforcement layer instead of overclaiming strict blocking.
|
|
552
553
|
- 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.`,
|
|
554
|
+
- Use --dry-run before mutating catalog/source installs, workspace deployments, submissions, visibility, or ownership state.`,ot=`${fr}
|
|
554
555
|
|
|
555
|
-
${
|
|
556
|
+
${wr}`;var bn=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"]),Sn=[...bn].sort(),vr={description:"Run this Skills Layer command.",mutates:!1,supportsDryRun:!1,requiresLogin:!1,requiresNetwork:!0,writesPaths:[],sideEffects:["cloud_read"],dryRun:void 0},yr={root:{description:"Show public CLI guidance and command discovery.",requiresNetwork:!1,sideEffects:["read_only"]},"add-issue":{description:"Report a public skill issue.",mutates:!0,requiresLogin:!0,sideEffects:["cloud_write"]},"add-review":{description:"Add a public skill review.",mutates:!0,requiresLogin:!0,sideEffects:["cloud_write"]},agents:{description:"Inspect supported local agent targets.",requiresNetwork:!1,sideEffects:["local_read"]},"api-key":{description:"Create, list, and revoke scoped automation API keys.",mutates:!0,supportsDryRun:!0,requiresLogin:!0,sideEffects:["cloud_read","credential_mutation","human_handoff"]},"api-key create":{description:"Create a named scoped automation API key, or validate it with --dry-run.",mutates:!0,supportsDryRun:!0,requiresLogin:!0,sideEffects:["cloud_read","credential_mutation","human_handoff"],dryRun:{flag:"--dry-run",mutates:!1,validates:["name","scopes","expiry","active-key-limit"],mayContactCloud:!0,createsRecords:!1,sendsEmail:!1}},"api-key list":{description:"List scoped automation, MCP, and session keys without exposing raw secrets.",mutates:!1,requiresLogin:!0,sideEffects:["cloud_read"]},"api-key revoke":{description:"Revoke a scoped API key after dry-run or confirmation.",mutates:!0,supportsDryRun:!0,requiresLogin:!0,sideEffects:["cloud_read","credential_mutation","destructive_cloud"],dryRun:{flag:"--dry-run",mutates:!1,validates:["key-id","key-exists","revocation-preview"],mayContactCloud:!0,createsRecords:!1,sendsEmail:!1}},approval:{description:"Inspect and complete human approval requests.",mutates:!0,requiresLogin:!0,sideEffects:["cloud_read","cloud_write","human_handoff"]},auth:{description:"Inspect, verify, repair, and recover account authentication.",mutates:!0,requiresNetwork:!0,sideEffects:["cloud_read","credential_mutation","human_handoff"]},backend:{description:"Inspect or select the backend used by this CLI.",mutates:!0,requiresNetwork:!1,writesPaths:["~/.skills-layer/backend.json"],sideEffects:["local_read","local_write"]},buy:{description:"Start a human-in-the-loop purchase flow for a skill.",mutates:!0,requiresLogin:!0,sideEffects:["cloud_read","payment_mutation","human_handoff"]},check:{description:"Check one installed skill against local install state.",requiresNetwork:!1,sideEffects:["local_read"]},creator:{description:"Create, validate, submit, and manage creator-owned skills.",mutates:!0,supportsDryRun:!0,requiresLogin:!0,sideEffects:["local_read","local_write","cloud_read","cloud_write","human_handoff"]},"creator source prepare":{description:"Prepare a source connection for creator publication review.",mutates:!0,requiresLogin:!0,sideEffects:["local_read","cloud_read","cloud_write","human_handoff"]},"creator source publish-request":{description:"Request publication from a prepared source connection.",mutates:!0,requiresLogin:!0,sideEffects:["cloud_read","cloud_write","human_handoff"]},"creator source release-status":{description:"Read source-connection release status.",requiresLogin:!0,sideEffects:["cloud_read"]},doctor:{description:"Run backend, auth, workspace, and Guardian readiness checks.",sideEffects:["local_read","cloud_read"]},export:{description:"Export an owned skill bundle or signed download URL.",mutates:!0,requiresLogin:!0,writesPaths:["<output path>"],sideEffects:["cloud_read","local_write"]},guardian:{description:"Run Guardian checks, incidents, modes, hooks, and guarded exec.",mutates:!0,supportsDryRun:!0,requiresLogin:!1,sideEffects:["local_read","local_write","cloud_read","cloud_write","human_handoff"]},help:{description:"Show local or Cloud-backed help.",requiresNetwork:!1,sideEffects:["read_only"]},identity:{description:"Manage social identity providers and linked identities.",mutates:!0,requiresLogin:!0,sideEffects:["cloud_read","cloud_write","human_handoff"]},import:{description:"Inspect or import supported skill sources.",mutates:!0,supportsDryRun:!0,requiresLogin:!0,sideEffects:["local_read","cloud_read","cloud_write"]},install:{description:"Install a catalog or source skill onto this machine.",mutates:!0,supportsDryRun:!0,requiresLogin:!0,writesPaths:[".codex/skills/<skill-slug>","~/.skills-layer/installs.json"],sideEffects:["local_read","local_write","cloud_read","cloud_write"],dryRun:{flag:"--dry-run",mutates:!1,validates:["slug-or-source","scope","agent","trust","materialization-plan"],mayContactCloud:!0,createsRecords:!1,sendsEmail:!1}},installed:{description:"List locally installed skill records.",requiresNetwork:!1,sideEffects:["local_read"]},library:{description:"Manage owned library records and buyer feedback.",mutates:!0,requiresLogin:!0,sideEffects:["cloud_read","cloud_write"]},login:{description:"Sign in and optionally set up MCP and Security Guardian.",mutates:!0,supportsDryRun:!1,writesPaths:["~/.skills-layer/config.json","~/.skills-layer/mcp.json"],sideEffects:["local_write","cloud_read","credential_mutation","human_handoff"]},logout:{description:"Remove the local CLI session.",mutates:!0,requiresNetwork:!1,writesPaths:["~/.skills-layer/config.json"],sideEffects:["credential_mutation","destructive_local"]},mcp:{description:"Set up, verify, repair, and disconnect MCP clients.",mutates:!0,requiresLogin:!0,writesPaths:["~/.skills-layer/mcp.json","agent MCP config files"],sideEffects:["local_read","local_write","cloud_read","credential_mutation"]},owned:{description:"List skills owned by the signed-in user.",requiresLogin:!0,sideEffects:["cloud_read"]},"preview-trigger":{description:"Preview skill trigger behavior from local source.",requiresNetwork:!0,sideEffects:["local_read","cloud_read"]},profile:{description:"View or update the signed-in account profile.",mutates:!0,requiresLogin:!0,sideEffects:["cloud_read","cloud_write"]},purchases:{description:"Inspect purchases, invoices, refunds, and spending.",mutates:!0,requiresLogin:!0,sideEffects:["cloud_read","cloud_write","payment_mutation"]},register:{description:"Create or verify an account through email or social auth.",mutates:!0,sideEffects:["cloud_write","human_handoff"]},remove:{description:"Remove a local skill install record and materialized files.",mutates:!0,requiresLogin:!1,writesPaths:[".codex/skills/<skill-slug>","~/.skills-layer/installs.json"],sideEffects:["local_read","destructive_local"]},restore:{description:"Inspect and restore a previously removed local install where possible.",mutates:!0,writesPaths:[".codex/skills/<skill-slug>","~/.skills-layer/installs.json"],sideEffects:["local_read","local_write","cloud_read"]},setup:{description:"Set up MCP and Security Guardian for detected AI tools.",mutates:!0,requiresLogin:!0,writesPaths:["~/.skills-layer/mcp.json","agent MCP and hook config files"],sideEffects:["local_read","local_write","cloud_read","credential_mutation","human_handoff"]},source:{description:"Manage source connections, approvals, and source references.",mutates:!0,requiresLogin:!0,sideEffects:["cloud_read","cloud_write","human_handoff"]},sync:{description:"Reconcile local install records against the selected backend catalog.",mutates:!1,sideEffects:["local_read","cloud_read"]},update:{description:"Check whether an installed skill has updates.",supportsDryRun:!0,sideEffects:["local_read","cloud_read"]},validate:{description:"Validate a local skill bundle.",requiresNetwork:!0,sideEffects:["local_read","cloud_read"]},workspace:{description:"Manage workspace skill availability.",mutates:!0,supportsDryRun:!0,requiresLogin:!0,sideEffects:["cloud_read","cloud_write"],dryRun:{flag:"--dry-run",mutates:!1,validates:["workspace","skill","trust","entitlement","policy"],mayContactCloud:!0,createsRecords:!1,sendsEmail:!1}},workspaces:{description:"Alias for workspace commands.",mutates:!0,supportsDryRun:!0,requiresLogin:!0,sideEffects:["cloud_read","cloud_write"],dryRun:{flag:"--dry-run",mutates:!1,validates:["workspace","skill","trust","entitlement","policy"],mayContactCloud:!0,createsRecords:!1,sendsEmail:!1}}},dl=new Set([...Sn,"api-key create","api-key list","api-key revoke","approval request","approval request complete","approval request status","auth recover","auth verify","creator init","creator source prepare","creator source publish-request","creator source release-status","creator submit","featured sort","find examples","guardian check","guardian exec","guardian hook","guardian hook install","guardian hook status","mcp disconnect","mcp repair","mcp setup","mcp status","mcp verify","profile update","source connection","source connection cancel","source connection complete","source connection start","source connection status","status details","validate examples","workspace create","workspace deploy","workspace guide","workspace list","workspace remove","workspace skills"]);function at(e,t){let n=br(e,t),i=n[0],r=n.slice(1).join(" ")||void 0;if(!i||!bn.has(i)||!dl.has(n.join(" ")))return null;if(i==="install")return`Skills Layer install help
|
|
556
557
|
|
|
557
558
|
Usage:
|
|
558
559
|
skills-layer install <skill-slug> [--version <semver>] [--scope <local|project|global|workspace>] [--agent <agent>] [--dry-run] [--json]
|
|
@@ -561,10 +562,12 @@ Usage:
|
|
|
561
562
|
|
|
562
563
|
What it does:
|
|
563
564
|
- Catalog install checks Skills Layer Cloud, then materializes approved files for your selected local agent/runtime.
|
|
564
|
-
- Source install
|
|
565
|
+
- Source install materializes locally after Cloud source inspection and trust checks.
|
|
565
566
|
- Local paths upload the bundle to your private Cloud library by default so the skill can travel across machines.
|
|
566
|
-
- GitHub
|
|
567
|
-
-
|
|
567
|
+
- Public GitHub sources create or reuse a shared public-source catalog record when anonymous inspection succeeds, even if you are signed in.
|
|
568
|
+
- Private GitHub/GitLab sources require login plus a provider/source connection so Cloud can verify access.
|
|
569
|
+
- Add --visibility private when you intentionally want a private Cloud skill instead of public-source intake.
|
|
570
|
+
- Add --visibility public on a private source only when you want the governed public submission/review path.
|
|
568
571
|
|
|
569
572
|
Good defaults:
|
|
570
573
|
skills-layer install <skill-slug> --dry-run
|
|
@@ -573,7 +576,7 @@ Good defaults:
|
|
|
573
576
|
skills-layer install --source <source> --skill <skill-slug> --dry-run
|
|
574
577
|
skills-layer install ./my-skill --agent codex
|
|
575
578
|
skills-layer install https://github.com/OWNER/REPO --skill <skill-slug>
|
|
576
|
-
skills-layer install https://github.com/OWNER/PUBLIC_REPO --skill <skill-slug>
|
|
579
|
+
skills-layer install https://github.com/OWNER/PUBLIC_REPO --skill <skill-slug>
|
|
577
580
|
|
|
578
581
|
After install:
|
|
579
582
|
skills-layer installed
|
|
@@ -726,15 +729,17 @@ Next:
|
|
|
726
729
|
skills-layer guardian status`;if(i==="add-review")return`Skills Layer add-review help
|
|
727
730
|
|
|
728
731
|
Usage:
|
|
729
|
-
skills-layer add-review <skill-slug> --rating <1-5> [--feedback <text>] [--json]
|
|
732
|
+
skills-layer add-review <skill-slug> --rating <1-5> [--feedback <text>] [--eval-summary <json-file>] [--json]
|
|
730
733
|
|
|
731
734
|
What it does:
|
|
732
735
|
- Adds or updates your review for a skill you can access.
|
|
733
736
|
- Rating is validated before submission.
|
|
737
|
+
- Optionally attaches a content-free buyer result summary from local or CI evidence.
|
|
734
738
|
- Use --json for agent-safe status output.
|
|
735
739
|
|
|
736
740
|
Examples:
|
|
737
741
|
skills-layer add-review project-planner --rating 5 --feedback "Useful planning workflow"
|
|
742
|
+
skills-layer add-review project-planner --rating 5 --eval-summary ./eval-summary.json
|
|
738
743
|
skills-layer show-reviews project-planner`;if(i==="add-issue")return`Skills Layer add-issue help
|
|
739
744
|
|
|
740
745
|
Usage:
|
|
@@ -1198,13 +1203,13 @@ Examples:
|
|
|
1198
1203
|
|
|
1199
1204
|
Next:
|
|
1200
1205
|
skills-layer source connection status <source-connection-id>
|
|
1201
|
-
skills-layer creator source prepare <source-connection-id> <path>`;if(i==="mcp")return
|
|
1206
|
+
skills-layer creator source prepare <source-connection-id> <path>`;if(i==="mcp")return hr;let s=r?` ${r}`:"";return`Skills Layer ${i}${s} help
|
|
1202
1207
|
|
|
1203
|
-
Run \`skills-layer --help\` for public CLI usage.`}function
|
|
1204
|
-
`).trim()}function
|
|
1205
|
-
`).trimStart().split(/\n\s*\n/u)[0].split(/\r?\n/u).map(s=>s.trim()).filter(Boolean)}function
|
|
1206
|
-
`)),credentialStore:t.credentialStore!==void 0?t.credentialStore:
|
|
1207
|
-
`,stderr:""};let r=
|
|
1208
|
+
Run \`skills-layer --help\` for public CLI usage.`}function Me(e,t){let n=br(e,t),i=n[0],r=n.slice(1).join(" ")||void 0;if(!i)return kr("root",void 0,wr);if(!bn.has(i))return null;let s=at(i,r?n.slice(1):void 0);return s?kr(i,r,s):null}function br(e,t){return[e,...Array.isArray(t)?t:t?[t]:[]].flatMap(n=>n?.split(/\s+/u)??[]).map(n=>n.trim().toLowerCase()).filter(Boolean)}function kr(e,t,n){let i=yr[e]??{},r=t?yr[`${e} ${t}`]??{}:{},s={...vr,...i,...r},o=r.description??i.description,a=pl(o,n),c=`skills-layer ${e==="root"?"<command>":e} [options]`;return{command:e,...t?{subcommand:t}:{},usage:ml(n,"Usage")||c,description:a,options:fl(n),examples:Pn(n,"Examples").filter(u=>u.startsWith("skills-layer ")),mutates:s.mutates,supportsJson:!0,supportsDryRun:s.supportsDryRun,requiresLogin:s.requiresLogin,requiresNetwork:s.requiresNetwork,writesPaths:s.writesPaths,sideEffects:s.sideEffects,...s.supportsDryRun?{dryRun:s.dryRun??{flag:"--dry-run",mutates:!1,validates:["arguments","policy"],mayContactCloud:s.requiresNetwork,createsRecords:!1,sendsEmail:!1}}:{}}}function pl(e,t){if(e)return e;let n=gl(t);return n||vr.description}function gl(e){let n=Pn(e,"What it does").find(i=>i.startsWith("- "));return n?n.replace(/^-+\s*/u,"").trim():""}function ml(e,t){return Pn(e,t).join(`
|
|
1209
|
+
`).trim()}function Pn(e,t){let n=e.split(/\r?\n/u),i=n.findIndex(s=>s.trim().toLowerCase()===`${t.toLowerCase()}:`);return i===-1?[]:n.slice(i+1).join(`
|
|
1210
|
+
`).trimStart().split(/\n\s*\n/u)[0].split(/\r?\n/u).map(s=>s.trim()).filter(Boolean)}function fl(e){return[...new Set([...e.matchAll(/--[a-z0-9][a-z0-9-]*/giu)].map(t=>t[0]).sort())]}var Be="0.1.8";var A=class extends Error{status;details;constructor(t,n,i){super(n),this.name="ApiError",this.status=t,this.details=i}},bs=1,ci=1,Sr=1,ui="skills-layer-public-cli-v1",be="skills-layer-security-hook",le="Skills Layer Security Hook",di="https://api.skills-layer.com",kl="http://127.0.0.1:8787",Pr=new Set(["json","dry-run","help","list","all","deep","verbose","show-url","no-open","quarantine","confirm","confirmed","yes","with-mcp","no-mcp","allow-unmanaged-once","disclose-source","allow-findings-featured"]),Cn=new Set(["accept-capability","approval-request-id","grant-json","paraphrase","should-not-trigger","should-trigger"]),Cr=new Set(["bio","company","description","display-name","feedback","message","note","reason","search","summary"]),_r=new Set(["action","action-json","agent","amount-cents","api-key","base-url","capability","category","claim-id","client","cloud-trust-ledger","code","commit-sha","created-after","created-before","decision","decision-evidence-json","dependency-audit-status","dir","email","environment","eval-summary","evidence-json","expires","expires-after","expires-before","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"]),xr=new Set(Sn),wl=new Set(["standards","marketplace-status","capabilities","schema-plan","optimize-tokens"]);async function rm(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??Np(t.platform??process.platform),stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY,promptText:t.promptText??Lp(),promptSecret:t.promptSecret??Up(),promptSelect:t.promptSelect??Tp(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}
|
|
1211
|
+
`)),credentialStore:t.credentialStore!==void 0?t.credentialStore:yn(t.platform??process.platform,t.env??process.env)},i=e[0];if(!i){let a=xn([]),c=await lt(a.flags,n);return await od(a.flags,c)}if(i==="--help"||i==="-h"){let a=xn(e.slice(1));if(a.flags.json){let c=await lt(a.flags,n),u=Me();return h(u,"Help loaded.",!0,c)}return{exitCode:0,stdout:ot,stderr:""}}if(i==="--version"||i==="-v")return{exitCode:0,stdout:`skills-layer ${Be}
|
|
1212
|
+
`,stderr:""};let r=xn(e.slice(1));if(r.error)return k(r.error,r.flags.json);let{flags:s,positionals:o}=r;if(i==="admin")return k("The public skills-layer package does not include internal commands.",s.json);if(i==="version"){let a=await lt(s,n);return h({status:"ok",name:"skills-layer",version:Be},`skills-layer ${Be}`,s.json,a)}if(s.help){if(s.json){let c=await lt(s,n),u=Me(i,o);return u?h(u,"Help loaded.",!0,c):xr.has(i)?Vn([i,...o],!0):k(_n(i),!0)}let a=at(i,o);return a?{exitCode:0,stdout:a,stderr:""}:xr.has(i)?Vn([i,...o],s.json):k(_n(i),s.json)}try{let a=await lt(s,n);switch(i){case"agents":return await Sl(o,s,a);case"backend":return await Pl(o,s,a);case"register":return await Ss(s,a);case"login":return await Ps(s,a);case"logout":return await Cs(s,a);case"whoami":return await $("/api/v1/whoami",s,a,"Account loaded.",{authenticated:!0});case"profile":return await xl(o,s,a);case"auth":return await $l(o,s,a);case"identity":return await jl(o,s,a);case"api-key":return await Ll(o,s,a);case"mcp":return await Ml(o,s,a);case"search":case"find":return await Vl(o,s,a);case"featured":case"trending":return await mc(i,s,a);case"categories":return o.length>0?qr("categories",o[0],s):await $("/api/v1/categories",s,a,"Categories loaded.");case"recommend":return await fc(o,s,a);case"compare":return await hc(o,s,a);case"show":return await yc(o,s,a);case"trust":return await kc(o,s,a);case"help":return await wc(o,s,a);case"status":return o.length>0?qr("status",o[0],s):await $("/api/v1/status",s,a,"Status loaded.");case"doctor":return await Ud(s,a);case"setup":return await Zs(s,a);case"validate":return await vc(o,s,a);case"preview-trigger":return await Cc(o,s,a);case"creator":return await _c(o,s,a);case"install":return await hi(o,s,a);case"installed":return await $u(s,a);case"remove":return await Au(o,s,a);case"update":return await Eu(o,s,a);case"sync":return await ju(s,a);case"restore":return await Du(o,s,a);case"check":return await Ku(o,s,a);case"import":return await Vu(o,s,a);case"source":return await Hu(o,s,a);case"approval":return await Ju(o,s,a);case"workspace":case"workspaces":return await Yu(o,s,a);case"buy":return await Zu(o,s,a);case"purchases":return await Qu(o,s,a);case"owned":return await $("/api/v1/me/library",s,a,"Owned skills loaded.",{authenticated:!0});case"export":return await ed(o,s,a);case"library":return await Xu(o,s,a);case"add-review":return await ns("add",o,s,a);case"show-reviews":return await ns("show",o,s,a);case"add-issue":return await is("add",o,s,a);case"show-issues":return await is("show",o,s,a);case"guardian":return await td(o,s,a);default:return k(_n(i),s.json)}}catch(a){return a instanceof A?Qt(a,s.json):k(te(a),s.json)}}function _n(e){let t=e.trim().toLowerCase();return t==="purchase"?`Unknown command "${e}".
|
|
1208
1213
|
|
|
1209
1214
|
Did you mean:
|
|
1210
1215
|
skills-layer buy <skill-slug>
|
|
@@ -1217,7 +1222,7 @@ Did you mean:
|
|
|
1217
1222
|
skills-layer show <skill-slug>`:t==="security-report"?`Unknown command "${e}".
|
|
1218
1223
|
|
|
1219
1224
|
Did you mean:
|
|
1220
|
-
skills-layer trust <skill-slug>`:`Unknown command "${e}".`}function en(e){let t={json:e.includes("--json"),help:!1,dryRun:!1,list:!1,all:!1,deep:!1,verbose:!1,showUrl:!1,noOpen:!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(s!=="install"&&!Bi.has(s)&&!Mi.has(s)&&!qi.has(s)&&!Qt.has(s))return{flags:t,positionals:n,error:`Unknown flag --${s}.`};if(Bi.has(s)){let a=tn(s);s==="confirm"||s==="yes"?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(Mi.has(s)){let a=Qo(e,i);if(!a.value)return{flags:t,positionals:n,error:`Flag --${s} requires a value.`};t[tn(s)]=a.value,i=a.nextIndex;continue}if(qi.has(s)||Qt.has(s)){let a=tn(s);if(Qt.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 Qo(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 tn(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function We(e,t){let n=Xo(t.env,t.platform),[i,r]=await Promise.all([Yu(n.configPath,t),D(n.backendPreferencePath)]),s=te(p(e.baseUrl)??ee(t.env.SKILLS_LAYER_BASE_URL)??ee(r?.preferredBaseUrl)??ee(i?.baseUrl)??Tn),o=p(e.apiKey)??ee(t.env.SKILLS_LAYER_API_KEY),a=ee(i?.apiKey),c=ee(i?.baseUrl),u=!c||te(c)===s,d=o??(u?a:void 0),g=!o&&a&&c&&!u?`Your saved login belongs to ${te(c)}, but the selected backend is ${s}. Run \`skills-layer backend --base-url ${te(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 Xo(e,t){let n=t==="win32"?Ue:jn,i=t==="win32"?ee(e.USERPROFILE)??ee(e.HOME):ee(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 ea(e,t,n){if(e[0]!=="list")return k(`Unknown agents command "${e[0]??""}".`,t.json);let i=ke(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 ta(e,t,n){let i=e[0],r=p(t.baseUrl);if(!i&&r||i==="cloud"||i==="local"){let c=te(r??(i==="local"?Yo:Tn)),u=Ka(c,t);if(u)return u;let d=ae(c),g=n.config?.baseUrl??null,f=!n.config?.baseUrl||te(n.config.baseUrl)===c;return await W(n.paths.backendPreferencePath,{version:Ln,preferredBaseUrl:c,savedAt:n.now()}),h({status:"updated",selectedBackend:d,selectedBaseUrl:c,savedLoginBaseUrl:g,loginMatchesSelectedBackend:f,loggedIn:!!n.apiKey&&f,...f?{}:{warning:`Saved login belongs to ${g}; selected backend is ${c}.`}},f?`Backend set to ${d}.`:`Backend set to ${d}. Saved login is for ${g}.`,t.json,n)}if(i&&i!=="status")return k(`Unknown backend command "${i}".`,t.json);let s=ae(n.baseUrl),o=!n.config?.baseUrl||te(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 Nn=[{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"}],na=[...Nn,{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"}],ia=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...Nn];async function Nr(e,t){let n=p(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",ia)}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)}let i=re("register","method",n,ja,e,"invalid_method");if(i)return i;if(n==="email"){let s=p(e.email);if(!s&&!e.json)try{s=await t.promptText("Enter your email address: ")}catch{return k("register --method email requires --email when interactive prompts are unavailable.",!1)}s=b(s,"register requires --email.");let o=await S(t,"/api/v1/register",{method:"POST",headers:j(),body:JSON.stringify({method:n,email:s})});if(e.json){let c=o.status==="already_registered"?Rn(o):G({...o,nextCommand:`skills-layer auth verify --email ${s} --code <code> --json`,nextAction:"auth.verify"}),u=o.status==="already_registered"?`${s} is already registered.`:`Registration started for ${s}.`;return h(c,u,e.json,t)}if(o.status==="already_registered")return h(Rn(o),`${s} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,!1,t);let a;try{a=await t.promptText(`Enter the verification code sent to ${s} (check spam/junk folder if missing): `)}catch{return h(G(o),`Registration started for ${s}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${s} --code <code>\`.`,!1,t)}return await ks(s,a,e,t,`Verified ${s}.`)}let r=await S(t,"/api/v1/identity/social/start",{method:"POST",headers:j(),body:JSON.stringify({provider:n,mode:"login"})});return e.json?h(r,"Social registration started.",e.json,t):await Wn(n,r,e,t,"login")}async function Fr(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 a=await et(t,n,{notifyLogin:!0}),c=await yn(e,{...t,config:a,apiKey:n});return J(c)?c:h(G({status:"verified",...a,...c.data?{mcp:c.data}:{}}),[`Logged in as ${a.email}.`,c.message??""].filter(Boolean).join(" "),e.json,t)}let i=p(e.method);if(!i&&!e.json)try{let a=await t.promptSelect("Choose how to sign in:",na);i=a==="api_key"?void 0:a}catch{return k("login requires --api-key or --method <email|google|github|gitlab|microsoft> when interactive selection is unavailable.",!1)}let r=re("login","method",i,Ia,e,"invalid_method");if(r)return r;if(i){if(i==="email"){let c=p(e.email);!c&&!e.json&&(c=(await t.promptText("Enter your email address: ")).trim()),c=b(c,"login --method email requires --email.");let u=await S(t,"/api/v1/identity/recover/start",{method:"POST",headers:j(),body:JSON.stringify({email:c,method:"email",intent:"login"})});if(e.json)return h(u,`Passwordless email login started for ${c}.`,!0,t);let d;try{d=(await t.promptText(`Enter the sign-in code sent to ${c} (check spam/junk folder if missing): `)).trim()}catch{return h(u,`Passwordless email login started for ${c}. Check your email, then run \`skills-layer login --method email --email ${c}\` again when prompts are available.`,!1,t)}let g=await S(t,"/api/v1/identity/recover/complete",{method:"POST",headers:j(),body:JSON.stringify({email:c,code:d,intent:"login"})});return await It(c,g,e,t,`Verified ${c}.`)}if(!["google","github","gitlab","microsoft"].includes(i))return k("login --method must be email, google, github, gitlab, or microsoft.",e.json);let a=await S(t,"/api/v1/identity/social/start",{method:"POST",headers:j(),body:JSON.stringify({provider:i,mode:"login"})});return e.json?h(a,"Social login started.",!0,t):await Wn(i,a,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 s=await et(t,n,{notifyLogin:!0}),o=await yn(e,{...t,config:s,apiKey:n});return J(o)?o:h(G({status:"verified",...s,...o.data?{mcp:o.data}:{}}),[`Logged in as ${s.email}.`,o.message??""].filter(Boolean).join(" "),e.json,t)}async function Br(e,t){return await Ai(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 ra(e,t,n){let i=e[0]??"show";if(i==="show")return await $("/api/v1/profile",t,n,"Editable profile loaded.",{authenticated:!0});if(i==="update"){let r=await sa(t,n);if(J(r))return r;let s=await S(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 sa(e,t){let n=H(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 oa(e,t,n){let i=e[0];if(i==="register")return await Nr({...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 ks(r,s,t,n,`Verified ${r}.`)}return i==="recover"?await ca(e.slice(1),t,n):i==="login"?await Fr(t,n):i==="logout"?await Br(t,n):i==="status"?aa(t,n):i==="repair"?await la(t,n):k(`Unknown auth command "${i??""}".`,t.json)}function aa(e,t){let n=t.config?.baseUrl?te(t.config.baseUrl):null,i=!!(t.apiKey&&n===t.baseUrl);return h({status:"auth_status",selectedBackend:ae(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 la(e,t){if(!t.config?.baseUrl||!t.config.apiKey||!t.config.email||!t.config.role||!t.config.savedAt)return w({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login` to create a saved session, then use `skills-layer auth repair` only if backend/session metadata drifts."},"No saved Skills Layer login was found to repair. Run `skills-layer login`.",e.json,"login_required");let n=te(t.config.baseUrl);return await W(t.paths.backendPreferencePath,{version:Ln,preferredBaseUrl:n,savedAt:t.now()}),await Yn(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 ca(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=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 k("auth recover complete requires --code when interactive prompts are unavailable.",!1)}return c=b(c,"auth recover complete requires --code."),await Ki(r,c,t,n)}let s=await S(n,"/api/v1/identity/recover/start",{method:"POST",headers:j(),body:JSON.stringify({email:r,method:i})}),o=Rn(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 Ki(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 Ki(e,t,n,i){let r=await S(i,"/api/v1/identity/recover/complete",{method:"POST",headers:j(),body:JSON.stringify({email:e,code:t})});if(n.json){let s=l(r,"apiKey");return s?(await et(i,s,{expectedEmail:e,knownEmail:l(r,"email")??e,knownRole:l(r,"role")??"user",knownRoles:se(r,"roles"),knownUserId:l(r,"userId")}),h(G({...r,loggedIn:!0}),"Recovery complete.",!0,i)):h(G({...r,email:e,loggedIn:!1}),"Recovery complete.",!0,i)}return await It(e,r,n,i,`Recovered access for ${e}.`)}async function ua(e,t,n){let i=e[0],r=1;if(i==="providers")return await $("/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:",Nn)}catch{return k("identity start requires --provider when interactive selection is unavailable.",!1)}s=b(s,"identity start requires --provider.");let o=await S(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 Wn(s,o,t,n,"login")}if(i==="status"){let s=p(t.state)??e[r];return s?await $(`/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=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 S(n,"/api/v1/identity/social/complete",{method:"POST",headers:j(n.apiKey),body:JSON.stringify({provider:s,state:o,code:a})});return await ru(c,n),h(G(c),"Social auth complete.",t.json,n)}if(i==="list")return await $("/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 S(n,`/api/v1/me/linked-identities/${encodeURIComponent(s)}`,{method:"DELETE",headers:T(n.apiKey,n.authBlockedMessage)});return h(o,"Identity unlinked.",t.json,n)}return k(`Unknown identity command "${i??""}".`,t.json)}async function da(e,t,n){let i=e[0];if(!i)return k("api-key requires create, list, or revoke.",t.json);if(i==="list"){let r=pa(t);if(r.failure)return r.failure;let s=await S(n,"/api/v1/me/api-keys",{headers:T(n.apiKey,n.authBlockedMessage)}),o=ga(hn(s),r.filters);return h({...s,filters:x({...r.filters}),results:o},"API keys loaded.",t.json,n)}if(i==="create"){let r=p(t.name),s=sd(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=s.find(u=>!Yi.includes(u));if(o)return Pe("api-key.create","scope",o,Yi,t,"invalid_scope");let a=Ga("api-key.create",t.expires,t);if(a)return a;if(t.dryRun){let u=await S(n,"/api/v1/me/api-keys",{headers:T(n.apiKey,n.authBlockedMessage)}),d=hn(u).filter(g=>Mr(g)==="active"&&l(g,"type")==="automation");return d.length>=er?w({status:"error",reasonCode:"api_key_active_limit_reached",maxActiveAutomationKeys:er,activeAutomationKeyCount:d.length,nextAction:"api-key.revoke",nextStep:"Revoke an unused automation key before creating another."},"Too many active automation keys. Revoke unused keys before creating another.",t.json,"api_key_active_limit_reached"):h(x({status:"pass",wouldCreate:!0,type:"automation",name:r,scopes:s,expiresAt:fa(p(t.expires),n.now()),secretReturned:!1,secretDelivery:"email",warnings:[]}),"API key create dry run passed.",t.json,n)}let c=await S(n,"/api/v1/me/api-keys",{method:"POST",headers:{"content-type":"application/json",...T(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:r,scopes:s,...p(t.expires)?{expiresIn:p(t.expires)}:{}})});return h({...G(c),secretReturned:!1,secretDelivery:"email"},"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.
|
|
1225
|
+
skills-layer trust <skill-slug>`:`Unknown command "${e}".`}function xn(e){let t={json:e.includes("--json"),help:!1,dryRun:!1,list:!1,all:!1,deep:!1,verbose:!1,showUrl:!1,noOpen:!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(s!=="install"&&!Pr.has(s)&&!Cr.has(s)&&!_r.has(s)&&!Cn.has(s))return{flags:t,positionals:n,error:`Unknown flag --${s}.`};if(Pr.has(s)){let a=Rn(s);s==="confirm"||s==="yes"?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(Cr.has(s)){let a=vl(e,i);if(!a.value)return{flags:t,positionals:n,error:`Flag --${s} requires a value.`};t[Rn(s)]=a.value,i=a.nextIndex;continue}if(_r.has(s)||Cn.has(s)){let a=Rn(s);if(Cn.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 vl(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 Rn(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function lt(e,t){let n=bl(t.env,t.platform),[i,r]=await Promise.all([jp(n.configPath,t),W(n.backendPreferencePath)]),s=Ce(p(e.baseUrl)??oe(t.env.SKILLS_LAYER_BASE_URL)??oe(r?.preferredBaseUrl)??oe(i?.baseUrl)??di),o=p(e.apiKey)??oe(t.env.SKILLS_LAYER_API_KEY),a=oe(i?.apiKey),c=oe(i?.baseUrl),u=!c||mt(c,s),d=o??(u?a:void 0),g=!o&&a&&c&&!u?`Your saved login belongs to ${Ce(c)}, but the selected backend is ${s}. Run \`skills-layer backend --base-url ${Ce(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 bl(e,t){let n=t==="win32"?ze:oi,i=t==="win32"?oe(e.USERPROFILE)??oe(e.HOME):oe(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 Sl(e,t,n){if(e[0]!=="list")return k(`Unknown agents command "${e[0]??""}".`,t.json);let i=Pe(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 Pl(e,t,n){let i=e[0],r=p(t.baseUrl);if(!i&&r||i==="cloud"||i==="local"){let c=Ce(r??(i==="local"?kl:di)),u=uc(c,t);if(u)return u;let d=pe(c),g=n.config?.baseUrl??null,f=!n.config?.baseUrl||mt(n.config.baseUrl,c);return await ee(n.paths.backendPreferencePath,{version:ci,preferredBaseUrl:c,savedAt:n.now()}),h({status:"updated",selectedBackend:d,selectedBaseUrl:c,savedLoginBaseUrl:g,loginMatchesSelectedBackend:f,loggedIn:!!n.apiKey&&f,...f?{}:{warning:`Saved login belongs to ${g}; selected backend is ${c}.`}},f?`Backend set to ${d}.`:`Backend set to ${d}. Saved login is for ${g}.`,t.json,n)}if(i&&i!=="status")return k(`Unknown backend command "${i}".`,t.json);let s=pe(n.baseUrl),o=!n.config?.baseUrl||mt(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 pi=[{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"}],Cl=[...pi,{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"}],_l=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...pi];async function Ss(e,t){let n=p(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",_l)}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)}let i=ce("register","method",n,Xl,e,"invalid_method");if(i)return i;if(n==="email"){let s=p(e.email);if(!s&&!e.json)try{s=await t.promptText("Enter your email address: ")}catch{return k("register --method email requires --email when interactive prompts are unavailable.",!1)}s=b(s,"register requires --email.");let o=await S(t,"/api/v1/register",{method:"POST",headers:I(),body:JSON.stringify({method:n,email:s})});if(e.json){let c=o.status==="already_registered"?ti(o):Y({...o,nextCommand:`skills-layer auth verify --email ${s} --code <code> --json`,nextAction:"auth.verify"}),u=o.status==="already_registered"?`${s} is already registered.`:`Registration started for ${s}.`;return h(c,u,e.json,t)}if(o.status==="already_registered")return h(ti(o),`${s} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,!1,t);let a;try{a=await t.promptText(`Enter the verification code sent to ${s} (check spam/junk folder if missing): `)}catch{return h(Y(o),`Registration started for ${s}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${s} --code <code>\`.`,!1,t)}return await co(s,a,e,t,`Verified ${s}.`)}let r=await S(t,"/api/v1/identity/social/start",{method:"POST",headers:I(),body:JSON.stringify({provider:n,mode:"login"})});return e.json?h(r,"Social registration started.",e.json,t):await _i(n,r,e,t,"login")}async function Ps(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 a=await pt(t,n,{notifyLogin:!0}),c=await Kn(e,{...t,config:a,apiKey:n});return H(c)?c:h(Y({status:"verified",...a,...c.data?{mcp:c.data}:{}}),[`Logged in as ${a.email}.`,c.message??""].filter(Boolean).join(" "),e.json,t)}let i=p(e.method);if(!i&&!e.json)try{let a=await t.promptSelect("Choose how to sign in:",Cl);i=a==="api_key"?void 0:a}catch{return k("login requires --api-key or --method <email|google|github|gitlab|microsoft> when interactive selection is unavailable.",!1)}let r=ce("login","method",i,Ql,e,"invalid_method");if(r)return r;if(i){if(i==="email"){let c=p(e.email);!c&&!e.json&&(c=(await t.promptText("Enter your email address: ")).trim()),c=b(c,"login --method email requires --email.");let u=await S(t,"/api/v1/identity/recover/start",{method:"POST",headers:I(),body:JSON.stringify({email:c,method:"email",intent:"login"})});if(e.json)return h(u,`Passwordless email login started for ${c}.`,!0,t);let d;try{d=(await t.promptText(`Enter the sign-in code sent to ${c} (check spam/junk folder if missing): `)).trim()}catch{return h(u,`Passwordless email login started for ${c}. Check your email, then run \`skills-layer login --method email --email ${c}\` again when prompts are available.`,!1,t)}let g=await S(t,"/api/v1/identity/recover/complete",{method:"POST",headers:I(),body:JSON.stringify({email:c,code:d,intent:"login"})});return await Wt(c,g,e,t,`Verified ${c}.`)}if(!["google","github","gitlab","microsoft"].includes(i))return k("login --method must be email, google, github, gitlab, or microsoft.",e.json);let a=await S(t,"/api/v1/identity/social/start",{method:"POST",headers:I(),body:JSON.stringify({provider:i,mode:"login"})});return e.json?h(a,"Social login started.",!0,t):await _i(i,a,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 s=await pt(t,n,{notifyLogin:!0}),o=await Kn(e,{...t,config:s,apiKey:n});return H(o)?o:h(Y({status:"verified",...s,...o.data?{mcp:o.data}:{}}),[`Logged in as ${s.email}.`,o.message??""].filter(Boolean).join(" "),e.json,t)}async function Cs(e,t){return await mr(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),await ri(t.paths.configPath,{force:!0}),h({status:"logged_out"},"Logged out.",e.json,t)}async function xl(e,t,n){let i=e[0]??"show";if(i==="show")return await $("/api/v1/profile",t,n,"Editable profile loaded.",{authenticated:!0});if(i==="update"){let r=await Rl(t,n);if(H(r))return r;let s=await S(n,"/api/v1/profile",{method:"PATCH",headers:I(n.apiKey),body:JSON.stringify(r)});return h(s,"Profile updated.",t.json,n)}return k(`Unknown profile command "${i}".`,t.json)}async function Rl(e,t){let n=Z(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=_({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 $l(e,t,n){let i=e[0];if(i==="register")return await Ss({...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 co(r,s,t,n,`Verified ${r}.`)}return i==="recover"?await Il(e.slice(1),t,n):i==="login"?await Ps(t,n):i==="logout"?await Cs(t,n):i==="status"?Al(t,n):i==="repair"?await El(t,n):k(`Unknown auth command "${i??""}".`,t.json)}function Al(e,t){let n=t.config?.baseUrl?Ce(t.config.baseUrl):null,i=!!(t.apiKey&&n&&mt(n,t.baseUrl));return h({status:"auth_status",selectedBackend:pe(t.baseUrl),selectedBaseUrl:t.baseUrl,loggedIn:i,requiresLogin:!i,...t.config?.email?{savedLogin:{baseUrl:n,email:t.config.email,role:t.config.role??null,roles:t.config.roles??[],savedAt:t.config.savedAt??null,...t.config.credentialStorage?{credentialStorage:t.config.credentialStorage}:{},matchesSelectedBackend:i}}:{}},i&&t.config?.email?`Logged in as ${t.config.email}.`:t.config?.baseUrl?`Saved login targets ${n}; selected backend is ${t.baseUrl}. Run \`skills-layer auth repair\` or \`skills-layer login\`.`:"Not logged in. Run `skills-layer login`.",e.json,t)}async function El(e,t){if(!t.config?.baseUrl||!t.config.apiKey||!t.config.email||!t.config.role||!t.config.savedAt)return w({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login` to create a saved session, then use `skills-layer auth repair` only if backend/session metadata drifts."},"No saved Skills Layer login was found to repair. Run `skills-layer login`.",e.json,"login_required");let n=Ce(t.config.baseUrl);return await ee(t.paths.backendPreferencePath,{version:ci,preferredBaseUrl:n,savedAt:t.now()}),await Ri(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 Il(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=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 k("auth recover complete requires --code when interactive prompts are unavailable.",!1)}return c=b(c,"auth recover complete requires --code."),await Rr(r,c,t,n)}let s=await S(n,"/api/v1/identity/recover/start",{method:"POST",headers:I(),body:JSON.stringify({email:r,method:i})}),o=ti(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 Rr(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 Rr(e,t,n,i){let r=await S(i,"/api/v1/identity/recover/complete",{method:"POST",headers:I(),body:JSON.stringify({email:e,code:t})});if(n.json){let s=l(r,"apiKey");return s?(await pt(i,s,{expectedEmail:e,knownEmail:l(r,"email")??e,knownRole:l(r,"role")??"user",knownRoles:ue(r,"roles"),knownUserId:l(r,"userId")}),h(Y({...r,loggedIn:!0}),"Recovery complete.",!0,i)):h(Y({...r,email:e,loggedIn:!1}),"Recovery complete.",!0,i)}return await Wt(e,r,n,i,`Recovered access for ${e}.`)}async function jl(e,t,n){let i=e[0],r=1;if(i==="providers")return await $("/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:",pi)}catch{return k("identity start requires --provider when interactive selection is unavailable.",!1)}s=b(s,"identity start requires --provider.");let o=await S(n,"/api/v1/identity/social/start",{method:"POST",headers:I(n.apiKey),body:JSON.stringify({provider:s,mode:p(t.mode)??"login"})});return t.json?h(o,"Social auth started.",!0,n):await _i(s,o,t,n,"login")}if(i==="status"){let s=p(t.state)??e[r];return s?await $(`/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=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 S(n,"/api/v1/identity/social/complete",{method:"POST",headers:I(n.apiKey),body:JSON.stringify({provider:s,state:o,code:a})});return await Bd(c,n),h(Y(c),"Social auth complete.",t.json,n)}if(i==="list")return await $("/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 S(n,`/api/v1/me/linked-identities/${encodeURIComponent(s)}`,{method:"DELETE",headers:F(n.apiKey,n.authBlockedMessage)});return h(o,"Identity unlinked.",t.json,n)}return k(`Unknown identity command "${i??""}".`,t.json)}async function Ll(e,t,n){let i=e[0];if(!i)return k("api-key requires create, list, or revoke.",t.json);if(i==="list"){let r=Ul(t);if(r.failure)return r.failure;let s=await S(n,"/api/v1/me/api-keys",{headers:F(n.apiKey,n.authBlockedMessage)}),o=Tl(Dn(s),r.filters);return h({...s,filters:_({...r.filters}),results:o},"API keys loaded.",t.json,n)}if(i==="create"){let r=p(t.name),s=qp(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=s.find(u=>!Tr.includes(u));if(o)return je("api-key.create","scope",o,Tr,t,"invalid_scope");let a=pc("api-key.create",t.expires,t);if(a)return a;if(t.dryRun){let u=await S(n,"/api/v1/me/api-keys",{headers:F(n.apiKey,n.authBlockedMessage)}),d=Dn(u).filter(g=>_s(g)==="active"&&l(g,"type")==="automation");return d.length>=Br?w({status:"error",reasonCode:"api_key_active_limit_reached",maxActiveAutomationKeys:Br,activeAutomationKeyCount:d.length,nextAction:"api-key.revoke",nextStep:"Revoke an unused automation key before creating another."},"Too many active automation keys. Revoke unused keys before creating another.",t.json,"api_key_active_limit_reached"):h(_({status:"pass",wouldCreate:!0,type:"automation",name:r,scopes:s,expiresAt:Nl(p(t.expires),n.now()),secretReturned:!1,secretDelivery:"email",warnings:[]}),"API key create dry run passed.",t.json,n)}let c=await S(n,"/api/v1/me/api-keys",{method:"POST",headers:{"content-type":"application/json",...F(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:r,scopes:s,...p(t.expires)?{expiresIn:p(t.expires)}:{}})});return h({...Y(c),secretReturned:!1,secretDelivery:"email"},"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.
|
|
1221
1226
|
|
|
1222
1227
|
For CLI access:
|
|
1223
1228
|
skills-layer login
|
|
@@ -1231,22 +1236,22 @@ To remove an old key:
|
|
|
1231
1236
|
|
|
1232
1237
|
Run:
|
|
1233
1238
|
skills-layer api-key list
|
|
1234
|
-
skills-layer api-key revoke --key-id <key-id>`,t.json,"missing_required_argument");let s=String(r);if(t.dryRun){let a=await Gi(s,n);return a?h(x({status:"pass",wouldRevoke:!0,keyId:s,keyPrefix:l(a,"keyPrefix"),type:l(a,"type"),name:l(a,"name"),scopes:se(a,"scopes")??[],revokedAt:a.revokedAt??null,nextAction:"api-key.revoke",nextStep:`Run \`skills-layer api-key revoke --key-id ${s} --yes\` to revoke this key.`}),"API key revoke dry run passed.",t.json,n):Vi(s,t)}if(!t.confirmed){let a=await Gi(s,n);if(!a)return Vi(s,t);let c=x({status:"confirmation_required",reasonCode:"confirmation_required",keyId:s,keyPrefix:l(a,"keyPrefix"),type:l(a,"type"),name:l(a,"name"),nextAction:"api-key.revoke",nextStep:`Re-run with \`skills-layer api-key revoke --key-id ${s} --yes\` after confirming this is the key to revoke.`});if(t.json||!n.stdoutIsTty)return w(c,"API key revoke needs confirmation. Re-run with --yes after checking the key id.",t.json,"confirmation_required");if(await n.promptSelect(`Revoke API key ${s}?`,[{value:"cancel",label:"Cancel",description:"Leave this API key active"},{value:"confirm",label:"Revoke",description:"Permanently revoke this API key"}])!=="confirm")return h({status:"canceled",keyId:s},"API key revoke canceled.",t.json,n)}let o=await S(n,`/api/v1/me/api-keys/${encodeURIComponent(s)}/revoke`,{method:"POST",headers:T(n.apiKey,n.authBlockedMessage)});return h(o,"API key revoked.",t.json,n)}return k(`Unknown api-key command "${i}".`,t.json)}function pa(e){let t=p(e.type);if(t&&!Zi.includes(t))return{failure:Pe("api-key.list","type",t,Zi,e,"invalid_api_key_filter","type")};let n=p(e.status)??"active";if(!Qi.includes(n))return{failure:Pe("api-key.list","status",n,Qi,e,"invalid_api_key_filter","status")};let i=p(e.sort)??"created-desc";if(!Xi.includes(i))return{failure:Pe("api-key.list","sort",i,Xi,e,"invalid_api_key_filter","sort")};let r=[["createdAfter","created-after",e.createdAfter],["createdBefore","created-before",e.createdBefore],["expiresAfter","expires-after",e.expiresAfter],["expiresBefore","expires-before",e.expiresBefore]],s={status:n,sort:i};for(let[o,a,c]of r){let u=p(c);if(u){if(Number.isNaN(Date.parse(u)))return{failure:w({status:"error",reasonCode:"invalid_api_key_filter",field:a,value:u,nextAction:"api-key.list",nextStep:`Use --${a} with an ISO date or timestamp.`},`Invalid api-key list --${a} "${u}". Use an ISO date or timestamp.`,e.json,"invalid_api_key_filter")};s[o]=u}}return{filters:x({...s,...t?{type:t}:{},...p(e.name)?{name:p(e.name)}:{}})}}function hn(e){return(fe(e,"results")??[]).filter(t=>R(t))}function ga(e,t){let n=t.name?.toLowerCase();return e.filter(i=>!t.type||l(i,"type")===t.type).filter(i=>t.status==="all"||Mr(i)===t.status).filter(i=>!n||(l(i,"name")??l(i,"id")??"").toLowerCase().includes(n)).filter(i=>mt(i,"createdAt",t.createdAfter,"after")).filter(i=>mt(i,"createdAt",t.createdBefore,"before")).filter(i=>mt(i,"expiresAt",t.expiresAfter,"after")).filter(i=>mt(i,"expiresAt",t.expiresBefore,"before")).sort((i,r)=>ma(i,r,t.sort))}function Mr(e,t=Date.now()){if(e.revokedAt!==null&&e.revokedAt!==void 0)return"revoked";let n=l(e,"expiresAt");if(!n)return"active";let i=Date.parse(n);return Number.isNaN(i)||i>t?"active":"expired"}function mt(e,t,n,i){if(!n)return!0;let r=l(e,t);if(!r)return!1;let s=Date.parse(r),o=Date.parse(n);return Number.isNaN(s)||Number.isNaN(o)?!1:i==="after"?s>=o:s<=o}function ma(e,t,n){if(n==="name-asc"||n==="name-desc")return(n==="name-asc"?1:-1)*(l(e,"name")??l(e,"id")??"").localeCompare(l(t,"name")??l(t,"id")??"");let i=n.endsWith("-asc")?1:-1,r=n.startsWith("expires-")?"expiresAt":n.startsWith("last-used-")?"lastUsedAt":"createdAt";return i*(Di(e,r)-Di(t,r))}function Di(e,t){let n=l(e,t);if(!n)return 0;let i=Date.parse(n);return Number.isNaN(i)?0:i}function fa(e,t){if(!e)return;let n=/^(\d+)d$/iu.exec(e.trim());if(!n)return;let i=Date.parse(t),r=Number.isNaN(i)?Date.now():i;return new Date(r+Number.parseInt(n[1],10)*24*60*60*1e3).toISOString()}async function Gi(e,t){let n=await S(t,"/api/v1/me/api-keys",{headers:T(t.apiKey,t.authBlockedMessage)});return hn(n).find(i=>l(i,"id")===e)}function Vi(e,t){return w({status:"not_found",reasonCode:"api_key_not_found",keyId:e,nextAction:"api-key.list",nextStep:"Run `skills-layer api-key list` to find an active key id, then retry revoke."},`API key ${e} was not found.`,t.json,"api_key_not_found")}async function ha(e,t,n){let i=e[0]??"status";if(i==="setup"||i==="repair"){let r=p(t.client)??p(t.agent);if(r&&t.all)return w({status:"error",reasonCode:"conflicting_mcp_client_selection",client:r,all:!0,nextAction:`mcp.${i}`,nextStep:"Use either --client <agent-id> for one agent or --all for every detected MCP-capable agent."},`mcp ${i} cannot use --client and --all together.`,t.json,"conflicting_mcp_client_selection");if(r&&!Ye(r))return nn(r,t);if(r){let o=await D(n.paths.mcpConfigPath),a=o?l(o,"baseUrl")??n.baseUrl:n.baseUrl,c=await De({baseUrl:a,mcpUrl:o?l(o,"mcpUrl")??`${a}/mcp`:`${a}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:o?l(o,"environment")??ae(a):ae(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:o});if(c.target.status==="skills_only"){let u=ft(c);return h(u,`${c.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}}let s=await Fn(t,n);return J(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&&!Ye(r))return nn(r,t);let s=await D(n.paths.mcpConfigPath);if(!s){if(r){let u=await De({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:ae(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=ft(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 De({baseUrl:a,mcpUrl:l(s,"mcpUrl")??`${a}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:o,environment:l(s,"environment")??ae(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=ft(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 di({nodePath:process.execPath,bridgePath:c.bridge.path}),d={...c,verified:u.status==="ok",liveProbe:u};return u.status!=="ok"?w(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(!Ye(r))return nn(r,t);let s=await D(n.paths.mcpConfigPath),o=s?l(s,"baseUrl")??n.baseUrl:n.baseUrl,a=await De({baseUrl:o,mcpUrl:s?l(s,"mcpUrl")??`${o}/mcp`:`${o}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:s?l(s,"environment")??ae(o):ae(o),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:s});if(a.target.status==="skills_only"){let d=ft(a);return h(d,`${a.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}let c=Ke({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:ae(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}),u=c.targets.find(d=>d.agentId===r);return await wa(s,n),await u?.disconnect?.(),await gi(c.bridgePath),await mi(c.brokerPath,c.brokerSocketPath),await An(n.paths.mcpConfigPath,{force:!0}),h({status:"mcp_disconnected",configured:!1,clientId:r},"MCP disconnected on this machine.",t.json,n)}return k(`Unknown mcp command "${i}". Use setup, status, verify, repair, or disconnect.`,t.json)}function Ye(e){return ve.includes(e)}function nn(e,t){return w({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 ft(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 Fn(e,t){let n=p(e.environment)??ae(t.baseUrl),i=["mcp:use","catalog:read","library:read","guardian:check","guardian:incident","creator:read"],r=`${t.baseUrl}/mcp`,s=Ke({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 ya(e,t,s),a=o.clientIds[0]??"codex",c=Ke({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 y=await S(t,"/api/v1/me/mcp-tokens",{method:"POST",headers:j(t.apiKey),body:JSON.stringify({clientId:m,environment:n,scopes:i})}),v=l(y,"apiKey");if(!v)return k("MCP setup did not receive a token from the backend.",e.json);let C=await ka(t,{token:v,clientId:m,environment:n});u[m]={clientId:m,environment:n,...C,tokenPrefix:l(y,"keyPrefix")??null,scopes:Array.isArray(y.scopes)?y.scopes:[],savedAt:t.now()},d??=y}let g=u[a]??{};await W(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{...G(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 ya(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 ti({env:t.env,platform:t.platform,cwd:t.cwd,pathExists:ce}),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 ka(e,t){if(!e.credentialStore)return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"};let n=ba({baseUrl:e.baseUrl,userId:e.config?.userId,email:e.config?.email,clientId:t.clientId,environment:t.environment});try{return await e.credentialStore.set(Ve,n,t.token),{tokenRef:n,credentialStorage:"macos_keychain",credentialService:Ve,tokenStorage:"macos_keychain"}}catch{return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}}async function wa(e,t){if(!e||!t.credentialStore)return;let n=va(e,Ve);for(let i of n)await t.credentialStore.delete(i.service,i.tokenRef)}function va(e,t){let n=new Map;Hi(e,t,n);let i=e.tokens;if(R(i))for(let r of Object.values(i))R(r)&&Hi(r,t,n);return[...n.values()]}function Hi(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 ba(e){let t=[e.baseUrl,e.userId??e.email??"unknown-user",e.clientId,e.environment,"mcpToken"].join(`
|
|
1235
|
-
`);return`skills-layer-cli:mcp-token:${$n("sha256").update(t).digest("base64url").slice(0,32)}`}async function yn(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 D(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 D(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 W(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 Fn(e,t);return J(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 Sa(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&&!zi.includes(s))return yt("runtime-risk",s,zi,t);let o=p(t.agent);if(o&&!Ye(o))return w({status:"error",reasonCode:"unknown_agent",filter:"agent",value:o,acceptedValues:ve,nextAction:"search",nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown search --agent "${o}". Run \`skills-layer agents list\` to inspect supported agents.`,t.json,"unknown_agent");let a=p(t.trust);if(a&&!Wi.includes(a))return yt("trust",a,Wi,t);let c=p(t.securityCapability),u=Fa(c);if(c&&!u)return yt("security-capability",c,qr,t);let d=p(t.limit);if(d){let f=Number(d);if(!Number.isInteger(f)||f<1||f>100)return yt("limit",d,["1-100"],t);r.set("limit",String(f))}M(r,"agent",t.agent),M(r,"capability",t.capability),M(r,"trust",a),M(r,"runtime-risk",s),M(r,"security-capability",u);let g=await S(n,`/api/v1/search${ue(r)}`);if(t.install!==void 0){let f=p(t.install);if(!f){if(t.json)return k("search --install requires an explicit skill slug in the public CLI package.",!0);let y=rt(g);if(y.length===0)return k("Search results do not include any installable skills. Run search again with a broader query.",!1);if(y.length===1)f=y[0].value;else try{f=await n.promptSelect("Select a search result to install:",y)}catch{return k("No search result was selected for install.",!1)}}let m=nd(g);return m.includes(f)?await qn([f],t,n):k(m.length===0?`Search results do not include "${f}". Run search again with a matching query first.`:`Search results do not include "${f}". Run search again with a matching query or choose one of: ${m.join(", ")}.`,t.json)}return h(g,"Search complete.",t.json,n)}var zi=["low","elevated","high"],Wi=["high","medium","low","published","published_with_findings","publishable","publishable_with_findings","blocked","unknown"],qr=["filesystem_read","filesystem_write","network_access","api_access","browser_access","device_control","generated_code_execution","secret_handling","model_context","shell_access"],Pa={network:"network_access",filesystem:"filesystem_read",files:"filesystem_read",file_read:"filesystem_read",file_write:"filesystem_write",shell:"shell_access",browser:"browser_access",device:"device_control",api:"api_access",secrets:"secret_handling",model:"model_context"},rn=["local","project","global","workspace"],Ze=["private","public","unlisted"],Ie=["private","public","unlisted"],Ji=["github","gitlab","local","generic_git","domain"],Ca=["owner","maintainer"],_a=["submitted","published","draft","pending_review","suspended","blocked","archived","unlisted"],xa=["open","acknowledged","fixed","closed","rejected","abusive","reopened","resolved"],Ra=["visible","flagged","hidden"],$a=["bug","quality","safety","other"],Aa=["approved","denied"],Ia=["email","google","github","gitlab","microsoft"],ja=["email","google","github","gitlab","microsoft"],Yi=["catalog:read","library:read","creator:read","creator:submit","guardian:check","guardian:incident","workspace:read","workspace:write","workspace:deploy","mcp:use"],Zi=["automation","mcp","agent"],Qi=["active","expired","revoked","all"],Xi=["created-desc","created-asc","expires-desc","expires-asc","name-asc","name-desc","last-used-desc","last-used-asc"],er=10,Ea=["personal","shared","team"],Or=["json","sarif"],ht=["featured","trending","newest","name","relevance"],La=/^(?:card(?:_[A-Za-z0-9]+)*|pm_[A-Za-z0-9_]+)$/u,Ua=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Ta=/^[a-f0-9]{6,64}$/iu,Na=new Set(["http:","https:"]);function Kr(e,t,n,i){let r=p(t);if(!r)return{};if(!/^\d+$/u.test(r))return{failure:w({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:w({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 yt(e,t,n,i){return w({status:"error",reasonCode:"invalid_search_filter",filter:e,value:t,acceptedValues:n,nextAction:"search",nextStep:e==="runtime-risk"?"Use --runtime-risk low, elevated, or high.":e==="limit"?"Use --limit with a whole number from 1 to 100.":`Use --${e} with one of: ${n.join(", ")}.`},e==="runtime-risk"?`Invalid runtime risk "${t}". Use one of: ${n.join(", ")}.`:e==="limit"?`Invalid search limit "${t}". Use a whole number from 1 to 100.`:`Invalid search --${e} "${t}". Use one of: ${n.join(", ")}.`,i.json,"invalid_search_filter")}function Fa(e){if(e)return qr.includes(e)?e:Pa[e]}function Pe(e,t,n,i,r,s,o=t){return w({status:"error",reasonCode:s,[t]:n,acceptedValues:i,nextAction:e,nextStep:`Use --${o} with one of: ${i.join(", ")}.`},`Invalid ${e} --${o} "${n}". Use one of: ${i.join(", ")}.`,r.json,s)}function re(e,t,n,i,r,s,o=t){let a=p(n);if(!(!a||i.includes(a)))return Pe(e,t,a,i,r,s,o)}function we(e,t){let n=p(t.version);return n&&!At(n)?Mn(e,n,t):void 0}function Ba(e,t,n){return w({status:"error",reasonCode:"invalid_slug",value:t,acceptedFormat:"lowercase words separated by hyphens",nextAction:e,nextStep:"Use a lowercase skill slug such as project-planner or year9-history-study-guide."},`Invalid skill slug "${t}". Use lowercase letters, numbers, and single hyphens.`,n.json,"invalid_slug")}function Dr(e,t,n){return t&&!Ua.test(t)?Ba(e,t,n):void 0}function Ma(e,t,n){return w({status:"error",reasonCode:"invalid_format",format:t,acceptedValues:Or,nextAction:e,nextStep:"Use --format json or --format sarif."},`Invalid ${e} --format "${t}". Use json or sarif.`,n.json,"invalid_format")}function Gr(e,t){let n=p(t.format);return n&&!Or.includes(n.toLowerCase())?Ma(e,n,t):void 0}function qa(e,t,n){return w({status:"error",reasonCode:"invalid_commit_sha",commitSha:t,nextAction:e,nextStep:"Use --commit-sha with a 6 to 64 character hexadecimal commit SHA."},`Invalid --commit-sha "${t}". Use a hexadecimal commit SHA.`,n.json,"invalid_commit_sha")}function Oa(e,t){let n=p(t.commitSha);return n&&!Ta.test(n)?qa(e,n,t):void 0}function tr(e,t){return w({status:"error",reasonCode:"invalid_base_url",baseUrl:e,nextAction:"backend",nextStep:"Use --base-url with an http or https URL, for example https://api.skills-layer.com."},`Invalid backend base URL "${e}". Use an http or https URL.`,t.json,"invalid_base_url")}function Ka(e,t){try{let n=new URL(e);return!Na.has(n.protocol)||!n.hostname?tr(e,t):void 0}catch{return tr(e,t)}}function nr(e,t,n){return w({status:"error",reasonCode:"unexpected_argument",command:e,argument:t,nextAction:e,nextStep:`Run \`skills-layer ${e} --help\` to see supported arguments for this command.`},`Unexpected argument "${t}" for ${e}.`,n.json,"unexpected_argument")}function Bn(e,t){let n=p(t.scope);if(n&&!rn.includes(n))return{failure:w({status:"error",reasonCode:"invalid_install_filter",filter:"scope",value:n,acceptedValues:rn,nextAction:e,nextStep:"Use --scope local, project, global, or workspace."},`Invalid ${e} --scope "${n}". Use one of: ${rn.join(", ")}.`,t.json,"invalid_install_filter")};let i=p(t.agent);return i&&!Ye(i)?{failure:w({status:"error",reasonCode:"unknown_agent",filter:"agent",value:i,acceptedValues:ve,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 Vr(e,t){let n=Bn(e,t);if(n.failure)return n.failure;let i=p(t.version);if(e==="install"&&i&&!At(i))return Mn("install",i,t)}function Mn(e,t,n){return w({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 Da(e,t,n){return w({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 Ga(e,t,n){let i=p(t);if(i&&!/^[1-9]\d*d$/iu.test(i))return Da(e,i,n)}function Ee(e,t,n,i,r,s){let o=p(e);if(!o)return{};if(!/^\d+$/u.test(o))return{failure:w({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:w({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 Va(e){let t=p(e.paymentMethod)??"card";return La.test(t)?{value:t}:{failure:w({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 Ha(e,t,n){let i=new URLSearchParams,r=Kr(e,t.limit,20,t);if(r.failure)return r.failure;let s=p(t.sort);return s&&!ht.includes(s)?w({status:"error",reasonCode:"invalid_sort",sort:s,acceptedValues:ht,nextAction:e,nextStep:`Use --sort with one of: ${ht.join(", ")}.`},`${e} --sort must be one of: ${ht.join(", ")}.`,t.json,"invalid_sort"):(M(i,"limit",r.value),M(i,"search",t.search),M(i,"sort",s),await $(`/api/v1/${e}${ue(i)}`,t,n,`${Nt(e)} skills loaded.`))}async function za(e,t,n){let i=e.join(" ").trim();if(!i)return k("recommend requires a task.",t.json);let r=Kr("recommend",t.limit,20,t);if(r.failure)return r.failure;let s=new URLSearchParams({task:i});return M(s,"limit",r.value),await $(`/api/v1/recommend?${s.toString()}`,t,n,"Recommendations loaded.")}async function Wa(e,t,n){if(e.length<2)return k("compare requires two or more skill slugs.",t.json);if(e.length>5)return w({status:"error",reasonCode:"too_many_compare_slugs",requestedCount:e.length,maxItems:5,nextAction:"compare",nextStep:"Compare up to 5 skills at a time."},"compare supports up to 5 skill slugs at a time.",t.json,"too_many_compare_slugs");let i=new URLSearchParams({slugs:e.join(",")}),r=await S(n,`/api/v1/skills/compare?${i.toString()}`),s=Array.isArray(r.missing)?r.missing.filter(o=>typeof o=="string"):[];return s.length>0?w({...r,status:"not_found",reasonCode:"compare_missing_skills",missing:s,nextAction:"search",nextStep:`Run \`skills-layer search ${s[0]}\` to find the correct slug, then retry compare.`},`Comparison could not find: ${s.join(", ")}.`,t.json,"compare_missing_skills"):t.json?h(r,"Comparison loaded.",!0,n):{exitCode:0,stdout:hu(r,"Comparison loaded.",Q(n),t.verbose),stderr:""}}async function Ja(e,t,n){let i=b(e[0],"show requires a skill slug."),r=await S(n,`/api/v1/skills/${encodeURIComponent(i)}`);return h(Dl(r),"Skill loaded.",t.json,n)}async function Ya(e,t,n){let i=b(e[0],"trust requires a skill slug."),r=Gr("trust",t);if(r)return r;let s=new URLSearchParams;M(s,"format",t.format),M(s,"version",t.version);let o=await S(n,`/api/v1/skills/${encodeURIComponent(i)}/trust${ue(s)}`);return p(t.format)?.toLowerCase()==="sarif"&&!t.json?{exitCode:0,stdout:Gl(o,i,n),stderr:""}:h(o,"Trust report loaded.",t.json,n)}async function Za(e,t,n){if(t.json){let s=e[0]==="full"?$e():e[0]==="topic"?$e(e[1]):$e(e[0],e.slice(1));if(s)return h(s,"Help loaded.",!0,n);if(e[0]!=="topic"&&!Zo.has(e[0]??""))return kn(e,!0)}let i=ze(e[0],e.slice(1));if(i)return sn(i,e.filter(Boolean).join(" "),t,n);let r=e[0];if(!r)return{exitCode:0,stdout:He,stderr:""};if(r==="full")return sn(He,"full",t,n);if(r==="topic"){let s=ze(e[1]);if(s)return sn(s,e[1]??"overview",t,n);let o=new URLSearchParams;return e[1]&&o.set("topic",e[1]),await $(`/api/v1/help${ue(o)}`,t,n,"Help topic loaded.")}if(r==="standards")return await $("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let s=await S(n,"/api/v1/marketplace/status");return t.json?h(s,"Marketplace status loaded.",!0,n):h(Su(s),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let s=await S(n,"/api/v1/capabilities");return h(Cu(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=b(t.text,"help optimize-tokens requires --text."),o=_u(t.maxCharacters,t.json);if(J(o))return o;let a=await S(n,"/api/v1/optimize-tokens",{method:"POST",headers:j(n.apiKey),body:JSON.stringify({text:s,...o?{maxCharacters:o}:{}})});return h(a,"Token optimization complete.",t.json,n)}return k(`Unknown help command "${r}".`,t.json)}function sn(e,t,n,i){return n.json?h({status:"ok",topic:t,content:e},"Help topic loaded.",!0,i):{exitCode:0,stdout:e,stderr:""}}function kn(e,t){let n=e.filter(Boolean).join(" ").trim()||"help";return w({status:"not_found",reasonCode:"help_topic_not_found",topic:n,nextAction:"help",nextStep:"Run `skills-layer --help`, `skills-layer help full`, or `skills-layer <command> --help` for a supported command."},`Help topic not found: ${n}.`,t,"help_topic_not_found")}async function Qa(e,t,n){let i=b(e[0]??t.path,"validate requires a file or directory."),r=K(n.cwd,i);if(!await ce(r))return is("validate",i,t,n);let o={files:await Lt(r),sourceIntakeContext:p(t.sourceIntakeContext),publicationStatus:p(t.publicationStatus),dependencyAuditStatus:p(t.dependencyAuditStatus),category:p(t.category),discloseSource:!!t.discloseSource,allowFindingsFeatured:!!t.allowFindingsFeatured},a;try{a=await S(n,"/api/v1/validation/preview",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(x(o))})}catch(c){if(c instanceof A&&c.status===422&&c.details)a=rd(c.details);else throw c}return t.json?h(a,"Validation complete.",!0,n):{exitCode:0,stdout:xu(a,i,n),stderr:""}}async function Xa(e,t,n){let i=b(e[0]??t.path,"preview-trigger requires a file or directory."),r=K(n.cwd,i);if(!await ce(r))return is("preview-trigger",i,t,n);let s=await Lt(r),o=await S(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:j(n.apiKey),body:JSON.stringify({files:s,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?h(o,"Trigger preview complete.",!0,n):{exitCode:0,stdout:Ru(o,i,n),stderr:""}}async function el(e,t,n){let i=e[0];if(i==="init")return await tl(e.slice(1),t,n);if(i==="rules")return await $("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(i==="submissions")return await $("/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 $(`/api/v1/me/submissions/${encodeURIComponent(r)}/status`,t,n,"Submission status loaded.",{authenticated:!0})}catch(s){if(s instanceof A&&s.status===404)return ll(r,t);throw s}}if(i==="charge-status"){let r=b(e[1],"creator charge-status requires a charge id.");return await $(`/api/v1/me/private-skill-charges/${encodeURIComponent(r)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(i==="submit")return await ir(e.slice(1),t,n,!1);if(i==="submit-version")return await ir(e.slice(1),t,n,!0);if(i==="check-slug"){let r=b(e[1],"creator check-slug requires a slug.");return await ol(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."),o=Dr("creator.rename",s,t);return o||await jt(`/api/v1/me/submissions/${encodeURIComponent(r)}/slug`,{nextSkillSlug:s},t,n,"Skill renamed.")}if(i==="pricing")return await dl(e,t,n);if(i==="update-listing"){let r=b(e[1],"creator update-listing requires a skill slug.");return await pl(r,t,n)}if(i==="visibility"){let r=b(e[1],"creator visibility requires a skill slug."),s=we("creator.visibility",t);if(s)return s;let o=p(t.visibility)??e[2],a=pt(o);if(!a||!Ze.includes(a))return w({status:"error",reasonCode:"invalid_visibility",skillSlug:r,visibility:o??null,acceptedValues:Ze,nextAction:"creator.visibility",nextStep:"Use --visibility private, public, or unlisted."},`Invalid creator visibility "${o??""}". Use one of: ${Ze.join(", ")}.`,t.json,"invalid_visibility");let c=await S(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/visibility`,{method:"PATCH",headers:j(n.apiKey),body:JSON.stringify(x({visibility:a,dryRun:t.dryRun}))});return rc(c)?w(c,sc(c,r),t.json,l(c,"reasonCode")??l(c,"status")):h(c,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=Gr("creator.security-report",t);if(s)return s;let o=we("creator.security-report",t);if(o)return o;let a=new URLSearchParams;M(a,"format",t.format),M(a,"version",t.version),M(a,"versionId",t.versionId);let c=await S(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust${ue(a)}`,{headers:T(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?h(c,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:Ku(c,r,n),stderr:""}}if(i==="rescan-security"){let r=b(e[1],"creator rescan-security requires a skill slug."),s=we("creator.rescan-security",t);if(s)return s;let o=await S(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust/rescan`,{method:"POST",headers:j(n.apiKey),body:JSON.stringify(x(H(t,["version","versionId"])))});return t.json?h(o,"Security rescan requested.",!0,n):{exitCode:0,stdout:Du(o,r,n),stderr:""}}if(i==="provenance"){let r=b(e[1],"creator provenance requires a skill slug.");return await $(`/api/v1/me/submissions/${encodeURIComponent(r)}/provenance`,t,n,"Provenance loaded.",{authenticated:!0})}if(i==="claim"||i==="verify"||i==="dispute")return await gl(i,e,t,n);if(i==="issues"||i==="reviews"||i==="update-issue"||i==="moderate-review")return await vl(i,e,t,n);if(i==="analytics"){let r=b(e[1],"creator analytics requires a skill slug.");return await ml(r,t,n)}if(i==="earnings")return await $("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0});if(i==="payout-profile")return await fl(t,n);if(i==="payout-link")return await hl(t,n);if(i==="payouts")return await $("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0});if(i==="withdraw"){if(!p(t.amountCents))return k("creator withdraw requires --amount-cents.",t.json);let r=Ee(t.amountCents,"--amount-cents","amountCents","invalid_amount_cents",t,{minimum:1});return r.failure?r.failure:await O("/api/v1/me/payouts/withdrawals",x({amountCents:r.value,reason:p(t.reason)}),t,n,"Withdrawal requested.")}return i==="source"?await Pl(e.slice(1),t,n):k(`Unknown creator command "${i??""}".`,t.json)}async function tl(e,t,n){let i=p(t.skill)??e[0]??"my-skill",r=Dr("creator.init",i,t);if(r)return r;let s=K(n.cwd,p(t.dir)??i),o=E(s,"SKILL.md"),a;try{a=bi(p(t.type))}catch(m){return k(Z(m),t.json)}let c=p(t.category),u=await nl(s);if((await ce(o)||u)&&!t.confirmed)return k(`Creator init target already exists at ${s}. Re-run with --confirm only if you want to overwrite ${o}.`,t.json);await nt(s,{recursive:!0});let g=Si({skillSlug:i,description:p(t.description)??"Describe what this skill helps an agent do.",skillType:a,category:c});for(let m of g)await le(E(s,m.path),m.content);let f=x({status:"created",path:o,skillSlug:i,skillType:a,category:c,fileCount:g.length});return t.json?h(f,`Created ${o}.`,!0,n):{exitCode:0,stdout:Uu(f,s,o,n),stderr:""}}async function ce(e){try{return await jr(e),!0}catch{return!1}}async function nl(e){try{return(await Lr(e)).length>0}catch{return await ce(e)}}async function ir(e,t,n,i){let r=p(t.visibility);if(r){let C=pt(r);if(!C||!Ze.includes(C))return Pe(i?"creator.submit-version":"creator.submit","visibility",r,Ze,t,"invalid_visibility")}let s=Ee(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(s.failure)return s.failure;let o=i?b(p(t.skill)??e[0],"creator submit-version requires a skill slug."):p(t.skill),a=b(p(t.source)??(i?e[1]:e[0])??t.path,`creator ${i?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),c=await Rt(a,n.cwd);if(t.list)return await il(a,c,o,t,n);let u=we(i?"creator.submit-version":"creator.submit",t);if(u)return u;if(p(t.source)&&!c&&Ls(a))return rl(a,t);let d=c?.files??await Lt(K(n.cwd,a));if(!i&&!t.dryRun){let C=await sl(d,t,n);if(C)return C}let g=x({files:d,version:p(t.version),dryRun:t.dryRun,allowFindingsFeatured:t.allowFindingsFeatured,pricing:s.value!==void 0?{priceCents:s.value}:void 0,...c?{sourceMetadata:c.sourceMetadata}:{},...H(t,["displayName","skillType","category","visibility","source","skill"])}),f=i&&o?`/api/v1/me/submissions/${encodeURIComponent(o)}/versions`:"/api/v1/me/submissions",m=await S(n,f,{method:"POST",headers:j(n.apiKey),body:JSON.stringify(g)});if(t.json||t.noOpen||m.status!=="checkout_required"||typeof m.checkoutUrl!="string"||typeof m.chargeId!="string")return h(m,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(m.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${m.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let v=await Jc(m.chargeId,n);return J(v)?v:v.status!=="submitted"?h({...m,chargeStatus:v.status},`Payment is still ${v.status}. You can rerun \`skills-layer creator charge-status ${m.chargeId}\` to continue tracking it.`,t.json,n):h(v,i?"Version submitted.":"Submission uploaded.",t.json,n)}async function il(e,t,n,i,r){if(t)return h(rr(Wr(e,t,n)),"Source skills loaded.",i.json,r);let s=await Je(r,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},i);return s.kind==="failure"?s.result:h(rr(s.inspection),"Source skills loaded.",i.json,r)}function rr(e){return{...e,sourceSubmissionSupported:!0}}function rl(e,t){let i=`skills-layer source connection start --provider ${Xr(e)} --source ${e} --visibility private --provenance-intent private_source_import`;return w({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 sl(e,t,n){let i=p(t.skill)??cl(e);if(!i)return null;let r;try{r=await S(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(i)}`,{headers:T(n.apiKey,n.authBlockedMessage)})}catch(s){if(s instanceof A&&s.status===404)return Hr(i,t);throw s}if(r.available===!1||l(r,"reasonCode")==="unavailable"||l(r,"reasonCode")==="reserved"){let s=l(r,"assignedSlug"),o=x({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 w(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 ol(e,t,n){try{let i=await S(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:T(n.apiKey,n.authBlockedMessage)});return h(al(i),"Slug status loaded.",t.json,n)}catch(i){if(i instanceof A&&i.status===404)return Hr(e,t);throw i}}function Hr(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 w(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 al(e){let t=e.available===!0,n=l(e,"assignedSlug");if(t)return x({requestedSlug:l(e,"requestedSlug"),available:!0,reasonCode:l(e,"reasonCode")??"available",assignedSlug:n});let i=P(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 ll(e,t){return w({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 cl(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 ul(n??V(ne(t.path)))}function ul(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function dl(e,t,n){let i=b(e[1],"creator pricing requires a skill slug."),r=we("creator.pricing",t);if(r)return r;let s=new URLSearchParams;if(M(s,"version",t.version),!t.priceCents)return await $(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${ue(s)}`,t,n,"Pricing loaded.",{authenticated:!0});let o=Ee(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(o.failure)return o.failure;let a=o.value??0,c=await S(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${ue(s)}`,{headers:T(n.apiKey,n.authBlockedMessage)}),u=q(c,"priceCents")??0;if(a>u){let d=x({status:"pending_approval",reasonCode:u===0?"paid_activation_requires_approval":"price_increase_requires_approval",skillSlug:i,version:l(c,"version"),currentPriceCents:u,requestedPriceCents:a,currency:l(c,"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(d,"Pricing change requires approval before it can affect buyers.",t.json,n)}return await jt(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing`,{priceCents:a,version:p(t.version)},t,n,"Pricing updated.")}async function pl(e,t,n){let i=re("creator.update-listing","listingStatus",t.listingStatus,_a,t,"invalid_listing_status","listing-status");if(i)return i;try{return await jt(`/api/v1/me/submissions/${encodeURIComponent(e)}`,H(t,["displayName","summary","description","category","skillType","license","listingStatus"]),t,n,"Listing updated.")}catch(r){if(r instanceof A&&r.status===404){let s={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 w(s,`No editable creator listing was found for ${e}. Run \`skills-layer creator submissions\` to see listings you can update.`,t.json,"creator_listing_not_found_or_not_owned")}throw r}}async function gl(e,t,n,i){let r=b(t[1],`creator ${e} requires a skill slug.`);if(e==="claim"){let s=re("creator.claim","requestedRole",n.requestedRole,Ca,n,"invalid_requested_role","requested-role");if(s)return s}try{if(e==="claim")return await O(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/claim`,H(n,["requestedRole","message"]),n,i,"Ownership claim submitted.");if(e==="verify"){let s=b(n.claimId,"creator verify requires --claim-id.");return await O(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/verify`,{claimId:s},n,i,"Ownership claim verified.")}return b(n.message,"creator dispute requires --message."),await O(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/dispute`,H(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 w(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 ml(e,t,n){try{return await $(`/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 w(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 fl(e,t){let n=await S(t,"/api/v1/me/payout-profile",{headers:T(t.apiKey,t.authBlockedMessage)});return h(n,"Creator payout profile loaded.",e.json,t)}async function hl(e,t){let n=yl(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 S(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&&wl(s))return w({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=Yc(i);return r&&kl(e)&&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 yl(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 kl(e){return!e.json&&!e.noOpen}function wl(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 vl(e,t,n,i){let r=b(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await $(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await $(`/api/v1/me/submissions/${encodeURIComponent(r)}/reviews`,n,i,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let c=b(n.issueId,"creator update-issue requires --issue-id."),u=b(n.status,"creator update-issue requires --status."),d=re("creator.update-issue","status",u,xa,n,"invalid_issue_status");if(d)return d;let g=we("creator.update-issue",{...n,version:n.fixedVersion});if(g)return g;try{return await jt(`/api/v1/me/skills/${encodeURIComponent(r)}/issues/${encodeURIComponent(c)}`,H(n,["status","fixedVersion","note"]),n,i,"Issue updated.")}catch(f){if(f instanceof A&&f.status===404)return bl(r,c,n);throw f}}let s=b(n.reviewId,"creator moderate-review requires --review-id."),o=b(n.status,"creator moderate-review requires --status."),a=re("creator.moderate-review","status",o,Ra,n,"invalid_review_status");if(a)return a;try{return await O(`/api/v1/me/submissions/${encodeURIComponent(r)}/reviews/${encodeURIComponent(s)}/moderate`,H(n,["status","reason"]),n,i,"Review updated.")}catch(c){if(c instanceof A&&c.status===404)return Sl(r,s,n);throw c}}function bl(e,t,n){return w({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 Sl(e,t,n){return w({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 Pl(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"){let o=we("creator.source.prepare",t);if(o)return o;let a=re("creator.source.prepare","visibility",t.visibility,Ie,t,"invalid_visibility");if(a)return a;let c=Ee(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});return c.failure?c.failure:await O(`/api/v1/me/source-connections/${encodeURIComponent(r)}/prepare`,x({...H(t,["skill","source","version","displayName","skillType","category","visibility"]),...c.value!==void 0?{priceCents:c.value}:{},source:p(t.source)??e[2]}),t,n,"Source release prepared.")}if(i==="publish-request"){let o=we("creator.source.publish-request",t);if(o)return o;let a=re("creator.source.publish-request","visibility",t.visibility,Ie,t,"invalid_visibility");if(a)return a;let c=Ee(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(c.failure)return c.failure;let u=t.approvalRequestId.length>0?t.approvalRequestId:p(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await O(`/api/v1/me/source-connections/${encodeURIComponent(r)}/publish-request`,x({skillSlug:s,approvalRequestIds:u,version:p(t.version),...H(t,["visibility","license","discloseSource"]),...c.value!==void 0?{priceCents:c.value}:{}}),t,n,"Source publish requested.")}if(i==="release-status"){let o=new URLSearchParams;return s&&o.set("skill",s),await $(`/api/v1/me/source-connections/${encodeURIComponent(r)}/release-status${ue(o)}`,t,n,"Source release status loaded.",{authenticated:!0})}return k(`Unknown creator source command "${i??""}".`,t.json)}async function qn(e,t,n){let i=Vr("install",t);if(i)return i;let r=p(t.source);if(r){let u=p(t.skill),d=cr(r,u,t);if(d)return d;let g=await Rt(r,n.cwd);if(g)return await sr(r,g,u,t,n);let f=ur(r,t);if(f)return f;let m=t.list||t.dryRun||!u&&!t.json&&!t.all,y=await Je(n,r,{source:r,skillSlug:u,listOnly:m},t);if(y.kind==="failure")return y.result;let v=y.inspection;if(t.list)return h(v,"Source skills loaded.",t.json,n);let C=vn(r,v,t);if(C)return C;let _=await bt({source:r,inspection:v,requestedSkillSlug:u,mode:"install",flags:t,backend:n});if(_.kind==="failure")return _.result;if(t.dryRun)return h(wn(r,v,_.skillSlug,t),"Source install preview ready.",t.json,n);let L=or(t,n),de;try{de=await S(n,L,{method:"POST",headers:ar(t,n),body:JSON.stringify(dr({source:r},_.skillSlug,t))})}catch(Ft){if(Ft instanceof A)return pr(r,Ft,t);throw Ft}let U=await cn(n,de);return await Pt(n,U,_.skillSlug??l(U,"skillSlug")??r),St(U,lr(t),t.json,n)}let s=b(e[0]??t.install,"install requires a skill slug or --source.");if(Ls(s)){let u=cr(s,p(t.skill),t);if(u)return u;let d=await Rt(s,n.cwd);if(d)return await sr(s,d,p(t.skill),t,n);let g=ur(s,t);if(g)return g;let f=p(t.skill),m;if(t.list){let _=await Je(n,s,{source:s,listOnly:!0},t);return _.kind==="failure"?_.result:h(_.inspection,"Source skills loaded.",t.json,n)}if(!f&&!t.json&&!t.all){let _=await Je(n,s,{source:s,listOnly:!0},t);if(_.kind==="failure")return _.result;let L=_.inspection;m=L;let de=vn(s,L,t);if(de)return de;let U=await bt({source:s,inspection:L,requestedSkillSlug:f,mode:"install",flags:t,backend:n});if(U.kind==="failure")return U.result;f=U.skillSlug}if(t.dryRun){if(!m){let L=await Je(n,s,{source:s,listOnly:!0},t);if(L.kind==="failure")return L.result;m=L.inspection}let _=await bt({source:s,inspection:m,requestedSkillSlug:f,mode:"install",flags:t,backend:n});return _.kind==="failure"?_.result:(f=_.skillSlug,h(wn(s,m,f,t),"Source install preview ready.",t.json,n))}let y=or(t,n),v;try{v=await S(n,y,{method:"POST",headers:ar(t,n),body:JSON.stringify(dr({source:s},f,t))})}catch(_){if(_ instanceof A)return pr(s,_,t);throw _}let C=await cn(n,v);return await Pt(n,C,f??l(C,"skillSlug")??V(s)),St(C,lr(t),t.json,n)}if(p(t.scope)==="workspace"){let u=b(t.workspace,"workspace installs require --workspace <workspace-id>."),d=await S(n,`/api/v1/workspaces/${encodeURIComponent(u)}/skills`,{method:"POST",headers:j(n.apiKey),body:JSON.stringify(x({skillSlug:s,version:p(t.version),dryRun:t.dryRun}))});return t.dryRun?await es(d,"Workspace install preview ready.",t,n):h(d,"Workspace deployment requested.",t.json,n)}let o=await S(n,"/api/v1/install",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(x({skillSlug:s,version:p(t.version),scope:p(t.scope),agent:p(t.agent),dryRun:t.dryRun}))});if(t.dryRun)return await Ol(o,t,n);let a=await cn(n,o),c=await Cl(n,a,s,t);return J(c)?c:(await Pt(n,c,s),St(c,"Skill installed.",t.json,n))}async function Cl(e,t,n,i){if(Array.isArray(t.materializedWrites)&&t.materializedWrites.length>0)return t;let r=_l(e,t,n,i);if(r.status==="skip")return t;if(r.status==="failure")return w({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:r.skillSlug,nextStep:r.nextStep},r.message,i.json,"materialization_target_invalid");let s=await xl(e,t,r.skillSlug,r.version),o=await zr({backend:e,exportResult:s,flags:i,skillSlug:r.skillSlug});if(J(o))return o;let a=await Il({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,...Rl(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 _l(e,t,n,i){let r=P(t,"materializationPlan")??P(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)??ee(e.config?.lastSelectedAgent)??"codex",c=ke(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 xl(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 S(e,`/api/v1/me/library/${encodeURIComponent(n)}/export${ue(r)}`,{headers:T(e.apiKey,e.authBlockedMessage)})}function Rl(e){return x({version:l(e,"version"),storageKey:l(e,"storageKey"),expiresAt:l(e,"expiresAt")})}async function zr(e){let t=l(e.exportResult,"downloadUrl");if(!t)return w({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($l(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=Al(i),s=l(e.exportResult,"archiveSha256")??n.headers.get("x-skills-layer-archive-sha256")?.trim()??void 0;return s&&r.archiveSha256!==s?w({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?w({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 $l(e,t){return/^https?:\/\//iu.test(t)?t:`${te(e)}${t.startsWith("/")?"":"/"}${t}`}function Al(e){let t=$n("sha256").update(e).digest("hex"),n=fi(e);return n?{archiveSha256:hi(n),archiveBytesSha256:t,format:"bundle_archive",files:n}:{archiveSha256:t,archiveBytesSha256:t,format:"raw",files:[]}}async function Il(e){let t=e.backend.platform==="win32"?Ue:jn,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 xn(n,e.bytes),await An(i,{recursive:!0,force:!0}),await xn(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,...jl(o.path)),c=o.content??"";if(await le(a,c),s.push({path:Ct(e.backend.cwd,a),bytes:new TextEncoder().encode(c).length}),V(o.path).toLowerCase()==="skill.md"){let u=await zn({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 jl(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 sr(e,t,n,i,r){let s=p(i.visibility)??"private";if(s!=="private")return w({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=Wr(e,t,n);if(i.list)return h(o,"Local source skills loaded.",i.json,r);let a=vn(e,o,i);if(a)return a;let c=await bt({source:e,inspection:o,requestedSkillSlug:n,mode:"install",flags:i,backend:r});if(c.kind==="failure")return c.result;let u=c.skillSlug??rt(o)[0]?.value??Yr(e);if(i.dryRun)return h({...wn(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 S(r,"/api/v1/me/submissions",{method:"POST",headers:{"content-type":"application/json",...T(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 Ul({backend:r,source:e,upload:t,skillSlug:l(d,"skillSlug")??u,flags:i,submitted:d});return await Pt(r,g,u),St(g,"Private Cloud skill installed.",i.json,r)}function Wr(e,t,n){let i=El(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 El(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=ne(t.path).replaceAll("\\","/"),i=n==="."?".":n,r=Jr(t.content??"")??Yr(i==="."?t.path:i),s=Ll(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 Jr(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function Ll(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function Yr(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 Ul(e){let t=Tl(e.backend,e.flags);if(t.status==="failure")throw new Error(t.message);let n=e.upload.files.map(r=>({path:E(t.skillsPath,e.skillSlug,vs(r.path)),content:r.content??""})),i=[];for(let r of n)if(await le(r.path,r.content),i.push({path:Ct(e.backend.cwd,r.path),bytes:new TextEncoder().encode(r.content).length}),V(r.path).toLowerCase()==="skill.md"){let s=await zn({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 Tl(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)??ee(e.config?.lastSelectedAgent)??"codex",r=ke(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=Xe(e,t);return n&&!n.startsWith("..")&&!Ue.isAbsolute(n)?n.split("\\").join("/"):t}function On(e){return p(e.visibility)==="public"?"public":"private"}function or(e,t){return On(e)==="public"&&!t.apiKey?"/api/v1/source-imports":"/api/v1/me/source-installs"}function ar(e,t){return{"content-type":"application/json",...On(e)==="private"?T(t.apiKey,t.authBlockedMessage):Ne(t.apiKey)}}function lr(e){return On(e)==="public"?"Public source install planned.":"Private source skill installed."}async function bt(e){let t=rt(e.inspection);if(e.requestedSkillSlug)return t.length>0&&!t.some(n=>n.value===e.requestedSkillSlug)?{kind:"failure",result:Nl(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: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 cr(e,t,n){if(n.all&&t)return w({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 ur(e,t){try{if(ut(e).kind!=="local")return}catch{return}return w({status:"error",reasonCode:"invalid_source",source:e,nextAction:"install",nextStep:_t(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."},_t(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 Nl(e,t,n,i){return w({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 rt(e){let t=[e.results,e.skills,e.discoveredSkills,P(e,"source")?.results,P(e,"inspection")?.results],n=new Set,i=[];for(let r of t)if(Array.isArray(r))for(let s of r){let o=Fl(s);!o||n.has(o.value)||(n.add(o.value),i.push(o))}return i}function Fl(e){if(!R(e))return;let t=l(e,"skillSlug")??l(e,"slug")??l(e,"name");if(!t)return;let n=l(e,"displayName")??l(e,"title")??l(e,"name"),i=n&&n!==t?`${t} - ${n}`:t,r=P(e,"parsedSkill"),s=P(e,"frontmatter")??(r?P(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 dr(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 wn(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:rt(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 Je(e,t,n,i){try{return{kind:"ok",inspection:await S(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:Ml(t,r,i)};throw r}}function vn(e,t,n){if(rt(t).length>0)return null;let r=Bl(t);return w({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."},ql(e,r),n.json)}function Bl(e){return(Array.isArray(e.issues)?e.issues:[]).filter(R).map(n=>({...l(n,"code")?{code:l(n,"code")}:{},...l(n,"message")?{message:l(n,"message")}:{},...l(n,"path")?{path:l(n,"path")}:{}}))}function Ml(e,t,n){let i=t.details??{},r=l(i,"error")??t.message;if(Zr(t.status,r))return Qr(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return Ut(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 w(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 pr(e,t,n){let i=t.details??{},r=l(i,"error")??t.message;if(Zr(t.status,r))return Qr(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return Ut(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 w(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 Zr(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function Qr(e,t,n,i){let r=t.details??{},s=l(r,"error")??t.message,a=`skills-layer source connection start --provider ${Xr(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 w(c,`Cloud could not ${i} ${e} directly. If this is a private source, start a private source connection first:
|
|
1236
|
-
${a}`,n.json,"private_source_access_required")}function
|
|
1237
|
-
`)}async function
|
|
1238
|
-
`)}function
|
|
1239
|
-
`)}function
|
|
1240
|
-
`)}function
|
|
1241
|
-
`)):(e.results.slice(0,
|
|
1242
|
-
`))}function
|
|
1243
|
-
`)}function
|
|
1244
|
-
`)}function
|
|
1245
|
-
Next step: ${o}`}async function oc(e,t,n){let i=await Ce(n),r=b(e[0],"restore requires a skill slug."),s=i.installs[r];if(!s)return w({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:ic(r,s,n),stderr:""}}async function ac(e,t,n){let i=b(e[0],"check requires a skill slug.");return await $(`/api/v1/skills/${encodeURIComponent(i)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function lc(e,t,n){let i=b(e[0]??t.source,"import requires a source."),r=re("import","visibility",t.visibility,Ie,t,"invalid_visibility");if(r)return r;let s=await Rt(i,n.cwd);if(!s){let a=cc(i,t);if(a)return a}let o=await S(n,"/api/v1/source-imports",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(x({...s??{source:i},quarantine:t.quarantine,skillSlug:p(t.skill),visibility:p(t.visibility)}))});return await W(n.paths.importsPath,{version:1,lastImport:o,savedAt:n.now()}),h(o,"Source import submitted.",t.json,n)}function cc(e,t){try{return ut(e).kind!=="local"?null:w({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:_t(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."},_t(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 w({status:"error",reasonCode:"invalid_source",source:e,error:Z(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${Z(n)}`,t.json,"invalid_source")}}function _t(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}function is(e,t,n,i){let r=K(i.cwd,t);return w({status:"error",reasonCode:"source_path_not_found",path:r,nextAction:e,nextStep:`Check that ${t} exists and contains a readable SKILL.md, then retry.`},`${e} source path does not exist: ${r}`,n.json,"source_path_not_found")}async function uc(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 S(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(r)}`);return s.status==="not_found"?w({...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 dc(e.slice(1),t,n):k(`Unknown source command "${e.join(" ")}".`,t.json)}async function dc(e,t,n){let i=e[0];if(i==="start"){let s=p(t.provider),o=p(t.source),a=p(t.visibility),c=s?.replace(/-/gu,"_");if(c&&!Ji.includes(c))return Pe("source.connection.start","provider",s??"",Ji,t,"invalid_source_provider");let u=Ee(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(u.failure)return u.failure;let d=pc(s,o,a,t);return d||await O("/api/v1/me/source-connections",H(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.`);if(i==="status")return await $(`/api/v1/me/source-connections/${encodeURIComponent(r)}`,t,n,"Source connection loaded.",{authenticated:!0});if(i==="complete"){let s=Oa("source.connection.complete",t);return s||await O(`/api/v1/me/source-connections/${encodeURIComponent(r)}/complete`,H(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed.")}return i==="cancel"?await O(`/api/v1/me/source-connections/${encodeURIComponent(r)}/cancel`,{},t,n,"Source connection cancelled."):k(`Unknown source connection command "${i??""}".`,t.json)}function pc(e,t,n,i){if(n){let r=pt(n);if(!r||!Ie.includes(r))return w({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:Ie,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${Ie.join(", ")}.`,i.json,"invalid_visibility")}if(!e||!t)return null;try{let r=ut(t);if((e==="github"||e==="gitlab")&&r.kind!==e)return on(e,t,i);if(e==="domain"){let s=new URL(t);if(s.protocol!=="https:"||!s.hostname)return on(e,t,i)}}catch{return on(e,t,i)}return null}function on(e,t,n){return w({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 gc(e,t,n){if(e[0]!=="request")return k(`Unknown approval command "${e[0]??""}".`,t.json);let i=e[1];if(i!=="status"&&i!=="complete")return k("approval request requires `status <approval-request-id>` or `complete <approval-request-id> --decision <approved|denied>`.",t.json);let r=b(e[2],`approval request ${i??""} requires an approval id.`);if(i==="status")return await $(`/api/v1/me/approvals/${encodeURIComponent(r)}`,t,n,"Approval status loaded.",{authenticated:!0});let s=b(t.decision,"approval request complete requires --decision."),o=re("approval.request.complete","decision",s,Aa,t,"invalid_decision");return o||await O(`/api/v1/me/approvals/${encodeURIComponent(r)}/complete`,x({decision:s,evidence:Tt(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed.")}async function mc(e,t,n){let i=e[0]??"list";if(i==="list")return await $("/api/v1/me/workspaces",t,n,"Workspaces loaded.",{authenticated:!0});if(i==="create"){let s=e.slice(1).join(" ").trim();if(!s)return k("workspace create requires a workspace name.",t.json);let o=re("workspace.create","kind",t.kind,Ea,t,"invalid_workspace_kind");if(o)return o;let a=p(t.kind);return await O("/api/v1/workspaces",{name:s,kind:a==="team"?"shared":a},t,n,"Workspace created.")}let r=b(e[1],`workspace ${i} requires a workspace id.`);if(i==="skills")try{return await $(`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0})}catch(s){if(s instanceof A&&(s.status===403||s.status===404))return an(r,t);throw s}if(i==="deploy"){let s=b(e[2],"workspace deploy requires a skill slug."),o;try{o=await S(n,`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,{method:"POST",headers:j(n.apiKey),body:JSON.stringify(x({skillSlug:s,dryRun:t.dryRun}))})}catch(a){if(a instanceof A&&(a.status===403||a.status===404))return an(r,t);throw a}return t.dryRun?await es(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 Et(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}`,{method:"DELETE",headers:T(n.apiKey,n.authBlockedMessage)},t,n,"Workspace skill removed.")}catch(o){if(o instanceof A&&o.status===404)return mr(r,s,t);if(o instanceof A&&o.status===403)return an(r,t);throw o}}if(i==="guide"){let s=b(e[2],"workspace guide requires a skill slug.");try{return await $(`/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 mr(r,s,t);throw o}}return k(`Unknown workspace command "${i}".`,t.json)}function an(e,t){return w({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 mr(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 w(i,`Workspace deployment not found for ${t}. Run \`skills-layer workspace deploy ${e} ${t}\` first.`,n.json,"workspace_deployment_not_found")}async function fc(e,t,n){let i=b(e[0],"buy requires a skill slug."),r=Va(t);if(r.failure)return r.failure;let s=await S(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||t.noOpen||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 Wc(s.purchaseId,n);return J(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 qn([i],t,n))}async function hc(e,t,n){let i=e[0]??"list";if(i==="list")return await $("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(i==="spending")return await $("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let r=b(e[1],`purchases ${i} requires a purchase id.`);return i==="invoice"?await $(`/api/v1/purchases/${encodeURIComponent(r)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0}):i==="refund-quote"?await $(`/api/v1/purchases/${encodeURIComponent(r)}/refund-quote`,t,n,"Refund quote loaded.",{authenticated:!0}):i==="refund"?await O(`/api/v1/purchases/${encodeURIComponent(r)}/refund`,H(t,["reason"]),t,n,"Refund requested."):k(`Unknown purchases command "${i}".`,t.json)}async function yc(e,t,n){let i=e[0];if(i==="add"){let r=b(e[1],"library add requires a skill slug.");return await O("/api/v1/install",{skillSlug:r},t,n,"Skill added to library.")}return k(`Unknown library command "${i}".`,t.json)}async function kc(e,t,n){let i=b(e[0],"export requires a skill slug.");if(t.showUrl&&p(t.output))return w({status:"error",reasonCode:"conflicting_export_output",nextAction:"export",nextStep:"Use either --show-url to inspect the signed URL or --output <file> to download the bundle, not both."},"export cannot use --show-url and --output together.",t.json,"conflicting_export_output");let r=new URLSearchParams,s=p(t.version);if(s&&!At(s))return Mn("export",s,t);M(r,"version",s);let o=await S(n,`/api/v1/me/library/${encodeURIComponent(i)}/export${ue(r)}`,{headers:T(n.apiKey,n.authBlockedMessage)}),a=p(t.output);if(a){let c=await zr({backend:n,exportResult:o,flags:t,skillSlug:i});if(J(c))return c;let u=K(n.cwd,a);await xn(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 fr(e,t,n,i){let r=b(t[0],`${e==="add"?"add-review":"show-reviews"} requires a skill slug.`);if(e==="show")return await $(`/api/v1/me/library/reviews?skillSlug=${encodeURIComponent(r)}`,n,i,"Reviews loaded.",{authenticated:!0});let s=b(n.rating,"add-review requires --rating.");return/^[1-5]$/u.test(s)?await O(`/api/v1/me/library/${encodeURIComponent(r)}/review`,H(n,["rating","feedback"]),n,i,"Review added."):w({status:"error",reasonCode:"invalid_rating",rating:s,acceptedValues:["1","2","3","4","5"],nextAction:"add-review",nextStep:"Use --rating with a whole number from 1 to 5."},`Invalid review rating "${s}". Use a whole number from 1 to 5.`,n.json,"invalid_rating")}async function hr(e,t,n,i){let r=b(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);if(e==="show")return await $(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0});b(n.message,"add-issue requires --message.");let s=re("add-issue","issueType",n.issueType,$a,n,"invalid_issue_type","issue-type");return s||await O(`/api/v1/me/library/${encodeURIComponent(r)}/report-issue`,H(n,["issueType","message"]),n,i,"Issue reported.")}async function wc(e,t,n){let i=e[0];if(i==="hook"){let r=e[1];return r==="install"?await ss(t,n):r==="status"?await Pc(t,n):k(`Unknown guardian hook command "${r??""}".`,t.json)}if(i==="enable")return e[1]||t.skill?await ln("enforce",e,t,n):k("guardian enable requires a skill slug.",t.json);if(i==="disable")return await ln("disabled",e,t,n);if(i==="enable-warnings-only")return await ln("warning_only",e,t,n);if(i==="status")return await bc(e,t,n);if(i==="exec")return await vc(e,t,n);if(i==="check"){let r=b(e[1]??t.skill,"guardian check requires a skill slug."),s=Cr(t,"check"),o=t.grantJson.map(y=>Qn(y,"grant-json")),a=id(t.cloudTrustLedger);if(a.status==="invalid")return k(a.message,t.json);let c=bn(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(c.status==="invalid")return k(c.message,t.json);let u=await as({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 Gn(n,r),unmanagedPolicy:u.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:c.mode,localPreflight:Se(u.context)}),m=await S(n,"/api/v1/guardian/enforce",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(f)});return await Qe(n,{skillSlug:r,version:g,action:s,decisionStatus:xt(m),reasonCode:Sn(m),telemetryMode:c.mode,path:d}),h({...m,localPreflight:Se(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=bn(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return k(o.message,t.json);let a=p(t.path);if(a&&!await ce(K(n.cwd,a)))return w({status:"error",reasonCode:"invalid_incident_path",path:a,nextAction:"guardian.incident",nextStep:"Use --path with an installed skill directory, or omit --path so Skills Layer resolves the local install record."},`Guardian incident path does not exist: ${a}`,t.json,"invalid_incident_path");let c=a??(await ls({skillSlug:r,flags:t,backend:n})).installedPath,u=Cr(t,"incident"),d=Tt(t.evidenceJson,"evidence-json"),g=o.mode==="cloud_managed"&&!n.apiKey?"local_only":o.mode,f=x({skillSlug:r,version:s,action:u,evidence:d,path:c,telemetryMode:g,incident:!0,reason:p(t.reason)});if(g==="local_only"){if(!c)return k("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let C=await br({backend:n,skillSlug:r,version:s,installedPath:c,action:u,reason:p(t.reason)??"Guardian local-only incident"});await Qe(n,{skillSlug:r,version:s,action:u,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:g,path:c});let _=Sr(n,r);return await le(_,JSON.stringify({request:f,response:null,localResponse:C,savedAt:n.now()},null,2)),h({status:"written",skillSlug:r,version:s,telemetryMode:g,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:C,incidentStatePath:_,incidentPath:C.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let m=await S(n,"/api/v1/guardian/enforce",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(f)}),y=c?await br({backend:n,skillSlug:r,version:s,installedPath:c,action:u,reason:p(t.reason)??"Guardian Cloud-managed incident"}):null;await nt(n.paths.incidentsDir,{recursive:!0});let v=Sr(n,r);return await le(v,JSON.stringify({request:f,response:m,localResponse:y,savedAt:n.now()},null,2)),await Qe(n,{skillSlug:r,version:s,action:u,decisionStatus:xt(m),reasonCode:Sn(m),telemetryMode:o.mode,path:c}),h({...m,telemetryMode:o.mode,localResponse:y,incidentPath:v},"Guardian incident recorded.",t.json,n)}return k(`Unknown guardian command "${i??""}".`,t.json)}async function vc(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 k("guardian exec requires a command after --.",t.json);let o=bn(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return k(o.message,t.json);let a=jc(t,s),c=await as({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=x({skillSlug:r,version:d,action:a,authorizationGrants:t.grantJson.map(C=>Qn(C,"grant-json")),path:u,guardianPreference:await Gn(n,r),telemetryMode:o.mode,localPreflight:Se(c.context)}),f=await S(n,"/api/v1/guardian/enforce",{method:"POST",headers:j(n.apiKey),body:JSON.stringify(g)}),m=xt(f),y=Sn(f);if(await Qe(n,{skillSlug:r,version:d,action:a,decisionStatus:m,reasonCode:y,telemetryMode:o.mode,path:u}),!Ec(f))return w({status:"blocked",reasonCode:y,skillSlug:r,guardian:f,localPreflight:Se(c.context),command:{executable:V(s[0]??""),executed:!1}},"Guardian blocked guarded execution.",t.json,y);if(t.dryRun)return h({status:"allowed",skillSlug:r,guardian:f,localPreflight:Se(c.context),command:{executable:V(s[0]??""),executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let v=await Lc(s,n);return{exitCode:v.exitCode,stdout:t.json?JSON.stringify({status:v.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:r,guardian:f,localPreflight:Se(c.context),command:v},warnings:[],links:[],reasonCode:v.exitCode===0?null:"command_failed",handoff:null},null,2):Uc(v),stderr:v.stderr}}async function ln(e,t,n,i){let r=b(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),s=await S(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 Tc(i,r,s),h(s,s.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,i)}async function bc(e,t,n){let i=p(t.skill)??p(e[1]),r;try{r=await rs(n,i)}catch(d){r={status:"unavailable",skillSlug:i,policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:Z(d),nextAction:"guardian.status",nextStep:"Cloud Guardian policy could not be loaded. Local hook and preference posture are still shown below."}}let s=await Te(n),o=i?await Nc(n,i):void 0,a=l(r,"status")==="unavailable",u=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(x({status:a?"degraded":"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:u,nextAction:l(u,"nextAction"),nextStep:l(u,"nextStep")}),a?"Guardian status loaded with limited Cloud policy data.":"Guardian status loaded.",t.json,n)}async function rs(e,t){let n=t?await Gn(e,t):void 0;return await S(e,"/api/v1/guardian/status",{method:"POST",headers:j(e.apiKey),body:JSON.stringify(x({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function Sc(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 rs(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:Z(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function ss(e,t){let n=p(e.agent)??"codex",i=us(e.scope);if(i.status==="invalid")return k(i.message,e.json);let r=ke(t.env,t.platform,t.cwd).find(g=>g.id===n);if(!r)return w({status:"error",reasonCode:"unknown_agent",agent:n,nextAction:"agents.list",nextStep:"Run `skills-layer agents list` to see supported agents, then retry Guardian hook install with a supported --agent value."},`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json,"unknown_agent");let s=Fc(r,i.scope,t);if(!s)return k(`Guardian ${i.scope} hooks are not available for ${r.displayName}.`,e.json);await Bc(s,t);let o=gs(t,i.scope),a=Pr(Xe(t.cwd,s.hookPath)),c=Pr(Xe(t.cwd,s.configPath)),d=[...(await ms(o)).hooks.filter(g=>l(g,"agent")!==r.id||l(g,"scope")!==i.scope),{hookId:ye,hookName:ie,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 W(o,{version:1,hooks:d}),h({status:"enabled",hookId:ye,hookName:ie,agent:r.id,agentName:r.displayName,scope:i.scope,hookPath:s.hookPath,configPath:s.configPath,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,agentCommandMatrix:Wt({purpose:"materialize_skill",command:"skills-layer install <skill-slug>",jsonCommand:"skills-layer install <skill-slug> --json"}),nextStep:"Guardian is installed into the selected host configuration. Local hooks call `skills-layer guardian check`; shell agents can route risky commands through `skills-layer guardian exec`; MCP-capable agents can call `guardian.check` or `guardian.enforce` before risky tool use.",warnings:s.enforcementLayer==="native_hook_candidate"?["This host does not expose the same stable native hook contract as Codex or Claude Code yet; Skills Layer records the guardrail config for host integration."]:[]},"Guardian hook enabled.",e.json,t)}async function Pc(e,t){let n=p(e.scope),i=n?us(n):null;if(i?.status==="invalid")return k(i.message,e.json);let r=await Te(t,i?.status==="valid"?i.scope:void 0);return h(r,"Guardian status loaded.",e.json,t)}async function Te(e,t){let n=t?[t]:["project","global"],i=[];for(let a of n){let c=gs(e,a),u=await ms(c);for(let d of u.hooks){let g=l(d,"hookPath"),f=g?vr(e,a,g):null,m=l(d,"configPath"),y=m?vr(e,a,m):null,v=f?await ce(f):!1,C=y?await ce(y):null,_=v?C===!1?"active_missing_config":"active":"stale_missing_hook";i.push({hookId:l(d,"hookId")??ye,hookName:l(d,"hookName")??ie,...d,scope:l(d,"scope")??a,hookPath:f??g??null,configPath:y??m??null,active:v,configActive:C,hookState:_})}}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 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 os(e,t){if(e.json){let u=await D(t.paths.mcpConfigPath);return h({setup:await Vn(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 Te(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:xc(t.now(),7)};return await wr(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 Fn(e,t);if(J(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 ss(u,t);if(d.exitCode!==0)return d;s.security=Vc(d.stdout)??{status:"enabled",agent:p(u.agent),scope:p(u.scope)}}await wr(t,o);let c=(R(s.mcp)?l(s.mcp,"status"):void 0)==="login_required"?"Skills Layer Security setup complete. MCP setup needs login; run `skills-layer login`, then `skills-layer setup`.":"Skills Layer setup complete. Open a fresh agent session if MCP tools are not visible yet.";return h(s,c,e.json,t)}async function Cc(e,t){let n=await Te(t),i=await Vn(t),r=q(n,"activeHookCount")??0;if(t.stdoutIsTty&&r===0&&!i)return await os(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:`${He}
|
|
1246
|
-
|
|
1247
|
-
${s}`,stderr:""}}function
|
|
1248
|
-
[output truncated]`:e}function
|
|
1249
|
-
`)}function
|
|
1239
|
+
skills-layer api-key revoke --key-id <key-id>`,t.json,"missing_required_argument");let s=String(r);if(t.dryRun){let a=await Ar(s,n);return a?h(_({status:"pass",wouldRevoke:!0,keyId:s,keyPrefix:l(a,"keyPrefix"),type:l(a,"type"),name:l(a,"name"),scopes:ue(a,"scopes")??[],revokedAt:a.revokedAt??null,nextAction:"api-key.revoke",nextStep:`Run \`skills-layer api-key revoke --key-id ${s} --yes\` to revoke this key.`}),"API key revoke dry run passed.",t.json,n):Er(s,t)}if(!t.confirmed){let a=await Ar(s,n);if(!a)return Er(s,t);let c=_({status:"confirmation_required",reasonCode:"confirmation_required",keyId:s,keyPrefix:l(a,"keyPrefix"),type:l(a,"type"),name:l(a,"name"),nextAction:"api-key.revoke",nextStep:`Re-run with \`skills-layer api-key revoke --key-id ${s} --yes\` after confirming this is the key to revoke.`});if(t.json||!n.stdoutIsTty)return w(c,"API key revoke needs confirmation. Re-run with --yes after checking the key id.",t.json,"confirmation_required");if(await n.promptSelect(`Revoke API key ${s}?`,[{value:"cancel",label:"Cancel",description:"Leave this API key active"},{value:"confirm",label:"Revoke",description:"Permanently revoke this API key"}])!=="confirm")return h({status:"canceled",keyId:s},"API key revoke canceled.",t.json,n)}let o=await S(n,`/api/v1/me/api-keys/${encodeURIComponent(s)}/revoke`,{method:"POST",headers:F(n.apiKey,n.authBlockedMessage)});return h(o,"API key revoked.",t.json,n)}return k(`Unknown api-key command "${i}".`,t.json)}function Ul(e){let t=p(e.type);if(t&&!Fr.includes(t))return{failure:je("api-key.list","type",t,Fr,e,"invalid_api_key_filter","type")};let n=p(e.status)??"active";if(!Nr.includes(n))return{failure:je("api-key.list","status",n,Nr,e,"invalid_api_key_filter","status")};let i=p(e.sort)??"created-desc";if(!Mr.includes(i))return{failure:je("api-key.list","sort",i,Mr,e,"invalid_api_key_filter","sort")};let r=[["createdAfter","created-after",e.createdAfter],["createdBefore","created-before",e.createdBefore],["expiresAfter","expires-after",e.expiresAfter],["expiresBefore","expires-before",e.expiresBefore]],s={status:n,sort:i};for(let[o,a,c]of r){let u=p(c);if(u){if(Number.isNaN(Date.parse(u)))return{failure:w({status:"error",reasonCode:"invalid_api_key_filter",field:a,value:u,nextAction:"api-key.list",nextStep:`Use --${a} with an ISO date or timestamp.`},`Invalid api-key list --${a} "${u}". Use an ISO date or timestamp.`,e.json,"invalid_api_key_filter")};s[o]=u}}return{filters:_({...s,...t?{type:t}:{},...p(e.name)?{name:p(e.name)}:{}})}}function Dn(e){return(we(e,"results")??[]).filter(t=>x(t))}function Tl(e,t){let n=t.name?.toLowerCase();return e.filter(i=>!t.type||l(i,"type")===t.type).filter(i=>t.status==="all"||_s(i)===t.status).filter(i=>!n||(l(i,"name")??l(i,"id")??"").toLowerCase().includes(n)).filter(i=>At(i,"createdAt",t.createdAfter,"after")).filter(i=>At(i,"createdAt",t.createdBefore,"before")).filter(i=>At(i,"expiresAt",t.expiresAfter,"after")).filter(i=>At(i,"expiresAt",t.expiresBefore,"before")).sort((i,r)=>Fl(i,r,t.sort))}function _s(e,t=Date.now()){if(e.revokedAt!==null&&e.revokedAt!==void 0)return"revoked";let n=l(e,"expiresAt");if(!n)return"active";let i=Date.parse(n);return Number.isNaN(i)||i>t?"active":"expired"}function At(e,t,n,i){if(!n)return!0;let r=l(e,t);if(!r)return!1;let s=Date.parse(r),o=Date.parse(n);return Number.isNaN(s)||Number.isNaN(o)?!1:i==="after"?s>=o:s<=o}function Fl(e,t,n){if(n==="name-asc"||n==="name-desc")return(n==="name-asc"?1:-1)*(l(e,"name")??l(e,"id")??"").localeCompare(l(t,"name")??l(t,"id")??"");let i=n.endsWith("-asc")?1:-1,r=n.startsWith("expires-")?"expiresAt":n.startsWith("last-used-")?"lastUsedAt":"createdAt";return i*($r(e,r)-$r(t,r))}function $r(e,t){let n=l(e,t);if(!n)return 0;let i=Date.parse(n);return Number.isNaN(i)?0:i}function Nl(e,t){if(!e)return;let n=/^(\d+)d$/iu.exec(e.trim());if(!n)return;let i=Date.parse(t),r=Number.isNaN(i)?Date.now():i;return new Date(r+Number.parseInt(n[1],10)*24*60*60*1e3).toISOString()}async function Ar(e,t){let n=await S(t,"/api/v1/me/api-keys",{headers:F(t.apiKey,t.authBlockedMessage)});return Dn(n).find(i=>l(i,"id")===e)}function Er(e,t){return w({status:"not_found",reasonCode:"api_key_not_found",keyId:e,nextAction:"api-key.list",nextStep:"Run `skills-layer api-key list` to find an active key id, then retry revoke."},`API key ${e} was not found.`,t.json,"api_key_not_found")}async function Ml(e,t,n){let i=e[0]??"status";if(i==="setup"||i==="repair"){let r=p(t.client)??p(t.agent);if(r&&t.all)return w({status:"error",reasonCode:"conflicting_mcp_client_selection",client:r,all:!0,nextAction:`mcp.${i}`,nextStep:"Use either --client <agent-id> for one agent or --all for every detected MCP-capable agent."},`mcp ${i} cannot use --client and --all together.`,t.json,"conflicting_mcp_client_selection");if(r&&!ct(r))return $n(r,t);if(r){let o=await W(n.paths.mcpConfigPath),a=o?l(o,"baseUrl")??n.baseUrl:n.baseUrl,c=await tt({baseUrl:a,mcpUrl:o?l(o,"mcpUrl")??`${a}/mcp`:`${a}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:o?l(o,"environment")??pe(a):pe(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:o});if(c.target.status==="skills_only"){let u=Et(c);return h(u,`${c.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}}let s=await gi(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&&!ct(r))return $n(r,t);let s=await W(n.paths.mcpConfigPath);if(!s){if(r){let u=await tt({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:pe(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:null});if(u.target.status==="skills_only"){let d=Et(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 tt({baseUrl:a,mcpUrl:l(s,"mcpUrl")??`${a}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:o,environment:l(s,"environment")??pe(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=Et(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 Di({nodePath:process.execPath,bridgePath:c.bridge.path}),d={...c,verified:u.status==="ok",liveProbe:u};return u.status!=="ok"?w(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(!ct(r))return $n(r,t);let s=await W(n.paths.mcpConfigPath),o=s?l(s,"baseUrl")??n.baseUrl:n.baseUrl,a=await tt({baseUrl:o,mcpUrl:s?l(s,"mcpUrl")??`${o}/mcp`:`${o}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:s?l(s,"environment")??pe(o):pe(o),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:s});if(a.target.status==="skills_only"){let d=Et(a);return h(d,`${a.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}let c=et({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:pe(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath}),u=c.targets.find(d=>d.agentId===r);return await ql(s,n),await u?.disconnect?.(),await Vi(c.bridgePath),await Gi(c.brokerPath,c.brokerSocketPath),await ri(n.paths.mcpConfigPath,{force:!0}),h({status:"mcp_disconnected",configured:!1,clientId:r},"MCP disconnected on this machine.",t.json,n)}return k(`Unknown mcp command "${i}". Use setup, status, verify, repair, or disconnect.`,t.json)}function ct(e){return Re.includes(e)}function $n(e,t){return w({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 Et(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 gi(e,t){let n=p(e.environment)??pe(t.baseUrl),i=["mcp:use","catalog:read","library:read","guardian:check","guardian:incident","creator:read"],r=`${t.baseUrl}/mcp`,s=et({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 Bl(e,t,s),a=o.clientIds[0]??"codex",c=et({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 y=await S(t,"/api/v1/me/mcp-tokens",{method:"POST",headers:I(t.apiKey),body:JSON.stringify({clientId:m,environment:n,scopes:i})}),v=l(y,"apiKey");if(!v)return k("MCP setup did not receive a token from the backend.",e.json);let P=await Ol(t,{token:v,clientId:m,environment:n});u[m]={clientId:m,environment:n,...P,tokenPrefix:l(y,"keyPrefix")??null,scopes:Array.isArray(y.scopes)?y.scopes:[],savedAt:t.now()},d??=y}let g=u[a]??{};await ee(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{...Y(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 Bl(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 ji({env:t.env,platform:t.platform,cwd:t.cwd,pathExists:me}),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 Ol(e,t){if(!e.credentialStore)return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"};let n=Kl({baseUrl:e.baseUrl,userId:e.config?.userId,email:e.config?.email,clientId:t.clientId,environment:t.environment});try{return await e.credentialStore.set(st,n,t.token),{tokenRef:n,credentialStorage:"macos_keychain",credentialService:st,tokenStorage:"macos_keychain"}}catch{return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}}async function ql(e,t){if(!e||!t.credentialStore)return;let n=Dl(e,st);for(let i of n)await t.credentialStore.delete(i.service,i.tokenRef)}function Dl(e,t){let n=new Map;Ir(e,t,n);let i=e.tokens;if(x(i))for(let r of Object.values(i))x(r)&&Ir(r,t,n);return[...n.values()]}function Ir(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 Kl(e){let t=[e.baseUrl,e.userId??e.email??"unknown-user",e.clientId,e.environment,"mcpToken"].join(`
|
|
1240
|
+
`);return`skills-layer-cli:mcp-token:${ni("sha256").update(t).digest("base64url").slice(0,32)}`}async function Kn(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 W(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 W(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 ee(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 gi(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 Vl(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&&!jr.includes(s))return jt("runtime-risk",s,jr,t);let o=p(t.agent);if(o&&!ct(o))return w({status:"error",reasonCode:"unknown_agent",filter:"agent",value:o,acceptedValues:Re,nextAction:"search",nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown search --agent "${o}". Run \`skills-layer agents list\` to inspect supported agents.`,t.json,"unknown_agent");let a=p(t.trust);if(a&&!Lr.includes(a))return jt("trust",a,Lr,t);let c=p(t.securityCapability),u=sc(c);if(c&&!u)return jt("security-capability",c,xs,t);let d=p(t.limit);if(d){let f=Number(d);if(!Number.isInteger(f)||f<1||f>100)return jt("limit",d,["1-100"],t);r.set("limit",String(f))}q(r,"agent",t.agent),q(r,"capability",t.capability),q(r,"trust",a),q(r,"runtime-risk",s),q(r,"security-capability",u);let g=await S(n,`/api/v1/search${ie(r)}`);if(t.install!==void 0){let f=p(t.install);if(!f){if(t.json)return k("search --install requires an explicit skill slug in the public CLI package.",!0);let y=ht(g);if(y.length===0)return k("Search results do not include any installable skills. Run search again with a broader query.",!1);if(y.length===1)f=y[0].value;else try{f=await n.promptSelect("Select a search result to install:",y)}catch{return k("No search result was selected for install.",!1)}}let m=Mp(g);return m.includes(f)?await hi([f],t,n):k(m.length===0?`Search results do not include "${f}". Run search again with a matching query first.`:`Search results do not include "${f}". Run search again with a matching query or choose one of: ${m.join(", ")}.`,t.json)}return h(g,"Search complete.",t.json,n)}var jr=["low","elevated","high"],Lr=["high","medium","low","published","published_with_findings","publishable","publishable_with_findings","blocked","unknown"],xs=["filesystem_read","filesystem_write","network_access","api_access","browser_access","device_control","generated_code_execution","secret_handling","model_context","shell_access"],Gl={network:"network_access",filesystem:"filesystem_read",files:"filesystem_read",file_read:"filesystem_read",file_write:"filesystem_write",shell:"shell_access",browser:"browser_access",device:"device_control",api:"api_access",secrets:"secret_handling",model:"model_context"},An=["local","project","global","workspace"],ut=["private","public","unlisted"],qe=["private","public","unlisted"],Ur=["github","gitlab","local","generic_git","domain"],Hl=["owner","maintainer"],zl=["submitted","published","draft","pending_review","suspended","blocked","archived","unlisted"],Wl=["open","acknowledged","fixed","closed","rejected","abusive","reopened","resolved"],Jl=["visible","flagged","hidden"],Yl=["bug","quality","safety","other"],Zl=["approved","denied"],Ql=["email","google","github","gitlab","microsoft"],Xl=["email","google","github","gitlab","microsoft"],Tr=["catalog:read","library:read","creator:read","creator:submit","guardian:check","guardian:incident","workspace:read","workspace:write","workspace:deploy","mcp:use"],Fr=["automation","mcp","agent"],Nr=["active","expired","revoked","all"],Mr=["created-desc","created-asc","expires-desc","expires-asc","name-asc","name-desc","last-used-desc","last-used-asc"],Br=10,ec=["personal","shared","team"],Rs=["json","sarif"],It=["featured","trending","newest","name","relevance"],tc=/^(?:card(?:_[A-Za-z0-9]+)*|pm_[A-Za-z0-9_]+)$/u,nc=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,ic=/^[a-f0-9]{6,64}$/iu,rc=new Set(["http:","https:"]);function $s(e,t,n,i){let r=p(t);if(!r)return{};if(!/^\d+$/u.test(r))return{failure:w({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:w({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 jt(e,t,n,i){return w({status:"error",reasonCode:"invalid_search_filter",filter:e,value:t,acceptedValues:n,nextAction:"search",nextStep:e==="runtime-risk"?"Use --runtime-risk low, elevated, or high.":e==="limit"?"Use --limit with a whole number from 1 to 100.":`Use --${e} with one of: ${n.join(", ")}.`},e==="runtime-risk"?`Invalid runtime risk "${t}". Use one of: ${n.join(", ")}.`:e==="limit"?`Invalid search limit "${t}". Use a whole number from 1 to 100.`:`Invalid search --${e} "${t}". Use one of: ${n.join(", ")}.`,i.json,"invalid_search_filter")}function sc(e){if(e)return xs.includes(e)?e:Gl[e]}function je(e,t,n,i,r,s,o=t){return w({status:"error",reasonCode:s,[t]:n,acceptedValues:i,nextAction:e,nextStep:`Use --${o} with one of: ${i.join(", ")}.`},`Invalid ${e} --${o} "${n}". Use one of: ${i.join(", ")}.`,r.json,s)}function ce(e,t,n,i,r,s,o=t){let a=p(n);if(!(!a||i.includes(a)))return je(e,t,a,i,r,s,o)}function xe(e,t){let n=p(t.version);return n&&!zt(n)?fi(e,n,t):void 0}function oc(e,t,n){return w({status:"error",reasonCode:"invalid_slug",value:t,acceptedFormat:"lowercase words separated by hyphens",nextAction:e,nextStep:"Use a lowercase skill slug such as project-planner or year9-history-study-guide."},`Invalid skill slug "${t}". Use lowercase letters, numbers, and single hyphens.`,n.json,"invalid_slug")}function As(e,t,n){return t&&!nc.test(t)?oc(e,t,n):void 0}function ac(e,t,n){return w({status:"error",reasonCode:"invalid_format",format:t,acceptedValues:Rs,nextAction:e,nextStep:"Use --format json or --format sarif."},`Invalid ${e} --format "${t}". Use json or sarif.`,n.json,"invalid_format")}function Es(e,t){let n=p(t.format);return n&&!Rs.includes(n.toLowerCase())?ac(e,n,t):void 0}function lc(e,t,n){return w({status:"error",reasonCode:"invalid_commit_sha",commitSha:t,nextAction:e,nextStep:"Use --commit-sha with a 6 to 64 character hexadecimal commit SHA."},`Invalid --commit-sha "${t}". Use a hexadecimal commit SHA.`,n.json,"invalid_commit_sha")}function cc(e,t){let n=p(t.commitSha);return n&&!ic.test(n)?lc(e,n,t):void 0}function Or(e,t){return w({status:"error",reasonCode:"invalid_base_url",baseUrl:e,nextAction:"backend",nextStep:"Use --base-url with an http or https URL, for example https://api.skills-layer.com."},`Invalid backend base URL "${e}". Use an http or https URL.`,t.json,"invalid_base_url")}function uc(e,t){try{let n=new URL(e);return!rc.has(n.protocol)||!n.hostname?Or(e,t):void 0}catch{return Or(e,t)}}function qr(e,t,n){return w({status:"error",reasonCode:"unexpected_argument",command:e,argument:t,nextAction:e,nextStep:`Run \`skills-layer ${e} --help\` to see supported arguments for this command.`},`Unexpected argument "${t}" for ${e}.`,n.json,"unexpected_argument")}function mi(e,t){let n=p(t.scope);if(n&&!An.includes(n))return{failure:w({status:"error",reasonCode:"invalid_install_filter",filter:"scope",value:n,acceptedValues:An,nextAction:e,nextStep:"Use --scope local, project, global, or workspace."},`Invalid ${e} --scope "${n}". Use one of: ${An.join(", ")}.`,t.json,"invalid_install_filter")};let i=p(t.agent);return i&&!ct(i)?{failure:w({status:"error",reasonCode:"unknown_agent",filter:"agent",value:i,acceptedValues:Re,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 Is(e,t){let n=mi(e,t);if(n.failure)return n.failure;let i=p(t.version);if(e==="install"&&i&&!zt(i))return fi("install",i,t)}function fi(e,t,n){return w({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 dc(e,t,n){return w({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 pc(e,t,n){let i=p(t);if(i&&!/^[1-9]\d*d$/iu.test(i))return dc(e,i,n)}function Ve(e,t,n,i,r,s){let o=p(e);if(!o)return{};if(!/^\d+$/u.test(o))return{failure:w({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:w({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 gc(e){let t=p(e.paymentMethod)??"card";return tc.test(t)?{value:t}:{failure:w({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 mc(e,t,n){let i=new URLSearchParams,r=$s(e,t.limit,20,t);if(r.failure)return r.failure;let s=p(t.sort);return s&&!It.includes(s)?w({status:"error",reasonCode:"invalid_sort",sort:s,acceptedValues:It,nextAction:e,nextStep:`Use --sort with one of: ${It.join(", ")}.`},`${e} --sort must be one of: ${It.join(", ")}.`,t.json,"invalid_sort"):(q(i,"limit",r.value),q(i,"search",t.search),q(i,"sort",s),await $(`/api/v1/${e}${ie(i)}`,t,n,`${en(e)} skills loaded.`))}async function fc(e,t,n){let i=e.join(" ").trim();if(!i)return k("recommend requires a task.",t.json);let r=$s("recommend",t.limit,20,t);if(r.failure)return r.failure;let s=new URLSearchParams({task:i});return q(s,"limit",r.value),await $(`/api/v1/recommend?${s.toString()}`,t,n,"Recommendations loaded.")}async function hc(e,t,n){if(e.length<2)return k("compare requires two or more skill slugs.",t.json);if(e.length>5)return w({status:"error",reasonCode:"too_many_compare_slugs",requestedCount:e.length,maxItems:5,nextAction:"compare",nextStep:"Compare up to 5 skills at a time."},"compare supports up to 5 skill slugs at a time.",t.json,"too_many_compare_slugs");let i=new URLSearchParams({slugs:e.join(",")}),r=await S(n,`/api/v1/skills/compare?${i.toString()}`),s=Array.isArray(r.missing)?r.missing.filter(o=>typeof o=="string"):[];return s.length>0?w({...r,status:"not_found",reasonCode:"compare_missing_skills",missing:s,nextAction:"search",nextStep:`Run \`skills-layer search ${s[0]}\` to find the correct slug, then retry compare.`},`Comparison could not find: ${s.join(", ")}.`,t.json,"compare_missing_skills"):t.json?h(r,"Comparison loaded.",!0,n):{exitCode:0,stdout:Zd(r,"Comparison loaded.",re(n),t.verbose),stderr:""}}async function yc(e,t,n){let i=b(e[0],"show requires a skill slug."),r=await S(n,`/api/v1/skills/${encodeURIComponent(i)}`);return h(_u(r),"Skill loaded.",t.json,n)}async function kc(e,t,n){let i=b(e[0],"trust requires a skill slug."),r=Es("trust",t);if(r)return r;let s=new URLSearchParams;q(s,"format",t.format),q(s,"version",t.version);let o=await S(n,`/api/v1/skills/${encodeURIComponent(i)}/trust${ie(s)}`);return p(t.format)?.toLowerCase()==="sarif"&&!t.json?{exitCode:0,stdout:xu(o,i,n),stderr:""}:h(o,"Trust report loaded.",t.json,n)}async function wc(e,t,n){if(t.json){let s=e[0]==="full"?Me():e[0]==="topic"?Me(e[1]):Me(e[0],e.slice(1));if(s)return h(s,"Help loaded.",!0,n);if(e[0]!=="topic"&&!wl.has(e[0]??""))return Vn(e,!0)}let i=at(e[0],e.slice(1));if(i)return En(i,e.filter(Boolean).join(" "),t,n);let r=e[0];if(!r)return{exitCode:0,stdout:ot,stderr:""};if(r==="full")return En(ot,"full",t,n);if(r==="topic"){let s=at(e[1]);if(s)return En(s,e[1]??"overview",t,n);let o=new URLSearchParams;return e[1]&&o.set("topic",e[1]),await $(`/api/v1/help${ie(o)}`,t,n,"Help topic loaded.")}if(r==="standards")return await $("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let s=await S(n,"/api/v1/marketplace/status");return t.json?h(s,"Marketplace status loaded.",!0,n):h(ip(s),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let s=await S(n,"/api/v1/capabilities");return h(sp(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=b(t.text,"help optimize-tokens requires --text."),o=op(t.maxCharacters,t.json);if(H(o))return o;let a=await S(n,"/api/v1/optimize-tokens",{method:"POST",headers:I(n.apiKey),body:JSON.stringify({text:s,...o?{maxCharacters:o}:{}})});return h(a,"Token optimization complete.",t.json,n)}return k(`Unknown help command "${r}".`,t.json)}function En(e,t,n,i){return n.json?h({status:"ok",topic:t,content:e},"Help topic loaded.",!0,i):{exitCode:0,stdout:e,stderr:""}}function Vn(e,t){let n=e.filter(Boolean).join(" ").trim()||"help";return w({status:"not_found",reasonCode:"help_topic_not_found",topic:n,nextAction:"help",nextStep:"Run `skills-layer --help`, `skills-layer help full`, or `skills-layer <command> --help` for a supported command."},`Help topic not found: ${n}.`,t,"help_topic_not_found")}async function vc(e,t,n){let i=b(e[0]??t.path,"validate requires a file or directory."),r=V(n.cwd,i);if(!await me(r))return Ws("validate",i,t,n);let s=await Zt(r),o={files:s,sourceIntakeContext:p(t.sourceIntakeContext),publicationStatus:p(t.publicationStatus),dependencyAuditStatus:p(t.dependencyAuditStatus),category:p(t.category),discloseSource:!!t.discloseSource,allowFindingsFeatured:!!t.allowFindingsFeatured},a;try{a=await S(n,"/api/v1/validation/preview",{method:"POST",headers:I(n.apiKey),body:JSON.stringify(_(o))})}catch(u){if(u instanceof A&&u.status===422&&u.details)a=Op(u.details);else throw u}let c=bc(a,s);return t.json?h(c,"Validation complete.",!0,n):{exitCode:0,stdout:ap(c,i,n),stderr:""}}function bc(e,t){return{...e,evalReadiness:ar(t)}}function Sc(e,t){let n=Pc(e);return _t({status:n?"not_run":"generated_only",skillSlug:t.skillSlug,version:t.version,artifactDigest:he(e),...n?{evalPackDigest:n}:{},generatedAt:t.generatedAt,runnerVersion:Be,counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})}function Pc(e){let t=e.find(n=>{let i=Ae(n.path,e);return i.type==="evidence"&&typeof n.content=="string"&&(i.relativePath.startsWith("evals/")||i.relativePath.endsWith(".eval.json")||i.relativePath.endsWith(".eval.yaml"))});if(t?.content)try{return Pt(JSON.parse(t.content))}catch{return}}async function Cc(e,t,n){let i=b(e[0]??t.path,"preview-trigger requires a file or directory."),r=V(n.cwd,i);if(!await me(r))return Ws("preview-trigger",i,t,n);let s=await Zt(r),o=await S(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:I(n.apiKey),body:JSON.stringify({files:s,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?h(o,"Trigger preview complete.",!0,n):{exitCode:0,stdout:lp(o,i,n),stderr:""}}async function _c(e,t,n){let i=e[0];if(i==="init")return await xc(e.slice(1),t,n);if(i==="rules")return await $("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(i==="submissions")return await $("/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 $(`/api/v1/me/submissions/${encodeURIComponent(r)}/status`,t,n,"Submission status loaded.",{authenticated:!0})}catch(s){if(s instanceof A&&s.status===404)return Lc(r,t);throw s}}if(i==="charge-status"){let r=b(e[1],"creator charge-status requires a charge id.");return await $(`/api/v1/me/private-skill-charges/${encodeURIComponent(r)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(i==="submit")return await Dr(e.slice(1),t,n,!1);if(i==="submit-version")return await Dr(e.slice(1),t,n,!0);if(i==="check-slug"){let r=b(e[1],"creator check-slug requires a slug.");return await Ic(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."),o=As("creator.rename",s,t);return o||await Jt(`/api/v1/me/submissions/${encodeURIComponent(r)}/slug`,{nextSkillSlug:s},t,n,"Skill renamed.")}if(i==="pricing")return await Tc(e,t,n);if(i==="update-listing"){let r=b(e[1],"creator update-listing requires a skill slug.");return await Fc(r,t,n)}if(i==="visibility"){let r=b(e[1],"creator visibility requires a skill slug."),s=xe("creator.visibility",t);if(s)return s;let o=p(t.visibility)??e[2],a=$t(o);if(!a||!ut.includes(a))return w({status:"error",reasonCode:"invalid_visibility",skillSlug:r,visibility:o??null,acceptedValues:ut,nextAction:"creator.visibility",nextStep:"Use --visibility private, public, or unlisted."},`Invalid creator visibility "${o??""}". Use one of: ${ut.join(", ")}.`,t.json,"invalid_visibility");let c=await S(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/visibility`,{method:"PATCH",headers:I(n.apiKey),body:JSON.stringify(_({visibility:a,dryRun:t.dryRun}))});return Ou(c)?w(c,qu(c,r),t.json,l(c,"reasonCode")??l(c,"status")):h(c,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=Es("creator.security-report",t);if(s)return s;let o=xe("creator.security-report",t);if(o)return o;let a=new URLSearchParams;q(a,"format",t.format),q(a,"version",t.version),q(a,"versionId",t.versionId);let c=await S(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust${ie(a)}`,{headers:F(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?h(c,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:Cp(c,r,n),stderr:""}}if(i==="rescan-security"){let r=b(e[1],"creator rescan-security requires a skill slug."),s=xe("creator.rescan-security",t);if(s)return s;let o=await S(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/trust/rescan`,{method:"POST",headers:I(n.apiKey),body:JSON.stringify(_(Z(t,["version","versionId"])))});return t.json?h(o,"Security rescan requested.",!0,n):{exitCode:0,stdout:_p(o,r,n),stderr:""}}if(i==="provenance"){let r=b(e[1],"creator provenance requires a skill slug.");return await $(`/api/v1/me/submissions/${encodeURIComponent(r)}/provenance`,t,n,"Provenance loaded.",{authenticated:!0})}if(i==="claim"||i==="verify"||i==="dispute")return await Nc(i,e,t,n);if(i==="issues"||i==="reviews"||i==="update-issue"||i==="moderate-review")return await Vc(i,e,t,n);if(i==="analytics"){let r=b(e[1],"creator analytics requires a skill slug.");return await Mc(r,t,n)}if(i==="earnings")return await $("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0});if(i==="payout-profile")return await Bc(t,n);if(i==="payout-link")return await Oc(t,n);if(i==="payouts")return await $("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0});if(i==="withdraw"){if(!p(t.amountCents))return k("creator withdraw requires --amount-cents.",t.json);let r=Ve(t.amountCents,"--amount-cents","amountCents","invalid_amount_cents",t,{minimum:1});return r.failure?r.failure:await z("/api/v1/me/payouts/withdrawals",_({amountCents:r.value,reason:p(t.reason)}),t,n,"Withdrawal requested.")}return i==="source"?await zc(e.slice(1),t,n):k(`Unknown creator command "${i??""}".`,t.json)}async function xc(e,t,n){let i=p(t.skill)??e[0]??"my-skill",r=As("creator.init",i,t);if(r)return r;let s=V(n.cwd,p(t.dir)??i),o=U(s,"SKILL.md"),a;try{a=Xi(p(t.type))}catch(m){return k(te(m),t.json)}let c=p(t.category),u=await Rc(s);if((await me(o)||u)&&!t.confirmed)return k(`Creator init target already exists at ${s}. Re-run with --confirm only if you want to overwrite ${o}.`,t.json);await ft(s,{recursive:!0});let g=er({skillSlug:i,description:p(t.description)??"Describe what this skill helps an agent do.",skillType:a,category:c});for(let m of g)await ge(U(s,m.path),m.content);let f=_({status:"created",path:o,skillSlug:i,skillType:a,category:c,fileCount:g.length});return t.json?h(f,`Created ${o}.`,!0,n):{exitCode:0,stdout:fp(f,s,o,n),stderr:""}}async function me(e){try{return await ws(e),!0}catch{return!1}}async function Rc(e){try{return(await ii(e)).length>0}catch{return await me(e)}}async function Dr(e,t,n,i){let r=p(t.visibility);if(r){let P=$t(r);if(!P||!ut.includes(P))return je(i?"creator.submit-version":"creator.submit","visibility",r,ut,t,"invalid_visibility")}let s=Ve(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(s.failure)return s.failure;let o=i?b(p(t.skill)??e[0],"creator submit-version requires a skill slug."):p(t.skill),a=b(p(t.source)??(i?e[1]:e[0])??t.path,`creator ${i?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),c=await Vt(a,n.cwd);if(t.list)return await $c(a,c,o,t,n);let u=xe(i?"creator.submit-version":"creator.submit",t);if(u)return u;if(p(t.source)&&!c&&xo(a))return Ac(a,t);let d=c?.files??await Zt(V(n.cwd,a));if(!i&&!t.dryRun){let P=await Ec(d,t,n);if(P)return P}let g=_({files:d,version:p(t.version),dryRun:t.dryRun,evalSummary:Sc(d,{skillSlug:o??Ls(d)??"unknown",version:p(t.version)??"0.0.0",generatedAt:n.now()}),allowFindingsFeatured:t.allowFindingsFeatured,pricing:s.value!==void 0?{priceCents:s.value}:void 0,...c?{sourceMetadata:c.sourceMetadata}:{},...Z(t,["displayName","skillType","category","visibility","source","skill"])}),f=i&&o?`/api/v1/me/submissions/${encodeURIComponent(o)}/versions`:"/api/v1/me/submissions",m=await S(n,f,{method:"POST",headers:I(n.apiKey),body:JSON.stringify(g)});if(t.json||t.noOpen||m.status!=="checkout_required"||typeof m.checkoutUrl!="string"||typeof m.chargeId!="string")return h(m,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(m.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${m.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let v=await Id(m.chargeId,n);return H(v)?v:v.status!=="submitted"?h({...m,chargeStatus:v.status},`Payment is still ${v.status}. You can rerun \`skills-layer creator charge-status ${m.chargeId}\` to continue tracking it.`,t.json,n):h(v,i?"Version submitted.":"Submission uploaded.",t.json,n)}async function $c(e,t,n,i,r){if(t)return h(Kr(Fs(e,t,n)),"Source skills loaded.",i.json,r);let s=await qs(r,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},i);return s.kind==="failure"?s.result:h(Kr(s.inspection),"Source skills loaded.",i.json,r)}function Kr(e){return{...e,sourceSubmissionSupported:!0}}function Ac(e,t){let i=`skills-layer source connection start --provider ${Vs(e)} --source ${e} --visibility private --provenance-intent private_source_import`;return w({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 Ec(e,t,n){let i=p(t.skill)??Ls(e);if(!i)return null;let r;try{r=await S(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(i)}`,{headers:F(n.apiKey,n.authBlockedMessage)})}catch(s){if(s instanceof A&&s.status===404)return js(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 w(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 Ic(e,t,n){try{let i=await S(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:F(n.apiKey,n.authBlockedMessage)});return h(jc(i),"Slug status loaded.",t.json,n)}catch(i){if(i instanceof A&&i.status===404)return js(e,t);throw i}}function js(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 w(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 jc(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=C(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 Lc(e,t){return w({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 Ls(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 Uc(n??D(ae(t.path)))}function Uc(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function Tc(e,t,n){let i=b(e[1],"creator pricing requires a skill slug."),r=xe("creator.pricing",t);if(r)return r;let s=new URLSearchParams;if(q(s,"version",t.version),!t.priceCents)return await $(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${ie(s)}`,t,n,"Pricing loaded.",{authenticated:!0});let o=Ve(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(o.failure)return o.failure;let a=o.value??0,c=await S(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing${ie(s)}`,{headers:F(n.apiKey,n.authBlockedMessage)}),u=T(c,"priceCents")??0;if(a>u){let d=_({status:"pending_approval",reasonCode:u===0?"paid_activation_requires_approval":"price_increase_requires_approval",skillSlug:i,version:l(c,"version"),currentPriceCents:u,requestedPriceCents:a,currency:l(c,"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(d,"Pricing change requires approval before it can affect buyers.",t.json,n)}return await Jt(`/api/v1/me/submissions/${encodeURIComponent(i)}/pricing`,{priceCents:a,version:p(t.version)},t,n,"Pricing updated.")}async function Fc(e,t,n){let i=ce("creator.update-listing","listingStatus",t.listingStatus,zl,t,"invalid_listing_status","listing-status");if(i)return i;try{return await Jt(`/api/v1/me/submissions/${encodeURIComponent(e)}`,Z(t,["displayName","summary","description","category","skillType","license","listingStatus"]),t,n,"Listing updated.")}catch(r){if(r instanceof A&&r.status===404){let s={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 w(s,`No editable creator listing was found for ${e}. Run \`skills-layer creator submissions\` to see listings you can update.`,t.json,"creator_listing_not_found_or_not_owned")}throw r}}async function Nc(e,t,n,i){let r=b(t[1],`creator ${e} requires a skill slug.`);if(e==="claim"){let s=ce("creator.claim","requestedRole",n.requestedRole,Hl,n,"invalid_requested_role","requested-role");if(s)return s}try{if(e==="claim")return await z(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/claim`,Z(n,["requestedRole","message"]),n,i,"Ownership claim submitted.");if(e==="verify"){let s=b(n.claimId,"creator verify requires --claim-id.");return await z(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/verify`,{claimId:s},n,i,"Ownership claim verified.")}return b(n.message,"creator dispute requires --message."),await z(`/api/v1/me/skills/${encodeURIComponent(r)}/ownership/dispute`,Z(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 w(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 Mc(e,t,n){try{return await $(`/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 w(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 Bc(e,t){let n=await S(t,"/api/v1/me/payout-profile",{headers:F(t.apiKey,t.authBlockedMessage)});return h(n,"Creator payout profile loaded.",e.json,t)}async function Oc(e,t){let n=qc(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 S(t,"/api/v1/me/payout-profile/link",{method:"POST",headers:I(t.apiKey),body:JSON.stringify(n?{mode:n}:{})})}catch(s){if(s instanceof A&&Kc(s))return w({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=jd(i);return r&&Dc(e)&&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 qc(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 Dc(e){return!e.json&&!e.noOpen}function Kc(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 Vc(e,t,n,i){let r=b(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await $(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await $(`/api/v1/me/submissions/${encodeURIComponent(r)}/reviews`,n,i,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let c=b(n.issueId,"creator update-issue requires --issue-id."),u=b(n.status,"creator update-issue requires --status."),d=ce("creator.update-issue","status",u,Wl,n,"invalid_issue_status");if(d)return d;let g=xe("creator.update-issue",{...n,version:n.fixedVersion});if(g)return g;try{return await Jt(`/api/v1/me/skills/${encodeURIComponent(r)}/issues/${encodeURIComponent(c)}`,Z(n,["status","fixedVersion","note"]),n,i,"Issue updated.")}catch(f){if(f instanceof A&&f.status===404)return Gc(r,c,n);throw f}}let s=b(n.reviewId,"creator moderate-review requires --review-id."),o=b(n.status,"creator moderate-review requires --status."),a=ce("creator.moderate-review","status",o,Jl,n,"invalid_review_status");if(a)return a;try{return await z(`/api/v1/me/submissions/${encodeURIComponent(r)}/reviews/${encodeURIComponent(s)}/moderate`,Z(n,["status","reason"]),n,i,"Review updated.")}catch(c){if(c instanceof A&&c.status===404)return Hc(r,s,n);throw c}}function Gc(e,t,n){return w({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 Hc(e,t,n){return w({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 zc(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"){let o=xe("creator.source.prepare",t);if(o)return o;let a=ce("creator.source.prepare","visibility",t.visibility,qe,t,"invalid_visibility");if(a)return a;let c=Ve(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});return c.failure?c.failure:await z(`/api/v1/me/source-connections/${encodeURIComponent(r)}/prepare`,_({...Z(t,["skill","source","version","displayName","skillType","category","visibility"]),...c.value!==void 0?{priceCents:c.value}:{},source:p(t.source)??e[2]}),t,n,"Source release prepared.")}if(i==="publish-request"){let o=xe("creator.source.publish-request",t);if(o)return o;let a=ce("creator.source.publish-request","visibility",t.visibility,qe,t,"invalid_visibility");if(a)return a;let c=Ve(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(c.failure)return c.failure;let u=t.approvalRequestId.length>0?t.approvalRequestId:p(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await z(`/api/v1/me/source-connections/${encodeURIComponent(r)}/publish-request`,_({skillSlug:s,approvalRequestIds:u,version:p(t.version),...Z(t,["visibility","license","discloseSource"]),...c.value!==void 0?{priceCents:c.value}:{}}),t,n,"Source publish requested.")}if(i==="release-status"){let o=new URLSearchParams;return s&&o.set("skill",s),await $(`/api/v1/me/source-connections/${encodeURIComponent(r)}/release-status${ie(o)}`,t,n,"Source release status loaded.",{authenticated:!0})}return k(`Unknown creator source command "${i??""}".`,t.json)}async function hi(e,t,n){let i=Is("install",t);if(i)return i;let r=p(t.source);if(r){let d=p(t.skill),g=Wr(r,d,t);if(g)return g;let f=await Vt(r,n.cwd);if(f)return await Hr(r,f,d,t,n);let m=Jr(r,t);if(m)return m;let y=t.list||t.dryRun||!d&&!t.json&&!t.all,v=await Qr(n,r,{source:r,skillSlug:d,listOnly:y},t);if(v.kind==="failure")return v.result;let P=v.inspection;if(t.list)return h(P,"Source skills loaded.",t.json,n);let R=zn(r,P,t);if(R)return R;let L=await Mt({source:r,inspection:P,requestedSkillSlug:d,mode:"install",flags:t,backend:n});if(L.kind==="failure")return L.result;if(t.dryRun)return h(Hn(r,P,L.skillSlug,t),"Source install preview ready.",t.json,n);let K;try{K=await Zr({source:r,skillSlug:L.skillSlug,flags:t,backend:n,sourceAccess:v.sourceAccess})}catch(Q){if(Q instanceof A)return Xr(r,Q,t);throw Q}let j=await Tn(n,K),Se=Vr(j)?await In(n,j,L.skillSlug??l(j,"skillSlug")??r,t,{exportMode:Gn(j)?"public":"auto"}):j;if(H(Se))return Se;let M=await Nt(n,Se,L.skillSlug??l(Se,"skillSlug")??r,t);return await Ot(n,M,L.skillSlug??l(M,"skillSlug")??r),Bt(M,zr(r,t,n,M,v.sourceAccess),t.json,n)}let s=b(e[0]??t.install,"install requires a skill slug or --source.");if(xo(s)){let d=Wr(s,p(t.skill),t);if(d)return d;let g=await Vt(s,n.cwd);if(g)return await Hr(s,g,p(t.skill),t,n);let f=Jr(s,t);if(f)return f;let m=p(t.skill),y,v="unknown",P=async M=>{if(y)return null;let Q=await Qr(n,s,{source:s,skillSlug:m,listOnly:M},t);return Q.kind==="failure"?Q.result:(y=Q.inspection,v=Q.sourceAccess,null)};if(t.list){let M=await P(!0);return M||h(y,"Source skills loaded.",t.json,n)}if(!m&&!t.json&&!t.all){let M=await P(!0);if(M)return M;let Q=y,Ue=zn(s,Q,t);if(Ue)return Ue;let tn=await Mt({source:s,inspection:Q,requestedSkillSlug:m,mode:"install",flags:t,backend:n});if(tn.kind==="failure")return tn.result;m=tn.skillSlug}if(t.dryRun){let M=await P(!0);if(M)return M;let Q=y,Ue=await Mt({source:s,inspection:Q,requestedSkillSlug:m,mode:"install",flags:t,backend:n});return Ue.kind==="failure"?Ue.result:(m=Ue.skillSlug,h(Hn(s,Q,m,t),"Source install preview ready.",t.json,n))}let R=await P(!1);if(R)return R;let L;try{L=await Zr({source:s,skillSlug:m,flags:t,backend:n,sourceAccess:v})}catch(M){if(M instanceof A)return Xr(s,M,t);throw M}let K=await Tn(n,L),j=Vr(K)?await In(n,K,m??l(K,"skillSlug")??D(s),t,{exportMode:Gn(K)?"public":"auto"}):K;if(H(j))return j;let Se=await Nt(n,j,m??l(j,"skillSlug")??D(s),t);return await Ot(n,Se,m??l(Se,"skillSlug")??D(s)),Bt(Se,zr(s,t,n,Se,v),t.json,n)}if(p(t.scope)==="workspace"){let d=b(t.workspace,"workspace installs require --workspace <workspace-id>."),g=await S(n,`/api/v1/workspaces/${encodeURIComponent(d)}/skills`,{method:"POST",headers:I(n.apiKey),body:JSON.stringify(_({skillSlug:s,version:p(t.version),dryRun:t.dryRun}))});return t.dryRun?await Gs(g,"Workspace install preview ready.",t,n):h(g,"Workspace deployment requested.",t.json,n)}let o=await S(n,"/api/v1/install",{method:"POST",headers:I(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 Pu(o,t,n);let a=await Tn(n,o),c=await In(n,a,s,t);if(H(c))return c;let u=await Nt(n,c,s,t);return await Ot(n,u,s),Bt(u,"Skill installed.",t.json,n)}async function In(e,t,n,i,r={}){if(Array.isArray(t.materializedWrites)&&t.materializedWrites.length>0)return t;let s=Wc(e,t,n,i);if(s.status==="skip")return t;if(s.status==="failure")return w({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:s.skillSlug,nextStep:s.nextStep},s.message,i.json,"materialization_target_invalid");let o=await Jc(e,t,s.skillSlug,s.version,r),a=await Us({backend:e,exportResult:o,flags:i,skillSlug:s.skillSlug});if(H(a))return a;let c=await eu({backend:e,skillSlug:s.skillSlug,version:s.version??l(o,"version")??"latest",scope:s.scope,agent:s.agent,skillsPath:s.skillsPath,bytes:a.bytes,files:a.files,archiveSha256:a.archiveSha256});return{...t,...Zc(o),archiveSha256:a.archiveSha256,archiveHashFormat:a.archiveHashFormat,scope:s.scope,agent:s.agent.id,targetAgent:s.agent.id,materializationPlan:{scope:s.scope,agent:s.agent.id},...c}}function Wc(e,t,n,i){let r=C(t,"materializationPlan")??C(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)??oe(e.config?.lastSelectedAgent)??"codex",c=Pe(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 Jc(e,t,n,i,r={}){if(typeof t.downloadUrl=="string"&&typeof t.archiveSha256=="string")return t;let s=new URLSearchParams;i&&s.set("version",i);let o=r.exportMode==="public"||!e.apiKey,a=o?`/api/v1/skills/${encodeURIComponent(n)}/export${ie(s)}`:`/api/v1/me/library/${encodeURIComponent(n)}/export${ie(s)}`,c=await S(e,a,{headers:o?{}:F(e.apiKey,e.authBlockedMessage)});return o?{...c,downloadUrl:Yc(n,l(c,"version")??i)}:c}function Yc(e,t){let n=new URLSearchParams;return t&&n.set("version",t),`/api/v1/skills/${encodeURIComponent(e)}/download${ie(n)}`}function Gn(e){let t=l(e,"visibility")??l(e,"versionVisibility"),n=l(e,"listingStatus"),i=l(e,"versionStatus"),r=l(e,"publicationStatus");return t==="public"||n==="published"&&i==="published"||r==="clean_publishable"||r==="publishable_with_findings"}function Vr(e){return Gn(e)||typeof e.downloadUrl=="string"&&typeof e.archiveSha256=="string"}function Zc(e){return _({version:l(e,"version"),storageKey:l(e,"storageKey"),expiresAt:l(e,"expiresAt")})}async function Us(e){let t=l(e.exportResult,"downloadUrl");if(!t)return w({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(Qc(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=Xc(i),s=l(e.exportResult,"archiveSha256")??n.headers.get("x-skills-layer-archive-sha256")?.trim()??void 0;return s&&r.archiveSha256!==s?w({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?w({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 Qc(e,t){return/^https?:\/\//iu.test(t)?t:`${Ce(e)}${t.startsWith("/")?"":"/"}${t}`}function Xc(e){let t=ni("sha256").update(e).digest("hex"),n=Hi(e);return n?{archiveSha256:zi(n),archiveBytesSha256:t,format:"bundle_archive",files:n}:{archiveSha256:t,archiveBytesSha256:t,format:"raw",files:[]}}async function eu(e){let t=e.backend.platform==="win32"?ze:oi,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 ei(n,e.bytes),await ri(i,{recursive:!0,force:!0}),await ei(r,e.bytes),s.push({path:qt(e.backend.cwd,r),bytes:e.bytes.byteLength});for(let o of e.files){let a=t.join(i,...gu(o.path)),c=o.content??"";if(await ge(a,c),s.push({path:qt(e.backend.cwd,a),bytes:new TextEncoder().encode(c).length}),D(o.path).toLowerCase()==="skill.md"){let u=await Ci({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}}var tu=new Set(["file_exists","json_valid","schema_match","section_exists","regex_match","artifact_valid"]);async function Nt(e,t,n,i){let r=l(t,"materializedSkillRoot");if(!r)return t;let s=l(t,"skillSlug")??l(t,"slug")??n,o=l(t,"version")??l(t,"currentVersion")??p(i.version)??"local";try{let a=await nu(V(e.cwd,r));if(a.length===0)return Lt(t,i,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"installed_files_unreadable"});let c=ru({files:a,skillSlug:s,version:o,generatedAt:e.now()}),u=await pu(e,c.summary);return u.status==="recorded"?Lt({...t,...u.effectiveness?{effectiveness:u.effectiveness}:{}},i,{status:"recorded",source:c.source,summaryStatus:c.summary.status,evalPackDigest:c.summary.evalPackDigest,evidenceRevision:u.evidenceRevision}):Lt(t,i,{status:u.status,source:c.source,summaryStatus:c.summary.status,evalPackDigest:c.summary.evalPackDigest,reasonCode:u.reasonCode})}catch(a){return Lt(t,i,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"local_eval_failed",message:te(a)})}}async function nu(e){let t=[];return await Ts(e,e,t),t.sort((n,i)=>n.path.localeCompare(i.path))}async function Ts(e,t,n){for(let i of await ii(t,{withFileTypes:!0})){if(po(i.name))continue;let r=U(t,i.name);if(i.isDirectory()){await Ts(e,r,n);continue}if(!(!i.isFile()||iu(i.name)))try{n.push({path:Ke(e,r).split("\\").join("/"),content:await He(r,"utf8")})}catch{continue}}}function iu(e){return e==="bundle.zip"||/^\.skills-layer-.*\.json$/u.test(e)}function ru(e){let t=he(e.files),n=su(e.files,t);if(!ir(n.pack).valid)return{source:"invalid_submitted",summary:_t({status:"runner_unavailable",skillSlug:e.skillSlug,version:e.version,artifactDigest:t,evalPackDigest:Pt(n.pack),generatedAt:e.generatedAt,runnerVersion:Gr(),counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})};let r=lu(n.pack).map(o=>({id:o.id,assertions:o.assertions.map(a=>cu(a,e.files))})),s=uu(r);return{source:n.source,summary:_t({status:du(s),skillSlug:e.skillSlug,version:e.version,artifactDigest:typeof n.pack.artifactDigest=="string"?n.pack.artifactDigest:t,evalPackDigest:Pt(n.pack),generatedAt:e.generatedAt,runnerVersion:Gr(),counts:{cases:r.length,assertions:s.total,passed:s.passed,failed:s.failed,skipped:s.skipped}})}}function su(e,t){let n=ou(e);return n?{pack:n,source:"submitted"}:{pack:au(e,t),source:"inferred"}}function ou(e){for(let t of e){let n=Ae(t.path,e);if(!(n.type!=="evidence"||!t.content||!n.relativePath.toLowerCase().endsWith(".eval.json")))try{let i=JSON.parse(t.content);if(x(i))return i}catch{return{schemaVersion:"invalid",artifactDigest:he(e),origin:"submitted",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[]}}}}function au(e,t){let i=e.find(r=>r.path.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()==="skill.md")?.path??"SKILL.md";return{schemaVersion:"skills-layer.eval.pack.v1",artifactDigest:t,origin:"inferred",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[{id:"starter-runtime-shape",assertions:[{type:"file_exists",path:i},{type:"regex_match",path:i,pattern:"^---[\\s\\S]*\\nname:\\s*"},{type:"artifact_valid",artifactDigest:t}]}]}}function lu(e){return Array.isArray(e.cases)?e.cases.flatMap(t=>!x(t)||typeof t.id!="string"||!Array.isArray(t.assertions)?[]:[{id:t.id,assertions:t.assertions.filter(x)}]):[]}function cu(e,t){return typeof e.type=="string"&&!tu.has(e.type)?{status:"skipped",reasonCode:"runner_unavailable"}:nr(e,{files:t})}function uu(e){return e.reduce((t,n)=>{for(let i of n.assertions)t.total+=1,i.status==="passed"&&(t.passed+=1),i.status==="failed"&&(t.failed+=1),i.status==="skipped"&&(t.skipped+=1);return t},{total:0,passed:0,failed:0,skipped:0})}function du(e){return e.failed>0?"failed":e.passed>0?"passed":e.skipped>0?"runner_unavailable":"not_run"}function Gr(){return`skills-layer-public-cli:${Be}:local-install`}async function pu(e,t){if(!e.apiKey)return{status:"local_only",reasonCode:"not_authenticated"};try{let n=await S(e,"/api/v1/me/evals/results",{method:"POST",headers:{"content-type":"application/json",...F(e.apiKey,e.authBlockedMessage)},body:JSON.stringify({evalSummary:t})}),i=C(n,"evalEvidence");return{status:"recorded",effectiveness:C(n,"effectiveness"),evidenceRevision:i?T(i,"revision"):void 0}}catch(n){return{status:"submit_failed",reasonCode:n instanceof A?`http_${n.status}`:"request_failed"}}}function Lt(e,t,n){return t.json?{...e,localEval:n}:e}function gu(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 Hr(e,t,n,i,r){let s=p(i.visibility)??"private";if(s!=="private")return w({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=Fs(e,t,n);if(i.list)return h(o,"Local source skills loaded.",i.json,r);let a=zn(e,o,i);if(a)return a;let c=await Mt({source:e,inspection:o,requestedSkillSlug:n,mode:"install",flags:i,backend:r});if(c.kind==="failure")return c.result;let u=c.skillSlug??ht(o)[0]?.value??Ms(e);if(i.dryRun)return h({...Hn(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 S(r,"/api/v1/me/submissions",{method:"POST",headers:{"content-type":"application/json",...F(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 hu({backend:r,source:e,upload:t,skillSlug:l(d,"skillSlug")??u,flags:i,submitted:d}),f=await Nt(r,g,u,i);return await Ot(r,f,u),Bt(f,"Private Cloud skill installed.",i.json,r)}function Fs(e,t,n){let i=mu(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 mu(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=ae(t.path).replaceAll("\\","/"),i=n==="."?".":n,r=Ns(t.content??"")??Ms(i==="."?t.path:i),s=fu(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 Ns(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function fu(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function Ms(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 hu(e){let t=yu(e.backend,e.flags);if(t.status==="failure")throw new Error(t.message);let n=e.upload.files.map(r=>({path:U(t.skillsPath,e.skillSlug,go(r.path)),content:r.content??""})),i=[];for(let r of n)if(await ge(r.path,r.content),i.push({path:qt(e.backend.cwd,r.path),bytes:new TextEncoder().encode(r.content).length}),D(r.path).toLowerCase()==="skill.md"){let s=await Ci({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},materializedSkillRoot:U(t.skillsPath,e.skillSlug),materializedWrites:i}}function yu(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)??oe(e.config?.lastSelectedAgent)??"codex",r=Pe(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 qt(e,t){let n=Ke(e,t);return n&&!n.startsWith("..")&&!ze.isAbsolute(n)?n.split("\\").join("/"):t}function yi(e,t,n,i="unknown"){let r=p(t.visibility);return r==="public"||r==="private"?r:i==="anonymous"?"public":i==="authenticated"?"private":!n.apiKey&&Bs(e)?"public":"private"}function Bs(e){try{return it(e).kind==="github"}catch{return/^https:\/\/github\.com\//iu.test(e.trim())}}function Os(e,t,n,i="unknown"){return yi(e,t,n,i)==="private"||i==="authenticated"?"/api/v1/me/source-installs":"/api/v1/source-imports"}function ku(e,t,n,i="unknown"){return{"content-type":"application/json",...Os(e,t,n,i)==="/api/v1/me/source-installs"?F(n.apiKey,n.authBlockedMessage):{}}}function zr(e,t,n,i,r="unknown"){let s=i?l(i,"visibility")??l(i,"versionVisibility"):void 0,o=i?l(i,"publicationStatus"):void 0,a=i?l(i,"catalogRecord"):void 0,c=i?l(i,"status"):void 0;return s==="public"||o==="clean_publishable"||o==="publishable_with_findings"||c==="published"?"Public source install planned.":s==="private"||o==="private"||a==="private"||c==="private_source_installed"?"Private source skill installed.":yi(e,t,n,r)==="public"?"Public source install planned.":"Private source skill installed."}async function Mt(e){let t=ht(e.inspection);if(e.requestedSkillSlug)return t.length>0&&!t.some(n=>n.value===e.requestedSkillSlug)?{kind:"failure",result:wu(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: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 Wr(e,t,n){if(n.all&&t)return w({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 Jr(e,t){try{if(it(e).kind!=="local")return}catch{return}return w({status:"error",reasonCode:"invalid_source",source:e,nextAction:"install",nextStep:Dt(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."},Dt(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 wu(e,t,n,i){return w({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 ht(e){let t=[e.results,e.skills,e.discoveredSkills,C(e,"source")?.results,C(e,"inspection")?.results],n=new Set,i=[];for(let r of t)if(Array.isArray(r))for(let s of r){let o=vu(s);!o||n.has(o.value)||(n.add(o.value),i.push(o))}return i}function vu(e){if(!x(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=C(e,"parsedSkill"),s=C(e,"frontmatter")??(r?C(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 Yr(e,t,n,i,r,s={}){return _({...t,skillSlug:n,scope:p(i.scope),agent:p(i.agent),workspace:p(i.workspace),version:p(i.version),visibility:s.visibility??yi(e,i,r,s.sourceAccess),category:p(i.category),displayName:p(i.displayName),skillType:p(i.skillType),all:i.all,quarantine:i.quarantine,acceptCapability:i.acceptCapability})}async function Zr(e){let t=e.sourceAccess??"unknown",n=Os(e.source,e.flags,e.backend,t);try{return await S(e.backend,n,{method:"POST",headers:ku(e.source,e.flags,e.backend,t),body:JSON.stringify(Yr(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{sourceAccess:t}))})}catch(i){if(i instanceof A&&i.status===401&&p(e.flags.visibility)!=="private"&&t!=="authenticated"&&Bs(e.source))return await S(e.backend,"/api/v1/source-imports",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Yr(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{visibility:"public"}))});throw i}}function Hn(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:ht(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 qs(e,t,n,i,r={}){try{return{kind:"ok",inspection:await S(e,"/api/v1/source-inspect",{method:"POST",headers:Ds(e,r.authMode??"auto"),body:JSON.stringify(_(n))})}}catch(s){if(s instanceof A)return{kind:"failure",result:Wn(t,s,i)};throw s}}function Ds(e,t){return t==="anonymous"?{"content-type":"application/json"}:I(e.apiKey)}async function Qr(e,t,n,i){try{return{kind:"ok",inspection:await S(e,"/api/v1/source-inspect",{method:"POST",headers:Ds(e,"anonymous"),body:JSON.stringify(_(n))}),sourceAccess:"anonymous"}}catch(s){if(!(s instanceof A))throw s;let o=s.details??{},a=l(o,"error")??s.message;if(!ki(s.status,a))return{kind:"failure",result:Wn(t,s,i)};if(!e.apiKey)return{kind:"failure",result:Wn(t,s,i)}}let r=await qs(e,t,n,i,{authMode:"authenticated"});return r.kind==="failure"?r:{kind:"ok",inspection:r.inspection,sourceAccess:"authenticated"}}function zn(e,t,n){if(ht(t).length>0)return null;let r=bu(t);return w({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."},Su(e,r),n.json)}function bu(e){return(Array.isArray(e.issues)?e.issues:[]).filter(x).map(n=>({...l(n,"code")?{code:l(n,"code")}:{},...l(n,"message")?{message:l(n,"message")}:{},...l(n,"path")?{path:l(n,"path")}:{}}))}function Wn(e,t,n){let i=t.details??{},r=l(i,"error")??t.message;if(ki(t.status,r))return Ks(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return Qt(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 w(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 Xr(e,t,n){let i=t.details??{},r=l(i,"error")??t.message;if(ki(t.status,r))return Ks(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(r)))return Qt(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 w(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 ki(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function Ks(e,t,n,i){let r=t.details??{},s=l(r,"error")??t.message,a=`skills-layer source connection start --provider ${Vs(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 w(c,`Cloud could not ${i} ${e} directly. If this is a private source, start a private source connection first:
|
|
1241
|
+
${a}`,n.json,"private_source_access_required")}function Vs(e){return/gitlab\./iu.test(e)?"gitlab":/github\./iu.test(e)||/^gh:/iu.test(e)?"github":"generic_git"}function Su(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(`
|
|
1242
|
+
`)}async function Pu(e,t,n){if(Hs(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 w(e,`Install preview is not ready: ${o}`,t.json,s)}let i=await zs(e,n),r=Array.isArray(i.warnings)&&i.warnings.length>0;return Cu(i,r?"Install preview ready with warnings.":"Install preview ready.",t,n)}function Cu(e,t,n,i){return n.json?h(e,t,!0,i):{exitCode:0,stdout:wi(e,t,i),stderr:""}}async function Gs(e,t,n,i){if(Hs(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 w(e,`Workspace deployment preview is not ready: ${o}`,n.json,s)}let r=await zs(e,i);return n.json?h(r,t,!0,i):{exitCode:0,stdout:wi(r,t,i),stderr:""}}function Hs(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 zs(e,t){let n=es(e);if(n)return{...e,...n};let i=l(e,"skillSlug")??l(e,"slug");if(!i)return e;try{let r=await S(t,`/api/v1/skills/${encodeURIComponent(i)}/trust`),s=es(r);return s?{...e,...s}:e}catch{return e}}function es(e){let t=C(e,"securityReport")??C(e,"report")??e,n=C(e,"trust")??C(t,"trust")??t,i=C(e,"securityPosture")??C(t,"securityPosture"),r=C(e,"capabilityProfile")??C(t,"capabilityProfile"),s=_({securityScore:T(n,"securityScore")??T(n,"score")??T(e,"securityScore")??(i?T(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:we(n,"detectedCapabilities")??we(e,"detectedCapabilities")??(r?we(r,"detectedCapabilities"):void 0),capabilityMismatches:we(n,"capabilityMismatches")??we(e,"capabilityMismatches")??(r?we(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:we(e,"warnings")??we(t,"warnings")??we(n,"warnings")})}function _u(e){let t=C(e,"securityPosture"),n=C(e,"trust"),i=t?T(t,"securityScore"):void 0,r=n?T(n,"securityScore")??T(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 Bt(e,t,n,i){return n?h(e,t,!0,i):{exitCode:0,stdout:wi(e,t,i),stderr:""}}function xu(e,t,n){let i=re(n),r=Array.isArray(e.runs)?e.runs.filter(x):[],s=r.flatMap(c=>Array.isArray(c.results)?c.results.filter(x):[]),o=r.flatMap(c=>{let u=C(c,"tool"),d=u?C(u,"driver"):void 0;return d&&Array.isArray(d.rules)?d.rules.filter(x):[]}),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,O).entries()){let d=l(u,"ruleId")??"unknown-rule",g=C(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(`
|
|
1243
|
+
`)}function wi(e,t,n){let i=re(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=C(e,"materializationPlan")??C(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(x):[];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 P of m.slice(0,O)){let R=l(P,"path");R&&r.push(` ${i.arrow} ${R}`)}let y=wo(e,i).filter(P=>!P.includes("materialized writes:"));y.length>0&&r.push("",...y);let v=Co(e);return v.length>0&&r.push("",i.section("Next"),...v.map(P=>` ${i.arrow} ${P}`)),r.join(`
|
|
1244
|
+
`)}function Ru(e,t){let n=C(e,"trust"),i=C(e,"securityPosture"),r=C(e,"capabilityProfile"),s=n?.securityScore??n?.score??e.securityScore??i?.securityScore,o=N(n,"runtimeRisk")??l(e,"runtimeRisk")??N(i,"runtimeRisk")??N(r,"runtimeRisk"),a=N(n,"recommendation")??l(e,"recommendation")??N(i,"recommendation"),c=N(n,"label")??N(n,"trust")??l(e,"trustStatus")??l(e,"trust")??N(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")}: ${G("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 $u(e,t){let n=mi("installed",e);if(n.failure)return n.failure;let i=await Le(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 Au(e,t,n){let i=b(e[0],"remove requires a skill slug."),r=Is("remove",t);if(r)return r;let s=await Le(n),o=s.installs[i];if(!o)return w({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 mo(n,s);let a={status:"removed",skillSlug:i,removedRecord:o};return t.json?h(a,`Removed ${i}.`,!0,n):{exitCode:0,stdout:Mu(i,n),stderr:""}}async function Eu(e,t,n){let i=b(e[0],"update requires a skill slug."),r=new URLSearchParams,s=p(t.pin);if(s&&!zt(s))return w({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");q(r,"pin",s),t.dryRun&&r.set("dryRun","true");let a=(await Le(n)).installs[i],c;try{c=await S(n,`/api/v1/skills/${encodeURIComponent(i)}${ie(r)}`,{headers:F(n.apiKey,n.authBlockedMessage)})}catch(d){if(d instanceof A&&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 w(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 A)return Qt(d,t.json);throw d}let u=Lu(i,c,a,n);return s&&t.dryRun&&!Iu(u,s)?w({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:Fu(u,n),stderr:""}}function zt(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 Iu(e,t){let n=[l(e,"version"),l(e,"currentVersion"),l(e,"latestVersion"),l(e,"targetVersion"),l(e,"availableVersion")].filter(Boolean),i=C(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 ju(e,t){let n=mi("sync",e);if(n.failure)return n.failure;let i=await Le(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=>Uu(a,t)))};return e.json?h(o,"Local install records synced.",!0,t):{exitCode:0,stdout:Nu(o,t),stderr:""}}function Lu(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 Uu(e,t){let n=l(e,"skillSlug")??l(e,"slug");if(!n)return{...e,syncStatus:"local_only",backendStatus:"unchecked"};try{let i=await S(t,`/api/v1/skills/${encodeURIComponent(n)}`,{headers:yt(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:Tu(i)}}catch(i){return i instanceof A&&i.status===404?{...e,syncStatus:"backend_missing",backendStatus:"not_found",selectedBackend:t.baseUrl}:{...e,syncStatus:"unchecked",backendStatus:"error",backendError:te(i)}}}function Tu(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 Fu(e,t){let n=re(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=C(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(`
|
|
1245
|
+
`)}function Nu(e,t){let n=re(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(`
|
|
1246
|
+
`)):(e.results.slice(0,O).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>O&&i.push(` ${n.muted(`... ${e.results.length-O} more`)}`),i.push("",n.section("Next")),i.push(` ${n.arrow} skills-layer installed`),i.push(` ${n.arrow} skills-layer update <skill-slug>`),i.join(`
|
|
1247
|
+
`))}function Mu(e,t){let n=re(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(`
|
|
1248
|
+
`)}function Bu(e,t,n){let i=re(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(`
|
|
1249
|
+
`)}function Ou(e){let t=l(e,"status"),n=l(e,"reasonCode");return t==="invalid_transition"||t==="forbidden"||t==="not_found"||n==="invalid_transition"}function qu(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}`:""}
|
|
1250
|
+
Next step: ${o}`}async function Du(e,t,n){let i=await Le(n),r=b(e[0],"restore requires a skill slug."),s=i.installs[r];if(!s)return w({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:Bu(r,s,n),stderr:""}}async function Ku(e,t,n){let i=b(e[0],"check requires a skill slug.");return await $(`/api/v1/skills/${encodeURIComponent(i)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function Vu(e,t,n){let i=b(e[0]??t.source,"import requires a source."),r=ce("import","visibility",t.visibility,qe,t,"invalid_visibility");if(r)return r;let s=await Vt(i,n.cwd);if(!s){let a=Gu(i,t);if(a)return a}let o=await S(n,"/api/v1/source-imports",{method:"POST",headers:I(n.apiKey),body:JSON.stringify(_({...s??{source:i},quarantine:t.quarantine,skillSlug:p(t.skill),visibility:p(t.visibility)}))});return await ee(n.paths.importsPath,{version:1,lastImport:o,savedAt:n.now()}),h(o,"Source import submitted.",t.json,n)}function Gu(e,t){try{return it(e).kind!=="local"?null:w({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:Dt(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."},Dt(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 w({status:"error",reasonCode:"invalid_source",source:e,error:te(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${te(n)}`,t.json,"invalid_source")}}function Dt(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}function Ws(e,t,n,i){let r=V(i.cwd,t);return w({status:"error",reasonCode:"source_path_not_found",path:r,nextAction:e,nextStep:`Check that ${t} exists and contains a readable SKILL.md, then retry.`},`${e} source path does not exist: ${r}`,n.json,"source_path_not_found")}async function Hu(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 S(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(r)}`);return s.status==="not_found"?w({...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 zu(e.slice(1),t,n):k(`Unknown source command "${e.join(" ")}".`,t.json)}async function zu(e,t,n){let i=e[0];if(i==="start"){let s=p(t.provider),o=p(t.source),a=p(t.visibility),c=s?.replace(/-/gu,"_");if(c&&!Ur.includes(c))return je("source.connection.start","provider",s??"",Ur,t,"invalid_source_provider");let u=Ve(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(u.failure)return u.failure;let d=Wu(s,o,a,t);return d||await z("/api/v1/me/source-connections",Z(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.`);if(i==="status")return await $(`/api/v1/me/source-connections/${encodeURIComponent(r)}`,t,n,"Source connection loaded.",{authenticated:!0});if(i==="complete"){let s=cc("source.connection.complete",t);return s||await z(`/api/v1/me/source-connections/${encodeURIComponent(r)}/complete`,Z(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed.")}return i==="cancel"?await z(`/api/v1/me/source-connections/${encodeURIComponent(r)}/cancel`,{},t,n,"Source connection cancelled."):k(`Unknown source connection command "${i??""}".`,t.json)}function Wu(e,t,n,i){if(n){let r=$t(n);if(!r||!qe.includes(r))return w({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:qe,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${qe.join(", ")}.`,i.json,"invalid_visibility")}if(!e||!t)return null;try{let r=it(t);if((e==="github"||e==="gitlab")&&r.kind!==e)return jn(e,t,i);if(e==="domain"){let s=new URL(t);if(s.protocol!=="https:"||!s.hostname)return jn(e,t,i)}}catch{return jn(e,t,i)}return null}function jn(e,t,n){return w({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 Ju(e,t,n){if(e[0]!=="request")return k(`Unknown approval command "${e[0]??""}".`,t.json);let i=e[1];if(i!=="status"&&i!=="complete")return k("approval request requires `status <approval-request-id>` or `complete <approval-request-id> --decision <approved|denied>`.",t.json);let r=b(e[2],`approval request ${i??""} requires an approval id.`);if(i==="status")return await $(`/api/v1/me/approvals/${encodeURIComponent(r)}`,t,n,"Approval status loaded.",{authenticated:!0});let s=b(t.decision,"approval request complete requires --decision."),o=ce("approval.request.complete","decision",s,Zl,t,"invalid_decision");return o||await z(`/api/v1/me/approvals/${encodeURIComponent(r)}/complete`,_({decision:s,evidence:Xt(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed.")}async function Yu(e,t,n){let i=e[0]??"list";if(i==="list")return await $("/api/v1/me/workspaces",t,n,"Workspaces loaded.",{authenticated:!0});if(i==="create"){let s=e.slice(1).join(" ").trim();if(!s)return k("workspace create requires a workspace name.",t.json);let o=ce("workspace.create","kind",t.kind,ec,t,"invalid_workspace_kind");if(o)return o;let a=p(t.kind);return await z("/api/v1/workspaces",{name:s,kind:a==="team"?"shared":a},t,n,"Workspace created.")}let r=b(e[1],`workspace ${i} requires a workspace id.`);if(i==="skills")try{return await $(`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0})}catch(s){if(s instanceof A&&(s.status===403||s.status===404))return Ln(r,t);throw s}if(i==="deploy"){let s=b(e[2],"workspace deploy requires a skill slug."),o;try{o=await S(n,`/api/v1/workspaces/${encodeURIComponent(r)}/skills`,{method:"POST",headers:I(n.apiKey),body:JSON.stringify(_({skillSlug:s,dryRun:t.dryRun}))})}catch(a){if(a instanceof A&&(a.status===403||a.status===404))return Ln(r,t);throw a}return t.dryRun?await Gs(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 Yt(`/api/v1/workspaces/${encodeURIComponent(r)}/skills/${encodeURIComponent(s)}`,{method:"DELETE",headers:F(n.apiKey,n.authBlockedMessage)},t,n,"Workspace skill removed.")}catch(o){if(o instanceof A&&o.status===404)return ts(r,s,t);if(o instanceof A&&o.status===403)return Ln(r,t);throw o}}if(i==="guide"){let s=b(e[2],"workspace guide requires a skill slug.");try{return await $(`/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 ts(r,s,t);throw o}}return k(`Unknown workspace command "${i}".`,t.json)}function Ln(e,t){return w({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 ts(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 w(i,`Workspace deployment not found for ${t}. Run \`skills-layer workspace deploy ${e} ${t}\` first.`,n.json,"workspace_deployment_not_found")}async function Zu(e,t,n){let i=b(e[0],"buy requires a skill slug."),r=gc(t);if(r.failure)return r.failure;let s=await S(n,"/api/v1/buy",{method:"POST",headers:I(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||t.noOpen||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 Ed(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 hi([i],t,n))}async function Qu(e,t,n){let i=e[0]??"list";if(i==="list")return await $("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(i==="spending")return await $("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let r=b(e[1],`purchases ${i} requires a purchase id.`);return i==="invoice"?await $(`/api/v1/purchases/${encodeURIComponent(r)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0}):i==="refund-quote"?await $(`/api/v1/purchases/${encodeURIComponent(r)}/refund-quote`,t,n,"Refund quote loaded.",{authenticated:!0}):i==="refund"?await z(`/api/v1/purchases/${encodeURIComponent(r)}/refund`,Z(t,["reason"]),t,n,"Refund requested."):k(`Unknown purchases command "${i}".`,t.json)}async function Xu(e,t,n){let i=e[0];if(i==="add"){let r=b(e[1],"library add requires a skill slug.");return await z("/api/v1/install",{skillSlug:r},t,n,"Skill added to library.")}return k(`Unknown library command "${i}".`,t.json)}async function ed(e,t,n){let i=b(e[0],"export requires a skill slug.");if(t.showUrl&&p(t.output))return w({status:"error",reasonCode:"conflicting_export_output",nextAction:"export",nextStep:"Use either --show-url to inspect the signed URL or --output <file> to download the bundle, not both."},"export cannot use --show-url and --output together.",t.json,"conflicting_export_output");let r=new URLSearchParams,s=p(t.version);if(s&&!zt(s))return fi("export",s,t);q(r,"version",s);let o=await S(n,`/api/v1/me/library/${encodeURIComponent(i)}/export${ie(r)}`,{headers:F(n.apiKey,n.authBlockedMessage)}),a=p(t.output);if(a){let c=await Us({backend:n,exportResult:o,flags:t,skillSlug:i});if(H(c))return c;let u=V(n.cwd,a);await ei(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 ns(e,t,n,i){let r=b(t[0],`${e==="add"?"add-review":"show-reviews"} requires a skill slug.`);if(e==="show")return await $(`/api/v1/me/library/reviews?skillSlug=${encodeURIComponent(r)}`,n,i,"Reviews loaded.",{authenticated:!0});let s=b(n.rating,"add-review requires --rating.");if(!/^[1-5]$/u.test(s))return w({status:"error",reasonCode:"invalid_rating",rating:s,acceptedValues:["1","2","3","4","5"],nextAction:"add-review",nextStep:"Use --rating with a whole number from 1 to 5."},`Invalid review rating "${s}". Use a whole number from 1 to 5.`,n.json,"invalid_rating");let o=Z(n,["rating","feedback"]);if(typeof n.evalSummary=="string"){let a=await W(ai(i.cwd,n.evalSummary));if(a===null)return w({status:"error",reasonCode:"invalid_eval_summary_file",path:n.evalSummary,nextAction:"add-review",nextStep:"Pass --eval-summary with a readable JSON redacted eval summary envelope."},`Could not read eval summary JSON from ${n.evalSummary}.`,n.json,"invalid_eval_summary_file");o.evalSummary=a}return await z(`/api/v1/me/library/${encodeURIComponent(r)}/review`,o,n,i,"Review added.")}async function is(e,t,n,i){let r=b(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);if(e==="show")return await $(`/api/v1/me/library/${encodeURIComponent(r)}/issues`,n,i,"Issues loaded.",{authenticated:!0});b(n.message,"add-issue requires --message.");let s=ce("add-issue","issueType",n.issueType,Yl,n,"invalid_issue_type","issue-type");return s||await z(`/api/v1/me/library/${encodeURIComponent(r)}/report-issue`,Z(n,["issueType","message"]),n,i,"Issue reported.")}async function td(e,t,n){let i=e[0];if(i==="hook"){let r=e[1];return r==="install"?await Ys(t,n):r==="status"?await sd(t,n):k(`Unknown guardian hook command "${r??""}".`,t.json)}if(i==="enable")return e[1]||t.skill?await Un("enforce",e,t,n):k("guardian enable requires a skill slug.",t.json);if(i==="disable")return await Un("disabled",e,t,n);if(i==="enable-warnings-only")return await Un("warning_only",e,t,n);if(i==="status")return await id(e,t,n);if(i==="exec")return await nd(e,t,n);if(i==="check"){let r=b(e[1]??t.skill,"guardian check requires a skill slug."),s=ds(t,"check"),o=t.grantJson.map(y=>Ai(y,"grant-json")),a=Bp(t.cloudTrustLedger);if(a.status==="invalid")return k(a.message,t.json);let c=Jn(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(c.status==="invalid")return k(c.message,t.json);let u=await Qs({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 bi(n,r),unmanagedPolicy:u.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:c.mode,localPreflight:Ie(u.context)}),m=await S(n,"/api/v1/guardian/enforce",{method:"POST",headers:I(n.apiKey),body:JSON.stringify(f)});return await dt(n,{skillSlug:r,version:g,action:s,decisionStatus:Kt(m),reasonCode:Yn(m),telemetryMode:c.mode,path:d}),h({...m,localPreflight:Ie(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=Jn(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return k(o.message,t.json);let a=p(t.path);if(a&&!await me(V(n.cwd,a)))return w({status:"error",reasonCode:"invalid_incident_path",path:a,nextAction:"guardian.incident",nextStep:"Use --path with an installed skill directory, or omit --path so Skills Layer resolves the local install record."},`Guardian incident path does not exist: ${a}`,t.json,"invalid_incident_path");let c=a??(await Xs({skillSlug:r,flags:t,backend:n})).installedPath,u=ds(t,"incident"),d=Xt(t.evidenceJson,"evidence-json"),g=o.mode==="cloud_managed"&&!n.apiKey?"local_only":o.mode,f=_({skillSlug:r,version:s,action:u,evidence:d,path:c,telemetryMode:g,incident:!0,reason:p(t.reason)});if(g==="local_only"){if(!c)return k("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let P=await ls({backend:n,skillSlug:r,version:s,installedPath:c,action:u,reason:p(t.reason)??"Guardian local-only incident"});await dt(n,{skillSlug:r,version:s,action:u,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:g,path:c});let R=cs(n,r);return await ge(R,JSON.stringify({request:f,response:null,localResponse:P,savedAt:n.now()},null,2)),h({status:"written",skillSlug:r,version:s,telemetryMode:g,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:P,incidentStatePath:R,incidentPath:P.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let m=await S(n,"/api/v1/guardian/enforce",{method:"POST",headers:I(n.apiKey),body:JSON.stringify(f)}),y=c?await ls({backend:n,skillSlug:r,version:s,installedPath:c,action:u,reason:p(t.reason)??"Guardian Cloud-managed incident"}):null;await ft(n.paths.incidentsDir,{recursive:!0});let v=cs(n,r);return await ge(v,JSON.stringify({request:f,response:m,localResponse:y,savedAt:n.now()},null,2)),await dt(n,{skillSlug:r,version:s,action:u,decisionStatus:Kt(m),reasonCode:Yn(m),telemetryMode:o.mode,path:c}),h({...m,telemetryMode:o.mode,localResponse:y,incidentPath:v},"Guardian incident recorded.",t.json,n)}return k(`Unknown guardian command "${i??""}".`,t.json)}async function nd(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 k("guardian exec requires a command after --.",t.json);let o=Jn(t.telemetryMode,"cloud_managed");if(o.status==="invalid")return k(o.message,t.json);let a=gd(t,s),c=await Qs({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(P=>Ai(P,"grant-json")),path:u,guardianPreference:await bi(n,r),telemetryMode:o.mode,localPreflight:Ie(c.context)}),f=await S(n,"/api/v1/guardian/enforce",{method:"POST",headers:I(n.apiKey),body:JSON.stringify(g)}),m=Kt(f),y=Yn(f);if(await dt(n,{skillSlug:r,version:d,action:a,decisionStatus:m,reasonCode:y,telemetryMode:o.mode,path:u}),!md(f))return w({status:"blocked",reasonCode:y,skillSlug:r,guardian:f,localPreflight:Ie(c.context),command:{executable:D(s[0]??""),executed:!1}},"Guardian blocked guarded execution.",t.json,y);if(t.dryRun)return h({status:"allowed",skillSlug:r,guardian:f,localPreflight:Ie(c.context),command:{executable:D(s[0]??""),executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let v=await fd(s,n);return{exitCode:v.exitCode,stdout:t.json?JSON.stringify({status:v.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:r,guardian:f,localPreflight:Ie(c.context),command:v},warnings:[],links:[],reasonCode:v.exitCode===0?null:"command_failed",handoff:null},null,2):hd(v),stderr:v.stderr}}async function Un(e,t,n,i){let r=b(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),s=await S(i,"/api/v1/guardian/mode",{method:"POST",headers:I(i.apiKey),body:JSON.stringify({skillSlug:r,requestedPreference:e,source:"public-cli"})});return s.preferenceAccepted===!0&&await yd(i,r,s),h(s,s.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,i)}async function id(e,t,n){let i=p(t.skill)??p(e[1]),r;try{r=await Js(n,i)}catch(d){r={status:"unavailable",skillSlug:i,policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:te(d),nextAction:"guardian.status",nextStep:"Cloud Guardian policy could not be loaded. Local hook and preference posture are still shown below."}}let s=await We(n),o=i?await kd(n,i):void 0,a=l(r,"status")==="unavailable",u=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:a?"degraded":"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:u,nextAction:l(u,"nextAction"),nextStep:l(u,"nextStep")}),a?"Guardian status loaded with limited Cloud policy data.":"Guardian status loaded.",t.json,n)}async function Js(e,t){let n=t?await bi(e,t):void 0;return await S(e,"/api/v1/guardian/status",{method:"POST",headers:I(e.apiKey),body:JSON.stringify(_({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function rd(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 Js(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:te(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function Ys(e,t){let n=p(e.agent)??"codex",i=to(e.scope);if(i.status==="invalid")return k(i.message,e.json);let r=Pe(t.env,t.platform,t.cwd).find(g=>g.id===n);if(!r)return w({status:"error",reasonCode:"unknown_agent",agent:n,nextAction:"agents.list",nextStep:"Run `skills-layer agents list` to see supported agents, then retry Guardian hook install with a supported --agent value."},`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json,"unknown_agent");let s=wd(r,i.scope,t);if(!s)return k(`Guardian ${i.scope} hooks are not available for ${r.displayName}.`,e.json);await vd(s,t);let o=ro(t,i.scope),a=us(Ke(t.cwd,s.hookPath)),c=us(Ke(t.cwd,s.configPath)),d=[...(await so(o)).hooks.filter(g=>l(g,"agent")!==r.id||l(g,"scope")!==i.scope),{hookId:be,hookName:le,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 ee(o,{version:1,hooks:d}),h({status:"enabled",hookId:be,hookName:le,agent:r.id,agentName:r.displayName,scope:i.scope,hookPath:s.hookPath,configPath:s.configPath,enforcementLayer:s.enforcementLayer,strictPreActionBlocking:s.strictPreActionBlocking,agentCommandMatrix:vn({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 sd(e,t){let n=p(e.scope),i=n?to(n):null;if(i?.status==="invalid")return k(i.message,e.json);let r=await We(t,i?.status==="valid"?i.scope:void 0);return h(r,"Guardian status loaded.",e.json,t)}async function We(e,t){let n=t?[t]:["project","global"],i=[];for(let a of n){let c=ro(e,a),u=await so(c);for(let d of u.hooks){let g=l(d,"hookPath"),f=g?as(e,a,g):null,m=l(d,"configPath"),y=m?as(e,a,m):null,v=f?await me(f):!1,P=y?await me(y):null,R=v?P===!1?"active_missing_config":"active":"stale_missing_hook";i.push({hookId:l(d,"hookId")??be,hookName:l(d,"hookName")??le,...d,scope:l(d,"scope")??a,hookPath:f??g??null,configPath:y??m??null,active:v,configActive:P,hookState:R})}}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 Si(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 Zs(e,t){if(e.json){let u=await W(t.paths.mcpConfigPath);return h({setup:await Si(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 We(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:ld(t.now(),7)};return await os(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 gi(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 Ys(u,t);if(d.exitCode!==0)return d;s.security=Rd(d.stdout)??{status:"enabled",agent:p(u.agent),scope:p(u.scope)}}await os(t,o);let c=(x(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 od(e,t){let n=await We(t),i=await Si(t),r=T(n,"activeHookCount")??0;if(t.stdoutIsTty&&r===0&&!i)return await Zs(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:`${ot}
|
|
1251
|
+
|
|
1252
|
+
${s}`,stderr:""}}function ad(e,t){let n=T(e,"activeHookCount")??0,i=T(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 ld(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?e:(n.setUTCDate(n.getUTCDate()+t),n.toISOString())}async function Qs(e){let t=eo(p(e.flags.unmanagedPolicy)??e.backend.env.SKILLS_LAYER_UNMANAGED_SKILL_POLICY);if(t.status==="invalid")return{status:"invalid",result:k(t.message,e.flags.json)};let n=await Xs({skillSlug:e.skillSlug,flags:e.flags,backend:e.backend,unmanagedPolicy:t.policy});if(n.unmanaged&&n.unmanagedPolicy==="block")return Ut({...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 _d(n.installedPath))return Ut({...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 dd(e.skillSlug,n.installedPath);if(n.identityAssessment=i,i.reattestationRequired===!0)return Ut({...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 pd(e.skillSlug,n.installedPath);return n.driftAssessment=r,r.reattestationRequired===!0?Ut({...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 Ut(e){return await dt(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:w({status:"blocked",skillSlug:e.skillSlug,version:e.version??e.context.version,reasonCode:e.reasonCode,localPreflight:Ie(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 Xs(e){let t=eo(p(e.flags.unmanagedPolicy)),n=e.unmanagedPolicy??(t.status==="valid"?t.policy:"warn"),i=p(e.flags.path),r=await cd(e.skillSlug,e.backend),s=i?V(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 cd(e,t){let i=(await Le(t)).installs[e];if(i){let r=rs(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 ud(t)){let s=await W(r);if(!x(s)||!x(s.installs))continue;let o=s.installs[e];if(x(o)){let a=rs(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 ud(e){return Array.from(new Set([U(e.cwd,"skills-layer-lock.json"),U(e.paths.stateDir,"skills-layer-lock.json")]))}function rs(e,t){let n=l(e,"materializedSkillRoot");if(n)return{installedPath:Tt(V(t.cwd,n)),installedPathSource:"materializedSkillRoot",status:"ok"};let i=l(e,"canonicalPath");if(i)return{installedPath:Tt(V(t.cwd,i)),installedPathSource:"canonicalPath",status:"ok"};let r=l(e,"path");if(r)return{installedPath:Tt(V(t.cwd,r)),installedPathSource:"path",status:"ok"};let s=l(e,"materializedPath")??l(e,"bundlePath");if(s){let u=V(t.cwd,s),d=D(u).toLowerCase()==="bundle.zip"||u.toLowerCase().endsWith(".zip");return{installedPath:d?ae(ae(u)):Tt(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(x):[]).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?ae(V(t.cwd,c)):void 0,installedPathSource:c?"materializedWrites":void 0,status:c?"ok":void 0}}function Tt(e){return D(e).toLowerCase()==="skill.md"?ae(e):e}async function dd(e,t){let n=U(t,"SKILL.md");if(!await me(n))return{status:"not_checked",reasonCode:"skill_document_unavailable",expectedSkillSlug:e,reattestationRequired:!1};try{let i=Ns(await He(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:te(i),reattestationRequired:!0}}}async function pd(e,t){let n=U(t,".skills-layer-runtime.json"),i=await W(n),r=i?C(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=U(t,"SKILL.md");if(!await me(o))return{status:"changed",reasonCode:"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:s,reattestationRequired:!0};let a=lo(await He(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 Ie(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 eo(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 Jn(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 gd(e,t){let n=Xt(e.actionJson,"action-json");return n&&typeof n=="object"&&!Array.isArray(n)?n:{type:"shell_command",command:D(t[0]??"command")}}function md(e){let t=C(e,"enforcement");return typeof t?.canExecute=="boolean"?t.canExecute:Kt(e)!=="blocked"}async function fd(e,t){let[n,...i]=e;return await new Promise((r,s)=>{let o=ks(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=ss(`${a}${u}`)}),o.stderr?.on("data",u=>{c=ss(`${c}${u}`)}),o.on("error",s),o.on("close",u=>{r({executable:D(n),argsCount:i.length,exitCode:typeof u=="number"?u:1,stdout:a,stderr:c})})})}function ss(e){return e.length>2e4?`${e.slice(0,2e4)}
|
|
1253
|
+
[output truncated]`:e}function hd(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(`
|
|
1254
|
+
`)}function to(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 no(e){return U(e.paths.stateDir,"guardian-modes.json")}function io(e){return U(e.paths.stateDir,"setup-state.json")}async function vi(e){let t=await W(no(e));return{version:1,skills:x(t?.skills)?t.skills:{}}}async function yd(e,t,n){let i=await vi(e);await ee(no(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 bi(e,t){let i=(await vi(e)).skills[t];return i?l(i,"requestedPreference"):void 0}async function kd(e,t){return(await vi(e)).skills[t]}async function Si(e){let t=await W(io(e));return x(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 os(e,t){await ee(io(e),t)}function wd(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:be,hookName:le,configPath:U(i,"hooks.json"),hookPath:U(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:be,hookName:le,configPath:U(i,"settings.json"),hookPath:U(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook",strictPreActionBlocking:!0}:e.id==="cline"?{agent:e.id,agentName:e.displayName,scope:t,hookId:be,hookName:le,configPath:U(i,"guardian-hooks.json"),hookPath:U(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1}:null:null}async function vd(e,t){if(await ge(e.hookPath,Cd(e.agentName)),await vs(e.hookPath,448).catch(()=>{}),e.agent==="codex"){await ee(e.configPath,bd(e.hookPath));return}if(e.agent==="claude-code"){await ee(e.configPath,Sd(e.hookPath));return}e.agent==="cline"&&await ee(e.configPath,Pd(e,t))}function ro(e,t){return t==="global"?U(e.paths.stateDir,"guardian-hooks.json"):U(e.cwd,".skills-layer","guardian-hooks.json")}async function so(e){let t=await W(e);return{version:1,hooks:Array.isArray(t?.hooks)?t.hooks.filter(x):[]}}function as(e,t,n){return ze.isAbsolute(n)||n.startsWith("/")?n:ai(t==="global"?e.paths.stateDir:e.cwd,n)}function bd(e){return{hooks:{PreToolUse:[{name:le,id:be,matcher:"Bash|Shell|Read|Write|Edit|apply_patch|mcp__.*",hooks:[{name:le,type:"command",command:`node ${Pi(e)}`}]}]}}}function Sd(e){return{hooks:{PreToolUse:[{name:le,id:be,matcher:"Bash|Read|Write|Edit|MultiEdit|NotebookEdit|WebFetch|WebSearch",hooks:[{name:le,type:"command",command:`node ${Pi(e)}`}]}]}}}function Pd(e,t){return{version:1,hookId:be,hookName:le,agent:e.agent,agentName:e.agentName,scope:e.scope,enforcementLayer:e.enforcementLayer,strictPreActionBlocking:e.strictPreActionBlocking,installedAt:t.now(),hooks:[{name:le,id:be,event:"PreToolUse",command:`node ${Pi(e.hookPath)}`,status:"candidate"}]}}function Cd(e){return`#!/usr/bin/env node
|
|
1250
1255
|
import { spawnSync } from "node:child_process";
|
|
1251
1256
|
import { readFileSync } from "node:fs";
|
|
1252
1257
|
|
|
@@ -1281,41 +1286,41 @@ const result = spawnSync("skills-layer", [
|
|
|
1281
1286
|
], { stdio: ["ignore", "inherit", "inherit"] });
|
|
1282
1287
|
|
|
1283
1288
|
process.exit(result.status ?? 1);
|
|
1284
|
-
`}function
|
|
1285
|
-
`;return await
|
|
1286
|
-
`),await
|
|
1287
|
-
`),await
|
|
1288
|
-
`)),{status:"written",generatedAt:t,incidentPath:r,writtenFiles:[n,i,r]}}function
|
|
1289
|
-
`,{encoding:"utf8",mode:384}),await
|
|
1289
|
+
`}function Pi(e){return JSON.stringify(e)}async function Ci(e){let t=U(ae(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:vn({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:lo(e.skillDocumentContent)}},i=`${JSON.stringify(n,null,2)}
|
|
1290
|
+
`;return await ge(t,i),{path:qt(e.backend.cwd,t),bytes:new TextEncoder().encode(i).length}}async function _d(e){return await me(U(e,".skills-layer-disabled.json"))}async function ls(e){let t=e.backend.now(),n=U(e.installedPath,".skills-layer-disabled.json"),i=U(e.installedPath,".skills-layer-quarantine.json"),r=U(e.installedPath,"incident.md"),s=l(e.action,"type")??"unknown";return await ge(n,`${JSON.stringify({disabled:!0,generatedAt:t,skillSlug:e.skillSlug,version:e.version,reason:"Skills Layer Guardian incident response"},null,2)}
|
|
1291
|
+
`),await ge(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)}
|
|
1292
|
+
`),await ge(r,["# Skills Layer Guardian Incident Report","",`Generated: ${t}`,`Skill: ${e.skillSlug}`,`Version: ${e.version}`,"","## Summary","",ao(e.reason),"","## Evidence","",`- ${t}: ${s} -> blocked (incident_recorded)`].join(`
|
|
1293
|
+
`)),{status:"written",generatedAt:t,incidentPath:r,writtenFiles:[n,i,r]}}function cs(e,t){let n=e.now().replace(/[:.]/gu,"-");return U(e.paths.incidentsDir,`${t}-${n}.json`)}async function dt(e,t){let n=U(e.paths.stateDir,"guardian-audit.jsonl");await _o(ae(n));let i={version:1,generatedAt:e.now(),skillSlug:t.skillSlug,...t.version?{skillVersion:t.version}:{},actionType:l(t.action,"type")??"unknown",actionTarget:xd(t.action),decisionStatus:t.decisionStatus,reasonCode:t.reasonCode,telemetryMode:t.telemetryMode,...t.path?{localPath:oo(t.path)}:{}};await hl(n,`${JSON.stringify(i)}
|
|
1294
|
+
`,{encoding:"utf8",mode:384}),await $i(n,384)}function Kt(e){let t=C(e,"decision"),n=C(e,"enforcement"),i=l(t??{},"status")??l(n??{},"status")??l(e,"status");return i==="allowed"||i==="advisory"?i:"blocked"}function Yn(e){let t=C(e,"decision");return l(t??{},"reasonCode")??l(e,"reasonCode")??l(e,"status")??"cloud_guardian_decision"}function xd(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 ao(i);let r=l(e,"path");return r?oo(r):null}function oo(e){let t=D(e.trim());return t?`<local-path>/${t}`:"<local-path>"}function ao(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 us(e){return e.split(/[\\/]+/u).join("/")}function lo(e){return ni("sha256").update(e).digest("hex")}async function co(e,t,n,i,r){let s=await S(i,"/api/v1/verify",{method:"POST",headers:I(),body:JSON.stringify({email:e,code:t,clientDelivery:"cli_secure_storage"})});if(n.json){let o=l(s,"apiKey");return o?(await pt(i,o,{expectedEmail:e,knownEmail:l(s,"email")??e,knownRole:l(s,"role")??"user",knownRoles:ue(s,"roles"),knownUserId:l(s,"userId")}),h(Y({...s,loggedIn:!0}),"Email verified and login completed.",!0,i)):h(Y({...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 Wt(e,s,n,i,r)}async function Wt(e,t,n,i,r){let s=l(t,"apiKey"),o=l(t,"role")??"user",a=ue(t,"roles"),c=l(t,"userId"),u=s;if(!u&&n.json)return h(Y({...t,email:e,role:o,...a?{roles:a}:{},loggedIn:!1}),`${r} Login still needs to be completed through a human handoff.`,!0,i);if(!u)try{u=(await i.promptSecret(`Enter the API key emailed to ${e} (check spam/junk folder if missing): `)).trim()}catch{return h(Y({...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 k("No API key was entered. Run `skills-layer login` once you have the emailed key.",n.json);let d=await pt(i,u,{expectedEmail:e,knownEmail:e,knownRole:o,knownRoles:a,knownUserId:c,forceProfileValidation:!s}),g=await Kn(n,{...i,config:d,apiKey:u});return H(g)?g:h(Y({...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 _i(e,t,n,i,r){let s=l(t,"authorizationUrl"),o=b(l(t,"state"),"Social auth did not return a state."),a=Kp(e);if(n.noOpen)return h({...t,status:"human_handoff",handoff:{kind:"browser_auth",provider:e,authorizationUrl:s,state:o,nextAction:"open_browser",nextStep:`Open the ${a} sign-in URL, finish authentication, then run \`skills-layer login\` again if needed.`}},`${a} sign-in started. Open the browser handoff URL to continue.`,n.json,i);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:
|
|
1290
1295
|
${s}
|
|
1291
|
-
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 zc(o,i);return J(c)?c:c.status==="verified"||c.status==="recovered"?await It(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):Hc(c)?k(Zc(c),n.json):k("Social auth completed with an unexpected response.",n.json)}function J(e){return R(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function Vc(e){try{let t=JSON.parse(e);return R(t)?t.data:void 0}catch{return}}function Hc(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 zc(e,t){for(let n=0;n<120;n+=1)try{let i=await S(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")}: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(Z(i),!1)}return k("Timed out while waiting for social auth to complete.",!1)}async function Wc(e,t){for(let n=0;n<120;n+=1)try{let r=(await S(t,"/api/v1/purchases",{headers:T(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(Z(i),!1)}return k("Timed out while waiting for purchase confirmation.",!1)}async function Jc(e,t){for(let n=0;n<120;n+=1)try{let i=await S(t,`/api/v1/me/private-skill-charges/${encodeURIComponent(e)}`,{headers:T(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 A&&i.status===429){await t.sleep(1500);continue}return k(Z(i),!1)}return k("Timed out while waiting for payment confirmation.",!1)}function Yc(e){let t=P(e,"accountLink");return(t?l(t,"url"):void 0)??l(e,"url")??l(e,"setupUrl")}function Zc(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 et(e,t,n={}){let r=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole?await S({...e,apiKey:t},"/api/v1/me",{headers:{...T(t),...n.notifyLogin?{"x-skills-layer-session-intent":"login"}:{}}}):{userId:n.knownUserId,email:n.knownEmail,role:n.knownRole,roles:n.knownRoles},s=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 S({...e,apiKey:t},"/api/v1/capabilities",{headers:T(t)}),a={version:Tr,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 Yn(e.paths.configPath,a,e),await W(e.paths.backendPreferencePath,{version:Ln,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),a}function Cr(e,t){let n=Tt(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 $(e,t,n,i,r={}){let s=r.authenticated?T(n.apiKey,n.authBlockedMessage):Ne(n.apiKey);return await Et(e,{headers:s},t,n,i)}async function Qc(e,t){if(e.deep)return await Xc(e,t);let n=await S(t,"/api/v1/doctor",{headers:Ne(t.apiKey)}),i=await Te(t),r=await Sc(t),s=[...Ps(n),_c(i,r)];return h({...n,guardian:{...i,policy:r},checks:s},"Doctor checks loaded.",e.json,t)}async function Xc(e,t){let n;try{let c=await S(t,"/api/v1/status",{headers:Ne(t.apiKey)});n=me("ok","backend_reachable","status","Backend status loaded.",{baseUrl:t.baseUrl,edition:l(c,"edition"),capabilityCount:Array.isArray(c.capabilities)?c.capabilities.length:void 0})}catch(c){n=me("error","backend_unreachable","backend.status","Selected backend could not be reached.",{baseUrl:t.baseUrl,error:Z(c)})}let i=t.config?.credentialStorage??(t.apiKey?"local_file_locked":"none"),r=await D(t.paths.mcpConfigPath),s=await Te(t),o=ke(t.env,t.platform,t.cwd).map(c=>({id:c.id,displayName:c.displayName,capabilities:c.capabilities})),a={backend:n,auth:t.apiKey?me("ok","authenticated","whoami","A local session is available for the selected backend.",{email:t.config?.email,role:t.config?.role,savedLoginMatchesSelectedBackend:!0}):me("login_required","login_required","login","No usable local session is available for the selected backend.",{savedLoginMatchesSelectedBackend:t.config?.baseUrl?te(t.config.baseUrl)===t.baseUrl:!0}),credentialStorage:me(i==="none"?"not_configured":"ok",i==="none"?"credential_storage_not_configured":"credential_storage_ready",i==="none"?"login":"auth.status",i==="none"?"Run `skills-layer login` to create a secure local session.":"Credential storage metadata is present.",{credentialStorage:i,configPath:t.paths.configPath}),mcp:r?me("configured","mcp_configured","mcp.verify","MCP is configured locally; verify from a fresh agent session if tools are not visible.",{clientId:l(r,"clientId"),clientIds:Array.isArray(r.clientIds)?r.clientIds:void 0,mcpUrl:l(r,"mcpUrl")}):me("not_configured","mcp_not_configured","mcp.setup","Run `skills-layer mcp setup` or `skills-layer setup` to configure MCP."),guardianHooks:me(l(s,"enforcementLayer")==="not_installed"?"not_installed":"ok",l(s,"enforcementLayer")==="not_installed"?"guardian_hook_not_installed":"guardian_hook_installed","guardian.hook.status",l(s,"enforcementLayer")==="not_installed"?"Cloud Guardian checks work when called, but local pre-action hooks are not installed.":"At least one Skills Layer Security Hook is installed.",s),localPaths:me("ok","local_paths_resolved","doctor.deep","Local Skills Layer paths resolved.",{stateDir:t.paths.stateDir,configPath:t.paths.configPath,installsPath:t.paths.installsPath,mcpConfigPath:t.paths.mcpConfigPath}),agentTargets:me("ok","agent_targets_loaded","agents.list","Supported local agent targets loaded.",{count:o.length,results:o})};return h({status:"ok",deep:!0,sections:a,nextAction:t.apiKey?"status":"login",nextStep:t.apiKey?"Run `skills-layer status --json` for Cloud journey readiness.":"Run `skills-layer login` to sign in, then rerun `skills-layer doctor --deep --json`."},"Deep doctor diagnostics loaded.",e.json,t)}function me(e,t,n,i,r={}){return x({status:e,reasonCode:t,nextAction:n,nextStep:i,...r})}async function O(e,t,n,i,r){return await Et(e,{method:"POST",headers:j(i.apiKey),body:JSON.stringify(x(t))},n,i,r)}async function jt(e,t,n,i,r){return await Et(e,{method:"PATCH",headers:j(i.apiKey),body:JSON.stringify(x(t))},n,i,r)}async function Et(e,t,n,i,r){let s=await S(i,e,t);return h(s,r,n.json,i)}async function S(e,t,n={}){let i=await e.fetchFn(`${e.baseUrl}${t}`,n).catch(o=>{throw new Error(`Unable to reach ${e.baseUrl}. ${Z(o)}`)});if(!i.ok)throw await eu(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 eu(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new A(e.status,l(n,"error")??(e.statusText||"Request failed"),n)}catch{return new A(e.status,t)}return new A(e.status,e.statusText||"Request failed")}function T(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 Ne(e){return e?{authorization:`Bearer ${e}`}:{}}function j(e){return{"content-type":"application/json",...Ne(e)}}async function Lt(e){let t=await Jo(e);if(t.isFile())return[{path:V(e),content:await it(e,"utf8")}];if(!t.isDirectory())throw new Error(`Unsupported path: ${e}`);let n=[];if(await ws(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 ws(e,t,n){for(let i of await Lr(t,{withFileTypes:!0})){if(tu(i.name))continue;let r=E(t,i.name);if(i.isDirectory()){await ws(e,r,n);continue}if(!i.isFile())continue;let s=Xe(e,r).split("\\").join("/");try{n.push({path:s,content:await it(r,"utf8")})}catch{continue}}}function tu(e){return e===".git"||e==="node_modules"||e==="coverage"||e===nu()||e==="dist"}function nu(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}async function Rt(e,t){if(/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e))return;let n=K(t,e);try{return await jr(n),{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:await Lt(n)}}catch{return}}async function cn(e,t){let n=iu(t);if(n.length===0)return t;let i=[];for(let r of n){let s=vs(r.path),o=K(e.cwd,s),a=Xe(e.cwd,o);if(!a||a.startsWith("..")||Ue.isAbsolute(a))throw new Error(`Cloud install plan attempted to write outside the current workspace: ${r.path}`);if(await le(o,r.content),i.push({path:s,bytes:new TextEncoder().encode(r.content).length}),V(s).toLowerCase()==="skill.md"){let c=l(t,"skillSlug")??l(t,"slug")??V(ne(s)),u=await zn({backend:e,skillSlug:c,version:l(t,"version"),skillDocumentPath:o,skillDocumentContent:r.content});i.push(u)}}return{...t,materializedWrites:i}}function iu(e){return[...un(e.localWrites),...un(P(e,"installPlan")?.localWrites),...un(P(e,"materializationPlan")?.localWrites)]}function un(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 vs(e){let t=e.replaceAll("\\","/").replace(/^\.\/+/u,"");if(!t||t.includes("\0")||jn.isAbsolute(t)||Ue.isAbsolute(e)||t.split("/").includes(".."))throw new Error(`Cloud install plan returned an unsafe local write path: ${e}`);return t}async function ru(e,t){let n=l(e,"apiKey");if(!n)return;let i={version:Tr,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 Yn(t.paths.configPath,i,t)}async function Ce(e){let t=await D(e.paths.installsPath);if(!R(t))return{version:Fi,installs:{}};let n=R(t.installs)?_r(t.installs):R(t.skills)?_r(t.skills):{};return{version:typeof t.version=="number"?t.version:Fi,installs:n}}async function bs(e,t){await W(e.paths.installsPath,t)}async function Pt(e,t,n){let i=l(t,"skillSlug")??l(t,"slug")??n,r=await Ce(e);r.installs[i]={skillSlug:i,...t,savedAt:e.now()},await bs(e,r)}function _r(e){let t={};for(let[n,i]of Object.entries(e))t[n]=R(i)?i:{skillSlug:n,value:i};return t}var B=5;function h(e,t,n,i){let r=e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"?String(e.status):"ok",s=$t(e),o={schemaVersion:Un,status:r,statusFamily:su(r,s),summary:t,why:null,nextAction:null,nextStep:null,data:s,warnings:[],links:[],reasonCode:null,handoff:null};return{exitCode:0,stdout:n?JSON.stringify(o,null,2):cu(s,t,i),stderr:""}}function su(e,t){let n=e.toLowerCase();return n==="pass"||n.includes("dry")?"dry_run_passed":n.includes("created")?"created":n.includes("updated")||n.includes("configured")||n.includes("synced")?"updated":n.includes("revoked")||n.includes("removed")||n.includes("disconnected")?"removed":n.includes("approval")||n.includes("handoff")||R(t)&&t.handoff?"human_handoff":"ok"}function ou(e){return e?e==="login_required"||e==="unauthorized"?"login_required":e==="confirmation_required"?"confirmation_required":e.includes("not_found")||e==="missing_record"?"not_found":e.includes("payment")||e.includes("checkout")||e.includes("purchase")?"payment_required":e.includes("source")?"source_required":e.includes("backend")||e.includes("unreachable")||e.includes("network")?"backend_unreachable":e.includes("agent")||e.includes("client")||e.includes("unsupported")?"unsupported_client":e.includes("blocked")||e.includes("policy")||e.includes("guardian")?"policy_blocked":e.includes("not_allowed")||e.includes("permission_denied")||e.includes("invalid_transition")?"operation_not_allowed":"invalid_input":null}var au="<redacted>";function $t(e){if(Array.isArray(e))return e.map(n=>$t(n));if(!R(e))return e;let t={};for(let[n,i]of Object.entries(e))t[n]=lu(n)?au:$t(i);return t}function lu(e){let t=e.replace(/[^a-z0-9]/giu,"").toLowerCase();return t==="devicecode"||t==="usercode"||t==="verificationcode"||t==="recoverycode"||t==="onetimecode"||t==="password"||t==="clientsecret"||t==="privatekey"||t==="apikey"||t==="rawapikey"||t==="accesstoken"||t==="refreshtoken"||t==="bearertoken"||t==="mcptoken"||t.endsWith("secret")?!0:t.endsWith("token")&&t!=="tokenprefix"}function cu(e,t,n){let i=Q(n);if(R(e)){if(t==="Status loaded."&&xr(e))return mu(e,t,i);if(t==="Doctor checks loaded."&&xr(e))return fu(e,t,i);if(t==="Creator payout profile loaded.")return Tu(e,t,i);if(t==="Creator earnings loaded."||t==="Earnings loaded.")return Nu(e,"Creator earnings loaded.",i);if(t==="Creator payouts loaded."||t==="Payouts loaded.")return Fu(e,"Creator payouts loaded.",i);if(t==="Guardian check complete.")return pu(e,t,i);if(t==="Reviews loaded.")return du(e,t,i);if(t==="Categories loaded.")return uu(e,t,i)}let r=[`${i.ok("OK")} ${t}`];if(R(e)){let s=xs(e,i);s.length>0&&r.push("",...s);let o=js(e);o.length>0&&r.push("",i.section("Next"),...o.map(a=>` ${i.arrow} ${a}`))}return r.join(`
|
|
1292
|
-
`)}function
|
|
1293
|
-
`)):(i.slice(0,
|
|
1294
|
-
`))}function
|
|
1295
|
-
`)}function
|
|
1296
|
-
`)}function
|
|
1297
|
-
`)}function
|
|
1298
|
-
`)}function
|
|
1299
|
-
`)}function
|
|
1300
|
-
`)}function
|
|
1301
|
-
`)}function
|
|
1302
|
-
`)}function
|
|
1303
|
-
`)}function
|
|
1304
|
-
`)}function
|
|
1305
|
-
`)}function
|
|
1306
|
-
`)}function
|
|
1307
|
-
`)}function
|
|
1308
|
-
`,{encoding:"utf8",mode:384}),await
|
|
1296
|
+
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 Ad(o,i);return H(c)?c:c.status==="verified"||c.status==="recovered"?await Wt(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):$d(c)?k(Ld(c),n.json):k("Social auth completed with an unexpected response.",n.json)}function H(e){return x(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function Rd(e){try{let t=JSON.parse(e);return x(t)?t.data:void 0}catch{return}}function $d(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 Ad(e,t){for(let n=0;n<120;n+=1)try{let i=await S(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:ue(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:ue(i,"roles"),linkedAccount:typeof i.linkedAccount=="boolean"?i.linkedAccount:void 0}:r==="linked"?{status:r}:r==="registration_required"||r==="state_expired"||r==="provider_mismatch"||r==="identity_conflict"||r==="email_required"||r==="failed"?{status:r,error:l(i,"error")}:k("Social auth completed with an unexpected response.",!1)}catch(i){if(i instanceof A&&(i.status===404||i.status===429)){await t.sleep(1500);continue}return k(te(i),!1)}return k("Timed out while waiting for social auth to complete.",!1)}async function Ed(e,t){for(let n=0;n<120;n+=1)try{let r=(await S(t,"/api/v1/purchases",{headers:F(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(te(i),!1)}return k("Timed out while waiting for purchase confirmation.",!1)}async function Id(e,t){for(let n=0;n<120;n+=1)try{let i=await S(t,`/api/v1/me/private-skill-charges/${encodeURIComponent(e)}`,{headers:F(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 A&&i.status===429){await t.sleep(1500);continue}return k(te(i),!1)}return k("Timed out while waiting for payment confirmation.",!1)}function jd(e){let t=C(e,"accountLink");return(t?l(t,"url"):void 0)??l(e,"url")??l(e,"setupUrl")}function Ld(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 pt(e,t,n={}){let r=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole?await S({...e,apiKey:t},"/api/v1/me",{headers:{...F(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 S({...e,apiKey:t},"/api/v1/capabilities",{headers:F(t)}),a={version:bs,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:ue(r,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await Ri(e.paths.configPath,a,e),await ee(e.paths.backendPreferencePath,{version:ci,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),a}function ds(e,t){let n=Xt(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 $(e,t,n,i,r={}){let s=r.authenticated?F(n.apiKey,n.authBlockedMessage):yt(n.apiKey);return await Yt(e,{headers:s},t,n,i)}async function Ud(e,t){if(e.deep)return await Td(e,t);let n=await S(t,"/api/v1/doctor",{headers:yt(t.apiKey)}),i=await We(t),r=await rd(t),s=[...ho(n),ad(i,r)];return h({...n,guardian:{...i,policy:r},checks:s},"Doctor checks loaded.",e.json,t)}async function Td(e,t){let n;try{let c=await S(t,"/api/v1/status",{headers:yt(t.apiKey)});n=ke("ok","backend_reachable","status","Backend status loaded.",{baseUrl:t.baseUrl,edition:l(c,"edition"),capabilityCount:Array.isArray(c.capabilities)?c.capabilities.length:void 0})}catch(c){n=ke("error","backend_unreachable","backend.status","Selected backend could not be reached.",{baseUrl:t.baseUrl,error:te(c)})}let i=t.config?.credentialStorage??(t.apiKey?"local_file_locked":"none"),r=await W(t.paths.mcpConfigPath),s=await We(t),o=Pe(t.env,t.platform,t.cwd).map(c=>({id:c.id,displayName:c.displayName,capabilities:c.capabilities})),a={backend:n,auth:t.apiKey?ke("ok","authenticated","whoami","A local session is available for the selected backend.",{email:t.config?.email,role:t.config?.role,savedLoginMatchesSelectedBackend:!0}):ke("login_required","login_required","login","No usable local session is available for the selected backend.",{savedLoginMatchesSelectedBackend:t.config?.baseUrl?mt(t.config.baseUrl,t.baseUrl):!0}),credentialStorage:ke(i==="none"?"not_configured":"ok",i==="none"?"credential_storage_not_configured":"credential_storage_ready",i==="none"?"login":"auth.status",i==="none"?"Run `skills-layer login` to create a secure local session.":"Credential storage metadata is present.",{credentialStorage:i,configPath:t.paths.configPath}),mcp:r?ke("configured","mcp_configured","mcp.verify","MCP is configured locally; verify from a fresh agent session if tools are not visible.",{clientId:l(r,"clientId"),clientIds:Array.isArray(r.clientIds)?r.clientIds:void 0,mcpUrl:l(r,"mcpUrl")}):ke("not_configured","mcp_not_configured","mcp.setup","Run `skills-layer mcp setup` or `skills-layer setup` to configure MCP."),guardianHooks:ke(l(s,"enforcementLayer")==="not_installed"?"not_installed":"ok",l(s,"enforcementLayer")==="not_installed"?"guardian_hook_not_installed":"guardian_hook_installed","guardian.hook.status",l(s,"enforcementLayer")==="not_installed"?"Cloud Guardian checks work when called, but local pre-action hooks are not installed.":"At least one Skills Layer Security Hook is installed.",s),localPaths:ke("ok","local_paths_resolved","doctor.deep","Local Skills Layer paths resolved.",{stateDir:t.paths.stateDir,configPath:t.paths.configPath,installsPath:t.paths.installsPath,mcpConfigPath:t.paths.mcpConfigPath}),agentTargets:ke("ok","agent_targets_loaded","agents.list","Supported local agent targets loaded.",{count:o.length,results:o})};return h({status:"ok",deep:!0,sections:a,nextAction:t.apiKey?"status":"login",nextStep:t.apiKey?"Run `skills-layer status --json` for Cloud journey readiness.":"Run `skills-layer login` to sign in, then rerun `skills-layer doctor --deep --json`."},"Deep doctor diagnostics loaded.",e.json,t)}function ke(e,t,n,i,r={}){return _({status:e,reasonCode:t,nextAction:n,nextStep:i,...r})}async function z(e,t,n,i,r){return await Yt(e,{method:"POST",headers:I(i.apiKey),body:JSON.stringify(_(t))},n,i,r)}async function Jt(e,t,n,i,r){return await Yt(e,{method:"PATCH",headers:I(i.apiKey),body:JSON.stringify(_(t))},n,i,r)}async function Yt(e,t,n,i,r){let s=await S(i,e,t);return h(s,r,n.json,i)}async function S(e,t,n={}){let i=await e.fetchFn(`${e.baseUrl}${t}`,n).catch(o=>{throw new Error(`Unable to reach ${e.baseUrl}. ${te(o)}`)});if(!i.ok)throw await Fd(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 Fd(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new A(e.status,l(n,"error")??(e.statusText||"Request failed"),n)}catch{return new A(e.status,t)}return new A(e.status,e.statusText||"Request failed")}function F(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 yt(e){return e?{authorization:`Bearer ${e}`}:{}}function I(e){return{"content-type":"application/json",...yt(e)}}async function Zt(e){let t=await yl(e);if(t.isFile())return[{path:D(e),content:await He(e,"utf8")}];if(!t.isDirectory())throw new Error(`Unsupported path: ${e}`);let n=[];if(await uo(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 uo(e,t,n){for(let i of await ii(t,{withFileTypes:!0})){if(po(i.name))continue;let r=U(t,i.name);if(i.isDirectory()){await uo(e,r,n);continue}if(!i.isFile())continue;let s=Ke(e,r).split("\\").join("/");try{n.push({path:s,content:await He(r,"utf8")})}catch{continue}}}function po(e){return e===".git"||e==="node_modules"||e==="coverage"||e===Nd()||e==="dist"}function Nd(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}async function Vt(e,t){if(/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e))return;let n=V(t,e);try{return await ws(n),{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:await Zt(n)}}catch{return}}async function Tn(e,t){let n=Md(t);if(n.length===0)return t;let i=[];for(let r of n){let s=go(r.path),o=V(e.cwd,s),a=Ke(e.cwd,o);if(!a||a.startsWith("..")||ze.isAbsolute(a))throw new Error(`Cloud install plan attempted to write outside the current workspace: ${r.path}`);if(await ge(o,r.content),i.push({path:s,bytes:new TextEncoder().encode(r.content).length}),D(s).toLowerCase()==="skill.md"){let c=l(t,"skillSlug")??l(t,"slug")??D(ae(s)),u=await Ci({backend:e,skillSlug:c,version:l(t,"version"),skillDocumentPath:o,skillDocumentContent:r.content});i.push(u)}}return{...t,materializedWrites:i}}function Md(e){return[...Fn(e.localWrites),...Fn(C(e,"installPlan")?.localWrites),...Fn(C(e,"materializationPlan")?.localWrites)]}function Fn(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 go(e){let t=e.replaceAll("\\","/").replace(/^\.\/+/u,"");if(!t||t.includes("\0")||oi.isAbsolute(t)||ze.isAbsolute(e)||t.split("/").includes(".."))throw new Error(`Cloud install plan returned an unsafe local write path: ${e}`);return t}async function Bd(e,t){let n=l(e,"apiKey");if(!n)return;let i={version:bs,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:ue(e,"roles")??t.config?.roles,lastSelectedAgent:t.config?.lastSelectedAgent,savedAt:t.now()};await Ri(t.paths.configPath,i,t)}async function Le(e){let t=await W(e.paths.installsPath);if(!x(t))return{version:Sr,installs:{}};let n=x(t.installs)?ps(t.installs):x(t.skills)?ps(t.skills):{};return{version:typeof t.version=="number"?t.version:Sr,installs:n}}async function mo(e,t){await ee(e.paths.installsPath,t)}async function Ot(e,t,n){let i=l(t,"skillSlug")??l(t,"slug")??n,r=await Le(e);r.installs[i]={skillSlug:i,...t,savedAt:e.now()},await mo(e,r)}function ps(e){let t={};for(let[n,i]of Object.entries(e))t[n]=x(i)?i:{skillSlug:n,value:i};return t}var O=5;function h(e,t,n,i){let r=e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"?String(e.status):"ok",s=Gt(e),o={schemaVersion:ui,status:r,statusFamily:Od(r,s),summary:t,why:null,nextAction:null,nextStep:null,data:s,warnings:[],links:[],reasonCode:null,handoff:null};return{exitCode:0,stdout:n?JSON.stringify(o,null,2):Vd(s,t,i),stderr:""}}function Od(e,t){let n=e.toLowerCase();return n==="pass"||n.includes("dry")?"dry_run_passed":n.includes("created")?"created":n.includes("updated")||n.includes("configured")||n.includes("synced")?"updated":n.includes("revoked")||n.includes("removed")||n.includes("disconnected")?"removed":n.includes("approval")||n.includes("handoff")||x(t)&&t.handoff?"human_handoff":"ok"}function qd(e){return e?e==="login_required"||e==="unauthorized"?"login_required":e==="confirmation_required"?"confirmation_required":e.includes("not_found")||e==="missing_record"?"not_found":e.includes("payment")||e.includes("checkout")||e.includes("purchase")?"payment_required":e.includes("source")?"source_required":e.includes("backend")||e.includes("unreachable")||e.includes("network")?"backend_unreachable":e.includes("agent")||e.includes("client")||e.includes("unsupported")?"unsupported_client":e.includes("blocked")||e.includes("policy")||e.includes("guardian")?"policy_blocked":e.includes("not_allowed")||e.includes("permission_denied")||e.includes("invalid_transition")?"operation_not_allowed":"invalid_input":null}var Dd="<redacted>";function Gt(e){if(Array.isArray(e))return e.map(n=>Gt(n));if(!x(e))return e;let t={};for(let[n,i]of Object.entries(e))t[n]=Kd(n)?Dd:Gt(i);return t}function Kd(e){let t=e.replace(/[^a-z0-9]/giu,"").toLowerCase();return t==="devicecode"||t==="usercode"||t==="verificationcode"||t==="recoverycode"||t==="onetimecode"||t==="password"||t==="clientsecret"||t==="privatekey"||t==="apikey"||t==="rawapikey"||t==="accesstoken"||t==="refreshtoken"||t==="bearertoken"||t==="mcptoken"||t.endsWith("secret")?!0:t.endsWith("token")&&t!=="tokenprefix"}function Vd(e,t,n){let i=re(n);if(x(e)){if(t==="Status loaded."&&gs(e))return Jd(e,t,i);if(t==="Doctor checks loaded."&&gs(e))return Yd(e,t,i);if(t==="Creator payout profile loaded.")return hp(e,t,i);if(t==="Creator earnings loaded."||t==="Earnings loaded.")return yp(e,"Creator earnings loaded.",i);if(t==="Creator payouts loaded."||t==="Payouts loaded.")return kp(e,"Creator payouts loaded.",i);if(t==="Guardian check complete.")return zd(e,t,i);if(t==="Reviews loaded.")return Hd(e,t,i);if(t==="Categories loaded.")return Gd(e,t,i)}let r=[`${i.ok("OK")} ${t}`];if(x(e)){let s=wo(e,i);s.length>0&&r.push("",...s);let o=Co(e);o.length>0&&r.push("",i.section("Next"),...o.map(a=>` ${i.arrow} ${a}`))}return r.join(`
|
|
1297
|
+
`)}function Gd(e,t,n){let i=ve(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(`
|
|
1298
|
+
`)):(i.slice(0,O).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}. ${Po(c)}`);let d=[a?`slug: ${a}`:void 0,u!==void 0?`count: ${G("count",u)}`:void 0].filter(g=>!!g);d.length>0&&r.push(` ${d.join("; ")}`)}),i.length>O&&r.push(` ${n.muted(`... ${i.length-O} more`)}`),r.join(`
|
|
1299
|
+
`))}function Hd(e,t,n){let i=ve(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: ${G("rating",d)}`:void 0,g?`status: ${g}`:void 0,f?`updated: ${f}`:void 0].filter(v=>!!v);r.push(`${o+1}. ${u}`),m.length>0&&r.push(` ${m.join("; ")}`);let y=l(s,"feedback")??l(s,"comment")??l(s,"message");y&&r.push(` ${n.label("feedback")}: ${Ge(y)}`)}),r.join(`
|
|
1300
|
+
`)}function zd(e,t,n){let i=C(e,"decision"),r=C(e,"enforcement"),s=C(e,"auditEvent"),o=N(i,"status")??N(r,"status")??"unknown",a=N(r,"actionType")??N(s,"actionType")??"action",c=N(i,"capability")??N(r,"capability")??"not specified",u=N(i,"reasonCode")??N(r,"reasonCode")??"not specified",d=N(i,"message")??N(r,"message")??"Guardian policy resolved this action.",g=N(s,"skillSlug")??"unknown",f=N(s,"version")??"unknown",m=Nn(r,"canExecute"),y=Nn(r,"auditRequired"),v=Nn(r,"telemetryRequired"),P=o==="blocked"?"BLOCKED":o==="allowed"?"ALLOWED":"WARNING",R=[`${n.ok("OK")} ${t}`,"",n.section(`${P} ${Wd(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")}: ${y===!1?"no":"yes"}`,` ${n.label("Cloud telemetry")}: ${v===!0?"yes":"no"}`,"",n.section("Next")];return o==="blocked"?R.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.`):R.push(` ${n.arrow} Continue only with the action Guardian evaluated.`,` ${n.arrow} Re-run guardian check if the action changes.`),R.join(`
|
|
1301
|
+
`)}function Nn(e,t){if(x(e))return typeof e[t]=="boolean"?e[t]:void 0}function N(e,t){return x(e)?l(e,t):void 0}function Wd(e){return e.split(/[_-]+/u).filter(Boolean).map(t=>`${t[0]?.toUpperCase()??""}${t.slice(1)}`).join(" ")}function gs(e){return!!(C(e,"backend")&&C(e,"auth")&&Array.isArray(e.checks))}function Jd(e,t,n){let i=[`${n.ok("OK")} ${t}`,"",n.section("Readiness")],r=l(e,"summary");r&&i.push(` ${r}`);let s=C(e,"backend"),o=s?ep(s):void 0;o&&i.push(` ${n.label("Backend")}: ${o}`);let a=C(e,"auth"),c=a?tp(a):void 0;c&&i.push(` ${n.label("Account")}: ${c}`);let u=a?T(a,"workspaceCount"):void 0;u!==void 0&&i.push(` ${n.label("Workspaces")}: ${u}`);let d=a?T(a,"libraryCount"):void 0;d!==void 0&&i.push(` ${n.label("Owned skills")}: ${d}`);let g=fo(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(`
|
|
1302
|
+
`)}function Yd(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=ho(e),a=o.filter(d=>np(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 y=l(d,"summary");y&&i.push(` ${y}`);let v=l(d,"why");if(v&&i.push(` ${n.label("Why")}: ${v}`),f!=="pass"){let P=l(d,"nextStep");P&&i.push(` ${n.label("Fix")}: ${P}`);let R=l(d,"recommendedCommand");R&&i.push(` ${n.label("Try")}: ${R}`)}});let u=fo(e);return u.length>0&&i.push("",n.section(a.length>0?"Recommended Fix":"Next"),...u.map(d=>` ${n.arrow} ${d}`)),i.join(`
|
|
1303
|
+
`)}function Zd(e,t,n,i){let r=[`${n.ok("OK")} ${t}`],s=ue(e,"requestedSlugs");s&&s.length>0&&r.push("",n.section("Requested"),` ${s.join(", ")}`);let o=ve(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=Qn(d)??`Skill ${g+1}`;r.push(`${g+1}. ${f}`);let m=Qd(d);m&&r.push(` ${m}`);let y=So(d);y&&r.push(` ${n.label("summary")}: ${i?y.replace(/\s+/gu," ").trim():Ge(y)}`)});let a=ve(e.missing);a.length>0&&(r.push("",n.section(`Missing (${a.length})`)),a.forEach((d,g)=>{let f=l(d,"slug")??l(d,"skillSlug")??Qn(d)??`Entry ${g+1}`,m=l(d,"reason")??l(d,"status");r.push(`${g+1}. ${m?`${f} - ${m}`:f}`)}));let c=ue(e,"guidance")??De(e.guidance);c.length>0&&r.push("",n.section("Guidance"),...c.slice(0,3).map(d=>` ${n.arrow} ${Ge(d)}`));let u=Xd(o);return u.length>0&&r.push("",n.section("Next"),...u.map(d=>` ${n.arrow} ${d}`)),r.join(`
|
|
1304
|
+
`)}function Qd(e){let t=C(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}: ${G(String(o),a)}`]).join("; ")}function Xd(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 ep(e){let t=l(e,"edition"),n=l(e,"baseUrl");return t&&n?`${t} at ${n}`:t??n}function tp(e){let t=l(e,"state");if(t&&t!=="authenticated")return t==="anonymous"?"not signed in":t;let n=l(e,"email"),i=ue(e,"roles");return n&&i&&i.length>0?`${n} (${i.join(", ")})`:n??l(e,"role")}function fo(e){let t=[],n=l(e,"recommendedCommand");n&&t.push(n);let i=l(e,"nextStep");return i&&t.push(i),t}function ho(e){return Array.isArray(e.checks)?e.checks.filter(x):[]}function np(e){return e!==void 0&&e!=="pass"&&e!=="warn"&&e!=="advisory"}function ve(e){return Array.isArray(e)?e.filter(x):[]}function De(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function ip(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 rp={"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 sp(e){let t=De(e.capabilities);return{status:"ok",edition:l(e,"edition")??"unknown",summary:"Public product capabilities available on the selected backend.",capabilities:t.map(n=>({name:rp[n]??en(n.replace(/^[^.]+\./u,"").replace(/[._-]+/gu," ")),available:!0})),count:t.length}}function op(e,t){let n=p(e);if(!n)return;let i=Number(n);return!Number.isInteger(i)||i<=0?k("help optimize-tokens --max-characters must be a positive integer.",t):i<120||i>4e3?k("help optimize-tokens --max-characters must be between 120 and 4000.",t):i}function ap(e,t,n){let i=re(n),r=C(e,"validation")??e,s=C(r,"parsedSkill")??C(e,"parsedSkill"),o=s?C(s,"frontmatter"):void 0,a=l(e,"skillSlug")??(o?l(o,"name"):void 0),c=r.valid===!0||e.valid===!0,u=Mn(r,e,"issues"),d=Mn(r,e,"warnings"),g=Mn(r,e,"advice"),f=C(r,"stats")??C(e,"stats"),m=[`${i.ok("OK")} Validation complete.`,"",i.section("Bundle")];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`);let y=C(e,"evalReadiness");if(y){let v=C(y,"summaryEnvelope"),P=Array.isArray(v?.statuses)?v.statuses.map(j=>String(j)).join(", "):void 0,R=C(y,"score"),L=R?T(R,"effectiveScorePercent"):void 0,K=R?T(R,"overallScore"):void 0;m.push("",i.section("Effectiveness Eval")),m.push(` ${i.label("Posture")}: ${l(y,"label")??l(y,"status")??"limited"}`),m.push(` ${i.label("Origin")}: ${l(y,"origin")??"inferred"}`),L!==void 0?m.push(` ${i.label("Effective score")}: ${Ht(L)}`):K!==void 0&&m.push(` ${i.label("Effective score")}: ${Ht(K*100)}`),m.push(` ${i.label("Artifact digest")}: ${l(y,"artifactDigest")??"unavailable"}`),y.runtimeFileCount!==void 0&&m.push(` ${i.label("Runtime files")}: ${G("runtimeFileCount",y.runtimeFileCount)}`),y.evidenceFileCount!==void 0&&m.push(` ${i.label("Evidence files excluded")}: ${G("evidenceFileCount",y.evidenceFileCount)}`),m.push(` ${i.label("Submit envelope")}: mandatory${P?` (${P})`:""}`)}if(f){let v=f.fileCount??f.files??e.fileCount,P=f.bodyWordCount??f.bodyWords??e.bodyWordCount;m.push("",i.section("File Summary")),v!==void 0&&m.push(` ${i.label("File count")}: ${G("fileCount",v)}`),P!==void 0&&m.push(` ${i.label("Body words")}: ${G("bodyWordCount",P)}`)}return m.push("",...Bn("Issues",u,i,"No blocking issues found.")),m.push("",...Bn("Warnings",d,i,"No warnings returned.")),m.push("",...Bn("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(`
|
|
1305
|
+
`)}function Mn(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 Bn(e,t,n,i){let r=[n.section(`${e} (${t.length})`)];return t.length===0?(r.push(` ${n.muted(i)}`),r):(t.slice(0,O).forEach((s,o)=>{r.push(`${o+1}. ${yo(s)}`)}),r)}function yo(e){return x(e)?(l(e,"message")??l(e,"title")??l(e,"code")??l(e,"path")??gt(e))||"Details available with --json":G("",e)}function lp(e,t,n){let i=re(n),r=cp(e),s=up(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,O).forEach((c,u)=>{o.push(`${u+1}. ${dp(c,u)}`)}),o.push("",i.section(`Guidance (${s.length})`)),s.length===0&&o.push(` ${i.muted("No extra trigger guidance returned.")}`),s.slice(0,O).forEach((c,u)=>{o.push(`${u+1}. ${c}`)}),o.push("",i.section("Next")),o.push(` ${i.arrow} skills-layer validate ${t}`),o.push(` ${i.arrow} skills-layer creator submit ${t} --dry-run`),o.join(`
|
|
1306
|
+
`)}function cp(e){return[...ve(e.promptResults),...ve(e.results),...ve(e.shouldTriggerResults),...ve(e.shouldNotTriggerResults),...ve(e.paraphraseResults)]}function up(e){let t=De(e.guidance),n=ve(e.guidance).map(i=>yo(i));return[...t,...n]}function dp(e,t){let n=l(e,"prompt")??l(e,"text")??l(e,"input")??`Prompt ${t+1}`,i=pp(e),r=gp(e),s=mp(e),o=e.score??e.confidence,a=l(e,"reason")??l(e,"explanation")??l(e,"message");return[`"${Ge(n)}"`,i?`expected: ${i}`:void 0,r?`actual: ${r}`:void 0,s,o!==void 0?`score: ${G("score",o)}`:void 0,a?`reason: ${Ge(a)}`:void 0].filter(c=>!!c).join("; ")}function pp(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 gp(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 mp(e){return typeof e.passed=="boolean"?e.passed?"pass":"fail":typeof e.pass=="boolean"?e.pass?"pass":"fail":l(e,"status")}function fp(e,t,n,i){let r=re(i),s=l(e,"skillSlug")??D(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(`
|
|
1307
|
+
`)}function hp(e,t,n){let i=C(e,"profile")??e,r=On(i,"requirementsCurrentlyDue"),s=On(i,"requirementsPastDue"),o=On(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")}: ${Ft(l(i,"status"))}`),d.push(` ${n.label("Ready for payouts")}: ${fs(c)}`),d.push(` ${n.label("Account details submitted")}: ${fs(i.detailsSubmitted)}`),d.push(` ${n.label("Currency")}: ${Ft(l(i,"currency")?.toUpperCase())}`),d.push(` ${n.label("Country")}: ${Ft(l(i,"country")?.toUpperCase())}`),d.push(` ${n.label("Minimum withdrawal")}: ${wp(i)}`),d.push(` ${n.label("Updated at")}: ${Ft(l(i,"updatedAt"))}`),d.push("",n.section("Requirements")),d.push(` ${n.label("Currently due")}: ${qn(r)}`),d.push(` ${n.label("Past due")}: ${qn(s)}`),d.push(` ${n.label("Pending verification")}: ${qn(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(`
|
|
1308
|
+
`)}function yp(e,t,n){let i=Zn(e),r=xi(e,"withdrawableBalanceCents"),s=[`${n.ok("OK")} ${t}`,"",n.section("Earnings Summary")];return s.push(` ${n.label("Gross sales")}: ${X(e,"successfulSalesCents",i)}`),s.push(` ${n.label("Platform fees")}: ${X(e,"platformFeeCents",i)}`),s.push(` ${n.label("Refunds requested")}: ${X(e,"refundRequestedCents",i)}`),s.push(` ${n.label("Refunded")}: ${X(e,"refundedCents",i)}`),s.push(` ${n.label("Estimated available")}: ${X(e,"estimatedAvailableCents",i)}`),s.push(` ${n.label("Withdrawable now")}: ${X(e,"withdrawableBalanceCents",i)}`),s.push(` ${n.label("Held balance")}: ${X(e,"heldBalanceCents",i)}`),s.push(` ${n.label("Refund exposure")}: ${X(e,"refundExposureCents",i)}`),s.push("",n.section("Activity")),s.push(` ${n.label("Successful purchases")}: ${ms(e,"successfulPurchaseCount")}`),s.push(` ${n.label("Refund requests")}: ${ms(e,"refundRequestedCount")}`),s.push(` ${n.label("Pending payouts")}: ${X(e,"pendingPayoutCents",i)}`),s.push(` ${n.label("Completed payouts")}: ${X(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(`
|
|
1309
|
+
`)}function kp(e,t,n){let i=Array.isArray(e.results)?e.results:[],r=Zn(e,i),s=xi(e,"withdrawableBalanceCents"),o=[`${n.ok("OK")} ${t}`,"",n.section("Payout History")];return o.push(` ${n.label("Withdrawable now")}: ${X(e,"withdrawableBalanceCents",r)}`),o.push(` ${n.label("Pending payouts")}: ${X(e,"pendingPayoutCents",r)}`),o.push(` ${n.label("Completed payouts")}: ${X(e,"completedPayoutCents",r)}`),o.push("",n.section(`Requests (${i.length})`)),i.length===0?o.push(` ${n.muted("No payout requests yet.")}`):(i.slice(0,O).forEach((a,c)=>{if(!x(a)){o.push(`${c+1}. ${G("",a)}`);return}let u=Zn(a,void 0,r),d=l(a,"payoutId")??l(a,"id")??`Payout ${c+1}`,g=l(a,"status")??"unknown",f=X(a,"amountCents",u),m=l(a,"requestedAt"),y=l(a,"completedAt"),v=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}`),y&&o.push(` ${n.label("Completed")}: ${y}`),v&&o.push(` ${n.label("Reason")}: ${v}`)}),i.length>O&&o.push(` ${n.muted(`... ${i.length-O} more`)}`)),o.push("",n.section("Guidance")),i.length===0?o.push("1. Payouts appear here after you request a withdrawal."):o.push("1. Use this history to track requested, processing, paid, or failed payouts."),o.push("2. Check payout profile if setup or verification looks incomplete."),o.push("",n.section("Next")),s>0&&o.push(` ${n.arrow} skills-layer creator withdraw --amount-cents ${s}`),o.push(` ${n.arrow} skills-layer creator earnings`),o.push(` ${n.arrow} skills-layer creator payout-profile`),o.join(`
|
|
1310
|
+
`)}function Zn(e,t,n="GBP"){let i=l(e,"currency");if(i)return i.toUpperCase();let r=t?.find(x);if(r){let s=l(r,"currency");if(s)return s.toUpperCase()}return n}function xi(e,t){return T(e,t)??0}function ms(e,t){return T(e,t)??0}function X(e,t,n){return`${ko(xi(e,t))} ${n}`}function On(e,t){return(ue(e,t)??[]).map(n=>n.replace(/[._-]+/gu," "))}function qn(e){return e.length>0?e.join(", "):"none"}function fs(e){return e===!0?"yes":e===!1?"no":"unknown"}function Ft(e){return e??"none"}function wp(e){let t=T(e,"minimumWithdrawalAmountCents"),n=l(e,"currency")?.toUpperCase()??"minor units";return t===void 0?"none":`${ko(t)} ${n}`}function ko(e){return(e/100).toFixed(2).replace(/\.00$/u,"").replace(/(\.\d)0$/u,"$1")}function re(e){let t=vp(e);return{ok:n=>t?Oe(32,n):n,section:n=>t?Oe(1,Oe(36,n)):n,label:n=>t?Oe(1,n):n,muted:n=>t?Oe(2,n):n,arrow:t?Oe(36,"->"):"->"}}function vp(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 Oe(e,t){return`\x1B[${e}m${t}\x1B[0m`}function wo(e,t){let n=[],i=Pp(e,t);i.length>0&&n.push(...i);let r=bp(e,t);r.length>0&&n.push(...r);for(let[s,o]of xp(e))if(Array.isArray(o))n.push(...Sp(s,o,t));else if(x(o)){let a=gt(o);a&&n.push(` ${t.label(Xn(s))}: ${a}`)}else n.push(` ${t.label(Xn(s))}: ${G(s,o)}`);return n}function bp(e,t){let n=C(e,"effectiveness");if(!n)return[];let i=l(n,"label"),r=l(n,"latestSummaryStatus"),s=T(n,"evidenceCount"),o=C(n,"score"),a=o?T(o,"overallScore"):void 0,c=o?T(o,"effectiveScorePercent"):void 0,u=o?C(o,"components"):void 0,d=u?T(u,"passRate"):void 0,g=u?T(u,"coverageRatio"):void 0;if(!i&&r===void 0&&s===void 0&&a===void 0)return[];let f=[t.section("Effectiveness")];return i&&f.push(` ${t.label("Label")}: ${i}`),r&&f.push(` ${t.label("Latest summary")}: ${r}`),s!==void 0&&f.push(` ${t.label("Evidence count")}: ${s}`),c!==void 0?f.push(` ${t.label("Effective score")}: ${Ht(c)}`):a!==void 0&&f.push(` ${t.label("Effective score")}: ${Ht(a*100)}`),d!==void 0&&f.push(` ${t.label("Pass rate")}: ${d}`),g!==void 0&&f.push(` ${t.label("Coverage")}: ${g}`),f}function Ht(e){let t=Math.round(e*10)/10;return`${Number.isInteger(t)?t.toFixed(0):t.toFixed(1)}%`}function Sp(e,t,n){let i=Rp(e),r=[n.section(`${i} (${t.length})`)];return t.length===0?(r.push(` ${n.muted("No entries.")}`),r):(t.slice(0,O).forEach((s,o)=>{r.push(...vo(s,o,n))}),t.length>O&&r.push(` ${n.muted(`... ${t.length-O} more`)}`),r)}function vo(e,t,n){if(!x(e))return[`${t+1}. ${G("",e)}`];let i=Qn(e)??oe(gt(e))??`Item ${t+1}`,r=[`${t+1}. ${i}`],s=So(e);s&&r.push(` ${s}`);let o=gt(e);return o&&r.push(` ${o}`),r}function Pp(e,t){let n=Ru(e,t);if(n.length>0)return n;let i=C(e,"capabilityProfile"),r=i?l(i,"runtimeRisk"):void 0;return r?[t.section("Trust"),` ${t.label("Runtime risk")}: ${r}`]:[]}function Cp(e,t,n){let i=re(n),r=l(e,"skillSlug")??t,s=l(e,"runtimeRisk")??(C(e,"capabilityProfile")?l(C(e,"capabilityProfile"),"runtimeRisk"):void 0),o=[`${i.ok("OK")} Creator security report loaded.`,"",i.section("Creator Security")];e.securityScore!==void 0&&o.push(` ${i.label("Security score")}: ${G("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=De(e.reviewDegradedReasons).includes(u),g=De(e.trustBadges).filter(y=>y==="capability-mismatch"),f=De(e.trustBadges).filter(y=>y!=="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((y,v)=>{o.push(`${d?v+2:v+1}. ${y==="capability-mismatch"?"Capability declaration needs review.":y}`)})),f.length>0&&(o.push("",i.section(`Trust badges (${f.length})`)),f.slice(0,O).forEach((y,v)=>o.push(`${v+1}. ${y}`)));let m=Array.isArray(e.findings)?e.findings:[];return o.push("",i.section(`Findings (${m.length})`)),m.length===0?o.push(` ${i.muted("No entries.")}`):m.slice(0,O).forEach((y,v)=>{o.push(...vo(y,v,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(`
|
|
1311
|
+
`)}function _p(e,t,n){let r=C(e,"report")??e,s=re(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")}: ${G("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(`
|
|
1312
|
+
`)}function xp(e){return Object.entries(e).filter(([t,n])=>bo(t,n))}function bo(e,t){let n=e.toLowerCase();return n==="status"||n==="securityscore"||n==="recommendation"||n==="capabilityprofile"||n==="securityposture"||n==="trust"||n==="effectiveness"||n.includes("apikey")||n.includes("secret")||n.includes("token")||n==="content"?!1:t!==void 0}function gt(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(!bo(r,e[r]))return[];let o=e[r];return o===void 0?[]:[`${s}: ${G(r,o)}`]}),i=C(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 So(e){return l(e,"shortDescription")??l(e,"summary")??l(e,"description")??l(e,"message")}function Qn(e){return l(e,"displayName")??l(e,"name")??l(e,"title")??l(e,"slug")??l(e,"skillSlug")??l(e,"code")??l(e,"id")}function G(e,t){return e==="downloadUrl"?"<hidden; use --json or --output>":typeof t=="string"?e.toLowerCase()==="category"?Po(t):Ge(t):typeof t=="number"||typeof t=="boolean"?String(t):t===null?"none":Array.isArray(t)?`${t.length} item${t.length===1?"":"s"}`:x(t)?gt(t)||"details available with --json":String(t)}function Po(e){return Ji(e)}function Ge(e){let t=e.replace(/\s+/gu," ").trim();return t.length>160?`${t.slice(0,157)}...`:t}function Rp(e){return en(Xn(e))}function Xn(e){return e.replace(/([a-z0-9])([A-Z])/gu,"$1 $2").replace(/[_-]+/gu," ").toLowerCase()}function Co(e){let t=$p(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 $p(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(x(i)){let r=l(i,"skillSlug")??l(i,"slug");if(r)return r}}}function x(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function k(e,t){let n=Ap(e);return n?w(n.payload,e,t,n.reasonCode):{exitCode:1,stdout:"",stderr:t?JSON.stringify({schemaVersion:ui,status:"error",reasonFamily:"invalid_input",summary:e,why:null,nextAction:null,nextStep:null,data:{error:e},warnings:[],links:[],reasonCode:null,handoff:null},null,2):e}}function Ap(e){let t=/^(?<code>EACCES|EPERM|EROFS):\s*(?<detail>.+)$/iu.exec(e);if(t?.groups){let d=t.groups.code.toUpperCase(),g=/'(?<path>[^']+)'/u.exec(e)?.groups?.path;return{reasonCode:"local_filesystem_permission_denied",payload:{status:"error",reasonCode:"local_filesystem_permission_denied",code:d,...g?{path:g}:{},nextAction:"check_local_permissions",nextStep:"Check the local path permissions, choose a writable installed skill directory, or rerun the command from a workspace you can write to."}}}let n=/^--(?<flag>[a-z0-9-]+) must be valid JSON\.$/iu.exec(e);if(n?.groups){let d=n.groups.flag;return{reasonCode:"invalid_json",payload:{status:"error",reasonCode:"invalid_json",flag:d,nextAction:"fix_json_flag",nextStep:`Provide valid JSON for --${d}.`}}}let i=/^Unknown flag --(?<flag>[a-z0-9-]+)\.$/iu.exec(e);if(i?.groups)return{reasonCode:"unknown_flag",payload:{status:"error",reasonCode:"unknown_flag",flag:i.groups.flag,nextAction:"help",nextStep:"Run `skills-layer <command> --help` to see supported flags for that command."}};let r=/^(?<command>.+?) --(?<flag>[a-z0-9-]+) must be one of: (?<accepted>.+?)\.$/iu.exec(e);if(r?.groups){let d=r.groups.flag,g=r.groups.accepted.split(",").map(f=>f.trim()).filter(Boolean);return{reasonCode:`invalid_${d.replace(/-/gu,"_")}`,payload:{status:"error",reasonCode:`invalid_${d.replace(/-/gu,"_")}`,command:r.groups.command,flag:d,acceptedValues:g,nextAction:r.groups.command.replace(/\s+/gu,"."),nextStep:`Use --${d} with one of: ${g.join(", ")}.`}}}let s=/^Unknown (?<namespace>.+?) command "(?<subcommand>.*?)"\.$/u.exec(e);if(s?.groups){let d=s.groups.namespace.trim(),g=s.groups.subcommand;return{reasonCode:"unknown_subcommand",payload:{status:"error",reasonCode:"unknown_subcommand",namespace:d,subcommand:g,nextAction:`${d.replace(/\s+/gu,".")}.help`,nextStep:`Run \`skills-layer ${d} --help\` to see supported ${d} commands.`}}}let o=/^(?<command>.+?) requires (?<argument>.+?)\.$/u.exec(e);if(!o?.groups)return;let a=o.groups.command.trim(),c=o.groups.argument.trim(),u=Ep(c);return{reasonCode:"missing_required_argument",payload:{status:"error",reasonCode:"missing_required_argument",command:a,argument:u,nextAction:a.replace(/\s+/gu,"."),nextStep:`Provide ${u.startsWith("--")?u:`<${u}>`} and retry.`}}}function Ep(e){let t=e.replace(/^(?:a|an|the)\s+/iu,"");if(/^two or more skill slugs$/iu.test(t))return"two-or-more-skill-slugs";let n=/--(?<name>[a-z0-9-]+)/iu.exec(t)?.groups?.name;return n||(/<(?<name>[^>]+)>/u.exec(t)?.groups?.name??t).replace(/\s+or\s+.*$/iu,"").replace(/[^a-z0-9]+/giu,"-").replace(/^-+|-+$/gu,"").toLowerCase()||"argument"}function w(e,t,n,i){let r=Gt(e),s=i??l(r,"reasonCode")??null,o={schemaVersion:ui,status:l(r,"status")??"error",summary:t,why:l(r,"why")??null,nextAction:l(r,"nextAction")??null,nextStep:l(r,"nextStep")??null,data:r,warnings:Array.isArray(r.warnings)?r.warnings:[],links:Array.isArray(r.links)?r.links:[],reasonCode:s,reasonFamily:qd(s),handoff:r.handoff??null};return{exitCode:1,stdout:"",stderr:n?JSON.stringify(o,null,2):t}}function Qt(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 w({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=x(n.data)?n.data:null,a=s!==null&&("summary"in n||"data"in n)?s:n,c=l(a,"error")??l(n,"error")??l(n,"summary")??e.message;return w({...a,status:l(n,"status")??l(a,"status")??(e.status===404?"not_found":"error"),nextAction:l(a,"nextAction")??l(n,"nextAction"),nextStep:l(a,"nextStep")??l(n,"nextStep"),warnings:Array.isArray(a.warnings)?a.warnings:n.warnings,links:Array.isArray(a.links)?a.links:n.links,handoff:a.handoff??n.handoff,reasonCode:i},c,t,i)}let r=Ip(e);return r?w(r.payload,r.message,t,r.reasonCode):k(l(n,"error")??e.message,t)}function Ip(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("security report")||n.includes("trust report"))?{reasonCode:"trust_report_not_found",message:"Trust report not found.",payload:{status:"not_found",error:t,reasonCode:"trust_report_not_found",nextAction:"trust",nextStep:"Run `skills-layer show <skill-slug>` to confirm the skill exists, then retry trust after the security report is generated."}}:e.status===404&&n.includes("help topic")?{reasonCode:"help_topic_not_found",message:"Help topic not found.",payload:{status:"not_found",error:t,reasonCode:"help_topic_not_found",nextAction:"help",nextStep:"Run `skills-layer help full` or `skills-layer --help` to see available topics."}}:e.status===404&&n.includes("skill")?{reasonCode:"skill_not_found",message:"Skill not found.",payload:{status:"not_found",error:t,reasonCode:"skill_not_found",nextAction:"search",nextStep:"Run `skills-layer search <query>` to find a valid skill slug before retrying."}}:null}async function W(e){try{return JSON.parse(await He(e,"utf8"))}catch{return null}}async function jp(e,t){let n=await W(e);return n?gr(n,{env:t.env,platform:t.platform,store:t.credentialStore}):null}async function Ri(e,t,n){let i=await pr(t,{env:n.env,platform:n.platform,store:n.credentialStore});await ee(e,i)}async function ee(e,t){await _o(ae(e)),await si(e,`${JSON.stringify(t,null,2)}
|
|
1313
|
+
`,{encoding:"utf8",mode:384}),await $i(e,384)}async function _o(e){await ft(e,{recursive:!0,mode:448}),await $i(e,448)}async function $i(e,t){if(process.platform!=="win32")try{await vs(e,t)}catch{}}async function ge(e,t){await ft(ae(e),{recursive:!0}),await si(e,t,"utf8")}async function ei(e,t){await ft(ae(e),{recursive:!0}),await si(e,t)}function Lp(e=process.stdin,t=process.stdout,n=li){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 Up(e=process.stdin,t=process.stdout,n=li){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(`
|
|
1309
1314
|
`),m())},f=m=>{let y=typeof m=="string"?m:m.toString("utf8");for(let v of y){if(v==="\r"||v===`
|
|
1310
1315
|
`){g(()=>s(u.trim()));return}if(v===""){g(()=>o(new Error("Interactive secret prompt cancelled.")));return}if(v==="\b"||v==="\x7F"){u.length>0&&(u=u.slice(0,-1),t.write("\b \b"));continue}u+=v,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!==`
|
|
1311
1316
|
`){let a=[...o].filter(c=>c!=="\r"&&c!==`
|
|
1312
1317
|
`).length;a>0&&t.write("*".repeat(a))}};try{t.write(i);let s=await r.question("");return t.write(`
|
|
1313
|
-
`),s.trim()}finally{r.close()}}}function
|
|
1314
|
-
`);for(let[
|
|
1318
|
+
`),s.trim()}finally{r.close()}}}function Tp(e=process.stdin,t=process.stdout,n=li){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,y=()=>{g>0&&t.write(`\x1B[${g}F\x1B[J`),t.write(`${i}
|
|
1319
|
+
`);for(let[R,L]of r.entries())t.write(`${Fp(R===u)} ${R+1}. ${hs(L)}
|
|
1315
1320
|
`);t.write(`Choice: ${d}
|
|
1316
1321
|
`),t.write(`Use up/down arrows, type a number, then press Enter.
|
|
1317
|
-
`),g=r.length+3},v=
|
|
1318
|
-
`),
|
|
1319
|
-
`)){if(d){let
|
|
1320
|
-
`);for(let[u,d]of r.entries())t.write(`${u+1}. ${
|
|
1321
|
-
`);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
|
|
1322
|
+
`),g=r.length+3},v=R=>{f||(f=!0,s.off?.("data",P),s.setRawMode?.(m),s.pause?.(),t.write(`
|
|
1323
|
+
`),R())},P=R=>{let L=typeof R=="string"?R:R.toString("utf8");if(L.includes("")){v(()=>c(new Error("Interactive selection cancelled.")));return}if(L.includes("\x1B[A")){d="",u=(u-1+r.length)%r.length,y();return}if(L.includes("\x1B[B")){d="",u=(u+1)%r.length,y();return}if(L.includes("\r")||L.includes(`
|
|
1324
|
+
`)){if(d){let j=Number.parseInt(d,10)-1;if(Number.isNaN(j)||j<0||j>=r.length){d="",t.write("\x07"),y();return}u=j}v(()=>a(r[u]?.value??r[0].value));return}if(L.includes("\b")||L.includes("\x7F")){d=d.slice(0,-1);let j=Number.parseInt(d,10)-1;!Number.isNaN(j)&&j>=0&&j<r.length&&(u=j),y();return}let K=[...L].filter(j=>/[0-9]/u.test(j));if(K.length>0){d=`${d}${K.join("")}`;let j=Number.parseInt(d,10)-1;!Number.isNaN(j)&&j>=0&&j<r.length&&(u=j),y()}};y(),s.resume?.(),s.on("data",P),s.setRawMode(!0)});let o=n({input:e,output:t});try{t.write(`${i}
|
|
1325
|
+
`);for(let[u,d]of r.entries())t.write(`${u+1}. ${hs(d)}
|
|
1326
|
+
`);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 Fp(e){return e?"\x1B[36m>\x1B[0m":" "}function hs(e){return e.description?`${e.label} (${e.description})`:e.label}function Np(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=ks(n.file,n.args,{detached:!0,stdio:"ignore"});r.on("error",()=>i(!1)),r.unref(),i(!0)}catch{i(!1)}})}}function Z(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 Mp(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 Bp(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 Xt(e,t){let n=p(e);return n?Ai(n,t):void 0}function Ai(e,t){try{return JSON.parse(e)}catch{throw new Error(`--${t} must be valid JSON.`)}}function Y(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 ti(e){let t=Y(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 oe(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 T(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim().length>0){let i=Number(n);return Number.isFinite(i)?i:void 0}}function C(e,t){let n=e[t];return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function ue(e,t){let n=e[t];return Array.isArray(n)?n.filter(i=>typeof i=="string"):void 0}function we(e,t){let n=e[t];return Array.isArray(n)?n:void 0}function Op(e){return C(e,"data")??e}function qp(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 q(e,t,n){let i=p(n);i&&e.set(t,i)}function ie(e){let t=e.toString();return t?`?${t}`:""}function Ce(e){return e.replace(/\/+$/u,"")}function ys(e){let t=Ce(e.trim());try{let n=new URL(t);if(n.protocol==="https:"&&(n.hostname==="staging.findfigg.co.uk"||n.hostname==="api.staging.findfigg.co.uk"))return"https://staging.findfigg.co.uk"}catch{return t}return t}function mt(e,t){return ys(e)===ys(t)}function pe(e){if(Ce(e)===di)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 xo(e){return e.includes("/")||e.startsWith(".")||/^https?:\/\//u.test(e)||/^[a-z]+:/iu.test(e)}function V(e,t){return ai(e,t)}function en(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var Dp={github:"GitHub",gitlab:"GitLab",google:"Google",microsoft:"Microsoft"};function Kp(e){return Dp[e.toLowerCase()]??en(e)}function te(e){return e instanceof Error?e.message:String(e)}export{rm as executePublicCli};
|