@deveco/deveco-cli-common 1.3.7 → 1.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,8 +3,8 @@ https://www.npmjs.com/package/generate-license-file
3
3
 
4
4
  The following npm packages may be included in this product:
5
5
 
6
- - @deveco/deveco-cli-knowledgebase@1.3.7
7
- - @deveco/deveco-cli@1.3.7
6
+ - @deveco/deveco-cli-knowledgebase@1.3.8
7
+ - @deveco/deveco-cli@1.3.8
8
8
 
9
9
  These packages each contain the following license:
10
10
 
@@ -14,7 +14,7 @@ MIT
14
14
 
15
15
  The following npm package may be included in this product:
16
16
 
17
- - @deveco/deveco-cli-common@1.3.7
17
+ - @deveco/deveco-cli-common@1.3.8
18
18
 
19
19
  This package contains the following license:
20
20
 
package/dist/cli.js CHANGED
@@ -4,7 +4,7 @@ var xC=Object.defineProperty;var IC=(n,e)=>{for(var t in e)xC(n,t,{get:e[t],enum
4
4
  `)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(i,o,s,a,c,l,h);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(i-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let i=0;i<t.length;i++){let o=t[i];if(!r.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(i===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}static assertModuleName(e){this.assertSafeName(e,"module name")}static assertAbilityName(e){this.assertSafeName(e,"ability name")}static assertSafeName(e,t){if(!/^[A-Za-z0-9_.]+$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(Oe.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=Oe.resolve(Oe.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=Oe.normalize(e),i=Oe.relative(r,t);if(i.split(Oe.sep)[0]===".."||Oe.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||Oe.isAbsolute(e)}static isPathContained(e,t){let r=Oe.resolve(t,e),i=Oe.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=mu.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=Oe.resolve(i,e),s;try{s=mu.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};import fg from"crypto";import ae from"fs";import Ba from"os";import ut from"path";import TC from"https";var $h={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var Aa=class n{static ENDPOINT=$h.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(e,"utf8"),6e4);return n.isSuccess(i)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),r=t?.code??t?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(e,t,r,i){let o=new URL(e);return new Promise((s,a)=>{let c=TC.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},l=>{let d=[];l.on("data",h=>d.push(h)),l.on("end",()=>{s({code:l.statusCode??0,body:Buffer.concat(d).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(r),c.end()})}};var Fh={identity:n=>n,camelCase:n=>n,snakeCase:n=>n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},fu=class{constructor(e={}){this.config=e}serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(o=>this.transform(o));if(typeof e!="object")return e;let t=this.config.namingStrategy??Fh.identity,r=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(e)){let a=r[o]??t(o);i[a]=this.transform(s)}return i}},jh=new fu({namingStrategy:Fh.snakeCase,fieldNames:{}});import zo from"crypto";import Ta from"fs";import OC from"path";var Oa="aes-256-gcm",NC=12,MC="deveco-cli-trace-file",LC="trace-file-secret",Uh=32;function Hh(n){try{let e=Ta.readFileSync(n,"utf8").trim();return e&&Buffer.from(e,"base64").length===Uh?e:null}catch{return null}}function Bh(n){let e=OC.join(n,LC),t=Hh(e);if(t)return hu(t);let r=zo.randomBytes(Uh).toString("base64");try{Ta.mkdirSync(n,{recursive:!0});try{Ta.writeFileSync(e,r,{flag:"wx"})}catch{let i=Hh(e);if(i)return hu(i);Ta.writeFileSync(e,r)}}catch{}return hu(r)}function hu(n){return zo.createHash("sha256").update(MC).update(n).digest()}function Wh(n,e){let t=zo.randomBytes(NC),r=zo.createCipheriv(Oa,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:Oa,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function Vh(n,e){let t;try{t=JSON.parse(n)}catch{return null}if(!_C(t))return n;try{let r=zo.createDecipheriv(Oa,e,Buffer.from(t.iv,"base64"));return r.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"base64")),r.final()]).toString("utf8")}catch{return null}}function _C(n){if(!n||typeof n!="object")return!1;let e=n;return e.version===1&&e.algorithm===Oa&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as J from"fs";import*as ja from"path";import re from"fs";import{spawn as $C}from"child_process";import*as Na from"os";import*as U from"path";import FC from"json5";var gu="Huawei";var Yh=3;function Ma(n){if(!re.existsSync(n)||!re.statSync(n).isDirectory())return!1;let e=re.existsSync(U.join(n,"build-profile.json5")),t=re.existsSync(U.join(n,"hvigorfile.js"))||re.existsSync(U.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=re.readFileSync(U.join(n,"build-profile.json5"),"utf-8");return FC.parse(r).app!==void 0}catch{return!1}}function yu(n,e,t){if(e>=t)return null;let r=jC(n),i=HC(r);if(i)return i;for(let o of r){let s=yu(o,e+1,t);if(s)return s}return null}function jC(n){try{let e=re.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(U.join(n,r.name));return t}catch{return[]}}function HC(n){for(let e of n)if(Ma(e))return e;return null}function br(n){if(!n||n.trim()==="")return null;let e=U.resolve(n),t;try{t=re.realpathSync(e)}catch{t=e}if(!re.existsSync(t))return null;if(Ma(t))return t;let r=t;for(let i=1;i<=3;i++){let o=U.dirname(r);if(o===r)break;if(Ma(o))return o;r=o}if(re.statSync(t).isDirectory()){let i=yu(t,0,Yh);if(i)return i}return null}function La(n){if(!n||n.trim()==="")return null;let e=U.resolve(n),t;try{t=re.realpathSync(e)}catch{t=e}return!re.existsSync(t)||!re.statSync(t).isDirectory()?null:Ma(t)?t:yu(t,0,Yh)}var Gh="DevEco Studio";function Kh(){if(process.platform==="win32"){let n=[U.join("C:\\Program Files",gu,Gh),U.join("C:\\Program Files (x86)",gu,Gh)];return qh(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",U.join(process.env.HOME??"","Applications","DevEco Studio.app")];return qh(n)}return null}function qh(n){for(let e of n)if(re.existsSync(e))return e;return null}function Ri(n,e){let t=e?U.join("standardIndex","index.js"):"index.js";return re.existsSync(U.join(n,"ace-server"))?U.join(n,"ace-server","out",t):U.join(n,"out",t)}function _a(n){return re.existsSync(Ri(n,!0))}var UC=5e3,BC=64*1024,zh=new Map;function Xh(n,e){let t=WC(n),r=zh.get(t);if(r)return r;let i=VC(n,e).catch(()=>!1);return zh.set(t,i),i}function WC(n){let e=U.resolve(n).replace(/\\/g,"/");return process.platform==="win32"?e.toLowerCase():e}function Jh(n){try{let e=JSON.parse(n.trim());return Array.isArray(e.protocols)?e.protocols.includes("--socket"):null}catch{return null}}function VC(n,e){let t=Ri(n,!0);if(!re.existsSync(t))return Promise.resolve(!1);let r=e||process.execPath||"node",i=[t,"--list-protocols"];return g.debug(`Executing: ${r} ${i.join(" ")}`),new Promise(o=>{let s=$C(r,i,{stdio:["ignore","pipe","ignore"],windowsHide:!0}),a="",c=!1,l=h=>{c||(c=!0,clearTimeout(d),s.exitCode===null&&s.signalCode===null&&s.kill(),o(h))},d=setTimeout(()=>l(!1),UC);s.stdout?.on("data",h=>{a=(a+h.toString("utf8")).slice(-BC);let w=Jh(a);w!==null&&l(w)}),s.on("error",()=>l(!1)),s.on("close",()=>l(Jh(a)??!1))})}var GC=[".idea",".deveco","cxx","compile_commands.json"];function Hn(n){return U.join(n,...GC)}function Zh(n){return new Promise(e=>setTimeout(e,n))}var qC=new Set(["c","cc","cpp","cxx","h","hh","hpp","hxx"]);function Un(n){let e=U.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&qC.has(e)}function $a(n){return U.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function xe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function zC(n){return xe(n)}function Ot(n){let e=zC(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Jr(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??U.join(Na.homedir(),"AppData","Local");return U.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?U.join(Na.homedir(),"Library","Logs","devecocli-mcp-server"):U.join(Na.homedir(),".local","share","devecocli-mcp-server","logs")}function Qh(n,e){let t=JC(e),r=YC(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=KC(t,n,s);return XC(e,a),i}function JC(n){let e;try{e=re.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function YC(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function KC(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function XC(n,e){try{re.mkdirSync(U.dirname(n),{recursive:!0})}catch{}try{re.writeFileSync(n,e.join(`
5
5
  `)+`
6
6
  `,"utf8")}catch{}}function wu(n,e,t="[Cleanup]"){try{let r=U.dirname(n);if(!re.existsSync(r))return;let i=Date.now();for(let o of re.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&ZC(U.join(r,o.name),i,e,t)}catch{}}function ZC(n,e,t,r){try{let{mtimeMs:i}=re.statSync(n);if(e-i<=t)return;re.rmSync(n,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${n}`)}catch(i){console.error(`${r} Failed to remove expired dir ${n}: ${i}`)}}var eg="mcp-server.log",QC="mcp-server",ek={maxSize:10*1024*1024,maxFiles:4},vu=class n{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...ek,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Jr(),this.currentLogFile=ja.join(this.logDir,eg),J.existsSync(this.logDir)||J.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return ja.join(this.logDir,`${QC}-${e}.log.${t}`)}fileExists(e){try{return J.accessSync(e,J.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=J.readdirSync(this.logDir),t=[];for(let i of e)if(i===eg||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=ja.join(this.logDir,i),s=J.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{J.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&J.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&J.renameSync(o,s)}let r=this.getRotatedFileName(e,1);J.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=J.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=J.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{J.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] [pid=${process.pid}] ${o}
7
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);J.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{J.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},bt=null;function Bn(n=!1){bt&&bt.dispose(),bt=new vu(n)}function tg(){bt&&(bt.dispose(),bt=null)}function rg(){bt&&bt.flush()}function ng(){return bt?.getLogFilePath()??null}function ig(){return bt?.getLogDirectory()??null}function Fa(){return bt||Bn(!1),bt}var g={debug:(n,...e)=>Fa().debug(n,...e),info:(n,...e)=>Fa().info(n,...e),warn:(n,...e)=>Fa().warn(n,...e),error:(n,...e)=>Fa().error(n,...e)};import Jo from"fs";import bu from"path";var Yo=300*1e3,Ko=3600*1e3,Su=10080*60*1e3,xi=8*1024*1024,Eu=3600*1e3,og=".pending",tk=/\.reclaim-\d+-\d+$/;function Xe(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var rk="upload-state.json";function ag(n){return bu.join(n,rk)}function nk(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function Ha(n){try{let e=Jo.readFileSync(ag(n),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return nk()}}function Pu(n,e){try{Jo.writeFileSync(ag(n),JSON.stringify(e),"utf8")}catch{}}function cg(n){let e=Ha(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),Pu(n,e))}function lg(n){let e=Ha(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,Pu(n,e)}function dg(n){let e=Ha(n);e.lastRetryAt=Date.now(),Pu(n,e)}function Cu(n){let e=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function ku(n){if(!n.startsWith("telemetry-"))return null;let e=tk.exec(n),t=e?n.slice(0,e.index):n;if(!t.endsWith(og))return null;let r=t.slice(0,-og.length);return r.endsWith(".txt")?r:null}function Du(n){return ku(n)!==null}function ik(n,e=Date.now()){try{return e-Jo.statSync(n).mtimeMs>=Eu}catch{return!1}}function sg(n,e=Date.now()){let t;try{t=Jo.readdirSync(n)}catch{return!1}return t.some(r=>Du(r)&&ik(bu.join(n,r),e))}function ok(n,e=Date.now()){if(sg(n,e))return!0;let t=bu.join(n,"failed");if(sg(t,e))return!0;let r;try{r=Jo.readdirSync(t)}catch{return!1}for(let i of r){if(!i.startsWith("telemetry-")||!i.endsWith(".txt"))continue;let o=Cu(i);if(o!==null&&e-o<=Su)return!0}return!1}function ug(n,e=Date.now()){let t=Ha(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=Yo||ok(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Ko))}import sk from"crypto";import Ua from"fs";import ak from"path";var ck="install-id";function lk(n){return ak.join(n,ck)}function pg(n){try{let e=Ua.readFileSync(n,"utf8").trim();return dk(e)?e:null}catch{return null}}function dk(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function mg(n){let e=lk(n),t=pg(e);if(t)return t;let r=sk.randomUUID();try{Ua.mkdirSync(n,{recursive:!0});try{Ua.writeFileSync(e,r,{flag:"wx"})}catch{let i=pg(e);if(i)return i;Ua.writeFileSync(e,r)}}catch{}return r}var Xo=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new Aa;storageDir="";failedDir="";installId="";disabled=Xe();traceFileKey=Buffer.alloc(0);sessionId=fg.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){g.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=ut.join(e,"failed"),this.cliVersion="1.3.7",this.nodeVersion=process.version,this.installId=mg(e).replace(/-/g,""),this.traceFileKey=Bh(e),ae.mkdirSync(e,{recursive:!0}),ae.mkdirSync(this.failedDir,{recursive:!0}),g.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,g.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,g.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,g.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let r=t,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,r,i){let o=this.buildTraceEvent(e,t,r,i);try{let s=Wh(JSON.stringify(o),this.traceFileKey);await ae.promises.appendFile(this.currentFile(),s+`
7
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);J.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{J.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},bt=null;function Bn(n=!1){bt&&bt.dispose(),bt=new vu(n)}function tg(){bt&&(bt.dispose(),bt=null)}function rg(){bt&&bt.flush()}function ng(){return bt?.getLogFilePath()??null}function ig(){return bt?.getLogDirectory()??null}function Fa(){return bt||Bn(!1),bt}var g={debug:(n,...e)=>Fa().debug(n,...e),info:(n,...e)=>Fa().info(n,...e),warn:(n,...e)=>Fa().warn(n,...e),error:(n,...e)=>Fa().error(n,...e)};import Jo from"fs";import bu from"path";var Yo=300*1e3,Ko=3600*1e3,Su=10080*60*1e3,xi=8*1024*1024,Eu=3600*1e3,og=".pending",tk=/\.reclaim-\d+-\d+$/;function Xe(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var rk="upload-state.json";function ag(n){return bu.join(n,rk)}function nk(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function Ha(n){try{let e=Jo.readFileSync(ag(n),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return nk()}}function Pu(n,e){try{Jo.writeFileSync(ag(n),JSON.stringify(e),"utf8")}catch{}}function cg(n){let e=Ha(n);e.firstEventAt===null&&(e.firstEventAt=Date.now(),Pu(n,e))}function lg(n){let e=Ha(n);e.lastUploadAt=Date.now(),e.firstEventAt=null,Pu(n,e)}function dg(n){let e=Ha(n);e.lastRetryAt=Date.now(),Pu(n,e)}function Cu(n){let e=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function ku(n){if(!n.startsWith("telemetry-"))return null;let e=tk.exec(n),t=e?n.slice(0,e.index):n;if(!t.endsWith(og))return null;let r=t.slice(0,-og.length);return r.endsWith(".txt")?r:null}function Du(n){return ku(n)!==null}function ik(n,e=Date.now()){try{return e-Jo.statSync(n).mtimeMs>=Eu}catch{return!1}}function sg(n,e=Date.now()){let t;try{t=Jo.readdirSync(n)}catch{return!1}return t.some(r=>Du(r)&&ik(bu.join(n,r),e))}function ok(n,e=Date.now()){if(sg(n,e))return!0;let t=bu.join(n,"failed");if(sg(t,e))return!0;let r;try{r=Jo.readdirSync(t)}catch{return!1}for(let i of r){if(!i.startsWith("telemetry-")||!i.endsWith(".txt"))continue;let o=Cu(i);if(o!==null&&e-o<=Su)return!0}return!1}function ug(n,e=Date.now()){let t=Ha(n);return!!(t.firstEventAt!==null&&e-t.firstEventAt>=Yo||ok(n,e)&&(t.lastRetryAt===null||e-t.lastRetryAt>=Ko))}import sk from"crypto";import Ua from"fs";import ak from"path";var ck="install-id";function lk(n){return ak.join(n,ck)}function pg(n){try{let e=Ua.readFileSync(n,"utf8").trim();return dk(e)?e:null}catch{return null}}function dk(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function mg(n){let e=lk(n),t=pg(e);if(t)return t;let r=sk.randomUUID();try{Ua.mkdirSync(n,{recursive:!0});try{Ua.writeFileSync(e,r,{flag:"wx"})}catch{let i=pg(e);if(i)return i;Ua.writeFileSync(e,r)}}catch{}return r}var Xo=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new Aa;storageDir="";failedDir="";installId="";disabled=Xe();traceFileKey=Buffer.alloc(0);sessionId=fg.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){g.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=ut.join(e,"failed"),this.cliVersion="1.3.8",this.nodeVersion=process.version,this.installId=mg(e).replace(/-/g,""),this.traceFileKey=Bh(e),ae.mkdirSync(e,{recursive:!0}),ae.mkdirSync(this.failedDir,{recursive:!0}),g.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,g.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,g.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,g.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let r=t,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,r,i){let o=this.buildTraceEvent(e,t,r,i);try{let s=Wh(JSON.stringify(o),this.traceFileKey);await ae.promises.appendFile(this.currentFile(),s+`
8
8
  `,"utf8"),cg(this.storageDir)}catch{}}buildTraceEvent(e,t,r,i){let o=`${n.EVENT_PREFIX}${e.event}`,s=jh.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:fg.randomUUID(),trace_os_version:n.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:t,success:r,error_code:i,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=Ba.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Ba.release().split(".");return(parseInt(e[e.length-1],10)||0)>=22e3?"Windows 11":"Windows 10"}case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}resolveOsSuffix(){switch(process.platform){case"win32":return"windows";case"darwin":return Ba.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(Ba.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${r}`}currentFile(){return ut.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){g.debug("[telemetry] scheduler not started (telemetry disabled)");return}g.debug(`[telemetry] scheduler started (flush every ${Yo/1e3}s, retry failed every ${Ko/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},Yo)},Yo),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},Ko)},Ko)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),g.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let e=await this.listPendingFiles(),t=!0;for(let r of e)await this.flushFile(r)||(t=!1);return lg(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");await this.reclaimStalePending();let e=Date.now(),t;try{t=await ae.promises.readdir(this.failedDir)}catch{return!0}let r=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>ut.join(this.failedDir,o)),i=!0;for(let o of r){let s=ut.basename(o),a=Cu(s);if(a!==null){if(e-a>Su){try{await ae.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||g.warn("[telemetry] retry failed"),dg(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let r;try{r=await ae.promises.readdir(t)}catch{continue}for(let i of r)Du(i)&&await this.reclaimOrphan(ut.join(t,i),e)}}async reclaimOrphan(e,t){let r;try{let l=await ae.promises.stat(e);if(t-l.mtimeMs<Eu)return;r=l.size}catch{return}let i=ut.dirname(e),o=ku(ut.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=ut.join(i,o),c=xi-await this.fileSize(a);if(r>c){try{await ae.promises.unlink(s)}catch{}g.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){g.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}g.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(e,t,r){let i=ut.join(t,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await ae.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await ae.promises.appendFile(t,await ae.promises.readFile(e))}catch(r){return g.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${r instanceof Error?r.message:String(r)}`),!1}try{await ae.promises.unlink(e)}catch(r){g.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${r instanceof Error?r.message:String(r)}`)}return!0}async fileSize(e){try{return(await ae.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await ae.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),r=this.flushChain.then(t,t);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let e;try{e=await ae.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>ut.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>xi){g.warn(`[telemetry] ${ut.basename(e)} is ${t} bytes (> ${xi}), dropped without uploading`);try{await ae.promises.unlink(e)}catch{}return!0}let r=e+".pending";try{await ae.promises.rename(e,r)}catch{return!1}await this.touch(r);let i;try{i=await ae.promises.readFile(r,"utf8")}catch{return!1}let o=i.split(`
9
9
  `).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await ae.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,o)}collectDecryptBatch(e,t){let r=[],i=16,o=t;for(;o<e.length&&r.length<n.MAX_BATCH;){let s=Vh(e[o],this.traceFileKey);if(s===null){o++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&i+a>n.MAX_PAYLOAD_BYTES)break;r.push(s),i+=a,o++}return{batch:r,next:o}}async uploadInBatches(e,t){let r=0;for(;r<t.length;){let i=r,{batch:o,next:s}=this.collectDecryptBatch(t,r);r=s;let a=this.buildPayloadItems(o);if(a.length===0)continue;let c=JSON.stringify(a),l=!1;try{l=await this.uploader.upload(c,this.installId)}catch{}if(!l){g.warn("[telemetry] upload failed");let d=t.slice(i).join(`
10
10
  `)+`
@@ -14,7 +14,7 @@ var xC=Object.defineProperty;var IC=(n,e)=>{for(var t in e)xC(n,t,{get:e[t],enum
14
14
  `,"utf8")}catch{return}try{await ae.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let r=[],i=0;for(let o=e.length-1;o>=0;o--){let s=Buffer.byteLength(e[o],"utf8")+1;if(i+s>t)break;i+=s,r.push(e[o])}return r.reverse(),r}};var R=new Xo;import{spawn as uk}from"child_process";import{existsSync as pk}from"fs";import{dirname as mk,join as fk}from"path";import{fileURLToPath as hk}from"url";function gk(){let n=mk(hk(import.meta.url)),e=fk(n,"internal","telemetry-upload-background.js");return pk(e)?e:null}function Ru(n){if(Xe()||!ug(n))return;let e=gk();if(!e){g.warn("[telemetry] background upload script not found, skipping spawn");return}try{uk(process.execPath,[e],{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1",DEVECO_CLI_TELEMETRY_UPLOAD:"1"}}).unref()}catch(t){g.warn("[telemetry] failed to spawn background upload:",t)}}var y=class extends Error{traceMessage;constructor(e,t,r){super(e,r),this.name="TraceError",this.traceMessage=t??e}};function X(n){if(n instanceof y)return n.traceMessage;if(n instanceof Error){let e=n.code;return typeof e=="string"&&e!==""?e:n.name}return"UnknownError"}var v={CommandExecuted:"Command_executed",McpToolCall:"serve_mcp",SkillOperation:"skills",Init:"mcp_config_operation",SkillConfigOperation:"skill_config_operation",DocOperation:"docs",ServeLsp:"serve_lsp",CheckCommand:"check"};var Pe={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json",LOCK_JSON5_PATH:"oh_modules/.ohpm/lock.json5",HVIGOR_CONFIG:"hvigor/hvigor-config.json5"};var B=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=j.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=j.join(e,"build-profile.json5");if(!Y.existsSync(t))return null;try{let r=Y.readFileSync(t,"utf-8"),i=Zt.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new y(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=j.join(r,"src","main","module.json5");if(!Y.existsSync(i))return"entry";try{let o=Y.readFileSync(i,"utf-8");return Zt.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=j.normalize(e);for(let r of this.profile.modules){let i=j.normalize(j.join(this.rootDir,r.srcPath)),o=i+j.sep;if(t.startsWith(o)||t===i)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new y(`Module '${e}' not found in project-level build-profile.json5.`,"Module not found in project-level build-profile.json5.");let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=j.join(r,"build-profile.json5");if(!Y.existsSync(i))throw new y(`Build profile for module '${e}' not found at ${i}.`,"Build profile for module not found at ${profilePath}.");try{let o=Y.readFileSync(i,"utf-8");return Zt.parse(o)}catch(o){throw new Error(`Failed to parse module build profile at ${i}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}getBundleName(e){if(e){let r=this.profile.app.products?.find(i=>i.name===e);if(r?.bundleName)return r.bundleName}let t=j.join(this.rootDir,"AppScope","app.json5");if(Y.existsSync(t))try{let r=Y.readFileSync(t,"utf-8"),i=Zt.parse(r);if(i?.app?.bundleName)return i.app.bundleName}catch(r){console.warn(`Warning: Failed to parse ${t}:`,r)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=j.join(this.rootDir,"AppScope","app.json5");if(!Y.existsSync(e))return!1;try{let t=Y.readFileSync(e,"utf-8");return Zt.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=E.resolvePathWithinRoot(this.rootDir,r.srcPath),o=j.join(i,"src","main","module.json5");if(!Y.existsSync(o))return"EntryAbility";try{let s=Y.readFileSync(o,"utf-8"),c=Zt.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new y(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`,"Invalid product name.");if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new y(`Product '${e}' not found in project configuration. Available products: ${r}`,"Productnot found in project configuration.")}}getModuleDependencies(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return[];let r=this.readLockFinalLocalModuleDeps(e);return r!==null?r:this.readOhPackageLocalModuleDeps(t)}readLockFinalLocalModuleDeps(e){let t=j.join(this.rootDir,Pe.LOCK_JSON5_PATH);if(!Y.existsSync(t))return null;let r;try{r=Zt.parse(Y.readFileSync(t,"utf-8"))}catch(d){return m(`Failed to parse lock.json5: ${d instanceof Error?d.message:String(d)}`),null}let i=r,o=i?.modules;if(!o||typeof o!="object")return null;let s=Object.values(o).find(d=>typeof d=="object"&&d!==null&&d.name===e);if(!s)return null;let a=this.buildOverrideMap(i.overrides),c=[],l=new Set;for(let d of["dependencies","dynamicDependencies"]){let h=s[d];!h||typeof h!="object"||this.collectLocalDeps(h,a,w=>this.resolveLockDepByVersion(w),c,l)}return c}resolveLockDepByVersion(e){if(typeof e!="object"||e===null)return null;let t=e.version;return typeof t=="string"?this.resolveLocalDepToModule(t):null}resolveDepModule(e,t,r){if(t?.has(e)){let i=t.get(e);if(i){let o=this.resolveLocalDepToModule(i);if(o)return o}}return r()}buildOverrideMap(e){if(!e||typeof e!="object")return null;let t=new Map;for(let[r,i]of Object.entries(e))typeof i=="string"&&t.set(r,i);return t.size>0?t:null}resolveLocalDepToModule(e){let t=n.stripLocalDep(e);if(!t)return null;let r=j.resolve(this.rootDir,t),i;try{i=E.ensurePathWithinRoot(this.rootDir,r)}catch{return null}let o=this.profile.modules.find(s=>j.resolve(this.rootDir,s.srcPath)===i);return o?o.name:null}static stripLocalDep(e){return!e.startsWith("file:")&&!e.startsWith(".")&&!e.startsWith("..")?null:e.startsWith("file:")?e.substring(5):e}readOhPackageLocalModuleDeps(e){let t=j.join(E.resolvePathWithinRoot(this.rootDir,e.srcPath),Pe.OH_PACKAGE_JSON5);if(!Y.existsSync(t))return[];let r=this.readRootOverrideMap(),i=[],o=new Set;try{let s=Zt.parse(Y.readFileSync(t,"utf-8"));for(let a of["dependencies","dynamicDependencies"]){let c=s?.[a];!c||typeof c!="object"||this.collectLocalDeps(c,r,l=>this.resolveOhPackageDepByValue(l,e),i,o)}}catch(s){m(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return i}readRootOverrideMap(){let e=j.join(this.rootDir,Pe.OH_PACKAGE_JSON5);if(!Y.existsSync(e))return null;try{let t=Zt.parse(Y.readFileSync(e,"utf-8"));return this.buildOverrideMap(t?.overrides)}catch{return null}}resolveOhPackageDepByValue(e,t){return typeof e=="string"?this.resolveLocalDepModuleName(e,t):null}collectLocalDeps(e,t,r,i,o){for(let[s,a]of Object.entries(e)){let c=this.resolveDepModule(s,t,()=>r(a));c&&!o.has(c)&&(o.add(c),i.push(c))}}resolveLocalDepModuleName(e,t){let r=n.stripLocalDep(e);if(!r)return null;let i=j.join(t.srcPath,r),o=E.resolvePathWithinRoot(this.rootDir,i),s=this.profile.modules.find(a=>j.resolve(this.rootDir,a.srcPath)===o);return s?s.name:null}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new y(`Module '${e}' not found. Available modules: ${l}`,"Module not found.")}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,r,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!Y.existsSync(a))throw new y(`Build metadata not found for module '${e}' at ${a}. Build the project first.`,"Build metadata not found for module. Build the project first.");let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,d=c;if(!l){let D=this.getSignedHapName(c,o.srcPath,i,t);D&&(d=D)}let h=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(h))throw new y(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`,"Target device is a real device, but the artifact is not signed.");let w=this.buildOutputPath(o.srcPath,i,["outputs",t,d]);if(!Y.existsSync(w))throw new y(`Generated package file not found in ${w}.`,"Generated package file not found.");return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=j.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!Y.existsSync(l))throw new y(`Remote HSP dependency not found: ${l}`,"Remote HSP dependency not found.");s.push(l)}return s}resolveModuleSpecsForProduct(e){let t=[];for(let r of this.profile.modules){let i=r.targets;if(!i||i.length===0){t.push(`${r.name}@default`);continue}let o=i.filter(s=>!s.applyToProducts||s.applyToProducts.includes(e));if(o.length!==0)for(let s of o)t.push(`${r.name}@${s.name}`)}return t}listBuildArtifacts(e,t){let r=[];for(let i of e){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default",c=this.profile.modules.find(d=>d.name===s);if(!c)continue;let l=this.buildOutputPath(c.srcPath,t,["outputs",a]);if(Y.existsSync(l))for(let d of Y.readdirSync(l))(d.endsWith(".hap")||d.endsWith(".hsp")||d.endsWith(".har"))&&r.push(j.join(l,d))}return r}listProjectAppArtifacts(e){let t=E.ensurePathWithinRoot(this.rootDir,j.resolve(this.rootDir,"build","outputs",e));if(!Y.existsSync(t))return[];let r=[],i=o=>{for(let s of Y.readdirSync(o,{withFileTypes:!0})){let a=j.join(o,s.name);s.isDirectory()?i(a):s.name.endsWith(".app")&&r.push(a)}};return i(t),r}collectBuildArtifacts(e,t,r){let i=t;if(!e){let s=new Set(t);i=[...t,...this.profile.modules.map(a=>`${a.name}@default`).filter(a=>!s.has(a))]}let o=this.listBuildArtifacts(i,r);return e&&o.push(...this.listProjectAppArtifacts(r)),o}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return Y.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=E.resolvePathWithinRoot(this.rootDir,e),o=j.resolve(i,"build",t,...r);return E.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let r;try{let c=Y.readFileSync(e,"utf-8");r=Zt.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let i,o=!1,s=Array.isArray(r)?r:[r];for(let c of s)i||(i=c[t]),o||(o=c.isSigned===!0);if(!i)throw new y(`Could not find ${t} in output_metadata.json at ${e}`,"Could not find metadataKey in output_metadata.json at metadataPath.");this.validatePackageName(i);let a=this.collectRemoteHsps(s);return{packageName:i,isSigned:o,dependRemoteHsps:a}}validatePackageName(e){let t=j.basename(e);if(t!==e)throw new y(`Invalid traversal name: '${e}'. It must contain path characters.`,"Invalid traversal name.");if(!t.endsWith(".hap")&&!t.endsWith(".hsp"))throw new y(`Invalid package name '${t}'.It must be a .hap or .hsp file.`,"Invalid package name.")}};import Xu from"fs/promises";import Xr from"path";function St(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}import Ou from"fs";import Wn from"path";import{homedir as yg}from"os";import He from"fs/promises";import pt from"path";import{randomUUID as hg}from"crypto";async function Ne(n){try{return await He.lstat(n)}catch(e){if(e.code==="ENOENT")return;throw e}}async function Ce(n){let e=pt.resolve(n),t=pt.dirname(e);try{return pt.join(await He.realpath(t),pt.basename(e))}catch(r){if(r.code!=="ENOENT"||t===e)throw r;return pt.join(await Ce(t),pt.basename(e))}}async function xu(n,e){let t=`${e}.backup-${hg()}`,r=await Ne(e);r&&await He.rename(e,t);try{await He.rename(n,e)}catch(i){throw r&&await He.rename(t,e),i}r&&await He.rm(t,{recursive:!0,force:!0})}function he(n,e){let t=r=>pt.resolve(r).replace(/^\\\\\?\\/,"").replace(/[\\/]+$/,"");return process.platform==="win32"?t(n).toLowerCase()===t(e).toLowerCase():t(n)===t(e)}function Ii(n,e){let t=(r,i)=>{let o=pt.relative(r,i);return o===""||!o.startsWith(`..${pt.sep}`)&&o!==".."&&!pt.isAbsolute(o)};return t(n,e)||t(e,n)}async function Wa(n,e,t=!1){let r=await He.realpath(n);if(!(await He.stat(r)).isDirectory())throw new Error(`Skill source is not a directory: ${n}`);let i=await Ce(e),o=await Ne(i);if(he(r,i))return Qt(i,"same-source");let s=o?await He.realpath(i).catch(()=>i):i;if(o?.isSymbolicLink()&&he(r,s))return Qt(i,"correct-link");let a=await Iu(i,t);if(a)return a;if(Ii(r,i)||o&&Ii(r,s))throw new Error(`Skill source and destination overlap: ${n}, ${e}`);await He.mkdir(pt.dirname(i),{recursive:!0});let c=`${i}.install-${hg()}`;try{let l=await yk(r,c);return await xu(c,i),{success:!0,path:i,...l}}finally{await He.rm(c,{recursive:!0,force:!0})}}function Qt(n,e){return{success:!0,skipped:!0,path:n,reason:e}}async function Iu(n,e){if(!e&&await Ne(n))return Qt(n,"already-exists")}async function yk(n,e){try{let t=process.platform==="win32"?n:pt.relative(pt.dirname(e),n);return await He.symlink(t,e,process.platform==="win32"?"junction":"dir"),{mode:"symlink"}}catch(t){return await He.rm(e,{recursive:!0,force:!0}),await He.cp(n,e,{recursive:!0,dereference:!0,errorOnExist:!0,force:!1}),{mode:"copy",fallbackReason:t.code??String(t)}}}async function Va(n){let e=await Ce(n),t=await Ne(e);return t?(await He.rm(e,{recursive:!t.isSymbolicLink(),force:!0}),{success:!0,path:e}):Qt(e,"not-installed")}var gg={amp:{displayName:"Amp",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},antigravity:{displayName:"Antigravity",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/antigravity/skills"},"antigravity-cli":{displayName:"Antigravity CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/antigravity-cli/skills"},astrbot:{displayName:"AstrBot",skillsDir:"data/skills",globalSkillsDir:"~/.astrbot/data/skills"},atomcode:{displayName:"atomcode",skillsDir:".atomcode/skills",globalSkillsDir:"~/.atomcode/skills",detect:["~/.atomcode"]},augment:{displayName:"Augment",skillsDir:".augment/skills",globalSkillsDir:"~/.augment/skills"},bob:{displayName:"IBM Bob",skillsDir:".bob/skills",globalSkillsDir:"~/.bob/skills"},"claude-code":{displayName:"Claude Code",skillsDir:".claude/skills",globalSkillsDir:"~/.claude/skills",detect:["~/.claude"]},cline:{displayName:"Cline",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},"codearts-agent":{displayName:"CodeArts Agent",skillsDir:".codeartsdoer/skills",globalSkillsDir:"~/.codeartsdoer/skills"},codebuddy:{displayName:"CodeBuddy",skillsDir:".codebuddy/skills",globalSkillsDir:"~/.codebuddy/skills",detect:["~/.codebuddy"]},codex:{displayName:"Codex",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills",detect:["~/.codex"],legacySkillsDirs:[".codex/skills"],legacyGlobalSkillsDirs:["~/.codex/skills"]},continue:{displayName:"Continue",skillsDir:".continue/skills",globalSkillsDir:"~/.continue/skills"},crush:{displayName:"Crush",skillsDir:".crush/skills",globalSkillsDir:"~/.config/crush/skills"},cursor:{displayName:"Cursor",skillsDir:".agents/skills",globalSkillsDir:"~/.cursor/skills",detect:["~/.cursor"],legacySkillsDirs:[".cursor/skills"]},deepagents:{displayName:"Deep Agents",skillsDir:".agents/skills",globalSkillsDir:"~/.deepagents/agent/skills"},deveco:{displayName:"deveco",skillsDir:".deveco/skills",globalSkillsDir:"~/.config/deveco/skills",detect:["~/.config/deveco"]},devin:{displayName:"Devin for Terminal",skillsDir:".devin/skills",globalSkillsDir:"~/.config/devin/skills"},droid:{displayName:"Droid",skillsDir:".agents/skills",globalSkillsDir:"~/.factory/skills"},dsh:{displayName:"deepseek harness",skillsDir:".dsh/skills",globalSkillsDir:"~/.dsh/skills",detect:["~/.dsh"]},"gemini-cli":{displayName:"Gemini CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.gemini/skills"},"github-copilot":{displayName:"GitHub Copilot",skillsDir:".agents/skills",globalSkillsDir:"~/.copilot/skills"},goose:{displayName:"Goose",skillsDir:".goose/skills",globalSkillsDir:"~/.config/goose/skills"},grok:{displayName:"Grok Build",skillsDir:".grok/skills",globalSkillsDir:"~/.grok/skills"},"hermes-agent":{displayName:"Hermes Agent",skillsDir:".hermes/skills",globalSkillsDir:"~/.hermes/skills"},"iflow-cli":{displayName:"iFlow CLI",skillsDir:".iflow/skills",globalSkillsDir:"~/.iflow/skills"},junie:{displayName:"Junie",skillsDir:".junie/skills",globalSkillsDir:"~/.junie/skills"},kilo:{displayName:"Kilo Code",skillsDir:".agents/skills",globalSkillsDir:"~/.kilo/skills"},"kimi-code-cli":{displayName:"Kimi Code CLI",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},"kiro-cli":{displayName:"Kiro CLI",skillsDir:".kiro/skills",globalSkillsDir:"~/.kiro/skills"},kode:{displayName:"Kode",skillsDir:".kode/skills",globalSkillsDir:"~/.kode/skills"},lingma:{displayName:"Lingma",skillsDir:".lingma/skills",globalSkillsDir:"~/.lingma/skills"},"minimax-code":{displayName:"MiniMax Code",skillsDir:".minimax/skills",globalSkillsDir:"~/.minimax/skills"},"mistral-vibe":{displayName:"Mistral Vibe",skillsDir:".vibe/skills",globalSkillsDir:"~/.vibe/skills"},neovate:{displayName:"Neovate",skillsDir:".neovate/skills",globalSkillsDir:"~/.neovate/skills"},ona:{displayName:"Ona",skillsDir:".ona/skills",globalSkillsDir:"~/.ona/skills"},openclaw:{displayName:"OpenClaw",skillsDir:"skills",globalSkillsDir:"~/.openclaw/skills"},opencode:{displayName:"OpenCode",skillsDir:".agents/skills",globalSkillsDir:"~/.config/opencode/skills",detect:["~/.config/opencode"],legacySkillsDirs:[".opencode/skills"]},openhands:{displayName:"OpenHands",skillsDir:".openhands/skills",globalSkillsDir:"~/.openhands/skills"},pi:{displayName:"Pi",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills",detect:["~/.pi/agent"],legacySkillsDirs:[".pi/skills"],legacyGlobalSkillsDirs:["~/.pi/agent/skills"]},qoder:{displayName:"Qoder",skillsDir:".qoder/skills",globalSkillsDir:"~/.qoder/skills",detect:["~/.qoder"]},"qoder-cn":{displayName:"Qoder CN",skillsDir:".qoder/skills",globalSkillsDir:"~/.qoder-cn/skills"},"qwen-code":{displayName:"Qwen Code",skillsDir:".qwen/skills",globalSkillsDir:"~/.qwen/skills"},reasonix:{displayName:"Reasonix",skillsDir:".reasonix/skills",globalSkillsDir:"~/.reasonix/skills"},replit:{displayName:"Replit",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},trae:{displayName:"Trae",skillsDir:".trae/skills",globalSkillsDir:"~/.trae/skills"},"trae-cn":{displayName:"Trae CN",skillsDir:".trae/skills",globalSkillsDir:"~/.trae-cn/skills",detect:["~/.trae-cn"],legacySkillsDirs:[".trae-cn/skills"]},universal:{displayName:"Universal",skillsDir:".agents/skills",globalSkillsDir:"~/.config/agents/skills"},warp:{displayName:"Warp",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"},windsurf:{displayName:"Windsurf",skillsDir:".windsurf/skills",globalSkillsDir:"~/.codeium/windsurf/skills"},zcode:{displayName:"ZCode",skillsDir:".zcode/skills",globalSkillsDir:"~/.zcode/skills"},zed:{displayName:"Zed",skillsDir:".agents/skills",globalSkillsDir:"~/.agents/skills"}};var Au="https://matrix.openharmony.cn",Et={TAGS_API_URL:`${Au}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Au}/api/registry/skill/skills`,SKILL_API_BASE:`${Au}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},Tu=".agents/skills",Zo=gg;function Mu(n){return Wn.resolve(n==="~"||n.startsWith("~/")?Wn.join(yg(),n.slice(1)):n)}function Ze(){return Object.keys(Zo)}function Ga(n){return[...new Set((n??"").split(",").map(e=>e.trim()).filter(Boolean))]}function Nt(n){let e=Object.prototype.hasOwnProperty.call(Zo,n)?Zo[n]:void 0;if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Ze().join(", ")}`);return e}function Nu(n){return Mu(Nt(n).globalSkillsDir)}function Lu(n,e){return Wn.join(n,Nt(e).skillsDir)}function er(n){return Wn.join(n??yg(),Tu)}function Yr(n,e){return e?Lu(e,n):Nu(n)}function qa(n,e){let t=Yr(n,e);return he(t,er(e))}function wg(n,e){let t=Nt(n),r=e?(t.legacySkillsDirs??[]).map(o=>Wn.join(e,o)):(t.legacyGlobalSkillsDirs??[]).map(Mu),i=[Yr(n,e)];return r.filter(o=>i.some(s=>he(s,o))?!1:(i.push(o),!0))}function _u(n,e){let t=Nt(e).skillsDir.split("/")[0];return t.startsWith(".")&&Ou.existsSync(Wn.join(n,t))}function Vn(n,e){let t=Nt(n);if(t.detect)return t.detect.some(o=>Ou.existsSync(Mu(o)));let r=Nu(n);return![er(),Nu("universal")].some(o=>he(o,r))&&Ou.existsSync(Wn.dirname(r))?!0:!!(e&&t.skillsDir!==Tu&&_u(e,n))}import za from"path";function vg(n){let e=[];n.agents.length&&e.push({agents:[...new Set(n.agents)]});let t=new Map;for(let{project:r,agent:i}of n.projectAgents){let o=t.get(r)??[];o.push(i),t.set(r,o)}for(let[r,i]of t)e.push({project:r,agents:[...new Set(i)]});return e}async function vk(n,e,t,r){let i=[];for(let o of wg(n,e.project)){let s=await Ce(za.join(o,t));!r.some(a=>he(a,s))&&await Ne(s)&&i.push(s)}return i}async function Ja(n,e,t=!0){let r=await Ce(za.join(er(n.project),e)),i=[];for(let o of n.agents){let s=Yr(o,n.project),a=await Ce(za.join(s,e)),c=await vk(o,n,e,[r,a]),l=!!(n.project&&!t&&!qa(o,n.project)&&c.length===0&&!_u(n.project,o)),d=i.find(h=>he(h.path,a));d?(d.legacy.push(...c.filter(h=>!d.legacy.some(w=>he(w,h)))),d.skipped&&=l):i.push({path:a,legacy:c,skipped:l})}return i}async function bg(n,e,t=!0){let r=await Ja(n,e,t);if(r.every(o=>o.skipped))return r;let i=await Ce(za.join(er(n.project),e));return r.some(o=>he(o.path,i))||r.unshift({path:i,legacy:[],skipped:!1}),r}import Ai from"fs/promises";import Lt from"path";import{randomUUID as qk}from"crypto";import{lock as zk}from"proper-lockfile";import*as Qo from"fs";import*as Cg from"path";import{homedir as bk}from"os";import*as Sg from"fs";import*as Qe from"path";function $u(n,e){let t=Qe.relative(e,n);return t===""||!Qe.isAbsolute(t)&&!t.startsWith(`..${Qe.sep}`)&&t!==".."}function Kr(n){let e=Qe.resolve(n),t=[],r=e;for(;;)try{let i=Sg.realpathSync(r);return t.length===0?i:Qe.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=Qe.dirname(r);if(o===r)return e;t.push(Qe.basename(r)),r=o}}function Eg(n,e){let t=Kr(e),r=Kr(n);return $u(r,t)?r:null}function Fu(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Ya(n){let e=Fu(n);if(!e)throw new Error("Path must not be empty.");return Kr(e)}var Sk="deveco-cli",Pg,ju=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Ek(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":Fu(n))||Cg.join(bk(),".local","share",Sk);try{return Ya(t)}catch(r){throw new ju(r instanceof Error?r.message:String(r))}}function F(){if(Pg!==void 0)return Pg;let n=Ek();try{if(Qo.existsSync(n))return Qo.realpathSync(n)}catch{}return n}import Hk from"adm-zip";import Uk from"crypto";import{timingSafeEqual as Bk}from"crypto";import Vu from"fs";import Mt from"path";import{fileURLToPath as Wk}from"url";import{homedir as tr}from"os";import et from"path";var rr="deveco-mcp",Ka={"trae-cn":".trae-cn",opencode:".config/opencode",pi:".pi/agent",deveco:".config/deveco",cursor:".cursor",codebuddy:".codebuddy",qoder:".qoder","claude-code":".claude",codex:".codex",atomcode:".atomcode",dsh:".dsh"};var Sr={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:et.join(tr(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},pi:{name:"pi",displayName:"Pi Coding Agent",supportsGlobal:!0,globalConfigPath:et.join(tr(),".pi","agent","mcp.json"),projectConfigPath:".pi/mcp.json",mcpServersKey:"mcpServers",format:"standard"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:et.join(process.platform==="win32"?et.join(process.env.APPDATA??et.join(tr(),"AppData","Roaming"),"Trae CN","User"):et.join(tr(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:et.join(tr(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:et.join(tr(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"codebuddy"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:et.join(process.platform==="win32"?et.join(process.env.APPDATA??et.join(tr(),"AppData","Roaming"),"Qoder","SharedClientCache"):et.join(tr(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"},"claude-code":{name:"claude-code",displayName:"Claude Code",supportsGlobal:!0,globalConfigPath:et.join(tr(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:et.join(tr(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Dg(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function kg(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Pk(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."}}}function Rg(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Xa(n,e){return n.format==="opencode"?Dg(e):n.format==="claude-code"||n.format==="codex"?kg(e):n.format==="codebuddy"?Pk(e):Rg(e)}var Hu="https://developer.huawei.com/consumer/cn/download/";import Mk from"axios";var Ck={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function kk(n){try{return new URL(n)}catch{return null}}function xg(n){var e=(typeof n=="string"?kk(n):n)||{},t=e.protocol,r=e.host,i=e.port;if(typeof r!="string"||!r||typeof t!="string"||(t=t.split(":",1)[0],r=r.replace(/:\d*$/,""),i=parseInt(i)||Ck[t]||0,!Dk(r,i)))return"";var o=Uu(t+"_proxy")||Uu("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function Dk(n,e){var t=Uu("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(r){if(!r)return!0;var i=r.match(/^(.+):(\d+)$/),o=i?i[1]:r,s=i?parseInt(i[2]):0;return s&&s!==e?!0:/^[.*]/.test(o)?(o.charAt(0)==="*"&&(o=o.slice(1)),!n.endsWith(o)):n!==o}):!0}function Uu(n){return process.env[n.toLowerCase()]||process.env[n.toUpperCase()]||""}import{spawn as Tg}from"child_process";import*as Gn from"fs";import*as Og from"os";import*as Za from"path";var Ng=6e4;async function Rk(){if(process.platform!=="win32")return null;let n="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await Ig(n,"ProxyServer");if(!e)return null;let t=await Ig(n,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function Ig(n,e){return new Promise(t=>{let r=Tg("reg.exe",["query",n,"/v",e],{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="";r.stdout.on("data",o=>{i+=o.toString()}),r.on("error",()=>t(null)),r.on("close",o=>{if(o!==0){t(null);return}let s=/REG_\w+\s+(\S+)/.exec(i);t(s?s[1]:null)})})}function xk(){let n=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!n)return null;try{return new URL(n).host}catch{return n}}function Ik(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function Ag(n){let e={},t=0,r="";for(let i of n.split(/\r?\n/)){let o=i.trim();if(!o)continue;let s=/^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(o);if(s){t=parseInt(s[1],10),r=s[2]??"";continue}let a=/^([^:]+):\s*(.*)$/.exec(o);a&&(e[a[1].toLowerCase()]=a[2])}return{statusCode:t,statusText:r,headers:e}}function Ak(n,e,t,r){let i=["--silent","--show-error","--location","--ssl-no-revoke","--insecure","-x",`http://${e}`,"--proxy-ntlm","--proxy-user",":","--max-time",String(Math.max(1,Math.floor((n.timeoutMs??Ng)/1e3)))];return n.method&&n.method!=="GET"&&i.push("-X",n.method),n.data!==void 0&&i.push("--data-binary",n.data),i.push(...Tk(n.headers,n.data!==void 0)),r?(i.push("--dump-header",t),i.push("--output",r)):i.push("--include"),i.push(n.url),i}function Tk(n,e){let t=new Set(["content-length","host","connection","proxy-authorization","proxy-connection","accept-encoding"]),r=[],i=!1;for(let[o,s]of Object.entries(n??{})){let a=o.toLowerCase();a==="content-type"&&(i=!0),t.has(a)||r.push("-H",`${o}: ${s}`)}return e&&!i&&r.push("-H","Content-Type: application/json"),r}function Ok(n,e,t){if(t){let l=Gn.readFileSync(e,"utf8"),d=Gn.readFileSync(t),h=Ag(l);return{statusCode:h.statusCode,statusText:h.statusText,body:d.toString("base64"),headers:h.headers,bodyBuffer:d}}let r=n.lastIndexOf("HTTP/");if(r===-1)return null;let i=n.slice(r),o=i.indexOf(`\r
15
15
  \r
16
16
  `);if(o===-1)return null;let s=i.slice(0,o),a=i.slice(o+4),c=Ag(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function Mg(n){if(process.platform!=="win32")return null;let e=xk()??await Rk();if(!e)return null;let t;n.binary&&(t=Gn.mkdtempSync(Za.join(Og.tmpdir(),"curl-")));let r=t?Za.join(t,"header.tmp"):void 0,i=t?Za.join(t,"body.tmp"):void 0;try{let o=Ak(n,e,r,i),s=await Nk(o,n.timeoutMs);return!s||s.code!==0?null:Ok(s.stdout,r,i)}catch{return null}finally{t&&Gn.rmSync(t,{recursive:!0,force:!0})}}function Nk(n,e){let t=Ik();return new Promise(r=>{let i=Tg(t,n,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="",s=!1,a=setTimeout(()=>{s||(s=!0,i.kill())},e??Ng);i.stdout.on("data",c=>{o+=c.toString()}),i.on("error",()=>{s||(s=!0,clearTimeout(a),r(null))}),i.on("close",c=>{if(clearTimeout(a),s){r(null);return}s=!0,r({code:c??-1,stdout:o})})})}function Lk(n){let e=new URL(n);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}var Bu=class{client;constructor(){let e={timeout:Vo.HTTP_TIMEOUT_MS,headers:{"User-Agent":Ia.USER_AGENT,"accept-language":Ia.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=Mk.create(e),this.client.interceptors.request.use(t=>{let r=xg(t.url??"");return t.proxy=r?Lk(r):!1,t}),this.client.interceptors.response.use(t=>t,t=>{let r=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`,i=new Error(`${t.message}
17
- ${r}`);throw i.code=t.code,i.response=t.response,i})}async get(e,t){try{let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"GET",t)}}async post(e,t){try{let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"POST",t)}}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){try{let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}catch(r){let i=await this.tryCurlFallback(r,e,"GET",t,!0);if(i?.bodyBuffer){if(i.statusCode!==200)throw new Error(`HTTP ${i.statusCode}`);return i.bodyBuffer}throw r}}async postAllowFailure(e,t){try{let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"POST",t)}}async deleteAllowFailure(e,t){try{let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"DELETE",t)}}async getBinaryAllowFailure(e,t){try{let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});let i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}catch(r){let i=await this.tryCurlFallback(r,e,"GET",t,!0);if(i?.bodyBuffer)return{statusCode:i.statusCode,statusText:i.statusText,buffer:i.bodyBuffer,body:i.bodyBuffer.toString("utf8")};throw r}}async withCurlFallback(e,t,r,i){let o=await this.tryCurlFallback(e,t,r,i,!1);if(o)return{data:o.body,statusCode:o.statusCode,statusText:o.statusText,headers:o.headers};throw e}async tryCurlFallback(e,t,r,i,o=!1){if(process.platform!=="win32"||!(e instanceof Error)||!_k(e))return null;let s,a=t;return r==="GET"?i?.params&&(a=$k(t,i.params)):i?.params!==void 0&&i.params!==null&&(s=typeof i.params=="string"?i.params:JSON.stringify(i.params)),Mg({url:a,method:r,data:s,headers:i?.headers,timeoutMs:i?.timeout,binary:o})}},$=new Bu;function _k(n){if(n.response?.status===407)return!0;let e=n.message??"";return/proxy auth(?:oriz|entic)/i.test(e)?!0:n.code==="SELF_SIGNED_CERT_IN_CHAIN"||n.code==="DEPTH_ZERO_SELF_SIGNED_CERT"||n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||n.code==="CERT_HAS_EXPIRED"||n.code==="ERR_TLS_CERT_ALTNAME_INVALID"}function $k(n,e){if(!e||typeof e!="object")return n;let t=new URLSearchParams;for(let[o,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${o}[]`,String(a));else t.append(o,String(s));let r=t.toString();if(!r)return n;let i=n.includes("?")?"&":"?";return`${n}${i}${r}`}import*as Lg from"fs";import*as _g from"path";var $g=["DevEco"];async function es(){let n=await $.get(Et.TAGS_API_URL),t=tc(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(r=>r.id)}async function Fk(n){let e=[],t=Et.DEFAULT_PAGE_SIZE,r=Et.DEFAULT_MAX_PAGES,i=1;for(;i<=r;){let o=await $.post(Et.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[n]}}),s=tc(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function Qa(n){let e=new Map,t=n.map(i=>Fk(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!$g.includes(o.name)))}async function jk(n,e){let t=await $.post(Et.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Et.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return tc(t,"Skills API").data.list}async function ec(n,e){let t=new Map,r=e.map(o=>jk(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!$g.includes(s.name)))}function Wu(n){St(n);let e=[];for(let t of Ze()){let r=Yr(t);if(!Vn(t))continue;let i=_g.join(r,n);Lg.existsSync(i)&&e.push(Nt(t).displayName)}return e.sort()}function tc(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=$.parseJson(n);if(t.code!==Et.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Fg(n){St(n);let e=`${Et.SKILL_API_BASE}/${n}/checksum`,t=await $.get(e);return tc(t,"Checksum API").data}var jg=Vu.promises;function Hg(n,e){let t=Mt.resolve(e),r=Mt.resolve(n),i=Mt.relative(r,t);if(i.startsWith("..")||Mt.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Gu(n){return Mt.isAbsolute(n)?n:Mt.resolve(process.cwd(),n)}function Vk(n){return Uk.createHash("sha256").update(n).digest("hex")}async function Gk(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=Vk(n),i=e.sha256.toLowerCase(),o=Buffer.from(r,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!Bk(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function qu(n){St(n);let e=`${Et.SKILL_API_BASE}/${n}/install?format=zip`,t=await $.getBinary(e),r=await Fg(n);return await Gk(t,r),t}async function Ug(n,e,t){St(t);let r=new Hk(n),i=r.getEntries();try{await jg.stat(e)}catch{await jg.mkdir(e,{recursive:!0})}let o=Mt.join(e,t);Hg(e,o);for(let s of i){let a=Mt.join(o,s.entryName);Hg(o,a)}r.extractAllTo(o,!0)}function qn(){let e=Mt.dirname(Wk(import.meta.url));for(;;){let t=Mt.join(e,"skills","deveco-cli");if(Vu.existsSync(t)&&Vu.statSync(t).isDirectory())return t;let r=Mt.dirname(e);if(r===e)break;e=r}throw new Error("skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.")}function Bg(n){return n?Lt.join(n,".deveco-cli","skills"):Lt.join(F(),"skills")}function Jk(n,e){return St(n),Lt.join(Bg(e),"store",n)}async function Wg(n,e){let t=e??F(),r=await Ai.realpath(t).catch(s=>{if(s.code==="ENOENT")return Ce(t);throw s}),i=Lt.join(r,Lt.relative(t,n)),o=await Ce(i);if(!he(i,o))throw new Error(`Skill storage parent redirects outside its managed location: ${i}`);return o}async function zu(n,e){return Wg(Jk(n,e),e)}async function ts(n,e,t){St(n);let r=e.customPath??Bg(e.project),i=e.customPath?await Ce(Lt.join(r,`.${n}.lock`)):await Wg(Lt.join(r,"locks",`${n}.lock`),e.project);await Ai.mkdir(Lt.dirname(i),{recursive:!0});let o=await zk(r,{realpath:!1,lockfilePath:i,stale:3e4,update:1e4,retries:{retries:100,minTimeout:50,maxTimeout:200}});try{return await t()}finally{await o()}}async function Vg(n){let e=await Ai.lstat(n);if(!e.isDirectory()||e.isSymbolicLink()||!(await Ai.stat(Lt.join(n,"SKILL.md"))).isFile())throw new Error(`Invalid Skill store: ${n}`)}async function Gg(n,e,t,r,i){let o=await zu(n,t),s=await Ne(o);if(!i&&!s&&(await Promise.all(r.map(c=>Ne(c.path)))).every(Boolean))return{results:r.map(c=>Qt(c.path,"already-exists"))};for(let a of r)for(let c of[a.path,...a.legacy])if(Ii(o,c))throw new Error(`Skill store and destination overlap: ${o}, ${c}`);if(!i&&s){try{await Vg(o)}catch(a){throw new Error(`Cannot reuse Skill store ${o}; use --force to replace: ${a.message}`,{cause:a})}return{source:o,results:[]}}return{source:o,results:[await zg(n,e,o)]}}async function qg(n,e,t,r){let i=await Ce(t);return await Iu(i,r)??zg(n,e,i)}async function zg(n,e,t){await Ai.mkdir(Lt.dirname(t),{recursive:!0});let r=`${t}.extract-${qk()}`;try{await Ug(e,r,n);let i=Lt.join(r,n);return await Vg(i),await xu(i,t),{success:!0,path:t,reason:"shared-entity-updated"}}finally{await Ai.rm(r,{recursive:!0,force:!0})}}function rs(n,e){return{success:!1,path:n,error:e instanceof Error?e.message:String(e)}}async function Ju(n,e,t){let r=[];for(let i of vg(e))try{r.push(...await ts(n,i,()=>t(i)))}catch(o){r.push(rs(Xr.join(er(i.project),n),o))}return r}async function Ku(n){return Xu.realpath(n).catch(e=>{if(e.code==="ENOENT"||e.code==="ELOOP")return n;throw e})}async function Yk(n,e){let t=await Xu.realpath(e);for(let r of n.legacy){let i=await Ne(r);if(i&&!i.isSymbolicLink()&&Ii(t,r))throw new Error(`Skill source and legacy destination overlap: ${e}, ${r}`);await Va(r)}}async function Kk(n,e,t,r){let i=[];for(let o of Ze()){let s=Yr(o,e.project);if(e.agents.includes(o)||qa(o,e.project)&&!Vn(o,e.project))continue;let a=await Ce(Xr.join(s,n)),c=await Ne(a);c&&(he(a,t)&&Vn(o,e.project)||r&&c.isSymbolicLink()&&he(await Ku(a),r))&&i.push(Nt(o).displayName)}return[...new Set(i)]}function Xk(n,e){let t=`still used by ${e.join(", ")}`;return console.log(`Skill ${Xr.basename(n)} in ${Xr.dirname(n)} is kept: ${t}.`),Qt(n,t)}async function Yu(n,e,t,r){try{if(!await Ne(n))return;let i=await Kk(e,t,n,r);return i.length?Xk(n,i):await Va(n)}catch(i){return rs(n,i)}}var nr=class{async installBundledSkill(e,t,r=!1){return await Xu.access(Xr.join(e,"SKILL.md")),t.customPath?this.installCustom("deveco-cli",e,t.customPath,r):Ju("deveco-cli",t,i=>this.installScope("deveco-cli",e,i,t.explicitAgents,r))}async installArchiveSkill(e,t,r,i=!1){return St(e),r.customPath?this.installCustom(e,t,r.customPath,i):Ju(e,r,o=>this.installScope(e,t,o,r.explicitAgents,i))}async installCustom(e,t,r,i){let o=Xr.join(r,e);try{return await ts(e,{customPath:r},async()=>[typeof t=="string"?await Wa(t,o,i):await qg(e,t,o,i)])}catch(s){return[rs(o,s)]}}async installScope(e,t,r,i=!0,o=!1){let s=await bg(r,e,i),a=s.filter(l=>!l.skipped),c=s.filter(l=>l.skipped).map(l=>Qt(l.path,"agent-project-root-missing"));if(!a.length)return c;try{let l=typeof t=="string"?{source:t,results:[]}:await Gg(e,t,r.project,a,o);return[...c,...l.results,...l.source?await this.installSkillEntries(l.source,a,o):[]]}catch(l){return[...c,...a.map(d=>rs(d.path,l))]}}async installSkillEntries(e,t,r){let i=[];for(let o of t)try{i.push(await Wa(e,o.path,r)),r&&await Yk(o,e)}catch(s){i.push(rs(o.path,s))}return i}async migrateBundledSkill(e,t){await ts("deveco-cli",t,()=>this.migrateBundledScope(e,t))}async migrateBundledScope(e,t){let r,i=[];for(let o of t.agents)try{for(let s of await Ja({...t,agents:[o]},"deveco-cli"))await this.migrateBundledDestination(e,s,i)}catch(s){r=s,console.error(`Skill migration failed for ${o}: ${s.message}`)}if(r)throw r}async migrateBundledDestination(e,t,r){let i=await Ne(t.path);(!i||!i.isDirectory()&&!i.isSymbolicLink())&&!t.legacy.length||r.some(o=>he(o,t.path))||((await Wa(e,t.path)).reason==="already-exists"&&console.warn(`Skill migration skipped: ${t.path} (already exists; run devecocli init --force to replace).`),r.push(t.path))}async removeSkill(e,t){if(St(e),t.customPath){let r=Xr.join(t.customPath,e);return ts(e,t,async()=>[await Va(r)])}return Ju(e,t,r=>this.removeScope(e,r,t.explicitAgents))}async removeScope(e,t,r=!0){let i=await Ce(Xr.join(er(t.project),e)),o=await this.removeAgentEntries(e,t,i,r);if(o.every(s=>s.success)){let s=await Yu(i,e,t,await Ku(i));s&&o.push(s)}if(o.every(s=>s.success)){let s=await zu(e,t.project),a=await Yu(s,e,{...t,agents:[]},await Ku(s));a&&o.push(a)}return o.length||(console.log(`Skill ${e} not found for the selected agents.`),o.push(Qt(i,"not-installed"))),o}async removeAgentEntries(e,t,r,i){let o=new Set;for(let a of await Ja(t,e,i))if(!a.skipped)for(let c of[a.path,...a.legacy])he(c,r)||o.add(c);let s=[];for(let a of o){let c=await Yu(a,e,t);c&&s.push(c)}return s}};import rc from"fs/promises";import Jg from"path";function Zk(n){return`'${process.platform==="win32"?n.replace(/'/g,"''"):n.replace(/'/g,"'\\''")}'`}async function Qk(n,e){try{if(!(await Ne(n))?.isSymbolicLink())return;let r=await rc.realpath(n);return he(r,e)?void 0:{path:n,reason:`points to ${r}`,repair:!0}}catch(t){let r=t.code,i=r==="ENOENT"||r==="ELOOP"||r==="ENOTDIR";return{path:n,reason:i?"broken link":`cannot check: ${t.message}`,repair:i}}}var Zu=class{checked=new Set;async warnInvalidBundledLinks(e){try{let t=await rc.realpath(e),r=process.platform==="win32"?t.toLowerCase():t;if(this.checked.has(r))return;this.checked.add(r);let i=await rc.realpath(qn());if(!(await rc.stat(Jg.join(i,"SKILL.md"))).isFile())throw new Error(`Skill source has no SKILL.md: ${i}`);let o=await this.checkKnownEntries(t,i);this.reportIssues(t,o)}catch(t){console.warn(`Cannot check project Skill links for ${e}: ${t.message}`)}}async checkKnownEntries(e,t){let r=new Set([er(e),...Ze().map(s=>Lu(e,s))]),i=[],o=[];for(let s of r){let a=Jg.join(s,"deveco-cli");try{let c=await Ce(a);if(i.some(d=>he(d,c)))continue;i.push(c);let l=await Qk(c,t);l&&o.push(l)}catch(c){o.push({path:a,reason:`cannot check: ${c.message}`,repair:!1})}}return o}reportIssues(e,t){for(let r of t)console.warn(`Project Skill link: ${r.path} (${r.reason}).`);t.some(r=>r.repair)&&(console.warn(`Run: devecocli init --project ${Zk(e)} -f`),console.warn("Existing copies and local edits in the selected installation scope will be replaced."))}},tt=new Zu;import rp from"fs";import Qg from"path";import{cyan as mD}from"colorette";import{spawn as cD}from"child_process";import*as Zg from"fs";import*as ic from"path";import{yellow as lD,cyan as dD}from"colorette";import uD from"proper-lockfile";import{compare as eD}from"semver";function Zr(n,e){return eD(n,e)}function Ti(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function Oi(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco/deveco-cli-common"}function ir(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.7"}function Qr(){return"latest"}function _t(){return Number.isFinite(1),1}var Er="@deveco/deveco-cli-knowledgebase";function Ni(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as ns from"fs";import*as is from"path";var tD={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},Qu=new Map,en=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=is.join(e,"cache.json"),this.lockFilePath=is.join(e,"check.lock")}async writeSuccess(e,t=[],r,i,o){let s=this.read();await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,checkedAgainstTag:i,latestDocsVersion:o?o.latestDocsVersion:s.latestDocsVersion??null,latestDocsApiVersion:o?o.latestDocsApiVersion:s.latestDocsApiVersion??null,latestCompatibleDocsVersion:o?o.latestCompatibleDocsVersion:s.latestCompatibleDocsVersion??null,checkedAgainstDocsApi:o?o.checkedAgainstDocsApi:s.checkedAgainstDocsApi??null})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}getLatestDocsVersion(){return this.read().latestDocsVersion??null}getLatestDocsApiVersion(){return this.read().latestDocsApiVersion??null}getLatestCompatibleDocsVersion(){return this.read().latestCompatibleDocsVersion??null}getCheckedAgainstDocsApi(){return this.read().checkedAgainstDocsApi??null}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(n.CHECK_WINDOW_HOUR,0,0,0),r=t>Date.now()?t-n.ONE_DAY_MS:t;return e<r}getLockPath(){return this.lockFilePath}read(){let e=Qu.get(this.cacheFilePath);if(e)return e;try{let t=ns.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return Qu.set(this.cacheFilePath,r),r}catch{return{...tD}}}async write(e){m(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await ns.promises.mkdir(is.dirname(this.cacheFilePath),{recursive:!0}),await ns.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Qu.set(this.cacheFilePath,e)}};import{createRequire as rD}from"module";import{dirname as nD,join as Mi}from"path";import{pathToFileURL as iD}from"url";import{readFile as Yg,access as ep}from"fs/promises";import*as Kg from"semver";var oD=rD(import.meta.url);async function sD(){try{let n=oD.resolve("@deveco/deveco-cli-knowledgebase/package.json"),e=JSON.parse(await Yg(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:nD(n)}}catch{return null}}async function Xg(){let n=F(),e=Mi(n,"doc-data","current.json"),t;try{t=JSON.parse(await Yg(e,"utf8"))}catch{return null}let r=Mi(n,"doc-data",t.version);try{return await ep(Mi(r,"dist","engine","index.js")),await ep(Mi(r,"docs.zip")),await ep(Mi(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function aD(){return[await Xg(),await sD()].filter(e=>e!==null).sort((e,t)=>Kg.rcompare(e.version,t.version))}async function Li(){let n=_t(),e=await Xg();return e&&e.apiVersion<=n?e.version:null}async function nc(){let n=_t(),e=await aD(),t=!1;for(let r of e){if(r.apiVersion>n){m(`docs: skip candidate v${r.version} (apiVersion ${r.apiVersion} > ${n})`);continue}t=!0;try{let i=Mi(r.dir,"dist","engine","index.js");return await import(iD(i).href)}catch(i){m(`docs: candidate v${r.version} load failed: ${i instanceof Error?i.message:String(i)}`)}}throw e.length>0&&!t?new Error("Documentation package version is incompatible, please upgrade CLI"):new Error("No available documentation package, please run `devecocli docs update` or reinstall CLI")}var os=class{constructor(e){this.actionCommand=e}cache=new en(ic.join(F(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=ir(),t=Qr(),r=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=r!=null&&r!==e,a=[],c=o?null:this.cache.getLatestVersion();c&&Zr(c,e)>0&&a.push(lD(`New cli version ${c} available, run \`devecocli update\` to update`));let l=await this.buildDocsMessage();if(l.message&&a.push(l.message),a.length>0){console.log();for(let d of a)console.log(d)}(o||s||l.stale||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){m(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}async buildDocsMessage(){let e=_t(),t=this.cache.getCheckedAgainstDocsApi();if(t!=null&&t!==e)return{message:null,stale:!0};let r=this.cache.getLatestCompatibleDocsVersion();if(!r)return{message:null,stale:!1};let i=await Li();return i&&Zr(r,i)<=0?{message:null,stale:!1}:{message:dD(`New docs version ${r} available, run \`devecocli docs update\` to upgrade`),stale:!1}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await pD(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];m(`Executing: ${process.execPath} ${e.join(" ")}`),cD(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{m("Update check lock held by another process, skipping")}}};async function pD(n,e){await Zg.promises.mkdir(ic.dirname(n),{recursive:!0});let t=await uD.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}var tp=rp.promises;async function fD(n){let e=Ga(n);for(let t of e)Nt(t);return e}async function hD(n){return Ze().filter(e=>Vn(e,n))}async function gD(){let n=qn();await new nr().migrateBundledSkill(n,{agents:Ze()})}async function ey(){try{let n=Qg.join(F(),"skills","migration-version"),e=await tp.readFile(n,"utf8").catch(r=>{if(r.code==="ENOENT")return"";throw r}),t=ir();if(e.trim()===t)return;await gD(),await tp.mkdir(Qg.dirname(n),{recursive:!0}),await tp.writeFile(n,t,"utf8")}catch{}}function _i(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(mD("Finished:"));for(let i of n){if(!i.path)continue;let o=i.reason==="already-exists"?"already exists; use --force to replace":i.reason,s=i.fallbackReason?" (link failed: "+i.fallbackReason+")":o??i.error?" ("+(o??i.error)+")":"",a=i.success?i.skipped?"skipped":i.mode??(i.reason==="shared-entity-updated"?"updated":"removed"):"failed";console.log(" "+a+": "+i.path+s)}console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Pr(n,e,t){if(!rp.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!rp.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function $i(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Gu(n):void 0,resolvedProject:e?Gu(e):void 0}}async function Fi(n,e,t){if(e)return{agents:[],projectAgents:[],customPath:e};let r=n.agent?await fD(n.agent):await hD(t);if(!r.length)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return t?{agents:[],explicitAgents:!!n.agent,projectAgents:r.map(i=>({project:t,agent:i}))}:{agents:r,projectAgents:[],explicitAgents:!!n.agent}}import yD from"fs";import oc from"path";import{cyan as wD}from"colorette";import*as sc from"smol-toml";var ji=yD.promises;async function vD(n){try{let e=await ji.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${n}: ${e.message}`,{cause:e})}}async function bD(n){try{let e=await ji.readFile(n,"utf8");return e.trim()===""?{}:sc.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${n}: ${e.message}`,{cause:e})}}async function SD(n,e){let t=oc.dirname(n);await ji.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await ji.writeFile(n,r,"utf8")}async function ED(n,e){let t=oc.dirname(n);await ji.mkdir(t,{recursive:!0});let r=sc.stringify(e);await ji.writeFile(n,r,"utf8")}function ty(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function ry(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function ny(n,e){return n.format==="codex"?bD(e):vD(e)}async function iy(n,e,t){return n.format==="codex"?ED(e,t):SD(e,t)}async function np(n,e,t=!1){let r=Sr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Sr).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await ny(r,r.globalConfigPath);if(ty(i,r.mcpServersKey,rr)&&!t)return console.log(`MCP server ${rr} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=Xa(r,void 0);return ry(i,r.mcpServersKey,rr,o,t),await iy(r,r.globalConfigPath,i),console.log(`MCP server ${rr} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function ac(n,e,t=!1){let r=Sr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Sr).join(", ")}`};let i=oc.isAbsolute(r.projectConfigPath)?r.projectConfigPath:oc.join(e,r.projectConfigPath);try{let o=await ny(r,i);if(ty(o,r.mcpServersKey,rr)&&!t)return console.log(`MCP server ${rr} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=Xa(r,e);return ry(o,r.mcpServersKey,rr,s,t),await iy(r,i,o),console.log(`MCP server ${rr} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function ip(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(wD("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}import PD from"fs";import CD from"path";import{homedir as kD}from"os";async function op(n,e){let t=[],r=n.agent?Ga(n.agent):Object.keys(Ka);for(let i of r){if(!Object.prototype.hasOwnProperty.call(Ka,i))throw new Error(`Invalid MCP agent: ${i}`);(n.agent||PD.existsSync(CD.join(kD(),Ka[i])))&&t.push(i)}if(!t.length)throw new Error("No agents supporting MCP configuration found; use --skill");return e?{agents:[],projectAgents:t.map(i=>({project:e,agent:i}))}:{agents:t,projectAgents:[]}}import{spawnSync as dy}from"child_process";import Me from"fs";import*as rt from"os";import*as I from"path";import lc from"fs";import*as dc from"os";import*as ss from"path";import xD from"regedit";import{execFileSync as DD}from"child_process";import oy from"fs";import*as sy from"os";import*as sp from"path";function cc(n,e){let t=sp.join(n,"Contents","Info.plist");if(!oy.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=DD(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function RD(n){let e=cc(n,"CFBundleShortVersionString");if(!e)return cc(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[cc(n,"CFBundleVersion"),cc(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function tn(n){if(sy.platform()==="darwin")return RD(n);let e=sp.join(n,"product-info.json");try{let t=JSON.parse(oy.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var ID="DevEco Studio",AD=["Contents","Resources","product-info.json"],TD="name";function OD(n){return n.filter(e=>{try{return lc.statSync(e).isDirectory()}catch{return!1}})}function ND(n){let e=ss.join(n,...AD);if(lc.existsSync(e))try{let r=JSON.parse(lc.readFileSync(e,"utf8"))[TD];return typeof r=="string"&&r.trim()?r.trim():void 0}catch{return}}function MD(n){return ND(n)===ID}function LD(){let n=[];for(let e of[ss.join(dc.homedir(),"Applications"),"/Applications"])try{n.push(...lc.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>ss.join(e,t)).filter(MD))}catch{}return n}function ay(n){return new Promise((e,t)=>xD.list(n,(r,i)=>r?t(r):e(i)))}async function cy(n,e,t){let i=((await ay([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await ay(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function _D(){let n=[ss.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{n.push(...await cy(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{n.push(...await cy(e,()=>!0,""))}catch{}return n}async function ly(){let n=dc.platform();if(n==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=n==="darwin"?LD():await _D(),t=OD(e).flatMap(r=>{let i=tn(r);return i?(m(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation, or set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");return t.reduce((r,i)=>Ti(i.version,r.version)>0?i:r)}var $D=/^#\s*Version:\s*(\S+)/,FD="26.0.0.810";function jD(n){try{let e=JSON.parse(Me.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){m(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function HD(n){let e=I.join(n,"default","openharmony");return[I.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>I.join(e,t,"oh-uni-package.json"))]}var P=class n{constructor(e,t,r,i,o,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get arktsLangServerPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).arktsLangServerCandidates;for(let t of e)if(Me.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return Me.existsSync(e)?e:null}get javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}assertJava(){if(this._sourceType==="clt"&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.")}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return Ti(e,t)}static async checkVersion(){let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?n.readCltVersion(this._toolchainRoot):tn(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.0.0"){this.assertStudio(),n.assertMinimumVersion(tn(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot)}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,r,i,o){if(!e)throw new y(`Failed to determine ${t} version from ${r} at ${o}`,`Failed to determine ${t} version from ${r}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new y(`Invalid ${t} version "${e}" from ${r} at ${o}`,`Invalid ${t} version "${e}" from ${r}`);if(Ti(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
17
+ ${r}`);throw i.code=t.code,i.response=t.response,i})}async get(e,t){try{let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"GET",t)}}async post(e,t){try{let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"POST",t)}}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){try{let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}catch(r){let i=await this.tryCurlFallback(r,e,"GET",t,!0);if(i?.bodyBuffer){if(i.statusCode!==200)throw new Error(`HTTP ${i.statusCode}`);return i.bodyBuffer}throw r}}async postAllowFailure(e,t){try{let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"POST",t)}}async deleteAllowFailure(e,t){try{let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(r)}catch(r){return this.withCurlFallback(r,e,"DELETE",t)}}async getBinaryAllowFailure(e,t){try{let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});if(r.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});let i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}catch(r){let i=await this.tryCurlFallback(r,e,"GET",t,!0);if(i?.bodyBuffer)return{statusCode:i.statusCode,statusText:i.statusText,buffer:i.bodyBuffer,body:i.bodyBuffer.toString("utf8")};throw r}}async withCurlFallback(e,t,r,i){let o=await this.tryCurlFallback(e,t,r,i,!1);if(o)return{data:o.body,statusCode:o.statusCode,statusText:o.statusText,headers:o.headers};throw e}async tryCurlFallback(e,t,r,i,o=!1){if(process.platform!=="win32"||!(e instanceof Error)||!_k(e))return null;let s,a=t;return r==="GET"?i?.params&&(a=$k(t,i.params)):i?.params!==void 0&&i.params!==null&&(s=typeof i.params=="string"?i.params:JSON.stringify(i.params)),Mg({url:a,method:r,data:s,headers:i?.headers,timeoutMs:i?.timeout,binary:o})}},$=new Bu;function _k(n){if(n.response?.status===407)return!0;let e=n.message??"";return/proxy auth(?:oriz|entic)/i.test(e)?!0:n.code==="SELF_SIGNED_CERT_IN_CHAIN"||n.code==="DEPTH_ZERO_SELF_SIGNED_CERT"||n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||n.code==="CERT_HAS_EXPIRED"||n.code==="ERR_TLS_CERT_ALTNAME_INVALID"}function $k(n,e){if(!e||typeof e!="object")return n;let t=new URLSearchParams;for(let[o,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${o}[]`,String(a));else t.append(o,String(s));let r=t.toString();if(!r)return n;let i=n.includes("?")?"&":"?";return`${n}${i}${r}`}import*as Lg from"fs";import*as _g from"path";var $g=["DevEco"];async function es(){let n=await $.get(Et.TAGS_API_URL),t=tc(n,"Tags API").data.skill.filter(r=>r.name==="HMOS");if(t.length===0)throw new Error("No HMOS tag found.");return t.map(r=>r.id)}async function Fk(n){let e=[],t=Et.DEFAULT_PAGE_SIZE,r=Et.DEFAULT_MAX_PAGES,i=1;for(;i<=r;){let o=await $.post(Et.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[n]}}),s=tc(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function Qa(n){let e=new Map,t=n.map(i=>Fk(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!$g.includes(o.name)))}async function jk(n,e){let t=await $.post(Et.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Et.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return tc(t,"Skills API").data.list}async function ec(n,e){let t=new Map,r=e.map(o=>jk(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!$g.includes(s.name)))}function Wu(n){St(n);let e=[];for(let t of Ze()){let r=Yr(t);if(!Vn(t))continue;let i=_g.join(r,n);Lg.existsSync(i)&&e.push(Nt(t).displayName)}return e.sort()}function tc(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=$.parseJson(n);if(t.code!==Et.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function Fg(n){St(n);let e=`${Et.SKILL_API_BASE}/${n}/checksum`,t=await $.get(e);return tc(t,"Checksum API").data}var jg=Vu.promises;function Hg(n,e){let t=Mt.resolve(e),r=Mt.resolve(n),i=Mt.relative(r,t);if(i.startsWith("..")||Mt.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Gu(n){return Mt.isAbsolute(n)?n:Mt.resolve(process.cwd(),n)}function Vk(n){return Uk.createHash("sha256").update(n).digest("hex")}async function Gk(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=Vk(n),i=e.sha256.toLowerCase(),o=Buffer.from(r,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!Bk(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function qu(n){St(n);let e=`${Et.SKILL_API_BASE}/${n}/install?format=zip`,t=await $.getBinary(e),r=await Fg(n);return await Gk(t,r),t}async function Ug(n,e,t){St(t);let r=new Hk(n),i=r.getEntries();try{await jg.stat(e)}catch{await jg.mkdir(e,{recursive:!0})}let o=Mt.join(e,t);Hg(e,o);for(let s of i){let a=Mt.join(o,s.entryName);Hg(o,a)}r.extractAllTo(o,!0)}function qn(){let e=Mt.dirname(Wk(import.meta.url));for(;;){let t=Mt.join(e,"skills","deveco-cli");if(Vu.existsSync(t)&&Vu.statSync(t).isDirectory())return t;let r=Mt.dirname(e);if(r===e)break;e=r}throw new Error("skills/deveco-cli directory not found in deveco-cli package. Reinstall deveco-cli.")}function Bg(n){return n?Lt.join(n,".deveco-cli","skills"):Lt.join(F(),"skills")}function Jk(n,e){return St(n),Lt.join(Bg(e),"store",n)}async function Wg(n,e){let t=e??F(),r=await Ai.realpath(t).catch(s=>{if(s.code==="ENOENT")return Ce(t);throw s}),i=Lt.join(r,Lt.relative(t,n)),o=await Ce(i);if(!he(i,o))throw new Error(`Skill storage parent redirects outside its managed location: ${i}`);return o}async function zu(n,e){return Wg(Jk(n,e),e)}async function ts(n,e,t){St(n);let r=e.customPath??Bg(e.project),i=e.customPath?await Ce(Lt.join(r,`.${n}.lock`)):await Wg(Lt.join(r,"locks",`${n}.lock`),e.project);await Ai.mkdir(Lt.dirname(i),{recursive:!0});let o=await zk(r,{realpath:!1,lockfilePath:i,stale:3e4,update:1e4,retries:{retries:100,minTimeout:50,maxTimeout:200}});try{return await t()}finally{await o()}}async function Vg(n){let e=await Ai.lstat(n);if(!e.isDirectory()||e.isSymbolicLink()||!(await Ai.stat(Lt.join(n,"SKILL.md"))).isFile())throw new Error(`Invalid Skill store: ${n}`)}async function Gg(n,e,t,r,i){let o=await zu(n,t),s=await Ne(o);if(!i&&!s&&(await Promise.all(r.map(c=>Ne(c.path)))).every(Boolean))return{results:r.map(c=>Qt(c.path,"already-exists"))};for(let a of r)for(let c of[a.path,...a.legacy])if(Ii(o,c))throw new Error(`Skill store and destination overlap: ${o}, ${c}`);if(!i&&s){try{await Vg(o)}catch(a){throw new Error(`Cannot reuse Skill store ${o}; use --force to replace: ${a.message}`,{cause:a})}return{source:o,results:[]}}return{source:o,results:[await zg(n,e,o)]}}async function qg(n,e,t,r){let i=await Ce(t);return await Iu(i,r)??zg(n,e,i)}async function zg(n,e,t){await Ai.mkdir(Lt.dirname(t),{recursive:!0});let r=`${t}.extract-${qk()}`;try{await Ug(e,r,n);let i=Lt.join(r,n);return await Vg(i),await xu(i,t),{success:!0,path:t,reason:"shared-entity-updated"}}finally{await Ai.rm(r,{recursive:!0,force:!0})}}function rs(n,e){return{success:!1,path:n,error:e instanceof Error?e.message:String(e)}}async function Ju(n,e,t){let r=[];for(let i of vg(e))try{r.push(...await ts(n,i,()=>t(i)))}catch(o){r.push(rs(Xr.join(er(i.project),n),o))}return r}async function Ku(n){return Xu.realpath(n).catch(e=>{if(e.code==="ENOENT"||e.code==="ELOOP")return n;throw e})}async function Yk(n,e){let t=await Xu.realpath(e);for(let r of n.legacy){let i=await Ne(r);if(i&&!i.isSymbolicLink()&&Ii(t,r))throw new Error(`Skill source and legacy destination overlap: ${e}, ${r}`);await Va(r)}}async function Kk(n,e,t,r){let i=[];for(let o of Ze()){let s=Yr(o,e.project);if(e.agents.includes(o)||qa(o,e.project)&&!Vn(o,e.project))continue;let a=await Ce(Xr.join(s,n)),c=await Ne(a);c&&(he(a,t)&&Vn(o,e.project)||r&&c.isSymbolicLink()&&he(await Ku(a),r))&&i.push(Nt(o).displayName)}return[...new Set(i)]}function Xk(n,e){let t=`still used by ${e.join(", ")}`;return console.log(`Skill ${Xr.basename(n)} in ${Xr.dirname(n)} is kept: ${t}.`),Qt(n,t)}async function Yu(n,e,t,r){try{if(!await Ne(n))return;let i=await Kk(e,t,n,r);return i.length?Xk(n,i):await Va(n)}catch(i){return rs(n,i)}}var nr=class{async installBundledSkill(e,t,r=!1){return await Xu.access(Xr.join(e,"SKILL.md")),t.customPath?this.installCustom("deveco-cli",e,t.customPath,r):Ju("deveco-cli",t,i=>this.installScope("deveco-cli",e,i,t.explicitAgents,r))}async installArchiveSkill(e,t,r,i=!1){return St(e),r.customPath?this.installCustom(e,t,r.customPath,i):Ju(e,r,o=>this.installScope(e,t,o,r.explicitAgents,i))}async installCustom(e,t,r,i){let o=Xr.join(r,e);try{return await ts(e,{customPath:r},async()=>[typeof t=="string"?await Wa(t,o,i):await qg(e,t,o,i)])}catch(s){return[rs(o,s)]}}async installScope(e,t,r,i=!0,o=!1){let s=await bg(r,e,i),a=s.filter(l=>!l.skipped),c=s.filter(l=>l.skipped).map(l=>Qt(l.path,"agent-project-root-missing"));if(!a.length)return c;try{let l=typeof t=="string"?{source:t,results:[]}:await Gg(e,t,r.project,a,o);return[...c,...l.results,...l.source?await this.installSkillEntries(l.source,a,o):[]]}catch(l){return[...c,...a.map(d=>rs(d.path,l))]}}async installSkillEntries(e,t,r){let i=[];for(let o of t)try{i.push(await Wa(e,o.path,r)),r&&await Yk(o,e)}catch(s){i.push(rs(o.path,s))}return i}async migrateBundledSkill(e,t){await ts("deveco-cli",t,()=>this.migrateBundledScope(e,t))}async migrateBundledScope(e,t){let r,i=[];for(let o of t.agents)try{for(let s of await Ja({...t,agents:[o]},"deveco-cli"))await this.migrateBundledDestination(e,s,i)}catch(s){r=s,console.error(`Skill migration failed for ${o}: ${s.message}`)}if(r)throw r}async migrateBundledDestination(e,t,r){let i=await Ne(t.path);(!i||!i.isDirectory()&&!i.isSymbolicLink())&&!t.legacy.length||r.some(o=>he(o,t.path))||((await Wa(e,t.path)).reason==="already-exists"&&console.warn(`Skill migration skipped: ${t.path} (already exists; run devecocli init --force to replace).`),r.push(t.path))}async removeSkill(e,t){if(St(e),t.customPath){let r=Xr.join(t.customPath,e);return ts(e,t,async()=>[await Va(r)])}return Ju(e,t,r=>this.removeScope(e,r,t.explicitAgents))}async removeScope(e,t,r=!0){let i=await Ce(Xr.join(er(t.project),e)),o=await this.removeAgentEntries(e,t,i,r);if(o.every(s=>s.success)){let s=await Yu(i,e,t,await Ku(i));s&&o.push(s)}if(o.every(s=>s.success)){let s=await zu(e,t.project),a=await Yu(s,e,{...t,agents:[]},await Ku(s));a&&o.push(a)}return o.length||(console.log(`Skill ${e} not found for the selected agents.`),o.push(Qt(i,"not-installed"))),o}async removeAgentEntries(e,t,r,i){let o=new Set;for(let a of await Ja(t,e,i))if(!a.skipped)for(let c of[a.path,...a.legacy])he(c,r)||o.add(c);let s=[];for(let a of o){let c=await Yu(a,e,t);c&&s.push(c)}return s}};import rc from"fs/promises";import Jg from"path";function Zk(n){return`'${process.platform==="win32"?n.replace(/'/g,"''"):n.replace(/'/g,"'\\''")}'`}async function Qk(n,e){try{if(!(await Ne(n))?.isSymbolicLink())return;let r=await rc.realpath(n);return he(r,e)?void 0:{path:n,reason:`points to ${r}`,repair:!0}}catch(t){let r=t.code,i=r==="ENOENT"||r==="ELOOP"||r==="ENOTDIR";return{path:n,reason:i?"broken link":`cannot check: ${t.message}`,repair:i}}}var Zu=class{checked=new Set;async warnInvalidBundledLinks(e){try{let t=await rc.realpath(e),r=process.platform==="win32"?t.toLowerCase():t;if(this.checked.has(r))return;this.checked.add(r);let i=await rc.realpath(qn());if(!(await rc.stat(Jg.join(i,"SKILL.md"))).isFile())throw new Error(`Skill source has no SKILL.md: ${i}`);let o=await this.checkKnownEntries(t,i);this.reportIssues(t,o)}catch(t){console.warn(`Cannot check project Skill links for ${e}: ${t.message}`)}}async checkKnownEntries(e,t){let r=new Set([er(e),...Ze().map(s=>Lu(e,s))]),i=[],o=[];for(let s of r){let a=Jg.join(s,"deveco-cli");try{let c=await Ce(a);if(i.some(d=>he(d,c)))continue;i.push(c);let l=await Qk(c,t);l&&o.push(l)}catch(c){o.push({path:a,reason:`cannot check: ${c.message}`,repair:!1})}}return o}reportIssues(e,t){for(let r of t)console.warn(`Project Skill link: ${r.path} (${r.reason}).`);t.some(r=>r.repair)&&(console.warn(`Run: devecocli init --project ${Zk(e)} -f`),console.warn("Existing copies and local edits in the selected installation scope will be replaced."))}},tt=new Zu;import rp from"fs";import Qg from"path";import{cyan as mD}from"colorette";import{spawn as cD}from"child_process";import*as Zg from"fs";import*as ic from"path";import{yellow as lD,cyan as dD}from"colorette";import uD from"proper-lockfile";import{compare as eD}from"semver";function Zr(n,e){return eD(n,e)}function Ti(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function Oi(){return process.env.DEVECO_CLI_WRAPPER_NAME?process.env.DEVECO_CLI_WRAPPER_NAME:"@deveco/deveco-cli-common"}function ir(){return process.env.DEVECO_CLI_WRAPPER_VERSION?process.env.DEVECO_CLI_WRAPPER_VERSION:"1.3.8"}function Qr(){return"latest"}function _t(){return Number.isFinite(1),1}var Er="@deveco/deveco-cli-knowledgebase";function Ni(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as ns from"fs";import*as is from"path";var tD={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null,latestDocsVersion:null,latestDocsApiVersion:null,latestCompatibleDocsVersion:null,checkedAgainstDocsApi:null},Qu=new Map,en=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=is.join(e,"cache.json"),this.lockFilePath=is.join(e,"check.lock")}async writeSuccess(e,t=[],r,i,o){let s=this.read();await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,checkedAgainstTag:i,latestDocsVersion:o?o.latestDocsVersion:s.latestDocsVersion??null,latestDocsApiVersion:o?o.latestDocsApiVersion:s.latestDocsApiVersion??null,latestCompatibleDocsVersion:o?o.latestCompatibleDocsVersion:s.latestCompatibleDocsVersion??null,checkedAgainstDocsApi:o?o.checkedAgainstDocsApi:s.checkedAgainstDocsApi??null})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}getLatestDocsVersion(){return this.read().latestDocsVersion??null}getLatestDocsApiVersion(){return this.read().latestDocsApiVersion??null}getLatestCompatibleDocsVersion(){return this.read().latestCompatibleDocsVersion??null}getCheckedAgainstDocsApi(){return this.read().checkedAgainstDocsApi??null}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(n.CHECK_WINDOW_HOUR,0,0,0),r=t>Date.now()?t-n.ONE_DAY_MS:t;return e<r}getLockPath(){return this.lockFilePath}read(){let e=Qu.get(this.cacheFilePath);if(e)return e;try{let t=ns.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return Qu.set(this.cacheFilePath,r),r}catch{return{...tD}}}async write(e){m(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await ns.promises.mkdir(is.dirname(this.cacheFilePath),{recursive:!0}),await ns.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Qu.set(this.cacheFilePath,e)}};import{createRequire as rD}from"module";import{dirname as nD,join as Mi}from"path";import{pathToFileURL as iD}from"url";import{readFile as Yg,access as ep}from"fs/promises";import*as Kg from"semver";var oD=rD(import.meta.url);async function sD(){try{let n=oD.resolve("@deveco/deveco-cli-knowledgebase/package.json"),e=JSON.parse(await Yg(n,"utf8"));return{version:e.version,apiVersion:e.apiVersion??0,dir:nD(n)}}catch{return null}}async function Xg(){let n=F(),e=Mi(n,"doc-data","current.json"),t;try{t=JSON.parse(await Yg(e,"utf8"))}catch{return null}let r=Mi(n,"doc-data",t.version);try{return await ep(Mi(r,"dist","engine","index.js")),await ep(Mi(r,"docs.zip")),await ep(Mi(r,"index.zip")),{version:t.version,apiVersion:t.apiVersion,dir:r}}catch{return null}}async function aD(){return[await Xg(),await sD()].filter(e=>e!==null).sort((e,t)=>Kg.rcompare(e.version,t.version))}async function Li(){let n=_t(),e=await Xg();return e&&e.apiVersion<=n?e.version:null}async function nc(){let n=_t(),e=await aD(),t=!1;for(let r of e){if(r.apiVersion>n){m(`docs: skip candidate v${r.version} (apiVersion ${r.apiVersion} > ${n})`);continue}t=!0;try{let i=Mi(r.dir,"dist","engine","index.js");return await import(iD(i).href)}catch(i){m(`docs: candidate v${r.version} load failed: ${i instanceof Error?i.message:String(i)}`)}}throw e.length>0&&!t?new Error("Documentation package version is incompatible, please upgrade CLI"):new Error("No available documentation package, please run `devecocli docs update` or reinstall CLI")}var os=class{constructor(e){this.actionCommand=e}cache=new en(ic.join(F(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=ir(),t=Qr(),r=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=r!=null&&r!==e,a=[],c=o?null:this.cache.getLatestVersion();c&&Zr(c,e)>0&&a.push(lD(`New cli version ${c} available, run \`devecocli update\` to update`));let l=await this.buildDocsMessage();if(l.message&&a.push(l.message),a.length>0){console.log();for(let d of a)console.log(d)}(o||s||l.stale||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){m(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}async buildDocsMessage(){let e=_t(),t=this.cache.getCheckedAgainstDocsApi();if(t!=null&&t!==e)return{message:null,stale:!0};let r=this.cache.getLatestCompatibleDocsVersion();if(!r)return{message:null,stale:!1};let i=await Li();return i&&Zr(r,i)<=0?{message:null,stale:!1}:{message:dD(`New docs version ${r} available, run \`devecocli docs update\` to upgrade`),stale:!1}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await pD(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];m(`Executing: ${process.execPath} ${e.join(" ")}`),cD(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{m("Update check lock held by another process, skipping")}}};async function pD(n,e){await Zg.promises.mkdir(ic.dirname(n),{recursive:!0});let t=await uD.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}var tp=rp.promises;async function fD(n){let e=Ga(n);for(let t of e)Nt(t);return e}async function hD(n){return Ze().filter(e=>Vn(e,n))}async function gD(){let n=qn();await new nr().migrateBundledSkill(n,{agents:Ze()})}async function ey(){try{let n=Qg.join(F(),"skills","migration-version"),e=await tp.readFile(n,"utf8").catch(r=>{if(r.code==="ENOENT")return"";throw r}),t=ir();if(e.trim()===t)return;await gD(),await tp.mkdir(Qg.dirname(n),{recursive:!0}),await tp.writeFile(n,t,"utf8")}catch{}}function _i(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(mD("Finished:"));for(let i of n){if(!i.path)continue;let o=i.reason==="already-exists"?"already exists; use --force to replace":i.reason,s=i.fallbackReason?" (link failed: "+i.fallbackReason+")":o??i.error?" ("+(o??i.error)+")":"",a=i.success?i.skipped?"skipped":i.mode??(i.reason==="shared-entity-updated"?"updated":"removed"):"failed";console.log(" "+a+": "+i.path+s)}console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Pr(n,e,t){if(!rp.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!rp.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function $i(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Gu(n):void 0,resolvedProject:e?Gu(e):void 0}}async function Fi(n,e,t){if(e)return{agents:[],projectAgents:[],customPath:e};let r=n.agent?await fD(n.agent):await hD(t);if(!r.length)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return t?{agents:[],explicitAgents:!!n.agent,projectAgents:r.map(i=>({project:t,agent:i}))}:{agents:r,projectAgents:[],explicitAgents:!!n.agent}}import yD from"fs";import oc from"path";import{cyan as wD}from"colorette";import*as sc from"smol-toml";var ji=yD.promises;async function vD(n){try{let e=await ji.readFile(n,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read configuration file ${n}: ${e.message}`,{cause:e})}}async function bD(n){try{let e=await ji.readFile(n,"utf8");return e.trim()===""?{}:sc.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read TOML config file ${n}: ${e.message}`,{cause:e})}}async function SD(n,e){let t=oc.dirname(n);await ji.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await ji.writeFile(n,r,"utf8")}async function ED(n,e){let t=oc.dirname(n);await ji.mkdir(t,{recursive:!0});let r=sc.stringify(e);await ji.writeFile(n,r,"utf8")}function ty(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function ry(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function ny(n,e){return n.format==="codex"?bD(e):vD(e)}async function iy(n,e,t){return n.format==="codex"?ED(e,t):SD(e,t)}async function np(n,e,t=!1){let r=Sr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Sr).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await ny(r,r.globalConfigPath);if(ty(i,r.mcpServersKey,rr)&&!t)return console.log(`MCP server ${rr} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=Xa(r,void 0);return ry(i,r.mcpServersKey,rr,o,t),await iy(r,r.globalConfigPath,i),console.log(`MCP server ${rr} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function ac(n,e,t=!1){let r=Sr[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Sr).join(", ")}`};let i=oc.isAbsolute(r.projectConfigPath)?r.projectConfigPath:oc.join(e,r.projectConfigPath);try{let o=await ny(r,i);if(ty(o,r.mcpServersKey,rr)&&!t)return console.log(`MCP server ${rr} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=Xa(r,e);return ry(o,r.mcpServersKey,rr,s,t),await iy(r,i,o),console.log(`MCP server ${rr} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function ip(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(wD("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}import PD from"fs";import CD from"path";import{homedir as kD}from"os";async function op(n,e){let t=[],r=n.agent?Ga(n.agent):Object.keys(Ka);for(let i of r){if(!Object.prototype.hasOwnProperty.call(Ka,i))throw new Error(`Invalid MCP agent: ${i}`);(n.agent||PD.existsSync(CD.join(kD(),Ka[i])))&&t.push(i)}if(!t.length)throw new Error("No agents supporting MCP configuration found; use --skill");return e?{agents:[],projectAgents:t.map(i=>({project:e,agent:i}))}:{agents:t,projectAgents:[]}}import{spawnSync as dy}from"child_process";import Me from"fs";import*as rt from"os";import*as I from"path";import lc from"fs";import*as dc from"os";import*as ss from"path";import xD from"regedit";import{execFileSync as DD}from"child_process";import oy from"fs";import*as sy from"os";import*as sp from"path";function cc(n,e){let t=sp.join(n,"Contents","Info.plist");if(!oy.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=DD(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function RD(n){let e=cc(n,"CFBundleShortVersionString");if(!e)return cc(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[cc(n,"CFBundleVersion"),cc(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function tn(n){if(sy.platform()==="darwin")return RD(n);let e=sp.join(n,"product-info.json");try{let t=JSON.parse(oy.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}var ID="DevEco Studio",AD=["Contents","Resources","product-info.json"],TD="name";function OD(n){return n.filter(e=>{try{return lc.statSync(e).isDirectory()}catch{return!1}})}function ND(n){let e=ss.join(n,...AD);if(lc.existsSync(e))try{let r=JSON.parse(lc.readFileSync(e,"utf8"))[TD];return typeof r=="string"&&r.trim()?r.trim():void 0}catch{return}}function MD(n){return ND(n)===ID}function LD(){let n=[];for(let e of[ss.join(dc.homedir(),"Applications"),"/Applications"])try{n.push(...lc.readdirSync(e).filter(t=>t.endsWith(".app")).map(t=>ss.join(e,t)).filter(MD))}catch{}return n}function ay(n){return new Promise((e,t)=>xD.list(n,(r,i)=>r?t(r):e(i)))}async function cy(n,e,t){let i=((await ay([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await ay(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function _D(){let n=[ss.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{n.push(...await cy(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{n.push(...await cy(e,()=>!0,""))}catch{}return n}async function ly(){let n=dc.platform();if(n==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=n==="darwin"?LD():await _D(),t=OD(e).flatMap(r=>{let i=tn(r);return i?(m(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation, or set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");return t.reduce((r,i)=>Ti(i.version,r.version)>0?i:r)}var $D=/^#\s*Version:\s*(\S+)/,FD="26.0.0.810";function jD(n){try{let e=JSON.parse(Me.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){m(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function HD(n){let e=I.join(n,"default","openharmony");return[I.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>I.join(e,t,"oh-uni-package.json"))]}var P=class n{constructor(e,t,r,i,o,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this._nodePath}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get arktsLangServerPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).arktsLangServerCandidates;for(let t of e)if(Me.existsSync(t.marker))return t.root;return null}get clangdPath(){let e=n.buildToolPaths(this._toolchainRoot,this._sourceType).clangdPath;return Me.existsSync(e)?e:null}get javaPath(){return this._javaPath??""}get sdkPath(){return this._sdkPath}get hdcPath(){return this._hdcPath}get emulatorPath(){return this._emulatorPath}get emulatorLauncherPath(){return this.emulatorPath}assertJava(){if(this._sourceType==="clt"&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.")}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return Ti(e,t)}static async checkVersion(){let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}readVersion(){return this._sourceType==="clt"?n.readCltVersion(this._toolchainRoot):tn(this._toolchainRoot)}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.0.0"){this.assertStudio(),n.assertMinimumVersion(tn(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot)}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,r,i,o){if(!e)throw new y(`Failed to determine ${t} version from ${r} at ${o}`,`Failed to determine ${t} version from ${r}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new y(`Invalid ${t} version "${e}" from ${r} at ${o}`,`Invalid ${t} version "${e}" from ${r}`);if(Ti(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
18
18
  ${Hu}`)}static resolveCodelinterPath(e,t){let r=n.buildToolPaths(e,t).codelinterCandidates,i=r.find(n.isFile);if(!i){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new y(`${a}
19
19
  Searched paths:
20
20
  ${r.join(`
@@ -1330,7 +1330,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
1330
1330
  `):"No valid C/C++ files"}],isError:!0};for(let c of i){await p0(d0);try{let l=await this.checkFile(c);r.push(u0(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let o=t.length>0,s=[];t.length>0&&s.push(t.join(`
1331
1331
  `)),r.length>0&&s.push(r.join(`
1332
1332
  `));let a=s.join(`
1333
- `).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Ot(e),r=await Cn.promises.readFile(e,"utf8"),i=$a(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=wi.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=wi.resolve(wi.isAbsolute(o)?o:wi.join(r,o));if(!Cn.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Cn.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!Un(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Cn.realpathSync(s))}catch{i.push(s)}}return i}};function u0(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}function p0(n){return new Promise(e=>setTimeout(e,n))}import*as $o from"fs";import*as Dd from"path";var _o=class n{manager;static FEATURE_METHOD_MAP={hover:b.HOVER,definition:b.DEFINITION,declaration:b.DECLARATION,references:b.REFERENCES,implementation:b.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return Mo();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return kd(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(b.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Mo();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(b.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return kd("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Mo();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return kd("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(b.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(r);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(b.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Ot(e),i=await $o.promises.readFile(e,"utf8"),o=$a(e);g.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=Dd.isAbsolute(e)?e:Dd.join(this.manager.projectRoot,e);return!$o.existsSync(t)||!$o.statSync(t).isFile()||!Un(t)?null:t}};import{spawn as m0}from"child_process";import*as xd from"fs";import*as uE from"path";var f0=30*1e3,h0=30*1e3,Rd=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new bn;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get clangdPid(){return this.clangdProcess?.pid??null}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new vn(r),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(b.INITIALIZE,i,nt),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(b.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(b.HOVER,e)}async definition(e){return this.sendLspRequest(b.DEFINITION,e)}async declaration(e){return this.sendLspRequest(b.DECLARATION,e)}async references(e){return this.sendLspRequest(b.REFERENCES,e)}async implementation(e){return this.sendLspRequest(b.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(b.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(b.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(b.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(b.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(b.DID_OPEN,e)}sendDidChange(e){this.sendNotification(b.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(b.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},h0);this.diagnosticWaiters.set(t,{resolve:r,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(b.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(b.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${ge(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=m0(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=Gi(this.config.workspaceRoot),t=$t(e),r=uE.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.7"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=f0){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0&&e.error!==null){let i=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case b.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case b.PROGRESS:this.onMessage({jsonrpc:L,method:b.PROGRESS,params:e.params});break;case b.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case b.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:L,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:L,method:b.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{xd.existsSync(this.config.logPath)||xd.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),$t(r)}}catch{}return e}};import*as la from"path";import*as Pf from"fs";var da=class n{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get clangdPid(){return this.proxy?.clangdPid??null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t,r,i,o){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(nn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await gc(e,a?async()=>(f.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>n.executeCompileNative(e,t,r,i));return c.acquired?c.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}static async executeCompileNative(e,t,r,i){try{return await Ay(e,t,r,i),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(nt);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=br(this.config.workspaceRoot);this.resolvedRoot=e?xe(e):xe(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();vc(t);let r=this.config.clangdPath;if(!r){let s="clangd not found (install DevEco Studio / CLT)";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=this.config.compileCommandsDir??la.dirname(Hn(this.resolvedRoot));try{Pf.mkdirSync(i,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new Rd({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case b.DID_OPEN:this.proxy.sendDidOpen(i);break;case b.DID_CHANGE:this.proxy.sendDidChange(i);break;case b.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=la.join(Jr(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=la.join(e,"lsp-log",t);return Pf.mkdirSync(r,{recursive:!0}),xe(r)}catch{return"auto"}}};function pE(n){let e=yc(n);return f.info(`[SyncGuard] ${e.reason}`),e}var fE=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(fE||{}),wr=3,Cf=600*1e3,kf=100,Id=["ohpm","hvigor","dep-parse","lsp-init"],mE={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},ua=15,Ad=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;arktsInitProgress=null;arktsPipelineStartedAt=0;standardProtocolAvailable=!1;socketAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;cppCustomCompileCommandsDir=null;cppCustomDirResolvedFor="";constructor(e={}){this.config=e,Bn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let i=br(t);g.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.sdkPath=this.config.sdkPath??"",this.arktsLangServerPath=this.config.arktsLangServerPath??null,this.nodePath=this.config.nodePath??"",this.ohpmJsPath=this.config.ohpmJsPath??"",this.hvigorJsPath=this.config.hvigorJsPath??"",this.clangdPath=this.config.clangdPath??null,this.cppEnabled=this.config.cppEnabled??!0,g.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCompileCommandsPath='${this.config.cppCompileCommandsPath??"(none)"}'`),this.server=new g0({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=wf(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),this.standardProtocolAvailable=this.detectStandardProtocolAvailable()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.socketAvailable||this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Only callable when the project state is ready/idle/error; during discovery/sync/init (large-project init can take minutes) it returns an error\u2014wait for ready and retry tools instead. Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:De.object({target:De.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:De.object({files:De.array(De.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=De.object({file:De.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:De.number().describe("Line number (0-based)"),character:De.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:De.object({query:De.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:De.object({file:De.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:De.object({file:De.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:De.number().describe("Line number (0-based)"),character:De.number().describe("Character offset in the line (0-based)"),direction:De.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=_a(e);return g.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return g.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}async detectSocketAvailable(){try{let e=this.arktsLangServerPath;if(!e){this.socketAvailable=!1;return}this.socketAvailable=await Xh(e,Jn(this.nodePath)),g.info(`Socket transport: ${this.socketAvailable?"enabled":"disabled (stdio mode)"} (--list-protocols probe)`)}catch{this.socketAvailable=!1}}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>kf)return g.warn(`check tool called with ${t.length} files (max: ${kf})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${kf}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=w0(t);o.length>0&&g.warn(`Unsupported file types in check request: ${o.join(", ")}`);let s=o.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),s,a),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
1333
+ `).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Ot(e),r=await Cn.promises.readFile(e,"utf8"),i=$a(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=wi.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=wi.resolve(wi.isAbsolute(o)?o:wi.join(r,o));if(!Cn.existsSync(s)){t.push(`File does not exist: ${o}`);continue}if(!Cn.statSync(s).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!Un(s)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(Cn.realpathSync(s))}catch{i.push(s)}}return i}};function u0(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}function p0(n){return new Promise(e=>setTimeout(e,n))}import*as $o from"fs";import*as Dd from"path";var _o=class n{manager;static FEATURE_METHOD_MAP={hover:b.HOVER,definition:b.DEFINITION,declaration:b.DECLARATION,references:b.REFERENCES,implementation:b.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return Mo();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return kd(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(b.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Mo();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(b.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return kd("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Mo();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return kd("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(b.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(r);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(b.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Ot(e),i=await $o.promises.readFile(e,"utf8"),o=$a(e);g.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=Dd.isAbsolute(e)?e:Dd.join(this.manager.projectRoot,e);return!$o.existsSync(t)||!$o.statSync(t).isFile()||!Un(t)?null:t}};import{spawn as m0}from"child_process";import*as xd from"fs";import*as uE from"path";var f0=30*1e3,h0=30*1e3,Rd=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new bn;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get clangdPid(){return this.clangdProcess?.pid??null}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new vn(r),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(b.INITIALIZE,i,nt),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(b.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(b.HOVER,e)}async definition(e){return this.sendLspRequest(b.DEFINITION,e)}async declaration(e){return this.sendLspRequest(b.DECLARATION,e)}async references(e){return this.sendLspRequest(b.REFERENCES,e)}async implementation(e){return this.sendLspRequest(b.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(b.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(b.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(b.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(b.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(b.DID_OPEN,e)}sendDidChange(e){this.sendNotification(b.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(b.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},h0);this.diagnosticWaiters.set(t,{resolve:r,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(b.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(b.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${ge(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=m0(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=Gi(this.config.workspaceRoot),t=$t(e),r=uE.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.8"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=f0){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0&&e.error!==null){let i=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case b.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case b.PROGRESS:this.onMessage({jsonrpc:L,method:b.PROGRESS,params:e.params});break;case b.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case b.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:L,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:L,method:b.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{xd.existsSync(this.config.logPath)||xd.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),$t(r)}}catch{}return e}};import*as la from"path";import*as Pf from"fs";var da=class n{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get clangdPid(){return this.proxy?.clangdPid??null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t,r,i,o){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(nn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let a=o?.skipCompileNative===!0,c=await gc(e,a?async()=>(f.info("[ClangdLspManager] compileNative skipped (C++ project up-to-date)"),{status:"success"}):async()=>n.executeCompileNative(e,t,r,i));return c.acquired?c.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}static async executeCompileNative(e,t,r,i){try{return await Ay(e,t,r,i),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(nt);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=br(this.config.workspaceRoot);this.resolvedRoot=e?xe(e):xe(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();vc(t);let r=this.config.clangdPath;if(!r){let s="clangd not found (install DevEco Studio / CLT)";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=this.config.compileCommandsDir??la.dirname(Hn(this.resolvedRoot));try{Pf.mkdirSync(i,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new Rd({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case b.DID_OPEN:this.proxy.sendDidOpen(i);break;case b.DID_CHANGE:this.proxy.sendDidChange(i);break;case b.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=la.join(Jr(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=la.join(e,"lsp-log",t);return Pf.mkdirSync(r,{recursive:!0}),xe(r)}catch{return"auto"}}};function pE(n){let e=yc(n);return f.info(`[SyncGuard] ${e.reason}`),e}var fE=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(fE||{}),wr=3,Cf=600*1e3,kf=100,Id=["ohpm","hvigor","dep-parse","lsp-init"],mE={ohpm:"ohpm install",hvigor:"hvigor sync","dep-parse":"dependency parse","lsp-init":"LSP init"},ua=15,Ad=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;nodePath="";ohpmJsPath="";hvigorJsPath="";clangdPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;arktsInitProgress=null;arktsPipelineStartedAt=0;standardProtocolAvailable=!1;socketAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;cppEnabled;cppCustomCompileCommandsDir=null;cppCustomDirResolvedFor="";constructor(e={}){this.config=e,Bn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let i=br(t);g.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.sdkPath=this.config.sdkPath??"",this.arktsLangServerPath=this.config.arktsLangServerPath??null,this.nodePath=this.config.nodePath??"",this.ohpmJsPath=this.config.ohpmJsPath??"",this.hvigorJsPath=this.config.hvigorJsPath??"",this.clangdPath=this.config.clangdPath??null,this.cppEnabled=this.config.cppEnabled??!0,g.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}', cppEnabled=${this.cppEnabled}, cppCompileCommandsPath='${this.config.cppCompileCommandsPath??"(none)"}'`),this.server=new g0({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=wf(e.telemetry,()=>this.arktsCheckTool?.aceServerPid??null,()=>this.config.projectPath??"",()=>this.sdkPath??""),this.standardProtocolAvailable=this.detectStandardProtocolAvailable()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.socketAvailable||this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Only callable when the project state is ready/idle/error; during discovery/sync/init (large-project init can take minutes) it returns an error\u2014wait for ready and retry tools instead. Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:De.object({target:De.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:De.object({files:De.array(De.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=De.object({file:De.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:De.number().describe("Line number (0-based)"),character:De.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:De.object({query:De.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:De.object({file:De.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:De.object({file:De.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:De.number().describe("Line number (0-based)"),character:De.number().describe("Character offset in the line (0-based)"),direction:De.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=_a(e);return g.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return g.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}async detectSocketAvailable(){try{let e=this.arktsLangServerPath;if(!e){this.socketAvailable=!1;return}this.socketAvailable=await Xh(e,Jn(this.nodePath)),g.info(`Socket transport: ${this.socketAvailable?"enabled":"disabled (stdio mode)"} (--list-protocols probe)`)}catch{this.socketAvailable=!1}}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>kf)return g.warn(`check tool called with ${t.length} files (max: ${kf})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${kf}.`}],isError:!0};let{etsFiles:r,cppFiles:i,unsupported:o}=w0(t);o.length>0&&g.warn(`Unsupported file types in check request: ${o.join(", ")}`);let s=o.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),s,a),i.length>0&&this.mergeCheckResult(await this.callCppCheck(i),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
1334
1334
  `),s.join(`
1335
1335
  `)].filter(d=>d.trim().length>0).join(`
1336
1336
  `).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return g.warn(`ArkTS check rejected: project is DISCOVERING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return g.warn(`ArkTS check rejected: project is SYNCING, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return g.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return g.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;return typeof r!="string"||typeof i!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:i,character:o});let s=e;return this.cppLspTool.handleLspFeature(s,{file:r,line:i,character:o})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){let a=this.describeArktsState(),c=this.describeCppState();return g.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){g.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${r}:${i}:${o}`}mergeSymbolItems(e,t,r){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),r.push(i))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return`syncing (retry ${ua}s)`;case 3:return`initializing (retry ${ua}s)`;case 5:return`error (${this.initRetryCount}/${wr})`;case 4:return"ready";default:return"unknown"}}describeCppState(){switch(this.cppProjectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 25s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.cppInitRetryCount}/${wr})`;case 4:return this.cppHasNoCppCode?"ready (no C++ code)":"ready";default:return"unknown"}}async handleDocumentSymbolCall(e){let t=e.file;return typeof t!="string"?{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0}:this.routeLspRequest(t,"documentSymbol",async()=>t.endsWith(".ets")?this.arktsCheckTool.handleDocumentSymbol(t):this.cppLspTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,r=e.line,i=e.character,o=e.direction;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:o!=="incoming"&&o!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${o})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:return g.warn(`ArkTS ${e} rejected: project is DISCOVERING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 2:return g.warn(`ArkTS ${e} rejected: project is SYNCING`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 3:return g.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:this.buildInitRetryMessage()}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return g.warn(`ArkTS ${e} rejected: unknown project state ${this.projectState}`),{content:[{type:"text",text:"Unknown project state, please retry"}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e=this.arktsInitProgress?this.buildInitRetryMessage():`Config file changed, resyncing project.${this.buildRetrySuffix()}`,t="config changed",this.configChangedTriggeredResync=!1):(e=this.arktsInitProgress?this.buildInitRetryMessage():`ArkTS project detected, syncing.${this.buildRetrySuffix()}`,t="initial"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:`Initializing.${this.buildRetrySuffix()}`}],isError:!0}):(g.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=wr?(g.error(`Init retry limit reached (${this.initRetryCount}/${wr}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${wr}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${wr})`),this.arktsInitProgress=null,this.ensureProjectReady(),{content:[{type:"text",text:`Project initialization failed, auto-retrying.${this.buildRetrySuffix()}`}],isError:!0})}buildRetrySuffix(){return` Retry in ${ua}s. Expected total: 30s\u201310min (depends on project size).`}buildInitRetryMessage(){let e=this.arktsInitProgress;if(!e)return`ArkTS init in progress.${this.buildRetrySuffix()}`;let t=Id.indexOf(e.phase)+1,r=Math.round((Date.now()-e.startedAt)/1e3),i=this.arktsPipelineStartedAt?Math.round((Date.now()-this.arktsPipelineStartedAt)/1e3):r,o=e.percent!==null?` (${e.percent}%)`:"";return[`ArkTS init [${t}/4] ${mE[e.phase]}: ${e.detail}${o} [${r}s, total ${i}s]`,this.buildPipelineLine(e.phase),`Retry in ${ua}s. Expected total: 30s\u201310min (depends on project size).`].join(`
@@ -1418,4 +1418,4 @@ ${Th(t)}`)}function Th(n){return n.map(e=>` - ${e.name} (${e.id})`).join(`
1418
1418
  `).join(""),!t)){console.log(`The log does not contain the keyword '${n.searchKeywords}'.`);return}let r=Number.parseInt(n.maxLogSize,10);if(r===-1){console.log(t);return}if(r<0||Number.isNaN(r))throw new Error("Please enter the correct max-log-size.");if(r===0){process.stdout.write("");return}t.length>r&&(t=`(exceeded log size limit, showing last ${r} characters)...
1419
1419
  ${t.slice(-r)}`),console.log(t)}function QU(n){let e=du.join(Di,n.id,"screenshots");if(!Wo.existsSync(e))throw new Error(`No screenshots found for ID: ${n.id}`);Wo.mkdirSync(n.savePath,{recursive:!0});let t=Wo.readdirSync(e).map(r=>{let i=du.join(n.savePath,r);return Wo.copyFileSync(du.join(e,r),i),i});console.log(JSON.stringify({filenames:t,message:"Screenshots saved successfully"},null,2))}var uu=new GU("verify").description("Run UI verification on a connected device").option("--test-plan <plan>","Natural-language test plan describing steps and expected results").option("--bundle-name <name>","Bundle name of the app to be tested").option("--no-fresh-start","Skip relaunching the app before verification").option("--device <name|serial>","Target device name or serial").allowExcessArguments(!0).action(XU);uu.command("init").description("Configure the vision model for UI verification").option("--base-url <url>","Base URL of the vision model").option("--model-name <name>","Vision model name").option("--api-key <key>","API key for the vision model").action(n=>{if(!n.baseUrl&&!n.modelName&&!n.apiKey)throw new Error("Error: at least one of --base-url, --model-name, --api-key is required");let e=xh(n);console.log(`UI verification config saved to ${e}`)});uu.command("log").description("Get verification log by ID").requiredOption("--id <id>","Verification task ID").option("--search-keywords <keywords>","Filter log by keywords").option("--max-log-size <n>","Max characters to show (-1 for unlimited)","5000").action(ZU);uu.command("screenshot").description("Save verification screenshots by ID").requiredOption("--id <id>","Verification task ID").requiredOption("--save-path <path>","Absolute path to save screenshots").action(QU);var CC=uu;if(!Xe())try{R.init(pu.join(F(),"TraceLogData")),R.startScheduler()}catch(n){g.error(`[telemetry] init failed: ${n instanceof Error?n.message:String(n)}`)}(async()=>{if(!Xe())try{let n=await P.new();R.setSourceType(n.sourceType);let e=n.readVersion();e&&(n.sourceType==="clt"?R.setCltVersion(e):R.setStudioVersion(e))}catch(n){g.error(`[telemetry] toolchain info failed: ${n instanceof Error?n.message:String(n)}`)}})();se.name("devecocli").description(`HarmonyOS application development command line tool
1420
1420
 
1421
- Privacy: ${Go.PRIVACY_URL}`).version("1.3.7");var kC=se.options.find(n=>n.long==="--version");kC&&(kC.flags="-V, -v, --version");se.addCommand(By);se.addCommand(Rv);se.addCommand(Ov);se.addCommand(Eb);se.addCommand(Jb);se.addCommand(yS);se.addCommand(ES);se.addCommand(kS);se.addCommand($S);se.addCommand(US);se.addCommand(wE);se.addCommand(CE);se.addCommand(JE);se.addCommand(AP);se.addCommand(wC);se.addCommand(CC);for(let n=2;n<process.argv.length;n++){let e=process.argv[n];if(e==="-v"){process.argv[n]="-V";break}if(!e.startsWith("-"))break}var Lh=process.argv.slice(2);Lh.length>=2&&Lh[Lh.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function t1(n){let e=n;for(;e.parent&&e.parent!==se;)e=e.parent;return e}var r1=new Set(["update","auth","serve"]);se.hook("preAction",async(n,e)=>{await ey().catch(()=>{});let t=t1(e),r=Ni();if(t.name()==="update"||t.name()==="docs"&&e.name()==="update")return;let i=new en(pu.join(F(),"update")),o=ir();if(r==="off"&&i.getBlockedVersions().includes(o))throw new Error(`devecocli ${o} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||r1.has(t.name())||await P.checkVersion()});function n1(n){if(n.name()!=="status"||n.opts().format!=="json")return!1;let t=n.parent;for(;t&&t!==se;){if(t.name()==="screenrecord")return!0;t=t.parent}return!1}se.hook("postAction",async(n,e)=>{if(process.exitCode||Ni()!=="off"||n1(e))return;await new os(e).checkAndNotify()});se.parseAsync(process.argv).finally(()=>{R.stopScheduler();try{Ru(pu.join(F(),"TraceLogData"))}catch(n){g.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(e1(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
1421
+ Privacy: ${Go.PRIVACY_URL}`).version("1.3.8");var kC=se.options.find(n=>n.long==="--version");kC&&(kC.flags="-V, -v, --version");se.addCommand(By);se.addCommand(Rv);se.addCommand(Ov);se.addCommand(Eb);se.addCommand(Jb);se.addCommand(yS);se.addCommand(ES);se.addCommand(kS);se.addCommand($S);se.addCommand(US);se.addCommand(wE);se.addCommand(CE);se.addCommand(JE);se.addCommand(AP);se.addCommand(wC);se.addCommand(CC);for(let n=2;n<process.argv.length;n++){let e=process.argv[n];if(e==="-v"){process.argv[n]="-V";break}if(!e.startsWith("-"))break}var Lh=process.argv.slice(2);Lh.length>=2&&Lh[Lh.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function t1(n){let e=n;for(;e.parent&&e.parent!==se;)e=e.parent;return e}var r1=new Set(["update","auth","serve"]);se.hook("preAction",async(n,e)=>{await ey().catch(()=>{});let t=t1(e),r=Ni();if(t.name()==="update"||t.name()==="docs"&&e.name()==="update")return;let i=new en(pu.join(F(),"update")),o=ir();if(r==="off"&&i.getBlockedVersions().includes(o))throw new Error(`devecocli ${o} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||r1.has(t.name())||await P.checkVersion()});function n1(n){if(n.name()!=="status"||n.opts().format!=="json")return!1;let t=n.parent;for(;t&&t!==se;){if(t.name()==="screenrecord")return!0;t=t.parent}return!1}se.hook("postAction",async(n,e)=>{if(process.exitCode||Ni()!=="off"||n1(e))return;await new os(e).checkAndNotify()});se.parseAsync(process.argv).finally(()=>{R.stopScheduler();try{Ru(pu.join(F(),"TraceLogData"))}catch(n){g.error(`[telemetry] background upload spawn check failed: ${n instanceof Error?n.message:String(n)}`)}}).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(e1(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
@@ -1,5 +1,5 @@
1
1
  import Vt from"path";import*as S from"fs";import*as Y from"path";import{homedir as bt}from"os";import*as H from"fs";import*as g from"path";function W(n){let t=g.resolve(n),e=[],r=t;for(;;)try{let i=H.realpathSync(r);return e.length===0?i:g.join(i,...e.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=g.dirname(r);if(o===r)return t;e.push(g.basename(r)),r=o}}function N(n){let t=n.trim();return(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1).trim()),t}function K(n){let t=N(n);if(!t)throw new Error("Path must not be empty.");return W(t)}var Et="deveco-cli",J,$=class extends Error{constructor(t){super(t),this.name="CliDataDirError"}};function wt(){let n=process.env.DEVECO_CLI_DATA_DIR,e=(n===void 0||n===""?"":N(n))||Y.join(bt(),".local","share",Et);try{return K(e)}catch(r){throw new $(r instanceof Error?r.message:String(r))}}function X(){if(J!==void 0)return J;let n=wt();try{if(S.existsSync(n))return S.realpathSync(n)}catch{}return n}import vt from"crypto";import u from"fs";import I from"os";import m from"path";import Tt from"https";var G={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var D=class n{static ENDPOINT=G.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(t,e){let r={"Content-Type":"application/json",sender:n.SENDER,deviceid:e.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(t,"utf8"))};try{let{body:i}=await this.httpPost(n.ENDPOINT,r,Buffer.from(t,"utf8"),6e4);return n.isSuccess(i)}catch{return!1}}static isSuccess(t){try{let e=JSON.parse(t),r=e?.code??e?.errorCode;return String(r)==="200"}catch{return!1}}async httpPost(t,e,r,i){let o=new URL(t);return new Promise((s,l)=>{let p=Tt.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:e,timeout:i},h=>{let T=[];h.on("data",St=>T.push(St)),h.on("end",()=>{s({code:h.statusCode??0,body:Buffer.concat(T).toString("utf8")})})});p.on("timeout",()=>{p.destroy(new Error("request timeout"))}),p.on("error",l),p.write(r),p.end()})}};var q={identity:n=>n,camelCase:n=>n,snakeCase:n=>n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},M=class{constructor(t={}){this.config=t}serialize(t){let e=this.transform(t);return this.config.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}toObject(t){return this.transform(t)}transform(t){if(t==null)return t;if(Array.isArray(t))return t.map(o=>this.transform(o));if(typeof t!="object")return t;let e=this.config.namingStrategy??q.identity,r=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(t)){let l=r[o]??e(o);i[l]=this.transform(s)}return i}},Z=new M({namingStrategy:q.snakeCase,fieldNames:{}});import b from"crypto";import C from"fs";import Dt from"path";var _="aes-256-gcm",Ct=12,_t="deveco-cli-trace-file",Lt="trace-file-secret",tt=32;function Q(n){try{let t=C.readFileSync(n,"utf8").trim();return t&&Buffer.from(t,"base64").length===tt?t:null}catch{return null}}function et(n){let t=Dt.join(n,Lt),e=Q(t);if(e)return B(e);let r=b.randomBytes(tt).toString("base64");try{C.mkdirSync(n,{recursive:!0});try{C.writeFileSync(t,r,{flag:"wx"})}catch{let i=Q(t);if(i)return B(i);C.writeFileSync(t,r)}}catch{}return B(r)}function B(n){return b.createHash("sha256").update(_t).update(n).digest()}function rt(n,t){let e=b.randomBytes(Ct),r=b.createCipheriv(_,t,e),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o={version:1,algorithm:_,ciphertext:i.toString("base64"),iv:e.toString("base64"),authTag:r.getAuthTag().toString("base64")};return JSON.stringify(o)}function nt(n,t){let e;try{e=JSON.parse(n)}catch{return null}if(!Ft(e))return n;try{let r=b.createDecipheriv(_,t,Buffer.from(e.iv,"base64"));return r.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([r.update(Buffer.from(e.ciphertext,"base64")),r.final()]).toString("utf8")}catch{return null}}function Ft(n){if(!n||typeof n!="object")return!1;let t=n;return t.version===1&&t.algorithm===_&&typeof t.ciphertext=="string"&&typeof t.iv=="string"&&typeof t.authTag=="string"}import*as a from"fs";import*as A from"path";import*as L from"os";import*as y from"path";import ge from"json5";var ve=64*1024;function it(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??y.join(L.homedir(),"AppData","Local");return y.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?y.join(L.homedir(),"Library","Logs","devecocli-mcp-server"):y.join(L.homedir(),".local","share","devecocli-mcp-server","logs")}var ot="mcp-server.log",At="mcp-server",kt={maxSize:10*1024*1024,maxFiles:4},j=class n{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(t,e){this.rotationOptions={...kt,...e},this.minLevel=t?"debug":"info",t?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=it(),this.currentLogFile=A.join(this.logDir,ot),a.existsSync(this.logDir)||a.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${i}`}getRotatedFileName(t,e){return A.join(this.logDir,`${At}-${t}.log.${e}`)}fileExists(t){try{return a.accessSync(t,a.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let t=a.readdirSync(this.logDir),e=[];for(let i of t)if(i===ot||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=A.join(this.logDir,i),s=a.statSync(o);e.push({name:i,mtime:s.mtime,path:o})}e.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<e.length;i++)try{a.unlinkSync(e[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let t=this.getCurrentDateString(),e=this.getRotatedFileName(t,this.rotationOptions.maxFiles);this.fileExists(e)&&a.unlinkSync(e);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(t,i),s=this.getRotatedFileName(t,i+1);this.fileExists(o)&&a.renameSync(o,s)}let r=this.getRotatedFileName(t,1);a.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let t=a.statSync(this.currentLogFile);this.currentFileSize=t.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=a.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{a.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(t){let e=this.getCurrentDateString();this.currentDate&&this.currentDate!==e&&(this.rotateLog(),this.currentDate=e),this.currentFileSize+=t,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(t,e,...r){if(this.mode==="silent"||n.LEVEL_ORDER[t]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(p=>p instanceof Error?`${p.name}: ${p.message}`:typeof p=="object"?JSON.stringify(p,null,2):String(p)).join(" "),o=i?`${e} ${i}`:e,l=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${t.toUpperCase()}] [pid=${process.pid}] ${o}
2
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let p=Buffer.from(l);a.writeSync(this.fd,p),this.checkRotation(p.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(l)}debug(t,...e){this.write("debug",t,...e)}info(t,...e){this.write("info",t,...e)}warn(t,...e){this.write("warn",t,...e)}error(t,...e){this.write("error",t,...e)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{a.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},E=null;function Ot(n=!1){E&&E.dispose(),E=new j(n)}function F(){return E||Ot(!1),E}var c={debug:(n,...t)=>F().debug(n,...t),info:(n,...t)=>F().info(n,...t),warn:(n,...t)=>F().warn(n,...t),error:(n,...t)=>F().error(n,...t)};import at from"fs";import Pt from"path";var k=300*1e3,O=3600*1e3,lt=10080*60*1e3,v=8*1024*1024,ct=3600*1e3,st=".pending",Rt=/\.reclaim-\d+-\d+$/;function P(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var It="upload-state.json";function ut(n){return Pt.join(n,It)}function Nt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function U(n){try{let t=at.readFileSync(ut(n),"utf8"),e=JSON.parse(t);return{firstEventAt:typeof e.firstEventAt=="number"?e.firstEventAt:null,lastUploadAt:typeof e.lastUploadAt=="number"?e.lastUploadAt:null,lastRetryAt:typeof e.lastRetryAt=="number"?e.lastRetryAt:null}}catch{return Nt()}}function V(n,t){try{at.writeFileSync(ut(n),JSON.stringify(t),"utf8")}catch{}}function pt(n){let t=U(n);t.firstEventAt===null&&(t.firstEventAt=Date.now(),V(n,t))}function ft(n){let t=U(n);t.lastUploadAt=Date.now(),t.firstEventAt=null,V(n,t)}function dt(n){let t=U(n);t.lastRetryAt=Date.now(),V(n,t)}function mt(n){let t=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!t)return null;let e=Date.parse(`${t[1]}-${t[2]}-${t[3]}T00:00:00`);return Number.isFinite(e)?e:null}function z(n){if(!n.startsWith("telemetry-"))return null;let t=Rt.exec(n),e=t?n.slice(0,t.index):n;if(!e.endsWith(st))return null;let r=e.slice(0,-st.length);return r.endsWith(".txt")?r:null}function gt(n){return z(n)!==null}import $t from"crypto";import R from"fs";import Mt from"path";var Bt="install-id";function jt(n){return Mt.join(n,Bt)}function ht(n){try{let t=R.readFileSync(n,"utf8").trim();return Ut(t)?t:null}catch{return null}}function Ut(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function yt(n){let t=jt(n),e=ht(t);if(e)return e;let r=$t.randomUUID();try{R.mkdirSync(n,{recursive:!0});try{R.writeFileSync(t,r,{flag:"wx"})}catch{let i=ht(t);if(i)return i;R.writeFileSync(t,r)}}catch{}return r}var w=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new D;storageDir="";failedDir="";installId="";disabled=P();traceFileKey=Buffer.alloc(0);sessionId=vt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){c.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(t){this.storageDir=t,this.failedDir=m.join(t,"failed"),this.cliVersion="1.3.7",this.nodeVersion=process.version,this.installId=yt(t).replace(/-/g,""),this.traceFileKey=et(t),u.mkdirSync(t,{recursive:!0}),u.mkdirSync(this.failedDir,{recursive:!0}),c.debug(`[telemetry] init: dir=${t}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(t){this.devecoStudioVersion=t,c.debug(`[telemetry] studio version set: ${t}`)}setSourceType(t){this.sourceType=t,c.debug(`[telemetry] sourceType set: ${t}`)}setCltVersion(t){this.cltVersion=t,c.debug(`[telemetry] CLT version set: ${t}`)}async track(t,e){if(this.disabled)return typeof e=="function"?e():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!e){await this.record(t,0,!0,null);return}if(typeof e!="function"){let o=e;await this.record(t,o.duration_ms,o.success,o.error_code);return}let r=e,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(t,s,!0,null),o}catch(o){let s=Date.now()-i,l=this.toErrorCode(o);throw await this.record(t,s,!1,l),o}}async record(t,e,r,i){let o=this.buildTraceEvent(t,e,r,i);try{let s=rt(JSON.stringify(o),this.traceFileKey);await u.promises.appendFile(this.currentFile(),s+`
2
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let p=Buffer.from(l);a.writeSync(this.fd,p),this.checkRotation(p.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(l)}debug(t,...e){this.write("debug",t,...e)}info(t,...e){this.write("info",t,...e)}warn(t,...e){this.write("warn",t,...e)}error(t,...e){this.write("error",t,...e)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{a.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},E=null;function Ot(n=!1){E&&E.dispose(),E=new j(n)}function F(){return E||Ot(!1),E}var c={debug:(n,...t)=>F().debug(n,...t),info:(n,...t)=>F().info(n,...t),warn:(n,...t)=>F().warn(n,...t),error:(n,...t)=>F().error(n,...t)};import at from"fs";import Pt from"path";var k=300*1e3,O=3600*1e3,lt=10080*60*1e3,v=8*1024*1024,ct=3600*1e3,st=".pending",Rt=/\.reclaim-\d+-\d+$/;function P(){let n=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return n==="1"||n==="true"}var It="upload-state.json";function ut(n){return Pt.join(n,It)}function Nt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function U(n){try{let t=at.readFileSync(ut(n),"utf8"),e=JSON.parse(t);return{firstEventAt:typeof e.firstEventAt=="number"?e.firstEventAt:null,lastUploadAt:typeof e.lastUploadAt=="number"?e.lastUploadAt:null,lastRetryAt:typeof e.lastRetryAt=="number"?e.lastRetryAt:null}}catch{return Nt()}}function V(n,t){try{at.writeFileSync(ut(n),JSON.stringify(t),"utf8")}catch{}}function pt(n){let t=U(n);t.firstEventAt===null&&(t.firstEventAt=Date.now(),V(n,t))}function ft(n){let t=U(n);t.lastUploadAt=Date.now(),t.firstEventAt=null,V(n,t)}function dt(n){let t=U(n);t.lastRetryAt=Date.now(),V(n,t)}function mt(n){let t=n.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!t)return null;let e=Date.parse(`${t[1]}-${t[2]}-${t[3]}T00:00:00`);return Number.isFinite(e)?e:null}function z(n){if(!n.startsWith("telemetry-"))return null;let t=Rt.exec(n),e=t?n.slice(0,t.index):n;if(!e.endsWith(st))return null;let r=e.slice(0,-st.length);return r.endsWith(".txt")?r:null}function gt(n){return z(n)!==null}import $t from"crypto";import R from"fs";import Mt from"path";var Bt="install-id";function jt(n){return Mt.join(n,Bt)}function ht(n){try{let t=R.readFileSync(n,"utf8").trim();return Ut(t)?t:null}catch{return null}}function Ut(n){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n)}function yt(n){let t=jt(n),e=ht(t);if(e)return e;let r=$t.randomUUID();try{R.mkdirSync(n,{recursive:!0});try{R.writeFileSync(t,r,{flag:"wx"})}catch{let i=ht(t);if(i)return i;R.writeFileSync(t,r)}}catch{}return r}var w=class n{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new D;storageDir="";failedDir="";installId="";disabled=P();traceFileKey=Buffer.alloc(0);sessionId=vt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){c.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(t){this.storageDir=t,this.failedDir=m.join(t,"failed"),this.cliVersion="1.3.8",this.nodeVersion=process.version,this.installId=yt(t).replace(/-/g,""),this.traceFileKey=et(t),u.mkdirSync(t,{recursive:!0}),u.mkdirSync(this.failedDir,{recursive:!0}),c.debug(`[telemetry] init: dir=${t}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(t){this.devecoStudioVersion=t,c.debug(`[telemetry] studio version set: ${t}`)}setSourceType(t){this.sourceType=t,c.debug(`[telemetry] sourceType set: ${t}`)}setCltVersion(t){this.cltVersion=t,c.debug(`[telemetry] CLT version set: ${t}`)}async track(t,e){if(this.disabled)return typeof e=="function"?e():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!e){await this.record(t,0,!0,null);return}if(typeof e!="function"){let o=e;await this.record(t,o.duration_ms,o.success,o.error_code);return}let r=e,i=Date.now();try{let o=await r(),s=Date.now()-i;return await this.record(t,s,!0,null),o}catch(o){let s=Date.now()-i,l=this.toErrorCode(o);throw await this.record(t,s,!1,l),o}}async record(t,e,r,i){let o=this.buildTraceEvent(t,e,r,i);try{let s=rt(JSON.stringify(o),this.traceFileKey);await u.promises.appendFile(this.currentFile(),s+`
3
3
  `,"utf8"),pt(this.storageDir)}catch{}}buildTraceEvent(t,e,r,i){let o=`${n.EVENT_PREFIX}${t.event}`,s=Z.toObject(t);return s&&typeof s=="object"&&delete s.event,{countryCode:n.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:vt.randomUUID(),trace_os_version:n.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:e,success:r,error_code:i,event_detail:s}}}toErrorCode(t){return t instanceof Error?t.code??t.name:"UnknownError"}resolveOsArch(){let t=I.arch();return t==="x64"?"amd64":t}resolveOsName(){switch(process.platform){case"win32":{let t=I.release().split(".");return(parseInt(t[t.length-1],10)||0)>=22e3?"Windows 11":"Windows 10"}case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}resolveOsSuffix(){switch(process.platform){case"win32":return"windows";case"darwin":return I.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(I.totalmem()/1024)}KB`}formatVersion(t){return t?`${t}_${this.resolveOsSuffix()}`:""}dateString(){let t=new Date,e=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${t.getFullYear()}-${e}-${r}`}currentFile(){return m.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){c.debug("[telemetry] scheduler not started (telemetry disabled)");return}c.debug(`[telemetry] scheduler started (flush every ${k/1e3}s, retry failed every ${O/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},k)},k),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},O)},O)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),c.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let t=await this.listPendingFiles(),e=!0;for(let r of t)await this.flushFile(r)||(e=!1);return ft(this.storageDir),e}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");await this.reclaimStalePending();let t=Date.now(),e;try{e=await u.promises.readdir(this.failedDir)}catch{return!0}let r=e.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>m.join(this.failedDir,o)),i=!0;for(let o of r){let s=m.basename(o),l=mt(s);if(l!==null){if(t-l>lt){try{await u.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||c.warn("[telemetry] retry failed"),dt(this.storageDir),i}async reclaimStalePending(){let t=Date.now();for(let e of[this.storageDir,this.failedDir]){let r;try{r=await u.promises.readdir(e)}catch{continue}for(let i of r)gt(i)&&await this.reclaimOrphan(m.join(e,i),t)}}async reclaimOrphan(t,e){let r;try{let h=await u.promises.stat(t);if(e-h.mtimeMs<ct)return;r=h.size}catch{return}let i=m.dirname(t),o=z(m.basename(t));if(o===null)return;let s=await this.claimOrphan(t,i,o);if(s===null)return;let l=m.join(i,o),p=v-await this.fileSize(l);if(r>p){try{await u.promises.unlink(s)}catch{}c.warn(`[telemetry] dropped stale orphan pending: ${s} (${r} bytes > budget ${p})`);return}if(await this.mergeOrphanInto(s,l)){c.warn(`[telemetry] reclaimed orphan pending: ${s} (${r} bytes)`);return}c.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${r} bytes)`)}async claimOrphan(t,e,r){let i=m.join(e,`${r}.pending.reclaim-${process.pid}-${Date.now()}`);try{await u.promises.rename(t,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(t,e){try{await u.promises.appendFile(e,await u.promises.readFile(t))}catch(r){return c.warn(`[telemetry] merge orphan pending failed: ${t} -> ${e}: ${r instanceof Error?r.message:String(r)}`),!1}try{await u.promises.unlink(t)}catch(r){c.warn(`[telemetry] merged but failed to remove orphan pending: ${t}: ${r instanceof Error?r.message:String(r)}`)}return!0}async fileSize(t){try{return(await u.promises.stat(t)).size}catch{return 0}}async touch(t){let e=new Date;try{await u.promises.utimes(t,e,e)}catch{}}runExclusive(t){let e=()=>t(),r=this.flushChain.then(e,e);return this.flushChain=r.then(()=>{},()=>{}),r}async listPendingFiles(){let t;try{t=await u.promises.readdir(this.storageDir)}catch{return[]}return t.filter(e=>e.startsWith("telemetry-")&&e.endsWith(".txt")).map(e=>m.join(this.storageDir,e)).sort()}async flushFile(t){let e=await this.fileSize(t);if(e>v){c.warn(`[telemetry] ${m.basename(t)} is ${e} bytes (> ${v}), dropped without uploading`);try{await u.promises.unlink(t)}catch{}return!0}let r=t+".pending";try{await u.promises.rename(t,r)}catch{return!1}await this.touch(r);let i;try{i=await u.promises.readFile(r,"utf8")}catch{return!1}let o=i.split(`
4
4
  `).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await u.promises.unlink(r)}catch{}return!0}return this.uploadInBatches(r,o)}collectDecryptBatch(t,e){let r=[],i=16,o=e;for(;o<t.length&&r.length<n.MAX_BATCH;){let s=nt(t[o],this.traceFileKey);if(s===null){o++;continue}let l=Buffer.byteLength(s,"utf8")+1;if(r.length>0&&i+l>n.MAX_PAYLOAD_BYTES)break;r.push(s),i+=l,o++}return{batch:r,next:o}}async uploadInBatches(t,e){let r=0;for(;r<e.length;){let i=r,{batch:o,next:s}=this.collectDecryptBatch(e,r);r=s;let l=this.buildPayloadItems(o);if(l.length===0)continue;let p=JSON.stringify(l),h=!1;try{h=await this.uploader.upload(p,this.installId)}catch{}if(!h){c.warn("[telemetry] upload failed");let T=e.slice(i).join(`
5
5
  `)+`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveco/deveco-cli-common",
3
- "version": "1.3.7",
3
+ "version": "1.3.8",
4
4
  "description": "HarmonyOS application development command line tool",
5
5
  "supportedDocsApi": 1,
6
6
  "license": "MIT",
@@ -34,7 +34,7 @@
34
34
  ],
35
35
  "keywords": ["harmonyos", "deveco", "cli"],
36
36
  "dependencies": {
37
- "@deveco/deveco-cli-knowledgebase": "1.3.7",
37
+ "@deveco/deveco-cli-knowledgebase": "1.3.8",
38
38
  "@modelcontextprotocol/sdk": "^1.29.0",
39
39
  "@xmldom/xmldom": "^0.8.15",
40
40
  "adm-zip": "0.6.1",