agent-skill-manager 2.18.0 → 2.19.0

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.
Files changed (97) hide show
  1. package/README.md +92 -31
  2. package/data/bundles/content-writing.json +9 -9
  3. package/data/bundles/frontend-dev.json +6 -6
  4. package/data/bundles/game-dev.json +60 -0
  5. package/data/bundles/ios-release.json +1 -1
  6. package/data/bundles/marketing.json +40 -0
  7. package/data/bundles/software-dev.json +40 -0
  8. package/data/repo-stars.json +80 -0
  9. package/data/skill-index/Affitor_affiliate-skills.json +692 -226
  10. package/data/skill-index/AvdLee_Core-Data-Agent-Skill.json +7 -5
  11. package/data/skill-index/AvdLee_Swift-Concurrency-Agent-Skill.json +7 -5
  12. package/data/skill-index/AvdLee_Swift-Testing-Agent-Skill.json +7 -5
  13. package/data/skill-index/AvdLee_SwiftUI-Agent-Skill.json +53 -13
  14. package/data/skill-index/AvdLee_Xcode-Build-Optimization-Agent-Skill.json +102 -30
  15. package/data/skill-index/ComposioHQ_awesome-claude-skills.json +5231 -3467
  16. package/data/skill-index/DietrichGebert_ponytail.json +1307 -0
  17. package/data/skill-index/Dimillian_Skills.json +182 -72
  18. package/data/skill-index/Egonex-AI_Understand-Anything.json +66 -48
  19. package/data/skill-index/Eronred_aso-skills.json +443 -177
  20. package/data/skill-index/GPTomics_bioSkills.json +3618 -2494
  21. package/data/skill-index/Galaxy-Dawn_claude-scholar.json +313 -203
  22. package/data/skill-index/Imbad0202_academic-research-skills.json +42 -34
  23. package/data/skill-index/JuliusBrussee_caveman.json +261 -359
  24. package/data/skill-index/K-Dense-AI_claude-scientific-skills.json +2473 -2643
  25. package/data/skill-index/Leonxlnx_taste-skill.json +86 -60
  26. package/data/skill-index/Master-cai_Research-Paper-Writing-Skills.json +7 -5
  27. package/data/skill-index/MiniMax-AI_skills.json +186 -104
  28. package/data/skill-index/Nutlope_hallmark.json +9 -7
  29. package/data/skill-index/Paramchoudhary_ResumeSkills.json +140 -96
  30. package/data/skill-index/ParthJadhav_app-store-screenshots.json +7 -5
  31. package/data/skill-index/addyosmani_agent-skills.json +572 -257
  32. package/data/skill-index/affaan-m_ECC.json +54685 -0
  33. package/data/skill-index/affaan-m_everything-claude-code.json +1903 -1248
  34. package/data/skill-index/alirezarezvani_claude-skills.json +14453 -8549
  35. package/data/skill-index/anthropics_skills.json +138 -98
  36. package/data/skill-index/antithesishq_antithesis-skills.json +173 -149
  37. package/data/skill-index/antonbabenko_terraform-skill.json +7 -5
  38. package/data/skill-index/ayghri_i-have-adhd.json +9 -7
  39. package/data/skill-index/badlogic_pi-skills.json +55 -39
  40. package/data/skill-index/blader_humanizer.json +18 -16
  41. package/data/skill-index/briiirussell_cybersecurity-skills.json +212 -343
  42. package/data/skill-index/bytedance_deer-flow.json +180 -126
  43. package/data/skill-index/cathrynlavery_diagram-design.json +10 -8
  44. package/data/skill-index/charlie947_answer-first.json +9 -7
  45. package/data/skill-index/charlie947_voiceprint.json +9 -7
  46. package/data/skill-index/cloudai-x_threejs-skills.json +149 -45
  47. package/data/skill-index/coreyhaines31_marketingskills.json +802 -467
  48. package/data/skill-index/davidondrej_skills.json +4580 -1075
  49. package/data/skill-index/emilkowalski_skills.json +353 -52
  50. package/data/skill-index/entireio_skills.json +185 -101
  51. package/data/skill-index/garrytan_gstack.json +968 -600
  52. package/data/skill-index/github_awesome-copilot.json +9624 -7636
  53. package/data/skill-index/google-labs-code_design.md.json +29 -21
  54. package/data/skill-index/google_skills.json +7013 -2434
  55. package/data/skill-index/hardikpandya_stop-slop.json +9 -7
  56. package/data/skill-index/heygen-com_hyperframes.json +191 -139
  57. package/data/skill-index/himself65_finance-skills.json +175 -340
  58. package/data/skill-index/ivan-magda_uikit-expert-skill.json +7 -5
  59. package/data/skill-index/kemiljk_fluid-design.json +7 -5
  60. package/data/skill-index/kepano_obsidian-skills.json +34 -24
  61. package/data/skill-index/luongnv89_asm.json +307 -219
  62. package/data/skill-index/luongnv89_idd.json +121 -107
  63. package/data/skill-index/luongnv89_skills.json +1503 -599
  64. package/data/skill-index/majidmanzarpour_threejs-game-skills.json +2024 -0
  65. package/data/skill-index/mattpocock_skills.json +235 -161
  66. package/data/skill-index/multica-ai_andrej-karpathy-skills.json +7 -5
  67. package/data/skill-index/mvanhorn_last30days-skill.json +16 -20
  68. package/data/skill-index/nextlevelbuilder_ui-ux-pro-max-skill.json +92 -78
  69. package/data/skill-index/obra_superpowers.json +95 -67
  70. package/data/skill-index/oliver-zehentleitner_keep-the-why.json +28 -26
  71. package/data/skill-index/openai_skills.json +8816 -0
  72. package/data/skill-index/pbakaus_impeccable.json +20 -18
  73. package/data/skill-index/romainsimon_paperasse.json +44 -32
  74. package/data/skill-index/rudrankriyam_app-store-connect-cli-skills.json +319 -119
  75. package/data/skill-index/santifer_career-ops.json +1009 -14
  76. package/data/skill-index/sickn33_antigravity-awesome-skills.json +63856 -42252
  77. package/data/skill-index/slavingia_skills.json +68 -48
  78. package/data/skill-index/tt-a1i_archify.json +18 -16
  79. package/data/skill-index/twostraws_Swift-Concurrency-Agent-Skill.json +7 -5
  80. package/data/skill-index/twostraws_Swift-Testing-Agent-Skill.json +7 -5
  81. package/data/skill-index/twostraws_SwiftData-Agent-Skill.json +7 -5
  82. package/data/skill-index/twostraws_SwiftUI-Agent-Skill.json +7 -5
  83. package/data/skill-index/warpdotdev_oz-skills.json +101 -71
  84. package/data/skill-index/zarazhangrui_follow-builders.json +7 -5
  85. package/data/skill-index/zarazhangrui_frontend-slides.json +11 -9
  86. package/data/skill-index-resources.json +37 -1
  87. package/dist/agent-skill-manager.js +464 -560
  88. package/dist/{chunk-ZAOVB3X2.js → chunk-3KGAHUVB.js} +1 -1
  89. package/dist/chunk-CBDNF2SR.js +166 -0
  90. package/dist/chunk-KWWFXT5F.js +3 -0
  91. package/dist/config-JPFUVYBM.js +2 -0
  92. package/dist/{lock-RVOMV2LT.js → lock-UEL3CMOV.js} +1 -1
  93. package/dist/{src-SP66WR5V.js → src-ORQ3FXUL.js} +1 -1
  94. package/package.json +1 -1
  95. package/dist/chunk-54VC5E5G.js +0 -23
  96. package/dist/chunk-VGQYV246.js +0 -3
  97. package/dist/config-PQRMSV7F.js +0 -2
@@ -1,167 +1,29 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __asmCreateRequire } from 'node:module'; const require = __asmCreateRequire(import.meta.url);
3
- import{a as oe}from"./chunk-ESKBKSXS.js";import{a as Zl,b as Ei,c as Ql,d as Ke,e as Et,f as ec,g as tc,h as sc}from"./chunk-ZAOVB3X2.js";import{$ as lc,A as Vl,D as wi,E as Kl,F as q,H as K,I as Wl,J as Si,K as Yl,L as zl,M as wn,N as Ve,O as $i,P as Xl,Q as kn,R as xi,S as ic,T as rc,U as nc,V as Pi,W as oc,X as ns,Y as vn,Z as ac,_ as Ci,a as qe,b as J,ba as cc,c as rt,ca as uc,d as es,da as dc,e as W,f as fe,g as fn,h as ts,i as Dl,j as X,k as ss,l as is,m as Fl,n as $t,o as l,p as _l,q as pn,r as Ue,s as yi,t as mn,u as hn,v as jl,w as Bl,x as bi,y as ql,z as Ul}from"./chunk-54VC5E5G.js";import{a as Gl,b as L,c as ki,d as vi,e as rs,f as Hl,g as gn,h as yn,i as xt,k as Fe,l as nt,m as bn,p as ie,q as j,r as Jl}from"./chunk-VGQYV246.js";import{a as gi,b as N,d as Ml}from"./chunk-RSVWCEZR.js";var U=N(le=>{"use strict";var Sn=Symbol.for("yaml.alias"),fc=Symbol.for("yaml.document"),Li=Symbol.for("yaml.map"),pc=Symbol.for("yaml.pair"),$n=Symbol.for("yaml.scalar"),Ai=Symbol.for("yaml.seq"),_e=Symbol.for("yaml.node.type"),vg=e=>!!e&&typeof e=="object"&&e[_e]===Sn,Sg=e=>!!e&&typeof e=="object"&&e[_e]===fc,$g=e=>!!e&&typeof e=="object"&&e[_e]===Li,xg=e=>!!e&&typeof e=="object"&&e[_e]===pc,mc=e=>!!e&&typeof e=="object"&&e[_e]===$n,Eg=e=>!!e&&typeof e=="object"&&e[_e]===Ai;function hc(e){if(e&&typeof e=="object")switch(e[_e]){case Li:case Ai:return!0}return!1}function Pg(e){if(e&&typeof e=="object")switch(e[_e]){case Sn:case Li:case $n:case Ai:return!0}return!1}var Cg=e=>(mc(e)||hc(e))&&!!e.anchor;le.ALIAS=Sn;le.DOC=fc;le.MAP=Li;le.NODE_TYPE=_e;le.PAIR=pc;le.SCALAR=$n;le.SEQ=Ai;le.hasAnchor=Cg;le.isAlias=vg;le.isCollection=hc;le.isDocument=Sg;le.isMap=$g;le.isNode=Pg;le.isPair=xg;le.isScalar=mc;le.isSeq=Eg});var os=N(xn=>{"use strict";var re=U(),pe=Symbol("break visit"),gc=Symbol("skip children"),Ne=Symbol("remove node");function Ri(e,t){let s=yc(t);re.isDocument(e)?Pt(null,e.contents,s,Object.freeze([e]))===Ne&&(e.contents=null):Pt(null,e,s,Object.freeze([]))}Ri.BREAK=pe;Ri.SKIP=gc;Ri.REMOVE=Ne;function Pt(e,t,s,i){let r=bc(e,t,s,i);if(re.isNode(r)||re.isPair(r))return wc(e,i,r),Pt(e,r,s,i);if(typeof r!="symbol"){if(re.isCollection(t)){i=Object.freeze(i.concat(t));for(let n=0;n<t.items.length;++n){let o=Pt(n,t.items[n],s,i);if(typeof o=="number")n=o-1;else{if(o===pe)return pe;o===Ne&&(t.items.splice(n,1),n-=1)}}}else if(re.isPair(t)){i=Object.freeze(i.concat(t));let n=Pt("key",t.key,s,i);if(n===pe)return pe;n===Ne&&(t.key=null);let o=Pt("value",t.value,s,i);if(o===pe)return pe;o===Ne&&(t.value=null)}}return r}async function Ni(e,t){let s=yc(t);re.isDocument(e)?await Ct(null,e.contents,s,Object.freeze([e]))===Ne&&(e.contents=null):await Ct(null,e,s,Object.freeze([]))}Ni.BREAK=pe;Ni.SKIP=gc;Ni.REMOVE=Ne;async function Ct(e,t,s,i){let r=await bc(e,t,s,i);if(re.isNode(r)||re.isPair(r))return wc(e,i,r),Ct(e,r,s,i);if(typeof r!="symbol"){if(re.isCollection(t)){i=Object.freeze(i.concat(t));for(let n=0;n<t.items.length;++n){let o=await Ct(n,t.items[n],s,i);if(typeof o=="number")n=o-1;else{if(o===pe)return pe;o===Ne&&(t.items.splice(n,1),n-=1)}}}else if(re.isPair(t)){i=Object.freeze(i.concat(t));let n=await Ct("key",t.key,s,i);if(n===pe)return pe;n===Ne&&(t.key=null);let o=await Ct("value",t.value,s,i);if(o===pe)return pe;o===Ne&&(t.value=null)}}return r}function yc(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function bc(e,t,s,i){if(typeof s=="function")return s(e,t,i);if(re.isMap(t))return s.Map?.(e,t,i);if(re.isSeq(t))return s.Seq?.(e,t,i);if(re.isPair(t))return s.Pair?.(e,t,i);if(re.isScalar(t))return s.Scalar?.(e,t,i);if(re.isAlias(t))return s.Alias?.(e,t,i)}function wc(e,t,s){let i=t[t.length-1];if(re.isCollection(i))i.items[e]=s;else if(re.isPair(i))e==="key"?i.key=s:i.value=s;else if(re.isDocument(i))i.contents=s;else{let r=re.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}xn.visit=Ri;xn.visitAsync=Ni});var En=N(vc=>{"use strict";var kc=U(),Ig=os(),Lg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ag=e=>e.replace(/[!,[\]{}]/g,t=>Lg[t]),as=class e{constructor(t,s){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,s)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,s){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(s(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[n,o]=i;return this.tags[n]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return s(0,"%YAML directive should contain exactly one part"),!1;let[n]=i;if(n==="1.1"||n==="1.2")return this.yaml.version=n,!0;{let o=/^\d+\.\d+$/.test(n);return s(6,`Unsupported YAML version ${n}`,o),!1}}default:return s(0,`Unknown directive ${r}`,!0),!1}}tagName(t,s){if(t==="!")return"!";if(t[0]!=="!")return s(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(s(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&s("Verbatim tags must end with a >"),o)}let[,i,r]=t.match(/^(.*!)([^!]*)$/s);r||s(`The ${t} tag has no suffix`);let n=this.tags[i];if(n)try{return n+decodeURIComponent(r)}catch(o){return s(String(o)),null}return i==="!"?t:(s(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[s,i]of Object.entries(this.tags))if(t.startsWith(i))return s+Ag(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let s=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(t&&i.length>0&&kc.isNode(t.contents)){let n={};Ig.visit(t.contents,(o,a)=>{kc.isNode(a)&&a.tag&&(n[a.tag]=!0)}),r=Object.keys(n)}else r=[];for(let[n,o]of i)n==="!!"&&o==="tag:yaml.org,2002:"||(!t||r.some(a=>a.startsWith(o)))&&s.push(`%TAG ${n} ${o}`);return s.join(`
4
- `)}};as.defaultYaml={explicit:!1,version:"1.2"};as.defaultTags={"!!":"tag:yaml.org,2002:"};vc.Directives=as});var Ti=N(ls=>{"use strict";var Sc=U(),Rg=os();function Ng(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let s=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(s)}return!0}function $c(e){let t=new Set;return Rg.visit(e,{Value(s,i){i.anchor&&t.add(i.anchor)}}),t}function xc(e,t){for(let s=1;;++s){let i=`${e}${s}`;if(!t.has(i))return i}}function Tg(e,t){let s=[],i=new Map,r=null;return{onAnchor:n=>{s.push(n),r??(r=$c(e));let o=xc(t,r);return r.add(o),o},setAnchors:()=>{for(let n of s){let o=i.get(n);if(typeof o=="object"&&o.anchor&&(Sc.isScalar(o.node)||Sc.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=n,a}}},sourceObjects:i}}ls.anchorIsValid=Ng;ls.anchorNames=$c;ls.createNodeAnchors=Tg;ls.findNewAnchor=xc});var Pn=N(Ec=>{"use strict";function cs(e,t,s,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,n=i.length;r<n;++r){let o=i[r],a=cs(e,i,String(r),o);a===void 0?delete i[r]:a!==o&&(i[r]=a)}else if(i instanceof Map)for(let r of Array.from(i.keys())){let n=i.get(r),o=cs(e,i,r,n);o===void 0?i.delete(r):o!==n&&i.set(r,o)}else if(i instanceof Set)for(let r of Array.from(i)){let n=cs(e,i,r,r);n===void 0?i.delete(r):n!==r&&(i.delete(r),i.add(n))}else for(let[r,n]of Object.entries(i)){let o=cs(e,i,r,n);o===void 0?delete i[r]:o!==n&&(i[r]=o)}return e.call(t,s,i)}Ec.applyReviver=cs});var Ge=N(Cc=>{"use strict";var Og=U();function Pc(e,t,s){if(Array.isArray(e))return e.map((i,r)=>Pc(i,String(r),s));if(e&&typeof e.toJSON=="function"){if(!s||!Og.hasAnchor(e))return e.toJSON(t,s);let i={aliasCount:0,count:1,res:void 0};s.anchors.set(e,i),s.onCreate=n=>{i.res=n,delete s.onCreate};let r=e.toJSON(t,s);return s.onCreate&&s.onCreate(r),r}return typeof e=="bigint"&&!s?.keep?Number(e):e}Cc.toJS=Pc});var Oi=N(Lc=>{"use strict";var Mg=Pn(),Ic=U(),Dg=Ge(),Cn=class{constructor(t){Object.defineProperty(this,Ic.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:s,maxAliasCount:i,onAnchor:r,reviver:n}={}){if(!Ic.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=Dg.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:u}of o.anchors.values())r(u,c);return typeof n=="function"?Mg.applyReviver(n,{"":a},"",a):a}};Lc.NodeBase=Cn});var us=N(Ac=>{"use strict";var Fg=Ti(),_g=os(),It=U(),jg=Oi(),Bg=Ge(),In=class extends jg.NodeBase{constructor(t){super(It.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,s){if(s?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;s?.aliasResolveCache?i=s.aliasResolveCache:(i=[],_g.visit(t,{Node:(n,o)=>{(It.isAlias(o)||It.hasAnchor(o))&&i.push(o)}}),s&&(s.aliasResolveCache=i));let r;for(let n of i){if(n===this)break;n.anchor===this.source&&(r=n)}return r}toJSON(t,s){if(!s)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:n}=s,o=this.resolve(r,s);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(Bg.toJS(o,null,s),a=i.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(n>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Mi(r,o,i)),a.count*a.aliasCount>n)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(t,s,i){let r=`*${this.source}`;if(t){if(Fg.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let n=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(n)}if(t.implicitKey)return`${r} `}return r}};function Mi(e,t,s){if(It.isAlias(t)){let i=t.resolve(e),r=s&&i&&s.get(i);return r?r.count*r.aliasCount:0}else if(It.isCollection(t)){let i=0;for(let r of t.items){let n=Mi(e,r,s);n>i&&(i=n)}return i}else if(It.isPair(t)){let i=Mi(e,t.key,s),r=Mi(e,t.value,s);return Math.max(i,r)}return 1}Ac.Alias=In});var Z=N(Ln=>{"use strict";var qg=U(),Ug=Oi(),Vg=Ge(),Kg=e=>!e||typeof e!="function"&&typeof e!="object",He=class extends Ug.NodeBase{constructor(t){super(qg.SCALAR),this.value=t}toJSON(t,s){return s?.keep?this.value:Vg.toJS(this.value,t,s)}toString(){return String(this.value)}};He.BLOCK_FOLDED="BLOCK_FOLDED";He.BLOCK_LITERAL="BLOCK_LITERAL";He.PLAIN="PLAIN";He.QUOTE_DOUBLE="QUOTE_DOUBLE";He.QUOTE_SINGLE="QUOTE_SINGLE";Ln.Scalar=He;Ln.isScalarValue=Kg});var ds=N(Nc=>{"use strict";var Gg=us(),ot=U(),Rc=Z(),Hg="tag:yaml.org,2002:";function Jg(e,t,s){if(t){let i=s.filter(n=>n.tag===t),r=i.find(n=>!n.format)??i[0];if(!r)throw new Error(`Tag ${t} not found`);return r}return s.find(i=>i.identify?.(e)&&!i.format)}function Wg(e,t,s){if(ot.isDocument(e)&&(e=e.contents),ot.isNode(e))return e;if(ot.isPair(e)){let d=s.schema[ot.MAP].createNode?.(s.schema,null,s);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:n,schema:o,sourceObjects:a}=s,c;if(i&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=r(e)),new Gg.Alias(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=Hg+t.slice(2));let u=Jg(e,t,o.tags);if(!u){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Rc.Scalar(e);return c&&(c.node=d),d}u=e instanceof Map?o[ot.MAP]:Symbol.iterator in Object(e)?o[ot.SEQ]:o[ot.MAP]}n&&(n(u),delete s.onTagObj);let f=u?.createNode?u.createNode(s.schema,e,s):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(s.schema,e,s):new Rc.Scalar(e);return t?f.tag=t:u.default||(f.tag=u.tag),c&&(c.node=f),f}Nc.createNode=Wg});var Fi=N(Di=>{"use strict";var Yg=ds(),Te=U(),zg=Oi();function An(e,t,s){let i=s;for(let r=t.length-1;r>=0;--r){let n=t[r];if(typeof n=="number"&&Number.isInteger(n)&&n>=0){let o=[];o[n]=i,i=o}else i=new Map([[n,i]])}return Yg.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Tc=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Rn=class extends zg.NodeBase{constructor(t,s){super(t),Object.defineProperty(this,"schema",{value:s,configurable:!0,enumerable:!1,writable:!0})}clone(t){let s=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(s.schema=t),s.items=s.items.map(i=>Te.isNode(i)||Te.isPair(i)?i.clone(t):i),this.range&&(s.range=this.range.slice()),s}addIn(t,s){if(Tc(t))this.add(s);else{let[i,...r]=t,n=this.get(i,!0);if(Te.isCollection(n))n.addIn(r,s);else if(n===void 0&&this.schema)this.set(i,An(this.schema,r,s));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(t){let[s,...i]=t;if(i.length===0)return this.delete(s);let r=this.get(s,!0);if(Te.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${s}. Remaining path: ${i}`)}getIn(t,s){let[i,...r]=t,n=this.get(i,!0);return r.length===0?!s&&Te.isScalar(n)?n.value:n:Te.isCollection(n)?n.getIn(r,s):void 0}hasAllNullValues(t){return this.items.every(s=>{if(!Te.isPair(s))return!1;let i=s.value;return i==null||t&&Te.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[s,...i]=t;if(i.length===0)return this.has(s);let r=this.get(s,!0);return Te.isCollection(r)?r.hasIn(i):!1}setIn(t,s){let[i,...r]=t;if(r.length===0)this.set(i,s);else{let n=this.get(i,!0);if(Te.isCollection(n))n.setIn(r,s);else if(n===void 0&&this.schema)this.set(i,An(this.schema,r,s));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Di.Collection=Rn;Di.collectionFromPath=An;Di.isEmptyPath=Tc});var fs=N(_i=>{"use strict";var Xg=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Nn(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Zg=(e,t,s)=>e.endsWith(`
5
- `)?Nn(s,t):s.includes(`
6
- `)?`
7
- `+Nn(s,t):(e.endsWith(" ")?"":" ")+s;_i.indentComment=Nn;_i.lineComment=Zg;_i.stringifyComment=Xg});var Mc=N(ps=>{"use strict";var Qg="flow",Tn="block",ji="quoted";function ey(e,t,s="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:n=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return e;r<n&&(n=0);let c=Math.max(1+n,1+r-t.length);if(e.length<=c)return e;let u=[],f={},d=r-t.length;typeof i=="number"&&(i>r-Math.max(2,n)?u.push(0):d=r-i);let p,m,g=!1,h=-1,y=-1,b=-1;s===Tn&&(h=Oc(e,h,t.length),h!==-1&&(d=h+c));for(let w;w=e[h+=1];){if(s===ji&&w==="\\"){switch(y=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}b=h}if(w===`
8
- `)s===Tn&&(h=Oc(e,h,t.length)),d=h+t.length+c,p=void 0;else{if(w===" "&&m&&m!==" "&&m!==`
9
- `&&m!==" "){let v=e[h+1];v&&v!==" "&&v!==`
10
- `&&v!==" "&&(p=h)}if(h>=d)if(p)u.push(p),d=p+c,p=void 0;else if(s===ji){for(;m===" "||m===" ";)m=w,w=e[h+=1],g=!0;let v=h>b+1?h-2:y-1;if(f[v])return e;u.push(v),f[v]=!0,d=v+c,p=void 0}else g=!0}m=w}if(g&&a&&a(),u.length===0)return e;o&&o();let k=e.slice(0,u[0]);for(let w=0;w<u.length;++w){let v=u[w],x=u[w+1]||e.length;v===0?k=`
11
- ${t}${e.slice(0,x)}`:(s===ji&&f[v]&&(k+=`${e[v]}\\`),k+=`
12
- ${t}${e.slice(v+1,x)}`)}return k}function Oc(e,t,s){let i=t,r=t+1,n=e[r];for(;n===" "||n===" ";)if(t<r+s)n=e[++t];else{do n=e[++t];while(n&&n!==`
13
- `);i=t,r=t+1,n=e[r]}return i}ps.FOLD_BLOCK=Tn;ps.FOLD_FLOW=Qg;ps.FOLD_QUOTED=ji;ps.foldFlowLines=ey});var hs=N(Dc=>{"use strict";var Ce=Z(),Je=Mc(),qi=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Ui=e=>/^(%|---|\.\.\.)/m.test(e);function ty(e,t,s){if(!t||t<0)return!1;let i=t-s,r=e.length;if(r<=i)return!1;for(let n=0,o=0;n<r;++n)if(e[n]===`
14
- `){if(n-o>i)return!0;if(o=n+1,r-o<=i)return!1}return!0}function ms(e,t){let s=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return s;let{implicitKey:i}=t,r=t.options.doubleQuotedMinMultiLineLength,n=t.indent||(Ui(e)?" ":""),o="",a=0;for(let c=0,u=s[c];u;u=s[++c])if(u===" "&&s[c+1]==="\\"&&s[c+2]==="n"&&(o+=s.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(s[c+1]){case"u":{o+=s.slice(a,c);let f=s.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=s.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||s[c+2]==='"'||s.length<r)c+=1;else{for(o+=s.slice(a,c)+`
15
-
16
- `;s[c+2]==="\\"&&s[c+3]==="n"&&s[c+4]!=='"';)o+=`
17
- `,c+=2;o+=n,s[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+s.slice(a):s,i?o:Je.foldFlowLines(o,n,Je.FOLD_QUOTED,qi(t,!1))}function On(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
18
- `)||/[ \t]\n|\n[ \t]/.test(e))return ms(e,t);let s=t.indent||(Ui(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
19
- ${s}`)+"'";return t.implicitKey?i:Je.foldFlowLines(i,s,Je.FOLD_FLOW,qi(t,!1))}function Lt(e,t){let{singleQuote:s}=t.options,i;if(s===!1)i=ms;else{let r=e.includes('"'),n=e.includes("'");r&&!n?i=On:n&&!r?i=ms:i=s?On:ms}return i(e,t)}var Mn;try{Mn=new RegExp(`(^|(?<!
20
- ))
21
- +(?!
22
- |$)`,"g")}catch{Mn=/\n+(?!\n|$)/g}function Bi({comment:e,type:t,value:s},i,r,n){let{blockQuote:o,commentString:a,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(s))return Lt(s,i);let u=i.indent||(i.forceBlockIndent||Ui(s)?" ":""),f=o==="literal"?!0:o==="folded"||t===Ce.Scalar.BLOCK_FOLDED?!1:t===Ce.Scalar.BLOCK_LITERAL?!0:!ty(s,c,u.length);if(!s)return f?`|
23
- `:`>
24
- `;let d,p;for(p=s.length;p>0;--p){let x=s[p-1];if(x!==`
25
- `&&x!==" "&&x!==" ")break}let m=s.substring(p),g=m.indexOf(`
26
- `);g===-1?d="-":s===m||g!==m.length-1?(d="+",n&&n()):d="",m&&(s=s.slice(0,-m.length),m[m.length-1]===`
27
- `&&(m=m.slice(0,-1)),m=m.replace(Mn,`$&${u}`));let h=!1,y,b=-1;for(y=0;y<s.length;++y){let x=s[y];if(x===" ")h=!0;else if(x===`
28
- `)b=y;else break}let k=s.substring(0,b<y?b+1:y);k&&(s=s.substring(k.length),k=k.replace(/\n+/g,`$&${u}`));let v=(h?u?"2":"1":"")+d;if(e&&(v+=" "+a(e.replace(/ ?[\r\n]+/g," ")),r&&r()),!f){let x=s.replace(/\n+/g,`
29
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`),C=!1,A=qi(i,!0);o!=="folded"&&t!==Ce.Scalar.BLOCK_FOLDED&&(A.onOverflow=()=>{C=!0});let E=Je.foldFlowLines(`${k}${x}${m}`,u,Je.FOLD_BLOCK,A);if(!C)return`>${v}
30
- ${u}${E}`}return s=s.replace(/\n+/g,`$&${u}`),`|${v}
31
- ${u}${k}${s}${m}`}function sy(e,t,s,i){let{type:r,value:n}=e,{actualString:o,implicitKey:a,indent:c,indentStep:u,inFlow:f}=t;if(a&&n.includes(`
32
- `)||f&&/[[\]{},]/.test(n))return Lt(n,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(n))return a||f||!n.includes(`
33
- `)?Lt(n,t):Bi(e,t,s,i);if(!a&&!f&&r!==Ce.Scalar.PLAIN&&n.includes(`
34
- `))return Bi(e,t,s,i);if(Ui(n)){if(c==="")return t.forceBlockIndent=!0,Bi(e,t,s,i);if(a&&c===u)return Lt(n,t)}let d=n.replace(/\n+/g,`$&
35
- ${c}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:m,tags:g}=t.doc.schema;if(g.some(p)||m?.some(p))return Lt(n,t)}return a?d:Je.foldFlowLines(d,c,Je.FOLD_FLOW,qi(t,!1))}function iy(e,t,s,i){let{implicitKey:r,inFlow:n}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==Ce.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Ce.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Ce.Scalar.BLOCK_FOLDED:case Ce.Scalar.BLOCK_LITERAL:return r||n?Lt(o.value,t):Bi(o,t,s,i);case Ce.Scalar.QUOTE_DOUBLE:return ms(o.value,t);case Ce.Scalar.QUOTE_SINGLE:return On(o.value,t);case Ce.Scalar.PLAIN:return sy(o,t,s,i);default:return null}},u=c(a);if(u===null){let{defaultKeyType:f,defaultStringType:d}=t.options,p=r&&f||d;if(u=c(p),u===null)throw new Error(`Unsupported default string type ${p}`)}return u}Dc.stringifyString=iy});var gs=N(Dn=>{"use strict";var ry=Ti(),We=U(),ny=fs(),oy=hs();function ay(e,t){let s=Object.assign({blockQuote:!0,commentString:ny.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(s.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:s.flowCollectionPadding?" ":"",indent:"",indentStep:typeof s.indent=="number"?" ".repeat(s.indent):" ",inFlow:i,options:s}}function ly(e,t){if(t.tag){let r=e.filter(n=>n.tag===t.tag);if(r.length>0)return r.find(n=>n.format===t.format)??r[0]}let s,i;if(We.isScalar(t)){i=t.value;let r=e.filter(n=>n.identify?.(i));if(r.length>1){let n=r.filter(o=>o.test);n.length>0&&(r=n)}s=r.find(n=>n.format===t.format)??r.find(n=>!n.format)}else i=t,s=e.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!s){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return s}function cy(e,t,{anchors:s,doc:i}){if(!i.directives)return"";let r=[],n=(We.isScalar(e)||We.isCollection(e))&&e.anchor;n&&ry.anchorIsValid(n)&&(s.add(n),r.push(`&${n}`));let o=e.tag??(t.default?null:t.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function uy(e,t,s,i){if(We.isPair(e))return e.toString(t,s,i);if(We.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let r,n=We.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=ly(t.doc.schema.tags,n));let o=cy(n,r,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(n,t,s,i):We.isScalar(n)?oy.stringifyString(n,t,s,i):n.toString(t,s,i);return o?We.isScalar(n)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
36
- ${t.indent}${a}`:a}Dn.createStringifyContext=ay;Dn.stringify=uy});var Bc=N(jc=>{"use strict";var je=U(),Fc=Z(),_c=gs(),ys=fs();function dy({key:e,value:t},s,i,r){let{allNullValues:n,doc:o,indent:a,indentStep:c,options:{commentString:u,indentSeq:f,simpleKeys:d}}=s,p=je.isNode(e)&&e.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(je.isCollection(e)||!je.isNode(e)&&typeof e=="object"){let A="With simple keys, collection cannot be used as a key value";throw new Error(A)}}let m=!d&&(!e||p&&t==null&&!s.inFlow||je.isCollection(e)||(je.isScalar(e)?e.type===Fc.Scalar.BLOCK_FOLDED||e.type===Fc.Scalar.BLOCK_LITERAL:typeof e=="object"));s=Object.assign({},s,{allNullValues:!1,implicitKey:!m&&(d||!n),indent:a+c});let g=!1,h=!1,y=_c.stringify(e,s,()=>g=!0,()=>h=!0);if(!m&&!s.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(s.inFlow){if(n||t==null)return g&&i&&i(),y===""?"?":m?`? ${y}`:y}else if(n&&!d||t==null&&m)return y=`? ${y}`,p&&!g?y+=ys.lineComment(y,s.indent,u(p)):h&&r&&r(),y;g&&(p=null),m?(p&&(y+=ys.lineComment(y,s.indent,u(p))),y=`? ${y}
37
- ${a}:`):(y=`${y}:`,p&&(y+=ys.lineComment(y,s.indent,u(p))));let b,k,w;je.isNode(t)?(b=!!t.spaceBefore,k=t.commentBefore,w=t.comment):(b=!1,k=null,w=null,t&&typeof t=="object"&&(t=o.createNode(t))),s.implicitKey=!1,!m&&!p&&je.isScalar(t)&&(s.indentAtStart=y.length+1),h=!1,!f&&c.length>=2&&!s.inFlow&&!m&&je.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(s.indent=s.indent.substring(2));let v=!1,x=_c.stringify(t,s,()=>v=!0,()=>h=!0),C=" ";if(p||b||k){if(C=b?`
38
- `:"",k){let A=u(k);C+=`
39
- ${ys.indentComment(A,s.indent)}`}x===""&&!s.inFlow?C===`
40
- `&&w&&(C=`
41
-
42
- `):C+=`
43
- ${s.indent}`}else if(!m&&je.isCollection(t)){let A=x[0],E=x.indexOf(`
44
- `),_=E!==-1,O=s.inFlow??t.flow??t.items.length===0;if(_||!O){let S=!1;if(_&&(A==="&"||A==="!")){let P=x.indexOf(" ");A==="&"&&P!==-1&&P<E&&x[P+1]==="!"&&(P=x.indexOf(" ",P+1)),(P===-1||E<P)&&(S=!0)}S||(C=`
45
- ${s.indent}`)}}else(x===""||x[0]===`
46
- `)&&(C="");return y+=C+x,s.inFlow?v&&i&&i():w&&!v?y+=ys.lineComment(y,s.indent,u(w)):h&&r&&r(),y}jc.stringifyPair=dy});var _n=N(Fn=>{"use strict";var qc=gi("process");function fy(e,...t){e==="debug"&&console.log(...t)}function py(e,t){(e==="debug"||e==="warn")&&(typeof qc.emitWarning=="function"?qc.emitWarning(t):console.warn(t))}Fn.debug=fy;Fn.warn=py});var Ji=N(Hi=>{"use strict";var Gi=U(),Uc=Z(),Vi="<<",Ki={identify:e=>e===Vi||typeof e=="symbol"&&e.description===Vi,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Uc.Scalar(Symbol(Vi)),{addToJSMap:Vc}),stringify:()=>Vi},my=(e,t)=>(Ki.identify(t)||Gi.isScalar(t)&&(!t.type||t.type===Uc.Scalar.PLAIN)&&Ki.identify(t.value))&&e?.doc.schema.tags.some(s=>s.tag===Ki.tag&&s.default);function Vc(e,t,s){let i=Kc(e,s);if(Gi.isSeq(i))for(let r of i.items)jn(e,t,r);else if(Array.isArray(i))for(let r of i)jn(e,t,r);else jn(e,t,i)}function jn(e,t,s){let i=Kc(e,s);if(!Gi.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,e,Map);for(let[n,o]of r)t instanceof Map?t.has(n)||t.set(n,o):t instanceof Set?t.add(n):Object.prototype.hasOwnProperty.call(t,n)||Object.defineProperty(t,n,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Kc(e,t){return e&&Gi.isAlias(t)?t.resolve(e.doc,e):t}Hi.addMergeToJSMap=Vc;Hi.isMergeKey=my;Hi.merge=Ki});var qn=N(Jc=>{"use strict";var hy=_n(),Gc=Ji(),gy=gs(),Hc=U(),Bn=Ge();function yy(e,t,{key:s,value:i}){if(Hc.isNode(s)&&s.addToJSMap)s.addToJSMap(e,t,i);else if(Gc.isMergeKey(e,s))Gc.addMergeToJSMap(e,t,i);else{let r=Bn.toJS(s,"",e);if(t instanceof Map)t.set(r,Bn.toJS(i,r,e));else if(t instanceof Set)t.add(r);else{let n=by(s,r,e),o=Bn.toJS(i,n,e);n in t?Object.defineProperty(t,n,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[n]=o}}return t}function by(e,t,s){if(t===null)return"";if(typeof t!="object")return String(t);if(Hc.isNode(e)&&s?.doc){let i=gy.createStringifyContext(s.doc,{});i.anchors=new Set;for(let n of s.anchors.keys())i.anchors.add(n.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=e.toString(i);if(!s.mapKeyWarned){let n=JSON.stringify(r);n.length>40&&(n=n.substring(0,36)+'..."'),hy.warn(s.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${n}. Set mapAsMap: true to use object keys.`),s.mapKeyWarned=!0}return r}return JSON.stringify(t)}Jc.addPairToJSMap=yy});var Ye=N(Un=>{"use strict";var Wc=ds(),wy=Bc(),ky=qn(),Wi=U();function vy(e,t,s){let i=Wc.createNode(e,void 0,s),r=Wc.createNode(t,void 0,s);return new Yi(i,r)}var Yi=class e{constructor(t,s=null){Object.defineProperty(this,Wi.NODE_TYPE,{value:Wi.PAIR}),this.key=t,this.value=s}clone(t){let{key:s,value:i}=this;return Wi.isNode(s)&&(s=s.clone(t)),Wi.isNode(i)&&(i=i.clone(t)),new e(s,i)}toJSON(t,s){let i=s?.mapAsMap?new Map:{};return ky.addPairToJSMap(s,i,this)}toString(t,s,i){return t?.doc?wy.stringifyPair(this,t,s,i):JSON.stringify(this)}};Un.Pair=Yi;Un.createPair=vy});var Vn=N(zc=>{"use strict";var at=U(),Yc=gs(),zi=fs();function Sy(e,t,s){return(t.inFlow??e.flow?xy:$y)(e,t,s)}function $y({comment:e,items:t},s,{blockItemPrefix:i,flowChars:r,itemIndent:n,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:u}}=s,f=Object.assign({},s,{indent:n,type:null}),d=!1,p=[];for(let g=0;g<t.length;++g){let h=t[g],y=null;if(at.isNode(h))!d&&h.spaceBefore&&p.push(""),Xi(s,p,h.commentBefore,d),h.comment&&(y=h.comment);else if(at.isPair(h)){let k=at.isNode(h.key)?h.key:null;k&&(!d&&k.spaceBefore&&p.push(""),Xi(s,p,k.commentBefore,d))}d=!1;let b=Yc.stringify(h,f,()=>y=null,()=>d=!0);y&&(b+=zi.lineComment(b,n,u(y))),d&&y&&(d=!1),p.push(i+b)}let m;if(p.length===0)m=r.start+r.end;else{m=p[0];for(let g=1;g<p.length;++g){let h=p[g];m+=h?`
47
- ${c}${h}`:`
48
- `}}return e?(m+=`
49
- `+zi.indentComment(u(e),c),a&&a()):d&&o&&o(),m}function xy({items:e},t,{flowChars:s,itemIndent:i}){let{indent:r,indentStep:n,flowCollectionPadding:o,options:{commentString:a}}=t;i+=n;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),u=!1,f=0,d=[];for(let g=0;g<e.length;++g){let h=e[g],y=null;if(at.isNode(h))h.spaceBefore&&d.push(""),Xi(t,d,h.commentBefore,!1),h.comment&&(y=h.comment);else if(at.isPair(h)){let k=at.isNode(h.key)?h.key:null;k&&(k.spaceBefore&&d.push(""),Xi(t,d,k.commentBefore,!1),k.comment&&(u=!0));let w=at.isNode(h.value)?h.value:null;w?(w.comment&&(y=w.comment),w.commentBefore&&(u=!0)):h.value==null&&k?.comment&&(y=k.comment)}y&&(u=!0);let b=Yc.stringify(h,c,()=>y=null);u||(u=d.length>f||b.includes(`
50
- `)),g<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(u||(u=d.reduce((k,w)=>k+w.length+2,2)+(b.length+2)>t.options.lineWidth)),u&&(b+=",")),y&&(b+=zi.lineComment(b,i,a(y))),d.push(b),f=d.length}let{start:p,end:m}=s;if(d.length===0)return p+m;if(!u){let g=d.reduce((h,y)=>h+y.length+2,2);u=t.options.lineWidth>0&&g>t.options.lineWidth}if(u){let g=p;for(let h of d)g+=h?`
51
- ${n}${r}${h}`:`
52
- `;return`${g}
53
- ${r}${m}`}else return`${p}${o}${d.join(" ")}${o}${m}`}function Xi({indent:e,options:{commentString:t}},s,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let n=zi.indentComment(t(i),e);s.push(n.trimStart())}}zc.stringifyCollection=Sy});var Xe=N(Gn=>{"use strict";var Ey=Vn(),Py=qn(),Cy=Fi(),ze=U(),Zi=Ye(),Iy=Z();function bs(e,t){let s=ze.isScalar(t)?t.value:t;for(let i of e)if(ze.isPair(i)&&(i.key===t||i.key===s||ze.isScalar(i.key)&&i.key.value===s))return i}var Kn=class extends Cy.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ze.MAP,t),this.items=[]}static from(t,s,i){let{keepUndefined:r,replacer:n}=i,o=new this(t),a=(c,u)=>{if(typeof n=="function")u=n.call(s,c,u);else if(Array.isArray(n)&&!n.includes(c))return;(u!==void 0||r)&&o.items.push(Zi.createPair(c,u,i))};if(s instanceof Map)for(let[c,u]of s)a(c,u);else if(s&&typeof s=="object")for(let c of Object.keys(s))a(c,s[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,s){let i;ze.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Zi.Pair(t,t?.value):i=new Zi.Pair(t.key,t.value);let r=bs(this.items,i.key),n=this.schema?.sortMapEntries;if(r){if(!s)throw new Error(`Key ${i.key} already set`);ze.isScalar(r.value)&&Iy.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(n){let o=this.items.findIndex(a=>n(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let s=bs(this.items,t);return s?this.items.splice(this.items.indexOf(s),1).length>0:!1}get(t,s){let r=bs(this.items,t)?.value;return(!s&&ze.isScalar(r)?r.value:r)??void 0}has(t){return!!bs(this.items,t)}set(t,s){this.add(new Zi.Pair(t,s),!0)}toJSON(t,s,i){let r=i?new i:s?.mapAsMap?new Map:{};s?.onCreate&&s.onCreate(r);for(let n of this.items)Py.addPairToJSMap(s,r,n);return r}toString(t,s,i){if(!t)return JSON.stringify(this);for(let r of this.items)if(!ze.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Ey.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:s})}};Gn.YAMLMap=Kn;Gn.findPair=bs});var At=N(Zc=>{"use strict";var Ly=U(),Xc=Xe(),Ay={collection:"map",default:!0,nodeClass:Xc.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Ly.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,s)=>Xc.YAMLMap.from(e,t,s)};Zc.map=Ay});var Ze=N(Qc=>{"use strict";var Ry=ds(),Ny=Vn(),Ty=Fi(),er=U(),Oy=Z(),My=Ge(),Hn=class extends Ty.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(er.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let s=Qi(t);return typeof s!="number"?!1:this.items.splice(s,1).length>0}get(t,s){let i=Qi(t);if(typeof i!="number")return;let r=this.items[i];return!s&&er.isScalar(r)?r.value:r}has(t){let s=Qi(t);return typeof s=="number"&&s<this.items.length}set(t,s){let i=Qi(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let r=this.items[i];er.isScalar(r)&&Oy.isScalarValue(s)?r.value=s:this.items[i]=s}toJSON(t,s){let i=[];s?.onCreate&&s.onCreate(i);let r=0;for(let n of this.items)i.push(My.toJS(n,String(r++),s));return i}toString(t,s,i){return t?Ny.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:s}):JSON.stringify(this)}static from(t,s,i){let{replacer:r}=i,n=new this(t);if(s&&Symbol.iterator in Object(s)){let o=0;for(let a of s){if(typeof r=="function"){let c=s instanceof Set?a:String(o++);a=r.call(s,c,a)}n.items.push(Ry.createNode(a,void 0,i))}}return n}};function Qi(e){let t=er.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Qc.YAMLSeq=Hn});var Rt=N(tu=>{"use strict";var Dy=U(),eu=Ze(),Fy={collection:"seq",default:!0,nodeClass:eu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Dy.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,s)=>eu.YAMLSeq.from(e,t,s)};tu.seq=Fy});var ws=N(su=>{"use strict";var _y=hs(),jy={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,s,i){return t=Object.assign({actualString:!0},t),_y.stringifyString(e,t,s,i)}};su.string=jy});var tr=N(nu=>{"use strict";var iu=Z(),ru={identify:e=>e==null,createNode:()=>new iu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new iu.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&ru.test.test(e)?e:t.options.nullStr};nu.nullTag=ru});var Jn=N(au=>{"use strict";var By=Z(),ou={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new By.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},s){if(e&&ou.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?s.options.trueStr:s.options.falseStr}};au.boolTag=ou});var Nt=N(lu=>{"use strict";function qy({format:e,minFractionDigits:t,tag:s,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let n=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!s||s==="tag:yaml.org,2002:float")&&/^-?\d/.test(n)&&!n.includes("e")){let o=n.indexOf(".");o<0&&(o=n.length,n+=".");let a=t-(n.length-o-1);for(;a-- >0;)n+="0"}return n}lu.stringifyNumber=qy});var Yn=N(sr=>{"use strict";var Uy=Z(),Wn=Nt(),Vy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Wn.stringifyNumber},Ky={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Wn.stringifyNumber(e)}},Gy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new Uy.Scalar(parseFloat(e)),s=e.indexOf(".");return s!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-s-1),t},stringify:Wn.stringifyNumber};sr.float=Gy;sr.floatExp=Ky;sr.floatNaN=Vy});var Xn=N(rr=>{"use strict";var cu=Nt(),ir=e=>typeof e=="bigint"||Number.isInteger(e),zn=(e,t,s,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),s);function uu(e,t,s){let{value:i}=e;return ir(i)&&i>=0?s+i.toString(t):cu.stringifyNumber(e)}var Hy={identify:e=>ir(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,s)=>zn(e,2,8,s),stringify:e=>uu(e,8,"0o")},Jy={identify:ir,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,s)=>zn(e,0,10,s),stringify:cu.stringifyNumber},Wy={identify:e=>ir(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,s)=>zn(e,2,16,s),stringify:e=>uu(e,16,"0x")};rr.int=Jy;rr.intHex=Wy;rr.intOct=Hy});var fu=N(du=>{"use strict";var Yy=At(),zy=tr(),Xy=Rt(),Zy=ws(),Qy=Jn(),Zn=Yn(),Qn=Xn(),eb=[Yy.map,Xy.seq,Zy.string,zy.nullTag,Qy.boolTag,Qn.intOct,Qn.int,Qn.intHex,Zn.floatNaN,Zn.floatExp,Zn.float];du.schema=eb});var hu=N(mu=>{"use strict";var tb=Z(),sb=At(),ib=Rt();function pu(e){return typeof e=="bigint"||Number.isInteger(e)}var nr=({value:e})=>JSON.stringify(e),rb=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:nr},{identify:e=>e==null,createNode:()=>new tb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:nr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:nr},{identify:pu,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:s})=>s?BigInt(e):parseInt(e,10),stringify:({value:e})=>pu(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:nr}],nb={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},ob=[sb.map,ib.seq].concat(rb,nb);mu.schema=ob});var to=N(gu=>{"use strict";var ks=gi("buffer"),eo=Z(),ab=hs(),lb={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ks.Buffer=="function")return ks.Buffer.from(e,"base64");if(typeof atob=="function"){let s=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(s.length);for(let r=0;r<s.length;++r)i[r]=s.charCodeAt(r);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:s},i,r,n){if(!s)return"";let o=s,a;if(typeof ks.Buffer=="function")a=o instanceof ks.Buffer?o.toString("base64"):ks.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let u=0;u<o.length;++u)c+=String.fromCharCode(o[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=eo.Scalar.BLOCK_LITERAL),t!==eo.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),u=Math.ceil(a.length/c),f=new Array(u);for(let d=0,p=0;d<u;++d,p+=c)f[d]=a.substr(p,c);a=f.join(t===eo.Scalar.BLOCK_LITERAL?`
54
- `:" ")}return ab.stringifyString({comment:e,type:t,value:a},i,r,n)}};gu.binary=lb});var lr=N(ar=>{"use strict";var or=U(),so=Ye(),cb=Z(),ub=Ze();function yu(e,t){if(or.isSeq(e))for(let s=0;s<e.items.length;++s){let i=e.items[s];if(!or.isPair(i)){if(or.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let r=i.items[0]||new so.Pair(new cb.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore}
55
- ${r.key.commentBefore}`:i.commentBefore),i.comment){let n=r.value??r.key;n.comment=n.comment?`${i.comment}
56
- ${n.comment}`:i.comment}i=r}e.items[s]=or.isPair(i)?i:new so.Pair(i)}}else t("Expected a sequence for this tag");return e}function bu(e,t,s){let{replacer:i}=s,r=new ub.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let n=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(n++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let u=Object.keys(o);if(u.length===1)a=u[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;r.items.push(so.createPair(a,c,s))}return r}var db={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:yu,createNode:bu};ar.createPairs=bu;ar.pairs=db;ar.resolvePairs=yu});var no=N(ro=>{"use strict";var wu=U(),io=Ge(),vs=Xe(),fb=Ze(),ku=lr(),lt=class e extends fb.YAMLSeq{constructor(){super(),this.add=vs.YAMLMap.prototype.add.bind(this),this.delete=vs.YAMLMap.prototype.delete.bind(this),this.get=vs.YAMLMap.prototype.get.bind(this),this.has=vs.YAMLMap.prototype.has.bind(this),this.set=vs.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,s){if(!s)return super.toJSON(t);let i=new Map;s?.onCreate&&s.onCreate(i);for(let r of this.items){let n,o;if(wu.isPair(r)?(n=io.toJS(r.key,"",s),o=io.toJS(r.value,n,s)):n=io.toJS(r,"",s),i.has(n))throw new Error("Ordered maps must not include duplicate keys");i.set(n,o)}return i}static from(t,s,i){let r=ku.createPairs(t,s,i),n=new this;return n.items=r.items,n}};lt.tag="tag:yaml.org,2002:omap";var pb={collection:"seq",identify:e=>e instanceof Map,nodeClass:lt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let s=ku.resolvePairs(e,t),i=[];for(let{key:r}of s.items)wu.isScalar(r)&&(i.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new lt,s)},createNode:(e,t,s)=>lt.from(e,t,s)};ro.YAMLOMap=lt;ro.omap=pb});var Eu=N(oo=>{"use strict";var vu=Z();function Su({value:e,source:t},s){return t&&(e?$u:xu).test.test(t)?t:e?s.options.trueStr:s.options.falseStr}var $u={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new vu.Scalar(!0),stringify:Su},xu={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new vu.Scalar(!1),stringify:Su};oo.falseTag=xu;oo.trueTag=$u});var Pu=N(cr=>{"use strict";var mb=Z(),ao=Nt(),hb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ao.stringifyNumber},gb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():ao.stringifyNumber(e)}},yb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new mb.Scalar(parseFloat(e.replace(/_/g,""))),s=e.indexOf(".");if(s!==-1){let i=e.substring(s+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:ao.stringifyNumber};cr.float=yb;cr.floatExp=gb;cr.floatNaN=hb});var Iu=N($s=>{"use strict";var Cu=Nt(),Ss=e=>typeof e=="bigint"||Number.isInteger(e);function ur(e,t,s,{intAsBigInt:i}){let r=e[0];if((r==="-"||r==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(s){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return r==="-"?BigInt(-1)*o:o}let n=parseInt(e,s);return r==="-"?-1*n:n}function lo(e,t,s){let{value:i}=e;if(Ss(i)){let r=i.toString(t);return i<0?"-"+s+r.substr(1):s+r}return Cu.stringifyNumber(e)}var bb={identify:Ss,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,s)=>ur(e,2,2,s),stringify:e=>lo(e,2,"0b")},wb={identify:Ss,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,s)=>ur(e,1,8,s),stringify:e=>lo(e,8,"0")},kb={identify:Ss,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,s)=>ur(e,0,10,s),stringify:Cu.stringifyNumber},vb={identify:Ss,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,s)=>ur(e,2,16,s),stringify:e=>lo(e,16,"0x")};$s.int=kb;$s.intBin=bb;$s.intHex=vb;$s.intOct=wb});var uo=N(co=>{"use strict";var pr=U(),dr=Ye(),fr=Xe(),ct=class e extends fr.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let s;pr.isPair(t)?s=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?s=new dr.Pair(t.key,null):s=new dr.Pair(t,null),fr.findPair(this.items,s.key)||this.items.push(s)}get(t,s){let i=fr.findPair(this.items,t);return!s&&pr.isPair(i)?pr.isScalar(i.key)?i.key.value:i.key:i}set(t,s){if(typeof s!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof s}`);let i=fr.findPair(this.items,t);i&&!s?this.items.splice(this.items.indexOf(i),1):!i&&s&&this.items.push(new dr.Pair(t))}toJSON(t,s){return super.toJSON(t,s,Set)}toString(t,s,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),s,i);throw new Error("Set items must all have null values")}static from(t,s,i){let{replacer:r}=i,n=new this(t);if(s&&Symbol.iterator in Object(s))for(let o of s)typeof r=="function"&&(o=r.call(s,o,o)),n.items.push(dr.createPair(o,null,i));return n}};ct.tag="tag:yaml.org,2002:set";var Sb={collection:"map",identify:e=>e instanceof Set,nodeClass:ct,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,s)=>ct.from(e,t,s),resolve(e,t){if(pr.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new ct,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};co.YAMLSet=ct;co.set=Sb});var po=N(mr=>{"use strict";var $b=Nt();function fo(e,t){let s=e[0],i=s==="-"||s==="+"?e.substring(1):e,r=o=>t?BigInt(o):Number(o),n=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return s==="-"?r(-1)*n:n}function Lu(e){let{value:t}=e,s=o=>o;if(typeof t=="bigint")s=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return $b.stringifyNumber(e);let i="";t<0&&(i="-",t*=s(-1));let r=s(60),n=[t%r];return t<60?n.unshift(0):(t=(t-n[0])/r,n.unshift(t%r),t>=60&&(t=(t-n[0])/r,n.unshift(t))),i+n.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var xb={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:s})=>fo(e,s),stringify:Lu},Eb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>fo(e,!1),stringify:Lu},Au={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Au.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,s,i,r,n,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,u=Date.UTC(s,i-1,r,n||0,o||0,a||0,c),f=t[8];if(f&&f!=="Z"){let d=fo(f,!1);Math.abs(d)<30&&(d*=60),u-=6e4*d}return new Date(u)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};mr.floatTime=Eb;mr.intTime=xb;mr.timestamp=Au});var Tu=N(Nu=>{"use strict";var Pb=At(),Cb=tr(),Ib=Rt(),Lb=ws(),Ab=to(),Ru=Eu(),mo=Pu(),hr=Iu(),Rb=Ji(),Nb=no(),Tb=lr(),Ob=uo(),ho=po(),Mb=[Pb.map,Ib.seq,Lb.string,Cb.nullTag,Ru.trueTag,Ru.falseTag,hr.intBin,hr.intOct,hr.int,hr.intHex,mo.floatNaN,mo.floatExp,mo.float,Ab.binary,Rb.merge,Nb.omap,Tb.pairs,Ob.set,ho.intTime,ho.floatTime,ho.timestamp];Nu.schema=Mb});var Vu=N(bo=>{"use strict";var Fu=At(),Db=tr(),_u=Rt(),Fb=ws(),_b=Jn(),go=Yn(),yo=Xn(),jb=fu(),Bb=hu(),ju=to(),xs=Ji(),Bu=no(),qu=lr(),Ou=Tu(),Uu=uo(),gr=po(),Mu=new Map([["core",jb.schema],["failsafe",[Fu.map,_u.seq,Fb.string]],["json",Bb.schema],["yaml11",Ou.schema],["yaml-1.1",Ou.schema]]),Du={binary:ju.binary,bool:_b.boolTag,float:go.float,floatExp:go.floatExp,floatNaN:go.floatNaN,floatTime:gr.floatTime,int:yo.int,intHex:yo.intHex,intOct:yo.intOct,intTime:gr.intTime,map:Fu.map,merge:xs.merge,null:Db.nullTag,omap:Bu.omap,pairs:qu.pairs,seq:_u.seq,set:Uu.set,timestamp:gr.timestamp},qb={"tag:yaml.org,2002:binary":ju.binary,"tag:yaml.org,2002:merge":xs.merge,"tag:yaml.org,2002:omap":Bu.omap,"tag:yaml.org,2002:pairs":qu.pairs,"tag:yaml.org,2002:set":Uu.set,"tag:yaml.org,2002:timestamp":gr.timestamp};function Ub(e,t,s){let i=Mu.get(t);if(i&&!e)return s&&!i.includes(xs.merge)?i.concat(xs.merge):i.slice();let r=i;if(!r)if(Array.isArray(e))r=[];else{let n=Array.from(Mu.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${n} or define customTags array`)}if(Array.isArray(e))for(let n of e)r=r.concat(n);else typeof e=="function"&&(r=e(r.slice()));return s&&(r=r.concat(xs.merge)),r.reduce((n,o)=>{let a=typeof o=="string"?Du[o]:o;if(!a){let c=JSON.stringify(o),u=Object.keys(Du).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return n.includes(a)||n.push(a),n},[])}bo.coreKnownTags=qb;bo.getTags=Ub});var vo=N(Ku=>{"use strict";var wo=U(),Vb=At(),Kb=Rt(),Gb=ws(),yr=Vu(),Hb=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ko=class e{constructor({compat:t,customTags:s,merge:i,resolveKnownTags:r,schema:n,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(t)?yr.getTags(t,"compat"):t?yr.getTags(null,t):null,this.name=typeof n=="string"&&n||"core",this.knownTags=r?yr.coreKnownTags:{},this.tags=yr.getTags(s,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,wo.MAP,{value:Vb.map}),Object.defineProperty(this,wo.SCALAR,{value:Gb.string}),Object.defineProperty(this,wo.SEQ,{value:Kb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Hb:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Ku.Schema=ko});var Hu=N(Gu=>{"use strict";var Jb=U(),So=gs(),Es=fs();function Wb(e,t){let s=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(s.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&s.push("---");let r=So.createStringifyContext(e,t),{commentString:n}=r.options;if(e.commentBefore){s.length!==1&&s.unshift("");let c=n(e.commentBefore);s.unshift(Es.indentComment(c,""))}let o=!1,a=null;if(e.contents){if(Jb.isNode(e.contents)){if(e.contents.spaceBefore&&i&&s.push(""),e.contents.commentBefore){let f=n(e.contents.commentBefore);s.push(Es.indentComment(f,""))}r.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>o=!0,u=So.stringify(e.contents,r,()=>a=null,c);a&&(u+=Es.lineComment(u,"",n(a))),(u[0]==="|"||u[0]===">")&&s[s.length-1]==="---"?s[s.length-1]=`--- ${u}`:s.push(u)}else s.push(So.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=n(e.comment);c.includes(`
57
- `)?(s.push("..."),s.push(Es.indentComment(c,""))):s.push(`... ${c}`)}else s.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&s[s.length-1]!==""&&s.push(""),s.push(Es.indentComment(n(c),"")))}return s.join(`
58
- `)+`
59
- `}Gu.stringifyDocument=Wb});var Ps=N(Ju=>{"use strict";var Yb=us(),Tt=Fi(),Se=U(),zb=Ye(),Xb=Ge(),Zb=vo(),Qb=Hu(),$o=Ti(),ew=Pn(),tw=ds(),xo=En(),Eo=class e{constructor(t,s,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Se.NODE_TYPE,{value:Se.DOC});let r=null;typeof s=="function"||Array.isArray(s)?r=s:i===void 0&&s&&(i=s,s=void 0);let n=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=n;let{version:o}=n;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new xo.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,r,i)}clone(){let t=Object.create(e.prototype,{[Se.NODE_TYPE]:{value:Se.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Se.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ot(this.contents)&&this.contents.add(t)}addIn(t,s){Ot(this.contents)&&this.contents.addIn(t,s)}createAlias(t,s){if(!t.anchor){let i=$o.anchorNames(this);t.anchor=!s||i.has(s)?$o.findNewAnchor(s||"a",i):s}return new Yb.Alias(t.anchor)}createNode(t,s,i){let r;if(typeof s=="function")t=s.call({"":t},"",t),r=s;else if(Array.isArray(s)){let y=k=>typeof k=="number"||k instanceof String||k instanceof Number,b=s.filter(y).map(String);b.length>0&&(s=s.concat(b)),r=s}else i===void 0&&s&&(i=s,s=void 0);let{aliasDuplicateObjects:n,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:u,tag:f}=i??{},{onAnchor:d,setAnchors:p,sourceObjects:m}=$o.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:n??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:u,replacer:r,schema:this.schema,sourceObjects:m},h=tw.createNode(t,f,g);return a&&Se.isCollection(h)&&(h.flow=!0),p(),h}createPair(t,s,i={}){let r=this.createNode(t,null,i),n=this.createNode(s,null,i);return new zb.Pair(r,n)}delete(t){return Ot(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Tt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ot(this.contents)?this.contents.deleteIn(t):!1}get(t,s){return Se.isCollection(this.contents)?this.contents.get(t,s):void 0}getIn(t,s){return Tt.isEmptyPath(t)?!s&&Se.isScalar(this.contents)?this.contents.value:this.contents:Se.isCollection(this.contents)?this.contents.getIn(t,s):void 0}has(t){return Se.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Tt.isEmptyPath(t)?this.contents!==void 0:Se.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,s){this.contents==null?this.contents=Tt.collectionFromPath(this.schema,[t],s):Ot(this.contents)&&this.contents.set(t,s)}setIn(t,s){Tt.isEmptyPath(t)?this.contents=s:this.contents==null?this.contents=Tt.collectionFromPath(this.schema,Array.from(t),s):Ot(this.contents)&&this.contents.setIn(t,s)}setSchema(t,s={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new xo.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new xo.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(s.schema instanceof Object)this.schema=s.schema;else if(i)this.schema=new Zb.Schema(Object.assign(i,s));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:s,mapAsMap:i,maxAliasCount:r,onAnchor:n,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=Xb.toJS(this.contents,s??"",a);if(typeof n=="function")for(let{count:u,res:f}of a.anchors.values())n(f,u);return typeof o=="function"?ew.applyReviver(o,{"":c},"",c):c}toJSON(t,s){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:s})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let s=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${s}`)}return Qb.stringifyDocument(this,t)}};function Ot(e){if(Se.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Ju.Document=Eo});var Ls=N(Is=>{"use strict";var Cs=class extends Error{constructor(t,s,i,r){super(),this.name=t,this.code=i,this.message=r,this.pos=s}},Po=class extends Cs{constructor(t,s,i){super("YAMLParseError",t,s,i)}},Co=class extends Cs{constructor(t,s,i){super("YAMLWarning",t,s,i)}},sw=(e,t)=>s=>{if(s.pos[0]===-1)return;s.linePos=s.pos.map(a=>t.linePos(a));let{line:i,col:r}=s.linePos[0];s.message+=` at line ${i}, column ${r}`;let n=r-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(n>=60&&o.length>80){let a=Math.min(n-39,o.length-79);o="\u2026"+o.substring(a),n-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),i>1&&/^ *$/.test(o.substring(0,n))){let a=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
60
- `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=s.linePos[1];c?.line===i&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-n)));let u=" ".repeat(n)+"^".repeat(a);s.message+=`:
61
-
62
- ${o}
63
- ${u}
64
- `}};Is.YAMLError=Cs;Is.YAMLParseError=Po;Is.YAMLWarning=Co;Is.prettifyError=sw});var As=N(Wu=>{"use strict";function iw(e,{flow:t,indicator:s,next:i,offset:r,onError:n,parentIndent:o,startOnNewline:a}){let c=!1,u=a,f=a,d="",p="",m=!1,g=!1,h=null,y=null,b=null,k=null,w=null,v=null,x=null;for(let E of e)switch(g&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&n(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),h&&(u&&E.type!=="comment"&&E.type!=="newline"&&n(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),E.type){case"space":!t&&(s!=="doc-start"||i?.type!=="flow-collection")&&E.source.includes(" ")&&(h=E),f=!0;break;case"comment":{f||n(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let _=E.source.substring(1)||" ";d?d+=p+_:d=_,p="",u=!1;break}case"newline":u?d?d+=E.source:(!v||s!=="seq-item-ind")&&(c=!0):p+=E.source,u=!0,m=!0,(y||b)&&(k=E),f=!0;break;case"anchor":y&&n(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&n(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=E,x??(x=E.offset),u=!1,f=!1,g=!0;break;case"tag":{b&&n(E,"MULTIPLE_TAGS","A node can have at most one tag"),b=E,x??(x=E.offset),u=!1,f=!1,g=!0;break}case s:(y||b)&&n(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),v&&n(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${t??"collection"}`),v=E,u=s==="seq-item-ind"||s==="explicit-key-ind",f=!1;break;case"comma":if(t){w&&n(E,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),w=E,u=!1,f=!1;break}default:n(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),u=!1,f=!1}let C=e[e.length-1],A=C?C.offset+C.source.length:r;return g&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&n(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(u&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&n(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:w,found:v,spaceBefore:c,comment:d,hasNewline:m,anchor:y,tag:b,newlineAfterProp:k,end:A,start:x??A}}Wu.resolveProps=iw});var br=N(Yu=>{"use strict";function Io(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
65
- `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let s of t.start)if(s.type==="newline")return!0;if(t.sep){for(let s of t.sep)if(s.type==="newline")return!0}if(Io(t.key)||Io(t.value))return!0}return!1;default:return!0}}Yu.containsNewline=Io});var Lo=N(zu=>{"use strict";var rw=br();function nw(e,t,s){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&rw.containsNewline(t)&&s(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}zu.flowIndentCheck=nw});var Ao=N(Zu=>{"use strict";var Xu=U();function ow(e,t,s){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let r=typeof i=="function"?i:(n,o)=>n===o||Xu.isScalar(n)&&Xu.isScalar(o)&&n.value===o.value;return t.some(n=>r(n.key,s))}Zu.mapIncludes=ow});var rd=N(id=>{"use strict";var Qu=Ye(),aw=Xe(),ed=As(),lw=br(),td=Lo(),cw=Ao(),sd="All mapping items must start at the same column";function uw({composeNode:e,composeEmptyNode:t},s,i,r,n){let o=n?.nodeClass??aw.YAMLMap,a=new o(s.schema);s.atRoot&&(s.atRoot=!1);let c=i.offset,u=null;for(let f of i.items){let{start:d,key:p,sep:m,value:g}=f,h=ed.resolveProps(d,{indicator:"explicit-key-ind",next:p??m?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),y=!h.found;if(y){if(p&&(p.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==i.indent&&r(c,"BAD_INDENT",sd)),!h.anchor&&!h.tag&&!m){u=h.end,h.comment&&(a.comment?a.comment+=`
66
- `+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||lw.containsNewline(p))&&r(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&r(c,"BAD_INDENT",sd);s.atKey=!0;let b=h.end,k=p?e(s,p,h,r):t(s,b,d,null,h,r);s.schema.compat&&td.flowIndentCheck(i.indent,p,r),s.atKey=!1,cw.mapIncludes(s,a.items,k)&&r(b,"DUPLICATE_KEY","Map keys must be unique");let w=ed.resolveProps(m??[],{indicator:"map-value-ind",next:g,offset:k.range[2],onError:r,parentIndent:i.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=w.end,w.found){y&&(g?.type==="block-map"&&!w.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),s.options.strict&&h.start<w.found.offset-1024&&r(k.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let v=g?e(s,g,w,r):t(s,c,m,null,w,r);s.schema.compat&&td.flowIndentCheck(i.indent,g,r),c=v.range[2];let x=new Qu.Pair(k,v);s.options.keepSourceTokens&&(x.srcToken=f),a.items.push(x)}else{y&&r(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),w.comment&&(k.comment?k.comment+=`
67
- `+w.comment:k.comment=w.comment);let v=new Qu.Pair(k);s.options.keepSourceTokens&&(v.srcToken=f),a.items.push(v)}}return u&&u<c&&r(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[i.offset,c,u??c],a}id.resolveBlockMap=uw});var od=N(nd=>{"use strict";var dw=Ze(),fw=As(),pw=Lo();function mw({composeNode:e,composeEmptyNode:t},s,i,r,n){let o=n?.nodeClass??dw.YAMLSeq,a=new o(s.schema);s.atRoot&&(s.atRoot=!1),s.atKey&&(s.atKey=!1);let c=i.offset,u=null;for(let{start:f,value:d}of i.items){let p=fw.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?r(p.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{u=p.end,p.comment&&(a.comment=p.comment);continue}let m=d?e(s,d,p,r):t(s,p.end,f,null,p,r);s.schema.compat&&pw.flowIndentCheck(i.indent,d,r),c=m.range[2],a.items.push(m)}return a.range=[i.offset,c,u??c],a}nd.resolveBlockSeq=mw});var Mt=N(ad=>{"use strict";function hw(e,t,s,i){let r="";if(e){let n=!1,o="";for(let a of e){let{source:c,type:u}=a;switch(u){case"space":n=!0;break;case"comment":{s&&!n&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";r?r+=o+f:r=f,o="";break}case"newline":r&&(o+=c),n=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}t+=c.length}}return{comment:r,offset:t}}ad.resolveEnd=hw});var dd=N(ud=>{"use strict";var gw=U(),yw=Ye(),ld=Xe(),bw=Ze(),ww=Mt(),cd=As(),kw=br(),vw=Ao(),Ro="Block collections are not allowed within flow collections",No=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Sw({composeNode:e,composeEmptyNode:t},s,i,r,n){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=n?.nodeClass??(o?ld.YAMLMap:bw.YAMLSeq),u=new c(s.schema);u.flow=!0;let f=s.atRoot;f&&(s.atRoot=!1),s.atKey&&(s.atKey=!1);let d=i.offset+i.start.source.length;for(let y=0;y<i.items.length;++y){let b=i.items[y],{start:k,key:w,sep:v,value:x}=b,C=cd.resolveProps(k,{flow:a,indicator:"explicit-key-ind",next:w??v?.[0],offset:d,onError:r,parentIndent:i.indent,startOnNewline:!1});if(!C.found){if(!C.anchor&&!C.tag&&!v&&!x){y===0&&C.comma?r(C.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<i.items.length-1&&r(C.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),C.comment&&(u.comment?u.comment+=`
68
- `+C.comment:u.comment=C.comment),d=C.end;continue}!o&&s.options.strict&&kw.containsNewline(w)&&r(w,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)C.comma&&r(C.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(C.comma||r(C.start,"MISSING_CHAR",`Missing , between ${a} items`),C.comment){let A="";e:for(let E of k)switch(E.type){case"comma":case"space":break;case"comment":A=E.source.substring(1);break e;default:break e}if(A){let E=u.items[u.items.length-1];gw.isPair(E)&&(E=E.value??E.key),E.comment?E.comment+=`
69
- `+A:E.comment=A,C.comment=C.comment.substring(A.length+1)}}if(!o&&!v&&!C.found){let A=x?e(s,x,C,r):t(s,C.end,v,null,C,r);u.items.push(A),d=A.range[2],No(x)&&r(A.range,"BLOCK_IN_FLOW",Ro)}else{s.atKey=!0;let A=C.end,E=w?e(s,w,C,r):t(s,A,k,null,C,r);No(w)&&r(E.range,"BLOCK_IN_FLOW",Ro),s.atKey=!1;let _=cd.resolveProps(v??[],{flow:a,indicator:"map-value-ind",next:x,offset:E.range[2],onError:r,parentIndent:i.indent,startOnNewline:!1});if(_.found){if(!o&&!C.found&&s.options.strict){if(v)for(let P of v){if(P===_.found)break;if(P.type==="newline"){r(P,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}C.start<_.found.offset-1024&&r(_.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?r(x,"MISSING_CHAR",`Missing space after : in ${a}`):r(_.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let O=x?e(s,x,_,r):_.found?t(s,_.end,v,null,_,r):null;O?No(x)&&r(O.range,"BLOCK_IN_FLOW",Ro):_.comment&&(E.comment?E.comment+=`
70
- `+_.comment:E.comment=_.comment);let S=new yw.Pair(E,O);if(s.options.keepSourceTokens&&(S.srcToken=b),o){let P=u;vw.mapIncludes(s,P.items,E)&&r(A,"DUPLICATE_KEY","Map keys must be unique"),P.items.push(S)}else{let P=new ld.YAMLMap(s.schema);P.flow=!0,P.items.push(S);let B=(O??E).range;P.range=[E.range[0],B[1],B[2]],u.items.push(P)}d=O?O.range[2]:_.end}}let p=o?"}":"]",[m,...g]=i.end,h=d;if(m?.source===p)h=m.offset+m.source.length;else{let y=a[0].toUpperCase()+a.substring(1),b=f?`${y} must end with a ${p}`:`${y} in block collection must be sufficiently indented and end with a ${p}`;r(d,f?"MISSING_CHAR":"BAD_INDENT",b),m&&m.source.length!==1&&g.unshift(m)}if(g.length>0){let y=ww.resolveEnd(g,h,s.options.strict,r);y.comment&&(u.comment?u.comment+=`
71
- `+y.comment:u.comment=y.comment),u.range=[i.offset,h,y.offset]}else u.range=[i.offset,h,h];return u}ud.resolveFlowCollection=Sw});var pd=N(fd=>{"use strict";var $w=U(),xw=Z(),Ew=Xe(),Pw=Ze(),Cw=rd(),Iw=od(),Lw=dd();function To(e,t,s,i,r,n){let o=s.type==="block-map"?Cw.resolveBlockMap(e,t,s,i,n):s.type==="block-seq"?Iw.resolveBlockSeq(e,t,s,i,n):Lw.resolveFlowCollection(e,t,s,i,n),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function Aw(e,t,s,i,r){let n=i.tag,o=n?t.directives.tagName(n.source,p=>r(n,"TAG_RESOLVE_FAILED",p)):null;if(s.type==="block-seq"){let{anchor:p,newlineAfterProp:m}=i,g=p&&n?p.offset>n.offset?p:n:p??n;g&&(!m||m.offset<g.offset)&&r(g,"MISSING_CHAR","Missing newline after block sequence props")}let a=s.type==="block-map"?"map":s.type==="block-seq"?"seq":s.start.source==="{"?"map":"seq";if(!n||!o||o==="!"||o===Ew.YAMLMap.tagName&&a==="map"||o===Pw.YAMLSeq.tagName&&a==="seq")return To(e,t,s,r,o);let c=t.schema.tags.find(p=>p.tag===o&&p.collection===a);if(!c){let p=t.schema.knownTags[o];if(p?.collection===a)t.schema.tags.push(Object.assign({},p,{default:!1})),c=p;else return p?r(n,"BAD_COLLECTION_TYPE",`${p.tag} used for ${a} collection, but expects ${p.collection??"scalar"}`,!0):r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),To(e,t,s,r,o)}let u=To(e,t,s,r,o,c),f=c.resolve?.(u,p=>r(n,"TAG_RESOLVE_FAILED",p),t.options)??u,d=$w.isNode(f)?f:new xw.Scalar(f);return d.range=u.range,d.tag=o,c?.format&&(d.format=c.format),d}fd.composeCollection=Aw});var Mo=N(md=>{"use strict";var Oo=Z();function Rw(e,t,s){let i=t.offset,r=Nw(t,e.options.strict,s);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let n=r.mode===">"?Oo.Scalar.BLOCK_FOLDED:Oo.Scalar.BLOCK_LITERAL,o=t.source?Tw(t.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=r.chomp==="+"&&o.length>0?`
72
- `.repeat(Math.max(1,o.length-1)):"",y=i+r.length;return t.source&&(y+=t.source.length),{value:h,type:n,comment:r.comment,range:[i,y,y]}}let c=t.indent+r.indent,u=t.offset+r.length,f=0;for(let h=0;h<a;++h){let[y,b]=o[h];if(b===""||b==="\r")r.indent===0&&y.length>c&&(c=y.length);else{y.length<c&&s(u+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(c=y.length),f=h,c===0&&!e.atRoot&&s(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=y.length+b.length+1}for(let h=o.length-1;h>=a;--h)o[h][0].length>c&&(a=h+1);let d="",p="",m=!1;for(let h=0;h<f;++h)d+=o[h][0].slice(c)+`
73
- `;for(let h=f;h<a;++h){let[y,b]=o[h];u+=y.length+b.length+1;let k=b[b.length-1]==="\r";if(k&&(b=b.slice(0,-1)),b&&y.length<c){let v=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;s(u-b.length-(k?2:1),"BAD_INDENT",v),y=""}n===Oo.Scalar.BLOCK_LITERAL?(d+=p+y.slice(c)+b,p=`
74
- `):y.length>c||b[0]===" "?(p===" "?p=`
75
- `:!m&&p===`
76
- `&&(p=`
77
-
78
- `),d+=p+y.slice(c)+b,p=`
79
- `,m=!0):b===""?p===`
80
- `?d+=`
81
- `:p=`
82
- `:(d+=p+b,p=" ",m=!1)}switch(r.chomp){case"-":break;case"+":for(let h=a;h<o.length;++h)d+=`
83
- `+o[h][0].slice(c);d[d.length-1]!==`
84
- `&&(d+=`
85
- `);break;default:d+=`
86
- `}let g=i+r.length+t.source.length;return{value:d,type:n,comment:r.comment,range:[i,g,g]}}function Nw({offset:e,props:t},s,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=t[0],n=r[0],o=0,a="",c=-1;for(let p=1;p<r.length;++p){let m=r[p];if(!a&&(m==="-"||m==="+"))a=m;else{let g=Number(m);!o&&g?o=g:c===-1&&(c=e+p)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let u=!1,f="",d=r.length;for(let p=1;p<t.length;++p){let m=t[p];switch(m.type){case"space":u=!0;case"newline":d+=m.source.length;break;case"comment":s&&!u&&i(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=m.source.length,f=m.source.substring(1);break;case"error":i(m,"UNEXPECTED_TOKEN",m.message),d+=m.source.length;break;default:{let g=`Unexpected token in block scalar header: ${m.type}`;i(m,"UNEXPECTED_TOKEN",g);let h=m.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:n,indent:o,chomp:a,comment:f,length:d}}function Tw(e){let t=e.split(/\n( *)/),s=t[0],i=s.match(/^( *)/),n=[i?.[1]?[i[1],s.slice(i[1].length)]:["",s]];for(let o=1;o<t.length;o+=2)n.push([t[o],t[o+1]]);return n}md.resolveBlockScalar=Rw});var Fo=N(gd=>{"use strict";var Do=Z(),Ow=Mt();function Mw(e,t,s){let{offset:i,type:r,source:n,end:o}=e,a,c,u=(p,m,g)=>s(i+p,m,g);switch(r){case"scalar":a=Do.Scalar.PLAIN,c=Dw(n,u);break;case"single-quoted-scalar":a=Do.Scalar.QUOTE_SINGLE,c=Fw(n,u);break;case"double-quoted-scalar":a=Do.Scalar.QUOTE_DOUBLE,c=_w(n,u);break;default:return s(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+n.length,i+n.length]}}let f=i+n.length,d=Ow.resolveEnd(o,f,t,s);return{value:c,type:a,comment:d.comment,range:[i,f,d.offset]}}function Dw(e,t){let s="";switch(e[0]){case" ":s="a tab character";break;case",":s="flow indicator character ,";break;case"%":s="directive indicator character %";break;case"|":case">":{s=`block scalar indicator ${e[0]}`;break}case"@":case"`":{s=`reserved character ${e[0]}`;break}}return s&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${s}`),hd(e)}function Fw(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),hd(e.slice(1,-1)).replace(/''/g,"'")}function hd(e){let t,s;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
- `,"sy"),s=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
88
- `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,s=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let r=i[1],n=" ",o=t.lastIndex;for(s.lastIndex=o;i=s.exec(e);)i[1]===""?n===`
89
- `?r+=n:n=`
90
- `:(r+=n+i[1],n=" "),o=s.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,i=a.exec(e),r+n+(i?.[1]??"")}function _w(e,t){let s="";for(let i=1;i<e.length-1;++i){let r=e[i];if(!(r==="\r"&&e[i+1]===`
91
- `))if(r===`
92
- `){let{fold:n,offset:o}=jw(e,i);s+=n,i=o}else if(r==="\\"){let n=e[++i],o=Bw[n];if(o)s+=o;else if(n===`
93
- `)for(n=e[i+1];n===" "||n===" ";)n=e[++i+1];else if(n==="\r"&&e[i+1]===`
94
- `)for(n=e[++i+1];n===" "||n===" ";)n=e[++i+1];else if(n==="x"||n==="u"||n==="U"){let a=n==="x"?2:n==="u"?4:8;s+=qw(e,i+1,a,t),i+=a}else{let a=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),s+=a}}else if(r===" "||r===" "){let n=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
95
- `&&!(o==="\r"&&e[i+2]===`
96
- `)&&(s+=i>n?e.slice(n,i+1):r)}else s+=r}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),s}function jw(e,t){let s="",i=e[t+1];for(;(i===" "||i===" "||i===`
97
- `||i==="\r")&&!(i==="\r"&&e[t+2]!==`
98
- `);)i===`
99
- `&&(s+=`
100
- `),t+=1,i=e[t+1];return s||(s=" "),{fold:s,offset:t}}var Bw={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
101
- `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function qw(e,t,s,i){let r=e.substr(t,s),o=r.length===s&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let a=e.substr(t-2,s+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}gd.resolveFlowScalar=Mw});var wd=N(bd=>{"use strict";var ut=U(),yd=Z(),Uw=Mo(),Vw=Fo();function Kw(e,t,s,i){let{value:r,type:n,comment:o,range:a}=t.type==="block-scalar"?Uw.resolveBlockScalar(e,t,i):Vw.resolveFlowScalar(t,e.options.strict,i),c=s?e.directives.tagName(s.source,d=>i(s,"TAG_RESOLVE_FAILED",d)):null,u;e.options.stringKeys&&e.atKey?u=e.schema[ut.SCALAR]:c?u=Gw(e.schema,r,c,s,i):t.type==="scalar"?u=Hw(e,r,t,i):u=e.schema[ut.SCALAR];let f;try{let d=u.resolve(r,p=>i(s??t,"TAG_RESOLVE_FAILED",p),e.options);f=ut.isScalar(d)?d:new yd.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);i(s??t,"TAG_RESOLVE_FAILED",p),f=new yd.Scalar(r)}return f.range=a,f.source=r,n&&(f.type=n),c&&(f.tag=c),u.format&&(f.format=u.format),o&&(f.comment=o),f}function Gw(e,t,s,i,r){if(s==="!")return e[ut.SCALAR];let n=[];for(let a of e.tags)if(!a.collection&&a.tag===s)if(a.default&&a.test)n.push(a);else return a;for(let a of n)if(a.test?.test(t))return a;let o=e.knownTags[s];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,s!=="tag:yaml.org,2002:str"),e[ut.SCALAR])}function Hw({atKey:e,directives:t,schema:s},i,r,n){let o=s.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(i))||s[ut.SCALAR];if(s.compat){let a=s.compat.find(c=>c.default&&c.test?.test(i))??s[ut.SCALAR];if(o.tag!==a.tag){let c=t.tagString(o.tag),u=t.tagString(a.tag),f=`Value may be parsed as either ${c} or ${u}`;n(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}bd.composeScalar=Kw});var vd=N(kd=>{"use strict";function Jw(e,t,s){if(t){s??(s=t.length);for(let i=s-1;i>=0;--i){let r=t[i];switch(r.type){case"space":case"comment":case"newline":e-=r.source.length;continue}for(r=t[++i];r?.type==="space";)e+=r.source.length,r=t[++i];break}}return e}kd.emptyScalarPosition=Jw});var xd=N(jo=>{"use strict";var Ww=us(),Yw=U(),zw=pd(),Sd=wd(),Xw=Mt(),Zw=vd(),Qw={composeNode:$d,composeEmptyNode:_o};function $d(e,t,s,i){let r=e.atKey,{spaceBefore:n,comment:o,anchor:a,tag:c}=s,u,f=!0;switch(t.type){case"alias":u=ek(e,t,i),(a||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=Sd.composeScalar(e,t,c,i),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{u=zw.composeCollection(Qw,e,t,s,i),a&&(u.anchor=a.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",p)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),f=!1}}return u??(u=_o(e,t.offset,void 0,null,s,i)),a&&u.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&e.options.stringKeys&&(!Yw.isScalar(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),n&&(u.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?u.comment=o:u.commentBefore=o),e.options.keepSourceTokens&&f&&(u.srcToken=t),u}function _o(e,t,s,i,{spaceBefore:r,comment:n,anchor:o,tag:a,end:c},u){let f={type:"scalar",offset:Zw.emptyScalarPosition(t,s,i),indent:-1,source:""},d=Sd.composeScalar(e,f,a,u);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(d.spaceBefore=!0),n&&(d.comment=n,d.range[2]=c),d}function ek({options:e},{offset:t,source:s,end:i},r){let n=new Ww.Alias(s.substring(1));n.source===""&&r(t,"BAD_ALIAS","Alias cannot be an empty string"),n.source.endsWith(":")&&r(t+s.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+s.length,a=Xw.resolveEnd(i,o,e.strict,r);return n.range=[t,o,a.offset],a.comment&&(n.comment=a.comment),n}jo.composeEmptyNode=_o;jo.composeNode=$d});var Cd=N(Pd=>{"use strict";var tk=Ps(),Ed=xd(),sk=Mt(),ik=As();function rk(e,t,{offset:s,start:i,value:r,end:n},o){let a=Object.assign({_directives:t},e),c=new tk.Document(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=ik.resolveProps(i,{indicator:"doc-start",next:r??n?.[0],offset:s,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Ed.composeNode(u,r,f,o):Ed.composeEmptyNode(u,f.end,i,null,f,o);let d=c.contents.range[2],p=sk.resolveEnd(n,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[s,d,p.offset],c}Pd.composeDoc=rk});var qo=N(Ad=>{"use strict";var nk=gi("process"),ok=En(),ak=Ps(),Rs=Ls(),Id=U(),lk=Cd(),ck=Mt();function Ns(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:s}=e;return[t,t+(typeof s=="string"?s.length:1)]}function Ld(e){let t="",s=!1,i=!1;for(let r=0;r<e.length;++r){let n=e[r];switch(n[0]){case"#":t+=(t===""?"":i?`
102
-
103
- `:`
104
- `)+(n.substring(1)||" "),s=!0,i=!1;break;case"%":e[r+1]?.[0]!=="#"&&(r+=1),s=!1;break;default:s||(i=!0),s=!1}}return{comment:t,afterEmptyLine:i}}var Bo=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(s,i,r,n)=>{let o=Ns(s);n?this.warnings.push(new Rs.YAMLWarning(o,i,r)):this.errors.push(new Rs.YAMLParseError(o,i,r))},this.directives=new ok.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,s){let{comment:i,afterEmptyLine:r}=Ld(this.prelude);if(i){let n=t.contents;if(s)t.comment=t.comment?`${t.comment}
105
- ${i}`:i;else if(r||t.directives.docStart||!n)t.commentBefore=i;else if(Id.isCollection(n)&&!n.flow&&n.items.length>0){let o=n.items[0];Id.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i}
106
- ${a}`:i}else{let o=n.commentBefore;n.commentBefore=o?`${i}
107
- ${o}`:i}}if(s){for(let n=0;n<this.errors.length;++n)t.errors.push(this.errors[n]);for(let n=0;n<this.warnings.length;++n)t.warnings.push(this.warnings[n])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Ld(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,s=!1,i=-1){for(let r of t)yield*this.next(r);yield*this.end(s,i)}*next(t){switch(nk.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(s,i,r)=>{let n=Ns(t);n[0]+=s,this.onError(n,"BAD_DIRECTIVE",i,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let s=lk.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!s.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(s,!1),this.doc&&(yield this.doc),this.doc=s,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let s=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new Rs.YAMLParseError(Ns(t),"UNEXPECTED_TOKEN",s);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Rs.YAMLParseError(Ns(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let s=ck.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),s.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
108
- ${s.comment}`:s.comment}this.doc.range[2]=s.offset;break}default:this.errors.push(new Rs.YAMLParseError(Ns(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,s=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),r=new ak.Document(void 0,i);this.atDirectives&&this.onError(s,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,s,s],this.decorate(r,!1),yield r}}};Ad.Composer=Bo});var Td=N(wr=>{"use strict";var uk=Mo(),dk=Fo(),fk=Ls(),Rd=hs();function pk(e,t=!0,s){if(e){let i=(r,n,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(s)s(a,n,o);else throw new fk.YAMLParseError([a,a+1],n,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return dk.resolveFlowScalar(e,t,i);case"block-scalar":return uk.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function mk(e,t){let{implicitKey:s=!1,indent:i,inFlow:r=!1,offset:n=-1,type:o="PLAIN"}=t,a=Rd.stringifyString({type:o,value:e},{implicitKey:s,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
109
- `}];switch(a[0]){case"|":case">":{let u=a.indexOf(`
110
- `),f=a.substring(0,u),d=a.substring(u+1)+`
111
- `,p=[{type:"block-scalar-header",offset:n,indent:i,source:f}];return Nd(p,c)||p.push({type:"newline",offset:-1,indent:i,source:`
112
- `}),{type:"block-scalar",offset:n,indent:i,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:n,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:n,indent:i,source:a,end:c};default:return{type:"scalar",offset:n,indent:i,source:a,end:c}}}function hk(e,t,s={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:n=!1,type:o}=s,a="indent"in e?e.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let u=e.props[0];if(u.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=Rd.stringifyString({type:o,value:t},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":gk(e,c);break;case'"':Uo(e,c,"double-quoted-scalar");break;case"'":Uo(e,c,"single-quoted-scalar");break;default:Uo(e,c,"scalar")}}function gk(e,t){let s=t.indexOf(`
113
- `),i=t.substring(0,s),r=t.substring(s+1)+`
114
- `;if(e.type==="block-scalar"){let n=e.props[0];if(n.type!=="block-scalar-header")throw new Error("Invalid block scalar header");n.source=i,e.source=r}else{let{offset:n}=e,o="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:n,indent:o,source:i}];Nd(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
115
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:a,source:r})}}function Nd(e,t){if(t)for(let s of t)switch(s.type){case"space":case"comment":e.push(s);break;case"newline":return e.push(s),!0}return!1}function Uo(e,t,s){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=s,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),r=t.length;e.props[0].type==="block-scalar-header"&&(r-=e.props[0].source.length);for(let n of i)n.offset+=r;delete e.props,Object.assign(e,{type:s,source:t,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
116
- `};delete e.items,Object.assign(e,{type:s,source:t,end:[r]});break}default:{let i="indent"in e?e.indent:-1,r="end"in e&&Array.isArray(e.end)?e.end.filter(n=>n.type==="space"||n.type==="comment"||n.type==="newline"):[];for(let n of Object.keys(e))n!=="type"&&n!=="offset"&&delete e[n];Object.assign(e,{type:s,indent:i,source:t,end:r})}}}wr.createScalarToken=mk;wr.resolveAsScalar=pk;wr.setScalarValue=hk});var Md=N(Od=>{"use strict";var yk=e=>"type"in e?vr(e):kr(e);function vr(e){switch(e.type){case"block-scalar":{let t="";for(let s of e.props)t+=vr(s);return t+e.source}case"block-map":case"block-seq":{let t="";for(let s of e.items)t+=kr(s);return t}case"flow-collection":{let t=e.start.source;for(let s of e.items)t+=kr(s);for(let s of e.end)t+=s.source;return t}case"document":{let t=kr(e);if(e.end)for(let s of e.end)t+=s.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let s of e.end)t+=s.source;return t}}}function kr({start:e,key:t,sep:s,value:i}){let r="";for(let n of e)r+=n.source;if(t&&(r+=vr(t)),s)for(let n of s)r+=n.source;return i&&(r+=vr(i)),r}Od.stringify=yk});var jd=N(_d=>{"use strict";var Vo=Symbol("break visit"),bk=Symbol("skip children"),Dd=Symbol("remove item");function dt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Fd(Object.freeze([]),e,t)}dt.BREAK=Vo;dt.SKIP=bk;dt.REMOVE=Dd;dt.itemAtPath=(e,t)=>{let s=e;for(let[i,r]of t){let n=s?.[i];if(n&&"items"in n)s=n.items[r];else return}return s};dt.parentCollection=(e,t)=>{let s=dt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],r=s?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Fd(e,t,s){let i=s(t,e);if(typeof i=="symbol")return i;for(let r of["key","value"]){let n=t[r];if(n&&"items"in n){for(let o=0;o<n.items.length;++o){let a=Fd(Object.freeze(e.concat([[r,o]])),n.items[o],s);if(typeof a=="number")o=a-1;else{if(a===Vo)return Vo;a===Dd&&(n.items.splice(o,1),o-=1)}}typeof i=="function"&&r==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}_d.visit=dt});var Sr=N(me=>{"use strict";var Ko=Td(),wk=Md(),kk=jd(),Go="\uFEFF",Ho="",Jo="",Wo="",vk=e=>!!e&&"items"in e,Sk=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function $k(e){switch(e){case Go:return"<BOM>";case Ho:return"<DOC>";case Jo:return"<FLOW_END>";case Wo:return"<SCALAR>";default:return JSON.stringify(e)}}function xk(e){switch(e){case Go:return"byte-order-mark";case Ho:return"doc-mode";case Jo:return"flow-error-end";case Wo:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
117
- `:case`\r
118
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}me.createScalarToken=Ko.createScalarToken;me.resolveAsScalar=Ko.resolveAsScalar;me.setScalarValue=Ko.setScalarValue;me.stringify=wk.stringify;me.visit=kk.visit;me.BOM=Go;me.DOCUMENT=Ho;me.FLOW_END=Jo;me.SCALAR=Wo;me.isCollection=vk;me.isScalar=Sk;me.prettyToken=$k;me.tokenType=xk});var Xo=N(qd=>{"use strict";var Ts=Sr();function Ie(e){switch(e){case void 0:case" ":case`
119
- `:case"\r":case" ":return!0;default:return!1}}var Bd=new Set("0123456789ABCDEFabcdef"),Ek=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$r=new Set(",[]{}"),Pk=new Set(` ,[]{}
120
- \r `),Yo=e=>!e||Pk.has(e),zo=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,s=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!s;let i=this.next??"stream";for(;i&&(s||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,s=this.buffer[t];for(;s===" "||s===" ";)s=this.buffer[++t];return!s||s==="#"||s===`
121
- `?!0:s==="\r"?this.buffer[t+1]===`
122
- `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let s=this.buffer[t];if(this.indentNext>0){let i=0;for(;s===" ";)s=this.buffer[++i+t];if(s==="\r"){let r=this.buffer[i+t+1];if(r===`
123
- `||!r&&!this.atEnd)return t+i+1}return s===`
124
- `||i>=this.indentNext||!s&&!this.atEnd?t+i:-1}if(s==="-"||s==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Ie(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
125
- `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Ts.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let s=t.length,i=t.indexOf("#");for(;i!==-1;){let n=t[i-1];if(n===" "||n===" "){s=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let n=t[s-1];if(n===" "||n===" ")s-=1;else break}let r=(yield*this.pushCount(s))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let s=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-s),yield*this.pushNewline(),"stream"}return yield Ts.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let s=this.peek(3);if((s==="---"||s==="...")&&Ie(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,s==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ie(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,s]=this.peek(2);if(!s&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ie(s)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let s=yield*this.pushIndicators();switch(t[s]){case"#":yield*this.pushCount(t.length-s);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Yo),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return s+=yield*this.parseBlockScalarHeader(),s+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-s),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,s,i=-1;do t=yield*this.pushNewline(),t>0?(s=yield*this.pushSpaces(!1),this.indentValue=i=s):s=0,s+=yield*this.pushSpaces(!0);while(t+s>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&r[0]!=="#"||i===0&&(r.startsWith("---")||r.startsWith("..."))&&Ie(r[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Ts.FLOW_END,yield*this.parseLineStart();let n=0;for(;r[n]===",";)n+=yield*this.pushCount(1),n+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(n+=yield*this.pushIndicators(),r[n]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-n),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Yo),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ie(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),s=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;s!==-1&&this.buffer[s+1]==="'";)s=this.buffer.indexOf("'",s+2);else for(;s!==-1;){let n=0;for(;this.buffer[s-1-n]==="\\";)n+=1;if(n%2===0)break;s=this.buffer.indexOf('"',s+1)}let i=this.buffer.substring(0,s),r=i.indexOf(`
126
- `,this.pos);if(r!==-1){for(;r!==-1;){let n=this.continueScalar(r+1);if(n===-1)break;r=i.indexOf(`
127
- `,n)}r!==-1&&(s=r-(i[r-1]==="\r"?2:1))}if(s===-1){if(!this.atEnd)return this.setNext("quoted-scalar");s=this.buffer.length}return yield*this.pushToIndex(s+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let s=this.buffer[++t];if(s==="+")this.blockScalarKeep=!0;else if(s>"0"&&s<="9")this.blockScalarIndent=Number(s)-1;else if(s!=="-")break}return yield*this.pushUntil(s=>Ie(s)||s==="#")}*parseBlockScalar(){let t=this.pos-1,s=0,i;e:for(let n=this.pos;i=this.buffer[n];++n)switch(i){case" ":s+=1;break;case`
128
- `:t=n,s=0;break;case"\r":{let o=this.buffer[n+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
129
- `)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(s>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=s:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let n=this.continueScalar(t+1);if(n===-1)break;t=this.buffer.indexOf(`
130
- `,n)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let r=t+1;for(i=this.buffer[r];i===" ";)i=this.buffer[++r];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
131
- `;)i=this.buffer[++r];t=r-1}else if(!this.blockScalarKeep)do{let n=t-1,o=this.buffer[n];o==="\r"&&(o=this.buffer[--n]);let a=n;for(;o===" ";)o=this.buffer[--n];if(o===`
132
- `&&n>=this.pos&&n+1+s>a)t=n;else break}while(!0);return yield Ts.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,s=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let n=this.buffer[i+1];if(Ie(n)||t&&$r.has(n))break;s=i}else if(Ie(r)){let n=this.buffer[i+1];if(r==="\r"&&(n===`
133
- `?(i+=1,r=`
134
- `,n=this.buffer[i+1]):s=i),n==="#"||t&&$r.has(n))break;if(r===`
135
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&$r.has(r))break;s=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Ts.SCALAR,yield*this.pushToIndex(s+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,s){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(s&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Yo),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let s=this.flowLevel>0,i=this.charAt(1);if(Ie(i)||s&&$r.has(i)){s?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,s=this.buffer[t];for(;!Ie(s)&&s!==">";)s=this.buffer[++t];return yield*this.pushToIndex(s===">"?t+1:t,!1)}else{let t=this.pos+1,s=this.buffer[t];for(;s;)if(Ek.has(s))s=this.buffer[++t];else if(s==="%"&&Bd.has(this.buffer[t+1])&&Bd.has(this.buffer[t+2]))s=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
136
- `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
137
- `?yield*this.pushCount(2):0}*pushSpaces(t){let s=this.pos-1,i;do i=this.buffer[++s];while(i===" "||t&&i===" ");let r=s-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=s),r}*pushUntil(t){let s=this.pos,i=this.buffer[s];for(;!t(i);)i=this.buffer[++s];return yield*this.pushToIndex(s,!1)}};qd.Lexer=zo});var Qo=N(Ud=>{"use strict";var Zo=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let s=0,i=this.lineStarts.length;for(;s<i;){let n=s+i>>1;this.lineStarts[n]<t?s=n+1:i=n}if(this.lineStarts[s]===t)return{line:s+1,col:1};if(s===0)return{line:0,col:t};let r=this.lineStarts[s-1];return{line:s,col:t-r+1}}}};Ud.LineCounter=Zo});var ta=N(Jd=>{"use strict";var Ck=gi("process"),Vd=Sr(),Ik=Xo();function Qe(e,t){for(let s=0;s<e.length;++s)if(e[s].type===t)return!0;return!1}function Kd(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Hd(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function xr(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Dt(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Er(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let s=0;s<t.length;++s)e.push(t[s])}function Gd(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Qe(t.start,"explicit-key-ind")&&!Qe(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Hd(t.value)?t.value.end?Er(t.value.end,t.sep):t.value.end=t.sep:Er(t.start,t.sep),delete t.sep)}var ea=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Ik.Lexer,this.onNewLine=t}*parse(t,s=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,s))yield*this.next(i);s||(yield*this.end())}*next(t){if(this.source=t,Ck.env.LOG_TOKENS&&console.log("|",Vd.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let s=Vd.tokenType(t);if(s)if(s==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=s,yield*this.step(),s){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let s=t??this.stack.pop();if(!s)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield s;else{let i=this.peek(1);switch(s.type==="block-scalar"?s.indent="indent"in i?i.indent:0:s.type==="flow-collection"&&i.type==="document"&&(s.indent=0),s.type==="flow-collection"&&Gd(s),i.type){case"document":i.value=s;break;case"block-scalar":i.props.push(s);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:s,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=s;else{Object.assign(r,{key:s,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:s}):r.value=s;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:s,sep:[]}):r.sep?r.value=s:Object.assign(r,{key:s,sep:[]});return}default:yield*this.pop(),yield*this.pop(s)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(s.type==="block-map"||s.type==="block-seq")){let r=s.items[s.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Kd(r.start)===-1&&(s.indent===0||r.start.every(n=>n.type!=="comment"||n.indent<s.indent))&&(i.type==="document"?i.end=r.start:i.items.push({start:r.start}),s.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Kd(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let s=this.startBlockValue(t);s?this.stack.push(s):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let s=xr(this.peek(2)),i=Dt(s),r;t.end?(r=t.end,r.push(this.sourceToken),delete t.end):r=[this.sourceToken];let n={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=n}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let s=this.source.indexOf(`
138
- `)+1;for(;s!==0;)this.onNewLine(this.offset+s),s=this.source.indexOf(`
139
- `,s)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let s=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,s.value){let i="end"in s.value?s.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else s.sep?s.sep.push(this.sourceToken):s.start.push(this.sourceToken);return;case"space":case"comment":if(s.value)t.items.push({start:[this.sourceToken]});else if(s.sep)s.sep.push(this.sourceToken);else{if(this.atIndentedComment(s.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){Er(r,s.start),r.push(this.sourceToken),t.items.pop();return}}s.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,r=i&&(s.sep||s.explicitKey)&&this.type!=="seq-item-ind",n=[];if(r&&s.sep&&!s.value){let o=[];for(let a=0;a<s.sep.length;++a){let c=s.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(n=s.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||s.value?(n.push(this.sourceToken),t.items.push({start:n}),this.onKeyLine=!0):s.sep?s.sep.push(this.sourceToken):s.start.push(this.sourceToken);return;case"explicit-key-ind":!s.sep&&!s.explicitKey?(s.start.push(this.sourceToken),s.explicitKey=!0):r||s.value?(n.push(this.sourceToken),t.items.push({start:n,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(s.explicitKey)if(s.sep)if(s.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Qe(s.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]});else if(Hd(s.key)&&!Qe(s.sep,"newline")){let o=Dt(s.start),a=s.key,c=s.sep;c.push(this.sourceToken),delete s.key,delete s.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else n.length>0?s.sep=s.sep.concat(n,this.sourceToken):s.sep.push(this.sourceToken);else if(Qe(s.start,"newline"))Object.assign(s,{key:null,sep:[this.sourceToken]});else{let o=Dt(s.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else s.sep?s.value||r?t.items.push({start:n,key:null,sep:[this.sourceToken]}):Qe(s.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):s.sep.push(this.sourceToken):Object.assign(s,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||s.value?(t.items.push({start:n,key:o,sep:[]}),this.onKeyLine=!0):s.sep?this.stack.push(o):(Object.assign(s,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!s.explicitKey&&s.sep&&!Qe(s.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:n});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let s=t.items[t.items.length-1];switch(this.type){case"newline":if(s.value){let i="end"in s.value?s.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else s.start.push(this.sourceToken);return;case"space":case"comment":if(s.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(s.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){Er(r,s.start),r.push(this.sourceToken),t.items.pop();return}}s.start.push(this.sourceToken)}return;case"anchor":case"tag":if(s.value||this.indent<=t.indent)break;s.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;s.value||Qe(s.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):s.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let s=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!s||s.sep?t.items.push({start:[this.sourceToken]}):s.start.push(this.sourceToken);return;case"map-value-ind":!s||s.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):s.sep?s.sep.push(this.sourceToken):Object.assign(s,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!s||s.value?t.items.push({start:[this.sourceToken]}):s.sep?s.sep.push(this.sourceToken):s.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!s||s.value?t.items.push({start:[],key:r,sep:[]}):s.sep?this.stack.push(r):Object.assign(s,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=xr(i),n=Dt(r);Gd(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let s=this.source.indexOf(`
140
- `)+1;for(;s!==0;)this.onNewLine(this.offset+s),s=this.source.indexOf(`
141
- `,s)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let s=xr(t),i=Dt(s);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let s=xr(t),i=Dt(s);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,s){return this.type!=="comment"||this.indent<=s?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Jd.Parser=ea});var Zd=N(Ms=>{"use strict";var Wd=qo(),Lk=Ps(),Os=Ls(),Ak=_n(),Rk=U(),Nk=Qo(),Yd=ta();function zd(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Nk.LineCounter||null,prettyErrors:t}}function Tk(e,t={}){let{lineCounter:s,prettyErrors:i}=zd(t),r=new Yd.Parser(s?.addNewLine),n=new Wd.Composer(t),o=Array.from(n.compose(r.parse(e)));if(i&&s)for(let a of o)a.errors.forEach(Os.prettifyError(e,s)),a.warnings.forEach(Os.prettifyError(e,s));return o.length>0?o:Object.assign([],{empty:!0},n.streamInfo())}function Xd(e,t={}){let{lineCounter:s,prettyErrors:i}=zd(t),r=new Yd.Parser(s?.addNewLine),n=new Wd.Composer(t),o=null;for(let a of n.compose(r.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Os.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&s&&(o.errors.forEach(Os.prettifyError(e,s)),o.warnings.forEach(Os.prettifyError(e,s))),o}function Ok(e,t,s){let i;typeof t=="function"?i=t:s===void 0&&t&&typeof t=="object"&&(s=t);let r=Xd(e,s);if(!r)return null;if(r.warnings.forEach(n=>Ak.warn(r.options.logLevel,n)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},s))}function Mk(e,t,s){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:s===void 0&&t&&(s=t),typeof s=="string"&&(s=s.length),typeof s=="number"){let r=Math.round(s);s=r<1?void 0:r>8?{indent:8}:{indent:r}}if(e===void 0){let{keepUndefined:r}=s??t??{};if(!r)return}return Rk.isDocument(e)&&!i?e.toString(s):new Lk.Document(e,i,s).toString(s)}Ms.parse=Ok;Ms.parseAllDocuments=Tk;Ms.parseDocument=Xd;Ms.stringify=Mk});var ia=N(G=>{"use strict";var Dk=qo(),Fk=Ps(),_k=vo(),sa=Ls(),jk=us(),et=U(),Bk=Ye(),qk=Z(),Uk=Xe(),Vk=Ze(),Kk=Sr(),Gk=Xo(),Hk=Qo(),Jk=ta(),Pr=Zd(),Qd=os();G.Composer=Dk.Composer;G.Document=Fk.Document;G.Schema=_k.Schema;G.YAMLError=sa.YAMLError;G.YAMLParseError=sa.YAMLParseError;G.YAMLWarning=sa.YAMLWarning;G.Alias=jk.Alias;G.isAlias=et.isAlias;G.isCollection=et.isCollection;G.isDocument=et.isDocument;G.isMap=et.isMap;G.isNode=et.isNode;G.isPair=et.isPair;G.isScalar=et.isScalar;G.isSeq=et.isSeq;G.Pair=Bk.Pair;G.Scalar=qk.Scalar;G.YAMLMap=Uk.YAMLMap;G.YAMLSeq=Vk.YAMLSeq;G.CST=Kk;G.Lexer=Gk.Lexer;G.LineCounter=Hk.LineCounter;G.Parser=Jk.Parser;G.parse=Pr.parse;G.parseAllDocuments=Pr.parseAllDocuments;G.parseDocument=Pr.parseDocument;G.stringify=Pr.stringify;G.visit=Qd.visit;G.visitAsync=Qd.visitAsync});import{access as cg,realpath as ug,stat as dg}from"fs/promises";import{constants as fg}from"fs";import{delimiter as pg,resolve as mg,sep as hg}from"path";var gg="asm";function yg(e){if(!e)return[];let t=new Set,s=[];for(let i of e.split(pg)){let r=i.trim();if(!r)continue;let n=r.endsWith(hg)?r.slice(0,-1):r;t.has(n)||(t.add(n),s.push(n))}return s}async function bg(e){try{if(!(await dg(e)).isFile())return!1}catch{return!1}try{return await cg(e,fg.X_OK),!0}catch{return!1}}async function wg(e){try{return await ug(e)}catch{return e}}async function kg(e=process.env.PATH){let t=new Set,s=[];for(let i of yg(e)){let r=mg(i,gg);if(!await bg(r))continue;let n=await wg(r);t.has(n)||(t.add(n),s.push({path:r,realPath:n}))}return s}async function Ii(e=process.env.PATH){let t=await kg(e);if(t.length===0)return{resolved:null,shadowed:[]};let[s,...i]=t;return{resolved:s,shadowed:i}}var tf=Ml(ia(),1);import{readFile as Wk}from"fs/promises";import{join as Yk}from"path";var ef=500;function zk(e){let t=e.split(`
142
- `),s=!1,i=!1;for(let r of t){if(r.trim()==="---")if(s){i=!0;continue}else{s=!0;continue}if(i&&r.trim().length>0)return!0}return!1}function Xk(e){let t=e.split(`
143
- `),s=-1;for(let i=0;i<t.length;i++)if(t[i].trim()==="---")if(s===-1)s=i+1;else return t.slice(s,i).join(`
144
- `);return null}function Zk(e){let t=Xk(e);if(t===null)return null;try{return(0,tf.parse)(t),null}catch(s){return s.message||"invalid YAML"}}async function sf(e){let t=[];(!e.description||e.description.trim()==="")&&t.push({category:"missing-description",message:"Skill has no description in SKILL.md frontmatter"}),(!e.version||e.version==="0.0.0")&&t.push({category:"missing-version",message:"Skill has no version (or default 0.0.0) in SKILL.md frontmatter"});try{let i=e._skillMdContent!==void 0?e._skillMdContent:await Wk(Yk(e.path,"SKILL.md"),"utf-8");zk(i)||t.push({category:"empty-body",message:"SKILL.md contains only frontmatter with no body content"});let r=Zk(i);r&&t.push({category:"invalid-yaml",message:`SKILL.md has invalid YAML frontmatter: ${r}`})}catch{}let s=e.fileCount;return s!==void 0&&s>ef&&t.push({category:"high-file-count",message:`Skill has ${s} files (threshold: ${ef})`}),t}function Qk(e){switch(e){case"dangerous":return 3;case"warning":return 2;case"caution":return 1;default:return 0}}function Cr(e){return{verdict:e.every(t=>t.verdict==="safe")?"safe":e.some(t=>t.verdict==="dangerous")?"dangerous":"warning",findings:e.map(t=>({skill:t.skillName,verdict:t.verdict,verdict_reason:t.verdictReason,total_files:t.totalFiles,total_lines:t.totalLines})),risk_score:e.reduce((t,s)=>t+Qk(s.verdict),0)}}function $(e){console.error(l.red(`Error: ${e}`))}async function Ds(e){await Promise.all(e.map(async t=>{t.warnings=await sf(t)}))}function H(){return new Promise(e=>{let t="",s=!1;function i(){process.stdin.removeListener("data",n),process.stdin.removeListener("end",o),process.stdin.pause(),clearTimeout(a)}function r(c){s||(s=!0,i(),e(c))}function n(c){t+=c,t.includes(`
145
- `)&&r(t.trim())}function o(){r(t.trim())}let a=setTimeout(()=>{r(t.trim())},3e4);process.stdin.setEncoding("utf-8"),process.stdin.on("data",n),process.stdin.on("end",o),process.stdin.resume()})}function Ft(e,t){let s=new Map;for(let r of t){let n=s.get(r.realPath)??[];n.push(r),s.set(r.realPath,n)}let i=new Map;for(let r of e)i.has(r.realPath)||i.set(r.realPath,{realPath:r.realPath,representative:r,siblings:s.get(r.realPath)??[r]});return[...i.values()]}import{readFile as ev,writeFile as tv,mkdir as sv,rename as nf,copyFile as iv,access as rv,realpath as nv}from"node:fs/promises";import{join as of,dirname as ov}from"node:path";function rf(){return{version:1,disabled:{}}}async function Fs(e){let t=e??gn(),s;try{s=await ev(t,"utf-8")}catch(i){if(i?.code==="ENOENT")return L("skill-state: file not found, returning empty state"),rf();throw i}try{let i=JSON.parse(s);if(!i||typeof i!="object"||i.version!==1||typeof i.disabled!="object"||i.disabled===null)throw new Error("invalid schema");return i}catch{let i=t+".bak";L(`skill-state: parse error, backing up to ${i}`);try{await iv(t,i)}catch{}return console.error(`Warning: skill-state.json was corrupted. Backup saved to ${i}. Starting fresh.`),rf()}}async function ra(e,t){let s=t??gn();await sv(ov(s),{recursive:!0}),await tv(s,JSON.stringify(e,null,2)+`
146
- `,"utf-8")}function af(e,t,s,i){let r=e.disabled[t]??={},n=r[s]??={};n[i]=!0}function lf(e,t,s,i){let r=e.disabled[t];if(!r)return;let n=r[s];n&&(delete n[i],Object.keys(n).length===0&&delete r[s],Object.keys(r).length===0&&delete e.disabled[t])}function av(e){return e.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}function lv(e){if(e==="*"||e==="all")return{kind:"all",test:()=>!0};if(e.includes("*")){let t=new RegExp("^"+av(e).replace(/\*/g,".*")+"$");return{kind:"wildcard",test:s=>t.test(s)}}return e.endsWith(":")||e.endsWith("-")?{kind:"prefix",test:t=>t.startsWith(e)}:{kind:"exact",test:t=>t===e}}function _s(e,t){let s=lv(t);return e.filter(i=>s.test(i.name)||s.test(i.dirName))}function cf(e){return of(e,"SKILL.md")}function Lr(e){return of(e,"SKILL.md.disabled")}async function Ir(e){try{return await rv(e),!0}catch{return!1}}async function uf(e){try{return await nv(e)}catch{return e}}async function df(e){let t=await uf(e),s=cf(t),i=Lr(t);return!await Ir(s)&&await Ir(i)?!1:(await nf(s,i),!0)}async function ff(e){let t=await uf(e),s=cf(t),i=Lr(t);return!await Ir(i)&&await Ir(s)?!1:(await nf(i,s),!0)}import{copyFile as cv,mkdir as uv,readFile as dv,writeFile as fv}from"node:fs/promises";import{dirname as pv}from"node:path";function na(){return{version:1,skills:{}}}function mv(e){if(!e||typeof e!="object")return{added:[],removed:[]};let t=e,s=X(Array.isArray(t.removed)?t.removed.filter(n=>typeof n=="string"):[]),i=new Set(s);return{added:X(Array.isArray(t.added)?t.added.filter(n=>typeof n=="string"):[]).filter(n=>!i.has(n)),removed:s}}async function _t(e){let t=e??yn(),s;try{s=await dv(t,"utf-8")}catch(i){if(i?.code==="ENOENT")return na();throw i}try{let i=JSON.parse(s);if(!i||i.version!==1||!i.skills||typeof i.skills!="object"||Array.isArray(i.skills))throw new Error("invalid schema");let r=na();for(let[n,o]of Object.entries(i.skills)){let a=mv(o);(a.added.length>0||a.removed.length>0)&&(r.skills[n]=a)}return r}catch{let i=`${t}.bak`;L(`skill-tags: parse error, backing up to ${i}`);try{await cv(t,i)}catch{}return na()}}async function pf(e,t){let s=t??yn();await uv(pv(s),{recursive:!0}),await fv(s,`${JSON.stringify(e,null,2)}
147
- `,"utf-8")}function oa(e){return e.realPath}function jt(e){let t=e.flatMap(i=>i.split(",")),s=t.filter(i=>Dl(i)===null);return{tags:X(t),invalid:s}}function Bt(e,t){let s=new Set(X(e||[]));return X(t).every(i=>s.has(i))}function js(e,t){let s=new Set(X(t?.removed||[]));return X([...X(e||[]).filter(i=>!s.has(i)),...X(t?.added||[]).filter(i=>!s.has(i))])}function Ar(e,t){for(let s of e)s.tags=js(s.tags,t.skills[oa(s)])}function mf(e,t){let s=e.skills[t];s&&s.added.length===0&&s.removed.length===0&&delete e.skills[t]}function hf(e,t,s,i){let r=new Set(X(s||[])),n=e.skills[t]??={added:[],removed:[]},o=new Set(X(n.added)),a=new Set(X(n.removed));for(let c of X(i))a.delete(c),r.has(c)||o.add(c);return n.added=[...o],n.removed=[...a],mf(e,t),js(s,e.skills[t])}function gf(e,t,s,i){let r=new Set(X(s||[])),n=e.skills[t]??={added:[],removed:[]},o=new Set(X(n.added)),a=new Set(X(n.removed));for(let c of X(i))o.delete(c),r.has(c)&&a.add(c);return n.added=[...o],n.removed=[...a],mf(e,t),js(s,e.skills[t])}var Y={SKILL_NOT_FOUND:"SKILL_NOT_FOUND",AUDIT_FAILED:"AUDIT_FAILED",INSTALL_FAILED:"INSTALL_FAILED",PUBLISH_FAILED:"PUBLISH_FAILED",NETWORK_ERROR:"NETWORK_ERROR",INVALID_ARGUMENT:"INVALID_ARGUMENT",UNKNOWN_ERROR:"UNKNOWN_ERROR"};function he(){let e=console.log,t=console.info,s=(...i)=>process.stderr.write(i.map(String).join(" ")+`
148
- `);return console.log=s,console.info=s,()=>{console.log=e,console.info=t}}function yf(e){return{timestamp:new Date().toISOString(),asm_version:zl,duration_ms:Math.round(performance.now()-e)}}function V(e,t,s){let i={version:1,command:e,status:"ok",data:t,meta:yf(s)},r=process.stdout.isTTY?2:0;return JSON.stringify(i,null,r)}function z(e,t,s,i,r){let n={version:1,command:e,status:"error",error:{code:t,message:s,...r!==void 0?{details:r}:{}},meta:yf(i)},o=process.stdout.isTTY?2:0;return JSON.stringify(n,null,o)}import{readFile as hv,realpath as gv}from"fs/promises";import{existsSync as yv}from"fs";import{join as bv}from"path";function wv(){console.log(`${l.bold("Usage:")} asm disable <target> [options]
3
+ import{a as re}from"./chunk-ESKBKSXS.js";import{a as Lt,b as st,c as ot,d as Te,e as nt,f as Mn,g as Fn,h as jn}from"./chunk-3KGAHUVB.js";import{$ as Sr,A as kn,B as vn,C as Sn,F as yr,G as $n,H as xn,I as Pn,J as Rn,K as En,L as j,N as V,O as Tn,P as kr,Q as Nn,R as On,S as xs,T as Ae,U as rt,V as Dn,W as Ps,X as vr,Y as _n,Z as Un,_ as Bn,a as Ce,aa as Vn,b as H,ba as At,c as Me,ca as Rs,d as Pt,da as Gn,e as fn,ea as $r,f as q,fa as Hn,g as ae,h as ys,ha as qn,i as Qe,ia as Wn,j as Rt,ja as Kn,k as gn,l as J,m as Et,n as It,o as hn,p as et,q as i,r as yn,s as bs,t as Le,u as gr,v as ws,w as ks,x as bn,y as wn,z as hr}from"./chunk-CBDNF2SR.js";import{a as In,b as P,c as br,d as wr,e as Ct,f as Cn,g as vs,h as Ss,i as tt,k as Re,l as Fe,m as Ln,n as $s,q as Q,r as O,s as An}from"./chunk-KWWFXT5F.js";import{d as mn}from"./chunk-RSVWCEZR.js";import{access as vd,realpath as Sd,stat as $d}from"fs/promises";import{constants as xd}from"fs";import{delimiter as Pd,resolve as Rd,sep as Ed}from"path";var Id="asm";function Cd(e){if(!e)return[];let t=new Set,r=[];for(let s of e.split(Pd)){let o=s.trim();if(!o)continue;let n=o.endsWith(Ed)?o.slice(0,-1):o;t.has(n)||(t.add(n),r.push(n))}return r}async function Ld(e){try{if(!(await $d(e)).isFile())return!1}catch{return!1}try{return await vd(e,xd.X_OK),!0}catch{return!1}}async function Ad(e){try{return await Sd(e)}catch{return e}}async function Td(e=process.env.PATH){let t=new Set,r=[];for(let s of Cd(e)){let o=Rd(s,Id);if(!await Ld(o))continue;let n=await Ad(o);t.has(n)||(t.add(n),r.push({path:o,realPath:n}))}return r}async function xr(e=process.env.PATH){let t=await Td(e);if(t.length===0)return{resolved:null,shadowed:[]};let[r,...s]=t;return{resolved:r,shadowed:s}}var zn=mn(fn(),1);import{readFile as Nd}from"fs/promises";import{join as Od}from"path";var Jn=500;function Dd(e){let t=e.split(`
4
+ `),r=!1,s=!1;for(let o of t){if(o.trim()==="---")if(r){s=!0;continue}else{r=!0;continue}if(s&&o.trim().length>0)return!0}return!1}function Md(e){let t=e.split(`
5
+ `),r=-1;for(let s=0;s<t.length;s++)if(t[s].trim()==="---")if(r===-1)r=s+1;else return t.slice(r,s).join(`
6
+ `);return null}function Fd(e){let t=Md(e);if(t===null)return null;try{return(0,zn.parse)(t),null}catch(r){return r.message||"invalid YAML"}}async function Yn(e){let t=[];(!e.description||e.description.trim()==="")&&t.push({category:"missing-description",message:"Skill has no description in SKILL.md frontmatter"}),(!e.version||e.version==="0.0.0")&&t.push({category:"missing-version",message:"Skill has no version (or default 0.0.0) in SKILL.md frontmatter"});try{let s=e._skillMdContent!==void 0?e._skillMdContent:await Nd(Od(e.path,"SKILL.md"),"utf-8");Dd(s)||t.push({category:"empty-body",message:"SKILL.md contains only frontmatter with no body content"});let o=Fd(s);o&&t.push({category:"invalid-yaml",message:`SKILL.md has invalid YAML frontmatter: ${o}`})}catch{}let r=e.fileCount;return r!==void 0&&r>Jn&&t.push({category:"high-file-count",message:`Skill has ${r} files (threshold: ${Jn})`}),t}function jd(e){switch(e){case"dangerous":return 3;case"warning":return 2;case"caution":return 1;default:return 0}}function Pr(e){return{verdict:e.every(t=>t.verdict==="safe")?"safe":e.some(t=>t.verdict==="dangerous")?"dangerous":"warning",findings:e.map(t=>({skill:t.skillName,verdict:t.verdict,verdict_reason:t.verdictReason,total_files:t.totalFiles,total_lines:t.totalLines})),risk_score:e.reduce((t,r)=>t+jd(r.verdict),0)}}function w(e){console.error(i.red(`Error: ${e}`))}async function Tt(e){await Promise.all(e.map(async t=>{t.warnings=await Yn(t)}))}function G(){return new Promise(e=>{let t="",r=!1;function s(){process.stdin.removeListener("data",n),process.stdin.removeListener("end",a),process.stdin.pause(),clearTimeout(l)}function o(c){r||(r=!0,s(),e(c))}function n(c){t+=c,t.includes(`
7
+ `)&&o(t.trim())}function a(){o(t.trim())}let l=setTimeout(()=>{o(t.trim())},3e4);process.stdin.setEncoding("utf-8"),process.stdin.on("data",n),process.stdin.on("end",a),process.stdin.resume()})}function it(e,t){let r=new Map;for(let o of t){let n=r.get(o.realPath)??[];n.push(o),r.set(o.realPath,n)}let s=new Map;for(let o of e)s.has(o.realPath)||s.set(o.realPath,{realPath:o.realPath,representative:o,siblings:r.get(o.realPath)??[o]});return[...s.values()]}import{readFile as _d,writeFile as Ud,mkdir as Bd,rename as Xn,copyFile as Vd,access as Gd,realpath as Hd}from"node:fs/promises";import{join as Qn,dirname as qd}from"node:path";function Zn(){return{version:1,disabled:{}}}async function Nt(e){let t=e??vs(),r;try{r=await _d(t,"utf-8")}catch(s){if(s?.code==="ENOENT")return P("skill-state: file not found, returning empty state"),Zn();throw s}try{let s=JSON.parse(r);if(!s||typeof s!="object"||s.version!==1||typeof s.disabled!="object"||s.disabled===null)throw new Error("invalid schema");return s}catch{let s=t+".bak";P(`skill-state: parse error, backing up to ${s}`);try{await Vd(t,s)}catch{}return console.error(`Warning: skill-state.json was corrupted. Backup saved to ${s}. Starting fresh.`),Zn()}}async function Es(e,t){let r=t??vs();await Bd(qd(r),{recursive:!0}),await Ud(r,JSON.stringify(e,null,2)+`
8
+ `,"utf-8")}function ei(e,t,r,s){let o=e.disabled[t]??={},n=o[r]??={};n[s]=!0}function ti(e,t,r,s){let o=e.disabled[t];if(!o)return;let n=o[r];n&&(delete n[s],Object.keys(n).length===0&&delete o[r],Object.keys(o).length===0&&delete e.disabled[t])}function Wd(e){return e.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}function Kd(e){if(e==="*"||e==="all")return{kind:"all",test:()=>!0};if(e.includes("*")){let t=new RegExp("^"+Wd(e).replace(/\*/g,".*")+"$");return{kind:"wildcard",test:r=>t.test(r)}}return e.endsWith(":")||e.endsWith("-")?{kind:"prefix",test:t=>t.startsWith(e)}:{kind:"exact",test:t=>t===e}}function Ot(e,t){let r=Kd(t);return e.filter(s=>r.test(s.name)||r.test(s.dirName))}function ri(e){return Qn(e,"SKILL.md")}function Er(e){return Qn(e,"SKILL.md.disabled")}async function Rr(e){try{return await Gd(e),!0}catch{return!1}}async function si(e){try{return await Hd(e)}catch{return e}}async function oi(e){let t=await si(e),r=ri(t),s=Er(t);return!await Rr(r)&&await Rr(s)?!1:(await Xn(r,s),!0)}async function ni(e){let t=await si(e),r=ri(t),s=Er(t);return!await Rr(s)&&await Rr(r)?!1:(await Xn(s,r),!0)}import{copyFile as Jd,mkdir as zd,readFile as Yd,writeFile as Zd}from"node:fs/promises";import{dirname as Xd}from"node:path";function Is(){return{version:1,skills:{}}}function Qd(e){if(!e||typeof e!="object")return{added:[],removed:[]};let t=e,r=J(Array.isArray(t.removed)?t.removed.filter(n=>typeof n=="string"):[]),s=new Set(r);return{added:J(Array.isArray(t.added)?t.added.filter(n=>typeof n=="string"):[]).filter(n=>!s.has(n)),removed:r}}async function at(e){let t=e??Ss(),r;try{r=await Yd(t,"utf-8")}catch(s){if(s?.code==="ENOENT")return Is();throw s}try{let s=JSON.parse(r);if(!s||s.version!==1||!s.skills||typeof s.skills!="object"||Array.isArray(s.skills))throw new Error("invalid schema");let o=Is();for(let[n,a]of Object.entries(s.skills)){let l=Qd(a);(l.added.length>0||l.removed.length>0)&&(o.skills[n]=l)}return o}catch{let s=`${t}.bak`;P(`skill-tags: parse error, backing up to ${s}`);try{await Jd(t,s)}catch{}return Is()}}async function ii(e,t){let r=t??Ss();await zd(Xd(r),{recursive:!0}),await Zd(r,`${JSON.stringify(e,null,2)}
9
+ `,"utf-8")}function Cs(e){return e.realPath}function lt(e){let t=e.flatMap(s=>s.split(",")),r=t.filter(s=>gn(s)===null);return{tags:J(t),invalid:r}}function ct(e,t){let r=new Set(J(e||[]));return J(t).every(s=>r.has(s))}function Dt(e,t){let r=new Set(J(t?.removed||[]));return J([...J(e||[]).filter(s=>!r.has(s)),...J(t?.added||[]).filter(s=>!r.has(s))])}function Ir(e,t){for(let r of e)r.tags=Dt(r.tags,t.skills[Cs(r)])}function ai(e,t){let r=e.skills[t];r&&r.added.length===0&&r.removed.length===0&&delete e.skills[t]}function li(e,t,r,s){let o=new Set(J(r||[])),n=e.skills[t]??={added:[],removed:[]},a=new Set(J(n.added)),l=new Set(J(n.removed));for(let c of J(s))l.delete(c),o.has(c)||a.add(c);return n.added=[...a],n.removed=[...l],ai(e,t),Dt(r,e.skills[t])}function ci(e,t,r,s){let o=new Set(J(r||[])),n=e.skills[t]??={added:[],removed:[]},a=new Set(J(n.added)),l=new Set(J(n.removed));for(let c of J(s))a.delete(c),o.has(c)&&l.add(c);return n.added=[...a],n.removed=[...l],ai(e,t),Dt(r,e.skills[t])}var W={SKILL_NOT_FOUND:"SKILL_NOT_FOUND",AUDIT_FAILED:"AUDIT_FAILED",INSTALL_FAILED:"INSTALL_FAILED",PUBLISH_FAILED:"PUBLISH_FAILED",NETWORK_ERROR:"NETWORK_ERROR",INVALID_ARGUMENT:"INVALID_ARGUMENT",UNKNOWN_ERROR:"UNKNOWN_ERROR"};function le(){let e=console.log,t=console.info,r=(...s)=>process.stderr.write(s.map(String).join(" ")+`
10
+ `);return console.log=r,console.info=r,()=>{console.log=e,console.info=t}}function di(e){return{timestamp:new Date().toISOString(),asm_version:On,duration_ms:Math.round(performance.now()-e)}}function B(e,t,r){let s={version:1,command:e,status:"ok",data:t,meta:di(r)},o=process.stdout.isTTY?2:0;return JSON.stringify(s,null,o)}function K(e,t,r,s,o){let n={version:1,command:e,status:"error",error:{code:t,message:r,...o!==void 0?{details:o}:{}},meta:di(s)},a=process.stdout.isTTY?2:0;return JSON.stringify(n,null,a)}import{readFile as eu,realpath as tu}from"fs/promises";import{existsSync as ru}from"fs";import{join as su}from"path";function ou(){console.log(`${i.bold("Usage:")} asm disable <target> [options]
149
11
  asm disable --all [options]
150
12
 
151
13
  Disable skills without uninstalling them. Disabling renames a skill's
152
- ${l.dim("SKILL.md")} to ${l.dim("SKILL.md.disabled")} so neither asm nor your agent sees it.
153
- The directory stays intact; ${l.bold("asm enable")} reverses it.
14
+ ${i.dim("SKILL.md")} to ${i.dim("SKILL.md.disabled")} so neither asm nor your agent sees it.
15
+ The directory stays intact; ${i.bold("asm enable")} reverses it.
154
16
 
155
- ${l.dim("Note: skills installed to several tools at once share one SKILL.md")}
156
- ${l.dim("(siblings are symlinks), so disabling one affects all of them \u2014 asm warns")}
157
- ${l.dim("and records every sibling. Separately-installed copies stay independent.")}
17
+ ${i.dim("Note: skills installed to several tools at once share one SKILL.md")}
18
+ ${i.dim("(siblings are symlinks), so disabling one affects all of them \u2014 asm warns")}
19
+ ${i.dim("and records every sibling. Separately-installed copies stay independent.")}
158
20
 
159
- ${l.bold("Targets:")}
21
+ ${i.bold("Targets:")}
160
22
  <name> Exact skill name or directory name
161
- '<glob>*' Glob match (${l.dim("* matches any characters")})
162
- <prefix>: | <prefix>- Prefix match (e.g. ${l.dim("openspec:")}, ${l.dim("asc-")})
23
+ '<glob>*' Glob match (${i.dim("* matches any characters")})
24
+ <prefix>: | <prefix>- Prefix match (e.g. ${i.dim("openspec:")}, ${i.dim("asc-")})
163
25
 
164
- ${l.bold("Options:")}
26
+ ${i.bold("Options:")}
165
27
  --all, -a Disable every matching skill
166
28
  -p, --tool <name> Limit to one tool/provider (e.g. claude, codex)
167
29
  -s, --scope <s> Filter: global, local, project, or both (default: both)
@@ -171,28 +33,28 @@ ${l.bold("Options:")}
171
33
  --no-color Disable ANSI colors
172
34
  -V, --verbose Show debug output
173
35
 
174
- ${l.bold("Examples:")}
175
- asm disable code-review ${l.dim("# one skill")}
176
- asm disable 'workflow*' ${l.dim("# glob")}
177
- asm disable '*-review' ${l.dim("# glob suffix")}
178
- asm disable openspec: ${l.dim("# prefix (colon)")}
179
- asm disable asc- ${l.dim("# prefix (hyphen)")}
180
- asm disable --all ${l.dim("# everything")}
181
- asm disable code-review --tool claude --scope local`)}function kv(){console.log(`${l.bold("Usage:")} asm enable <target> [options]
36
+ ${i.bold("Examples:")}
37
+ asm disable code-review ${i.dim("# one skill")}
38
+ asm disable 'workflow*' ${i.dim("# glob")}
39
+ asm disable '*-review' ${i.dim("# glob suffix")}
40
+ asm disable openspec: ${i.dim("# prefix (colon)")}
41
+ asm disable asc- ${i.dim("# prefix (hyphen)")}
42
+ asm disable --all ${i.dim("# everything")}
43
+ asm disable code-review --tool claude --scope local`)}function nu(){console.log(`${i.bold("Usage:")} asm enable <target> [options]
182
44
  asm enable --all [options]
183
45
 
184
- Re-enable skills previously disabled with ${l.bold("asm disable")}. Enabling renames
185
- ${l.dim("SKILL.md.disabled")} back to ${l.dim("SKILL.md")} so asm and your agent see it again.
46
+ Re-enable skills previously disabled with ${i.bold("asm disable")}. Enabling renames
47
+ ${i.dim("SKILL.md.disabled")} back to ${i.dim("SKILL.md")} so asm and your agent see it again.
186
48
 
187
- ${l.dim("Note: a skill shared across tools via symlinks re-enables for every tool")}
188
- ${l.dim("at once (one shared SKILL.md); asm warns and clears state for all siblings.")}
49
+ ${i.dim("Note: a skill shared across tools via symlinks re-enables for every tool")}
50
+ ${i.dim("at once (one shared SKILL.md); asm warns and clears state for all siblings.")}
189
51
 
190
- ${l.bold("Targets:")}
52
+ ${i.bold("Targets:")}
191
53
  <name> Exact skill name or directory name
192
- '<glob>*' Glob match (${l.dim("* matches any characters")})
193
- <prefix>: | <prefix>- Prefix match (e.g. ${l.dim("openspec:")}, ${l.dim("asc-")})
54
+ '<glob>*' Glob match (${i.dim("* matches any characters")})
55
+ <prefix>: | <prefix>- Prefix match (e.g. ${i.dim("openspec:")}, ${i.dim("asc-")})
194
56
 
195
- ${l.bold("Options:")}
57
+ ${i.bold("Options:")}
196
58
  --all, -a Enable every matching disabled skill
197
59
  -p, --tool <name> Limit to one tool/provider (e.g. claude, codex)
198
60
  -s, --scope <s> Filter: global, local, project, or both (default: both)
@@ -202,20 +64,20 @@ ${l.bold("Options:")}
202
64
  --no-color Disable ANSI colors
203
65
  -V, --verbose Show debug output
204
66
 
205
- ${l.bold("Examples:")}
67
+ ${i.bold("Examples:")}
206
68
  asm enable code-review
207
69
  asm enable '*-review'
208
70
  asm enable openspec:
209
- asm enable --all`)}async function aa(e,t,s,i,r){let n=new Map(e.providers.map(a=>[a.name,a])),o=[];for(let[a,c]of Object.entries(t.disabled))for(let[u,f]of Object.entries(c)){if(i&&u!==i)continue;let d=n.get(u);if(d)for(let p of["global","project"]){if(!f[p]||s==="global"&&p!=="global"||s==="project"&&p!=="project"||r?.has(`${a}||${u}||${p}`))continue;let m=p==="global"?d.global:d.project;if(!m)continue;let g=ie(m),h=bv(g,a),y=Lr(h);if(!yv(y))continue;let b={};try{b=W(await hv(y,"utf-8"))}catch{}let k=h;try{k=await gv(h)}catch{}o.push({name:b.name||a,version:b["metadata.version"]||b.version||"0.0.0",description:(b.description||"").replace(/\s*\n\s*/g," ").trim(),creator:b["metadata.creator"]||"",license:(b.license||"").trim(),compatibility:(b.compatibility||"").trim(),allowedTools:[],tags:ts(b),modelInvocable:ss(b),userInvocable:is(b),dirName:a,path:h,originalPath:h,location:`${p}-${u}`,scope:p,provider:u,providerLabel:d.label,isSymlink:!1,symlinkTarget:null,realPath:k,disabled:!0})}}return o}function bf(e,t){if(e.flags.json)console.log(JSON.stringify(t,null,2));else if(e.flags.machine)for(let s of t)console.log([s.name,s.provider,s.scope,s.action].join(" "))}async function wf(e){if(e.flags.help){wv();return}let t=e.subcommand;if(!t&&!e.flags.all){$("Missing target. Provide a skill name/pattern or use --all."),process.exitCode=2;return}if(t&&e.flags.all){$("Provide either a target or --all, not both."),process.exitCode=2;return}let s=await j(),i=e.flags.provider,r=(await K(s,e.flags.scope)).filter(d=>d.provider!=="plugin"&&d.provider!=="codex-plugin"),n=i?r.filter(d=>d.provider===i):r,o=e.flags.all?n:_s(n,t);if(o.length===0){let d=t?` for '${t}'`:"";console.log(l.dim(`No matching active skills${d}.`));return}let a=Ft(o,r),c=new Set(o.map(d=>`${d.realPath}||${d.provider}||${d.scope}`));if(!e.flags.json&&!e.flags.machine){let d=a.reduce((p,m)=>p+m.siblings.length,0);console.log(l.bold(`Will disable ${d} skill instance(s):`));for(let p of a){for(let m of p.siblings){let g=c.has(`${m.realPath}||${m.provider}||${m.scope}`)?"":l.yellow(" (shared via symlink)");console.log(` ${l.dim("\u2022")} ${m.name} (${m.provider}, ${m.scope})${g}`)}p.siblings.length>1&&console.log(l.yellow(` \u26A0 ${p.representative.name} shares one SKILL.md across ${p.siblings.length} tools \u2014 disabling affects all of them.`))}if(!e.flags.yes&&process.stdin.isTTY){process.stdout.write(`
210
- ${l.bold("Proceed?")} [y/N] `);let p=await H();if(p.toLowerCase()!=="y"&&p.toLowerCase()!=="yes"){console.log("Aborted.");return}}}let u=await Fs(),f=[];try{for(let d of a){await df(d.representative.path);for(let p of d.siblings)af(u,p.dirName,p.provider,p.scope),f.push({name:p.name,provider:p.provider,scope:p.scope,action:"disabled"}),!e.flags.json&&!e.flags.machine&&console.log(`${l.green("\u2713")} disabled ${p.name} (${p.provider}, ${p.scope})`)}}finally{await ra(u)}bf(e,f)}async function kf(e){if(e.flags.help){kv();return}let t=e.subcommand;if(!t&&!e.flags.all){$("Missing target. Provide a skill name/pattern or use --all."),process.exitCode=2;return}if(t&&e.flags.all){$("Provide either a target or --all, not both."),process.exitCode=2;return}let s=await j(),i=e.flags.provider,r=await Fs(),n=await aa(s,r,e.flags.scope),o=i?n.filter(d=>d.provider===i):n,a=e.flags.all?o:_s(o,t);if(a.length===0){let d=t?` for '${t}'`:"";console.log(l.dim(`No matching disabled skills${d}.`));return}let c=Ft(a,n),u=new Set(a.map(d=>`${d.realPath}||${d.provider}||${d.scope}`));if(!e.flags.json&&!e.flags.machine){let d=c.reduce((p,m)=>p+m.siblings.length,0);console.log(l.bold(`Will enable ${d} skill instance(s):`));for(let p of c){for(let m of p.siblings){let g=u.has(`${m.realPath}||${m.provider}||${m.scope}`)?"":l.yellow(" (shared via symlink)");console.log(` ${l.dim("\u2022")} ${m.name} (${m.provider}, ${m.scope})${g}`)}p.siblings.length>1&&console.log(l.yellow(` \u26A0 ${p.representative.name} shares one SKILL.md across ${p.siblings.length} tools \u2014 enabling affects all of them.`))}if(!e.flags.yes&&process.stdin.isTTY){process.stdout.write(`
211
- ${l.bold("Proceed?")} [y/N] `);let p=await H();if(p.toLowerCase()!=="y"&&p.toLowerCase()!=="yes"){console.log("Aborted.");return}}}let f=[];try{for(let d of c){await ff(d.representative.path);for(let p of d.siblings)lf(r,p.dirName,p.provider,p.scope),f.push({name:p.name,provider:p.provider,scope:p.scope,action:"enabled"}),!e.flags.json&&!e.flags.machine&&console.log(`${l.green("\u2713")} enabled ${p.name} (${p.provider}, ${p.scope})`)}}finally{await ra(r)}bf(e,f)}function vv(){console.log(`${l.bold("Usage:")} asm list [options]
71
+ asm enable --all`)}async function Ls(e,t,r,s,o){let n=new Map(e.providers.map(l=>[l.name,l])),a=[];for(let[l,c]of Object.entries(t.disabled))for(let[d,u]of Object.entries(c)){if(s&&d!==s)continue;let p=n.get(d);if(p)for(let f of["global","project"]){if(!u[f]||r==="global"&&f!=="global"||r==="project"&&f!=="project"||o?.has(`${l}||${d}||${f}`))continue;let m=f==="global"?p.global:p.project;if(!m)continue;let g=Q(m),h=su(g,l),y=Er(h);if(!ru(y))continue;let b={};try{b=q(await eu(y,"utf-8"))}catch{}let $=h;try{$=await tu(h)}catch{}a.push({name:b.name||l,version:b["metadata.version"]||b.version||"0.0.0",description:(b.description||"").replace(/\s*\n\s*/g," ").trim(),creator:b["metadata.creator"]||"",license:(b.license||"").trim(),compatibility:(b.compatibility||"").trim(),allowedTools:[],tags:Rt(b),modelInvocable:Et(b),userInvocable:It(b),dirName:l,path:h,originalPath:h,location:`${f}-${d}`,scope:f,provider:d,providerLabel:p.label,isSymlink:!1,symlinkTarget:null,realPath:$,disabled:!0})}}return a}function ui(e,t){if(e.flags.json)console.log(JSON.stringify(t,null,2));else if(e.flags.machine)for(let r of t)console.log([r.name,r.provider,r.scope,r.action].join(" "))}async function pi(e){if(e.flags.help){ou();return}let t=e.subcommand;if(!t&&!e.flags.all){w("Missing target. Provide a skill name/pattern or use --all."),process.exitCode=2;return}if(t&&e.flags.all){w("Provide either a target or --all, not both."),process.exitCode=2;return}let r=await O(),s=e.flags.provider,o=(await V(r,e.flags.scope)).filter(p=>p.provider!=="plugin"&&p.provider!=="codex-plugin"),n=s?o.filter(p=>p.provider===s):o,a=e.flags.all?n:Ot(n,t);if(a.length===0){let p=t?` for '${t}'`:"";console.log(i.dim(`No matching active skills${p}.`));return}let l=it(a,o),c=new Set(a.map(p=>`${p.realPath}||${p.provider}||${p.scope}`));if(!e.flags.json&&!e.flags.machine){let p=l.reduce((f,m)=>f+m.siblings.length,0);console.log(i.bold(`Will disable ${p} skill instance(s):`));for(let f of l){for(let m of f.siblings){let g=c.has(`${m.realPath}||${m.provider}||${m.scope}`)?"":i.yellow(" (shared via symlink)");console.log(` ${i.dim("\u2022")} ${m.name} (${m.provider}, ${m.scope})${g}`)}f.siblings.length>1&&console.log(i.yellow(` \u26A0 ${f.representative.name} shares one SKILL.md across ${f.siblings.length} tools \u2014 disabling affects all of them.`))}if(!e.flags.yes&&process.stdin.isTTY){process.stdout.write(`
72
+ ${i.bold("Proceed?")} [y/N] `);let f=await G();if(f.toLowerCase()!=="y"&&f.toLowerCase()!=="yes"){console.log("Aborted.");return}}}let d=await Nt(),u=[];try{for(let p of l){await oi(p.representative.path);for(let f of p.siblings)ei(d,f.dirName,f.provider,f.scope),u.push({name:f.name,provider:f.provider,scope:f.scope,action:"disabled"}),!e.flags.json&&!e.flags.machine&&console.log(`${i.green("\u2713")} disabled ${f.name} (${f.provider}, ${f.scope})`)}}finally{await Es(d)}ui(e,u)}async function mi(e){if(e.flags.help){nu();return}let t=e.subcommand;if(!t&&!e.flags.all){w("Missing target. Provide a skill name/pattern or use --all."),process.exitCode=2;return}if(t&&e.flags.all){w("Provide either a target or --all, not both."),process.exitCode=2;return}let r=await O(),s=e.flags.provider,o=await Nt(),n=await Ls(r,o,e.flags.scope),a=s?n.filter(p=>p.provider===s):n,l=e.flags.all?a:Ot(a,t);if(l.length===0){let p=t?` for '${t}'`:"";console.log(i.dim(`No matching disabled skills${p}.`));return}let c=it(l,n),d=new Set(l.map(p=>`${p.realPath}||${p.provider}||${p.scope}`));if(!e.flags.json&&!e.flags.machine){let p=c.reduce((f,m)=>f+m.siblings.length,0);console.log(i.bold(`Will enable ${p} skill instance(s):`));for(let f of c){for(let m of f.siblings){let g=d.has(`${m.realPath}||${m.provider}||${m.scope}`)?"":i.yellow(" (shared via symlink)");console.log(` ${i.dim("\u2022")} ${m.name} (${m.provider}, ${m.scope})${g}`)}f.siblings.length>1&&console.log(i.yellow(` \u26A0 ${f.representative.name} shares one SKILL.md across ${f.siblings.length} tools \u2014 enabling affects all of them.`))}if(!e.flags.yes&&process.stdin.isTTY){process.stdout.write(`
73
+ ${i.bold("Proceed?")} [y/N] `);let f=await G();if(f.toLowerCase()!=="y"&&f.toLowerCase()!=="yes"){console.log("Aborted.");return}}}let u=[];try{for(let p of c){await ni(p.representative.path);for(let f of p.siblings)ti(o,f.dirName,f.provider,f.scope),u.push({name:f.name,provider:f.provider,scope:f.scope,action:"enabled"}),!e.flags.json&&!e.flags.machine&&console.log(`${i.green("\u2713")} enabled ${f.name} (${f.provider}, ${f.scope})`)}}finally{await Es(o)}ui(e,u)}function iu(){console.log(`${i.bold("Usage:")} asm list [options]
212
74
 
213
75
  List all discovered skills. By default, skills installed across multiple
214
76
  tools are grouped into a single row with tool badges. When more than
215
- ${mn} skills are present, a compact summary is
77
+ ${ws} skills are present, a compact summary is
216
78
  automatically prepended above the table.
217
79
 
218
- ${l.bold("Options:")}
80
+ ${i.bold("Options:")}
219
81
  --sort <field> Sort by: name, version, or location (default: name)
220
82
  -s, --scope <s> Filter: global, project, or both (default: both)
221
83
  -p, --tool <p> Filter by tool (claude, codex, openclaw, agents)
@@ -232,28 +94,28 @@ ${l.bold("Options:")}
232
94
  --no-color Disable ANSI colors
233
95
  -V, --verbose Show debug output
234
96
 
235
- ${l.bold("Examples:")}
236
- asm list ${l.dim("List all skills (grouped)")}
237
- asm list --flat ${l.dim("One row per tool instance")}
238
- asm list --compact ${l.dim("One line per skill (dense)")}
239
- asm list --summary ${l.dim("Counts by tool/scope/effort only")}
240
- asm list --group-by tool ${l.dim("Group rows under tool headers")}
241
- asm list --group-by scope ${l.dim("Group rows under scope headers")}
242
- asm list --group-by effort ${l.dim("Group rows under effort headers")}
243
- asm list --limit 20 ${l.dim("Show first 20 rows only")}
244
- asm list -p claude ${l.dim("Only Claude Code skills")}
245
- asm list -s project ${l.dim("Only project-scoped skills")}
246
- asm list --tag cli --tag testing ${l.dim("Require both tags")}
247
- asm list --sort version ${l.dim("Sort by version")}
248
- asm list --json ${l.dim("Output as JSON")}
249
- asm list --machine ${l.dim("Machine-readable v1 envelope output")}`)}async function vf(e){if(e.flags.help){vv();return}let t=jt(e.flags.tagFilters);if(t.invalid.length>0){$(`Invalid tag value(s): ${t.invalid.map(f=>JSON.stringify(f)).join(", ")}.`),process.exitCode=2;return}let s=performance.now(),i=await j(),r=await K(i,e.flags.scope),n=await Fs(),o=new Set(r.map(f=>`${f.dirName}||${f.provider}||${f.scope}`)),a=await aa(i,n,e.flags.scope,e.flags.provider,o);r=[...r,...a];let c=await _t();Ar(r,c),t.tags.length>0&&(r=r.filter(f=>Bt(f.tags,t.tags))),e.flags.provider&&e.command==="list"&&(r=r.filter(f=>f.provider===e.flags.provider)),(e.flags.modelInvocable||e.flags.userInvocable)&&(r=r.filter(f=>$t(f,{modelInvocable:e.flags.modelInvocable,userInvocable:e.flags.userInvocable}))),await Ds(r);let u=Si(r,e.flags.sort);if(e.flags.machine){let f=u.map(d=>({name:d.name,version:d.version,description:d.description,scope:d.scope,provider:d.provider,path:d.path,tags:d.tags||[]}));console.log(V("list",f,s));return}if(e.flags.json)console.log(q(u));else if(e.flags.flat){let f=yi(u),d=u.filter(p=>p.warnings&&p.warnings.length>0);d.length>0&&(f+=`
250
- ${l.yellow(`${d.length} skill${d.length===1?"":"s"} with warnings -- use --json for details`)}`),console.log(f)}else if(e.flags.summary)console.log(hn(u));else if(e.flags.groupBy){let{skills:f,hint:d}=bi(u,e.flags.limit);console.log(Bl(f,e.flags.groupBy)),d&&console.log(d)}else if(e.flags.compact){let{skills:f,hint:d}=bi(u,e.flags.limit);console.log(jl(f)),d&&console.log(d)}else{let f=[];u.length>mn&&(f.push(hn(u,{showHint:!1})),f.push(""));let{skills:d,hint:p}=bi(u,e.flags.limit);f.push(ql(d)),p&&f.push(p),console.log(f.join(`
251
- `))}}import{readdir as Pf,readFile as Cf}from"fs/promises";import{join as If}from"path";var Bs=null,Rr,Lf=0;function ge(e){let t=new Set,s=e.toLowerCase().split(/[\s\-_.,;:()[\]{}"']+/);for(let i of s)i.length>=2&&t.add(i);return t}var Sv=10,$v=5,xv=3,Ev=1;function Pv(e,t){let s=ge(e),i=ge(t.name),r=ge(t.description),n=0;for(let o of s)i.has(o)&&(n+=Sv),r.has(o)&&(n+=xv),t.name.toLowerCase().includes(o)&&(n+=$v),t.description.toLowerCase().includes(o)&&(n+=Ev);return n}async function Sf(e){let t=new Map,s;try{s=await Pf(e)}catch{return t}for(let i of s){if(!i.endsWith(".json"))continue;let r=If(e,i);try{Lf++;let n=await Cf(r,"utf-8"),o=JSON.parse(n);for(let a of o.skills){let c=a;(!("license"in c)||c.license===void 0)&&(c.license=""),(!("creator"in c)||c.creator===void 0)&&(c.creator=""),(!("compatibility"in c)||c.compatibility===void 0)&&(c.compatibility=""),(!("allowedTools"in c)||c.allowedTools===void 0)&&(c.allowedTools=[]),(!("verified"in c)||c.verified===void 0)&&(c.verified=!1),c.tags=Array.isArray(c.tags)?X(c.tags.filter(u=>typeof u=="string")):[]}t.set(`${o.owner}/${o.repo}`,o)}catch{}}return t}async function Oe(){if(Bs!==null)return Bs;let e=await Sf(bn()),t=await Sf(xt()),s=new Map(e);for(let[i,r]of t)s.set(i,r);return Bs=Array.from(s.values()),Rr=Bs.reduce((i,r)=>i+r.skillCount,0),Bs}async function Cv(e){try{Lf++;let s=(await Cf(e,"utf-8")).match(/"skillCount"\s*:\s*(\d+)/);return s?Number(s[1]):null}catch{return null}}async function $f(e){let t=0,s;try{s=await Pf(e)}catch{return t}for(let i of s){if(!i.endsWith(".json"))continue;let r=await Cv(If(e,i));r!==null&&(t+=r)}return t}async function Af(){if(Rr!==void 0)return Rr;let e=await $f(bn()),t=await $f(xt()),s=e+t;return Rr=s,s}var Iv=["license","creator","version"];function xf(e){return Iv.includes(e)}function Ef(e,t){return e[t]||""}function Lv(e,t){if(!$t(e,t))return!1;if(t.has){for(let s of t.has)if(xf(s)&&!Ef(e,s))return!1}if(t.missing){for(let s of t.missing)if(xf(s)&&Ef(e,s))return!1}if(t.tags&&t.tags.length>0){let s=X(t.tags);if(s.length===0||!Bt(e.tags,s))return!1}return!0}function Rf(e){let t=[];return e.license||t.push("license"),e.creator||t.push("creator"),(!e.version||e.version==="0.0.0")&&t.push("version"),t}async function qs(e,t=20,s){let i=await Oe(),r=[],n=!e&&s;for(let o of i)for(let a of o.skills){if(s&&!Lv(a,s))continue;let c=n?1:Pv(e,a);c>0&&r.push({skill:a,repo:{owner:o.owner,repo:o.repo},score:c})}return r.sort((o,a)=>a.score-o.score),r.slice(0,t)}async function la(){let e=await Oe(),t=[];for(let s of e)for(let i of s.skills)t.push({skill:i,repo:{owner:s.owner,repo:s.repo}});return t}async function Nf(e,t){let s=e.trim().toLowerCase();if(!s)return{status:"none"};let r=(t??await la()).filter(a=>a.skill.name.toLowerCase()===s);if(r.length===0)return{status:"none"};let n=new Set,o=[];for(let a of r){let c=`${a.repo.owner}/${a.repo.repo}:${a.skill.relPath}`;n.has(c)||(n.add(c),o.push(a))}return o.length===1?{status:"found",match:o[0]}:{status:"ambiguous",matches:o}}function Av(){console.log(`${l.bold("Usage:")} asm search <query> [options]
97
+ ${i.bold("Examples:")}
98
+ asm list ${i.dim("List all skills (grouped)")}
99
+ asm list --flat ${i.dim("One row per tool instance")}
100
+ asm list --compact ${i.dim("One line per skill (dense)")}
101
+ asm list --summary ${i.dim("Counts by tool/scope/effort only")}
102
+ asm list --group-by tool ${i.dim("Group rows under tool headers")}
103
+ asm list --group-by scope ${i.dim("Group rows under scope headers")}
104
+ asm list --group-by effort ${i.dim("Group rows under effort headers")}
105
+ asm list --limit 20 ${i.dim("Show first 20 rows only")}
106
+ asm list -p claude ${i.dim("Only Claude Code skills")}
107
+ asm list -s project ${i.dim("Only project-scoped skills")}
108
+ asm list --tag cli --tag testing ${i.dim("Require both tags")}
109
+ asm list --sort version ${i.dim("Sort by version")}
110
+ asm list --json ${i.dim("Output as JSON")}
111
+ asm list --machine ${i.dim("Machine-readable v1 envelope output")}`)}async function fi(e){if(e.flags.help){iu();return}let t=lt(e.flags.tagFilters);if(t.invalid.length>0){w(`Invalid tag value(s): ${t.invalid.map(u=>JSON.stringify(u)).join(", ")}.`),process.exitCode=2;return}let r=performance.now(),s=await O(),o=await V(s,e.flags.scope),n=await Nt(),a=new Set(o.map(u=>`${u.dirName}||${u.provider}||${u.scope}`)),l=await Ls(s,n,e.flags.scope,e.flags.provider,a);o=[...o,...l];let c=await at();Ir(o,c),t.tags.length>0&&(o=o.filter(u=>ct(u.tags,t.tags))),e.flags.provider&&e.command==="list"&&(o=o.filter(u=>u.provider===e.flags.provider)),(e.flags.modelInvocable||e.flags.userInvocable)&&(o=o.filter(u=>et(u,{modelInvocable:e.flags.modelInvocable,userInvocable:e.flags.userInvocable}))),await Tt(o);let d=kr(o,e.flags.sort);if(e.flags.machine){let u=d.map(p=>({name:p.name,version:p.version,description:p.description,scope:p.scope,provider:p.provider,path:p.path,tags:p.tags||[]}));console.log(B("list",u,r));return}if(e.flags.json)console.log(j(d));else if(e.flags.flat){let u=gr(d),p=d.filter(f=>f.warnings&&f.warnings.length>0);p.length>0&&(u+=`
112
+ ${i.yellow(`${p.length} skill${p.length===1?"":"s"} with warnings -- use --json for details`)}`),console.log(u)}else if(e.flags.summary)console.log(ks(d));else if(e.flags.groupBy){let{skills:u,hint:p}=hr(d,e.flags.limit);console.log(wn(u,e.flags.groupBy)),p&&console.log(p)}else if(e.flags.compact){let{skills:u,hint:p}=hr(d,e.flags.limit);console.log(bn(u)),p&&console.log(p)}else{let u=[];d.length>ws&&(u.push(ks(d,{showHint:!1})),u.push(""));let{skills:p,hint:f}=hr(d,e.flags.limit);u.push(kn(p)),f&&u.push(f),console.log(u.join(`
113
+ `))}}import{readdir as wi,readFile as ki}from"fs/promises";import{join as vi}from"path";var Mt=null,Cr,Si=0;function ce(e){let t=new Set,r=e.toLowerCase().split(/[\s\-_.,;:()[\]{}"']+/);for(let s of r)s.length>=2&&t.add(s);return t}var au=10,lu=5,cu=3,du=1;function uu(e,t){let r=ce(e),s=ce(t.name),o=ce(t.description),n=0;for(let a of r)s.has(a)&&(n+=au),o.has(a)&&(n+=cu),t.name.toLowerCase().includes(a)&&(n+=lu),t.description.toLowerCase().includes(a)&&(n+=du);return n}async function gi(e){let t=new Map,r;try{r=await wi(e)}catch{return t}for(let s of r){if(!s.endsWith(".json"))continue;let o=vi(e,s);try{Si++;let n=await ki(o,"utf-8"),a=JSON.parse(n);for(let l of a.skills){let c=l;(!("license"in c)||c.license===void 0)&&(c.license=""),(!("creator"in c)||c.creator===void 0)&&(c.creator=""),(!("compatibility"in c)||c.compatibility===void 0)&&(c.compatibility=""),(!("allowedTools"in c)||c.allowedTools===void 0)&&(c.allowedTools=[]),(!("verified"in c)||c.verified===void 0)&&(c.verified=!1),c.tags=Array.isArray(c.tags)?J(c.tags.filter(d=>typeof d=="string")):[]}t.set(`${a.owner}/${a.repo}`,a)}catch{}}return t}async function $e(){if(Mt!==null)return Mt;let e=await gi($s()),t=await gi(tt()),r=new Map(e);for(let[s,o]of t)r.set(s,o);return Mt=Array.from(r.values()),Cr=Mt.reduce((s,o)=>s+o.skillCount,0),Mt}async function pu(e){try{Si++;let r=(await ki(e,"utf-8")).match(/"skillCount"\s*:\s*(\d+)/);return r?Number(r[1]):null}catch{return null}}async function hi(e){let t=0,r;try{r=await wi(e)}catch{return t}for(let s of r){if(!s.endsWith(".json"))continue;let o=await pu(vi(e,s));o!==null&&(t+=o)}return t}async function $i(){if(Cr!==void 0)return Cr;let e=await hi($s()),t=await hi(tt()),r=e+t;return Cr=r,r}var mu=["license","creator","version"];function yi(e){return mu.includes(e)}function bi(e,t){return e[t]||""}function fu(e,t){if(!et(e,t))return!1;if(t.has){for(let r of t.has)if(yi(r)&&!bi(e,r))return!1}if(t.missing){for(let r of t.missing)if(yi(r)&&bi(e,r))return!1}if(t.tags&&t.tags.length>0){let r=J(t.tags);if(r.length===0||!ct(e.tags,r))return!1}return!0}function xi(e){let t=[];return e.license||t.push("license"),e.creator||t.push("creator"),(!e.version||e.version==="0.0.0")&&t.push("version"),t}async function Ft(e,t=20,r){let s=await $e(),o=[],n=!e&&r;for(let a of s)for(let l of a.skills){if(r&&!fu(l,r))continue;let c=n?1:uu(e,l);c>0&&o.push({skill:l,repo:{owner:a.owner,repo:a.repo},score:c})}return o.sort((a,l)=>l.score-a.score),o.slice(0,t)}async function As(){let e=await $e(),t=[];for(let r of e)for(let s of r.skills)t.push({skill:s,repo:{owner:r.owner,repo:r.repo}});return t}async function Pi(e,t){let r=e.trim().toLowerCase();if(!r)return{status:"none"};let o=(t??await As()).filter(l=>l.skill.name.toLowerCase()===r);if(o.length===0)return{status:"none"};let n=new Set,a=[];for(let l of o){let c=`${l.repo.owner}/${l.repo.repo}:${l.skill.relPath}`;n.has(c)||(n.add(c),a.push(l))}return a.length===1?{status:"found",match:a[0]}:{status:"ambiguous",matches:a}}function gu(){console.log(`${i.bold("Usage:")} asm search <query> [options]
252
114
 
253
115
  Search both installed skills and the skill index. Results show installation
254
116
  status and include copy-paste install commands for available skills.
255
117
 
256
- ${l.bold("Options:")}
118
+ ${i.bold("Options:")}
257
119
  --sort <field> Sort by: name, version, or location (default: name)
258
120
  -s, --scope <s> Filter: global, project, or both (default: both)
259
121
  -p, --tool <p> Filter by tool (claude, codex, openclaw, agents)
@@ -268,100 +130,100 @@ ${l.bold("Options:")}
268
130
  --no-color Disable ANSI colors
269
131
  -V, --verbose Show debug output
270
132
 
271
- ${l.bold("Examples:")}
272
- asm search code ${l.dim("Search installed and available skills")}
273
- asm search review -p claude ${l.dim("Search within Claude Code only")}
274
- asm search "test" --installed ${l.dim("Search installed skills only")}
275
- asm search "test" --available ${l.dim("Search available skills only")}
276
- asm search code --tag cli,testing ${l.dim("Require both tags")}
277
- asm search openspec --json ${l.dim("Output matches as JSON")}
278
- asm search openspec --machine ${l.dim("Machine-readable v1 envelope output")}`)}async function Tf(e){if(e.flags.help){Av();return}let t=e.flags.machine?he():void 0,s=performance.now(),i=e.subcommand;i||(e.flags.machine&&(t?.(),console.log(z("search",Y.INVALID_ARGUMENT,"Missing required argument: <query>",s)),process.exit(2)),$("Missing required argument: <query>"),console.error('Run "asm search --help" for usage.'),process.exit(2));let r=jt(e.flags.tagFilters);if(r.invalid.length>0){t?.(),$(`Invalid tag value(s): ${r.invalid.map(d=>JSON.stringify(d)).join(", ")}.`),process.exitCode=2;return}let n=!e.flags.available,o=!e.flags.installed,a=[];if(n){let d=await j(),p=await K(d,e.flags.scope);Ar(p,await _t()),r.tags.length>0&&(p=p.filter(g=>Bt(g.tags,r.tags))),e.flags.provider&&(p=p.filter(g=>g.provider===e.flags.provider)),(e.flags.modelInvocable||e.flags.userInvocable)&&(p=p.filter(g=>$t(g,{modelInvocable:e.flags.modelInvocable,userInvocable:e.flags.userInvocable})));let m=Wl(p,i);a=Si(m,e.flags.sort)}let c=[];if(o){let d={modelInvocable:e.flags.modelInvocable||void 0,userInvocable:e.flags.userInvocable||void 0,tags:r.tags.length>0?r.tags:void 0};if(c=await qs(i,20,d),a.length>0){let p=new Set(a.map(m=>m.name.toLowerCase()));c=c.filter(m=>!p.has(m.skill.name.toLowerCase()))}}if(e.flags.machine){t?.();let d=a.map(m=>({name:m.name,description:m.description,source:"installed",url:null,tags:m.tags||[],match_count:1})),p=c.map(m=>({name:m.skill.name,description:m.skill.description,source:"index",url:m.skill.installUrl,tags:m.skill.tags||[],match_count:1}));console.log(V("search",[...d,...p],s));return}if(e.flags.json){let d=a.map(m=>({name:m.name,description:m.description,version:m.version,scope:m.scope,provider:m.provider,tags:m.tags||[],status:"installed"})),p=c.map(m=>({name:m.skill.name,description:m.skill.description,version:m.skill.version,repo:`${m.repo.owner}/${m.repo.repo}`,installCommand:`asm install ${m.skill.installUrl}`,tags:m.skill.tags||[],status:"available"}));console.log(q([...d,...p]));return}let u=a.length>0,f=c.length>0;if(!u&&!f){console.error(`No skills matching "${i}".`),console.error(l.dim("Try ingesting more repos with: asm index ingest <repo>"));return}if(u&&(console.error(l.bold(`Installed skills matching "${i}":
279
- `)),e.flags.flat?console.log(yi(a)):console.log(Ul(a,i))),f){u&&console.error("");let d=Vl(c.map(p=>({name:p.skill.name,version:p.skill.version,description:p.skill.description,verified:p.skill.verified,repoLabel:`${p.repo.owner}/${p.repo.repo}`,installUrl:p.skill.installUrl,invocability:Fl(p.skill.modelInvocable,p.skill.userInvocable)})),i);console.error(d)}}function Rv(){console.log(`${l.bold("Usage:")} asm tag add <skill> <tag> [tag...]
133
+ ${i.bold("Examples:")}
134
+ asm search code ${i.dim("Search installed and available skills")}
135
+ asm search review -p claude ${i.dim("Search within Claude Code only")}
136
+ asm search "test" --installed ${i.dim("Search installed skills only")}
137
+ asm search "test" --available ${i.dim("Search available skills only")}
138
+ asm search code --tag cli,testing ${i.dim("Require both tags")}
139
+ asm search openspec --json ${i.dim("Output matches as JSON")}
140
+ asm search openspec --machine ${i.dim("Machine-readable v1 envelope output")}`)}async function Ri(e){if(e.flags.help){gu();return}let t=e.flags.machine?le():void 0,r=performance.now(),s=e.subcommand;s||(e.flags.machine&&(t?.(),console.log(K("search",W.INVALID_ARGUMENT,"Missing required argument: <query>",r)),process.exit(2)),w("Missing required argument: <query>"),console.error('Run "asm search --help" for usage.'),process.exit(2));let o=lt(e.flags.tagFilters);if(o.invalid.length>0){t?.(),w(`Invalid tag value(s): ${o.invalid.map(p=>JSON.stringify(p)).join(", ")}.`),process.exitCode=2;return}let n=!e.flags.available,a=!e.flags.installed,l=[];if(n){let p=await O(),f=await V(p,e.flags.scope);Ir(f,await at()),o.tags.length>0&&(f=f.filter(g=>ct(g.tags,o.tags))),e.flags.provider&&(f=f.filter(g=>g.provider===e.flags.provider)),(e.flags.modelInvocable||e.flags.userInvocable)&&(f=f.filter(g=>et(g,{modelInvocable:e.flags.modelInvocable,userInvocable:e.flags.userInvocable})));let m=Tn(f,s);l=kr(m,e.flags.sort)}let c=[];if(a){let p={modelInvocable:e.flags.modelInvocable||void 0,userInvocable:e.flags.userInvocable||void 0,tags:o.tags.length>0?o.tags:void 0};if(c=await Ft(s,20,p),l.length>0){let f=new Set(l.map(m=>m.name.toLowerCase()));c=c.filter(m=>!f.has(m.skill.name.toLowerCase()))}}if(e.flags.machine){t?.();let p=l.map(m=>({name:m.name,description:m.description,source:"installed",url:null,tags:m.tags||[],match_count:1})),f=c.map(m=>({name:m.skill.name,description:m.skill.description,source:"index",url:m.skill.installUrl,tags:m.skill.tags||[],match_count:1}));console.log(B("search",[...p,...f],r));return}if(e.flags.json){let p=l.map(m=>({name:m.name,description:m.description,version:m.version,scope:m.scope,provider:m.provider,tags:m.tags||[],status:"installed"})),f=c.map(m=>({name:m.skill.name,description:m.skill.description,version:m.skill.version,repo:`${m.repo.owner}/${m.repo.repo}`,installCommand:`asm install ${m.skill.installUrl}`,tags:m.skill.tags||[],status:"available"}));console.log(j([...p,...f]));return}let d=l.length>0,u=c.length>0;if(!d&&!u){console.error(`No skills matching "${s}".`),console.error(i.dim("Try ingesting more repos with: asm index ingest <repo>"));return}if(d&&(console.error(i.bold(`Installed skills matching "${s}":
141
+ `)),e.flags.flat?console.log(gr(l)):console.log(vn(l,s))),u){d&&console.error("");let p=Sn(c.map(f=>({name:f.skill.name,version:f.skill.version,description:f.skill.description,verified:f.skill.verified,repoLabel:`${f.repo.owner}/${f.repo.repo}`,installUrl:f.skill.installUrl,invocability:hn(f.skill.modelInvocable,f.skill.userInvocable)})),s);console.error(p)}}function hu(){console.log(`${i.bold("Usage:")} asm tag add <skill> <tag> [tag...]
280
142
  asm tag remove <skill> <tag> [tag...]
281
143
 
282
144
  Edit local tags for installed skills without changing their SKILL.md files.
283
145
  Tags are lowercase identifiers and may also be comma-separated.
284
146
 
285
- ${l.bold("Options:")}
147
+ ${i.bold("Options:")}
286
148
  -s, --scope <s> Limit matches to global, project, or both
287
149
  -p, --tool <p> Limit matches to one tool/provider
288
150
  --json Output updated skills as JSON
289
151
  --machine Output a stable machine-readable v1 envelope
290
152
 
291
- ${l.bold("Examples:")}
153
+ ${i.bold("Examples:")}
292
154
  asm tag add code-review testing cli
293
155
  asm tag add code-review testing,automation
294
- asm tag remove code-review automation`)}async function Of(e){if(e.flags.help){Rv();return}let t=e.subcommand;if(t!=="add"&&t!=="remove"){$('Missing or invalid action. Use "tag add" or "tag remove".'),process.exitCode=2;return}let s=e.positional[0],i=jt(e.positional.slice(1));if(i.invalid.length>0){let f=i.invalid.map(d=>JSON.stringify(d)).join(", ");$(`Invalid tag value(s): ${f}. Use 1-32 lowercase letters, numbers, hyphens, or underscores.`),process.exitCode=2;return}if(!s||i.tags.length===0){$(`Usage: asm tag ${t} <skill> <tag> [tag...]`),process.exitCode=2;return}let r=performance.now(),n=await j(),o=await K(n,e.flags.scope);e.flags.provider&&(o=o.filter(f=>f.provider===e.flags.provider));let a=_s(o,s);if(a.length===0){$(`Skill not found: "${s}".`),process.exitCode=1;return}let c=await _t(),u=[];for(let f of Ft(a,o)){let d=f.representative,p=oa(d),m=js(d.tags,c.skills[p]),g=t==="add"?hf(c,p,d.tags,i.tags):gf(c,p,d.tags,i.tags);u.push({name:d.name,path:d.realPath,tags:g,changed:JSON.stringify(m)!==JSON.stringify(g)})}await pf(c),e.flags.machine?console.log(V("tag",u,r)):e.flags.json?console.log(q(u)):console.log(Kl(t,u))}function Nv(){console.log(`${l.bold("Usage:")} asm inspect <skill-name> [options]
156
+ asm tag remove code-review automation`)}async function Ei(e){if(e.flags.help){hu();return}let t=e.subcommand;if(t!=="add"&&t!=="remove"){w('Missing or invalid action. Use "tag add" or "tag remove".'),process.exitCode=2;return}let r=e.positional[0],s=lt(e.positional.slice(1));if(s.invalid.length>0){let u=s.invalid.map(p=>JSON.stringify(p)).join(", ");w(`Invalid tag value(s): ${u}. Use 1-32 lowercase letters, numbers, hyphens, or underscores.`),process.exitCode=2;return}if(!r||s.tags.length===0){w(`Usage: asm tag ${t} <skill> <tag> [tag...]`),process.exitCode=2;return}let o=performance.now(),n=await O(),a=await V(n,e.flags.scope);e.flags.provider&&(a=a.filter(u=>u.provider===e.flags.provider));let l=Ot(a,r);if(l.length===0){w(`Skill not found: "${r}".`),process.exitCode=1;return}let c=await at(),d=[];for(let u of it(l,a)){let p=u.representative,f=Cs(p),m=Dt(p.tags,c.skills[f]),g=t==="add"?li(c,f,p.tags,s.tags):ci(c,f,p.tags,s.tags);d.push({name:p.name,path:p.realPath,tags:g,changed:JSON.stringify(m)!==JSON.stringify(g)})}await ii(c),e.flags.machine?console.log(B("tag",d,o)):e.flags.json?console.log(j(d)):console.log($n(t,d))}function yu(){console.log(`${i.bold("Usage:")} asm inspect <skill-name> [options]
295
157
 
296
158
  Show detailed information for a skill. The <skill-name> is the directory name.
297
159
  Shows version, description, file count, and all provider installations.
298
160
 
299
- ${l.bold("Options:")}
161
+ ${i.bold("Options:")}
300
162
  -s, --scope <s> Filter: global, project, or both (default: both)
301
163
  --json Output as JSON object
302
164
  --no-color Disable ANSI colors
303
165
  -V, --verbose Show debug output
304
166
 
305
- ${l.bold("Examples:")}
306
- asm inspect code-review ${l.dim("Show details for code-review")}
307
- asm inspect code-review --json ${l.dim("Output as JSON")}
308
- asm inspect code-review -s global ${l.dim("Global installations only")}`)}async function Mf(e){if(e.flags.help){Nv();return}let t=e.subcommand;t||($("Missing required argument: <skill-name>"),console.error('Run "asm inspect --help" for usage.'),process.exit(2));let s=await j(),r=(await K(s,e.flags.scope)).filter(n=>n.dirName===t);r.length===0&&($(`Skill "${t}" not found.`),console.error(l.dim(`Try ${l.bold("asm list")} to see all skills or ${l.bold(`asm search "${t}"`)} to search.`)),process.exit(1)),await Ds(r),e.flags.json?console.log(q(r.length===1?r[0]:r)):console.log(await Yl(r))}var qt=class extends Error{candidates;constructor(t,s){super(t),this.name="AmbiguousGetError",this.candidates=s}};import{readFile as rn}from"fs/promises";import{execFile as Tv}from"child_process";import{promisify as Ov}from"util";import{mkdtemp as Df,readdir as Mv,readFile as Tr,rm as Or,cp as Dv,access as ua,stat as Bf,lstat as Fv,mkdir as _v}from"fs/promises";import{join as Le,resolve as Us,relative as jv,basename as qf,sep as Bv}from"path";import{homedir as Ff}from"os";import{tmpdir as _f}from"os";var Ut=Ov(Tv),qv=/^[a-zA-Z0-9_-]+$/,Uv=/^[a-zA-Z0-9._-]+$/,Vv=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/,jf=128,Kv=/^https?:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\/tree\/(.+))?\/?$/;function ft(e){return e.startsWith("/")||e.startsWith("./")||e.startsWith(".\\")||e.startsWith("../")||e.startsWith("..\\")||e.startsWith("~/")||e.startsWith("~\\")||e==="~"||e==="."||e===".."||/^[a-zA-Z]:[/\\]/.test(e)}async function Ks(e){if(!e.includes("/")&&!e.includes("\\"))return!1;try{return(await Bf(Us(e))).isDirectory()}catch{return!1}}function Uf(e){let t;e==="~"?t=Ff():e.startsWith("~/")||e.startsWith("~\\")?t=Us(Ff(),e.slice(2)):t=Us(e);let s=qf(t);return L(`install: parsed local source -> path=${t}`),{owner:"local",repo:s,ref:null,subpath:null,cloneUrl:"",sshCloneUrl:"",isLocal:!0,localPath:t}}function ue(e){if(ft(e))return Uf(e);let t=Kv.exec(e);if(t){let[,d,p,m]=t,g=p.endsWith(".git")?p.slice(0,-4):p;e=`github:${d}/${g}${m?`#${m}`:""}`}if(!e.startsWith("github:"))throw new Error(`Invalid source format. Got: "${e}"
167
+ ${i.bold("Examples:")}
168
+ asm inspect code-review ${i.dim("Show details for code-review")}
169
+ asm inspect code-review --json ${i.dim("Output as JSON")}
170
+ asm inspect code-review -s global ${i.dim("Global installations only")}`)}async function Ii(e){if(e.flags.help){yu();return}let t=e.subcommand;t||(w("Missing required argument: <skill-name>"),console.error('Run "asm inspect --help" for usage.'),process.exit(2));let r=await O(),o=(await V(r,e.flags.scope)).filter(n=>n.dirName===t);o.length===0&&(w(`Skill "${t}" not found.`),console.error(i.dim(`Try ${i.bold("asm list")} to see all skills or ${i.bold(`asm search "${t}"`)} to search.`)),process.exit(1)),await Tt(o),e.flags.json?console.log(j(o.length===1?o[0]:o)):console.log(await Nn(o))}var dt=class extends Error{candidates;constructor(t,r){super(t),this.name="AmbiguousGetError",this.candidates=r}};import{readFile as ts}from"fs/promises";import{execFile as bu}from"child_process";import{promisify as wu}from"util";import{mkdtemp as Ci,readdir as ku,readFile as Ar,rm as Tr,cp as vu,access as Ns,stat as Ni,lstat as Su,mkdir as $u}from"fs/promises";import{join as ke,resolve as jt,relative as xu,basename as Oi,sep as Pu}from"path";import{homedir as Li}from"os";import{tmpdir as Ai}from"os";var ut=wu(bu),Ru=/^[a-zA-Z0-9_-]+$/,Eu=/^[a-zA-Z0-9._-]+$/,Iu=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/,Ti=128,Cu=/^https?:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\/tree\/(.+))?\/?$/;function je(e){return e.startsWith("/")||e.startsWith("./")||e.startsWith(".\\")||e.startsWith("../")||e.startsWith("..\\")||e.startsWith("~/")||e.startsWith("~\\")||e==="~"||e==="."||e===".."||/^[a-zA-Z]:[/\\]/.test(e)}async function Ut(e){if(!e.includes("/")&&!e.includes("\\"))return!1;try{return(await Ni(jt(e))).isDirectory()}catch{return!1}}function Di(e){let t;e==="~"?t=Li():e.startsWith("~/")||e.startsWith("~\\")?t=jt(Li(),e.slice(2)):t=jt(e);let r=Oi(t);return P(`install: parsed local source -> path=${t}`),{owner:"local",repo:r,ref:null,subpath:null,cloneUrl:"",sshCloneUrl:"",isLocal:!0,localPath:t}}function oe(e){if(je(e))return Di(e);let t=Cu.exec(e);if(t){let[,p,f,m]=t,g=f.endsWith(".git")?f.slice(0,-4):f;e=`github:${p}/${g}${m?`#${m}`:""}`}if(!e.startsWith("github:"))throw new Error(`Invalid source format. Got: "${e}"
309
171
  Supported formats:
310
172
  github:owner/repo[#ref]
311
173
  github:owner/repo#ref:path
312
174
  https://github.com/owner/repo
313
175
  https://github.com/owner/repo/tree/branch/path/to/skill
314
176
  /path/to/local/skill
315
- ./relative/path/to/skill`);let s=e.slice(7),i=s.indexOf("#"),r,n=null,o=null;if(i!==-1){r=s.slice(0,i);let d=s.slice(i+1);if(!d)throw new Error("Invalid source: ref cannot be empty after #");let p=d.indexOf(":");if(p!==-1){if(n=d.slice(0,p),!n)throw new Error("Invalid source: ref cannot be empty before :");o=d.slice(p+1)||null}else n=d}else{let d=s.indexOf(":");d!==-1?(r=s.slice(0,d),o=s.slice(d+1)||null):r=s}let a=r.indexOf("/");if(a===-1)throw new Error(`Invalid source: format must be github:owner/repo. Got: "${e}"`);let c=r.slice(0,a),u=r.slice(a+1);if(!c)throw new Error("Invalid source: owner cannot be empty");if(!u)throw new Error("Invalid source: repo cannot be empty");if(!qv.test(c))throw new Error(`Invalid source: owner contains invalid characters: "${c}". Allowed: [a-zA-Z0-9_-]`);if(!Uv.test(u))throw new Error(`Invalid source: repo contains invalid characters: "${u}". Allowed: [a-zA-Z0-9._-]`);let f={owner:c,repo:u,ref:n,subpath:o,cloneUrl:`https://github.com/${c}/${u}.git`,sshCloneUrl:`git@github.com:${c}/${u}.git`};return L(`install: parsed source -> owner=${c} repo=${u} ref=${n} subpath=${o}`),f}function Vs(e){return!!e&&e.split(/[/\\]/).includes("..")}function ye(e,t){if(Vs(e.subpath)||Vs(e.ref))throw new Error(`Invalid source: the subpath in "${t}" escapes the repository.`)}function Be(e,t,s){let i=Us(e),r=Us(t);if(r!==i&&!r.startsWith(i+Bv))throw new Error(`Invalid source: the subpath in "${s}" escapes the repository.`)}async function pt(e){if(e.subpath!==null||!e.ref||!e.ref.includes("/"))return e;try{let{stdout:t}=await Ut("git",["ls-remote","--heads","--tags",e.cloneUrl],{timeout:15e3}),s=new Set;for(let r of t.split(`
316
- `)){let n=r.match(/\trefs\/(?:heads|tags)\/(.+)$/);n&&s.add(n[1])}let i=e.ref.split("/");for(let r=1;r<i.length;r++){let n=i.slice(0,r).join("/");if(s.has(n)){let o=i.slice(r).join("/");return L(`install: resolved ref="${n}" subpath="${o}"`),{...e,ref:n,subpath:o||null}}}}catch(t){L(`install: ls-remote failed, treating entire ref as branch: ${t}`)}return e}function be(e){if(!e)throw new Error("Invalid skill name: name cannot be empty");if(e.includes("\0"))throw new Error("Invalid skill name: contains unsafe characters (null byte)");if(e.includes(".."))throw new Error("Invalid skill name: contains unsafe characters (..)");if(e.includes("/")||e.includes("\\"))throw new Error("Invalid skill name: contains unsafe characters (path separator)");if(e.startsWith("."))throw new Error("Invalid skill name: must not start with a dot");if(e.length>jf)throw new Error(`Invalid skill name: exceeds maximum length of ${jf} characters`);if(!Vv.test(e))throw new Error(`Invalid skill name: "${e}" does not match allowed pattern [a-zA-Z0-9][a-zA-Z0-9._-]*`);return e}function Mr(e){let t=e.split(/[/\\]/).filter(Boolean),s=t.length>0?t[t.length-1]:e;return be(s)}function da(e,t=Mr){let s=new Map;for(let i of e){let r=t(i),n=s.get(r);n?n.push(i):s.set(r,[i])}return[...s.entries()].filter(([,i])=>i.length>1).map(([i,r])=>({name:i,paths:r}))}async function Ae(){try{await Ut("git",["--version"]),L("install: git available")}catch{throw new Error("git is required for installing skills. Install git from https://git-scm.com")}}function Vf(e){if(e.killed)return!1;let t=(e.stderr||e.message||"").toLowerCase();return t.includes("authentication failed")||t.includes("could not read username")||t.includes("repository not found")||t.includes("returned error: 403")||t.includes("returned error: 401")||t.includes("terminal prompts disabled")||t.includes("permission denied")}function Nr(e){return e.killed?"Clone timed out after 60 seconds":`Clone failed: ${e.stderr||e.message}`}async function ca(e,t,s){if(t!==null&&/^[0-9a-f]{40}$/i.test(t))return await Ut("git",["clone","--no-checkout",e,s],{timeout:6e4}),await Ut("git",["checkout",t],{cwd:s,timeout:3e4}),s;let r=["clone","--depth","1"];return t&&r.push("--branch",t),r.push(e,s),await Ut("git",r,{timeout:6e4}),s}async function Re(e,t="auto"){L(`install: cloning ${e.owner}/${e.repo}${e.ref?` (ref: ${e.ref})`:""} (transport: ${t})`);let s=await Df(Le(_f(),"asm-install-"));if(t==="ssh"||t==="https"){let i=t==="ssh"?e.sshCloneUrl:e.cloneUrl;try{return await ca(i,e.ref,s)}catch(r){await Q(s);let n=r;throw new Error(Nr(n),{cause:r})}}try{return await ca(e.cloneUrl,e.ref,s)}catch(i){if(!Vf(i))throw await Q(s),new Error(Nr(i),{cause:i});L("install: HTTPS clone failed with auth error, retrying with SSH..."),await Q(s);let r=await Df(Le(_f(),"asm-install-"));try{return await ca(e.sshCloneUrl,e.ref,r)}catch(n){throw await Q(r),new Error(`Clone failed with both transports:
317
- HTTPS: ${Nr(i)}
318
- SSH: ${Nr(n)}`,{cause:n})}}}async function we(e){let t=Le(e,"SKILL.md"),s;try{s=await Tr(t,"utf-8")}catch{throw new Error("Not a valid skill: SKILL.md not found in repository root")}let i=W(s),r=e.split(/[/\\]/).pop()||"unknown",n=i.name||r,o=fe(i);return L(`install: validated skill "${n}" v${o}`),{name:n,version:o,description:(i.description||"").replace(/\s*\n\s*/g," ").trim(),effort:i.effort||i["metadata.effort"]||void 0}}async function mt(e,t=5){let s=[];try{let r=await Tr(Le(e,"SKILL.md"),"utf-8"),n=W(r);s.push({relPath:"",name:n.name||qf(e),version:fe(n),description:(n.description||"").replace(/\s*\n\s*/g," ").trim(),effort:n.effort||n["metadata.effort"]||void 0,license:(n.license||"").trim(),creator:(n["metadata.creator"]||"").trim(),compatibility:(n.compatibility||"").trim(),allowedTools:fn(n),tags:ts(n),modelInvocable:ss(n),userInvocable:is(n),tokenCount:qe(r)})}catch{}async function i(r,n,o){let a;try{a=await Mv(r)}catch{return}for(let c of a){if(c===".git"||c==="node_modules")continue;let u=Le(r,c);try{if(!(await Bf(u)).isDirectory())continue}catch{continue}let f=n?`${n}/${c}`:c,d=o+1,p=Le(u,"SKILL.md");try{let m=await Tr(p,"utf-8"),g=W(m);s.push({relPath:f,name:g.name||c,version:fe(g),description:(g.description||"").replace(/\s*\n\s*/g," ").trim(),effort:g.effort||g["metadata.effort"]||void 0,license:(g.license||"").trim(),creator:(g["metadata.creator"]||"").trim(),compatibility:(g.compatibility||"").trim(),allowedTools:fn(g),tags:ts(g),modelInvocable:ss(g),userInvocable:is(g),tokenCount:qe(m)})}catch{d<t&&await i(u,f,d)}}}return await i(e,"",0),s.sort((r,n)=>r.name.localeCompare(n.name)),s}async function Kf(e,t=Ut){let s=Le(e,"scripts"),i=Le(s,"package.json");try{await ua(i)}catch{L(`install: no scripts/package.json in ${e}; skipping npm install`);return}L(`install: installing script dependencies in ${s}`);try{await t("npm",["install"],{cwd:s,timeout:12e4})}catch(r){let n=r;throw new Error(`Installed skill, but failed to install dependencies in scripts/: ${n.stderr||n.message}`,{cause:r})}}var Gv=[{category:"Shell commands",pattern:/\b(bash|sh\s+-c)\b/},{category:"Shell commands",pattern:/\bexec\(/},{category:"Shell commands",pattern:/\bchild_process\b/},{category:"Shell commands",pattern:/\bBun\.spawn\b/},{category:"Code execution",pattern:/\beval\(/},{category:"Code execution",pattern:/\bFunction\(/},{category:"Code execution",pattern:/\bnew\s+Function\b/},{category:"Credentials",pattern:/\b(API_KEY|SECRET|TOKEN|PASSWORD)\s*[=:]/},{category:"External URLs",pattern:/https?:\/\//}];async function Gs(e){let t=[],s=await xi(e);for(let{relPath:i,content:r}of s){let n=r.split(`
319
- `);for(let o=0;o<n.length;o++)for(let{category:a,pattern:c}of Gv)if(c.test(n[o])){let u=n[o].trim();t.push({category:a,file:i,line:o+1,match:u.length>100?u.slice(0,100)+"\u2026":u})}}return t}var Hv=["Shell commands","Code execution","Credentials"],Jv=["External URLs"];function Hs(e){return e.some(t=>Hv.includes(t.category))?"high":e.some(t=>Jv.includes(t.category))?"medium":"safe"}async function Vt(e){let t=e.source.isLocal?`local:${e.source.localPath}`:`github:${e.source.owner}/${e.source.repo}${e.source.ref?`#${e.source.ref}`:""}${e.source.subpath?`:${e.source.subpath}`:""}`;if(e.force)try{await ua(e.targetDir),await Or(e.targetDir,{recursive:!0,force:!0})}catch{}let s=e.sourceDir;try{await Dv(s,e.targetDir,{recursive:!0})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Failed to install: ${c}`,{cause:a})}let i=Le(e.targetDir,".git");try{await Or(i,{recursive:!0,force:!0})}catch{}L(`install: copied files to ${e.targetDir}`);let r=Le(e.targetDir,"SKILL.md");try{await ua(r)}catch{throw new Error("Installation verification failed: SKILL.md not found at target")}await Kf(e.targetDir);let n=await Tr(r,"utf-8"),o=W(n);return{success:!0,path:e.targetDir,name:o.name||e.skillName,version:fe(o),provider:e.providerLabel,source:t}}async function fa(e,t){let s=await Vt(e);for(let i of t){if(i.name===e.providerName)continue;let r=e.scope==="project"?i.project:i.global,n=ie(r),o=Le(n,e.skillName);await _v(n,{recursive:!0});try{if((await Fv(o)).isSymbolicLink())await Or(o);else{L(`install: skipping ${o} \u2014 existing non-symlink directory`);continue}}catch{}let a=jv(n,e.targetDir);await Ve(a,o),L(`install: symlinked ${o} -> ${a}`)}return s.provider=`All (${t.map(i=>i.label).join(", ")})`,s}async function Q(e){try{await Or(e,{recursive:!0,force:!0})}catch{}}import{execFile as eS}from"child_process";import{promisify as tS}from"util";import{readFile as sS,access as ya}from"fs/promises";import{existsSync as iS}from"fs";import{join as gt,dirname as rS}from"path";var ma=class{selected;cursor;scrollOffset;pageSize;itemCount;filter;searchActive;filteredMap;constructor(t,s){this.selected=t.map(i=>i.checked),this.cursor=1,this.scrollOffset=0,this.pageSize=s,this.itemCount=t.length,this.filter="",this.searchActive=!1,this.filteredMap=t.map((i,r)=>r)}get totalRows(){return this.filteredMap.length+1}applyFilter(t){if(this.filter==="")this.filteredMap=t.map((s,i)=>i);else{let s=this.filter.toLowerCase();this.filteredMap=[];for(let i=0;i<t.length;i++)(t[i].label.toLowerCase()+" "+(t[i].hint?.toLowerCase()??"")).includes(s)&&this.filteredMap.push(i)}this.cursor>=this.totalRows&&(this.cursor=Math.max(0,this.totalRows-1)),this.scrollOffset>0&&this.scrollOffset>=this.totalRows&&(this.scrollOffset=Math.max(0,this.totalRows-this.pageSize))}cursorToOriginalIndex(){return this.cursor===0?-1:this.filteredMap[this.cursor-1]??-1}toggleCurrent(){if(this.cursor===0)this.toggleAll();else{let t=this.cursorToOriginalIndex();t>=0&&(this.selected[t]=!this.selected[t])}}toggleAll(){let t=this.filteredMap,i=!t.every(r=>this.selected[r]);for(let r of t)this.selected[r]=i}moveUp(){this.cursor>0?this.cursor--:this.cursor=this.totalRows-1,this.adjustScroll()}moveDown(){this.cursor<this.totalRows-1?this.cursor++:this.cursor=0,this.adjustScroll()}getSelectedIndices(){let t=[];for(let s=0;s<this.selected.length;s++)this.selected[s]&&t.push(s);return t}getVisibleRange(){let t=this.scrollOffset,s=Math.min(this.scrollOffset+this.pageSize,this.totalRows);return{start:t,end:s}}adjustScroll(){this.cursor<this.scrollOffset?this.scrollOffset=this.cursor:this.cursor>=this.scrollOffset+this.pageSize&&(this.scrollOffset=this.cursor-this.pageSize+1)}};function Wv(e,t,s){let i=[];if(e.searchActive||e.filter!==""){let u=l.cyan("/"),f=e.filter,d=e.searchActive?l.cyan("\u2588"):"";i.push(` ${u}${f}${d}`),e.filteredMap.length===0&&i.push(l.dim(" No matches found")),i.push("")}let{start:r,end:n}=e.getVisibleRange();r>0&&i.push(l.dim(` ... ${r} more above`));for(let u=r;u<n;u++){let d=u===e.cursor?l.cyan(">"):" ";if(u===0){let p=e.filteredMap,g=p.length>0&&p.every(y=>e.selected[y])?l.green("[*]"):"[ ]",h=e.filter!==""?`Select All Matching (${e.filteredMap.length})`:"Select All / Deselect All";i.push(`${d} ${g} ${l.bold(h)}`)}else{let p=e.filteredMap[u-1],m=t[p],h=e.selected[p]?l.green("[*]"):"[ ]",y=`${d} ${h} `,b=7,k=l.bold(m.label),w=m.label.length;if(m.hint){let v=s-b-w-2;if(v>10){let x=pa(m.hint,v);i.push(`${y}${k} ${l.dim(x)}`)}else{let x=pa(m.label,s-b);i.push(`${y}${l.bold(x)}`)}}else{let v=pa(m.label,s-b);i.push(`${y}${l.bold(v)}`)}}}let o=e.totalRows-n;o>0&&i.push(l.dim(` ... ${o} more below`));let a=e.getSelectedIndices().length,c=e.filter!==""?` matching: ${e.filteredMap.length}/${e.itemCount}`:"";return i.push(""),e.searchActive?i.push(l.dim(` ${a} of ${e.itemCount} selected${c} | Type to filter Esc Clear Enter Done searching`)):i.push(l.dim(` ${a} of ${e.itemCount} selected${c} | \u2191/\u2193 Navigate Space Toggle a All / Search Enter Confirm Esc Cancel`)),i}function pa(e,t){return t<=0?"":e.length<=t?e:t<=3?e.slice(0,t):e.slice(0,t-3)+"..."}async function ht(e){let{items:t}=e,s=e.pageSize??Math.min(t.length+1,15),i=new ma(t,s),r=process.stderr,n=process.stdin,o=r.columns||80;typeof n.setRawMode=="function"&&n.setRawMode(!0),n.resume(),n.setEncoding("utf-8"),r.write("\x1B[?25l");let a=0;function c(){let u=Wv(i,t,o);a>0&&r.write(`\x1B[${a}F`);let f=Math.max(u.length,a),d="";for(let p=0;p<f;p++)d+=`\x1B[2K${p<u.length?u[p]:""}
320
- `;r.write(d),a=f}return c(),new Promise(u=>{let f="",d=null;function p(){n.removeListener("data",h),typeof n.setRawMode=="function"&&n.setRawMode(!1),n.pause(),r.write("\x1B[?25h"),d&&clearTimeout(d)}function m(y){p(),u(y)}function g(y){if(i.searchActive){if(y==="\x1B"){i.searchActive=!1,i.filter="",i.applyFilter(t),c();return}if(y==="\r"||y===`
321
- `){i.searchActive=!1,c();return}if(y==="\x7F"||y==="\b"){i.filter.length>0?(i.filter=i.filter.slice(0,-1),i.applyFilter(t)):i.searchActive=!1,c();return}if(y===""){p(),process.kill(process.pid,"SIGINT");return}if(y==="\x1B[A"){i.moveUp(),c();return}if(y==="\x1B[B"){i.moveDown(),c();return}if(y===" "){i.toggleCurrent(),c();return}if(y.length===1&&y>=" "&&y<="~"){i.filter+=y,i.applyFilter(t),c();return}return}switch(y){case"\x1B[A":case"k":i.moveUp(),c();break;case"\x1B[B":case"j":i.moveDown(),c();break;case" ":i.toggleCurrent(),c();break;case"a":i.toggleAll(),c();break;case"/":i.searchActive=!0,c();break;case"\r":case`
322
- `:m(i.getSelectedIndices());break;case"\x1B":i.filter!==""?(i.filter="",i.applyFilter(t),c()):m([]);break;case"\x7F":case"\b":i.filter.length>0&&(i.filter=i.filter.slice(0,-1),i.applyFilter(t),c());break;case"":p(),process.kill(process.pid,"SIGINT");break}}function h(y){if(f.length>0){if(f+=y,d&&clearTimeout(d),f.length>=3&&f[1]==="["){let k=f.slice(0,3),w=f.slice(3);f="",g(k),w&&h(w);return}let b=f;f="",g("\x1B");for(let k=1;k<b.length;k++)g(b[k]);return}for(let b=0;b<y.length;b++){let k=y[b];if(k==="\x1B"){let w=y.slice(b);if(w.length>=3&&w[1]==="[")g(w.slice(0,3)),b+=2;else if(w.length>=2){f=w,d=setTimeout(()=>{let v=f;f="",g("\x1B");for(let x=1;x<v.length;x++)g(v[x])},50);return}else{f="\x1B",d=setTimeout(()=>{f="",g("\x1B")},50);return}}else g(k)}}n.on("data",h)})}import{access as Yv,lstat as zv,mkdir as Xv,readdir as Zv,readFile as Gf,rm as Qv,stat as Hf}from"fs/promises";import{join as Dr}from"path";async function ha(e){let t;try{t=await Hf(e)}catch{throw new Error(`Path does not exist: ${e}`)}if(!t.isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=Dr(e,"SKILL.md"),i;try{i=await Gf(s,"utf-8")}catch{throw new Error(`No SKILL.md found in ${e}`)}let r=W(i);if(!r.name)throw new Error(`Invalid SKILL.md in ${e}: missing "name" in frontmatter`);return{name:r.name,version:fe(r)}}async function Fr(e,t,s,i){let r=Dr(t,s),n=!1;try{await Yv(r),n=!0}catch{}if(n){if(!i)throw new Error(`Target already exists: ${r}. Use --force to overwrite.`);await Qv(r,{recursive:!0,force:!0})}await Xv(t,{recursive:!0}),await Ve(e,r)}async function ga(e){let t;try{t=await Hf(e)}catch{throw new Error(`Path does not exist: ${e}`)}if(!t.isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=await Zv(e),i=[];for(let r of s){if(r.startsWith(".")||r==="node_modules")continue;let n=Dr(e,r);try{if(!(await zv(n)).isDirectory())continue}catch{continue}let o=Dr(n,"SKILL.md");try{let a=await Gf(o,"utf-8"),c=W(a);c.name&&i.push({absPath:n,dirName:r,name:c.name,version:fe(c)})}catch{}}return i.sort((r,n)=>r.name.localeCompare(n.name)),i}var Jf=tS(eS);function Wf(e=rS(process.execPath)){let t=[gt(e,"node_modules","npm","bin","npx-cli.js"),gt(e,"..","lib","node_modules","npm","bin","npx-cli.js"),gt(e,"..","libexec","lib","node_modules","npm","bin","npx-cli.js")];for(let s of t)if(iS(s))return s;return null}function Yf(e,t={}){if(process.platform==="win32"){let s=Wf();if(s)return Jf(process.execPath,[s,...e],t)}return Jf("npx",e,t)}async function ba(){try{await Yf(["--version"]),L("install: npx available")}catch{throw new Error("npx is required for Vercel method installation. Install Node.js from https://nodejs.org")}}async function wa(e,t){let s=["--yes","skills","add",e];t&&s.push("--skill",t),L(`install: running npx ${s.join(" ")}`);try{let i=await Yf(s,{timeout:12e4});return{stdout:i.stdout,stderr:i.stderr}}catch(i){let r=i,n=r.stderr||r.message||"";throw new Error(`npx skills add failed: ${n}`,{cause:i})}}function ka(e){if(e.isLocal)return e.localPath;let t=`https://github.com/${e.owner}/${e.repo}`;return e.ref?`${t}/tree/${e.ref}${e.subpath?`/${e.subpath}`:""}`:t}async function ke(e,t,s){let i=e.providers.filter(m=>m.enabled);if(t==="all"){if(i.length===0)throw new Error("No providers are enabled. Enable a provider in your config.");return{provider:i.find(g=>g.name==="agents")||i[0],allProviders:i}}if(t){let m=e.providers.find(g=>g.name===t);if(!m){let g=e.providers.map(h=>h.name).join(", ");throw new Error(`Unknown provider: "${t}". Valid providers: ${g}, all`)}if(!m.enabled)throw new Error(`Provider "${t}" is disabled. Enable it in your config or choose another provider.`);return{provider:m,allProviders:null}}if(i.length===1)return{provider:i[0],allProviders:null};if(!s){if(i.length===0)throw new Error("No providers are enabled. Enable a provider in your config.");let m=i.map(g=>g.name).join(", ");throw new Error(`--tool (or --provider) is required in non-interactive mode. Available: ${m}, all`)}let r=e.preferences.selectedTools,o=r&&r.length>0?new Set(r):null,a=e.providers.map(m=>({label:`${m.label} (${m.name})`,hint:m.global,checked:o?o.has(m.name):m.name==="agents"})),c=await ht({items:a});if(c.length===0)throw new Error("No tools selected. Aborting.");let u=c.map(m=>e.providers[m]),f=u.map(m=>m.name),{saveSelectedTools:d}=await import("./config-PQRMSV7F.js");return await d(f),u.length===1?{provider:u[0],allProviders:null}:{provider:u.find(m=>m.name==="agents")||u[0],allProviders:u}}function Js(e,t,s,i,r,n,o="global"){let a=o==="project"?r.project:r.global,c=ie(a),u=gt(c,i);return{source:e,tempDir:t,sourceDir:s,targetDir:u,skillName:i,force:n,providerName:r.name,providerLabel:r.label,scope:o}}async function va(e,t){try{if(await ya(e),L(`install: target ${e} \u2014 conflict (exists)${t?", force overwrite":""}`),!t)throw new Error(`Skill already exists at: ${e}
323
- Use --force to overwrite.`)}catch(s){if(s instanceof Error&&s.message?.includes("--force"))throw s;L(`install: target ${e} \u2014 no conflict`)}}async function Sa(e,t,s){for(let i of s.providers){if(!i.enabled||i.name===t)continue;let r=ie(i.global),n=gt(r,e);try{await ya(n);let o=gt(n,"SKILL.md");await ya(o);let a=await sS(o,"utf-8");if((W(a).name||n.split(/[/\\]/).pop()||"")===e)return L(`install: cross-tool link found \u2014 "${e}" already installed in ${i.label} at ${n}`),{existingProvider:i.name,existingProviderLabel:i.label,existingPath:n,isLocalSource:!1}}catch{continue}}return null}async function $a(e,t,s,i,r,n=!1){let o=r.providers.find(f=>f.name===s);if(!o)throw new Error(`Target provider "${s}" not found in config.`);let a=i==="project"?o.project:o.global,c=ie(a),u=gt(c,e);return await Fr(t,c,e,n),L(`install: linked "${e}" from ${t} -> ${u}`),u}import{join as fS}from"path";import{readFile as nS,writeFile as oS,mkdir as aS}from"fs/promises";import{dirname as lS}from"path";async function cS(e){try{let t=await nS(e,"utf-8"),s=JSON.parse(t);return!s.fetched_at||s.data===void 0||s.data===null?null:s}catch{return null}}async function uS(e,t,s){let i={fetched_at:new Date().toISOString(),ttl_seconds:s,data:t};try{await aS(lS(e),{recursive:!0}),await oS(e,JSON.stringify(i,null,2),"utf-8"),L(`http: wrote cache -> ${e}`)}catch(r){L(`http: failed to write cache: ${r}`)}}function dS(e){let t=new Date(e.fetched_at).getTime();return(Date.now()-t)/1e3<e.ttl_seconds}async function zf(e,t,s={}){let i=s.ttl??3600,r=s.noCache??!1,n=await cS(t);if(n&&!r&&dS(n))return L(`http: cache hit (fresh) -> ${t}`),n.data;try{L(`http: fetching -> ${e}`);let o=await fetch(e);if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let a=await o.json();return await uS(t,a,i),a}catch(o){return L(`http: fetch failed: ${o}`),n?(L(`http: using stale cache as fallback -> ${t}`),n.data):null}}var pS=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,mS=/^[a-zA-Z0-9_-]+$/,Qf=/^https:\/\/github\.com\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9._-]+$/,hS=/^[0-9a-f]{40}$/,gS=/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?(\+[a-zA-Z0-9.]+)?$/,yS=/^[a-z0-9-]+$/,bS=/^sha256:[0-9a-f]{64}$/,Xf=["pass","warning","dangerous"];function _r(e){let t=[];if(!e||typeof e!="object"||Array.isArray(e))return[{field:"(root)",message:"manifest must be a non-null object"}];let s=e,i=new Set(["name","author","description","repository","commit","skill_path","version","license","tags","security_verdict","published_at","checksum"]);for(let o of Object.keys(s))i.has(o)||t.push({field:o,message:`unknown property "${o}" is not allowed`});let r=[{field:"name",pattern:pS,maxLength:128},{field:"author",pattern:mS,maxLength:39},{field:"description",maxLength:256},{field:"repository",pattern:Qf},{field:"commit",pattern:hS},{field:"published_at"}];for(let{field:o,pattern:a,maxLength:c}of r){let u=s[o];if(u==null){t.push({field:o,message:`required field "${o}" is missing`});continue}if(typeof u!="string"){t.push({field:o,message:`"${o}" must be a string`});continue}if(u.length===0){t.push({field:o,message:`"${o}" must not be empty`});continue}c&&u.length>c&&t.push({field:o,message:`"${o}" exceeds maximum length of ${c}`}),a&&!a.test(u)&&t.push({field:o,message:`"${o}" does not match required pattern`})}let n=s.security_verdict;if(n==null?t.push({field:"security_verdict",message:'required field "security_verdict" is missing'}):(typeof n!="string"||!Xf.includes(n))&&t.push({field:"security_verdict",message:`"security_verdict" must be one of: ${Xf.join(", ")}`}),typeof s.published_at=="string"&&s.published_at.length>0&&(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/.test(s.published_at)||t.push({field:"published_at",message:'"published_at" must be a valid ISO 8601 date-time'})),s.version!==void 0&&(typeof s.version!="string"||!gS.test(s.version))&&t.push({field:"version",message:'"version" must be a valid semver string'}),s.license!==void 0&&(typeof s.license!="string"?t.push({field:"license",message:'"license" must be a string'}):s.license.length>64&&t.push({field:"license",message:'"license" exceeds maximum length of 64'})),s.tags!==void 0)if(!Array.isArray(s.tags))t.push({field:"tags",message:'"tags" must be an array'});else{s.tags.length>10&&t.push({field:"tags",message:'"tags" has more than 10 items'});let o=new Set;for(let a=0;a<s.tags.length;a++){let c=s.tags[a];if(typeof c!="string"){t.push({field:`tags[${a}]`,message:"tag must be a string"});continue}c.length>32&&t.push({field:`tags[${a}]`,message:`tag "${c}" exceeds maximum length of 32`}),yS.test(c)||t.push({field:`tags[${a}]`,message:`tag "${c}" does not match pattern (lowercase alphanumeric and hyphens)`}),o.has(c)&&t.push({field:`tags[${a}]`,message:`duplicate tag "${c}"`}),o.add(c)}}return s.checksum!==void 0&&(typeof s.checksum!="string"||!bS.test(s.checksum))&&t.push({field:"checksum",message:'"checksum" must match pattern sha256:<64-hex-chars>'}),s.skill_path!==void 0&&(typeof s.skill_path!="string"?t.push({field:"skill_path",message:'"skill_path" must be a string'}):s.skill_path.length===0?t.push({field:"skill_path",message:'"skill_path" must not be empty'}):s.skill_path.length>256?t.push({field:"skill_path",message:'"skill_path" exceeds maximum length of 256'}):/\.\.|^\//.test(s.skill_path)&&t.push({field:"skill_path",message:'"skill_path" must not contain ".." or start with "/"'})),t}function wS(e,t){let s=e.length,i=t.length;if(s===0)return i;if(i===0)return s;let r=new Array(i+1),n=new Array(i+1);for(let o=0;o<=i;o++)r[o]=o;for(let o=1;o<=s;o++){n[0]=o;for(let a=1;a<=i;a++){let c=e[o-1]===t[a-1]?0:1;n[a]=Math.min(r[a]+1,n[a-1]+1,r[a-1]+c)}[r,n]=[n,r]}return r[i]}function kS(e,t,s=2){let i=[];for(let r of t){if(e===r)continue;let n=wS(e,r);n<=s&&i.push({existingName:r,distance:n})}return i.sort((r,n)=>r.distance-n.distance)}var xa=process.env.ASM_REGISTRY_URL??"https://raw.githubusercontent.com/luongnv89/asm-registry/main/index.json";function vS(){return process.env.ASM_REGISTRY_CACHE??fS(ki(),"registry-cache.json")}var SS=3600;function tt(e){if(e.startsWith("github:")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e==="~"||e==="."||e==="..")return!1;let t=(e.match(/\//g)||[]).length;if(t>1)return!1;if(t===1){let[s,i]=e.split("/");return/^[a-zA-Z0-9_-]+$/.test(s)&&/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(i)}return/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e)}function Ea(e){return tt(e)?e.includes("/"):!1}async function Pa(e){let t=await zf(xa,vS(),{ttl:SS,noCache:e?.noCache});if(!t)return null;if(typeof t!="object"||!Array.isArray(t.manifests)||typeof t.generated_at!="string")return L("registry: fetched index has invalid structure \u2014 discarding"),null;let s=[];for(let i of t.manifests){let r=_r(i);if(r.length>0){L(`registry: dropping invalid manifest entry (${i?.name??"unknown"}): ${r.map(n=>n.message).join(", ")}`);continue}if(!Qf.test(i.repository)){L(`registry: dropping manifest with unexpected repository URL: ${i.repository}`);continue}s.push(i)}return{generated_at:t.generated_at,manifests:s}}function $S(e,t){return t.manifests.filter(s=>s.name.toLowerCase()===e.toLowerCase())}function xS(e,t,s){return s.manifests.find(i=>i.author.toLowerCase()===e.toLowerCase()&&i.name.toLowerCase()===t.toLowerCase())??null}function Zf(e,t,s=5){return kS(e,t.manifests.map(r=>r.name),3).slice(0,s).map(r=>r.existingName)}async function jr(e,t){let s=await Pa(t);if(!s)return L("registry: failed to fetch index \u2014 skipping registry resolution"),{resolved:null,multipleMatches:[],suggestions:[]};if(Ea(e)){let[n,o]=e.split("/"),a=xS(n,o,s);if(a)return{resolved:{manifest:a,source:"registry"},multipleMatches:[],suggestions:[]};let c=Zf(o,s);return{resolved:null,multipleMatches:[],suggestions:c}}let i=$S(e,s);if(i.length===1)return{resolved:{manifest:i[0],source:"registry"},multipleMatches:[],suggestions:[]};if(i.length>1)return{resolved:null,multipleMatches:i,suggestions:[]};let r=Zf(e,s);return{resolved:null,multipleMatches:[],suggestions:r}}var sp=[{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\bcurl\b/,severity:"critical",permissionType:"network"},{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\bwget\b/,severity:"critical",permissionType:"network"},{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\bfetch\s*\(/,severity:"warning",permissionType:"network"},{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\baxios\b/,severity:"warning",permissionType:"network"},{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\bhttp\.request\b/,severity:"warning",permissionType:"network"},{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\bXMLHttpRequest\b/,severity:"warning",permissionType:"network"},{category:"External URLs",description:"Hardcoded URLs that may indicate data exfiltration or remote payload loading",pattern:/https?:\/\/(?!github\.com|localhost|127\.0\.0\.1|example\.com)/,severity:"warning",permissionType:"network"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bexec\s*\(/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bexecSync\b/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bchild_process\b/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bspawn\s*\(/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bBun\.spawn\b/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bshelljs\b/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\b(?:bash|sh|zsh)\s+-c\b/,severity:"critical",permissionType:"shell"},{category:"Dynamic code execution",description:"Patterns that execute dynamically constructed code at runtime",pattern:/\beval\s*\(/,severity:"critical",permissionType:"code-execution"},{category:"Dynamic code execution",description:"Patterns that execute dynamically constructed code at runtime",pattern:/\bnew\s+Function\b/,severity:"critical",permissionType:"code-execution"},{category:"Dynamic code execution",description:"Patterns that execute dynamically constructed code at runtime",pattern:/\bFunction\s*\(/,severity:"critical",permissionType:"code-execution"},{category:"Dynamic code execution",description:"Patterns that execute dynamically constructed code at runtime",pattern:/\bimport\s*\(\s*[^'"]/,severity:"warning",permissionType:"code-execution"},{category:"File system access",description:"Operations that read, write, or modify files on disk",pattern:/\bfs\.(?:write|append|unlink|rm|mkdir|rename)\b/,severity:"warning",permissionType:"filesystem"},{category:"File system access",description:"Operations that read, write, or modify files on disk",pattern:/\bwriteFile(?:Sync)?\b/,severity:"warning",permissionType:"filesystem"},{category:"File system access",description:"Operations that read, write, or modify files on disk",pattern:/\brm\s+-rf?\b/,severity:"critical",permissionType:"filesystem"},{category:"File system access",description:"Operations that read, write, or modify files on disk",pattern:/\bchmod\b/,severity:"warning",permissionType:"filesystem"},{category:"Embedded credentials",description:"Hardcoded secrets, API keys, tokens, or passwords",pattern:/\b(?:API_KEY|SECRET_KEY|ACCESS_TOKEN|PRIVATE_KEY)\s*[=:]/,severity:"critical"},{category:"Embedded credentials",description:"Hardcoded secrets, API keys, tokens, or passwords",pattern:/\bPASSWORD\s*[=:]/,severity:"critical"},{category:"Embedded credentials",description:"Hardcoded secrets, API keys, tokens, or passwords",pattern:/(?:sk|pk)[-_](?:live|test)[-_][a-zA-Z0-9]{20,}/,severity:"critical"},{category:"Environment variable access",description:"Reading environment variables which may contain secrets or configuration",pattern:/\bprocess\.env\b/,severity:"info",permissionType:"environment"},{category:"Environment variable access",description:"Reading environment variables which may contain secrets or configuration",pattern:/\bBun\.env\b/,severity:"info",permissionType:"environment"},{category:"Obfuscation patterns",description:"Base64 encoding, hex strings, or other obfuscation techniques",pattern:/\batob\s*\(/,severity:"warning"},{category:"Obfuscation patterns",description:"Base64 encoding, hex strings, or other obfuscation techniques",pattern:/\bBuffer\.from\s*\([^,]+,\s*['"]base64['"]\)/,severity:"warning"},{category:"Obfuscation patterns",description:"Base64 encoding, hex strings, or other obfuscation techniques",pattern:/\\x[0-9a-fA-F]{2}(?:\\x[0-9a-fA-F]{2}){5,}/,severity:"warning"}];async function ES(e,t){let s={owner:e,repo:t,profileUrl:`https://github.com/${e}`,reposUrl:`https://github.com/${e}?tab=repositories`,isOrganization:null,publicRepos:null,accountAge:null,fetchError:null};try{let i=await fetch(`https://api.github.com/users/${e}`,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"agent-skill-manager"},signal:AbortSignal.timeout(1e4)});if(!i.ok)return s.fetchError=`GitHub API returned ${i.status}`,s;let r=await i.json();if(s.isOrganization=r.type==="Organization",s.publicRepos=typeof r.public_repos=="number"?r.public_repos:null,typeof r.created_at=="string"){let n=new Date(r.created_at),o=new Date,a=Math.floor((o.getTime()-n.getTime())/(365.25*24*60*60*1e3)),c=Math.floor((o.getTime()-n.getTime())%(365.25*24*60*60*1e3)/(30.44*24*60*60*1e3));s.accountAge=a>0?`${a}y ${c}m`:`${c}m`}L(`security-audit: source analysis for ${e} -> repos=${s.publicRepos}, org=${s.isOrganization}, age=${s.accountAge}`)}catch(i){s.fetchError=i.message||"Failed to fetch GitHub profile",L(`security-audit: source analysis failed -> ${s.fetchError}`)}return s}function PS(e){let t=new Map;for(let{relPath:r,content:n}of e){let o=n.split(`
324
- `);for(let a=0;a<o.length;a++){let c=o[a],u=c.trim();for(let f of sp)if(f.pattern.test(c)){let d=f.category;t.has(d)||t.set(d,{description:f.description,matches:[]});let p=u.length>120?u.slice(0,120)+"...":u;t.get(d).matches.push({file:r,line:a+1,match:p,severity:f.severity})}}}let s=[];for(let[r,n]of t)s.push({category:r,description:n.description,matches:n.matches});let i={critical:0,warning:1,info:2};return s.sort((r,n)=>{let o=Math.min(...r.matches.map(c=>i[c.severity])),a=Math.min(...n.matches.map(c=>i[c.severity]));return o-a}),s}function CS(e){let t=new Map;for(let n of e)for(let o of n.matches)for(let a of sp)if(a.permissionType&&a.category===n.category&&a.pattern.test(o.match)){let c=a.permissionType;t.has(c)||t.set(c,{evidence:[],categories:new Set});let u=t.get(c);u.evidence.push({file:o.file,line:o.line,match:o.match}),u.categories.add(n.category);break}let s={filesystem:"Skill reads, writes, or modifies files on disk. Verify it only accesses intended paths.",shell:"Skill executes shell commands or spawns processes. This allows arbitrary system access.",network:"Skill makes network requests or downloads external content. Data may be sent to remote servers.","code-execution":"Skill dynamically constructs and executes code. This can bypass static analysis.",environment:"Skill reads environment variables, which may contain secrets or API keys."},i=[];for(let[n,o]of t)i.push({type:n,evidence:o.evidence,reason:s[n]});let r={shell:0,"code-execution":1,network:2,filesystem:3,environment:4};return i.sort((n,o)=>(r[n.type]??99)-(r[o.type]??99)),i}function IS(e,t,s){let i=0,r=0;for(let c of e)for(let u of c.matches)u.severity==="critical"&&i++,u.severity==="warning"&&r++;let n=t.some(c=>c.type==="shell"),o=t.some(c=>c.type==="code-execution"),a=t.some(c=>c.type==="network");return n&&a?{verdict:"dangerous",reason:"Skill has both shell execution and network access -- potential data exfiltration risk."}:o&&a?{verdict:"dangerous",reason:"Skill has dynamic code execution and network access -- potential remote code execution risk."}:i>=10?{verdict:"dangerous",reason:`${i} critical findings detected. High concentration of risky patterns.`}:n||o?{verdict:"warning",reason:n?"Skill executes shell commands. Review commands carefully before installing.":"Skill uses dynamic code execution. Review usage carefully."}:i>0?{verdict:"warning",reason:`${i} critical finding${i>1?"s":""} detected. Manual review recommended.`}:r>0?{verdict:"caution",reason:`${r} warning${r>1?"s":""} found. Generally acceptable but worth reviewing.`}:s&&s.publicRepos!==null&&s.publicRepos<3?{verdict:"caution",reason:"No code issues found, but the author has very few public repositories."}:{verdict:"safe",reason:"No suspicious patterns detected."}}var LS=new Set([".md",".txt",".rst",".adoc",".markdown"]),AS=new Set(["SKILL.md","README.md","readme.md","CHANGELOG.md","changelog.md","LICENSE","LICENSE.md","LICENSE.txt","CONTRIBUTING.md","contributing.md","CODE_OF_CONDUCT.md","security.md","SECURITY.md","SUPPORT.md","support.md","TODO.md","todo.md","ROADMAP.md","roadmap.md"]);function RS(e){let t=e.split("/").pop();if(AS.has(t))return!0;let s=t.includes(".")?`.${t.split(".").pop().toLowerCase()}`:"";return LS.has(s)}async function Me(e,t,s,i){L(`security-audit: scanning ${e}`);let n=(await xi(e)).filter(p=>!RS(p.relPath)),o=n.reduce((p,m)=>p+m.lineCount,0),a=null;s&&i&&(a=await ES(s,i));let c=PS(n),u=CS(c),{verdict:f,reason:d}=IS(c,u,a);return{scannedAt:new Date().toISOString(),skillName:t,skillPath:e,source:a,codeScans:c,permissions:u,totalFiles:n.length,totalLines:o,verdict:f,verdictReason:d}}var D=l,yt=56,NS={"Shell execution":"shell","Dynamic code execution":"code-execution","Network requests":"network","External URLs":"network","File system access":"filesystem","Environment variable access":"environment","Embedded credentials":"credentials","Obfuscation patterns":"obfuscation"},ep={critical:0,warning:1,info:2};function TS(e){switch(e){case"safe":return D.bgGreen(" SAFE ");case"caution":return D.bgCyan(" CAUTION ");case"warning":return D.bgYellow(" WARNING ");case"dangerous":return D.bgRed(" DANGEROUS ")}}function OS(e){switch(e){case"safe":return D.green;case"caution":return D.cyan;case"warning":return D.yellow;case"dangerous":return D.red}}function Kt(e){switch(e){case"critical":return D.red("!!");case"warning":return D.yellow(" !");case"info":return D.dim(" i")}}function Ca(e,t){return e.length>t?e.slice(0,t-3)+"...":e}function Br(e){return e.toLocaleString("en-US")}function ip(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function tp(e){return ip(e).length}function MS(e){let t=new Map;for(let s of e){let i=`${s.file}:${s.line}`,r=t.get(i);(!r||ep[s.severity]<ep[r.severity])&&t.set(i,s)}return Array.from(t.values())}function DS(e){let t=new Map;for(let s of e){let i=t.get(s.file);i||(i={file:s.file,entries:[]},t.set(s.file,i)),i.entries.push({line:s.line,match:s.match,severity:s.severity})}return Array.from(t.values())}function Gt(e){let t=[],s=TS(e.verdict),i=ip(s),r=` ${D.bold(e.skillName)}`,n=` ${e.skillName}`,o=yt-4,a=Math.max(1,o-n.length-i.length);if(t.push(""),t.push(D.dim(" +-- ")+D.bold("Security Audit")+D.dim(" "+"-".repeat(yt-19)+"+")),t.push(D.dim(" |")+r+" ".repeat(a)+s+D.dim("|")),t.push(D.dim(" |")+D.dim(` ${Br(e.totalFiles)} files | ${Br(e.totalLines)} lines`)+" ".repeat(Math.max(1,o-` ${Br(e.totalFiles)} files | ${Br(e.totalLines)} lines`.length))+D.dim("|")),t.push(D.dim(" +"+"-".repeat(yt-2)+"+")),e.source){let d=e.source;if(d.fetchError)t.push(` ${D.yellow("!")} Could not fetch profile: ${d.fetchError}`);else{let p=[];if(p.push(`${d.owner} ${d.isOrganization?D.cyan("(org)"):D.dim("(user)")}`),d.publicRepos!==null){let m=d.publicRepos,g=m<3?D.yellow(`${m} repos`):m<10?D.cyan(`${m} repos`):D.green(`${m} repos`);p.push(g)}d.accountAge&&p.push(d.accountAge),t.push(` ${D.dim("Author:")} ${p.join(D.dim(" | "))}`)}}if(t.push(""),e.codeScans.length===0)t.push(` ${D.green("*")} ${D.green("No suspicious patterns detected.")}`);else{let d=OS(e.verdict),p=e.verdict==="dangerous"||e.verdict==="warning"?Kt("critical"):e.verdict==="caution"?Kt("warning"):Kt("info");t.push(` ${p} ${d(e.verdictReason)}`);let m=0,g=0,h=0;for(let w of e.codeScans)for(let v of w.matches)v.severity==="critical"?m++:v.severity==="warning"?g++:h++;let y=[];m>0&&y.push(D.red(`${m} critical`)),g>0&&y.push(D.yellow(`${g} warning`)),h>0&&y.push(D.dim(`${h} info`));let b=e.permissions.map(w=>w.type),k=b.length>0?D.dim(`Perms: ${b.join(", ")}`):"";t.push(` ${y.join(D.dim(" | "))} ${k}`)}if(t.push(""),e.codeScans.length>0){t.push(` ${D.bold("Findings")}`),t.push(D.dim(" "+"=".repeat(yt-2)));for(let d of e.codeScans){let p=MS(d.matches),m=p.filter(O=>O.severity==="critical").length,g=p.filter(O=>O.severity==="warning").length,h=p.filter(O=>O.severity==="info").length,y=m>0?Kt("critical"):g>0?Kt("warning"):Kt("info"),b=[];m>0&&b.push(D.red(`${m} critical`)),g>0&&b.push(D.yellow(`${g} warning`)),h>0&&b.push(D.dim(`${h} info`));let k=NS[d.category],w=k?D.dim(`PERM: ${k}`):"",v=` ${y} ${D.bold(d.category)} (${b.join(", ")})`;if(w){let O=tp(v),S=tp(w),P=Math.max(2,yt-O-S);t.push(v+" ".repeat(P)+w)}else t.push(v);let x=DS(p),C=Math.min(24,Math.max(...x.map(O=>O.file.length))),A=0,E=3;for(let O of x){if(A>=E)break;let S=Ca(O.file,24),P=D.dim(S.padEnd(C));if(O.entries.length===1){let B=O.entries[0],te=Ca(B.match,50);t.push(` ${P} :${B.line} ${D.dim("--")} ${B.severity==="critical"?te:D.dim(te)}`),A++}else if(O.entries.length<=3){let B=O.entries.map(ce=>`:${ce.line}`).join(", "),te=Ca(O.entries[0].match,40);t.push(` ${P} ${B} ${D.dim("--")} ${D.dim(te)}`),A++}else{let te=O.entries.slice(0,3).map(Pe=>`:${Pe.line}`).join(", "),ce=O.entries.length-3;t.push(` ${P} ${te} ${D.dim(`(+${ce} more)`)}`),A++}}let _=x.length-Math.min(x.length,E);if(_>0){let O=p.length-x.slice(0,E).reduce((S,P)=>S+P.entries.length,0);O>0&&t.push(` ${D.dim(`... ${O} more in ${_} file${_>1?"s":""}`)}`)}t.push("")}}t.push(D.dim(" "+"=".repeat(yt-2)));let c=new Date(e.scannedAt),u=`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}-${String(c.getDate()).padStart(2,"0")} ${String(c.getHours()).padStart(2,"0")}:${String(c.getMinutes()).padStart(2,"0")}`,f=e.source&&!e.source.fetchError?`github.com/${e.source.owner}`:"";if(f){let d=Math.max(2,yt-2-u.length-f.length);t.push(D.dim(` ${u}${" ".repeat(d)}${f}`))}else t.push(D.dim(` ${u}`));return t.push(""),t.join(`
325
- `)}function Ia(e){return JSON.stringify(e,null,2)}var Ws="Relocate `README.md` out of the skill root so SKILL.md remains the sole top-level document (e.g., move it to `docs/README.md`).",qr=["name","description","version","license","author","creator","compatibility","allowed-tools","effort","tags","metadata"],rp=["add","analyze","audit","build","check","configure","convert","create","debug","deploy","detect","edit","evaluate","explain","export","extract","fetch","find","fix","format","generate","identify","improve","index","inspect","install","list","manage","migrate","optimize","parse","plan","prepare","publish","refactor","remove","rename","report","research","review","run","scaffold","scan","score","search","set","setup","show","summarize","sync","test","transform","translate","update","validate","verify","write"],FS=["confirm","confirmation","error","errors","fail","failure","caution","warning","prerequisite","prerequisites","requires","requirements","rollback","dry-run","dry run","safety","validate","validation","check","backup"],_S=["acceptance criteria","expected output","expected result","edge case","edge cases","test","tests","testing","verify","verification","assert","example input","example output","given","then"],jS=["reference","references","see","template","templates","script","scripts","helper","helpers","link"],BS=["when to use","quick start","overview","instructions","steps","workflow","phases","progressive"];function Ur(e){let t=e.split(`
326
- `);if(t.length===0||t[0].trim()!=="---")return{rawFrontmatter:null,body:e};for(let s=1;s<t.length;s++)if(t[s].trim()==="---"){let i=t.slice(1,s).join(`
327
- `),r=t.slice(s+1).join(`
328
- `);return{rawFrontmatter:i,body:r}}return{rawFrontmatter:t.slice(1).join(`
329
- `),body:""}}function La(e){return e?e.split(`
330
- `).length:0}function Aa(e){return e?e.split(/\s+/).map(t=>t.trim()).filter(Boolean).length:0}function qS(e,t=1){return(e.match(/^#{1,6}\s+\S/gm)||[]).length>=t}function Vr(e,t){let s=e.toLowerCase();return t.filter(i=>s.includes(i))}function US(e){return/```[\s\S]+?```/m.test(e)}function VS(e){return/^\s*[-*]\s+\S/m.test(e)||/^\s*\d+\.\s+\S/m.test(e)}function np(e,t,s,i){let r=[],n=[],o=0;s!==null?(o+=2,r.push("Has YAML frontmatter block.")):(r.push("SKILL.md has no YAML frontmatter."),n.push("Add a YAML frontmatter block delimited by `---` with at least `name` and `description` fields."));let a=!!(e.name&&e.name.trim()),c=!!(e.description&&e.description.trim());a?o+=1.5:(r.push("Missing required field: name."),n.push("Add `name:` to frontmatter (use the skill directory name).")),c?o+=1.5:(r.push("Missing required field: description."),n.push("Add a one-line `description:` to frontmatter."));let u=fe(e);u&&u!=="0.0.0"?o+=1:(r.push("Missing or default version."),n.push("Set `metadata.version` (or top-level `version`) using semver (e.g. 0.1.0).")),!!(e.author||e["metadata.author"]||e.creator||e["metadata.creator"])?o+=1:(r.push("Missing `author`."),n.push("Add an `author` field so users know who authored and maintains the skill.")),!!e.license?o+=1:(r.push("Missing `license`."),n.push("Add a `license` field (e.g. `license: MIT`)."));let m=t.trim().length>=20,g=qS(t,1);if(m?(o+=1,r.push("Body has meaningful content.")):(r.push("Body content is too short (<20 chars of instructions)."),n.push("Flesh out the markdown body with at least one paragraph of instructions for the agent.")),g?(o+=1,r.push("Body uses markdown headings.")):(r.push("Body has no markdown headings."),n.push("Add section headings (e.g. `## When to Use`, `## Instructions`) so the agent can navigate the skill quickly.")),i){let h=i.find(y=>y.toLowerCase()==="readme.md");h&&(r.push(`\`${h}\` found at skill root; move it to a subdirectory (e.g., \`docs/README.md\`).`),n.push(Ws))}return{id:"structure",name:"Structure & completeness",score:Math.round(o),max:10,findings:r,suggestions:n}}function op(e,t){let s=[],i=[],r=0,n=(e.description||"").trim();if(!n)return s.push("No description."),i.push("Write a one-sentence description that says specifically what the skill does and when to use it."),{id:"description",name:"Description quality",score:0,max:10,findings:s,suggestions:i};let o=Aa(n);s.push(`Description is ${o} words.`),o>=8&&o<=40?r+=4:o>=5&&o<8?(r+=2,i.push("Lengthen the description slightly so it names both the action and the trigger (aim for 8\u201320 words).")):o>=41&&o<=60?(r+=2,i.push("Trim the description \u2014 aim for under 40 words. Move the long version to the markdown body.")):o>60?(r+=0,i.push("Description is too long. Keep it under 40 words; put detail in the body.")):(r+=0,i.push("Description is too short. Aim for 8\u201320 words."));let a=n.split(/\s+/)[0]?.toLowerCase().replace(/[^\w-]/g,"");return!!(a&&(rp.includes(a)||rp.includes(a.replace(/s$/,""))))?(r+=3,s.push("Starts with an action verb.")):(s.push(`Does not start with a recognized action verb (got "${a??""}").`),i.push('Start the description with an imperative action verb (e.g. "Generate...", "Analyze...", "Review...").')),/\buse when\b|\btrigger\b|\bwhen\b|\bfor\b/i.test(n)||/\b(before|after|during)\b/i.test(n)?(r+=3,s.push("Mentions a trigger or use-case signal.")):(s.push("No explicit trigger / use-case phrase."),i.push('Name the trigger in the description \u2014 e.g. "Use when...", "for reviewing...", "before publishing...".')),{id:"description",name:"Description quality",score:Math.min(10,Math.round(r)),max:10,findings:s,suggestions:i}}function ap(e,t){let s=[],i=[],r=0,n=Vr(t,BS);n.length>=2?(r+=3,s.push(`Progressive disclosure cues present: ${n.slice(0,3).join(", ")}.`)):n.length===1?(r+=1,i.push('Add clearer section labels \u2014 e.g. "## When to Use" and "## Instructions" \u2014 to support progressive disclosure.')):i.push('Structure the body with "## When to Use" and "## Instructions" sections so the agent reads only what it needs.'),VS(t)?(r+=2,s.push("Uses lists or numbered steps.")):(s.push("No lists or steps detected."),i.push("Use bulleted or numbered steps to narrow the agent's degrees of freedom."));let o=US(t),a=/\bexample\b/i.test(t);o&&a?(r+=2,s.push("Includes example code block.")):o||a?(r+=1,i.push('Back up examples with fenced code blocks labelled under "## Example" so the agent sees concrete input/output.')):i.push('Add an "## Example" section with a fenced code block showing the desired output.');let c=(t.match(/^\s*[-*0-9.]*\s*(Do|Use|Run|Call|Check|Validate|Return|Emit|Write|Read|Ask|Confirm|Avoid|Never|Always)\b/gim)||[]).length;c>=3?(r+=2,s.push(`Uses imperative voice (${c} cues).`)):c>=1?(r+=1,i.push("Favor imperative voice (Do / Use / Avoid / Never) to narrow the agent's choices.")):i.push('Rewrite instructions in the imperative mood \u2014 e.g. "Run `git status` first" instead of "you might want to run".');let u=Aa(t);return u>=80&&u<=3e3?(r+=1,s.push(`Body length within healthy range (${u} words).`)):u<80?(s.push(`Body is very short (${u} words).`),i.push("Expand the instructions; an underspecified skill gives the agent too much freedom.")):(s.push(`Body is very long (${u} words).`),i.push("Split large content into referenced files; keep SKILL.md focused under ~3000 words.")),{id:"prompt-engineering",name:"Prompt engineering",score:Math.min(10,Math.round(r)),max:10,findings:s,suggestions:i}}function lp(e,t){let s=[],i=[],r=0,n=Aa(t);s.push(`Body is ${n} words.`),n>=120&&n<=1500?r+=4:n>=60&&n<120?(r+=2,i.push("Expand instructions slightly \u2014 too little context can push the agent to improvise.")):n>1500&&n<=3e3?(r+=2,i.push("Consider moving large sections into referenced files (e.g. `references/*.md`) and linking them instead of inlining.")):n>3e3&&(r+=0,i.push("Body is over 3000 words \u2014 split long content into referenced files or templates."));let o=Vr(t,jS);o.length>=2?(r+=3,s.push(`References external files or links (${o.slice(0,3).join(", ")}).`)):o.length===1?(r+=1,i.push('Link out to supporting files (e.g. "see `references/examples.md`") instead of inlining them.')):i.push('Offload verbose content to referenced files and link to them ("see `./templates/x.md`").');let c=(t.match(/```[\s\S]+?```/g)||[]).filter(u=>La(u)>60);return c.length===0?(r+=2,s.push("No oversized code blocks.")):(s.push(`${c.length} code block(s) longer than 60 lines.`),i.push("Move large code blocks into referenced template files; link to them from SKILL.md.")),/\btoken\b|\bbudget\b|\bcontext window\b/i.test(t)&&(r+=1,s.push("Mentions tokens/budget/context window.")),{id:"context-efficiency",name:"Context efficiency",score:Math.min(10,Math.round(r)),max:10,findings:s,suggestions:i}}function cp(e,t){let s=[],i=[],r=0,n=Vr(t,FS);n.length>=4?(r+=4,s.push(`Covers multiple safety cues (${n.slice(0,4).join(", ")}).`)):n.length>=2?(r+=2,s.push(`Mentions a few safety cues: ${n.join(", ")}.`),i.push("Add explicit error-handling and confirmation steps so the agent knows how to recover from failures.")):n.length===1?(r+=1,i.push('Expand the safety section \u2014 include prerequisites, validation steps, and what to do "on error".')):i.push("Describe prerequisites, confirmation prompts, and error-handling steps to reduce blast radius.");let o=/\b(rm\s|delete|remove|drop|force|overwrite|destructive)\b/i.test(t),a=/\bconfirm\b|\bdry-?run\b|\bare you sure\b|\bbackup\b/i.test(t);return o&&a?(r+=3,s.push("Destructive actions paired with confirmation/dry-run.")):o?(s.push("References destructive actions without explicit confirmation/dry-run."),i.push("Pair any destructive command with an explicit confirmation prompt, dry-run flag, or backup step.")):r+=1.5,/\bprerequisit/i.test(t)||/\brequire/i.test(t)||/\bdepend/i.test(t)?(r+=3,s.push("Declares prerequisites or requirements.")):(s.push("No prerequisites / requirements section."),i.push('Add a "## Prerequisites" block listing required tools, credentials, and environment state.')),{id:"safety",name:"Safety & guardrails",score:Math.min(10,Math.round(r)),max:10,findings:s,suggestions:i}}function up(e,t){let s=[],i=[],r=0,n=Vr(t,_S);return n.length>=4?(r+=5,s.push(`Many testability cues present (${n.slice(0,4).join(", ")}).`)):n.length>=2?(r+=3,s.push(`Some testability cues: ${n.join(", ")}.`),i.push('Add an "## Acceptance Criteria" block listing verifiable outputs or checklist items.')):n.length===1?(r+=1,i.push('Add concrete "expected output" examples so the agent can self-check.')):i.push('Add a "## Acceptance Criteria" section with testable statements (e.g. "produces a JSON report with overall_score").'),/expected\s+(output|result|response)/i.test(t)?(r+=3,s.push("Describes expected output/result.")):i.push('Include an "Expected output" example so reviewers and the agent can verify correctness.'),/\bedge case|gotcha|pitfall|limitation/i.test(t)?(r+=2,s.push("Mentions edge cases or limitations.")):i.push('Add a short "Edge cases" list to describe inputs the skill should reject or handle carefully.'),{id:"testability",name:"Testability",score:Math.min(10,Math.round(r)),max:10,findings:s,suggestions:i}}var KS=new Set(["MIT","MIT-0","Apache-2.0","Apache-2.0 WITH LLVM-exception","BSD-2-Clause","BSD-3-Clause","ISC","Unlicense","0BSD","Zlib","BSL-1.0","CC0-1.0","LGPL-2.1-only","LGPL-2.1-or-later","LGPL-3.0-only","LGPL-3.0-or-later","MPL-2.0","MPL-2.0-no-copyleft-exception","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0-only","GPL-3.0-or-later","AGPL-3.0-only","AGPL-3.0-or-later","Artistic-2.0","EPL-1.0","EPL-2.0","CDDL-1.0","CDDL-1.1","CPAL-1.0","ECL-2.0","EFL-2.0","Nokia-1.0a","OFL-1.1","SIL-OpenFont-1.1","VSLAM-1.0","WTFPL","ZPL-2.1","NCSA","PostgreSQL","X11","JSON","CC-BY-4.0","CC-BY-SA-4.0","CC-BY-NC-4.0","CC-BY-NC-SA-4.0","CC-BY-ND-4.0","CC-BY-NC-ND-4.0","Fair","NTP","AFL-3.0","APAFML","OLDAP-2.8"]);function dp(e,t,s){let i=[],r=[],n=0,o=(e.license||"").trim(),a=!!o,u=!!s?.find(d=>d.toLowerCase()==="license"||d.toLowerCase()==="license.md"||d.toLowerCase()==="license.txt"),f="missing";switch(a?KS.has(o)?f="recognised":f="unrecognised":u&&(f="unrecognised"),f){case"recognised":{n=u?10:5,i.push(`License declared: \`${o}\` (SPDX recognised).`),u?i.push("LICENSE file present at skill root."):i.push("No LICENSE file found \u2014 consider adding one for clarity.");break}case"unrecognised":{n=2,a&&i.push(`License declared as \`${o}\` but not in the SPDX list.`),u&&!a&&i.push("LICENSE file present but no frontmatter license field."),r.push("Use a standard SPDX licence identifier (e.g. `MIT`, `Apache-2.0`, `GPL-3.0-only`) so tooling can verify redistributability.");break}case"missing":{n=0,i.push("No license declared."),r.push("Add a `license` field to frontmatter (e.g. `license: MIT`) so users know the redistribution terms."),u&&r.push("A LICENSE file exists \u2014 add the corresponding `license:` frontmatter field to match it.");break}}return{id:"license",name:"License verification",score:Math.min(10,Math.round(n)),max:10,findings:i,suggestions:r,licenseStatus:f}}function fp(e,t){let s=[],i=[],r=0,n=(e.name||"").trim();if(n){let c=/^[a-z][a-z0-9-]*$/.test(n),u=n.length<=40;c&&u?(r+=4,s.push(`name "${n}" follows kebab-case convention.`)):(c||(s.push(`name "${n}" is not lowercase kebab-case.`),i.push(`Rename to lowercase kebab-case (e.g. "${n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}").`)),u||s.push(`name is ${n.length} chars; keep it <= 40.`))}else i.push("Add a kebab-case `name` (e.g. `my-skill`).");let o=t.match(/^#{1,6}\s+(.+)$/gm)||[];return o.length>0&&(o.filter(f=>/^#{1,6}\s+([A-Z][a-z]+|Use|How|When|Workflow|Instructions|Examples|Steps|Acceptance)/.test(f)).length/o.length>=.5?(r+=3,s.push("Most headings use action/imperative labels.")):(r+=1,i.push("Rename body headings to action-oriented labels (e.g. `## Instructions`, `## When to Use`)."))),/(?:\s\s|\bTODO\b|\bFIXME\b|\?{2,})/.test(e.description||"")?i.push("Clean up description \u2014 remove TODOs, FIXMEs, double spaces, or trailing punctuation."):(r+=2,s.push("Description looks clean (no TODO/FIXME/stray noise).")),{id:"naming",name:"Naming & conventions",score:Math.min(10,Math.round(r)),max:10,findings:s,suggestions:i}}import{readFile as Na,writeFile as YS,stat as vp,copyFile as zS,readdir as XS}from"fs/promises";import{join as Sp,resolve as $p,basename as Ta,isAbsolute as xp}from"path";import{readFile as GS,readdir as pp,stat as mp}from"fs/promises";import{join as hp,isAbsolute as gp,resolve as yp}from"path";var HS=[{category:"email",pattern:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/gi},{category:"phone",pattern:/\b(?:\+?1[-.]?)?\(?\d{3}\)?[\s-]?\d{3}[-.]?\d{4}\b/g},{category:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g},{category:"address",pattern:/\b\d{1,5}\s+(?:[A-Z][a-z]+\s+){1,3}(?:Street|St|Avenue|Ave|Boulevard|Blvd|Drive|Dr|Lane|Ln|Road|Rd|Court|Ct|Place|Pl|Way|Circle|Cir)\b/gi},{category:"license",pattern:/\b[A-Z]{2}\d{6,8}\b/g}];async function bp(e){let t=[],s=[],i=10,r=new Set,n=gp(e)?e:yp(e),o=new Set([".md",".txt",".json",".yaml",".yml",".sh",".py",".bash",".js",".ts",".jsx",".tsx",".html",".css",".log"]);async function a(c){let u;try{u=await pp(c)}catch{return}for(let f of u){let d=hp(c,f),p;try{p=await mp(d)}catch{continue}if(p.isDirectory()){if(f.startsWith(".")||f==="node_modules")continue;await a(d)}else if(p.isFile()){let m=f.includes(".")?"."+f.split(".").pop():"";if(!o.has(m))continue;try{let h=(await GS(d,"utf-8")).split(`
331
- `),y=!1,b=!1;for(let k of HS){k.pattern.lastIndex=0,y=!1,b=!1;for(let w=0;w<h.length;w++){let v=h[w];if(v.trim()==="---"){y=!y;continue}if(v.trim().startsWith("```")){b=!b;continue}if(y||b)continue;let x=v.match(k.pattern);if(x&&x.length>0){r.has(k.category)||(r.add(k.category),i-=2);let C=d.replace(n+"/","");t.push(`[${k.category}] ${C}:${w+1} \u2014 found ${x.length} match(es)`)}}}}catch{}}}}return await a(n),r.size===0?t.push("No PII detected in skill files."):(t.push(`PII detected in ${r.size} category/categories: ${[...r].join(", ")}.`),s.push("Remove or redact personal data from examples, transcripts, and fixture files before publishing.")),{id:"pii",name:"PII detection",score:Math.max(0,Math.min(10,Math.round(i))),max:10,findings:t,suggestions:s}}var JS=new Set([".sh",".bash",".py"]),wp={".sh":{command:"shellcheck",args:["--format=json1"],language:"bash/shell"},".bash":{command:"shellcheck",args:["--format=json1"],language:"bash/shell"},".py":{command:"python3",args:["-m","py_compile"],language:"python"}};async function WS(e,t){let s=wp[t];if(!s)return null;try{let{runCommand:i}=await import("./spawn-JDSII5L3.js"),r=await i([s.command,...s.args,e]);if(r.exitCode!==0){if(t===".py"){let n=r.stderr.split(`
332
- `),o=[],a=0;for(let c of n){let u=c.match(/File "([^"]+)", line (\d+)/);if(u){a=parseInt(u[2],10);continue}let f=c.match(/^\s*(SyntaxError|IndentationError|ImportError|AttributeError|TypeError|ValueError):\s*(.+)$/);f&&(o.push({file:e,line:a||0,severity:"error",message:`${f[1]}: ${f[2].trim()}`}),a=0)}return o}try{let n=JSON.parse(r.stderr),o=[];if(Array.isArray(n)){for(let a of n)if(a&&typeof a=="object"){let c=a;o.push({file:e,line:Number(c.line)||0,severity:c.level==="error"||c.level==="e"?"error":c.level==="warning"||c.level==="w"?"warning":"info",message:c.message||"Unknown issue"})}}return o}catch{return[{file:e,line:0,severity:"warning",message:`Linter exited with code ${r.exitCode}: ${r.stderr.slice(0,200)}`}]}}return[]}catch(i){return i&&typeof i=="object"&&"code"in i&&i.code==="ENOENT",null}}async function kp(e){let t=[],s=[],i=10,r=0,n=!1,o=[],a=gp(e)?e:yp(e);async function c(u){let f;try{f=await pp(u)}catch{return}for(let d of f){let p=hp(u,d),m;try{m=await mp(p)}catch{continue}if(m.isDirectory()){if(d.startsWith(".")||d==="node_modules")continue;await c(p)}else if(m.isFile()){let g=d.includes(".")?"."+d.split(".").pop():"";if(!JS.has(g))continue;let h=p.replace(a+"/",""),y=await WS(p,g);if(y===null){n=!0;let b=wp[g]?.language||g;t.push(`[${b}] ${h}: lint skipped \u2014 linter not available`)}else{r++,o.push(...y);for(let b of y){let k=b.severity.toUpperCase();t.push(`[${k}] ${h}:${b.line||"*"} \u2014 ${b.message}`)}}}}}if(await c(a),r===0&&!n)t.push("No bundled scripts found to lint.");else if(n&&r===0)t.push("No bundled scripts found and linter is unavailable.");else if(o.length===0)t.push(`Linted ${r} script(s) \u2014 no issues found.`);else{let u=o.filter(d=>d.severity==="error").length,f=o.filter(d=>d.severity==="warning").length;i=Math.max(0,10-u*3-f),t.push(`Found ${u} error(s) and ${f} warning(s) across ${r} script(s).`),s.push("Fix lint errors in bundled scripts \u2014 quoting issues, undefined variables, and syntax errors can cause runtime failures.")}return{id:"script-lint",name:"Script linting",score:Math.max(0,Math.min(10,Math.round(i))),max:10,findings:t,suggestions:s}}async function Ht(e){let{content:t,skillPath:s,skillMdPath:i,rootEntries:r}=e,n=W(t),{rawFrontmatter:o,body:a}=Ur(t),c=[np(n,a,o,r),op(n,a),ap(n,a),lp(n,a),cp(n,a),up(n,a),dp(n,a,r),fp(n,a)],[u,f]=await Promise.all([bp(s),kp(s)]),d=[...c,u,f];if(n.name&&Ta(s)===n.name){let w=d.find(v=>v.id==="naming");w.score<w.max&&(w.score=Math.min(w.max,w.score+1),w.findings.push("Directory name matches frontmatter `name`."))}let p=d.reduce((w,v)=>w+v.score,0),m=d.reduce((w,v)=>w+v.max,0),g=Math.round(p/m*100),h="F";g>=90?h="A":g>=80?h="B":g>=65?h="C":g>=50&&(h="D");let y=[];d.find(w=>w.id==="structure")?.suggestions.includes(Ws)&&y.push(Ws);let k=[...d].sort((w,v)=>w.score/w.max-v.score/v.max);for(let w of k){for(let v of w.suggestions){if(y.length>=3)break;y.includes(v)||y.push(v)}if(y.length>=3)break}return{skillPath:s,skillMdPath:i,evaluatedAt:new Date().toISOString(),categories:d,overallScore:g,grade:h,topSuggestions:y,frontmatter:n}}async function Oa(e){let t=xp(e)?e:$p(e),s;try{s=await vp(t)}catch{throw new Error(`Skill path does not exist: ${t}`)}let i,r;if(s.isFile())return i=t,r=await Na(i,"utf-8"),Ht({content:r,skillPath:Ta(t)==="SKILL.md"?Ta(t):t,skillMdPath:i});if(!s.isDirectory())throw new Error(`Skill path is not a directory or file: ${t}`);i=Sp(t,"SKILL.md");try{r=await Na(i,"utf-8")}catch{throw new Error(`SKILL.md not found in ${t}. Run "asm init" to create one.`)}let n;try{n=await XS(t)}catch{n=void 0}return Ht({content:r,skillPath:t,skillMdPath:i,rootEntries:n})}function ZS(e){return e<=20?"low":e<=80?"medium":e<=250?"high":"max"}function QS(e){let t=e.split(`
333
- `),s=[],i=[],r=0;for(;r<t.length;){let u=t[r];if(!u.trim()){r++;continue}let d=u.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);if(!d)return{newFrontmatter:e,changed:!1};let p=d[1],m=d[2];if(m===""||m===">"||m==="|"){let g=[u];for(r++;r<t.length;){let h=t[r];if(h.trim()===""){g.push(h),r++;continue}if(/^\s+/.test(h))g.push(h),r++;else break}i.push({key:p,text:g.join(`
334
- `)})}else s.push({key:p,text:u}),r++}let n=u=>{let f=qr.indexOf(u);return f===-1?qr.length+1:f},o=[...s].sort((u,f)=>{let d=n(u.key),p=n(f.key);return d!==p?d-p:s.indexOf(u)-s.indexOf(f)}),a=o.some((u,f)=>u!==s[f]);return{newFrontmatter:[...o.map(u=>u.text),...i.map(u=>u.text)].join(`
335
- `),changed:a}}function Ep(e,t={}){let s=[],i=[],r=e.replace(/\r\n/g,`
336
- `);r!==e&&s.push({id:"normalise-line-endings",description:"Convert CRLF line endings to LF."});let n=r.split(`
337
- `),o=n.map(y=>y.replace(/[ \t]+$/g,""));o.some((y,b)=>y!==n[b])&&s.push({id:"strip-trailing-whitespace",description:"Strip trailing whitespace from lines."}),r=o.join(`
338
- `);let{rawFrontmatter:a,body:c}=Ur(r),u=W(r);if(a===null)return i.push({id:"missing-frontmatter",description:"SKILL.md has no frontmatter \u2014 not auto-fixable (requires author decisions)."}),{newContent:r,applied:s,skipped:i};let f=a;if(u.version||u["metadata.version"]||(f=Ra(f,"version","0.1.0"),s.push({id:"add-missing-version",description:"Add `version: 0.1.0`."})),!!!(u.author||u["metadata.author"]||u.creator||u["metadata.creator"])){let y=t.gitAuthor?.trim();y?(f=Ra(f,"author",y),s.push({id:"add-missing-author",description:`Add \`author: ${y}\` from git config.`})):i.push({id:"add-missing-author",description:"Missing `author` \u2014 no git user.name found to fill in safely."})}if(!u.effort){let y=ZS(La(c));f=Ra(f,"effort",y),s.push({id:"infer-missing-effort",description:`Infer \`effort: ${y}\` from body size.`})}u.description||i.push({id:"missing-description",description:"Missing `description` \u2014 content-level fix, left to the author."});let m=QS(f);m.changed&&(s.push({id:"reorder-frontmatter",description:"Reorder frontmatter fields to canonical order."}),f=m.newFrontmatter);let g=c.replace(/^\n+/,""),h=`---
339
- ${f.replace(/^\n+|\n+$/g,"")}
177
+ ./relative/path/to/skill`);let r=e.slice(7),s=r.indexOf("#"),o,n=null,a=null;if(s!==-1){o=r.slice(0,s);let p=r.slice(s+1);if(!p)throw new Error("Invalid source: ref cannot be empty after #");let f=p.indexOf(":");if(f!==-1){if(n=p.slice(0,f),!n)throw new Error("Invalid source: ref cannot be empty before :");a=p.slice(f+1)||null}else n=p}else{let p=r.indexOf(":");p!==-1?(o=r.slice(0,p),a=r.slice(p+1)||null):o=r}let l=o.indexOf("/");if(l===-1)throw new Error(`Invalid source: format must be github:owner/repo. Got: "${e}"`);let c=o.slice(0,l),d=o.slice(l+1);if(!c)throw new Error("Invalid source: owner cannot be empty");if(!d)throw new Error("Invalid source: repo cannot be empty");if(!Ru.test(c))throw new Error(`Invalid source: owner contains invalid characters: "${c}". Allowed: [a-zA-Z0-9_-]`);if(!Eu.test(d))throw new Error(`Invalid source: repo contains invalid characters: "${d}". Allowed: [a-zA-Z0-9._-]`);let u={owner:c,repo:d,ref:n,subpath:a,cloneUrl:`https://github.com/${c}/${d}.git`,sshCloneUrl:`git@github.com:${c}/${d}.git`};return P(`install: parsed source -> owner=${c} repo=${d} ref=${n} subpath=${a}`),u}function _t(e){return!!e&&e.split(/[/\\]/).includes("..")}function de(e,t){if(_t(e.subpath)||_t(e.ref))throw new Error(`Invalid source: the subpath in "${t}" escapes the repository.`)}function Ee(e,t,r){let s=jt(e),o=jt(t);if(o!==s&&!o.startsWith(s+Pu))throw new Error(`Invalid source: the subpath in "${r}" escapes the repository.`)}async function _e(e){if(e.subpath!==null||!e.ref||!e.ref.includes("/"))return e;try{let{stdout:t}=await ut("git",["ls-remote","--heads","--tags",e.cloneUrl],{timeout:15e3}),r=new Set;for(let o of t.split(`
178
+ `)){let n=o.match(/\trefs\/(?:heads|tags)\/(.+)$/);n&&r.add(n[1])}let s=e.ref.split("/");for(let o=1;o<s.length;o++){let n=s.slice(0,o).join("/");if(r.has(n)){let a=s.slice(o).join("/");return P(`install: resolved ref="${n}" subpath="${a}"`),{...e,ref:n,subpath:a||null}}}}catch(t){P(`install: ls-remote failed, treating entire ref as branch: ${t}`)}return e}function ue(e){if(!e)throw new Error("Invalid skill name: name cannot be empty");if(e.includes("\0"))throw new Error("Invalid skill name: contains unsafe characters (null byte)");if(e.includes(".."))throw new Error("Invalid skill name: contains unsafe characters (..)");if(e.includes("/")||e.includes("\\"))throw new Error("Invalid skill name: contains unsafe characters (path separator)");if(e.startsWith("."))throw new Error("Invalid skill name: must not start with a dot");if(e.length>Ti)throw new Error(`Invalid skill name: exceeds maximum length of ${Ti} characters`);if(!Iu.test(e))throw new Error(`Invalid skill name: "${e}" does not match allowed pattern [a-zA-Z0-9][a-zA-Z0-9._-]*`);return e}function Nr(e){let t=e.split(/[/\\]/).filter(Boolean),r=t.length>0?t[t.length-1]:e;return ue(r)}function Os(e,t=Nr){let r=new Map;for(let s of e){let o=t(s),n=r.get(o);n?n.push(s):r.set(o,[s])}return[...r.entries()].filter(([,s])=>s.length>1).map(([s,o])=>({name:s,paths:o}))}async function ve(){try{await ut("git",["--version"]),P("install: git available")}catch{throw new Error("git is required for installing skills. Install git from https://git-scm.com")}}function Mi(e){if(e.killed)return!1;let t=(e.stderr||e.message||"").toLowerCase();return t.includes("authentication failed")||t.includes("could not read username")||t.includes("repository not found")||t.includes("returned error: 403")||t.includes("returned error: 401")||t.includes("terminal prompts disabled")||t.includes("permission denied")}function Lr(e){return e.killed?"Clone timed out after 60 seconds":`Clone failed: ${e.stderr||e.message}`}async function Ts(e,t,r){if(t!==null&&/^[0-9a-f]{40}$/i.test(t))return await ut("git",["clone","--no-checkout",e,r],{timeout:6e4}),await ut("git",["checkout",t],{cwd:r,timeout:3e4}),r;let o=["clone","--depth","1"];return t&&o.push("--branch",t),o.push(e,r),await ut("git",o,{timeout:6e4}),r}async function Se(e,t="auto"){P(`install: cloning ${e.owner}/${e.repo}${e.ref?` (ref: ${e.ref})`:""} (transport: ${t})`);let r=await Ci(ke(Ai(),"asm-install-"));if(t==="ssh"||t==="https"){let s=t==="ssh"?e.sshCloneUrl:e.cloneUrl;try{return await Ts(s,e.ref,r)}catch(o){await z(r);let n=o;throw new Error(Lr(n),{cause:o})}}try{return await Ts(e.cloneUrl,e.ref,r)}catch(s){if(!Mi(s))throw await z(r),new Error(Lr(s),{cause:s});P("install: HTTPS clone failed with auth error, retrying with SSH..."),await z(r);let o=await Ci(ke(Ai(),"asm-install-"));try{return await Ts(e.sshCloneUrl,e.ref,o)}catch(n){throw await z(o),new Error(`Clone failed with both transports:
179
+ HTTPS: ${Lr(s)}
180
+ SSH: ${Lr(n)}`,{cause:n})}}}async function pe(e){let t=ke(e,"SKILL.md"),r;try{r=await Ar(t,"utf-8")}catch{throw new Error("Not a valid skill: SKILL.md not found in repository root")}let s=q(r),o=e.split(/[/\\]/).pop()||"unknown",n=s.name||o,a=ae(s);return P(`install: validated skill "${n}" v${a}`),{name:n,version:a,description:(s.description||"").replace(/\s*\n\s*/g," ").trim(),effort:s.effort||s["metadata.effort"]||void 0}}async function Ue(e,t=5){let r=[];try{let o=await Ar(ke(e,"SKILL.md"),"utf-8"),n=q(o);r.push({relPath:"",name:n.name||Oi(e),version:ae(n),description:(n.description||"").replace(/\s*\n\s*/g," ").trim(),effort:n.effort||n["metadata.effort"]||void 0,license:(n.license||"").trim(),creator:(n["metadata.creator"]||"").trim(),compatibility:(n.compatibility||"").trim(),allowedTools:ys(n),tags:Rt(n),dependencies:Qe(n),modelInvocable:Et(n),userInvocable:It(n),tokenCount:Ce(o)})}catch{}async function s(o,n,a){let l;try{l=await ku(o)}catch{return}for(let c of l){if(c===".git"||c==="node_modules")continue;let d=ke(o,c);try{if(!(await Ni(d)).isDirectory())continue}catch{continue}let u=n?`${n}/${c}`:c,p=a+1,f=ke(d,"SKILL.md");try{let m=await Ar(f,"utf-8"),g=q(m);r.push({relPath:u,name:g.name||c,version:ae(g),description:(g.description||"").replace(/\s*\n\s*/g," ").trim(),effort:g.effort||g["metadata.effort"]||void 0,license:(g.license||"").trim(),creator:(g["metadata.creator"]||"").trim(),compatibility:(g.compatibility||"").trim(),allowedTools:ys(g),tags:Rt(g),dependencies:Qe(g),modelInvocable:Et(g),userInvocable:It(g),tokenCount:Ce(m)})}catch{p<t&&await s(d,u,p)}}}return await s(e,"",0),r.sort((o,n)=>o.name.localeCompare(n.name)),r}async function Fi(e,t=ut){let r=ke(e,"scripts"),s=ke(r,"package.json");try{await Ns(s)}catch{P(`install: no scripts/package.json in ${e}; skipping npm install`);return}P(`install: installing script dependencies in ${r}`);try{await t("npm",["install"],{cwd:r,timeout:12e4})}catch(o){let n=o;throw new Error(`Installed skill, but failed to install dependencies in scripts/: ${n.stderr||n.message}`,{cause:o})}}var Lu=[{category:"Shell commands",pattern:/\b(bash|sh\s+-c)\b/},{category:"Shell commands",pattern:/\bexec\(/},{category:"Shell commands",pattern:/\bchild_process\b/},{category:"Shell commands",pattern:/\bBun\.spawn\b/},{category:"Code execution",pattern:/\beval\(/},{category:"Code execution",pattern:/\bFunction\(/},{category:"Code execution",pattern:/\bnew\s+Function\b/},{category:"Credentials",pattern:/\b(API_KEY|SECRET|TOKEN|PASSWORD)\s*[=:]/},{category:"External URLs",pattern:/https?:\/\//}];async function Bt(e){let t=[],r=await vr(e);for(let{relPath:s,content:o}of r){let n=o.split(`
181
+ `);for(let a=0;a<n.length;a++)for(let{category:l,pattern:c}of Lu)if(c.test(n[a])){let d=n[a].trim();t.push({category:l,file:s,line:a+1,match:d.length>100?d.slice(0,100)+"\u2026":d})}}return t}var Au=["Shell commands","Code execution","Credentials"],Tu=["External URLs"];function Vt(e){return e.some(t=>Au.includes(t.category))?"high":e.some(t=>Tu.includes(t.category))?"medium":"safe"}async function pt(e){let t=e.source.isLocal?`local:${e.source.localPath}`:`github:${e.source.owner}/${e.source.repo}${e.source.ref?`#${e.source.ref}`:""}${e.source.subpath?`:${e.source.subpath}`:""}`;if(e.force)try{await Ns(e.targetDir),await Tr(e.targetDir,{recursive:!0,force:!0})}catch{}let r=e.sourceDir;try{await vu(r,e.targetDir,{recursive:!0})}catch(l){let c=l instanceof Error?l.message:String(l);throw new Error(`Failed to install: ${c}`,{cause:l})}let s=ke(e.targetDir,".git");try{await Tr(s,{recursive:!0,force:!0})}catch{}P(`install: copied files to ${e.targetDir}`);let o=ke(e.targetDir,"SKILL.md");try{await Ns(o)}catch{throw new Error("Installation verification failed: SKILL.md not found at target")}await Fi(e.targetDir);let n=await Ar(o,"utf-8"),a=q(n);return{success:!0,path:e.targetDir,name:a.name||e.skillName,version:ae(a),provider:e.providerLabel,source:t}}async function Gt(e,t){let r=await pt(e);for(let s of t){if(s.name===e.providerName)continue;let o=e.scope==="project"?s.project:s.global,n=Q(o),a=ke(n,e.skillName);await $u(n,{recursive:!0});try{if((await Su(a)).isSymbolicLink())await Tr(a);else{P(`install: skipping ${a} \u2014 existing non-symlink directory`);continue}}catch{}let l=xu(n,e.targetDir);await Ae(l,a),P(`install: symlinked ${a} -> ${l}`)}return r.provider=`All (${t.map(s=>s.label).join(", ")})`,r}async function z(e){try{await Tr(e,{recursive:!0,force:!0})}catch{}}import{execFile as _u}from"child_process";import{promisify as Uu}from"util";import{readFile as Bu,access as _s}from"fs/promises";import{existsSync as Vu}from"fs";import{join as Be,dirname as Gu}from"path";var Ms=class{selected;cursor;scrollOffset;pageSize;itemCount;filter;searchActive;filteredMap;constructor(t,r){this.selected=t.map(s=>s.checked),this.cursor=1,this.scrollOffset=0,this.pageSize=r,this.itemCount=t.length,this.filter="",this.searchActive=!1,this.filteredMap=t.map((s,o)=>o)}get totalRows(){return this.filteredMap.length+1}applyFilter(t){if(this.filter==="")this.filteredMap=t.map((r,s)=>s);else{let r=this.filter.toLowerCase();this.filteredMap=[];for(let s=0;s<t.length;s++)(t[s].label.toLowerCase()+" "+(t[s].hint?.toLowerCase()??"")).includes(r)&&this.filteredMap.push(s)}this.cursor>=this.totalRows&&(this.cursor=Math.max(0,this.totalRows-1)),this.scrollOffset>0&&this.scrollOffset>=this.totalRows&&(this.scrollOffset=Math.max(0,this.totalRows-this.pageSize))}cursorToOriginalIndex(){return this.cursor===0?-1:this.filteredMap[this.cursor-1]??-1}toggleCurrent(){if(this.cursor===0)this.toggleAll();else{let t=this.cursorToOriginalIndex();t>=0&&(this.selected[t]=!this.selected[t])}}toggleAll(){let t=this.filteredMap,s=!t.every(o=>this.selected[o]);for(let o of t)this.selected[o]=s}moveUp(){this.cursor>0?this.cursor--:this.cursor=this.totalRows-1,this.adjustScroll()}moveDown(){this.cursor<this.totalRows-1?this.cursor++:this.cursor=0,this.adjustScroll()}getSelectedIndices(){let t=[];for(let r=0;r<this.selected.length;r++)this.selected[r]&&t.push(r);return t}getVisibleRange(){let t=this.scrollOffset,r=Math.min(this.scrollOffset+this.pageSize,this.totalRows);return{start:t,end:r}}adjustScroll(){this.cursor<this.scrollOffset?this.scrollOffset=this.cursor:this.cursor>=this.scrollOffset+this.pageSize&&(this.scrollOffset=this.cursor-this.pageSize+1)}};function Nu(e,t,r){let s=[];if(e.searchActive||e.filter!==""){let d=i.cyan("/"),u=e.filter,p=e.searchActive?i.cyan("\u2588"):"";s.push(` ${d}${u}${p}`),e.filteredMap.length===0&&s.push(i.dim(" No matches found")),s.push("")}let{start:o,end:n}=e.getVisibleRange();o>0&&s.push(i.dim(` ... ${o} more above`));for(let d=o;d<n;d++){let p=d===e.cursor?i.cyan(">"):" ";if(d===0){let f=e.filteredMap,g=f.length>0&&f.every(y=>e.selected[y])?i.green("[*]"):"[ ]",h=e.filter!==""?`Select All Matching (${e.filteredMap.length})`:"Select All / Deselect All";s.push(`${p} ${g} ${i.bold(h)}`)}else{let f=e.filteredMap[d-1],m=t[f],h=e.selected[f]?i.green("[*]"):"[ ]",y=`${p} ${h} `,b=7,$=i.bold(m.label),v=m.label.length;if(m.hint){let S=r-b-v-2;if(S>10){let C=Ds(m.hint,S);s.push(`${y}${$} ${i.dim(C)}`)}else{let C=Ds(m.label,r-b);s.push(`${y}${i.bold(C)}`)}}else{let S=Ds(m.label,r-b);s.push(`${y}${i.bold(S)}`)}}}let a=e.totalRows-n;a>0&&s.push(i.dim(` ... ${a} more below`));let l=e.getSelectedIndices().length,c=e.filter!==""?` matching: ${e.filteredMap.length}/${e.itemCount}`:"";return s.push(""),e.searchActive?s.push(i.dim(` ${l} of ${e.itemCount} selected${c} | Type to filter Esc Clear Enter Done searching`)):s.push(i.dim(` ${l} of ${e.itemCount} selected${c} | \u2191/\u2193 Navigate Space Toggle a All / Search Enter Confirm Esc Cancel`)),s}function Ds(e,t){return t<=0?"":e.length<=t?e:t<=3?e.slice(0,t):e.slice(0,t-3)+"..."}async function Ie(e){let{items:t}=e,r=e.pageSize??Math.min(t.length+1,15),s=new Ms(t,r),o=process.stderr,n=process.stdin,a=o.columns||80;typeof n.setRawMode=="function"&&n.setRawMode(!0),n.resume(),n.setEncoding("utf-8"),o.write("\x1B[?25l");let l=0;function c(){let d=Nu(s,t,a);l>0&&o.write(`\x1B[${l}F`);let u=Math.max(d.length,l),p="";for(let f=0;f<u;f++)p+=`\x1B[2K${f<d.length?d[f]:""}
182
+ `;o.write(p),l=u}return c(),new Promise(d=>{let u="",p=null;function f(){n.removeListener("data",h),typeof n.setRawMode=="function"&&n.setRawMode(!1),n.pause(),o.write("\x1B[?25h"),p&&clearTimeout(p)}function m(y){f(),d(y)}function g(y){if(s.searchActive){if(y==="\x1B"){s.searchActive=!1,s.filter="",s.applyFilter(t),c();return}if(y==="\r"||y===`
183
+ `){s.searchActive=!1,c();return}if(y==="\x7F"||y==="\b"){s.filter.length>0?(s.filter=s.filter.slice(0,-1),s.applyFilter(t)):s.searchActive=!1,c();return}if(y===""){f(),process.kill(process.pid,"SIGINT");return}if(y==="\x1B[A"){s.moveUp(),c();return}if(y==="\x1B[B"){s.moveDown(),c();return}if(y===" "){s.toggleCurrent(),c();return}if(y.length===1&&y>=" "&&y<="~"){s.filter+=y,s.applyFilter(t),c();return}return}switch(y){case"\x1B[A":case"k":s.moveUp(),c();break;case"\x1B[B":case"j":s.moveDown(),c();break;case" ":s.toggleCurrent(),c();break;case"a":s.toggleAll(),c();break;case"/":s.searchActive=!0,c();break;case"\r":case`
184
+ `:m(s.getSelectedIndices());break;case"\x1B":s.filter!==""?(s.filter="",s.applyFilter(t),c()):m([]);break;case"\x7F":case"\b":s.filter.length>0&&(s.filter=s.filter.slice(0,-1),s.applyFilter(t),c());break;case"":f(),process.kill(process.pid,"SIGINT");break}}function h(y){if(u.length>0){if(u+=y,p&&clearTimeout(p),u.length>=3&&u[1]==="["){let $=u.slice(0,3),v=u.slice(3);u="",g($),v&&h(v);return}let b=u;u="",g("\x1B");for(let $=1;$<b.length;$++)g(b[$]);return}for(let b=0;b<y.length;b++){let $=y[b];if($==="\x1B"){let v=y.slice(b);if(v.length>=3&&v[1]==="[")g(v.slice(0,3)),b+=2;else if(v.length>=2){u=v,p=setTimeout(()=>{let S=u;u="",g("\x1B");for(let C=1;C<S.length;C++)g(S[C])},50);return}else{u="\x1B",p=setTimeout(()=>{u="",g("\x1B")},50);return}}else g($)}}n.on("data",h)})}import{access as Ou,lstat as Du,mkdir as Mu,readdir as Fu,readFile as ji,rm as ju,stat as _i}from"fs/promises";import{join as Or}from"path";async function Fs(e){let t;try{t=await _i(e)}catch{throw new Error(`Path does not exist: ${e}`)}if(!t.isDirectory())throw new Error(`Path is not a directory: ${e}`);let r=Or(e,"SKILL.md"),s;try{s=await ji(r,"utf-8")}catch{throw new Error(`No SKILL.md found in ${e}`)}let o=q(s);if(!o.name)throw new Error(`Invalid SKILL.md in ${e}: missing "name" in frontmatter`);return{name:o.name,version:ae(o)}}async function Dr(e,t,r,s){let o=Or(t,r),n=!1;try{await Ou(o),n=!0}catch{}if(n){if(!s)throw new Error(`Target already exists: ${o}. Use --force to overwrite.`);await ju(o,{recursive:!0,force:!0})}await Mu(t,{recursive:!0}),await Ae(e,o)}async function js(e){let t;try{t=await _i(e)}catch{throw new Error(`Path does not exist: ${e}`)}if(!t.isDirectory())throw new Error(`Path is not a directory: ${e}`);let r=await Fu(e),s=[];for(let o of r){if(o.startsWith(".")||o==="node_modules")continue;let n=Or(e,o);try{if(!(await Du(n)).isDirectory())continue}catch{continue}let a=Or(n,"SKILL.md");try{let l=await ji(a,"utf-8"),c=q(l);c.name&&s.push({absPath:n,dirName:o,name:c.name,version:ae(c)})}catch{}}return s.sort((o,n)=>o.name.localeCompare(n.name)),s}var Ui=Uu(_u);function Bi(e=Gu(process.execPath)){let t=[Be(e,"node_modules","npm","bin","npx-cli.js"),Be(e,"..","lib","node_modules","npm","bin","npx-cli.js"),Be(e,"..","libexec","lib","node_modules","npm","bin","npx-cli.js")];for(let r of t)if(Vu(r))return r;return null}function Vi(e,t={}){if(process.platform==="win32"){let r=Bi();if(r)return Ui(process.execPath,[r,...e],t)}return Ui("npx",e,t)}async function Us(){try{await Vi(["--version"]),P("install: npx available")}catch{throw new Error("npx is required for Vercel method installation. Install Node.js from https://nodejs.org")}}async function Bs(e,t){let r=["--yes","skills","add",e];t&&r.push("--skill",t),P(`install: running npx ${r.join(" ")}`);try{let s=await Vi(r,{timeout:12e4});return{stdout:s.stdout,stderr:s.stderr}}catch(s){let o=s,n=o.stderr||o.message||"";throw new Error(`npx skills add failed: ${n}`,{cause:s})}}function Vs(e){if(e.isLocal)return e.localPath;let t=`https://github.com/${e.owner}/${e.repo}`;return e.ref?`${t}/tree/${e.ref}${e.subpath?`/${e.subpath}`:""}`:t}async function me(e,t,r){let s=e.providers.filter(m=>m.enabled);if(t==="all"){if(s.length===0)throw new Error("No providers are enabled. Enable a provider in your config.");return{provider:s.find(g=>g.name==="agents")||s[0],allProviders:s}}if(t){let m=e.providers.find(g=>g.name===t);if(!m){let g=e.providers.map(h=>h.name).join(", ");throw new Error(`Unknown provider: "${t}". Valid providers: ${g}, all`)}if(!m.enabled)throw new Error(`Provider "${t}" is disabled. Enable it in your config or choose another provider.`);return{provider:m,allProviders:null}}if(s.length===1)return{provider:s[0],allProviders:null};if(!r){if(s.length===0)throw new Error("No providers are enabled. Enable a provider in your config.");let m=s.map(g=>g.name).join(", ");throw new Error(`--tool (or --provider) is required in non-interactive mode. Available: ${m}, all`)}let o=e.preferences.selectedTools,a=o&&o.length>0?new Set(o):null,l=e.providers.map(m=>({label:`${m.label} (${m.name})`,hint:m.name==="agents"?`except Claude Code; most harnesses \u2014 ${m.global}`:m.global,checked:a?a.has(m.name):m.enabled&&(m.name==="agents"||m.name==="claude")})),c=await Ie({items:l});if(c.length===0)throw new Error("No tools selected. Aborting.");let d=c.map(m=>e.providers[m]),u=d.map(m=>m.name),{saveSelectedTools:p}=await import("./config-JPFUVYBM.js");return await p(u),d.length===1?{provider:d[0],allProviders:null}:{provider:d.find(m=>m.name==="agents")||d[0],allProviders:d}}async function Gs(e){let{scopeFlag:t,provider:r,isTTY:s,yes:o}=e;if(t==="global"||t==="project")return t;if(!s||o)return"global";let n=[{label:`Global (${r.global})`,hint:"Available in all projects",checked:!0},{label:`Project (${r.project})`,hint:"Available only in this project",checked:!1}],a=await Ie({items:n});if(a.length===0)throw new Error("No scope selected. Aborting.");return a[0]===0?"global":"project"}function Ht(e,t,r,s,o,n,a="global"){let l=a==="project"?o.project:o.global,c=Q(l),d=Be(c,s);return{source:e,tempDir:t,sourceDir:r,targetDir:d,skillName:s,force:n,providerName:o.name,providerLabel:o.label,scope:a}}async function Hs(e,t){try{if(await _s(e),P(`install: target ${e} \u2014 conflict (exists)${t?", force overwrite":""}`),!t)throw new Error(`Skill already exists at: ${e}
185
+ Use --force to overwrite.`)}catch(r){if(r instanceof Error&&r.message?.includes("--force"))throw r;P(`install: target ${e} \u2014 no conflict`)}}async function qs(e,t,r){for(let s of r.providers){if(!s.enabled||s.name===t)continue;let o=Q(s.global),n=Be(o,e);try{await _s(n);let a=Be(n,"SKILL.md");await _s(a);let l=await Bu(a,"utf-8");if((q(l).name||n.split(/[/\\]/).pop()||"")===e)return P(`install: cross-tool link found \u2014 "${e}" already installed in ${s.label} at ${n}`),{existingProvider:s.name,existingProviderLabel:s.label,existingPath:n,isLocalSource:!1}}catch{continue}}return null}async function Ws(e,t,r,s,o,n=!1){let a=o.providers.find(u=>u.name===r);if(!a)throw new Error(`Target provider "${r}" not found in config.`);let l=s==="project"?a.project:a.global,c=Q(l),d=Be(c,e);return await Dr(t,c,e,n),P(`install: linked "${e}" from ${t} -> ${d}`),d}import{join as Zu}from"path";import{readFile as Hu,writeFile as qu,mkdir as Wu}from"fs/promises";import{dirname as Ku}from"path";async function Ju(e){try{let t=await Hu(e,"utf-8"),r=JSON.parse(t);return!r.fetched_at||r.data===void 0||r.data===null?null:r}catch{return null}}async function zu(e,t,r){let s={fetched_at:new Date().toISOString(),ttl_seconds:r,data:t};try{await Wu(Ku(e),{recursive:!0}),await qu(e,JSON.stringify(s,null,2),"utf-8"),P(`http: wrote cache -> ${e}`)}catch(o){P(`http: failed to write cache: ${o}`)}}function Yu(e){let t=new Date(e.fetched_at).getTime();return(Date.now()-t)/1e3<e.ttl_seconds}async function Gi(e,t,r={}){let s=r.ttl??3600,o=r.noCache??!1,n=await Ju(t);if(n&&!o&&Yu(n))return P(`http: cache hit (fresh) -> ${t}`),n.data;try{P(`http: fetching -> ${e}`);let a=await fetch(e);if(!a.ok)throw new Error(`HTTP ${a.status}: ${a.statusText}`);let l=await a.json();return await zu(t,l,s),l}catch(a){return P(`http: fetch failed: ${a}`),n?(P(`http: using stale cache as fallback -> ${t}`),n.data):null}}var Xu=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,Qu=/^[a-zA-Z0-9_-]+$/,Wi=/^https:\/\/github\.com\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9._-]+$/,ep=/^[0-9a-f]{40}$/,tp=/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?(\+[a-zA-Z0-9.]+)?$/,rp=/^[a-z0-9-]+$/,sp=/^sha256:[0-9a-f]{64}$/,Hi=["pass","warning","dangerous"];function Mr(e){let t=[];if(!e||typeof e!="object"||Array.isArray(e))return[{field:"(root)",message:"manifest must be a non-null object"}];let r=e,s=new Set(["name","author","description","repository","commit","skill_path","version","license","tags","security_verdict","published_at","checksum"]);for(let a of Object.keys(r))s.has(a)||t.push({field:a,message:`unknown property "${a}" is not allowed`});let o=[{field:"name",pattern:Xu,maxLength:128},{field:"author",pattern:Qu,maxLength:39},{field:"description",maxLength:256},{field:"repository",pattern:Wi},{field:"commit",pattern:ep},{field:"published_at"}];for(let{field:a,pattern:l,maxLength:c}of o){let d=r[a];if(d==null){t.push({field:a,message:`required field "${a}" is missing`});continue}if(typeof d!="string"){t.push({field:a,message:`"${a}" must be a string`});continue}if(d.length===0){t.push({field:a,message:`"${a}" must not be empty`});continue}c&&d.length>c&&t.push({field:a,message:`"${a}" exceeds maximum length of ${c}`}),l&&!l.test(d)&&t.push({field:a,message:`"${a}" does not match required pattern`})}let n=r.security_verdict;if(n==null?t.push({field:"security_verdict",message:'required field "security_verdict" is missing'}):(typeof n!="string"||!Hi.includes(n))&&t.push({field:"security_verdict",message:`"security_verdict" must be one of: ${Hi.join(", ")}`}),typeof r.published_at=="string"&&r.published_at.length>0&&(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/.test(r.published_at)||t.push({field:"published_at",message:'"published_at" must be a valid ISO 8601 date-time'})),r.version!==void 0&&(typeof r.version!="string"||!tp.test(r.version))&&t.push({field:"version",message:'"version" must be a valid semver string'}),r.license!==void 0&&(typeof r.license!="string"?t.push({field:"license",message:'"license" must be a string'}):r.license.length>64&&t.push({field:"license",message:'"license" exceeds maximum length of 64'})),r.tags!==void 0)if(!Array.isArray(r.tags))t.push({field:"tags",message:'"tags" must be an array'});else{r.tags.length>10&&t.push({field:"tags",message:'"tags" has more than 10 items'});let a=new Set;for(let l=0;l<r.tags.length;l++){let c=r.tags[l];if(typeof c!="string"){t.push({field:`tags[${l}]`,message:"tag must be a string"});continue}c.length>32&&t.push({field:`tags[${l}]`,message:`tag "${c}" exceeds maximum length of 32`}),rp.test(c)||t.push({field:`tags[${l}]`,message:`tag "${c}" does not match pattern (lowercase alphanumeric and hyphens)`}),a.has(c)&&t.push({field:`tags[${l}]`,message:`duplicate tag "${c}"`}),a.add(c)}}return r.checksum!==void 0&&(typeof r.checksum!="string"||!sp.test(r.checksum))&&t.push({field:"checksum",message:'"checksum" must match pattern sha256:<64-hex-chars>'}),r.skill_path!==void 0&&(typeof r.skill_path!="string"?t.push({field:"skill_path",message:'"skill_path" must be a string'}):r.skill_path.length===0?t.push({field:"skill_path",message:'"skill_path" must not be empty'}):r.skill_path.length>256?t.push({field:"skill_path",message:'"skill_path" exceeds maximum length of 256'}):/\.\.|^\//.test(r.skill_path)&&t.push({field:"skill_path",message:'"skill_path" must not contain ".." or start with "/"'})),t}function op(e,t){let r=e.length,s=t.length;if(r===0)return s;if(s===0)return r;let o=new Array(s+1),n=new Array(s+1);for(let a=0;a<=s;a++)o[a]=a;for(let a=1;a<=r;a++){n[0]=a;for(let l=1;l<=s;l++){let c=e[a-1]===t[l-1]?0:1;n[l]=Math.min(o[l]+1,n[l-1]+1,o[l-1]+c)}[o,n]=[n,o]}return o[s]}function np(e,t,r=2){let s=[];for(let o of t){if(e===o)continue;let n=op(e,o);n<=r&&s.push({existingName:o,distance:n})}return s.sort((o,n)=>o.distance-n.distance)}var Ks=process.env.ASM_REGISTRY_URL??"https://raw.githubusercontent.com/luongnv89/asm-registry/main/index.json";function ip(){return process.env.ASM_REGISTRY_CACHE??Zu(br(),"registry-cache.json")}var ap=3600;function Ne(e){if(e.startsWith("github:")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")||e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e==="~"||e==="."||e==="..")return!1;let t=(e.match(/\//g)||[]).length;if(t>1)return!1;if(t===1){let[r,s]=e.split("/");return/^[a-zA-Z0-9_-]+$/.test(r)&&/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(s)}return/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e)}function Js(e){return Ne(e)?e.includes("/"):!1}async function zs(e){let t=await Gi(Ks,ip(),{ttl:ap,noCache:e?.noCache});if(!t)return null;if(typeof t!="object"||!Array.isArray(t.manifests)||typeof t.generated_at!="string")return P("registry: fetched index has invalid structure \u2014 discarding"),null;let r=[];for(let s of t.manifests){let o=Mr(s);if(o.length>0){P(`registry: dropping invalid manifest entry (${s?.name??"unknown"}): ${o.map(n=>n.message).join(", ")}`);continue}if(!Wi.test(s.repository)){P(`registry: dropping manifest with unexpected repository URL: ${s.repository}`);continue}r.push(s)}return{generated_at:t.generated_at,manifests:r}}function lp(e,t){return t.manifests.filter(r=>r.name.toLowerCase()===e.toLowerCase())}function cp(e,t,r){return r.manifests.find(s=>s.author.toLowerCase()===e.toLowerCase()&&s.name.toLowerCase()===t.toLowerCase())??null}function qi(e,t,r=5){return np(e,t.manifests.map(o=>o.name),3).slice(0,r).map(o=>o.existingName)}async function Fr(e,t){let r=await zs(t);if(!r)return P("registry: failed to fetch index \u2014 skipping registry resolution"),{resolved:null,multipleMatches:[],suggestions:[]};if(Js(e)){let[n,a]=e.split("/"),l=cp(n,a,r);if(l)return{resolved:{manifest:l,source:"registry"},multipleMatches:[],suggestions:[]};let c=qi(a,r);return{resolved:null,multipleMatches:[],suggestions:c}}let s=lp(e,r);if(s.length===1)return{resolved:{manifest:s[0],source:"registry"},multipleMatches:[],suggestions:[]};if(s.length>1)return{resolved:null,multipleMatches:s,suggestions:[]};let o=qi(e,r);return{resolved:null,multipleMatches:[],suggestions:o}}var zi=[{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\bcurl\b/,severity:"critical",permissionType:"network"},{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\bwget\b/,severity:"critical",permissionType:"network"},{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\bfetch\s*\(/,severity:"warning",permissionType:"network"},{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\baxios\b/,severity:"warning",permissionType:"network"},{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\bhttp\.request\b/,severity:"warning",permissionType:"network"},{category:"Network requests",description:"Commands or APIs that download or upload data over the network",pattern:/\bXMLHttpRequest\b/,severity:"warning",permissionType:"network"},{category:"External URLs",description:"Hardcoded URLs that may indicate data exfiltration or remote payload loading",pattern:/https?:\/\/(?!github\.com|localhost|127\.0\.0\.1|example\.com)/,severity:"warning",permissionType:"network"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bexec\s*\(/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bexecSync\b/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bchild_process\b/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bspawn\s*\(/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bBun\.spawn\b/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\bshelljs\b/,severity:"critical",permissionType:"shell"},{category:"Shell execution",description:"Commands that execute shell processes or arbitrary system commands",pattern:/\b(?:bash|sh|zsh)\s+-c\b/,severity:"critical",permissionType:"shell"},{category:"Dynamic code execution",description:"Patterns that execute dynamically constructed code at runtime",pattern:/\beval\s*\(/,severity:"critical",permissionType:"code-execution"},{category:"Dynamic code execution",description:"Patterns that execute dynamically constructed code at runtime",pattern:/\bnew\s+Function\b/,severity:"critical",permissionType:"code-execution"},{category:"Dynamic code execution",description:"Patterns that execute dynamically constructed code at runtime",pattern:/\bFunction\s*\(/,severity:"critical",permissionType:"code-execution"},{category:"Dynamic code execution",description:"Patterns that execute dynamically constructed code at runtime",pattern:/\bimport\s*\(\s*[^'"]/,severity:"warning",permissionType:"code-execution"},{category:"File system access",description:"Operations that read, write, or modify files on disk",pattern:/\bfs\.(?:write|append|unlink|rm|mkdir|rename)\b/,severity:"warning",permissionType:"filesystem"},{category:"File system access",description:"Operations that read, write, or modify files on disk",pattern:/\bwriteFile(?:Sync)?\b/,severity:"warning",permissionType:"filesystem"},{category:"File system access",description:"Operations that read, write, or modify files on disk",pattern:/\brm\s+-rf?\b/,severity:"critical",permissionType:"filesystem"},{category:"File system access",description:"Operations that read, write, or modify files on disk",pattern:/\bchmod\b/,severity:"warning",permissionType:"filesystem"},{category:"Embedded credentials",description:"Hardcoded secrets, API keys, tokens, or passwords",pattern:/\b(?:API_KEY|SECRET_KEY|ACCESS_TOKEN|PRIVATE_KEY)\s*[=:]/,severity:"critical"},{category:"Embedded credentials",description:"Hardcoded secrets, API keys, tokens, or passwords",pattern:/\bPASSWORD\s*[=:]/,severity:"critical"},{category:"Embedded credentials",description:"Hardcoded secrets, API keys, tokens, or passwords",pattern:/(?:sk|pk)[-_](?:live|test)[-_][a-zA-Z0-9]{20,}/,severity:"critical"},{category:"Environment variable access",description:"Reading environment variables which may contain secrets or configuration",pattern:/\bprocess\.env\b/,severity:"info",permissionType:"environment"},{category:"Environment variable access",description:"Reading environment variables which may contain secrets or configuration",pattern:/\bBun\.env\b/,severity:"info",permissionType:"environment"},{category:"Obfuscation patterns",description:"Base64 encoding, hex strings, or other obfuscation techniques",pattern:/\batob\s*\(/,severity:"warning"},{category:"Obfuscation patterns",description:"Base64 encoding, hex strings, or other obfuscation techniques",pattern:/\bBuffer\.from\s*\([^,]+,\s*['"]base64['"]\)/,severity:"warning"},{category:"Obfuscation patterns",description:"Base64 encoding, hex strings, or other obfuscation techniques",pattern:/\\x[0-9a-fA-F]{2}(?:\\x[0-9a-fA-F]{2}){5,}/,severity:"warning"}];async function dp(e,t){let r={owner:e,repo:t,profileUrl:`https://github.com/${e}`,reposUrl:`https://github.com/${e}?tab=repositories`,isOrganization:null,publicRepos:null,accountAge:null,fetchError:null};try{let s=await fetch(`https://api.github.com/users/${e}`,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"agent-skill-manager"},signal:AbortSignal.timeout(1e4)});if(!s.ok)return r.fetchError=`GitHub API returned ${s.status}`,r;let o=await s.json();if(r.isOrganization=o.type==="Organization",r.publicRepos=typeof o.public_repos=="number"?o.public_repos:null,typeof o.created_at=="string"){let n=new Date(o.created_at),a=new Date,l=Math.floor((a.getTime()-n.getTime())/(365.25*24*60*60*1e3)),c=Math.floor((a.getTime()-n.getTime())%(365.25*24*60*60*1e3)/(30.44*24*60*60*1e3));r.accountAge=l>0?`${l}y ${c}m`:`${c}m`}P(`security-audit: source analysis for ${e} -> repos=${r.publicRepos}, org=${r.isOrganization}, age=${r.accountAge}`)}catch(s){r.fetchError=s.message||"Failed to fetch GitHub profile",P(`security-audit: source analysis failed -> ${r.fetchError}`)}return r}function up(e){let t=new Map;for(let{relPath:o,content:n}of e){let a=n.split(`
186
+ `);for(let l=0;l<a.length;l++){let c=a[l],d=c.trim();for(let u of zi)if(u.pattern.test(c)){let p=u.category;t.has(p)||t.set(p,{description:u.description,matches:[]});let f=d.length>120?d.slice(0,120)+"...":d;t.get(p).matches.push({file:o,line:l+1,match:f,severity:u.severity})}}}let r=[];for(let[o,n]of t)r.push({category:o,description:n.description,matches:n.matches});let s={critical:0,warning:1,info:2};return r.sort((o,n)=>{let a=Math.min(...o.matches.map(c=>s[c.severity])),l=Math.min(...n.matches.map(c=>s[c.severity]));return a-l}),r}function pp(e){let t=new Map;for(let n of e)for(let a of n.matches)for(let l of zi)if(l.permissionType&&l.category===n.category&&l.pattern.test(a.match)){let c=l.permissionType;t.has(c)||t.set(c,{evidence:[],categories:new Set});let d=t.get(c);d.evidence.push({file:a.file,line:a.line,match:a.match}),d.categories.add(n.category);break}let r={filesystem:"Skill reads, writes, or modifies files on disk. Verify it only accesses intended paths.",shell:"Skill executes shell commands or spawns processes. This allows arbitrary system access.",network:"Skill makes network requests or downloads external content. Data may be sent to remote servers.","code-execution":"Skill dynamically constructs and executes code. This can bypass static analysis.",environment:"Skill reads environment variables, which may contain secrets or API keys."},s=[];for(let[n,a]of t)s.push({type:n,evidence:a.evidence,reason:r[n]});let o={shell:0,"code-execution":1,network:2,filesystem:3,environment:4};return s.sort((n,a)=>(o[n.type]??99)-(o[a.type]??99)),s}function mp(e,t,r){let s=0,o=0;for(let c of e)for(let d of c.matches)d.severity==="critical"&&s++,d.severity==="warning"&&o++;let n=t.some(c=>c.type==="shell"),a=t.some(c=>c.type==="code-execution"),l=t.some(c=>c.type==="network");return n&&l?{verdict:"dangerous",reason:"Skill has both shell execution and network access -- potential data exfiltration risk."}:a&&l?{verdict:"dangerous",reason:"Skill has dynamic code execution and network access -- potential remote code execution risk."}:s>=10?{verdict:"dangerous",reason:`${s} critical findings detected. High concentration of risky patterns.`}:n||a?{verdict:"warning",reason:n?"Skill executes shell commands. Review commands carefully before installing.":"Skill uses dynamic code execution. Review usage carefully."}:s>0?{verdict:"warning",reason:`${s} critical finding${s>1?"s":""} detected. Manual review recommended.`}:o>0?{verdict:"caution",reason:`${o} warning${o>1?"s":""} found. Generally acceptable but worth reviewing.`}:r&&r.publicRepos!==null&&r.publicRepos<3?{verdict:"caution",reason:"No code issues found, but the author has very few public repositories."}:{verdict:"safe",reason:"No suspicious patterns detected."}}var fp=new Set([".md",".txt",".rst",".adoc",".markdown"]),gp=new Set(["SKILL.md","README.md","readme.md","CHANGELOG.md","changelog.md","LICENSE","LICENSE.md","LICENSE.txt","CONTRIBUTING.md","contributing.md","CODE_OF_CONDUCT.md","security.md","SECURITY.md","SUPPORT.md","support.md","TODO.md","todo.md","ROADMAP.md","roadmap.md"]);function hp(e){let t=e.split("/").pop();if(gp.has(t))return!0;let r=t.includes(".")?`.${t.split(".").pop().toLowerCase()}`:"";return fp.has(r)}async function xe(e,t,r,s){P(`security-audit: scanning ${e}`);let n=(await vr(e)).filter(f=>!hp(f.relPath)),a=n.reduce((f,m)=>f+m.lineCount,0),l=null;r&&s&&(l=await dp(r,s));let c=up(n),d=pp(c),{verdict:u,reason:p}=mp(c,d,l);return{scannedAt:new Date().toISOString(),skillName:t,skillPath:e,source:l,codeScans:c,permissions:d,totalFiles:n.length,totalLines:a,verdict:u,verdictReason:p}}var T=i,Ve=56,yp={"Shell execution":"shell","Dynamic code execution":"code-execution","Network requests":"network","External URLs":"network","File system access":"filesystem","Environment variable access":"environment","Embedded credentials":"credentials","Obfuscation patterns":"obfuscation"},Ki={critical:0,warning:1,info:2};function bp(e){switch(e){case"safe":return T.bgGreen(" SAFE ");case"caution":return T.bgCyan(" CAUTION ");case"warning":return T.bgYellow(" WARNING ");case"dangerous":return T.bgRed(" DANGEROUS ")}}function wp(e){switch(e){case"safe":return T.green;case"caution":return T.cyan;case"warning":return T.yellow;case"dangerous":return T.red}}function mt(e){switch(e){case"critical":return T.red("!!");case"warning":return T.yellow(" !");case"info":return T.dim(" i")}}function Ys(e,t){return e.length>t?e.slice(0,t-3)+"...":e}function jr(e){return e.toLocaleString("en-US")}function Yi(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function Ji(e){return Yi(e).length}function kp(e){let t=new Map;for(let r of e){let s=`${r.file}:${r.line}`,o=t.get(s);(!o||Ki[r.severity]<Ki[o.severity])&&t.set(s,r)}return Array.from(t.values())}function vp(e){let t=new Map;for(let r of e){let s=t.get(r.file);s||(s={file:r.file,entries:[]},t.set(r.file,s)),s.entries.push({line:r.line,match:r.match,severity:r.severity})}return Array.from(t.values())}function ft(e){let t=[],r=bp(e.verdict),s=Yi(r),o=` ${T.bold(e.skillName)}`,n=` ${e.skillName}`,a=Ve-4,l=Math.max(1,a-n.length-s.length);if(t.push(""),t.push(T.dim(" +-- ")+T.bold("Security Audit")+T.dim(" "+"-".repeat(Ve-19)+"+")),t.push(T.dim(" |")+o+" ".repeat(l)+r+T.dim("|")),t.push(T.dim(" |")+T.dim(` ${jr(e.totalFiles)} files | ${jr(e.totalLines)} lines`)+" ".repeat(Math.max(1,a-` ${jr(e.totalFiles)} files | ${jr(e.totalLines)} lines`.length))+T.dim("|")),t.push(T.dim(" +"+"-".repeat(Ve-2)+"+")),e.source){let p=e.source;if(p.fetchError)t.push(` ${T.yellow("!")} Could not fetch profile: ${p.fetchError}`);else{let f=[];if(f.push(`${p.owner} ${p.isOrganization?T.cyan("(org)"):T.dim("(user)")}`),p.publicRepos!==null){let m=p.publicRepos,g=m<3?T.yellow(`${m} repos`):m<10?T.cyan(`${m} repos`):T.green(`${m} repos`);f.push(g)}p.accountAge&&f.push(p.accountAge),t.push(` ${T.dim("Author:")} ${f.join(T.dim(" | "))}`)}}if(t.push(""),e.codeScans.length===0)t.push(` ${T.green("*")} ${T.green("No suspicious patterns detected.")}`);else{let p=wp(e.verdict),f=e.verdict==="dangerous"||e.verdict==="warning"?mt("critical"):e.verdict==="caution"?mt("warning"):mt("info");t.push(` ${f} ${p(e.verdictReason)}`);let m=0,g=0,h=0;for(let v of e.codeScans)for(let S of v.matches)S.severity==="critical"?m++:S.severity==="warning"?g++:h++;let y=[];m>0&&y.push(T.red(`${m} critical`)),g>0&&y.push(T.yellow(`${g} warning`)),h>0&&y.push(T.dim(`${h} info`));let b=e.permissions.map(v=>v.type),$=b.length>0?T.dim(`Perms: ${b.join(", ")}`):"";t.push(` ${y.join(T.dim(" | "))} ${$}`)}if(t.push(""),e.codeScans.length>0){t.push(` ${T.bold("Findings")}`),t.push(T.dim(" "+"=".repeat(Ve-2)));for(let p of e.codeScans){let f=kp(p.matches),m=f.filter(M=>M.severity==="critical").length,g=f.filter(M=>M.severity==="warning").length,h=f.filter(M=>M.severity==="info").length,y=m>0?mt("critical"):g>0?mt("warning"):mt("info"),b=[];m>0&&b.push(T.red(`${m} critical`)),g>0&&b.push(T.yellow(`${g} warning`)),h>0&&b.push(T.dim(`${h} info`));let $=yp[p.category],v=$?T.dim(`PERM: ${$}`):"",S=` ${y} ${T.bold(p.category)} (${b.join(", ")})`;if(v){let M=Ji(S),k=Ji(v),E=Math.max(2,Ve-M-k);t.push(S+" ".repeat(E)+v)}else t.push(S);let C=vp(f),D=Math.min(24,Math.max(...C.map(M=>M.file.length))),U=0,A=3;for(let M of C){if(U>=A)break;let k=Ys(M.file,24),E=T.dim(k.padEnd(D));if(M.entries.length===1){let F=M.entries[0],Z=Ys(F.match,50);t.push(` ${E} :${F.line} ${T.dim("--")} ${F.severity==="critical"?Z:T.dim(Z)}`),U++}else if(M.entries.length<=3){let F=M.entries.map(se=>`:${se.line}`).join(", "),Z=Ys(M.entries[0].match,40);t.push(` ${E} ${F} ${T.dim("--")} ${T.dim(Z)}`),U++}else{let Z=M.entries.slice(0,3).map(we=>`:${we.line}`).join(", "),se=M.entries.length-3;t.push(` ${E} ${Z} ${T.dim(`(+${se} more)`)}`),U++}}let _=C.length-Math.min(C.length,A);if(_>0){let M=f.length-C.slice(0,A).reduce((k,E)=>k+E.entries.length,0);M>0&&t.push(` ${T.dim(`... ${M} more in ${_} file${_>1?"s":""}`)}`)}t.push("")}}t.push(T.dim(" "+"=".repeat(Ve-2)));let c=new Date(e.scannedAt),d=`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}-${String(c.getDate()).padStart(2,"0")} ${String(c.getHours()).padStart(2,"0")}:${String(c.getMinutes()).padStart(2,"0")}`,u=e.source&&!e.source.fetchError?`github.com/${e.source.owner}`:"";if(u){let p=Math.max(2,Ve-2-d.length-u.length);t.push(T.dim(` ${d}${" ".repeat(p)}${u}`))}else t.push(T.dim(` ${d}`));return t.push(""),t.join(`
187
+ `)}function Zs(e){return JSON.stringify(e,null,2)}var qt="Relocate `README.md` out of the skill root so SKILL.md remains the sole top-level document (e.g., move it to `docs/README.md`).",_r=["name","description","version","license","author","creator","compatibility","allowed-tools","effort","tags","metadata"],Zi=["add","analyze","audit","build","check","configure","convert","create","debug","deploy","detect","edit","evaluate","explain","export","extract","fetch","find","fix","format","generate","identify","improve","index","inspect","install","list","manage","migrate","optimize","parse","plan","prepare","publish","refactor","remove","rename","report","research","review","run","scaffold","scan","score","search","set","setup","show","summarize","sync","test","transform","translate","update","validate","verify","write"],Sp=["confirm","confirmation","error","errors","fail","failure","caution","warning","prerequisite","prerequisites","requires","requirements","rollback","dry-run","dry run","safety","validate","validation","check","backup"],$p=["acceptance criteria","expected output","expected result","edge case","edge cases","test","tests","testing","verify","verification","assert","example input","example output","given","then"],xp=["reference","references","see","template","templates","script","scripts","helper","helpers","link"],Pp=["when to use","quick start","overview","instructions","steps","workflow","phases","progressive"];function Ur(e){let t=e.split(`
188
+ `);if(t.length===0||t[0].trim()!=="---")return{rawFrontmatter:null,body:e};for(let r=1;r<t.length;r++)if(t[r].trim()==="---"){let s=t.slice(1,r).join(`
189
+ `),o=t.slice(r+1).join(`
190
+ `);return{rawFrontmatter:s,body:o}}return{rawFrontmatter:t.slice(1).join(`
191
+ `),body:""}}function Xs(e){return e?e.split(`
192
+ `).length:0}function Qs(e){return e?e.split(/\s+/).map(t=>t.trim()).filter(Boolean).length:0}function Rp(e,t=1){return(e.match(/^#{1,6}\s+\S/gm)||[]).length>=t}function Br(e,t){let r=e.toLowerCase();return t.filter(s=>r.includes(s))}function Ep(e){return/```[\s\S]+?```/m.test(e)}function Ip(e){return/^\s*[-*]\s+\S/m.test(e)||/^\s*\d+\.\s+\S/m.test(e)}function Xi(e,t,r,s){let o=[],n=[],a=0;r!==null?(a+=2,o.push("Has YAML frontmatter block.")):(o.push("SKILL.md has no YAML frontmatter."),n.push("Add a YAML frontmatter block delimited by `---` with at least `name` and `description` fields."));let l=!!(e.name&&e.name.trim()),c=!!(e.description&&e.description.trim());l?a+=1.5:(o.push("Missing required field: name."),n.push("Add `name:` to frontmatter (use the skill directory name).")),c?a+=1.5:(o.push("Missing required field: description."),n.push("Add a one-line `description:` to frontmatter."));let d=ae(e);d&&d!=="0.0.0"?a+=1:(o.push("Missing or default version."),n.push("Set `metadata.version` (or top-level `version`) using semver (e.g. 0.1.0).")),!!(e.author||e["metadata.author"]||e.creator||e["metadata.creator"])?a+=1:(o.push("Missing `author`."),n.push("Add an `author` field so users know who authored and maintains the skill.")),!!e.license?a+=1:(o.push("Missing `license`."),n.push("Add a `license` field (e.g. `license: MIT`)."));let m=t.trim().length>=20,g=Rp(t,1);if(m?(a+=1,o.push("Body has meaningful content.")):(o.push("Body content is too short (<20 chars of instructions)."),n.push("Flesh out the markdown body with at least one paragraph of instructions for the agent.")),g?(a+=1,o.push("Body uses markdown headings.")):(o.push("Body has no markdown headings."),n.push("Add section headings (e.g. `## When to Use`, `## Instructions`) so the agent can navigate the skill quickly.")),s){let h=s.find(y=>y.toLowerCase()==="readme.md");h&&(o.push(`\`${h}\` found at skill root; move it to a subdirectory (e.g., \`docs/README.md\`).`),n.push(qt))}return{id:"structure",name:"Structure & completeness",score:Math.round(a),max:10,findings:o,suggestions:n}}function Qi(e,t){let r=[],s=[],o=0,n=(e.description||"").trim();if(!n)return r.push("No description."),s.push("Write a one-sentence description that says specifically what the skill does and when to use it."),{id:"description",name:"Description quality",score:0,max:10,findings:r,suggestions:s};let a=Qs(n);r.push(`Description is ${a} words.`),a>=8&&a<=40?o+=4:a>=5&&a<8?(o+=2,s.push("Lengthen the description slightly so it names both the action and the trigger (aim for 8\u201320 words).")):a>=41&&a<=60?(o+=2,s.push("Trim the description \u2014 aim for under 40 words. Move the long version to the markdown body.")):a>60?(o+=0,s.push("Description is too long. Keep it under 40 words; put detail in the body.")):(o+=0,s.push("Description is too short. Aim for 8\u201320 words."));let l=n.split(/\s+/)[0]?.toLowerCase().replace(/[^\w-]/g,"");return!!(l&&(Zi.includes(l)||Zi.includes(l.replace(/s$/,""))))?(o+=3,r.push("Starts with an action verb.")):(r.push(`Does not start with a recognized action verb (got "${l??""}").`),s.push('Start the description with an imperative action verb (e.g. "Generate...", "Analyze...", "Review...").')),/\buse when\b|\btrigger\b|\bwhen\b|\bfor\b/i.test(n)||/\b(before|after|during)\b/i.test(n)?(o+=3,r.push("Mentions a trigger or use-case signal.")):(r.push("No explicit trigger / use-case phrase."),s.push('Name the trigger in the description \u2014 e.g. "Use when...", "for reviewing...", "before publishing...".')),{id:"description",name:"Description quality",score:Math.min(10,Math.round(o)),max:10,findings:r,suggestions:s}}function ea(e,t){let r=[],s=[],o=0,n=Br(t,Pp);n.length>=2?(o+=3,r.push(`Progressive disclosure cues present: ${n.slice(0,3).join(", ")}.`)):n.length===1?(o+=1,s.push('Add clearer section labels \u2014 e.g. "## When to Use" and "## Instructions" \u2014 to support progressive disclosure.')):s.push('Structure the body with "## When to Use" and "## Instructions" sections so the agent reads only what it needs.'),Ip(t)?(o+=2,r.push("Uses lists or numbered steps.")):(r.push("No lists or steps detected."),s.push("Use bulleted or numbered steps to narrow the agent's degrees of freedom."));let a=Ep(t),l=/\bexample\b/i.test(t);a&&l?(o+=2,r.push("Includes example code block.")):a||l?(o+=1,s.push('Back up examples with fenced code blocks labelled under "## Example" so the agent sees concrete input/output.')):s.push('Add an "## Example" section with a fenced code block showing the desired output.');let c=(t.match(/^\s*[-*0-9.]*\s*(Do|Use|Run|Call|Check|Validate|Return|Emit|Write|Read|Ask|Confirm|Avoid|Never|Always)\b/gim)||[]).length;c>=3?(o+=2,r.push(`Uses imperative voice (${c} cues).`)):c>=1?(o+=1,s.push("Favor imperative voice (Do / Use / Avoid / Never) to narrow the agent's choices.")):s.push('Rewrite instructions in the imperative mood \u2014 e.g. "Run `git status` first" instead of "you might want to run".');let d=Qs(t);return d>=80&&d<=3e3?(o+=1,r.push(`Body length within healthy range (${d} words).`)):d<80?(r.push(`Body is very short (${d} words).`),s.push("Expand the instructions; an underspecified skill gives the agent too much freedom.")):(r.push(`Body is very long (${d} words).`),s.push("Split large content into referenced files; keep SKILL.md focused under ~3000 words.")),{id:"prompt-engineering",name:"Prompt engineering",score:Math.min(10,Math.round(o)),max:10,findings:r,suggestions:s}}function ta(e,t){let r=[],s=[],o=0,n=Qs(t);r.push(`Body is ${n} words.`),n>=120&&n<=1500?o+=4:n>=60&&n<120?(o+=2,s.push("Expand instructions slightly \u2014 too little context can push the agent to improvise.")):n>1500&&n<=3e3?(o+=2,s.push("Consider moving large sections into referenced files (e.g. `references/*.md`) and linking them instead of inlining.")):n>3e3&&(o+=0,s.push("Body is over 3000 words \u2014 split long content into referenced files or templates."));let a=Br(t,xp);a.length>=2?(o+=3,r.push(`References external files or links (${a.slice(0,3).join(", ")}).`)):a.length===1?(o+=1,s.push('Link out to supporting files (e.g. "see `references/examples.md`") instead of inlining them.')):s.push('Offload verbose content to referenced files and link to them ("see `./templates/x.md`").');let c=(t.match(/```[\s\S]+?```/g)||[]).filter(d=>Xs(d)>60);return c.length===0?(o+=2,r.push("No oversized code blocks.")):(r.push(`${c.length} code block(s) longer than 60 lines.`),s.push("Move large code blocks into referenced template files; link to them from SKILL.md.")),/\btoken\b|\bbudget\b|\bcontext window\b/i.test(t)&&(o+=1,r.push("Mentions tokens/budget/context window.")),{id:"context-efficiency",name:"Context efficiency",score:Math.min(10,Math.round(o)),max:10,findings:r,suggestions:s}}function ra(e,t){let r=[],s=[],o=0,n=Br(t,Sp);n.length>=4?(o+=4,r.push(`Covers multiple safety cues (${n.slice(0,4).join(", ")}).`)):n.length>=2?(o+=2,r.push(`Mentions a few safety cues: ${n.join(", ")}.`),s.push("Add explicit error-handling and confirmation steps so the agent knows how to recover from failures.")):n.length===1?(o+=1,s.push('Expand the safety section \u2014 include prerequisites, validation steps, and what to do "on error".')):s.push("Describe prerequisites, confirmation prompts, and error-handling steps to reduce blast radius.");let a=/\b(rm\s|delete|remove|drop|force|overwrite|destructive)\b/i.test(t),l=/\bconfirm\b|\bdry-?run\b|\bare you sure\b|\bbackup\b/i.test(t);return a&&l?(o+=3,r.push("Destructive actions paired with confirmation/dry-run.")):a?(r.push("References destructive actions without explicit confirmation/dry-run."),s.push("Pair any destructive command with an explicit confirmation prompt, dry-run flag, or backup step.")):o+=1.5,/\bprerequisit/i.test(t)||/\brequire/i.test(t)||/\bdepend/i.test(t)?(o+=3,r.push("Declares prerequisites or requirements.")):(r.push("No prerequisites / requirements section."),s.push('Add a "## Prerequisites" block listing required tools, credentials, and environment state.')),{id:"safety",name:"Safety & guardrails",score:Math.min(10,Math.round(o)),max:10,findings:r,suggestions:s}}function sa(e,t){let r=[],s=[],o=0,n=Br(t,$p);return n.length>=4?(o+=5,r.push(`Many testability cues present (${n.slice(0,4).join(", ")}).`)):n.length>=2?(o+=3,r.push(`Some testability cues: ${n.join(", ")}.`),s.push('Add an "## Acceptance Criteria" block listing verifiable outputs or checklist items.')):n.length===1?(o+=1,s.push('Add concrete "expected output" examples so the agent can self-check.')):s.push('Add a "## Acceptance Criteria" section with testable statements (e.g. "produces a JSON report with overall_score").'),/expected\s+(output|result|response)/i.test(t)?(o+=3,r.push("Describes expected output/result.")):s.push('Include an "Expected output" example so reviewers and the agent can verify correctness.'),/\bedge case|gotcha|pitfall|limitation/i.test(t)?(o+=2,r.push("Mentions edge cases or limitations.")):s.push('Add a short "Edge cases" list to describe inputs the skill should reject or handle carefully.'),{id:"testability",name:"Testability",score:Math.min(10,Math.round(o)),max:10,findings:r,suggestions:s}}var Cp=new Set(["MIT","MIT-0","Apache-2.0","Apache-2.0 WITH LLVM-exception","BSD-2-Clause","BSD-3-Clause","ISC","Unlicense","0BSD","Zlib","BSL-1.0","CC0-1.0","LGPL-2.1-only","LGPL-2.1-or-later","LGPL-3.0-only","LGPL-3.0-or-later","MPL-2.0","MPL-2.0-no-copyleft-exception","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0-only","GPL-3.0-or-later","AGPL-3.0-only","AGPL-3.0-or-later","Artistic-2.0","EPL-1.0","EPL-2.0","CDDL-1.0","CDDL-1.1","CPAL-1.0","ECL-2.0","EFL-2.0","Nokia-1.0a","OFL-1.1","SIL-OpenFont-1.1","VSLAM-1.0","WTFPL","ZPL-2.1","NCSA","PostgreSQL","X11","JSON","CC-BY-4.0","CC-BY-SA-4.0","CC-BY-NC-4.0","CC-BY-NC-SA-4.0","CC-BY-ND-4.0","CC-BY-NC-ND-4.0","Fair","NTP","AFL-3.0","APAFML","OLDAP-2.8"]);function oa(e,t,r){let s=[],o=[],n=0,a=(e.license||"").trim(),l=!!a,d=!!r?.find(p=>p.toLowerCase()==="license"||p.toLowerCase()==="license.md"||p.toLowerCase()==="license.txt"),u="missing";switch(l?Cp.has(a)?u="recognised":u="unrecognised":d&&(u="unrecognised"),u){case"recognised":{n=d?10:5,s.push(`License declared: \`${a}\` (SPDX recognised).`),d?s.push("LICENSE file present at skill root."):s.push("No LICENSE file found \u2014 consider adding one for clarity.");break}case"unrecognised":{n=2,l&&s.push(`License declared as \`${a}\` but not in the SPDX list.`),d&&!l&&s.push("LICENSE file present but no frontmatter license field."),o.push("Use a standard SPDX licence identifier (e.g. `MIT`, `Apache-2.0`, `GPL-3.0-only`) so tooling can verify redistributability.");break}case"missing":{n=0,s.push("No license declared."),o.push("Add a `license` field to frontmatter (e.g. `license: MIT`) so users know the redistribution terms."),d&&o.push("A LICENSE file exists \u2014 add the corresponding `license:` frontmatter field to match it.");break}}return{id:"license",name:"License verification",score:Math.min(10,Math.round(n)),max:10,findings:s,suggestions:o,licenseStatus:u}}function na(e,t){let r=[],s=[],o=0,n=(e.name||"").trim();if(n){let c=/^[a-z][a-z0-9-]*$/.test(n),d=n.length<=40;c&&d?(o+=4,r.push(`name "${n}" follows kebab-case convention.`)):(c||(r.push(`name "${n}" is not lowercase kebab-case.`),s.push(`Rename to lowercase kebab-case (e.g. "${n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}").`)),d||r.push(`name is ${n.length} chars; keep it <= 40.`))}else s.push("Add a kebab-case `name` (e.g. `my-skill`).");let a=t.match(/^#{1,6}\s+(.+)$/gm)||[];return a.length>0&&(a.filter(u=>/^#{1,6}\s+([A-Z][a-z]+|Use|How|When|Workflow|Instructions|Examples|Steps|Acceptance)/.test(u)).length/a.length>=.5?(o+=3,r.push("Most headings use action/imperative labels.")):(o+=1,s.push("Rename body headings to action-oriented labels (e.g. `## Instructions`, `## When to Use`)."))),/(?:\s\s|\bTODO\b|\bFIXME\b|\?{2,})/.test(e.description||"")?s.push("Clean up description \u2014 remove TODOs, FIXMEs, double spaces, or trailing punctuation."):(o+=2,r.push("Description looks clean (no TODO/FIXME/stray noise).")),{id:"naming",name:"Naming & conventions",score:Math.min(10,Math.round(o)),max:10,findings:r,suggestions:s}}import{readFile as to,writeFile as Op,stat as fa,copyFile as Dp,readdir as Mp}from"fs/promises";import{join as ga,resolve as ha,basename as ro,isAbsolute as ya}from"path";import{readFile as Lp,readdir as ia,stat as aa}from"fs/promises";import{join as la,isAbsolute as ca,resolve as da}from"path";var Ap=[{category:"email",pattern:/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/gi},{category:"phone",pattern:/\b(?:\+?1[-.]?)?\(?\d{3}\)?[\s-]?\d{3}[-.]?\d{4}\b/g},{category:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g},{category:"address",pattern:/\b\d{1,5}\s+(?:[A-Z][a-z]+\s+){1,3}(?:Street|St|Avenue|Ave|Boulevard|Blvd|Drive|Dr|Lane|Ln|Road|Rd|Court|Ct|Place|Pl|Way|Circle|Cir)\b/gi},{category:"license",pattern:/\b[A-Z]{2}\d{6,8}\b/g}];async function ua(e){let t=[],r=[],s=10,o=new Set,n=ca(e)?e:da(e),a=new Set([".md",".txt",".json",".yaml",".yml",".sh",".py",".bash",".js",".ts",".jsx",".tsx",".html",".css",".log"]);async function l(c){let d;try{d=await ia(c)}catch{return}for(let u of d){let p=la(c,u),f;try{f=await aa(p)}catch{continue}if(f.isDirectory()){if(u.startsWith(".")||u==="node_modules")continue;await l(p)}else if(f.isFile()){let m=u.includes(".")?"."+u.split(".").pop():"";if(!a.has(m))continue;try{let h=(await Lp(p,"utf-8")).split(`
193
+ `),y=!1,b=!1;for(let $ of Ap){$.pattern.lastIndex=0,y=!1,b=!1;for(let v=0;v<h.length;v++){let S=h[v];if(S.trim()==="---"){y=!y;continue}if(S.trim().startsWith("```")){b=!b;continue}if(y||b)continue;let C=S.match($.pattern);if(C&&C.length>0){o.has($.category)||(o.add($.category),s-=2);let D=p.replace(n+"/","");t.push(`[${$.category}] ${D}:${v+1} \u2014 found ${C.length} match(es)`)}}}}catch{}}}}return await l(n),o.size===0?t.push("No PII detected in skill files."):(t.push(`PII detected in ${o.size} category/categories: ${[...o].join(", ")}.`),r.push("Remove or redact personal data from examples, transcripts, and fixture files before publishing.")),{id:"pii",name:"PII detection",score:Math.max(0,Math.min(10,Math.round(s))),max:10,findings:t,suggestions:r}}var Tp=new Set([".sh",".bash",".py"]),pa={".sh":{command:"shellcheck",args:["--format=json1"],language:"bash/shell"},".bash":{command:"shellcheck",args:["--format=json1"],language:"bash/shell"},".py":{command:"python3",args:["-m","py_compile"],language:"python"}};async function Np(e,t){let r=pa[t];if(!r)return null;try{let{runCommand:s}=await import("./spawn-JDSII5L3.js"),o=await s([r.command,...r.args,e]);if(o.exitCode!==0){if(t===".py"){let n=o.stderr.split(`
194
+ `),a=[],l=0;for(let c of n){let d=c.match(/File "([^"]+)", line (\d+)/);if(d){l=parseInt(d[2],10);continue}let u=c.match(/^\s*(SyntaxError|IndentationError|ImportError|AttributeError|TypeError|ValueError):\s*(.+)$/);u&&(a.push({file:e,line:l||0,severity:"error",message:`${u[1]}: ${u[2].trim()}`}),l=0)}return a}try{let n=JSON.parse(o.stderr),a=[];if(Array.isArray(n)){for(let l of n)if(l&&typeof l=="object"){let c=l;a.push({file:e,line:Number(c.line)||0,severity:c.level==="error"||c.level==="e"?"error":c.level==="warning"||c.level==="w"?"warning":"info",message:c.message||"Unknown issue"})}}return a}catch{return[{file:e,line:0,severity:"warning",message:`Linter exited with code ${o.exitCode}: ${o.stderr.slice(0,200)}`}]}}return[]}catch(s){return s&&typeof s=="object"&&"code"in s&&s.code==="ENOENT",null}}async function ma(e){let t=[],r=[],s=10,o=0,n=!1,a=[],l=ca(e)?e:da(e);async function c(d){let u;try{u=await ia(d)}catch{return}for(let p of u){let f=la(d,p),m;try{m=await aa(f)}catch{continue}if(m.isDirectory()){if(p.startsWith(".")||p==="node_modules")continue;await c(f)}else if(m.isFile()){let g=p.includes(".")?"."+p.split(".").pop():"";if(!Tp.has(g))continue;let h=f.replace(l+"/",""),y=await Np(f,g);if(y===null){n=!0;let b=pa[g]?.language||g;t.push(`[${b}] ${h}: lint skipped \u2014 linter not available`)}else{o++,a.push(...y);for(let b of y){let $=b.severity.toUpperCase();t.push(`[${$}] ${h}:${b.line||"*"} \u2014 ${b.message}`)}}}}}if(await c(l),o===0&&!n)t.push("No bundled scripts found to lint.");else if(n&&o===0)t.push("No bundled scripts found and linter is unavailable.");else if(a.length===0)t.push(`Linted ${o} script(s) \u2014 no issues found.`);else{let d=a.filter(p=>p.severity==="error").length,u=a.filter(p=>p.severity==="warning").length;s=Math.max(0,10-d*3-u),t.push(`Found ${d} error(s) and ${u} warning(s) across ${o} script(s).`),r.push("Fix lint errors in bundled scripts \u2014 quoting issues, undefined variables, and syntax errors can cause runtime failures.")}return{id:"script-lint",name:"Script linting",score:Math.max(0,Math.min(10,Math.round(s))),max:10,findings:t,suggestions:r}}async function gt(e){let{content:t,skillPath:r,skillMdPath:s,rootEntries:o}=e,n=q(t),{rawFrontmatter:a,body:l}=Ur(t),c=[Xi(n,l,a,o),Qi(n,l),ea(n,l),ta(n,l),ra(n,l),sa(n,l),oa(n,l,o),na(n,l)],[d,u]=await Promise.all([ua(r),ma(r)]),p=[...c,d,u];if(n.name&&ro(r)===n.name){let v=p.find(S=>S.id==="naming");v.score<v.max&&(v.score=Math.min(v.max,v.score+1),v.findings.push("Directory name matches frontmatter `name`."))}let f=p.reduce((v,S)=>v+S.score,0),m=p.reduce((v,S)=>v+S.max,0),g=Math.round(f/m*100),h="F";g>=90?h="A":g>=80?h="B":g>=65?h="C":g>=50&&(h="D");let y=[];p.find(v=>v.id==="structure")?.suggestions.includes(qt)&&y.push(qt);let $=[...p].sort((v,S)=>v.score/v.max-S.score/S.max);for(let v of $){for(let S of v.suggestions){if(y.length>=3)break;y.includes(S)||y.push(S)}if(y.length>=3)break}return{skillPath:r,skillMdPath:s,evaluatedAt:new Date().toISOString(),categories:p,overallScore:g,grade:h,topSuggestions:y,frontmatter:n}}async function so(e){let t=ya(e)?e:ha(e),r;try{r=await fa(t)}catch{throw new Error(`Skill path does not exist: ${t}`)}let s,o;if(r.isFile())return s=t,o=await to(s,"utf-8"),gt({content:o,skillPath:ro(t)==="SKILL.md"?ro(t):t,skillMdPath:s});if(!r.isDirectory())throw new Error(`Skill path is not a directory or file: ${t}`);s=ga(t,"SKILL.md");try{o=await to(s,"utf-8")}catch{throw new Error(`SKILL.md not found in ${t}. Run "asm init" to create one.`)}let n;try{n=await Mp(t)}catch{n=void 0}return gt({content:o,skillPath:t,skillMdPath:s,rootEntries:n})}function Fp(e){return e<=20?"low":e<=80?"medium":e<=250?"high":"max"}function jp(e){let t=e.split(`
195
+ `),r=[],s=[],o=0;for(;o<t.length;){let d=t[o];if(!d.trim()){o++;continue}let p=d.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);if(!p)return{newFrontmatter:e,changed:!1};let f=p[1],m=p[2];if(m===""||m===">"||m==="|"){let g=[d];for(o++;o<t.length;){let h=t[o];if(h.trim()===""){g.push(h),o++;continue}if(/^\s+/.test(h))g.push(h),o++;else break}s.push({key:f,text:g.join(`
196
+ `)})}else r.push({key:f,text:d}),o++}let n=d=>{let u=_r.indexOf(d);return u===-1?_r.length+1:u},a=[...r].sort((d,u)=>{let p=n(d.key),f=n(u.key);return p!==f?p-f:r.indexOf(d)-r.indexOf(u)}),l=a.some((d,u)=>d!==r[u]);return{newFrontmatter:[...a.map(d=>d.text),...s.map(d=>d.text)].join(`
197
+ `),changed:l}}function ba(e,t={}){let r=[],s=[],o=e.replace(/\r\n/g,`
198
+ `);o!==e&&r.push({id:"normalise-line-endings",description:"Convert CRLF line endings to LF."});let n=o.split(`
199
+ `),a=n.map(y=>y.replace(/[ \t]+$/g,""));a.some((y,b)=>y!==n[b])&&r.push({id:"strip-trailing-whitespace",description:"Strip trailing whitespace from lines."}),o=a.join(`
200
+ `);let{rawFrontmatter:l,body:c}=Ur(o),d=q(o);if(l===null)return s.push({id:"missing-frontmatter",description:"SKILL.md has no frontmatter \u2014 not auto-fixable (requires author decisions)."}),{newContent:o,applied:r,skipped:s};let u=l;if(d.version||d["metadata.version"]||(u=eo(u,"version","0.1.0"),r.push({id:"add-missing-version",description:"Add `version: 0.1.0`."})),!!!(d.author||d["metadata.author"]||d.creator||d["metadata.creator"])){let y=t.gitAuthor?.trim();y?(u=eo(u,"author",y),r.push({id:"add-missing-author",description:`Add \`author: ${y}\` from git config.`})):s.push({id:"add-missing-author",description:"Missing `author` \u2014 no git user.name found to fill in safely."})}if(!d.effort){let y=Fp(Xs(c));u=eo(u,"effort",y),r.push({id:"infer-missing-effort",description:`Infer \`effort: ${y}\` from body size.`})}d.description||s.push({id:"missing-description",description:"Missing `description` \u2014 content-level fix, left to the author."});let m=jp(u);m.changed&&(r.push({id:"reorder-frontmatter",description:"Reorder frontmatter fields to canonical order."}),u=m.newFrontmatter);let g=c.replace(/^\n+/,""),h=`---
201
+ ${u.replace(/^\n+|\n+$/g,"")}
340
202
  ---
341
203
 
342
204
  ${g}`;return h.endsWith(`
343
205
  `)||(h+=`
344
206
  `),e.replace(/\r\n/g,`
345
- `),{newContent:h,applied:s,skipped:i}}function Ra(e,t,s){if(new RegExp(`^${t}:\\s*`,"m").test(e))return e;let r=/[:#{}[\],&*?|<>=!%@`"']/.test(s)?JSON.stringify(s):s,n=e.length===0||e.endsWith(`
207
+ `),{newContent:h,applied:r,skipped:s}}function eo(e,t,r){if(new RegExp(`^${t}:\\s*`,"m").test(e))return e;let o=/[:#{}[\],&*?|<>=!%@`"']/.test(r)?JSON.stringify(r):r,n=e.length===0||e.endsWith(`
346
208
  `)?"":`
347
- `;return`${e}${n}${t}: ${r}
348
- `}function Kr(e,t,s="SKILL.md"){if(e===t)return"";let i=e.split(`
349
- `),r=t.split(`
350
- `),n=[`--- a/${s}`,`+++ b/${s}`],o=0;for(;o<i.length&&o<r.length&&i[o]===r[o];)o++;let a=0;for(;a<i.length-o&&a<r.length-o&&i[i.length-1-a]===r[r.length-1-a];)a++;let c=i.slice(o,i.length-a),u=r.slice(o,r.length-a),f=o+1,d=o+1;n.push(`@@ -${f},${c.length} +${d},${u.length} @@`);let p=i.slice(Math.max(0,o-3),o).map(g=>` ${g}`),m=i.slice(i.length-a,Math.min(i.length,i.length-a+3)).map(g=>` ${g}`);n.push(...p);for(let g of c)n.push(`-${g}`);for(let g of u)n.push(`+${g}`);return n.push(...m),n.join(`
351
- `)}async function Ma(e,t){let s=xp(e)?e:$p(e),i,r=await vp(s).catch(()=>null);if(!r)throw new Error(`Skill path does not exist: ${s}`);if(r.isFile())i=s;else if(r.isDirectory())i=Sp(s,"SKILL.md");else throw new Error(`Skill path is not a directory or file: ${s}`);let n;try{n=await Na(i,"utf-8")}catch{throw new Error(`SKILL.md not found at ${i}.`)}let o=Ep(n,{gitAuthor:t.gitAuthor}),a=Kr(n,o.newContent),c=null;return!t.dryRun&&o.newContent!==n&&(c=`${i}.bak`,await zS(i,c),await YS(i,o.newContent,"utf-8")),{report:await Ht({content:t.dryRun?n:o.newContent,skillPath:s,skillMdPath:i}),applied:o.applied,skipped:o.skipped,diff:a,dryRun:t.dryRun,backupPath:c,skillMdPath:i}}async function Da(){try{let{stdout:e,exitCode:t}=await oe(["git","config","--global","--get","user.name"]);if(t!==0)return null;let s=e.trim();return s||null}catch{return null}}function e$(e,t,s=20){let i=Math.round(e/t*s);return"\u2588".repeat(i)+"\u2591".repeat(Math.max(0,s-i))}function Ys(e){let t=[];t.push(`Skill evaluation: ${e.skillPath}`),t.push(`SKILL.md: ${e.skillMdPath}`),t.push(""),t.push(`Overall score: ${e.overallScore}/100 (${e.grade})`);let s=(e.providers??[]).filter(i=>i.id!=="quality");for(let i of s){let r=i.passed?"pass":"fail",n=`${i.id}@${i.version}`;t.push(` ${n}: ${i.score}/100 ${r}`)}t.push(""),t.push("Categories:");for(let i of e.categories)t.push(` ${i.name.padEnd(28)} ${String(i.score).padStart(2)}/${i.max} ${e$(i.score,i.max)}`);if(t.push(""),e.topSuggestions.length>0){t.push("Top suggestions:");for(let i of e.topSuggestions)t.push(` \u2022 ${i}`)}else t.push("No suggestions \u2014 skill looks great.");for(let i of s){let r=t$(i.raw);if(r&&r.length>0){t.push(""),t.push(`${i.id}@${i.version} breakdown:`);for(let n of r){let o=n.passed?"\u221A":n.severity==="warning"?"\u26A0":"\xD7";t.push(` ${o} ${n.label}`),n.passed||t.push(` [${n.severity}] ${n.message}`)}continue}if(i.findings.length!==0){t.push(""),t.push(`${i.id}@${i.version} findings:`);for(let n of i.findings)t.push(` [${n.severity}] ${n.message}`)}}return t.join(`
352
- `)}function t$(e){if(!e||typeof e!="object")return null;let t=e.checks;if(!Array.isArray(t))return null;let s=[];for(let i of t){if(!i||typeof i!="object")return null;let r=i;if(typeof r.id!="string"||typeof r.label!="string"||typeof r.passed!="boolean"||typeof r.message!="string"||r.severity!=="error"&&r.severity!=="warning")return null;s.push({id:r.id,label:r.label,passed:r.passed,severity:r.severity,message:r.message})}return s}function Fa(e){return JSON.stringify(e,null,2)}function _a(e){let t=[];if(e.applied.length===0&&e.skipped.length===0)return t.push("No fixes needed \u2014 SKILL.md is already clean."),t.join(`
353
- `);if(e.applied.length>0){t.push(`${e.dryRun?"Would apply":"Applied"} ${e.applied.length} fix(es):`);for(let s of e.applied)t.push(` \u2022 ${s.description}`)}if(e.skipped.length>0){t.push(""),t.push(`Skipped ${e.skipped.length} issue(s) (not auto-fixable):`);for(let s of e.skipped)t.push(` \u2022 ${s.description}`)}return e.diff&&(t.push(""),t.push("Diff:"),t.push(e.diff)),!e.dryRun&&e.backupPath&&(t.push(""),t.push(`Backup: ${e.backupPath}`)),t.join(`
354
- `)}import{stat as Gr,readdir as s$}from"fs/promises";import{join as Hr,resolve as i$,basename as Jt,isAbsolute as r$}from"path";async function Cp(e){let t;try{t=await s$(e)}catch{return[]}let s=[];for(let i of t){if(i.startsWith(".")||i==="node_modules"||i==="dist"||i==="build")continue;let r=Hr(e,i),n;try{n=await Gr(r)}catch{continue}if(!n.isDirectory())continue;let o=Hr(r,"SKILL.md");try{(await Gr(o)).isFile()&&s.push(r)}catch{}}return s.sort((i,r)=>Jt(i).localeCompare(Jt(r))),s}async function ja(e){let t=Hr(e,"SKILL.md");try{if((await Gr(t)).isFile())return{kind:"single",skillDirs:[e]}}catch{}let s=await Cp(e);return s.length>0?{kind:"collection",skillDirs:s}:{kind:"none",skillDirs:[]}}function Wt(e){return e?!!(e.startsWith("github:")||/^https?:\/\/github\.com\//i.test(e)):!1}function Pp(e){return{skillPath:e,skillMdPath:Hr(e,"SKILL.md"),label:Jt(e)}}async function Ba(e,t={}){if(!e)throw new Error("resolveEvalInput: input must be a non-empty string");if(Wt(e)){if(!t.fetchRemote)throw new Error(`Remote evaluation is not available in this context: "${e}"`);let n=await t.fetchRemote(e),o;try{o=await ja(n.rootDir)}catch(a){throw await n.cleanup().catch(()=>{}),a}if(o.kind==="none")throw await n.cleanup().catch(()=>{}),new Error(`No SKILL.md found at ${n.rootDir} (source: ${e}). The location is neither a single skill nor a skill collection.`);return{targets:o.skillDirs.map(Pp),isCollection:o.kind==="collection",cleanup:n.cleanup,provenance:{input:e,remote:!0,sourceRef:n.sourceRef,commitSha:n.commitSha,tempPath:n.rootDir}}}let s=r$(e)?e:i$(e),i;try{i=await Gr(s)}catch{throw new Error(`Skill path does not exist: ${s}`)}if(i.isFile())return{targets:[{skillPath:Jt(s)==="SKILL.md"?Jt(s):s,skillMdPath:s,label:Jt(s)}],isCollection:!1,cleanup:async()=>{},provenance:{input:e,remote:!1,sourceRef:null}};if(!i.isDirectory())throw new Error(`Skill path is not a directory or file: ${s}`);let r=await ja(s);if(r.kind==="none")throw new Error(`No SKILL.md found in ${s}. Pass a skill directory, a SKILL.md file, or a collection root with SKILL.md in its children.`);return{targets:r.skillDirs.map(Pp),isCollection:r.kind==="collection",cleanup:async()=>{},provenance:{input:e,remote:!1,sourceRef:null}}}function qa(e){let t=e.filter(f=>f.report!==null),s=e.length,i=s-t.length;if(t.length===0)return{total:s,succeeded:0,failed:i,meanScore:null,top:null,bottom:null};let r=t.map(f=>f.report.overallScore),n=r.reduce((f,d)=>f+d,0)/r.length,o=Math.round(n),a=[...t].sort((f,d)=>d.report.overallScore-f.report.overallScore),c=a[0],u=a[a.length-1];return{total:s,succeeded:t.length,failed:i,meanScore:o,top:{label:c.label,score:c.report.overallScore},bottom:{label:u.label,score:u.report.overallScore}}}async function zs(e,t,s){let i=new Array(e.length),r=0,n=!1,o,a=Math.max(1,Math.floor(t)),c=[],u=Math.min(a,e.length);for(let f=0;f<u;f++)c.push((async()=>{for(;!n;){let d=r++;if(d>=e.length)break;try{i[d]=await s(e[d],d)}catch(p){n||(n=!0,o=p);break}}})());if(await Promise.all(c),n)throw o;return i}function Ua(e,t=28){let s=[];return s.push(""),s.push("Batch summary:"),s.push(` Skills evaluated: ${e.aggregate.succeeded}/${e.aggregate.total}`+(e.aggregate.failed>0?` (${e.aggregate.failed} failed)`:"")),e.aggregate.meanScore!==null&&s.push(` Mean score: ${e.aggregate.meanScore}/100`),e.aggregate.top&&s.push(` Top: ${e.aggregate.top.label} (${e.aggregate.top.score}/100)`),e.aggregate.bottom&&e.aggregate.bottom.label!==e.aggregate.top?.label&&s.push(` Bottom: ${e.aggregate.bottom.label} (${e.aggregate.bottom.score}/100)`),e.provenance.remote&&(e.provenance.sourceRef&&s.push(` Source: ${e.provenance.sourceRef}`),e.provenance.commitSha&&s.push(` Commit: ${e.provenance.commitSha}`),e.provenance.tempPath&&s.push(` Fetched to: ${e.provenance.tempPath}`)),s.join(`
355
- `)}function Va(e){return{provenance:{input:e.provenance.input,remote:e.provenance.remote,source_ref:e.provenance.sourceRef??null,commit_sha:e.provenance.commitSha??null,temp_path:e.provenance.tempPath??null},aggregate:{total:e.aggregate.total,succeeded:e.aggregate.succeeded,failed:e.aggregate.failed,mean_score:e.aggregate.meanScore,top:e.aggregate.top,bottom:e.aggregate.bottom},results:e.results.map(t=>({label:t.label,skill_path:t.skillPath,error:t.error,report:t.report?Xs(t.report,null):null}))}}function Xs(e,t=null){return{skill_path:e.skillPath,skill_md_path:e.skillMdPath,overall_score:e.overallScore,grade:e.grade,categories:e.categories.map(s=>({id:s.id,name:s.name,score:s.score,max:s.max,findings:s.findings,suggestions:s.suggestions})),top_suggestions:e.topSuggestions,providers:e.providers?.map(s=>({id:s.id,version:s.version,schemaVersion:s.schemaVersion,score:s.score,passed:s.passed,categories:s.categories.map(i=>({id:i.id,name:i.name,score:i.score,max:i.max,findings:i.findings??[]})),findings:s.findings}))??[],fix:t?{dry_run:t.dryRun,applied:t.applied,skipped:t.skipped,backup_path:t.backupPath,diff:t.diff}:null}}import{access as jp,copyFile as p$,cp as m$,mkdtemp as Bp,lstat as qp,mkdir as Qa,readdir as h$,readFile as el,readlink as g$,realpath as si,rename as Wr,rm as st}from"fs/promises";import{execFile as y$}from"child_process";import{createHash as b$}from"crypto";import{promisify as w$}from"util";import{dirname as ii,isAbsolute as tl,join as ve,relative as Up,resolve as xe}from"path";import{execFile as n$}from"child_process";import{promisify as o$}from"util";import{join as a$}from"path";var l$=o$(n$),c$=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_IMPLICIT_WORK_TREE","GIT_GRAFT_FILE","GIT_SHALLOW_FILE","GIT_NO_REPLACE_OBJECTS","GIT_REPLACE_REF_BASE","GIT_PREFIX","GIT_INTERNAL_SUPER_PREFIX","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM","GIT_NAMESPACE","GIT_QUARANTINE_PATH","GIT_CONFIG","GIT_CONFIG_PARAMETERS","GIT_CONFIG_COUNT"];function Lp(e){let t={...process.env};for(let s of c$)delete t[s];for(let s of Object.keys(t))/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(s)&&delete t[s];return t.GIT_DEFAULT_HASH=e,t}var Ka=new WeakMap;function Ip(e,t){return Ka.set(e,t),e}function Ap(e){return e.normalize("NFC").toLowerCase().normalize("NFC")}async function Ga(e,t,s){let i=new Array(e.length),r=0;async function n(){for(;r<e.length;){let a=r++;i[a]=await s(e[a])}}let o=[];for(let a=0;a<Math.min(t,e.length);a++)o.push(n());return await Promise.all(o),i}async function Rp(e,t){try{let s=["ls-remote",e];t?s.push(t,`${t}^{}`):s.push("HEAD");let{stdout:i}=await l$("git",s,{timeout:1e4}),r=new Map;for(let n of i.split(`
356
- `)){let[o,a]=n.trim().split(/\s+/);a&&o&&/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(o)&&r.set(a,o)}return!t||t==="HEAD"?r.get("HEAD")??null:t.startsWith("refs/")?r.get(`${t}^{}`)??r.get(t)??null:r.get(`refs/heads/${t}`)??r.get(`refs/tags/${t}^{}`)??r.get(`refs/tags/${t}`)??null}catch(s){return L(`updater: git ls-remote failed for ${e}: ${s}`),null}}function Zs(e){return e.sourceType?e.sourceType:e.source.startsWith("local:")?"local":"github"}function Yt(e){if(e.startsWith("github:")){let t=e.slice(7),s=t.indexOf("#");return s!==-1&&(t=t.slice(0,s)),`https://github.com/${t}.git`}return e.startsWith("file://")?e:null}function Ha(e){if(!e.startsWith("github:"))return null;let t=e.slice(7),s=t.indexOf("#");s!==-1&&(t=t.slice(0,s));let i=t.split("/");return i.length<2||!i[0]||!i[1]?null:{owner:i[0],repo:i[1]}}function Np(e,t){return t.skillPath?a$(e,t.skillPath):e}async function Qs(e){let t=e?.readLockFn??Ke,s=e?.fetchRegistryIndexFn??Pa,i=e?.lock??await t(),r=Object.entries(i.skills);if(r.length===0)return{entries:[],outdatedCount:0,upToDateCount:0,untrackedCount:0,errorCount:0};let n=null;r.some(([,c])=>Zs(c)==="registry"||c.registryName)&&(n=await s());let a=await Ga(r,5,async([c,u])=>{let f=Zs(u);if(!u.commitHash||u.commitHash==="unknown")return{name:c,installedCommit:u.commitHash||"unknown",latestCommit:"unknown",source:u.source,sourceType:f,status:"untracked"};if(f==="local")return{name:c,installedCommit:u.commitHash,latestCommit:u.commitHash,source:u.source,sourceType:f,status:"up-to-date"};if(f==="registry"&&n){let g=u.registryName||c,h=n.manifests.find(y=>y.name.toLowerCase()===g.toLowerCase());if(h){let y=h.commit!==u.commitHash;return Ip({name:c,installedCommit:$e(u.commitHash),latestCommit:$e(h.commit),source:u.source,sourceType:f,status:y?"outdated":"up-to-date"},h.commit)}}let d=Yt(u.source);if(!d)return{name:c,installedCommit:$e(u.commitHash),latestCommit:"unknown",source:u.source,sourceType:f,status:"error",error:"Cannot determine remote URL"};let p=await Rp(d,u.ref);if(!p)return{name:c,installedCommit:$e(u.commitHash),latestCommit:"unknown",source:u.source,sourceType:f,status:"error",error:"Failed to fetch remote commit"};let m=p!==u.commitHash;return Ip({name:c,installedCommit:$e(u.commitHash),latestCommit:$e(p),source:u.source,sourceType:f,status:m?"outdated":"up-to-date"},p)});return{entries:a,outdatedCount:a.filter(c=>c.status==="outdated").length,upToDateCount:a.filter(c=>c.status==="up-to-date").length,untrackedCount:a.filter(c=>c.status==="untracked").length,errorCount:a.filter(c=>c.status==="error").length}}function $e(e){return!e||e==="unknown"?"unknown":e.slice(0,7)}import{execFile as u$}from"child_process";import{promisify as d$}from"util";import{join as Jr}from"path";import{homedir as Tp}from"os";import{mkdir as Op,rm as bt,rename as Ja,cp as Mp,access as f$}from"fs/promises";var ei=d$(u$);async function Dp(e,t,s,i,r){if(Zs(t)==="local")return{name:e,status:"skipped",reason:"Local skill (not updatable)"};let o;if(r!==void 0){if(!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(r))return{name:e,status:"failed",reason:"Invalid known commit OID"};if(o=r.toLowerCase(),o===t.commitHash.toLowerCase())return{name:e,status:"skipped",reason:"Already up to date"}}let a=Yt(t.source);if(!a)return{name:e,status:"failed",reason:"Cannot determine remote URL"};let c=Jr(Tp(),".config","agent-skill-manager",".tmp",`${e}-${Date.now()}`);try{let u=Jr(Tp(),".config","agent-skill-manager",".tmp");if(await Op(u,{recursive:!0}),L(`updater: fetching latest ${e} to ${c}`),o)try{let S=o.length===40?"sha1":"sha256",P=Lp(S);await ei("git",["init",c],{timeout:1e4,env:P}),await ei("git",["fetch","--depth","1",a,o],{cwd:c,timeout:6e4,env:P}),await ei("git",["checkout","--detach",o],{cwd:c,timeout:1e4,env:P})}catch{return{name:e,status:"failed",reason:"Resolved commit is unavailable in the shallow fetch"}}else{let S=["clone","--depth","1"];t.ref&&t.ref!=="HEAD"&&S.push("--branch",t.ref),S.push(a,c);try{await ei("git",S,{timeout:6e4})}catch(P){let B=P;return{name:e,status:"failed",reason:`Clone failed: ${B.stderr||B.message||String(P)}`}}}let f;if(o)f=o;else try{let{stdout:S}=await ei("git",["rev-parse","HEAD"],{cwd:c,timeout:5e3});f=S.trim().toLowerCase()}catch{return{name:e,status:"failed",reason:"Could not read new commit"}}if(f===t.commitHash)return{name:e,status:"skipped",reason:"Already up to date"};let d=Np(c,t);L(`updater: running security audit on ${e}`);let p="safe";try{let S=i?.auditFn??Me,P=Ha(t.source);if(p=(await S(d,e,P?.owner,P?.repo)).verdict,p==="dangerous")return{name:e,status:"skipped",reason:"Security audit: dangerous \u2014 update blocked",securityVerdict:p};if(p==="warning"||p==="caution"){if(!s)return{name:e,status:"skipped",reason:`Security audit: ${p} \u2014 use --yes to override`,securityVerdict:p};L(`updater: security audit ${p} for ${e} \u2014 proceeding (--yes)`)}}catch(S){let P=S instanceof Error?S.message:String(S);return L(`updater: security audit failed for ${e}: ${P}`),{name:e,status:"failed",reason:`Security audit failed \u2014 skipping update: ${P}`}}let m=i?.loadConfigFn??j,g=i?.resolveProviderPathFn??ie,y=(await m()).providers.find(S=>S.name===t.provider),b=t.scope??"global",k=y?b==="project"?y.project:y.global:`~/.${t.provider}/skills`,w=g(k),v=Jr(w,e),x=Jr(c,".git");try{await bt(x,{recursive:!0,force:!0})}catch{}let C=!0;try{await f$(v)}catch(S){if(!(S instanceof Error)||!("code"in S)||S.code!=="ENOENT"){let P=S instanceof Error?S.message:String(S);return{name:e,status:"failed",reason:`Cannot access installed skill: ${P}`}}C=!1}let A=i?.writeLockEntryFn??Et,E={...t,commitHash:f,installedAt:new Date().toISOString()};if(!C){try{await Op(w,{recursive:!0}),await Mp(d,v,{recursive:!0})}catch(S){await bt(v,{recursive:!0,force:!0});let P=S instanceof Error?S.message:String(S);return{name:e,status:"failed",reason:`Atomic swap failed: ${P}`}}try{await A(e,E)}catch(S){try{await bt(v,{recursive:!0,force:!0})}catch(B){let te=S instanceof Error?S.message:String(S),ce=B instanceof Error?B.message:String(B);return{name:e,status:"failed",reason:`Lock file update failed: ${te}. Removal of the new installation also failed: ${ce}`}}let P=S instanceof Error?S.message:String(S);return{name:e,status:"failed",reason:`Lock file update failed: ${P}`}}return{name:e,status:"updated",oldCommit:$e(t.commitHash),newCommit:$e(f),securityVerdict:p}}let _=`${v}.bak-${Date.now()}`,O=!1;try{await Ja(v,_),O=!0,await Mp(d,v,{recursive:!0})}catch(S){if(O)try{await bt(v,{recursive:!0,force:!0}),await Ja(_,v),O=!1}catch(P){let B=S instanceof Error?S.message:String(S),te=P instanceof Error?P.message:String(P);return{name:e,status:"failed",reason:`Atomic swap failed: ${B}. Restore also failed; backup preserved at ${_}: ${te}`}}return{name:e,status:"failed",reason:`Atomic swap failed: ${S instanceof Error?S.message:String(S)}`}}try{await A(e,E)}catch(S){try{await bt(v,{recursive:!0,force:!0}),await Ja(_,v),O=!1}catch(B){let te=S instanceof Error?S.message:String(S),ce=B instanceof Error?B.message:String(B);return{name:e,status:"failed",reason:`Lock file update failed: ${te}. Restore also failed; backup preserved at ${_}: ${ce}`}}let P=S instanceof Error?S.message:String(S);return{name:e,status:"failed",reason:`Lock file update failed: ${P}`}}if(O)try{await bt(_,{recursive:!0,force:!0})}catch(S){L(`updater: failed to remove backup ${_}: ${S}`)}return{name:e,status:"updated",oldCommit:$e(t.commitHash),newCommit:$e(f),securityVerdict:p}}finally{try{await bt(c,{recursive:!0,force:!0})}catch{}}}async function Wa(e,t,s){let i=s?.readLockFn??Ke,r=s?.checkOutdatedFn??Qs,n=s?.updateSkillFn??Dp,o=await i(),a=await r({lock:o}),c=a.entries.filter(y=>y.status==="outdated"),u=[];if(e&&e.length>0){let y=new Set(e.map(b=>b.toLowerCase()));c=c.filter(b=>y.has(b.name.toLowerCase()));for(let b of e)c.find(k=>k.name.toLowerCase()===b.toLowerCase())||(a.entries.find(w=>w.name.toLowerCase()===b.toLowerCase())?L(`updater: skill "${b}" is already up to date`):(L(`updater: skill "${b}" not found in lock file`),u.push(b)))}if(c.length===0)return{results:[],updatedCount:0,skippedCount:0,failedCount:0,...u.length>0?{warnings:u}:{}};let f=c.flatMap(y=>{let b=o.skills[y.name];return b?[{name:y.name,lockEntry:b,knownLatestCommit:Ka.get(y)}]:[]}),d=s?.writeLockEntryFn??Et,p=Promise.resolve(),m=(y,b)=>{let k=p.then(()=>d(y,b));return p=k.then(()=>{},()=>{}),k},g=new Map;f.forEach((y,b)=>{let k=Ap(y.name),w=g.get(k)??[];w.push({...y,index:b}),g.set(k,w)});let h=new Array(f.length);return await Ga([...g.values()],4,async y=>{for(let b of y)try{h[b.index]=await n(b.name,b.lockEntry,t,{writeLockEntryFn:m},b.knownLatestCommit)}catch(k){let w=k instanceof Error?k.message:String(k);h[b.index]={name:b.name,status:"failed",reason:`Unexpected update failure: ${w}`}}}),{results:h,updatedCount:h.filter(y=>y.status==="updated").length,skippedCount:h.filter(y=>y.status==="skipped").length,failedCount:h.filter(y=>y.status==="failed").length,...u.length>0?{warnings:u}:{}}}function Ya(e,t){if(e.entries.length===0)return"No skills installed.";let s=d=>d,i=t?l.red:s,r=t?l.green:s,n=t?l.yellow:s,o=t?l.dim:s,a=`${"Skill".padEnd(22)}${"Installed".padEnd(14)}${"Latest".padEnd(14)}Source`,c="\u2500".repeat(60),u=[a,c];for(let d of e.entries){let p=d.name.padEnd(22),m=d.installedCommit.padEnd(14),g,h;switch(d.status){case"outdated":g=i(d.latestCommit.padEnd(14)),h=d.sourceType;break;case"up-to-date":g=r(d.latestCommit.padEnd(14)),h=o("(up to date)");break;case"untracked":g=n("untracked".padEnd(14)),h=n("untracked");break;case"error":g=o("error".padEnd(14)),h=o(d.error||"error");break}u.push(`${p}${m}${g}${h}`)}u.push("");let f=[];return e.outdatedCount>0&&f.push(i(`${e.outdatedCount} outdated`)),e.upToDateCount>0&&f.push(r(`${e.upToDateCount} up to date`)),e.untrackedCount>0&&f.push(n(`${e.untrackedCount} untracked`)),e.errorCount>0&&f.push(o(`${e.errorCount} error`)),u.push(f.join(", ")),u.join(`
357
- `)}function za(e){return JSON.stringify({skills:e.entries.map(t=>({name:t.name,installed:t.installedCommit,latest:t.latestCommit,source:t.sourceType,status:t.status,...t.error?{error:t.error}:{}})),summary:{outdated:e.outdatedCount,upToDate:e.upToDateCount,untracked:e.untrackedCount,errors:e.errorCount}},null,2)}function Xa(e){return JSON.stringify({results:e.results.map(t=>({name:t.name,status:t.status,...t.reason?{reason:t.reason}:{},...t.oldCommit?{oldCommit:t.oldCommit}:{},...t.newCommit?{newCommit:t.newCommit}:{},...t.securityVerdict?{securityVerdict:t.securityVerdict}:{}})),summary:{updated:e.updatedCount,skipped:e.skippedCount,failed:e.failedCount}},null,2)}var ti=w$(y$),k$=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/,Fp=128,v$=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Za(){return{version:1,skills:{}}}async function ri(e=nt()){return Yr(e)}async function wt(e=nt()){let t=await ri(e),s=[];for(let[i,r]of Object.entries(t.skills)){let n=!1;try{await jp(ve(r.libraryPath,"SKILL.md"))}catch{n=!0}s.push({dirName:i,...r,missing:n})}return s.sort((i,r)=>i.name.localeCompare(r.name)),s}function ni(e,t){let s=e.find(r=>r.dirName===t);return s||(e.find(r=>r.name===t)??null)}function ee(e,t){return{name:e,status:"failed",reason:t}}async function Vp(e,t,s){return e.sourceType!==t.sourceType||xe(e.libraryPath)!==xe(t.libraryPath)?!1:e.sourceType==="local"?s?await S$(e)===s:!1:e.source===t.source&&e.ref===t.ref&&e.skillPath===t.skillPath}function sl(e){return ee(e,`Library skill "${e}" changed while update was in progress. Run "asm library update ${e}" again.`)}function il(e){let t=Date.parse(e??""),s=Number.isFinite(t)?Math.max(Date.now(),t+1):Date.now();return new Date(s).toISOString()}function rl(e){if(!e.source.startsWith("local:"))return null;let t=e.source.slice(6);return t?xe(t):null}async function S$(e){let t=rl(e);if(!t)throw new Error("Unsupported library source for update");let s=zr(t,ve(t,e.skillPath));if(!s)throw new Error("Invalid update metadata: skillPath escapes source root");let[i,r]=await Promise.all([si(t),si(s)]);if(!oi(i,r))throw new Error("Invalid update metadata: skillPath escapes source root");return r}async function Yr(e){let t;try{t=await el(e,"utf-8")}catch(s){if(s instanceof Error&&"code"in s&&s.code==="ENOENT")return L("library: lock file not found, returning empty lock"),Za();throw s}try{let s=JSON.parse(t);if(!s||typeof s!="object"||Array.isArray(s)||s.version!==1||typeof s.skills!="object"||s.skills===null||Array.isArray(s.skills))throw new Error("invalid schema");return s}catch{let s=e+".bak";try{await p$(e,s)}catch{}return console.error(`Warning: library-lock.json was corrupted. Backup saved to ${s}. Starting fresh.`),Za()}}async function nl(e,t){await Ql(t,JSON.stringify(e,null,2)+`
358
- `)}function Kp(e){let t=e.name?.trim();if(!t)return{reason:"Invalid source SKILL.md: missing name"};let s=(e["metadata.version"]||e.version)?.trim();return s?v$.test(s)?{name:t,version:s}:{reason:"Invalid source SKILL.md: invalid version"}:{reason:"Invalid source SKILL.md: missing version"}}function oi(e,t){let s=xe(e),i=xe(t),r=Up(s,i);return r===""||!!r&&!r.startsWith("..")&&!tl(r)}function zr(e,t){let s=xe(e),i=xe(t);return oi(s,i)?i:null}async function $$(e){let t=xe(e);for(;;)try{return await si(t)}catch(s){if(!(s instanceof Error)||!("code"in s)||s.code!=="ENOENT")throw s;let i=ii(t);if(i===t)throw s;t=i}}async function Gp(e,t){try{let[s,i]=await Promise.all([si(e),$$(t)]);return oi(s,i)}catch{return!1}}async function Hp(e){let t=b$("sha256");async function s(i,r){let n=await h$(i,{withFileTypes:!0});n.sort((o,a)=>o.name.localeCompare(a.name));for(let o of n){if(o.name===".git")continue;let a=r?ve(r,o.name):o.name,c=ve(i,o.name);o.isDirectory()?(t.update(`dir:${a}
359
- `),await s(c,a)):o.isFile()&&(t.update(`file:${a}
360
- `),t.update(await el(c)),t.update(`
361
- `))}}return await s(e,""),t.digest("hex")}async function Jp(e,t,s){let i=Yt(e.source);if(!i)return{reason:"Cannot determine remote URL"};let r=ve(ii(s),".tmp");await Qa(r,{recursive:!0});let n=await Bp(ve(r,`${t}-`)),o=e.ref&&e.ref!=="HEAD"?e.ref:null,a=!!o&&/^[0-9a-f]{40}$/i.test(o),c=["clone","--depth","1"];o&&!a&&c.push("--branch",o),c.push(i,n);try{await ti("git",c,{timeout:6e4})}catch(u){let f=u;return{tempDir:n,reason:`Clone failed: ${f.stderr||f.message||String(u)}`}}if(o&&a)try{await ti("git",["checkout",o],{cwd:n,timeout:3e4})}catch{try{await ti("git",["fetch","--depth","1","origin",o],{cwd:n,timeout:6e4}),await ti("git",["checkout","FETCH_HEAD"],{cwd:n,timeout:3e4})}catch(u){let f=u;return{tempDir:n,reason:`Checkout failed for ref ${o}: ${f.stderr||f.message||String(u)}`}}}try{let{stdout:u}=await ti("git",["rev-parse","HEAD"],{cwd:n,timeout:5e3}),f=u.trim();return/^[0-9a-f]{40}$/i.test(f)?{tempDir:n,commitHash:f}:{tempDir:n,reason:"Could not read new commit"}}catch{return{tempDir:n,reason:"Could not read new commit"}}}async function ol(e,t){let s=await Bp(ve(ii(t),".library-update-"));try{return await m$(e,s,{recursive:!0}),await st(ve(s,".git"),{recursive:!0,force:!0}),s}catch(i){throw await st(s,{recursive:!0,force:!0}),i}}async function al(e){let t=ii(e.targetDir),s=null,i=!1;try{try{await Wp(e.targetDir)&&(s=ve(t,`.library-update-backup-${Date.now()}`),await Wr(e.targetDir,s)),await Wr(e.stagedDir,e.targetDir);try{return await e.writeLock(),null}catch(r){if(r instanceof Zl)return{name:"",status:"failed",reason:`Lock metadata and library files were published as the new generation, but parent-directory durability could not be confirmed: ${r.cause instanceof Error?r.cause.message:String(r.cause)}`};if(await st(e.targetDir,{recursive:!0,force:!0}),s)try{await Wr(s,e.targetDir),s=null}catch{return i=!0,{name:"",status:"failed",reason:`Updated library copy, but failed to write lock file: ${r instanceof Error?r.message??String(r):String(r)}. Restore of previous library copy also failed; backup preserved at ${s}.`}}return{name:"",status:"failed",reason:`Updated library copy, but failed to write lock file: ${r instanceof Error?r.message??String(r):String(r)}`}}}catch(r){if(s)try{await Wr(s,e.targetDir),s=null}catch{i=!0}return{name:"",status:"failed",reason:`Failed to refresh library skill: ${r instanceof Error?r.message??String(r):String(r)}`}}}finally{await st(e.stagedDir,{recursive:!0,force:!0}),s&&!i&&await st(s,{recursive:!0,force:!0})}}function x$(e,t){let s=Up(e,t);return s===""||!!s&&!s.startsWith("..")&&!tl(s)}async function _p(e){try{return{path:await si(e),exists:!0}}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return{path:xe(e),exists:!1};throw t}}async function ll(e){let t=ul(e.activationName),s=ve(e.targetDir,t),i;try{i=await qp(s)}catch(p){throw p instanceof Error&&"code"in p&&p.code==="ENOENT"?new Error(`Skill "${t}" is not active for ${e.provider}/${e.scope}.`,{cause:p}):p}if(!i.isSymbolicLink())throw new Error(`Refusing to deactivate non-symlink target: ${s}.`);let r=await g$(s),n=tl(r)?r:xe(ii(s),r),o=e.librarySkillsDir??Fe(),a=await _p(n),c=await _p(o),u=a.exists&&c.exists,f=u?a.path:xe(n),d=u?c.path:xe(o);if(!x$(d,f))throw new Error(`Refusing to deactivate symlink outside the ASM library: ${s}.`);return await st(s),{name:t,provider:e.provider,scope:e.scope,path:s,target:f}}async function cl(e){let t=ul(e.activationName),s=ve(e.targetDir,t);try{let i=await qp(s);if(!e.force)throw new Error(`Target already exists: ${s}. Use --force to overwrite.`);if(!i.isSymbolicLink())throw new Error(`Refusing to overwrite non-symlink target: ${s}.`);await st(s,{force:!0})}catch(i){if(!(i instanceof Error&&"code"in i&&i.code==="ENOENT"))throw i}return await Qa(e.targetDir,{recursive:!0}),await Ve(e.libraryPath,s),{symlinkPath:s,targetPath:e.libraryPath}}async function Wp(e){try{return await jp(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function ul(e){if(!e)throw new Error("Invalid skill name: name cannot be empty");if(e.includes("\0"))throw new Error("Invalid skill name: contains unsafe characters (null byte)");if(e.includes(".."))throw new Error("Invalid skill name: contains unsafe characters (..)");if(e.includes("/")||e.includes("\\"))throw new Error("Invalid skill name: contains unsafe characters (path separator)");if(e.startsWith("."))throw new Error("Invalid skill name: must not start with a dot");if(e.length>Fp)throw new Error(`Invalid skill name: exceeds maximum length of ${Fp} characters`);if(!k$.test(e))throw new Error(`Invalid skill name: "${e}" does not match allowed pattern [a-zA-Z0-9][a-zA-Z0-9._-]*`);return e}async function dl(e,t={}){let s=t.skillsDir??Fe(),i=t.lockPath??nt(),r=ul(e.libraryName),n=ve(s,r);await Qa(s,{recursive:!0});let o=await ol(e.sourceDir,n);try{let a=await el(ve(o,"SKILL.md"),"utf-8"),c=W(a),u=c.name||r,f=fe(c);return await Ei(i,async()=>{let d=await Yr(i);if(await Wp(n)&&!e.force)throw new Error(`Library skill already exists: ${n}. Use --force to overwrite.`);let p={...d,skills:{...d.skills,[r]:{name:u,version:f,source:e.source,sourceType:e.sourceType,commitHash:e.commitHash,ref:e.ref,skillPath:e.skillPath,libraryPath:n,installedAt:il(d.skills[r]?.installedAt)}}},m=await al({stagedDir:o,targetDir:n,writeLock:()=>nl(p,i)});if(m)throw new Error(m.reason??"Failed to install library skill")}),{name:u,version:f,libraryPath:n}}finally{await st(o,{recursive:!0,force:!0})}}import{readFile as E$,realpath as Yp,rm as zp}from"fs/promises";import{join as fl}from"path";async function Xp(e,t={},s){let i=t.lockPath??nt(),r=t.skillsDir??Fe(),n=s?.writeLibraryLockFn??nl,o=await ri(i),a=o.skills[e]??null,c=Object.entries(o.skills).find(([,h])=>h.name===e)??null,u=a?[e,a]:c;if(!u)return ee(e,`Library skill "${e}" not found. Run "asm library list".`);let[f,d]=u,p={...d};if(!d.source||!d.source.trim())return ee(f,"Missing update metadata: source");if(!d.sourceType||!d.sourceType.trim())return ee(f,"Missing update metadata: sourceType");if(d.skillPath===void 0||d.skillPath===null)return ee(f,"Missing update metadata: skillPath");if(!d.libraryPath||!d.libraryPath.trim())return ee(f,"Missing update metadata: libraryPath");let m=null,g=null;try{let h,y=null;if(d.sourceType==="local"){let S=rl(d);if(!S)return ee(f,`Unsupported library source for update: ${d.source}`);h=S}else if(d.sourceType==="github"||d.sourceType==="registry"){let S=await Jp(d,f,i);if("reason"in S)return S.tempDir&&(m=S.tempDir),ee(f,S.reason);h=S.tempDir,m=S.tempDir,y=S.commitHash}else return ee(f,`Unsupported library source type for update: ${d.sourceType}`);let b=zr(h,fl(h,d.skillPath));if(!b)return ee(f,"Invalid update metadata: skillPath escapes source root");let k=fl(b,"SKILL.md"),w,v;try{[w,v]=await Promise.all([Yp(h),Yp(b)])}catch(S){return ee(f,`Unable to read source SKILL.md at ${k}: ${S instanceof Error?S.message??String(S):String(S)}`)}if(!oi(w,v))return ee(f,"Invalid update metadata: skillPath escapes source root");d.sourceType==="local"&&(g=v);let x;try{x=await E$(k,"utf-8")}catch(S){return ee(f,`Unable to read source SKILL.md at ${k}: ${S instanceof Error?S.message??String(S):String(S)}`)}let C=W(x),A=Kp(C);if("reason"in A)return ee(f,A.reason);let E=A.name,_=A.version;if(d.sourceType==="local"&&(y=await Hp(b)),!y)return ee(f,"Could not read new commit");let O=await ol(b,fl(r,f));try{return await Ei(i,async()=>{let S=await Yr(i),P=S.skills[f];if(!P)return ee(f,`Library skill "${f}" not found. Run "asm library list".`);let B=zr(r,P.libraryPath);if(!B)return ee(f,"Invalid update metadata: libraryPath escapes library skills directory");if(!await Gp(r,B))return ee(f,"Invalid update metadata: libraryPath escapes library skills directory");let te;try{te=await Vp(P,p,g)}catch{return sl(f)}let ce=P.installedAt===p.installedAt;if(ce&&te&&P.commitHash===y)return{name:P.name,status:"skipped",oldVersion:P.version,newVersion:_,oldCommit:P.commitHash,newCommit:y};if(!ce||!te||P.commitHash!==p.commitHash)return sl(f);let Pe={...S,skills:{...S.skills,[f]:{...P,name:E,version:_,commitHash:y,installedAt:il(P.installedAt)}}},R=await al({stagedDir:O,targetDir:B,writeLock:()=>n(Pe,i)});return R?ee(f,R.reason??"Failed to update library skill"):{name:E,status:"updated",oldVersion:P.version,newVersion:_,oldCommit:P.commitHash,newCommit:y}})}finally{await zp(O,{recursive:!0,force:!0})}}finally{m&&await zp(m,{recursive:!0,force:!0})}}async function pl(e,t={}){let s=t.lockPath??nt(),i=await ri(s),r=e===null?Object.keys(i.skills):e,n=[],o=[];for(let a of r){let c=await Xp(a,t);c.status==="failed"&&c.reason?.includes('Run "asm library list"')&&n.push(c.reason),o.push(c)}return{results:o,updatedCount:o.filter(a=>a.status==="updated").length,skippedCount:o.filter(a=>a.status==="skipped").length,failedCount:o.filter(a=>a.status==="failed").length,warnings:n}}import{join as nn}from"path";var P$=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function C$(e){if(typeof e!="string")return null;let t=P$.exec(e.trim());if(!t)return null;let[,s,i,r,n]=t;return{major:Number(s),minor:Number(i),patch:Number(r),prerelease:n?n.split("."):[]}}function I$(e,t){let s=C$(e);if(!s)throw new Error(`invalid semver: ${t} "${e}"`);return s}var ml=new Map;function hl(e){if(!e||typeof e.id!="string"||e.id.length===0)throw new Error("register: provider.id is required");if(I$(e.version,`provider ${e.id} version`),typeof e.schemaVersion!="number"||!Number.isInteger(e.schemaVersion))throw new Error(`register: provider ${e.id} schemaVersion must be an integer`);let t=ml.get(e.id)??[];if(t.some(s=>s.version===e.version))throw new Error(`register: provider ${e.id}@${e.version} already registered`);t.push(e),ml.set(e.id,t)}function Xr(){let e=[];for(let t of ml.values())for(let s of t)e.push(s);return e}import{stat as L$}from"fs/promises";var Zp="quality",Qp="1.0.0",em=1;function A$(e){return e.topSuggestions.map(t=>({severity:"info",message:t}))}function R$(e){return e.categories.map(t=>({id:t.id,name:t.name,score:t.score,max:t.max}))}var tm={id:Zp,version:Qp,schemaVersion:em,description:"Static linter for SKILL.md structure, description, and safety.",async applicable(e){try{return(await L$(e.skillMdPath)).isFile()?{ok:!0}:{ok:!1,reason:`${e.skillMdPath} is not a file`}}catch{return{ok:!1,reason:`SKILL.md not found at ${e.skillMdPath}`}}},async run(e,t){let s=await Oa(e.skillPath);return{providerId:Zp,providerVersion:Qp,schemaVersion:em,score:s.overallScore,passed:s.grade!=="F",categories:R$(s),findings:A$(s),raw:s,startedAt:"",durationMs:0}}};var om=Ml(ia(),1);import{readFile as N$,stat as T$}from"fs/promises";import{basename as O$}from"path";var sm="skill-best-practice",im="1.1.0",rm=1,M$=new Set(["name","description","license","allowed-tools","metadata","compatibility","effort"]),nm=new Set(["low","medium","high","xhigh","max"]),gl=250,D$=/^\d+\.\d+\.\d+$/;function F$(e){if(!e.startsWith("---"))return null;let t=e.split(`
362
- `);if(t.length<3||t[0]?.trim()!=="---")return null;let s=t.findIndex((i,r)=>r>0&&i.trim()==="---");return s===-1?null:t.slice(1,s).join(`
363
- `)}function Zr(e){return{severity:e.severity,message:e.message,code:e.id,categoryId:"validation"}}function ae(e,t,s,i,r,n){e.push({id:t,label:s,passed:i,severity:r,message:n})}function Qr(e,t,s){return{skillPath:e.skillPath,skillMdPath:e.skillMdPath,validatedAt:new Date().toISOString(),checkCount:t.length,passedChecks:t.filter(i=>i.passed).length,checks:t,frontmatter:s}}async function _$(e){let t=await N$(e.skillMdPath,"utf-8"),s=[],i=F$(t);if(i===null){ae(s,"missing-frontmatter","Frontmatter exists",!1,"error","SKILL.md must start with a YAML frontmatter block.");let A=Qr(e,s,null);return{score:0,passed:!1,findings:s.map(Zr),raw:A}}ae(s,"frontmatter-present","Frontmatter exists",!0,"error","SKILL.md contains a YAML frontmatter block.");let r;try{r=(0,om.parse)(i)}catch(A){ae(s,"invalid-yaml","Frontmatter parses as YAML",!1,"error",`Invalid YAML in frontmatter: ${A?.message??String(A)}`);let E=Qr(e,s,null);return{score:0,passed:!1,findings:s.map(Zr),raw:E}}if(!r||typeof r!="object"||Array.isArray(r)){ae(s,"frontmatter-not-object","Frontmatter is a mapping",!1,"error","Frontmatter must parse to a YAML object.");let A=Qr(e,s,null);return{score:0,passed:!1,findings:s.map(Zr),raw:A}}let n=r;ae(s,"frontmatter-object","Frontmatter is a mapping",!0,"error","Frontmatter parses to a YAML object.");let o=Object.keys(n).filter(A=>!M$.has(A));ae(s,"allowed-keys","Allowed top-level keys only",o.length===0,"error",o.length===0?"Frontmatter uses only the allowed top-level keys.":`Unexpected frontmatter key(s): ${o.sort().join(", ")}.`);let a=n.name,c=typeof a=="string"?a.trim():"";if(ae(s,"name-present","Name is present and non-empty",c.length>0,"error",c.length>0?"Frontmatter includes a non-empty `name`.":"Frontmatter must include a non-empty string `name`."),c.length>0){let A=/^[a-z0-9-]+$/.test(c)&&!c.startsWith("-")&&!c.endsWith("-")&&!c.includes("--")&&c.length<=64;ae(s,"name-kebab-case","Name follows skill-best-practice naming rules",A,"error",A?"Name follows the skill-best-practice kebab-case naming rules.":"Name must be kebab-case, avoid consecutive/edge hyphens, and stay within 64 characters.")}let u=n.description,f=typeof u=="string"?u.trim():"";if(ae(s,"description-present","Description is present and non-empty",f.length>0,"error",f.length>0?"Frontmatter includes a non-empty `description`.":"Frontmatter must include a non-empty string `description`."),f.length>0){let A=!f.includes(`
364
- `)&&!f.includes("\r")&&!f.includes("<")&&!f.includes(">")&&f.length<=1024;ae(s,"description-shape","Description follows skill-best-practice formatting rules",A,"error",A?"Description is single-line, angle-bracket free, and within 1024 characters.":"Description must be a single line, avoid angle brackets, and stay within 1024 characters.");let E=f.length<=gl;ae(s,"description-runtime-budget","Description fits the runtime context budget",E,"warning",E?`Description is ${f.length} chars (target \u2264 ${gl}).`:`Description is ${f.length} chars; target \u2264 ${gl}. The /skills listing truncates tail-first, often chopping the negative-trigger clause.`)}let d=n.effort;ae(s,"effort-enum","Effort uses the supported enum",d===void 0||typeof d=="string"&&nm.has(d.trim()),"error",d===void 0||typeof d=="string"&&nm.has(d.trim())?"Effort is omitted or uses a supported value.":"Effort must be one of: low, medium, high, xhigh, max.");let p=n.compatibility;if(p!==void 0){let A=typeof p=="string"&&p.length<=500;ae(s,"compatibility-shape","Compatibility is a short string",A,"error",A?"Compatibility is a valid short string.":"Compatibility must be a string no longer than 500 characters.")}let m=n.metadata&&typeof n.metadata=="object"&&!Array.isArray(n.metadata)?n.metadata:null,g=m?.version,h=typeof g=="string"||typeof g=="number"?String(g).trim():"",y=h.length>0;if(ae(s,"metadata-version-present","metadata.version is present",y,"error",y?"Frontmatter declares `metadata.version`.":"Frontmatter must declare `metadata.version` (start new skills at 1.0.0)."),y){let A=D$.test(h);ae(s,"metadata-version-semver","metadata.version follows MAJOR.MINOR.PATCH",A,"error",A?"`metadata.version` follows semantic versioning.":`\`metadata.version\` must follow semantic versioning (e.g. 1.0.0); got "${h}".`)}let b=m?.author,k=typeof b=="string"&&b.trim().length>0;if(ae(s,"metadata-author-present","metadata.author is present",k,"warning",k?"Frontmatter declares `metadata.author`.":"Add `metadata.author` (recommended for published skills) so users know who maintains the skill."),c.length>0){let A=O$(e.skillPath),E=A===c;ae(s,"name-matches-directory","Name matches the parent directory",E,"error",E?"Frontmatter `name` matches the skill directory.":`Frontmatter \`name\` ("${c}") must match the parent directory ("${A}").`)}let w=/don'?t use (?:for|when|if|on)|not (?:for|intended for|suitable for|meant for)\b|skip (?:for|when|if)|avoid (?:using )?(?:for|when|on)|never (?:use )?for\b|only (?:use )?for\b/i.test(f);ae(s,"negative-trigger-clause","Description includes a negative-trigger clause",w,"warning",w?"Description names adjacent cases that should not trigger the skill.":"Description appears to lack a negative-trigger clause; consider naming adjacent cases that should not trigger the skill.");let v=Qr(e,s,n),x=v.checkCount===0?100:Math.round(v.passedChecks/v.checkCount*100),C=s.filter(A=>!A.passed).map(Zr);return{score:x,passed:C.every(A=>A.severity!=="error"),findings:C,raw:v}}var am={id:sm,version:im,schemaVersion:rm,description:"Deterministic SKILL.md best-practice validation (rules aligned with the skill-creator standard, v1.7.1).",async applicable(e){try{return(await T$(e.skillMdPath)).isFile()?{ok:!0}:{ok:!1,reason:`${e.skillMdPath} is not a file`}}catch{return{ok:!1,reason:`SKILL.md not found at ${e.skillMdPath}`}}},async run(e,t){let s=await _$(e);return{providerId:sm,providerVersion:im,schemaVersion:rm,score:s.score,passed:s.passed,categories:[{id:"validation",name:"Deterministic validation",score:s.raw.passedChecks,max:s.raw.checkCount,findings:s.findings.length>0?s.findings:void 0}],findings:s.findings,raw:s.raw,startedAt:"",durationMs:0}}};function lm(){hl(tm),hl(am)}var cm=!1;function en(){cm||(lm(),cm=!0)}function tn(){return en(),Xr()}function um(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function dm(e,t,s,i,r){let n={severity:"error",message:i,code:r};return{providerId:e.id,providerVersion:e.version,schemaVersion:e.schemaVersion,score:0,passed:!1,categories:[],findings:[n],raw:void 0,startedAt:t,durationMs:s}}async function sn(e,t,s={}){let i=new Date().toISOString(),r=performance.now(),n={id:e.id,version:e.version,schemaVersion:e.schemaVersion},o=new AbortController;s.signal&&(s.signal.aborted?o.abort(s.signal.reason):s.signal.addEventListener("abort",()=>o.abort(s.signal?.reason)));let a=null;typeof s.timeoutMs=="number"&&s.timeoutMs>0&&(a=setTimeout(()=>o.abort(new Error("timeout")),s.timeoutMs));let c={...s,signal:o.signal};try{let u=await Promise.race([e.run(t,c).then(p=>({kind:"ok",value:p})),new Promise(p=>{if(o.signal.aborted){p({kind:"timeout"});return}o.signal.addEventListener("abort",()=>p({kind:"timeout"}))})]),f=Math.max(0,Math.round(performance.now()-r));if(u.kind==="timeout"){let p=o.signal.reason,m=p instanceof Error&&p.message==="timeout"?`provider timed out after ${s.timeoutMs}ms`:`provider aborted: ${um(p)}`;return dm(n,i,f,m,p instanceof Error&&p.message==="timeout"?"timeout":"aborted")}let d=u.value;return{...d,providerId:n.id,providerVersion:n.version,schemaVersion:d.schemaVersion??n.schemaVersion,startedAt:i,durationMs:f}}catch(u){let f=Math.max(0,Math.round(performance.now()-r));return dm(n,i,f,um(u),"provider-threw")}finally{a&&clearTimeout(a)}}function j$(e){return e>=90?"A":e>=80?"B":e>=65?"C":e>=50?"D":"F"}function fm(e){return{id:e.providerId,version:e.providerVersion,schemaVersion:e.schemaVersion,score:e.score,passed:e.passed,categories:e.categories,findings:e.findings,raw:e.raw}}function pm(e,t){return{providerId:e.providerId,providerVersion:e.providerVersion,schemaVersion:e.schemaVersion,passed:e.passed,overallScore:e.score,grade:j$(e.score),categories:e.categories.map(s=>({id:s.id,name:s.name,score:s.score,max:s.max})),evaluatedAt:e.startedAt,evaluatedVersion:t}}function ai(e){return[...e].sort((t,s)=>t.id==="quality"&&s.id!=="quality"?-1:s.id==="quality"&&t.id!=="quality"?1:t.id.localeCompare(s.id))}import{join as B$}from"path";function q$(){console.log(`${l.bold("Usage:")} asm eval <target> [options]
209
+ `;return`${e}${n}${t}: ${o}
210
+ `}function Vr(e,t,r="SKILL.md"){if(e===t)return"";let s=e.split(`
211
+ `),o=t.split(`
212
+ `),n=[`--- a/${r}`,`+++ b/${r}`],a=0;for(;a<s.length&&a<o.length&&s[a]===o[a];)a++;let l=0;for(;l<s.length-a&&l<o.length-a&&s[s.length-1-l]===o[o.length-1-l];)l++;let c=s.slice(a,s.length-l),d=o.slice(a,o.length-l),u=a+1,p=a+1;n.push(`@@ -${u},${c.length} +${p},${d.length} @@`);let f=s.slice(Math.max(0,a-3),a).map(g=>` ${g}`),m=s.slice(s.length-l,Math.min(s.length,s.length-l+3)).map(g=>` ${g}`);n.push(...f);for(let g of c)n.push(`-${g}`);for(let g of d)n.push(`+${g}`);return n.push(...m),n.join(`
213
+ `)}async function oo(e,t){let r=ya(e)?e:ha(e),s,o=await fa(r).catch(()=>null);if(!o)throw new Error(`Skill path does not exist: ${r}`);if(o.isFile())s=r;else if(o.isDirectory())s=ga(r,"SKILL.md");else throw new Error(`Skill path is not a directory or file: ${r}`);let n;try{n=await to(s,"utf-8")}catch{throw new Error(`SKILL.md not found at ${s}.`)}let a=ba(n,{gitAuthor:t.gitAuthor}),l=Vr(n,a.newContent),c=null;return!t.dryRun&&a.newContent!==n&&(c=`${s}.bak`,await Dp(s,c),await Op(s,a.newContent,"utf-8")),{report:await gt({content:t.dryRun?n:a.newContent,skillPath:r,skillMdPath:s}),applied:a.applied,skipped:a.skipped,diff:l,dryRun:t.dryRun,backupPath:c,skillMdPath:s}}async function no(){try{let{stdout:e,exitCode:t}=await re(["git","config","--global","--get","user.name"]);if(t!==0)return null;let r=e.trim();return r||null}catch{return null}}function _p(e,t,r=20){let s=Math.round(e/t*r);return"\u2588".repeat(s)+"\u2591".repeat(Math.max(0,r-s))}function Wt(e){let t=[];t.push(`Skill evaluation: ${e.skillPath}`),t.push(`SKILL.md: ${e.skillMdPath}`),t.push(""),t.push(`Overall score: ${e.overallScore}/100 (${e.grade})`);let r=(e.providers??[]).filter(s=>s.id!=="quality");for(let s of r){let o=s.passed?"pass":"fail",n=`${s.id}@${s.version}`;t.push(` ${n}: ${s.score}/100 ${o}`)}t.push(""),t.push("Categories:");for(let s of e.categories)t.push(` ${s.name.padEnd(28)} ${String(s.score).padStart(2)}/${s.max} ${_p(s.score,s.max)}`);if(t.push(""),e.topSuggestions.length>0){t.push("Top suggestions:");for(let s of e.topSuggestions)t.push(` \u2022 ${s}`)}else t.push("No suggestions \u2014 skill looks great.");for(let s of r){let o=Up(s.raw);if(o&&o.length>0){t.push(""),t.push(`${s.id}@${s.version} breakdown:`);for(let n of o){let a=n.passed?"\u221A":n.severity==="warning"?"\u26A0":"\xD7";t.push(` ${a} ${n.label}`),n.passed||t.push(` [${n.severity}] ${n.message}`)}continue}if(s.findings.length!==0){t.push(""),t.push(`${s.id}@${s.version} findings:`);for(let n of s.findings)t.push(` [${n.severity}] ${n.message}`)}}return t.join(`
214
+ `)}function Up(e){if(!e||typeof e!="object")return null;let t=e.checks;if(!Array.isArray(t))return null;let r=[];for(let s of t){if(!s||typeof s!="object")return null;let o=s;if(typeof o.id!="string"||typeof o.label!="string"||typeof o.passed!="boolean"||typeof o.message!="string"||o.severity!=="error"&&o.severity!=="warning")return null;r.push({id:o.id,label:o.label,passed:o.passed,severity:o.severity,message:o.message})}return r}function io(e){return JSON.stringify(e,null,2)}function ao(e){let t=[];if(e.applied.length===0&&e.skipped.length===0)return t.push("No fixes needed \u2014 SKILL.md is already clean."),t.join(`
215
+ `);if(e.applied.length>0){t.push(`${e.dryRun?"Would apply":"Applied"} ${e.applied.length} fix(es):`);for(let r of e.applied)t.push(` \u2022 ${r.description}`)}if(e.skipped.length>0){t.push(""),t.push(`Skipped ${e.skipped.length} issue(s) (not auto-fixable):`);for(let r of e.skipped)t.push(` \u2022 ${r.description}`)}return e.diff&&(t.push(""),t.push("Diff:"),t.push(e.diff)),!e.dryRun&&e.backupPath&&(t.push(""),t.push(`Backup: ${e.backupPath}`)),t.join(`
216
+ `)}import{stat as Gr,readdir as Bp}from"fs/promises";import{join as Hr,resolve as Vp,basename as ht,isAbsolute as Gp}from"path";async function ka(e){let t;try{t=await Bp(e)}catch{return[]}let r=[];for(let s of t){if(s.startsWith(".")||s==="node_modules"||s==="dist"||s==="build")continue;let o=Hr(e,s),n;try{n=await Gr(o)}catch{continue}if(!n.isDirectory())continue;let a=Hr(o,"SKILL.md");try{(await Gr(a)).isFile()&&r.push(o)}catch{}}return r.sort((s,o)=>ht(s).localeCompare(ht(o))),r}async function lo(e){let t=Hr(e,"SKILL.md");try{if((await Gr(t)).isFile())return{kind:"single",skillDirs:[e]}}catch{}let r=await ka(e);return r.length>0?{kind:"collection",skillDirs:r}:{kind:"none",skillDirs:[]}}function yt(e){return e?!!(e.startsWith("github:")||/^https?:\/\/github\.com\//i.test(e)):!1}function wa(e){return{skillPath:e,skillMdPath:Hr(e,"SKILL.md"),label:ht(e)}}async function co(e,t={}){if(!e)throw new Error("resolveEvalInput: input must be a non-empty string");if(yt(e)){if(!t.fetchRemote)throw new Error(`Remote evaluation is not available in this context: "${e}"`);let n=await t.fetchRemote(e),a;try{a=await lo(n.rootDir)}catch(l){throw await n.cleanup().catch(()=>{}),l}if(a.kind==="none")throw await n.cleanup().catch(()=>{}),new Error(`No SKILL.md found at ${n.rootDir} (source: ${e}). The location is neither a single skill nor a skill collection.`);return{targets:a.skillDirs.map(wa),isCollection:a.kind==="collection",cleanup:n.cleanup,provenance:{input:e,remote:!0,sourceRef:n.sourceRef,commitSha:n.commitSha,tempPath:n.rootDir}}}let r=Gp(e)?e:Vp(e),s;try{s=await Gr(r)}catch{throw new Error(`Skill path does not exist: ${r}`)}if(s.isFile())return{targets:[{skillPath:ht(r)==="SKILL.md"?ht(r):r,skillMdPath:r,label:ht(r)}],isCollection:!1,cleanup:async()=>{},provenance:{input:e,remote:!1,sourceRef:null}};if(!s.isDirectory())throw new Error(`Skill path is not a directory or file: ${r}`);let o=await lo(r);if(o.kind==="none")throw new Error(`No SKILL.md found in ${r}. Pass a skill directory, a SKILL.md file, or a collection root with SKILL.md in its children.`);return{targets:o.skillDirs.map(wa),isCollection:o.kind==="collection",cleanup:async()=>{},provenance:{input:e,remote:!1,sourceRef:null}}}function uo(e){let t=e.filter(u=>u.report!==null),r=e.length,s=r-t.length;if(t.length===0)return{total:r,succeeded:0,failed:s,meanScore:null,top:null,bottom:null};let o=t.map(u=>u.report.overallScore),n=o.reduce((u,p)=>u+p,0)/o.length,a=Math.round(n),l=[...t].sort((u,p)=>p.report.overallScore-u.report.overallScore),c=l[0],d=l[l.length-1];return{total:r,succeeded:t.length,failed:s,meanScore:a,top:{label:c.label,score:c.report.overallScore},bottom:{label:d.label,score:d.report.overallScore}}}async function Kt(e,t,r){let s=new Array(e.length),o=0,n=!1,a,l=Math.max(1,Math.floor(t)),c=[],d=Math.min(l,e.length);for(let u=0;u<d;u++)c.push((async()=>{for(;!n;){let p=o++;if(p>=e.length)break;try{s[p]=await r(e[p],p)}catch(f){n||(n=!0,a=f);break}}})());if(await Promise.all(c),n)throw a;return s}function po(e,t=28){let r=[];return r.push(""),r.push("Batch summary:"),r.push(` Skills evaluated: ${e.aggregate.succeeded}/${e.aggregate.total}`+(e.aggregate.failed>0?` (${e.aggregate.failed} failed)`:"")),e.aggregate.meanScore!==null&&r.push(` Mean score: ${e.aggregate.meanScore}/100`),e.aggregate.top&&r.push(` Top: ${e.aggregate.top.label} (${e.aggregate.top.score}/100)`),e.aggregate.bottom&&e.aggregate.bottom.label!==e.aggregate.top?.label&&r.push(` Bottom: ${e.aggregate.bottom.label} (${e.aggregate.bottom.score}/100)`),e.provenance.remote&&(e.provenance.sourceRef&&r.push(` Source: ${e.provenance.sourceRef}`),e.provenance.commitSha&&r.push(` Commit: ${e.provenance.commitSha}`),e.provenance.tempPath&&r.push(` Fetched to: ${e.provenance.tempPath}`)),r.join(`
217
+ `)}function mo(e){return{provenance:{input:e.provenance.input,remote:e.provenance.remote,source_ref:e.provenance.sourceRef??null,commit_sha:e.provenance.commitSha??null,temp_path:e.provenance.tempPath??null},aggregate:{total:e.aggregate.total,succeeded:e.aggregate.succeeded,failed:e.aggregate.failed,mean_score:e.aggregate.meanScore,top:e.aggregate.top,bottom:e.aggregate.bottom},results:e.results.map(t=>({label:t.label,skill_path:t.skillPath,error:t.error,report:t.report?Jt(t.report,null):null}))}}function Jt(e,t=null){return{skill_path:e.skillPath,skill_md_path:e.skillMdPath,overall_score:e.overallScore,grade:e.grade,categories:e.categories.map(r=>({id:r.id,name:r.name,score:r.score,max:r.max,findings:r.findings,suggestions:r.suggestions})),top_suggestions:e.topSuggestions,providers:e.providers?.map(r=>({id:r.id,version:r.version,schemaVersion:r.schemaVersion,score:r.score,passed:r.passed,categories:r.categories.map(s=>({id:s.id,name:s.name,score:s.score,max:s.max,findings:s.findings??[]})),findings:r.findings}))??[],fix:t?{dry_run:t.dryRun,applied:t.applied,skipped:t.skipped,backup_path:t.backupPath,diff:t.diff}:null}}import{access as Ta,copyFile as Xp,cp as Qp,mkdtemp as Na,lstat as Oa,mkdir as $o,readdir as em,readFile as xo,readlink as tm,realpath as Qt,rename as Wr,rm as Oe}from"fs/promises";import{execFile as rm}from"child_process";import{createHash as sm}from"crypto";import{promisify as om}from"util";import{dirname as er,isAbsolute as Po,join as fe,relative as Da,resolve as he}from"path";import{execFile as Hp}from"child_process";import{promisify as qp}from"util";import{join as Wp}from"path";var Kp=qp(Hp),Jp=["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_IMPLICIT_WORK_TREE","GIT_GRAFT_FILE","GIT_SHALLOW_FILE","GIT_NO_REPLACE_OBJECTS","GIT_REPLACE_REF_BASE","GIT_PREFIX","GIT_INTERNAL_SUPER_PREFIX","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM","GIT_NAMESPACE","GIT_QUARANTINE_PATH","GIT_CONFIG","GIT_CONFIG_PARAMETERS","GIT_CONFIG_COUNT"];function Sa(e){let t={...process.env};for(let r of Jp)delete t[r];for(let r of Object.keys(t))/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(r)&&delete t[r];return t.GIT_DEFAULT_HASH=e,t}var fo=new WeakMap;function va(e,t){return fo.set(e,t),e}function $a(e){return e.normalize("NFC").toLowerCase().normalize("NFC")}async function go(e,t,r){let s=new Array(e.length),o=0;async function n(){for(;o<e.length;){let l=o++;s[l]=await r(e[l])}}let a=[];for(let l=0;l<Math.min(t,e.length);l++)a.push(n());return await Promise.all(a),s}async function xa(e,t){try{let r=["ls-remote",e];t?r.push(t,`${t}^{}`):r.push("HEAD");let{stdout:s}=await Kp("git",r,{timeout:1e4}),o=new Map;for(let n of s.split(`
218
+ `)){let[a,l]=n.trim().split(/\s+/);l&&a&&/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(a)&&o.set(l,a)}return!t||t==="HEAD"?o.get("HEAD")??null:t.startsWith("refs/")?o.get(`${t}^{}`)??o.get(t)??null:o.get(`refs/heads/${t}`)??o.get(`refs/tags/${t}^{}`)??o.get(`refs/tags/${t}`)??null}catch(r){return P(`updater: git ls-remote failed for ${e}: ${r}`),null}}function zt(e){return e.sourceType?e.sourceType:e.source.startsWith("local:")?"local":"github"}function bt(e){if(e.startsWith("github:")){let t=e.slice(7),r=t.indexOf("#");return r!==-1&&(t=t.slice(0,r)),`https://github.com/${t}.git`}return e.startsWith("file://")?e:null}function ho(e){if(!e.startsWith("github:"))return null;let t=e.slice(7),r=t.indexOf("#");r!==-1&&(t=t.slice(0,r));let s=t.split("/");return s.length<2||!s[0]||!s[1]?null:{owner:s[0],repo:s[1]}}function Pa(e,t){return t.skillPath?Wp(e,t.skillPath):e}async function Yt(e){let t=e?.readLockFn??Te,r=e?.fetchRegistryIndexFn??zs,s=e?.lock??await t(),o=Object.entries(s.skills);if(o.length===0)return{entries:[],outdatedCount:0,upToDateCount:0,untrackedCount:0,errorCount:0};let n=null;o.some(([,c])=>zt(c)==="registry"||c.registryName)&&(n=await r());let l=await go(o,5,async([c,d])=>{let u=zt(d);if(!d.commitHash||d.commitHash==="unknown")return{name:c,installedCommit:d.commitHash||"unknown",latestCommit:"unknown",source:d.source,sourceType:u,status:"untracked"};if(u==="local")return{name:c,installedCommit:d.commitHash,latestCommit:d.commitHash,source:d.source,sourceType:u,status:"up-to-date"};if(u==="registry"&&n){let g=d.registryName||c,h=n.manifests.find(y=>y.name.toLowerCase()===g.toLowerCase());if(h){let y=h.commit!==d.commitHash;return va({name:c,installedCommit:ge(d.commitHash),latestCommit:ge(h.commit),source:d.source,sourceType:u,status:y?"outdated":"up-to-date"},h.commit)}}let p=bt(d.source);if(!p)return{name:c,installedCommit:ge(d.commitHash),latestCommit:"unknown",source:d.source,sourceType:u,status:"error",error:"Cannot determine remote URL"};let f=await xa(p,d.ref);if(!f)return{name:c,installedCommit:ge(d.commitHash),latestCommit:"unknown",source:d.source,sourceType:u,status:"error",error:"Failed to fetch remote commit"};let m=f!==d.commitHash;return va({name:c,installedCommit:ge(d.commitHash),latestCommit:ge(f),source:d.source,sourceType:u,status:m?"outdated":"up-to-date"},f)});return{entries:l,outdatedCount:l.filter(c=>c.status==="outdated").length,upToDateCount:l.filter(c=>c.status==="up-to-date").length,untrackedCount:l.filter(c=>c.status==="untracked").length,errorCount:l.filter(c=>c.status==="error").length}}function ge(e){return!e||e==="unknown"?"unknown":e.slice(0,7)}import{execFile as zp}from"child_process";import{promisify as Yp}from"util";import{join as qr}from"path";import{homedir as Ra}from"os";import{mkdir as Ea,rm as Ge,rename as yo,cp as Ia,access as Zp}from"fs/promises";var Zt=Yp(zp);async function Ca(e,t,r,s,o){if(zt(t)==="local")return{name:e,status:"skipped",reason:"Local skill (not updatable)"};let a;if(o!==void 0){if(!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(o))return{name:e,status:"failed",reason:"Invalid known commit OID"};if(a=o.toLowerCase(),a===t.commitHash.toLowerCase())return{name:e,status:"skipped",reason:"Already up to date"}}let l=bt(t.source);if(!l)return{name:e,status:"failed",reason:"Cannot determine remote URL"};let c=qr(Ra(),".config","agent-skill-manager",".tmp",`${e}-${Date.now()}`);try{let d=qr(Ra(),".config","agent-skill-manager",".tmp");if(await Ea(d,{recursive:!0}),P(`updater: fetching latest ${e} to ${c}`),a)try{let k=a.length===40?"sha1":"sha256",E=Sa(k);await Zt("git",["init",c],{timeout:1e4,env:E}),await Zt("git",["fetch","--depth","1",l,a],{cwd:c,timeout:6e4,env:E}),await Zt("git",["checkout","--detach",a],{cwd:c,timeout:1e4,env:E})}catch{return{name:e,status:"failed",reason:"Resolved commit is unavailable in the shallow fetch"}}else{let k=["clone","--depth","1"];t.ref&&t.ref!=="HEAD"&&k.push("--branch",t.ref),k.push(l,c);try{await Zt("git",k,{timeout:6e4})}catch(E){let F=E;return{name:e,status:"failed",reason:`Clone failed: ${F.stderr||F.message||String(E)}`}}}let u;if(a)u=a;else try{let{stdout:k}=await Zt("git",["rev-parse","HEAD"],{cwd:c,timeout:5e3});u=k.trim().toLowerCase()}catch{return{name:e,status:"failed",reason:"Could not read new commit"}}if(u===t.commitHash)return{name:e,status:"skipped",reason:"Already up to date"};let p=Pa(c,t);P(`updater: running security audit on ${e}`);let f="safe";try{let k=s?.auditFn??xe,E=ho(t.source);if(f=(await k(p,e,E?.owner,E?.repo)).verdict,f==="dangerous")return{name:e,status:"skipped",reason:"Security audit: dangerous \u2014 update blocked",securityVerdict:f};if(f==="warning"||f==="caution"){if(!r)return{name:e,status:"skipped",reason:`Security audit: ${f} \u2014 use --yes to override`,securityVerdict:f};P(`updater: security audit ${f} for ${e} \u2014 proceeding (--yes)`)}}catch(k){let E=k instanceof Error?k.message:String(k);return P(`updater: security audit failed for ${e}: ${E}`),{name:e,status:"failed",reason:`Security audit failed \u2014 skipping update: ${E}`}}let m=s?.loadConfigFn??O,g=s?.resolveProviderPathFn??Q,y=(await m()).providers.find(k=>k.name===t.provider),b=t.scope??"global",$=y?b==="project"?y.project:y.global:`~/.${t.provider}/skills`,v=g($),S=qr(v,e),C=qr(c,".git");try{await Ge(C,{recursive:!0,force:!0})}catch{}let D=!0;try{await Zp(S)}catch(k){if(!(k instanceof Error)||!("code"in k)||k.code!=="ENOENT"){let E=k instanceof Error?k.message:String(k);return{name:e,status:"failed",reason:`Cannot access installed skill: ${E}`}}D=!1}let U=s?.writeLockEntryFn??nt,A={...t,commitHash:u,installedAt:new Date().toISOString()};if(!D){try{await Ea(v,{recursive:!0}),await Ia(p,S,{recursive:!0})}catch(k){await Ge(S,{recursive:!0,force:!0});let E=k instanceof Error?k.message:String(k);return{name:e,status:"failed",reason:`Atomic swap failed: ${E}`}}try{await U(e,A)}catch(k){try{await Ge(S,{recursive:!0,force:!0})}catch(F){let Z=k instanceof Error?k.message:String(k),se=F instanceof Error?F.message:String(F);return{name:e,status:"failed",reason:`Lock file update failed: ${Z}. Removal of the new installation also failed: ${se}`}}let E=k instanceof Error?k.message:String(k);return{name:e,status:"failed",reason:`Lock file update failed: ${E}`}}return{name:e,status:"updated",oldCommit:ge(t.commitHash),newCommit:ge(u),securityVerdict:f}}let _=`${S}.bak-${Date.now()}`,M=!1;try{await yo(S,_),M=!0,await Ia(p,S,{recursive:!0})}catch(k){if(M)try{await Ge(S,{recursive:!0,force:!0}),await yo(_,S),M=!1}catch(E){let F=k instanceof Error?k.message:String(k),Z=E instanceof Error?E.message:String(E);return{name:e,status:"failed",reason:`Atomic swap failed: ${F}. Restore also failed; backup preserved at ${_}: ${Z}`}}return{name:e,status:"failed",reason:`Atomic swap failed: ${k instanceof Error?k.message:String(k)}`}}try{await U(e,A)}catch(k){try{await Ge(S,{recursive:!0,force:!0}),await yo(_,S),M=!1}catch(F){let Z=k instanceof Error?k.message:String(k),se=F instanceof Error?F.message:String(F);return{name:e,status:"failed",reason:`Lock file update failed: ${Z}. Restore also failed; backup preserved at ${_}: ${se}`}}let E=k instanceof Error?k.message:String(k);return{name:e,status:"failed",reason:`Lock file update failed: ${E}`}}if(M)try{await Ge(_,{recursive:!0,force:!0})}catch(k){P(`updater: failed to remove backup ${_}: ${k}`)}return{name:e,status:"updated",oldCommit:ge(t.commitHash),newCommit:ge(u),securityVerdict:f}}finally{try{await Ge(c,{recursive:!0,force:!0})}catch{}}}async function bo(e,t,r){let s=r?.readLockFn??Te,o=r?.checkOutdatedFn??Yt,n=r?.updateSkillFn??Ca,a=await s(),l=await o({lock:a}),c=l.entries.filter(y=>y.status==="outdated"),d=[];if(e&&e.length>0){let y=new Set(e.map(b=>b.toLowerCase()));c=c.filter(b=>y.has(b.name.toLowerCase()));for(let b of e)c.find($=>$.name.toLowerCase()===b.toLowerCase())||(l.entries.find(v=>v.name.toLowerCase()===b.toLowerCase())?P(`updater: skill "${b}" is already up to date`):(P(`updater: skill "${b}" not found in lock file`),d.push(b)))}if(c.length===0)return{results:[],updatedCount:0,skippedCount:0,failedCount:0,...d.length>0?{warnings:d}:{}};let u=c.flatMap(y=>{let b=a.skills[y.name];return b?[{name:y.name,lockEntry:b,knownLatestCommit:fo.get(y)}]:[]}),p=r?.writeLockEntryFn??nt,f=Promise.resolve(),m=(y,b)=>{let $=f.then(()=>p(y,b));return f=$.then(()=>{},()=>{}),$},g=new Map;u.forEach((y,b)=>{let $=$a(y.name),v=g.get($)??[];v.push({...y,index:b}),g.set($,v)});let h=new Array(u.length);return await go([...g.values()],4,async y=>{for(let b of y)try{h[b.index]=await n(b.name,b.lockEntry,t,{writeLockEntryFn:m},b.knownLatestCommit)}catch($){let v=$ instanceof Error?$.message:String($);h[b.index]={name:b.name,status:"failed",reason:`Unexpected update failure: ${v}`}}}),{results:h,updatedCount:h.filter(y=>y.status==="updated").length,skippedCount:h.filter(y=>y.status==="skipped").length,failedCount:h.filter(y=>y.status==="failed").length,...d.length>0?{warnings:d}:{}}}function wo(e,t){if(e.entries.length===0)return"No skills installed.";let r=p=>p,s=t?i.red:r,o=t?i.green:r,n=t?i.yellow:r,a=t?i.dim:r,l=`${"Skill".padEnd(22)}${"Installed".padEnd(14)}${"Latest".padEnd(14)}Source`,c="\u2500".repeat(60),d=[l,c];for(let p of e.entries){let f=p.name.padEnd(22),m=p.installedCommit.padEnd(14),g,h;switch(p.status){case"outdated":g=s(p.latestCommit.padEnd(14)),h=p.sourceType;break;case"up-to-date":g=o(p.latestCommit.padEnd(14)),h=a("(up to date)");break;case"untracked":g=n("untracked".padEnd(14)),h=n("untracked");break;case"error":g=a("error".padEnd(14)),h=a(p.error||"error");break}d.push(`${f}${m}${g}${h}`)}d.push("");let u=[];return e.outdatedCount>0&&u.push(s(`${e.outdatedCount} outdated`)),e.upToDateCount>0&&u.push(o(`${e.upToDateCount} up to date`)),e.untrackedCount>0&&u.push(n(`${e.untrackedCount} untracked`)),e.errorCount>0&&u.push(a(`${e.errorCount} error`)),d.push(u.join(", ")),d.join(`
219
+ `)}function ko(e){return JSON.stringify({skills:e.entries.map(t=>({name:t.name,installed:t.installedCommit,latest:t.latestCommit,source:t.sourceType,status:t.status,...t.error?{error:t.error}:{}})),summary:{outdated:e.outdatedCount,upToDate:e.upToDateCount,untracked:e.untrackedCount,errors:e.errorCount}},null,2)}function vo(e){return JSON.stringify({results:e.results.map(t=>({name:t.name,status:t.status,...t.reason?{reason:t.reason}:{},...t.oldCommit?{oldCommit:t.oldCommit}:{},...t.newCommit?{newCommit:t.newCommit}:{},...t.securityVerdict?{securityVerdict:t.securityVerdict}:{}})),summary:{updated:e.updatedCount,skipped:e.skippedCount,failed:e.failedCount}},null,2)}var Xt=om(rm),nm=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/,La=128,im=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function So(){return{version:1,skills:{}}}async function tr(e=Fe()){return Kr(e)}async function He(e=Fe()){let t=await tr(e),r=[];for(let[s,o]of Object.entries(t.skills)){let n=!1;try{await Ta(fe(o.libraryPath,"SKILL.md"))}catch{n=!0}r.push({dirName:s,...o,missing:n})}return r.sort((s,o)=>s.name.localeCompare(o.name)),r}function rr(e,t){let r=e.find(o=>o.dirName===t);return r||(e.find(o=>o.name===t)??null)}function Y(e,t){return{name:e,status:"failed",reason:t}}async function Ma(e,t,r){return e.sourceType!==t.sourceType||he(e.libraryPath)!==he(t.libraryPath)?!1:e.sourceType==="local"?r?await am(e)===r:!1:e.source===t.source&&e.ref===t.ref&&e.skillPath===t.skillPath}function Ro(e){return Y(e,`Library skill "${e}" changed while update was in progress. Run "asm library update ${e}" again.`)}function Eo(e){let t=Date.parse(e??""),r=Number.isFinite(t)?Math.max(Date.now(),t+1):Date.now();return new Date(r).toISOString()}function Io(e){if(!e.source.startsWith("local:"))return null;let t=e.source.slice(6);return t?he(t):null}async function am(e){let t=Io(e);if(!t)throw new Error("Unsupported library source for update");let r=Jr(t,fe(t,e.skillPath));if(!r)throw new Error("Invalid update metadata: skillPath escapes source root");let[s,o]=await Promise.all([Qt(t),Qt(r)]);if(!sr(s,o))throw new Error("Invalid update metadata: skillPath escapes source root");return o}async function Kr(e){let t;try{t=await xo(e,"utf-8")}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return P("library: lock file not found, returning empty lock"),So();throw r}try{let r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r)||r.version!==1||typeof r.skills!="object"||r.skills===null||Array.isArray(r.skills))throw new Error("invalid schema");return r}catch{let r=e+".bak";try{await Xp(e,r)}catch{}return console.error(`Warning: library-lock.json was corrupted. Backup saved to ${r}. Starting fresh.`),So()}}async function Co(e,t){await ot(t,JSON.stringify(e,null,2)+`
220
+ `)}function Fa(e){let t=e.name?.trim();if(!t)return{reason:"Invalid source SKILL.md: missing name"};let r=(e["metadata.version"]||e.version)?.trim();return r?im.test(r)?{name:t,version:r}:{reason:"Invalid source SKILL.md: invalid version"}:{reason:"Invalid source SKILL.md: missing version"}}function sr(e,t){let r=he(e),s=he(t),o=Da(r,s);return o===""||!!o&&!o.startsWith("..")&&!Po(o)}function Jr(e,t){let r=he(e),s=he(t);return sr(r,s)?s:null}async function lm(e){let t=he(e);for(;;)try{return await Qt(t)}catch(r){if(!(r instanceof Error)||!("code"in r)||r.code!=="ENOENT")throw r;let s=er(t);if(s===t)throw r;t=s}}async function ja(e,t){try{let[r,s]=await Promise.all([Qt(e),lm(t)]);return sr(r,s)}catch{return!1}}async function _a(e){let t=sm("sha256");async function r(s,o){let n=await em(s,{withFileTypes:!0});n.sort((a,l)=>a.name.localeCompare(l.name));for(let a of n){if(a.name===".git")continue;let l=o?fe(o,a.name):a.name,c=fe(s,a.name);a.isDirectory()?(t.update(`dir:${l}
221
+ `),await r(c,l)):a.isFile()&&(t.update(`file:${l}
222
+ `),t.update(await xo(c)),t.update(`
223
+ `))}}return await r(e,""),t.digest("hex")}async function Ua(e,t,r){let s=bt(e.source);if(!s)return{reason:"Cannot determine remote URL"};let o=fe(er(r),".tmp");await $o(o,{recursive:!0});let n=await Na(fe(o,`${t}-`)),a=e.ref&&e.ref!=="HEAD"?e.ref:null,l=!!a&&/^[0-9a-f]{40}$/i.test(a),c=["clone","--depth","1"];a&&!l&&c.push("--branch",a),c.push(s,n);try{await Xt("git",c,{timeout:6e4})}catch(d){let u=d;return{tempDir:n,reason:`Clone failed: ${u.stderr||u.message||String(d)}`}}if(a&&l)try{await Xt("git",["checkout",a],{cwd:n,timeout:3e4})}catch{try{await Xt("git",["fetch","--depth","1","origin",a],{cwd:n,timeout:6e4}),await Xt("git",["checkout","FETCH_HEAD"],{cwd:n,timeout:3e4})}catch(d){let u=d;return{tempDir:n,reason:`Checkout failed for ref ${a}: ${u.stderr||u.message||String(d)}`}}}try{let{stdout:d}=await Xt("git",["rev-parse","HEAD"],{cwd:n,timeout:5e3}),u=d.trim();return/^[0-9a-f]{40}$/i.test(u)?{tempDir:n,commitHash:u}:{tempDir:n,reason:"Could not read new commit"}}catch{return{tempDir:n,reason:"Could not read new commit"}}}async function Lo(e,t){let r=await Na(fe(er(t),".library-update-"));try{return await Qp(e,r,{recursive:!0}),await Oe(fe(r,".git"),{recursive:!0,force:!0}),r}catch(s){throw await Oe(r,{recursive:!0,force:!0}),s}}async function Ao(e){let t=er(e.targetDir),r=null,s=!1;try{try{await Ba(e.targetDir)&&(r=fe(t,`.library-update-backup-${Date.now()}`),await Wr(e.targetDir,r)),await Wr(e.stagedDir,e.targetDir);try{return await e.writeLock(),null}catch(o){if(o instanceof Lt)return{name:"",status:"failed",reason:`Lock metadata and library files were published as the new generation, but parent-directory durability could not be confirmed: ${o.cause instanceof Error?o.cause.message:String(o.cause)}`};if(await Oe(e.targetDir,{recursive:!0,force:!0}),r)try{await Wr(r,e.targetDir),r=null}catch{return s=!0,{name:"",status:"failed",reason:`Updated library copy, but failed to write lock file: ${o instanceof Error?o.message??String(o):String(o)}. Restore of previous library copy also failed; backup preserved at ${r}.`}}return{name:"",status:"failed",reason:`Updated library copy, but failed to write lock file: ${o instanceof Error?o.message??String(o):String(o)}`}}}catch(o){if(r)try{await Wr(r,e.targetDir),r=null}catch{s=!0}return{name:"",status:"failed",reason:`Failed to refresh library skill: ${o instanceof Error?o.message??String(o):String(o)}`}}}finally{await Oe(e.stagedDir,{recursive:!0,force:!0}),r&&!s&&await Oe(r,{recursive:!0,force:!0})}}function cm(e,t){let r=Da(e,t);return r===""||!!r&&!r.startsWith("..")&&!Po(r)}async function Aa(e){try{return{path:await Qt(e),exists:!0}}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return{path:he(e),exists:!1};throw t}}async function To(e){let t=Oo(e.activationName),r=fe(e.targetDir,t),s;try{s=await Oa(r)}catch(f){throw f instanceof Error&&"code"in f&&f.code==="ENOENT"?new Error(`Skill "${t}" is not active for ${e.provider}/${e.scope}.`,{cause:f}):f}if(!s.isSymbolicLink())throw new Error(`Refusing to deactivate non-symlink target: ${r}.`);let o=await tm(r),n=Po(o)?o:he(er(r),o),a=e.librarySkillsDir??Re(),l=await Aa(n),c=await Aa(a),d=l.exists&&c.exists,u=d?l.path:he(n),p=d?c.path:he(a);if(!cm(p,u))throw new Error(`Refusing to deactivate symlink outside the ASM library: ${r}.`);return await Oe(r),{name:t,provider:e.provider,scope:e.scope,path:r,target:u}}async function No(e){let t=Oo(e.activationName),r=fe(e.targetDir,t);try{let s=await Oa(r);if(!e.force)throw new Error(`Target already exists: ${r}. Use --force to overwrite.`);if(!s.isSymbolicLink())throw new Error(`Refusing to overwrite non-symlink target: ${r}.`);await Oe(r,{force:!0})}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s}return await $o(e.targetDir,{recursive:!0}),await Ae(e.libraryPath,r),{symlinkPath:r,targetPath:e.libraryPath}}async function Ba(e){try{return await Ta(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function Oo(e){if(!e)throw new Error("Invalid skill name: name cannot be empty");if(e.includes("\0"))throw new Error("Invalid skill name: contains unsafe characters (null byte)");if(e.includes(".."))throw new Error("Invalid skill name: contains unsafe characters (..)");if(e.includes("/")||e.includes("\\"))throw new Error("Invalid skill name: contains unsafe characters (path separator)");if(e.startsWith("."))throw new Error("Invalid skill name: must not start with a dot");if(e.length>La)throw new Error(`Invalid skill name: exceeds maximum length of ${La} characters`);if(!nm.test(e))throw new Error(`Invalid skill name: "${e}" does not match allowed pattern [a-zA-Z0-9][a-zA-Z0-9._-]*`);return e}async function Do(e,t={}){let r=t.skillsDir??Re(),s=t.lockPath??Fe(),o=Oo(e.libraryName),n=fe(r,o);await $o(r,{recursive:!0});let a=await Lo(e.sourceDir,n);try{let l=await xo(fe(a,"SKILL.md"),"utf-8"),c=q(l),d=c.name||o,u=ae(c);return await st(s,async()=>{let p=await Kr(s);if(await Ba(n)&&!e.force)throw new Error(`Library skill already exists: ${n}. Use --force to overwrite.`);let f={...p,skills:{...p.skills,[o]:{name:d,version:u,source:e.source,sourceType:e.sourceType,commitHash:e.commitHash,ref:e.ref,skillPath:e.skillPath,libraryPath:n,installedAt:Eo(p.skills[o]?.installedAt)}}},m=await Ao({stagedDir:a,targetDir:n,writeLock:()=>Co(f,s)});if(m)throw new Error(m.reason??"Failed to install library skill")}),{name:d,version:u,libraryPath:n}}finally{await Oe(a,{recursive:!0,force:!0})}}import{readFile as dm,realpath as Va,rm as Ga}from"fs/promises";import{join as Mo}from"path";async function Ha(e,t={},r){let s=t.lockPath??Fe(),o=t.skillsDir??Re(),n=r?.writeLibraryLockFn??Co,a=await tr(s),l=a.skills[e]??null,c=Object.entries(a.skills).find(([,h])=>h.name===e)??null,d=l?[e,l]:c;if(!d)return Y(e,`Library skill "${e}" not found. Run "asm library list".`);let[u,p]=d,f={...p};if(!p.source||!p.source.trim())return Y(u,"Missing update metadata: source");if(!p.sourceType||!p.sourceType.trim())return Y(u,"Missing update metadata: sourceType");if(p.skillPath===void 0||p.skillPath===null)return Y(u,"Missing update metadata: skillPath");if(!p.libraryPath||!p.libraryPath.trim())return Y(u,"Missing update metadata: libraryPath");let m=null,g=null;try{let h,y=null;if(p.sourceType==="local"){let k=Io(p);if(!k)return Y(u,`Unsupported library source for update: ${p.source}`);h=k}else if(p.sourceType==="github"||p.sourceType==="registry"){let k=await Ua(p,u,s);if("reason"in k)return k.tempDir&&(m=k.tempDir),Y(u,k.reason);h=k.tempDir,m=k.tempDir,y=k.commitHash}else return Y(u,`Unsupported library source type for update: ${p.sourceType}`);let b=Jr(h,Mo(h,p.skillPath));if(!b)return Y(u,"Invalid update metadata: skillPath escapes source root");let $=Mo(b,"SKILL.md"),v,S;try{[v,S]=await Promise.all([Va(h),Va(b)])}catch(k){return Y(u,`Unable to read source SKILL.md at ${$}: ${k instanceof Error?k.message??String(k):String(k)}`)}if(!sr(v,S))return Y(u,"Invalid update metadata: skillPath escapes source root");p.sourceType==="local"&&(g=S);let C;try{C=await dm($,"utf-8")}catch(k){return Y(u,`Unable to read source SKILL.md at ${$}: ${k instanceof Error?k.message??String(k):String(k)}`)}let D=q(C),U=Fa(D);if("reason"in U)return Y(u,U.reason);let A=U.name,_=U.version;if(p.sourceType==="local"&&(y=await _a(b)),!y)return Y(u,"Could not read new commit");let M=await Lo(b,Mo(o,u));try{return await st(s,async()=>{let k=await Kr(s),E=k.skills[u];if(!E)return Y(u,`Library skill "${u}" not found. Run "asm library list".`);let F=Jr(o,E.libraryPath);if(!F)return Y(u,"Invalid update metadata: libraryPath escapes library skills directory");if(!await ja(o,F))return Y(u,"Invalid update metadata: libraryPath escapes library skills directory");let Z;try{Z=await Ma(E,f,g)}catch{return Ro(u)}let se=E.installedAt===f.installedAt;if(se&&Z&&E.commitHash===y)return{name:E.name,status:"skipped",oldVersion:E.version,newVersion:_,oldCommit:E.commitHash,newCommit:y};if(!se||!Z||E.commitHash!==f.commitHash)return Ro(u);let we={...k,skills:{...k.skills,[u]:{...E,name:A,version:_,commitHash:y,installedAt:Eo(E.installedAt)}}},R=await Ao({stagedDir:M,targetDir:F,writeLock:()=>n(we,s)});return R?Y(u,R.reason??"Failed to update library skill"):{name:A,status:"updated",oldVersion:E.version,newVersion:_,oldCommit:E.commitHash,newCommit:y}})}finally{await Ga(M,{recursive:!0,force:!0})}}finally{m&&await Ga(m,{recursive:!0,force:!0})}}async function Fo(e,t={}){let r=t.lockPath??Fe(),s=await tr(r),o=e===null?Object.keys(s.skills):e,n=[],a=[];for(let l of o){let c=await Ha(l,t);c.status==="failed"&&c.reason?.includes('Run "asm library list"')&&n.push(c.reason),a.push(c)}return{results:a,updatedCount:a.filter(l=>l.status==="updated").length,skippedCount:a.filter(l=>l.status==="skipped").length,failedCount:a.filter(l=>l.status==="failed").length,warnings:n}}import{join as rs}from"path";var um=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function pm(e){if(typeof e!="string")return null;let t=um.exec(e.trim());if(!t)return null;let[,r,s,o,n]=t;return{major:Number(r),minor:Number(s),patch:Number(o),prerelease:n?n.split("."):[]}}function mm(e,t){let r=pm(e);if(!r)throw new Error(`invalid semver: ${t} "${e}"`);return r}var jo=new Map;function _o(e){if(!e||typeof e.id!="string"||e.id.length===0)throw new Error("register: provider.id is required");if(mm(e.version,`provider ${e.id} version`),typeof e.schemaVersion!="number"||!Number.isInteger(e.schemaVersion))throw new Error(`register: provider ${e.id} schemaVersion must be an integer`);let t=jo.get(e.id)??[];if(t.some(r=>r.version===e.version))throw new Error(`register: provider ${e.id}@${e.version} already registered`);t.push(e),jo.set(e.id,t)}function zr(){let e=[];for(let t of jo.values())for(let r of t)e.push(r);return e}import{stat as fm}from"fs/promises";var qa="quality",Wa="1.0.0",Ka=1;function gm(e){return e.topSuggestions.map(t=>({severity:"info",message:t}))}function hm(e){return e.categories.map(t=>({id:t.id,name:t.name,score:t.score,max:t.max}))}var Ja={id:qa,version:Wa,schemaVersion:Ka,description:"Static linter for SKILL.md structure, description, and safety.",async applicable(e){try{return(await fm(e.skillMdPath)).isFile()?{ok:!0}:{ok:!1,reason:`${e.skillMdPath} is not a file`}}catch{return{ok:!1,reason:`SKILL.md not found at ${e.skillMdPath}`}}},async run(e,t){let r=await so(e.skillPath);return{providerId:qa,providerVersion:Wa,schemaVersion:Ka,score:r.overallScore,passed:r.grade!=="F",categories:hm(r),findings:gm(r),raw:r,startedAt:"",durationMs:0}}};var Qa=mn(fn(),1);import{readFile as ym,stat as bm}from"fs/promises";import{basename as wm}from"path";var za="skill-best-practice",Ya="1.2.0",Za=1,km=new Set(["name","description","license","allowed-tools","metadata","compatibility","effort","dependencies"]),Xa=new Set(["low","medium","high","xhigh","max"]),Uo=250,vm=/^\d+\.\d+\.\d+$/;function Sm(e){if(!e.startsWith("---"))return null;let t=e.split(`
224
+ `);if(t.length<3||t[0]?.trim()!=="---")return null;let r=t.findIndex((s,o)=>o>0&&s.trim()==="---");return r===-1?null:t.slice(1,r).join(`
225
+ `)}function Yr(e){return{severity:e.severity,message:e.message,code:e.id,categoryId:"validation"}}function ee(e,t,r,s,o,n){e.push({id:t,label:r,passed:s,severity:o,message:n})}function Zr(e,t,r){return{skillPath:e.skillPath,skillMdPath:e.skillMdPath,validatedAt:new Date().toISOString(),checkCount:t.length,passedChecks:t.filter(s=>s.passed).length,checks:t,frontmatter:r}}async function $m(e){let t=await ym(e.skillMdPath,"utf-8"),r=[],s=Sm(t);if(s===null){ee(r,"missing-frontmatter","Frontmatter exists",!1,"error","SKILL.md must start with a YAML frontmatter block.");let A=Zr(e,r,null);return{score:0,passed:!1,findings:r.map(Yr),raw:A}}ee(r,"frontmatter-present","Frontmatter exists",!0,"error","SKILL.md contains a YAML frontmatter block.");let o;try{o=(0,Qa.parse)(s)}catch(A){ee(r,"invalid-yaml","Frontmatter parses as YAML",!1,"error",`Invalid YAML in frontmatter: ${A?.message??String(A)}`);let _=Zr(e,r,null);return{score:0,passed:!1,findings:r.map(Yr),raw:_}}if(!o||typeof o!="object"||Array.isArray(o)){ee(r,"frontmatter-not-object","Frontmatter is a mapping",!1,"error","Frontmatter must parse to a YAML object.");let A=Zr(e,r,null);return{score:0,passed:!1,findings:r.map(Yr),raw:A}}let n=o;ee(r,"frontmatter-object","Frontmatter is a mapping",!0,"error","Frontmatter parses to a YAML object.");let a=Object.keys(n).filter(A=>!km.has(A));ee(r,"allowed-keys","Allowed top-level keys only",a.length===0,"error",a.length===0?"Frontmatter uses only the allowed top-level keys.":`Unexpected frontmatter key(s): ${a.sort().join(", ")}.`);let l=n.name,c=typeof l=="string"?l.trim():"";if(ee(r,"name-present","Name is present and non-empty",c.length>0,"error",c.length>0?"Frontmatter includes a non-empty `name`.":"Frontmatter must include a non-empty string `name`."),c.length>0){let A=/^[a-z0-9-]+$/.test(c)&&!c.startsWith("-")&&!c.endsWith("-")&&!c.includes("--")&&c.length<=64;ee(r,"name-kebab-case","Name follows skill-best-practice naming rules",A,"error",A?"Name follows the skill-best-practice kebab-case naming rules.":"Name must be kebab-case, avoid consecutive/edge hyphens, and stay within 64 characters.")}let d=n.description,u=typeof d=="string"?d.trim():"";if(ee(r,"description-present","Description is present and non-empty",u.length>0,"error",u.length>0?"Frontmatter includes a non-empty `description`.":"Frontmatter must include a non-empty string `description`."),u.length>0){let A=!u.includes(`
226
+ `)&&!u.includes("\r")&&!u.includes("<")&&!u.includes(">")&&u.length<=1024;ee(r,"description-shape","Description follows skill-best-practice formatting rules",A,"error",A?"Description is single-line, angle-bracket free, and within 1024 characters.":"Description must be a single line, avoid angle brackets, and stay within 1024 characters.");let _=u.length<=Uo;ee(r,"description-runtime-budget","Description fits the runtime context budget",_,"warning",_?`Description is ${u.length} chars (target \u2264 ${Uo}).`:`Description is ${u.length} chars; target \u2264 ${Uo}. The /skills listing truncates tail-first, often chopping the negative-trigger clause.`)}let p=n.effort;ee(r,"effort-enum","Effort uses the supported enum",p===void 0||typeof p=="string"&&Xa.has(p.trim()),"error",p===void 0||typeof p=="string"&&Xa.has(p.trim())?"Effort is omitted or uses a supported value.":"Effort must be one of: low, medium, high, xhigh, max.");let f=n.dependencies;if(f!==void 0){let A=Array.isArray(f)&&f.length>0&&f.every(_=>typeof _=="string"&&_.trim().length>0);ee(r,"dependencies-shape","Dependencies are non-empty skill reference strings",A,"error",A?"Dependencies are a non-empty YAML sequence of skill reference strings.":"Dependencies must be a non-empty YAML sequence containing only non-empty skill reference strings.")}let m=n.compatibility;if(m!==void 0){let A=typeof m=="string"&&m.length<=500;ee(r,"compatibility-shape","Compatibility is a short string",A,"error",A?"Compatibility is a valid short string.":"Compatibility must be a string no longer than 500 characters.")}let g=n.metadata&&typeof n.metadata=="object"&&!Array.isArray(n.metadata)?n.metadata:null,h=g?.version,y=typeof h=="string"||typeof h=="number"?String(h).trim():"",b=y.length>0;if(ee(r,"metadata-version-present","metadata.version is present",b,"error",b?"Frontmatter declares `metadata.version`.":"Frontmatter must declare `metadata.version` (start new skills at 1.0.0)."),b){let A=vm.test(y);ee(r,"metadata-version-semver","metadata.version follows MAJOR.MINOR.PATCH",A,"error",A?"`metadata.version` follows semantic versioning.":`\`metadata.version\` must follow semantic versioning (e.g. 1.0.0); got "${y}".`)}let $=g?.author,v=typeof $=="string"&&$.trim().length>0;if(ee(r,"metadata-author-present","metadata.author is present",v,"warning",v?"Frontmatter declares `metadata.author`.":"Add `metadata.author` (recommended for published skills) so users know who maintains the skill."),c.length>0){let A=wm(e.skillPath),_=A===c;ee(r,"name-matches-directory","Name matches the parent directory",_,"error",_?"Frontmatter `name` matches the skill directory.":`Frontmatter \`name\` ("${c}") must match the parent directory ("${A}").`)}let S=/don'?t use (?:for|when|if|on)|not (?:for|intended for|suitable for|meant for)\b|skip (?:for|when|if)|avoid (?:using )?(?:for|when|on)|never (?:use )?for\b|only (?:use )?for\b/i.test(u);ee(r,"negative-trigger-clause","Description includes a negative-trigger clause",S,"warning",S?"Description names adjacent cases that should not trigger the skill.":"Description appears to lack a negative-trigger clause; consider naming adjacent cases that should not trigger the skill.");let C=Zr(e,r,n),D=C.checkCount===0?100:Math.round(C.passedChecks/C.checkCount*100),U=r.filter(A=>!A.passed).map(Yr);return{score:D,passed:U.every(A=>A.severity!=="error"),findings:U,raw:C}}var el={id:za,version:Ya,schemaVersion:Za,description:"Deterministic SKILL.md best-practice validation (rules aligned with the skill-creator standard, v1.7.1).",async applicable(e){try{return(await bm(e.skillMdPath)).isFile()?{ok:!0}:{ok:!1,reason:`${e.skillMdPath} is not a file`}}catch{return{ok:!1,reason:`SKILL.md not found at ${e.skillMdPath}`}}},async run(e,t){let r=await $m(e);return{providerId:za,providerVersion:Ya,schemaVersion:Za,score:r.score,passed:r.passed,categories:[{id:"validation",name:"Deterministic validation",score:r.raw.passedChecks,max:r.raw.checkCount,findings:r.findings.length>0?r.findings:void 0}],findings:r.findings,raw:r.raw,startedAt:"",durationMs:0}}};function tl(){_o(Ja),_o(el)}var rl=!1;function Xr(){rl||(tl(),rl=!0)}function Qr(){return Xr(),zr()}function sl(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function ol(e,t,r,s,o){let n={severity:"error",message:s,code:o};return{providerId:e.id,providerVersion:e.version,schemaVersion:e.schemaVersion,score:0,passed:!1,categories:[],findings:[n],raw:void 0,startedAt:t,durationMs:r}}async function es(e,t,r={}){let s=new Date().toISOString(),o=performance.now(),n={id:e.id,version:e.version,schemaVersion:e.schemaVersion},a=new AbortController;r.signal&&(r.signal.aborted?a.abort(r.signal.reason):r.signal.addEventListener("abort",()=>a.abort(r.signal?.reason)));let l=null;typeof r.timeoutMs=="number"&&r.timeoutMs>0&&(l=setTimeout(()=>a.abort(new Error("timeout")),r.timeoutMs));let c={...r,signal:a.signal};try{let d=await Promise.race([e.run(t,c).then(f=>({kind:"ok",value:f})),new Promise(f=>{if(a.signal.aborted){f({kind:"timeout"});return}a.signal.addEventListener("abort",()=>f({kind:"timeout"}))})]),u=Math.max(0,Math.round(performance.now()-o));if(d.kind==="timeout"){let f=a.signal.reason,m=f instanceof Error&&f.message==="timeout"?`provider timed out after ${r.timeoutMs}ms`:`provider aborted: ${sl(f)}`;return ol(n,s,u,m,f instanceof Error&&f.message==="timeout"?"timeout":"aborted")}let p=d.value;return{...p,providerId:n.id,providerVersion:n.version,schemaVersion:p.schemaVersion??n.schemaVersion,startedAt:s,durationMs:u}}catch(d){let u=Math.max(0,Math.round(performance.now()-o));return ol(n,s,u,sl(d),"provider-threw")}finally{l&&clearTimeout(l)}}function xm(e){return e>=90?"A":e>=80?"B":e>=65?"C":e>=50?"D":"F"}function nl(e){return{id:e.providerId,version:e.providerVersion,schemaVersion:e.schemaVersion,score:e.score,passed:e.passed,categories:e.categories,findings:e.findings,raw:e.raw}}function il(e,t){return{providerId:e.providerId,providerVersion:e.providerVersion,schemaVersion:e.schemaVersion,passed:e.passed,overallScore:e.score,grade:xm(e.score),categories:e.categories.map(r=>({id:r.id,name:r.name,score:r.score,max:r.max})),evaluatedAt:e.startedAt,evaluatedVersion:t}}function or(e){return[...e].sort((t,r)=>t.id==="quality"&&r.id!=="quality"?-1:r.id==="quality"&&t.id!=="quality"?1:t.id.localeCompare(r.id))}import{join as Pm}from"path";function Rm(){console.log(`${i.bold("Usage:")} asm eval <target> [options]
365
227
 
366
228
  Evaluate a skill's SKILL.md against best practices and produce a scored quality
367
229
  report with recommendations. Zero configuration \u2014 just point it at a skill
@@ -372,11 +234,11 @@ Accepts a local path, a GitHub shorthand, or a GitHub URL. When the target is a
372
234
  collection (no SKILL.md at the root but each immediate child has one), every
373
235
  child skill is evaluated and an aggregate summary is printed.
374
236
 
375
- ${l.bold("Arguments:")}
237
+ ${i.bold("Arguments:")}
376
238
  target Local path, github:owner/repo[#ref][:subpath], or
377
239
  https://github.com/owner/repo[/tree/<ref>/<sub>]
378
240
 
379
- ${l.bold("Options:")}
241
+ ${i.bold("Options:")}
380
242
  --fix Apply deterministic auto-fixes to SKILL.md (creates .bak)
381
243
  --dry-run With --fix, preview the diff without writing
382
244
  --json Output report as JSON
@@ -387,34 +249,34 @@ ${l.bold("Options:")}
387
249
  --no-color Disable ANSI colors
388
250
  -V, --verbose Show debug output
389
251
 
390
- ${l.bold("Examples:")}
391
- asm eval ./my-skill ${l.dim("Score a single skill")}
392
- asm eval ./skills/ ${l.dim("Batch-score every skill in the dir")}
393
- asm eval github:mattpocock/skills:grill-me ${l.dim("Fetch a remote skill and score it")}
394
- asm eval github:mattpocock/skills ${l.dim("Batch-score a remote collection")}
252
+ ${i.bold("Examples:")}
253
+ asm eval ./my-skill ${i.dim("Score a single skill")}
254
+ asm eval ./skills/ ${i.dim("Batch-score every skill in the dir")}
255
+ asm eval github:mattpocock/skills:grill-me ${i.dim("Fetch a remote skill and score it")}
256
+ asm eval github:mattpocock/skills ${i.dim("Batch-score a remote collection")}
395
257
  asm eval https://github.com/mattpocock/skills/tree/main/grill-me
396
- asm eval ./my-skill --json ${l.dim("Output report as JSON")}
397
- asm eval ./my-skill --fix ${l.dim("Auto-fix deterministic issues")}
398
- asm eval ./my-skill --fix --dry-run ${l.dim("Preview fixes as diff")}
399
- asm eval ./my-skill --machine ${l.dim("Machine-readable v1 envelope")}
400
- asm eval-providers list ${l.dim("List registered eval providers")}`)}function U$(e){let t=e.findings.find(s=>s.severity==="error"&&(s.code==="provider-threw"||s.code==="timeout"||s.code==="aborted"));if(t)throw new Error(t.message)}async function yl(e,t,s){await Ae();let i=ue(e);if(i.isLocal)throw new Error(`fetchRemoteSkillDir received a local path: "${e}". This is a bug \u2014 local paths should use the non-remote branch.`);ye(i,e),i=await pt(i);let r=await Re(i,t),n=i.subpath?B$(r,i.subpath):r;try{Be(r,n,e)}catch(u){throw await Q(r),u}let o=null;try{let{execFile:u}=await import("child_process"),{promisify:f}=await import("util"),d=f(u),{stdout:p}=await d("git",["-C",r,"rev-parse","HEAD"],{timeout:5e3}),m=p.trim();/^[0-9a-f]{40}$/i.test(m)&&(o=m)}catch{}let a=`github:${i.owner}/${i.repo}${i.ref?`#${i.ref}`:""}${i.subpath?`:${i.subpath}`:""}`;return{rootDir:n,tempDir:r,cleanup:async()=>{s||await Q(r)},sourceRef:a,commitSha:o}}async function mm(e){en();try{let t={skillPath:e.skillPath,skillMdPath:e.skillMdPath},s=(await Promise.all(ai(tn()).map(async n=>(await n.applicable(t,{})).ok?sn(n,t):null))).filter(n=>n!==null),i=s.find(n=>n.providerId==="quality");if(!i)throw new Error("quality provider did not produce a result");return U$(i),{report:{...i.raw,providers:ai(s.map(fm))},error:null}}catch(t){return{report:null,error:t?.message??String(t)}}}async function hm(e){if(e.flags.help){q$();return}let t=e.flags.machine?he():void 0,s=performance.now(),i=e.subcommand;if(i||(e.flags.machine&&(t?.(),console.log(z("eval",Y.INVALID_ARGUMENT,"Missing required argument: <skill-path>",s)),process.exit(2)),$("Missing required argument: <skill-path>"),console.error('Run "asm eval --help" for usage.'),process.exit(2)),e.flags.fix){if(Wt(i)){let n="--fix is only supported for local skill paths. Clone the repo first or run `asm install` to materialise it locally.";e.flags.machine&&(t?.(),console.log(z("eval",Y.INVALID_ARGUMENT,n,s)),process.exit(2)),$(n),process.exit(2)}try{let n=await Da(),o=await Ma(i,{dryRun:e.flags.dryRun,gitAuthor:n});if(e.flags.machine){t?.(),console.log(V("eval",Xs(o.report,o),s));return}if(e.flags.json){console.log(JSON.stringify({report:o.report,fix:{dryRun:o.dryRun,applied:o.applied,skipped:o.skipped,backupPath:o.backupPath,diff:o.diff}},null,2));return}console.log(Ys(o.report)),console.log(""),console.log(_a(o));return}catch(n){e.flags.machine&&(t?.(),console.log(z("eval",Y.SKILL_NOT_FOUND,n?.message??String(n),s)),process.exit(1)),$(n?.message??String(n)),process.exit(1)}return}let r=null;try{r=await Ba(i,{fetchRemote:n=>yl(n,e.flags.transport,e.flags.keep)})}catch(n){e.flags.machine&&(t?.(),console.log(z("eval",Y.SKILL_NOT_FOUND,n?.message??String(n),s)),process.exit(1)),$(n?.message??String(n)),process.exit(1)}try{if(!r.isCollection&&r.targets.length===1){let u=r.targets[0],{report:f,error:d}=await mm(u);if(!f)throw new Error(d??"eval failed");if(e.flags.machine){t?.();let p=Xs(f,null),m=r.provenance.remote?{...p,provenance:{input:r.provenance.input,remote:!0,source_ref:r.provenance.sourceRef??null,commit_sha:r.provenance.commitSha??null,temp_path:r.provenance.tempPath??null}}:p;console.log(V("eval",m,s));return}if(e.flags.json){r.provenance.remote?console.log(JSON.stringify({...f,provenance:{input:r.provenance.input,remote:!0,sourceRef:r.provenance.sourceRef??null,commitSha:r.provenance.commitSha??null,tempPath:r.provenance.tempPath??null}},null,2)):console.log(Fa(f));return}console.log(Ys(f)),r.provenance.remote&&V$(r.provenance);return}let n=e.flags.concurrency||4;if(r.targets.length===0)throw new Error(`No skills to evaluate at "${i}" \u2014 the resolved location has no SKILL.md in itself or its immediate children.`);let o=await zs(r.targets,n,async u=>{let{report:f,error:d}=await mm(u);return{label:u.label,skillPath:u.skillPath,report:f,error:d}}),a=qa(o),c={provenance:r.provenance,aggregate:a,results:o};if(e.flags.machine){t?.(),console.log(V("eval",Va(c),s));return}if(e.flags.json){console.log(JSON.stringify({provenance:c.provenance,aggregate:c.aggregate,results:c.results.map(u=>({label:u.label,skillPath:u.skillPath,error:u.error,report:u.report}))},null,2));return}for(let u of c.results)u.report?console.log(Ys(u.report)):(console.log(`Skill evaluation: ${u.skillPath}`),console.log(` ${l.red("error:")} ${u.error??"unknown failure"}`)),console.log("");console.log(Ua(c)),r.provenance.remote&&e.flags.verbose}catch(n){e.flags.machine&&(t?.(),console.log(z("eval",Y.SKILL_NOT_FOUND,n?.message??String(n),s)),process.exit(1)),$(n?.message??String(n)),process.exit(1)}finally{if(r)try{await r.cleanup()}catch{}}}function V$(e){let t=[];t.push(""),t.push(l.dim("Fetched remote skill:")),e.sourceRef&&t.push(l.dim(` Source: ${e.sourceRef}`)),e.commitSha&&t.push(l.dim(` Commit: ${e.commitSha}`)),e.tempPath&&t.push(l.dim(` Temp: ${e.tempPath}`)),console.log(t.join(`
401
- `))}function K$(){console.log(`${l.bold("Usage:")} asm eval-providers <subcommand> [options]
402
-
403
- Manage evaluation providers registered with the ${l.bold("asm eval")} framework.
404
- Providers implement the ${l.bold("EvalProvider")} contract (see src/eval/types.ts) and
258
+ asm eval ./my-skill --json ${i.dim("Output report as JSON")}
259
+ asm eval ./my-skill --fix ${i.dim("Auto-fix deterministic issues")}
260
+ asm eval ./my-skill --fix --dry-run ${i.dim("Preview fixes as diff")}
261
+ asm eval ./my-skill --machine ${i.dim("Machine-readable v1 envelope")}
262
+ asm eval-providers list ${i.dim("List registered eval providers")}`)}function Em(e){let t=e.findings.find(r=>r.severity==="error"&&(r.code==="provider-threw"||r.code==="timeout"||r.code==="aborted"));if(t)throw new Error(t.message)}async function Bo(e,t,r){await ve();let s=oe(e);if(s.isLocal)throw new Error(`fetchRemoteSkillDir received a local path: "${e}". This is a bug \u2014 local paths should use the non-remote branch.`);de(s,e),s=await _e(s);let o=await Se(s,t),n=s.subpath?Pm(o,s.subpath):o;try{Ee(o,n,e)}catch(d){throw await z(o),d}let a=null;try{let{execFile:d}=await import("child_process"),{promisify:u}=await import("util"),p=u(d),{stdout:f}=await p("git",["-C",o,"rev-parse","HEAD"],{timeout:5e3}),m=f.trim();/^[0-9a-f]{40}$/i.test(m)&&(a=m)}catch{}let l=`github:${s.owner}/${s.repo}${s.ref?`#${s.ref}`:""}${s.subpath?`:${s.subpath}`:""}`;return{rootDir:n,tempDir:o,cleanup:async()=>{r||await z(o)},sourceRef:l,commitSha:a}}async function al(e){Xr();try{let t={skillPath:e.skillPath,skillMdPath:e.skillMdPath},r=(await Promise.all(or(Qr()).map(async n=>(await n.applicable(t,{})).ok?es(n,t):null))).filter(n=>n!==null),s=r.find(n=>n.providerId==="quality");if(!s)throw new Error("quality provider did not produce a result");return Em(s),{report:{...s.raw,providers:or(r.map(nl))},error:null}}catch(t){return{report:null,error:t?.message??String(t)}}}async function ll(e){if(e.flags.help){Rm();return}let t=e.flags.machine?le():void 0,r=performance.now(),s=e.subcommand;if(s||(e.flags.machine&&(t?.(),console.log(K("eval",W.INVALID_ARGUMENT,"Missing required argument: <skill-path>",r)),process.exit(2)),w("Missing required argument: <skill-path>"),console.error('Run "asm eval --help" for usage.'),process.exit(2)),e.flags.fix){if(yt(s)){let n="--fix is only supported for local skill paths. Clone the repo first or run `asm install` to materialise it locally.";e.flags.machine&&(t?.(),console.log(K("eval",W.INVALID_ARGUMENT,n,r)),process.exit(2)),w(n),process.exit(2)}try{let n=await no(),a=await oo(s,{dryRun:e.flags.dryRun,gitAuthor:n});if(e.flags.machine){t?.(),console.log(B("eval",Jt(a.report,a),r));return}if(e.flags.json){console.log(JSON.stringify({report:a.report,fix:{dryRun:a.dryRun,applied:a.applied,skipped:a.skipped,backupPath:a.backupPath,diff:a.diff}},null,2));return}console.log(Wt(a.report)),console.log(""),console.log(ao(a));return}catch(n){e.flags.machine&&(t?.(),console.log(K("eval",W.SKILL_NOT_FOUND,n?.message??String(n),r)),process.exit(1)),w(n?.message??String(n)),process.exit(1)}return}let o=null;try{o=await co(s,{fetchRemote:n=>Bo(n,e.flags.transport,e.flags.keep)})}catch(n){e.flags.machine&&(t?.(),console.log(K("eval",W.SKILL_NOT_FOUND,n?.message??String(n),r)),process.exit(1)),w(n?.message??String(n)),process.exit(1)}try{if(!o.isCollection&&o.targets.length===1){let d=o.targets[0],{report:u,error:p}=await al(d);if(!u)throw new Error(p??"eval failed");if(e.flags.machine){t?.();let f=Jt(u,null),m=o.provenance.remote?{...f,provenance:{input:o.provenance.input,remote:!0,source_ref:o.provenance.sourceRef??null,commit_sha:o.provenance.commitSha??null,temp_path:o.provenance.tempPath??null}}:f;console.log(B("eval",m,r));return}if(e.flags.json){o.provenance.remote?console.log(JSON.stringify({...u,provenance:{input:o.provenance.input,remote:!0,sourceRef:o.provenance.sourceRef??null,commitSha:o.provenance.commitSha??null,tempPath:o.provenance.tempPath??null}},null,2)):console.log(io(u));return}console.log(Wt(u)),o.provenance.remote&&Im(o.provenance);return}let n=e.flags.concurrency||4;if(o.targets.length===0)throw new Error(`No skills to evaluate at "${s}" \u2014 the resolved location has no SKILL.md in itself or its immediate children.`);let a=await Kt(o.targets,n,async d=>{let{report:u,error:p}=await al(d);return{label:d.label,skillPath:d.skillPath,report:u,error:p}}),l=uo(a),c={provenance:o.provenance,aggregate:l,results:a};if(e.flags.machine){t?.(),console.log(B("eval",mo(c),r));return}if(e.flags.json){console.log(JSON.stringify({provenance:c.provenance,aggregate:c.aggregate,results:c.results.map(d=>({label:d.label,skillPath:d.skillPath,error:d.error,report:d.report}))},null,2));return}for(let d of c.results)d.report?console.log(Wt(d.report)):(console.log(`Skill evaluation: ${d.skillPath}`),console.log(` ${i.red("error:")} ${d.error??"unknown failure"}`)),console.log("");console.log(po(c)),o.provenance.remote&&e.flags.verbose}catch(n){e.flags.machine&&(t?.(),console.log(K("eval",W.SKILL_NOT_FOUND,n?.message??String(n),r)),process.exit(1)),w(n?.message??String(n)),process.exit(1)}finally{if(o)try{await o.cleanup()}catch{}}}function Im(e){let t=[];t.push(""),t.push(i.dim("Fetched remote skill:")),e.sourceRef&&t.push(i.dim(` Source: ${e.sourceRef}`)),e.commitSha&&t.push(i.dim(` Commit: ${e.commitSha}`)),e.tempPath&&t.push(i.dim(` Temp: ${e.tempPath}`)),console.log(t.join(`
263
+ `))}function Cm(){console.log(`${i.bold("Usage:")} asm eval-providers <subcommand> [options]
264
+
265
+ Manage evaluation providers registered with the ${i.bold("asm eval")} framework.
266
+ Providers implement the ${i.bold("EvalProvider")} contract (see src/eval/types.ts) and
405
267
  are resolved by id and semver range.
406
268
 
407
- ${l.bold("Subcommands:")}
269
+ ${i.bold("Subcommands:")}
408
270
  list List every registered (id, version) provider
409
271
 
410
- ${l.bold("Options:")}
272
+ ${i.bold("Options:")}
411
273
  --json Output as JSON (list)
412
274
  --no-color Disable ANSI colors
413
275
  -V, --verbose Show debug output
414
276
 
415
- ${l.bold("Examples:")}
416
- asm eval-providers list ${l.dim("Show registered providers")}
417
- asm eval-providers list --json ${l.dim("Machine-readable listing")}`)}async function gm(e){if(e.flags.help){K$();return}let t=e.subcommand;switch(t||($("Missing subcommand. Use: list"),console.error('Run "asm eval-providers --help" for usage.'),process.exit(2)),t){case"list":{en();let s=Xr();if(e.flags.json){console.log(q(s.map(a=>({id:a.id,version:a.version,schemaVersion:a.schemaVersion,description:a.description,requires:a.requires??[]}))));return}if(s.length===0){console.log("No eval providers registered.");return}let i=["id","version","schemaVersion","description","requires"],r=s.map(a=>[a.id,a.version,String(a.schemaVersion),a.description,a.requires&&a.requires.length>0?a.requires.join(","):"-"]),n=i.map((a,c)=>Math.max(a.length,...r.map(u=>u[c].length))),o=a=>a.map((c,u)=>c.padEnd(n[u])).join(" ");console.log(l.bold(o(i))),console.log(n.map(a=>"-".repeat(a)).join(" "));for(let a of r)console.log(o(a));return}default:$(`Unknown eval-providers subcommand: "${t}". Use: list`),console.error('Run "asm eval-providers --help" for usage.'),process.exit(2)}}function G$(){console.log(`${l.bold("Usage:")} asm get <skill> [options]
277
+ ${i.bold("Examples:")}
278
+ asm eval-providers list ${i.dim("Show registered providers")}
279
+ asm eval-providers list --json ${i.dim("Machine-readable listing")}`)}async function cl(e){if(e.flags.help){Cm();return}let t=e.subcommand;switch(t||(w("Missing subcommand. Use: list"),console.error('Run "asm eval-providers --help" for usage.'),process.exit(2)),t){case"list":{Xr();let r=zr();if(e.flags.json){console.log(j(r.map(l=>({id:l.id,version:l.version,schemaVersion:l.schemaVersion,description:l.description,requires:l.requires??[]}))));return}if(r.length===0){console.log("No eval providers registered.");return}let s=["id","version","schemaVersion","description","requires"],o=r.map(l=>[l.id,l.version,String(l.schemaVersion),l.description,l.requires&&l.requires.length>0?l.requires.join(","):"-"]),n=s.map((l,c)=>Math.max(l.length,...o.map(d=>d[c].length))),a=l=>l.map((c,d)=>c.padEnd(n[d])).join(" ");console.log(i.bold(a(s))),console.log(n.map(l=>"-".repeat(l)).join(" "));for(let l of o)console.log(a(l));return}default:w(`Unknown eval-providers subcommand: "${t}". Use: list`),console.error('Run "asm eval-providers --help" for usage.'),process.exit(2)}}function Lm(){console.log(`${i.bold("Usage:")} asm get <skill> [options]
418
280
 
419
281
  Resolve a skill and write its SKILL.md body to stdout. Nothing is installed:
420
282
  no provider directory, no library entry, no residency in any system prompt.
@@ -432,7 +294,7 @@ Index, registry and remote sources are fetched into a temp clone, scanned with
432
294
  the same pre-install security scan \`asm install\` runs, and deleted. The body
433
295
  goes to stdout; provenance and the security verdict go to stderr.
434
296
 
435
- ${l.bold("Options:")}
297
+ ${i.bold("Options:")}
436
298
  --json Output {name, description, tier, source, commit,
437
299
  tokenCount, security, content} as a JSON object
438
300
  --machine Stable machine-readable v1 envelope
@@ -444,66 +306,94 @@ ${l.bold("Options:")}
444
306
  --no-color Disable ANSI colors
445
307
  -V, --verbose Show debug output
446
308
 
447
- ${l.bold("Examples:")}
448
- asm get code-review ${l.dim("Print the body to stdout")}
449
- asm get code-review > SKILL.md ${l.dim("Save it without installing")}
450
- asm get github:owner/repo:skills/review ${l.dim("Fetch a remote skill")}
451
- asm get owner/review --audit ${l.dim("Show the full security audit")}
452
- asm get code-review --json ${l.dim("Structured output")}`)}function H$(e){return e==="high"?l.red("[!] High Risk"):e==="medium"?l.yellow("[~] Medium Risk"):l.green("[ok] Safe")}function J$(e){let t=[` ${l.bold(e.name)} ${l.dim(J(e.tokenCount))}`,` ${l.dim("source:")} ${e.source}${e.commit?` @ ${e.commit.slice(0,7)}`:""} ${l.dim(`(${e.tier})`)}`];if(e.security){let{risk:s,warnings:i,categories:r}=e.security,n=i?l.dim(` (${i} warning${i===1?"":"s"}: ${r.join(", ")})`):"";t.push(` ${l.dim("security:")} ${H$(s)}${n}`)}t.push(` ${l.dim("residency:")} ${l.dim("none \u2014 nothing was installed")}`),process.stderr.write(t.join(`
309
+ ${i.bold("Examples:")}
310
+ asm get code-review ${i.dim("Print the body to stdout")}
311
+ asm get code-review > SKILL.md ${i.dim("Save it without installing")}
312
+ asm get github:owner/repo:skills/review ${i.dim("Fetch a remote skill")}
313
+ asm get owner/review --audit ${i.dim("Show the full security audit")}
314
+ asm get code-review --json ${i.dim("Structured output")}`)}function Am(e){return e==="high"?i.red("[!] High Risk"):e==="medium"?i.yellow("[~] Medium Risk"):i.green("[ok] Safe")}function Tm(e){let t=[` ${i.bold(e.name)} ${i.dim(H(e.tokenCount))}`,` ${i.dim("source:")} ${e.source}${e.commit?` @ ${e.commit.slice(0,7)}`:""} ${i.dim(`(${e.tier})`)}`];if(e.security){let{risk:r,warnings:s,categories:o}=e.security,n=s?i.dim(` (${s} warning${s===1?"":"s"}: ${o.join(", ")})`):"";t.push(` ${i.dim("security:")} ${Am(r)}${n}`)}t.push(` ${i.dim("residency:")} ${i.dim("none \u2014 nothing was installed")}`),process.stderr.write(t.join(`
453
315
  `)+`
454
316
 
455
- `)}async function W$(e,t){try{let{name:s,description:i}=await we(e);return{name:s,description:i}}catch(s){let i=(await mt(e)).filter(r=>r.relPath);if(i.length>0){let r=i.slice(0,5);throw new Error(`"${t}" holds ${i.length} skills, not one. Pick a skill:
456
- `+r.map(n=>` asm get ${t}:${n.relPath}`).join(`
457
- `),{cause:s})}throw s}}async function bl(e,t,s){ye(ue(t),t),process.stderr.write(l.dim(`Fetching ${t}\u2026
458
- `));let i=await yl(t,e.flags.transport,!1);try{let r=ue(t),n=`github:${r.owner}/${r.repo}${r.ref?`#${r.ref}`:""}`,{name:o,description:a}=await W$(i.rootDir,n),c=await rn(nn(i.rootDir,"SKILL.md"),"utf-8"),u=await Gs(i.rootDir),f={risk:Hs(u),warnings:u.length,categories:Array.from(new Set(u.map(d=>d.category))).sort()};return{result:{name:o,description:a,tier:s,source:i.sourceRef,commit:i.commitSha,tokenCount:qe(c),security:f,content:c},cleanup:i.cleanup,dir:i.rootDir,owner:r.owner,repo:r.repo}}catch(r){throw await i.cleanup(),r}}function wl(e,t,s,i={}){let r=W(e);return{name:i.name||r.name||s.split(/[/\\]/).pop()||s,description:i.description??(r.description||"").replace(/\s*\n\s*/g," ").trim(),tier:t,source:s,commit:i.commit??null,tokenCount:i.tokenCount??qe(e),security:null,content:e}}async function Y$(e,t){if(Wt(t))return bl(e,t,"remote");if(ft(t)||await Ks(t)){let a=ue(ft(t)?t:`./${t}`).localPath,c;try{c=await rn(nn(a,"SKILL.md"),"utf-8")}catch{throw new Error(`No SKILL.md found in "${a}".`)}return{result:wl(c,"local",a),cleanup:null,dir:a}}let s=await j(),i=await K(s,e.flags.scope),r=i.find(a=>a.dirName===t)??i.find(a=>a.name===t);if(r){let a=r._skillMdContent!==void 0?r._skillMdContent:await rn(nn(r.path,"SKILL.md"),"utf-8");return{result:wl(a,"installed",r.path,{name:r.name,description:r.description,tokenCount:r.tokenCount}),cleanup:null,dir:r.path}}let n=ni(await wt(),t);if(n&&!n.missing){let a=await rn(nn(n.libraryPath,"SKILL.md"),"utf-8");return{result:wl(a,"library",n.libraryPath,{name:n.name,commit:n.commitHash||null}),cleanup:null,dir:n.libraryPath}}let o=await Nf(t);if(o.status==="ambiguous")throw new qt(`"${t}" matches ${o.matches.length} indexed skills.`,o.matches.map(a=>`${a.repo.owner}/${a.repo.repo} \u2014 asm get ${a.skill.installUrl}`));if(o.status==="found")return bl(e,o.match.skill.installUrl,"index");if(tt(t)){let{resolved:a,multipleMatches:c,suggestions:u}=await jr(t,{noCache:e.flags.noCache});if(a){let f=a.manifest,d=f.repository.replace("https://github.com/",""),p=f.skill_path?`github:${d}#${f.commit}:${f.skill_path}`:`github:${d}#${f.commit}`;return bl(e,p,"registry")}if(c.length>0)throw new qt(`"${t}" is published by ${c.length} authors.`,c.slice(0,5).map(f=>`${f.author}/${f.name} \u2014 asm get ${f.author}/${f.name}`));if(u.length>0)throw new Error(`Skill "${t}" not found. Did you mean: ${u.join(", ")}?`)}throw new Error(`Skill "${t}" not found installed, in the library, in the index, or in the registry.`)}async function ym(e){if(e.flags.help){G$();return}let t=performance.now(),s=e.subcommand;s||($("Missing required argument: <skill>"),console.error('Run "asm get --help" for usage.'),process.exit(2));let i=he(),r=null;try{let n=await Y$(e,s);r=n.cleanup;let o=n.result;if(e.flags.audit){let a=await Me(n.dir,o.name,n.owner,n.repo);process.stderr.write(Gt(a)+`
459
- `)}e.flags.machine?process.stdout.write(V("get",o,t)+`
460
- `):e.flags.json?process.stdout.write(q(o)+`
461
- `):(J$(o),process.stdout.write(o.content),o.content.endsWith(`
317
+ `)}async function Nm(e,t){try{let{name:r,description:s}=await pe(e);return{name:r,description:s}}catch(r){let s=(await Ue(e)).filter(o=>o.relPath);if(s.length>0){let o=s.slice(0,5);throw new Error(`"${t}" holds ${s.length} skills, not one. Pick a skill:
318
+ `+o.map(n=>` asm get ${t}:${n.relPath}`).join(`
319
+ `),{cause:r})}throw r}}async function Vo(e,t,r){de(oe(t),t),process.stderr.write(i.dim(`Fetching ${t}\u2026
320
+ `));let s=await Bo(t,e.flags.transport,!1);try{let o=oe(t),n=`github:${o.owner}/${o.repo}${o.ref?`#${o.ref}`:""}`,{name:a,description:l}=await Nm(s.rootDir,n),c=await ts(rs(s.rootDir,"SKILL.md"),"utf-8"),d=Qe(q(c)),u=await Bt(s.rootDir),p={risk:Vt(u),warnings:u.length,categories:Array.from(new Set(u.map(f=>f.category))).sort()};return{result:{name:a,description:l,dependencies:d,tier:r,source:s.sourceRef,commit:s.commitSha,tokenCount:Ce(c),security:p,content:c},cleanup:s.cleanup,dir:s.rootDir,owner:o.owner,repo:o.repo}}catch(o){throw await s.cleanup(),o}}function Go(e,t,r,s={}){let o=q(e);return{name:s.name||o.name||r.split(/[/\\]/).pop()||r,description:s.description??(o.description||"").replace(/\s*\n\s*/g," ").trim(),dependencies:Qe(o),tier:t,source:r,commit:s.commit??null,tokenCount:s.tokenCount??Ce(e),security:null,content:e}}async function ss(e,t){if(yt(t))return Vo(e,t,"remote");if(je(t)||await Ut(t)){let l=oe(je(t)?t:`./${t}`).localPath,c;try{c=await ts(rs(l,"SKILL.md"),"utf-8")}catch{throw new Error(`No SKILL.md found in "${l}".`)}return{result:Go(c,"local",l),cleanup:null,dir:l}}let r=await O(),s=await V(r,e.flags.scope),o=s.find(l=>l.dirName===t)??s.find(l=>l.name===t);if(o){let l=o._skillMdContent!==void 0?o._skillMdContent:await ts(rs(o.path,"SKILL.md"),"utf-8");return{result:Go(l,"installed",o.path,{name:o.name,description:o.description,tokenCount:o.tokenCount}),cleanup:null,dir:o.path}}let n=rr(await He(),t);if(n&&!n.missing){let l=await ts(rs(n.libraryPath,"SKILL.md"),"utf-8");return{result:Go(l,"library",n.libraryPath,{name:n.name,commit:n.commitHash||null}),cleanup:null,dir:n.libraryPath}}let a=await Pi(t);if(a.status==="ambiguous")throw new dt(`"${t}" matches ${a.matches.length} indexed skills.`,a.matches.map(l=>`${l.repo.owner}/${l.repo.repo} \u2014 asm get ${l.skill.installUrl}`));if(a.status==="found")return Vo(e,a.match.skill.installUrl,"index");if(Ne(t)){let{resolved:l,multipleMatches:c,suggestions:d}=await Fr(t,{noCache:e.flags.noCache});if(l){let u=l.manifest,p=u.repository.replace("https://github.com/",""),f=u.skill_path?`github:${p}#${u.commit}:${u.skill_path}`:`github:${p}#${u.commit}`;return Vo(e,f,"registry")}if(c.length>0)throw new dt(`"${t}" is published by ${c.length} authors.`,c.slice(0,5).map(u=>`${u.author}/${u.name} \u2014 asm get ${u.author}/${u.name}`));if(d.length>0)throw new Error(`Skill "${t}" not found. Did you mean: ${d.join(", ")}?`)}throw new Error(`Skill "${t}" not found installed, in the library, in the index, or in the registry.`)}async function dl(e){if(e.flags.help){Lm();return}let t=performance.now(),r=e.subcommand;r||(w("Missing required argument: <skill>"),console.error('Run "asm get --help" for usage.'),process.exit(2));let s=le(),o=null;try{let n=await ss(e,r);o=n.cleanup;let a=n.result;if(e.flags.audit){let l=await xe(n.dir,a.name,n.owner,n.repo);process.stderr.write(ft(l)+`
321
+ `)}e.flags.machine?process.stdout.write(B("get",a,t)+`
322
+ `):e.flags.json?process.stdout.write(j(a)+`
323
+ `):(Tm(a),process.stdout.write(a.content),a.content.endsWith(`
462
324
  `)||process.stdout.write(`
463
- `))}catch(n){let o=n?.message||String(n),a=n instanceof qt?n.candidates:void 0;if(e.flags.machine)process.stdout.write(z("get",a?Y.INVALID_ARGUMENT:Y.SKILL_NOT_FOUND,o,t,a?{candidates:a}:void 0)+`
464
- `);else if($(o),a)for(let c of a)process.stderr.write(` ${l.cyan("\u2022")} ${c}
465
- `);else process.stderr.write(l.dim(`Try ${l.bold("asm list")} or ${l.bold(`asm search "${s}"`)}.
466
- `));process.exitCode=1}finally{r&&await r(),i()}}import{resolve as bm}from"path";function z$(){console.log(`${l.bold("Usage:")} asm uninstall <skill-name> [options]
325
+ `))}catch(n){let a=n?.message||String(n),l=n instanceof dt?n.candidates:void 0;if(e.flags.machine)process.stdout.write(K("get",l?W.INVALID_ARGUMENT:W.SKILL_NOT_FOUND,a,t,l?{candidates:l}:void 0)+`
326
+ `);else if(w(a),l)for(let c of l)process.stderr.write(` ${i.cyan("\u2022")} ${c}
327
+ `);else process.stderr.write(i.dim(`Try ${i.bold("asm list")} or ${i.bold(`asm search "${r}"`)}.
328
+ `));process.exitCode=1}finally{o&&await o(),s()}}import{createHash as Om,randomUUID as qo}from"crypto";import{execFile as Dm}from"child_process";import{access as ml,cp as Mm,lstat as ye,mkdir as Wo,readFile as ir,readdir as Ko,realpath as We,rename as Fm,rm as Ke,rmdir as jm}from"fs/promises";import{basename as is,dirname as as,isAbsolute as _m,join as ne,relative as fl,resolve as qe}from"path";import{promisify as Um}from"util";var Bm=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Vm=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Gm=100,Hm=10*6e4,qm=Um(Dm);function kt(e){if(!Bm.test(e))throw new Error("Invalid session identity. Use 1-128 letters, digits, dots, underscores, colons, or hyphens.");return e}function Wm(e){return qe(e.rootDir??Ln())}function gl(e){return Om("sha256").update(e).digest("hex")}function hl(e){return gl(kt(e))}function yl(e){return gl(e.trim())}function ze(e,t){return ne(e,"sessions",`${hl(t)}.json`)}function os(e,t){return ne(e,"artifacts",hl(t))}function bl(e,t){return ne(e,`.asm-owner-${t}.json`)}function Km(e){return`${e}.lock`}function Jm(e,t){try{let r=JSON.parse(e);return!r||r.version!==1||!Number.isSafeInteger(r.pid)||r.pid<=0||!(r.processStartIdentity===void 0||r.processStartIdentity===null||typeof r.processStartIdentity=="string"&&r.processStartIdentity.length>0&&r.processStartIdentity.length<=256)||r.token!==t||!Vm.test(r.token)||!Number.isFinite(Date.parse(r.acquiredAt??""))||!(r.ticket===null||Number.isSafeInteger(r.ticket)&&r.ticket>0)?null:{...r,processStartIdentity:r.processStartIdentity??null}}catch{return null}}function zm(e){try{return process.kill(e,0),"alive"}catch(t){return t?.code==="ESRCH"?"dead":"unknown"}}async function Ym(e,t,r){try{let{stdout:s}=await qm(e,t,{timeout:Math.max(1,Math.min(2e3,r)),env:{...process.env,LANG:"C",LC_ALL:"C"}});return s.trim()||null}catch{return null}}async function Zm(e,t,r,s){if(!Number.isSafeInteger(e)||e<=0||t<=0)return null;try{if(r==="linux"){let n=await ir(`/proc/${e}/stat`,"utf-8"),l=n.slice(n.lastIndexOf(")")+2).split(" ")[19];return l?`linux:${l}`:null}if(r==="win32"){let n=await s("powershell.exe",["-NoProfile","-NonInteractive","-Command","$p = Get-Process -Id ([int]$args[0]) -ErrorAction Stop; $p.StartTime.ToUniversalTime().Ticks",String(e)],t);return n&&/^\d+$/.test(n)?`windows:${n}`:null}let o=await s("ps",["-o","lstart=","-p",String(e)],t);return o?`ps:${o}`:null}catch{return null}}function nr(e){return new Error(`Timed out waiting for dependency lease lock: ${e}`)}async function wl(e,t,r,s){let o=t-Date.now();if(o<=0)throw nr(r);let n=s.lockProcessStartIdentity,a=n?n(e,o):Zm(e,o,s.lockPlatform??process.platform,s.lockProcessIdentityCommand??Ym),l;try{return await Promise.race([a,new Promise((c,d)=>{l=setTimeout(()=>d(nr(r)),o)})])}finally{l&&clearTimeout(l)}}async function ul(e,t){await ot(e,JSON.stringify(t,null,2)+`
329
+ `)}async function pl(e,t,r,s){let o=[],n=!1;for(let a of(await Ko(e)).filter(l=>l.endsWith(".json")).sort()){if(Date.now()>=r)throw nr(e);let l=is(a,".json"),c=ne(e,a),d;try{let m=await ye(c);if(m.isSymbolicLink()||!m.isFile()){n=!0;continue}d=Jm(await ir(c,"utf-8"),l)}catch(m){if(m?.code==="ENOENT")continue;throw m}if(!d){n=!0;continue}if(d.token===t){o.push(d);continue}if((s.lockProcessLiveness??zm)(d.pid)==="dead"){await Ke(c,{force:!0});continue}let p=await wl(d.pid,r,e,s);if(d.processStartIdentity!==null&&p!==null&&d.processStartIdentity!==p){await Ke(c,{force:!0});continue}o.push(d)}return{candidates:o,invalidOwner:n}}async function Xm(e,t,r,s){let o=Km(t);await ns(e,as(t)),await Qm(e,t),await ns(e,o);let n=Date.now(),a=s.lockTimeoutMs??Hm,l=s.lockRetryMs??Gm,c=n+a,d=qo(),u=ne(o,`${d}.json`),p={version:1,pid:process.pid,processStartIdentity:await wl(process.pid,c,o,s),token:d,acquiredAt:new Date().toISOString(),ticket:null};await ul(u,p);try{for(;p.ticket===null;){let{candidates:f,invalidOwner:m}=await pl(o,d,c,s);if(!m){p.ticket=Math.max(0,...f.map(g=>g.ticket??0))+1,await ul(u,p);break}if(Date.now()>=c)throw nr(o);await new Promise(g=>setTimeout(g,Math.min(l,c-Date.now())))}for(;;){let{candidates:f,invalidOwner:m}=await pl(o,d,c,s),g=f.some(h=>h.token!==d&&(h.ticket===null||h.ticket<p.ticket||h.ticket===p.ticket&&h.token.localeCompare(d)<0));if(!m&&!g)break;if(Date.now()>=c)throw nr(o);await new Promise(h=>setTimeout(h,Math.min(l,c-Date.now())))}return await r()}finally{await Ke(u,{force:!0})}}function Jo(e,t,r,s){return st(t,()=>Xm(e,t,r,s))}function Je(e,t){let r=fl(qe(e),qe(t));return r===""||!!r&&!r.startsWith("..")&&!_m(r)}async function zo(e,t){let r=Wm(e);try{t&&await Wo(r,{recursive:!0});let s=await We(r),o=await ye(s);if(!o.isDirectory()||o.isSymbolicLink())throw new Error(`Dependency leases root is not a real directory: ${r}`);return s}catch(s){if(!t&&s?.code==="ENOENT")return null;throw s}}async function ns(e,t){if(!Je(e,t))throw new Error(`Managed dependency path escapes lease root: ${t}`);let r=e,s=fl(e,t).split(/[\\/]+/).filter(Boolean);for(let o of s){r=ne(r,o);try{let a=await ye(r);if(a.isSymbolicLink()||!a.isDirectory())throw new Error(`Refusing symlink or non-directory in managed dependency path: ${r}`)}catch(a){if(a?.code!=="ENOENT")throw a;try{await Wo(r)}catch(c){if(c?.code!=="EEXIST")throw c}let l=await ye(r);if(l.isSymbolicLink()||!l.isDirectory())throw new Error(`Refusing symlink or non-directory in managed dependency path: ${r}`,{cause:a})}let n=await We(r);if(!Je(e,n))throw new Error(`Managed dependency directory resolves outside lease root: ${r}`)}}async function Qm(e,t){if(!Je(e,t))throw new Error(`Managed dependency file escapes lease root: ${t}`);let r=await We(as(t));if(!Je(e,r))throw new Error(`Managed dependency file parent resolves outside lease root: ${t}`);try{let s=await ye(t);if(s.isSymbolicLink()||!s.isFile())throw new Error(`Refusing symlink or non-file in managed dependency path: ${t}`)}catch(s){if(s?.code!=="ENOENT")throw s}}async function ls(e,t){let r=await ye(e);if(r.isSymbolicLink())throw new Error(`Dependency tree contains a symbolic link: ${e}`);if(!r.isDirectory()){if(!r.isFile())throw new Error(`Dependency tree contains an unsupported entry: ${e}`);return}for(let s of await Ko(e))t&&s===".git"||await ls(ne(e,s),t)}async function ef(e){let t=await ye(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error(`Temporary dependency source must be a real directory: ${e}`);let r=await We(e),s=ne(e,"SKILL.md"),o=await ye(s);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Temporary dependency SKILL.md must be a real file: ${s}`);let n=await We(s);if(!Je(r,n))throw new Error(`Temporary dependency SKILL.md resolves outside its source: ${s}`);return await ls(r,!0),r}function tf(e){return e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+/,"").slice(0,64)||"skill"}function rf(e,t){return{version:1,sessionId:e,createdAt:t,updatedAt:t,acquisitions:{}}}function kl(e,t){let r=JSON.parse(e);if(!r||typeof r!="object"||r.version!==1||typeof r.sessionId!="string"||typeof r.createdAt!="string"||typeof r.updatedAt!="string"||!r.acquisitions||typeof r.acquisitions!="object"||Array.isArray(r.acquisitions)||t!==void 0&&r.sessionId!==t)throw new Error("Invalid dependency lease state.");return r}async function Yo(e,t){try{return kl(await ir(ze(e,t),"utf-8"),t)}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return null;throw r instanceof SyntaxError?new Error(`Dependency lease state for session "${t}" is corrupted; refusing to mutate its artifacts.`,{cause:r}):r}}async function wt(e,t,r){let s=ze(e,t.sessionId),o=JSON.stringify(t,null,2)+`
330
+ `;await(r.writeState??ot)(s,o)}async function vl(e){if(!e||e.status!=="ready")return!1;try{return await ml(e.skillMdPath),!0}catch{return!1}}async function sf(e,t,r){kt(t);let s=r.trim();if(!s)throw new Error("Dependency reference cannot be empty.");let n=(await Yo(e,t))?.acquisitions[yl(s)];return await vl(n)?{...n,sessionId:t,reused:!0}:null}async function Sl(e,t,r={}){let s=kt(e),o=await zo(r,!0);return Jo(o,ze(o,s),()=>t({find:n=>sf(o,s,n),acquire:n=>{if(kt(n.sessionId)!==s)throw new Error("Dependency acquisition session does not match the locked session.");return of(n,o,r)}}),r)}async function of(e,t,r){let s=kt(e.sessionId),o=e.request.trim();if(!o)throw new Error("Dependency reference cannot be empty.");let n=e.temporary?await ef(e.sourceDir):null;e.temporary||await ml(ne(e.sourceDir,"SKILL.md"));let a=ze(t,s),l=new Date().toISOString(),c=yl(o),d;if(e.temporary){let m=qo(),g=ne(os(t,s),`${tf(e.name)}-${c.slice(0,12)}-${m.slice(0,8)}`);d={request:o,name:e.name,path:g,skillMdPath:ne(g,"SKILL.md"),tier:e.tier,source:e.source,commit:e.commit,status:"pending",owned:!0,artifactId:m,acquiredAt:l}}else{let m=await We(e.sourceDir);d={request:o,name:e.name,path:m,skillMdPath:ne(m,"SKILL.md"),tier:e.tier,source:e.source,commit:e.commit,status:"ready",owned:!1,artifactId:null,acquiredAt:l}}let u=await Yo(t,s),p=u?.acquisitions[c];if(await vl(p))return{...p,sessionId:s,reused:!0};p?.owned&&await Ho(t,s,p,r);let f=u??rf(s,l);if(f.updatedAt=l,f.acquisitions[c]=d,!d.owned)return await wt(t,f,r),{...d,sessionId:s,reused:!1};try{await wt(t,f,r)}catch(m){if(!(m instanceof Lt))throw m}try{let m=os(t,s);await ns(t,m);let g=await We(as(d.path));if(!Je(t,g))throw new Error(`Dependency artifact parent resolves outside lease root: ${d.path}`);await Wo(d.path);let h=await ye(d.path);if(h.isSymbolicLink()||!h.isDirectory())throw new Error(`Dependency artifact is not a real directory: ${d.path}`);let y={version:1,sessionId:s,artifactId:d.artifactId,path:d.path};await ot(bl(d.path,d.artifactId),JSON.stringify(y,null,2)+`
331
+ `),await Mm(n,d.path,{recursive:!0,filter:b=>b===n||is(b)!==".git"}),await ls(d.path,!1),d.status="ready",f.updatedAt=new Date().toISOString(),f.acquisitions[c]=d;try{await wt(t,f,r)}catch(b){if(!(b instanceof Lt))throw b}return{...d,sessionId:s,reused:!1}}catch(m){try{await Ho(t,s,d,r),delete f.acquisitions[c],Object.keys(f.acquisitions).length===0?await Ke(a,{force:!0}):(f.updatedAt=new Date().toISOString(),await wt(t,f,r))}catch(g){throw new Error(`Dependency acquisition failed (${m instanceof Error?m.message:String(m)}) and its artifact was preserved because ownership-safe cleanup failed: ${g instanceof Error?g.message:String(g)}`,{cause:g})}throw m}}async function Ho(e,t,r,s){let o=os(e,t);if(!Je(o,r.path))throw new Error(`Refusing to remove artifact outside its lease: ${r.path}`);if(qe(as(r.path))!==qe(o))throw new Error(`Refusing to remove artifact from an unexpected lease descendant: ${r.path}`);if(!r.artifactId)throw new Error(`Refusing to remove artifact without an ownership identity: ${r.path}`);await ns(e,o);try{if((await ye(r.path)).isSymbolicLink())throw new Error(`Refusing to remove symbolic-link artifact: ${r.path}`)}catch(p){if(p?.code==="ENOENT")return"missing";throw p}let n=ne(o,`.${is(r.path)}.quarantine-${qo()}`);try{await(s.renameArtifact??Fm)(r.path,n)}catch(p){let f=p?.code;if(f==="ENOENT")return"missing";throw f==="EXDEV"?new Error(`Refusing non-atomic cross-device artifact removal: ${r.path}`,{cause:p}):p}let a=await ye(n);if(a.isSymbolicLink()||!a.isDirectory())throw new Error(`Preserved quarantined replacement that is not an owned directory: ${n}`);let l=bl(n,r.artifactId),c=await ye(l).catch(p=>{throw new Error(`Preserved quarantined artifact without an ownership marker: ${n}`,{cause:p})});if(c.isSymbolicLink()||!c.isFile())throw new Error(`Preserved quarantined artifact with an unsafe ownership marker: ${n}`);let d,u;try{d=await ir(l,"utf-8"),u=JSON.parse(d)}catch(p){throw new Error(`Preserved quarantined artifact with invalid ownership marker: ${n}`,{cause:p})}if(u.version!==1||u.sessionId!==t||u.artifactId!==r.artifactId||qe(u.path??"")!==qe(r.path))throw new Error(`Preserved quarantined artifact with mismatched ownership: ${n}`);return await ls(n,!1),await Ke(n,{recursive:!0}),"removed"}async function $l(e,t={}){kt(e);let r=await zo(t,!1);if(!r)return{sessionId:e,alreadyReleased:!0,removed:[],preserved:[],missing:[],errors:[]};let s=ze(r,e);return Jo(r,s,()=>xl(r,e,t),t)}async function xl(e,t,r){let s=ze(e,t),o=await Yo(e,t);if(!o)return{sessionId:t,alreadyReleased:!0,removed:[],preserved:[],missing:[],errors:[]};let n={sessionId:t,alreadyReleased:!1,removed:[],preserved:[],missing:[],errors:[]},a={};for(let[l,c]of Object.entries(o.acquisitions)){if(!c.owned){n.preserved.push(c.path);continue}try{let d=await Ho(e,t,c,r);n[d].push(c.path)}catch(d){n.errors.push(d instanceof Error?d.message:String(d)),a[l]=c}}if(Object.keys(a).length===0){let l=os(e,t);try{await jm(l),await Ke(s,{force:!0})}catch(c){c?.code==="ENOENT"?await Ke(s,{force:!0}):(n.errors.push(`Preserved unknown content in dependency lease artifacts directory: ${l}`),o.updatedAt=new Date().toISOString(),o.acquisitions={},await wt(e,o,r))}}else o.updatedAt=new Date().toISOString(),o.acquisitions=a,await wt(e,o,r);return n}async function Pl(e,t,r={}){if(!Number.isFinite(e.getTime()))throw new Error("--stale-before must be a valid ISO-8601 timestamp.");let s={staleBefore:e.toISOString(),dryRun:t,stale:[],active:[],cleaned:[],errors:[]},o=await zo(r,!1);if(!o)return s;let n;try{n=await Ko(ne(o,"sessions"))}catch(a){if(a instanceof Error&&"code"in a&&a.code==="ENOENT")return s;throw a}for(let a of n.filter(l=>l.endsWith(".json")).sort()){let l=ne(o,"sessions",a);try{await Jo(o,l,async()=>{let c;try{c=await ir(l,"utf-8")}catch(f){if(f?.code==="ENOENT")return;throw f}let d=kl(c);if(ze(o,d.sessionId)!==l)throw new Error("Dependency lease filename does not match session.");let u=Date.parse(d.updatedAt);if(!Number.isFinite(u))throw new Error("Lease has an invalid updatedAt timestamp.");if(u>=e.getTime()){s.active.push(d.sessionId);return}if(s.stale.push(d.sessionId),t)return;let p=await xl(o,d.sessionId,r);p.errors.length>0?s.errors.push({sessionId:d.sessionId,message:p.errors.join("; ")}):s.cleaned.push(d.sessionId)},r)}catch(c){s.errors.push({sessionId:is(a,".json"),message:c instanceof Error?c.message:String(c)})}}return s}function nf(){console.log(`${i.bold("Usage:")} asm deps <subcommand> [arguments] [options]
332
+
333
+ Discover and acquire optional skill dependencies with caller-owned leases.
334
+ ASM returns a directly usable path; it does not launch or supervise the agent.
335
+
336
+ ${i.bold("Subcommands:")}
337
+ discover <parent> List dependencies declared by a skill
338
+ acquire <dependency> Make one dependency usable for a session
339
+ release Release a session and remove only lease-owned copies
340
+ cleanup Recover explicitly stale sessions from earlier runs
341
+
342
+ ${i.bold("Options:")}
343
+ --session <id> Caller-supplied session identity (acquire, release)
344
+ --stale-before <time> ISO-8601 cutoff chosen by the caller (cleanup)
345
+ --dry-run Classify stale sessions without releasing them
346
+ --json Output a JSON object
347
+ -s, --scope <scope> Installed lookup scope (default: both)
348
+ --transport <mode> Remote clone transport: auto, https, ssh
349
+ --no-cache Bypass registry cache
350
+ --no-color Disable ANSI colors
351
+
352
+ ${i.bold("Examples:")}
353
+ asm deps discover parent-skill --json
354
+ asm deps acquire code-review --session run-123 --json
355
+ asm deps release --session run-123 --json
356
+ asm deps cleanup --stale-before 2026-09-08T00:00:00Z --dry-run --json`)}function Rl(e,t){let r=e.positional[0];return r||(w(`Missing required argument: <${t}>`),console.error('Run "asm deps --help" for usage.'),process.exitCode=2,null)}function El(e){return e.flags.session?e.flags.session:(w('Missing required option: "--session <id>".'),console.error('Run "asm deps --help" for usage.'),process.exitCode=2,null)}function cs(e,t,r){console.log(e.flags.json?j(t):r)}async function af(e){let t=Rl(e,"parent");if(!t)return;let r=await ss(e,t);try{let s={name:r.result.name,source:r.result.source,dependencies:r.result.dependencies};cs(e,s,xn(s))}finally{await r.cleanup?.()}}async function lf(e){let t=Rl(e,"dependency"),r=El(e);if(!t||!r)return;let s=await Sl(r,async o=>{let n=await o.find(t);if(n)return n;let a=await ss(e,t);try{return await o.acquire({sessionId:r,request:t,name:a.result.name,sourceDir:a.dir,tier:a.result.tier,source:a.result.source,commit:a.result.commit,temporary:a.cleanup!==null})}finally{await a.cleanup?.()}});cs(e,s,Pn(s))}async function cf(e){let t=El(e);if(!t)return;let r=await $l(t);cs(e,r,Rn(r)),r.errors.length>0&&(process.exitCode=1)}async function df(e){let t=e.flags.staleBefore;if(!t){w('Missing required option: "--stale-before <ISO-8601>".'),console.error('Run "asm deps --help" for usage.'),process.exitCode=2;return}let r=new Date(t);if(!Number.isFinite(r.getTime())){w('"--stale-before" must be a valid ISO-8601 timestamp.'),process.exitCode=2;return}let s=await Pl(r,e.flags.dryRun);cs(e,s,En(s)),s.errors.length>0&&(process.exitCode=1)}async function Il(e){if(e.flags.help){nf();return}try{switch(e.subcommand){case"discover":await af(e);return;case"acquire":await lf(e);return;case"release":await cf(e);return;case"cleanup":await df(e);return;default:w("Missing or unknown deps subcommand. Use: discover, acquire, release, or cleanup."),console.error('Run "asm deps --help" for usage.'),process.exitCode=2}}catch(t){w(t instanceof Error?t.message:String(t)),process.exitCode=1}}import{resolve as Cl}from"path";function uf(){console.log(`${i.bold("Usage:")} asm uninstall <skill-name> [options]
467
357
 
468
358
  Remove a skill and its associated rule files. Shows a removal plan
469
359
  before proceeding and asks for confirmation.
470
360
 
471
- ${l.bold("Options:")}
361
+ ${i.bold("Options:")}
472
362
  -y, --yes Skip confirmation prompt
473
363
  -s, --scope <s> Filter: global, project, or both (default: both)
474
364
  -p, --tool <name> Filter by tool/provider (e.g., claude, codex)
475
365
  --no-color Disable ANSI colors
476
366
  -V, --verbose Show debug output
477
367
 
478
- ${l.bold("Examples:")}
479
- asm uninstall code-review ${l.dim("Remove with confirmation")}
480
- asm uninstall code-review -y ${l.dim("Remove without confirmation")}
481
- asm uninstall code-review -s project ${l.dim("Remove project copy only")}
482
- asm uninstall code-review -p claude ${l.dim("Remove from Claude only")}`)}async function wm(e){if(e.flags.help){z$();return}let t=e.subcommand;t||($("Missing required argument: <skill-name>"),console.error('Run "asm uninstall --help" for usage.'),process.exit(2));let s=await j(),i=await K(s,e.flags.scope),r={};e.flags.provider&&(r.providerFilter=e.flags.provider),e.flags.scope&&e.flags.scope!=="both"&&(r.scopeFilter=e.flags.scope);let n=rc(t,i,s,r),o=await oc(n);o.length===0&&($(`Skill "${t}" not found or nothing to remove.`),process.exit(1));let a=i.filter(m=>m.dirName===t),c=r.providerFilter,u=null;c&&(u=nc(n,a,c)),console.error(l.bold("Removal plan:")),console.error(` ${l.dim("Scope:")} ${r.scopeFilter||"both"}`),c&&(console.error(` ${l.dim("Tool:")} ${c}`),u?.needed&&console.error(` ${l.yellow("\u26A0 Real folder relocation:")} ${u.fromPath} \u2192 ${u.toPath} (${u.toProvider})`)),console.error("");for(let m of o)console.error(` ${l.red("\u2022")} ${Ue(m)}`);if(!e.flags.yes){process.stdin.isTTY||($("Cannot prompt for confirmation in non-interactive mode. Use --yes to skip."),process.exit(2)),process.stderr.write(`
483
- ${l.bold("Proceed with removal?")} [y/N] `);let m=await H();m.toLowerCase()!=="y"&&m.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let f;try{f=await Pi(n,void 0,u?.needed?u:void 0)}catch(m){let g=Array.isArray(m?.log)?m.log:[];for(let h of g)console.error(h);$(m?.message||"Uninstall failed."),process.exit(1)}for(let m of f)console.error(m);let d=new Set(n.directories.map(m=>bm(m.path))),p=a.filter(m=>!d.has(bm(m.originalPath)));try{c&&p.length>0?u?.needed&&!u.repointOnly&&await tc(t,u.toProvider):await ec(t)}catch{}console.error(l.green(`
484
- Done.`))}import{realpath as Sx}from"fs/promises";import{resolve as Nm,sep as Tm}from"path";import{readdir as X$,stat as Z$}from"fs/promises";import{join as Q$}from"path";async function ex(e){let t=0;try{let i=(await X$(e,{recursive:!0})).map(async n=>{try{let o=await Z$(Q$(e,n));if(o.isFile())return o.size}catch{}return 0});t=(await Promise.all(i)).reduce((n,o)=>n+o,0)}catch{}return t}async function Sm(e,t){let s={},i={global:0,project:0},r={},n=0,o=0,a=e.map(async f=>{s[f.provider]=(s[f.provider]||0)+1,i[f.scope]++,n+=rt(f),o+=es(f);let d=await ex(f.path);return r[f.path]=d,d}),u=(await Promise.all(a)).reduce((f,d)=>f+d,0);return{totalSkills:e.length,byProvider:s,byScope:i,totalDiskBytes:u,perSkillDiskBytes:r,duplicateGroups:t.duplicateGroups.length,duplicateInstances:t.totalDuplicateInstances,totalResidentTokens:n,totalBodyTokens:o}}function tx(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function zt(e,t,s=20){let i=Math.round(e/t*s),r=s-i;return l.green("#".repeat(i))+l.dim("-".repeat(r))}var km={claude:"Claude Code",codex:"Codex",openclaw:"OpenClaw",agents:"Agents"};function $m(e){let t=[];t.push(""),t.push(l.blueBold(" Skill Statistics")),t.push(l.dim(" "+"-".repeat(20))),t.push(""),t.push(` ${l.bold("Total:")} ${l.cyan(String(e.totalSkills))} skills`),t.push(` ${l.bold("Disk:")} ${l.cyan(tx(e.totalDiskBytes))}`),t.push(` ${l.bold("Resident:")} ${l.cyan(J(e.totalResidentTokens))} ${l.dim("(every message)")}`),t.push(` ${l.bold("Bodies:")} ${l.cyan(J(e.totalBodyTokens))} ${l.dim("(only when a skill fires)")}`),t.push(l.dim(` Run ${l.bold("asm stats --tokens")} for the attention budget`)),t.push(""),t.push(l.bold(" By Tool"));let s=Object.entries(e.byProvider).sort((c,u)=>u[1]-c[1]),i=Math.max(...s.map(([,c])=>c)),r=Math.max(...s.map(([c])=>(km[c]||c).length));for(let[c,u]of s){let f=km[c]||c,d=pn(c,f.padEnd(r)),p=String(u).padStart(4);t.push(` ${d} ${p} ${zt(u,i)}`)}t.push(""),t.push(l.bold(" By Scope"));let n=Math.max(e.byScope.global,e.byScope.project),o=String(e.byScope.global).padStart(4),a=String(e.byScope.project).padStart(4);return t.push(` ${"global ".padEnd(r)} ${o} ${zt(e.byScope.global,n)}`),t.push(` ${"project".padEnd(r)} ${a} ${zt(e.byScope.project,n)}`),t.push(""),t.push(l.bold(" Duplicates")),e.duplicateGroups>0?(t.push(` ${l.yellow(`${e.duplicateGroups} group(s), ${e.duplicateInstances} total instance(s)`)}`),t.push(l.dim(` Run ${l.bold("asm audit")} to review`))):t.push(` ${l.green("None")}`),t.push(""),t.join(`
485
- `)}var sx=10;function kl(e){if(e.length===0)return 0;let t=[...e].sort((i,r)=>i-r),s=Math.floor(t.length/2);return t.length%2===1?t[s]:Math.round((t[s-1]+t[s])/2)}function vm(e,t,s,i,r){let n=e.get(t);n||(n={key:t,label:s,skills:0,residentTokens:0,bodyTokens:0},e.set(t,n)),n.skills++,n.residentTokens+=i,n.bodyTokens+=r}function xm(e,t=sx){let s=new Map,i=new Map,r=[],n=0,o=0;for(let f of e){let d=rt(f),p=es(f);n+=d,o+=p,vm(s,f.provider,f.providerLabel||f.provider,d,p),vm(i,f.scope,f.scope,d,p),r.push({name:f.name,dirName:f.dirName,provider:f.provider,providerLabel:f.providerLabel||f.provider,scope:f.scope,path:f.path,residentTokens:d,bodyTokens:p})}let a=[...r].sort((f,d)=>d.residentTokens-f.residentTokens||f.name.localeCompare(d.name)),c=t>0?t:a.length,u=a.slice(0,c);return{totalSkills:e.length,totalResidentTokens:n,totalBodyTokens:o,medianResidentTokens:kl(r.map(f=>f.residentTokens)),byProvider:[...s.values()].sort((f,d)=>d.residentTokens-f.residentTokens||d.skills-f.skills),byScope:[...i.values()].sort((f,d)=>d.residentTokens-f.residentTokens),heaviestResident:u,heaviestResidentTotal:r.length,heaviestResidentTruncated:u.length<r.length}}function Em(e){let t=[];if(t.push(""),t.push(l.blueBold(" Attention Budget")),t.push(l.dim(" "+"-".repeat(40))),t.push(""),t.push(l.dim(` Resident = frontmatter descriptions, paid on every message.
368
+ ${i.bold("Examples:")}
369
+ asm uninstall code-review ${i.dim("Remove with confirmation")}
370
+ asm uninstall code-review -y ${i.dim("Remove without confirmation")}
371
+ asm uninstall code-review -s project ${i.dim("Remove project copy only")}
372
+ asm uninstall code-review -p claude ${i.dim("Remove from Claude only")}`)}async function Ll(e){if(e.flags.help){uf();return}let t=e.subcommand;t||(w("Missing required argument: <skill-name>"),console.error('Run "asm uninstall --help" for usage.'),process.exit(2));let r=await O(),s=await V(r,e.flags.scope),o={};e.flags.provider&&(o.providerFilter=e.flags.provider),e.flags.scope&&e.flags.scope!=="both"&&(o.scopeFilter=e.flags.scope);let n=Un(t,s,r,o),a=await Vn(n);a.length===0&&(w(`Skill "${t}" not found or nothing to remove.`),process.exit(1));let l=s.filter(m=>m.dirName===t),c=o.providerFilter,d=null;c&&(d=Bn(n,l,c)),console.error(i.bold("Removal plan:")),console.error(` ${i.dim("Scope:")} ${o.scopeFilter||"both"}`),c&&(console.error(` ${i.dim("Tool:")} ${c}`),d?.needed&&console.error(` ${i.yellow("\u26A0 Real folder relocation:")} ${d.fromPath} \u2192 ${d.toPath} (${d.toProvider})`)),console.error("");for(let m of a)console.error(` ${i.red("\u2022")} ${Le(m)}`);if(!e.flags.yes){process.stdin.isTTY||(w("Cannot prompt for confirmation in non-interactive mode. Use --yes to skip."),process.exit(2)),process.stderr.write(`
373
+ ${i.bold("Proceed with removal?")} [y/N] `);let m=await G();m.toLowerCase()!=="y"&&m.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let u;try{u=await Sr(n,void 0,d?.needed?d:void 0)}catch(m){let g=Array.isArray(m?.log)?m.log:[];for(let h of g)console.error(h);w(m?.message||"Uninstall failed."),process.exit(1)}for(let m of u)console.error(m);let p=new Set(n.directories.map(m=>Cl(m.path))),f=l.filter(m=>!p.has(Cl(m.originalPath)));try{c&&f.length>0?d?.needed&&!d.repointOnly&&await Fn(t,d.toProvider):await Mn(t)}catch{}console.error(i.green(`
374
+ Done.`))}import{realpath as Ff}from"fs/promises";import{resolve as Gl,sep as Hl}from"path";import{readdir as pf,stat as mf}from"fs/promises";import{join as ff}from"path";async function gf(e){let t=0;try{let s=(await pf(e,{recursive:!0})).map(async n=>{try{let a=await mf(ff(e,n));if(a.isFile())return a.size}catch{}return 0});t=(await Promise.all(s)).reduce((n,a)=>n+a,0)}catch{}return t}async function Nl(e,t){let r={},s={global:0,project:0},o={},n=0,a=0,l=e.map(async u=>{r[u.provider]=(r[u.provider]||0)+1,s[u.scope]++,n+=Me(u),a+=Pt(u);let p=await gf(u.path);return o[u.path]=p,p}),d=(await Promise.all(l)).reduce((u,p)=>u+p,0);return{totalSkills:e.length,byProvider:r,byScope:s,totalDiskBytes:d,perSkillDiskBytes:o,duplicateGroups:t.duplicateGroups.length,duplicateInstances:t.totalDuplicateInstances,totalResidentTokens:n,totalBodyTokens:a}}function hf(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function vt(e,t,r=20){let s=Math.round(e/t*r),o=r-s;return i.green("#".repeat(s))+i.dim("-".repeat(o))}var Al={claude:"Claude Code",codex:"Codex",openclaw:"OpenClaw",agents:"Agents"};function Ol(e){let t=[];t.push(""),t.push(i.blueBold(" Skill Statistics")),t.push(i.dim(" "+"-".repeat(20))),t.push(""),t.push(` ${i.bold("Total:")} ${i.cyan(String(e.totalSkills))} skills`),t.push(` ${i.bold("Disk:")} ${i.cyan(hf(e.totalDiskBytes))}`),t.push(` ${i.bold("Resident:")} ${i.cyan(H(e.totalResidentTokens))} ${i.dim("(every message)")}`),t.push(` ${i.bold("Bodies:")} ${i.cyan(H(e.totalBodyTokens))} ${i.dim("(only when a skill fires)")}`),t.push(i.dim(` Run ${i.bold("asm stats --tokens")} for the attention budget`)),t.push(""),t.push(i.bold(" By Tool"));let r=Object.entries(e.byProvider).sort((c,d)=>d[1]-c[1]),s=Math.max(...r.map(([,c])=>c)),o=Math.max(...r.map(([c])=>(Al[c]||c).length));for(let[c,d]of r){let u=Al[c]||c,p=bs(c,u.padEnd(o)),f=String(d).padStart(4);t.push(` ${p} ${f} ${vt(d,s)}`)}t.push(""),t.push(i.bold(" By Scope"));let n=Math.max(e.byScope.global,e.byScope.project),a=String(e.byScope.global).padStart(4),l=String(e.byScope.project).padStart(4);return t.push(` ${"global ".padEnd(o)} ${a} ${vt(e.byScope.global,n)}`),t.push(` ${"project".padEnd(o)} ${l} ${vt(e.byScope.project,n)}`),t.push(""),t.push(i.bold(" Duplicates")),e.duplicateGroups>0?(t.push(` ${i.yellow(`${e.duplicateGroups} group(s), ${e.duplicateInstances} total instance(s)`)}`),t.push(i.dim(` Run ${i.bold("asm audit")} to review`))):t.push(` ${i.green("None")}`),t.push(""),t.join(`
375
+ `)}var yf=10;function Zo(e){if(e.length===0)return 0;let t=[...e].sort((s,o)=>s-o),r=Math.floor(t.length/2);return t.length%2===1?t[r]:Math.round((t[r-1]+t[r])/2)}function Tl(e,t,r,s,o){let n=e.get(t);n||(n={key:t,label:r,skills:0,residentTokens:0,bodyTokens:0},e.set(t,n)),n.skills++,n.residentTokens+=s,n.bodyTokens+=o}function Dl(e,t=yf){let r=new Map,s=new Map,o=[],n=0,a=0;for(let u of e){let p=Me(u),f=Pt(u);n+=p,a+=f,Tl(r,u.provider,u.providerLabel||u.provider,p,f),Tl(s,u.scope,u.scope,p,f),o.push({name:u.name,dirName:u.dirName,provider:u.provider,providerLabel:u.providerLabel||u.provider,scope:u.scope,path:u.path,residentTokens:p,bodyTokens:f})}let l=[...o].sort((u,p)=>p.residentTokens-u.residentTokens||u.name.localeCompare(p.name)),c=t>0?t:l.length,d=l.slice(0,c);return{totalSkills:e.length,totalResidentTokens:n,totalBodyTokens:a,medianResidentTokens:Zo(o.map(u=>u.residentTokens)),byProvider:[...r.values()].sort((u,p)=>p.residentTokens-u.residentTokens||p.skills-u.skills),byScope:[...s.values()].sort((u,p)=>p.residentTokens-u.residentTokens),heaviestResident:d,heaviestResidentTotal:o.length,heaviestResidentTruncated:d.length<o.length}}function Ml(e){let t=[];if(t.push(""),t.push(i.blueBold(" Attention Budget")),t.push(i.dim(" "+"-".repeat(40))),t.push(""),t.push(i.dim(` Resident = frontmatter descriptions, paid on every message.
486
376
  Bodies = full SKILL.md, paid only when a skill fires.`)),t.push(""),e.totalSkills===0)return t.push(" No installed skills."),t.push(""),t.join(`
487
- `);let s=[...e.byProvider.map(a=>["provider",a])],i=Math.max(8,...s.map(([,a])=>a.label.length),5),r=e.byProvider.map(a=>J(a.residentTokens)),n=Math.max(...r.map(a=>a.length),J(e.totalResidentTokens).length),o=" "+"Tool".padEnd(i)+" "+"Skills".padStart(6)+" "+"Resident".padStart(n)+" Bodies";t.push(l.bold(o));for(let a of e.byProvider)t.push(" "+pn(a.key,a.label.padEnd(i))+" "+String(a.skills).padStart(6)+" "+l.cyan(J(a.residentTokens).padStart(n))+" "+l.dim(J(a.bodyTokens)));t.push(l.dim(" "+"-".repeat(i+n+22))),t.push(" "+l.bold("Total".padEnd(i))+" "+String(e.totalSkills).padStart(6)+" "+l.cyan(J(e.totalResidentTokens).padStart(n))+" "+l.dim(J(e.totalBodyTokens))),t.push(""),t.push(l.bold(" By Scope"));for(let a of e.byScope)t.push(" "+a.label.padEnd(i)+" "+String(a.skills).padStart(6)+" "+l.cyan(J(a.residentTokens).padStart(n))+" "+l.dim(J(a.bodyTokens)));if(t.push(""),e.heaviestResident.length>0){t.push(l.bold(" Heaviest resident descriptions"));let a=Math.max(...e.heaviestResident.map(f=>f.name.length)),c=Math.max(...e.heaviestResident.map(f=>J(f.residentTokens).length));for(let f of e.heaviestResident)t.push(" "+f.name.padEnd(a)+" "+l.cyan(J(f.residentTokens).padStart(c))+" "+l.dim(`(${f.provider}, ${f.scope})`));let u=e.heaviestResidentTotal-e.heaviestResident.length;u>0&&t.push(l.dim(` \u2026 ${u} more not shown \u2014 use --json for the full list`)),t.push(""),t.push(l.dim(` Median resident cost: ${J(e.medianResidentTokens)}`)),t.push(l.dim(` Run ${l.bold("asm audit residency")} for demotion advice`)),t.push("")}return t.join(`
488
- `)}function Pm(e){let t=[];for(let s of e){let i={},r=0,n=0,o=0,a=0;for(let u of s.skills){let f=vl(u.name,u.description);for(let d of f)i[d]=(i[d]||0)+1;u.verified&&r++,n+=u.tokenCount??0,u.evalSummary&&(o+=u.evalSummary.overallScore,a++)}let c=a>0?Math.round(o/a):void 0;t.push({owner:s.owner,repo:s.repo,repoUrl:s.repoUrl,skillCount:s.skills.length,categories:i,verifiedCount:r,totalTokens:n,avgEvalScore:c})}return t.sort((s,i)=>i.skillCount-s.skillCount)}function Cm(e){let t=new Map;for(let i of e){let r=t.get(i.owner);r||(r={owner:i.owner,totalSkills:0,repos:[],categories:{},verifiedCount:0,totalTokens:0,topSkills:[]},t.set(i.owner,r)),r.repos.push(`${i.owner}/${i.repo}`);for(let n of i.skills){r.totalSkills++;let o=vl(n.name,n.description);for(let a of o)r.categories[a]=(r.categories[a]||0)+1;n.verified&&r.verifiedCount++,r.totalTokens+=n.tokenCount??0,r.topSkills.push({name:n.name,repo:`${i.owner}/${i.repo}`})}}let s=[];for(let[i,r]of t){let n=r.topSkills.sort((o,a)=>a.name.localeCompare(o.name)).slice(0,10);s.push({...r,topSkills:n})}return s.sort((i,r)=>r.totalSkills-i.totalSkills)}function Im(e){let t=0,s=0,i=0,r={},n=new Set;for(let o of e){n.add(o.owner),t+=o.skills.length;for(let a of o.skills){a.verified&&s++,i+=a.tokenCount??0;let c=vl(a.name,a.description);for(let u of c)r[u]=(r[u]||0)+1}}return{totalRepos:e.length,totalSkills:t,totalAuthors:n.size,categoryDistribution:r,verifiedCount:s,totalTokens:i,avgTokensPerSkill:t>0?Math.round(i/t):0}}function Lm(e){let t=[];t.push(""),t.push(l.blueBold(` Repo: ${e.owner}/${e.repo}`)),t.push(l.dim(" "+"-".repeat(40))),t.push(""),t.push(` ${l.bold("Skills: ")}${l.cyan(String(e.skillCount))}`),t.push(` ${l.bold("Verified: ")}${l.cyan(String(e.verifiedCount))}`),t.push(` ${l.bold("Tokens: ")}${l.cyan(J(e.totalTokens))}`),e.avgEvalScore!==void 0&&t.push(` ${l.bold("Avg Eval: ")}${l.cyan(String(e.avgEvalScore))}`),t.push("");let s=Object.entries(e.categories).sort((i,r)=>r[1]-i[1]);if(s.length>0){t.push(l.bold(" Categories"));let i=Math.max(...s.map(([,r])=>r));for(let[r,n]of s){let o=r.padEnd(18),a=String(n).padStart(4);t.push(` ${o} ${a} ${zt(n,i,20)}`)}t.push("")}return t.push(""),t.join(`
489
- `)}function Am(e){let t=[];t.push(""),t.push(l.blueBold(` Author: ${e.owner}`)),t.push(l.dim(" "+"-".repeat(40))),t.push(""),t.push(` ${l.bold("Total Skills: ")}${l.cyan(String(e.totalSkills))}`),t.push(` ${l.bold("Repos: ")}${l.cyan(String(e.repos.length))}`),t.push(` ${l.bold("Verified: ")}${l.cyan(String(e.verifiedCount))}`),t.push(` ${l.bold("Tokens: ")}${l.cyan(J(e.totalTokens))}`),t.push("");let s=Object.entries(e.categories).sort((i,r)=>r[1]-i[1]);if(s.length>0){t.push(l.bold(" Categories"));let i=Math.max(...s.map(([,r])=>r));for(let[r,n]of s){let o=r.padEnd(18),a=String(n).padStart(4);t.push(` ${o} ${a} ${zt(n,i,20)}`)}t.push("")}if(e.topSkills.length>0){t.push(l.bold(" Top Skills"));for(let i=0;i<e.topSkills.length;i++){let r=e.topSkills[i];t.push(` ${l.dim(`${i+1}.`)} ${l.cyan(r.name)} ${l.dim(`(${r.repo})`)}`)}t.push("")}return t.push(""),t.join(`
490
- `)}function Rm(e){let t=[];t.push(""),t.push(l.blueBold(" Index Statistics")),t.push(l.dim(" "+"-".repeat(40))),t.push(""),t.push(` ${l.bold("Repos: ")}${l.cyan(String(e.totalRepos))}`),t.push(` ${l.bold("Skills: ")}${l.cyan(String(e.totalSkills))}`),t.push(` ${l.bold("Authors: ")}${l.cyan(String(e.totalAuthors))}`),t.push(` ${l.bold("Verified: ")}${l.cyan(String(e.verifiedCount))}`),t.push(` ${l.bold("Avg Tokens/Skill: ")}${l.cyan(J(e.avgTokensPerSkill))}`),t.push("");let s=Object.entries(e.categoryDistribution).sort((i,r)=>r[1]-i[1]);if(s.length>0){t.push(l.bold(" Category Distribution"));let i=Math.max(...s.map(([,r])=>r));for(let[r,n]of s){let o=r.padEnd(18),a=String(n).padStart(4);t.push(` ${o} ${a} ${zt(n,i,20)}`)}t.push("")}return t.push(""),t.join(`
491
- `)}function vl(e,t){let s=`${e??""} ${t??""}`.toLowerCase(),i=[],r={"ai-agents":["agent","llm","claude","gpt","prompt","openai","anthropic","model","skill-creator","mcp","orchestrat"],security:["security","auth","oauth","jwt","ssl","vulnerab","audit","pentest","owasp","encrypt","threat","cso"],devops:["docker","kubernetes","deploy","pipeline","terraform","ansible","github action","pre-commit","devops"],frontend:["ui","ux","css","html","react","vue","svelte","frontend","component","layout","landing page","web artifact","design system"],design:["design","visual","algorithmic art","generative art","canvas","color","logo","brand","theme","figma","typography","illustration"],backend:["api","rest","graphql","database","sql","postgres","redis","server","backend","microservice"],testing:["test","spec","e2e","unit test","coverage","mock","qa","benchmark","playwright"],coding:["code review","refactor","debug","lint","typescript","python","javascript","rust","golang","build","cli","optimizer"],writing:["write","blog","article","documentation","docs","draft","content","copy","proposal","readme","changelog"],mobile:["ios","android","mobile","xcode","swift","kotlin","flutter","app store","testflight","asc"],finance:["finance","trading","stock","crypto","payment","billing","fintech","invest","revenue"],marketing:["seo","aso","marketing","analytics","growth","conversion","affiliate","campaign","social media","reddit","twitter"],git:["git","commit","branch","pull request","pr review","merge"],productivity:["workflow","automation","task","schedule","pdf","xlsx","docx","pptx","spreadsheet","presentation"],research:["research","scholar","paper","academic","peer review","investigation"]};for(let[n,o]of Object.entries(r))for(let a of o)if(ix(s,a)){i.push(n);break}return i.length>0?i:["general"]}function ix(e,t){return t.length<=3?new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(e):e.includes(t)}var rx=new Set(["plugin","codex-plugin"]),nx=40,ox=2,ax=15,lx=3;function cx(e){let t=e.slice(0,lx).map(i=>`${i.provider}/${i.scope}`),s=e.length-t.length;return s>0?`${t.join(", ")}, +${s} more`:t.join(", ")}function ux(e,t){let s=Nm(e),i=Nm(t);return s===i?!1:i.startsWith(s.endsWith(Tm)?s:s+Tm)}function dx(){return[{id:"expensive-description",label:"Expensive residency",available:!0},{id:"redundant-activation",label:"Redundant activation",available:!0},{id:"trigger-collision",label:"Trigger collision",available:!1,reason:"needs trigger-overlap detection (issue #18)"},{id:"unused",label:"Unused",available:!1,reason:"needs skill usage statistics (issue #354)"}]}function fx(e,t){let s={command:`asm get ${e}`,hint:"read it on demand, zero residency"};if(t.length===1&&t[0].libraryLinked){let i=t[0];if(px(i.provider))return{kind:"deactivate",command:`asm deactivate ${e} --provider ${i.provider} --scope ${i.scope}`,hint:"keep it in the library, activate when needed",reference:s}}return{kind:"disable",command:`asm disable ${e}`,hint:t.length>1?"reversible with asm enable; disables every ASM-managed copy of this skill name":"reversible with asm enable"}}function px(e){return vi().providers.some(t=>t.name===e)}function Om(e,t={}){let s=t.librarySkillsDir??"",i=t.limit??0,r=e.map(p=>rt(p)),n=r.reduce((p,m)=>p+m,0),o=kl(r),a=e.filter(p=>!rx.has(p.provider)),c=e.length-a.length,u=new Map;for(let p of a){let m=p.dirName||p.name,g=u.get(m);g?g.push(p):u.set(m,[p])}let f=Math.max(nx,o*ox),d=[];for(let[p,m]of u){let g=m[0],h=rt(g),y=m.reduce((v,x)=>v+rt(x),0),b=m.reduce((v,x)=>v+es(x),0),k=m.map(v=>({provider:v.provider,providerLabel:v.providerLabel||v.provider,scope:v.scope,path:v.path,libraryLinked:v.isSymlink&&s.length>0&&ux(s,v.realPath||v.path)})),w=[];if(h>=f&&h>0){let v=o>0?`${(h/o).toFixed(1)}x the median description`:"well above the rest of the installed set";w.push({id:"expensive-description",detail:`${J(h)} resident \xB7 ${v}`})}k.length>1&&w.push({id:"redundant-activation",detail:`resident in ${k.length} places (${cx(k)}) \xB7 each pays ${J(h)}`}),w.length!==0&&d.push({name:g.name,dirName:p,residentTokens:h,totalResidentTokens:y,bodyTokens:b,score:y,instances:k,reasons:w,action:fx(p,k)})}return d.sort((p,m)=>m.score-p.score||p.name.localeCompare(m.name)),{scannedAt:new Date().toISOString(),totalSkills:e.length,totalResidentTokens:n,medianResidentTokens:o,unmanagedSkills:c,candidates:i>0?d.slice(0,i):d,signals:dx()}}function Mm(e,t=ax){let s=[];if(s.push(""),s.push(l.blueBold(" Residency Audit")),s.push(l.dim(" "+"-".repeat(40))),s.push(""),e.totalSkills===0)return s.push(" No installed skills."),s.push(""),s.join(`
492
- `);if(s.push(` ${l.bold("Resident total:")} ${l.cyan(J(e.totalResidentTokens))} `+l.dim(`across ${e.totalSkills} skill(s), every message`)),s.push(` ${l.bold("Median skill:")} ${l.cyan(J(e.medianResidentTokens))}`),s.push(""),e.candidates.length===0)s.push(` ${l.green("No demotion candidates.")}`),s.push("");else{let r=t>0?e.candidates.slice(0,t):e.candidates;s.push(l.bold(` Demotion candidates (${e.candidates.length})`)),s.push(l.dim(" Highest resident cost first.")),s.push("");for(let o of r){s.push(` ${l.cyan(o.name)} `+l.dim(`${J(o.totalResidentTokens)} total`));for(let a of o.reasons)s.push(l.dim(` ${a.detail}`));s.push(` ${l.yellow("\u2192")} ${l.bold(o.action.command)}`+l.dim(` (${o.action.hint})`)),o.action.reference&&s.push(` ${l.yellow("\u2192")} ${l.bold(o.action.reference.command)}`+l.dim(` (${o.action.reference.hint})`)),s.push("")}let n=e.candidates.length-r.length;n>0&&(s.push(l.dim(` \u2026 ${n} more not shown \u2014 use --json for the full list`)),s.push(""))}e.unmanagedSkills>0&&(s.push(l.dim(` ${e.unmanagedSkills} plugin-provided skill(s) are counted but not ASM-managed \u2014 no ASM command demotes them.`)),s.push(""));let i=e.signals.filter(r=>!r.available);if(i.length>0){s.push(l.dim(" Signals not yet available:"));for(let r of i)s.push(l.dim(` ${r.label} \u2014 ${r.reason}`));s.push("")}return s.push(l.dim(" Nothing was changed. Run a suggested command to demote.")),s.push(""),s.join(`
493
- `)}var mx=.35,_m=.55,jm=new Set(["the","a","an","and","or","but","nor","for","to","of","in","on","at","by","with","from","into","onto","about","over","under","across","between","through","during","before","after","above","below","up","down","out","off","again","as","is","are","was","were","be","been","being","am","do","does","did","doing","have","has","had","will","would","shall","should","can","could","may","might","must","not","no","yes","if","then","than","so","such","that","this","these","those","it","its","they","them","their","there","here","when","while","where","which","who","whom","whose","what","why","how","all","any","both","each","few","more","most","other","others","some","only","own","same","too","very","just","also","you","your","yours","we","our","ours","us","skill","skills","agent","agents","ai","claude","code","coding","llm","llms","assistant","assistants","use","uses","using","used","user","users","provide","provides","provided","providing","help","helps","helping","support","supports","supported","supporting","enable","enables","enabling","allow","allows","allowing","lets","make","makes","making","get","gets","getting","give","gives","work","works","working","tool","tools","based","via","per","new","like","want","needs","need","including","include","includes","various","multiple","different","specific","without","within"]);function hx(e){let t=new Set;for(let s of ge(e))jm.has(s)||t.add(s);return t}function gx(e){let t=new Set;for(let s of ge(e))jm.has(s)||t.add(s);return t}function yx(e){let t=e.length,s=new Map;for(let r of e)for(let n of r)s.set(n,(s.get(n)??0)+1);let i=new Map;for(let[r,n]of s)i.set(r,1+Math.log(t/n));return i}function Dm(e,t,s){let i=0,r=0,n=0;for(let a of e)r+=s.get(a)??1,t.has(a)&&(i+=s.get(a)??1);for(let a of t)n+=s.get(a)??1;let o=Math.min(r,n);return o===0?0:i/o}function bx(e,t,s,i,r){return .6*Dm(e,s,r)+.4*Dm(t,i,r)}function wx(e,t,s,i,r){let n=[...e].filter(u=>t.has(u)).sort((u,f)=>(s.get(f)??1)-(s.get(u)??1)||u.localeCompare(f));if(n.length===0)return r?"Similar names \u2014 descriptions share no distinctive terms":"Names and descriptions are near-identical";let o=n.slice(0,3).join(", "),a=n.length>3?` +${n.length-3} more`:"";return`${i>=_m?"Very similar":"Substantially overlapping"} \u2014 shared terms: ${o}${a}`}function kx(e){let t=new Map;for(let s of e){let i=t.get(s.realPath);i?i.isSymlink&&!s.isSymlink&&t.set(s.realPath,s):t.set(s.realPath,s)}return[...t.values()]}function Fm(e){return{name:e.name,dirName:e.dirName,provider:e.provider,providerLabel:e.providerLabel||e.provider,scope:e.scope,path:e.path}}function vx(e,t){return ns(e.dirName)===ns(t.dirName)||!!e.name&&!!t.name&&ns(e.name)===ns(t.name)}function Bm(e,t=mx){let s=kx(e),i=s.map(a=>hx(a.description)),r=s.map(a=>gx(a.name)),n=yx(i),o=[];for(let a=0;a<s.length;a++)for(let c=a+1;c<s.length;c++){if(vx(s[a],s[c]))continue;let u=bx(i[a],r[a],i[c],r[c],n);if(u>=t){let f=[...r[a]].some(d=>r[c].has(d));o.push({a:Fm(s[a]),b:Fm(s[c]),score:u,highConfidence:u>=_m,reason:wx(i[a],i[c],n,u,f)})}}return o.sort((a,c)=>c.score-a.score||a.a.name.localeCompare(c.a.name)||a.b.name.localeCompare(c.b.name)),{scannedAt:new Date().toISOString(),totalSkills:e.length,comparedSkills:s.length,pairs:o,highConfidenceCount:o.filter(a=>a.highConfidence).length}}function qm(e){let t=[];if(t.push(""),t.push(l.blueBold(" Semantic Overlap Audit")),t.push(l.dim(" "+"-".repeat(40))),t.push(""),e.totalSkills===0)return t.push(" No installed skills."),t.push(""),t.join(`
494
- `);if(t.push(` ${l.bold("Compared:")} ${e.comparedSkills} distinct skill(s)`+l.dim(` (from ${e.totalSkills} installed)`)),t.push(""),e.pairs.length===0)return t.push(l.green("No overlapping skills found.")),t.push(""),t.join(`
495
- `);t.push(l.bold(` Found ${e.pairs.length} overlapping pair(s) (${e.highConfidenceCount} high confidence):`)),t.push("");for(let s of e.pairs){let i=Math.round(s.score*100);t.push(` ${l.bold(`${i}%`)} ${l.yellow(`"${s.a.name}"`)} ${l.dim("\u2194")} ${l.yellow(`"${s.b.name}"`)}`),t.push(l.dim(` ${s.a.providerLabel} (${s.a.scope}) ${Ue(s.a.path)}`)),t.push(l.dim(` ${s.b.providerLabel} (${s.b.scope}) ${Ue(s.b.path)}`)),s.highConfidence&&t.push(l.red(" \u26A0 likely redundant \u2014 review before keeping both")),t.push(l.dim(` ${s.reason}`)),t.push("")}return t.push(l.dim(" Nothing was changed. Review each pair before removing either skill.")),t.push(""),t.join(`
496
- `)}function Um(e){return JSON.stringify(e,null,2)}function $x(){console.log(`${l.bold("Usage:")} asm audit [subcommand] [options]
377
+ `);let r=[...e.byProvider.map(l=>["provider",l])],s=Math.max(8,...r.map(([,l])=>l.label.length),5),o=e.byProvider.map(l=>H(l.residentTokens)),n=Math.max(...o.map(l=>l.length),H(e.totalResidentTokens).length),a=" "+"Tool".padEnd(s)+" "+"Skills".padStart(6)+" "+"Resident".padStart(n)+" Bodies";t.push(i.bold(a));for(let l of e.byProvider)t.push(" "+bs(l.key,l.label.padEnd(s))+" "+String(l.skills).padStart(6)+" "+i.cyan(H(l.residentTokens).padStart(n))+" "+i.dim(H(l.bodyTokens)));t.push(i.dim(" "+"-".repeat(s+n+22))),t.push(" "+i.bold("Total".padEnd(s))+" "+String(e.totalSkills).padStart(6)+" "+i.cyan(H(e.totalResidentTokens).padStart(n))+" "+i.dim(H(e.totalBodyTokens))),t.push(""),t.push(i.bold(" By Scope"));for(let l of e.byScope)t.push(" "+l.label.padEnd(s)+" "+String(l.skills).padStart(6)+" "+i.cyan(H(l.residentTokens).padStart(n))+" "+i.dim(H(l.bodyTokens)));if(t.push(""),e.heaviestResident.length>0){t.push(i.bold(" Heaviest resident descriptions"));let l=Math.max(...e.heaviestResident.map(u=>u.name.length)),c=Math.max(...e.heaviestResident.map(u=>H(u.residentTokens).length));for(let u of e.heaviestResident)t.push(" "+u.name.padEnd(l)+" "+i.cyan(H(u.residentTokens).padStart(c))+" "+i.dim(`(${u.provider}, ${u.scope})`));let d=e.heaviestResidentTotal-e.heaviestResident.length;d>0&&t.push(i.dim(` \u2026 ${d} more not shown \u2014 use --json for the full list`)),t.push(""),t.push(i.dim(` Median resident cost: ${H(e.medianResidentTokens)}`)),t.push(i.dim(` Run ${i.bold("asm audit residency")} for demotion advice`)),t.push("")}return t.join(`
378
+ `)}function Fl(e){let t=[];for(let r of e){let s={},o=0,n=0,a=0,l=0;for(let d of r.skills){let u=Xo(d.name,d.description);for(let p of u)s[p]=(s[p]||0)+1;d.verified&&o++,n+=d.tokenCount??0,d.evalSummary&&(a+=d.evalSummary.overallScore,l++)}let c=l>0?Math.round(a/l):void 0;t.push({owner:r.owner,repo:r.repo,repoUrl:r.repoUrl,skillCount:r.skills.length,categories:s,verifiedCount:o,totalTokens:n,avgEvalScore:c})}return t.sort((r,s)=>s.skillCount-r.skillCount)}function jl(e){let t=new Map;for(let s of e){let o=t.get(s.owner);o||(o={owner:s.owner,totalSkills:0,repos:[],categories:{},verifiedCount:0,totalTokens:0,topSkills:[]},t.set(s.owner,o)),o.repos.push(`${s.owner}/${s.repo}`);for(let n of s.skills){o.totalSkills++;let a=Xo(n.name,n.description);for(let l of a)o.categories[l]=(o.categories[l]||0)+1;n.verified&&o.verifiedCount++,o.totalTokens+=n.tokenCount??0,o.topSkills.push({name:n.name,repo:`${s.owner}/${s.repo}`})}}let r=[];for(let[s,o]of t){let n=o.topSkills.sort((a,l)=>l.name.localeCompare(a.name)).slice(0,10);r.push({...o,topSkills:n})}return r.sort((s,o)=>o.totalSkills-s.totalSkills)}function _l(e){let t=0,r=0,s=0,o={},n=new Set;for(let a of e){n.add(a.owner),t+=a.skills.length;for(let l of a.skills){l.verified&&r++,s+=l.tokenCount??0;let c=Xo(l.name,l.description);for(let d of c)o[d]=(o[d]||0)+1}}return{totalRepos:e.length,totalSkills:t,totalAuthors:n.size,categoryDistribution:o,verifiedCount:r,totalTokens:s,avgTokensPerSkill:t>0?Math.round(s/t):0}}function Ul(e){let t=[];t.push(""),t.push(i.blueBold(` Repo: ${e.owner}/${e.repo}`)),t.push(i.dim(" "+"-".repeat(40))),t.push(""),t.push(` ${i.bold("Skills: ")}${i.cyan(String(e.skillCount))}`),t.push(` ${i.bold("Verified: ")}${i.cyan(String(e.verifiedCount))}`),t.push(` ${i.bold("Tokens: ")}${i.cyan(H(e.totalTokens))}`),e.avgEvalScore!==void 0&&t.push(` ${i.bold("Avg Eval: ")}${i.cyan(String(e.avgEvalScore))}`),t.push("");let r=Object.entries(e.categories).sort((s,o)=>o[1]-s[1]);if(r.length>0){t.push(i.bold(" Categories"));let s=Math.max(...r.map(([,o])=>o));for(let[o,n]of r){let a=o.padEnd(18),l=String(n).padStart(4);t.push(` ${a} ${l} ${vt(n,s,20)}`)}t.push("")}return t.push(""),t.join(`
379
+ `)}function Bl(e){let t=[];t.push(""),t.push(i.blueBold(` Author: ${e.owner}`)),t.push(i.dim(" "+"-".repeat(40))),t.push(""),t.push(` ${i.bold("Total Skills: ")}${i.cyan(String(e.totalSkills))}`),t.push(` ${i.bold("Repos: ")}${i.cyan(String(e.repos.length))}`),t.push(` ${i.bold("Verified: ")}${i.cyan(String(e.verifiedCount))}`),t.push(` ${i.bold("Tokens: ")}${i.cyan(H(e.totalTokens))}`),t.push("");let r=Object.entries(e.categories).sort((s,o)=>o[1]-s[1]);if(r.length>0){t.push(i.bold(" Categories"));let s=Math.max(...r.map(([,o])=>o));for(let[o,n]of r){let a=o.padEnd(18),l=String(n).padStart(4);t.push(` ${a} ${l} ${vt(n,s,20)}`)}t.push("")}if(e.topSkills.length>0){t.push(i.bold(" Top Skills"));for(let s=0;s<e.topSkills.length;s++){let o=e.topSkills[s];t.push(` ${i.dim(`${s+1}.`)} ${i.cyan(o.name)} ${i.dim(`(${o.repo})`)}`)}t.push("")}return t.push(""),t.join(`
380
+ `)}function Vl(e){let t=[];t.push(""),t.push(i.blueBold(" Index Statistics")),t.push(i.dim(" "+"-".repeat(40))),t.push(""),t.push(` ${i.bold("Repos: ")}${i.cyan(String(e.totalRepos))}`),t.push(` ${i.bold("Skills: ")}${i.cyan(String(e.totalSkills))}`),t.push(` ${i.bold("Authors: ")}${i.cyan(String(e.totalAuthors))}`),t.push(` ${i.bold("Verified: ")}${i.cyan(String(e.verifiedCount))}`),t.push(` ${i.bold("Avg Tokens/Skill: ")}${i.cyan(H(e.avgTokensPerSkill))}`),t.push("");let r=Object.entries(e.categoryDistribution).sort((s,o)=>o[1]-s[1]);if(r.length>0){t.push(i.bold(" Category Distribution"));let s=Math.max(...r.map(([,o])=>o));for(let[o,n]of r){let a=o.padEnd(18),l=String(n).padStart(4);t.push(` ${a} ${l} ${vt(n,s,20)}`)}t.push("")}return t.push(""),t.join(`
381
+ `)}function Xo(e,t){let r=`${e??""} ${t??""}`.toLowerCase(),s=[],o={"ai-agents":["agent","llm","claude","gpt","prompt","openai","anthropic","model","skill-creator","mcp","orchestrat"],security:["security","auth","oauth","jwt","ssl","vulnerab","audit","pentest","owasp","encrypt","threat","cso"],devops:["docker","kubernetes","deploy","pipeline","terraform","ansible","github action","pre-commit","devops"],frontend:["ui","ux","css","html","react","vue","svelte","frontend","component","layout","landing page","web artifact","design system"],design:["design","visual","algorithmic art","generative art","canvas","color","logo","brand","theme","figma","typography","illustration"],backend:["api","rest","graphql","database","sql","postgres","redis","server","backend","microservice"],testing:["test","spec","e2e","unit test","coverage","mock","qa","benchmark","playwright"],coding:["code review","refactor","debug","lint","typescript","python","javascript","rust","golang","build","cli","optimizer"],writing:["write","blog","article","documentation","docs","draft","content","copy","proposal","readme","changelog"],mobile:["ios","android","mobile","xcode","swift","kotlin","flutter","app store","testflight","asc"],finance:["finance","trading","stock","crypto","payment","billing","fintech","invest","revenue"],marketing:["seo","aso","marketing","analytics","growth","conversion","affiliate","campaign","social media","reddit","twitter"],git:["git","commit","branch","pull request","pr review","merge"],productivity:["workflow","automation","task","schedule","pdf","xlsx","docx","pptx","spreadsheet","presentation"],research:["research","scholar","paper","academic","peer review","investigation"]};for(let[n,a]of Object.entries(o))for(let l of a)if(bf(r,l)){s.push(n);break}return s.length>0?s:["general"]}function bf(e,t){return t.length<=3?new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(e):e.includes(t)}var wf=new Set(["plugin","codex-plugin"]),kf=40,vf=2,Sf=15,$f=3;function xf(e){let t=e.slice(0,$f).map(s=>`${s.provider}/${s.scope}`),r=e.length-t.length;return r>0?`${t.join(", ")}, +${r} more`:t.join(", ")}function Pf(e,t){let r=Gl(e),s=Gl(t);return r===s?!1:s.startsWith(r.endsWith(Hl)?r:r+Hl)}function Rf(){return[{id:"expensive-description",label:"Expensive residency",available:!0},{id:"redundant-activation",label:"Redundant activation",available:!0},{id:"trigger-collision",label:"Trigger collision",available:!1,reason:"needs trigger-overlap detection (issue #18)"},{id:"unused",label:"Unused",available:!1,reason:"needs skill usage statistics (issue #354)"}]}function Ef(e,t){let r={command:`asm get ${e}`,hint:"read it on demand, zero residency"};if(t.length===1&&t[0].libraryLinked){let s=t[0];if(If(s.provider))return{kind:"deactivate",command:`asm deactivate ${e} --provider ${s.provider} --scope ${s.scope}`,hint:"keep it in the library, activate when needed",reference:r}}return{kind:"disable",command:`asm disable ${e}`,hint:t.length>1?"reversible with asm enable; disables every ASM-managed copy of this skill name":"reversible with asm enable"}}function If(e){return wr().providers.some(t=>t.name===e)}function ql(e,t={}){let r=t.librarySkillsDir??"",s=t.limit??0,o=e.map(f=>Me(f)),n=o.reduce((f,m)=>f+m,0),a=Zo(o),l=e.filter(f=>!wf.has(f.provider)),c=e.length-l.length,d=new Map;for(let f of l){let m=f.dirName||f.name,g=d.get(m);g?g.push(f):d.set(m,[f])}let u=Math.max(kf,a*vf),p=[];for(let[f,m]of d){let g=m[0],h=Me(g),y=m.reduce((S,C)=>S+Me(C),0),b=m.reduce((S,C)=>S+Pt(C),0),$=m.map(S=>({provider:S.provider,providerLabel:S.providerLabel||S.provider,scope:S.scope,path:S.path,libraryLinked:S.isSymlink&&r.length>0&&Pf(r,S.realPath||S.path)})),v=[];if(h>=u&&h>0){let S=a>0?`${(h/a).toFixed(1)}x the median description`:"well above the rest of the installed set";v.push({id:"expensive-description",detail:`${H(h)} resident \xB7 ${S}`})}$.length>1&&v.push({id:"redundant-activation",detail:`resident in ${$.length} places (${xf($)}) \xB7 each pays ${H(h)}`}),v.length!==0&&p.push({name:g.name,dirName:f,residentTokens:h,totalResidentTokens:y,bodyTokens:b,score:y,instances:$,reasons:v,action:Ef(f,$)})}return p.sort((f,m)=>m.score-f.score||f.name.localeCompare(m.name)),{scannedAt:new Date().toISOString(),totalSkills:e.length,totalResidentTokens:n,medianResidentTokens:a,unmanagedSkills:c,candidates:s>0?p.slice(0,s):p,signals:Rf()}}function Wl(e,t=Sf){let r=[];if(r.push(""),r.push(i.blueBold(" Residency Audit")),r.push(i.dim(" "+"-".repeat(40))),r.push(""),e.totalSkills===0)return r.push(" No installed skills."),r.push(""),r.join(`
382
+ `);if(r.push(` ${i.bold("Resident total:")} ${i.cyan(H(e.totalResidentTokens))} `+i.dim(`across ${e.totalSkills} skill(s), every message`)),r.push(` ${i.bold("Median skill:")} ${i.cyan(H(e.medianResidentTokens))}`),r.push(""),e.candidates.length===0)r.push(` ${i.green("No demotion candidates.")}`),r.push("");else{let o=t>0?e.candidates.slice(0,t):e.candidates;r.push(i.bold(` Demotion candidates (${e.candidates.length})`)),r.push(i.dim(" Highest resident cost first.")),r.push("");for(let a of o){r.push(` ${i.cyan(a.name)} `+i.dim(`${H(a.totalResidentTokens)} total`));for(let l of a.reasons)r.push(i.dim(` ${l.detail}`));r.push(` ${i.yellow("\u2192")} ${i.bold(a.action.command)}`+i.dim(` (${a.action.hint})`)),a.action.reference&&r.push(` ${i.yellow("\u2192")} ${i.bold(a.action.reference.command)}`+i.dim(` (${a.action.reference.hint})`)),r.push("")}let n=e.candidates.length-o.length;n>0&&(r.push(i.dim(` \u2026 ${n} more not shown \u2014 use --json for the full list`)),r.push(""))}e.unmanagedSkills>0&&(r.push(i.dim(` ${e.unmanagedSkills} plugin-provided skill(s) are counted but not ASM-managed \u2014 no ASM command demotes them.`)),r.push(""));let s=e.signals.filter(o=>!o.available);if(s.length>0){r.push(i.dim(" Signals not yet available:"));for(let o of s)r.push(i.dim(` ${o.label} \u2014 ${o.reason}`));r.push("")}return r.push(i.dim(" Nothing was changed. Run a suggested command to demote.")),r.push(""),r.join(`
383
+ `)}var Cf=.35,zl=.55,Yl=new Set(["the","a","an","and","or","but","nor","for","to","of","in","on","at","by","with","from","into","onto","about","over","under","across","between","through","during","before","after","above","below","up","down","out","off","again","as","is","are","was","were","be","been","being","am","do","does","did","doing","have","has","had","will","would","shall","should","can","could","may","might","must","not","no","yes","if","then","than","so","such","that","this","these","those","it","its","they","them","their","there","here","when","while","where","which","who","whom","whose","what","why","how","all","any","both","each","few","more","most","other","others","some","only","own","same","too","very","just","also","you","your","yours","we","our","ours","us","skill","skills","agent","agents","ai","claude","code","coding","llm","llms","assistant","assistants","use","uses","using","used","user","users","provide","provides","provided","providing","help","helps","helping","support","supports","supported","supporting","enable","enables","enabling","allow","allows","allowing","lets","make","makes","making","get","gets","getting","give","gives","work","works","working","tool","tools","based","via","per","new","like","want","needs","need","including","include","includes","various","multiple","different","specific","without","within"]);function Lf(e){let t=new Set;for(let r of ce(e))Yl.has(r)||t.add(r);return t}function Af(e){let t=new Set;for(let r of ce(e))Yl.has(r)||t.add(r);return t}function Tf(e){let t=e.length,r=new Map;for(let o of e)for(let n of o)r.set(n,(r.get(n)??0)+1);let s=new Map;for(let[o,n]of r)s.set(o,1+Math.log(t/n));return s}function Kl(e,t,r){let s=0,o=0,n=0;for(let l of e)o+=r.get(l)??1,t.has(l)&&(s+=r.get(l)??1);for(let l of t)n+=r.get(l)??1;let a=Math.min(o,n);return a===0?0:s/a}function Nf(e,t,r,s,o){return .6*Kl(e,r,o)+.4*Kl(t,s,o)}function Of(e,t,r,s,o){let n=[...e].filter(d=>t.has(d)).sort((d,u)=>(r.get(u)??1)-(r.get(d)??1)||d.localeCompare(u));if(n.length===0)return o?"Similar names \u2014 descriptions share no distinctive terms":"Names and descriptions are near-identical";let a=n.slice(0,3).join(", "),l=n.length>3?` +${n.length-3} more`:"";return`${s>=zl?"Very similar":"Substantially overlapping"} \u2014 shared terms: ${a}${l}`}function Df(e){let t=new Map;for(let r of e){let s=t.get(r.realPath);s?s.isSymlink&&!r.isSymlink&&t.set(r.realPath,r):t.set(r.realPath,r)}return[...t.values()]}function Jl(e){return{name:e.name,dirName:e.dirName,provider:e.provider,providerLabel:e.providerLabel||e.provider,scope:e.scope,path:e.path}}function Mf(e,t){return At(e.dirName)===At(t.dirName)||!!e.name&&!!t.name&&At(e.name)===At(t.name)}function Zl(e,t=Cf){let r=Df(e),s=r.map(l=>Lf(l.description)),o=r.map(l=>Af(l.name)),n=Tf(s),a=[];for(let l=0;l<r.length;l++)for(let c=l+1;c<r.length;c++){if(Mf(r[l],r[c]))continue;let d=Nf(s[l],o[l],s[c],o[c],n);if(d>=t){let u=[...o[l]].some(p=>o[c].has(p));a.push({a:Jl(r[l]),b:Jl(r[c]),score:d,highConfidence:d>=zl,reason:Of(s[l],s[c],n,d,u)})}}return a.sort((l,c)=>c.score-l.score||l.a.name.localeCompare(c.a.name)||l.b.name.localeCompare(c.b.name)),{scannedAt:new Date().toISOString(),totalSkills:e.length,comparedSkills:r.length,pairs:a,highConfidenceCount:a.filter(l=>l.highConfidence).length}}function Xl(e){let t=[];if(t.push(""),t.push(i.blueBold(" Semantic Overlap Audit")),t.push(i.dim(" "+"-".repeat(40))),t.push(""),e.totalSkills===0)return t.push(" No installed skills."),t.push(""),t.join(`
384
+ `);if(t.push(` ${i.bold("Compared:")} ${e.comparedSkills} distinct skill(s)`+i.dim(` (from ${e.totalSkills} installed)`)),t.push(""),e.pairs.length===0)return t.push(i.green("No overlapping skills found.")),t.push(""),t.join(`
385
+ `);t.push(i.bold(` Found ${e.pairs.length} overlapping pair(s) (${e.highConfidenceCount} high confidence):`)),t.push("");for(let r of e.pairs){let s=Math.round(r.score*100);t.push(` ${i.bold(`${s}%`)} ${i.yellow(`"${r.a.name}"`)} ${i.dim("\u2194")} ${i.yellow(`"${r.b.name}"`)}`),t.push(i.dim(` ${r.a.providerLabel} (${r.a.scope}) ${Le(r.a.path)}`)),t.push(i.dim(` ${r.b.providerLabel} (${r.b.scope}) ${Le(r.b.path)}`)),r.highConfidence&&t.push(i.red(" \u26A0 likely redundant \u2014 review before keeping both")),t.push(i.dim(` ${r.reason}`)),t.push("")}return t.push(i.dim(" Nothing was changed. Review each pair before removing either skill.")),t.push(""),t.join(`
386
+ `)}function Ql(e){return JSON.stringify(e,null,2)}function jf(){console.log(`${i.bold("Usage:")} asm audit [subcommand] [options]
497
387
 
498
388
  Detect duplicate skills or run security audits on installed/remote skills.
499
389
 
500
- ${l.bold("Subcommands:")}
390
+ ${i.bold("Subcommands:")}
501
391
  duplicates Find duplicate skills (default)
502
392
  overlap Find installed skills that do the same job under different names
503
393
  security <name|source> Run security audit on an installed skill or GitHub source
504
394
  residency Rank installed skills that do not earn their resident context
505
395
 
506
- ${l.bold("Options:")}
396
+ ${i.bold("Options:")}
507
397
  --json Output as JSON
508
398
  --machine Output in stable machine-readable v1 envelope format
509
399
  -y, --yes Auto-remove duplicates, keeping one instance per group
@@ -512,38 +402,39 @@ ${l.bold("Options:")}
512
402
  --no-color Disable ANSI colors
513
403
  -V, --verbose Show debug output
514
404
 
515
- ${l.bold("Examples:")}
516
- asm audit ${l.dim("Find duplicates")}
517
- asm audit -y ${l.dim("Auto-remove duplicates")}
518
- asm audit --json ${l.dim("Output as JSON")}
519
- asm audit overlap ${l.dim("Find same-job skills under different names")}
520
- asm audit overlap --json ${l.dim("Overlap report as JSON")}
521
- asm audit residency ${l.dim("Rank demotion candidates")}
522
- asm audit residency --json ${l.dim("Residency report as JSON")}
523
- asm audit security code-review ${l.dim("Audit an installed skill")}
524
- asm audit security github:user/repo ${l.dim("Audit a remote skill before installing")}
525
- asm audit security --all ${l.dim("Audit all installed skills")}
526
- asm audit security code-review --json ${l.dim("Output audit as JSON")}
527
- asm audit security code-review --machine ${l.dim("Machine-readable v1 envelope output")}
405
+ ${i.bold("Examples:")}
406
+ asm audit ${i.dim("Find duplicates")}
407
+ asm audit -y ${i.dim("Auto-remove duplicates")}
408
+ asm audit --json ${i.dim("Output as JSON")}
409
+ asm audit overlap ${i.dim("Find same-job skills under different names")}
410
+ asm audit overlap --json ${i.dim("Overlap report as JSON")}
411
+ asm audit residency ${i.dim("Rank demotion candidates")}
412
+ asm audit residency --json ${i.dim("Residency report as JSON")}
413
+ asm audit security code-review ${i.dim("Audit an installed skill")}
414
+ asm audit security github:user/repo ${i.dim("Audit a remote skill before installing")}
415
+ asm audit security --all ${i.dim("Audit all installed skills")}
416
+ asm audit security code-review --json ${i.dim("Output audit as JSON")}
417
+ asm audit security code-review --machine ${i.dim("Machine-readable v1 envelope output")}
528
418
  asm audit security https://github.com/user/skills/tree/main/skills/agent-config
529
- ${l.dim("Audit a skill from a subfolder URL")}`)}async function Vm(e){if(e.flags.help){$x();return}let t=performance.now(),s=e.subcommand??"duplicates";if(s==="security"){await Px(e,t);return}if(s==="residency"){await xx(e,t);return}if(s==="overlap"){await Ex(e,t);return}s!=="duplicates"&&($(`Unknown audit subcommand: "${s}". Use: duplicates, overlap, security, residency`),process.exit(2));let i=await j(),r=await K(i,"both");await Promise.all(r.map(ac));let n=Ci(r);if(e.flags.machine){let o={duplicate_groups:n.duplicateGroups.map(a=>({name:a.key,reason:a.reason,...a.contentClass?{contentClass:a.contentClass}:{},count:a.instances.length,instances:a.instances.map(c=>({path:c.path,scope:c.scope,provider:c.provider}))})),total_duplicates:n.duplicateGroups.length,totalDuplicateInstances:n.totalDuplicateInstances};console.log(V("audit duplicates",o,t));return}if(e.flags.json){console.log(uc(n));return}if(console.log(cc(n)),e.flags.yes&&n.duplicateGroups.length>0){console.error(l.bold(`
530
- Auto-removing duplicates...`));let o=0,a=0;for(let c of n.duplicateGroups){let u=lc(c.instances),f=u[0],d=vn(f);for(let p=1;p<u.length;p++){let m=u[p],g=vn(m);if(!(d!==null&&g!==null&&d===g)&&!e.flags.force){a++;let k=d===null||g===null?"contents could not be verified":"contents differ from the kept copy";console.error(l.yellow(` Skipping ${Ue(m.path)} \u2014 ${k}. Kept ${Ue(f.path)}. Re-run with --force to remove it anyway.`));continue}let y=ic(m,i),b=await Pi(y,f.path);for(let k of b)console.error(k);o++}}a>0&&console.error(l.yellow(`
531
- ${a} duplicate cop${a===1?"y":"ies"} skipped (content differs or could not be verified).`)),console.error(l.green(`
532
- Done. Removed ${o} duplicate cop${o===1?"y":"ies"}.`))}}async function xx(e,t){let s=await j(),i=await K(s,e.flags.scope),r=Fe();try{r=await Sx(r)}catch{}let n=Om(i,{librarySkillsDir:r});if(e.flags.machine){console.log(V("audit residency",n,t));return}if(e.flags.json){console.log(q(n));return}console.log(Mm(n))}async function Ex(e,t){let s=await j(),i=await K(s,"both"),r=Bm(i);if(e.flags.machine){let n={compared_skills:r.comparedSkills,total_overlaps:r.pairs.length,high_confidence_overlaps:r.highConfidenceCount,pairs:r.pairs.map(o=>({score:Number(o.score.toFixed(4)),high_confidence:o.highConfidence,reason:o.reason,a:{name:o.a.name,provider:o.a.provider,scope:o.a.scope,path:o.a.path},b:{name:o.b.name,provider:o.b.provider,scope:o.b.scope,path:o.b.path}}))};console.log(V("audit overlap",n,t));return}if(e.flags.json){console.log(Um(r));return}console.log(qm(r))}async function Px(e,t){let s=e.positional[0];e.flags.all?await Cx(e,t):s?s.startsWith("github:")||s.startsWith("https://github.com/")?await Ix(e,s,t):await Lx(e,s,t):(e.flags.machine&&(console.log(z("audit security",Y.INVALID_ARGUMENT,"Missing target. Provide a skill name, GitHub source, or use --all.",t)),process.exit(2)),$(`Missing target. Provide a skill name, GitHub source, or use --all.
533
- Usage: asm audit security <name|github:owner/repo> [--all]`),process.exit(2))}async function Cx(e,t){let s=await j(),i=await K(s,e.flags.scope);if(i.length===0){e.flags.machine?console.log(V("audit security",[],t)):e.flags.json?console.log("[]"):console.log("No skills found to audit.");return}let r=new Set,n=i.filter(a=>r.has(a.realPath)?!1:(r.add(a.realPath),!0));console.error(`Auditing ${n.length} skill${n.length>1?"s":""}...
534
- `);let o=[];for(let a of n){console.error(` Scanning ${l.bold(a.name)}...`);let c=await Me(a.realPath,a.name);o.push(c)}if(e.flags.machine)console.log(V("audit security",Cr(o),t));else if(e.flags.json)console.log(JSON.stringify(o,null,2));else{for(let c of o)console.log(Gt(c));let a={safe:0,caution:0,warning:0,dangerous:0};for(let c of o)a[c.verdict]++;console.log(l.bold(`
535
- Summary:`)),a.dangerous>0&&console.log(` ${l.red(`${a.dangerous} dangerous`)}`),a.warning>0&&console.log(` ${l.yellow(`${a.warning} warning`)}`),a.caution>0&&console.log(` ${a.caution} caution`),a.safe>0&&console.log(` ${l.green(`${a.safe} safe`)}`),console.log("")}}async function Ix(e,t,s){let i=null;try{let r=ue(t);if(r.isLocal)throw new Error("Local paths are not supported for remote security audits. Use: asm audit security <installed-skill-name>");ye(r,t),await Ae(),r=await pt(r),console.error(`Cloning ${t} for audit...`),i=await Re(r,e.flags.transport);let{join:n}=await import("path"),o=r.subpath?n(i,r.subpath):i;try{Be(i,o,t)}catch(u){throw await Q(i),i=null,u}let{name:a}=await we(o),c=await Me(o,a,r.owner,r.repo);e.flags.machine?console.log(V("audit security",Cr([c]),s)):e.flags.json?console.log(Ia(c)):console.log(Gt(c))}catch(r){e.flags.machine&&(console.log(z("audit security",Y.AUDIT_FAILED,r.message,s)),process.exit(1)),$(r.message),process.exit(1)}finally{i&&await Q(i)}}async function Lx(e,t,s){let i=await j(),n=(await K(i,e.flags.scope)).filter(c=>c.dirName===t);n.length===0&&(e.flags.machine&&(console.log(z("audit security",Y.SKILL_NOT_FOUND,`Skill "${t}" not found.`,s)),process.exit(1)),$(`Skill "${t}" not found. Use "asm list" to see installed skills.`),process.exit(1));let o=n[0];console.error(`Auditing installed skill: ${l.bold(o.name)}...
536
- `);let a=await Me(o.realPath,o.name);e.flags.machine?console.log(V("audit security",Cr([a]),s)):e.flags.json?console.log(Ia(a)):console.log(Gt(a))}import{relative as Rx}from"path";import{relative as Ax}from"path";function Km(){console.log(`${l.bold("Usage:")} asm install <source> [options]
419
+ ${i.dim("Audit a skill from a subfolder URL")}`)}async function ec(e){if(e.flags.help){jf();return}let t=performance.now(),r=e.subcommand??"duplicates";if(r==="security"){await Bf(e,t);return}if(r==="residency"){await _f(e,t);return}if(r==="overlap"){await Uf(e,t);return}r!=="duplicates"&&(w(`Unknown audit subcommand: "${r}". Use: duplicates, overlap, security, residency`),process.exit(2));let s=await O(),o=await V(s,"both");await Promise.all(o.map(Gn));let n=$r(o);if(e.flags.machine){let a={duplicate_groups:n.duplicateGroups.map(l=>({name:l.key,reason:l.reason,...l.contentClass?{contentClass:l.contentClass}:{},count:l.instances.length,instances:l.instances.map(c=>({path:c.path,scope:c.scope,provider:c.provider}))})),total_duplicates:n.duplicateGroups.length,totalDuplicateInstances:n.totalDuplicateInstances};console.log(B("audit duplicates",a,t));return}if(e.flags.json){console.log(Wn(n));return}if(console.log(qn(n)),e.flags.yes&&n.duplicateGroups.length>0){console.error(i.bold(`
420
+ Auto-removing duplicates...`));let a=0,l=0;for(let c of n.duplicateGroups){let d=Hn(c.instances),u=d[0],p=Rs(u);for(let f=1;f<d.length;f++){let m=d[f],g=Rs(m);if(!(p!==null&&g!==null&&p===g)&&!e.flags.force){l++;let $=p===null||g===null?"contents could not be verified":"contents differ from the kept copy";console.error(i.yellow(` Skipping ${Le(m.path)} \u2014 ${$}. Kept ${Le(u.path)}. Re-run with --force to remove it anyway.`));continue}let y=_n(m,s),b=await Sr(y,u.path);for(let $ of b)console.error($);a++}}l>0&&console.error(i.yellow(`
421
+ ${l} duplicate cop${l===1?"y":"ies"} skipped (content differs or could not be verified).`)),console.error(i.green(`
422
+ Done. Removed ${a} duplicate cop${a===1?"y":"ies"}.`))}}async function _f(e,t){let r=await O(),s=await V(r,e.flags.scope),o=Re();try{o=await Ff(o)}catch{}let n=ql(s,{librarySkillsDir:o});if(e.flags.machine){console.log(B("audit residency",n,t));return}if(e.flags.json){console.log(j(n));return}console.log(Wl(n))}async function Uf(e,t){let r=await O(),s=await V(r,"both"),o=Zl(s);if(e.flags.machine){let n={compared_skills:o.comparedSkills,total_overlaps:o.pairs.length,high_confidence_overlaps:o.highConfidenceCount,pairs:o.pairs.map(a=>({score:Number(a.score.toFixed(4)),high_confidence:a.highConfidence,reason:a.reason,a:{name:a.a.name,provider:a.a.provider,scope:a.a.scope,path:a.a.path},b:{name:a.b.name,provider:a.b.provider,scope:a.b.scope,path:a.b.path}}))};console.log(B("audit overlap",n,t));return}if(e.flags.json){console.log(Ql(o));return}console.log(Xl(o))}async function Bf(e,t){let r=e.positional[0];e.flags.all?await Vf(e,t):r?r.startsWith("github:")||r.startsWith("https://github.com/")?await Gf(e,r,t):await Hf(e,r,t):(e.flags.machine&&(console.log(K("audit security",W.INVALID_ARGUMENT,"Missing target. Provide a skill name, GitHub source, or use --all.",t)),process.exit(2)),w(`Missing target. Provide a skill name, GitHub source, or use --all.
423
+ Usage: asm audit security <name|github:owner/repo> [--all]`),process.exit(2))}async function Vf(e,t){let r=await O(),s=await V(r,e.flags.scope);if(s.length===0){e.flags.machine?console.log(B("audit security",[],t)):e.flags.json?console.log("[]"):console.log("No skills found to audit.");return}let o=new Set,n=s.filter(l=>o.has(l.realPath)?!1:(o.add(l.realPath),!0));console.error(`Auditing ${n.length} skill${n.length>1?"s":""}...
424
+ `);let a=[];for(let l of n){console.error(` Scanning ${i.bold(l.name)}...`);let c=await xe(l.realPath,l.name);a.push(c)}if(e.flags.machine)console.log(B("audit security",Pr(a),t));else if(e.flags.json)console.log(JSON.stringify(a,null,2));else{for(let c of a)console.log(ft(c));let l={safe:0,caution:0,warning:0,dangerous:0};for(let c of a)l[c.verdict]++;console.log(i.bold(`
425
+ Summary:`)),l.dangerous>0&&console.log(` ${i.red(`${l.dangerous} dangerous`)}`),l.warning>0&&console.log(` ${i.yellow(`${l.warning} warning`)}`),l.caution>0&&console.log(` ${l.caution} caution`),l.safe>0&&console.log(` ${i.green(`${l.safe} safe`)}`),console.log("")}}async function Gf(e,t,r){let s=null;try{let o=oe(t);if(o.isLocal)throw new Error("Local paths are not supported for remote security audits. Use: asm audit security <installed-skill-name>");de(o,t),await ve(),o=await _e(o),console.error(`Cloning ${t} for audit...`),s=await Se(o,e.flags.transport);let{join:n}=await import("path"),a=o.subpath?n(s,o.subpath):s;try{Ee(s,a,t)}catch(d){throw await z(s),s=null,d}let{name:l}=await pe(a),c=await xe(a,l,o.owner,o.repo);e.flags.machine?console.log(B("audit security",Pr([c]),r)):e.flags.json?console.log(Zs(c)):console.log(ft(c))}catch(o){e.flags.machine&&(console.log(K("audit security",W.AUDIT_FAILED,o.message,r)),process.exit(1)),w(o.message),process.exit(1)}finally{s&&await z(s)}}async function Hf(e,t,r){let s=await O(),n=(await V(s,e.flags.scope)).filter(c=>c.dirName===t);n.length===0&&(e.flags.machine&&(console.log(K("audit security",W.SKILL_NOT_FOUND,`Skill "${t}" not found.`,r)),process.exit(1)),w(`Skill "${t}" not found. Use "asm list" to see installed skills.`),process.exit(1));let a=n[0];console.error(`Auditing installed skill: ${i.bold(a.name)}...
426
+ `);let l=await xe(a.realPath,a.name);e.flags.machine?console.log(B("audit security",Pr([l]),r)):e.flags.json?console.log(Zs(l)):console.log(ft(l))}import{relative as Wf}from"path";async function ds(e){let{scopeFlag:t,provider:r,isTTY:s,yes:o,log:n=l=>console.error(l)}=e;if(t==="global"||t==="project")return n(` ${i.dim(`scope: ${t}`)}${t==="global"?` (${r.global})`:` (${r.project})`}`),t;if(!s||o)return n(` ${i.dim("scope: global (default)")} (${r.global})`),"global";n("");let a=await Gs({scopeFlag:t,provider:r,isTTY:s,yes:o});return n(` Selected: ${i.bold(a)} ${i.dim(`(${a==="global"?r.global:r.project})`)}`),a}async function tc(e,t){let{isTTY:r,yes:s,log:o=l=>console.error(l)}=t;if(e.length<=1||!r||s)return e;o(i.bold(`Select skills to install from this bundle:
427
+ `));let n=e.map(l=>({label:l.name,hint:l.description?l.description.slice(0,60)+(l.description.length>60?"...":""):l.version?`v${l.version}`:l.installUrl,checked:!0})),a=await Ie({items:n});if(a.length===0)throw new Error("No skills selected. Aborting.");return a.map(l=>e[l])}import{relative as qf}from"path";function rc(){console.log(`${i.bold("Usage:")} asm install <source> [options]
537
428
 
538
429
  Install a skill from a GitHub repository, the curated registry, or a local path.
539
430
 
540
- ${l.bold("Cross-tool linking (issue #322):")}
431
+ ${i.bold("Cross-tool linking (issue #322):")}
541
432
  If the skill is already installed in another tool, ASM offers two options:
542
433
  1. Reinstall \u2014 download fresh from the index (gets latest version)
543
434
  2. Link \u2014 symlink from the existing install (no download, shares files)
544
435
  Skills installed from a local folder always reinstall (link does not apply).
545
436
 
546
- ${l.bold("Source Format:")}
437
+ ${i.bold("Source Format:")}
547
438
  code-review Install by name from the curated registry
548
439
  author/code-review Install a scoped name (author/name) from registry
549
440
  github:owner/repo Install from default branch
@@ -556,7 +447,7 @@ ${l.bold("Source Format:")}
556
447
  ./relative/path/to/skill Install from a local folder (relative path)
557
448
  ~/path/to/skill Install from a local folder (home-relative path)
558
449
 
559
- ${l.bold("Options:")}
450
+ ${i.bold("Options:")}
560
451
  -p, --tool <name> Target tool (claude, codex, openclaw, agents, all)
561
452
  Use "all" to install to all tools (shared + symlinks)
562
453
  -s, --scope <scope> Installation scope: global or project (default: prompt)
@@ -579,67 +470,67 @@ ${l.bold("Options:")}
579
470
  --no-color Disable ANSI colors
580
471
  -V, --verbose Show debug output
581
472
 
582
- ${l.bold("Registry (bare name):")}
583
- asm install code-review ${l.dim("(resolve from registry)")}
584
- asm install luongnv89/code-review ${l.dim("(scoped name, no ambiguity)")}
585
- asm install code-review --no-cache ${l.dim("(force fresh registry fetch)")}
473
+ ${i.bold("Registry (bare name):")}
474
+ asm install code-review ${i.dim("(resolve from registry)")}
475
+ asm install luongnv89/code-review ${i.dim("(scoped name, no ambiguity)")}
476
+ asm install code-review --no-cache ${i.dim("(force fresh registry fetch)")}
586
477
 
587
- ${l.bold("Local folder:")}
588
- asm install ./my-skill ${l.dim("(relative path)")}
589
- asm install /home/user/skills/my-skill ${l.dim("(absolute path)")}
590
- asm install ~/skills/my-skill ${l.dim("(home-relative path)")}
591
- asm install ../other-project/skill ${l.dim("(parent-relative path)")}
592
- asm install ./skills-dir --all ${l.dim("(all skills in directory)")}
593
- asm install ./skills-dir --library --all -y ${l.dim("(install to local library)")}
478
+ ${i.bold("Local folder:")}
479
+ asm install ./my-skill ${i.dim("(relative path)")}
480
+ asm install /home/user/skills/my-skill ${i.dim("(absolute path)")}
481
+ asm install ~/skills/my-skill ${i.dim("(home-relative path)")}
482
+ asm install ../other-project/skill ${i.dim("(parent-relative path)")}
483
+ asm install ./skills-dir --all ${i.dim("(all skills in directory)")}
484
+ asm install ./skills-dir --library --all -y ${i.dim("(install to local library)")}
594
485
 
595
- ${l.bold("Single-skill repo:")}
486
+ ${i.bold("Single-skill repo:")}
596
487
  asm install github:user/my-skill
597
488
  asm install github:user/my-skill#v1.0.0 -p claude
598
489
  asm install https://github.com/user/my-skill
599
- asm install github:user/my-skill -p all ${l.dim("(install to all tools)")}
600
- asm install github:user/private-skill -t ssh ${l.dim("(clone via SSH)")}
490
+ asm install github:user/my-skill -p all ${i.dim("(install to all tools)")}
491
+ asm install github:user/private-skill -t ssh ${i.dim("(clone via SSH)")}
601
492
 
602
- ${l.bold("Multi-skill repo:")}
493
+ ${i.bold("Multi-skill repo:")}
603
494
  asm install github:user/skills --path skills/code-review
604
495
  asm install github:user/skills --all -p claude -y
605
- asm install github:user/skills --all -p all -y ${l.dim("(all skills, all tools)")}
496
+ asm install github:user/skills --all -p all -y ${i.dim("(all skills, all tools)")}
606
497
  asm install https://github.com/user/skills --all
607
- asm install github:user/skills ${l.dim("(interactive picker)")}
498
+ asm install github:user/skills ${i.dim("(interactive picker)")}
608
499
 
609
- ${l.bold("Subfolder URL:")}
500
+ ${i.bold("Subfolder URL:")}
610
501
  asm install https://github.com/user/skills/tree/main/skills/agent-config
611
502
  asm install github:user/skills#main:skills/agent-config
612
503
 
613
- ${l.bold("Vercel skills CLI:")}
504
+ ${i.bold("Vercel skills CLI:")}
614
505
  asm install github:user/skills --method vercel --skill my-skill
615
506
  asm install https://github.com/user/skills -m vercel --skill my-skill -y
616
- ${l.dim("Delegates to npx skills add for Vercel tracking, then registers in asm")}`)}async function Gm(e,t,s,i,r,n,o,a,c="global"){let u=await we(i),f=await Gs(i),d=i===s?null:i.split(/[/\\]/).pop(),p=r||d||t.repo,m=be(p),g=a.find(x=>x.name.toLowerCase()===u.name.toLowerCase()&&x.provider===o.name),h,y=null,b=!!g;g?g.version===u.version?h=e.flags.force?"REINSTALL":`UPDATE: ${g.version} (same version)`:h=`UPDATE: ${g.version} \u2192 ${u.version}`:(y=await Sa(m,o.name,n),y?h="LINK_AVAILABLE":h="NEW");let k=Js(t,s,i,m,o,e.flags.force||b,c),w=Hs(f),v=w==="high"?l.red("[!] High Risk"):w==="medium"?l.yellow("[~] Medium Risk"):l.green("[ok] Safe");return{metadata:u,skillName:m,warnings:f,installStatus:h,riskLevel:w,riskLabel:v,plan:k,crossToolLink:y??null}}function Hm(e,t,s,i,r,n){let{metadata:o,warnings:a,installStatus:c,riskLabel:u,plan:f,crossToolLink:d}=e;if(r&&n){let p=l.dim(`[${n.index}/${n.total}]`),m=c==="NEW"?l.green(`[${c}]`):l.yellow(`[${c}]`);console.info(`${p} ${l.bold(o.name)} v${o.version} ${m} ${u}`)}else{let p=c==="NEW"?l.green(`[${c}]`):l.yellow(`[${c}]`);if(console.info(` ${l.bold(o.name)} v${o.version} ${p}`),c==="LINK_AVAILABLE"&&d&&console.info(` ${l.dim(`Already installed in ${d.existingProviderLabel}. `)}${l.cyan(`Run with --tool ${s.name} to link, or reinstall for a fresh copy.`)}`),console.info(`
617
- ${l.bold("Install preview:")}`),console.info(` ${l.bold("Name:")} ${o.name}`),console.info(` ${l.bold("Version:")} ${o.version}`),o.description&&console.info(` ${l.bold("Description:")} ${l.dim(o.description)}`),o.effort&&console.info(` ${l.bold("Effort:")} ${_l(o.effort)}`),console.info(` ${l.bold("Source:")} ${t}`),i?(console.info(` ${l.bold("Tool:")} All (${i.map(m=>m.label).join(", ")})`),console.info(` ${l.bold("Primary:")} ${s.label} (${s.name})`),console.info(` ${l.bold("Symlinks:")} ${i.filter(m=>m.name!==s.name).map(m=>m.label).join(", ")}`)):console.info(` ${l.bold("Tool:")} ${s.label} (${s.name})`),console.info(` ${l.bold("Scope:")} ${f.scope==="project"?"Project":"Global"}`),console.info(` ${l.bold("Target:")} ${f.targetDir}`),console.info(` ${l.bold("Status:")} ${p}`),console.info(` ${l.bold("Risk:")} ${u}`),a.length>0){console.info(`
618
- ${l.bold("Security warnings:")}`);let m=new Map;for(let g of a){let h=m.get(g.category)||[];h.push(g),m.set(g.category,h)}for(let[g,h]of m){let b=["Shell commands","Code execution","Credentials"].includes(g)?l.red(`[${g}]`):l.yellow(`[${g}]`);console.info(`
619
- ${b} ${l.dim(`(${h.length} match${h.length>1?"es":""})`)}`);for(let k of h.slice(0,5))console.info(` ${l.dim(`${k.file}:${k.line}`)} -- ${k.match}`);h.length>5&&console.info(l.dim(` ... and ${h.length-5} more`))}}}}async function Jm(e,t){return t?await fa(e,t):await Vt(e)}async function Wm(e){let{inspection:t,source:s,isLocal:i,resolutionSource:r,commitHash:n,scanBaseDir:o,force:a}=e,c=i?`local:${s.localPath}`:`github:${s.owner}/${s.repo}`,u=i?"local":r==="registry"?"registry":"github",f=$i(Ax(o,t.plan.sourceDir)),d=await dl({sourceDir:t.plan.sourceDir,libraryName:t.skillName,source:c,sourceType:u,commitHash:n||"unknown",ref:s.ref||"main",skillPath:f,force:a});return{success:!0,path:d.libraryPath,name:d.name,version:d.version,provider:"Library",source:c}}async function Sl(e){if(e.flags.help){Km();return}let t=e.flags.machine?he():void 0,s=performance.now(),i=e.flags.force,r=e.subcommand;r||($("Missing required argument: <source>"),console.error('Run "asm install --help" for usage.'),process.exit(2));let n=null,o="github",a=8,c=0,u=d=>(c++,`
620
- ${l.cyan(`[Step ${c}/${a}]`)} ${l.bold(d)}`),f=()=>{n?Q(n).finally(()=>process.exit(1)):process.exit(1)};process.on("SIGINT",f),process.on("SIGTERM",f);try{if(!ft(r)&&await Ks(r)&&(r=`./${r}`),tt(r)){console.info(`
621
- ${l.cyan("\u25CF")} Resolving "${l.bold(r)}" from registry...`);let{resolved:R,multipleMatches:I,suggestions:F}=await jr(r,{noCache:e.flags.noCache});if(R){o="registry";let T=R.manifest,M=T.repository.replace("https://github.com/","");r=T.skill_path?`github:${M}#${T.commit}:${T.skill_path}`:`github:${M}#${T.commit}`,console.info(` ${l.green("\u2713")} Resolved: ${l.bold(`${T.author}/${T.name}`)} @ ${T.commit.slice(0,7)}`)}else if(I.length>0){console.info(`
622
- ${l.yellow("\u26A0")} Multiple skills found for "${l.bold(r)}":`);let T=I.slice(0,5);for(let De=0;De<T.length;De++){let it=T[De];console.info(` ${l.cyan(`${De+1}.`)} ${l.bold(`${it.author}/${it.name}`)} \u2014 ${it.description}`)}process.stdin.isTTY||($(`Ambiguous skill name "${r}". Use a scoped name: asm install author/name`),process.exit(2));let M=`
623
- Select a skill [1-${T.length}]: `;process.stderr.write(M);let se=await new Promise(De=>{let it="",hi=!1,ag=setTimeout(()=>{hi||(hi=!0,process.stdin.removeListener("data",dn),De(it.trim()))},3e4);function dn(lg){it=lg.toString().trim(),hi||(hi=!0,clearTimeout(ag),process.stdin.removeListener("data",dn),De(it))}process.stdin.setEncoding("utf-8"),process.stdin.on("data",dn)}),ne=parseInt(se,10);(isNaN(ne)||ne<1||ne>T.length)&&($("Invalid selection. Aborting."),process.exit(2));let de=T[ne-1];o="registry";let Qt=de.repository.replace("https://github.com/","");r=de.skill_path?`github:${Qt}#${de.commit}:${de.skill_path}`:`github:${Qt}#${de.commit}`,console.info(` ${l.green("\u2713")} Selected: ${l.bold(`${de.author}/${de.name}`)} @ ${de.commit.slice(0,7)}`)}else Ea(r)?($(`Skill "${r}" not found in the registry.`),F.length>0&&console.error(`
624
- Did you mean: ${F.map(T=>l.cyan(T)).join(", ")}?`),process.exit(1)):(console.info(` ${l.dim("Not found in registry \u2014 trying existing sources...")}`),o="pre-indexed")}console.info(u("Parsing source"));let d=ue(r);if(!d.isLocal&&(ye(d,r),Vs(e.flags.path)))throw new Error(`Invalid source: the subpath in "${e.flags.path}" escapes the repository.`);let p=!!d.isLocal;if(p){let R=d.localPath;console.info(` ${l.dim(`local: ${R}`)}`);let{stat:I}=await import("fs/promises");try{if(!(await I(R)).isDirectory())throw new Error(`Path is not a directory: ${R}`)}catch(F){throw F.code==="ENOENT"?new Error(`Path does not exist: ${R}`,{cause:F}):F}}else await Ae(),d=await pt(d),console.info(` ${l.dim(r)}`);if(e.flags.library&&e.flags.method==="vercel")throw new Error("--library cannot be combined with --method vercel because the Vercel installer writes to provider skill folders. Use the default method for library installs.");if(e.flags.method==="vercel"){console.info(u("Installing via Vercel skills CLI")),await ba();let R=ka(d),I=e.flags.path||null;console.info(` ${l.dim(`npx skills add ${R}${I?` --skill ${I}`:""}`)}`);let{stdout:F,stderr:T}=await wa(R,I);F.trim()&&console.info(` ${l.dim(F.trim())}`),T.trim()&&console.error(` ${l.dim(T.trim())}`),console.info(` ${l.green("\u2713")} Vercel skills CLI install completed`),e.flags.force=!0,console.info(` ${l.dim("Continuing with asm install to register in local inventory...")}`)}let m=await j(),g,h=null,y="global";if(e.flags.library){console.info(u("Selecting library"));let R=m.providers.find(I=>I.enabled)??m.providers[0];if(!R)throw new Error("No providers configured.");g=R,console.info(` ${l.dim(`library: ${Fe()}`)}`)}else{console.info(u("Selecting provider"));let R=await ke(m,e.flags.provider,!!process.stdin.isTTY);if(g=R.provider,h=R.allProviders,console.info(u("Selecting scope")),e.flags.scope==="global"||e.flags.scope==="project")y=e.flags.scope,console.info(` ${l.dim(`scope: ${y}`)}${y==="global"?` (${g.global})`:` (${g.project})`}`);else if(!process.stdin.isTTY||e.flags.yes)y="global",console.info(` ${l.dim("scope: global (default)")} (${g.global})`);else{let I=[{label:`Global (${g.global})`,hint:"Available in all projects",checked:!0},{label:`Project (${g.project})`,hint:"Available only in this project",checked:!1}];console.info("");let F=await ht({items:I});if(F.length===0)throw new Error("No scope selected. Aborting.");y=F[0]===0?"global":"project",console.info(` Selected: ${l.bold(y)} ${l.dim(`(${y==="global"?g.global:g.project})`)}`)}}if(p)console.info(u("Reading local source")),console.info(` ${l.dim(d.localPath)}`),n=null;else{console.info(u("Cloning repository"));let R=e.flags.transport,I=R==="ssh"?d.sshCloneUrl:R==="https"?d.cloneUrl:`${d.cloneUrl} ${l.dim("(auto)")}`;console.info(` ${I}${d.ref?` ${l.dim(`(ref: ${d.ref})`)}`:""}${d.subpath?` ${l.dim(`(path: ${d.subpath})`)}`:""}`),n=await Re(d,R)}let b=p?d.localPath:n;console.info(u("Scanning for skills"));let{join:k}=await import("path"),w=[],v=e.flags.path||d.subpath,x=[],C=!1,A=b,E="",_=!1;if(v){let R=k(b,v);if(!p)try{Be(b,R,r)}catch(F){throw n&&(await Q(n),n=null),F}let I=!1;try{await we(R),I=!0}catch{if(!e.flags.all)throw new Error(`No SKILL.md found at path "${v}" in the repository.`);let{stat:F}=await import("fs/promises");try{if(!(await F(R)).isDirectory())throw new Error(`No SKILL.md found at path "${v}" in the repository.`)}catch(T){throw T&&T.code==="ENOENT"?new Error(`No SKILL.md found at path "${v}" in the repository.`,{cause:T}):T}C=!0,A=R,E=v}I&&(console.info(` Found skill at ${l.bold(v)}`),x=[{skillDir:R,nameOverride:e.flags.name}])}else{try{await we(b),_=!0}catch{}if(_&&!e.flags.all){let R=await we(b);console.info(` Found: ${l.bold(R.name)} v${R.version}`),x=[{skillDir:b,nameOverride:e.flags.name}]}else _&&e.flags.all,C=!0}if(C){console.info(E?` No SKILL.md at ${l.bold(E)}. Scanning subdirectories...`:_?" Root SKILL.md found. Scanning for additional skills in subdirectories...":" No SKILL.md at root. Scanning subdirectories...");let R=await mt(A),I=E?R.map(M=>({...M,relPath:`${E}/${M.relPath}`})):R;if(I.length===0)throw new Error(E?`No skills found under path "${E}". Skills must have a SKILL.md file.`:"No skills found in this repository. Skills must have a SKILL.md file.");console.info(` Found ${l.bold(String(I.length))} skill(s):
625
- `);for(let M=0;M<I.length;M++){let se=l.cyan(` ${String(M+1).padStart(String(I.length).length)})`);console.info(`${se} ${l.bold(I[M].name)} ${l.dim(`v${I[M].version}`)} ${l.dim(`(${I[M].relPath})`)}`),I[M].description&&console.info(` ${l.dim(I[M].description)}`)}console.info(u("Selecting skills")),c--;let F;if(e.flags.all&&(e.flags.yes||!process.stdin.isTTY))F=I.map(M=>M.relPath),console.info(` Selected all ${l.bold(String(F.length))} skills`);else if(process.stdin.isTTY)if(I.length===1)F=[I[0].relPath],console.info(` Auto-selected: ${l.bold(I[0].name)} ${l.dim(`v${I[0].version}`)}`);else{let M=I.map(ne=>({label:ne.name,hint:`v${ne.version}${ne.description?" "+ne.description:""}`,checked:!!e.flags.all}));console.info("");let se=await ht({items:M});if(se.length===0)throw new Error("No skills selected. Aborting.");F=se.map(ne=>I[ne].relPath),console.info(` Selected ${l.bold(String(F.length))} skill(s)`)}else{$(`Repository contains ${I.length} skills. Use --path <subdir> to pick one or --all to install all.
507
+ ${i.dim("Delegates to npx skills add for Vercel tracking, then registers in asm")}`)}async function sc(e,t,r,s,o,n,a,l,c="global"){let d=await pe(s),u=await Bt(s),p=s===r?null:s.split(/[/\\]/).pop(),f=o||p||t.repo,m=ue(f),g=l.find(C=>C.name.toLowerCase()===d.name.toLowerCase()&&C.provider===a.name),h,y=null,b=!!g;g?g.version===d.version?h=e.flags.force?"REINSTALL":`UPDATE: ${g.version} (same version)`:h=`UPDATE: ${g.version} \u2192 ${d.version}`:(y=await qs(m,a.name,n),y?h="LINK_AVAILABLE":h="NEW");let $=Ht(t,r,s,m,a,e.flags.force||b,c),v=Vt(u),S=v==="high"?i.red("[!] High Risk"):v==="medium"?i.yellow("[~] Medium Risk"):i.green("[ok] Safe");return{metadata:d,skillName:m,warnings:u,installStatus:h,riskLevel:v,riskLabel:S,plan:$,crossToolLink:y??null}}function oc(e,t,r,s,o,n){let{metadata:a,warnings:l,installStatus:c,riskLabel:d,plan:u,crossToolLink:p}=e;if(o&&n){let f=i.dim(`[${n.index}/${n.total}]`),m=c==="NEW"?i.green(`[${c}]`):i.yellow(`[${c}]`);console.info(`${f} ${i.bold(a.name)} v${a.version} ${m} ${d}`)}else{let f=c==="NEW"?i.green(`[${c}]`):i.yellow(`[${c}]`);if(console.info(` ${i.bold(a.name)} v${a.version} ${f}`),c==="LINK_AVAILABLE"&&p&&console.info(` ${i.dim(`Already installed in ${p.existingProviderLabel}. `)}${i.cyan(`Run with --tool ${r.name} to link, or reinstall for a fresh copy.`)}`),console.info(`
508
+ ${i.bold("Install preview:")}`),console.info(` ${i.bold("Name:")} ${a.name}`),console.info(` ${i.bold("Version:")} ${a.version}`),a.description&&console.info(` ${i.bold("Description:")} ${i.dim(a.description)}`),a.effort&&console.info(` ${i.bold("Effort:")} ${yn(a.effort)}`),console.info(` ${i.bold("Source:")} ${t}`),s?(console.info(` ${i.bold("Tool:")} All (${s.map(m=>m.label).join(", ")})`),console.info(` ${i.bold("Primary:")} ${r.label} (${r.name})`),console.info(` ${i.bold("Symlinks:")} ${s.filter(m=>m.name!==r.name).map(m=>m.label).join(", ")}`)):console.info(` ${i.bold("Tool:")} ${r.label} (${r.name})`),console.info(` ${i.bold("Scope:")} ${u.scope==="project"?"Project":"Global"}`),console.info(` ${i.bold("Target:")} ${u.targetDir}`),console.info(` ${i.bold("Status:")} ${f}`),console.info(` ${i.bold("Risk:")} ${d}`),l.length>0){console.info(`
509
+ ${i.bold("Security warnings:")}`);let m=new Map;for(let g of l){let h=m.get(g.category)||[];h.push(g),m.set(g.category,h)}for(let[g,h]of m){let b=["Shell commands","Code execution","Credentials"].includes(g)?i.red(`[${g}]`):i.yellow(`[${g}]`);console.info(`
510
+ ${b} ${i.dim(`(${h.length} match${h.length>1?"es":""})`)}`);for(let $ of h.slice(0,5))console.info(` ${i.dim(`${$.file}:${$.line}`)} -- ${$.match}`);h.length>5&&console.info(i.dim(` ... and ${h.length-5} more`))}}}}async function nc(e,t){return t?await Gt(e,t):await pt(e)}async function ic(e){let{inspection:t,source:r,isLocal:s,resolutionSource:o,commitHash:n,scanBaseDir:a,force:l}=e,c=s?`local:${r.localPath}`:`github:${r.owner}/${r.repo}`,d=s?"local":o==="registry"?"registry":"github",u=rt(qf(a,t.plan.sourceDir)),p=await Do({sourceDir:t.plan.sourceDir,libraryName:t.skillName,source:c,sourceType:d,commitHash:n||"unknown",ref:r.ref||"main",skillPath:u,force:l});return{success:!0,path:p.libraryPath,name:p.name,version:p.version,provider:"Library",source:c}}async function Qo(e){if(e.flags.help){rc();return}let t=e.flags.machine?le():void 0,r=performance.now(),s=e.flags.force,o=e.subcommand;o||(w("Missing required argument: <source>"),console.error('Run "asm install --help" for usage.'),process.exit(2));let n=null,a="github",l=8,c=0,d=p=>(c++,`
511
+ ${i.cyan(`[Step ${c}/${l}]`)} ${i.bold(p)}`),u=()=>{n?z(n).finally(()=>process.exit(1)):process.exit(1)};process.on("SIGINT",u),process.on("SIGTERM",u);try{if(!je(o)&&await Ut(o)&&(o=`./${o}`),Ne(o)){console.info(`
512
+ ${i.cyan("\u25CF")} Resolving "${i.bold(o)}" from registry...`);let{resolved:R,multipleMatches:x,suggestions:N}=await Fr(o,{noCache:e.flags.noCache});if(R){a="registry";let I=R.manifest,L=I.repository.replace("https://github.com/","");o=I.skill_path?`github:${L}#${I.commit}:${I.skill_path}`:`github:${L}#${I.commit}`,console.info(` ${i.green("\u2713")} Resolved: ${i.bold(`${I.author}/${I.name}`)} @ ${I.commit.slice(0,7)}`)}else if(x.length>0){console.info(`
513
+ ${i.yellow("\u26A0")} Multiple skills found for "${i.bold(o)}":`);let I=x.slice(0,5);for(let Pe=0;Pe<I.length;Pe++){let De=I[Pe];console.info(` ${i.cyan(`${Pe+1}.`)} ${i.bold(`${De.author}/${De.name}`)} \u2014 ${De.description}`)}process.stdin.isTTY||(w(`Ambiguous skill name "${o}". Use a scoped name: asm install author/name`),process.exit(2));let L=`
514
+ Select a skill [1-${I.length}]: `;process.stderr.write(L);let X=await new Promise(Pe=>{let De="",fr=!1,wd=setTimeout(()=>{fr||(fr=!0,process.stdin.removeListener("data",hs),Pe(De.trim()))},3e4);function hs(kd){De=kd.toString().trim(),fr||(fr=!0,clearTimeout(wd),process.stdin.removeListener("data",hs),Pe(De))}process.stdin.setEncoding("utf-8"),process.stdin.on("data",hs)}),te=parseInt(X,10);(isNaN(te)||te<1||te>I.length)&&(w("Invalid selection. Aborting."),process.exit(2));let ie=I[te-1];a="registry";let xt=ie.repository.replace("https://github.com/","");o=ie.skill_path?`github:${xt}#${ie.commit}:${ie.skill_path}`:`github:${xt}#${ie.commit}`,console.info(` ${i.green("\u2713")} Selected: ${i.bold(`${ie.author}/${ie.name}`)} @ ${ie.commit.slice(0,7)}`)}else Js(o)?(w(`Skill "${o}" not found in the registry.`),N.length>0&&console.error(`
515
+ Did you mean: ${N.map(I=>i.cyan(I)).join(", ")}?`),process.exit(1)):(console.info(` ${i.dim("Not found in registry \u2014 trying existing sources...")}`),a="pre-indexed")}console.info(d("Parsing source"));let p=oe(o);if(!p.isLocal&&(de(p,o),_t(e.flags.path)))throw new Error(`Invalid source: the subpath in "${e.flags.path}" escapes the repository.`);let f=!!p.isLocal;if(f){let R=p.localPath;console.info(` ${i.dim(`local: ${R}`)}`);let{stat:x}=await import("fs/promises");try{if(!(await x(R)).isDirectory())throw new Error(`Path is not a directory: ${R}`)}catch(N){throw N.code==="ENOENT"?new Error(`Path does not exist: ${R}`,{cause:N}):N}}else await ve(),p=await _e(p),console.info(` ${i.dim(o)}`);if(e.flags.library&&e.flags.method==="vercel")throw new Error("--library cannot be combined with --method vercel because the Vercel installer writes to provider skill folders. Use the default method for library installs.");if(e.flags.method==="vercel"){console.info(d("Installing via Vercel skills CLI")),await Us();let R=Vs(p),x=e.flags.path||null;console.info(` ${i.dim(`npx skills add ${R}${x?` --skill ${x}`:""}`)}`);let{stdout:N,stderr:I}=await Bs(R,x);N.trim()&&console.info(` ${i.dim(N.trim())}`),I.trim()&&console.error(` ${i.dim(I.trim())}`),console.info(` ${i.green("\u2713")} Vercel skills CLI install completed`),e.flags.force=!0,console.info(` ${i.dim("Continuing with asm install to register in local inventory...")}`)}let m=await O(),g,h=null,y="global";if(e.flags.library){console.info(d("Selecting library"));let R=m.providers.find(x=>x.enabled)??m.providers[0];if(!R)throw new Error("No providers configured.");g=R,console.info(` ${i.dim(`library: ${Re()}`)}`)}else{console.info(d("Selecting provider"));let R=await me(m,e.flags.provider,!!process.stdin.isTTY);g=R.provider,h=R.allProviders,console.info(d("Selecting scope")),y=await ds({scopeFlag:e.flags.scope,provider:g,isTTY:!!process.stdin.isTTY,yes:!!e.flags.yes,log:x=>console.info(x)})}if(f)console.info(d("Reading local source")),console.info(` ${i.dim(p.localPath)}`),n=null;else{console.info(d("Cloning repository"));let R=e.flags.transport,x=R==="ssh"?p.sshCloneUrl:R==="https"?p.cloneUrl:`${p.cloneUrl} ${i.dim("(auto)")}`;console.info(` ${x}${p.ref?` ${i.dim(`(ref: ${p.ref})`)}`:""}${p.subpath?` ${i.dim(`(path: ${p.subpath})`)}`:""}`),n=await Se(p,R)}let b=f?p.localPath:n;console.info(d("Scanning for skills"));let{join:$}=await import("path"),v=[],S=e.flags.path||p.subpath,C=[],D=!1,U=b,A="",_=!1;if(S){let R=$(b,S);if(!f)try{Ee(b,R,o)}catch(N){throw n&&(await z(n),n=null),N}let x=!1;try{await pe(R),x=!0}catch{if(!e.flags.all)throw new Error(`No SKILL.md found at path "${S}" in the repository.`);let{stat:N}=await import("fs/promises");try{if(!(await N(R)).isDirectory())throw new Error(`No SKILL.md found at path "${S}" in the repository.`)}catch(I){throw I&&I.code==="ENOENT"?new Error(`No SKILL.md found at path "${S}" in the repository.`,{cause:I}):I}D=!0,U=R,A=S}x&&(console.info(` Found skill at ${i.bold(S)}`),C=[{skillDir:R,nameOverride:e.flags.name}])}else{try{await pe(b),_=!0}catch{}if(_&&!e.flags.all){let R=await pe(b);console.info(` Found: ${i.bold(R.name)} v${R.version}`),C=[{skillDir:b,nameOverride:e.flags.name}]}else _&&e.flags.all,D=!0}if(D){console.info(A?` No SKILL.md at ${i.bold(A)}. Scanning subdirectories...`:_?" Root SKILL.md found. Scanning for additional skills in subdirectories...":" No SKILL.md at root. Scanning subdirectories...");let R=await Ue(U),x=A?R.map(L=>({...L,relPath:`${A}/${L.relPath}`})):R;if(x.length===0)throw new Error(A?`No skills found under path "${A}". Skills must have a SKILL.md file.`:"No skills found in this repository. Skills must have a SKILL.md file.");console.info(` Found ${i.bold(String(x.length))} skill(s):
516
+ `);for(let L=0;L<x.length;L++){let X=i.cyan(` ${String(L+1).padStart(String(x.length).length)})`);console.info(`${X} ${i.bold(x[L].name)} ${i.dim(`v${x[L].version}`)} ${i.dim(`(${x[L].relPath})`)}`),x[L].description&&console.info(` ${i.dim(x[L].description)}`)}console.info(d("Selecting skills")),c--;let N;if(e.flags.all&&(e.flags.yes||!process.stdin.isTTY))N=x.map(L=>L.relPath),console.info(` Selected all ${i.bold(String(N.length))} skills`);else if(process.stdin.isTTY)if(x.length===1)N=[x[0].relPath],console.info(` Auto-selected: ${i.bold(x[0].name)} ${i.dim(`v${x[0].version}`)}`);else{let L=x.map(te=>({label:te.name,hint:`v${te.version}${te.description?" "+te.description:""}`,checked:!!e.flags.all}));console.info("");let X=await Ie({items:L});if(X.length===0)throw new Error("No skills selected. Aborting.");N=X.map(te=>x[te].relPath),console.info(` Selected ${i.bold(String(N.length))} skill(s)`)}else{w(`Repository contains ${x.length} skills. Use --path <subdir> to pick one or --all to install all.
626
517
  Available skills:
627
- ${I.map(M=>` --path ${M.relPath}`).join(`
628
- `)}`),process.exit(2);return}let T=da(F,M=>M===""?be(d.repo):Mr(M));if(T.length>0){let M=T.map(ne=>` - ${ne.name}: ${ne.paths.map(de=>`"${de}"`).join(", ")}`).join(`
629
- `),se=new Error(`Duplicate skill names detected in selection:
630
- ${M}
631
- Choose one path per skill name or install with --path.`);throw se.duplicates=T,se}x=F.map(M=>({skillDir:k(b,M),nameOverride:F.length===1?e.flags.name:null})),c++}console.info(u("Inspecting skills"));let O=await K(m,"both"),S=[],P=x.length>1;for(let R=0;R<x.length;R++){let{skillDir:I,nameOverride:F}=x[R],T=await Gm(e,d,b,I,F,m,g,O,y);S.push(T),Hm(T,r,g,h,P,P?{index:R+1,total:x.length}:void 0)}if(P){console.info(""),console.info(` ${l.bold("Install settings:")}`),console.info(` ${l.bold("Source:")} ${r}`),console.info(h?` ${l.bold("Tool:")} All (${h.map(M=>M.label).join(", ")})`:` ${l.bold("Tool:")} ${g.label} (${g.name})`),console.info(` ${l.bold("Scope:")} ${y==="project"?"Project":"Global"}`);let R=S.filter(M=>M.riskLevel==="high").length,I=S.filter(M=>M.riskLevel==="medium").length,F=S.filter(M=>M.riskLevel==="safe").length,T=[];F>0&&T.push(l.green(`${F} Safe`)),I>0&&T.push(l.yellow(`${I} Medium Risk`)),R>0&&T.push(l.red(`${R} High Risk`)),console.info(` ${l.bold("Risk:")} ${T.join(", ")}`)}console.info(u("Installing"));let B=new Map;if(S.some(R=>R.installStatus==="LINK_AVAILABLE"&&R.crossToolLink)&&!e.flags.yes)if(process.stdin.isTTY)for(let R=0;R<S.length;R++){let I=S[R];if(I.installStatus!=="LINK_AVAILABLE"||!I.crossToolLink)continue;let F=I.crossToolLink;console.info(`
632
- ${l.yellow("\u26A0")} ${l.bold(I.metadata.name)} is already installed in ${F.existingProviderLabel}.`),console.info(` Existing: ${l.dim(F.existingPath)}`),console.info(`
633
- ${l.cyan("Option 1")} \u2014 ${l.bold("Reinstall")}: Download fresh from index (gets latest version)`),console.info(` ${l.cyan("Option 2")} \u2014 ${l.bold("Link")}: Symlink from existing install (no download, shares files)`),process.stderr.write(" Choose (1/2): ");let T=await H();T==="2"||T.toLowerCase()==="link"?(B.set(R,"link"),console.info(` ${l.green("\u2713")} Selected: Link from ${F.existingProviderLabel}`)):(B.set(R,"reinstall"),console.info(` ${l.green("\u2713")} Selected: Reinstall from index`))}else for(let R=0;R<S.length;R++)S[R].installStatus==="LINK_AVAILABLE"&&B.set(R,"link");if(!e.flags.yes&&S.some((I,F)=>I.installStatus!=="LINK_AVAILABLE"||B.get(F)==="reinstall")){let I=S.some(se=>se.riskLevel==="high");process.stdin.isTTY||($("Cannot prompt for confirmation in non-interactive mode. Use --yes to skip."),process.exit(2));let F=P?`${S.length} skills`:`"${S[0].metadata.name}"`,T=I?`
634
- ${l.red("[!]")} ${l.bold(`Install ${F}? Some have high-risk patterns.`)} [y/N] `:`
635
- ${l.bold(`Install ${F}?`)} [Y/n] `;process.stderr.write(T);let M=await H();I?M.toLowerCase()!=="y"&&M.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0)):(M.toLowerCase()==="n"||M.toLowerCase()==="no")&&(console.error("Aborted."),process.exit(0))}let ce=n?await sc(n):null,Pe=[];for(let R=0;R<S.length;R++){let I=S[R],F=P?l.dim(`[${R+1}/${S.length}]`)+" ":" ";if(B.get(R)==="link"&&I.crossToolLink){let T=I.crossToolLink;try{console.info(`${F}Linking ${l.bold(I.metadata.name)} from ${T.existingProviderLabel}...`);let M=await $a(I.skillName,T.existingPath,g.name,y,m,e.flags.force);w.push({success:!0,path:M,name:I.metadata.name,version:I.metadata.version,provider:`Linked from ${T.existingProviderLabel}`,source:`link:${T.existingPath}`}),console.info(`${F}${l.green("\u2713")} ${I.metadata.name} linked to ${l.dim(M)}`);try{await Et(I.metadata.name,{source:`link:${T.existingPath}`,commitHash:"linked",ref:null,installedAt:new Date().toISOString(),provider:g.name,sourceType:"local"})}catch{}}catch(M){Pe.push({name:I.metadata.name,error:M.message}),console.error(`${F}${l.red("\u2717")} ${l.bold(I.metadata.name)} \u2014 ${l.red(M.message)}`)}continue}try{console.info(`${F}Installing ${l.bold(I.metadata.name)}...`);let T=e.flags.library?await Wm({inspection:I,source:d,isLocal:p,resolutionSource:o,commitHash:ce,scanBaseDir:b,force:i}):await Jm(I.plan,h);if(w.push(T),console.info(`${F}${l.green("\u2713")} ${I.metadata.name} installed to ${l.dim(T.path)}`),!e.flags.library)try{let M=p?`local:${d.localPath}`:`github:${d.owner}/${d.repo}`,se=p?"local":o==="registry"?"registry":"github";await Et(T.name,{source:M,commitHash:ce||"unknown",ref:d.ref||"main",installedAt:new Date().toISOString(),provider:I.plan.providerName,scope:I.plan.scope,skillPath:$i(Rx(I.plan.tempDir,I.plan.sourceDir)),targetDir:I.plan.targetDir,sourceType:se,...o==="registry"?{registryName:T.name}:{}})}catch{}}catch(T){Pe.push({name:I.metadata.name,error:T.message}),console.error(`${F}${l.red("\u2717")} ${l.bold(I.metadata.name)} \u2014 ${l.red(T.message)}`)}}if(process.removeListener("SIGINT",f),process.removeListener("SIGTERM",f),Pe.length>0){console.error(`
636
- ${l.yellow(`${Pe.length} skill(s) failed to install:`)}`);for(let R of Pe)console.error(` ${l.red("\u2717")} ${R.name}: ${R.error}`);e.flags.library&&(process.exitCode=1)}if(e.flags.machine){t?.();let R=w.map(I=>({name:I.name,path:I.path,version:I.version,provider:I.provider,source:I.source,resolution_source:o}));console.log(V("install",R.length===1?R[0]:R,s))}else if(e.flags.json){let R=w.map(I=>({...I,resolutionSource:o}));console.log(JSON.stringify(R.length===1?R[0]:R,null,2))}else w.length===1?console.error(l.green(`
637
- Done! Installed "${w[0].name}" to ${w[0].path}`)):w.length>0&&console.error(`
638
- ${l.green(`Done! Installed ${w.length} skill(s) successfully.`)}`)}catch(d){if(process.removeListener("SIGINT",f),process.removeListener("SIGTERM",f),e.flags.machine)t?.(),console.log(z("install",Y.INSTALL_FAILED,d.message,s,d?.duplicates?{duplicates:d.duplicates}:void 0));else if(e.flags.json){let p={success:!1,error:d.message};d?.duplicates&&(p.duplicates=d.duplicates),console.log(JSON.stringify(p,null,2))}else $(d.message);process.exit(1)}finally{n&&await Q(n),t?.()}}function Nx(){console.log(`${l.bold("Usage:")} asm activate <skill> -p <tool> -s <scope> [options]
518
+ ${x.map(L=>` --path ${L.relPath}`).join(`
519
+ `)}`),process.exit(2);return}let I=Os(N,L=>L===""?ue(p.repo):Nr(L));if(I.length>0){let L=I.map(te=>` - ${te.name}: ${te.paths.map(ie=>`"${ie}"`).join(", ")}`).join(`
520
+ `),X=new Error(`Duplicate skill names detected in selection:
521
+ ${L}
522
+ Choose one path per skill name or install with --path.`);throw X.duplicates=I,X}C=N.map(L=>({skillDir:$(b,L),nameOverride:N.length===1?e.flags.name:null})),c++}console.info(d("Inspecting skills"));let M=await V(m,"both"),k=[],E=C.length>1;for(let R=0;R<C.length;R++){let{skillDir:x,nameOverride:N}=C[R],I=await sc(e,p,b,x,N,m,g,M,y);k.push(I),oc(I,o,g,h,E,E?{index:R+1,total:C.length}:void 0)}if(E){console.info(""),console.info(` ${i.bold("Install settings:")}`),console.info(` ${i.bold("Source:")} ${o}`),console.info(h?` ${i.bold("Tool:")} All (${h.map(L=>L.label).join(", ")})`:` ${i.bold("Tool:")} ${g.label} (${g.name})`),console.info(` ${i.bold("Scope:")} ${y==="project"?"Project":"Global"}`);let R=k.filter(L=>L.riskLevel==="high").length,x=k.filter(L=>L.riskLevel==="medium").length,N=k.filter(L=>L.riskLevel==="safe").length,I=[];N>0&&I.push(i.green(`${N} Safe`)),x>0&&I.push(i.yellow(`${x} Medium Risk`)),R>0&&I.push(i.red(`${R} High Risk`)),console.info(` ${i.bold("Risk:")} ${I.join(", ")}`)}console.info(d("Installing"));let F=new Map;if(k.some(R=>R.installStatus==="LINK_AVAILABLE"&&R.crossToolLink)&&!e.flags.yes)if(process.stdin.isTTY)for(let R=0;R<k.length;R++){let x=k[R];if(x.installStatus!=="LINK_AVAILABLE"||!x.crossToolLink)continue;let N=x.crossToolLink;console.info(`
523
+ ${i.yellow("\u26A0")} ${i.bold(x.metadata.name)} is already installed in ${N.existingProviderLabel}.`),console.info(` Existing: ${i.dim(N.existingPath)}`),console.info(`
524
+ ${i.cyan("Option 1")} \u2014 ${i.bold("Reinstall")}: Download fresh from index (gets latest version)`),console.info(` ${i.cyan("Option 2")} \u2014 ${i.bold("Link")}: Symlink from existing install (no download, shares files)`),process.stderr.write(" Choose (1/2): ");let I=await G();I==="2"||I.toLowerCase()==="link"?(F.set(R,"link"),console.info(` ${i.green("\u2713")} Selected: Link from ${N.existingProviderLabel}`)):(F.set(R,"reinstall"),console.info(` ${i.green("\u2713")} Selected: Reinstall from index`))}else for(let R=0;R<k.length;R++)k[R].installStatus==="LINK_AVAILABLE"&&F.set(R,"link");if(!e.flags.yes&&k.some((x,N)=>x.installStatus!=="LINK_AVAILABLE"||F.get(N)==="reinstall")){let x=k.some(X=>X.riskLevel==="high");process.stdin.isTTY||(w("Cannot prompt for confirmation in non-interactive mode. Use --yes to skip."),process.exit(2));let N=E?`${k.length} skills`:`"${k[0].metadata.name}"`,I=x?`
525
+ ${i.red("[!]")} ${i.bold(`Install ${N}? Some have high-risk patterns.`)} [y/N] `:`
526
+ ${i.bold(`Install ${N}?`)} [Y/n] `;process.stderr.write(I);let L=await G();x?L.toLowerCase()!=="y"&&L.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0)):(L.toLowerCase()==="n"||L.toLowerCase()==="no")&&(console.error("Aborted."),process.exit(0))}let se=n?await jn(n):null,we=[];for(let R=0;R<k.length;R++){let x=k[R],N=E?i.dim(`[${R+1}/${k.length}]`)+" ":" ";if(F.get(R)==="link"&&x.crossToolLink){let I=x.crossToolLink;try{console.info(`${N}Linking ${i.bold(x.metadata.name)} from ${I.existingProviderLabel}...`);let L=await Ws(x.skillName,I.existingPath,g.name,y,m,e.flags.force);v.push({success:!0,path:L,name:x.metadata.name,version:x.metadata.version,provider:`Linked from ${I.existingProviderLabel}`,source:`link:${I.existingPath}`}),console.info(`${N}${i.green("\u2713")} ${x.metadata.name} linked to ${i.dim(L)}`);try{await nt(x.metadata.name,{source:`link:${I.existingPath}`,commitHash:"linked",ref:null,installedAt:new Date().toISOString(),provider:g.name,sourceType:"local"})}catch{}}catch(L){we.push({name:x.metadata.name,error:L.message}),console.error(`${N}${i.red("\u2717")} ${i.bold(x.metadata.name)} \u2014 ${i.red(L.message)}`)}continue}try{console.info(`${N}Installing ${i.bold(x.metadata.name)}...`);let I=e.flags.library?await ic({inspection:x,source:p,isLocal:f,resolutionSource:a,commitHash:se,scanBaseDir:b,force:s}):await nc(x.plan,h);if(v.push(I),console.info(`${N}${i.green("\u2713")} ${x.metadata.name} installed to ${i.dim(I.path)}`),!e.flags.library)try{let L=f?`local:${p.localPath}`:`github:${p.owner}/${p.repo}`,X=f?"local":a==="registry"?"registry":"github";await nt(I.name,{source:L,commitHash:se||"unknown",ref:p.ref||"main",installedAt:new Date().toISOString(),provider:x.plan.providerName,scope:x.plan.scope,skillPath:rt(Wf(x.plan.tempDir,x.plan.sourceDir)),targetDir:x.plan.targetDir,sourceType:X,...a==="registry"?{registryName:I.name}:{}})}catch{}}catch(I){we.push({name:x.metadata.name,error:I.message}),console.error(`${N}${i.red("\u2717")} ${i.bold(x.metadata.name)} \u2014 ${i.red(I.message)}`)}}if(process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u),we.length>0){console.error(`
527
+ ${i.yellow(`${we.length} skill(s) failed to install:`)}`);for(let R of we)console.error(` ${i.red("\u2717")} ${R.name}: ${R.error}`);e.flags.library&&(process.exitCode=1)}if(e.flags.machine){t?.();let R=v.map(x=>({name:x.name,path:x.path,version:x.version,provider:x.provider,source:x.source,resolution_source:a}));console.log(B("install",R.length===1?R[0]:R,r))}else if(e.flags.json){let R=v.map(x=>({...x,resolutionSource:a}));console.log(JSON.stringify(R.length===1?R[0]:R,null,2))}else v.length===1?console.error(i.green(`
528
+ Done! Installed "${v[0].name}" to ${v[0].path}`)):v.length>0&&console.error(`
529
+ ${i.green(`Done! Installed ${v.length} skill(s) successfully.`)}`)}catch(p){if(process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u),e.flags.machine)t?.(),console.log(K("install",W.INSTALL_FAILED,p.message,r,p?.duplicates?{duplicates:p.duplicates}:void 0));else if(e.flags.json){let f={success:!1,error:p.message};p?.duplicates&&(f.duplicates=p.duplicates),console.log(JSON.stringify(f,null,2))}else w(p.message);process.exit(1)}finally{n&&await z(n),t?.()}}function Kf(){console.log(`${i.bold("Usage:")} asm activate <skill> -p <tool> -s <scope> [options]
639
530
 
640
531
  Link a centrally installed library skill into a provider skill folder.
641
532
 
642
- ${l.bold("Options:")}
533
+ ${i.bold("Options:")}
643
534
  -p, --tool <name> Provider to activate into (e.g., claude, codex)
644
535
  -s, --scope <scope> Activation scope: global or project
645
536
  --name <name> Link name to create (default: library directory name)
@@ -647,70 +538,70 @@ ${l.bold("Options:")}
647
538
  --json Output as JSON object
648
539
  -V, --verbose Show debug output
649
540
 
650
- ${l.bold("Examples:")}
541
+ ${i.bold("Examples:")}
651
542
  asm activate brainstorming -p codex -s project
652
- asm activate brainstorming -p claude -s global --json`)}function Tx(){console.log(`${l.bold("Usage:")} asm deactivate <skill> -p <tool> -s <global|project> [options]
543
+ asm activate brainstorming -p claude -s global --json`)}function Jf(){console.log(`${i.bold("Usage:")} asm deactivate <skill> -p <tool> -s <global|project> [options]
653
544
 
654
545
  Remove a centrally activated library skill from a provider skill folder.
655
546
 
656
- ${l.bold("Options:")}
547
+ ${i.bold("Options:")}
657
548
  -p, --tool <name> Provider to deactivate from (e.g., claude, codex)
658
549
  -s, --scope <scope> Activation scope: global or project
659
550
  --json Output as JSON object
660
551
  -V, --verbose Show debug output
661
552
 
662
- ${l.bold("Examples:")}
553
+ ${i.bold("Examples:")}
663
554
  asm deactivate brainstorming -p codex -s project
664
- asm deactivate brainstorming -p claude -s global --json`)}async function Ym(e){if(e.flags.help){Nx();return}let t=e.subcommand;t||($("Missing skill name. Use: asm activate <skill>"),console.error('Run "asm activate --help" for usage.'),process.exit(2)),e.flags.scope==="both"&&($("Activation requires --scope global or --scope project."),process.exit(2));let s=await wt(),i=ni(s,t);i||($(`Library skill "${t}" not found. Run "asm library list".`),process.exit(1)),i.missing&&($(`Library skill "${t}" is missing on disk: ${i.libraryPath}`),process.exit(1));let r=await j(),{provider:n}=await ke(r,e.flags.provider,process.stdin.isTTY),o=e.flags.scope==="global"?n.global:n.project,a=ie(o),c=e.flags.name||i.dirName,u=await cl({libraryPath:i.libraryPath,targetDir:a,activationName:c,force:e.flags.force}),f={name:c,skill:i.dirName,provider:n.name,scope:e.flags.scope,path:u.symlinkPath,target:u.targetPath};if(e.flags.json){console.log(JSON.stringify(f,null,2));return}console.log(`${l.green("\u2713")} activated ${c} (${n.name}/${e.flags.scope}) -> ${u.targetPath}`)}async function zm(e){if(e.flags.help){Tx();return}let t=e.subcommand;t||($("Missing skill name. Use: asm deactivate <skill>"),console.error('Run "asm deactivate --help" for usage.'),process.exit(2)),e.flags.scope==="both"&&($("Deactivation requires --scope global or --scope project."),process.exit(2));let s=await j(),i;try{i=(await ke(s,e.flags.provider,process.stdin.isTTY)).provider}catch(r){let n=r instanceof Error?r.message:String(r);$(n),process.exit(2)}try{let r=e.flags.scope==="global"?i.global:i.project,n=ie(r),o=await ll({targetDir:n,activationName:t,provider:i.name,scope:e.flags.scope});if(e.flags.json){console.log(JSON.stringify(o,null,2));return}console.log(`${l.green("\u2713")} deactivated ${o.name} (${o.provider}/${o.scope}) -> ${o.target}`)}catch(r){let n=r instanceof Error?r.message:String(r);e.flags.json&&(console.log(JSON.stringify({error:n},null,2)),process.exit(1)),$(n),process.exit(1)}}function Ox(){console.log(`${l.bold("Usage:")} asm library <subcommand> [options]
555
+ asm deactivate brainstorming -p claude -s global --json`)}async function ac(e){if(e.flags.help){Kf();return}let t=e.subcommand;t||(w("Missing skill name. Use: asm activate <skill>"),console.error('Run "asm activate --help" for usage.'),process.exit(2)),e.flags.scope==="both"&&(w("Activation requires --scope global or --scope project."),process.exit(2));let r=await He(),s=rr(r,t);s||(w(`Library skill "${t}" not found. Run "asm library list".`),process.exit(1)),s.missing&&(w(`Library skill "${t}" is missing on disk: ${s.libraryPath}`),process.exit(1));let o=await O(),{provider:n}=await me(o,e.flags.provider,process.stdin.isTTY),a=e.flags.scope==="global"?n.global:n.project,l=Q(a),c=e.flags.name||s.dirName,d=await No({libraryPath:s.libraryPath,targetDir:l,activationName:c,force:e.flags.force}),u={name:c,skill:s.dirName,provider:n.name,scope:e.flags.scope,path:d.symlinkPath,target:d.targetPath};if(e.flags.json){console.log(JSON.stringify(u,null,2));return}console.log(`${i.green("\u2713")} activated ${c} (${n.name}/${e.flags.scope}) -> ${d.targetPath}`)}async function lc(e){if(e.flags.help){Jf();return}let t=e.subcommand;t||(w("Missing skill name. Use: asm deactivate <skill>"),console.error('Run "asm deactivate --help" for usage.'),process.exit(2)),e.flags.scope==="both"&&(w("Deactivation requires --scope global or --scope project."),process.exit(2));let r=await O(),s;try{s=(await me(r,e.flags.provider,process.stdin.isTTY)).provider}catch(o){let n=o instanceof Error?o.message:String(o);w(n),process.exit(2)}try{let o=e.flags.scope==="global"?s.global:s.project,n=Q(o),a=await To({targetDir:n,activationName:t,provider:s.name,scope:e.flags.scope});if(e.flags.json){console.log(JSON.stringify(a,null,2));return}console.log(`${i.green("\u2713")} deactivated ${a.name} (${a.provider}/${a.scope}) -> ${a.target}`)}catch(o){let n=o instanceof Error?o.message:String(o);e.flags.json&&(console.log(JSON.stringify({error:n},null,2)),process.exit(1)),w(n),process.exit(1)}}function zf(){console.log(`${i.bold("Usage:")} asm library <subcommand> [options]
665
556
 
666
557
  Manage centrally installed library skills.
667
558
 
668
- ${l.bold("Subcommands:")}
559
+ ${i.bold("Subcommands:")}
669
560
  list List skills installed in the local library
670
561
  update <skill> Update one local library skill
671
562
  update --all Update all local library skills
672
563
 
673
- ${l.bold("Options:")}
564
+ ${i.bold("Options:")}
674
565
  --json Output as JSON
675
566
  -V, --verbose Show debug output
676
567
 
677
- ${l.bold("Examples:")}
678
- asm library list ${l.dim("List local library skills")}
679
- asm library update brainstorming ${l.dim("Update one local library skill")}
680
- asm library update --all --json ${l.dim("Update all and output as JSON")}`)}async function Xm(e){if(e.flags.help){Ox();return}if(e.subcommand==="update"){await Fx(e);return}if(e.subcommand==="list"){let t=await wt();if(e.flags.json){console.log(JSON.stringify(t,null,2));return}Mx(t);return}$("Missing or unknown library subcommand. Use: asm library list or asm library update"),console.error('Run "asm library --help" for usage.'),process.exit(2)}function Mx(e){if(e.length===0){console.log(l.dim("No skills installed in the local library."));return}let t={name:Math.max(4,...e.map(r=>r.name.length)),version:Math.max(7,...e.map(r=>r.version.length)),source:Math.max(6,...e.map(r=>r.source.length)),path:Math.max(4,...e.map(r=>r.skillPath.length)),status:6},s=(r,n,o,a,c)=>[r.padEnd(t.name),n.padEnd(t.version),o.padEnd(t.source),a.padEnd(t.path),c.padEnd(t.status)].join(" "),i=[l.bold(s("Name","Version","Source","Path","Status")),...e.map(r=>s(r.name,r.version,r.source,r.skillPath,r.missing?"missing":"ok"))];console.log(i.join(`
681
- `))}function Dx(e){for(let t of e.results)t.status==="updated"?console.log(`${l.green("\u2713")} ${t.name}: ${t.oldVersion??"unknown"} -> ${t.newVersion??"unknown"}`):t.status==="skipped"?console.log(`${l.yellow("-")} ${t.name}: ${t.reason??"skipped"}`):console.log(`${l.red("x")} ${t.name}: ${t.reason??"failed"}`);console.log(`${e.updatedCount} updated, ${e.skippedCount} skipped, ${e.failedCount} failed`)}async function Fx(e){let t=[...e.positional];!e.flags.all&&t.length===0&&($("Missing skill name. Use: asm library update <skill> or asm library update --all"),process.exit(2)),e.flags.all&&t.length>0&&($("Use either asm library update <skill> or asm library update --all, not both."),process.exit(2));let s=await pl(e.flags.all?null:t);e.flags.json?console.log(JSON.stringify(s,null,2)):Dx(s),s.failedCount>0&&process.exit(1)}function _x(){console.log(`${l.bold("Usage:")} asm config <subcommand>
568
+ ${i.bold("Examples:")}
569
+ asm library list ${i.dim("List local library skills")}
570
+ asm library update brainstorming ${i.dim("Update one local library skill")}
571
+ asm library update --all --json ${i.dim("Update all and output as JSON")}`)}async function cc(e){if(e.flags.help){zf();return}if(e.subcommand==="update"){await Xf(e);return}if(e.subcommand==="list"){let t=await He();if(e.flags.json){console.log(JSON.stringify(t,null,2));return}Yf(t);return}w("Missing or unknown library subcommand. Use: asm library list or asm library update"),console.error('Run "asm library --help" for usage.'),process.exit(2)}function Yf(e){if(e.length===0){console.log(i.dim("No skills installed in the local library."));return}let t={name:Math.max(4,...e.map(o=>o.name.length)),version:Math.max(7,...e.map(o=>o.version.length)),source:Math.max(6,...e.map(o=>o.source.length)),path:Math.max(4,...e.map(o=>o.skillPath.length)),status:6},r=(o,n,a,l,c)=>[o.padEnd(t.name),n.padEnd(t.version),a.padEnd(t.source),l.padEnd(t.path),c.padEnd(t.status)].join(" "),s=[i.bold(r("Name","Version","Source","Path","Status")),...e.map(o=>r(o.name,o.version,o.source,o.skillPath,o.missing?"missing":"ok"))];console.log(s.join(`
572
+ `))}function Zf(e){for(let t of e.results)t.status==="updated"?console.log(`${i.green("\u2713")} ${t.name}: ${t.oldVersion??"unknown"} -> ${t.newVersion??"unknown"}`):t.status==="skipped"?console.log(`${i.yellow("-")} ${t.name}: ${t.reason??"skipped"}`):console.log(`${i.red("x")} ${t.name}: ${t.reason??"failed"}`);console.log(`${e.updatedCount} updated, ${e.skippedCount} skipped, ${e.failedCount} failed`)}async function Xf(e){let t=[...e.positional];!e.flags.all&&t.length===0&&(w("Missing skill name. Use: asm library update <skill> or asm library update --all"),process.exit(2)),e.flags.all&&t.length>0&&(w("Use either asm library update <skill> or asm library update --all, not both."),process.exit(2));let r=await Fo(e.flags.all?null:t);e.flags.json?console.log(JSON.stringify(r,null,2)):Zf(r),r.failedCount>0&&process.exit(1)}function Qf(){console.log(`${i.bold("Usage:")} asm config <subcommand>
682
573
 
683
574
  Manage configuration. Config is stored at ~/.config/agent-skill-manager/.
684
575
 
685
- ${l.bold("Subcommands:")}
576
+ ${i.bold("Subcommands:")}
686
577
  show Print current config as JSON
687
578
  path Print config file path
688
579
  reset Reset config to defaults (with confirmation)
689
580
  edit Open config in $EDITOR
690
581
 
691
- ${l.bold("Options:")}
582
+ ${i.bold("Options:")}
692
583
  -V, --verbose Show debug output
693
584
 
694
- ${l.bold("Examples:")}
695
- asm config show ${l.dim("View current config")}
696
- asm config edit ${l.dim("Edit in $EDITOR")}
697
- asm config reset -y ${l.dim("Reset without confirmation")}`)}async function Zm(e){if(e.flags.help){_x();return}let t=e.subcommand;switch(t||($("Missing subcommand. Use: show, path, reset, or edit."),console.error('Run "asm config --help" for usage.'),process.exit(2)),t){case"show":{let s=await j();console.log(q(s));break}case"path":{console.log(rs());break}case"reset":{if(!e.flags.yes){process.stdin.isTTY||($("Cannot prompt for confirmation in non-interactive mode. Use --yes to skip."),process.exit(2)),process.stderr.write(`${l.bold("Reset config to defaults?")} [y/N] `);let i=await H();i.toLowerCase()!=="y"&&i.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let s=vi();await Jl(s),console.error(l.green("Config reset to defaults."));break}case"edit":{let s=process.env.VISUAL||process.env.EDITOR||"vi",[i,r]=dc(s),n=rs();await j();let{spawn:o}=await import("child_process");await new Promise((a,c)=>{let u=o(i,[...r,n],{stdio:"inherit"});u.on("close",()=>a()),u.on("error",c)});break}default:$(`Unknown config subcommand: "${t}". Use: show, path, reset, or edit.`),process.exit(2)}}function Qm(e){let t=e.filter(s=>s.provider!=="plugin").map(s=>({name:s.name,version:s.version,dirName:s.dirName,provider:s.provider,scope:s.scope,path:s.path,isSymlink:s.isSymlink,symlinkTarget:s.symlinkTarget,effort:s.effort}));return{version:1,exportedAt:new Date().toISOString(),skills:t}}import{readFile as li,readdir as jx,access as ah,mkdir as Bx,cp as $l,rm as eh,rename as th,realpath as xl,stat as El}from"fs/promises";import{join as Pl,basename as qx,resolve as sh}from"path";function Ux(e){let t=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Manifest must be a JSON object."]};let s=e;if(s.version!==1&&t.push(`Unsupported manifest version: ${JSON.stringify(s.version)}. Expected 1.`),typeof s.exportedAt!="string"&&t.push("Missing or invalid 'exportedAt' field."),!Array.isArray(s.skills))return t.push("Missing or invalid 'skills' array."),{valid:!1,errors:t};for(let i=0;i<s.skills.length;i++){let r=s.skills[i];if(typeof r!="object"||r===null){t.push(`skills[${i}]: must be an object.`);continue}let n=r;(typeof n.name!="string"||!n.name)&&t.push(`skills[${i}]: missing or empty 'name'.`),(typeof n.dirName!="string"||!n.dirName)&&t.push(`skills[${i}]: missing or empty 'dirName'.`),(typeof n.provider!="string"||!n.provider)&&t.push(`skills[${i}]: missing or empty 'provider'.`),n.scope!=="global"&&n.scope!=="project"&&t.push(`skills[${i}]: invalid 'scope' "${String(n.scope)}". Must be "global" or "project".`)}return{valid:t.length===0,errors:t}}async function lh(e){let t;try{t=await li(e,"utf-8")}catch(r){throw r?.code==="ENOENT"?new Error(`Manifest file not found: ${e}`,{cause:r}):new Error(`Failed to read manifest file: ${r.message}`,{cause:r})}let s;try{s=JSON.parse(t)}catch{throw new Error("Manifest file is not valid JSON.")}let i=Ux(s);if(!i.valid)throw new Error(`Invalid manifest:
698
- ${i.errors.join(`
699
- `)}`);return s}async function Vx(e){try{return await ah(e),!0}catch{return!1}}async function ih(e,t){let s,i;try{[s,i]=await Promise.all([xl(e),xl(t)])}catch{s=sh(e),i=sh(t)}return process.platform==="win32"?s.toLowerCase()===i.toLowerCase():s===i}async function ci(e){let t=new Map,s=new Set;async function i(r,n){let o=await xl(r),a=process.platform==="win32"?o.toLowerCase():o;if(s.has(a))return;s.add(a);let c=await jx(r,{withFileTypes:!0});for(let u of c){if(u.name===".git")continue;let f=n?`${n}/${u.name}`:u.name,d=Pl(r,u.name);if(u.isDirectory())await i(d,f);else if(u.isFile())t.set(f,d);else try{(await El(d)).isDirectory()?await i(d,f):t.set(f,d)}catch{t.set(f,d)}}s.delete(a)}return await i(e,""),t}async function Kx(e,t){try{let[s,i]=await Promise.all([ci(e),ci(t)]);if(s.size!==i.size)return!1;for(let[r,n]of s){let o=i.get(r);if(!o)return!1;let[a,c]=await Promise.all([li(n),li(o)]);if(!a.equals(c))return!1}return!0}catch{return!1}}async function rh(e){try{let t=await ci(e),s=0;for(let i of t.values())try{let r=await El(i);r.mtimeMs>s&&(s=r.mtimeMs)}catch{}return s===0&&(s=(await El(e)).mtimeMs),s}catch{return 0}}async function Gx(e,t,s){let[i,r]=await Promise.all([rh(s),rh(t)]),o=i===0||r===0||Math.abs(i-r)<=2e3?"same":i>r?"local":"imported";return{skillName:e.name,provider:e.provider,scope:e.scope,targetDir:s,sourcePath:t,localModified:new Date(i).toISOString(),importedModified:new Date(r).toISOString(),newer:o}}async function Cl(e){let[t,s]=await Promise.all([ci(e.targetDir),ci(e.sourcePath)]),i=Array.from(new Set([...t.keys(),...s.keys()])).sort(),r=[];for(let n of i){let o=t.get(n),a=s.get(n);if(!a){r.push(`only in local: ${n}`);continue}if(!o){r.push(`only in imported: ${n}`);continue}let c=n.includes(".")?`.${n.split(".").pop().toLowerCase()}`:"";try{let[u,f]=await Promise.all([li(o),li(a)]);if(u.equals(f))continue;if(Xl.has(c)){r.push(`differs (binary): ${n}`);continue}if(u.length>kn||f.length>kn){r.push(`differs (too large to diff): ${n}`);continue}let d=Kr(u.toString("utf-8"),f.toString("utf-8"),n);d&&r.push(d)}catch{r.push(`differs (unreadable): ${n}`)}}return r.join(`
700
- `)}async function nh(e,t){let s=`${e}.import-backup-${Date.now()}`;await th(e,s);try{await t(),await eh(s,{recursive:!0,force:!0})}catch(i){try{await eh(e,{recursive:!0,force:!0}),await th(s,e)}catch{}throw i}}function Hx(e,t){return e.providers.find(s=>s.name===t&&s.enabled)}function Jx(e,t,s,i){let r=Hx(e,t);if(!r)return null;let n=s==="global"?r.global:r.project,o=ie(n),a=qx(i);return!a||a==="."||a===".."?null:Pl(o,a)}function oh(e,t){let s=e.find(i=>i.dirName===t.dirName&&i.provider===t.provider);return s||e.find(i=>i.dirName===t.dirName)||null}async function ch(e,t,s){let i=s?.config??await j(),r=s?.installedSkills??await K(i,"both"),n=[];for(let f of e.skills){if(t.scopeFilter!=="both"&&f.scope!==t.scopeFilter){L(`import: skipping "${f.name}" \u2014 scope "${f.scope}" filtered out`);continue}let d=Jx(i,f.provider,f.scope,f.dirName);if(!d){n.push({skillName:f.name,provider:f.provider,scope:f.scope,status:"failed",reason:`Provider "${f.provider}" not found or not enabled.`});continue}let p=await Vx(d);if(p&&!t.force&&!t.dryRun){let g=oh(r,f);if(!g||await ih(g.realPath,d)||await Kx(g.realPath,d)){n.push({skillName:f.name,provider:f.provider,scope:f.scope,status:"skipped",reason:"Already installed.",path:d});continue}let h=await Gx(f,g.realPath,d),y=t.onConflict?await t.onConflict(h):"skip";if(y==="use-imported")try{await nh(d,()=>$l(g.realPath,d,{recursive:!0})),L(`import: conflict resolved, copied "${f.name}" from ${g.realPath} to ${d}`),n.push({skillName:f.name,provider:f.provider,scope:f.scope,status:"installed",reason:"Conflict resolved: used imported version.",path:d,conflict:h})}catch(b){n.push({skillName:f.name,provider:f.provider,scope:f.scope,status:"failed",reason:`Copy failed: ${b.message}`,conflict:h})}else{let b=y==="keep-local"?"Conflict: kept local version.":t.onConflict?"Conflict: skipped.":h.newer==="local"?"Conflict: local version is newer. Use --force to overwrite.":h.newer==="imported"?"Conflict: imported version is newer. Use --force to overwrite.":"Conflict: contents differ. Use --force to overwrite.";n.push({skillName:f.name,provider:f.provider,scope:f.scope,status:"skipped",reason:b,path:d,conflict:h})}continue}if(p&&!t.force){n.push({skillName:f.name,provider:f.provider,scope:f.scope,status:"skipped",reason:"Already installed.",path:d});continue}if(t.dryRun){n.push({skillName:f.name,provider:f.provider,scope:f.scope,status:"dry-run",reason:p?"Would overwrite (--force).":"Would install.",path:d});continue}let m=oh(r,f);if(!m){n.push({skillName:f.name,provider:f.provider,scope:f.scope,status:"failed",reason:"No installed source found. Install the skill first with: asm install <source>"});continue}if(p&&await ih(m.realPath,d)){n.push({skillName:f.name,provider:f.provider,scope:f.scope,status:"skipped",reason:"Already installed.",path:d});continue}try{await Bx(Pl(d,".."),{recursive:!0});let g=async()=>{if(f.isSymlink&&f.symlinkTarget)try{await ah(f.symlinkTarget),await Ve(f.symlinkTarget,d),L(`import: symlinked "${f.name}" -> ${f.symlinkTarget} at ${d}`)}catch{await $l(m.realPath,d,{recursive:!0}),L(`import: symlink target unreachable, copied "${f.name}" from ${m.realPath} to ${d}`)}else await $l(m.realPath,d,{recursive:!0}),L(`import: copied "${f.name}" from ${m.realPath} to ${d}`)};p?await nh(d,g):await g(),n.push({skillName:f.name,provider:f.provider,scope:f.scope,status:"installed",path:d})}catch(g){n.push({skillName:f.name,provider:f.provider,scope:f.scope,status:"failed",reason:`Copy failed: ${g.message}`})}}let o=n.filter(f=>f.status==="installed").length,a=n.filter(f=>f.status==="skipped").length,c=n.filter(f=>f.status==="failed").length,u=n.filter(f=>f.conflict!==void 0).length;return{total:n.length,installed:o,skipped:a,failed:c,conflicts:u,results:n}}function Wx(){console.log(`${l.bold("Usage:")} asm export [options]
585
+ ${i.bold("Examples:")}
586
+ asm config show ${i.dim("View current config")}
587
+ asm config edit ${i.dim("Edit in $EDITOR")}
588
+ asm config reset -y ${i.dim("Reset without confirmation")}`)}async function dc(e){if(e.flags.help){Qf();return}let t=e.subcommand;switch(t||(w("Missing subcommand. Use: show, path, reset, or edit."),console.error('Run "asm config --help" for usage.'),process.exit(2)),t){case"show":{let r=await O();console.log(j(r));break}case"path":{console.log(Ct());break}case"reset":{if(!e.flags.yes){process.stdin.isTTY||(w("Cannot prompt for confirmation in non-interactive mode. Use --yes to skip."),process.exit(2)),process.stderr.write(`${i.bold("Reset config to defaults?")} [y/N] `);let s=await G();s.toLowerCase()!=="y"&&s.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let r=wr();await An(r),console.error(i.green("Config reset to defaults."));break}case"edit":{let r=process.env.VISUAL||process.env.EDITOR||"vi",[s,o]=Kn(r),n=Ct();await O();let{spawn:a}=await import("child_process");await new Promise((l,c)=>{let d=a(s,[...o,n],{stdio:"inherit"});d.on("close",()=>l()),d.on("error",c)});break}default:w(`Unknown config subcommand: "${t}". Use: show, path, reset, or edit.`),process.exit(2)}}function uc(e){let t=e.filter(r=>r.provider!=="plugin").map(r=>({name:r.name,version:r.version,dirName:r.dirName,provider:r.provider,scope:r.scope,path:r.path,isSymlink:r.isSymlink,symlinkTarget:r.symlinkTarget,effort:r.effort}));return{version:1,exportedAt:new Date().toISOString(),skills:t}}import{readFile as ar,readdir as eg,access as wc,mkdir as tg,cp as en,rm as pc,rename as mc,realpath as tn,stat as rn}from"fs/promises";import{join as sn,basename as rg,resolve as fc}from"path";function sg(e){let t=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Manifest must be a JSON object."]};let r=e;if(r.version!==1&&t.push(`Unsupported manifest version: ${JSON.stringify(r.version)}. Expected 1.`),typeof r.exportedAt!="string"&&t.push("Missing or invalid 'exportedAt' field."),!Array.isArray(r.skills))return t.push("Missing or invalid 'skills' array."),{valid:!1,errors:t};for(let s=0;s<r.skills.length;s++){let o=r.skills[s];if(typeof o!="object"||o===null){t.push(`skills[${s}]: must be an object.`);continue}let n=o;(typeof n.name!="string"||!n.name)&&t.push(`skills[${s}]: missing or empty 'name'.`),(typeof n.dirName!="string"||!n.dirName)&&t.push(`skills[${s}]: missing or empty 'dirName'.`),(typeof n.provider!="string"||!n.provider)&&t.push(`skills[${s}]: missing or empty 'provider'.`),n.scope!=="global"&&n.scope!=="project"&&t.push(`skills[${s}]: invalid 'scope' "${String(n.scope)}". Must be "global" or "project".`)}return{valid:t.length===0,errors:t}}async function kc(e){let t;try{t=await ar(e,"utf-8")}catch(o){throw o?.code==="ENOENT"?new Error(`Manifest file not found: ${e}`,{cause:o}):new Error(`Failed to read manifest file: ${o.message}`,{cause:o})}let r;try{r=JSON.parse(t)}catch{throw new Error("Manifest file is not valid JSON.")}let s=sg(r);if(!s.valid)throw new Error(`Invalid manifest:
589
+ ${s.errors.join(`
590
+ `)}`);return r}async function og(e){try{return await wc(e),!0}catch{return!1}}async function gc(e,t){let r,s;try{[r,s]=await Promise.all([tn(e),tn(t)])}catch{r=fc(e),s=fc(t)}return process.platform==="win32"?r.toLowerCase()===s.toLowerCase():r===s}async function lr(e){let t=new Map,r=new Set;async function s(o,n){let a=await tn(o),l=process.platform==="win32"?a.toLowerCase():a;if(r.has(l))return;r.add(l);let c=await eg(o,{withFileTypes:!0});for(let d of c){if(d.name===".git")continue;let u=n?`${n}/${d.name}`:d.name,p=sn(o,d.name);if(d.isDirectory())await s(p,u);else if(d.isFile())t.set(u,p);else try{(await rn(p)).isDirectory()?await s(p,u):t.set(u,p)}catch{t.set(u,p)}}r.delete(l)}return await s(e,""),t}async function ng(e,t){try{let[r,s]=await Promise.all([lr(e),lr(t)]);if(r.size!==s.size)return!1;for(let[o,n]of r){let a=s.get(o);if(!a)return!1;let[l,c]=await Promise.all([ar(n),ar(a)]);if(!l.equals(c))return!1}return!0}catch{return!1}}async function hc(e){try{let t=await lr(e),r=0;for(let s of t.values())try{let o=await rn(s);o.mtimeMs>r&&(r=o.mtimeMs)}catch{}return r===0&&(r=(await rn(e)).mtimeMs),r}catch{return 0}}async function ig(e,t,r){let[s,o]=await Promise.all([hc(r),hc(t)]),a=s===0||o===0||Math.abs(s-o)<=2e3?"same":s>o?"local":"imported";return{skillName:e.name,provider:e.provider,scope:e.scope,targetDir:r,sourcePath:t,localModified:new Date(s).toISOString(),importedModified:new Date(o).toISOString(),newer:a}}async function on(e){let[t,r]=await Promise.all([lr(e.targetDir),lr(e.sourcePath)]),s=Array.from(new Set([...t.keys(),...r.keys()])).sort(),o=[];for(let n of s){let a=t.get(n),l=r.get(n);if(!l){o.push(`only in local: ${n}`);continue}if(!a){o.push(`only in imported: ${n}`);continue}let c=n.includes(".")?`.${n.split(".").pop().toLowerCase()}`:"";try{let[d,u]=await Promise.all([ar(a),ar(l)]);if(d.equals(u))continue;if(Dn.has(c)){o.push(`differs (binary): ${n}`);continue}if(d.length>Ps||u.length>Ps){o.push(`differs (too large to diff): ${n}`);continue}let p=Vr(d.toString("utf-8"),u.toString("utf-8"),n);p&&o.push(p)}catch{o.push(`differs (unreadable): ${n}`)}}return o.join(`
591
+ `)}async function yc(e,t){let r=`${e}.import-backup-${Date.now()}`;await mc(e,r);try{await t(),await pc(r,{recursive:!0,force:!0})}catch(s){try{await pc(e,{recursive:!0,force:!0}),await mc(r,e)}catch{}throw s}}function ag(e,t){return e.providers.find(r=>r.name===t&&r.enabled)}function lg(e,t,r,s){let o=ag(e,t);if(!o)return null;let n=r==="global"?o.global:o.project,a=Q(n),l=rg(s);return!l||l==="."||l===".."?null:sn(a,l)}function bc(e,t){let r=e.find(s=>s.dirName===t.dirName&&s.provider===t.provider);return r||e.find(s=>s.dirName===t.dirName)||null}async function vc(e,t,r){let s=r?.config??await O(),o=r?.installedSkills??await V(s,"both"),n=[];for(let u of e.skills){if(t.scopeFilter!=="both"&&u.scope!==t.scopeFilter){P(`import: skipping "${u.name}" \u2014 scope "${u.scope}" filtered out`);continue}let p=lg(s,u.provider,u.scope,u.dirName);if(!p){n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"failed",reason:`Provider "${u.provider}" not found or not enabled.`});continue}let f=await og(p);if(f&&!t.force&&!t.dryRun){let g=bc(o,u);if(!g||await gc(g.realPath,p)||await ng(g.realPath,p)){n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"skipped",reason:"Already installed.",path:p});continue}let h=await ig(u,g.realPath,p),y=t.onConflict?await t.onConflict(h):"skip";if(y==="use-imported")try{await yc(p,()=>en(g.realPath,p,{recursive:!0})),P(`import: conflict resolved, copied "${u.name}" from ${g.realPath} to ${p}`),n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"installed",reason:"Conflict resolved: used imported version.",path:p,conflict:h})}catch(b){n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"failed",reason:`Copy failed: ${b.message}`,conflict:h})}else{let b=y==="keep-local"?"Conflict: kept local version.":t.onConflict?"Conflict: skipped.":h.newer==="local"?"Conflict: local version is newer. Use --force to overwrite.":h.newer==="imported"?"Conflict: imported version is newer. Use --force to overwrite.":"Conflict: contents differ. Use --force to overwrite.";n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"skipped",reason:b,path:p,conflict:h})}continue}if(f&&!t.force){n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"skipped",reason:"Already installed.",path:p});continue}if(t.dryRun){n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"dry-run",reason:f?"Would overwrite (--force).":"Would install.",path:p});continue}let m=bc(o,u);if(!m){n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"failed",reason:"No installed source found. Install the skill first with: asm install <source>"});continue}if(f&&await gc(m.realPath,p)){n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"skipped",reason:"Already installed.",path:p});continue}try{await tg(sn(p,".."),{recursive:!0});let g=async()=>{if(u.isSymlink&&u.symlinkTarget)try{await wc(u.symlinkTarget),await Ae(u.symlinkTarget,p),P(`import: symlinked "${u.name}" -> ${u.symlinkTarget} at ${p}`)}catch{await en(m.realPath,p,{recursive:!0}),P(`import: symlink target unreachable, copied "${u.name}" from ${m.realPath} to ${p}`)}else await en(m.realPath,p,{recursive:!0}),P(`import: copied "${u.name}" from ${m.realPath} to ${p}`)};f?await yc(p,g):await g(),n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"installed",path:p})}catch(g){n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"failed",reason:`Copy failed: ${g.message}`})}}let a=n.filter(u=>u.status==="installed").length,l=n.filter(u=>u.status==="skipped").length,c=n.filter(u=>u.status==="failed").length,d=n.filter(u=>u.conflict!==void 0).length;return{total:n.length,installed:a,skipped:l,failed:c,conflicts:d,results:n}}function cg(){console.log(`${i.bold("Usage:")} asm export [options]
701
592
 
702
593
  Export skill inventory as a portable JSON manifest. Useful for backup,
703
594
  sharing, or scripting.
704
595
 
705
- ${l.bold("Options:")}
596
+ ${i.bold("Options:")}
706
597
  -s, --scope <s> Filter: global, project, or both (default: both)
707
598
  --no-color Disable ANSI colors
708
599
  -V, --verbose Show debug output
709
600
 
710
- ${l.bold("Examples:")}
711
- asm export ${l.dim("Export all skills")}
712
- asm export -s global ${l.dim("Export global skills only")}
713
- asm export > skills.json ${l.dim("Save to file")}`)}async function uh(e){if(e.flags.help){Wx();return}let t=await j(),s=await K(t,e.flags.scope),i=Qm(s);console.log(JSON.stringify(i,null,2))}function Yx(){console.log(`${l.bold("Usage:")} asm import <file> [options]
601
+ ${i.bold("Examples:")}
602
+ asm export ${i.dim("Export all skills")}
603
+ asm export -s global ${i.dim("Export global skills only")}
604
+ asm export > skills.json ${i.dim("Save to file")}`)}async function Sc(e){if(e.flags.help){cg();return}let t=await O(),r=await V(t,e.flags.scope),s=uc(r);console.log(JSON.stringify(s,null,2))}function dg(){console.log(`${i.bold("Usage:")} asm import <file> [options]
714
605
 
715
606
  Import skills from a previously exported JSON manifest. Recreates skill
716
607
  installations based on the manifest metadata.
@@ -723,7 +614,7 @@ overwrites all conflicts without asking. Skills whose source files cannot
723
614
  be found locally are reported as failed \u2014 install them first with
724
615
  "asm install".
725
616
 
726
- ${l.bold("Options:")}
617
+ ${i.bold("Options:")}
727
618
  -s, --scope <s> Filter: global, project, or both (default: both)
728
619
  -f, --force Overwrite existing skills without conflict prompts
729
620
  --diff Show unified diffs (cannot be combined with --force)
@@ -732,20 +623,20 @@ ${l.bold("Options:")}
732
623
  --no-color Disable ANSI colors
733
624
  -V, --verbose Show debug output
734
625
 
735
- ${l.bold("Examples:")}
736
- asm import skills.json ${l.dim("Import from manifest")}
737
- asm import skills.json --diff ${l.dim("Show diffs for conflicting skills")}
738
- asm import skills.json --force ${l.dim("Overwrite existing skills")}
739
- asm import skills.json -s global ${l.dim("Import only global skills")}
740
- asm export > backup.json ${l.dim("Export first, then import later")}
741
- asm import backup.json ${l.dim("Restore from backup")}`)}async function dh(e,t={}){let{showDiff:s=!1,readAnswer:i=H,renderDiff:r=Cl,writeLine:n=console.error,writePrompt:o=u=>process.stderr.write(u)}=t,a=u=>e.newer===u?` ${l.green("(newer)")}`:e.newer==="same"?"":` ${l.dim("(older)")}`;n(""),n(`${l.bold("Conflict:")} ${e.skillName} (${e.provider}/${e.scope})`),n(` local: ${e.localModified}${a("local")}`),n(` imported: ${e.importedModified}${a("imported")}`);let c=!1;if(s){let u=await r(e);n(u?`
626
+ ${i.bold("Examples:")}
627
+ asm import skills.json ${i.dim("Import from manifest")}
628
+ asm import skills.json --diff ${i.dim("Show diffs for conflicting skills")}
629
+ asm import skills.json --force ${i.dim("Overwrite existing skills")}
630
+ asm import skills.json -s global ${i.dim("Import only global skills")}
631
+ asm export > backup.json ${i.dim("Export first, then import later")}
632
+ asm import backup.json ${i.dim("Restore from backup")}`)}async function $c(e,t={}){let{showDiff:r=!1,readAnswer:s=G,renderDiff:o=on,writeLine:n=console.error,writePrompt:a=d=>process.stderr.write(d)}=t,l=d=>e.newer===d?` ${i.green("(newer)")}`:e.newer==="same"?"":` ${i.dim("(older)")}`;n(""),n(`${i.bold("Conflict:")} ${e.skillName} (${e.provider}/${e.scope})`),n(` local: ${e.localModified}${l("local")}`),n(` imported: ${e.importedModified}${l("imported")}`);let c=!1;if(r){let d=await o(e);n(d?`
633
+ ${d}
634
+ `:" (no textual differences found)"),c=!0}for(;;){a(` [k] keep local [u] use imported [s] skip${c?"":" [d] show diff"} ${i.dim("[s]")} `);let d=(await s()).trim().toLowerCase();if(d==="k"||d==="keep")return"keep-local";if(d==="u"||d==="use")return"use-imported";if(d===""||d==="s"||d==="skip")return"skip";if(d==="d"||d==="diff"){let u=await o(e);n(u?`
742
635
  ${u}
743
- `:" (no textual differences found)"),c=!0}for(;;){o(` [k] keep local [u] use imported [s] skip${c?"":" [d] show diff"} ${l.dim("[s]")} `);let u=(await i()).trim().toLowerCase();if(u==="k"||u==="keep")return"keep-local";if(u==="u"||u==="use")return"use-imported";if(u===""||u==="s"||u==="skip")return"skip";if(u==="d"||u==="diff"){let f=await r(e);n(f?`
744
- ${f}
745
- `:" (no textual differences found)"),c=!0}}}async function fh(e,t=Cl,s=console.error){for(let i of e){if(!i.conflict)continue;let r=await t(i.conflict);s(`
746
- ${l.bold(`Conflict diff: ${i.skillName} (${i.provider}/${i.scope})`)} ${l.dim("local -> imported")}`),s(r||" (no textual differences found)")}}async function ph(e){if(e.flags.help){Yx();return}let t=e.subcommand;t||($("Missing required argument: <file>"),console.error('Run "asm import --help" for usage.'),process.exit(2)),e.flags.force&&e.flags.diff&&($("--force and --diff cannot be used together. Run without --force to inspect conflicts, or omit --diff to overwrite them."),process.exit(2));let{resolve:s}=await import("path"),i=s(t),r;try{r=await lh(i)}catch(d){$(d.message),process.exit(1)}let n=r.skills.length;if(n===0){e.flags.json?console.log(JSON.stringify({total:0,installed:0,skipped:0,failed:0,conflicts:0,results:[]},null,2)):console.log("Manifest contains no skills. Nothing to import.");return}let o=e.flags.scope==="both"?"all scopes":e.flags.scope;if(console.error(`${l.bold("Importing")} ${n} skill${n>1?"s":""} from ${l.dim(i)}`),console.error(` Scope filter: ${o}`),e.flags.force&&console.error(` ${l.yellow("Force mode: existing skills will be overwritten")}`),!e.flags.yes&&process.stdin.isTTY){process.stderr.write(`
747
- ${l.bold("Proceed?")} [y/N] `);let d=await H();d.toLowerCase()!=="y"&&d.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let a=!e.flags.force&&!e.flags.yes&&!!process.stdin.isTTY,c=e.flags.diff,u=await ch(r,{force:e.flags.force,dryRun:!1,scopeFilter:e.flags.scope,onConflict:a?d=>dh(d,{showDiff:c}):void 0});if(c&&!a&&await fh(u.results),e.flags.json){console.log(JSON.stringify(u,null,2));return}if(u.total===0){console.error(`
748
- Nothing to import after scope filtering (--scope ${e.flags.scope}). All skills in the manifest were excluded.`);return}console.error("");for(let d of u.results){let p=d.status==="installed"?l.green("+++"):d.status==="skipped"?l.yellow("---"):d.status==="dry-run"?l.cyan("~~~"):l.red("!!!"),m=d.reason?` ${l.dim(d.reason)}`:"",g=d.path?` ${l.dim(d.path)}`:"";console.error(` ${p} ${d.skillName} (${d.provider}/${d.scope})${m}${g}`)}console.error("");let f=u.conflicts>0?`, ${l.yellow(String(u.conflicts))} conflicts`:"";console.error(`${l.bold("Summary:")} ${u.total} total, ${l.green(String(u.installed))} installed, ${l.yellow(String(u.skipped))} skipped, ${l.red(String(u.failed))} failed${f}`),u.conflicts>0&&!a&&!e.flags.force&&console.error(l.dim("Conflicts were skipped. Re-run in a terminal to resolve each one, add --diff to inspect, or --force to overwrite all.")),u.failed>0&&(process.exitCode=1)}import{mkdir as zx,writeFile as Xx,access as Zx}from"fs/promises";import{join as Qx}from"path";function e0(e){return`---
636
+ `:" (no textual differences found)"),c=!0}}}async function xc(e,t=on,r=console.error){for(let s of e){if(!s.conflict)continue;let o=await t(s.conflict);r(`
637
+ ${i.bold(`Conflict diff: ${s.skillName} (${s.provider}/${s.scope})`)} ${i.dim("local -> imported")}`),r(o||" (no textual differences found)")}}async function Pc(e){if(e.flags.help){dg();return}let t=e.subcommand;t||(w("Missing required argument: <file>"),console.error('Run "asm import --help" for usage.'),process.exit(2)),e.flags.force&&e.flags.diff&&(w("--force and --diff cannot be used together. Run without --force to inspect conflicts, or omit --diff to overwrite them."),process.exit(2));let{resolve:r}=await import("path"),s=r(t),o;try{o=await kc(s)}catch(p){w(p.message),process.exit(1)}let n=o.skills.length;if(n===0){e.flags.json?console.log(JSON.stringify({total:0,installed:0,skipped:0,failed:0,conflicts:0,results:[]},null,2)):console.log("Manifest contains no skills. Nothing to import.");return}let a=e.flags.scope==="both"?"all scopes":e.flags.scope;if(console.error(`${i.bold("Importing")} ${n} skill${n>1?"s":""} from ${i.dim(s)}`),console.error(` Scope filter: ${a}`),e.flags.force&&console.error(` ${i.yellow("Force mode: existing skills will be overwritten")}`),!e.flags.yes&&process.stdin.isTTY){process.stderr.write(`
638
+ ${i.bold("Proceed?")} [y/N] `);let p=await G();p.toLowerCase()!=="y"&&p.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let l=!e.flags.force&&!e.flags.yes&&!!process.stdin.isTTY,c=e.flags.diff,d=await vc(o,{force:e.flags.force,dryRun:!1,scopeFilter:e.flags.scope,onConflict:l?p=>$c(p,{showDiff:c}):void 0});if(c&&!l&&await xc(d.results),e.flags.json){console.log(JSON.stringify(d,null,2));return}if(d.total===0){console.error(`
639
+ Nothing to import after scope filtering (--scope ${e.flags.scope}). All skills in the manifest were excluded.`);return}console.error("");for(let p of d.results){let f=p.status==="installed"?i.green("+++"):p.status==="skipped"?i.yellow("---"):p.status==="dry-run"?i.cyan("~~~"):i.red("!!!"),m=p.reason?` ${i.dim(p.reason)}`:"",g=p.path?` ${i.dim(p.path)}`:"";console.error(` ${f} ${p.skillName} (${p.provider}/${p.scope})${m}${g}`)}console.error("");let u=d.conflicts>0?`, ${i.yellow(String(d.conflicts))} conflicts`:"";console.error(`${i.bold("Summary:")} ${d.total} total, ${i.green(String(d.installed))} installed, ${i.yellow(String(d.skipped))} skipped, ${i.red(String(d.failed))} failed${u}`),d.conflicts>0&&!l&&!e.flags.force&&console.error(i.dim("Conflicts were skipped. Re-run in a terminal to resolve each one, add --diff to inspect, or --force to overwrite all.")),d.failed>0&&(process.exitCode=1)}import{mkdir as ug,writeFile as pg,access as mg}from"fs/promises";import{join as fg}from"path";function gg(e){return`---
749
640
  name: ${e}
750
641
  description: ""
751
642
  license: ""
@@ -766,33 +657,33 @@ as instructions for when and how to use this skill.
766
657
  ## Instructions
767
658
 
768
659
  - Step-by-step instructions for the agent
769
- `}async function mh(e,t){await zx(t,{recursive:!0});let s=Qx(t,"SKILL.md"),i=e0(e);await Xx(s,i,"utf-8")}async function hh(e){try{return await Zx(e),!0}catch{return!1}}function t0(){console.log(`${l.bold("Usage:")} asm init <name> [options]
660
+ `}async function Rc(e,t){await ug(t,{recursive:!0});let r=fg(t,"SKILL.md"),s=gg(e);await pg(r,s,"utf-8")}async function Ec(e){try{return await mg(e),!0}catch{return!1}}function hg(){console.log(`${i.bold("Usage:")} asm init <name> [options]
770
661
 
771
662
  Scaffold a new skill directory with a SKILL.md template. Creates a
772
663
  ready-to-edit skill in the target tool's skill folder.
773
664
 
774
- ${l.bold("Options:")}
665
+ ${i.bold("Options:")}
775
666
  -p, --tool <name> Target tool (claude, codex, openclaw, agents)
776
667
  --path <dir> Scaffold in specified directory instead of provider path
777
668
  -f, --force Overwrite if skill already exists
778
669
  --no-color Disable ANSI colors
779
670
  -V, --verbose Show debug output
780
671
 
781
- ${l.bold("Examples:")}
782
- asm init my-skill ${l.dim("Scaffold (interactive tool)")}
783
- asm init my-skill -p claude ${l.dim("Scaffold in Claude Code")}
784
- asm init my-skill --path ./skills ${l.dim("Scaffold in custom directory")}`)}async function gh(e){if(e.flags.help){t0();return}let t=e.subcommand;t||($("Missing required argument: <name>"),console.error('Run "asm init --help" for usage.'),process.exit(2));let s=be(t),i;if(e.flags.path){let{resolve:r}=await import("path");i=r(e.flags.path)}else{let r=await j(),{provider:n}=await ke(r,e.flags.provider,!!process.stdin.isTTY),{join:o}=await import("path"),{resolveProviderPath:a}=await import("./config-PQRMSV7F.js"),c=a(r.providers.find(u=>u.name===n.name).global);i=o(c,s)}if(await hh(i)&&!e.flags.force){process.stdin.isTTY||($(`Directory already exists: ${i}. Use --force to overwrite.`),process.exit(2)),process.stderr.write(`${l.yellow(`Directory already exists: ${i}`)}
785
- ${l.bold("Overwrite?")} [y/N] `);let r=await H();r.toLowerCase()!=="y"&&r.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}await mh(s,i),console.error(l.green(`Done! Created skill "${s}" at ${i}`))}function s0(){console.log(`${l.bold("Usage:")} asm stats [subcommand] [options]
672
+ ${i.bold("Examples:")}
673
+ asm init my-skill ${i.dim("Scaffold (interactive tool)")}
674
+ asm init my-skill -p claude ${i.dim("Scaffold in Claude Code")}
675
+ asm init my-skill --path ./skills ${i.dim("Scaffold in custom directory")}`)}async function Ic(e){if(e.flags.help){hg();return}let t=e.subcommand;t||(w("Missing required argument: <name>"),console.error('Run "asm init --help" for usage.'),process.exit(2));let r=ue(t),s;if(e.flags.path){let{resolve:o}=await import("path");s=o(e.flags.path)}else{let o=await O(),{provider:n}=await me(o,e.flags.provider,!!process.stdin.isTTY),{join:a}=await import("path"),{resolveProviderPath:l}=await import("./config-JPFUVYBM.js"),c=l(o.providers.find(d=>d.name===n.name).global);s=a(c,r)}if(await Ec(s)&&!e.flags.force){process.stdin.isTTY||(w(`Directory already exists: ${s}. Use --force to overwrite.`),process.exit(2)),process.stderr.write(`${i.yellow(`Directory already exists: ${s}`)}
676
+ ${i.bold("Overwrite?")} [y/N] `);let o=await G();o.toLowerCase()!=="y"&&o.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}await Rc(r,s),console.error(i.green(`Done! Created skill "${r}" at ${s}`))}function yg(){console.log(`${i.bold("Usage:")} asm stats [subcommand] [options]
786
677
 
787
678
  Show aggregate skill metrics with provider distribution charts,
788
679
  scope breakdown, disk usage, resident context cost, and duplicate summary.
789
680
 
790
- ${l.bold("Subcommands:")}
681
+ ${i.bold("Subcommands:")}
791
682
  repo <owner/repo> Show per-repo stats from the skill index
792
683
  author <owner> Show per-author stats from the skill index
793
684
  index Show index-wide statistics
794
685
 
795
- ${l.bold("Options:")}
686
+ ${i.bold("Options:")}
796
687
  --tokens Attention budget: resident vs body tokens per tool/scope
797
688
  --json Output as JSON
798
689
  --machine Output in stable machine-readable v1 envelope format
@@ -800,54 +691,54 @@ ${l.bold("Options:")}
800
691
  --no-color Disable ANSI colors
801
692
  -V, --verbose Show debug output
802
693
 
803
- ${l.bold("Examples:")}
804
- asm stats ${l.dim("Show installed skills dashboard")}
805
- asm stats --tokens ${l.dim("Resident context cost per tool")}
806
- asm stats --tokens --json ${l.dim("Attention budget as JSON")}
807
- asm stats -s global ${l.dim("Global skills only")}
808
- asm stats --json ${l.dim("Output raw data as JSON")}
809
- asm stats --machine ${l.dim("Machine-readable v1 envelope output")}
810
- asm stats repo anthropics/skills ${l.dim("Show indexed repo stats")}
811
- asm stats author luongnv89 ${l.dim("Show indexed author stats")}
812
- asm stats index ${l.dim("Show index-wide stats")}`)}async function yh(e){if(e.flags.help){s0();return}let t=e.subcommand;if(t==="repo"){await r0(e);return}if(t==="author"){await o0(e);return}if(t==="index"){await l0(e);return}let s=performance.now(),i=await j(),r=await K(i,e.flags.scope);if(e.flags.tokens){let a=xm(r);if(e.flags.machine){console.log(V("stats tokens",a,s));return}if(e.flags.json){console.log(q(a));return}console.log(Em(a));return}if(r.length===0&&!e.flags.json&&!e.flags.machine){console.log(" No installed skills.");return}let n=Ci(r),o=await Sm(r,n);if(e.flags.machine){let{perSkillDiskBytes:a,...c}=o;console.log(V("stats",e.flags.verbose?o:c,s));return}if(e.flags.json)if(e.flags.verbose)console.log(q(o));else{let{perSkillDiskBytes:a,...c}=o;console.log(q(c))}else console.log($m(o))}function i0(){console.log(`${l.bold("Usage:")} asm stats repo <owner/repo> [options]
694
+ ${i.bold("Examples:")}
695
+ asm stats ${i.dim("Show installed skills dashboard")}
696
+ asm stats --tokens ${i.dim("Resident context cost per tool")}
697
+ asm stats --tokens --json ${i.dim("Attention budget as JSON")}
698
+ asm stats -s global ${i.dim("Global skills only")}
699
+ asm stats --json ${i.dim("Output raw data as JSON")}
700
+ asm stats --machine ${i.dim("Machine-readable v1 envelope output")}
701
+ asm stats repo anthropics/skills ${i.dim("Show indexed repo stats")}
702
+ asm stats author luongnv89 ${i.dim("Show indexed author stats")}
703
+ asm stats index ${i.dim("Show index-wide stats")}`)}async function Cc(e){if(e.flags.help){yg();return}let t=e.subcommand;if(t==="repo"){await wg(e);return}if(t==="author"){await vg(e);return}if(t==="index"){await $g(e);return}let r=performance.now(),s=await O(),o=await V(s,e.flags.scope);if(e.flags.tokens){let l=Dl(o);if(e.flags.machine){console.log(B("stats tokens",l,r));return}if(e.flags.json){console.log(j(l));return}console.log(Ml(l));return}if(o.length===0&&!e.flags.json&&!e.flags.machine){console.log(" No installed skills.");return}let n=$r(o),a=await Nl(o,n);if(e.flags.machine){let{perSkillDiskBytes:l,...c}=a;console.log(B("stats",e.flags.verbose?a:c,r));return}if(e.flags.json)if(e.flags.verbose)console.log(j(a));else{let{perSkillDiskBytes:l,...c}=a;console.log(j(c))}else console.log(Ol(a))}function bg(){console.log(`${i.bold("Usage:")} asm stats repo <owner/repo> [options]
813
704
 
814
705
  Show statistics for a specific indexed repository.
815
706
 
816
- ${l.bold("Arguments:")}
707
+ ${i.bold("Arguments:")}
817
708
  owner/repo Repository identifier (e.g. anthropics/skills)
818
709
 
819
- ${l.bold("Options:")}
710
+ ${i.bold("Options:")}
820
711
  --json Output as JSON
821
712
  --no-color Disable ANSI colors
822
713
 
823
- ${l.bold("Examples:")}
714
+ ${i.bold("Examples:")}
824
715
  asm stats repo anthropics/skills
825
- asm stats repo luongnv89/asm --json`)}async function r0(e){if(e.flags.help){i0();return}let t=e.positional[0];t||($("Missing required argument: <owner/repo>"),console.error('Run "asm stats repo --help" for usage.'),process.exit(2));let[s,i]=t.split("/");(!s||!i)&&($(`Invalid repository: "${t}". Expected format: owner/repo`),process.exit(2));let n=(await Oe()).find(a=>a.owner===s&&a.repo===i);n||($(`Repository "${s}/${i}" not found in the skill index.`),console.error(l.dim('Run "asm index list" to see all indexed repositories.')),process.exit(1));let o=Pm([n]);if(o.length===0){console.log(`No stats for "${s}/${i}".`);return}e.flags.json?console.log(q(o[0])):console.log(Lm(o[0]))}function n0(){console.log(`${l.bold("Usage:")} asm stats author <owner> [options]
716
+ asm stats repo luongnv89/asm --json`)}async function wg(e){if(e.flags.help){bg();return}let t=e.positional[0];t||(w("Missing required argument: <owner/repo>"),console.error('Run "asm stats repo --help" for usage.'),process.exit(2));let[r,s]=t.split("/");(!r||!s)&&(w(`Invalid repository: "${t}". Expected format: owner/repo`),process.exit(2));let n=(await $e()).find(l=>l.owner===r&&l.repo===s);n||(w(`Repository "${r}/${s}" not found in the skill index.`),console.error(i.dim('Run "asm index list" to see all indexed repositories.')),process.exit(1));let a=Fl([n]);if(a.length===0){console.log(`No stats for "${r}/${s}".`);return}e.flags.json?console.log(j(a[0])):console.log(Ul(a[0]))}function kg(){console.log(`${i.bold("Usage:")} asm stats author <owner> [options]
826
717
 
827
718
  Show statistics for a specific author across all indexed repositories.
828
719
 
829
- ${l.bold("Arguments:")}
720
+ ${i.bold("Arguments:")}
830
721
  owner Author/organization name (e.g. luongnv89)
831
722
 
832
- ${l.bold("Options:")}
723
+ ${i.bold("Options:")}
833
724
  --json Output as JSON
834
725
  --no-color Disable ANSI colors
835
726
 
836
- ${l.bold("Examples:")}
727
+ ${i.bold("Examples:")}
837
728
  asm stats author anthropics
838
- asm stats author luongnv89 --json`)}async function o0(e){if(e.flags.help){n0();return}let t=e.positional[0];t||($("Missing required argument: <owner>"),console.error('Run "asm stats author --help" for usage.'),process.exit(2));let s=await Oe(),i=Cm(s),r=i.find(n=>n.owner===t);if(!r){$(`Author "${t}" not found in the skill index.`);let o=i.slice(0,10).map(a=>` ${a.owner} (${a.totalSkills} skills)`).join(`
839
- `);console.error(l.dim(`Available authors (top 10 by skill count):
840
- ${o}`)),process.exit(1)}e.flags.json?console.log(q(r)):console.log(Am(r))}function a0(){console.log(`${l.bold("Usage:")} asm stats index [options]
729
+ asm stats author luongnv89 --json`)}async function vg(e){if(e.flags.help){kg();return}let t=e.positional[0];t||(w("Missing required argument: <owner>"),console.error('Run "asm stats author --help" for usage.'),process.exit(2));let r=await $e(),s=jl(r),o=s.find(n=>n.owner===t);if(!o){w(`Author "${t}" not found in the skill index.`);let a=s.slice(0,10).map(l=>` ${l.owner} (${l.totalSkills} skills)`).join(`
730
+ `);console.error(i.dim(`Available authors (top 10 by skill count):
731
+ ${a}`)),process.exit(1)}e.flags.json?console.log(j(o)):console.log(Bl(o))}function Sg(){console.log(`${i.bold("Usage:")} asm stats index [options]
841
732
 
842
733
  Show aggregate statistics across all indexed repositories.
843
734
 
844
- ${l.bold("Options:")}
735
+ ${i.bold("Options:")}
845
736
  --json Output as JSON
846
737
  --no-color Disable ANSI colors
847
738
 
848
- ${l.bold("Examples:")}
739
+ ${i.bold("Examples:")}
849
740
  asm stats index
850
- asm stats index --json`)}async function l0(e){if(e.flags.help){a0();return}let t=await Oe();if(t.length===0){console.log("No indexed repositories found."),console.error(l.dim('Run "asm index ingest <repo>" to add repositories.'));return}let s=Im(t);e.flags.json?console.log(q(s)):console.log(Rm(s))}function c0(){console.log(`${l.bold("Usage:")} asm link <path> [<path2> ...] [options]
741
+ asm stats index --json`)}async function $g(e){if(e.flags.help){Sg();return}let t=await $e();if(t.length===0){console.log("No indexed repositories found."),console.error(i.dim('Run "asm index ingest <repo>" to add repositories.'));return}let r=_l(t);e.flags.json?console.log(j(r)):console.log(Vl(r))}function xg(){console.log(`${i.bold("Usage:")} asm link <path> [<path2> ...] [options]
851
742
 
852
743
  Symlink a local skill directory into an agent's skill folder. Useful
853
744
  for local development \u2014 changes to the source are reflected immediately.
@@ -858,7 +749,7 @@ files, all discovered skills are linked in a single invocation.
858
749
 
859
750
  Multiple paths can be provided to link several skills at once.
860
751
 
861
- ${l.bold("Options:")}
752
+ ${i.bold("Options:")}
862
753
  -p, --tool <name> Target tool (claude, codex, openclaw, agents)
863
754
  --name <name> Override symlink name (single skill only)
864
755
  -f, --force Overwrite if target already exists
@@ -866,31 +757,31 @@ ${l.bold("Options:")}
866
757
  --no-color Disable ANSI colors
867
758
  -V, --verbose Show debug output
868
759
 
869
- ${l.bold("Examples:")}
870
- asm link ./my-skill ${l.dim("Link (interactive tool)")}
871
- asm link ./my-skill -p claude ${l.dim("Link to Claude Code")}
872
- asm link ./my-skill --name alias ${l.dim("Link with custom name")}
873
- asm link ./my-skills-folder ${l.dim("Link all skills in folder")}
874
- asm link ./skill1 ./skill2 ./skill3 -p claude ${l.dim("Link multiple skills at once")}`)}async function u0(e,t){if(t)return!0;let{access:s}=await import("fs/promises"),i=!1;try{await s(e),i=!0}catch{}if(!i)return!1;if(!process.stdin.isTTY)throw new Error(`Target already exists: ${e}. Use --force to overwrite.`);process.stderr.write(`${l.yellow(`Target already exists: ${e}`)}
875
- ${l.bold("Overwrite?")} [y/N] `);let r=await H();return r.toLowerCase()!=="y"&&r.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0)),!0}async function on(e,t,s,i){let{join:r}=await import("path"),n=r(t,s),o=await u0(n,i);return await Fr(e,t,s,o),{name:s,symlinkPath:n,targetPath:e}}async function bh(e){if(e.flags.help){c0();return}let t=[];if(e.subcommand&&t.push(e.subcommand),t.push(...e.positional),t.length===0&&($("Missing required argument: <path>"),console.error('Run "asm link --help" for usage.'),process.exit(2)),t.length>1){e.flags.name&&($("--name cannot be used when linking multiple paths. Link each skill individually to use --name."),process.exit(2));let g=await j(),{provider:h}=await ke(g,e.flags.provider,!!process.stdin.isTTY),{resolveProviderPath:y}=await import("./config-PQRMSV7F.js"),b=y(g.providers.find(C=>C.name===h.name).global),{resolve:k,basename:w}=await import("path"),v=[],x=[];for(let C of t){let A=k(C),E=!1,_=null;try{await ha(A),E=!0}catch(O){let S=O instanceof Error?O.message:String(O);S.startsWith("Path does not exist")||S.startsWith("Path is not a directory")||S.startsWith("No SKILL.md found")||(_=S)}if(_){x.push({name:C,error:_}),e.flags.json||console.error(l.red(` Failed to process "${C}": ${_}`));continue}if(E){let O=w(A);try{let S=await on(A,b,O,!!e.flags.force);v.push(S),e.flags.json||console.error(l.green(` Linked "${S.name}" -> ${S.targetPath}`))}catch(S){let P=S instanceof Error?S.message:String(S);x.push({name:O,error:P}),e.flags.json||console.error(l.red(` Failed to link "${O}": ${P}`))}}else{let O;try{O=await ga(A)}catch(S){let P=S instanceof Error?S.message:String(S),B=P;P.startsWith("Path does not exist")&&tt(C)&&(B=`${P} \u2014 "${C}" looks like a registry name; try "asm install ${C}" first.`),x.push({name:C,error:B}),e.flags.json||console.error(l.red(` Failed to process "${C}": ${B}`));continue}if(O.length===0){let S=`No SKILL.md found in ${A} or its immediate subdirectories.`;x.push({name:C,error:S}),e.flags.json||console.error(l.red(` ${S}`));continue}for(let S of O)try{let P=await on(S.absPath,b,S.dirName,!!e.flags.force);v.push(P),e.flags.json||console.error(l.green(` Linked "${P.name}" -> ${P.targetPath}`))}catch(P){let B=P instanceof Error?P.message:String(P);x.push({name:S.name,error:B}),e.flags.json||console.error(l.red(` Failed to link "${S.name}": ${B}`))}}}e.flags.json?console.log(q({success:x.length===0,linked:v,failures:x})):x.length>0?console.error(l.yellow(`
876
- ${v.length} linked, ${x.length} failed.`)):console.error(l.green(`
877
- Done! Linked ${v.length} skill(s) successfully.`)),x.length>0&&process.exit(1);return}let s=t[0],{resolve:i,basename:r}=await import("path"),n=i(s),o=!1;try{await ha(n),o=!0}catch(g){let h=g instanceof Error?g.message:String(g);h.startsWith("Path does not exist")||h.startsWith("Path is not a directory")||h.startsWith("No SKILL.md found")||($(h),process.exit(1))}let a=[];if(!o){try{a=await ga(n)}catch(g){let h=g instanceof Error?g.message:String(g);h.startsWith("Path does not exist")?($(`No such skill or path: ${s}`),tt(s)?(console.error(` "${s}" looks like a registry name, not a local path.`),console.error(` Install it first: ${l.bold(`asm install ${s}`)}`),console.error(` Or pass a local path: ${l.bold(`asm link ./path/to/${s}`)}`)):console.error(' Pass a local directory containing SKILL.md, or run "asm install <name>" first.')):$(h),process.exit(1)}a.length===0&&($(`No SKILL.md found in ${n} or its immediate subdirectories.`),process.exit(1)),e.flags.name&&a.length>1&&($(`--name cannot be used when linking multiple skills (found ${a.length} skills). Link each skill individually to use --name.`),process.exit(2))}let c=await j(),{provider:u}=await ke(c,e.flags.provider,!!process.stdin.isTTY),{resolveProviderPath:f}=await import("./config-PQRMSV7F.js"),d=f(c.providers.find(g=>g.name===u.name).global);if(o){let g=e.flags.name?be(e.flags.name):r(n),h;try{h=await on(n,d,g,!!e.flags.force)}catch(y){let b=y instanceof Error?y.message:String(y);e.flags.json?console.log(q({success:!1,error:b})):$(b),process.exit(2)}e.flags.json?console.log(q({success:!0,...h})):(console.error(l.green(`Done! Linked "${h.name}" -> ${h.targetPath}`)),console.error(` Symlink: ${h.symlinkPath}`),console.error(l.dim(` If you move or delete the source, run "asm uninstall ${h.name}" to clean up.`)));return}console.error(`Found ${l.bold(String(a.length))} skill(s) in ${n}:`);for(let g of a)console.error(` ${l.bold(g.name)} ${l.dim(`v${g.version}`)} ${l.dim(`(${g.dirName}/)`)}`);if(process.stdin.isTTY&&!e.flags.force){process.stderr.write(`
878
- ${l.bold(`Link ${a.length} skill(s)?`)} [Y/n] `);let g=await H();(g.toLowerCase()==="n"||g.toLowerCase()==="no")&&(console.error("Aborted."),process.exit(0))}let p=[],m=[];for(let g of a){let h=e.flags.name&&a.length===1?be(e.flags.name):g.dirName;try{let y=await on(g.absPath,d,h,!!e.flags.force);p.push(y),e.flags.json||console.error(l.green(` Linked "${y.name}" -> ${y.targetPath}`))}catch(y){let b=y instanceof Error?y.message:String(y);m.push({name:g.name,error:b}),e.flags.json||console.error(l.red(` Failed to link "${g.name}": ${b}`))}}e.flags.json?console.log(q({success:m.length===0,linked:p,failures:m})):m.length>0?console.error(l.yellow(`
879
- ${p.length} linked, ${m.length} failed.`)):console.error(l.green(`
880
- Done! Linked ${p.length} skill(s) successfully.`)),m.length>0&&process.exit(1)}import{writeFile as E0,mkdir as P0,unlink as C0,readFile as I0,readdir as L0}from"fs/promises";import{join as di}from"path";function Il(e){return e==="skills"||e.startsWith("skills/")?{priority:1,root:"skills/"}:e===".claude/skills"||e.startsWith(".claude/skills/")?{priority:2,root:".claude/skills/"}:e===".agent/skills"||e.startsWith(".agent/skills/")?{priority:3,root:".agent/skills/"}:e===".agents/skills"||e.startsWith(".agents/skills/")?{priority:3,root:".agents/skills/"}:{priority:4,root:"(other)"}}function wh(e){let t=new Map;for(let n of e){let o=t.get(n.name);o?o.push(n):t.set(n.name,[n])}let s=[],i=[],r=new Set;for(let n of e){if(r.has(n.name))continue;r.add(n.name);let o=t.get(n.name);if(o.length===1){s.push(o[0]);continue}let a=0,c=Il(o[0].relPath);for(let f=1;f<o.length;f++){let d=Il(o[f].relPath);d.priority<c.priority&&(a=f,c=d)}let u=o[a];s.push(u),i.push({name:n.name,kept:{relPath:u.relPath,root:c.root},dropped:o.filter((f,d)=>d!==a).map(f=>({relPath:f.relPath,root:Il(f.relPath).root})),reason:c.priority===4?"first occurrence (no priority match)":`${c.root} priority`})}return{kept:s,decisions:i}}var d0=[{label:"obfuscation:atob",pattern:/\batob\s*\(/},{label:"obfuscation:base64",pattern:/(?:^|[=:\s])[A-Za-z0-9+/]{40,}={1,2}(?:\s|$)/m},{label:"obfuscation:hex-escape",pattern:/\\x[0-9a-fA-F]{2}(?:\\x[0-9a-fA-F]{2}){3,}/},{label:"credential-leak:api-key",pattern:/\bAPI_KEY\s*=\s*['"][^'"]+['"]/},{label:"credential-leak:secret",pattern:/\bSECRET_KEY\s*=\s*['"][^'"]+['"]/},{label:"credential-leak:password",pattern:/\bPASSWORD\s*=\s*['"][^'"]+['"]/}];function kh(e,t){let s=[];(!e.name||!e.name.trim())&&s.push("missing frontmatter field: name"),(!e.description||!e.description.trim())&&s.push("missing frontmatter field: description"),f0(t).trim().length<20&&s.push("SKILL.md body too short (less than 20 chars of instructions)");for(let{label:r,pattern:n}of d0)n.test(t)&&s.push(`malicious pattern detected: ${r}`);return{verified:s.length===0,reasons:s}}function f0(e){let t=e.trimStart();if(!t.startsWith("---"))return t;let s=t.indexOf(`
881
- ---`,3);return s===-1?"":t.slice(s+4)}import{readdir as p0,readFile as vh,stat as $h}from"fs/promises";import{join as Ll}from"path";var m0=[{id:"marketing",title:"Marketing Skills",description:"Marketing, growth, SEO, ASO, affiliate, sales, and conversion skills.",tags:["marketing","growth","seo"],keywords:["marketing","growth","seo","aso","affiliate","sales","copy","copywriting","conversion","cro","brand","social","campaign"]},{id:"writing",title:"Writing Skills",description:"Writing, editing, documentation, publishing, and content-production skills.",tags:["writing","content","docs"],keywords:["write","writing","writer","blog","article","content","docs","documentation","draft","copy","readme","paper","thesis","proposal"]},{id:"research",title:"Research Skills",description:"Research, academic, literature-review, citation, paper, and analysis skills.",tags:["research","academic","analysis"],keywords:["research","academic","scholar","paper","literature","citation","review","analysis","summar","evaluate","verify"]},{id:"engineering",title:"Engineering Skills",description:"Coding, debugging, testing, architecture, review, and software engineering skills.",tags:["engineering","coding","testing"],keywords:["code","coding","debug","test","testing","coverage","review","refactor","architecture","typescript","python","javascript","build","cli","api"]},{id:"frontend-design",title:"Frontend & Design Skills",description:"Frontend, UI, UX, visual design, component, theme, and landing-page skills.",tags:["frontend","design","ui"],keywords:["frontend","ui","ux","design","component","react","css","html","figma","theme","landing","layout","visual","brand","logo"]},{id:"devops",title:"DevOps Skills",description:"Deployment, CI/CD, infrastructure, cloud, Docker, Kubernetes, and automation skills.",tags:["devops","infra","automation"],keywords:["devops","deploy","deployment","ci","cd","pipeline","docker","kubernetes","terraform","ansible","cloud","infra","infrastructure","workflow","release"]},{id:"data-ai",title:"Data & AI Skills",description:"Data, analytics, AI, model, prompt, agent, and automation skills.",tags:["data","ai","agents"],keywords:["data","analytics","analysis","ai","agent","llm","model","prompt","openai","claude","gemini","automation","dataset","sql"]},{id:"product-business",title:"Product & Business Skills",description:"Product, strategy, PRD, planning, finance, resume, and business workflow skills.",tags:["product","business","planning"],keywords:["product","prd","strategy","planning","business","finance","resume","career","startup","market","competitor","customer","sales"]}],Sh=2,h0=80,g0=["asm-bundles.json","asm.bundle.json",".asm/bundles.json",".asm/bundle.json"],y0=["bundles","data/bundles",".asm/bundles"];function ui(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function xh(e,t,s){let i=ui(e),r=ui(t),n=ui(s),o=`${i}-${r}`;return n.startsWith(o)?n:`${o}-${n}`}function b0(e){return[e.name,e.description,e.relPath,e.installUrl].filter(Boolean).join(" ").toLowerCase()}function w0(e,t){let s=b0(e);return t.keywords.some(i=>s.includes(i))}function Eh(e){return{name:e.name,installUrl:e.installUrl,description:e.description||void 0,version:e.version||void 0}}function k0(e){let t=new Set,s=[];for(let i of e){let r=`${i.installUrl||""}\0${i.name}`;t.has(r)||(t.add(r),s.push(i))}return s}function Ph(e){return[...e].sort((t,s)=>t.name.localeCompare(s.name))}function Al(e){let t=[];if(!e.skills||e.skills.length<Sh)return t;for(let s of m0){let i=e.skills.filter(n=>w0(n,s)).slice(0,h0);if(i.length<Sh)continue;let r=xh(e.owner,e.repo,s.id);t.push({version:1,name:r,description:`${s.description} Derived from ${e.owner}/${e.repo}.`,author:`ASM (${e.owner}/${e.repo})`,createdAt:e.updatedAt,tags:["repo-derived","inferred",...s.tags,ui(e.owner),ui(e.repo)],skills:Ph(i.map(Eh)),sourceRepo:{owner:e.owner,repo:e.repo,repoUrl:e.repoUrl},inferred:!0})}return t}function v0(e,t,s){if(!e||typeof e!="object"||Array.isArray(e))return null;let i=e,r=Array.isArray(i.skills)?i.skills:[];if(r.length===0)return null;let n=new Map(t.skills.map(c=>[c.name,c])),o=k0(r.map(c=>{if(typeof c=="string"){let p=n.get(c);return p?Eh(p):null}if(!c||typeof c!="object"||Array.isArray(c))return null;let u=c,f=typeof u.name=="string"?u.name:"";if(!f)return null;let d=n.get(f);return d?{name:d.name,installUrl:d.installUrl,description:typeof u.description=="string"&&u.description?u.description:d.description||void 0,version:typeof u.version=="string"&&u.version?u.version:d.version||void 0}:null}).filter(c=>c!==null));if(o.length===0)return null;let a=typeof i.name=="string"&&i.name?i.name:s.replace(/\.json$/,"");return{version:1,name:xh(t.owner,t.repo,a),description:typeof i.description=="string"&&i.description?i.description:`Bundle from ${t.owner}/${t.repo}.`,author:typeof i.author=="string"&&i.author?i.author:`ASM (${t.owner}/${t.repo})`,createdAt:typeof i.createdAt=="string"&&i.createdAt?i.createdAt:t.updatedAt,tags:Array.isArray(i.tags)?["repo-derived","explicit",...i.tags.filter(c=>typeof c=="string")]:["repo-derived","explicit"],skills:Ph(o),sourceRepo:{owner:t.owner,repo:t.repo,repoUrl:t.repoUrl,relPath:s},explicit:!0}}async function S0(e){try{return(await $h(e)).isFile()}catch{return!1}}async function $0(e){try{return(await $h(e)).isDirectory()}catch{return!1}}async function x0(e){let t=[];for(let s of g0){let i=Ll(e,s);if(await S0(i))try{t.push({relPath:s,data:JSON.parse(await vh(i,"utf-8"))})}catch{}}for(let s of y0){let i=Ll(e,s);if(!await $0(i))continue;let r;try{r=await p0(i)}catch{continue}for(let n of r.filter(o=>o.endsWith(".json")).sort()){let o=`${s}/${n}`;try{t.push({relPath:o,data:JSON.parse(await vh(Ll(i,n),"utf-8"))})}catch{}}}return t}async function Ch(e,t){let s=[],i=await x0(e);for(let r of i){let n=r.data,o=Array.isArray(n?.bundles)?n.bundles:[n];for(let a of o){let c=v0(a,t,r.relPath);c&&s.push(c)}}return an(s)}function an(e){let t=new Map;for(let s of e){let i=t.get(s.name);(!i||s.explicit&&!i.explicit)&&t.set(s.name,s)}return Array.from(t.values()).sort((s,i)=>s.name.localeCompare(i.name))}function Ih(e){let t=e.bundles||[],s=Al(e);return an([...t,...s])}var A0=8;async function R0(){let e=xt();return await P0(e,{recursive:!0}),e}function N0(e,t){return`github:${e.owner}/${e.repo}${e.ref?`#${e.ref}`:""}${t?`:${t}`:""}`}async function Lh(e){await Ae();let t;try{t=ue(e)}catch(i){return{success:!1,repoIndex:null,error:i.message}}if(t.isLocal)return{success:!1,repoIndex:null,error:"Local paths are not supported for indexing. Use a GitHub source instead."};try{ye(t,e)}catch(i){return{success:!1,repoIndex:null,error:i.message}}L(`ingester: cloning ${t.owner}/${t.repo}`);let s=null;try{s=await Re(t),L(`ingester: discovering skills in ${s}`);let i=await mt(s);L(`ingester: found ${i.length} skills`);let{kept:r,decisions:n}=wh(i);for(let d of n){let p=d.dropped.map(m=>m.relPath).join(", ");L(`ingester: dedupe "${d.name}": kept ${d.kept.relPath} (${d.reason}); dropped ${p}`)}n.length>0&&L(`ingester: deduped ${i.length} -> ${r.length} skills (${n.length} name collision${n.length===1?"":"s"})`);let o=s,a=await zs(r,A0,async d=>{let p=di(o,d.relPath,"SKILL.md"),m="";try{m=await I0(p,"utf-8")}catch{L(`ingester: could not read SKILL.md at ${p}`)}let g=kh(d,m);g.verified||L(`ingester: ${d.name} not verified: ${g.reasons.join(", ")}`);let h=typeof d.tokenCount=="number"?d.tokenCount:m?qe(m):void 0,y,b;if(m){let k;try{k=await L0(di(o,d.relPath))}catch{k=void 0}try{let w=await Ht({content:m,skillPath:d.relPath||d.name,skillMdPath:p,rootEntries:k});y={overallScore:w.overallScore,grade:w.grade,categories:w.categories.map(v=>({id:v.id,name:v.name,score:v.score,max:v.max})),evaluatedAt:w.evaluatedAt,evaluatedVersion:d.version||void 0}}catch(w){L(`ingester: eval failed for ${d.name}: ${w}`)}try{let w={skillPath:di(o,d.relPath),skillMdPath:p},x=(await Promise.all(ai(tn()).map(async C=>(await C.applicable(w,{})).ok?sn(C,w):null))).filter(C=>C!==null).map(C=>pm(C,d.version||void 0));x.length>0&&(b=Object.fromEntries(x.filter(C=>C.providerId).map(C=>[C.providerId,C])))}catch(w){L(`ingester: provider eval failed for ${d.name}: ${w}`)}}return{name:d.name,description:d.description,version:d.version,license:d.license,creator:d.creator,compatibility:d.compatibility,allowedTools:d.allowedTools,tags:d.tags,modelInvocable:d.modelInvocable!==!1,userInvocable:d.userInvocable!==!1,installUrl:N0(t,d.relPath),relPath:d.relPath,verified:g.verified,tokenCount:h,evalSummary:y,evalSummaries:b}}),c={repoUrl:t.cloneUrl,owner:t.owner,repo:t.repo,updatedAt:new Date().toISOString(),skillCount:a.length,skills:a};c.bundles=an([...await Ch(s,c),...Al(c)]);let u=await R0(),f=di(u,`${t.owner}_${t.repo}.json`);return await E0(f,JSON.stringify(c,null,2)+`
882
- `,"utf-8"),L(`ingester: wrote index to ${f}`),{success:!0,repoIndex:c}}catch(i){return{success:!1,repoIndex:null,error:i.message}}finally{s&&await Q(s)}}async function Ah(){return(await Oe()).map(t=>({owner:t.owner,repo:t.repo,skillCount:t.skillCount,updatedAt:t.updatedAt})).sort((t,s)=>s.skillCount-t.skillCount)}async function Rh(e,t){let s=xt(),i=di(s,`${e}_${t}.json`);try{return await C0(i),!0}catch{return!1}}var Xt=.55,ln=.7;function Nh(e,t){if(e.size===0&&t.size===0)return 0;let s=new Set;for(let r of e)t.has(r)&&s.add(r);let i=e.size+t.size-s.size;return i===0?0:s.size/i}function T0(e,t){let s=ge(e.description),i=ge(t.description),r=Nh(s,i),n=ge(e.name),o=ge(t.name),a=Nh(n,o);return .6*r+.4*a}function O0(e,t,s){let i=ge(e.description),r=ge(t.description),o=[...i].filter(c=>r.has(c)).length,a=i.size+r.size-o;return s>=ln?`Very similar descriptions (${o}/${a} shared tokens)`:s>=Xt?`Similar descriptions (${o}/${a} shared tokens)`:`Some overlapping concepts (${o}/${a} shared tokens)`}function Rl(e,t=Xt){let s=[];for(let i=0;i<e.length;i++)for(let r=i+1;r<e.length;r++){let n=T0(e[i].skill,e[r].skill);n>=t&&s.push({skillA:e[i].skill,skillB:e[r].skill,repoA:e[i].repo,repoB:e[r].repo,score:n,reason:O0(e[i].skill,e[r].skill,n)})}return s.sort((i,r)=>r.score-i.score),s}function Th(e,t=Xt){let s=Rl(e,t);if(s.length===0)return[];let i=new Map,r=new Map,n=new Map;function o(f){for(;i.get(f)!==f;)i.set(f,i.get(i.get(f))),f=i.get(f);return f}function a(f,d,p){let m=o(f),g=o(d);if(m===g){let h=r.get(m)??0;r.set(m,Math.max(h,p)),n.set(m,(n.get(m)??0)+1);return}if(m!==g){i.set(g,m);let h=Math.max(r.get(m)??0,r.get(g)??0,p);r.set(m,h),n.set(m,(n.get(m)??0)+(n.get(g)??0)+1)}}for(let f=0;f<e.length;f++)i.set(f,f),r.set(f,0),n.set(f,0);for(let f of s){let d=e.findIndex(m=>m.skill.name===f.skillA.name&&m.skill.installUrl===f.skillA.installUrl),p=e.findIndex(m=>m.skill.name===f.skillB.name&&m.skill.installUrl===f.skillB.installUrl);d>=0&&p>=0&&a(d,p,f.score)}let c=new Map;for(let f=0;f<e.length;f++){let d=o(f);c.has(d)||c.set(d,[]),c.get(d).push(f)}let u=[];for(let[f,d]of c){if(d.length<2)continue;let p=r.get(f)??0;if(p<t)continue;let m=n.get(f)??0;u.push({skills:d.map(g=>({skill:e[g].skill,repo:e[g].repo})),maxScore:p,pairCount:m})}return u.sort((f,d)=>d.maxScore-f.maxScore),u}function M0(){console.log(`${l.bold("Usage:")} asm index <subcommand> [options]
760
+ ${i.bold("Examples:")}
761
+ asm link ./my-skill ${i.dim("Link (interactive tool)")}
762
+ asm link ./my-skill -p claude ${i.dim("Link to Claude Code")}
763
+ asm link ./my-skill --name alias ${i.dim("Link with custom name")}
764
+ asm link ./my-skills-folder ${i.dim("Link all skills in folder")}
765
+ asm link ./skill1 ./skill2 ./skill3 -p claude ${i.dim("Link multiple skills at once")}`)}async function Pg(e,t){if(t)return!0;let{access:r}=await import("fs/promises"),s=!1;try{await r(e),s=!0}catch{}if(!s)return!1;if(!process.stdin.isTTY)throw new Error(`Target already exists: ${e}. Use --force to overwrite.`);process.stderr.write(`${i.yellow(`Target already exists: ${e}`)}
766
+ ${i.bold("Overwrite?")} [y/N] `);let o=await G();return o.toLowerCase()!=="y"&&o.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0)),!0}async function us(e,t,r,s){let{join:o}=await import("path"),n=o(t,r),a=await Pg(n,s);return await Dr(e,t,r,a),{name:r,symlinkPath:n,targetPath:e}}async function Lc(e){if(e.flags.help){xg();return}let t=[];if(e.subcommand&&t.push(e.subcommand),t.push(...e.positional),t.length===0&&(w("Missing required argument: <path>"),console.error('Run "asm link --help" for usage.'),process.exit(2)),t.length>1){e.flags.name&&(w("--name cannot be used when linking multiple paths. Link each skill individually to use --name."),process.exit(2));let g=await O(),{provider:h}=await me(g,e.flags.provider,!!process.stdin.isTTY),{resolveProviderPath:y}=await import("./config-JPFUVYBM.js"),b=y(g.providers.find(D=>D.name===h.name).global),{resolve:$,basename:v}=await import("path"),S=[],C=[];for(let D of t){let U=$(D),A=!1,_=null;try{await Fs(U),A=!0}catch(M){let k=M instanceof Error?M.message:String(M);k.startsWith("Path does not exist")||k.startsWith("Path is not a directory")||k.startsWith("No SKILL.md found")||(_=k)}if(_){C.push({name:D,error:_}),e.flags.json||console.error(i.red(` Failed to process "${D}": ${_}`));continue}if(A){let M=v(U);try{let k=await us(U,b,M,!!e.flags.force);S.push(k),e.flags.json||console.error(i.green(` Linked "${k.name}" -> ${k.targetPath}`))}catch(k){let E=k instanceof Error?k.message:String(k);C.push({name:M,error:E}),e.flags.json||console.error(i.red(` Failed to link "${M}": ${E}`))}}else{let M;try{M=await js(U)}catch(k){let E=k instanceof Error?k.message:String(k),F=E;E.startsWith("Path does not exist")&&Ne(D)&&(F=`${E} \u2014 "${D}" looks like a registry name; try "asm install ${D}" first.`),C.push({name:D,error:F}),e.flags.json||console.error(i.red(` Failed to process "${D}": ${F}`));continue}if(M.length===0){let k=`No SKILL.md found in ${U} or its immediate subdirectories.`;C.push({name:D,error:k}),e.flags.json||console.error(i.red(` ${k}`));continue}for(let k of M)try{let E=await us(k.absPath,b,k.dirName,!!e.flags.force);S.push(E),e.flags.json||console.error(i.green(` Linked "${E.name}" -> ${E.targetPath}`))}catch(E){let F=E instanceof Error?E.message:String(E);C.push({name:k.name,error:F}),e.flags.json||console.error(i.red(` Failed to link "${k.name}": ${F}`))}}}e.flags.json?console.log(j({success:C.length===0,linked:S,failures:C})):C.length>0?console.error(i.yellow(`
767
+ ${S.length} linked, ${C.length} failed.`)):console.error(i.green(`
768
+ Done! Linked ${S.length} skill(s) successfully.`)),C.length>0&&process.exit(1);return}let r=t[0],{resolve:s,basename:o}=await import("path"),n=s(r),a=!1;try{await Fs(n),a=!0}catch(g){let h=g instanceof Error?g.message:String(g);h.startsWith("Path does not exist")||h.startsWith("Path is not a directory")||h.startsWith("No SKILL.md found")||(w(h),process.exit(1))}let l=[];if(!a){try{l=await js(n)}catch(g){let h=g instanceof Error?g.message:String(g);h.startsWith("Path does not exist")?(w(`No such skill or path: ${r}`),Ne(r)?(console.error(` "${r}" looks like a registry name, not a local path.`),console.error(` Install it first: ${i.bold(`asm install ${r}`)}`),console.error(` Or pass a local path: ${i.bold(`asm link ./path/to/${r}`)}`)):console.error(' Pass a local directory containing SKILL.md, or run "asm install <name>" first.')):w(h),process.exit(1)}l.length===0&&(w(`No SKILL.md found in ${n} or its immediate subdirectories.`),process.exit(1)),e.flags.name&&l.length>1&&(w(`--name cannot be used when linking multiple skills (found ${l.length} skills). Link each skill individually to use --name.`),process.exit(2))}let c=await O(),{provider:d}=await me(c,e.flags.provider,!!process.stdin.isTTY),{resolveProviderPath:u}=await import("./config-JPFUVYBM.js"),p=u(c.providers.find(g=>g.name===d.name).global);if(a){let g=e.flags.name?ue(e.flags.name):o(n),h;try{h=await us(n,p,g,!!e.flags.force)}catch(y){let b=y instanceof Error?y.message:String(y);e.flags.json?console.log(j({success:!1,error:b})):w(b),process.exit(2)}e.flags.json?console.log(j({success:!0,...h})):(console.error(i.green(`Done! Linked "${h.name}" -> ${h.targetPath}`)),console.error(` Symlink: ${h.symlinkPath}`),console.error(i.dim(` If you move or delete the source, run "asm uninstall ${h.name}" to clean up.`)));return}console.error(`Found ${i.bold(String(l.length))} skill(s) in ${n}:`);for(let g of l)console.error(` ${i.bold(g.name)} ${i.dim(`v${g.version}`)} ${i.dim(`(${g.dirName}/)`)}`);if(process.stdin.isTTY&&!e.flags.force){process.stderr.write(`
769
+ ${i.bold(`Link ${l.length} skill(s)?`)} [Y/n] `);let g=await G();(g.toLowerCase()==="n"||g.toLowerCase()==="no")&&(console.error("Aborted."),process.exit(0))}let f=[],m=[];for(let g of l){let h=e.flags.name&&l.length===1?ue(e.flags.name):g.dirName;try{let y=await us(g.absPath,p,h,!!e.flags.force);f.push(y),e.flags.json||console.error(i.green(` Linked "${y.name}" -> ${y.targetPath}`))}catch(y){let b=y instanceof Error?y.message:String(y);m.push({name:g.name,error:b}),e.flags.json||console.error(i.red(` Failed to link "${g.name}": ${b}`))}}e.flags.json?console.log(j({success:m.length===0,linked:f,failures:m})):m.length>0?console.error(i.yellow(`
770
+ ${f.length} linked, ${m.length} failed.`)):console.error(i.green(`
771
+ Done! Linked ${f.length} skill(s) successfully.`)),m.length>0&&process.exit(1)}import{writeFile as Ug,mkdir as Bg,unlink as Vg,readFile as Gg,readdir as Hg}from"fs/promises";import{join as dr}from"path";function nn(e){return e==="skills"||e.startsWith("skills/")?{priority:1,root:"skills/"}:e===".claude/skills"||e.startsWith(".claude/skills/")?{priority:2,root:".claude/skills/"}:e===".agent/skills"||e.startsWith(".agent/skills/")?{priority:3,root:".agent/skills/"}:e===".agents/skills"||e.startsWith(".agents/skills/")?{priority:3,root:".agents/skills/"}:{priority:4,root:"(other)"}}function Ac(e){let t=new Map;for(let n of e){let a=t.get(n.name);a?a.push(n):t.set(n.name,[n])}let r=[],s=[],o=new Set;for(let n of e){if(o.has(n.name))continue;o.add(n.name);let a=t.get(n.name);if(a.length===1){r.push(a[0]);continue}let l=0,c=nn(a[0].relPath);for(let u=1;u<a.length;u++){let p=nn(a[u].relPath);p.priority<c.priority&&(l=u,c=p)}let d=a[l];r.push(d),s.push({name:n.name,kept:{relPath:d.relPath,root:c.root},dropped:a.filter((u,p)=>p!==l).map(u=>({relPath:u.relPath,root:nn(u.relPath).root})),reason:c.priority===4?"first occurrence (no priority match)":`${c.root} priority`})}return{kept:r,decisions:s}}var Rg=[{label:"obfuscation:atob",pattern:/\batob\s*\(/},{label:"obfuscation:base64",pattern:/(?:^|[=:\s])[A-Za-z0-9+/]{40,}={1,2}(?:\s|$)/m},{label:"obfuscation:hex-escape",pattern:/\\x[0-9a-fA-F]{2}(?:\\x[0-9a-fA-F]{2}){3,}/},{label:"credential-leak:api-key",pattern:/\bAPI_KEY\s*=\s*['"][^'"]+['"]/},{label:"credential-leak:secret",pattern:/\bSECRET_KEY\s*=\s*['"][^'"]+['"]/},{label:"credential-leak:password",pattern:/\bPASSWORD\s*=\s*['"][^'"]+['"]/}];function Tc(e,t){let r=[];(!e.name||!e.name.trim())&&r.push("missing frontmatter field: name"),(!e.description||!e.description.trim())&&r.push("missing frontmatter field: description"),Eg(t).trim().length<20&&r.push("SKILL.md body too short (less than 20 chars of instructions)");for(let{label:o,pattern:n}of Rg)n.test(t)&&r.push(`malicious pattern detected: ${o}`);return{verified:r.length===0,reasons:r}}function Eg(e){let t=e.trimStart();if(!t.startsWith("---"))return t;let r=t.indexOf(`
772
+ ---`,3);return r===-1?"":t.slice(r+4)}import{readdir as Ig,readFile as Nc,stat as Dc}from"fs/promises";import{join as an}from"path";var Cg=[{id:"marketing",title:"Marketing Skills",description:"Marketing, growth, SEO, ASO, affiliate, sales, and conversion skills.",tags:["marketing","growth","seo"],keywords:["marketing","growth","seo","aso","affiliate","sales","copy","copywriting","conversion","cro","brand","social","campaign"]},{id:"writing",title:"Writing Skills",description:"Writing, editing, documentation, publishing, and content-production skills.",tags:["writing","content","docs"],keywords:["write","writing","writer","blog","article","content","docs","documentation","draft","copy","readme","paper","thesis","proposal"]},{id:"research",title:"Research Skills",description:"Research, academic, literature-review, citation, paper, and analysis skills.",tags:["research","academic","analysis"],keywords:["research","academic","scholar","paper","literature","citation","review","analysis","summar","evaluate","verify"]},{id:"engineering",title:"Engineering Skills",description:"Coding, debugging, testing, architecture, review, and software engineering skills.",tags:["engineering","coding","testing"],keywords:["code","coding","debug","test","testing","coverage","review","refactor","architecture","typescript","python","javascript","build","cli","api"]},{id:"frontend-design",title:"Frontend & Design Skills",description:"Frontend, UI, UX, visual design, component, theme, and landing-page skills.",tags:["frontend","design","ui"],keywords:["frontend","ui","ux","design","component","react","css","html","figma","theme","landing","layout","visual","brand","logo"]},{id:"game",title:"Game Development Skills",description:"Game development, gameplay systems, game UI, 3D assets, and Three.js skills.",tags:["game","gamedev","threejs"],keywords:["game","playtest","godot","unreal","threejs","sprite"]},{id:"mobile",title:"Mobile & iOS Skills",description:"iOS, Swift, SwiftUI, Xcode, macOS, and App Store skills.",tags:["mobile","ios","swift"],keywords:["swift","swiftui","uikit","swiftdata","coredata","xcode","testflight","macos","watchos","appstore","app store","mobile","apple","iphone","ipad"]},{id:"devops",title:"DevOps Skills",description:"Deployment, CI/CD, infrastructure, cloud, Docker, Kubernetes, and automation skills.",tags:["devops","infra","automation"],keywords:["devops","deploy","deployment","ci","cd","pipeline","docker","kubernetes","terraform","ansible","cloud","infra","infrastructure","workflow","release"]},{id:"data-ai",title:"Data & AI Skills",description:"Data, analytics, AI, model, prompt, agent, and automation skills.",tags:["data","ai","agents"],keywords:["data","analytics","analysis","ai","agent","llm","model","prompt","openai","claude","gemini","automation","dataset","sql"]},{id:"product-business",title:"Product & Business Skills",description:"Product, strategy, PRD, planning, finance, resume, and business workflow skills.",tags:["product","business","planning"],keywords:["product","prd","strategy","planning","business","finance","resume","career","startup","market","competitor","customer","sales"]}],Oc=2,Lg=80,Ag=["asm-bundles.json","asm.bundle.json",".asm/bundles.json",".asm/bundle.json"],Tg=["bundles","data/bundles",".asm/bundles"];function cr(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Mc(e,t,r){let s=cr(e),o=cr(t),n=cr(r),a=`${s}-${o}`;return n.startsWith(a)?n:`${a}-${n}`}function Ng(e){return[e.name,e.description,e.relPath,e.installUrl].filter(Boolean).join(" ").toLowerCase()}function Og(e,t){let r=Ng(e);return t.keywords.some(s=>r.includes(s))}function Fc(e){return{name:e.name,installUrl:e.installUrl,description:e.description||void 0,version:e.version||void 0}}function Dg(e){let t=new Set,r=[];for(let s of e){let o=`${s.installUrl||""}\0${s.name}`;t.has(o)||(t.add(o),r.push(s))}return r}function jc(e){return[...e].sort((t,r)=>t.name.localeCompare(r.name))}function ln(e){let t=[];if(!e.skills||e.skills.length<Oc)return t;for(let r of Cg){let s=e.skills.filter(n=>Og(n,r)).slice(0,Lg);if(s.length<Oc)continue;let o=Mc(e.owner,e.repo,r.id);t.push({version:1,name:o,description:`${r.description} Derived from ${e.owner}/${e.repo}.`,author:`ASM (${e.owner}/${e.repo})`,createdAt:e.updatedAt,tags:["repo-derived","inferred",...r.tags,cr(e.owner),cr(e.repo)],skills:jc(s.map(Fc)),sourceRepo:{owner:e.owner,repo:e.repo,repoUrl:e.repoUrl},inferred:!0})}return t}function Mg(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;let s=e,o=Array.isArray(s.skills)?s.skills:[];if(o.length===0)return null;let n=new Map(t.skills.map(c=>[c.name,c])),a=Dg(o.map(c=>{if(typeof c=="string"){let f=n.get(c);return f?Fc(f):null}if(!c||typeof c!="object"||Array.isArray(c))return null;let d=c,u=typeof d.name=="string"?d.name:"";if(!u)return null;let p=n.get(u);return p?{name:p.name,installUrl:p.installUrl,description:typeof d.description=="string"&&d.description?d.description:p.description||void 0,version:typeof d.version=="string"&&d.version?d.version:p.version||void 0}:null}).filter(c=>c!==null));if(a.length===0)return null;let l=typeof s.name=="string"&&s.name?s.name:r.replace(/\.json$/,"");return{version:1,name:Mc(t.owner,t.repo,l),description:typeof s.description=="string"&&s.description?s.description:`Bundle from ${t.owner}/${t.repo}.`,author:typeof s.author=="string"&&s.author?s.author:`ASM (${t.owner}/${t.repo})`,createdAt:typeof s.createdAt=="string"&&s.createdAt?s.createdAt:t.updatedAt,tags:Array.isArray(s.tags)?["repo-derived","explicit",...s.tags.filter(c=>typeof c=="string")]:["repo-derived","explicit"],skills:jc(a),sourceRepo:{owner:t.owner,repo:t.repo,repoUrl:t.repoUrl,relPath:r},explicit:!0}}async function Fg(e){try{return(await Dc(e)).isFile()}catch{return!1}}async function jg(e){try{return(await Dc(e)).isDirectory()}catch{return!1}}async function _g(e){let t=[];for(let r of Ag){let s=an(e,r);if(await Fg(s))try{t.push({relPath:r,data:JSON.parse(await Nc(s,"utf-8"))})}catch{}}for(let r of Tg){let s=an(e,r);if(!await jg(s))continue;let o;try{o=await Ig(s)}catch{continue}for(let n of o.filter(a=>a.endsWith(".json")).sort()){let a=`${r}/${n}`;try{t.push({relPath:a,data:JSON.parse(await Nc(an(s,n),"utf-8"))})}catch{}}}return t}async function _c(e,t){let r=[],s=await _g(e);for(let o of s){let n=o.data,a=Array.isArray(n?.bundles)?n.bundles:[n];for(let l of a){let c=Mg(l,t,o.relPath);c&&r.push(c)}}return ps(r)}function ps(e){let t=new Map;for(let r of e){let s=t.get(r.name);(!s||r.explicit&&!s.explicit)&&t.set(r.name,r)}return Array.from(t.values()).sort((r,s)=>r.name.localeCompare(s.name))}function Uc(e){let t=e.bundles||[],r=ln(e);return ps([...t,...r])}var qg=8;async function Wg(){let e=tt();return await Bg(e,{recursive:!0}),e}function Kg(e,t){return`github:${e.owner}/${e.repo}${e.ref?`#${e.ref}`:""}${t?`:${t}`:""}`}async function Bc(e){await ve();let t;try{t=oe(e)}catch(s){return{success:!1,repoIndex:null,error:s.message}}if(t.isLocal)return{success:!1,repoIndex:null,error:"Local paths are not supported for indexing. Use a GitHub source instead."};try{de(t,e)}catch(s){return{success:!1,repoIndex:null,error:s.message}}P(`ingester: cloning ${t.owner}/${t.repo}`);let r=null;try{r=await Se(t),P(`ingester: discovering skills in ${r}`);let s=await Ue(r);P(`ingester: found ${s.length} skills`);let{kept:o,decisions:n}=Ac(s);for(let p of n){let f=p.dropped.map(m=>m.relPath).join(", ");P(`ingester: dedupe "${p.name}": kept ${p.kept.relPath} (${p.reason}); dropped ${f}`)}n.length>0&&P(`ingester: deduped ${s.length} -> ${o.length} skills (${n.length} name collision${n.length===1?"":"s"})`);let a=r,l=await Kt(o,qg,async p=>{let f=dr(a,p.relPath,"SKILL.md"),m="";try{m=await Gg(f,"utf-8")}catch{P(`ingester: could not read SKILL.md at ${f}`)}let g=Tc(p,m);g.verified||P(`ingester: ${p.name} not verified: ${g.reasons.join(", ")}`);let h=typeof p.tokenCount=="number"?p.tokenCount:m?Ce(m):void 0,y,b;if(m){let $;try{$=await Hg(dr(a,p.relPath))}catch{$=void 0}try{let v=await gt({content:m,skillPath:p.relPath||p.name,skillMdPath:f,rootEntries:$});y={overallScore:v.overallScore,grade:v.grade,categories:v.categories.map(S=>({id:S.id,name:S.name,score:S.score,max:S.max})),evaluatedAt:v.evaluatedAt,evaluatedVersion:p.version||void 0}}catch(v){P(`ingester: eval failed for ${p.name}: ${v}`)}try{let v={skillPath:dr(a,p.relPath),skillMdPath:f},C=(await Promise.all(or(Qr()).map(async D=>(await D.applicable(v,{})).ok?es(D,v):null))).filter(D=>D!==null).map(D=>il(D,p.version||void 0));C.length>0&&(b=Object.fromEntries(C.filter(D=>D.providerId).map(D=>[D.providerId,D])))}catch(v){P(`ingester: provider eval failed for ${p.name}: ${v}`)}}return{name:p.name,description:p.description,version:p.version,license:p.license,creator:p.creator,compatibility:p.compatibility,allowedTools:p.allowedTools,tags:p.tags,dependencies:p.dependencies,modelInvocable:p.modelInvocable!==!1,userInvocable:p.userInvocable!==!1,installUrl:Kg(t,p.relPath),relPath:p.relPath,verified:g.verified,tokenCount:h,evalSummary:y,evalSummaries:b}}),c={repoUrl:t.cloneUrl,owner:t.owner,repo:t.repo,updatedAt:new Date().toISOString(),skillCount:l.length,skills:l};c.bundles=ps([...await _c(r,c),...ln(c)]);let d=await Wg(),u=dr(d,`${t.owner}_${t.repo}.json`);return await Ug(u,JSON.stringify(c,null,2)+`
773
+ `,"utf-8"),P(`ingester: wrote index to ${u}`),{success:!0,repoIndex:c}}catch(s){return{success:!1,repoIndex:null,error:s.message}}finally{r&&await z(r)}}async function Vc(){return(await $e()).map(t=>({owner:t.owner,repo:t.repo,skillCount:t.skillCount,updatedAt:t.updatedAt})).sort((t,r)=>r.skillCount-t.skillCount)}async function Gc(e,t){let r=tt(),s=dr(r,`${e}_${t}.json`);try{return await Vg(s),!0}catch{return!1}}var St=.55,ms=.7;function Hc(e,t){if(e.size===0&&t.size===0)return 0;let r=new Set;for(let o of e)t.has(o)&&r.add(o);let s=e.size+t.size-r.size;return s===0?0:r.size/s}function Jg(e,t){let r=ce(e.description),s=ce(t.description),o=Hc(r,s),n=ce(e.name),a=ce(t.name),l=Hc(n,a);return .6*o+.4*l}function zg(e,t,r){let s=ce(e.description),o=ce(t.description),a=[...s].filter(c=>o.has(c)).length,l=s.size+o.size-a;return r>=ms?`Very similar descriptions (${a}/${l} shared tokens)`:r>=St?`Similar descriptions (${a}/${l} shared tokens)`:`Some overlapping concepts (${a}/${l} shared tokens)`}function cn(e,t=St){let r=[];for(let s=0;s<e.length;s++)for(let o=s+1;o<e.length;o++){let n=Jg(e[s].skill,e[o].skill);n>=t&&r.push({skillA:e[s].skill,skillB:e[o].skill,repoA:e[s].repo,repoB:e[o].repo,score:n,reason:zg(e[s].skill,e[o].skill,n)})}return r.sort((s,o)=>o.score-s.score),r}function qc(e,t=St){let r=cn(e,t);if(r.length===0)return[];let s=new Map,o=new Map,n=new Map;function a(u){for(;s.get(u)!==u;)s.set(u,s.get(s.get(u))),u=s.get(u);return u}function l(u,p,f){let m=a(u),g=a(p);if(m===g){let h=o.get(m)??0;o.set(m,Math.max(h,f)),n.set(m,(n.get(m)??0)+1);return}if(m!==g){s.set(g,m);let h=Math.max(o.get(m)??0,o.get(g)??0,f);o.set(m,h),n.set(m,(n.get(m)??0)+(n.get(g)??0)+1)}}for(let u=0;u<e.length;u++)s.set(u,u),o.set(u,0),n.set(u,0);for(let u of r){let p=e.findIndex(m=>m.skill.name===u.skillA.name&&m.skill.installUrl===u.skillA.installUrl),f=e.findIndex(m=>m.skill.name===u.skillB.name&&m.skill.installUrl===u.skillB.installUrl);p>=0&&f>=0&&l(p,f,u.score)}let c=new Map;for(let u=0;u<e.length;u++){let p=a(u);c.has(p)||c.set(p,[]),c.get(p).push(u)}let d=[];for(let[u,p]of c){if(p.length<2)continue;let f=o.get(u)??0;if(f<t)continue;let m=n.get(u)??0;d.push({skills:p.map(g=>({skill:e[g].skill,repo:e[g].repo})),maxScore:f,pairCount:m})}return d.sort((u,p)=>p.maxScore-u.maxScore),d}function Yg(){console.log(`${i.bold("Usage:")} asm index <subcommand> [options]
883
774
 
884
775
  Manage the skill index for searching available skills from indexed repos.
885
776
 
886
- ${l.bold("Subcommands:")}
777
+ ${i.bold("Subcommands:")}
887
778
  ingest <repo> Ingest a skill repository into the index
888
779
  search <query> Search indexed skills by name or description
889
780
  list List all indexed repositories
890
781
  remove <owner/repo> Remove a repo from the index
891
782
  overlap Find semantically overlapping skills in the index
892
783
 
893
- ${l.bold("Options:")}
784
+ ${i.bold("Options:")}
894
785
  --json Output as JSON
895
786
  --has <field> Only show skills that have <field> (license, creator, version)
896
787
  --missing <field> Only show skills missing <field> (license, creator, version)
@@ -900,33 +791,33 @@ ${l.bold("Options:")}
900
791
  --no-color Disable ANSI colors
901
792
  -V, --verbose Show debug output
902
793
 
903
- ${l.bold("Examples:")}
904
- asm index ingest github:obra/superpowers ${l.dim("Index superpowers repo")}
905
- asm index search code review ${l.dim("Search for skills")}
906
- asm index search marketing --has license ${l.dim("Only with license")}
907
- asm index search "" --missing creator ${l.dim("Skills missing creator")}
908
- asm index overlap ${l.dim("Find overlapping skills")}
909
- asm index overlap --threshold 0.6 ${l.dim("Custom threshold")}
910
- asm index list ${l.dim("List indexed repos")}
911
- asm index remove obra/superpowers ${l.dim("Remove from index")}`)}async function Oh(e){if(e.flags.help){M0();return}let t=e.subcommand;switch(t||($("Missing subcommand. Use: ingest, search, overlap, list, or remove"),console.error('Run "asm index --help" for usage.'),process.exit(2)),t){case"ingest":{let s=e.positional[0];s||($("Missing required argument: <repo>"),console.error('Run "asm index --help" for usage.'),process.exit(2)),console.error(l.blueBold(`Ingesting ${s}...`));let i=await Lh(s);i.success||($(`Failed to ingest: ${i.error}`),process.exit(1)),i.repoIndex&&(e.flags.json?console.log(q({success:!0,owner:i.repoIndex.owner,repo:i.repoIndex.repo,skillCount:i.repoIndex.skillCount,updatedAt:i.repoIndex.updatedAt})):(console.error(l.green(`Successfully indexed ${i.repoIndex.owner}/${i.repoIndex.repo}`)),console.error(` Skills found: ${i.repoIndex.skillCount}`)));break}case"search":{let s=e.positional.join(" ");!s&&e.flags.has.length===0&&e.flags.missing.length===0&&!e.flags.modelInvocable&&!e.flags.userInvocable&&($("Missing required argument: <query>"),console.error('Run "asm index --help" for usage.'),process.exit(2));let i={};e.flags.has.length>0&&(i.has=e.flags.has),e.flags.missing.length>0&&(i.missing=e.flags.missing),e.flags.modelInvocable&&(i.modelInvocable=!0),e.flags.userInvocable&&(i.userInvocable=!0);let n=i.has||i.missing||i.modelInvocable||i.userInvocable?await qs(s||"",20,i):await qs(s);if(n.length===0){e.flags.json?console.log(q([])):(console.info("No skills found matching your query."),console.error(l.dim("Try ingesting more repos with: asm index ingest <repo>")));return}if(e.flags.json)console.log(q(n.map(o=>({name:o.skill.name,description:o.skill.description,version:o.skill.version,license:o.skill.license||"",creator:o.skill.creator||"",compatibility:o.skill.compatibility||"",allowedTools:o.skill.allowedTools||[],verified:o.skill.verified===!0,installUrl:o.skill.installUrl,installCommand:`asm install ${o.skill.installUrl}`,repo:`${o.repo.owner}/${o.repo.repo}`}))));else{console.error(l.bold(`Found ${n.length} skills:
912
- `));for(let o of n){let a=o.skill.verified?l.blue(" [verified]"):"";console.error(`${l.cyan(o.skill.name)} ${l.dim(`v${o.skill.version}`)}${a} ${l.dim(`[${o.repo.owner}/${o.repo.repo}]`)}`);for(let u of wi(o.skill.description,80))console.error(` ${u}`);let c=Rf(o.skill);c.length>0&&console.error(` ${l.yellow(`\u26A0 Missing: ${c.join(", ")}`)}`),console.error(` ${l.green(`asm install ${o.skill.installUrl}`)}
913
- `)}}break}case"list":{let s=await Ah();if(s.length===0){e.flags.json?console.log(q([])):(console.info("No repositories indexed."),console.error(l.dim("Add repos with: asm index ingest <repo>")));return}let i=await Af();if(e.flags.json)console.log(q(s));else{console.error(l.bold(`Indexed Repositories (${i} total skills):
914
- `));for(let r of s)console.error(`${l.cyan(`${r.owner}/${r.repo}`)} - ${r.skillCount} skills ${l.dim(`(${new Date(r.updatedAt).toLocaleDateString()})`)}`)}break}case"remove":{let s=e.positional[0];s||($("Missing required argument: <owner/repo>"),console.error('Run "asm index --help" for usage.'),process.exit(2));let[i,r]=s.split("/");if((!i||!r)&&($("Invalid format. Use: <owner/repo>"),process.exit(2)),!e.flags.yes&&process.stdin.isTTY){process.stderr.write(`${l.bold("Remove")} ${l.cyan(`${i}/${r}`)} ${l.bold("from index?")} [y/N] `);let o=await H();o.toLowerCase()!=="y"&&o.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}await Rh(i,r)?console.error(l.green(`Removed ${i}/${r} from index`)):($(`Repository not found in index: ${i}/${r}`),process.exit(1));break}case"overlap":{let s=e.flags.threshold??Xt,i=500,r=await la(),n=r.slice(0,i);if(n.length===0){e.flags.json?console.log(q({groups:[],pairs:[],totalSkills:0})):console.info("No skills indexed. Run `asm index ingest` first.");return}let o=Rl(n,s);if(o.length===0){e.flags.json?console.log(q({groups:[],pairs:[],totalSkills:r.length,threshold:s,message:`No overlaps found above threshold ${s}`})):console.info(l.green(`No semantic overlaps found above threshold ${s} across ${r.length} indexed skills (comparing top ${i}).`));return}let a=Th(n,s);if(e.flags.json)console.log(q({groups:a.map(c=>({skills:c.skills.map(u=>({name:u.skill.name,description:u.skill.description,repo:`${u.repo.owner}/${u.repo.repo}`})),maxScore:c.maxScore,pairCount:c.pairCount})),pairs:o.map(c=>({skillA:c.skillA.name,skillB:c.skillB.name,repoA:`${c.repoA.owner}/${c.repoA.repo}`,repoB:`${c.repoB.owner}/${c.repoB.repo}`,score:c.score,reason:c.reason})),totalSkills:r.length,skillsCompared:n.length,threshold:s,totalOverlappingPairs:o.length,totalOverlapGroups:a.length}));else{if(console.error(l.bold(`Found ${o.length} overlapping pair(s) among ${r.length} indexed skills (comparing top ${i}, threshold: ${s}):
915
- `)),a.length>0){console.error(l.yellow(` ${a.length} group(s):
916
- `));for(let c of a){console.error(` ${l.bold(`Group (max score: ${c.maxScore.toFixed(3)}, ${c.pairCount} pair(s))`)}
917
- `);for(let u of c.skills){let f=c.maxScore>=ln?l.yellow(" [high overlap]"):"";console.error(` ${l.cyan(u.skill.name)} ${l.dim(`[${u.repo.owner}/${u.repo.repo}]`)}${f}
918
- `);for(let d of wi(u.skill.description,72))console.error(` ${d}`)}console.error("")}}console.error(l.yellow(` ${o.length} overlapping pair(s):
919
- `));for(let c of o.slice(0,20)){let u=c.score>=ln?l.red("HIGH"):c.score>=Xt?l.yellow("MED"):l.dim("LOW");console.error(` ${u} ${c.score.toFixed(3)} ${l.cyan(c.skillA.name)} \u2194 ${l.cyan(c.skillB.name)}
794
+ ${i.bold("Examples:")}
795
+ asm index ingest github:obra/superpowers ${i.dim("Index superpowers repo")}
796
+ asm index search code review ${i.dim("Search for skills")}
797
+ asm index search marketing --has license ${i.dim("Only with license")}
798
+ asm index search "" --missing creator ${i.dim("Skills missing creator")}
799
+ asm index overlap ${i.dim("Find overlapping skills")}
800
+ asm index overlap --threshold 0.6 ${i.dim("Custom threshold")}
801
+ asm index list ${i.dim("List indexed repos")}
802
+ asm index remove obra/superpowers ${i.dim("Remove from index")}`)}async function Wc(e){if(e.flags.help){Yg();return}let t=e.subcommand;switch(t||(w("Missing subcommand. Use: ingest, search, overlap, list, or remove"),console.error('Run "asm index --help" for usage.'),process.exit(2)),t){case"ingest":{let r=e.positional[0];r||(w("Missing required argument: <repo>"),console.error('Run "asm index --help" for usage.'),process.exit(2)),console.error(i.blueBold(`Ingesting ${r}...`));let s=await Bc(r);s.success||(w(`Failed to ingest: ${s.error}`),process.exit(1)),s.repoIndex&&(e.flags.json?console.log(j({success:!0,owner:s.repoIndex.owner,repo:s.repoIndex.repo,skillCount:s.repoIndex.skillCount,updatedAt:s.repoIndex.updatedAt})):(console.error(i.green(`Successfully indexed ${s.repoIndex.owner}/${s.repoIndex.repo}`)),console.error(` Skills found: ${s.repoIndex.skillCount}`)));break}case"search":{let r=e.positional.join(" ");!r&&e.flags.has.length===0&&e.flags.missing.length===0&&!e.flags.modelInvocable&&!e.flags.userInvocable&&(w("Missing required argument: <query>"),console.error('Run "asm index --help" for usage.'),process.exit(2));let s={};e.flags.has.length>0&&(s.has=e.flags.has),e.flags.missing.length>0&&(s.missing=e.flags.missing),e.flags.modelInvocable&&(s.modelInvocable=!0),e.flags.userInvocable&&(s.userInvocable=!0);let n=s.has||s.missing||s.modelInvocable||s.userInvocable?await Ft(r||"",20,s):await Ft(r);if(n.length===0){e.flags.json?console.log(j([])):(console.info("No skills found matching your query."),console.error(i.dim("Try ingesting more repos with: asm index ingest <repo>")));return}if(e.flags.json)console.log(j(n.map(a=>({name:a.skill.name,description:a.skill.description,version:a.skill.version,license:a.skill.license||"",creator:a.skill.creator||"",compatibility:a.skill.compatibility||"",allowedTools:a.skill.allowedTools||[],verified:a.skill.verified===!0,installUrl:a.skill.installUrl,installCommand:`asm install ${a.skill.installUrl}`,repo:`${a.repo.owner}/${a.repo.repo}`}))));else{console.error(i.bold(`Found ${n.length} skills:
803
+ `));for(let a of n){let l=a.skill.verified?i.blue(" [verified]"):"";console.error(`${i.cyan(a.skill.name)} ${i.dim(`v${a.skill.version}`)}${l} ${i.dim(`[${a.repo.owner}/${a.repo.repo}]`)}`);for(let d of yr(a.skill.description,80))console.error(` ${d}`);let c=xi(a.skill);c.length>0&&console.error(` ${i.yellow(`\u26A0 Missing: ${c.join(", ")}`)}`),console.error(` ${i.green(`asm install ${a.skill.installUrl}`)}
804
+ `)}}break}case"list":{let r=await Vc();if(r.length===0){e.flags.json?console.log(j([])):(console.info("No repositories indexed."),console.error(i.dim("Add repos with: asm index ingest <repo>")));return}let s=await $i();if(e.flags.json)console.log(j(r));else{console.error(i.bold(`Indexed Repositories (${s} total skills):
805
+ `));for(let o of r)console.error(`${i.cyan(`${o.owner}/${o.repo}`)} - ${o.skillCount} skills ${i.dim(`(${new Date(o.updatedAt).toLocaleDateString()})`)}`)}break}case"remove":{let r=e.positional[0];r||(w("Missing required argument: <owner/repo>"),console.error('Run "asm index --help" for usage.'),process.exit(2));let[s,o]=r.split("/");if((!s||!o)&&(w("Invalid format. Use: <owner/repo>"),process.exit(2)),!e.flags.yes&&process.stdin.isTTY){process.stderr.write(`${i.bold("Remove")} ${i.cyan(`${s}/${o}`)} ${i.bold("from index?")} [y/N] `);let a=await G();a.toLowerCase()!=="y"&&a.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}await Gc(s,o)?console.error(i.green(`Removed ${s}/${o} from index`)):(w(`Repository not found in index: ${s}/${o}`),process.exit(1));break}case"overlap":{let r=e.flags.threshold??St,s=500,o=await As(),n=o.slice(0,s);if(n.length===0){e.flags.json?console.log(j({groups:[],pairs:[],totalSkills:0})):console.info("No skills indexed. Run `asm index ingest` first.");return}let a=cn(n,r);if(a.length===0){e.flags.json?console.log(j({groups:[],pairs:[],totalSkills:o.length,threshold:r,message:`No overlaps found above threshold ${r}`})):console.info(i.green(`No semantic overlaps found above threshold ${r} across ${o.length} indexed skills (comparing top ${s}).`));return}let l=qc(n,r);if(e.flags.json)console.log(j({groups:l.map(c=>({skills:c.skills.map(d=>({name:d.skill.name,description:d.skill.description,repo:`${d.repo.owner}/${d.repo.repo}`})),maxScore:c.maxScore,pairCount:c.pairCount})),pairs:a.map(c=>({skillA:c.skillA.name,skillB:c.skillB.name,repoA:`${c.repoA.owner}/${c.repoA.repo}`,repoB:`${c.repoB.owner}/${c.repoB.repo}`,score:c.score,reason:c.reason})),totalSkills:o.length,skillsCompared:n.length,threshold:r,totalOverlappingPairs:a.length,totalOverlapGroups:l.length}));else{if(console.error(i.bold(`Found ${a.length} overlapping pair(s) among ${o.length} indexed skills (comparing top ${s}, threshold: ${r}):
806
+ `)),l.length>0){console.error(i.yellow(` ${l.length} group(s):
807
+ `));for(let c of l){console.error(` ${i.bold(`Group (max score: ${c.maxScore.toFixed(3)}, ${c.pairCount} pair(s))`)}
808
+ `);for(let d of c.skills){let u=c.maxScore>=ms?i.yellow(" [high overlap]"):"";console.error(` ${i.cyan(d.skill.name)} ${i.dim(`[${d.repo.owner}/${d.repo.repo}]`)}${u}
809
+ `);for(let p of yr(d.skill.description,72))console.error(` ${p}`)}console.error("")}}console.error(i.yellow(` ${a.length} overlapping pair(s):
810
+ `));for(let c of a.slice(0,20)){let d=c.score>=ms?i.red("HIGH"):c.score>=St?i.yellow("MED"):i.dim("LOW");console.error(` ${d} ${c.score.toFixed(3)} ${i.cyan(c.skillA.name)} \u2194 ${i.cyan(c.skillB.name)}
920
811
  `),console.error(` ${c.repoA.owner}/${c.repoA.repo} \u2194 ${c.repoB.owner}/${c.repoB.repo}
921
- `);for(let f of wi(c.reason,72))console.error(` ${f}`);console.error("")}o.length>20&&console.error(l.dim(` \u2026 and ${o.length-20} more pair(s). Use --json for full list.`))}break}default:$(`Unknown subcommand: "${t}"`),console.error('Run "asm index --help" for usage.'),process.exit(2)}}import{readFile as D0,writeFile as F0,readdir as Mh,access as Dh,mkdir as _0,rm as j0}from"fs/promises";import{join as vt,resolve as Fh,dirname as B0}from"path";import{fileURLToPath as q0}from"url";var U0=q0(import.meta.url),V0=B0(U0),cn=Fh(V0,"..","data","bundles");function K0(e){let t=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Bundle must be a JSON object."]};let s=e;if(s.version!==1&&t.push(`Unsupported bundle version: ${JSON.stringify(s.version)}. Expected 1.`),(typeof s.name!="string"||!s.name)&&t.push("Missing or empty 'name' field."),(typeof s.description!="string"||!s.description)&&t.push("Missing or empty 'description' field."),(typeof s.author!="string"||!s.author)&&t.push("Missing or empty 'author' field."),typeof s.createdAt!="string"&&t.push("Missing or invalid 'createdAt' field."),!Array.isArray(s.skills))return t.push("Missing or invalid 'skills' array."),{valid:!1,errors:t};s.skills.length===0&&t.push("Bundle must contain at least one skill.");for(let i=0;i<s.skills.length;i++){let r=s.skills[i];if(typeof r!="object"||r===null){t.push(`skills[${i}]: must be an object.`);continue}let n=r;(typeof n.name!="string"||!n.name)&&t.push(`skills[${i}]: missing or empty 'name'.`),(typeof n.installUrl!="string"||!n.installUrl)&&t.push(`skills[${i}]: missing or empty 'installUrl'.`)}return s.tags!==void 0&&(Array.isArray(s.tags)?s.tags.some(i=>typeof i!="string")&&t.push("'tags' must contain only strings."):t.push("'tags' must be an array of strings if provided.")),{valid:t.length===0,errors:t}}function _h(e,t,s,i,r){return{version:1,name:e,description:t,author:s,createdAt:new Date().toISOString(),skills:i,tags:r}}async function jh(e,t){let s=t??await Ke(),i=s.skills[e.name]||s.skills[e.dirName],r;return e.isSymlink&&e.symlinkTarget?r=e.symlinkTarget:i?.source?r=i.source:r=e.path,{name:e.name,installUrl:r,description:e.description||void 0,version:e.version||void 0}}function kt(){return vt(ki(),"bundles")}async function G0(){await _0(kt(),{recursive:!0})}function pi(e){let t=e.toLowerCase().replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(t=t.replace(/^\.+|\.+$/g,""),!t||t==="."||t==="..")throw new Error("Invalid bundle name: results in an empty filename after sanitization.");return t}async function Nl(e){await G0();let t=`${pi(e.name)}.json`,s=vt(kt(),t);return await F0(s,JSON.stringify(e,null,2)+`
922
- `,"utf-8"),L(`bundle: saved to ${s}`),s}async function fi(e){let t;try{t=await D0(e,"utf-8")}catch(r){throw r?.code==="ENOENT"?new Error(`Bundle file not found: ${e}`,{cause:r}):new Error(`Failed to read bundle file: ${r.message}`,{cause:r})}let s;try{s=JSON.parse(t)}catch{throw new Error("Bundle file is not valid JSON.")}let i=K0(s);if(!i.valid)throw new Error(`Invalid bundle:
923
- ${i.errors.join(`
924
- `)}`);return s}async function mi(e){if(e.includes("/")||e.includes("\\")||e.endsWith(".json")){let i=Fh(e);return fi(i)}let t=`${pi(e)}.json`,s=vt(kt(),t);try{return await fi(s)}catch(i){if(i?.message?.includes("Bundle file not found")){let r=vt(cn,t);try{return await fi(r)}catch(n){if(n?.message?.includes("Bundle file not found")){let o=await H0(e);if(o)return o;throw new Error(`Bundle file not found: ${s}`,{cause:n})}throw n}}throw i}}async function Bh(){let e=[];try{await Dh(cn);let s;try{s=await Mh(cn)}catch{s=[]}for(let i of s){if(!i.endsWith(".json"))continue;let r=vt(cn,i);try{let n=await fi(r);e.push(n)}catch{L(`bundle: skipping invalid predefined file ${r}`)}}}catch{}e.push(...await qh());let t=new Map;for(let s of e)t.has(s.name)||t.set(s.name,s);return Array.from(t.values()).sort((s,i)=>s.name.localeCompare(i.name))}async function qh(){try{return(await Oe()).flatMap(t=>Ih(t))}catch(e){return L(`bundle: failed to load repo-derived bundles: ${e}`),[]}}async function H0(e){let t=pi(e),s=await qh();return s.find(i=>i.name===e)||s.find(i=>pi(i.name)===t)||null}async function Uh(){let e=[];try{await Dh(kt())}catch{return e}let t;try{t=await Mh(kt())}catch{return e}for(let s of t){if(!s.endsWith(".json"))continue;let i=vt(kt(),s);try{let r=await fi(i);e.push(r)}catch{L(`bundle: skipping invalid file ${i}`)}}return e.sort((s,i)=>s.name.localeCompare(i.name)),e}async function Vh(e){let t=`${pi(e)}.json`,s=vt(kt(),t);try{return await j0(s),L(`bundle: removed ${s}`),!0}catch(i){if(i?.code==="ENOENT")return!1;throw i}}import{join as J0}from"path";function W0(){console.log(`${l.bold("Usage:")} asm bundle <subcommand> [options]
812
+ `);for(let u of yr(c.reason,72))console.error(` ${u}`);console.error("")}a.length>20&&console.error(i.dim(` \u2026 and ${a.length-20} more pair(s). Use --json for full list.`))}break}default:w(`Unknown subcommand: "${t}"`),console.error('Run "asm index --help" for usage.'),process.exit(2)}}import{readFile as Zg,writeFile as Xg,readdir as Kc,access as Jc,mkdir as Qg,rm as eh}from"fs/promises";import{join as Ze,resolve as zc,dirname as th}from"path";import{fileURLToPath as rh}from"url";var sh=rh(import.meta.url),oh=th(sh),fs=zc(oh,"..","data","bundles");function nh(e){let t=[];if(typeof e!="object"||e===null||Array.isArray(e))return{valid:!1,errors:["Bundle must be a JSON object."]};let r=e;if(r.version!==1&&t.push(`Unsupported bundle version: ${JSON.stringify(r.version)}. Expected 1.`),(typeof r.name!="string"||!r.name)&&t.push("Missing or empty 'name' field."),(typeof r.description!="string"||!r.description)&&t.push("Missing or empty 'description' field."),(typeof r.author!="string"||!r.author)&&t.push("Missing or empty 'author' field."),typeof r.createdAt!="string"&&t.push("Missing or invalid 'createdAt' field."),!Array.isArray(r.skills))return t.push("Missing or invalid 'skills' array."),{valid:!1,errors:t};r.skills.length===0&&t.push("Bundle must contain at least one skill.");for(let s=0;s<r.skills.length;s++){let o=r.skills[s];if(typeof o!="object"||o===null){t.push(`skills[${s}]: must be an object.`);continue}let n=o;(typeof n.name!="string"||!n.name)&&t.push(`skills[${s}]: missing or empty 'name'.`),(typeof n.installUrl!="string"||!n.installUrl)&&t.push(`skills[${s}]: missing or empty 'installUrl'.`)}return r.tags!==void 0&&(Array.isArray(r.tags)?r.tags.some(s=>typeof s!="string")&&t.push("'tags' must contain only strings."):t.push("'tags' must be an array of strings if provided.")),{valid:t.length===0,errors:t}}function Yc(e,t,r,s,o){return{version:1,name:e,description:t,author:r,createdAt:new Date().toISOString(),skills:s,tags:o}}async function Zc(e,t){let r=t??await Te(),s=r.skills[e.name]||r.skills[e.dirName],o;return e.isSymlink&&e.symlinkTarget?o=e.symlinkTarget:s?.source?o=s.source:o=e.path,{name:e.name,installUrl:o,description:e.description||void 0,version:e.version||void 0}}function Ye(){return Ze(br(),"bundles")}async function ih(){await Qg(Ye(),{recursive:!0})}function pr(e){let t=e.toLowerCase().replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"");if(t=t.replace(/^\.+|\.+$/g,""),!t||t==="."||t==="..")throw new Error("Invalid bundle name: results in an empty filename after sanitization.");return t}async function dn(e){await ih();let t=`${pr(e.name)}.json`,r=Ze(Ye(),t);return await Xg(r,JSON.stringify(e,null,2)+`
813
+ `,"utf-8"),P(`bundle: saved to ${r}`),r}async function ur(e){let t;try{t=await Zg(e,"utf-8")}catch(o){throw o?.code==="ENOENT"?new Error(`Bundle file not found: ${e}`,{cause:o}):new Error(`Failed to read bundle file: ${o.message}`,{cause:o})}let r;try{r=JSON.parse(t)}catch{throw new Error("Bundle file is not valid JSON.")}let s=nh(r);if(!s.valid)throw new Error(`Invalid bundle:
814
+ ${s.errors.join(`
815
+ `)}`);return r}async function mr(e){if(e.includes("/")||e.includes("\\")||e.endsWith(".json")){let s=zc(e);return ur(s)}let t=`${pr(e)}.json`,r=Ze(Ye(),t);try{return await ur(r)}catch(s){if(s?.message?.includes("Bundle file not found")){let o=Ze(fs,t);try{return await ur(o)}catch(n){if(n?.message?.includes("Bundle file not found")){let a=await ah(e);if(a)return a;throw new Error(`Bundle file not found: ${r}`,{cause:n})}throw n}}throw s}}async function Xc(){let e=[];try{await Jc(fs);let r;try{r=await Kc(fs)}catch{r=[]}for(let s of r){if(!s.endsWith(".json"))continue;let o=Ze(fs,s);try{let n=await ur(o);e.push(n)}catch{P(`bundle: skipping invalid predefined file ${o}`)}}}catch{}e.push(...await Qc());let t=new Map;for(let r of e)t.has(r.name)||t.set(r.name,r);return Array.from(t.values()).sort((r,s)=>r.name.localeCompare(s.name))}async function Qc(){try{return(await $e()).flatMap(t=>Uc(t))}catch(e){return P(`bundle: failed to load repo-derived bundles: ${e}`),[]}}async function ah(e){let t=pr(e),r=await Qc();return r.find(s=>s.name===e)||r.find(s=>pr(s.name)===t)||null}async function ed(){let e=[];try{await Jc(Ye())}catch{return e}let t;try{t=await Kc(Ye())}catch{return e}for(let r of t){if(!r.endsWith(".json"))continue;let s=Ze(Ye(),r);try{let o=await ur(s);e.push(o)}catch{P(`bundle: skipping invalid file ${s}`)}}return e.sort((r,s)=>r.name.localeCompare(s.name)),e}async function td(e){let t=`${pr(e)}.json`,r=Ze(Ye(),t);try{return await eh(r),P(`bundle: removed ${r}`),!0}catch(s){if(s?.code==="ENOENT")return!1;throw s}}import{join as lh}from"path";function ch(){console.log(`${i.bold("Usage:")} asm bundle <subcommand> [options]
925
816
 
926
817
  Create, install, and manage curated skill bundles. A bundle is a reusable
927
818
  recipe of skills for a particular workflow, domain, or project setup.
928
819
 
929
- ${l.bold("Subcommands:")}
820
+ ${i.bold("Subcommands:")}
930
821
  create <name> Create a new bundle from installed skills
931
822
  install <name|file> Install all skills from a bundle (supports pre-defined names)
932
823
  list List all saved bundles
@@ -936,55 +827,67 @@ ${l.bold("Subcommands:")}
936
827
  modify <name> Add/remove skills or update bundle metadata
937
828
  export <name> [file] Export a bundle to a JSON file
938
829
 
939
- ${l.bold("Options:")}
940
- -s, --scope <s> Filter: global, project, or both (default: both)
941
- -y, --yes Skip confirmation prompts
830
+ ${i.bold("Options:")}
831
+ -p, --tool <name> install: target tool (claude, codex, openclaw, agents, all)
832
+ -s, --scope <s> install: install scope, global or project (default: global)
833
+ create/list: filter by global, project, or both (default: both)
834
+ -y, --yes Skip confirmation prompts and the skill/scope pickers
942
835
  --json Output as JSON
943
836
  --predefined Show pre-defined bundles shipped with ASM (for list)
944
837
  --no-color Disable ANSI colors
945
838
  -V, --verbose Show debug output
946
839
 
947
- ${l.bold("Examples:")}
948
- asm bundle create my-workflow ${l.dim("Create from installed skills")}
949
- asm bundle install my-workflow ${l.dim("Install a saved bundle")}
950
- asm bundle install frontend-dev ${l.dim("Install a pre-defined bundle")}
951
- asm bundle install ./bundle.json ${l.dim("Install from file")}
952
- asm bundle list ${l.dim("Show all saved bundles")}
953
- asm bundle list --predefined ${l.dim("List pre-defined bundles")}
954
- asm bundle list --json ${l.dim("List bundles as JSON")}
955
- asm bundle show my-workflow ${l.dim("Show bundle details")}
956
- asm bundle remove my-workflow ${l.dim("Remove a saved bundle")}
957
- asm bundle modify my-workflow --add github:u/r ${l.dim("Add a skill to bundle")}
958
- asm bundle modify my-workflow --remove skill ${l.dim("Remove a skill from bundle")}
959
- asm bundle export my-workflow ${l.dim("Export to ./my-workflow.json")}
960
- asm bundle export my-workflow out.json ${l.dim("Export bundle to file")}`)}async function Kh(e){if(e.flags.help){W0();return}let t=e.subcommand;switch(t||($("Missing subcommand. Use: create, install, list, show, remove, modify, or export"),console.error('Run "asm bundle --help" for usage.'),process.exit(2)),t){case"create":{let s=e.positional[0];s||($("Missing required argument: <name>"),console.error("Usage: asm bundle create <name>"),process.exit(2));let i=await j(),r=await K(i,e.flags.scope);r.length===0&&($("No skills found to include in the bundle."),process.exit(1));let n=new Set,o=r.filter(h=>{let y=h.name.toLowerCase();return n.has(y)?!1:(n.add(y),!0)}),a=o;if(process.stdin.isTTY&&!e.flags.yes){let h=o.map(b=>({label:`${b.name} v${b.version}`,hint:b.description?b.description.slice(0,60)+(b.description.length>60?"...":""):`(${b.provider}/${b.scope})`,checked:!0}));console.error(l.bold(`Select skills for bundle "${s}":
961
- `));let y=await ht({items:h});y.length===0&&($("No skills selected. Bundle not created."),process.exit(1)),a=y.map(b=>o[b])}let{readLock:c}=await import("./lock-RVOMV2LT.js"),u=await c(),f=await Promise.all(a.map(h=>jh(h,u))),d=`Bundle of ${f.length} skills`,p="unknown";try{let{execFile:h}=await import("child_process"),{promisify:y}=await import("util"),k=(await y(h)("git",["config","user.name"],{encoding:"utf-8",timeout:5e3})).stdout.trim();k&&(p=k)}catch{}if(process.stdin.isTTY&&!e.flags.yes){process.stderr.write(`
962
- ${l.bold("Description")} (optional, press Enter to skip): `);let h=await H();h.trim()&&(d=h.trim()),process.stderr.write(`${l.bold("Author")} (optional, press Enter to skip): `);let y=await H();y.trim()&&(p=y.trim())}let m=_h(s,d,p,f),g=await Nl(m);e.flags.json?console.log(JSON.stringify(m,null,2)):(console.error(l.green(`Bundle "${s}" created with ${f.length} skill(s).`)),console.error(` Saved to: ${l.dim(g)}`));break}case"install":{let s=e.positional[0];s||($("Missing required argument: <name|file>"),console.error("Usage: asm bundle install <name|file>"),process.exit(2));let i;try{i=await mi(s)}catch(d){$(d.message),process.exit(1)}console.error(`${l.bold("Bundle:")} ${i.name} (${i.skills.length} skills)`),i.description&&console.error(` ${l.dim(i.description)}`),console.error("");for(let d of i.skills){let p=d.version?` v${d.version}`:"";console.error(` ${l.cyan(d.name)}${l.dim(p)} ${l.dim(`-> ${d.installUrl}`)}`)}if(!e.flags.yes&&process.stdin.isTTY){process.stderr.write(`
963
- ${l.bold("Install all skills from this bundle?")} [y/N] `);let d=await H();d.toLowerCase()!=="y"&&d.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let r=[],n=await j(),{provider:o}=await ke(n,e.flags.provider,!1),a=e.flags.scope==="global"||e.flags.scope==="project"?e.flags.scope:"global";for(let d of i.skills){console.error(`
964
- Installing ${l.bold(d.name)}...`);try{(d.installUrl.startsWith("github:")||d.installUrl.startsWith("https://github.com/"))&&await Ae();let m=ue(d.installUrl),g=!!m.isLocal,h=null;try{let y,b;if(g)y=m.localPath,b=m.localPath;else{ye(m,d.installUrl),h=await Re(m,e.flags.transport),y=h,b=m.subpath?J0(h,m.subpath):h;try{Be(h,b,d.installUrl)}catch(x){throw await Q(h),h=null,x}}let k=await we(b),w=be(d.name||k.name||m.repo),v=Js(m,y,b,w,o,e.flags.force,a);try{await va(v.targetDir,v.force)}catch(x){if(x.message?.includes("--force")){r.push({name:d.name,status:"skipped",reason:"Already installed. Use --force to overwrite."}),console.error(` ${l.dim("---")} ${d.name} skipped (already installed)`);continue}throw x}await Vt(v),r.push({name:d.name,status:"installed"}),console.error(` ${l.green("+++")} ${d.name} installed`)}finally{h&&await Q(h)}}catch(p){r.push({name:d.name,status:"failed",reason:p.message}),console.error(` ${l.red("!!!")} ${d.name}: ${p.message}`)}}let c=r.filter(d=>d.status==="installed").length,u=r.filter(d=>d.status==="skipped").length,f=r.filter(d=>d.status==="failed").length;e.flags.json?console.log(JSON.stringify({bundleName:i.name,total:r.length,installed:c,skipped:u,failed:f,results:r},null,2)):(console.error(""),console.error(`${l.bold("Summary:")} ${r.length} total, ${l.green(String(c))} installed, `+(u>0?`${l.dim(String(u))} skipped, `:"")+`${l.red(String(f))} failed`)),f>0&&(process.exitCode=1);break}case"list":{if(!!e.flags.predefined){let r=await Bh();if(r.length===0){e.flags.json?console.log("[]"):console.log("No predefined bundles found.");return}if(e.flags.json)console.log(JSON.stringify(r,null,2));else{console.error(l.bold(`Pre-defined Bundles (${r.length}):
965
- `));for(let n of r){let o=n.tags&&n.tags.length>0?` ${l.dim(`[${n.tags.join(", ")}]`)}`:"";console.error(` ${l.cyan(n.name)} ${l.dim(`(${n.skills.length} skills)`)}${o}`),n.description&&console.error(` ${l.dim(n.description)}`)}console.error(`
966
- ${l.dim("Install a bundle with: asm bundle install <name>")}`)}return}let i=await Uh();if(i.length===0){e.flags.json?console.log("[]"):(console.log("No bundles found."),console.error(l.dim("Create one with: asm bundle create <name>")),console.error(l.dim("List pre-defined bundles with: asm bundle list --predefined")));return}if(e.flags.json)console.log(JSON.stringify(i,null,2));else{console.error(l.bold(`Saved Bundles (${i.length}):
967
- `));for(let r of i){let n=r.tags&&r.tags.length>0?` ${l.dim(`[${r.tags.join(", ")}]`)}`:"";console.error(` ${l.cyan(r.name)} ${l.dim(`(${r.skills.length} skills)`)}${n}`),r.description&&console.error(` ${l.dim(r.description)}`),r.author&&console.error(` ${l.dim(`by ${r.author}`)}`)}}break}case"show":{let s=e.positional[0];s||($("Missing required argument: <name|file>"),console.error("Usage: asm bundle show <name|file>"),process.exit(2));let i;try{i=await mi(s)}catch(r){$(r.message),process.exit(1)}if(e.flags.json)console.log(JSON.stringify(i,null,2));else{console.error(l.bold(`Bundle: ${i.name}`)),i.description&&console.error(` ${i.description}`),i.author&&console.error(` ${l.dim(`Author: ${i.author}`)}`),console.error(` ${l.dim(`Created: ${new Date(i.createdAt).toLocaleString()}`)}`),i.tags&&i.tags.length>0&&console.error(` ${l.dim(`Tags: ${i.tags.join(", ")}`)}`),console.error(`
968
- ${l.bold(`Skills (${i.skills.length})`)}:`);for(let r of i.skills){let n=r.version?` v${r.version}`:"";console.error(` ${l.cyan(r.name)}${l.dim(n)}`),r.description&&console.error(` ${l.dim(r.description)}`),console.error(` ${l.dim(`install: ${r.installUrl}`)}`)}}break}case"remove":{let s=e.positional[0];if(s||($("Missing required argument: <name>"),console.error("Usage: asm bundle remove <name>"),process.exit(2)),!e.flags.yes&&process.stdin.isTTY){process.stderr.write(`${l.bold("Remove bundle")} ${l.cyan(s)}${l.bold("?")} [y/N] `);let r=await H();r.toLowerCase()!=="y"&&r.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let i;try{i=await Vh(s)}catch(r){$(r.message),process.exit(1)}i?console.error(l.green(`Bundle "${s}" removed.`)):($(`Bundle "${s}" not found.`),process.exit(1));break}case"modify":{let s=e.positional[0];s||($("Missing required argument: <name>"),console.error("Usage: asm bundle modify <name> [--add <installUrl>] [--remove <skillName>] [--description <desc>] [--author <author>] [--tags <tag,...>]"),process.exit(2));let i;try{i=await mi(s)}catch(d){$(d.message),process.exit(1)}let r=!1,n=e.flags.add;if(n){let d={name:n.split("/").pop()?.replace(/\.json$/,"")??n,installUrl:n};i.skills.push(d),r=!0,console.error(l.green(`Added skill from ${n}`))}let o=e.flags.remove;if(o){let d=i.skills.length;i.skills=i.skills.filter(p=>p.name.toLowerCase()!==o.toLowerCase()),i.skills.length<d?(r=!0,console.error(l.green(`Removed skill "${o}"`))):console.error(l.dim(`Skill "${o}" not found in bundle (no change)`))}let a=e.flags.description;a!==null&&(i.description=a,r=!0);let c=e.flags.author;c!==null&&(i.author=c,r=!0);let u=e.flags.tags;if(u!==null&&(i.tags=u.split(",").map(d=>d.trim()).filter(d=>d.length>0),r=!0),!r&&process.stdin.isTTY&&!e.flags.yes&&!n&&!o&&a===null&&c===null&&u===null){console.error(l.bold(`Modifying bundle "${i.name}"`)),console.error(` Current skills: ${i.skills.map(g=>g.name).join(", ")}`),console.error(` Description: ${i.description}`),console.error(` Author: ${i.author}`),console.error(` Tags: ${i.tags?.join(", ")??"(none)"}`),console.error(""),process.stderr.write(`${l.bold("New description")} (Enter to keep current): `);let d=await H();d.trim()&&(i.description=d.trim(),r=!0),process.stderr.write(`${l.bold("New author")} (Enter to keep current): `);let p=await H();p.trim()&&(i.author=p.trim(),r=!0),process.stderr.write(`${l.bold("New tags (comma-separated)")} (Enter to keep current): `);let m=await H();m.trim()&&(i.tags=m.split(",").map(g=>g.trim()).filter(g=>g.length>0),r=!0)}if(!r){console.error(l.dim("No changes made to bundle."));break}i.skills.length===0&&($("Bundle must contain at least one skill after modification."),process.exit(1));let f=await Nl(i);e.flags.json?console.log(JSON.stringify(i,null,2)):(console.error(l.green(`Bundle "${i.name}" updated (${i.skills.length} skill(s)).`)),console.error(` Saved to: ${l.dim(f)}`));break}case"export":{let s=e.positional[0];s||($("Missing required argument: <name>"),console.error("Usage: asm bundle export <name> [output-file]"),process.exit(2));let i;try{i=await mi(s)}catch(c){$(c.message),process.exit(1)}let r=e.positional[1]??`./${s}.json`,{resolve:n}=await import("path"),o=n(r);if(!e.flags.force){let{access:c}=await import("fs/promises");try{if(await c(o),process.stdin.isTTY&&!e.flags.yes){process.stderr.write(`File ${l.bold(o)} already exists. Overwrite? [y/N] `);let u=await H();u.toLowerCase()!=="y"&&u.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}else e.flags.yes||($(`File "${o}" already exists. Use --force to overwrite.`),process.exit(1))}catch{}}let{writeFile:a}=await import("fs/promises");await a(o,JSON.stringify(i,null,2)+`
969
- `,"utf-8"),e.flags.json?console.log(JSON.stringify({exported:!0,path:o,bundle:i},null,2)):console.error(l.green(`Exported to ${o}`));break}default:$(`Unknown subcommand: "${t}". Use: create, install, list, show, remove, modify, or export`),console.error('Run "asm bundle --help" for usage.'),process.exit(2)}}import{readFile as Y0,realpath as z0}from"fs/promises";import{join as X0,resolve as Z0,relative as Q0}from"path";function un(e){return e.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[^[\]]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}function eE(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\[/g,"\\[").replace(/\]/g,"\\]").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\|/g,"\\|")}function Tl(e){return eE(un(e))}var St="luongnv89/asm-registry";async function tE(e){let t=X0(e,"SKILL.md"),s;try{s=await Y0(t,"utf-8")}catch{throw new Error(`No SKILL.md found in ${e}. Run "asm init" to create one.`)}let i=W(s);if(!i.name)throw new Error("SKILL.md is missing required field: name");if(!i.description)throw new Error("SKILL.md is missing required field: description");let r=fe(i),n=i.tags?i.tags.split(/[\s,]+/).map(o=>o.trim().toLowerCase()).filter(Boolean):[];return{name:i.name,description:i.description.replace(/\s*\n\s*/g," ").trim(),version:r,license:i.license||"MIT",creator:i.creator||"",tags:n}}async function sE(e){let{exitCode:t}=await oe(["git","rev-parse","--git-dir"],{cwd:e});if(t!==0)throw new Error(`${e} is not inside a git repository.`)}async function iE(e){let{stdout:t,exitCode:s}=await oe(["git","rev-parse","HEAD"],{cwd:e});if(s!==0)throw new Error("Failed to get HEAD commit. Is this a git repository?");return t.trim()}async function rE(e){let{stdout:t,exitCode:s}=await oe(["git","rev-parse","--show-toplevel"],{cwd:e});if(s!==0)throw new Error("Failed to determine git repository root.");return t.trim()}async function nE(e){let{stdout:t,exitCode:s}=await oe(["git","remote","get-url","origin"],{cwd:e});if(s!==0)throw new Error("No remote origin found. Add one with: git remote add origin <url>");let i=t.trim(),r=i.match(/^git@github\.com:([a-zA-Z0-9_-]+)\/([a-zA-Z0-9._-]+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}/${r[2]}`:i.replace(/\.git$/,"")}async function oE(){let{exitCode:e}=await oe(["gh","--version"]);if(e!==0)return{available:!1,authenticated:!1,login:null};let{exitCode:t}=await oe(["gh","auth","status"]);if(t!==0)return{available:!0,authenticated:!1,login:null};let{stdout:s,exitCode:i}=await oe(["gh","api","user","--jq",".login"]);return{available:!0,authenticated:!0,login:i===0?s.trim():null}}function aE(e){switch(e){case"safe":case"caution":return"pass";case"warning":return"warning";case"dangerous":return"dangerous"}}function Gh(e){let t={name:e.metadata.name,author:e.author,description:e.metadata.description,repository:e.repository,commit:e.commit,security_verdict:e.securityVerdict,published_at:new Date().toISOString()};return e.skillPath&&(t.skill_path=e.skillPath),e.metadata.version&&e.metadata.version!=="0.0.0"&&/^\d+\.\d+\.\d+/.test(e.metadata.version)&&(t.version=e.metadata.version),e.metadata.license&&(t.license=e.metadata.license),e.metadata.tags&&e.metadata.tags.length>0&&(t.tags=e.metadata.tags.slice(0,10)),t}function lE(e){let t=Gh({metadata:e.metadata,author:e.metadata.creator||"unknown",commit:e.commit,repository:e.repository,securityVerdict:e.registryVerdict}),s=_r(t);return s.length>0?{success:!1,manifest:t,prUrl:null,error:`Manifest validation failed: ${s.map(i=>`${i.field}: ${i.message}`).join("; ")}`,securityVerdict:e.registryVerdict,securityReport:e.securityReport}:{success:!0,manifest:t,prUrl:null,error:null,securityVerdict:e.registryVerdict,securityReport:e.securityReport,fallback:!0,fallbackReason:e.fallbackReason}}async function Hh(e){let t=Z0(e.path);L(`publish: starting for ${t}`),await sE(t);let s=await tE(t);L(`publish: parsed metadata for "${s.name}"`);let r=await(e._auditFn??Me)(t,s.name),n=aE(r.verdict);if(n==="dangerous")return{success:!1,manifest:null,prUrl:null,error:`Security audit verdict: dangerous. ${r.verdictReason}`,securityVerdict:n,securityReport:r};if(n==="warning"&&!e.force)return{success:!1,manifest:null,prUrl:null,error:"Security audit verdict: warning. Use --force to override warnings.",securityVerdict:n,securityReport:r};let o=await iE(t),a=await nE(t),c=await rE(t),u=await z0(t),f=Q0(c,u),d=f&&f!=="."?f:void 0,m=await(e._checkGhCliFn??oE)();if(!m.available||!m.authenticated){let T=m.available?"gh CLI not authenticated":"gh CLI not found";return lE({metadata:s,commit:o,repository:a,registryVerdict:n,securityReport:r,fallbackReason:T})}if(!m.login)throw new Error("Could not determine GitHub username. The gh CLI is authenticated but the API call failed. Check your network connection and try again.");let g=m.login,h=Gh({metadata:s,author:g,commit:o,repository:a,skillPath:d,securityVerdict:n}),y=_r(h);if(y.length>0)return{success:!1,manifest:h,prUrl:null,error:`Manifest validation failed: ${y.map(T=>`${T.field}: ${T.message}`).join("; ")}`,securityVerdict:n,securityReport:r};if(e.dryRun)return{success:!0,manifest:h,prUrl:null,error:null,securityVerdict:n,securityReport:r};if(!e.yes){if(!process.stdin.isTTY)return{success:!1,manifest:h,prUrl:null,error:"Cannot prompt for confirmation in non-interactive mode. Use --yes to skip.",securityVerdict:n,securityReport:r};let T=un(s.name),M=un(g);process.stderr.write(`
970
- About to publish "${T}" by ${M} to ${St}.
840
+ ${i.bold("Interactive install:")}
841
+ ${i.dim("`asm bundle install` in a terminal prompts for the tool(s), then which")}
842
+ ${i.dim("bundle skills to install, then the install scope. Any picker can be")}
843
+ ${i.dim("dismissed with Esc to abort. Passing a prompt's own flag skips it:")}
844
+ ${i.dim("-p/--tool for the tool picker, -s/--scope for the scope picker, -y")}
845
+ ${i.dim("for the skill and scope pickers. Outside a terminal there are no")}
846
+ ${i.dim("pickers, and -p/--tool is required unless exactly one tool is enabled.")}
847
+
848
+ ${i.bold("Examples:")}
849
+ asm bundle create my-workflow ${i.dim("Create from installed skills")}
850
+ asm bundle install my-workflow ${i.dim("Install a saved bundle")}
851
+ asm bundle install frontend-dev ${i.dim("Install a pre-defined bundle")}
852
+ asm bundle install ./bundle.json ${i.dim("Install from file")}
853
+ asm bundle list ${i.dim("Show all saved bundles")}
854
+ asm bundle list --predefined ${i.dim("List pre-defined bundles")}
855
+ asm bundle list --json ${i.dim("List bundles as JSON")}
856
+ asm bundle show my-workflow ${i.dim("Show bundle details")}
857
+ asm bundle remove my-workflow ${i.dim("Remove a saved bundle")}
858
+ asm bundle modify my-workflow --add github:u/r ${i.dim("Add a skill to bundle")}
859
+ asm bundle modify my-workflow --remove skill ${i.dim("Remove a skill from bundle")}
860
+ asm bundle export my-workflow ${i.dim("Export to ./my-workflow.json")}
861
+ asm bundle export my-workflow out.json ${i.dim("Export bundle to file")}`)}async function rd(e){if(e.flags.help){ch();return}let t=e.subcommand;switch(t||(w("Missing subcommand. Use: create, install, list, show, remove, modify, or export"),console.error('Run "asm bundle --help" for usage.'),process.exit(2)),t){case"create":{let r=e.positional[0];r||(w("Missing required argument: <name>"),console.error("Usage: asm bundle create <name>"),process.exit(2));let s=await O(),o=await V(s,e.flags.scope);o.length===0&&(w("No skills found to include in the bundle."),process.exit(1));let n=new Set,a=o.filter(h=>{let y=h.name.toLowerCase();return n.has(y)?!1:(n.add(y),!0)}),l=a;if(process.stdin.isTTY&&!e.flags.yes){let h=a.map(b=>({label:`${b.name} v${b.version}`,hint:b.description?b.description.slice(0,60)+(b.description.length>60?"...":""):`(${b.provider}/${b.scope})`,checked:!0}));console.error(i.bold(`Select skills for bundle "${r}":
862
+ `));let y=await Ie({items:h});y.length===0&&(w("No skills selected. Bundle not created."),process.exit(1)),l=y.map(b=>a[b])}let{readLock:c}=await import("./lock-UEL3CMOV.js"),d=await c(),u=await Promise.all(l.map(h=>Zc(h,d))),p=`Bundle of ${u.length} skills`,f="unknown";try{let{execFile:h}=await import("child_process"),{promisify:y}=await import("util"),$=(await y(h)("git",["config","user.name"],{encoding:"utf-8",timeout:5e3})).stdout.trim();$&&(f=$)}catch{}if(process.stdin.isTTY&&!e.flags.yes){process.stderr.write(`
863
+ ${i.bold("Description")} (optional, press Enter to skip): `);let h=await G();h.trim()&&(p=h.trim()),process.stderr.write(`${i.bold("Author")} (optional, press Enter to skip): `);let y=await G();y.trim()&&(f=y.trim())}let m=Yc(r,p,f,u),g=await dn(m);e.flags.json?console.log(JSON.stringify(m,null,2)):(console.error(i.green(`Bundle "${r}" created with ${u.length} skill(s).`)),console.error(` Saved to: ${i.dim(g)}`));break}case"install":{let r=e.positional[0];r||(w("Missing required argument: <name|file>"),console.error("Usage: asm bundle install <name|file>"),process.exit(2));let s;try{s=await mr(r)}catch(m){w(m.message),process.exit(1)}console.error(`${i.bold("Bundle:")} ${s.name} (${s.skills.length} skills)`),s.description&&console.error(` ${i.dim(s.description)}`),console.error("");for(let m of s.skills){let g=m.version?` v${m.version}`:"";console.error(` ${i.cyan(m.name)}${i.dim(g)} ${i.dim(`-> ${m.installUrl}`)}`)}let o=await O(),n=s.skills,a,l,c;try{process.stdin.isTTY&&!e.flags.provider&&o.providers.filter(m=>m.enabled).length>1&&console.error(i.bold(`
864
+ Select tool(s) to install into:
865
+ `)),{provider:l,allProviders:c}=await me(o,e.flags.provider,!!process.stdin.isTTY),process.stdin.isTTY&&!e.flags.yes&&s.skills.length>1&&(n=await tc(s.skills,{isTTY:!0,yes:!1})),a=await ds({scopeFlag:e.flags.scope,provider:l,isTTY:!!process.stdin.isTTY,yes:!!e.flags.yes})}catch(m){w(m.message),process.exit(1)}if(!e.flags.yes&&process.stdin.isTTY){let m=n.length===s.skills.length?"all skills from this bundle":`${n.length} selected skill(s) from this bundle`;process.stderr.write(`
866
+ ${i.bold(`Install ${m}?`)} [y/N] `);let g=await G();g.toLowerCase()!=="y"&&g.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let d=[];for(let m of n){console.error(`
867
+ Installing ${i.bold(m.name)}...`);try{(m.installUrl.startsWith("github:")||m.installUrl.startsWith("https://github.com/"))&&await ve();let h=oe(m.installUrl),y=!!h.isLocal,b=null;try{let $,v;if(y)$=h.localPath,v=h.localPath;else{de(h,m.installUrl),b=await Se(h,e.flags.transport),$=b,v=h.subpath?lh(b,h.subpath):b;try{Ee(b,v,m.installUrl)}catch(U){throw await z(b),b=null,U}}let S=await pe(v),C=ue(m.name||S.name||h.repo),D=Ht(h,$,v,C,l,e.flags.force,a);try{await Hs(D.targetDir,D.force)}catch(U){if(U.message?.includes("--force")){d.push({name:m.name,status:"skipped",reason:"Already installed. Use --force to overwrite."}),console.error(` ${i.dim("---")} ${m.name} skipped (already installed)`);continue}throw U}c?await Gt(D,c):await pt(D),d.push({name:m.name,status:"installed"}),console.error(` ${i.green("+++")} ${m.name} installed`)}finally{b&&await z(b)}}catch(g){d.push({name:m.name,status:"failed",reason:g.message}),console.error(` ${i.red("!!!")} ${m.name}: ${g.message}`)}}let u=d.filter(m=>m.status==="installed").length,p=d.filter(m=>m.status==="skipped").length,f=d.filter(m=>m.status==="failed").length;e.flags.json?console.log(JSON.stringify({bundleName:s.name,total:d.length,installed:u,skipped:p,failed:f,scope:a,results:d},null,2)):(console.error(""),console.error(`${i.bold("Summary:")} ${d.length} total, ${i.green(String(u))} installed, `+(p>0?`${i.dim(String(p))} skipped, `:"")+`${i.red(String(f))} failed`)),f>0&&(process.exitCode=1);break}case"list":{if(!!e.flags.predefined){let o=await Xc();if(o.length===0){e.flags.json?console.log("[]"):console.log("No predefined bundles found.");return}if(e.flags.json)console.log(JSON.stringify(o,null,2));else{console.error(i.bold(`Pre-defined Bundles (${o.length}):
868
+ `));for(let n of o){let a=n.tags&&n.tags.length>0?` ${i.dim(`[${n.tags.join(", ")}]`)}`:"";console.error(` ${i.cyan(n.name)} ${i.dim(`(${n.skills.length} skills)`)}${a}`),n.description&&console.error(` ${i.dim(n.description)}`)}console.error(`
869
+ ${i.dim("Install a bundle with: asm bundle install <name>")}`)}return}let s=await ed();if(s.length===0){e.flags.json?console.log("[]"):(console.log("No bundles found."),console.error(i.dim("Create one with: asm bundle create <name>")),console.error(i.dim("List pre-defined bundles with: asm bundle list --predefined")));return}if(e.flags.json)console.log(JSON.stringify(s,null,2));else{console.error(i.bold(`Saved Bundles (${s.length}):
870
+ `));for(let o of s){let n=o.tags&&o.tags.length>0?` ${i.dim(`[${o.tags.join(", ")}]`)}`:"";console.error(` ${i.cyan(o.name)} ${i.dim(`(${o.skills.length} skills)`)}${n}`),o.description&&console.error(` ${i.dim(o.description)}`),o.author&&console.error(` ${i.dim(`by ${o.author}`)}`)}}break}case"show":{let r=e.positional[0];r||(w("Missing required argument: <name|file>"),console.error("Usage: asm bundle show <name|file>"),process.exit(2));let s;try{s=await mr(r)}catch(o){w(o.message),process.exit(1)}if(e.flags.json)console.log(JSON.stringify(s,null,2));else{console.error(i.bold(`Bundle: ${s.name}`)),s.description&&console.error(` ${s.description}`),s.author&&console.error(` ${i.dim(`Author: ${s.author}`)}`),console.error(` ${i.dim(`Created: ${new Date(s.createdAt).toLocaleString()}`)}`),s.tags&&s.tags.length>0&&console.error(` ${i.dim(`Tags: ${s.tags.join(", ")}`)}`),console.error(`
871
+ ${i.bold(`Skills (${s.skills.length})`)}:`);for(let o of s.skills){let n=o.version?` v${o.version}`:"";console.error(` ${i.cyan(o.name)}${i.dim(n)}`),o.description&&console.error(` ${i.dim(o.description)}`),console.error(` ${i.dim(`install: ${o.installUrl}`)}`)}}break}case"remove":{let r=e.positional[0];if(r||(w("Missing required argument: <name>"),console.error("Usage: asm bundle remove <name>"),process.exit(2)),!e.flags.yes&&process.stdin.isTTY){process.stderr.write(`${i.bold("Remove bundle")} ${i.cyan(r)}${i.bold("?")} [y/N] `);let o=await G();o.toLowerCase()!=="y"&&o.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let s;try{s=await td(r)}catch(o){w(o.message),process.exit(1)}s?console.error(i.green(`Bundle "${r}" removed.`)):(w(`Bundle "${r}" not found.`),process.exit(1));break}case"modify":{let r=e.positional[0];r||(w("Missing required argument: <name>"),console.error("Usage: asm bundle modify <name> [--add <installUrl>] [--remove <skillName>] [--description <desc>] [--author <author>] [--tags <tag,...>]"),process.exit(2));let s;try{s=await mr(r)}catch(p){w(p.message),process.exit(1)}let o=!1,n=e.flags.add;if(n){let p={name:n.split("/").pop()?.replace(/\.json$/,"")??n,installUrl:n};s.skills.push(p),o=!0,console.error(i.green(`Added skill from ${n}`))}let a=e.flags.remove;if(a){let p=s.skills.length;s.skills=s.skills.filter(f=>f.name.toLowerCase()!==a.toLowerCase()),s.skills.length<p?(o=!0,console.error(i.green(`Removed skill "${a}"`))):console.error(i.dim(`Skill "${a}" not found in bundle (no change)`))}let l=e.flags.description;l!==null&&(s.description=l,o=!0);let c=e.flags.author;c!==null&&(s.author=c,o=!0);let d=e.flags.tags;if(d!==null&&(s.tags=d.split(",").map(p=>p.trim()).filter(p=>p.length>0),o=!0),!o&&process.stdin.isTTY&&!e.flags.yes&&!n&&!a&&l===null&&c===null&&d===null){console.error(i.bold(`Modifying bundle "${s.name}"`)),console.error(` Current skills: ${s.skills.map(g=>g.name).join(", ")}`),console.error(` Description: ${s.description}`),console.error(` Author: ${s.author}`),console.error(` Tags: ${s.tags?.join(", ")??"(none)"}`),console.error(""),process.stderr.write(`${i.bold("New description")} (Enter to keep current): `);let p=await G();p.trim()&&(s.description=p.trim(),o=!0),process.stderr.write(`${i.bold("New author")} (Enter to keep current): `);let f=await G();f.trim()&&(s.author=f.trim(),o=!0),process.stderr.write(`${i.bold("New tags (comma-separated)")} (Enter to keep current): `);let m=await G();m.trim()&&(s.tags=m.split(",").map(g=>g.trim()).filter(g=>g.length>0),o=!0)}if(!o){console.error(i.dim("No changes made to bundle."));break}s.skills.length===0&&(w("Bundle must contain at least one skill after modification."),process.exit(1));let u=await dn(s);e.flags.json?console.log(JSON.stringify(s,null,2)):(console.error(i.green(`Bundle "${s.name}" updated (${s.skills.length} skill(s)).`)),console.error(` Saved to: ${i.dim(u)}`));break}case"export":{let r=e.positional[0];r||(w("Missing required argument: <name>"),console.error("Usage: asm bundle export <name> [output-file]"),process.exit(2));let s;try{s=await mr(r)}catch(c){w(c.message),process.exit(1)}let o=e.positional[1]??`./${r}.json`,{resolve:n}=await import("path"),a=n(o);if(!e.flags.force){let{access:c}=await import("fs/promises");try{if(await c(a),process.stdin.isTTY&&!e.flags.yes){process.stderr.write(`File ${i.bold(a)} already exists. Overwrite? [y/N] `);let d=await G();d.toLowerCase()!=="y"&&d.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}else e.flags.yes||(w(`File "${a}" already exists. Use --force to overwrite.`),process.exit(1))}catch{}}let{writeFile:l}=await import("fs/promises");await l(a,JSON.stringify(s,null,2)+`
872
+ `,"utf-8"),e.flags.json?console.log(JSON.stringify({exported:!0,path:a,bundle:s},null,2)):console.error(i.green(`Exported to ${a}`));break}default:w(`Unknown subcommand: "${t}". Use: create, install, list, show, remove, modify, or export`),console.error('Run "asm bundle --help" for usage.'),process.exit(2)}}import{readFile as dh,realpath as uh}from"fs/promises";import{join as ph,resolve as mh,relative as fh}from"path";function gs(e){return e.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"").replace(/\x1b\][^\x07]*\x07/g,"").replace(/\x1b[^[\]]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"")}function gh(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\[/g,"\\[").replace(/\]/g,"\\]").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\|/g,"\\|")}function un(e){return gh(gs(e))}var Xe="luongnv89/asm-registry";async function hh(e){let t=ph(e,"SKILL.md"),r;try{r=await dh(t,"utf-8")}catch{throw new Error(`No SKILL.md found in ${e}. Run "asm init" to create one.`)}let s=q(r);if(!s.name)throw new Error("SKILL.md is missing required field: name");if(!s.description)throw new Error("SKILL.md is missing required field: description");let o=ae(s),n=s.tags?s.tags.split(/[\s,]+/).map(a=>a.trim().toLowerCase()).filter(Boolean):[];return{name:s.name,description:s.description.replace(/\s*\n\s*/g," ").trim(),version:o,license:s.license||"MIT",creator:s.creator||"",tags:n}}async function yh(e){let{exitCode:t}=await re(["git","rev-parse","--git-dir"],{cwd:e});if(t!==0)throw new Error(`${e} is not inside a git repository.`)}async function bh(e){let{stdout:t,exitCode:r}=await re(["git","rev-parse","HEAD"],{cwd:e});if(r!==0)throw new Error("Failed to get HEAD commit. Is this a git repository?");return t.trim()}async function wh(e){let{stdout:t,exitCode:r}=await re(["git","rev-parse","--show-toplevel"],{cwd:e});if(r!==0)throw new Error("Failed to determine git repository root.");return t.trim()}async function kh(e){let{stdout:t,exitCode:r}=await re(["git","remote","get-url","origin"],{cwd:e});if(r!==0)throw new Error("No remote origin found. Add one with: git remote add origin <url>");let s=t.trim(),o=s.match(/^git@github\.com:([a-zA-Z0-9_-]+)\/([a-zA-Z0-9._-]+?)(?:\.git)?$/);return o?`https://github.com/${o[1]}/${o[2]}`:s.replace(/\.git$/,"")}async function vh(){let{exitCode:e}=await re(["gh","--version"]);if(e!==0)return{available:!1,authenticated:!1,login:null};let{exitCode:t}=await re(["gh","auth","status"]);if(t!==0)return{available:!0,authenticated:!1,login:null};let{stdout:r,exitCode:s}=await re(["gh","api","user","--jq",".login"]);return{available:!0,authenticated:!0,login:s===0?r.trim():null}}function Sh(e){switch(e){case"safe":case"caution":return"pass";case"warning":return"warning";case"dangerous":return"dangerous"}}function sd(e){let t={name:e.metadata.name,author:e.author,description:e.metadata.description,repository:e.repository,commit:e.commit,security_verdict:e.securityVerdict,published_at:new Date().toISOString()};return e.skillPath&&(t.skill_path=e.skillPath),e.metadata.version&&e.metadata.version!=="0.0.0"&&/^\d+\.\d+\.\d+/.test(e.metadata.version)&&(t.version=e.metadata.version),e.metadata.license&&(t.license=e.metadata.license),e.metadata.tags&&e.metadata.tags.length>0&&(t.tags=e.metadata.tags.slice(0,10)),t}function $h(e){let t=sd({metadata:e.metadata,author:e.metadata.creator||"unknown",commit:e.commit,repository:e.repository,skillPath:e.skillPath,securityVerdict:e.registryVerdict}),r=Mr(t);return r.length>0?{success:!1,manifest:t,prUrl:null,error:`Manifest validation failed: ${r.map(s=>`${s.field}: ${s.message}`).join("; ")}`,securityVerdict:e.registryVerdict,securityReport:e.securityReport}:{success:!0,manifest:t,prUrl:null,error:null,securityVerdict:e.registryVerdict,securityReport:e.securityReport,fallback:!0,fallbackReason:e.fallbackReason}}async function od(e){let t=mh(e.path);P(`publish: starting for ${t}`),await yh(t);let r=await hh(t);P(`publish: parsed metadata for "${r.name}"`);let o=await(e._auditFn??xe)(t,r.name),n=Sh(o.verdict);if(n==="dangerous")return{success:!1,manifest:null,prUrl:null,error:`Security audit verdict: dangerous. ${o.verdictReason}`,securityVerdict:n,securityReport:o};if(n==="warning"&&!e.force)return{success:!1,manifest:null,prUrl:null,error:"Security audit verdict: warning. Use --force to override warnings.",securityVerdict:n,securityReport:o};let a=await bh(t),l=await kh(t),c=await wh(t),d=await uh(t),u=fh(c,d),p=u&&u!=="."?rt(u):void 0,m=await(e._checkGhCliFn??vh)();if(!m.available||!m.authenticated){let I=m.available?"gh CLI not authenticated":"gh CLI not found";return $h({metadata:r,commit:a,repository:l,skillPath:p,registryVerdict:n,securityReport:o,fallbackReason:I})}if(!m.login)throw new Error("Could not determine GitHub username. The gh CLI is authenticated but the API call failed. Check your network connection and try again.");let g=m.login,h=sd({metadata:r,author:g,commit:a,repository:l,skillPath:p,securityVerdict:n}),y=Mr(h);if(y.length>0)return{success:!1,manifest:h,prUrl:null,error:`Manifest validation failed: ${y.map(I=>`${I.field}: ${I.message}`).join("; ")}`,securityVerdict:n,securityReport:o};if(e.dryRun)return{success:!0,manifest:h,prUrl:null,error:null,securityVerdict:n,securityReport:o};if(!e.yes){if(!process.stdin.isTTY)return{success:!1,manifest:h,prUrl:null,error:"Cannot prompt for confirmation in non-interactive mode. Use --yes to skip.",securityVerdict:n,securityReport:o};let I=gs(r.name),L=gs(g);process.stderr.write(`
873
+ About to publish "${I}" by ${L} to ${Xe}.
971
874
  Security verdict: ${n}
972
875
 
973
- Proceed? [y/N] `);let se=await new Promise(ne=>{let de="",Qt=De=>{de+=De.toString(),de.includes(`
974
- `)&&(process.stdin.removeListener("data",Qt),process.stdin.pause(),ne(de.trim()))};process.stdin.resume(),process.stdin.on("data",Qt)});if(se.toLowerCase()!=="y"&&se.toLowerCase()!=="yes")return{success:!1,manifest:h,prUrl:null,error:"Publish aborted by user.",securityVerdict:n,securityReport:r}}L(`publish: forking ${St}`),await oe(["gh","repo","fork",St,"--clone=false"]);let b=`publish/${g}/${s.name}`,k=`manifests/${g}/${s.name}.json`,w=JSON.stringify(h,null,2)+`
975
- `,v=Buffer.from(w,"utf-8").toString("base64"),{stdout:x,exitCode:C}=await oe(["gh","api",`repos/${g}/asm-registry/git/refs/heads/main`,"--jq",".object.sha"]);if(C!==0)return{success:!1,manifest:h,prUrl:null,error:`Failed to read fork's main branch. Ensure the fork exists at ${g}/asm-registry.`,securityVerdict:n,securityReport:r};let A=x.trim(),{exitCode:E}=await oe(["gh","api",`repos/${g}/asm-registry/git/refs`,"-X","POST","-f",`ref=refs/heads/${b}`,"-f",`sha=${A}`]);E!==0&&await oe(["gh","api",`repos/${g}/asm-registry/git/refs/heads/${b}`,"-X","PATCH","-f",`sha=${A}`,"-f","force=true"]);let{stderr:_,exitCode:O}=await oe(["gh","api",`repos/${g}/asm-registry/contents/${k}`,"-X","PUT","-f",`message=Publish ${g}/${s.name}`,"-f",`content=${v}`,"-f",`branch=${b}`]);if(O!==0){let{stdout:T,exitCode:M}=await oe(["gh","api",`repos/${g}/asm-registry/contents/${k}?ref=${b}`,"-q",".sha"]),se=T.trim();if(M===0&&se){let{exitCode:ne}=await oe(["gh","api",`repos/${g}/asm-registry/contents/${k}`,"-X","PUT","-f",`message=Update ${g}/${s.name}`,"-f",`content=${v}`,"-f",`branch=${b}`,"-f",`sha=${se}`]);if(ne!==0)return{success:!1,manifest:h,prUrl:null,error:"Failed to write manifest to registry fork.",securityVerdict:n,securityReport:r}}else return{success:!1,manifest:h,prUrl:null,error:`Failed to write manifest to registry fork. ${_}`,securityVerdict:n,securityReport:r}}let S=Tl(s.name),P=Tl(s.description),B=Tl(s.license),te=`Publish ${g}/${un(s.name)}`,ce=[`## Skill: ${S}`,"",`**Author:** ${g}`,`**Version:** ${s.version}`,`**Description:** ${P}`,`**License:** ${B}`,`**Repository:** ${a}`,`**Commit:** \`${o}\``,`**Security verdict:** ${n}`,"","---","","*This PR was generated by `asm publish`.*"].join(`
976
- `),{stdout:Pe,stderr:R,exitCode:I}=await oe(["gh","pr","create","--repo",St,"--head",`${g}:${b}`,"--title",te,"--body",ce]),F=null;if(I===0)F=Pe.trim();else{let T=R.match(/https:\/\/github\.com\/[^\s]+\/pull\/\d+/);T&&(F=T[0])}return F?{success:!0,manifest:h,prUrl:F,error:null,securityVerdict:n,securityReport:r}:{success:!1,manifest:h,prUrl:null,error:`Failed to create PR against ${St}. ${R}`,securityVerdict:n,securityReport:r}}function Jh(e){let t=e.manifest;return t?["",` gh CLI is unavailable (${e.fallbackReason}).`," To publish manually:","",` 1. Fork ${St} on GitHub`,` 2. Create branch: publish/${t.author}/${t.name}`,` 3. Add file: manifests/${t.author}/${t.name}.json`," 4. Paste the manifest below into that file",` 5. Open a PR against ${St}`,"",' Run "asm doctor" to fix your environment.',""," Generated manifest:",JSON.stringify(t,null,2).split(`
977
- `).map(i=>` ${i}`).join(`
876
+ Proceed? [y/N] `);let X=await new Promise(te=>{let ie="",xt=Pe=>{ie+=Pe.toString(),ie.includes(`
877
+ `)&&(process.stdin.removeListener("data",xt),process.stdin.pause(),te(ie.trim()))};process.stdin.resume(),process.stdin.on("data",xt)});if(X.toLowerCase()!=="y"&&X.toLowerCase()!=="yes")return{success:!1,manifest:h,prUrl:null,error:"Publish aborted by user.",securityVerdict:n,securityReport:o}}P(`publish: forking ${Xe}`),await re(["gh","repo","fork",Xe,"--clone=false"]);let b=`publish/${g}/${r.name}`,$=`manifests/${g}/${r.name}.json`,v=JSON.stringify(h,null,2)+`
878
+ `,S=Buffer.from(v,"utf-8").toString("base64"),{stdout:C,exitCode:D}=await re(["gh","api",`repos/${g}/asm-registry/git/refs/heads/main`,"--jq",".object.sha"]);if(D!==0)return{success:!1,manifest:h,prUrl:null,error:`Failed to read fork's main branch. Ensure the fork exists at ${g}/asm-registry.`,securityVerdict:n,securityReport:o};let U=C.trim(),{exitCode:A}=await re(["gh","api",`repos/${g}/asm-registry/git/refs`,"-X","POST","-f",`ref=refs/heads/${b}`,"-f",`sha=${U}`]);A!==0&&await re(["gh","api",`repos/${g}/asm-registry/git/refs/heads/${b}`,"-X","PATCH","-f",`sha=${U}`,"-f","force=true"]);let{stderr:_,exitCode:M}=await re(["gh","api",`repos/${g}/asm-registry/contents/${$}`,"-X","PUT","-f",`message=Publish ${g}/${r.name}`,"-f",`content=${S}`,"-f",`branch=${b}`]);if(M!==0){let{stdout:I,exitCode:L}=await re(["gh","api",`repos/${g}/asm-registry/contents/${$}?ref=${b}`,"-q",".sha"]),X=I.trim();if(L===0&&X){let{exitCode:te}=await re(["gh","api",`repos/${g}/asm-registry/contents/${$}`,"-X","PUT","-f",`message=Update ${g}/${r.name}`,"-f",`content=${S}`,"-f",`branch=${b}`,"-f",`sha=${X}`]);if(te!==0)return{success:!1,manifest:h,prUrl:null,error:"Failed to write manifest to registry fork.",securityVerdict:n,securityReport:o}}else return{success:!1,manifest:h,prUrl:null,error:`Failed to write manifest to registry fork. ${_}`,securityVerdict:n,securityReport:o}}let k=un(r.name),E=un(r.description),F=un(r.license),Z=`Publish ${g}/${gs(r.name)}`,se=[`## Skill: ${k}`,"",`**Author:** ${g}`,`**Version:** ${r.version}`,`**Description:** ${E}`,`**License:** ${F}`,`**Repository:** ${l}`,`**Commit:** \`${a}\``,`**Security verdict:** ${n}`,"","---","","*This PR was generated by `asm publish`.*"].join(`
879
+ `),{stdout:we,stderr:R,exitCode:x}=await re(["gh","pr","create","--repo",Xe,"--head",`${g}:${b}`,"--title",Z,"--body",se]),N=null;if(x===0)N=we.trim();else{let I=R.match(/https:\/\/github\.com\/[^\s]+\/pull\/\d+/);I&&(N=I[0])}return N?{success:!0,manifest:h,prUrl:N,error:null,securityVerdict:n,securityReport:o}:{success:!1,manifest:h,prUrl:null,error:`Failed to create PR against ${Xe}. ${R}`,securityVerdict:n,securityReport:o}}function nd(e){let t=e.manifest;return t?["",` gh CLI is unavailable (${e.fallbackReason}).`," To publish manually:","",` 1. Fork ${Xe} on GitHub`,` 2. Create branch: publish/${t.author}/${t.name}`,` 3. Add file: manifests/${t.author}/${t.name}.json`," 4. Paste the manifest below into that file",` 5. Open a PR against ${Xe}`,"",' Run "asm doctor" to fix your environment.',""," Generated manifest:",JSON.stringify(t,null,2).split(`
880
+ `).map(s=>` ${s}`).join(`
978
881
  `)].join(`
979
- `):""}function cE(){console.log(`${l.bold("Usage:")} asm publish [path] [options]
882
+ `):""}function xh(){console.log(`${i.bold("Usage:")} asm publish [path] [options]
980
883
 
981
884
  Validate a skill, run a security audit, generate a registry manifest,
982
885
  and open a PR against the asm-registry.
983
886
 
984
- ${l.bold("Arguments:")}
887
+ ${i.bold("Arguments:")}
985
888
  path Path to skill directory (default: current directory)
986
889
 
987
- ${l.bold("Options:")}
890
+ ${i.bold("Options:")}
988
891
  --dry-run Print generated manifest without opening a PR
989
892
  --force Override 'warning' security verdict (blocks 'dangerous')
990
893
  -y, --yes Skip confirmation prompts
@@ -993,76 +896,77 @@ ${l.bold("Options:")}
993
896
  --no-color Disable ANSI colors
994
897
  -V, --verbose Show debug output
995
898
 
996
- ${l.bold("Examples:")}
997
- asm publish ${l.dim("Publish skill in current directory")}
998
- asm publish ./my-skill ${l.dim("Publish skill at the given path")}
999
- asm publish --dry-run ${l.dim("Preview manifest without side effects")}
1000
- asm publish --force ${l.dim("Override warning-level security findings")}
1001
- asm publish --json ${l.dim("Output as JSON")}
1002
- asm publish --machine ${l.dim("Machine-readable v1 envelope output")}`)}async function Wh(e){if(e.flags.help){cE();return}let t=e.flags.machine?he():void 0,s=performance.now(),i=e.subcommand||".";try{let r=await Hh({path:i,dryRun:e.flags.dryRun,force:e.flags.force,yes:e.flags.yes});if(e.flags.machine){t?.(),r.success||(console.log(z("publish",Y.PUBLISH_FAILED,r.error||"Publish failed",s,{manifest:r.manifest,security_verdict:r.securityVerdict,fallback:r.fallback??!1})),process.exit(1)),console.log(V("publish",{manifest:r.manifest,pr_url:r.prUrl,status:r.securityVerdict},s));return}if(e.flags.json){console.log(JSON.stringify({success:r.success,manifest:r.manifest,pr_url:r.prUrl,error:r.error,security_verdict:r.securityVerdict},null,2)),r.success||process.exit(1);return}if(r.success||($(r.error||"Publish failed."),process.exit(1)),r.fallback){console.log(l.yellow("Manifest generated (gh CLI unavailable):")),console.log(Jh(r));return}if(e.flags.dryRun){console.error(l.dim(`Dry run \u2014 no PR created.
1003
- `)),console.log(JSON.stringify(r.manifest,null,2));return}r.prUrl&&(console.error(l.green("Published successfully!")),console.error(""),console.error(` PR: ${r.prUrl}`),console.error(` Manifest: manifests/${r.manifest?.author}/${r.manifest?.name}.json`),console.error(` Security: ${r.securityVerdict}`),console.error(""),console.error(l.dim("The registry maintainers will review your submission.")))}catch(r){e.flags.machine&&(t?.(),console.log(z("publish",Y.PUBLISH_FAILED,r.message,s)),process.exit(1)),e.flags.json&&(console.log(JSON.stringify({success:!1,manifest:null,pr_url:null,error:r.message,security_verdict:null},null,2)),process.exit(1)),$(r.message),process.exit(1)}}function uE(){console.log(`${l.bold("Usage:")} asm outdated [options]
899
+ ${i.bold("Examples:")}
900
+ asm publish ${i.dim("Publish skill in current directory")}
901
+ asm publish ./my-skill ${i.dim("Publish skill at the given path")}
902
+ asm publish --dry-run ${i.dim("Preview manifest without side effects")}
903
+ asm publish --force ${i.dim("Override warning-level security findings")}
904
+ asm publish --json ${i.dim("Output as JSON")}
905
+ asm publish --machine ${i.dim("Machine-readable v1 envelope output")}`)}async function id(e){if(e.flags.help){xh();return}let t=e.flags.machine?le():void 0,r=performance.now(),s=e.subcommand||".";try{let o=await od({path:s,dryRun:e.flags.dryRun,force:e.flags.force,yes:e.flags.yes});if(e.flags.machine){t?.(),o.success||(console.log(K("publish",W.PUBLISH_FAILED,o.error||"Publish failed",r,{manifest:o.manifest,security_verdict:o.securityVerdict,fallback:o.fallback??!1})),process.exit(1)),console.log(B("publish",{manifest:o.manifest,pr_url:o.prUrl,status:o.securityVerdict},r));return}if(e.flags.json){console.log(JSON.stringify({success:o.success,manifest:o.manifest,pr_url:o.prUrl,error:o.error,security_verdict:o.securityVerdict},null,2)),o.success||process.exit(1);return}if(o.success||(w(o.error||"Publish failed."),process.exit(1)),e.flags.dryRun){console.error(i.dim(`Dry run \u2014 no PR created.
906
+ `)),console.log(JSON.stringify(o.manifest,null,2));return}if(o.fallback){console.log(i.yellow("Manifest generated (gh CLI unavailable):")),console.log(nd(o));return}o.prUrl&&(console.error(i.green("Published successfully!")),console.error(""),console.error(` PR: ${o.prUrl}`),console.error(` Manifest: manifests/${o.manifest?.author}/${o.manifest?.name}.json`),console.error(` Security: ${o.securityVerdict}`),console.error(""),console.error(i.dim("The registry maintainers will review your submission.")))}catch(o){e.flags.machine&&(t?.(),console.log(K("publish",W.PUBLISH_FAILED,o.message,r)),process.exit(1)),e.flags.json&&(console.log(JSON.stringify({success:!1,manifest:null,pr_url:null,error:o.message,security_verdict:null},null,2)),process.exit(1)),w(o.message),process.exit(1)}}function Ph(){console.log(`${i.bold("Usage:")} asm outdated [options]
1004
907
 
1005
908
  Show which installed skills have newer versions available.
1006
909
 
1007
- ${l.bold("Options:")}
910
+ ${i.bold("Options:")}
1008
911
  --json Output as JSON
1009
912
  --machine Output in stable machine-readable format
1010
913
  --no-color Disable ANSI colors
1011
914
  -V, --verbose Show debug output
1012
915
 
1013
- ${l.bold("Examples:")}
1014
- asm outdated ${l.dim("Show outdated skills")}
1015
- asm outdated --json ${l.dim("Output as JSON")}
1016
- asm outdated --machine ${l.dim("Machine-readable output")}`)}async function Yh(e){if(e.flags.help){uE();return}let t=e.flags.machine?he():void 0,s=performance.now();try{let i=await Qs();if(e.flags.machine){t?.();let n=i.entries.map(o=>({name:o.name,installed_commit:o.installedCommit,latest_commit:o.latestCommit,source:o.sourceType,status:o.status}));console.log(V("outdated",n,s));return}if(e.flags.json){console.log(za(i));return}let r=!e.flags.noColor&&process.stdout.isTTY!==!1;console.log(Ya(i,r)),i.outdatedCount>0&&(process.exitCode=1)}catch(i){e.flags.machine&&(t?.(),console.log(z("outdated",Y.UNKNOWN_ERROR,i.message,s)),process.exit(1)),$(i.message),process.exit(1)}}function dE(){console.log(`${l.bold("Usage:")} asm update [name...] [options]
916
+ ${i.bold("Examples:")}
917
+ asm outdated ${i.dim("Show outdated skills")}
918
+ asm outdated --json ${i.dim("Output as JSON")}
919
+ asm outdated --machine ${i.dim("Machine-readable output")}`)}async function ad(e){if(e.flags.help){Ph();return}let t=e.flags.machine?le():void 0,r=performance.now();try{let s=await Yt();if(e.flags.machine){t?.();let n=s.entries.map(a=>({name:a.name,installed_commit:a.installedCommit,latest_commit:a.latestCommit,source:a.sourceType,status:a.status}));console.log(B("outdated",n,r));return}if(e.flags.json){console.log(ko(s));return}let o=!e.flags.noColor&&process.stdout.isTTY!==!1;console.log(wo(s,o)),s.outdatedCount>0&&(process.exitCode=1)}catch(s){e.flags.machine&&(t?.(),console.log(K("outdated",W.UNKNOWN_ERROR,s.message,r)),process.exit(1)),w(s.message),process.exit(1)}}function Rh(){console.log(`${i.bold("Usage:")} asm update [name...] [options]
1017
920
 
1018
921
  Update outdated skills to their latest version with security re-audit.
1019
922
 
1020
- ${l.bold("Arguments:")}
923
+ ${i.bold("Arguments:")}
1021
924
  name Specific skill(s) to update (default: all outdated)
1022
925
 
1023
- ${l.bold("Options:")}
926
+ ${i.bold("Options:")}
1024
927
  -y, --yes Skip confirmation prompts
1025
928
  --json Output as JSON
1026
929
  --machine Output in stable machine-readable format
1027
930
  --no-color Disable ANSI colors
1028
931
  -V, --verbose Show debug output
1029
932
 
1030
- ${l.bold("Examples:")}
1031
- asm update ${l.dim("Update all outdated skills")}
1032
- asm update code-review ${l.dim("Update a specific skill")}
1033
- asm update --yes ${l.dim("Skip confirmation prompts")}
1034
- asm update --json ${l.dim("Output as JSON")}`)}async function zh(e){if(e.flags.help){dE();return}let t=e.flags.machine?he():void 0,s=performance.now(),i=[];e.subcommand&&i.push(e.subcommand),i.push(...e.positional);try{let r=await Wa(i.length>0?i:null,e.flags.yes);if(e.flags.machine){t?.();let o=r.results.map(a=>({name:a.name,status:a.status,reason:a.reason||null,old_commit:a.oldCommit||null,new_commit:a.newCommit||null,security_verdict:a.securityVerdict||null}));console.log(V("update",o,s));return}if(e.flags.json){console.log(Xa(r));return}if(r.results.length>0&&console.error(l.yellow("Note: project-scoped skill detection is not yet supported. All updates target the global skill path.")),r.warnings&&r.warnings.length>0)for(let o of r.warnings)console.error(l.yellow(`Warning: skill "${o}" not found in lock file \u2014 skipped`));if(r.results.length===0){console.log("All skills are up to date.");return}for(let o of r.results)switch(o.status){case"updated":console.log(`${l.green("\u2713")} ${o.name} ${l.dim(o.oldCommit||"")} \u2192 ${o.newCommit||""}`),o.securityVerdict==="warning"&&console.error(l.yellow(` \u26A0 Security audit returned warning for ${o.name} \u2014 updated because --yes was supplied`));break;case"skipped":console.log(`${l.yellow("\u25CB")} ${o.name} ${l.dim(o.reason||"skipped")}`);break;case"failed":console.log(`${l.red("\u2717")} ${o.name} ${l.dim(o.reason||"failed")}`);break}console.log("");let n=[];r.updatedCount>0&&n.push(l.green(`${r.updatedCount} updated`)),r.skippedCount>0&&n.push(l.yellow(`${r.skippedCount} skipped`)),r.failedCount>0&&n.push(l.red(`${r.failedCount} failed`)),console.log(n.join(", ")),r.failedCount>0&&(process.exitCode=1)}catch(r){e.flags.machine&&(t?.(),console.log(z("update",Y.UNKNOWN_ERROR,r.message,s)),process.exit(1)),$(r.message),process.exit(1)}}import{execFile as fE}from"child_process";import{promisify as pE}from"util";import{access as Xh,readFile as Qh,readdir as mE,writeFile as hE,rm as gE,stat as eg}from"fs/promises";import{join as Ol}from"path";import{homedir as yE}from"os";import{constants as Zh}from"fs";var Zt=pE(fE);async function bE(e){let t=e?.execFn??Zt;try{let{stdout:s}=await t("git",["--version"],{timeout:5e3});return{name:"Git available",status:"pass",message:s.trim().replace("git version ","")}}catch{return{name:"Git available",status:"fail",message:"git not found",fix:"Install git: https://git-scm.com/downloads"}}}async function wE(e){let t=e?.execFn??Zt;try{let{stdout:s}=await t("git",["--version"],{timeout:5e3}),i=s.match(/(\d+)\.(\d+)/);if(!i)return{name:"Git version",status:"warn",message:"Could not parse git version",fix:"Upgrade git: https://git-scm.com/downloads"};let r=parseInt(i[1],10),n=parseInt(i[2],10);return r>2||r===2&&n>=20?{name:"Git version",status:"pass",message:`${r}.${n} (>= 2.20)`}:{name:"Git version",status:"fail",message:`${r}.${n} (requires >= 2.20)`,fix:"Upgrade git: https://git-scm.com/downloads"}}catch{return{name:"Git version",status:"pass",message:"Skipped \u2014 git not available"}}}async function kE(e){let t=e?.execFn??Zt;try{let{stdout:s}=await t("gh",["--version"],{timeout:5e3}),i=s.trim().split(`
1035
- `)[0],r=i.match(/(\d+\.\d+\.\d+)/);return{name:"GitHub CLI available",status:"pass",message:r?r[1]:i}}catch{return{name:"GitHub CLI available",status:"fail",message:"gh not found",fix:"Install GitHub CLI: https://cli.github.com"}}}async function vE(e){let t=e?.execFn??Zt;try{let{stdout:s}=await t("gh",["auth","status"],{timeout:1e4}),i=s.match(/Logged in to .+ account (\S+)/);return{name:"GitHub CLI authenticated",status:"pass",message:i?i[1]:"authenticated"}}catch(s){let r=(s?.stderr??"").match(/Logged in to .+ account (\S+)/);return r?{name:"GitHub CLI authenticated",status:"pass",message:r[1]}:{name:"GitHub CLI authenticated",status:"fail",message:"Not authenticated",fix:"Run: gh auth login"}}}async function SE(e){let t=e?.execFn??Zt;try{let{stdout:s}=await t("node",["--version"],{timeout:5e3}),i=s.trim().replace(/^v/,"");return parseInt(i.split(".")[0],10)>=22?{name:"Node.js version",status:"pass",message:i}:{name:"Node.js version",status:"fail",message:`${i} (requires >= 22.0)`,fix:"Upgrade Node.js: https://nodejs.org"}}catch{return{name:"Node.js version",status:"fail",message:"node not found",fix:"Install Node.js >= 22: https://nodejs.org"}}}async function $E(e){try{let t=Ol(e,".asm-doctor-write-test");return await hE(t,"test","utf-8"),await gE(t),{writable:!0,exists:!0}}catch{}try{return await Xh(e,Zh.W_OK),{writable:!0,exists:!0}}catch{}try{return await Xh(e,Zh.F_OK),{writable:!1,exists:!0}}catch{return{writable:!0,exists:!1}}}async function xE(e){let t=e.providers.filter(n=>n.enabled),s=0,i=0;for(let n of t){let o=ie(n.global);i++,(await $E(o)).writable&&s++}if(s===i)return{name:"Agent directories writable",status:"pass",message:`${s}/${i} providers`};let r=i-s;return{name:"Agent directories writable",status:"warn",message:`${s}/${i} providers (${r} not writable)`,fix:"Fix permissions on agent skill directories"}}async function EE(){let e=rs();try{let t=await Qh(e,"utf-8"),s=JSON.parse(t),i=[];return s.version===void 0&&i.push("version"),Array.isArray(s.providers)||i.push("providers"),i.length>0?{name:"Config file valid",status:"fail",message:`Missing required fields: ${i.join(", ")}`,fix:"Run: asm init"}:{name:"Config file valid",status:"pass",message:"OK"}}catch(t){return t?.code==="ENOENT"?{name:"Config file valid",status:"pass",message:"No config file (using defaults)"}:{name:"Config file valid",status:"fail",message:"Corrupted or unreadable config",fix:"Run: asm init, or delete corrupted config"}}}async function PE(){let e=Hl();try{let t=await Qh(e,"utf-8"),s=JSON.parse(t);if(s.version!==1||typeof s.skills!="object")return{name:"Lock file integrity",status:"fail",message:"Invalid lock file schema",fix:"Run: asm install to regenerate"};let i=s.skills,r=Object.entries(i),n=["source","installedAt","provider"],o=[];for(let[a,c]of r){if(typeof c!="object"||c===null){o.push(a);continue}let u=c;for(let f of n)if(!u[f]){o.push(a);break}}return o.length>0?{name:"Lock file integrity",status:"warn",message:`${r.length} skills tracked, ${o.length} with missing fields`,fix:"Run: asm install to regenerate"}:{name:"Lock file integrity",status:"pass",message:`${r.length} skills tracked`}}catch(t){return t?.code==="ENOENT"?{name:"Lock file integrity",status:"pass",message:"No lock file (first-time user)"}:{name:"Lock file integrity",status:"fail",message:"Corrupted lock file",fix:"Run: asm install to regenerate"}}}async function CE(){try{let e=await fetch(xa,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return e.ok?{name:"Registry reachable",status:"pass",message:"OK"}:{name:"Registry reachable",status:"fail",message:`HTTP ${e.status}`,fix:"Check network connection or proxy settings"}}catch{return{name:"Registry reachable",status:"fail",message:"Network error",fix:"Check network connection or proxy settings"}}}async function IE(e,t){let s=Object.entries(t.skills);if(s.length===0)return{name:"Installed skills intact",status:"pass",message:"No skills in lock file"};let i=[];for(let[o,a]of s){let c=e.providers.find(d=>d.name===a.provider);if(!c){i.push(o);continue}let u=ie(c.global),f=Ol(u,o);try{(await eg(f)).isDirectory()||i.push(o)}catch{i.push(o)}}if(i.length===0)return{name:"Installed skills intact",status:"pass",message:`${s.length} skills verified`};let r=i[0],n=i.length>1?` (+${i.length-1} more)`:"";return{name:"Installed skills intact",status:"fail",message:`Missing: ${r}${n}`,fix:`Run: asm update ${r}`}}async function LE(e,t){let s=new Set(Object.keys(t.skills)),i=[];for(let r of e.providers.filter(n=>n.enabled)){let n=ie(r.global);try{let o=await mE(n);for(let a of o)try{(await eg(Ol(n,a))).isDirectory()&&!s.has(a)&&i.push(a)}catch{}}catch{}}return i.length===0?{name:"No orphaned skills",status:"pass",message:"OK"}:{name:"No orphaned skills",status:"warn",message:`${i.length} skill(s) without lock entries`,fix:"Run: asm list to review"}}async function AE(e){let t=e?.execFn??Zt;try{let{stdout:s}=await t("df",["-Pk",yE()],{timeout:5e3}),i=s.trim().split(`
1036
- `);if(i.length<2)return{name:"Disk space",status:"warn",message:"Could not parse df output"};let r=i[1].split(/\s+/),n=parseInt(r[3],10);if(isNaN(n))return{name:"Disk space",status:"warn",message:"Could not parse available space"};let o=n/1024,a=o/1024;return o>100?{name:"Disk space",status:"pass",message:`OK (${a>=1?`${a.toFixed(1)} GB free`:`${Math.round(o)} MB free`})`}:{name:"Disk space",status:"fail",message:`${Math.round(o)} MB free (requires > 100 MB)`,fix:"Free disk space in home directory"}}catch{return{name:"Disk space",status:"warn",message:"Could not check disk space"}}}async function RE(){try{let e=await Ii();if(e.shadowed.length===0)return e.resolved?{name:"No PATH shadowing",status:"pass",message:`single install at ${e.resolved.path}`}:{name:"No PATH shadowing",status:"pass",message:"asm not yet on PATH"};let t=e.resolved,s=e.shadowed[0].path,i=e.shadowed.length>1?` (+${e.shadowed.length-1} more)`:"";return{name:"No PATH shadowing",status:"warn",message:`resolved ${t.path}, shadowed ${s}${i}`,fix:`Remove the shadowed install at ${s} (e.g. \`npm uninstall -g agent-skill-manager\`) and keep ${t.path}.`}}catch(e){return{name:"No PATH shadowing",status:"warn",message:`Could not scan PATH: ${e?.message??e}`}}}async function tg(){let e=await j(),t=await Ke(),i=(await Promise.allSettled([bE(),wE(),kE(),vE(),SE(),xE(e),EE(),PE(),CE(),IE(e,t),LE(e,t),AE(),RE()])).map((a,c)=>a.status==="fulfilled"?a.value:{name:["Git available","Git version","GitHub CLI available","GitHub CLI authenticated","Node.js version","Agent directories writable","Config file valid","Lock file integrity","Registry reachable","Installed skills intact","No orphaned skills","Disk space","No PATH shadowing"][c],status:"fail",message:`Check threw: ${a.reason}`}),r=i.filter(a=>a.status==="pass").length,n=i.filter(a=>a.status==="warn").length,o=i.filter(a=>a.status==="fail").length;return{checks:i,passed:r,warnings:n,failures:o}}var NE={pass:"\u2705",warn:"\u26A0\uFE0F ",fail:"\u274C"};function sg(e){let t=["Checking your environment...",""];for(let s of e.checks){let r=` ${NE[s.status]} ${s.name}${s.message?` (${s.message})`:""}`;if(t.push(r),s.fix&&s.status!=="pass"){let n;s.fix.startsWith("Run: ")?n=s.fix:/^[a-z/~]/.test(s.fix)?n=`Run: ${s.fix}`:n=`Fix: ${s.fix}`,t.push(` \u2192 ${n}`)}}return t.push(""),t.push(`${e.passed} passed, ${e.warnings} warning${e.warnings!==1?"s":""}, ${e.failures} error${e.failures!==1?"s":""}`),t.join(`
1037
- `)}function ig(e){return JSON.stringify({checks:e.checks.map(t=>({name:t.name,status:t.status,message:t.message,...t.fix?{fix:t.fix}:{}})),summary:{passed:e.passed,warnings:e.warnings,failures:e.failures}},null,2)}function TE(){console.log(`${l.bold("Usage:")} asm doctor [options]
933
+ ${i.bold("Examples:")}
934
+ asm update ${i.dim("Update all outdated skills")}
935
+ asm update code-review ${i.dim("Update a specific skill")}
936
+ asm update --yes ${i.dim("Skip confirmation prompts")}
937
+ asm update --json ${i.dim("Output as JSON")}`)}async function ld(e){if(e.flags.help){Rh();return}let t=e.flags.machine?le():void 0,r=performance.now(),s=[];e.subcommand&&s.push(e.subcommand),s.push(...e.positional);try{let o=await bo(s.length>0?s:null,e.flags.yes);if(e.flags.machine){t?.();let a=o.results.map(l=>({name:l.name,status:l.status,reason:l.reason||null,old_commit:l.oldCommit||null,new_commit:l.newCommit||null,security_verdict:l.securityVerdict||null}));console.log(B("update",a,r));return}if(e.flags.json){console.log(vo(o));return}if(o.results.length>0&&console.error(i.yellow("Note: project-scoped skill detection is not yet supported. All updates target the global skill path.")),o.warnings&&o.warnings.length>0)for(let a of o.warnings)console.error(i.yellow(`Warning: skill "${a}" not found in lock file \u2014 skipped`));if(o.results.length===0){console.log("All skills are up to date.");return}for(let a of o.results)switch(a.status){case"updated":console.log(`${i.green("\u2713")} ${a.name} ${i.dim(a.oldCommit||"")} \u2192 ${a.newCommit||""}`),a.securityVerdict==="warning"&&console.error(i.yellow(` \u26A0 Security audit returned warning for ${a.name} \u2014 updated because --yes was supplied`));break;case"skipped":console.log(`${i.yellow("\u25CB")} ${a.name} ${i.dim(a.reason||"skipped")}`);break;case"failed":console.log(`${i.red("\u2717")} ${a.name} ${i.dim(a.reason||"failed")}`);break}console.log("");let n=[];o.updatedCount>0&&n.push(i.green(`${o.updatedCount} updated`)),o.skippedCount>0&&n.push(i.yellow(`${o.skippedCount} skipped`)),o.failedCount>0&&n.push(i.red(`${o.failedCount} failed`)),console.log(n.join(", ")),o.failedCount>0&&(process.exitCode=1)}catch(o){e.flags.machine&&(t?.(),console.log(K("update",W.UNKNOWN_ERROR,o.message,r)),process.exit(1)),w(o.message),process.exit(1)}}import{execFile as Eh}from"child_process";import{promisify as Ih}from"util";import{access as cd,readFile as ud,readdir as Ch,writeFile as Lh,rm as Ah,stat as pd}from"fs/promises";import{join as pn}from"path";import{homedir as Th}from"os";import{constants as dd}from"fs";var $t=Ih(Eh);async function Nh(e){let t=e?.execFn??$t;try{let{stdout:r}=await t("git",["--version"],{timeout:5e3});return{name:"Git available",status:"pass",message:r.trim().replace("git version ","")}}catch{return{name:"Git available",status:"fail",message:"git not found",fix:"Install git: https://git-scm.com/downloads"}}}async function Oh(e){let t=e?.execFn??$t;try{let{stdout:r}=await t("git",["--version"],{timeout:5e3}),s=r.match(/(\d+)\.(\d+)/);if(!s)return{name:"Git version",status:"warn",message:"Could not parse git version",fix:"Upgrade git: https://git-scm.com/downloads"};let o=parseInt(s[1],10),n=parseInt(s[2],10);return o>2||o===2&&n>=20?{name:"Git version",status:"pass",message:`${o}.${n} (>= 2.20)`}:{name:"Git version",status:"fail",message:`${o}.${n} (requires >= 2.20)`,fix:"Upgrade git: https://git-scm.com/downloads"}}catch{return{name:"Git version",status:"pass",message:"Skipped \u2014 git not available"}}}async function Dh(e){let t=e?.execFn??$t;try{let{stdout:r}=await t("gh",["--version"],{timeout:5e3}),s=r.trim().split(`
938
+ `)[0],o=s.match(/(\d+\.\d+\.\d+)/);return{name:"GitHub CLI available",status:"pass",message:o?o[1]:s}}catch{return{name:"GitHub CLI available",status:"fail",message:"gh not found",fix:"Install GitHub CLI: https://cli.github.com"}}}async function Mh(e){let t=e?.execFn??$t;try{let{stdout:r}=await t("gh",["auth","status"],{timeout:1e4}),s=r.match(/Logged in to .+ account (\S+)/);return{name:"GitHub CLI authenticated",status:"pass",message:s?s[1]:"authenticated"}}catch(r){let o=(r?.stderr??"").match(/Logged in to .+ account (\S+)/);return o?{name:"GitHub CLI authenticated",status:"pass",message:o[1]}:{name:"GitHub CLI authenticated",status:"fail",message:"Not authenticated",fix:"Run: gh auth login"}}}async function Fh(e){let t=e?.execFn??$t;try{let{stdout:r}=await t("node",["--version"],{timeout:5e3}),s=r.trim().replace(/^v/,"");return parseInt(s.split(".")[0],10)>=22?{name:"Node.js version",status:"pass",message:s}:{name:"Node.js version",status:"fail",message:`${s} (requires >= 22.0)`,fix:"Upgrade Node.js: https://nodejs.org"}}catch{return{name:"Node.js version",status:"fail",message:"node not found",fix:"Install Node.js >= 22: https://nodejs.org"}}}async function jh(e){try{let t=pn(e,".asm-doctor-write-test");return await Lh(t,"test","utf-8"),await Ah(t),{writable:!0,exists:!0}}catch{}try{return await cd(e,dd.W_OK),{writable:!0,exists:!0}}catch{}try{return await cd(e,dd.F_OK),{writable:!1,exists:!0}}catch{return{writable:!0,exists:!1}}}async function _h(e){let t=e.providers.filter(n=>n.enabled),r=0,s=0;for(let n of t){let a=Q(n.global);s++,(await jh(a)).writable&&r++}if(r===s)return{name:"Agent directories writable",status:"pass",message:`${r}/${s} providers`};let o=s-r;return{name:"Agent directories writable",status:"warn",message:`${r}/${s} providers (${o} not writable)`,fix:"Fix permissions on agent skill directories"}}async function Uh(){let e=Ct();try{let t=await ud(e,"utf-8"),r=JSON.parse(t),s=[];return r.version===void 0&&s.push("version"),Array.isArray(r.providers)||s.push("providers"),s.length>0?{name:"Config file valid",status:"fail",message:`Missing required fields: ${s.join(", ")}`,fix:"Run: asm init"}:{name:"Config file valid",status:"pass",message:"OK"}}catch(t){return t?.code==="ENOENT"?{name:"Config file valid",status:"pass",message:"No config file (using defaults)"}:{name:"Config file valid",status:"fail",message:"Corrupted or unreadable config",fix:"Run: asm init, or delete corrupted config"}}}async function Bh(){let e=Cn();try{let t=await ud(e,"utf-8"),r=JSON.parse(t);if(r.version!==1||typeof r.skills!="object")return{name:"Lock file integrity",status:"fail",message:"Invalid lock file schema",fix:"Run: asm install to regenerate"};let s=r.skills,o=Object.entries(s),n=["source","installedAt","provider"],a=[];for(let[l,c]of o){if(typeof c!="object"||c===null){a.push(l);continue}let d=c;for(let u of n)if(!d[u]){a.push(l);break}}return a.length>0?{name:"Lock file integrity",status:"warn",message:`${o.length} skills tracked, ${a.length} with missing fields`,fix:"Run: asm install to regenerate"}:{name:"Lock file integrity",status:"pass",message:`${o.length} skills tracked`}}catch(t){return t?.code==="ENOENT"?{name:"Lock file integrity",status:"pass",message:"No lock file (first-time user)"}:{name:"Lock file integrity",status:"fail",message:"Corrupted lock file",fix:"Run: asm install to regenerate"}}}async function Vh(){try{let e=await fetch(Ks,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return e.ok?{name:"Registry reachable",status:"pass",message:"OK"}:{name:"Registry reachable",status:"fail",message:`HTTP ${e.status}`,fix:"Check network connection or proxy settings"}}catch{return{name:"Registry reachable",status:"fail",message:"Network error",fix:"Check network connection or proxy settings"}}}async function Gh(e,t){let r=Object.entries(t.skills);if(r.length===0)return{name:"Installed skills intact",status:"pass",message:"No skills in lock file"};let s=[];for(let[a,l]of r){let c=e.providers.find(p=>p.name===l.provider);if(!c){s.push(a);continue}let d=Q(c.global),u=pn(d,a);try{(await pd(u)).isDirectory()||s.push(a)}catch{s.push(a)}}if(s.length===0)return{name:"Installed skills intact",status:"pass",message:`${r.length} skills verified`};let o=s[0],n=s.length>1?` (+${s.length-1} more)`:"";return{name:"Installed skills intact",status:"fail",message:`Missing: ${o}${n}`,fix:`Run: asm update ${o}`}}async function Hh(e,t){let r=new Set(Object.keys(t.skills)),s=[];for(let o of e.providers.filter(n=>n.enabled)){let n=Q(o.global);try{let a=await Ch(n);for(let l of a)try{(await pd(pn(n,l))).isDirectory()&&!r.has(l)&&s.push(l)}catch{}}catch{}}return s.length===0?{name:"No orphaned skills",status:"pass",message:"OK"}:{name:"No orphaned skills",status:"warn",message:`${s.length} skill(s) without lock entries`,fix:"Run: asm list to review"}}async function qh(e){let t=e?.execFn??$t;try{let{stdout:r}=await t("df",["-Pk",Th()],{timeout:5e3}),s=r.trim().split(`
939
+ `);if(s.length<2)return{name:"Disk space",status:"warn",message:"Could not parse df output"};let o=s[1].split(/\s+/),n=parseInt(o[3],10);if(isNaN(n))return{name:"Disk space",status:"warn",message:"Could not parse available space"};let a=n/1024,l=a/1024;return a>100?{name:"Disk space",status:"pass",message:`OK (${l>=1?`${l.toFixed(1)} GB free`:`${Math.round(a)} MB free`})`}:{name:"Disk space",status:"fail",message:`${Math.round(a)} MB free (requires > 100 MB)`,fix:"Free disk space in home directory"}}catch{return{name:"Disk space",status:"warn",message:"Could not check disk space"}}}async function Wh(){try{let e=await xr();if(e.shadowed.length===0)return e.resolved?{name:"No PATH shadowing",status:"pass",message:`single install at ${e.resolved.path}`}:{name:"No PATH shadowing",status:"pass",message:"asm not yet on PATH"};let t=e.resolved,r=e.shadowed[0].path,s=e.shadowed.length>1?` (+${e.shadowed.length-1} more)`:"";return{name:"No PATH shadowing",status:"warn",message:`resolved ${t.path}, shadowed ${r}${s}`,fix:`Remove the shadowed install at ${r} (e.g. \`npm uninstall -g agent-skill-manager\`) and keep ${t.path}.`}}catch(e){return{name:"No PATH shadowing",status:"warn",message:`Could not scan PATH: ${e?.message??e}`}}}async function md(){let e=await O(),t=await Te(),s=(await Promise.allSettled([Nh(),Oh(),Dh(),Mh(),Fh(),_h(e),Uh(),Bh(),Vh(),Gh(e,t),Hh(e,t),qh(),Wh()])).map((l,c)=>l.status==="fulfilled"?l.value:{name:["Git available","Git version","GitHub CLI available","GitHub CLI authenticated","Node.js version","Agent directories writable","Config file valid","Lock file integrity","Registry reachable","Installed skills intact","No orphaned skills","Disk space","No PATH shadowing"][c],status:"fail",message:`Check threw: ${l.reason}`}),o=s.filter(l=>l.status==="pass").length,n=s.filter(l=>l.status==="warn").length,a=s.filter(l=>l.status==="fail").length;return{checks:s,passed:o,warnings:n,failures:a}}var Kh={pass:"\u2705",warn:"\u26A0\uFE0F ",fail:"\u274C"};function fd(e){let t=["Checking your environment...",""];for(let r of e.checks){let o=` ${Kh[r.status]} ${r.name}${r.message?` (${r.message})`:""}`;if(t.push(o),r.fix&&r.status!=="pass"){let n;r.fix.startsWith("Run: ")?n=r.fix:/^[a-z/~]/.test(r.fix)?n=`Run: ${r.fix}`:n=`Fix: ${r.fix}`,t.push(` \u2192 ${n}`)}}return t.push(""),t.push(`${e.passed} passed, ${e.warnings} warning${e.warnings!==1?"s":""}, ${e.failures} error${e.failures!==1?"s":""}`),t.join(`
940
+ `)}function gd(e){return JSON.stringify({checks:e.checks.map(t=>({name:t.name,status:t.status,message:t.message,...t.fix?{fix:t.fix}:{}})),summary:{passed:e.passed,warnings:e.warnings,failures:e.failures}},null,2)}function Jh(){console.log(`${i.bold("Usage:")} asm doctor [options]
1038
941
 
1039
942
  Run environment health checks and diagnostics. Validates all
1040
943
  prerequisites for using asm \u2014 git, GitHub CLI, Node.js, config,
1041
944
  lock file, registry, installed skills, and disk space.
1042
945
 
1043
- ${l.bold("Options:")}
946
+ ${i.bold("Options:")}
1044
947
  --json Output as JSON
1045
948
  --machine Output in stable machine-readable v1 envelope format
1046
949
  --no-color Disable ANSI colors
1047
950
  -V, --verbose Show debug output
1048
951
 
1049
- ${l.bold("Examples:")}
1050
- asm doctor ${l.dim("Run all health checks")}
1051
- asm doctor --json ${l.dim("Output as JSON")}
1052
- asm doctor --machine ${l.dim("Machine-readable v1 envelope output")}`)}async function rg(e){if(e.flags.help){TE();return}let t=performance.now(),s=await tg();if(e.flags.machine){let i={checks:s.checks.map(r=>({name:r.name,status:r.status,message:r.message,...r.fix?{fix:r.fix}:{}})),passed:s.passed,warnings:s.warnings,failures:s.failures};console.log(V("doctor",i,t))}else e.flags.json?console.log(ig(s)):console.log(sg(s));s.failures>0&&process.exit(1)}function OE(e){let t=e.slice(2),s={command:null,subcommand:null,positional:[],flags:{help:!1,version:!1,json:!1,yes:!1,noColor:!1,scope:"both",sort:"name",provider:null,name:null,force:!1,path:null,all:!1,library:!1,verbose:!1,flat:!1,transport:"auto",method:"default",installed:!1,available:!1,has:[],missing:[],modelInvocable:!1,userInvocable:!1,tagFilters:[],dryRun:!1,diff:!1,machine:!1,noCache:!1,fix:!1,compact:!1,summary:!1,groupBy:null,limit:0,concurrency:0,keep:!1,tokens:!1,add:null,remove:null,description:null,author:null,tags:null,predefined:!1,audit:!1,threshold:null}},i=0;for(;i<t.length;){let r=t[i];if(r==="--help"||r==="-h")s.flags.help=!0;else if(r==="--version"||r==="-v")s.flags.version=!0;else if(r==="--json")s.flags.json=!0;else if(r==="--yes"||r==="-y")s.flags.yes=!0;else if(r==="--no-color")s.flags.noColor=!0;else if(r==="--scope"||r==="-s"){i++;let n=t[i],o=n==="local"?"project":n;o==="global"||o==="project"||o==="both"?s.flags.scope=o:(Ee(`Invalid scope: "${n}". Must be global, local, project, or both.`),process.exit(2))}else if(r==="--sort"){i++;let n=t[i];n==="name"||n==="version"||n==="location"?s.flags.sort=n:(Ee(`Invalid sort: "${n}". Must be name, version, or location.`),process.exit(2))}else if(r==="--provider"||r==="-p"||r==="--tool")i++,s.flags.provider=t[i]||null;else if(r==="--name")i++,s.flags.name=t[i]||null;else if(r==="--force"||r==="-f")s.flags.force=!0;else if(r==="--path")i++,s.flags.path=t[i]||null;else if(r==="--all")s.flags.all=!0;else if(r==="--library")s.flags.library=!0;else if(r==="--verbose"||r==="-V")s.flags.verbose=!0;else if(r==="--flat")s.flags.flat=!0;else if(r==="--compact")s.flags.compact=!0;else if(r==="--summary")s.flags.summary=!0;else if(r==="--group-by"){i++;let n=t[i];n==="tool"||n==="scope"||n==="effort"?s.flags.groupBy=n:(Ee(`Invalid --group-by: "${n}". Must be tool, scope, or effort.`),process.exit(2))}else if(r==="--limit"){i++;let n=t[i],o=Number(n);(!Number.isFinite(o)||o<0||!Number.isInteger(o))&&(Ee(`Invalid --limit: "${n}". Must be a non-negative integer (0 means no limit).`),process.exit(2)),s.flags.limit=o}else if(r==="--installed")s.flags.installed=!0;else if(r==="--available")s.flags.available=!0;else if(r==="--concurrency"){i++;let n=t[i],o=Number(n);(!Number.isFinite(o)||o<1||!Number.isInteger(o))&&(Ee(`Invalid --concurrency: "${n}". Must be a positive integer.`),process.exit(2)),s.flags.concurrency=o}else if(r==="--keep")s.flags.keep=!0;else if(r==="--tokens")s.flags.tokens=!0;else if(r==="--transport"||r==="-t"){i++;let n=t[i];n==="https"||n==="ssh"||n==="auto"?s.flags.transport=n:(Ee(`Invalid transport: "${n}". Must be https, ssh, or auto.`),process.exit(2))}else if(r==="--method"||r==="-m"){i++;let n=t[i];n==="default"||n==="vercel"?s.flags.method=n:(Ee(`Invalid method: "${n}". Must be default or vercel.`),process.exit(2))}else if(r==="--skill")i++,s.flags.path=t[i]||null;else if(r==="--dry-run")s.flags.dryRun=!0;else if(r==="--diff")s.flags.diff=!0;else if(r==="--fix")s.flags.fix=!0;else if(r==="--machine")s.flags.machine=!0;else if(r==="--no-cache")s.flags.noCache=!0;else if(r==="--has")i++,t[i]&&s.flags.has.push(t[i]);else if(r==="--missing")i++,t[i]&&s.flags.missing.push(t[i]);else if(r==="--model-invocable")s.flags.modelInvocable=!0;else if(r==="--user-invocable")s.flags.userInvocable=!0;else if(r==="--tag")i++,t[i]||(Ee('Missing value for "--tag".'),process.exit(2)),s.flags.tagFilters.push(t[i]);else if(r==="--add")i++,s.flags.add=t[i]||null;else if(r==="--remove")i++,s.flags.remove=t[i]||null;else if(r==="--description")i++,s.flags.description=t[i]||null;else if(r==="--author")i++,s.flags.author=t[i]||null;else if(r==="--tags")i++,s.flags.tags=t[i]||null;else if(r==="--predefined")s.flags.predefined=!0;else if(r==="--audit")s.flags.audit=!0;else if(r==="--threshold"){i++;let n=t[i],o=Number(n);!isNaN(o)&&o>=0&&o<=1?s.flags.threshold=o:(Ee(`Invalid --threshold: "${n}". Must be a number between 0 and 1.`),process.exit(2))}else r.startsWith("-")?(Ee(`Unknown option: ${r}`),console.error('Run "asm --help" for usage.'),process.exit(2)):s.command?s.subcommand?s.positional.push(r):s.subcommand=r:s.command=r;i++}return s}function Ee(e){console.error(l.red(`Error: ${e}`))}function ME(){console.log(`${l.blueBold("agent-skill-manager")} (${l.bold("asm")}) ${wn()}
952
+ ${i.bold("Examples:")}
953
+ asm doctor ${i.dim("Run all health checks")}
954
+ asm doctor --json ${i.dim("Output as JSON")}
955
+ asm doctor --machine ${i.dim("Machine-readable v1 envelope output")}`)}async function hd(e){if(e.flags.help){Jh();return}let t=performance.now(),r=await md();if(e.flags.machine){let s={checks:r.checks.map(o=>({name:o.name,status:o.status,message:o.message,...o.fix?{fix:o.fix}:{}})),passed:r.passed,warnings:r.warnings,failures:r.failures};console.log(B("doctor",s,t))}else e.flags.json?console.log(gd(r)):console.log(fd(r));r.failures>0&&process.exit(1)}function zh(e){let t=e.slice(2),r={command:null,subcommand:null,positional:[],flags:{help:!1,version:!1,json:!1,yes:!1,noColor:!1,scope:"both",sort:"name",provider:null,name:null,force:!1,path:null,all:!1,library:!1,verbose:!1,flat:!1,transport:"auto",method:"default",installed:!1,available:!1,has:[],missing:[],modelInvocable:!1,userInvocable:!1,tagFilters:[],dryRun:!1,diff:!1,machine:!1,noCache:!1,fix:!1,compact:!1,summary:!1,groupBy:null,limit:0,concurrency:0,keep:!1,tokens:!1,add:null,remove:null,description:null,author:null,tags:null,predefined:!1,audit:!1,threshold:null,session:null,staleBefore:null}},s=0;for(;s<t.length;){let o=t[s];if(o==="--help"||o==="-h")r.flags.help=!0;else if(o==="--version"||o==="-v")r.flags.version=!0;else if(o==="--json")r.flags.json=!0;else if(o==="--yes"||o==="-y")r.flags.yes=!0;else if(o==="--no-color")r.flags.noColor=!0;else if(o==="--scope"||o==="-s"){s++;let n=t[s],a=n==="local"?"project":n;a==="global"||a==="project"||a==="both"?r.flags.scope=a:(be(`Invalid scope: "${n}". Must be global, local, project, or both.`),process.exit(2))}else if(o==="--sort"){s++;let n=t[s];n==="name"||n==="version"||n==="location"?r.flags.sort=n:(be(`Invalid sort: "${n}". Must be name, version, or location.`),process.exit(2))}else if(o==="--provider"||o==="-p"||o==="--tool")s++,r.flags.provider=t[s]||null;else if(o==="--name")s++,r.flags.name=t[s]||null;else if(o==="--force"||o==="-f")r.flags.force=!0;else if(o==="--path")s++,r.flags.path=t[s]||null;else if(o==="--all")r.flags.all=!0;else if(o==="--library")r.flags.library=!0;else if(o==="--verbose"||o==="-V")r.flags.verbose=!0;else if(o==="--flat")r.flags.flat=!0;else if(o==="--compact")r.flags.compact=!0;else if(o==="--summary")r.flags.summary=!0;else if(o==="--group-by"){s++;let n=t[s];n==="tool"||n==="scope"||n==="effort"?r.flags.groupBy=n:(be(`Invalid --group-by: "${n}". Must be tool, scope, or effort.`),process.exit(2))}else if(o==="--limit"){s++;let n=t[s],a=Number(n);(!Number.isFinite(a)||a<0||!Number.isInteger(a))&&(be(`Invalid --limit: "${n}". Must be a non-negative integer (0 means no limit).`),process.exit(2)),r.flags.limit=a}else if(o==="--installed")r.flags.installed=!0;else if(o==="--available")r.flags.available=!0;else if(o==="--concurrency"){s++;let n=t[s],a=Number(n);(!Number.isFinite(a)||a<1||!Number.isInteger(a))&&(be(`Invalid --concurrency: "${n}". Must be a positive integer.`),process.exit(2)),r.flags.concurrency=a}else if(o==="--keep")r.flags.keep=!0;else if(o==="--tokens")r.flags.tokens=!0;else if(o==="--transport"||o==="-t"){s++;let n=t[s];n==="https"||n==="ssh"||n==="auto"?r.flags.transport=n:(be(`Invalid transport: "${n}". Must be https, ssh, or auto.`),process.exit(2))}else if(o==="--method"||o==="-m"){s++;let n=t[s];n==="default"||n==="vercel"?r.flags.method=n:(be(`Invalid method: "${n}". Must be default or vercel.`),process.exit(2))}else if(o==="--skill")s++,r.flags.path=t[s]||null;else if(o==="--dry-run")r.flags.dryRun=!0;else if(o==="--diff")r.flags.diff=!0;else if(o==="--fix")r.flags.fix=!0;else if(o==="--machine")r.flags.machine=!0;else if(o==="--no-cache")r.flags.noCache=!0;else if(o==="--has")s++,t[s]&&r.flags.has.push(t[s]);else if(o==="--missing")s++,t[s]&&r.flags.missing.push(t[s]);else if(o==="--model-invocable")r.flags.modelInvocable=!0;else if(o==="--user-invocable")r.flags.userInvocable=!0;else if(o==="--tag")s++,t[s]||(be('Missing value for "--tag".'),process.exit(2)),r.flags.tagFilters.push(t[s]);else if(o==="--add")s++,r.flags.add=t[s]||null;else if(o==="--remove")s++,r.flags.remove=t[s]||null;else if(o==="--description")s++,r.flags.description=t[s]||null;else if(o==="--author")s++,r.flags.author=t[s]||null;else if(o==="--tags")s++,r.flags.tags=t[s]||null;else if(o==="--predefined")r.flags.predefined=!0;else if(o==="--audit")r.flags.audit=!0;else if(o==="--threshold"){s++;let n=t[s],a=Number(n);!isNaN(a)&&a>=0&&a<=1?r.flags.threshold=a:(be(`Invalid --threshold: "${n}". Must be a number between 0 and 1.`),process.exit(2))}else o==="--session"?(s++,r.flags.session=t[s]||null):o==="--stale-before"?(s++,r.flags.staleBefore=t[s]||null):o.startsWith("-")?(be(`Unknown option: ${o}`),console.error('Run "asm --help" for usage.'),process.exit(2)):r.command?r.subcommand?r.positional.push(o):r.subcommand=o:r.command=o;s++}return r}function be(e){console.error(i.red(`Error: ${e}`))}function Yh(){console.log(`${i.blueBold("agent-skill-manager")} (${i.bold("asm")}) ${xs()}
1053
956
 
1054
957
  Interactive TUI and CLI for managing installed skills for AI coding agents.
1055
958
 
1056
- ${l.bold("Usage:")}
959
+ ${i.bold("Usage:")}
1057
960
  asm Launch interactive TUI
1058
961
  asm <command> [options] Run a CLI command
1059
962
 
1060
- ${l.bold("Commands:")}
963
+ ${i.bold("Commands:")}
1061
964
  list List all discovered skills
1062
965
  search <query> Search skills by name/description/tool
1063
966
  tag add|remove Edit local tags for an installed skill
1064
967
  inspect <skill-name> Show detailed info for a skill
1065
968
  get <skill> Print a skill's SKILL.md body (installs nothing)
969
+ deps Manage caller-owned temporary dependency leases
1066
970
  uninstall <skill-name> Remove a skill (with confirmation)
1067
971
  disable <target> Disable skill(s) without uninstalling
1068
972
  enable <target> Re-enable disabled skill(s)
@@ -1093,7 +997,7 @@ ${l.bold("Commands:")}
1093
997
  config reset Reset config to defaults
1094
998
  config edit Open config in $EDITOR
1095
999
 
1096
- ${l.bold("Global Options:")}
1000
+ ${i.bold("Global Options:")}
1097
1001
  -h, --help Show help for any command
1098
1002
  -v, --version Print version and exit
1099
1003
  --json Output as JSON (list, search, inspect)
@@ -1105,4 +1009,4 @@ ${l.bold("Global Options:")}
1105
1009
  --sort <field> Sort by: name, version, or location (default: name)
1106
1010
  --flat Show one row per tool instance (list, search)
1107
1011
  -y, --yes Skip confirmation prompts
1108
- -V, --verbose Show debug output`)}async function ng(e){let t=OE(e);if(t.flags.json&&t.flags.machine&&(Ee("--json and --machine are mutually exclusive. Use one or the other."),process.exit(2)),t.flags.machine&&(t.flags.yes=!0),t.flags.noColor&&(globalThis.__CLI_NO_COLOR=!0),t.flags.verbose&&Gl(!0),t.flags.version){console.log(`asm ${wn()}`);let s=await Ii();if(t.flags.verbose&&s.resolved&&(console.log(` path: ${s.resolved.path}`),s.resolved.realPath!==s.resolved.path&&console.log(` real: ${s.resolved.realPath}`)),s.shadowed.length>0&&s.resolved){console.error(""),console.error(l.yellow(`Warning: ${s.shadowed.length+1} \`asm\` binaries on PATH \u2014 you may be running a shadowed install.`)),console.error(` resolved: ${s.resolved.path}`);for(let i of s.shadowed)console.error(` shadowed: ${i.path}`);console.error(l.dim(` Remove the shadowed install at ${s.shadowed[0].path} (e.g. \`npm uninstall -g agent-skill-manager\`) and keep ${s.resolved.path}.`)),console.error(l.dim(" See: https://github.com/luongnv89/asm#troubleshooting"))}return}if(!t.command&&t.flags.help){ME();return}if(t.command)switch(t.command){case"list":await vf(t);break;case"search":await Tf(t);break;case"tag":await Of(t);break;case"inspect":await Mf(t);break;case"get":await ym(t);break;case"uninstall":await wm(t);break;case"disable":await wf(t);break;case"enable":await kf(t);break;case"audit":await Vm(t);break;case"install":await Sl(t);break;case"activate":await Ym(t);break;case"deactivate":await zm(t);break;case"library":await Xm(t);break;case"config":await Zm(t);break;case"export":await uh(t);break;case"import":await ph(t);break;case"init":await gh(t);break;case"stats":await yh(t);break;case"link":await bh(t);break;case"index":await Oh(t);break;case"bundle":await Kh(t);break;case"publish":await Wh(t);break;case"outdated":await Yh(t);break;case"update":await zh(t);break;case"doctor":await rg(t);break;case"eval":await hm(t);break;case"eval-providers":await gm(t);break;default:Ee(`Unknown command: "${t.command}"`),console.error('Run "asm --help" for usage.'),process.exit(2)}}function og(e){let t=e.slice(2);if(t.length===0)return!1;let s=["list","search","tag","inspect","get","uninstall","audit","config","install","activate","deactivate","library","export","import","init","stats","link","index","bundle","publish","outdated","update","doctor","eval","eval-providers","disable","enable"],i=t[0];return!!(s.includes(i)||i==="--help"||i==="-h"||i==="--version"||i==="-v"||i.startsWith("-")||i.length>0)}if(og(process.argv))await ng(process.argv).catch(e=>{console.error("Fatal error:",e),process.exit(1)});else{let{main:e}=await import("./src-SP66WR5V.js");await e().catch(t=>{console.error("Fatal error:",t),process.exit(1)})}
1012
+ -V, --verbose Show debug output`)}async function yd(e){let t=zh(e);if(t.flags.json&&t.flags.machine&&(be("--json and --machine are mutually exclusive. Use one or the other."),process.exit(2)),t.flags.machine&&(t.flags.yes=!0),t.flags.noColor&&(globalThis.__CLI_NO_COLOR=!0),t.flags.verbose&&In(!0),t.flags.version){console.log(`asm ${xs()}`);let r=await xr();if(t.flags.verbose&&r.resolved&&(console.log(` path: ${r.resolved.path}`),r.resolved.realPath!==r.resolved.path&&console.log(` real: ${r.resolved.realPath}`)),r.shadowed.length>0&&r.resolved){console.error(""),console.error(i.yellow(`Warning: ${r.shadowed.length+1} \`asm\` binaries on PATH \u2014 you may be running a shadowed install.`)),console.error(` resolved: ${r.resolved.path}`);for(let s of r.shadowed)console.error(` shadowed: ${s.path}`);console.error(i.dim(` Remove the shadowed install at ${r.shadowed[0].path} (e.g. \`npm uninstall -g agent-skill-manager\`) and keep ${r.resolved.path}.`)),console.error(i.dim(" See: https://github.com/luongnv89/asm#troubleshooting"))}return}if(!t.command&&t.flags.help){Yh();return}if(t.command)switch(t.command){case"list":await fi(t);break;case"search":await Ri(t);break;case"tag":await Ei(t);break;case"inspect":await Ii(t);break;case"get":await dl(t);break;case"deps":await Il(t);break;case"uninstall":await Ll(t);break;case"disable":await pi(t);break;case"enable":await mi(t);break;case"audit":await ec(t);break;case"install":await Qo(t);break;case"activate":await ac(t);break;case"deactivate":await lc(t);break;case"library":await cc(t);break;case"config":await dc(t);break;case"export":await Sc(t);break;case"import":await Pc(t);break;case"init":await Ic(t);break;case"stats":await Cc(t);break;case"link":await Lc(t);break;case"index":await Wc(t);break;case"bundle":await rd(t);break;case"publish":await id(t);break;case"outdated":await ad(t);break;case"update":await ld(t);break;case"doctor":await hd(t);break;case"eval":await ll(t);break;case"eval-providers":await cl(t);break;default:be(`Unknown command: "${t.command}"`),console.error('Run "asm --help" for usage.'),process.exit(2)}}function bd(e){let t=e.slice(2);if(t.length===0)return!1;let r=["list","search","tag","inspect","get","deps","uninstall","audit","config","install","activate","deactivate","library","export","import","init","stats","link","index","bundle","publish","outdated","update","doctor","eval","eval-providers","disable","enable"],s=t[0];return!!(r.includes(s)||s==="--help"||s==="-h"||s==="--version"||s==="-v"||s.startsWith("-")||s.length>0)}if(bd(process.argv))await yd(process.argv).catch(e=>{console.error("Fatal error:",e),process.exit(1)});else{let{main:e}=await import("./src-ORQ3FXUL.js");await e().catch(t=>{console.error("Fatal error:",t),process.exit(1)})}