agent-skill-manager 2.19.0 → 2.20.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 +42 -10
- package/dist/agent-skill-manager.js +179 -172
- package/dist/{chunk-3KGAHUVB.js → chunk-ATTTEI26.js} +1 -1
- package/dist/chunk-HODWB56T.js +3 -0
- package/dist/chunk-ZSFSQQFX.js +176 -0
- package/dist/config-5X2UQBDB.js +2 -0
- package/dist/{lock-UEL3CMOV.js → lock-6JXXQRLX.js} +1 -1
- package/dist/src-W3UM7BUS.js +119 -0
- package/package.json +17 -17
- package/dist/chunk-CBDNF2SR.js +0 -166
- package/dist/chunk-KWWFXT5F.js +0 -3
- package/dist/config-JPFUVYBM.js +0 -2
- package/dist/src-ORQ3FXUL.js +0 -119
|
@@ -1,13 +1,13 @@
|
|
|
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
|
-
`),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
|
|
3
|
+
import{a as se}from"./chunk-ESKBKSXS.js";import{a as Tt,b as lt,c as Ve,d as Oe,e as dt,f as gi,g as hi,h as yi}from"./chunk-ATTTEI26.js";import{$ as Nr,A as Yn,B as Er,C as Zn,D as Xn,E as Qn,F as Ir,G as ei,H as Ts,I as ti,J as Cr,K as ri,L as si,M as oi,N as ni,O as ii,P as j,R as V,S as ui,T as Tr,U as pi,V as mi,W as Fs,X as Ne,Y as ct,Z as fi,_ as js,a as Le,aa as bi,b as J,ba as wi,c as Ae,ca as ki,d as ot,da as Or,e as i,ea as vi,f as qn,fa as Nt,g as Pr,ga as _s,ha as Si,ia as Dr,j as Wn,ja as $i,k as K,l as ae,la as xi,m as Cs,ma as Pi,n as nt,na as Ri,o as It,p as Jn,q as Y,r as Ct,s as Lt,t as Kn,u as it,v as Te,w as Rr,x as Ls,y as As,z as zn}from"./chunk-ZSFSQQFX.js";import{a as ai,b as P,c as Lr,d as Ar,e as At,f as li,g as Ns,h as Os,i as at,k as Pe,l as Ge,m as ci,n as Ds,o as Ms,r as ee,s as D,t as di}from"./chunk-HODWB56T.js";import{d as Hn}from"./chunk-RSVWCEZR.js";import{access as zd,realpath as Yd,stat as Zd}from"fs/promises";import{constants as Xd}from"fs";import{delimiter as Qd,resolve as eu,sep as tu}from"path";var ru="asm";function su(e){if(!e)return[];let t=new Set,r=[];for(let s of e.split(Qd)){let o=s.trim();if(!o)continue;let n=o.endsWith(tu)?o.slice(0,-1):o;t.has(n)||(t.add(n),r.push(n))}return r}async function ou(e){try{if(!(await Zd(e)).isFile())return!1}catch{return!1}try{return await zd(e,Xd.X_OK),!0}catch{return!1}}async function nu(e){try{return await Yd(e)}catch{return e}}async function iu(e=process.env.PATH){let t=new Set,r=[];for(let s of su(e)){let o=eu(s,ru);if(!await ou(o))continue;let n=await nu(o);t.has(n)||(t.add(n),r.push({path:o,realPath:n}))}return r}async function Mr(e=process.env.PATH){let t=await iu(e);if(t.length===0)return{resolved:null,shadowed:[]};let[r,...s]=t;return{resolved:r,shadowed:s}}var Ii=Hn(Wn(),1);import{readFile as au}from"fs/promises";import{join as lu}from"path";function A(e){let t=e?.message;return t==null?String(e):String(t)}var Ei=500;function cu(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 du(e){let t=e.split(`
|
|
5
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
|
|
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
|
|
8
|
-
`,"utf-8")}function
|
|
9
|
-
`,"utf-8")}function
|
|
10
|
-
`);return console.log=r,console.info=r,()=>{console.log=e,console.info=t}}function
|
|
6
|
+
`);return null}function uu(e){let t=du(e);if(t===null)return null;try{return(0,Ii.parse)(t),null}catch(r){return A(r)||"invalid YAML"}}async function Ci(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 au(lu(e.path,"SKILL.md"),"utf-8");cu(s)||t.push({category:"empty-body",message:"SKILL.md contains only frontmatter with no body content"});let o=uu(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>Ei&&t.push({category:"high-file-count",message:`Skill has ${r} files (threshold: ${Ei})`}),t}function pu(e){switch(e){case"dangerous":return 3;case"warning":return 2;case"caution":return 1;default:return 0}}function Fr(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+pu(r.verdict),0)}}function w(e){console.error(i.red(`Error: ${e}`))}async function Ot(e){await Promise.all(e.map(async t=>{t.warnings=await Ci(t)}))}function H(){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 ut(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 mu,writeFile as fu,mkdir as gu,rename as Ai,copyFile as hu,access as yu,realpath as bu}from"node:fs/promises";import{join as Ti,dirname as wu}from"node:path";function Li(){return{version:1,disabled:{}}}async function Dt(e){let t=e??Ns(),r;try{r=await mu(t,"utf-8")}catch(s){if(s?.code==="ENOENT")return P("skill-state: file not found, returning empty state"),Li();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 hu(t,s)}catch{}return console.error(`Warning: skill-state.json was corrupted. Backup saved to ${s}. Starting fresh.`),Li()}}async function Us(e,t){let r=t??Ns();await gu(wu(r),{recursive:!0}),await fu(r,JSON.stringify(e,null,2)+`
|
|
8
|
+
`,"utf-8")}function Ni(e,t,r,s){let o=e.disabled[t]??={},n=o[r]??={};n[s]=!0}function Oi(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 ku(e){return e.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}function vu(e){if(e==="*"||e==="all")return{kind:"all",test:()=>!0};if(e.includes("*")){let t=new RegExp("^"+ku(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 Mt(e,t){let r=vu(t);return e.filter(s=>r.test(s.name)||r.test(s.dirName))}function Di(e){return Ti(e,"SKILL.md")}function _r(e){return Ti(e,"SKILL.md.disabled")}async function jr(e){try{return await yu(e),!0}catch{return!1}}async function Mi(e){try{return await bu(e)}catch{return e}}async function Fi(e){let t=await Mi(e),r=Di(t),s=_r(t);return!await jr(r)&&await jr(s)?!1:(await Ai(r,s),!0)}async function ji(e){let t=await Mi(e),r=Di(t),s=_r(t);return!await jr(s)&&await jr(r)?!1:(await Ai(s,r),!0)}import{copyFile as Su,mkdir as $u,readFile as xu,writeFile as Pu}from"node:fs/promises";import{dirname as Ru}from"node:path";function Bs(){return{version:1,skills:{}}}function Eu(e){if(!e||typeof e!="object")return{added:[],removed:[]};let t=e,r=Y(Array.isArray(t.removed)?t.removed.filter(n=>typeof n=="string"):[]),s=new Set(r);return{added:Y(Array.isArray(t.added)?t.added.filter(n=>typeof n=="string"):[]).filter(n=>!s.has(n)),removed:r}}async function De(e){let t=e??Os(),r;try{r=await xu(t,"utf-8")}catch(s){if(s?.code==="ENOENT")return Bs();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=Bs();for(let[n,a]of Object.entries(s.skills)){let l=Eu(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 Su(t,s)}catch{}return Bs()}}async function _i(e,t){let r=t??Os();await $u(Ru(r),{recursive:!0}),await Pu(r,`${JSON.stringify(e,null,2)}
|
|
9
|
+
`,"utf-8")}function Gs(e){return e.realPath}function pt(e){let t=e.flatMap(s=>s.split(",")),r=t.filter(s=>Jn(s)===null);return{tags:Y(t),invalid:r}}function mt(e,t){let r=new Set(Y(e||[]));return Y(t).every(s=>r.has(s))}function Ft(e,t){let r=new Set(Y(t?.removed||[]));return Y([...Y(e||[]).filter(s=>!r.has(s)),...Y(t?.added||[]).filter(s=>!r.has(s))])}function ft(e,t){for(let r of e)r.tags=Ft(r.tags,t.skills[Gs(r)])}function Ui(e,t){let r=e.skills[t];r&&r.added.length===0&&r.removed.length===0&&delete e.skills[t]}function Bi(e,t,r,s){let o=new Set(Y(r||[])),n=e.skills[t]??={added:[],removed:[]},a=new Set(Y(n.added)),l=new Set(Y(n.removed));for(let c of Y(s))l.delete(c),o.has(c)||a.add(c);return n.added=[...a],n.removed=[...l],Ui(e,t),Ft(r,e.skills[t])}function Gi(e,t,r,s){let o=new Set(Y(r||[])),n=e.skills[t]??={added:[],removed:[]},a=new Set(Y(n.added)),l=new Set(Y(n.removed));for(let c of Y(s))a.delete(c),o.has(c)&&l.add(c);return n.added=[...a],n.removed=[...l],Ui(e,t),Ft(r,e.skills[t])}var q={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 Vi(e){return{timestamp:new Date().toISOString(),asm_version:mi,duration_ms:Math.round(performance.now()-e)}}function B(e,t,r){let s={version:1,command:e,status:"ok",data:t,meta:Vi(r)},o=process.stdout.isTTY?2:0;return JSON.stringify(s,null,o)}function W(e,t,r,s,o){let n={version:1,command:e,status:"error",error:{code:t,message:r,...o!==void 0?{details:o}:{}},meta:Vi(s)},a=process.stdout.isTTY?2:0;return JSON.stringify(n,null,a)}import{readFile as Iu,realpath as Cu}from"fs/promises";import{existsSync as Lu}from"fs";import{join as Au}from"path";function Tu(){console.log(`${i.bold("Usage:")} asm disable <target> [options]
|
|
11
11
|
asm disable --all [options]
|
|
12
12
|
|
|
13
13
|
Disable skills without uninstalling them. Disabling renames a skill's
|
|
@@ -40,7 +40,7 @@ ${i.bold("Examples:")}
|
|
|
40
40
|
asm disable openspec: ${i.dim("# prefix (colon)")}
|
|
41
41
|
asm disable asc- ${i.dim("# prefix (hyphen)")}
|
|
42
42
|
asm disable --all ${i.dim("# everything")}
|
|
43
|
-
asm disable code-review --tool claude --scope local`)}function
|
|
43
|
+
asm disable code-review --tool claude --scope local`)}function Nu(){console.log(`${i.bold("Usage:")} asm enable <target> [options]
|
|
44
44
|
asm enable --all [options]
|
|
45
45
|
|
|
46
46
|
Re-enable skills previously disabled with ${i.bold("asm disable")}. Enabling renames
|
|
@@ -68,13 +68,13 @@ ${i.bold("Examples:")}
|
|
|
68
68
|
asm enable code-review
|
|
69
69
|
asm enable '*-review'
|
|
70
70
|
asm enable openspec:
|
|
71
|
-
asm enable --all`)}async function
|
|
72
|
-
${i.bold("Proceed?")} [y/N] `);let f=await
|
|
73
|
-
${i.bold("Proceed?")} [y/N] `);let f=await
|
|
71
|
+
asm enable --all`)}async function Vs(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=ee(m),h=Au(g,l),y=_r(h);if(!Lu(y))continue;let b={};try{b=K(await Iu(y,"utf-8"))}catch{}let $=h;try{$=await Cu(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:It(b),modelInvocable:Ct(b),userInvocable:Lt(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 Hi(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 qi(e){if(e.flags.help){Tu();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 D(),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:Mt(n,t);if(a.length===0){let p=t?` for '${t}'`:"";console.log(i.dim(`No matching active skills${p}.`));return}let l=ut(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 H();if(f.toLowerCase()!=="y"&&f.toLowerCase()!=="yes"){console.log("Aborted.");return}}}let d=await Dt(),u=[];try{for(let p of l){await Fi(p.representative.path);for(let f of p.siblings)Ni(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 Us(d)}Hi(e,u)}async function Wi(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 D(),s=e.flags.provider,o=await Dt(),n=await Vs(r,o,e.flags.scope),a=s?n.filter(p=>p.provider===s):n,l=e.flags.all?a:Mt(a,t);if(l.length===0){let p=t?` for '${t}'`:"";console.log(i.dim(`No matching disabled skills${p}.`));return}let c=ut(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 H();if(f.toLowerCase()!=="y"&&f.toLowerCase()!=="yes"){console.log("Aborted.");return}}}let u=[];try{for(let p of c){await ji(p.representative.path);for(let f of p.siblings)Oi(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 Us(o)}Hi(e,u)}function Ou(){console.log(`${i.bold("Usage:")} asm list [options]
|
|
74
74
|
|
|
75
75
|
List all discovered skills. By default, skills installed across multiple
|
|
76
76
|
tools are grouped into a single row with tool badges. When more than
|
|
77
|
-
${
|
|
77
|
+
${Ls} skills are present, a compact summary is
|
|
78
78
|
automatically prepended above the table.
|
|
79
79
|
|
|
80
80
|
${i.bold("Options:")}
|
|
@@ -108,9 +108,9 @@ ${i.bold("Examples:")}
|
|
|
108
108
|
asm list --tag cli --tag testing ${i.dim("Require both tags")}
|
|
109
109
|
asm list --sort version ${i.dim("Sort by version")}
|
|
110
110
|
asm list --json ${i.dim("Output as JSON")}
|
|
111
|
-
asm list --machine ${i.dim("Machine-readable v1 envelope output")}`)}async function
|
|
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(
|
|
113
|
-
`))}}import{readdir as
|
|
111
|
+
asm list --machine ${i.dim("Machine-readable v1 envelope output")}`)}async function Ji(e){if(e.flags.help){Ou();return}let t=pt(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 D(),o=await V(s,e.flags.scope),n=await Dt(),a=new Set(o.map(u=>`${u.dirName}||${u.provider}||${u.scope}`)),l=await Vs(s,n,e.flags.scope,e.flags.provider,a);o=[...o,...l];let c=await De();ft(o,c),t.tags.length>0&&(o=o.filter(u=>mt(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=>it(u,{modelInvocable:e.flags.modelInvocable,userInvocable:e.flags.userInvocable}))),await Ot(o);let d=Tr(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=Rr(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(As(d));else if(e.flags.groupBy){let{skills:u,hint:p}=Er(d,e.flags.limit);console.log(Yn(u,e.flags.groupBy)),p&&console.log(p)}else if(e.flags.compact){let{skills:u,hint:p}=Er(d,e.flags.limit);console.log(zn(u)),p&&console.log(p)}else{let u=[];d.length>Ls&&(u.push(As(d,{showHint:!1})),u.push(""));let{skills:p,hint:f}=Er(d,e.flags.limit);u.push(Zn(p)),f&&u.push(f),console.log(u.join(`
|
|
113
|
+
`))}}import{readdir as Xi,readFile as Qi}from"fs/promises";import{join as ea}from"path";var jt=null,Ur,ta=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 Du=10,Mu=5,Fu=3,ju=1;function _u(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+=Du),o.has(a)&&(n+=Fu),t.name.toLowerCase().includes(a)&&(n+=Mu),t.description.toLowerCase().includes(a)&&(n+=ju);return n}async function Ki(e){let t=new Map,r;try{r=await Xi(e)}catch{return t}for(let s of r){if(!s.endsWith(".json"))continue;let o=ea(e,s);try{ta++;let n=await Qi(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)?Y(c.tags.filter(d=>typeof d=="string")):[]}t.set(`${a.owner}/${a.repo}`,a)}catch{}}return t}async function Se(){if(jt!==null)return jt;let e=await Ki(Ms()),t=await Ki(at()),r=new Map(e);for(let[s,o]of t)r.set(s,o);return jt=Array.from(r.values()),Ur=jt.reduce((s,o)=>s+o.skillCount,0),jt}async function Uu(e){try{ta++;let r=(await Qi(e,"utf-8")).match(/"skillCount"\s*:\s*(\d+)/);return r?Number(r[1]):null}catch{return null}}async function zi(e){let t=0,r;try{r=await Xi(e)}catch{return t}for(let s of r){if(!s.endsWith(".json"))continue;let o=await Uu(ea(e,s));o!==null&&(t+=o)}return t}async function ra(){if(Ur!==void 0)return Ur;let e=await zi(Ms()),t=await zi(at()),r=e+t;return Ur=r,r}var Bu=["license","creator","version"];function Yi(e){return Bu.includes(e)}function Zi(e,t){return e[t]||""}function Gu(e,t){if(!it(e,t))return!1;if(t.has){for(let r of t.has)if(Yi(r)&&!Zi(e,r))return!1}if(t.missing){for(let r of t.missing)if(Yi(r)&&Zi(e,r))return!1}if(t.tags&&t.tags.length>0){let r=Y(t.tags);if(r.length===0||!mt(e.tags,r))return!1}return!0}function sa(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 _t(e,t=20,r){let s=await Se(),o=[],n=!e&&r;for(let a of s)for(let l of a.skills){if(r&&!Gu(l,r))continue;let c=n?1:_u(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 Hs(){let e=await Se(),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 oa(e,t){let r=e.trim().toLowerCase();if(!r)return{status:"none"};let o=(t??await Hs()).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 Vu(){console.log(`${i.bold("Usage:")} asm search <query> [options]
|
|
114
114
|
|
|
115
115
|
Search both installed skills and the skill index. Results show installation
|
|
116
116
|
status and include copy-paste install commands for available skills.
|
|
@@ -137,8 +137,8 @@ ${i.bold("Examples:")}
|
|
|
137
137
|
asm search "test" --available ${i.dim("Search available skills only")}
|
|
138
138
|
asm search code --tag cli,testing ${i.dim("Require both tags")}
|
|
139
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
|
|
141
|
-
`)),e.flags.flat?console.log(
|
|
140
|
+
asm search openspec --machine ${i.dim("Machine-readable v1 envelope output")}`)}async function na(e){if(e.flags.help){Vu();return}let t=e.flags.machine?le():void 0,r=performance.now(),s=e.subcommand;s||(e.flags.machine&&(t?.(),console.log(W("search",q.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=pt(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 D(),f=await V(p,e.flags.scope);ft(f,await De()),o.tags.length>0&&(f=f.filter(g=>mt(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=>it(g,{modelInvocable:e.flags.modelInvocable,userInvocable:e.flags.userInvocable})));let m=ui(f,s);l=Tr(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 _t(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(Rr(l)):console.log(Xn(l,s))),u){d&&console.error("");let p=Qn(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:Kn(f.skill.modelInvocable,f.skill.userInvocable)})),s);console.error(p)}}function Hu(){console.log(`${i.bold("Usage:")} asm tag add <skill> <tag> [tag...]
|
|
142
142
|
asm tag remove <skill> <tag> [tag...]
|
|
143
143
|
|
|
144
144
|
Edit local tags for installed skills without changing their SKILL.md files.
|
|
@@ -153,7 +153,7 @@ ${i.bold("Options:")}
|
|
|
153
153
|
${i.bold("Examples:")}
|
|
154
154
|
asm tag add code-review testing cli
|
|
155
155
|
asm tag add code-review testing,automation
|
|
156
|
-
asm tag remove code-review automation`)}async function
|
|
156
|
+
asm tag remove code-review automation`)}async function ia(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=pt(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 D(),a=await V(n,e.flags.scope);e.flags.provider&&(a=a.filter(u=>u.provider===e.flags.provider));let l=Mt(a,r);if(l.length===0){w(`Skill not found: "${r}".`),process.exitCode=1;return}let c=await De(),d=[];for(let u of ut(l,a)){let p=u.representative,f=Gs(p),m=Ft(p.tags,c.skills[f]),g=t==="add"?Bi(c,f,p.tags,s.tags):Gi(c,f,p.tags,s.tags),h=t==="add"?g.filter(y=>!m.includes(y)):m.filter(y=>!g.includes(y));d.push({name:p.name,path:p.realPath,tags:g,applied:h,changed:JSON.stringify(m)!==JSON.stringify(g)})}await _i(c),e.flags.machine?console.log(B("tag",d,o)):e.flags.json?console.log(j(d)):console.log(ei(t,d))}function qu(){console.log(`${i.bold("Usage:")} asm inspect <skill-name> [options]
|
|
157
157
|
|
|
158
158
|
Show detailed information for a skill. The <skill-name> is the directory name.
|
|
159
159
|
Shows version, description, file count, and all provider installations.
|
|
@@ -167,63 +167,66 @@ ${i.bold("Options:")}
|
|
|
167
167
|
${i.bold("Examples:")}
|
|
168
168
|
asm inspect code-review ${i.dim("Show details for code-review")}
|
|
169
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
|
|
170
|
+
asm inspect code-review -s global ${i.dim("Global installations only")}`)}async function aa(e){if(e.flags.help){qu();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 D(),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 Ot(o),ft(o,await De()),e.flags.json?console.log(j(o.length===1?o[0]:o)):console.log(await pi(o))}var gt=class extends Error{candidates;constructor(t,r){super(t),this.name="AmbiguousGetError",this.candidates=r}};import{readFile as ys}from"fs/promises";import{randomUUID as vp}from"crypto";import{readdir as Sp,realpath as $p}from"fs/promises";import{join as xp}from"path";import{randomUUID as Sa}from"crypto";import{access as pp,cp as mp,lstat as Vr,mkdir as fp,readFile as Xs,readdir as gp,realpath as va,rename as hp,rm as Hr,rmdir as yp}from"fs/promises";import{basename as Qs,dirname as $a,isAbsolute as bp,join as Ee,relative as wp,resolve as Jt}from"path";import{createHash as Wu,randomUUID as Ju}from"crypto";import{execFile as Ku}from"child_process";import{access as zu,lstat as Me,mkdir as da,readFile as Js,readdir as ua,realpath as Ut,rm as qs}from"fs/promises";import{basename as Yu,dirname as pa,isAbsolute as Zu,join as je,relative as ma,resolve as Ws}from"path";import{promisify as Xu}from"util";var Qu=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,ep=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,tp=100,rp=10*6e4,sp=Xu(Ku);function He(e){if(!Qu.test(e))throw new Error("Invalid session identity. Use 1-128 letters, digits, dots, underscores, colons, or hyphens.");return e}function op(e){return Ws(e.rootDir??ci())}function fa(e){return Wu("sha256").update(e).digest("hex")}function ga(e){return fa(He(e))}function Ks(e){return fa(e.trim())}function Re(e,t){return je(e,"sessions",`${ga(t)}.json`)}function Vt(e,t){return je(e,"artifacts",ga(t))}function zs(e,t){return je(e,`.asm-owner-${t}.json`)}function np(e){return`${e}.lock`}function ip(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||!ep.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 ap(e){try{return process.kill(e,0),"alive"}catch(t){return t?.code==="ESRCH"?"dead":"unknown"}}async function lp(e,t,r){try{let{stdout:s}=await sp(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 cp(e,t,r,s){if(!Number.isSafeInteger(e)||e<=0||t<=0)return null;try{if(r==="linux"){let n=await Js(`/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 Bt(e){return new Error(`Timed out waiting for dependency lease lock: ${e}`)}async function ha(e,t,r,s){let o=t-Date.now();if(o<=0)throw Bt(r);let n=s.lockProcessStartIdentity,a=n?n(e,o):cp(e,o,s.lockPlatform??process.platform,s.lockProcessIdentityCommand??lp),l;try{return await Promise.race([a,new Promise((c,d)=>{l=setTimeout(()=>d(Bt(r)),o)})])}finally{l&&clearTimeout(l)}}async function la(e,t){await Ve(e,JSON.stringify(t,null,2)+`
|
|
171
|
+
`)}async function ca(e,t,r,s){let o=[],n=!1;for(let a of(await ua(e)).filter(l=>l.endsWith(".json")).sort()){if(Date.now()>=r)throw Bt(e);let l=Yu(a,".json"),c=je(e,a),d;try{let m=await Me(c);if(m.isSymbolicLink()||!m.isFile()){n=!0;continue}d=ip(await Js(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??ap)(d.pid)==="dead"){await qs(c,{force:!0});continue}let p=await ha(d.pid,r,e,s);if(d.processStartIdentity!==null&&p!==null&&d.processStartIdentity!==p){await qs(c,{force:!0});continue}o.push(d)}return{candidates:o,invalidOwner:n}}async function dp(e,t,r,s){let o=np(t);await Gt(e,pa(t)),await up(e,t),await Gt(e,o);let n=Date.now(),a=s.lockTimeoutMs??rp,l=s.lockRetryMs??tp,c=n+a,d=Ju(),u=je(o,`${d}.json`),p={version:1,pid:process.pid,processStartIdentity:await ha(process.pid,c,o,s),token:d,acquiredAt:new Date().toISOString(),ticket:null};await la(u,p);try{for(;p.ticket===null;){let{candidates:f,invalidOwner:m}=await ca(o,d,c,s);if(!m){p.ticket=Math.max(0,...f.map(g=>g.ticket??0))+1,await la(u,p);break}if(Date.now()>=c)throw Bt(o);await new Promise(g=>setTimeout(g,Math.min(l,c-Date.now())))}for(;;){let{candidates:f,invalidOwner:m}=await ca(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 Bt(o);await new Promise(h=>setTimeout(h,Math.min(l,c-Date.now())))}return await r()}finally{await qs(u,{force:!0})}}function Ht(e,t,r,s){return lt(t,()=>dp(e,t,r,s))}function Fe(e,t){let r=ma(Ws(e),Ws(t));return r===""||!!r&&!r.startsWith("..")&&!Zu(r)}async function qt(e,t){let r=op(e);try{t&&await da(r,{recursive:!0});let s=await Ut(r),o=await Me(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 Gt(e,t){if(!Fe(e,t))throw new Error(`Managed dependency path escapes lease root: ${t}`);let r=e,s=ma(e,t).split(/[\\/]+/).filter(Boolean);for(let o of s){r=je(r,o);try{let a=await Me(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 da(r)}catch(c){if(c?.code!=="EEXIST")throw c}let l=await Me(r);if(l.isSymbolicLink()||!l.isDirectory())throw new Error(`Refusing symlink or non-directory in managed dependency path: ${r}`,{cause:a})}let n=await Ut(r);if(!Fe(e,n))throw new Error(`Managed dependency directory resolves outside lease root: ${r}`)}}async function up(e,t){if(!Fe(e,t))throw new Error(`Managed dependency file escapes lease root: ${t}`);let r=await Ut(pa(t));if(!Fe(e,r))throw new Error(`Managed dependency file parent resolves outside lease root: ${t}`);try{let s=await Me(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 Wt(e,t){let r=await Me(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 ua(e))t&&s===".git"||await Wt(je(e,s),t)}async function ya(e){let t=await Me(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error(`Temporary dependency source must be a real directory: ${e}`);let r=await Ut(e),s=je(e,"SKILL.md"),o=await Me(s);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Temporary dependency SKILL.md must be a real file: ${s}`);let n=await Ut(s);if(!Fe(r,n))throw new Error(`Temporary dependency SKILL.md resolves outside its source: ${s}`);return await Wt(r,!0),r}function ba(e){return e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+/,"").slice(0,64)||"skill"}function wa(e,t){return{version:1,sessionId:e,createdAt:t,updatedAt:t,acquisitions:{}}}function Br(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 Gr(e,t){try{return Br(await Js(Re(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 qe(e,t,r){let s=Re(e,t.sessionId),o=JSON.stringify(t,null,2)+`
|
|
172
|
+
`;await(r.writeState??Ve)(s,o)}async function Ys(e){if(!e||e.status!=="ready")return!1;try{return await zu(e.skillMdPath),!0}catch{return!1}}async function ka(e,t,r){He(t);let s=r.trim();if(!s)throw new Error("Dependency reference cannot be empty.");let n=(await Gr(e,t))?.acquisitions[Ks(s)];return await Ys(n)?{...n,sessionId:t,reused:!0}:null}async function eo(e,t,r={}){let s=He(e),o=await qt(r,!0);return Ht(o,Re(o,s),()=>t({find:n=>ka(o,s,n),acquire:n=>{if(He(n.sessionId)!==s)throw new Error("Dependency acquisition session does not match the locked session.");return kp(n,o,r)}}),r)}async function xa(e,t={}){return eo(e.sessionId,r=>r.acquire(e),t)}async function kp(e,t,r){let s=He(e.sessionId),o=e.request.trim();if(!o)throw new Error("Dependency reference cannot be empty.");let n=e.temporary?await ya(e.sourceDir):null;e.temporary||await pp(Ee(e.sourceDir,"SKILL.md"));let a=Re(t,s),l=new Date().toISOString(),c=Ks(o),d;if(e.temporary){let m=Sa(),g=Ee(Vt(t,s),`${ba(e.name)}-${c.slice(0,12)}-${m.slice(0,8)}`);d={request:o,name:e.name,path:g,skillMdPath:Ee(g,"SKILL.md"),tier:e.tier,source:e.source,commit:e.commit,status:"pending",owned:!0,artifactId:m,acquiredAt:l}}else{let m=await va(e.sourceDir);d={request:o,name:e.name,path:m,skillMdPath:Ee(m,"SKILL.md"),tier:e.tier,source:e.source,commit:e.commit,status:"ready",owned:!1,artifactId:null,acquiredAt:l}}let u=await Gr(t,s),p=u?.acquisitions[c];if(await Ys(p))return{...p,sessionId:s,reused:!0};p?.owned&&await Zs(t,s,p,r);let f=u??wa(s,l);if(f.updatedAt=l,f.acquisitions[c]=d,!d.owned)return await qe(t,f,r),{...d,sessionId:s,reused:!1};try{await qe(t,f,r)}catch(m){if(!(m instanceof Tt))throw m}try{let m=Vt(t,s);await Gt(t,m);let g=await va($a(d.path));if(!Fe(t,g))throw new Error(`Dependency artifact parent resolves outside lease root: ${d.path}`);await fp(d.path);let h=await Vr(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 Ve(zs(d.path,d.artifactId),JSON.stringify(y,null,2)+`
|
|
173
|
+
`),await mp(n,d.path,{recursive:!0,filter:b=>b===n||Qs(b)!==".git"}),await Wt(d.path,!1),d.status="ready",f.updatedAt=new Date().toISOString(),f.acquisitions[c]=d;try{await qe(t,f,r)}catch(b){if(!(b instanceof Tt))throw b}return{...d,sessionId:s,reused:!1}}catch(m){try{await Zs(t,s,d,r),delete f.acquisitions[c],Object.keys(f.acquisitions).length===0?await Hr(a,{force:!0}):(f.updatedAt=new Date().toISOString(),await qe(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 Zs(e,t,r,s){let o=Vt(e,t);if(!Fe(o,r.path))throw new Error(`Refusing to remove artifact outside its lease: ${r.path}`);if(Jt($a(r.path))!==Jt(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 Gt(e,o);try{if((await Vr(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=Ee(o,`.${Qs(r.path)}.quarantine-${Sa()}`);try{await(s.renameArtifact??hp)(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 Vr(n);if(a.isSymbolicLink()||!a.isDirectory())throw new Error(`Preserved quarantined replacement that is not an owned directory: ${n}`);let l=zs(n,r.artifactId),c=await Vr(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 Xs(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||Jt(u.path??"")!==Jt(r.path))throw new Error(`Preserved quarantined artifact with mismatched ownership: ${n}`);return await Wt(n,!1),await Hr(n,{recursive:!0}),"removed"}async function qr(e,t={}){He(e);let r=await qt(t,!1);if(!r)return{sessionId:e,alreadyReleased:!0,removed:[],preserved:[],missing:[],errors:[]};let s=Re(r,e);return Ht(r,s,()=>to(r,e,t),t)}async function Pa(e,t={}){if(!bp(e)||Jt(e)!==e)return null;let r=await qt(t,!1);if(!r)return null;let s=wp(r,e).split(/[\\/]+/);if(s.length!==3||s[0]!=="artifacts"||!/^[a-f0-9]{64}$/.test(s[1])||Ee(r,...s)!==e)return null;let o=Ee(r,"sessions",`${s[1]}.json`);return Ht(r,o,async()=>{let n;try{n=await Xs(o,"utf-8")}catch(c){if(c?.code==="ENOENT")return null;throw c}let a=Br(n);if(Re(r,a.sessionId)!==o)throw new Error("Dependency lease filename does not match session.");let l=Object.values(a.acquisitions);if(!l.some(c=>c?.path===e))return null;if(l.length!==1||l[0].owned!==!0||!l[0].artifactId)throw new Error("Refusing path cleanup without a single owned acquisition.");return to(r,a.sessionId,t)},t)}async function to(e,t,r){let s=Re(e,t),o=await Gr(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 Zs(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=Vt(e,t);try{await yp(l),await Hr(s,{force:!0})}catch(c){c?.code==="ENOENT"?await Hr(s,{force:!0}):(n.errors.push(`Preserved unknown content in dependency lease artifacts directory: ${l}`),o.updatedAt=new Date().toISOString(),o.acquisitions={},await qe(e,o,r))}}else o.updatedAt=new Date().toISOString(),o.acquisitions=a,await qe(e,o,r);return n}async function Ra(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 qt(r,!1);if(!o)return s;let n;try{n=await gp(Ee(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=Ee(o,"sessions",a);try{await Ht(o,l,async()=>{let c;try{c=await Xs(l,"utf-8")}catch(f){if(f?.code==="ENOENT")return;throw f}let d=Br(c);if(Re(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 to(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:Qs(a,".json"),message:c instanceof Error?c.message:String(c)})}}return s}async function Ea(e,t=""){let r=[];for(let s of await Sp(e,{withFileTypes:!0})){if(s.name===".git"||/^\.asm-owner-.*\.json$/.test(s.name))continue;let o=`${t}${s.name}`;if(s.isDirectory())r.push(...await Ea(xp(e,s.name),`${o}/`));else if(s.isFile())r.push(o);else throw new Error(`Borrow contains an unsupported entry: ${o}`)}return r.sort()}async function Ia(e,t,r){let s=vp(),o={rootDir:Ds()},n=await xa({sessionId:s,request:e,name:r.name,sourceDir:await $p(t),tier:r.tier,source:r.source,commit:r.commit,temporary:!0},o);try{return{name:r.name,description:r.description,dependencies:r.dependencies,tier:r.tier,source:r.source,commit:r.commit,tokenCount:r.tokenCount,security:r.security,path:n.path,files:await Ea(n.path),cleanup:{command:"asm",args:["cleanup",n.path]}}}catch(a){let l=await qr(s,o);throw l.errors.length?new Error(`Borrow failed; ownership-safe cleanup refused: ${l.errors.join("; ")}`,{cause:a}):a}}async function Ca(e){try{let t=await Pa(e,{rootDir:Ds()});return{path:e,status:t?t.errors.length?"refused":t.removed.length?"removed":"missing":"not-found",errors:t?.errors??[]}}catch(t){return{path:e,status:"refused",errors:[t instanceof Error?t.message:String(t)]}}}import{execFile as Pp}from"child_process";import{promisify as Rp}from"util";import{mkdtemp as La,readdir as Ep,readFile as Jr,rm as Kr,cp as Ip,access as so,stat as Oa,lstat as Cp,mkdir as Lp}from"fs/promises";import{join as we,resolve as Kt,relative as Ap,basename as Da,sep as Tp}from"path";import{homedir as Aa}from"os";import{tmpdir as Ta}from"os";var ht=Rp(Pp),Np=/^[a-zA-Z0-9_-]+$/,Op=/^[a-zA-Z0-9._-]+$/,Dp=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/,Na=128,Mp=/^https?:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\/tree\/(.+))?\/?$/;function We(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 Yt(e){if(!e.includes("/")&&!e.includes("\\"))return!1;try{return(await Oa(Kt(e))).isDirectory()}catch{return!1}}function Ma(e){let t;e==="~"?t=Aa():e.startsWith("~/")||e.startsWith("~\\")?t=Kt(Aa(),e.slice(2)):t=Kt(e);let r=Da(t);return P(`install: parsed local source -> path=${t}`),{owner:"local",repo:r,ref:null,subpath:null,cloneUrl:"",sshCloneUrl:"",isLocal:!0,localPath:t}}function ne(e){if(We(e))return Ma(e);let t=Mp.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}"
|
|
171
174
|
Supported formats:
|
|
172
175
|
github:owner/repo[#ref]
|
|
173
176
|
github:owner/repo#ref:path
|
|
174
177
|
https://github.com/owner/repo
|
|
175
178
|
https://github.com/owner/repo/tree/branch/path/to/skill
|
|
176
179
|
/path/to/local/skill
|
|
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(!
|
|
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>
|
|
179
|
-
HTTPS: ${
|
|
180
|
-
SSH: ${
|
|
181
|
-
`);for(let a=0;a<n.length;a++)for(let{category:l,pattern:c}of
|
|
180
|
+
./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(!Np.test(c))throw new Error(`Invalid source: owner contains invalid characters: "${c}". Allowed: [a-zA-Z0-9_-]`);if(!Op.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 zt(e){return!!e&&e.split(/[/\\]/).includes("..")}function de(e,t){if(zt(e.subpath)||zt(e.ref))throw new Error(`Invalid source: the subpath in "${t}" escapes the repository.`)}function Ie(e,t,r){let s=Kt(e),o=Kt(t);if(o!==s&&!o.startsWith(s+Tp))throw new Error(`Invalid source: the subpath in "${r}" escapes the repository.`)}async function Je(e){if(e.subpath!==null||!e.ref||!e.ref.includes("/"))return e;try{let{stdout:t}=await ht("git",["ls-remote","--heads","--tags",e.cloneUrl],{timeout:15e3}),r=new Set;for(let o of t.split(`
|
|
181
|
+
`)){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>Na)throw new Error(`Invalid skill name: exceeds maximum length of ${Na} characters`);if(!Dp.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 zr(e){let t=e.split(/[/\\]/).filter(Boolean),r=t.length>0?t[t.length-1]:e;return ue(r)}function oo(e,t=zr){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 ke(){try{await ht("git",["--version"]),P("install: git available")}catch{throw new Error("git is required for installing skills. Install git from https://git-scm.com")}}function Fa(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 Wr(e){return e.killed?"Clone timed out after 60 seconds":`Clone failed: ${e.stderr||e.message}`}async function ro(e,t,r){if(t!==null&&/^[0-9a-f]{40}$/i.test(t))return await ht("git",["clone","--no-checkout",e,r],{timeout:6e4}),await ht("git",["checkout",t],{cwd:r,timeout:3e4}),r;let o=["clone","--depth","1"];return t&&o.push("--branch",t),o.push(e,r),await ht("git",o,{timeout:6e4}),r}async function ve(e,t="auto"){P(`install: cloning ${e.owner}/${e.repo}${e.ref?` (ref: ${e.ref})`:""} (transport: ${t})`);let r=await La(we(Ta(),"asm-install-"));if(t==="ssh"||t==="https"){let s=t==="ssh"?e.sshCloneUrl:e.cloneUrl;try{return await ro(s,e.ref,r)}catch(o){await Z(r);let n=o;throw new Error(Wr(n),{cause:o})}}try{return await ro(e.cloneUrl,e.ref,r)}catch(s){if(!Fa(s))throw await Z(r),new Error(Wr(s),{cause:s});P("install: HTTPS clone failed with auth error, retrying with SSH..."),await Z(r);let o=await La(we(Ta(),"asm-install-"));try{return await ro(e.sshCloneUrl,e.ref,o)}catch(n){throw await Z(o),new Error(`Clone failed with both transports:
|
|
182
|
+
HTTPS: ${Wr(s)}
|
|
183
|
+
SSH: ${Wr(n)}`,{cause:n})}}}async function pe(e){let t=we(e,"SKILL.md"),r;try{r=await Jr(t,"utf-8")}catch{throw new Error("Not a valid skill: SKILL.md not found in repository root")}let s=K(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 Ke(e,t=5){let r=[];try{let o=await Jr(we(e,"SKILL.md"),"utf-8"),n=K(o);r.push({relPath:"",name:n.name||Da(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:Cs(n),tags:It(n),dependencies:nt(n),modelInvocable:Ct(n),userInvocable:Lt(n),tokenCount:Le(o)})}catch{}async function s(o,n,a){let l;try{l=await Ep(o)}catch{return}for(let c of l){if(c===".git"||c==="node_modules")continue;let d=we(o,c);try{if(!(await Oa(d)).isDirectory())continue}catch{continue}let u=n?`${n}/${c}`:c,p=a+1,f=we(d,"SKILL.md");try{let m=await Jr(f,"utf-8"),g=K(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:Cs(g),tags:It(g),dependencies:nt(g),modelInvocable:Ct(g),userInvocable:Lt(g),tokenCount:Le(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 ja(e,t=ht){let r=we(e,"scripts"),s=we(r,"package.json");try{await so(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 Fp=[{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 Zt(e){let t=[],r=await Nr(e);for(let{relPath:s,content:o}of r){let n=o.split(`
|
|
184
|
+
`);for(let a=0;a<n.length;a++)for(let{category:l,pattern:c}of Fp)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 jp=["Shell commands","Code execution","Credentials"],_p=["External URLs"];function Xt(e){return e.some(t=>jp.includes(t.category))?"high":e.some(t=>_p.includes(t.category))?"medium":"safe"}async function yt(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 so(e.targetDir),await Kr(e.targetDir,{recursive:!0,force:!0})}catch{}let r=e.sourceDir;try{await Ip(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=we(e.targetDir,".git");try{await Kr(s,{recursive:!0,force:!0})}catch{}P(`install: copied files to ${e.targetDir}`);let o=we(e.targetDir,"SKILL.md");try{await so(o)}catch{throw new Error("Installation verification failed: SKILL.md not found at target")}await ja(e.targetDir);let n=await Jr(o,"utf-8"),a=K(n);return{success:!0,path:e.targetDir,name:a.name||e.skillName,version:ae(a),provider:e.providerLabel,source:t}}async function Qt(e,t){let r=await yt(e);for(let s of t){if(s.name===e.providerName)continue;let o=e.scope==="project"?s.project:s.global,n=ee(o),a=we(n,e.skillName);await Lp(n,{recursive:!0});try{if((await Cp(a)).isSymbolicLink())await Kr(a);else{P(`install: skipping ${a} \u2014 existing non-symlink directory`);continue}}catch{}let l=Ap(n,e.targetDir);await Ne(l,a),P(`install: symlinked ${a} -> ${l}`)}return r.provider=`All (${t.map(s=>s.label).join(", ")})`,r}async function Z(e){try{await Kr(e,{recursive:!0,force:!0})}catch{}}import{execFile as Wp}from"child_process";import{promisify as Jp}from"util";import{readFile as Kp,access as co}from"fs/promises";import{existsSync as zp}from"fs";import{join as ze,dirname as Yp}from"path";var io=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 Up(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=no(m.hint,S);s.push(`${y}${$} ${i.dim(C)}`)}else{let C=no(m.label,r-b);s.push(`${y}${i.bold(C)}`)}}else{let S=no(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 no(e,t){return t<=0?"":e.length<=t?e:t<=3?e.slice(0,t):e.slice(0,t-3)+"..."}async function Ce(e){let{items:t}=e,r=e.pageSize??Math.min(t.length+1,15),s=new io(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=Up(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
185
|
`;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
186
|
`){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
|
|
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
|
|
187
|
-
`)}function
|
|
187
|
+
`: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 Bp,lstat as Gp,mkdir as Vp,readdir as Hp,readFile as _a,rm as qp,stat as Ua}from"fs/promises";import{join as Yr}from"path";async function ao(e){let t;try{t=await Ua(e)}catch{throw new Error(`Path does not exist: ${e}`)}if(!t.isDirectory())throw new Error(`Path is not a directory: ${e}`);let r=Yr(e,"SKILL.md"),s;try{s=await _a(r,"utf-8")}catch{throw new Error(`No SKILL.md found in ${e}`)}let o=K(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 Zr(e,t,r,s){let o=Yr(t,r),n=!1;try{await Bp(o),n=!0}catch{}if(n){if(!s)throw new Error(`Target already exists: ${o}. Use --force to overwrite.`);await qp(o,{recursive:!0,force:!0})}await Vp(t,{recursive:!0}),await Ne(e,o)}async function lo(e){let t;try{t=await Ua(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 Hp(e),s=[];for(let o of r){if(o.startsWith(".")||o==="node_modules")continue;let n=Yr(e,o);try{if(!(await Gp(n)).isDirectory())continue}catch{continue}let a=Yr(n,"SKILL.md");try{let l=await _a(a,"utf-8"),c=K(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 Ba=Jp(Wp);function Ga(e=Yp(process.execPath)){let t=[ze(e,"node_modules","npm","bin","npx-cli.js"),ze(e,"..","lib","node_modules","npm","bin","npx-cli.js"),ze(e,"..","libexec","lib","node_modules","npm","bin","npx-cli.js")];for(let r of t)if(zp(r))return r;return null}function Va(e,t={}){if(process.platform==="win32"){let r=Ga();if(r)return Ba(process.execPath,[r,...e],t)}return Ba("npx",e,t)}async function uo(){try{await Va(["--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 po(e,t){let r=["--yes","skills","add",e];t&&r.push("--skill",t),P(`install: running npx ${r.join(" ")}`);try{let s=await Va(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 mo(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 Ce({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-5X2UQBDB.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 bt(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 Ce({items:n});if(a.length===0)throw new Error("No scope selected. Aborting.");return a[0]===0?"global":"project"}function er(e,t,r,s,o,n,a="global"){let l=a==="project"?o.project:o.global,c=ee(l),d=ze(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 fo(e,t){try{if(await co(e),P(`install: target ${e} \u2014 conflict (exists)${t?", force overwrite":""}`),!t)throw new Error(`Skill already exists at: ${e}
|
|
188
|
+
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 go(e,t,r){for(let s of r.providers){if(!s.enabled||s.name===t)continue;let o=ee(s.global),n=ze(o,e);try{await co(n);let a=ze(n,"SKILL.md");await co(a);let l=await Kp(a,"utf-8");if((K(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 ho(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=ee(l),d=ze(c,e);return await Zr(t,c,e,n),P(`install: linked "${e}" from ${t} -> ${d}`),d}import{join as om}from"path";import{readFile as Zp,writeFile as Xp,mkdir as Qp}from"fs/promises";import{dirname as em}from"path";async function tm(e){try{let t=await Zp(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 rm(e,t,r){let s={fetched_at:new Date().toISOString(),ttl_seconds:r,data:t};try{await Qp(em(e),{recursive:!0}),await Xp(e,JSON.stringify(s,null,2),"utf-8"),P(`http: wrote cache -> ${e}`)}catch(o){P(`http: failed to write cache: ${o}`)}}function sm(e){let t=new Date(e.fetched_at).getTime();return(Date.now()-t)/1e3<e.ttl_seconds}async function Ha(e,t,r={}){let s=r.ttl??3600,o=r.noCache??!1,n=await tm(t);if(n&&!o&&sm(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 rm(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 nm=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,im=/^[a-zA-Z0-9_-]+$/,Ja=/^https:\/\/github\.com\/[a-zA-Z0-9_-]+\/[a-zA-Z0-9._-]+$/,am=/^[0-9a-f]{40}$/,lm=/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?(\+[a-zA-Z0-9.]+)?$/,cm=/^[a-z0-9-]+$/,dm=/^sha256:[0-9a-f]{64}$/,qa=["pass","warning","dangerous"];function Xr(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:nm,maxLength:128},{field:"author",pattern:im,maxLength:39},{field:"description",maxLength:256},{field:"repository",pattern:Ja},{field:"commit",pattern:am},{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"||!qa.includes(n))&&t.push({field:"security_verdict",message:`"security_verdict" must be one of: ${qa.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"||!lm.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`}),cm.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"||!dm.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 um(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 pm(e,t,r=2){let s=[];for(let o of t){if(e===o)continue;let n=um(e,o);n<=r&&s.push({existingName:o,distance:n})}return s.sort((o,n)=>o.distance-n.distance)}var yo=process.env.ASM_REGISTRY_URL??"https://raw.githubusercontent.com/luongnv89/asm-registry/main/index.json";function mm(){return process.env.ASM_REGISTRY_CACHE??om(Lr(),"registry-cache.json")}var fm=3600;function _e(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 bo(e){return _e(e)?e.includes("/"):!1}async function wo(e){let t=await Ha(yo,mm(),{ttl:fm,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=Xr(s);if(o.length>0){P(`registry: dropping invalid manifest entry (${s?.name??"unknown"}): ${o.map(n=>n.message).join(", ")}`);continue}if(!Ja.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 gm(e,t){return t.manifests.filter(r=>r.name.toLowerCase()===e.toLowerCase())}function hm(e,t,r){return r.manifests.find(s=>s.author.toLowerCase()===e.toLowerCase()&&s.name.toLowerCase()===t.toLowerCase())??null}function Wa(e,t,r=5){return pm(e,t.manifests.map(o=>o.name),3).slice(0,r).map(o=>o.existingName)}async function Qr(e,t){let r=await wo(t);if(!r)return P("registry: failed to fetch index \u2014 skipping registry resolution"),{resolved:null,multipleMatches:[],suggestions:[]};if(bo(e)){let[n,a]=e.split("/"),l=hm(n,a,r);if(l)return{resolved:{manifest:l,source:"registry"},multipleMatches:[],suggestions:[]};let c=Wa(a,r);return{resolved:null,multipleMatches:[],suggestions:c}}let s=gm(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=Wa(e,r);return{resolved:null,multipleMatches:[],suggestions:o}}var Ka=[{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 ko(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=A(s)||"Failed to fetch GitHub profile",P(`security-audit: source analysis failed -> ${r.fetchError}`)}return r}function vo(e){let t=new Map;for(let{relPath:o,content:n}of e){let a=n.split(`
|
|
189
|
+
`);for(let l=0;l<a.length;l++){let c=a[l],d=c.trim();for(let u of Ka)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 So(e){let t=new Map;for(let n of e)for(let a of n.matches)for(let l of Ka)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}var T=i,Ye=56,ym={"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"},za={critical:0,warning:1,info:2};function bm(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 wm(e){switch(e){case"safe":return T.green;case"caution":return T.cyan;case"warning":return T.yellow;case"dangerous":return T.red}}function wt(e){switch(e){case"critical":return T.red("!!");case"warning":return T.yellow(" !");case"info":return T.dim(" i")}}function $o(e,t){return e.length>t?e.slice(0,t-3)+"...":e}function es(e){return e.toLocaleString("en-US")}function Za(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function Ya(e){return Za(e).length}function km(e){let t=new Map;for(let r of e){let s=`${r.file}:${r.line}`,o=t.get(s);(!o||za[r.severity]<za[o.severity])&&t.set(s,r)}return Array.from(t.values())}function vm(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 Ze(e){let t=[],r=bm(e.verdict),s=Za(r),o=` ${T.bold(e.skillName)}`,n=` ${e.skillName}`,a=Ye-4,l=Math.max(1,a-n.length-s.length);if(t.push(""),t.push(T.dim(" +-- ")+T.bold("Security Audit")+T.dim(" "+"-".repeat(Ye-19)+"+")),t.push(T.dim(" |")+o+" ".repeat(l)+r+T.dim("|")),t.push(T.dim(" |")+T.dim(` ${es(e.totalFiles)} files | ${es(e.totalLines)} lines`)+" ".repeat(Math.max(1,a-` ${es(e.totalFiles)} files | ${es(e.totalLines)} lines`.length))+T.dim("|")),t.push(T.dim(" +"+"-".repeat(Ye-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=wm(e.verdict),f=e.verdict==="dangerous"||e.verdict==="warning"?wt("critical"):e.verdict==="caution"?wt("warning"):wt("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(Ye-2)));for(let p of e.codeScans){let f=km(p.matches),m=f.filter(F=>F.severity==="critical").length,g=f.filter(F=>F.severity==="warning").length,h=f.filter(F=>F.severity==="info").length,y=m>0?wt("critical"):g>0?wt("warning"):wt("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 $=ym[p.category],v=$?T.dim(`PERM: ${$}`):"",S=` ${y} ${T.bold(p.category)} (${b.join(", ")})`;if(v){let F=Ya(S),k=Ya(v),E=Math.max(2,Ye-F-k);t.push(S+" ".repeat(E)+v)}else t.push(S);let C=vm(f),M=Math.min(24,Math.max(...C.map(F=>F.file.length))),G=0,N=3;for(let F of C){if(G>=N)break;let k=$o(F.file,24),E=T.dim(k.padEnd(M));if(F.entries.length===1){let _=F.entries[0],Q=$o(_.match,50);t.push(` ${E} :${_.line} ${T.dim("--")} ${_.severity==="critical"?Q:T.dim(Q)}`),G++}else if(F.entries.length<=3){let _=F.entries.map(oe=>`:${oe.line}`).join(", "),Q=$o(F.entries[0].match,40);t.push(` ${E} ${_} ${T.dim("--")} ${T.dim(Q)}`),G++}else{let Q=F.entries.slice(0,3).map(be=>`:${be.line}`).join(", "),oe=F.entries.length-3;t.push(` ${E} ${Q} ${T.dim(`(+${oe} more)`)}`),G++}}let U=C.length-Math.min(C.length,N);if(U>0){let F=f.length-C.slice(0,N).reduce((k,E)=>k+E.entries.length,0);F>0&&t.push(` ${T.dim(`... ${F} more in ${U} file${U>1?"s":""}`)}`)}t.push("")}}t.push(T.dim(" "+"=".repeat(Ye-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,Ye-2-d.length-u.length);t.push(T.dim(` ${d}${" ".repeat(p)}${u}`))}else t.push(T.dim(` ${d}`));return t.push(""),t.join(`
|
|
190
|
+
`)}function ts(e){return JSON.stringify(e,null,2)}function Sm(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 $m=new Set([".md",".txt",".rst",".adoc",".markdown"]),xm=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 Pm(e){let t=e.split("/").pop();if(xm.has(t))return!0;let r=t.includes(".")?`.${t.split(".").pop().toLowerCase()}`:"";return $m.has(r)}async function $e(e,t,r,s){P(`security-audit: scanning ${e}`);let n=(await Nr(e)).filter(f=>!Pm(f.relPath)),a=n.reduce((f,m)=>f+m.lineCount,0),l=null;r&&s&&(l=await ko(r,s));let c=vo(n),d=So(c),{verdict:u,reason:p}=Sm(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 kt="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`).",Xa=["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"],Qa=["confirm","confirmation","error","errors","fail","failure","caution","warning","prerequisite","prerequisites","requires","requirements","rollback","dry-run","dry run","safety","validate","validation","check","backup"],el=["acceptance criteria","expected output","expected result","edge case","edge cases","test","tests","testing","verify","verification","assert","example input","example output","given","then"],Rm=["reference","references","see","template","templates","script","scripts","helper","helpers","link"],Em=["when to use","quick start","overview","instructions","steps","workflow","phases","progressive"];function tr(e){let t=e.split(`
|
|
188
191
|
`);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
192
|
`),o=t.slice(r+1).join(`
|
|
190
193
|
`);return{rawFrontmatter:s,body:o}}return{rawFrontmatter:t.slice(1).join(`
|
|
191
|
-
`),body:""}}function
|
|
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
|
|
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.
|
|
194
|
+
`),body:""}}function rs(e){return e?e.split(`
|
|
195
|
+
`).length:0}function xo(e){return e?e.split(/\s+/).map(t=>t.trim()).filter(Boolean).length:0}function Im(e,t=1){return(e.match(/^#{1,6}\s+\S/gm)||[]).length>=t}function rr(e,t){let r=e.toLowerCase();return t.filter(s=>r.includes(s))}function Cm(e){return/```[\s\S]+?```/m.test(e)}function Lm(e){return/^\s*[-*]\s+\S/m.test(e)||/^\s*\d+\.\s+\S/m.test(e)}function Po(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=Im(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(kt))}return{id:"structure",name:"Structure & completeness",score:Math.round(a),max:10,findings:o,suggestions:n}}function Ro(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=xo(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&&(Xa.includes(l)||Xa.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 Eo(e,t){let r=[],s=[],o=0,n=rr(t,Em);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.'),Lm(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=Cm(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=xo(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 Io(e,t){let r=[],s=[],o=0,n=xo(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=rr(t,Rm);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=>rs(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 Co(e,t){let r=[],s=[],o=0,n=rr(t,Qa);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 Lo(e,t){let r=[],s=[],o=0,n=rr(t,el);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 Am=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 Ao(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?Am.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 To(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}}var ss=["name","description","version","license","author","creator","compatibility","allowed-tools","effort","tags","metadata"];import{readFile as Oo,writeFile as Mm,stat as cl,copyFile as Fm,readdir as jm}from"fs/promises";import{join as dl,resolve as ul,basename as Do,isAbsolute as pl}from"path";import{readFile as Tm,readdir as tl,stat as rl}from"fs/promises";import{join as sl,isAbsolute as ol,resolve as nl}from"path";var Nm=[{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 il(e){let t=[],r=[],s=10,o=new Set,n=ol(e)?e:nl(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 tl(c)}catch{return}for(let u of d){let p=sl(c,u),f;try{f=await rl(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 Tm(p,"utf-8")).split(`
|
|
196
|
+
`),y=!1,b=!1;for(let $ of Nm){$.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 M=p.replace(n+"/","");t.push(`[${$.category}] ${M}:${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 Om=new Set([".sh",".bash",".py"]),al={".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 Dm(e,t){let r=al[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(`
|
|
197
|
+
`),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.stdout),a=Array.isArray(n)?n:n.comments,l=[];if(Array.isArray(a)){for(let c of a)if(c&&typeof c=="object"){let d=c;l.push({file:e,line:Number(d.line)||0,severity:d.level==="error"||d.level==="e"?"error":d.level==="warning"||d.level==="w"?"warning":"info",message:d.message||"Unknown issue"})}}return l}catch{return[{file:e,line:0,severity:"warning",message:`Linter exited with code ${o.exitCode}: ${(o.stderr||o.stdout).slice(0,200)}`}]}}return[]}catch(s){return s&&typeof s=="object"&&"code"in s&&s.code==="ENOENT",null}}async function ll(e){let t=[],r=[],s=10,o=0,n=!1,a=[],l=ol(e)?e:nl(e);async function c(d){let u;try{u=await tl(d)}catch{return}for(let p of u){let f=sl(d,p),m;try{m=await rl(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(!Om.has(g))continue;let h=f.replace(l+"/",""),y=await Dm(f,g);if(y===null){n=!0;let b=al[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 vt(e){let{content:t,skillPath:r,skillMdPath:s,rootEntries:o}=e,n=K(t),{rawFrontmatter:a,body:l}=tr(t),c=[Po(n,l,a,o),Ro(n,l),Eo(n,l),Io(n,l),Co(n,l),Lo(n,l),Ao(n,l,o),To(n,l)],[d,u]=await Promise.all([il(r),ll(r)]),p=[...c,d,u];if(n.name&&Do(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(kt)&&y.push(kt);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 Mo(e){let t=pl(e)?e:ul(e),r;try{r=await cl(t)}catch{throw new Error(`Skill path does not exist: ${t}`)}let s,o;if(r.isFile())return s=t,o=await Oo(s,"utf-8"),vt({content:o,skillPath:Do(t)==="SKILL.md"?Do(t):t,skillMdPath:s});if(!r.isDirectory())throw new Error(`Skill path is not a directory or file: ${t}`);s=dl(t,"SKILL.md");try{o=await Oo(s,"utf-8")}catch{throw new Error(`SKILL.md not found in ${t}. Run "asm init" to create one.`)}let n;try{n=await jm(t)}catch{n=void 0}return vt({content:o,skillPath:t,skillMdPath:s,rootEntries:n})}function _m(e){return e<=20?"low":e<=80?"medium":e<=250?"high":"max"}function Um(e){let t=e.split(`
|
|
195
198
|
`),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=
|
|
197
|
-
`),changed:l}}function
|
|
199
|
+
`)})}else r.push({key:f,text:d}),o++}let n=d=>{let u=ss.indexOf(d);return u===-1?ss.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(`
|
|
200
|
+
`),changed:l}}function ml(e,t={}){let r=[],s=[],o=e.replace(/\r\n/g,`
|
|
198
201
|
`);o!==e&&r.push({id:"normalise-line-endings",description:"Convert CRLF line endings to LF."});let n=o.split(`
|
|
199
202
|
`),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}=
|
|
203
|
+
`);let{rawFrontmatter:l,body:c}=tr(o),d=K(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=No(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=No(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=_m(rs(c));u=No(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=Um(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
204
|
${u.replace(/^\n+|\n+$/g,"")}
|
|
202
205
|
---
|
|
203
206
|
|
|
204
207
|
${g}`;return h.endsWith(`
|
|
205
208
|
`)||(h+=`
|
|
206
209
|
`),e.replace(/\r\n/g,`
|
|
207
|
-
`),{newContent:h,applied:r,skipped:s}}function
|
|
210
|
+
`),{newContent:h,applied:r,skipped:s}}function No(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(`
|
|
208
211
|
`)?"":`
|
|
209
212
|
`;return`${e}${n}${t}: ${o}
|
|
210
|
-
`}function
|
|
213
|
+
`}function os(e,t,r="SKILL.md"){if(e===t)return"";let s=e.split(`
|
|
211
214
|
`),o=t.split(`
|
|
212
215
|
`),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
|
|
214
|
-
`)}function
|
|
216
|
+
`)}async function Fo(e,t){let r=pl(e)?e:ul(e),s,o=await cl(r).catch(()=>null);if(!o)throw new Error(`Skill path does not exist: ${r}`);if(o.isFile())s=r;else if(o.isDirectory())s=dl(r,"SKILL.md");else throw new Error(`Skill path is not a directory or file: ${r}`);let n;try{n=await Oo(s,"utf-8")}catch{throw new Error(`SKILL.md not found at ${s}.`)}let a=ml(n,{gitAuthor:t.gitAuthor}),l=os(n,a.newContent),c=null;return!t.dryRun&&a.newContent!==n&&(c=`${s}.bak`,await Fm(s,c),await Mm(s,a.newContent,"utf-8")),{report:await vt({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 jo(){try{let{stdout:e,exitCode:t}=await se(["git","config","--global","--get","user.name"]);if(t!==0)return null;let r=e.trim();return r||null}catch{return null}}function Bm(e,t,r=20){let s=Math.round(e/t*r);return"\u2588".repeat(s)+"\u2591".repeat(Math.max(0,r-s))}function sr(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} ${Bm(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=Gm(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(`
|
|
217
|
+
`)}function Gm(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 _o(e){return JSON.stringify(e,null,2)}function Uo(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
218
|
`);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
|
|
217
|
-
`)}function
|
|
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
|
|
219
|
-
`)}function
|
|
220
|
-
`)}function
|
|
219
|
+
`)}import{stat as ns,readdir as Vm}from"fs/promises";import{join as is,resolve as Hm,basename as St,isAbsolute as qm}from"path";async function gl(e){let t;try{t=await Vm(e)}catch{return[]}let r=[];for(let s of t){if(s.startsWith(".")||s==="node_modules"||s==="dist"||s==="build")continue;let o=is(e,s),n;try{n=await ns(o)}catch{continue}if(!n.isDirectory())continue;let a=is(o,"SKILL.md");try{(await ns(a)).isFile()&&r.push(o)}catch{}}return r.sort((s,o)=>St(s).localeCompare(St(o))),r}async function Bo(e){let t=is(e,"SKILL.md");try{if((await ns(t)).isFile())return{kind:"single",skillDirs:[e]}}catch{}let r=await gl(e);return r.length>0?{kind:"collection",skillDirs:r}:{kind:"none",skillDirs:[]}}function $t(e){return e?!!(e.startsWith("github:")||/^https?:\/\/github\.com\//i.test(e)):!1}function fl(e){return{skillPath:e,skillMdPath:is(e,"SKILL.md"),label:St(e)}}async function Go(e,t={}){if(!e)throw new Error("resolveEvalInput: input must be a non-empty string");if($t(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 Bo(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(fl),isCollection:a.kind==="collection",cleanup:n.cleanup,provenance:{input:e,remote:!0,sourceRef:n.sourceRef,commitSha:n.commitSha,tempPath:n.rootDir}}}let r=qm(e)?e:Hm(e),s;try{s=await ns(r)}catch{throw new Error(`Skill path does not exist: ${r}`)}if(s.isFile())return{targets:[{skillPath:St(r)==="SKILL.md"?St(r):r,skillMdPath:r,label:St(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 Bo(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(fl),isCollection:o.kind==="collection",cleanup:async()=>{},provenance:{input:e,remote:!1,sourceRef:null}}}function Vo(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 or(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 Ho(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(`
|
|
220
|
+
`)}function qo(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?nr(t.report,null):null}))}}function nr(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 El,copyFile as ef,cp as tf,mkdtemp as Il,lstat as Cl,mkdir as en,readdir as rf,readFile as tn,readlink as sf,realpath as ur,rename as ls,rm as Ue}from"fs/promises";import{execFile as of}from"child_process";import{createHash as nf}from"crypto";import{promisify as af}from"util";import{dirname as pr,isAbsolute as rn,join as fe,relative as Ll,resolve as he}from"path";import{execFile as Wm}from"child_process";import{promisify as Jm}from"util";import{join as Km}from"path";var zm=Jm(Wm),Ym=["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 yl(e){let t={...process.env};for(let r of Ym)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 Wo=new WeakMap;function hl(e,t){return Wo.set(e,t),e}function bl(e){return e.normalize("NFC").toLowerCase().normalize("NFC")}async function ar(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 wl(e,t){try{let r=["ls-remote",e];t?r.push(t,`${t}^{}`):r.push("HEAD");let{stdout:s}=await zm("git",r,{timeout:1e4}),o=new Map;for(let n of s.split(`
|
|
221
|
+
`)){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 ir(e){return e.sourceType?e.sourceType:e.source.startsWith("local:")?"local":"github"}function xt(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 Jo(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 kl(e,t){return t.skillPath?Km(e,t.skillPath):e}async function lr(e){let t=e?.readLockFn??Oe,r=e?.fetchRegistryIndexFn??wo,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])=>ir(c)==="registry"||c.registryName)&&(n=await r());let l=await ar(o,5,async([c,d])=>{let u=ir(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 hl({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=xt(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 wl(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 hl({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 Zm}from"child_process";import{promisify as Xm}from"util";import{join as as}from"path";import{homedir as vl}from"os";import{mkdir as Sl,rm as Xe,rename as Ko,cp as $l,access as Qm}from"fs/promises";var cr=Xm(Zm);async function xl(e,t,r,s,o){if(ir(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=xt(t.source);if(!l)return{name:e,status:"failed",reason:"Cannot determine remote URL"};let c=as(vl(),".config","agent-skill-manager",".tmp",`${e}-${Date.now()}`);try{let d=as(vl(),".config","agent-skill-manager",".tmp");if(await Sl(d,{recursive:!0}),P(`updater: fetching latest ${e} to ${c}`),a)try{let k=a.length===40?"sha1":"sha256",E=yl(k);await cr("git",["init",c],{timeout:1e4,env:E}),await cr("git",["fetch","--depth","1",l,a],{cwd:c,timeout:6e4,env:E}),await cr("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 cr("git",k,{timeout:6e4})}catch(E){let _=E;return{name:e,status:"failed",reason:`Clone failed: ${_.stderr||_.message||String(E)}`}}}let u;if(a)u=a;else try{let{stdout:k}=await cr("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=kl(c,t);P(`updater: running security audit on ${e}`);let f="safe";try{let k=s?.auditFn??$e,E=Jo(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??D,g=s?.resolveProviderPathFn??ee,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=as(v,e),C=as(c,".git");try{await Xe(C,{recursive:!0,force:!0})}catch{}let M=!0;try{await Qm(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}`}}M=!1}let G=s?.writeLockEntryFn??dt,N={...t,commitHash:u,installedAt:new Date().toISOString()};if(!M){try{await Sl(v,{recursive:!0}),await $l(p,S,{recursive:!0})}catch(k){await Xe(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 G(e,N)}catch(k){try{await Xe(S,{recursive:!0,force:!0})}catch(_){let Q=k instanceof Error?k.message:String(k),oe=_ instanceof Error?_.message:String(_);return{name:e,status:"failed",reason:`Lock file update failed: ${Q}. Removal of the new installation also failed: ${oe}`}}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 U=`${S}.bak-${Date.now()}`,F=!1;try{await Ko(S,U),F=!0,await $l(p,S,{recursive:!0})}catch(k){if(F)try{await Xe(S,{recursive:!0,force:!0}),await Ko(U,S),F=!1}catch(E){let _=k instanceof Error?k.message:String(k),Q=E instanceof Error?E.message:String(E);return{name:e,status:"failed",reason:`Atomic swap failed: ${_}. Restore also failed; backup preserved at ${U}: ${Q}`}}return{name:e,status:"failed",reason:`Atomic swap failed: ${k instanceof Error?k.message:String(k)}`}}try{await G(e,N)}catch(k){try{await Xe(S,{recursive:!0,force:!0}),await Ko(U,S),F=!1}catch(_){let Q=k instanceof Error?k.message:String(k),oe=_ instanceof Error?_.message:String(_);return{name:e,status:"failed",reason:`Lock file update failed: ${Q}. Restore also failed; backup preserved at ${U}: ${oe}`}}let E=k instanceof Error?k.message:String(k);return{name:e,status:"failed",reason:`Lock file update failed: ${E}`}}if(F)try{await Xe(U,{recursive:!0,force:!0})}catch(k){P(`updater: failed to remove backup ${U}: ${k}`)}return{name:e,status:"updated",oldCommit:ge(t.commitHash),newCommit:ge(u),securityVerdict:f}}finally{try{await Xe(c,{recursive:!0,force:!0})}catch{}}}async function zo(e,t,r){let s=r?.readLockFn??Oe,o=r?.checkOutdatedFn??lr,n=r?.updateSkillFn??xl,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:Wo.get(y)}]:[]}),p=r?.writeLockEntryFn??dt,f=Promise.resolve(),m=(y,b)=>{let $=f.then(()=>p(y,b));return f=$.then(()=>{},()=>{}),$},g=new Map;u.forEach((y,b)=>{let $=bl(y.name),v=g.get($)??[];v.push({...y,index:b}),g.set($,v)});let h=new Array(u.length);return await ar([...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 Yo(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(`
|
|
222
|
+
`)}function Zo(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 Xo(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 dr=af(of),lf=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/,Pl=128,cf=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Qo(){return{version:1,skills:{}}}async function mr(e=Ge()){return cs(e)}async function Qe(e=Ge()){let t=await mr(e),r=[];for(let[s,o]of Object.entries(t.skills)){let n=!1;try{await El(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 fr(e,t){let r=e.find(o=>o.dirName===t);return r||(e.find(o=>o.name===t)??null)}function X(e,t){return{name:e,status:"failed",reason:t}}async function Al(e,t,r){return e.sourceType!==t.sourceType||he(e.libraryPath)!==he(t.libraryPath)?!1:e.sourceType==="local"?r?await df(e)===r:!1:e.source===t.source&&e.ref===t.ref&&e.skillPath===t.skillPath}function sn(e){return X(e,`Library skill "${e}" changed while update was in progress. Run "asm library update ${e}" again.`)}function on(e){let t=Date.parse(e??""),r=Number.isFinite(t)?Math.max(Date.now(),t+1):Date.now();return new Date(r).toISOString()}function nn(e){if(!e.source.startsWith("local:"))return null;let t=e.source.slice(6);return t?he(t):null}async function df(e){let t=nn(e);if(!t)throw new Error("Unsupported library source for update");let r=ds(t,fe(t,e.skillPath));if(!r)throw new Error("Invalid update metadata: skillPath escapes source root");let[s,o]=await Promise.all([ur(t),ur(r)]);if(!gr(s,o))throw new Error("Invalid update metadata: skillPath escapes source root");return o}async function cs(e){let t;try{t=await tn(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"),Qo();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 ef(e,r)}catch{}return console.error(`Warning: library-lock.json was corrupted. Backup saved to ${r}. Starting fresh.`),Qo()}}async function an(e,t){await Ve(t,JSON.stringify(e,null,2)+`
|
|
223
|
+
`)}function Tl(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?cf.test(r)?{name:t,version:r}:{reason:"Invalid source SKILL.md: invalid version"}:{reason:"Invalid source SKILL.md: missing version"}}function gr(e,t){let r=he(e),s=he(t),o=Ll(r,s);return o===""||!!o&&!o.startsWith("..")&&!rn(o)}function ds(e,t){let r=he(e),s=he(t);return gr(r,s)?s:null}async function uf(e){let t=he(e);for(;;)try{return await ur(t)}catch(r){if(!(r instanceof Error)||!("code"in r)||r.code!=="ENOENT")throw r;let s=pr(t);if(s===t)throw r;t=s}}async function Nl(e,t){try{let[r,s]=await Promise.all([ur(e),uf(t)]);return gr(r,s)}catch{return!1}}async function Ol(e){let t=nf("sha256");async function r(s,o){let n=await rf(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
224
|
`),await r(c,l)):a.isFile()&&(t.update(`file:${l}
|
|
222
|
-
`),t.update(await
|
|
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(`
|
|
225
|
+
`),t.update(await tn(c)),t.update(`
|
|
226
|
+
`))}}return await r(e,""),t.digest("hex")}async function Dl(e,t,r){let s=xt(e.source);if(!s)return{reason:"Cannot determine remote URL"};let o=fe(pr(r),".tmp");await en(o,{recursive:!0});let n=await Il(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 dr("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 dr("git",["checkout",a],{cwd:n,timeout:3e4})}catch{try{await dr("git",["fetch","--depth","1","origin",a],{cwd:n,timeout:6e4}),await dr("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 dr("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 ln(e,t){let r=await Il(fe(pr(t),".library-update-"));try{return await tf(e,r,{recursive:!0}),await Ue(fe(r,".git"),{recursive:!0,force:!0}),r}catch(s){throw await Ue(r,{recursive:!0,force:!0}),s}}async function cn(e){let t=pr(e.targetDir),r=null,s=!1;try{try{await Ml(e.targetDir)&&(r=fe(t,`.library-update-backup-${Date.now()}`),await ls(e.targetDir,r)),await ls(e.stagedDir,e.targetDir);try{return await e.writeLock(),null}catch(o){if(o instanceof Tt)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 Ue(e.targetDir,{recursive:!0,force:!0}),r)try{await ls(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 ls(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 Ue(e.stagedDir,{recursive:!0,force:!0}),r&&!s&&await Ue(r,{recursive:!0,force:!0})}}function pf(e,t){let r=Ll(e,t);return r===""||!!r&&!r.startsWith("..")&&!rn(r)}async function Rl(e){try{return{path:await ur(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 dn(e){let t=pn(e.activationName),r=fe(e.targetDir,t),s;try{s=await Cl(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 sf(r),n=rn(o)?o:he(pr(r),o),a=e.librarySkillsDir??Pe(),l=await Rl(n),c=await Rl(a),d=l.exists&&c.exists,u=d?l.path:he(n),p=d?c.path:he(a);if(!pf(p,u))throw new Error(`Refusing to deactivate symlink outside the ASM library: ${r}.`);return await Ue(r),{name:t,provider:e.provider,scope:e.scope,path:r,target:u}}async function un(e){let t=pn(e.activationName),r=fe(e.targetDir,t);try{let s=await Cl(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 Ue(r,{force:!0})}catch(s){if(!(s instanceof Error&&"code"in s&&s.code==="ENOENT"))throw s}return await en(e.targetDir,{recursive:!0}),await Ne(e.libraryPath,r),{symlinkPath:r,targetPath:e.libraryPath}}async function Ml(e){try{return await El(e),!0}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function pn(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>Pl)throw new Error(`Invalid skill name: exceeds maximum length of ${Pl} characters`);if(!lf.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 mn(e,t={}){let r=t.skillsDir??Pe(),s=t.lockPath??Ge(),o=pn(e.libraryName),n=fe(r,o);await en(r,{recursive:!0});let a=await ln(e.sourceDir,n);try{let l=await tn(fe(a,"SKILL.md"),"utf-8"),c=K(l),d=c.name||o,u=ae(c);return await lt(s,async()=>{let p=await cs(s);if(await Ml(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:on(p.skills[o]?.installedAt)}}},m=await cn({stagedDir:a,targetDir:n,writeLock:()=>an(f,s)});if(m)throw new Error(m.reason??"Failed to install library skill")}),{name:d,version:u,libraryPath:n}}finally{await Ue(a,{recursive:!0,force:!0})}}import{readFile as mf,realpath as Fl,rm as jl}from"fs/promises";import{join as fn}from"path";async function _l(e,t={},r){let s=t.lockPath??Ge(),o=t.skillsDir??Pe(),n=r?.writeLibraryLockFn??an,a=await mr(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 X(e,`Library skill "${e}" not found. Run "asm library list".`);let[u,p]=d,f={...p};if(!p.source||!p.source.trim())return X(u,"Missing update metadata: source");if(!p.sourceType||!p.sourceType.trim())return X(u,"Missing update metadata: sourceType");if(p.skillPath===void 0||p.skillPath===null)return X(u,"Missing update metadata: skillPath");if(!p.libraryPath||!p.libraryPath.trim())return X(u,"Missing update metadata: libraryPath");let m=null,g=null;try{let h,y=null;if(p.sourceType==="local"){let k=nn(p);if(!k)return X(u,`Unsupported library source for update: ${p.source}`);h=k}else if(p.sourceType==="github"||p.sourceType==="registry"){let k=await Dl(p,u,s);if("reason"in k)return k.tempDir&&(m=k.tempDir),X(u,k.reason);h=k.tempDir,m=k.tempDir,y=k.commitHash}else return X(u,`Unsupported library source type for update: ${p.sourceType}`);let b=ds(h,fn(h,p.skillPath));if(!b)return X(u,"Invalid update metadata: skillPath escapes source root");let $=fn(b,"SKILL.md"),v,S;try{[v,S]=await Promise.all([Fl(h),Fl(b)])}catch(k){return X(u,`Unable to read source SKILL.md at ${$}: ${k instanceof Error?k.message??String(k):String(k)}`)}if(!gr(v,S))return X(u,"Invalid update metadata: skillPath escapes source root");p.sourceType==="local"&&(g=S);let C;try{C=await mf($,"utf-8")}catch(k){return X(u,`Unable to read source SKILL.md at ${$}: ${k instanceof Error?k.message??String(k):String(k)}`)}let M=K(C),G=Tl(M);if("reason"in G)return X(u,G.reason);let N=G.name,U=G.version;if(p.sourceType==="local"&&(y=await Ol(b)),!y)return X(u,"Could not read new commit");let F=await ln(b,fn(o,u));try{return await lt(s,async()=>{let k=await cs(s),E=k.skills[u];if(!E)return X(u,`Library skill "${u}" not found. Run "asm library list".`);let _=ds(o,E.libraryPath);if(!_)return X(u,"Invalid update metadata: libraryPath escapes library skills directory");if(!await Nl(o,_))return X(u,"Invalid update metadata: libraryPath escapes library skills directory");let Q;try{Q=await Al(E,f,g)}catch{return sn(u)}let oe=E.installedAt===f.installedAt;if(oe&&Q&&E.commitHash===y)return{name:E.name,status:"skipped",oldVersion:E.version,newVersion:U,oldCommit:E.commitHash,newCommit:y};if(!oe||!Q||E.commitHash!==f.commitHash)return sn(u);let be={...k,skills:{...k.skills,[u]:{...E,name:N,version:U,commitHash:y,installedAt:on(E.installedAt)}}},R=await cn({stagedDir:F,targetDir:_,writeLock:()=>n(be,s)});return R?X(u,R.reason??"Failed to update library skill"):{name:N,status:"updated",oldVersion:E.version,newVersion:U,oldCommit:E.commitHash,newCommit:y}})}finally{await jl(F,{recursive:!0,force:!0})}}finally{m&&await jl(m,{recursive:!0,force:!0})}}var ff=4;async function gn(e,t={},r){let s=t.lockPath??Ge(),o=await mr(s),n=e===null?Object.keys(o.skills):e,a=[],l=r?.updateLibrarySkillFn??_l,c=await ar(n,ff,d=>l(d,t));for(let d of c)d.status==="failed"&&d.reason?.includes('Run "asm library list"')&&a.push(d.reason);return{results:c,updatedCount:c.filter(d=>d.status==="updated").length,skippedCount:c.filter(d=>d.status==="skipped").length,failedCount:c.filter(d=>d.status==="failed").length,warnings:a}}import{join as bs}from"path";var gf=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function hf(e){if(typeof e!="string")return null;let t=gf.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 yf(e,t){let r=hf(e);if(!r)throw new Error(`invalid semver: ${t} "${e}"`);return r}var hn=new Map;function yn(e){if(!e||typeof e.id!="string"||e.id.length===0)throw new Error("register: provider.id is required");if(yf(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=hn.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),hn.set(e.id,t)}function us(){let e=[];for(let t of hn.values())for(let r of t)e.push(r);return e}import{stat as bf}from"fs/promises";var Ul="quality",Bl="1.0.0",Gl=1;function wf(e){return e.topSuggestions.map(t=>({severity:"info",message:t}))}function kf(e){return e.categories.map(t=>({id:t.id,name:t.name,score:t.score,max:t.max}))}var Vl={id:Ul,version:Bl,schemaVersion:Gl,description:"Static linter for SKILL.md structure, description, and safety.",async applicable(e){try{return(await bf(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 Mo(e.skillPath);return{providerId:Ul,providerVersion:Bl,schemaVersion:Gl,score:r.overallScore,passed:r.grade!=="F",categories:kf(r),findings:wf(r),raw:r,startedAt:"",durationMs:0}}};var Kl=Hn(Wn(),1);import{readFile as vf,stat as Sf}from"fs/promises";import{basename as $f}from"path";var Hl="skill-best-practice",ql="1.2.0",Wl=1,xf=new Set(["name","description","license","allowed-tools","metadata","compatibility","effort","dependencies"]),Jl=new Set(["low","medium","high","xhigh","max"]),bn=250,Pf=/^\d+\.\d+\.\d+$/;function Rf(e){if(!e.startsWith("---"))return null;let t=e.split(`
|
|
224
227
|
`);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
|
|
226
|
-
`)&&!u.includes("\r")&&!u.includes("<")&&!u.includes(">")&&u.length<=1024;
|
|
228
|
+
`)}function ps(e){return{severity:e.severity,message:e.message,code:e.id,categoryId:"validation"}}function te(e,t,r,s,o,n){e.push({id:t,label:r,passed:s,severity:o,message:n})}function ms(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 Ef(e){let t=await vf(e.skillMdPath,"utf-8"),r=[],s=Rf(t);if(s===null){te(r,"missing-frontmatter","Frontmatter exists",!1,"error","SKILL.md must start with a YAML frontmatter block.");let N=ms(e,r,null);return{score:0,passed:!1,findings:r.map(ps),raw:N}}te(r,"frontmatter-present","Frontmatter exists",!0,"error","SKILL.md contains a YAML frontmatter block.");let o;try{o=(0,Kl.parse)(s)}catch(N){te(r,"invalid-yaml","Frontmatter parses as YAML",!1,"error",`Invalid YAML in frontmatter: ${A(N)}`);let U=ms(e,r,null);return{score:0,passed:!1,findings:r.map(ps),raw:U}}if(!o||typeof o!="object"||Array.isArray(o)){te(r,"frontmatter-not-object","Frontmatter is a mapping",!1,"error","Frontmatter must parse to a YAML object.");let N=ms(e,r,null);return{score:0,passed:!1,findings:r.map(ps),raw:N}}let n=o;te(r,"frontmatter-object","Frontmatter is a mapping",!0,"error","Frontmatter parses to a YAML object.");let a=Object.keys(n).filter(N=>!xf.has(N));te(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(te(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 N=/^[a-z0-9-]+$/.test(c)&&!c.startsWith("-")&&!c.endsWith("-")&&!c.includes("--")&&c.length<=64;te(r,"name-kebab-case","Name follows skill-best-practice naming rules",N,"error",N?"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(te(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 N=!u.includes(`
|
|
229
|
+
`)&&!u.includes("\r")&&!u.includes("<")&&!u.includes(">")&&u.length<=1024;te(r,"description-shape","Description follows skill-best-practice formatting rules",N,"error",N?"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=u.length<=bn;te(r,"description-runtime-budget","Description fits the runtime context budget",U,"warning",U?`Description is ${u.length} chars (target \u2264 ${bn}).`:`Description is ${u.length} chars; target \u2264 ${bn}. The /skills listing truncates tail-first, often chopping the negative-trigger clause.`)}let p=n.effort;te(r,"effort-enum","Effort uses the supported enum",p===void 0||typeof p=="string"&&Jl.has(p.trim()),"error",p===void 0||typeof p=="string"&&Jl.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 N=Array.isArray(f)&&f.length>0&&f.every(U=>typeof U=="string"&&U.trim().length>0);te(r,"dependencies-shape","Dependencies are non-empty skill reference strings",N,"error",N?"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 N=typeof m=="string"&&m.length<=500;te(r,"compatibility-shape","Compatibility is a short string",N,"error",N?"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(te(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 N=Pf.test(y);te(r,"metadata-version-semver","metadata.version follows MAJOR.MINOR.PATCH",N,"error",N?"`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(te(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 N=$f(e.skillPath),U=N===c;te(r,"name-matches-directory","Name matches the parent directory",U,"error",U?"Frontmatter `name` matches the skill directory.":`Frontmatter \`name\` ("${c}") must match the parent directory ("${N}").`)}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);te(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=ms(e,r,n),M=C.checkCount===0?100:Math.round(C.passedChecks/C.checkCount*100),G=r.filter(N=>!N.passed).map(ps);return{score:M,passed:G.every(N=>N.severity!=="error"),findings:G,raw:C}}var zl={id:Hl,version:ql,schemaVersion:Wl,description:"Deterministic SKILL.md best-practice validation (rules aligned with the skill-creator standard, v1.7.1).",async applicable(e){try{return(await Sf(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 Ef(e);return{providerId:Hl,providerVersion:ql,schemaVersion:Wl,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 Yl(){yn(Vl),yn(zl)}var Zl=!1;function fs(){Zl||(Yl(),Zl=!0)}function gs(){return fs(),us()}function Xl(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Ql(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 hs(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: ${Xl(f)}`;return Ql(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 Ql(n,s,u,Xl(d),"provider-threw")}finally{l&&clearTimeout(l)}}function If(e){return e>=90?"A":e>=80?"B":e>=65?"C":e>=50?"D":"F"}function ec(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 tc(e,t){return{providerId:e.providerId,providerVersion:e.providerVersion,schemaVersion:e.schemaVersion,passed:e.passed,overallScore:e.score,grade:If(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 hr(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 Cf}from"path";function Lf(){console.log(`${i.bold("Usage:")} asm eval <target> [options]
|
|
227
230
|
|
|
228
231
|
Evaluate a skill's SKILL.md against best practices and produce a scored quality
|
|
229
232
|
report with recommendations. Zero configuration \u2014 just point it at a skill
|
|
@@ -259,8 +262,8 @@ ${i.bold("Examples:")}
|
|
|
259
262
|
asm eval ./my-skill --fix ${i.dim("Auto-fix deterministic issues")}
|
|
260
263
|
asm eval ./my-skill --fix --dry-run ${i.dim("Preview fixes as diff")}
|
|
261
264
|
asm eval ./my-skill --machine ${i.dim("Machine-readable v1 envelope")}
|
|
262
|
-
asm eval-providers list ${i.dim("List registered eval providers")}`)}function
|
|
263
|
-
`))}function
|
|
265
|
+
asm eval-providers list ${i.dim("List registered eval providers")}`)}function Af(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 wn(e,t,r){await ke();let s=ne(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 Je(s);let o=await ve(s,t),n=s.subpath?Cf(o,s.subpath):o;try{Ie(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 rc(e){fs();try{let t={skillPath:e.skillPath,skillMdPath:e.skillMdPath},r=(await Promise.all(hr(gs()).map(async n=>(await n.applicable(t,{})).ok?hs(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 Af(s),{report:{...s.raw,providers:hr(r.map(ec))},error:null}}catch(t){return{report:null,error:A(t)}}}async function sc(e){if(e.flags.help){Lf();return}let t=e.flags.machine?le():void 0,r=performance.now(),s=e.subcommand;if(s||(e.flags.machine&&(t?.(),console.log(W("eval",q.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($t(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(W("eval",q.INVALID_ARGUMENT,n,r)),process.exit(2)),w(n),process.exit(2)}try{let n=await jo(),a=await Fo(s,{dryRun:e.flags.dryRun,gitAuthor:n});if(e.flags.machine){t?.(),console.log(B("eval",nr(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(sr(a.report)),console.log(""),console.log(Uo(a));return}catch(n){e.flags.machine&&(t?.(),console.log(W("eval",q.SKILL_NOT_FOUND,A(n),r)),process.exit(1)),w(A(n)),process.exit(1)}return}let o=null;try{o=await Go(s,{fetchRemote:n=>wn(n,e.flags.transport,e.flags.keep)})}catch(n){e.flags.machine&&(t?.(),console.log(W("eval",q.SKILL_NOT_FOUND,A(n),r)),process.exit(1)),w(A(n)),process.exit(1)}try{if(!o.isCollection&&o.targets.length===1){let d=o.targets[0],{report:u,error:p}=await rc(d);if(!u)throw new Error(p??"eval failed");if(e.flags.machine){t?.();let f=nr(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(_o(u));return}console.log(sr(u)),o.provenance.remote&&Tf(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 or(o.targets,n,async d=>{let{report:u,error:p}=await rc(d);return{label:d.label,skillPath:d.skillPath,report:u,error:p}}),l=Vo(a),c={provenance:o.provenance,aggregate:l,results:a};if(e.flags.machine){t?.(),console.log(B("eval",qo(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(sr(d.report)):(console.log(`Skill evaluation: ${d.skillPath}`),console.log(` ${i.red("error:")} ${d.error??"unknown failure"}`)),console.log("");console.log(Ho(c)),o.provenance.remote&&e.flags.verbose}catch(n){e.flags.machine&&(t?.(),console.log(W("eval",q.SKILL_NOT_FOUND,A(n),r)),process.exit(1)),w(A(n)),process.exit(1)}finally{if(o)try{await o.cleanup()}catch{}}}function Tf(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(`
|
|
266
|
+
`))}function Nf(){console.log(`${i.bold("Usage:")} asm eval-providers <subcommand> [options]
|
|
264
267
|
|
|
265
268
|
Manage evaluation providers registered with the ${i.bold("asm eval")} framework.
|
|
266
269
|
Providers implement the ${i.bold("EvalProvider")} contract (see src/eval/types.ts) and
|
|
@@ -276,7 +279,7 @@ ${i.bold("Options:")}
|
|
|
276
279
|
|
|
277
280
|
${i.bold("Examples:")}
|
|
278
281
|
asm eval-providers list ${i.dim("Show registered providers")}
|
|
279
|
-
asm eval-providers list --json ${i.dim("Machine-readable listing")}`)}async function
|
|
282
|
+
asm eval-providers list --json ${i.dim("Machine-readable listing")}`)}async function oc(e){if(e.flags.help){Nf();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":{fs();let r=us();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 Of(){console.log(`${i.bold("Usage:")} asm get <skill> [options]
|
|
280
283
|
|
|
281
284
|
Resolve a skill and write its SKILL.md body to stdout. Nothing is installed:
|
|
282
285
|
no provider directory, no library entry, no residency in any system prompt.
|
|
@@ -294,9 +297,16 @@ Index, registry and remote sources are fetched into a temp clone, scanned with
|
|
|
294
297
|
the same pre-install security scan \`asm install\` runs, and deleted. The body
|
|
295
298
|
goes to stdout; provenance and the security verdict go to stderr.
|
|
296
299
|
|
|
300
|
+
With --path, copy the full selected directory (scripts, templates, assets, etc.)
|
|
301
|
+
into an ASM-owned borrow and print its absolute path instead. The copy survives
|
|
302
|
+
process exit. Later run asm cleanup <borrowed-path>; originals are never removed.
|
|
303
|
+
No --keep is needed. Use asm install for permanent provider/library installation.
|
|
304
|
+
|
|
297
305
|
${i.bold("Options:")}
|
|
306
|
+
--path Borrow the full skill directory, not just its body
|
|
298
307
|
--json Output {name, description, tier, source, commit,
|
|
299
|
-
tokenCount, security, content} as a JSON object
|
|
308
|
+
tokenCount, security, content} as a JSON object;
|
|
309
|
+
--path returns path, sorted files and cleanup argv instead of content
|
|
300
310
|
--machine Stable machine-readable v1 envelope
|
|
301
311
|
--audit Also print the full security audit report (stderr),
|
|
302
312
|
for any resolved skill, not only fetched ones
|
|
@@ -311,24 +321,20 @@ ${i.bold("Examples:")}
|
|
|
311
321
|
asm get code-review > SKILL.md ${i.dim("Save it without installing")}
|
|
312
322
|
asm get github:owner/repo:skills/review ${i.dim("Fetch a remote skill")}
|
|
313
323
|
asm get owner/review --audit ${i.dim("Show the full security audit")}
|
|
314
|
-
asm get code-review --json ${i.dim("Structured output")}
|
|
315
|
-
|
|
316
|
-
|
|
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:
|
|
324
|
+
asm get code-review --json ${i.dim("Structured output")}
|
|
325
|
+
asm get --path code-review ${i.dim("Borrow the full directory")}
|
|
326
|
+
asm cleanup /absolute/borrowed-path ${i.dim("Remove only that borrow")}`)}async function Df(e,t){try{let{name:r,description:s}=await pe(e);return{name:r,description:s}}catch(r){let s=(await Ke(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
327
|
`+o.map(n=>` asm get ${t}:${n.relPath}`).join(`
|
|
319
|
-
`),{cause:r})}throw r}}async function
|
|
320
|
-
`));let s=await
|
|
321
|
-
`)}e.flags.machine?process.stdout.write(B("get",
|
|
322
|
-
`):e.flags.json?process.stdout.write(j(
|
|
323
|
-
`):(
|
|
328
|
+
`),{cause:r})}throw r}}async function kn(e,t,r){de(ne(t),t),process.stderr.write(i.dim(`Fetching ${t}\u2026
|
|
329
|
+
`));let s=await wn(t,e.flags.transport,!1);try{let o=ne(t),n=`github:${o.owner}/${o.repo}${o.ref?`#${o.ref}`:""}`,{name:a,description:l}=await Df(s.rootDir,n),c=await ys(bs(s.rootDir,"SKILL.md"),"utf-8"),d=nt(K(c)),u=await Zt(s.rootDir),p={risk:Xt(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:Le(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 vn(e,t,r,s={}){let o=K(e);return{name:s.name||o.name||r.split(/[/\\]/).pop()||r,description:s.description??(o.description||"").replace(/\s*\n\s*/g," ").trim(),dependencies:nt(o),tier:t,source:r,commit:s.commit??null,tokenCount:s.tokenCount??Le(e),security:null,content:e}}async function ws(e,t){if($t(t))return kn(e,t,"remote");if(We(t)||await Yt(t)){let l=ne(We(t)?t:`./${t}`).localPath,c;try{c=await ys(bs(l,"SKILL.md"),"utf-8")}catch{throw new Error(`No SKILL.md found in "${l}".`)}return{result:vn(c,"local",l),cleanup:null,dir:l}}let r=await D(),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 ys(bs(o.path,"SKILL.md"),"utf-8");return{result:vn(l,"installed",o.path,{name:o.name,description:o.description,tokenCount:o.tokenCount}),cleanup:null,dir:o.path}}let n=fr(await Qe(),t);if(n&&!n.missing){let l=await ys(bs(n.libraryPath,"SKILL.md"),"utf-8");return{result:vn(l,"library",n.libraryPath,{name:n.name,commit:n.commitHash||null}),cleanup:null,dir:n.libraryPath}}let a=await oa(t);if(a.status==="ambiguous")throw new gt(`"${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 kn(e,a.match.skill.installUrl,"index");if(_e(t)){let{resolved:l,multipleMatches:c,suggestions:d}=await Qr(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 kn(e,f,"registry")}if(c.length>0)throw new gt(`"${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 nc(e){if(e.flags.help){Of();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 ws(e,r);o=n.cleanup;let a=n.result;if(e.flags.audit){let c=await $e(n.dir,a.name,n.owner,n.repo);process.stderr.write(Ze(c)+`
|
|
330
|
+
`)}let l=e.flags.getPath?await Ia(r,n.dir,a):a;e.flags.machine?process.stdout.write(B("get",l,t)+`
|
|
331
|
+
`):e.flags.json?process.stdout.write(j(l)+`
|
|
332
|
+
`):"path"in l?(process.stderr.write(Ts(l)),process.stdout.write(ti(l))):(process.stderr.write(Ts(a)),process.stdout.write(a.content),a.content.endsWith(`
|
|
324
333
|
`)||process.stdout.write(`
|
|
325
|
-
`))}catch(n){let a=n
|
|
334
|
+
`))}catch(n){let a=A(n)||String(n),l=n instanceof gt?n.candidates:void 0;if(e.flags.machine)process.stdout.write(W("get",l?q.INVALID_ARGUMENT:q.SKILL_NOT_FOUND,a,t,l?{candidates:l}:void 0)+`
|
|
326
335
|
`);else if(w(a),l)for(let c of l)process.stderr.write(` ${i.cyan("\u2022")} ${c}
|
|
327
336
|
`);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()}}
|
|
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]
|
|
337
|
+
`));process.exitCode=1}finally{o&&await o(),s()}}async function ic(e){if(e.flags.help){console.log(ri());return}let t=performance.now();if(e.flags.dryRun){let s="asm cleanup does not support --dry-run. Re-run without it to remove the borrow, or leave the directory in place.";e.flags.machine?console.log(W("cleanup",q.INVALID_ARGUMENT,s,t)):w(s),process.exitCode=2;return}if(!e.subcommand||e.positional.length){let s="Expected exactly one argument: <borrowed-path>. Run asm cleanup --help for usage.";e.flags.machine?console.log(W("cleanup",q.INVALID_ARGUMENT,s,t)):w(s),process.exitCode=2;return}let r=await Ca(e.subcommand);e.flags.machine?console.log(r.status==="refused"?W("cleanup",q.INVALID_ARGUMENT,Cr(r),t,r):B("cleanup",r,t)):e.flags.json?console.log(j(r)):r.status==="refused"?w(Cr(r)):console.log(Cr(r)),r.status==="refused"&&(process.exitCode=1)}function Mf(){console.log(`${i.bold("Usage:")} asm deps <subcommand> [arguments] [options]
|
|
332
338
|
|
|
333
339
|
Discover and acquire optional skill dependencies with caller-owned leases.
|
|
334
340
|
ASM returns a directly usable path; it does not launch or supervise the agent.
|
|
@@ -353,7 +359,7 @@ ${i.bold("Examples:")}
|
|
|
353
359
|
asm deps discover parent-skill --json
|
|
354
360
|
asm deps acquire code-review --session run-123 --json
|
|
355
361
|
asm deps release --session run-123 --json
|
|
356
|
-
asm deps cleanup --stale-before 2026-09-08T00:00:00Z --dry-run --json`)}function
|
|
362
|
+
asm deps cleanup --stale-before 2026-09-08T00:00:00Z --dry-run --json`)}function ac(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 lc(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 ks(e,t,r){console.log(e.flags.json?j(t):r)}async function Ff(e){let t=ac(e,"parent");if(!t)return;let r=await ws(e,t);try{let s={name:r.result.name,source:r.result.source,dependencies:r.result.dependencies};ks(e,s,si(s))}finally{await r.cleanup?.()}}async function jf(e){let t=ac(e,"dependency"),r=lc(e);if(!t||!r)return;let s=await eo(r,async o=>{let n=await o.find(t);if(n)return n;let a=await ws(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?.()}});ks(e,s,oi(s))}async function _f(e){let t=lc(e);if(!t)return;let r=await qr(t);ks(e,r,ni(r)),r.errors.length>0&&(process.exitCode=1)}async function Uf(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 Ra(r,e.flags.dryRun);ks(e,s,ii(s)),s.errors.length>0&&(process.exitCode=1)}async function cc(e){if(e.flags.help){Mf();return}try{switch(e.subcommand){case"discover":await Ff(e);return;case"acquire":await jf(e);return;case"release":await _f(e);return;case"cleanup":await Uf(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 dc}from"path";function Bf(){console.log(`${i.bold("Usage:")} asm uninstall <skill-name> [options]
|
|
357
363
|
|
|
358
364
|
Remove a skill and its associated rule files. Shows a removal plan
|
|
359
365
|
before proceeding and asks for confirmation.
|
|
@@ -369,21 +375,21 @@ ${i.bold("Examples:")}
|
|
|
369
375
|
asm uninstall code-review ${i.dim("Remove with confirmation")}
|
|
370
376
|
asm uninstall code-review -y ${i.dim("Remove without confirmation")}
|
|
371
377
|
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
|
|
373
|
-
${i.bold("Proceed with removal?")} [y/N] `);let m=await
|
|
374
|
-
Done.`))}import{realpath as
|
|
375
|
-
`)}
|
|
378
|
+
asm uninstall code-review -p claude ${i.dim("Remove from Claude only")}`)}async function uc(e){if(e.flags.help){Bf();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 D(),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=wi(t,s,r,o),a=await vi(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=ki(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")} ${Te(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(`
|
|
379
|
+
${i.bold("Proceed with removal?")} [y/N] `);let m=await H();m.toLowerCase()!=="y"&&m.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let u;try{u=await Or(n,void 0,d?.needed?d:void 0)}catch(m){let g=m?.log,h=Array.isArray(g)?g:[];for(let y of h)console.error(y);w(A(m)||"Uninstall failed."),process.exit(1)}for(let m of u)console.error(m);let p=new Set(n.directories.map(m=>dc(m.path))),f=l.filter(m=>!p.has(dc(m.originalPath)));try{c&&f.length>0?d?.needed&&!d.repointOnly&&await hi(t,d.toProvider):await gi(t)}catch{}console.error(i.green(`
|
|
380
|
+
Done.`))}import{realpath as pg}from"fs/promises";import{resolve as yc,sep as bc}from"path";import{readdir as Vf,stat as Hf}from"fs/promises";import{join as qf}from"path";function et(e,t,r=20){let s=Math.round(e/t*r),o=r-s;return i.green("#".repeat(s))+i.dim("-".repeat(o))}function Sn(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=In(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 $n(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=In(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 xn(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=In(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 Pn(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(J(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} ${et(n,s,20)}`)}t.push("")}return t.push(""),t.join(`
|
|
381
|
+
`)}function Rn(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(J(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} ${et(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(`
|
|
382
|
+
`)}function En(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(J(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} ${et(n,s,20)}`)}t.push("")}return t.push(""),t.join(`
|
|
383
|
+
`)}function In(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(Gf(r,l)){s.push(n);break}return s.length>0?s:["general"]}function Gf(e,t){return t.length<=3?new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(e):e.includes(t)}var mc=10;function vs(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 pc(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 Cn(e,t=mc){let r=new Map,s=new Map,o=[],n=0,a=0;for(let u of e){let p=Ae(u),f=ot(u);n+=p,a+=f,pc(r,u.provider,u.providerLabel||u.provider,p,f),pc(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:vs(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 Ln(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.
|
|
376
384
|
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(`
|
|
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=>
|
|
378
|
-
`)}function
|
|
379
|
-
`)}function
|
|
380
|
-
`)
|
|
381
|
-
`)}
|
|
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(`
|
|
385
|
+
`);let r=[...e.byProvider.map(l=>["provider",l])],s=Math.max(8,...r.map(([,l])=>l.label.length),5),o=e.byProvider.map(l=>J(l.residentTokens)),n=Math.max(...o.map(l=>l.length),J(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(" "+Pr(l.key,l.label.padEnd(s))+" "+String(l.skills).padStart(6)+" "+i.cyan(J(l.residentTokens).padStart(n))+" "+i.dim(J(l.bodyTokens)));t.push(i.dim(" "+"-".repeat(s+n+22))),t.push(" "+i.bold("Total".padEnd(s))+" "+String(e.totalSkills).padStart(6)+" "+i.cyan(J(e.totalResidentTokens).padStart(n))+" "+i.dim(J(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(J(l.residentTokens).padStart(n))+" "+i.dim(J(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=>J(u.residentTokens).length));for(let u of e.heaviestResident)t.push(" "+u.name.padEnd(l)+" "+i.cyan(J(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: ${J(e.medianResidentTokens)}`)),t.push(i.dim(` Run ${i.bold("asm audit residency")} for demotion advice`)),t.push("")}return t.join(`
|
|
386
|
+
`)}async function Wf(e){let t=0;try{let s=(await Vf(e,{recursive:!0})).map(async n=>{try{let a=await Hf(qf(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 gc(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+=Ae(u),a+=ot(u);let p=await Wf(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 Jf(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`}var fc={claude:"Claude Code",codex:"Codex",openclaw:"OpenClaw",agents:"Agents"};function hc(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(Jf(e.totalDiskBytes))}`),t.push(` ${i.bold("Resident:")} ${i.cyan(J(e.totalResidentTokens))} ${i.dim("(every message)")}`),t.push(` ${i.bold("Bodies:")} ${i.cyan(J(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])=>(fc[c]||c).length));for(let[c,d]of r){let u=fc[c]||c,p=Pr(c,u.padEnd(o)),f=String(d).padStart(4);t.push(` ${p} ${f} ${et(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} ${et(e.byScope.global,n)}`),t.push(` ${"project".padEnd(o)} ${l} ${et(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(`
|
|
387
|
+
`)}var Kf=new Set(["plugin","codex-plugin"]),zf=40,Yf=2,Zf=15,Xf=3;function Qf(e){let t=e.slice(0,Xf).map(s=>`${s.provider}/${s.scope}`),r=e.length-t.length;return r>0?`${t.join(", ")}, +${r} more`:t.join(", ")}function eg(e,t){let r=yc(e),s=yc(t);return r===s?!1:s.startsWith(r.endsWith(bc)?r:r+bc)}function tg(){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 rg(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(sg(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 sg(e){return Ar().providers.some(t=>t.name===e)}function wc(e,t={}){let r=t.librarySkillsDir??"",s=t.limit??0,o=e.map(f=>Ae(f)),n=o.reduce((f,m)=>f+m,0),a=vs(o),l=e.filter(f=>!Kf.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(zf,a*Yf),p=[];for(let[f,m]of d){let g=m[0],h=Ae(g),y=m.reduce((S,C)=>S+Ae(C),0),b=m.reduce((S,C)=>S+ot(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&&eg(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:`${J(h)} resident \xB7 ${S}`})}$.length>1&&v.push({id:"redundant-activation",detail:`resident in ${$.length} places (${Qf($)}) \xB7 each pays ${J(h)}`}),v.length!==0&&p.push({name:g.name,dirName:f,residentTokens:h,totalResidentTokens:y,bodyTokens:b,score:y,instances:$,reasons:v,action:rg(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:tg()}}function kc(e,t=Zf){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(`
|
|
388
|
+
`);if(r.push(` ${i.bold("Resident total:")} ${i.cyan(J(e.totalResidentTokens))} `+i.dim(`across ${e.totalSkills} skill(s), every message`)),r.push(` ${i.bold("Median skill:")} ${i.cyan(J(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(`${J(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(`
|
|
389
|
+
`)}var og=.35,$c=.55,xc=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 ng(e){let t=new Set;for(let r of ce(e))xc.has(r)||t.add(r);return t}function ig(e){let t=new Set;for(let r of ce(e))xc.has(r)||t.add(r);return t}function ag(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 vc(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 lg(e,t,r,s,o){return .6*vc(e,r,o)+.4*vc(t,s,o)}function cg(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>=$c?"Very similar":"Substantially overlapping"} \u2014 shared terms: ${a}${l}`}function dg(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 Sc(e){return{name:e.name,dirName:e.dirName,provider:e.provider,providerLabel:e.providerLabel||e.provider,scope:e.scope,path:e.path}}function ug(e,t){return Nt(e.dirName)===Nt(t.dirName)||!!e.name&&!!t.name&&Nt(e.name)===Nt(t.name)}function Pc(e,t=og){let r=dg(e),s=r.map(l=>ng(l.description)),o=r.map(l=>ig(l.name)),n=ag(s),a=[];for(let l=0;l<r.length;l++)for(let c=l+1;c<r.length;c++){if(ug(r[l],r[c]))continue;let d=lg(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:Sc(r[l]),b:Sc(r[c]),score:d,highConfidence:d>=$c,reason:cg(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 Rc(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
390
|
`);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}) ${
|
|
386
|
-
`)}function
|
|
391
|
+
`);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}) ${Te(r.a.path)}`)),t.push(i.dim(` ${r.b.providerLabel} (${r.b.scope}) ${Te(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(`
|
|
392
|
+
`)}function Ec(e){return JSON.stringify(e,null,2)}function mg(){console.log(`${i.bold("Usage:")} asm audit [subcommand] [options]
|
|
387
393
|
|
|
388
394
|
Detect duplicate skills or run security audits on installed/remote skills.
|
|
389
395
|
|
|
@@ -416,15 +422,15 @@ ${i.bold("Examples:")}
|
|
|
416
422
|
asm audit security code-review --json ${i.dim("Output audit as JSON")}
|
|
417
423
|
asm audit security code-review --machine ${i.dim("Machine-readable v1 envelope output")}
|
|
418
424
|
asm audit security https://github.com/user/skills/tree/main/skills/agent-config
|
|
419
|
-
${i.dim("Audit a skill from a subfolder URL")}`)}async function
|
|
420
|
-
Auto-removing duplicates...`));let a=0,l=0;for(let c of n.duplicateGroups){let d
|
|
425
|
+
${i.dim("Audit a skill from a subfolder URL")}`)}async function Ic(e){if(e.flags.help){mg();return}let t=performance.now(),r=e.subcommand??"duplicates";if(r==="security"){await hg(e,t);return}if(r==="residency"){await fg(e,t);return}if(r==="overlap"){await gg(e,t);return}r!=="duplicates"&&(w(`Unknown audit subcommand: "${r}". Use: duplicates, overlap, security, residency`),process.exit(2));let s=await D(),o=await V(s,"both");await Promise.all(o.map(Si));let n=Dr(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(Pi(n));return}if(console.log(xi(n)),e.flags.yes&&n.duplicateGroups.length>0){console.error(i.bold(`
|
|
426
|
+
Auto-removing duplicates...`));let a=0,l=0;for(let c of n.duplicateGroups){let d=$i(c.instances),u=d[0],p=_s(u);for(let f=1;f<d.length;f++){let m=d[f],g=_s(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 ${Te(m.path)} \u2014 ${$}. Kept ${Te(u.path)}. Re-run with --force to remove it anyway.`));continue}let y=bi(m,s),b=await Or(y,u.path);for(let $ of b)console.error($);a++}}l>0&&console.error(i.yellow(`
|
|
421
427
|
${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
|
|
423
|
-
Usage: asm audit security <name|github:owner/repo> [--all]`),process.exit(2))}async function
|
|
424
|
-
`);let a=[];for(let l of n){console.error(` Scanning ${i.bold(l.name)}...`);let c=await
|
|
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
|
|
426
|
-
`);let l=await
|
|
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
|
|
428
|
+
Done. Removed ${a} duplicate cop${a===1?"y":"ies"}.`))}}async function fg(e,t){let r=await D(),s=await V(r,e.flags.scope),o=Pe();try{o=await pg(o)}catch{}let n=wc(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(kc(n))}async function gg(e,t){let r=await D(),s=await V(r,"both"),o=Pc(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(Ec(o));return}console.log(Rc(o))}async function hg(e,t){let r=e.positional[0];e.flags.all?await yg(e,t):r?r.startsWith("github:")||r.startsWith("https://github.com/")?await bg(e,r,t):await wg(e,r,t):(e.flags.machine&&(console.log(W("audit security",q.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.
|
|
429
|
+
Usage: asm audit security <name|github:owner/repo> [--all]`),process.exit(2))}async function yg(e,t){let r=await D(),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":""}...
|
|
430
|
+
`);let a=[];for(let l of n){console.error(` Scanning ${i.bold(l.name)}...`);let c=await $e(l.realPath,l.name);a.push(c)}if(e.flags.machine)console.log(B("audit security",Fr(a),t));else if(e.flags.json)console.log(JSON.stringify(a,null,2));else{for(let c of a)console.log(Ze(c));let l={safe:0,caution:0,warning:0,dangerous:0};for(let c of a)l[c.verdict]++;console.log(i.bold(`
|
|
431
|
+
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 bg(e,t,r){let s=null;try{let o=ne(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 ke(),o=await Je(o),console.error(`Cloning ${t} for audit...`),s=await ve(o,e.flags.transport);let{join:n}=await import("path"),a=o.subpath?n(s,o.subpath):s;try{Ie(s,a,t)}catch(d){throw await Z(s),s=null,d}let{name:l}=await pe(a),c=await $e(a,l,o.owner,o.repo);e.flags.machine?console.log(B("audit security",Fr([c]),r)):e.flags.json?console.log(ts(c)):console.log(Ze(c))}catch(o){let n=A(o);e.flags.machine&&(console.log(W("audit security",q.AUDIT_FAILED,n,r)),process.exit(1)),w(n),process.exit(1)}finally{s&&await Z(s)}}async function wg(e,t,r){let s=await D(),n=(await V(s,e.flags.scope)).filter(c=>c.dirName===t);n.length===0&&(e.flags.machine&&(console.log(W("audit security",q.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)}...
|
|
432
|
+
`);let l=await $e(a.realPath,a.name);e.flags.machine?console.log(B("audit security",Fr([l]),r)):e.flags.json?console.log(ts(l)):console.log(Ze(l))}import{relative as vg}from"path";async function Ss(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 bt({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 Cc(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:
|
|
433
|
+
`));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 Ce({items:n});if(a.length===0)throw new Error("No skills selected. Aborting.");return a.map(l=>e[l])}import{relative as kg}from"path";function Lc(){console.log(`${i.bold("Usage:")} asm install <source> [options]
|
|
428
434
|
|
|
429
435
|
Install a skill from a GitHub repository, the curated registry, or a local path.
|
|
430
436
|
|
|
@@ -504,35 +510,35 @@ ${i.bold("Subfolder URL:")}
|
|
|
504
510
|
${i.bold("Vercel skills CLI:")}
|
|
505
511
|
asm install github:user/skills --method vercel --skill my-skill
|
|
506
512
|
asm install https://github.com/user/skills -m vercel --skill my-skill -y
|
|
507
|
-
${i.dim("Delegates to npx skills add for Vercel tracking, then registers in asm")}`)}async function
|
|
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:")} ${
|
|
513
|
+
${i.dim("Delegates to npx skills add for Vercel tracking, then registers in asm")}`)}async function Ac(e,t,r,s,o,n,a,l,c="global"){let d=await pe(s),u=await Zt(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 go(m,a.name,n),y?h="LINK_AVAILABLE":h="NEW");let $=er(t,r,s,m,a,e.flags.force||b,c),v=Xt(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 Tc(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(`
|
|
514
|
+
${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:")} ${qn(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
515
|
${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
|
|
511
|
-
${i.cyan(`[Step ${c}/${l}]`)} ${i.bold(p)}`),u=()=>{n?
|
|
512
|
-
${i.cyan("\u25CF")} Resolving "${i.bold(o)}" from registry...`);let{resolved:R,multipleMatches:x,suggestions:
|
|
513
|
-
${i.yellow("\u26A0")} Multiple skills found for "${i.bold(o)}":`);let I=x.slice(0,5);for(let
|
|
514
|
-
Select a skill [1-${I.length}]: `;process.stderr.write(L);let
|
|
515
|
-
Did you mean: ${
|
|
516
|
-
`);for(let L=0;L<x.length;L++){let
|
|
516
|
+
${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 Qt(e,t):await yt(e)}async function Oc(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=ct(kg(a,t.plan.sourceDir)),p=await mn({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 An(e){if(e.flags.help){Lc();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++,`
|
|
517
|
+
${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(!We(o)&&await Yt(o)&&(o=`./${o}`),_e(o)){console.info(`
|
|
518
|
+
${i.cyan("\u25CF")} Resolving "${i.bold(o)}" from registry...`);let{resolved:R,multipleMatches:x,suggestions:O}=await Qr(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(`
|
|
519
|
+
${i.yellow("\u26A0")} Multiple skills found for "${i.bold(o)}":`);let I=x.slice(0,5);for(let xe=0;xe<I.length;xe++){let Be=I[xe];console.info(` ${i.cyan(`${xe+1}.`)} ${i.bold(`${Be.author}/${Be.name}`)} \u2014 ${Be.description}`)}process.stdin.isTTY||(w(`Ambiguous skill name "${o}". Use a scoped name: asm install author/name`),process.exit(2));let L=`
|
|
520
|
+
Select a skill [1-${I.length}]: `;process.stderr.write(L);let z=await new Promise(xe=>{let Be="",xr=!1,Jd=setTimeout(()=>{xr||(xr=!0,process.stdin.removeListener("data",Is),xe(Be.trim()))},3e4);function Is(Kd){Be=Kd.toString().trim(),xr||(xr=!0,clearTimeout(Jd),process.stdin.removeListener("data",Is),xe(Be))}process.stdin.setEncoding("utf-8"),process.stdin.on("data",Is)}),re=parseInt(z,10);(isNaN(re)||re<1||re>I.length)&&(w("Invalid selection. Aborting."),process.exit(2));let ie=I[re-1];a="registry";let Et=ie.repository.replace("https://github.com/","");o=ie.skill_path?`github:${Et}#${ie.commit}:${ie.skill_path}`:`github:${Et}#${ie.commit}`,console.info(` ${i.green("\u2713")} Selected: ${i.bold(`${ie.author}/${ie.name}`)} @ ${ie.commit.slice(0,7)}`)}else bo(o)?(w(`Skill "${o}" not found in the registry.`),O.length>0&&console.error(`
|
|
521
|
+
Did you mean: ${O.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=ne(o);if(!p.isLocal&&(de(p,o),zt(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(O){throw O?.code==="ENOENT"?new Error(`Path does not exist: ${R}`,{cause:O}):O}}else await ke(),p=await Je(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 uo();let R=mo(p),x=e.flags.path||null;console.info(` ${i.dim(`npx skills add ${R}${x?` --skill ${x}`:""}`)}`);let{stdout:O,stderr:I}=await po(R,x);O.trim()&&console.info(` ${i.dim(O.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 D(),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: ${Pe()}`)}`)}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 Ss({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 ve(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=[],M=!1,G=b,N="",U=!1;if(S){let R=$(b,S);if(!f)try{Ie(b,R,o)}catch(O){throw n&&(await Z(n),n=null),O}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:O}=await import("fs/promises");try{if(!(await O(R)).isDirectory())throw new Error(`No SKILL.md found at path "${S}" in the repository.`)}catch(I){throw I?.code==="ENOENT"?new Error(`No SKILL.md found at path "${S}" in the repository.`,{cause:I}):I}M=!0,G=R,N=S}x&&(console.info(` Found skill at ${i.bold(S)}`),C=[{skillDir:R,nameOverride:e.flags.name}])}else{try{await pe(b),U=!0}catch{}if(U&&!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 U&&e.flags.all,M=!0}if(M){console.info(N?` No SKILL.md at ${i.bold(N)}. Scanning subdirectories...`:U?" Root SKILL.md found. Scanning for additional skills in subdirectories...":" No SKILL.md at root. Scanning subdirectories...");let R=await Ke(G),x=N?R.map(L=>({...L,relPath:`${N}/${L.relPath}`})):R;if(x.length===0)throw new Error(N?`No skills found under path "${N}". 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):
|
|
522
|
+
`);for(let L=0;L<x.length;L++){let z=i.cyan(` ${String(L+1).padStart(String(x.length).length)})`);console.info(`${z} ${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 O;if(e.flags.all&&(e.flags.yes||!process.stdin.isTTY))O=x.map(L=>L.relPath),console.info(` Selected all ${i.bold(String(O.length))} skills`);else if(process.stdin.isTTY)if(x.length===1)O=[x[0].relPath],console.info(` Auto-selected: ${i.bold(x[0].name)} ${i.dim(`v${x[0].version}`)}`);else{let L=x.map(re=>({label:re.name,hint:`v${re.version}${re.description?" "+re.description:""}`,checked:!!e.flags.all}));console.info("");let z=await Ce({items:L});if(z.length===0)throw new Error("No skills selected. Aborting.");O=z.map(re=>x[re].relPath),console.info(` Selected ${i.bold(String(O.length))} skill(s)`)}else{w(`Repository contains ${x.length} skills. Use --path <subdir> to pick one or --all to install all.
|
|
517
523
|
Available skills:
|
|
518
524
|
${x.map(L=>` --path ${L.relPath}`).join(`
|
|
519
|
-
`)}`),process.exit(2);return}let I=
|
|
520
|
-
`),
|
|
525
|
+
`)}`),process.exit(2);return}let I=oo(O,L=>L===""?ue(p.repo):zr(L));if(I.length>0){let L=I.map(re=>` - ${re.name}: ${re.paths.map(ie=>`"${ie}"`).join(", ")}`).join(`
|
|
526
|
+
`),z=new Error(`Duplicate skill names detected in selection:
|
|
521
527
|
${L}
|
|
522
|
-
Choose one path per skill name or install with --path.`);throw
|
|
523
|
-
${i.yellow("\u26A0")} ${i.bold(x.metadata.name)} is already installed in ${
|
|
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
|
|
525
|
-
${i.red("[!]")} ${i.bold(`Install ${
|
|
526
|
-
${i.bold(`Install ${
|
|
527
|
-
${i.yellow(`${
|
|
528
|
+
Choose one path per skill name or install with --path.`);throw z.duplicates=I,z}C=O.map(L=>({skillDir:$(b,L),nameOverride:O.length===1?e.flags.name:null})),c++}console.info(d("Inspecting skills"));let F=await V(m,"both"),k=[],E=C.length>1;for(let R=0;R<C.length;R++){let{skillDir:x,nameOverride:O}=C[R],I=await Ac(e,p,b,x,O,m,g,F,y);k.push(I),Tc(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,O=k.filter(L=>L.riskLevel==="safe").length,I=[];O>0&&I.push(i.green(`${O} 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 _=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 O=x.crossToolLink;console.info(`
|
|
529
|
+
${i.yellow("\u26A0")} ${i.bold(x.metadata.name)} is already installed in ${O.existingProviderLabel}.`),console.info(` Existing: ${i.dim(O.existingPath)}`),console.info(`
|
|
530
|
+
${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 H();I==="2"||I.toLowerCase()==="link"?(_.set(R,"link"),console.info(` ${i.green("\u2713")} Selected: Link from ${O.existingProviderLabel}`)):(_.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"&&_.set(R,"link");if(!e.flags.yes&&k.some((x,O)=>x.installStatus!=="LINK_AVAILABLE"||_.get(O)==="reinstall")){let x=k.some(z=>z.riskLevel==="high");process.stdin.isTTY||(w("Cannot prompt for confirmation in non-interactive mode. Use --yes to skip."),process.exit(2));let O=E?`${k.length} skills`:`"${k[0].metadata.name}"`,I=x?`
|
|
531
|
+
${i.red("[!]")} ${i.bold(`Install ${O}? Some have high-risk patterns.`)} [y/N] `:`
|
|
532
|
+
${i.bold(`Install ${O}?`)} [Y/n] `;process.stderr.write(I);let L=await H();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 oe=n?await yi(n):null,be=[];for(let R=0;R<k.length;R++){let x=k[R],O=E?i.dim(`[${R+1}/${k.length}]`)+" ":" ";if(_.get(R)==="link"&&x.crossToolLink){let I=x.crossToolLink;try{console.info(`${O}Linking ${i.bold(x.metadata.name)} from ${I.existingProviderLabel}...`);let L=await ho(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(`${O}${i.green("\u2713")} ${x.metadata.name} linked to ${i.dim(L)}`);try{await dt(x.metadata.name,{source:`link:${I.existingPath}`,commitHash:"linked",ref:null,installedAt:new Date().toISOString(),provider:g.name,sourceType:"local"})}catch{}}catch(L){let z=A(L);be.push({name:x.metadata.name,error:z}),console.error(`${O}${i.red("\u2717")} ${i.bold(x.metadata.name)} \u2014 ${i.red(z)}`)}continue}try{console.info(`${O}Installing ${i.bold(x.metadata.name)}...`);let I=e.flags.library?await Oc({inspection:x,source:p,isLocal:f,resolutionSource:a,commitHash:oe,scanBaseDir:b,force:s}):await Nc(x.plan,h);if(v.push(I),console.info(`${O}${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}`,z=f?"local":a==="registry"?"registry":"github";await dt(I.name,{source:L,commitHash:oe||"unknown",ref:p.ref||"main",installedAt:new Date().toISOString(),provider:x.plan.providerName,scope:x.plan.scope,skillPath:ct(vg(x.plan.tempDir,x.plan.sourceDir)),targetDir:x.plan.targetDir,sourceType:z,...a==="registry"?{registryName:I.name}:{}})}catch{}}catch(I){let L=A(I);be.push({name:x.metadata.name,error:L}),console.error(`${O}${i.red("\u2717")} ${i.bold(x.metadata.name)} \u2014 ${i.red(L)}`)}}if(process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u),be.length>0){console.error(`
|
|
533
|
+
${i.yellow(`${be.length} skill(s) failed to install:`)}`);for(let R of be)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
534
|
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){
|
|
535
|
+
${i.green(`Done! Installed ${v.length} skill(s) successfully.`)}`)}catch(p){process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);let f=A(p),m=p?.duplicates;if(e.flags.machine)t?.(),console.log(W("install",q.INSTALL_FAILED,f,r,m?{duplicates:m}:void 0));else if(e.flags.json){let g={success:!1,error:f};m&&(g.duplicates=m),console.log(JSON.stringify(g,null,2))}else w(f);process.exit(1)}finally{n&&await Z(n),t?.()}}function Sg(){console.log(`${i.bold("Usage:")} asm activate <skill> -p <tool> -s <scope> [options]
|
|
530
536
|
|
|
531
537
|
Link a centrally installed library skill into a provider skill folder.
|
|
532
538
|
|
|
533
539
|
${i.bold("Options:")}
|
|
534
540
|
-p, --tool <name> Provider to activate into (e.g., claude, codex)
|
|
535
|
-
-s, --scope <scope> Activation scope: global or project
|
|
541
|
+
-s, --scope <scope> Activation scope: global or project (default: prompt)
|
|
536
542
|
--name <name> Link name to create (default: library directory name)
|
|
537
543
|
-f, --force Replace an existing target
|
|
538
544
|
--json Output as JSON object
|
|
@@ -540,19 +546,19 @@ ${i.bold("Options:")}
|
|
|
540
546
|
|
|
541
547
|
${i.bold("Examples:")}
|
|
542
548
|
asm activate brainstorming -p codex -s project
|
|
543
|
-
asm activate brainstorming -p claude -s global --json`)}function
|
|
549
|
+
asm activate brainstorming -p claude -s global --json`)}function $g(){console.log(`${i.bold("Usage:")} asm deactivate <skill> -p <tool> -s <global|project> [options]
|
|
544
550
|
|
|
545
551
|
Remove a centrally activated library skill from a provider skill folder.
|
|
546
552
|
|
|
547
553
|
${i.bold("Options:")}
|
|
548
554
|
-p, --tool <name> Provider to deactivate from (e.g., claude, codex)
|
|
549
|
-
-s, --scope <scope>
|
|
555
|
+
-s, --scope <scope> Deactivation scope: global or project (default: prompt)
|
|
550
556
|
--json Output as JSON object
|
|
551
557
|
-V, --verbose Show debug output
|
|
552
558
|
|
|
553
559
|
${i.bold("Examples:")}
|
|
554
560
|
asm deactivate brainstorming -p codex -s project
|
|
555
|
-
asm deactivate brainstorming -p claude -s global --json`)}async function
|
|
561
|
+
asm deactivate brainstorming -p claude -s global --json`)}async function Dc(e){if(e.flags.help){Sg();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));let r=await Qe(),s=fr(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 D(),{provider:n}=await me(o,e.flags.provider,process.stdin.isTTY),a=await bt({scopeFlag:e.flags.scope,provider:n,isTTY:!!process.stdin.isTTY,yes:e.flags.yes}),l=a==="global"?n.global:n.project,c=ee(l),d=e.flags.name||s.dirName,u=await un({libraryPath:s.libraryPath,targetDir:c,activationName:d,force:e.flags.force}),p={name:d,skill:s.dirName,provider:n.name,scope:a,path:u.symlinkPath,target:u.targetPath};if(e.flags.json){console.log(JSON.stringify(p,null,2));return}console.log(`${i.green("\u2713")} activated ${d} (${n.name}/${a}) -> ${u.targetPath}`)}async function Mc(e){if(e.flags.help){$g();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));let r=await D(),s;try{s=(await me(r,e.flags.provider,process.stdin.isTTY)).provider}catch(n){let a=n instanceof Error?n.message:String(n);w(a),process.exit(2)}let o=await bt({scopeFlag:e.flags.scope,provider:s,isTTY:!!process.stdin.isTTY,yes:e.flags.yes});try{let n=o==="global"?s.global:s.project,a=ee(n),l=await dn({targetDir:a,activationName:t,provider:s.name,scope:o});if(e.flags.json){console.log(JSON.stringify(l,null,2));return}console.log(`${i.green("\u2713")} deactivated ${l.name} (${l.provider}/${l.scope}) -> ${l.target}`)}catch(n){let a=n instanceof Error?n.message:String(n);e.flags.json&&(console.log(JSON.stringify({error:a},null,2)),process.exit(1)),w(a),process.exit(1)}}function xg(){console.log(`${i.bold("Usage:")} asm library <subcommand> [options]
|
|
556
562
|
|
|
557
563
|
Manage centrally installed library skills.
|
|
558
564
|
|
|
@@ -568,8 +574,8 @@ ${i.bold("Options:")}
|
|
|
568
574
|
${i.bold("Examples:")}
|
|
569
575
|
asm library list ${i.dim("List local library skills")}
|
|
570
576
|
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
|
|
572
|
-
`))}function
|
|
577
|
+
asm library update --all --json ${i.dim("Update all and output as JSON")}`)}async function Fc(e){if(e.flags.help){xg();return}if(e.subcommand==="update"){await Eg(e);return}if(e.subcommand==="list"){let t=await Qe();if(e.flags.json){console.log(JSON.stringify(t,null,2));return}Pg(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 Pg(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(`
|
|
578
|
+
`))}function Rg(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 Eg(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 gn(e.flags.all?null:t);e.flags.json?console.log(JSON.stringify(r,null,2)):Rg(r),r.failedCount>0&&process.exit(1)}function Ig(){console.log(`${i.bold("Usage:")} asm config <subcommand>
|
|
573
579
|
|
|
574
580
|
Manage configuration. Config is stored at ~/.config/agent-skill-manager/.
|
|
575
581
|
|
|
@@ -585,10 +591,10 @@ ${i.bold("Options:")}
|
|
|
585
591
|
${i.bold("Examples:")}
|
|
586
592
|
asm config show ${i.dim("View current config")}
|
|
587
593
|
asm config edit ${i.dim("Edit in $EDITOR")}
|
|
588
|
-
asm config reset -y ${i.dim("Reset without confirmation")}`)}async function
|
|
594
|
+
asm config reset -y ${i.dim("Reset without confirmation")}`)}async function jc(e){if(e.flags.help){Ig();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 D();console.log(j(r));break}case"path":{console.log(At());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 H();s.toLowerCase()!=="y"&&s.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let r=Ar();await di(r),console.error(i.green("Config reset to defaults."));break}case"edit":{let r=process.env.VISUAL||process.env.EDITOR||"vi",[s,o]=Ri(r),n=At();await D();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 _c(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 yr,readdir as Cg,access as Jc,mkdir as Lg,cp as Tn,rm as Uc,rename as Bc,realpath as Nn,stat as On}from"fs/promises";import{join as Dn,basename as Ag,resolve as Gc}from"path";function Tg(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 yr(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: ${A(o)}`,{cause:o})}let r;try{r=JSON.parse(t)}catch{throw new Error("Manifest file is not valid JSON.")}let s=Tg(r);if(!s.valid)throw new Error(`Invalid manifest:
|
|
589
595
|
${s.errors.join(`
|
|
590
|
-
`)}`);return r}async function
|
|
591
|
-
`)}async function
|
|
596
|
+
`)}`);return r}async function Ng(e){try{return await Jc(e),!0}catch{return!1}}async function Vc(e,t){let r,s;try{[r,s]=await Promise.all([Nn(e),Nn(t)])}catch{r=Gc(e),s=Gc(t)}return process.platform==="win32"?r.toLowerCase()===s.toLowerCase():r===s}async function br(e){let t=new Map,r=new Set;async function s(o,n){let a=await Nn(o),l=process.platform==="win32"?a.toLowerCase():a;if(r.has(l))return;r.add(l);let c=await Cg(o,{withFileTypes:!0});for(let d of c){if(d.name===".git")continue;let u=n?`${n}/${d.name}`:d.name,p=Dn(o,d.name);if(d.isDirectory())await s(p,u);else if(d.isFile())t.set(u,p);else try{(await On(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 Og(e,t){try{let[r,s]=await Promise.all([br(e),br(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([yr(n),yr(a)]);if(!l.equals(c))return!1}return!0}catch{return!1}}async function Hc(e){try{let t=await br(e),r=0;for(let s of t.values())try{let o=await On(s);o.mtimeMs>r&&(r=o.mtimeMs)}catch{}return r===0&&(r=(await On(e)).mtimeMs),r}catch{return 0}}async function Dg(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 Mn(e){let[t,r]=await Promise.all([br(e.targetDir),br(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([yr(a),yr(l)]);if(d.equals(u))continue;if(fi.has(c)){o.push(`differs (binary): ${n}`);continue}if(d.length>js||u.length>js){o.push(`differs (too large to diff): ${n}`);continue}let p=os(d.toString("utf-8"),u.toString("utf-8"),n);p&&o.push(p)}catch{o.push(`differs (unreadable): ${n}`)}}return o.join(`
|
|
597
|
+
`)}async function qc(e,t){let r=`${e}.import-backup-${Date.now()}`;await Bc(e,r);try{await t(),await Uc(r,{recursive:!0,force:!0})}catch(s){try{await Uc(e,{recursive:!0,force:!0}),await Bc(r,e)}catch{}throw s}}function Mg(e,t){return e.providers.find(r=>r.name===t&&r.enabled)}function Fg(e,t,r,s){let o=Mg(e,t);if(!o)return null;let n=r==="global"?o.global:o.project,a=ee(n),l=Ag(s);return!l||l==="."||l===".."?null:Dn(a,l)}function Wc(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 zc(e,t,r){let s=r?.config??await D(),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=Fg(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 Ng(p);if(f&&!t.force&&!t.dryRun){let g=Wc(o,u);if(!g||await Vc(g.realPath,p)||await Og(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 Dg(u,g.realPath,p),y=t.onConflict?await t.onConflict(h):"skip";if(y==="use-imported")try{await qc(p,()=>Tn(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: ${A(b)}`,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=Wc(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 Vc(m.realPath,p)){n.push({skillName:u.name,provider:u.provider,scope:u.scope,status:"skipped",reason:"Already installed.",path:p});continue}try{await Lg(Dn(p,".."),{recursive:!0});let g=async()=>{if(u.isSymlink&&u.symlinkTarget)try{await Jc(u.symlinkTarget),await Ne(u.symlinkTarget,p),P(`import: symlinked "${u.name}" -> ${u.symlinkTarget} at ${p}`)}catch{await Tn(m.realPath,p,{recursive:!0}),P(`import: symlink target unreachable, copied "${u.name}" from ${m.realPath} to ${p}`)}else await Tn(m.realPath,p,{recursive:!0}),P(`import: copied "${u.name}" from ${m.realPath} to ${p}`)};f?await qc(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: ${A(g)}`})}}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 jg(){console.log(`${i.bold("Usage:")} asm export [options]
|
|
592
598
|
|
|
593
599
|
Export skill inventory as a portable JSON manifest. Useful for backup,
|
|
594
600
|
sharing, or scripting.
|
|
@@ -601,7 +607,7 @@ ${i.bold("Options:")}
|
|
|
601
607
|
${i.bold("Examples:")}
|
|
602
608
|
asm export ${i.dim("Export all skills")}
|
|
603
609
|
asm export -s global ${i.dim("Export global skills only")}
|
|
604
|
-
asm export > skills.json ${i.dim("Save to file")}`)}async function
|
|
610
|
+
asm export > skills.json ${i.dim("Save to file")}`)}async function Yc(e){if(e.flags.help){jg();return}let t=await D(),r=await V(t,e.flags.scope),s=_c(r);console.log(JSON.stringify(s,null,2))}function _g(){console.log(`${i.bold("Usage:")} asm import <file> [options]
|
|
605
611
|
|
|
606
612
|
Import skills from a previously exported JSON manifest. Recreates skill
|
|
607
613
|
installations based on the manifest metadata.
|
|
@@ -629,14 +635,14 @@ ${i.bold("Examples:")}
|
|
|
629
635
|
asm import skills.json --force ${i.dim("Overwrite existing skills")}
|
|
630
636
|
asm import skills.json -s global ${i.dim("Import only global skills")}
|
|
631
637
|
asm export > backup.json ${i.dim("Export first, then import later")}
|
|
632
|
-
asm import backup.json ${i.dim("Restore from backup")}`)}async function
|
|
638
|
+
asm import backup.json ${i.dim("Restore from backup")}`)}async function Zc(e,t={}){let{showDiff:r=!1,readAnswer:s=H,renderDiff:o=Mn,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
639
|
${d}
|
|
634
640
|
`:" (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?`
|
|
635
641
|
${u}
|
|
636
|
-
`:" (no textual differences found)"),c=!0}}}async function
|
|
637
|
-
${i.bold(`Conflict diff: ${s.skillName} (${s.provider}/${s.scope})`)} ${i.dim("local -> imported")}`),r(o||" (no textual differences found)")}}async function
|
|
638
|
-
${i.bold("Proceed?")} [y/N] `);let p=await
|
|
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
|
|
642
|
+
`:" (no textual differences found)"),c=!0}}}async function Xc(e,t=Mn,r=console.error){for(let s of e){if(!s.conflict)continue;let o=await t(s.conflict);r(`
|
|
643
|
+
${i.bold(`Conflict diff: ${s.skillName} (${s.provider}/${s.scope})`)} ${i.dim("local -> imported")}`),r(o||" (no textual differences found)")}}async function Qc(e){if(e.flags.help){_g();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(A(p)),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(`
|
|
644
|
+
${i.bold("Proceed?")} [y/N] `);let p=await H();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 zc(o,{force:e.flags.force,dryRun:!1,scopeFilter:e.flags.scope,onConflict:l?p=>Zc(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(`
|
|
645
|
+
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 Bg,access as Gg}from"fs/promises";import{join as Vg}from"path";function Hg(e){return`---
|
|
640
646
|
name: ${e}
|
|
641
647
|
description: ""
|
|
642
648
|
license: ""
|
|
@@ -657,7 +663,7 @@ as instructions for when and how to use this skill.
|
|
|
657
663
|
## Instructions
|
|
658
664
|
|
|
659
665
|
- Step-by-step instructions for the agent
|
|
660
|
-
`}async function
|
|
666
|
+
`}async function ed(e,t){await Ug(t,{recursive:!0});let r=Vg(t,"SKILL.md"),s=Hg(e);await Bg(r,s,"utf-8")}async function td(e){try{return await Gg(e),!0}catch{return!1}}function qg(){console.log(`${i.bold("Usage:")} asm init <name> [options]
|
|
661
667
|
|
|
662
668
|
Scaffold a new skill directory with a SKILL.md template. Creates a
|
|
663
669
|
ready-to-edit skill in the target tool's skill folder.
|
|
@@ -672,8 +678,8 @@ ${i.bold("Options:")}
|
|
|
672
678
|
${i.bold("Examples:")}
|
|
673
679
|
asm init my-skill ${i.dim("Scaffold (interactive tool)")}
|
|
674
680
|
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
|
|
676
|
-
${i.bold("Overwrite?")} [y/N] `);let o=await
|
|
681
|
+
asm init my-skill --path ./skills ${i.dim("Scaffold in custom directory")}`)}async function rd(e){if(e.flags.help){qg();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 D(),{provider:n}=await me(o,e.flags.provider,!!process.stdin.isTTY),{join:a}=await import("path"),{resolveProviderPath:l}=await import("./config-5X2UQBDB.js"),c=l(o.providers.find(d=>d.name===n.name).global);s=a(c,r)}if(await td(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}`)}
|
|
682
|
+
${i.bold("Overwrite?")} [y/N] `);let o=await H();o.toLowerCase()!=="y"&&o.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}await ed(r,s),console.error(i.green(`Done! Created skill "${r}" at ${s}`))}function Wg(){console.log(`${i.bold("Usage:")} asm stats [subcommand] [options]
|
|
677
683
|
|
|
678
684
|
Show aggregate skill metrics with provider distribution charts,
|
|
679
685
|
scope breakdown, disk usage, resident context cost, and duplicate summary.
|
|
@@ -700,7 +706,7 @@ ${i.bold("Examples:")}
|
|
|
700
706
|
asm stats --machine ${i.dim("Machine-readable v1 envelope output")}
|
|
701
707
|
asm stats repo anthropics/skills ${i.dim("Show indexed repo stats")}
|
|
702
708
|
asm stats author luongnv89 ${i.dim("Show indexed author stats")}
|
|
703
|
-
asm stats index ${i.dim("Show index-wide stats")}`)}async function
|
|
709
|
+
asm stats index ${i.dim("Show index-wide stats")}`)}async function sd(e){if(e.flags.help){Wg();return}let t=e.subcommand;if(t==="repo"){await Kg(e);return}if(t==="author"){await Yg(e);return}if(t==="index"){await Xg(e);return}let r=performance.now(),s=await D(),o=await V(s,e.flags.scope);if(e.flags.tokens){let l=Cn(o);if(e.flags.machine){console.log(B("stats tokens",l,r));return}if(e.flags.json){console.log(j(l));return}console.log(Ln(l));return}if(o.length===0&&!e.flags.json&&!e.flags.machine){console.log(" No installed skills.");return}let n=Dr(o),a=await gc(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(hc(a))}function Jg(){console.log(`${i.bold("Usage:")} asm stats repo <owner/repo> [options]
|
|
704
710
|
|
|
705
711
|
Show statistics for a specific indexed repository.
|
|
706
712
|
|
|
@@ -713,7 +719,7 @@ ${i.bold("Options:")}
|
|
|
713
719
|
|
|
714
720
|
${i.bold("Examples:")}
|
|
715
721
|
asm stats repo anthropics/skills
|
|
716
|
-
asm stats repo luongnv89/asm --json`)}async function
|
|
722
|
+
asm stats repo luongnv89/asm --json`)}async function Kg(e){if(e.flags.help){Jg();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 Se()).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=Sn([n]);if(a.length===0){console.log(`No stats for "${r}/${s}".`);return}e.flags.json?console.log(j(a[0])):console.log(Pn(a[0]))}function zg(){console.log(`${i.bold("Usage:")} asm stats author <owner> [options]
|
|
717
723
|
|
|
718
724
|
Show statistics for a specific author across all indexed repositories.
|
|
719
725
|
|
|
@@ -726,9 +732,9 @@ ${i.bold("Options:")}
|
|
|
726
732
|
|
|
727
733
|
${i.bold("Examples:")}
|
|
728
734
|
asm stats author anthropics
|
|
729
|
-
asm stats author luongnv89 --json`)}async function
|
|
735
|
+
asm stats author luongnv89 --json`)}async function Yg(e){if(e.flags.help){zg();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 Se(),s=$n(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
736
|
`);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(
|
|
737
|
+
${a}`)),process.exit(1)}e.flags.json?console.log(j(o)):console.log(Rn(o))}function Zg(){console.log(`${i.bold("Usage:")} asm stats index [options]
|
|
732
738
|
|
|
733
739
|
Show aggregate statistics across all indexed repositories.
|
|
734
740
|
|
|
@@ -738,7 +744,7 @@ ${i.bold("Options:")}
|
|
|
738
744
|
|
|
739
745
|
${i.bold("Examples:")}
|
|
740
746
|
asm stats index
|
|
741
|
-
asm stats index --json`)}async function
|
|
747
|
+
asm stats index --json`)}async function Xg(e){if(e.flags.help){Zg();return}let t=await Se();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=xn(t);e.flags.json?console.log(j(r)):console.log(En(r))}function Qg(){console.log(`${i.bold("Usage:")} asm link <path> [<path2> ...] [options]
|
|
742
748
|
|
|
743
749
|
Symlink a local skill directory into an agent's skill folder. Useful
|
|
744
750
|
for local development \u2014 changes to the source are reflected immediately.
|
|
@@ -762,15 +768,15 @@ ${i.bold("Examples:")}
|
|
|
762
768
|
asm link ./my-skill -p claude ${i.dim("Link to Claude Code")}
|
|
763
769
|
asm link ./my-skill --name alias ${i.dim("Link with custom name")}
|
|
764
770
|
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
|
|
766
|
-
${i.bold("Overwrite?")} [y/N] `);let o=await
|
|
771
|
+
asm link ./skill1 ./skill2 ./skill3 -p claude ${i.dim("Link multiple skills at once")}`)}async function eh(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}`)}
|
|
772
|
+
${i.bold("Overwrite?")} [y/N] `);let o=await H();return o.toLowerCase()!=="y"&&o.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0)),!0}async function $s(e,t,r,s){let{join:o}=await import("path"),n=o(t,r),a=await eh(n,s);return await Zr(e,t,r,a),{name:r,symlinkPath:n,targetPath:e}}async function od(e){if(e.flags.help){Qg();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 D(),{provider:h}=await me(g,e.flags.provider,!!process.stdin.isTTY),{resolveProviderPath:y}=await import("./config-5X2UQBDB.js"),b=y(g.providers.find(M=>M.name===h.name).global),{resolve:$,basename:v}=await import("path"),S=[],C=[];for(let M of t){let G=$(M),N=!1,U=null;try{await ao(G),N=!0}catch(F){let k=F instanceof Error?F.message:String(F);k.startsWith("Path does not exist")||k.startsWith("Path is not a directory")||k.startsWith("No SKILL.md found")||(U=k)}if(U){C.push({name:M,error:U}),e.flags.json||console.error(i.red(` Failed to process "${M}": ${U}`));continue}if(N){let F=v(G);try{let k=await $s(G,b,F,!!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:F,error:E}),e.flags.json||console.error(i.red(` Failed to link "${F}": ${E}`))}}else{let F;try{F=await lo(G)}catch(k){let E=k instanceof Error?k.message:String(k),_=E;E.startsWith("Path does not exist")&&_e(M)&&(_=`${E} \u2014 "${M}" looks like a registry name; try "asm install ${M}" first.`),C.push({name:M,error:_}),e.flags.json||console.error(i.red(` Failed to process "${M}": ${_}`));continue}if(F.length===0){let k=`No SKILL.md found in ${G} or its immediate subdirectories.`;C.push({name:M,error:k}),e.flags.json||console.error(i.red(` ${k}`));continue}for(let k of F)try{let E=await $s(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 _=E instanceof Error?E.message:String(E);C.push({name:k.name,error:_}),e.flags.json||console.error(i.red(` Failed to link "${k.name}": ${_}`))}}}e.flags.json?console.log(j({success:C.length===0,linked:S,failures:C})):C.length>0?console.error(i.yellow(`
|
|
767
773
|
${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
|
|
769
|
-
${i.bold(`Link ${l.length} skill(s)?`)} [Y/n] `);let g=await
|
|
774
|
+
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 ao(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 lo(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}`),_e(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 D(),{provider:d}=await me(c,e.flags.provider,!!process.stdin.isTTY),{resolveProviderPath:u}=await import("./config-5X2UQBDB.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 $s(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(`
|
|
775
|
+
${i.bold(`Link ${l.length} skill(s)?`)} [Y/n] `);let g=await H();(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 $s(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
776
|
${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
|
|
772
|
-
---`,3);return r===-1?"":t.slice(r+4)}import{readdir as
|
|
773
|
-
`,"utf-8"),P(`ingester: wrote index to ${u}`),{success:!0,repoIndex:c}}catch(s){return{success:!1,repoIndex:null,error:s
|
|
777
|
+
Done! Linked ${f.length} skill(s) successfully.`)),m.length>0&&process.exit(1)}import{writeFile as gh,mkdir as hh,unlink as yh,readFile as bh,readdir as wh}from"fs/promises";import{join as kr}from"path";function Fn(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 nd(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=Fn(a[0].relPath);for(let u=1;u<a.length;u++){let p=Fn(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:Fn(u.relPath).root})),reason:c.priority===4?"first occurrence (no priority match)":`${c.root} priority`})}return{kept:r,decisions:s}}var th=[{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 id(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"),rh(t).trim().length<20&&r.push("SKILL.md body too short (less than 20 chars of instructions)");for(let{label:o,pattern:n}of th)n.test(t)&&r.push(`malicious pattern detected: ${o}`);return{verified:r.length===0,reasons:r}}function rh(e){let t=e.trimStart();if(!t.startsWith("---"))return t;let r=t.indexOf(`
|
|
778
|
+
---`,3);return r===-1?"":t.slice(r+4)}import{readdir as sh,readFile as ad,stat as cd}from"fs/promises";import{join as jn}from"path";var oh=[{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"]}],ld=2,nh=80,ih=["asm-bundles.json","asm.bundle.json",".asm/bundles.json",".asm/bundle.json"],ah=["bundles","data/bundles",".asm/bundles"];function wr(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function dd(e,t,r){let s=wr(e),o=wr(t),n=wr(r),a=`${s}-${o}`;return n.startsWith(a)?n:`${a}-${n}`}function lh(e){return[e.name,e.description,e.relPath,e.installUrl].filter(Boolean).join(" ").toLowerCase()}function ch(e,t){let r=lh(e);return t.keywords.some(s=>r.includes(s))}function ud(e){return{name:e.name,installUrl:e.installUrl,description:e.description||void 0,version:e.version||void 0}}function dh(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 pd(e){return[...e].sort((t,r)=>t.name.localeCompare(r.name))}function _n(e){let t=[];if(!e.skills||e.skills.length<ld)return t;for(let r of oh){let s=e.skills.filter(n=>ch(n,r)).slice(0,nh);if(s.length<ld)continue;let o=dd(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,wr(e.owner),wr(e.repo)],skills:pd(s.map(ud)),sourceRepo:{owner:e.owner,repo:e.repo,repoUrl:e.repoUrl},inferred:!0})}return t}function uh(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=dh(o.map(c=>{if(typeof c=="string"){let f=n.get(c);return f?ud(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:dd(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:pd(a),sourceRepo:{owner:t.owner,repo:t.repo,repoUrl:t.repoUrl,relPath:r},explicit:!0}}async function ph(e){try{return(await cd(e)).isFile()}catch{return!1}}async function mh(e){try{return(await cd(e)).isDirectory()}catch{return!1}}async function fh(e){let t=[];for(let r of ih){let s=jn(e,r);if(await ph(s))try{t.push({relPath:r,data:JSON.parse(await ad(s,"utf-8"))})}catch{}}for(let r of ah){let s=jn(e,r);if(!await mh(s))continue;let o;try{o=await sh(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 ad(jn(s,n),"utf-8"))})}catch{}}}return t}async function md(e,t){let r=[],s=await fh(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=uh(l,t,o.relPath);c&&r.push(c)}}return xs(r)}function xs(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 fd(e){let t=e.bundles||[],r=_n(e);return xs([...t,...r])}var kh=8;async function vh(){let e=at();return await hh(e,{recursive:!0}),e}function Sh(e,t){return`github:${e.owner}/${e.repo}${e.ref?`#${e.ref}`:""}${t?`:${t}`:""}`}async function gd(e){await ke();let t;try{t=ne(e)}catch(s){return{success:!1,repoIndex:null,error:A(s)}}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:A(s)}}P(`ingester: cloning ${t.owner}/${t.repo}`);let r=null;try{r=await ve(t),P(`ingester: discovering skills in ${r}`);let s=await Ke(r);P(`ingester: found ${s.length} skills`);let{kept:o,decisions:n}=nd(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 or(o,kh,async p=>{let f=kr(a,p.relPath,"SKILL.md"),m="";try{m=await bh(f,"utf-8")}catch{P(`ingester: could not read SKILL.md at ${f}`)}let g=id(p,m);g.verified||P(`ingester: ${p.name} not verified: ${g.reasons.join(", ")}`);let h=typeof p.tokenCount=="number"?p.tokenCount:m?Le(m):void 0,y,b;if(m){let $;try{$=await wh(kr(a,p.relPath))}catch{$=void 0}try{let v=await vt({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:kr(a,p.relPath),skillMdPath:f},C=(await Promise.all(hr(gs()).map(async M=>(await M.applicable(v,{})).ok?hs(M,v):null))).filter(M=>M!==null).map(M=>tc(M,p.version||void 0));C.length>0&&(b=Object.fromEntries(C.filter(M=>M.providerId).map(M=>[M.providerId,M])))}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:Sh(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=xs([...await md(r,c),..._n(c)]);let d=await vh(),u=kr(d,`${t.owner}_${t.repo}.json`);return await gh(u,JSON.stringify(c,null,2)+`
|
|
779
|
+
`,"utf-8"),P(`ingester: wrote index to ${u}`),{success:!0,repoIndex:c}}catch(s){return{success:!1,repoIndex:null,error:A(s)}}finally{r&&await Z(r)}}async function hd(){return(await Se()).map(t=>({owner:t.owner,repo:t.repo,skillCount:t.skillCount,updatedAt:t.updatedAt})).sort((t,r)=>r.skillCount-t.skillCount)}async function yd(e,t){let r=at(),s=kr(r,`${e}_${t}.json`);try{return await yh(s),!0}catch{return!1}}var Pt=.55,Ps=.7;function bd(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 $h(e,t){let r=ce(e.description),s=ce(t.description),o=bd(r,s),n=ce(e.name),a=ce(t.name),l=bd(n,a);return .6*o+.4*l}function xh(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>=Ps?`Very similar descriptions (${a}/${l} shared tokens)`:r>=Pt?`Similar descriptions (${a}/${l} shared tokens)`:`Some overlapping concepts (${a}/${l} shared tokens)`}function Un(e,t=Pt){let r=[];for(let s=0;s<e.length;s++)for(let o=s+1;o<e.length;o++){let n=$h(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:xh(e[s].skill,e[o].skill,n)})}return r.sort((s,o)=>o.score-s.score),r}function wd(e,t=Pt){let r=Un(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 Ph(){console.log(`${i.bold("Usage:")} asm index <subcommand> [options]
|
|
774
780
|
|
|
775
781
|
Manage the skill index for searching available skills from indexed repos.
|
|
776
782
|
|
|
@@ -799,20 +805,20 @@ ${i.bold("Examples:")}
|
|
|
799
805
|
asm index overlap ${i.dim("Find overlapping skills")}
|
|
800
806
|
asm index overlap --threshold 0.6 ${i.dim("Custom threshold")}
|
|
801
807
|
asm index list ${i.dim("List indexed repos")}
|
|
802
|
-
asm index remove obra/superpowers ${i.dim("Remove from index")}`)}async function
|
|
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
|
|
804
|
-
`)}}break}case"list":{let r=await
|
|
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
|
|
808
|
+
asm index remove obra/superpowers ${i.dim("Remove from index")}`)}async function kd(e){if(e.flags.help){Ph();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 gd(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 _t(r||"",20,s):await _t(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:
|
|
809
|
+
`));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 Ir(a.skill.description,80))console.error(` ${d}`);let c=sa(a.skill);c.length>0&&console.error(` ${i.yellow(`\u26A0 Missing: ${c.join(", ")}`)}`),console.error(` ${i.green(`asm install ${a.skill.installUrl}`)}
|
|
810
|
+
`)}}break}case"list":{let r=await hd();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 ra();if(e.flags.json)console.log(j(r));else{console.error(i.bold(`Indexed Repositories (${s} total skills):
|
|
811
|
+
`));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 H();a.toLowerCase()!=="y"&&a.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}await yd(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??Pt,s=500,o=await Hs(),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=Un(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=wd(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
812
|
`)),l.length>0){console.error(i.yellow(` ${l.length} group(s):
|
|
807
813
|
`));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>=
|
|
809
|
-
`);for(let p of
|
|
810
|
-
`));for(let c of a.slice(0,20)){let d=c.score>=
|
|
814
|
+
`);for(let d of c.skills){let u=c.maxScore>=Ps?i.yellow(" [high overlap]"):"";console.error(` ${i.cyan(d.skill.name)} ${i.dim(`[${d.repo.owner}/${d.repo.repo}]`)}${u}
|
|
815
|
+
`);for(let p of Ir(d.skill.description,72))console.error(` ${p}`)}console.error("")}}console.error(i.yellow(` ${a.length} overlapping pair(s):
|
|
816
|
+
`));for(let c of a.slice(0,20)){let d=c.score>=Ps?i.red("HIGH"):c.score>=Pt?i.yellow("MED"):i.dim("LOW");console.error(` ${d} ${c.score.toFixed(3)} ${i.cyan(c.skillA.name)} \u2194 ${i.cyan(c.skillB.name)}
|
|
811
817
|
`),console.error(` ${c.repoA.owner}/${c.repoA.repo} \u2194 ${c.repoB.owner}/${c.repoB.repo}
|
|
812
|
-
`);for(let u of
|
|
813
|
-
`,"utf-8"),P(`bundle: saved to ${r}`),r}async function
|
|
818
|
+
`);for(let u of Ir(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 Rh,writeFile as Eh,readdir as vd,access as Sd,mkdir as Ih,rm as Ch}from"fs/promises";import{join as rt,resolve as $d,dirname as Lh}from"path";import{fileURLToPath as Ah}from"url";var Th=Ah(import.meta.url),Nh=Lh(Th),Rs=$d(Nh,"..","data","bundles");function Oh(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 xd(e,t,r,s,o){return{version:1,name:e,description:t,author:r,createdAt:new Date().toISOString(),skills:s,tags:o}}async function Pd(e,t){let r=t??await Oe(),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 tt(){return rt(Lr(),"bundles")}async function Dh(){await Ih(tt(),{recursive:!0})}function Sr(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 Bn(e){await Dh();let t=`${Sr(e.name)}.json`,r=rt(tt(),t);return await Eh(r,JSON.stringify(e,null,2)+`
|
|
819
|
+
`,"utf-8"),P(`bundle: saved to ${r}`),r}async function vr(e){let t;try{t=await Rh(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: ${A(o)}`,{cause:o})}let r;try{r=JSON.parse(t)}catch{throw new Error("Bundle file is not valid JSON.")}let s=Oh(r);if(!s.valid)throw new Error(`Invalid bundle:
|
|
814
820
|
${s.errors.join(`
|
|
815
|
-
`)}`);return r}async function
|
|
821
|
+
`)}`);return r}async function $r(e){if(e.includes("/")||e.includes("\\")||e.endsWith(".json")){let s=$d(e);return vr(s)}let t=`${Sr(e)}.json`,r=rt(tt(),t);try{return await vr(r)}catch(s){if(A(s).includes("Bundle file not found")){let o=rt(Rs,t);try{return await vr(o)}catch(n){if(A(n).includes("Bundle file not found")){let a=await Mh(e);if(a)return a;throw new Error(`Bundle file not found: ${r}`,{cause:n})}throw n}}throw s}}async function Rd(){let e=[];try{await Sd(Rs);let r;try{r=await vd(Rs)}catch{r=[]}for(let s of r){if(!s.endsWith(".json"))continue;let o=rt(Rs,s);try{let n=await vr(o);e.push(n)}catch{P(`bundle: skipping invalid predefined file ${o}`)}}}catch{}e.push(...await Ed());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 Ed(){try{return(await Se()).flatMap(t=>fd(t))}catch(e){return P(`bundle: failed to load repo-derived bundles: ${e}`),[]}}async function Mh(e){let t=Sr(e),r=await Ed();return r.find(s=>s.name===e)||r.find(s=>Sr(s.name)===t)||null}async function Id(){let e=[];try{await Sd(tt())}catch{return e}let t;try{t=await vd(tt())}catch{return e}for(let r of t){if(!r.endsWith(".json"))continue;let s=rt(tt(),r);try{let o=await vr(s);e.push(o)}catch{P(`bundle: skipping invalid file ${s}`)}}return e.sort((r,s)=>r.name.localeCompare(s.name)),e}async function Cd(e){let t=`${Sr(e)}.json`,r=rt(tt(),t);try{return await Ch(r),P(`bundle: removed ${r}`),!0}catch(s){if(s?.code==="ENOENT")return!1;throw s}}import{join as Fh}from"path";function jh(){console.log(`${i.bold("Usage:")} asm bundle <subcommand> [options]
|
|
816
822
|
|
|
817
823
|
Create, install, and manage curated skill bundles. A bundle is a reusable
|
|
818
824
|
recipe of skills for a particular workflow, domain, or project setup.
|
|
@@ -858,28 +864,28 @@ ${i.bold("Examples:")}
|
|
|
858
864
|
asm bundle modify my-workflow --add github:u/r ${i.dim("Add a skill to bundle")}
|
|
859
865
|
asm bundle modify my-workflow --remove skill ${i.dim("Remove a skill from bundle")}
|
|
860
866
|
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
|
|
862
|
-
`));let y=await
|
|
863
|
-
${i.bold("Description")} (optional, press Enter to skip): `);let h=await
|
|
867
|
+
asm bundle export my-workflow out.json ${i.dim("Export bundle to file")}`)}async function Ld(e){if(e.flags.help){jh();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 D(),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}":
|
|
868
|
+
`));let y=await Ce({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-6JXXQRLX.js"),d=await c(),u=await Promise.all(l.map(h=>Pd(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(`
|
|
869
|
+
${i.bold("Description")} (optional, press Enter to skip): `);let h=await H();h.trim()&&(p=h.trim()),process.stderr.write(`${i.bold("Author")} (optional, press Enter to skip): `);let y=await H();y.trim()&&(f=y.trim())}let m=xd(r,p,f,u),g=await Bn(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 $r(r)}catch(m){w(A(m)),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 D(),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
870
|
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
|
|
866
|
-
${i.bold(`Install ${m}?`)} [y/N] `);let g=await
|
|
867
|
-
Installing ${i.bold(m.name)}...`);try{(m.installUrl.startsWith("github:")||m.installUrl.startsWith("https://github.com/"))&&await
|
|
871
|
+
`)),{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 Cc(s.skills,{isTTY:!0,yes:!1})),a=await Ss({scopeFlag:e.flags.scope,provider:l,isTTY:!!process.stdin.isTTY,yes:!!e.flags.yes})}catch(m){w(A(m)),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(`
|
|
872
|
+
${i.bold(`Install ${m}?`)} [y/N] `);let g=await H();g.toLowerCase()!=="y"&&g.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let d=[];for(let m of n){console.error(`
|
|
873
|
+
Installing ${i.bold(m.name)}...`);try{(m.installUrl.startsWith("github:")||m.installUrl.startsWith("https://github.com/"))&&await ke();let h=ne(m.installUrl),y=!!h.isLocal,b=null;try{let $,v;if(y)$=h.localPath,v=h.localPath;else{de(h,m.installUrl),b=await ve(h,e.flags.transport),$=b,v=h.subpath?Fh(b,h.subpath):b;try{Ie(b,v,m.installUrl)}catch(G){throw await Z(b),b=null,G}}let S=await pe(v),C=ue(m.name||S.name||h.repo),M=er(h,$,v,C,l,e.flags.force,a);try{await fo(M.targetDir,M.force)}catch(G){if(A(G).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 G}c?await Qt(M,c):await yt(M),d.push({name:m.name,status:"installed"}),console.error(` ${i.green("+++")} ${m.name} installed`)}finally{b&&await Z(b)}}catch(g){let h=A(g);d.push({name:m.name,status:"failed",reason:h}),console.error(` ${i.red("!!!")} ${m.name}: ${h}`)}}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 Rd();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
874
|
`));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
|
|
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
|
|
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
|
|
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
|
|
873
|
-
About to publish "${I}" by ${L} to ${
|
|
875
|
+
${i.dim("Install a bundle with: asm bundle install <name>")}`)}return}let s=await Id();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}):
|
|
876
|
+
`));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 $r(r)}catch(o){w(A(o)),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(`
|
|
877
|
+
${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 H();o.toLowerCase()!=="y"&&o.toLowerCase()!=="yes"&&(console.error("Aborted."),process.exit(0))}let s;try{s=await Cd(r)}catch(o){w(A(o)),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 $r(r)}catch(p){w(A(p)),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 H();p.trim()&&(s.description=p.trim(),o=!0),process.stderr.write(`${i.bold("New author")} (Enter to keep current): `);let f=await H();f.trim()&&(s.author=f.trim(),o=!0),process.stderr.write(`${i.bold("New tags (comma-separated)")} (Enter to keep current): `);let m=await H();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 Bn(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 $r(r)}catch(c){w(A(c)),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 H();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)+`
|
|
878
|
+
`,"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 _h,realpath as Uh}from"fs/promises";import{join as Bh,resolve as Gh,relative as Vh}from"path";function Es(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 Hh(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\[/g,"\\[").replace(/\]/g,"\\]").replace(/</g,"<").replace(/>/g,">").replace(/\|/g,"\\|")}function Gn(e){return Hh(Es(e))}var st="luongnv89/asm-registry";async function qh(e){let t=Bh(e,"SKILL.md"),r;try{r=await _h(t,"utf-8")}catch{throw new Error(`No SKILL.md found in ${e}. Run "asm init" to create one.`)}let s=K(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 Wh(e){let{exitCode:t}=await se(["git","rev-parse","--git-dir"],{cwd:e});if(t!==0)throw new Error(`${e} is not inside a git repository.`)}async function Jh(e){let{stdout:t,exitCode:r}=await se(["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 Kh(e){let{stdout:t,exitCode:r}=await se(["git","rev-parse","--show-toplevel"],{cwd:e});if(r!==0)throw new Error("Failed to determine git repository root.");return t.trim()}async function zh(e){let{stdout:t,exitCode:r}=await se(["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 Yh(){let{exitCode:e}=await se(["gh","--version"]);if(e!==0)return{available:!1,authenticated:!1,login:null};let{exitCode:t}=await se(["gh","auth","status"]);if(t!==0)return{available:!0,authenticated:!1,login:null};let{stdout:r,exitCode:s}=await se(["gh","api","user","--jq",".login"]);return{available:!0,authenticated:!0,login:s===0?r.trim():null}}function Zh(e){switch(e){case"safe":case"caution":return"pass";case"warning":return"warning";case"dangerous":return"dangerous"}}function Ad(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 Xh(e){let t=Ad({metadata:e.metadata,author:e.metadata.creator||"unknown",commit:e.commit,repository:e.repository,skillPath:e.skillPath,securityVerdict:e.registryVerdict}),r=Xr(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 Td(e){let t=Gh(e.path);P(`publish: starting for ${t}`),await Wh(t);let r=await qh(t);P(`publish: parsed metadata for "${r.name}"`);let o=await(e._auditFn??$e)(t,r.name),n=Zh(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 Jh(t),l=await zh(t),c=await Kh(t),d=await Uh(t),u=Vh(c,d),p=u&&u!=="."?ct(u):void 0,m=await(e._checkGhCliFn??Yh)();if(!m.available||!m.authenticated){let I=m.available?"gh CLI not authenticated":"gh CLI not found";return Xh({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=Ad({metadata:r,author:g,commit:a,repository:l,skillPath:p,securityVerdict:n}),y=Xr(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=Es(r.name),L=Es(g);process.stderr.write(`
|
|
879
|
+
About to publish "${I}" by ${L} to ${st}.
|
|
874
880
|
Security verdict: ${n}
|
|
875
881
|
|
|
876
|
-
Proceed? [y/N] `);let
|
|
877
|
-
`)&&(process.stdin.removeListener("data",
|
|
878
|
-
`,S=Buffer.from(v,"utf-8").toString("base64"),{stdout:C,exitCode:
|
|
879
|
-
`),{stdout:
|
|
882
|
+
Proceed? [y/N] `);let z=await new Promise(re=>{let ie="",Et=xe=>{ie+=xe.toString(),ie.includes(`
|
|
883
|
+
`)&&(process.stdin.removeListener("data",Et),process.stdin.pause(),re(ie.trim()))};process.stdin.resume(),process.stdin.on("data",Et)});if(z.toLowerCase()!=="y"&&z.toLowerCase()!=="yes")return{success:!1,manifest:h,prUrl:null,error:"Publish aborted by user.",securityVerdict:n,securityReport:o}}P(`publish: forking ${st}`),await se(["gh","repo","fork",st,"--clone=false"]);let b=`publish/${g}/${r.name}`,$=`manifests/${g}/${r.name}.json`,v=JSON.stringify(h,null,2)+`
|
|
884
|
+
`,S=Buffer.from(v,"utf-8").toString("base64"),{stdout:C,exitCode:M}=await se(["gh","api",`repos/${g}/asm-registry/git/refs/heads/main`,"--jq",".object.sha"]);if(M!==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 G=C.trim(),{exitCode:N}=await se(["gh","api",`repos/${g}/asm-registry/git/refs`,"-X","POST","-f",`ref=refs/heads/${b}`,"-f",`sha=${G}`]);N!==0&&await se(["gh","api",`repos/${g}/asm-registry/git/refs/heads/${b}`,"-X","PATCH","-f",`sha=${G}`,"-f","force=true"]);let{stderr:U,exitCode:F}=await se(["gh","api",`repos/${g}/asm-registry/contents/${$}`,"-X","PUT","-f",`message=Publish ${g}/${r.name}`,"-f",`content=${S}`,"-f",`branch=${b}`]);if(F!==0){let{stdout:I,exitCode:L}=await se(["gh","api",`repos/${g}/asm-registry/contents/${$}?ref=${b}`,"-q",".sha"]),z=I.trim();if(L===0&&z){let{exitCode:re}=await se(["gh","api",`repos/${g}/asm-registry/contents/${$}`,"-X","PUT","-f",`message=Update ${g}/${r.name}`,"-f",`content=${S}`,"-f",`branch=${b}`,"-f",`sha=${z}`]);if(re!==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. ${U}`,securityVerdict:n,securityReport:o}}let k=Gn(r.name),E=Gn(r.description),_=Gn(r.license),Q=`Publish ${g}/${Es(r.name)}`,oe=[`## Skill: ${k}`,"",`**Author:** ${g}`,`**Version:** ${r.version}`,`**Description:** ${E}`,`**License:** ${_}`,`**Repository:** ${l}`,`**Commit:** \`${a}\``,`**Security verdict:** ${n}`,"","---","","*This PR was generated by `asm publish`.*"].join(`
|
|
885
|
+
`),{stdout:be,stderr:R,exitCode:x}=await se(["gh","pr","create","--repo",st,"--head",`${g}:${b}`,"--title",Q,"--body",oe]),O=null;if(x===0)O=be.trim();else{let I=R.match(/https:\/\/github\.com\/[^\s]+\/pull\/\d+/);I&&(O=I[0])}return O?{success:!0,manifest:h,prUrl:O,error:null,securityVerdict:n,securityReport:o}:{success:!1,manifest:h,prUrl:null,error:`Failed to create PR against ${st}. ${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 ${st} on GitHub`,` 2. Create branch: publish/${t.author}/${t.name}`,` 3. Add file: manifests/${t.author}/${t.name}.json`," 4. Paste the manifest below into that file",` 5. Open a PR against ${st}`,"",' Run "asm doctor" to fix your environment.',""," Generated manifest:",JSON.stringify(t,null,2).split(`
|
|
880
886
|
`).map(s=>` ${s}`).join(`
|
|
881
887
|
`)].join(`
|
|
882
|
-
`):""}function
|
|
888
|
+
`):""}function Qh(){console.log(`${i.bold("Usage:")} asm publish [path] [options]
|
|
883
889
|
|
|
884
890
|
Validate a skill, run a security audit, generate a registry manifest,
|
|
885
891
|
and open a PR against the asm-registry.
|
|
@@ -902,8 +908,8 @@ ${i.bold("Examples:")}
|
|
|
902
908
|
asm publish --dry-run ${i.dim("Preview manifest without side effects")}
|
|
903
909
|
asm publish --force ${i.dim("Override warning-level security findings")}
|
|
904
910
|
asm publish --json ${i.dim("Output as JSON")}
|
|
905
|
-
asm publish --machine ${i.dim("Machine-readable v1 envelope output")}`)}async function
|
|
906
|
-
`)),console.log(JSON.stringify(o.manifest,null,2));return}if(o.fallback){console.log(i.yellow("Manifest generated (gh CLI unavailable):")),console.log(
|
|
911
|
+
asm publish --machine ${i.dim("Machine-readable v1 envelope output")}`)}async function Od(e){if(e.flags.help){Qh();return}let t=e.flags.machine?le():void 0,r=performance.now(),s=e.subcommand||".";try{let o=await Td({path:s,dryRun:e.flags.dryRun,force:e.flags.force,yes:e.flags.yes});if(e.flags.machine){t?.(),o.success||(console.log(W("publish",q.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.
|
|
912
|
+
`)),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){let n=A(o);e.flags.machine&&(t?.(),console.log(W("publish",q.PUBLISH_FAILED,n,r)),process.exit(1)),e.flags.json&&(console.log(JSON.stringify({success:!1,manifest:null,pr_url:null,error:n,security_verdict:null},null,2)),process.exit(1)),w(n),process.exit(1)}}function ey(){console.log(`${i.bold("Usage:")} asm outdated [options]
|
|
907
913
|
|
|
908
914
|
Show which installed skills have newer versions available.
|
|
909
915
|
|
|
@@ -916,7 +922,7 @@ ${i.bold("Options:")}
|
|
|
916
922
|
${i.bold("Examples:")}
|
|
917
923
|
asm outdated ${i.dim("Show outdated skills")}
|
|
918
924
|
asm outdated --json ${i.dim("Output as JSON")}
|
|
919
|
-
asm outdated --machine ${i.dim("Machine-readable output")}`)}async function
|
|
925
|
+
asm outdated --machine ${i.dim("Machine-readable output")}`)}async function Dd(e){if(e.flags.help){ey();return}let t=e.flags.machine?le():void 0,r=performance.now();try{let s=await lr();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(Zo(s));return}let o=!e.flags.noColor&&process.stdout.isTTY!==!1;console.log(Yo(s,o)),s.outdatedCount>0&&(process.exitCode=1)}catch(s){let o=A(s);e.flags.machine&&(t?.(),console.log(W("outdated",q.UNKNOWN_ERROR,o,r)),process.exit(1)),w(o),process.exit(1)}}function ty(){console.log(`${i.bold("Usage:")} asm update [name...] [options]
|
|
920
926
|
|
|
921
927
|
Update outdated skills to their latest version with security re-audit.
|
|
922
928
|
|
|
@@ -934,10 +940,10 @@ ${i.bold("Examples:")}
|
|
|
934
940
|
asm update ${i.dim("Update all outdated skills")}
|
|
935
941
|
asm update code-review ${i.dim("Update a specific skill")}
|
|
936
942
|
asm update --yes ${i.dim("Skip confirmation prompts")}
|
|
937
|
-
asm update --json ${i.dim("Output as JSON")}`)}async function
|
|
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
|
|
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
|
|
940
|
-
`)}function
|
|
943
|
+
asm update --json ${i.dim("Output as JSON")}`)}async function Md(e){if(e.flags.help){ty();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 zo(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(Xo(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){let n=A(o);e.flags.machine&&(t?.(),console.log(W("update",q.UNKNOWN_ERROR,n,r)),process.exit(1)),w(n),process.exit(1)}}import{execFile as ry}from"child_process";import{promisify as sy}from"util";import{access as Fd,readFile as _d,readdir as oy,writeFile as ny,rm as iy,stat as Ud}from"fs/promises";import{join as Vn}from"path";import{homedir as ay}from"os";import{constants as jd}from"fs";var Rt=sy(ry);async function ly(e){let t=e?.execFn??Rt;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 cy(e){let t=e?.execFn??Rt;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 dy(e){let t=e?.execFn??Rt;try{let{stdout:r}=await t("gh",["--version"],{timeout:5e3}),s=r.trim().split(`
|
|
944
|
+
`)[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 uy(e){let t=e?.execFn??Rt;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 s=r?.stderr,n=(typeof s=="string"?s:"").match(/Logged in to .+ account (\S+)/);return n?{name:"GitHub CLI authenticated",status:"pass",message:n[1]}:{name:"GitHub CLI authenticated",status:"fail",message:"Not authenticated",fix:"Run: gh auth login"}}}async function py(e){let t=e?.execFn??Rt;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 my(e){try{let t=Vn(e,".asm-doctor-write-test");return await ny(t,"test","utf-8"),await iy(t),{writable:!0,exists:!0}}catch{}try{return await Fd(e,jd.W_OK),{writable:!0,exists:!0}}catch{}try{return await Fd(e,jd.F_OK),{writable:!1,exists:!0}}catch{return{writable:!0,exists:!1}}}async function fy(e){let t=e.providers.filter(n=>n.enabled),r=0,s=0;for(let n of t){let a=ee(n.global);s++,(await my(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 gy(){let e=At();try{let t=await _d(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 hy(){let e=li();try{let t=await _d(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 yy(){try{let e=await fetch(yo,{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 by(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=ee(c.global),u=Vn(d,a);try{(await Ud(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 wy(e,t){let r=new Set(Object.keys(t.skills)),s=[];for(let o of e.providers.filter(n=>n.enabled)){let n=ee(o.global);try{let a=await oy(n);for(let l of a)try{(await Ud(Vn(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 ky(e){let t=e?.execFn??Rt;try{let{stdout:r}=await t("df",["-Pk",ay()],{timeout:5e3}),s=r.trim().split(`
|
|
945
|
+
`);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 vy(){try{let e=await Mr();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: ${A(e)}`}}}async function Bd(){let e=await D(),t=await Oe(),s=(await Promise.allSettled([ly(),cy(),dy(),uy(),py(),fy(e),gy(),hy(),yy(),by(e,t),wy(e,t),ky(),vy()])).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 Sy={pass:"\u2705",warn:"\u26A0\uFE0F ",fail:"\u274C"};function Gd(e){let t=["Checking your environment...",""];for(let r of e.checks){let o=` ${Sy[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(`
|
|
946
|
+
`)}function Vd(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 $y(){console.log(`${i.bold("Usage:")} asm doctor [options]
|
|
941
947
|
|
|
942
948
|
Run environment health checks and diagnostics. Validates all
|
|
943
949
|
prerequisites for using asm \u2014 git, GitHub CLI, Node.js, config,
|
|
@@ -952,7 +958,7 @@ ${i.bold("Options:")}
|
|
|
952
958
|
${i.bold("Examples:")}
|
|
953
959
|
asm doctor ${i.dim("Run all health checks")}
|
|
954
960
|
asm doctor --json ${i.dim("Output as JSON")}
|
|
955
|
-
asm doctor --machine ${i.dim("Machine-readable v1 envelope output")}`)}async function
|
|
961
|
+
asm doctor --machine ${i.dim("Machine-readable v1 envelope output")}`)}async function Hd(e){if(e.flags.help){$y();return}let t=performance.now(),r=await Bd();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(Vd(r)):console.log(Gd(r));r.failures>0&&process.exit(1)}function xy(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,getPath:!1,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:(ye(`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:(ye(`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")r.command==="get"?r.flags.getPath=!0:(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:(ye(`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))&&(ye(`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))&&(ye(`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:(ye(`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:(ye(`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]||(ye('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:(ye(`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("-")?(ye(`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 ye(e){console.error(i.red(`Error: ${e}`))}function Py(){console.log(`${i.blueBold("agent-skill-manager")} (${i.bold("asm")}) ${Fs()}
|
|
956
962
|
|
|
957
963
|
Interactive TUI and CLI for managing installed skills for AI coding agents.
|
|
958
964
|
|
|
@@ -965,7 +971,8 @@ ${i.bold("Commands:")}
|
|
|
965
971
|
search <query> Search skills by name/description/tool
|
|
966
972
|
tag add|remove Edit local tags for an installed skill
|
|
967
973
|
inspect <skill-name> Show detailed info for a skill
|
|
968
|
-
get <skill> Print a skill
|
|
974
|
+
get <skill> Print a skill body, or borrow its directory with --path
|
|
975
|
+
cleanup <path> Remove an exact directory borrowed by get --path
|
|
969
976
|
deps Manage caller-owned temporary dependency leases
|
|
970
977
|
uninstall <skill-name> Remove a skill (with confirmation)
|
|
971
978
|
disable <target> Disable skill(s) without uninstalling
|
|
@@ -1009,4 +1016,4 @@ ${i.bold("Global Options:")}
|
|
|
1009
1016
|
--sort <field> Sort by: name, version, or location (default: name)
|
|
1010
1017
|
--flat Show one row per tool instance (list, search)
|
|
1011
1018
|
-y, --yes Skip confirmation prompts
|
|
1012
|
-
-V, --verbose Show debug output`)}async function
|
|
1019
|
+
-V, --verbose Show debug output`)}async function qd(e){let t=xy(e);if(t.flags.json&&t.flags.machine&&(ye("--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&&ai(!0),t.flags.version){console.log(`asm ${Fs()}`);let r=await Mr();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){Py();return}if(t.command)switch(t.command){case"list":await Ji(t);break;case"search":await na(t);break;case"tag":await ia(t);break;case"inspect":await aa(t);break;case"get":await nc(t);break;case"cleanup":await ic(t);break;case"deps":await cc(t);break;case"uninstall":await uc(t);break;case"disable":await qi(t);break;case"enable":await Wi(t);break;case"audit":await Ic(t);break;case"install":await An(t);break;case"activate":await Dc(t);break;case"deactivate":await Mc(t);break;case"library":await Fc(t);break;case"config":await jc(t);break;case"export":await Yc(t);break;case"import":await Qc(t);break;case"init":await rd(t);break;case"stats":await sd(t);break;case"link":await od(t);break;case"index":await kd(t);break;case"bundle":await Ld(t);break;case"publish":await Od(t);break;case"outdated":await Dd(t);break;case"update":await Md(t);break;case"doctor":await Hd(t);break;case"eval":await sc(t);break;case"eval-providers":await oc(t);break;default:ye(`Unknown command: "${t.command}"`),console.error('Run "asm --help" for usage.'),process.exit(2)}}function Wd(e){let t=e.slice(2);if(t.length===0)return!1;let r=["list","search","tag","inspect","get","cleanup","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(Wd(process.argv))await qd(process.argv).catch(e=>{console.error("Fatal error:",e),process.exit(1)});else{let{main:e}=await import("./src-W3UM7BUS.js");await e().catch(t=>{console.error("Fatal error:",t),process.exit(1)})}
|