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.
- package/README.md +92 -31
- package/data/bundles/content-writing.json +9 -9
- package/data/bundles/frontend-dev.json +6 -6
- package/data/bundles/game-dev.json +60 -0
- package/data/bundles/ios-release.json +1 -1
- package/data/bundles/marketing.json +40 -0
- package/data/bundles/software-dev.json +40 -0
- package/data/repo-stars.json +80 -0
- package/data/skill-index/Affitor_affiliate-skills.json +692 -226
- package/data/skill-index/AvdLee_Core-Data-Agent-Skill.json +7 -5
- package/data/skill-index/AvdLee_Swift-Concurrency-Agent-Skill.json +7 -5
- package/data/skill-index/AvdLee_Swift-Testing-Agent-Skill.json +7 -5
- package/data/skill-index/AvdLee_SwiftUI-Agent-Skill.json +53 -13
- package/data/skill-index/AvdLee_Xcode-Build-Optimization-Agent-Skill.json +102 -30
- package/data/skill-index/ComposioHQ_awesome-claude-skills.json +5231 -3467
- package/data/skill-index/DietrichGebert_ponytail.json +1307 -0
- package/data/skill-index/Dimillian_Skills.json +182 -72
- package/data/skill-index/Egonex-AI_Understand-Anything.json +66 -48
- package/data/skill-index/Eronred_aso-skills.json +443 -177
- package/data/skill-index/GPTomics_bioSkills.json +3618 -2494
- package/data/skill-index/Galaxy-Dawn_claude-scholar.json +313 -203
- package/data/skill-index/Imbad0202_academic-research-skills.json +42 -34
- package/data/skill-index/JuliusBrussee_caveman.json +261 -359
- package/data/skill-index/K-Dense-AI_claude-scientific-skills.json +2473 -2643
- package/data/skill-index/Leonxlnx_taste-skill.json +86 -60
- package/data/skill-index/Master-cai_Research-Paper-Writing-Skills.json +7 -5
- package/data/skill-index/MiniMax-AI_skills.json +186 -104
- package/data/skill-index/Nutlope_hallmark.json +9 -7
- package/data/skill-index/Paramchoudhary_ResumeSkills.json +140 -96
- package/data/skill-index/ParthJadhav_app-store-screenshots.json +7 -5
- package/data/skill-index/addyosmani_agent-skills.json +572 -257
- package/data/skill-index/affaan-m_ECC.json +54685 -0
- package/data/skill-index/affaan-m_everything-claude-code.json +1903 -1248
- package/data/skill-index/alirezarezvani_claude-skills.json +14453 -8549
- package/data/skill-index/anthropics_skills.json +138 -98
- package/data/skill-index/antithesishq_antithesis-skills.json +173 -149
- package/data/skill-index/antonbabenko_terraform-skill.json +7 -5
- package/data/skill-index/ayghri_i-have-adhd.json +9 -7
- package/data/skill-index/badlogic_pi-skills.json +55 -39
- package/data/skill-index/blader_humanizer.json +18 -16
- package/data/skill-index/briiirussell_cybersecurity-skills.json +212 -343
- package/data/skill-index/bytedance_deer-flow.json +180 -126
- package/data/skill-index/cathrynlavery_diagram-design.json +10 -8
- package/data/skill-index/charlie947_answer-first.json +9 -7
- package/data/skill-index/charlie947_voiceprint.json +9 -7
- package/data/skill-index/cloudai-x_threejs-skills.json +149 -45
- package/data/skill-index/coreyhaines31_marketingskills.json +802 -467
- package/data/skill-index/davidondrej_skills.json +4580 -1075
- package/data/skill-index/emilkowalski_skills.json +353 -52
- package/data/skill-index/entireio_skills.json +185 -101
- package/data/skill-index/garrytan_gstack.json +968 -600
- package/data/skill-index/github_awesome-copilot.json +9624 -7636
- package/data/skill-index/google-labs-code_design.md.json +29 -21
- package/data/skill-index/google_skills.json +7013 -2434
- package/data/skill-index/hardikpandya_stop-slop.json +9 -7
- package/data/skill-index/heygen-com_hyperframes.json +191 -139
- package/data/skill-index/himself65_finance-skills.json +175 -340
- package/data/skill-index/ivan-magda_uikit-expert-skill.json +7 -5
- package/data/skill-index/kemiljk_fluid-design.json +7 -5
- package/data/skill-index/kepano_obsidian-skills.json +34 -24
- package/data/skill-index/luongnv89_asm.json +307 -219
- package/data/skill-index/luongnv89_idd.json +121 -107
- package/data/skill-index/luongnv89_skills.json +1503 -599
- package/data/skill-index/majidmanzarpour_threejs-game-skills.json +2024 -0
- package/data/skill-index/mattpocock_skills.json +235 -161
- package/data/skill-index/multica-ai_andrej-karpathy-skills.json +7 -5
- package/data/skill-index/mvanhorn_last30days-skill.json +16 -20
- package/data/skill-index/nextlevelbuilder_ui-ux-pro-max-skill.json +92 -78
- package/data/skill-index/obra_superpowers.json +95 -67
- package/data/skill-index/oliver-zehentleitner_keep-the-why.json +28 -26
- package/data/skill-index/openai_skills.json +8816 -0
- package/data/skill-index/pbakaus_impeccable.json +20 -18
- package/data/skill-index/romainsimon_paperasse.json +44 -32
- package/data/skill-index/rudrankriyam_app-store-connect-cli-skills.json +319 -119
- package/data/skill-index/santifer_career-ops.json +1009 -14
- package/data/skill-index/sickn33_antigravity-awesome-skills.json +63856 -42252
- package/data/skill-index/slavingia_skills.json +68 -48
- package/data/skill-index/tt-a1i_archify.json +18 -16
- package/data/skill-index/twostraws_Swift-Concurrency-Agent-Skill.json +7 -5
- package/data/skill-index/twostraws_Swift-Testing-Agent-Skill.json +7 -5
- package/data/skill-index/twostraws_SwiftData-Agent-Skill.json +7 -5
- package/data/skill-index/twostraws_SwiftUI-Agent-Skill.json +7 -5
- package/data/skill-index/warpdotdev_oz-skills.json +101 -71
- package/data/skill-index/zarazhangrui_follow-builders.json +7 -5
- package/data/skill-index/zarazhangrui_frontend-slides.json +11 -9
- package/data/skill-index-resources.json +37 -1
- package/dist/agent-skill-manager.js +464 -560
- package/dist/{chunk-ZAOVB3X2.js → chunk-3KGAHUVB.js} +1 -1
- package/dist/chunk-CBDNF2SR.js +166 -0
- package/dist/chunk-KWWFXT5F.js +3 -0
- package/dist/config-JPFUVYBM.js +2 -0
- package/dist/{lock-RVOMV2LT.js → lock-UEL3CMOV.js} +1 -1
- package/dist/{src-SP66WR5V.js → src-ORQ3FXUL.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-54VC5E5G.js +0 -23
- package/dist/chunk-VGQYV246.js +0 -3
- 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
|
|
4
|
-
`)
|
|
5
|
-
`)
|
|
6
|
-
`)
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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
|
-
${
|
|
153
|
-
The directory stays intact; ${
|
|
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
|
-
${
|
|
156
|
-
${
|
|
157
|
-
${
|
|
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
|
-
${
|
|
21
|
+
${i.bold("Targets:")}
|
|
160
22
|
<name> Exact skill name or directory name
|
|
161
|
-
'<glob>*' Glob match (${
|
|
162
|
-
<prefix>: | <prefix>- Prefix match (e.g. ${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
175
|
-
asm disable code-review ${
|
|
176
|
-
asm disable 'workflow*' ${
|
|
177
|
-
asm disable '*-review' ${
|
|
178
|
-
asm disable openspec: ${
|
|
179
|
-
asm disable asc- ${
|
|
180
|
-
asm disable --all ${
|
|
181
|
-
asm disable code-review --tool claude --scope local`)}function
|
|
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 ${
|
|
185
|
-
${
|
|
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
|
-
${
|
|
188
|
-
${
|
|
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
|
-
${
|
|
52
|
+
${i.bold("Targets:")}
|
|
191
53
|
<name> Exact skill name or directory name
|
|
192
|
-
'<glob>*' Glob match (${
|
|
193
|
-
<prefix>: | <prefix>- Prefix match (e.g. ${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
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
|
|
210
|
-
${
|
|
211
|
-
${
|
|
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
|
-
${
|
|
77
|
+
${ws} skills are present, a compact summary is
|
|
216
78
|
automatically prepended above the table.
|
|
217
79
|
|
|
218
|
-
${
|
|
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
|
-
${
|
|
236
|
-
asm list ${
|
|
237
|
-
asm list --flat ${
|
|
238
|
-
asm list --compact ${
|
|
239
|
-
asm list --summary ${
|
|
240
|
-
asm list --group-by tool ${
|
|
241
|
-
asm list --group-by scope ${
|
|
242
|
-
asm list --group-by effort ${
|
|
243
|
-
asm list --limit 20 ${
|
|
244
|
-
asm list -p claude ${
|
|
245
|
-
asm list -s project ${
|
|
246
|
-
asm list --tag cli --tag testing ${
|
|
247
|
-
asm list --sort version ${
|
|
248
|
-
asm list --json ${
|
|
249
|
-
asm list --machine ${
|
|
250
|
-
${
|
|
251
|
-
`))}}import{readdir as
|
|
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
|
-
${
|
|
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
|
-
${
|
|
272
|
-
asm search code ${
|
|
273
|
-
asm search review -p claude ${
|
|
274
|
-
asm search "test" --installed ${
|
|
275
|
-
asm search "test" --available ${
|
|
276
|
-
asm search code --tag cli,testing ${
|
|
277
|
-
asm search openspec --json ${
|
|
278
|
-
asm search openspec --machine ${
|
|
279
|
-
`)),e.flags.flat?console.log(
|
|
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
|
-
${
|
|
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
|
-
${
|
|
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
|
|
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
|
-
${
|
|
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
|
-
${
|
|
306
|
-
asm inspect code-review ${
|
|
307
|
-
asm inspect code-review --json ${
|
|
308
|
-
asm inspect code-review -s global ${
|
|
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
|
|
316
|
-
`)){let n=
|
|
317
|
-
HTTPS: ${
|
|
318
|
-
SSH: ${
|
|
319
|
-
`);for(let
|
|
320
|
-
`;
|
|
321
|
-
`){
|
|
322
|
-
`:m(
|
|
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
|
|
325
|
-
`)}function
|
|
326
|
-
`);if(t.length===0||t[0].trim()!=="---")return{rawFrontmatter:null,body:e};for(let
|
|
327
|
-
`),
|
|
328
|
-
`);return{rawFrontmatter:
|
|
329
|
-
`),body:""}}function
|
|
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
|
|
332
|
-
`),
|
|
333
|
-
`),
|
|
334
|
-
`)})}else
|
|
335
|
-
`),changed:
|
|
336
|
-
`);
|
|
337
|
-
`),
|
|
338
|
-
`);let{rawFrontmatter:
|
|
339
|
-
${
|
|
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:
|
|
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}: ${
|
|
348
|
-
`}function
|
|
349
|
-
`),
|
|
350
|
-
`),n=[`--- a/${
|
|
351
|
-
`)}async function
|
|
352
|
-
`)}function
|
|
353
|
-
`);if(e.applied.length>0){t.push(`${e.dryRun?"Would apply":"Applied"} ${e.applied.length} fix(es):`);for(let
|
|
354
|
-
`)}import{stat as Gr,readdir as
|
|
355
|
-
`)}function
|
|
356
|
-
`)){let[
|
|
357
|
-
`)}function
|
|
358
|
-
`)}function
|
|
359
|
-
`),await
|
|
360
|
-
`),t.update(await
|
|
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
|
|
363
|
-
`)}function
|
|
364
|
-
`)&&!
|
|
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
|
-
${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
391
|
-
asm eval ./my-skill ${
|
|
392
|
-
asm eval ./skills/ ${
|
|
393
|
-
asm eval github:mattpocock/skills:grill-me ${
|
|
394
|
-
asm eval github:mattpocock/skills ${
|
|
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 ${
|
|
397
|
-
asm eval ./my-skill --fix ${
|
|
398
|
-
asm eval ./my-skill --fix --dry-run ${
|
|
399
|
-
asm eval ./my-skill --machine ${
|
|
400
|
-
asm eval-providers list ${
|
|
401
|
-
`))}function
|
|
402
|
-
|
|
403
|
-
Manage evaluation providers registered with the ${
|
|
404
|
-
Providers implement the ${
|
|
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
|
-
${
|
|
269
|
+
${i.bold("Subcommands:")}
|
|
408
270
|
list List every registered (id, version) provider
|
|
409
271
|
|
|
410
|
-
${
|
|
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
|
-
${
|
|
416
|
-
asm eval-providers list ${
|
|
417
|
-
asm eval-providers list --json ${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
448
|
-
asm get code-review ${
|
|
449
|
-
asm get code-review > SKILL.md ${
|
|
450
|
-
asm get github:owner/repo:skills/review ${
|
|
451
|
-
asm get owner/review --audit ${
|
|
452
|
-
asm get code-review --json ${
|
|
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
|
|
456
|
-
`+
|
|
457
|
-
`),{cause:
|
|
458
|
-
`));let
|
|
459
|
-
`)}e.flags.machine?process.stdout.write(
|
|
460
|
-
`):e.flags.json?process.stdout.write(
|
|
461
|
-
`):(
|
|
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
|
|
464
|
-
`);else if(
|
|
465
|
-
`);else process.stderr.write(
|
|
466
|
-
`));process.exitCode=1}finally{
|
|
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
|
-
${
|
|
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
|
-
${
|
|
479
|
-
asm uninstall code-review ${
|
|
480
|
-
asm uninstall code-review -y ${
|
|
481
|
-
asm uninstall code-review -s project ${
|
|
482
|
-
asm uninstall code-review -p claude ${
|
|
483
|
-
${
|
|
484
|
-
Done.`))}import{realpath as
|
|
485
|
-
`)}var
|
|
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
|
|
488
|
-
`)}function
|
|
489
|
-
`)}function
|
|
490
|
-
`)}function
|
|
491
|
-
`)}function
|
|
492
|
-
`);if(
|
|
493
|
-
`)}var
|
|
494
|
-
`);if(t.push(` ${
|
|
495
|
-
`);t.push(
|
|
496
|
-
`)}function
|
|
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
|
-
${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
516
|
-
asm audit ${
|
|
517
|
-
asm audit -y ${
|
|
518
|
-
asm audit --json ${
|
|
519
|
-
asm audit overlap ${
|
|
520
|
-
asm audit overlap --json ${
|
|
521
|
-
asm audit residency ${
|
|
522
|
-
asm audit residency --json ${
|
|
523
|
-
asm audit security code-review ${
|
|
524
|
-
asm audit security github:user/repo ${
|
|
525
|
-
asm audit security --all ${
|
|
526
|
-
asm audit security code-review --json ${
|
|
527
|
-
asm audit security code-review --machine ${
|
|
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
|
-
${
|
|
530
|
-
Auto-removing duplicates...`));let
|
|
531
|
-
${
|
|
532
|
-
Done. Removed ${
|
|
533
|
-
Usage: asm audit security <name|github:owner/repo> [--all]`),process.exit(2))}async function
|
|
534
|
-
`);let
|
|
535
|
-
Summary:`)),
|
|
536
|
-
`);let
|
|
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
|
-
${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
583
|
-
asm install code-review ${
|
|
584
|
-
asm install luongnv89/code-review ${
|
|
585
|
-
asm install code-review --no-cache ${
|
|
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
|
-
${
|
|
588
|
-
asm install ./my-skill ${
|
|
589
|
-
asm install /home/user/skills/my-skill ${
|
|
590
|
-
asm install ~/skills/my-skill ${
|
|
591
|
-
asm install ../other-project/skill ${
|
|
592
|
-
asm install ./skills-dir --all ${
|
|
593
|
-
asm install ./skills-dir --library --all -y ${
|
|
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
|
-
${
|
|
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 ${
|
|
600
|
-
asm install github:user/private-skill -t 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
|
-
${
|
|
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 ${
|
|
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 ${
|
|
498
|
+
asm install github:user/skills ${i.dim("(interactive picker)")}
|
|
608
499
|
|
|
609
|
-
${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
617
|
-
${
|
|
618
|
-
${
|
|
619
|
-
${b} ${
|
|
620
|
-
${
|
|
621
|
-
${
|
|
622
|
-
${
|
|
623
|
-
Select a skill [1-${
|
|
624
|
-
Did you mean: ${
|
|
625
|
-
`);for(let
|
|
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
|
-
${
|
|
628
|
-
`)}`),process.exit(2);return}let
|
|
629
|
-
`),
|
|
630
|
-
${
|
|
631
|
-
Choose one path per skill name or install with --path.`);throw
|
|
632
|
-
${
|
|
633
|
-
${
|
|
634
|
-
${
|
|
635
|
-
${
|
|
636
|
-
${
|
|
637
|
-
Done! Installed "${
|
|
638
|
-
${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
541
|
+
${i.bold("Examples:")}
|
|
651
542
|
asm activate brainstorming -p codex -s project
|
|
652
|
-
asm activate brainstorming -p claude -s global --json`)}function
|
|
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
|
-
${
|
|
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
|
-
${
|
|
553
|
+
${i.bold("Examples:")}
|
|
663
554
|
asm deactivate brainstorming -p codex -s project
|
|
664
|
-
asm deactivate brainstorming -p claude -s global --json`)}async function
|
|
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
|
-
${
|
|
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
|
-
${
|
|
564
|
+
${i.bold("Options:")}
|
|
674
565
|
--json Output as JSON
|
|
675
566
|
-V, --verbose Show debug output
|
|
676
567
|
|
|
677
|
-
${
|
|
678
|
-
asm library list ${
|
|
679
|
-
asm library update brainstorming ${
|
|
680
|
-
asm library update --all --json ${
|
|
681
|
-
`))}function
|
|
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
|
-
${
|
|
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
|
-
${
|
|
582
|
+
${i.bold("Options:")}
|
|
692
583
|
-V, --verbose Show debug output
|
|
693
584
|
|
|
694
|
-
${
|
|
695
|
-
asm config show ${
|
|
696
|
-
asm config edit ${
|
|
697
|
-
asm config reset -y ${
|
|
698
|
-
${
|
|
699
|
-
`)}`);return
|
|
700
|
-
`)}async function
|
|
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
|
-
${
|
|
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
|
-
${
|
|
711
|
-
asm export ${
|
|
712
|
-
asm export -s global ${
|
|
713
|
-
asm export > skills.json ${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
736
|
-
asm import skills.json ${
|
|
737
|
-
asm import skills.json --diff ${
|
|
738
|
-
asm import skills.json --force ${
|
|
739
|
-
asm import skills.json -s global ${
|
|
740
|
-
asm export > backup.json ${
|
|
741
|
-
asm import backup.json ${
|
|
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}
|
|
744
|
-
${
|
|
745
|
-
|
|
746
|
-
|
|
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
|
|
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
|
-
${
|
|
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
|
-
${
|
|
782
|
-
asm init my-skill ${
|
|
783
|
-
asm init my-skill -p claude ${
|
|
784
|
-
asm init my-skill --path ./skills ${
|
|
785
|
-
${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
804
|
-
asm stats ${
|
|
805
|
-
asm stats --tokens ${
|
|
806
|
-
asm stats --tokens --json ${
|
|
807
|
-
asm stats -s global ${
|
|
808
|
-
asm stats --json ${
|
|
809
|
-
asm stats --machine ${
|
|
810
|
-
asm stats repo anthropics/skills ${
|
|
811
|
-
asm stats author luongnv89 ${
|
|
812
|
-
asm stats index ${
|
|
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
|
-
${
|
|
707
|
+
${i.bold("Arguments:")}
|
|
817
708
|
owner/repo Repository identifier (e.g. anthropics/skills)
|
|
818
709
|
|
|
819
|
-
${
|
|
710
|
+
${i.bold("Options:")}
|
|
820
711
|
--json Output as JSON
|
|
821
712
|
--no-color Disable ANSI colors
|
|
822
713
|
|
|
823
|
-
${
|
|
714
|
+
${i.bold("Examples:")}
|
|
824
715
|
asm stats repo anthropics/skills
|
|
825
|
-
asm stats repo luongnv89/asm --json`)}async function
|
|
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
|
-
${
|
|
720
|
+
${i.bold("Arguments:")}
|
|
830
721
|
owner Author/organization name (e.g. luongnv89)
|
|
831
722
|
|
|
832
|
-
${
|
|
723
|
+
${i.bold("Options:")}
|
|
833
724
|
--json Output as JSON
|
|
834
725
|
--no-color Disable ANSI colors
|
|
835
726
|
|
|
836
|
-
${
|
|
727
|
+
${i.bold("Examples:")}
|
|
837
728
|
asm stats author anthropics
|
|
838
|
-
asm stats author luongnv89 --json`)}async function
|
|
839
|
-
`);console.error(
|
|
840
|
-
${
|
|
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
|
-
${
|
|
735
|
+
${i.bold("Options:")}
|
|
845
736
|
--json Output as JSON
|
|
846
737
|
--no-color Disable ANSI colors
|
|
847
738
|
|
|
848
|
-
${
|
|
739
|
+
${i.bold("Examples:")}
|
|
849
740
|
asm stats index
|
|
850
|
-
asm stats index --json`)}async function
|
|
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
|
-
${
|
|
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
|
-
${
|
|
870
|
-
asm link ./my-skill ${
|
|
871
|
-
asm link ./my-skill -p claude ${
|
|
872
|
-
asm link ./my-skill --name alias ${
|
|
873
|
-
asm link ./my-skills-folder ${
|
|
874
|
-
asm link ./skill1 ./skill2 ./skill3 -p claude ${
|
|
875
|
-
${
|
|
876
|
-
${
|
|
877
|
-
Done! Linked ${
|
|
878
|
-
${
|
|
879
|
-
${
|
|
880
|
-
Done! Linked ${
|
|
881
|
-
---`,3);return
|
|
882
|
-
`,"utf-8"),
|
|
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
|
-
${
|
|
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
|
-
${
|
|
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
|
-
${
|
|
904
|
-
asm index ingest github:obra/superpowers ${
|
|
905
|
-
asm index search code review ${
|
|
906
|
-
asm index search marketing --has license ${
|
|
907
|
-
asm index search "" --missing creator ${
|
|
908
|
-
asm index overlap ${
|
|
909
|
-
asm index overlap --threshold 0.6 ${
|
|
910
|
-
asm index list ${
|
|
911
|
-
asm index remove obra/superpowers ${
|
|
912
|
-
`));for(let
|
|
913
|
-
`)}}break}case"list":{let
|
|
914
|
-
`));for(let
|
|
915
|
-
`)),
|
|
916
|
-
`));for(let c of
|
|
917
|
-
`);for(let
|
|
918
|
-
`);for(let
|
|
919
|
-
`));for(let c of
|
|
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
|
|
922
|
-
`,"utf-8"),
|
|
923
|
-
${
|
|
924
|
-
`)}`);return
|
|
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
|
-
${
|
|
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
|
-
${
|
|
940
|
-
-
|
|
941
|
-
-
|
|
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
|
-
${
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
asm bundle
|
|
957
|
-
asm bundle
|
|
958
|
-
asm bundle
|
|
959
|
-
asm bundle
|
|
960
|
-
asm bundle
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
${
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
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,"<").replace(/>/g,">").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
|
|
974
|
-
`)&&(process.stdin.removeListener("data",
|
|
975
|
-
`,
|
|
976
|
-
`),{stdout:
|
|
977
|
-
`).map(
|
|
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
|
|
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
|
-
${
|
|
887
|
+
${i.bold("Arguments:")}
|
|
985
888
|
path Path to skill directory (default: current directory)
|
|
986
889
|
|
|
987
|
-
${
|
|
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
|
-
${
|
|
997
|
-
asm publish ${
|
|
998
|
-
asm publish ./my-skill ${
|
|
999
|
-
asm publish --dry-run ${
|
|
1000
|
-
asm publish --force ${
|
|
1001
|
-
asm publish --json ${
|
|
1002
|
-
asm publish --machine ${
|
|
1003
|
-
`)),console.log(JSON.stringify(
|
|
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
|
-
${
|
|
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
|
-
${
|
|
1014
|
-
asm outdated ${
|
|
1015
|
-
asm outdated --json ${
|
|
1016
|
-
asm outdated --machine ${
|
|
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
|
-
${
|
|
923
|
+
${i.bold("Arguments:")}
|
|
1021
924
|
name Specific skill(s) to update (default: all outdated)
|
|
1022
925
|
|
|
1023
|
-
${
|
|
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
|
-
${
|
|
1031
|
-
asm update ${
|
|
1032
|
-
asm update code-review ${
|
|
1033
|
-
asm update --yes ${
|
|
1034
|
-
asm update --json ${
|
|
1035
|
-
`)[0],
|
|
1036
|
-
`);if(
|
|
1037
|
-
`)}function
|
|
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
|
-
${
|
|
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
|
-
${
|
|
1050
|
-
asm doctor ${
|
|
1051
|
-
asm doctor --json ${
|
|
1052
|
-
asm doctor --machine ${
|
|
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
|
-
${
|
|
959
|
+
${i.bold("Usage:")}
|
|
1057
960
|
asm Launch interactive TUI
|
|
1058
961
|
asm <command> [options] Run a CLI command
|
|
1059
962
|
|
|
1060
|
-
${
|
|
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
|
-
${
|
|
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
|
|
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)})}
|