@truenine/memory-sync-cli 2026.10218.12101 → 2026.10219.10049
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +10 -10
- package/dist/index.mjs +10 -10
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -433,7 +433,7 @@ node_modules/
|
|
|
433
433
|
pnpm-lock.yaml
|
|
434
434
|
.DS_Store
|
|
435
435
|
`,"public/tnmsc.example.json":`{
|
|
436
|
-
"version": "2026.
|
|
436
|
+
"version": "2026.10219.10049",
|
|
437
437
|
"workspaceDir": "~/project",
|
|
438
438
|
"shadowSourceProject": {
|
|
439
439
|
"name": "tnmsc-shadow",
|
|
@@ -978,7 +978,7 @@ API 接口 (Spring WebFlux 6.2)
|
|
|
978
978
|
- \`controllers/\`: 控制器
|
|
979
979
|
- \`dto/\`: 数据传输对象
|
|
980
980
|
\`\`\`
|
|
981
|
-
`};const Ut=Object.fromEntries(Vt.map(e=>[e,{path:e,content:Ht[e]??``}])),R={USER_HOME:`~`,WORKSPACE:`$WORKSPACE`},Wt=JSON.parse(Ut[`public/tnmsc.example.json`].content),z={reset:`\x1B[0m`,red:`\x1B[31m`,yellow:`\x1B[33m`,cyan:`\x1B[36m`,magenta:`\x1B[35m`,gray:`\x1B[90m`,blue:`\x1B[34m`,green:`\x1B[32m`,white:`\x1B[37m`,dim:`\x1B[2m`,bgRed:`\x1B[41m`},Gt={red:e=>`${z.red}${e}${z.reset}`,yellow:e=>`${z.yellow}${e}${z.reset}`,cyan:e=>`${z.cyan}${e}${z.reset}`,magenta:e=>`${z.magenta}${e}${z.reset}`,gray:e=>`${z.gray}${e}${z.reset}`,blue:e=>`${z.blue}${e}${z.reset}`,green:e=>`${z.green}${e}${z.reset}`,white:e=>`${z.white}${e}${z.reset}`,dim:e=>`${z.dim}${e}${z.reset}`,bgRed:e=>`${z.bgRed}${e}${z.reset}`};let Kt;const qt={error:Gt.red,warn:Gt.yellow,info:Gt.cyan,debug:Gt.magenta,trace:Gt.gray,fatal:Gt.bgRed},Jt={silent:0,fatal:1,error:2,warn:3,info:4,debug:5,trace:6};function Yt(e){if(e===null)return Gt.dim(`null`);if(e===void 0)return Gt.dim(`undefined`);if(typeof e==`boolean`)return Gt.yellow(String(e));if(typeof e==`number`)return Gt.blue(String(e));if(typeof e==`string`)return Gt.green(`"${e}"`);if(Array.isArray(e))return e.length===0?`[]`:`[${e.map(e=>Yt(e)).join(`,`)}]`;if(e instanceof Error){let t={name:e.name,message:e.message,stack:e.stack};for(let n of Object.getOwnPropertyNames(e))n!==`name`&&n!==`message`&&n!==`stack`&&(t[n]=e[n]);return Xt(t)}return typeof e==`object`?Xt(e):String(e)}function Xt(e){let t=Object.entries(e);return t.length===0?`{}`:`{${t.map(([e,t])=>`${/^[\w$]+$/.test(e)?Gt.magenta(e):Gt.yellow(`"${e}"`)}:${Yt(t)}`).join(`,`)}}`}function Zt(){let e=new Date;return`${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}.${String(e.getMilliseconds()).padStart(3,`0`)}`}function Qt(e,t,n,r){let i=Zt(),a=qt[e]??Gt.white,o=String(n),s=r!=null&&Object.keys(r).length>0,c=o===``,l={$:[i,e,t],_:s?c?r:{[o]:r}:n},u={$:[i,a(e.toUpperCase()),t]},d=s?c?r:{[o]:r}:n,f=Xt({...u,_:d});return e===`error`||e===`fatal`?console.error(f):e===`warn`?console.warn(f):e===`debug`||e===`trace`?console.debug(f):console.log(f),l}function $t(e,t,n){let r=Jt[e],i=Jt[n];return(n,...a)=>r>i?{$:[Zt(),e,t],_:n}:typeof n==`string`?Qt(e,t,n,a.length===1&&typeof a[0]==`object`&&a[0]!==null?a[0]:a.length>0?{args:a}:void 0):typeof n==`object`&&n?Qt(e,t,``,n):Qt(e,t,n)}function en(e){Kt=e}function tn(){return Kt}function nn(e,t){let n=t??Kt??process.env.LOG_LEVEL??`info`;return{error:$t(`error`,e,n),warn:$t(`warn`,e,n),info:$t(`info`,e,n),debug:$t(`debug`,e,n),trace:$t(`trace`,e,n),fatal:$t(`fatal`,e,n)}}const rn=`.tnmsc.json`,an=`.aindex`;function on(){return f.join(p.homedir(),an,rn)}function sn(){return{...Wt}}function cn(e,t){let n=on(),r=f.dirname(n);d.existsSync(r)||d.mkdirSync(r,{recursive:!0}),d.writeFileSync(n,`${JSON.stringify(e,null,2)}\n`,`utf8`),t.info(`global config created`,{path:n})}function ln(e,t){let n=[];if(typeof e!=`object`||!e||Array.isArray(e))return n.push(`${t} must be an object with "src" and "dist" string fields`),n;let r=e;return(!(`src`in r)||typeof r.src!=`string`)&&n.push(`${t}.src must be a string`),(!(`dist`in r)||typeof r.dist!=`string`)&&n.push(`${t}.dist must be a string`),n}function un(e,t){let n=[];if(typeof e!=`object`||!e||Array.isArray(e))return n.push(`${t} must be an object`),{errors:n,config:void 0};let r=e;(!(`name`in r)||typeof r.name!=`string`)&&n.push(`${t}.name must be a string`);let i=[`skill`,`fastCommand`,`subAgent`,`rule`,`globalMemory`,`workspaceMemory`,`project`],a={};for(let e of i)if(e in r){let i=ln(r[e],`${t}.${e}`);if(n.push(...i),i.length===0){let t=r[e];a[e]={src:t.src,dist:t.dist}}}return n.length>0?{errors:n,config:void 0}:{errors:n,config:{name:r.name,skill:a.skill??{src:`src/skills`,dist:`dist/skills`},fastCommand:a.fastCommand??{src:`src/commands`,dist:`dist/commands`},subAgent:a.subAgent??{src:`src/agents`,dist:`dist/agents`},rule:a.rule??{src:`src/rules`,dist:`dist/rules`},globalMemory:a.globalMemory??{src:`app/global.cn.mdx`,dist:`dist/global.mdx`},workspaceMemory:a.workspaceMemory??{src:`app/workspace.cn.mdx`,dist:`dist/app/workspace.mdx`},project:a.project??{src:`app`,dist:`dist/app`}}}}var dn=class{configFileName;searchCwd;searchGlobal;customSearchPaths;logger;constructor(e={}){this.configFileName=e.configFileName??rn,this.searchCwd=e.searchCwd??!0,this.searchGlobal=e.searchGlobal??!0,this.customSearchPaths=e.searchPaths??[],this.logger=nn(`ConfigLoader`)}getSearchPaths(e=u.default.cwd()){let t=[];for(let e of this.customSearchPaths)t.push(this.resolveTilde(e));return this.searchCwd&&t.push(f.join(e,this.configFileName)),this.searchGlobal&&t.push(f.join(p.homedir(),an,this.configFileName)),t}loadFromFile(e){let t=this.resolveTilde(e);try{if(!d.existsSync(t))return{config:{},source:null,found:!1};let e=d.readFileSync(t,`utf8`),n=this.parseConfig(e,t);return this.logger.debug(`loaded`,{source:t}),{config:n,source:t,found:!0}}catch(e){return this.logger.warn(`load failed`,{path:t,error:e}),{config:{},source:null,found:!1}}}load(e=u.default.cwd()){let t=this.getSearchPaths(e),n=[];for(let e of t){let t=this.loadFromFile(e);t.found&&n.push(t)}return{config:this.mergeConfigs(n.map(e=>e.config)),sources:n.map(e=>e.source).filter(e=>e!==null),found:n.length>0}}parseConfig(e,t){try{let n=JSON.parse(e);if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`Config must be a JSON object`);return this.validateConfig(n,t)}catch(e){throw e instanceof SyntaxError?Error(`Invalid JSON in ${t}: ${e.message}`):e}}validateConfig(e,t){let n={},r=[];if(`version`in e&&(typeof e.version==`string`?n.version=e.version:r.push(`version must be a string`)),`workspaceDir`in e&&(typeof e.workspaceDir==`string`?n.workspaceDir=e.workspaceDir:r.push(`workspaceDir must be a string`)),`shadowSourceProject`in e){let{errors:t,config:i}=un(e.shadowSourceProject,`shadowSourceProject`);r.push(...t),i!=null&&(n.shadowSourceProject=i)}if(`logLevel`in e){let t=[`trace`,`debug`,`info`,`warn`,`error`],i=e.logLevel;typeof i==`string`&&t.includes(i)?n.logLevel=i:r.push(`logLevel must be one of: ${t.join(`, `)}`)}if(`profile`in e){let t=e.profile;typeof t==`object`&&t&&!Array.isArray(t)?n.profile=t:r.push(`profile must be an object`)}if(`tool`in e){let t=e.tool;if(typeof t==`object`&&t&&!Array.isArray(t)){let e=t,i={},a=!0;for(let[t,n]of Object.entries(e))typeof n==`string`||n===void 0?i[t]=n:(r.push(`tool.${t} must be a string`),a=!1);a&&(n.tool=i)}else r.push(`tool must be an object`)}if(`fastCommandSeriesOptions`in e){let t=e.fastCommandSeriesOptions;typeof t==`object`&&t&&!Array.isArray(t)?n.fastCommandSeriesOptions=t:r.push(`fastCommandSeriesOptions must be an object`)}return r.length>0&&this.logger.warn(`validation warnings`,{path:t,errors:r}),n}mergeConfigs(e){if(e.length===0)return{};let t=e[0];return e.length===1&&t!=null?t:[...e].reverse().reduce((e,t)=>{let n=this.mergeShadowSourceProject(e.shadowSourceProject,t.shadowSourceProject);return{...e,...t,...n==null?{}:{shadowSourceProject:n}}},{})}mergeShadowSourceProject(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{name:t.name??e.name,skill:{...e.skill,...t.skill},fastCommand:{...e.fastCommand,...t.fastCommand},subAgent:{...e.subAgent,...t.subAgent},rule:{...e.rule,...t.rule},globalMemory:{...e.globalMemory,...t.globalMemory},workspaceMemory:{...e.workspaceMemory,...t.workspaceMemory},project:{...e.project,...t.project}}}resolveTilde(e){return e.startsWith(`~`)?f.join(p.homedir(),e.slice(1)):e}};let fn=null;function pn(e){return(e||!fn)&&(fn=new dn(e)),fn}function mn(e){return pn().load(e)}function hn(){let e=nn(`ConfigLoader`),t=on();if(!d.existsSync(t))return e.warn(`global config not found, creating default config`,{path:t}),cn(sn(),e),{valid:!0,exists:!1,errors:[],shouldExit:!1};let n;try{n=d.readFileSync(t,`utf8`)}catch(n){let r=n instanceof Error?n.message:String(n);return e.error(`failed to read global config`,{path:t,error:r}),_n(t,e,[`Failed to read config: ${r}`])}let r;try{r=JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return e.error(`invalid JSON in global config`,{path:t,error:r}),_n(t,e,[`Invalid JSON: ${r}`])}if(typeof r!=`object`||!r||Array.isArray(r))return e.error(`global config must be a JSON object`,{path:t}),_n(t,e,[`Config must be a JSON object`]);let i=gn(r);if(i.length>0){for(let n of i)e.error(`config validation error`,{path:t,error:n});return _n(t,e,i)}return{valid:!0,exists:!0,errors:[],shouldExit:!1}}function gn(e){let t=[];if(`version`in e&&typeof e.version!=`string`&&t.push(`version must be a string`),`workspaceDir`in e&&typeof e.workspaceDir!=`string`&&t.push(`workspaceDir must be a string`),`shadowSourceProject`in e){let{errors:n}=un(e.shadowSourceProject,`shadowSourceProject`);t.push(...n)}if(`logLevel`in e){let n=[`trace`,`debug`,`info`,`warn`,`error`],r=e.logLevel;(typeof r!=`string`||!n.includes(r))&&t.push(`logLevel must be one of: ${n.join(`, `)}`)}if(`profile`in e){let n=e.profile;(typeof n!=`object`||!n||Array.isArray(n))&&t.push(`profile must be an object`)}if(!(`tool`in e))return t;let n=e.tool;if(typeof n!=`object`||!n||Array.isArray(n))t.push(`tool must be an object`);else{let e=n;for(let[n,r]of Object.entries(e))typeof r!=`string`&&r!==void 0&&t.push(`tool.${n} must be a string`)}return t}function _n(e,t,n){try{d.unlinkSync(e),t.info(`deleted invalid config`,{path:e})}catch{t.warn(`failed to delete invalid config`,{path:e})}return cn(sn(),t),t.error(`recreated default config, please review and restart`,{path:e}),{valid:!1,exists:!0,errors:n,shouldExit:!0}}const vn=[`workspaceDir`,`shadowSourceProject.name`,`shadowSourceProject.skill.src`,`shadowSourceProject.skill.dist`,`shadowSourceProject.fastCommand.src`,`shadowSourceProject.fastCommand.dist`,`shadowSourceProject.subAgent.src`,`shadowSourceProject.subAgent.dist`,`shadowSourceProject.rule.src`,`shadowSourceProject.rule.dist`,`shadowSourceProject.globalMemory.src`,`shadowSourceProject.globalMemory.dist`,`shadowSourceProject.workspaceMemory.src`,`shadowSourceProject.workspaceMemory.dist`,`shadowSourceProject.project.src`,`shadowSourceProject.project.dist`,`logLevel`];function yn(e){return vn.includes(e)}function bn(e){return[`trace`,`debug`,`info`,`warn`,`error`].includes(e)}function xn(){return f.join(p.homedir(),an,rn)}function Sn(){let e=xn();if(!d.existsSync(e))return{};try{let t=d.readFileSync(e,`utf8`);return JSON.parse(t)}catch{return{}}}function Cn(e){let t=xn(),n=f.dirname(t);d.existsSync(n)||d.mkdirSync(n,{recursive:!0}),d.writeFileSync(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)}function wn(e,t,n){let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++){let t=r[e];(typeof i[t]!=`object`||i[t]===null)&&(i[t]={}),i=i[t]}i[r.at(-1)]=n}function Tn(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return;r=r[e]}return r}var En=class{name=`config`;constructor(e){this.options=e}async execute(e){let{logger:t}=e;if(this.options.length===0)return t.error(`No configuration key-value pairs provided`),t.info(`Usage: tnmsc config key=value`),t.info(`Valid keys: ${vn.join(`, `)}`),{success:!1,filesAffected:0,dirsAffected:0,message:`No options provided`};let n=Sn(),r=[],i=[];for(let[e,a]of this.options){if(!yn(e)){r.push(`Invalid key: ${e} (valid keys: ${vn.join(`, `)})`);continue}if(e===`logLevel`&&!bn(a)){r.push(`Invalid logLevel value: ${a} (must be: trace, debug, info, warn, or error)`);continue}let o=Tn(n,e);wn(n,e,a),o!==a&&i.push(`${e}=${a}`),t.info(`configuration updated`,{key:e,value:a})}if(i.length>0&&(Cn(n),t.info(`global config written`,{path:xn()})),r.length>0)for(let e of r)t.error(e);let a=r.length===0,o=a?`Configuration updated: ${i.join(`, `)}`:`Partial update: ${i.join(`, `)}. Errors: ${r.join(`, `)}`;return{success:a,filesAffected:i.length>0?1:0,dirsAffected:0,message:o}}},Dn=class{name=`config-show`;async execute(e){let{logger:t}=e,n=new dn,r=n.load(),i=r.sources.map(e=>{let t=n.loadFromFile(e);return{path:e,layer:this.inferLayer(e),config:t.config}}),a={merged:r.config,sources:i};return u.default.stdout.write(`${JSON.stringify(a)}\n`),t.info(`config shown`,{sources:r.sources.length}),{success:!0,filesAffected:0,dirsAffected:0,message:`Configuration displayed (${i.length} source(s))`}}inferLayer(e){let t=u.default.cwd();return e.startsWith(t)?`cwd`:`global`}},On=class{name=`dry-run-clean`;async execute(e){let{logger:t,outputPlugins:n,createCleanContext:r}=e;t.info(`running clean pipeline`,{command:`dry-run-clean`,dryRun:!0});let i=r(!0),a=await ut(n,i);t.info(`collected outputs for cleanup`,{dryRun:!0,projectDirs:a.projectDirs.length,projectFiles:a.projectFiles.length,globalDirs:a.globalDirs.length,globalFiles:a.globalFiles.length});let{filesToDelete:o,dirsToDelete:s}=await ht(n,await dt(n,i),i);return this.logDryRunFiles(o,t),this.logDryRunDirectories(s,t),await ft(n,i),t.info(`clean complete`,{dryRun:!0,filesAffected:o.length,dirsAffected:s.length}),{success:!0,filesAffected:o.length,dirsAffected:s.length,message:`Dry-run complete, no files were deleted`}}logDryRunFiles(e,t){for(let n of e){let e=f.isAbsolute(n)?n:f.resolve(n);t.info(`would delete file`,{path:e,dryRun:!0})}}logDryRunDirectories(e,t){let n=[...e].sort((e,t)=>t.length-e.length);for(let e of n){let n=f.isAbsolute(e)?e:f.resolve(e);t.info(`would delete directory`,{path:n,dryRun:!0})}}},kn=class{name=`dry-run-output`;async execute(e){let{logger:t,outputPlugins:n,createWriteContext:r}=e;t.info(`started`,{command:`dry-run-output`,dryRun:!0});let i=r(!0),a=await pt(n,i),o=await mt(n.filter(e=>!!(a.get(e.name)?.project??!0)),i),s=0,c=0;for(let[e,n]of o)s+=n.files.length,c+=n.dirs.length,t.info(`plugin result`,{plugin:e,files:n.files.length,dirs:n.dirs.length,dryRun:!0});return t.info(`complete`,{command:`dry-run-output`,totalFiles:s,totalDirs:c,dryRun:!0}),{success:!0,filesAffected:s,dirsAffected:c,message:`Dry-run complete, no files were written`}}},An=class{name=`execute`;async execute(e){let{logger:t,outputPlugins:n,createCleanContext:r,createWriteContext:i}=e;t.info(`started`,{command:`execute`});let a=await vt(n,r(!1),t,{executeHooks:!1});t.info(`cleanup complete`,{deletedFiles:a.deletedFiles,deletedDirs:a.deletedDirs});let o=i(!1),s=await pt(n,o),c=await mt(n.filter(e=>s.get(e.name)?.project??!0),o),l=0,u=0;for(let e of c.values())l+=e.files.length,u+=e.dirs.length;return t.info(`complete`,{command:`execute`,pluginCount:c.size}),{success:!0,filesAffected:l,dirsAffected:u}}};function jn(){return`2026.10218.12101`}var Mn=class{name=`version`;async execute(e){return e.logger.error(`tnmsc v${jn()}`),{success:!0,filesAffected:0,dirsAffected:0,message:`Version displayed`}}};const Nn=`tnmsc`,Pn=`
|
|
981
|
+
`};const Ut=Object.fromEntries(Vt.map(e=>[e,{path:e,content:Ht[e]??``}])),R={USER_HOME:`~`,WORKSPACE:`$WORKSPACE`},Wt=JSON.parse(Ut[`public/tnmsc.example.json`].content),z={reset:`\x1B[0m`,red:`\x1B[31m`,yellow:`\x1B[33m`,cyan:`\x1B[36m`,magenta:`\x1B[35m`,gray:`\x1B[90m`,blue:`\x1B[34m`,green:`\x1B[32m`,white:`\x1B[37m`,dim:`\x1B[2m`,bgRed:`\x1B[41m`},Gt={red:e=>`${z.red}${e}${z.reset}`,yellow:e=>`${z.yellow}${e}${z.reset}`,cyan:e=>`${z.cyan}${e}${z.reset}`,magenta:e=>`${z.magenta}${e}${z.reset}`,gray:e=>`${z.gray}${e}${z.reset}`,blue:e=>`${z.blue}${e}${z.reset}`,green:e=>`${z.green}${e}${z.reset}`,white:e=>`${z.white}${e}${z.reset}`,dim:e=>`${z.dim}${e}${z.reset}`,bgRed:e=>`${z.bgRed}${e}${z.reset}`};let Kt;const qt={error:Gt.red,warn:Gt.yellow,info:Gt.cyan,debug:Gt.magenta,trace:Gt.gray,fatal:Gt.bgRed},Jt={silent:0,fatal:1,error:2,warn:3,info:4,debug:5,trace:6};function Yt(e){if(e===null)return Gt.dim(`null`);if(e===void 0)return Gt.dim(`undefined`);if(typeof e==`boolean`)return Gt.yellow(String(e));if(typeof e==`number`)return Gt.blue(String(e));if(typeof e==`string`)return Gt.green(`"${e}"`);if(Array.isArray(e))return e.length===0?`[]`:`[${e.map(e=>Yt(e)).join(`,`)}]`;if(e instanceof Error){let t={name:e.name,message:e.message,stack:e.stack};for(let n of Object.getOwnPropertyNames(e))n!==`name`&&n!==`message`&&n!==`stack`&&(t[n]=e[n]);return Xt(t)}return typeof e==`object`?Xt(e):String(e)}function Xt(e){let t=Object.entries(e);return t.length===0?`{}`:`{${t.map(([e,t])=>`${/^[\w$]+$/.test(e)?Gt.magenta(e):Gt.yellow(`"${e}"`)}:${Yt(t)}`).join(`,`)}}`}function Zt(){let e=new Date;return`${String(e.getHours()).padStart(2,`0`)}:${String(e.getMinutes()).padStart(2,`0`)}:${String(e.getSeconds()).padStart(2,`0`)}.${String(e.getMilliseconds()).padStart(3,`0`)}`}function Qt(e,t,n,r){let i=Zt(),a=qt[e]??Gt.white,o=String(n),s=r!=null&&Object.keys(r).length>0,c=o===``,l={$:[i,e,t],_:s?c?r:{[o]:r}:n},u={$:[i,a(e.toUpperCase()),t]},d=s?c?r:{[o]:r}:n,f=Xt({...u,_:d});return e===`error`||e===`fatal`?console.error(f):e===`warn`?console.warn(f):e===`debug`||e===`trace`?console.debug(f):console.log(f),l}function $t(e,t,n){let r=Jt[e],i=Jt[n];return(n,...a)=>r>i?{$:[Zt(),e,t],_:n}:typeof n==`string`?Qt(e,t,n,a.length===1&&typeof a[0]==`object`&&a[0]!==null?a[0]:a.length>0?{args:a}:void 0):typeof n==`object`&&n?Qt(e,t,``,n):Qt(e,t,n)}function en(e){Kt=e}function tn(){return Kt}function nn(e,t){let n=t??Kt??process.env.LOG_LEVEL??`info`;return{error:$t(`error`,e,n),warn:$t(`warn`,e,n),info:$t(`info`,e,n),debug:$t(`debug`,e,n),trace:$t(`trace`,e,n),fatal:$t(`fatal`,e,n)}}const rn=`.tnmsc.json`,an=`.aindex`;function on(){return f.join(p.homedir(),an,rn)}function sn(){return{...Wt}}function cn(e,t){let n=on(),r=f.dirname(n);d.existsSync(r)||d.mkdirSync(r,{recursive:!0}),d.writeFileSync(n,`${JSON.stringify(e,null,2)}\n`,`utf8`),t.info(`global config created`,{path:n})}function ln(e,t){let n=[];if(typeof e!=`object`||!e||Array.isArray(e))return n.push(`${t} must be an object with "src" and "dist" string fields`),n;let r=e;return(!(`src`in r)||typeof r.src!=`string`)&&n.push(`${t}.src must be a string`),(!(`dist`in r)||typeof r.dist!=`string`)&&n.push(`${t}.dist must be a string`),n}function un(e,t){let n=[];if(typeof e!=`object`||!e||Array.isArray(e))return n.push(`${t} must be an object`),{errors:n,config:void 0};let r=e;(!(`name`in r)||typeof r.name!=`string`)&&n.push(`${t}.name must be a string`);let i=[`skill`,`fastCommand`,`subAgent`,`rule`,`globalMemory`,`workspaceMemory`,`project`],a={};for(let e of i)if(e in r){let i=ln(r[e],`${t}.${e}`);if(n.push(...i),i.length===0){let t=r[e];a[e]={src:t.src,dist:t.dist}}}return n.length>0?{errors:n,config:void 0}:{errors:n,config:{name:r.name,skill:a.skill??{src:`src/skills`,dist:`dist/skills`},fastCommand:a.fastCommand??{src:`src/commands`,dist:`dist/commands`},subAgent:a.subAgent??{src:`src/agents`,dist:`dist/agents`},rule:a.rule??{src:`src/rules`,dist:`dist/rules`},globalMemory:a.globalMemory??{src:`app/global.cn.mdx`,dist:`dist/global.mdx`},workspaceMemory:a.workspaceMemory??{src:`app/workspace.cn.mdx`,dist:`dist/app/workspace.mdx`},project:a.project??{src:`app`,dist:`dist/app`}}}}var dn=class{configFileName;searchCwd;searchGlobal;customSearchPaths;logger;constructor(e={}){this.configFileName=e.configFileName??rn,this.searchCwd=e.searchCwd??!0,this.searchGlobal=e.searchGlobal??!0,this.customSearchPaths=e.searchPaths??[],this.logger=nn(`ConfigLoader`)}getSearchPaths(e=u.default.cwd()){let t=[];for(let e of this.customSearchPaths)t.push(this.resolveTilde(e));return this.searchCwd&&t.push(f.join(e,this.configFileName)),this.searchGlobal&&t.push(f.join(p.homedir(),an,this.configFileName)),t}loadFromFile(e){let t=this.resolveTilde(e);try{if(!d.existsSync(t))return{config:{},source:null,found:!1};let e=d.readFileSync(t,`utf8`),n=this.parseConfig(e,t);return this.logger.debug(`loaded`,{source:t}),{config:n,source:t,found:!0}}catch(e){return this.logger.warn(`load failed`,{path:t,error:e}),{config:{},source:null,found:!1}}}load(e=u.default.cwd()){let t=this.getSearchPaths(e),n=[];for(let e of t){let t=this.loadFromFile(e);t.found&&n.push(t)}return{config:this.mergeConfigs(n.map(e=>e.config)),sources:n.map(e=>e.source).filter(e=>e!==null),found:n.length>0}}parseConfig(e,t){try{let n=JSON.parse(e);if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`Config must be a JSON object`);return this.validateConfig(n,t)}catch(e){throw e instanceof SyntaxError?Error(`Invalid JSON in ${t}: ${e.message}`):e}}validateConfig(e,t){let n={},r=[];if(`version`in e&&(typeof e.version==`string`?n.version=e.version:r.push(`version must be a string`)),`workspaceDir`in e&&(typeof e.workspaceDir==`string`?n.workspaceDir=e.workspaceDir:r.push(`workspaceDir must be a string`)),`shadowSourceProject`in e){let{errors:t,config:i}=un(e.shadowSourceProject,`shadowSourceProject`);r.push(...t),i!=null&&(n.shadowSourceProject=i)}if(`logLevel`in e){let t=[`trace`,`debug`,`info`,`warn`,`error`],i=e.logLevel;typeof i==`string`&&t.includes(i)?n.logLevel=i:r.push(`logLevel must be one of: ${t.join(`, `)}`)}if(`profile`in e){let t=e.profile;typeof t==`object`&&t&&!Array.isArray(t)?n.profile=t:r.push(`profile must be an object`)}if(`tool`in e){let t=e.tool;if(typeof t==`object`&&t&&!Array.isArray(t)){let e=t,i={},a=!0;for(let[t,n]of Object.entries(e))typeof n==`string`||n===void 0?i[t]=n:(r.push(`tool.${t} must be a string`),a=!1);a&&(n.tool=i)}else r.push(`tool must be an object`)}if(`fastCommandSeriesOptions`in e){let t=e.fastCommandSeriesOptions;typeof t==`object`&&t&&!Array.isArray(t)?n.fastCommandSeriesOptions=t:r.push(`fastCommandSeriesOptions must be an object`)}return r.length>0&&this.logger.warn(`validation warnings`,{path:t,errors:r}),n}mergeConfigs(e){if(e.length===0)return{};let t=e[0];return e.length===1&&t!=null?t:[...e].reverse().reduce((e,t)=>{let n=this.mergeShadowSourceProject(e.shadowSourceProject,t.shadowSourceProject);return{...e,...t,...n==null?{}:{shadowSourceProject:n}}},{})}mergeShadowSourceProject(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{name:t.name??e.name,skill:{...e.skill,...t.skill},fastCommand:{...e.fastCommand,...t.fastCommand},subAgent:{...e.subAgent,...t.subAgent},rule:{...e.rule,...t.rule},globalMemory:{...e.globalMemory,...t.globalMemory},workspaceMemory:{...e.workspaceMemory,...t.workspaceMemory},project:{...e.project,...t.project}}}resolveTilde(e){return e.startsWith(`~`)?f.join(p.homedir(),e.slice(1)):e}};let fn=null;function pn(e){return(e||!fn)&&(fn=new dn(e)),fn}function mn(e){return pn().load(e)}function hn(){let e=nn(`ConfigLoader`),t=on();if(!d.existsSync(t))return e.warn(`global config not found, creating default config`,{path:t}),cn(sn(),e),{valid:!0,exists:!1,errors:[],shouldExit:!1};let n;try{n=d.readFileSync(t,`utf8`)}catch(n){let r=n instanceof Error?n.message:String(n);return e.error(`failed to read global config`,{path:t,error:r}),_n(t,e,[`Failed to read config: ${r}`])}let r;try{r=JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return e.error(`invalid JSON in global config`,{path:t,error:r}),_n(t,e,[`Invalid JSON: ${r}`])}if(typeof r!=`object`||!r||Array.isArray(r))return e.error(`global config must be a JSON object`,{path:t}),_n(t,e,[`Config must be a JSON object`]);let i=gn(r);if(i.length>0){for(let n of i)e.error(`config validation error`,{path:t,error:n});return _n(t,e,i)}return{valid:!0,exists:!0,errors:[],shouldExit:!1}}function gn(e){let t=[];if(`version`in e&&typeof e.version!=`string`&&t.push(`version must be a string`),`workspaceDir`in e&&typeof e.workspaceDir!=`string`&&t.push(`workspaceDir must be a string`),`shadowSourceProject`in e){let{errors:n}=un(e.shadowSourceProject,`shadowSourceProject`);t.push(...n)}if(`logLevel`in e){let n=[`trace`,`debug`,`info`,`warn`,`error`],r=e.logLevel;(typeof r!=`string`||!n.includes(r))&&t.push(`logLevel must be one of: ${n.join(`, `)}`)}if(`profile`in e){let n=e.profile;(typeof n!=`object`||!n||Array.isArray(n))&&t.push(`profile must be an object`)}if(!(`tool`in e))return t;let n=e.tool;if(typeof n!=`object`||!n||Array.isArray(n))t.push(`tool must be an object`);else{let e=n;for(let[n,r]of Object.entries(e))typeof r!=`string`&&r!==void 0&&t.push(`tool.${n} must be a string`)}return t}function _n(e,t,n){try{d.unlinkSync(e),t.info(`deleted invalid config`,{path:e})}catch{t.warn(`failed to delete invalid config`,{path:e})}return cn(sn(),t),t.error(`recreated default config, please review and restart`,{path:e}),{valid:!1,exists:!0,errors:n,shouldExit:!0}}const vn=[`workspaceDir`,`shadowSourceProject.name`,`shadowSourceProject.skill.src`,`shadowSourceProject.skill.dist`,`shadowSourceProject.fastCommand.src`,`shadowSourceProject.fastCommand.dist`,`shadowSourceProject.subAgent.src`,`shadowSourceProject.subAgent.dist`,`shadowSourceProject.rule.src`,`shadowSourceProject.rule.dist`,`shadowSourceProject.globalMemory.src`,`shadowSourceProject.globalMemory.dist`,`shadowSourceProject.workspaceMemory.src`,`shadowSourceProject.workspaceMemory.dist`,`shadowSourceProject.project.src`,`shadowSourceProject.project.dist`,`logLevel`];function yn(e){return vn.includes(e)}function bn(e){return[`trace`,`debug`,`info`,`warn`,`error`].includes(e)}function xn(){return f.join(p.homedir(),an,rn)}function Sn(){let e=xn();if(!d.existsSync(e))return{};try{let t=d.readFileSync(e,`utf8`);return JSON.parse(t)}catch{return{}}}function Cn(e){let t=xn(),n=f.dirname(t);d.existsSync(n)||d.mkdirSync(n,{recursive:!0}),d.writeFileSync(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)}function wn(e,t,n){let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++){let t=r[e];(typeof i[t]!=`object`||i[t]===null)&&(i[t]={}),i=i[t]}i[r.at(-1)]=n}function Tn(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r)return;r=r[e]}return r}var En=class{name=`config`;constructor(e){this.options=e}async execute(e){let{logger:t}=e;if(this.options.length===0)return t.error(`No configuration key-value pairs provided`),t.info(`Usage: tnmsc config key=value`),t.info(`Valid keys: ${vn.join(`, `)}`),{success:!1,filesAffected:0,dirsAffected:0,message:`No options provided`};let n=Sn(),r=[],i=[];for(let[e,a]of this.options){if(!yn(e)){r.push(`Invalid key: ${e} (valid keys: ${vn.join(`, `)})`);continue}if(e===`logLevel`&&!bn(a)){r.push(`Invalid logLevel value: ${a} (must be: trace, debug, info, warn, or error)`);continue}let o=Tn(n,e);wn(n,e,a),o!==a&&i.push(`${e}=${a}`),t.info(`configuration updated`,{key:e,value:a})}if(i.length>0&&(Cn(n),t.info(`global config written`,{path:xn()})),r.length>0)for(let e of r)t.error(e);let a=r.length===0,o=a?`Configuration updated: ${i.join(`, `)}`:`Partial update: ${i.join(`, `)}. Errors: ${r.join(`, `)}`;return{success:a,filesAffected:i.length>0?1:0,dirsAffected:0,message:o}}},Dn=class{name=`config-show`;async execute(e){let{logger:t}=e,n=new dn,r=n.load(),i=r.sources.map(e=>{let t=n.loadFromFile(e);return{path:e,layer:this.inferLayer(e),config:t.config}}),a={merged:r.config,sources:i};return u.default.stdout.write(`${JSON.stringify(a)}\n`),t.info(`config shown`,{sources:r.sources.length}),{success:!0,filesAffected:0,dirsAffected:0,message:`Configuration displayed (${i.length} source(s))`}}inferLayer(e){let t=u.default.cwd();return e.startsWith(t)?`cwd`:`global`}},On=class{name=`dry-run-clean`;async execute(e){let{logger:t,outputPlugins:n,createCleanContext:r}=e;t.info(`running clean pipeline`,{command:`dry-run-clean`,dryRun:!0});let i=r(!0),a=await ut(n,i);t.info(`collected outputs for cleanup`,{dryRun:!0,projectDirs:a.projectDirs.length,projectFiles:a.projectFiles.length,globalDirs:a.globalDirs.length,globalFiles:a.globalFiles.length});let{filesToDelete:o,dirsToDelete:s}=await ht(n,await dt(n,i),i);return this.logDryRunFiles(o,t),this.logDryRunDirectories(s,t),await ft(n,i),t.info(`clean complete`,{dryRun:!0,filesAffected:o.length,dirsAffected:s.length}),{success:!0,filesAffected:o.length,dirsAffected:s.length,message:`Dry-run complete, no files were deleted`}}logDryRunFiles(e,t){for(let n of e){let e=f.isAbsolute(n)?n:f.resolve(n);t.info(`would delete file`,{path:e,dryRun:!0})}}logDryRunDirectories(e,t){let n=[...e].sort((e,t)=>t.length-e.length);for(let e of n){let n=f.isAbsolute(e)?e:f.resolve(e);t.info(`would delete directory`,{path:n,dryRun:!0})}}},kn=class{name=`dry-run-output`;async execute(e){let{logger:t,outputPlugins:n,createWriteContext:r}=e;t.info(`started`,{command:`dry-run-output`,dryRun:!0});let i=r(!0),a=await pt(n,i),o=await mt(n.filter(e=>!!(a.get(e.name)?.project??!0)),i),s=0,c=0;for(let[e,n]of o)s+=n.files.length,c+=n.dirs.length,t.info(`plugin result`,{plugin:e,files:n.files.length,dirs:n.dirs.length,dryRun:!0});return t.info(`complete`,{command:`dry-run-output`,totalFiles:s,totalDirs:c,dryRun:!0}),{success:!0,filesAffected:s,dirsAffected:c,message:`Dry-run complete, no files were written`}}},An=class{name=`execute`;async execute(e){let{logger:t,outputPlugins:n,createCleanContext:r,createWriteContext:i}=e;t.info(`started`,{command:`execute`});let a=await vt(n,r(!1),t,{executeHooks:!1});t.info(`cleanup complete`,{deletedFiles:a.deletedFiles,deletedDirs:a.deletedDirs});let o=i(!1),s=await pt(n,o),c=await mt(n.filter(e=>s.get(e.name)?.project??!0),o),l=0,u=0;for(let e of c.values())l+=e.files.length,u+=e.dirs.length;return t.info(`complete`,{command:`execute`,pluginCount:c.size}),{success:!0,filesAffected:l,dirsAffected:u}}};function jn(){return`2026.10219.10049`}var Mn=class{name=`version`;async execute(e){return e.logger.error(`tnmsc v${jn()}`),{success:!0,filesAffected:0,dirsAffected:0,message:`Version displayed`}}};const Nn=`tnmsc`,Pn=`
|
|
982
982
|
${Nn} v${jn()} - Memory Sync CLI
|
|
983
983
|
|
|
984
984
|
Synchronize AI memory and configuration files across projects.
|
|
@@ -1039,7 +1039,7 @@ CONFIG OPTIONS:
|
|
|
1039
1039
|
CONFIGURATION:
|
|
1040
1040
|
Configure via plugin.config.ts in your project root.
|
|
1041
1041
|
See documentation for detailed configuration options.
|
|
1042
|
-
`.trim();var Fn=class{name=`help`;async execute(e){return console.log(Pn),{success:!0,filesAffected:0,dirsAffected:0,message:`Help displayed`}}};function In(e,t){let n=f.join(e,`.git`),r=d.existsSync(n);return r?t?.info(`version control detected`,{path:n}):t?.warn(`no version control detected, please use git to manage your shadow source project`,{path:e}),{hasGit:r,gitPath:n}}function Ln(e,t,n,r,i){if(n==null)return r;let a=f.relative(t,e),o=f.join(n,a);return d.existsSync(o)&&d.statSync(o).isFile()?(i?.debug(`copying from source`,{path:o}),d.readFileSync(o,`utf8`)):r}function Rn(e,t={}){let{sourceDir:n,logger:r}=t,i=[],a=[],o=[],s=[],c=new Set;d.existsSync(e)?(o.push(e),r?.debug(`directory exists`,{path:e})):(d.mkdirSync(e,{recursive:!0}),i.push(e),c.add(e),r?.info(`created directory`,{path:e}));for(let t of Object.values(Ut)){let o=t.path,l=f.join(e,o),u=f.dirname(l);if(!d.existsSync(u)){d.mkdirSync(u,{recursive:!0});let t=u;for(;t!==e&&!c.has(t);)c.add(t),i.push(t),r?.info(`created directory`,{path:t}),t=f.dirname(t)}if(d.existsSync(l))s.push(l),r?.debug(`file exists`,{path:l});else{let i=Ln(l,e,n,t.content,r);d.writeFileSync(l,i,`utf8`),a.push(l),r?.info(`created file`,{path:l})}}return{success:!0,rootPath:e,createdDirs:i,createdFiles:a,existedDirs:o,existedFiles:s}}function zn(e){let t=e;return t.startsWith(`~`)&&(t=f.join(p.homedir(),t.slice(1))),f.normalize(t)}var Bn=class{name=`init`;async execute(e){let{logger:t,userConfigOptions:n}=e;t.info(`initializing shadow source project structure`,{command:`init`});let r=zn(n.workspaceDir),i=Rn(f.join(r,n.shadowSourceProject.name),{logger:t}),a=i.createdDirs.length===0&&i.createdFiles.length===0?`All ${i.existedDirs.length} directories and ${i.existedFiles.length} files already exist`:`Created ${i.createdDirs.length} directories and ${i.createdFiles.length} files (${i.existedDirs.length} dirs, ${i.existedFiles.length} files already existed)`;return t.info(`initialization complete`,{dirsCreated:i.createdDirs.length,filesCreated:i.createdFiles.length,dirsExisted:i.existedDirs.length,filesExisted:i.existedFiles.length}),{success:i.success,filesAffected:i.createdFiles.length,dirsAffected:i.createdDirs.length,message:a}}},Vn=class{name;inner;constructor(e){this.inner=e,this.name=`json:${e.name}`}async execute(e){let t=await this.inner.execute(e),n=Hn(t);return u.default.stdout.write(`${JSON.stringify(n)}\n`),t}};function Hn(e){return{success:e.success,filesAffected:e.filesAffected,dirsAffected:e.dirsAffected,...e.message!=null&&{message:e.message},pluginResults:[],errors:[]}}function Un(){return`@truenine/memory-sync-cli`}function Wn(){return`https://registry.npmjs.org/${Un()}/latest`}function Gn(e){let t=e.replace(/^v/,``),n=/^(\d+)\.(\d+)\.(\d+)/.exec(t);return n==null?null:[Number.parseInt(n[1],10),Number.parseInt(n[2],10),Number.parseInt(n[3],10)]}function Kn(e,t){let n=Gn(e),r=Gn(t);if(n==null||r==null)return 0;for(let e=0;e<3;e++){if(n[e]<r[e])return-1;if(n[e]>r[e])return 1}return 0}const qn=3e3;async function Jn(){let e=new AbortController,t=setTimeout(()=>e.abort(),qn);typeof t==`object`&&`unref`in t&&t.unref();try{let n=await fetch(Wn(),{headers:{Accept:`application/json`},signal:e.signal});if(clearTimeout(t),!n.ok)return{error:`HTTP ${n.status}: ${n.statusText}`};let r=await n.json();return r.version==null?{error:`Invalid response: missing version field`}:{version:r.version}}catch(e){return clearTimeout(t),e instanceof Error?e.name===`TimeoutError`||e.name===`AbortError`?{error:`Request timeout after ${qn}ms`}:{error:e.message}:{error:`Unknown network error`}}}function Yn(){return`2026.10218.12101`}async function Xn(){let e=Yn();if(e===`dev`)return{status:`development`,localVersion:e,remoteVersion:null};let t=await Jn();if(`error`in t)return{status:`current`,localVersion:e,remoteVersion:null,error:t.error};let n=t.version,r=Kn(e,n);return r<0?{status:`outdated`,localVersion:e,remoteVersion:n}:r>0?{status:`development`,localVersion:e,remoteVersion:n}:{status:`current`,localVersion:e,remoteVersion:n}}function Zn(e,t){let{status:n,localVersion:r,remoteVersion:i}=e;switch(n){case`outdated`:t.warn(`Version outdated: ${r} → ${i}. Run 'npm i -g ${Un()}@latest' to update.`);break;case`current`:e.error==null?t.info(`Version ${r} is up to date.`):t.error(`Version check failed: ${e.error}`);break;case`development`:i==null?t.debug(`Running in development mode, version check skipped.`):t.info(`Development version detected: ${r} > ${i}. Thanks for contributing!`);break}}function Qn(){return new Date().getMinutes()%2==0}function $n(e){Qn()&&Xn().then(t=>{(t.status===`outdated`||t.error!=null)&&Zn(t,e)}).catch(t=>{let n=t instanceof Error?t.message:`Unknown error`;e.error(`Version check failed: ${n}`)})}var er=class{name=`outdated`;async execute(e){let t=await Xn();return Zn(t,e.logger),{success:!0,filesAffected:0,dirsAffected:0,message:`Version status: ${t.status}`}}},tr=class{name=`plugins`;async execute(e){let{logger:t,outputPlugins:n,userConfigOptions:r}=e,i=r.plugins,a=[];for(let e of i)a.push({name:e.name,kind:e.type===bt.Input?`Input`:`Output`,description:e.name,dependencies:[...e.dependsOn??[]]});let o=new Set(a.map(e=>e.name));for(let e of n)o.has(e.name)||a.push({name:e.name,kind:`Output`,description:e.name,dependencies:[...e.dependsOn??[]]});return u.default.stdout.write(`${JSON.stringify(a)}\n`),t.info(`plugins listed`,{count:a.length}),{success:!0,filesAffected:0,dirsAffected:0,message:`Listed ${a.length} plugin(s)`}}},nr=class{name=`unknown`;constructor(e){this.unknownCmd=e}async execute(e){return console.error(`Unknown command: ${this.unknownCmd}`),console.error(`Run "tnmsc help" for available commands.`),{success:!1,filesAffected:0,dirsAffected:0}}};const rr={default:{websearch:`web_search`,webfetch:`web_fetch`,readFile:`read_file`,writeFile:`write_file`,executeCommand:`execute_command`,todolistWrite:`todolist_write`,grep:`grep`,listDirectory:`list_directory`},claudeCode:{readFile:`Read`,writeFile:`Write`,executeCommand:`Execute`,todolistWrite:`TodoWrite`,listDirectory:`List`},kiro:{websearch:`remote_web_search`,webfetch:`webFetch`,readFile:`readFile`,writeFile:`fsWrite`,executeCommand:`executeBash`,todolistWrite:`todolistWrite`,grep:`grepSearch`,listDirectory:`listDir`}};let ir=function(e){return e.Bash=`bash`,e.Zsh=`zsh`,e.Fish=`fish`,e.Sh=`sh`,e.PowerShell=`powershell`,e.Pwsh=`pwsh`,e.Cmd=`cmd`,e.Unknown=`unknown`,e}({}),ar=function(e){return e.Win=`win`,e.Mac=`mac`,e.Linux=`linux`,e.Unknown=`unknown`,e}({});var or=class{userConfig;toolPreset;constructor(e={}){this.userConfig=e.userConfig,this.toolPreset=e.toolPreset??`default`}collect(){return{os:this.collectOsInfo(),env:this.collectEnvContext(),profile:this.collectProfile(),tool:this.collectToolReferences(),Md:this.createMdComponent()}}collectOsInfo(){let e=p.platform();return{platform:e,arch:p.arch(),hostname:p.hostname(),homedir:p.homedir(),tmpdir:p.tmpdir(),type:p.type(),release:p.release(),shellKind:this.detectShellKind(),kind:this.detectOsKind(e)}}detectOsKind(e){switch(e){case`win32`:return ar.Win;case`darwin`:return ar.Mac;case`linux`:case`freebsd`:case`openbsd`:case`sunos`:case`aix`:return ar.Linux;default:return ar.Unknown}}detectShellKind(){let e=(u.default.env.SHELL??u.default.env.ComSpec??``).toLowerCase();return e.includes(`bash`)?ir.Bash:e.includes(`zsh`)?ir.Zsh:e.includes(`fish`)?ir.Fish:e.includes(`pwsh`)?ir.Pwsh:e.includes(`powershell`)?ir.PowerShell:e.includes(`cmd`)?ir.Cmd:e.endsWith(`/sh`)?ir.Sh:ir.Unknown}collectEnvContext(){return{...u.default.env}}collectProfile(){return this.userConfig?.profile==null?{}:this.userConfig.profile}collectToolReferences(){let e={...rr.default};return this.toolPreset===`claudeCode`?{...e,...rr.claudeCode}:this.toolPreset===`kiro`?{...e,...rr.kiro}:e}createMdComponent(){let e=(e=>e.when===!1?null:e.children);return e.Line=e=>e.when===!1?null:e.children,e}};let sr=function(e){return e[e.SystemDefault=0]=`SystemDefault`,e[e.UserConfig=10]=`UserConfig`,e[e.PluginRegistered=20]=`PluginRegistered`,e[e.CompileTime=30]=`CompileTime`,e}({});var cr=class{registrations=[];globalScope=null;setGlobalScope(e){this.globalScope=e}getGlobalScope(){return this.globalScope}register(e,t,n=sr.PluginRegistered){this.registrations.push({namespace:e,values:t,priority:n})}getRegistrations(){return this.registrations}merge(e){let t={};this.globalScope!=null&&(t.os={...this.globalScope.os},t.env={...this.globalScope.env},t.profile={...this.globalScope.profile},t.tool={...this.globalScope.tool});let n=[...this.registrations].sort((e,t)=>e.priority-t.priority);for(let e of n)t[e.namespace]=this.deepMerge(t[e.namespace],e.values);if(e!=null)for(let[n,r]of Object.entries(e))t[n]=typeof r==`object`&&r&&!Array.isArray(r)?this.deepMerge(t[n],r):r;return t}deepMerge(e,t){if(e==null)return{...t};let n={...e};for(let[e,r]of Object.entries(t))n[e]=typeof r==`object`&&r&&!Array.isArray(r)&&typeof n[e]==`object`&&n[e]!==null&&!Array.isArray(n[e])?this.deepMerge(n[e],r):r;return n}clear(){this.registrations.length=0,this.globalScope=null}};function lr(e){let t=[...e],n=t[0];n!=null&&ur(n)&&t.shift();let r=t[0];return r!=null&&dr(r)&&t.shift(),t}function ur(e){let t=[`node`,`nodejs`,`bun`,`deno`,`tsx`,`ts-node`,`npx`,`pnpx`,`yarn`,`pnpm`],n=e.toLowerCase().replaceAll(`\\`,`/`);return t.some(e=>RegExp(`(?:^|/)${e}(?:\\.exe|\\.cmd|\\.ps1)?$`,`i`).test(n)||n===e)}function dr(e){return/\.(?:m?[jt]s|cjs)$/.test(e)||/[/\\]/.test(e)&&!e.startsWith(`-`)?!0:/^(?:@[\w-]+\/)?[\w-]+$/.test(e)&&!e.startsWith(`-`)}const fr=new Set([`help`,`version`,`outdated`,`init`,`dry-run`,`clean`,`config`,`plugins`]),pr=new Map([[`--trace`,`trace`],[`--debug`,`debug`],[`--info`,`info`],[`--warn`,`warn`],[`--error`,`error`]]),mr=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4]]);function hr(e){let{logLevelFlags:t}=e;if(t.length===0)return;let n=t[0],r=mr.get(n)??4;for(let e of t){let t=mr.get(e)??4;t<r&&(r=t,n=e)}return n}function gr(e){let{helpFlag:t,versionFlag:n,subcommand:r,dryRun:i,unknownCommand:a,setOption:o,positional:s,showFlag:c}=e;if(n)return new Mn;if(t)return new Fn;if(a!=null)return new nr(a);if(r===`version`)return new Mn;if(r===`help`)return new Fn;if(r===`outdated`)return new er;if(r===`init`)return new Bn;if(r===`dry-run`)return new kn;if(r===`clean`)return i?new On:new yt;if(r===`plugins`)return new tr;if(r===`config`&&c)return new Dn;if(r!==`config`||o.length>0)return new An;let l=[];for(let e of s){let t=e.indexOf(`=`);t>0&&l.push([e.slice(0,t),e.slice(t+1)])}return new En([...o,...l])}function _r(e){let t={subcommand:void 0,helpFlag:!1,versionFlag:!1,dryRun:!1,jsonFlag:!1,showFlag:!1,logLevel:void 0,logLevelFlags:[],setOption:[],unknownCommand:void 0,positional:[],unknown:[]},n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i!=null){if(i===`--`){t.positional.push(...e.slice(r+1).filter(e=>e!=null));break}if(i.startsWith(`--`)){let n=i.split(`=`),a=n[0]??``,o=pr.get(a);if(o!=null){t.logLevelFlags.push(o),t.logLevel=o;continue}switch(a){case`--help`:t.helpFlag=!0;break;case`--version`:t.versionFlag=!0;break;case`--dry-run`:t.dryRun=!0;break;case`--json`:t.jsonFlag=!0;break;case`--show`:t.showFlag=!0;break;case`--set`:if(n.length>1){let e=n.slice(1).join(`=`),r=e.indexOf(`=`);r>0&&t.setOption.push([e.slice(0,r),e.slice(r+1)])}else{let n=e[r+1];if(n!=null){let e=n.indexOf(`=`);e>0&&(t.setOption.push([n.slice(0,e),n.slice(e+1)]),r++)}}break;default:t.unknown.push(i)}continue}if(i.startsWith(`-`)&&i.length>1){let e=i.slice(1);for(let n of e)switch(n){case`h`:t.helpFlag=!0;break;case`v`:t.versionFlag=!0;break;case`n`:t.dryRun=!0;break;case`j`:t.jsonFlag=!0;break;default:t.unknown.push(`-${n}`)}continue}if(!n){n=!0,fr.has(i)?t.subcommand=i:t.unknownCommand=i;continue}t.positional.push(i)}}return t}var vr=class{logger;args;outputPlugins=[];constructor(...e){this.args=_r(lr(e.filter(e=>e!=null)));let t=hr(this.args);t!=null&&en(t),this.logger=nn(`PluginPipeline`,t),this.logger.debug(`initialized`,{args:this.args})}registerOutputPlugins(e){return this.outputPlugins.push(...e),this}async run(e){$n(this.logger);let{context:t,outputPlugins:n,userConfigOptions:r}=e;this.registerOutputPlugins([...n]);let i=this.resolveCommand();this.args.jsonFlag&&(en(`silent`),new Set([`config-show`,`plugins`]).has(i.name)||(i=new Vn(i)));let a=this.createCommandContext(t,r);await i.execute(a)}resolveCommand(){return gr(this.args)}createCommandContext(e,t){return{logger:this.logger,outputPlugins:this.outputPlugins,collectedInputContext:e,userConfigOptions:t,createCleanContext:t=>this.createCleanContext(e,t),createWriteContext:t=>this.createWriteContext(e,t)}}createCleanContext(e,t){return{logger:this.logger,fs:d,path:f,glob:Je.default,collectedInputContext:e,dryRun:t}}createWriteContext(e,t){return{logger:this.logger,fs:d,path:f,glob:Je.default,collectedInputContext:e,dryRun:t,registeredPluginNames:this.outputPlugins.map(e=>e.name)}}buildDependencyGraph(e){let t=new Map;for(let n of e){let e=n.dependsOn??[];t.set(n.name,[...e])}return t}validateDependencies(e){let t=new Set(e.map(e=>e.name));for(let n of e){let e=n.dependsOn??[];for(let r of e)if(!t.has(r))throw new Dt(n.name,r)}}topologicalSort(e){this.validateDependencies(e);let t=new Map;for(let n of e)t.set(n.name,n);let n=new Map;for(let t of e)n.set(t.name,0);let r=new Map;for(let t of e)r.set(t.name,[]);for(let t of e){let e=t.dependsOn??[];for(let i of e){n.set(t.name,(n.get(t.name)??0)+1);let e=r.get(i)??[];e.push(t.name),r.set(i,e)}}let i=[];for(let t of e)n.get(t.name)===0&&i.push(t.name);let a=[];for(;i.length>0;){let o=i.shift(),s=t.get(o);a.push(s);let c=(r.get(o)??[]).sort((t,n)=>e.findIndex(e=>e.name===t)-e.findIndex(e=>e.name===n));for(let e of c){let t=(n.get(e)??0)-1;n.set(e,t),t===0&&i.push(e)}}if(a.length===e.length)return a;throw new Et(this.findCyclePath(e,n))}findCyclePath(e,t){let n=new Set;for(let[e,r]of t)r>0&&n.add(e);let r=new Map;for(let t of e)if(n.has(t.name)){let e=(t.dependsOn??[]).filter(e=>n.has(e));r.set(t.name,e)}let i=new Set,a=[],o=e=>{if(a.includes(e))return a.push(e),!0;if(i.has(e))return!1;i.add(e),a.push(e);for(let t of r.get(e)??[])if(o(t))return!0;return a.pop(),!1};for(let e of n){if(o(e)){let e=a.indexOf(a.at(-1));return a.slice(e)}i.clear(),a.length=0}return[...n]}async executePluginsInOrder(e,t,n=!1,r){if(e.length===0)return{};let i=this.topologicalSort(e),a=new or({userConfig:r}).collect(),o=new cr;o.setGlobalScope(a),this.logger.debug(`global scope collected`,{osInfo:{platform:a.os.platform,arch:a.os.arch,shellKind:a.os.shellKind},hasProfile:Object.keys(a.profile).length>0,hasTool:Object.keys(a.tool).length>0});let s=new Map,c={};for(let e of i){let r=this.buildDependencyContext(e,s),i={...t,dependencyContext:r,globalScope:a,scopeRegistry:o},l=e;l.executeEffects!=null&&await l.executeEffects(i,n);let u=await e.collect(i);s.set(e.name,u),c=this.mergeContexts(c,u);let d=e;if(d.getRegisteredScopes!=null){let t=d.getRegisteredScopes();for(let{namespace:n,values:r}of t)o.register(n,r,sr.PluginRegistered),this.logger.debug(`plugin scope registered`,{plugin:e.name,namespace:n,keys:Object.keys(r)})}}return c}buildDependencyContext(e,t){if((e.dependsOn??[]).length===0)return{};let n=this.collectTransitiveDependencies(e,t),r={};for(let e of n){let n=t.get(e);n!=null&&(r=this.mergeContexts(r,n))}return r}collectTransitiveDependencies(e,t){let n=new Set,r=[];return(e=>{for(let i of e)n.has(i)||(n.add(i),t.get(i)!=null&&r.push(i))})(e.dependsOn??[]),r}mergeContexts(e,t){let{workspace:n}=e;if(t.workspace!=null)if(n!=null){let e=new Map;for(let t of n.projects)e.set(t.name,t);for(let n of t.workspace.projects)e.set(n.name,n);n={directory:t.workspace.directory??n.directory,projects:[...e.values()]}}else ({workspace:n}=t);let r=t.ideConfigFiles==null?e.ideConfigFiles:[...e.ideConfigFiles??[],...t.ideConfigFiles],i=t.fastCommands==null?e.fastCommands:[...e.fastCommands??[],...t.fastCommands],a=t.subAgents==null?e.subAgents:[...e.subAgents??[],...t.subAgents],o=t.skills==null?e.skills:[...e.skills??[],...t.skills],s=t.rules==null?e.rules:[...e.rules??[],...t.rules],c=t.aiAgentIgnoreConfigFiles==null?e.aiAgentIgnoreConfigFiles:[...e.aiAgentIgnoreConfigFiles??[],...t.aiAgentIgnoreConfigFiles],l=t.globalMemory??e.globalMemory,u=t.shadowSourceProjectDir??e.shadowSourceProjectDir,d=t.readmePrompts==null?e.readmePrompts:[...e.readmePrompts??[],...t.readmePrompts],f=t.globalGitIgnore??e.globalGitIgnore,p=t.shadowGitExclude??e.shadowGitExclude;return{...n==null?{}:{workspace:n},...r==null?{}:{ideConfigFiles:r},...i==null?{}:{fastCommands:i},...a==null?{}:{subAgents:a},...o==null?{}:{skills:o},...s==null?{}:{rules:s},...c==null?{}:{aiAgentIgnoreConfigFiles:c},...l==null?{}:{globalMemory:l},...u==null?{}:{shadowSourceProjectDir:u},...d==null?{}:{readmePrompts:d},...f==null?{}:{globalGitIgnore:f},...p==null?{}:{shadowGitExclude:p}}}};const yr={name:`tnmsc-shadow`,skill:{src:`src/skills`,dist:`dist/skills`},fastCommand:{src:`src/commands`,dist:`dist/commands`},subAgent:{src:`src/agents`,dist:`dist/agents`},rule:{src:`src/rules`,dist:`dist/rules`},globalMemory:{src:`app/global.cn.mdx`,dist:`dist/global.mdx`},workspaceMemory:{src:`app/workspace.cn.mdx`,dist:`dist/app/workspace.mdx`},project:{src:`app`,dist:`dist/app`}},br={...Wt,shadowSourceProject:yr,fastCommandSeriesOptions:{},plugins:[]};function xr(e){return{...e.version==null?{}:{version:e.version},...e.workspaceDir==null?{}:{workspaceDir:e.workspaceDir},...e.shadowSourceProject==null?{}:{shadowSourceProject:e.shadowSourceProject},...e.fastCommandSeriesOptions==null?{}:{fastCommandSeriesOptions:e.fastCommandSeriesOptions},...e.logLevel==null?{}:{logLevel:e.logLevel}}}function Sr(...e){return e.reduce((e,t)=>Cr(e,t),{...br})}function Cr(e,t){let n=t.plugins,r=t.fastCommandSeriesOptions;return{...e,...t,shadowSourceProject:wr(e.shadowSourceProject,t.shadowSourceProject),plugins:[...e.plugins,...n??[]],fastCommandSeriesOptions:Tr(e.fastCommandSeriesOptions,r)}}function wr(e,t){return t==null?e:{name:t.name??e.name,skill:{...e.skill,...t.skill},fastCommand:{...e.fastCommand,...t.fastCommand},subAgent:{...e.subAgent,...t.subAgent},rule:{...e.rule,...t.rule},globalMemory:{...e.globalMemory,...t.globalMemory},workspaceMemory:{...e.workspaceMemory,...t.workspaceMemory},project:{...e.project,...t.project}}}function Tr(e,t){if(t==null)return e??{};if(e==null)return t;let n={};if(e.pluginOverrides!=null)for(let[t,r]of Object.entries(e.pluginOverrides))n[t]={...r};if(t.pluginOverrides!=null)for(let[e,r]of Object.entries(t.pluginOverrides))n[e]={...n[e],...r};let r=t.includeSeriesPrefix??e.includeSeriesPrefix,i=Object.keys(n).length>0;return r!=null&&i?{includeSeriesPrefix:r,pluginOverrides:n}:r==null?i?{pluginOverrides:n}:{}:{includeSeriesPrefix:r}}function Er(e){return`pluginOptions`in e||`configLoaderOptions`in e||`loadUserConfig`in e}async function Dr(e={}){hn().shouldExit&&u.default.exit(1);let t,n,r;Er(e)?({pluginOptions:r={},cwd:n}={pluginOptions:e.pluginOptions,cwd:e.cwd},t=e.loadUserConfig??!0):(r=e,t=!0);let i={},a=!1,o=[],s;if(t){let e=mn(n);a=e.found,o=e.sources,e.found&&(i=xr(e.config),s=e.config)}let c=Sr(i,r),{plugins:l=[],logLevel:p}=c,m=nn(`defineConfig`,p);a?m.info(`user config loaded`,{sources:o}):m.info(`no user config found, using defaults`,{workspaceDir:br.workspaceDir,shadowSourceProjectName:br.shadowSourceProject.name,logLevel:br.logLevel});let h={logger:m,userConfigOptions:c,fs:d,path:f,glob:Je.default},g=l.filter(e=>e.type===bt.Input),_=l.filter(e=>e.type===bt.Output),v=await new vr().executePluginsInOrder(g,h,!1,s);if(v.workspace==null)throw Error(`Workspace not initialized by any plugin`);let y={workspace:v.workspace,ideConfigFiles:v.ideConfigFiles??[],...v.fastCommands!=null&&{fastCommands:v.fastCommands},...v.subAgents!=null&&{subAgents:v.subAgents},...v.skills!=null&&{skills:v.skills},...v.rules!=null&&{rules:v.rules},...v.globalMemory!=null&&{globalMemory:v.globalMemory},...v.aiAgentIgnoreConfigFiles!=null&&{aiAgentIgnoreConfigFiles:v.aiAgentIgnoreConfigFiles},...v.shadowSourceProjectDir!=null&&{shadowSourceProjectDir:v.shadowSourceProjectDir},...v.readmePrompts!=null&&{readmePrompts:v.readmePrompts},...v.globalGitIgnore!=null&&{globalGitIgnore:v.globalGitIgnore},...v.shadowGitExclude!=null&&{shadowGitExclude:v.shadowGitExclude}};return v.shadowSourceProjectDir!=null&&In(v.shadowSourceProjectDir,m),{context:y,outputPlugins:_,userConfigOptions:c}}const Or=Lr(/[A-Za-z]/),kr=Lr(/[\dA-Za-z]/),Ar=Lr(/[#-'*+\--9=?A-Z^-~]/);function jr(e){return e!==null&&(e<32||e===127)}const Mr=Lr(/\d/),Nr=Lr(/[\dA-Fa-f]/),Pr=Lr(/[!-/:-@[-`{-~]/);function B(e){return e!==null&&e<-2}function V(e){return e!==null&&(e<0||e===32)}function H(e){return e===-2||e===-1||e===32}const Fr=Lr(/\p{P}|\p{S}/u),Ir=Lr(/\s/);function Lr(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}var Rr=l(o(((e,t)=>{(function(){var e=t===void 0?function(){return this||(0,eval)(`this`)}():t.exports=i;e.format=i,e.vsprintf=r,typeof console<`u`&&typeof console.log==`function`&&(e.printf=n);function n(){console.log(i.apply(null,arguments))}function r(e,t){return i.apply(null,[e].concat(t))}function i(e){for(var t=1,n=[].slice.call(arguments),r=0,i=e.length,a=``,o,s=!1,c,l,u=!1,d,f=function(){return n[t++]},p=function(){for(var t=``;/\d/.test(e[r]);)t+=e[r++],o=e[r];return t.length>0?parseInt(t):null};r<i;++r)if(o=e[r],s)switch(s=!1,o==`.`?(u=!1,o=e[++r]):o==`0`&&e[r+1]==`.`?(u=!0,r+=2,o=e[r]):u=!0,d=p(),o){case`b`:a+=parseInt(f(),10).toString(2);break;case`c`:c=f(),typeof c==`string`||c instanceof String?a+=c:a+=String.fromCharCode(parseInt(c,10));break;case`d`:a+=parseInt(f(),10);break;case`f`:l=String(parseFloat(f()).toFixed(d||6)),a+=u?l:l.replace(/^0/,``);break;case`j`:a+=JSON.stringify(f());break;case`o`:a+=`0`+parseInt(f(),10).toString(8);break;case`s`:a+=f();break;case`x`:a+=`0x`+parseInt(f(),10).toString(16);break;case`X`:a+=`0x`+parseInt(f(),10).toString(16).toUpperCase();break;default:a+=o;break}else o===`%`?s=!0:a+=o;return a}})()}))(),1);const zr=Object.assign(Br(Error),{eval:Br(EvalError),range:Br(RangeError),reference:Br(ReferenceError),syntax:Br(SyntaxError),type:Br(TypeError),uri:Br(URIError)});function Br(e){return t.displayName=e.displayName||e.name,t;function t(t,...n){return new e(t&&(0,Rr.default)(t,...n))}}const Vr={}.hasOwnProperty,Hr={yaml:`-`,toml:`+`};function Ur(e){let t=[],n=-1,r=Array.isArray(e)?e:e?[e]:[`yaml`];for(;++n<r.length;)t[n]=Wr(r[n]);return t}function Wr(e){let t=e;if(typeof t==`string`){if(!Vr.call(Hr,t))throw zr("Missing matter definition for `%s`",t);t={type:t,marker:Hr[t]}}else if(typeof t!=`object`)throw zr("Expected matter to be an object, not `%j`",t);if(!Vr.call(t,`type`))throw zr("Missing `type` in matter `%j`",t);if(!Vr.call(t,`fence`)&&!Vr.call(t,`marker`))throw zr("Missing `marker` or `fence` in matter `%j`",t);return t}function Gr(e){let t=Ur(e),n={},r=-1;for(;++r<t.length;){let e=t[r],i=qr(e,`open`).charCodeAt(0),a=Kr(e),o=n[i];Array.isArray(o)?o.push(a):n[i]=[a]}return{flow:n}}function Kr(e){let t=e.anywhere,n=e.type,r=n+`Fence`,i=r+`Sequence`,a=n+`Value`,o={tokenize:u,partial:!0},s,c=0;return{tokenize:l,concrete:!0};function l(l,u,d){let f=this;return p;function p(a){let o=f.now();return o.column===1&&(o.line===1||t)&&(s=qr(e,`open`),c=0,a===s.charCodeAt(c))?(l.enter(n),l.enter(r),l.enter(i),m(a)):d(a)}function m(e){return c===s.length?(l.exit(i),H(e)?(l.enter(`whitespace`),h(e)):g(e)):e===s.charCodeAt(c++)?(l.consume(e),m):d(e)}function h(e){return H(e)?(l.consume(e),h):(l.exit(`whitespace`),g(e))}function g(t){return B(t)?(l.exit(r),l.enter(`lineEnding`),l.consume(t),l.exit(`lineEnding`),s=qr(e,`close`),c=0,l.attempt(o,b,_)):d(t)}function _(e){return e===null||B(e)?y(e):(l.enter(a),v(e))}function v(e){return e===null||B(e)?(l.exit(a),y(e)):(l.consume(e),v)}function y(e){return e===null?d(e):(l.enter(`lineEnding`),l.consume(e),l.exit(`lineEnding`),l.attempt(o,b,_))}function b(e){return l.exit(n),u(e)}}function u(e,t,n){let a=0;return o;function o(t){return t===s.charCodeAt(a)?(e.enter(r),e.enter(i),c(t)):n(t)}function c(t){return a===s.length?(e.exit(i),H(t)?(e.enter(`whitespace`),l(t)):u(t)):t===s.charCodeAt(a++)?(e.consume(t),c):n(t)}function l(t){return H(t)?(e.consume(t),l):(e.exit(`whitespace`),u(t))}function u(i){return i===null||B(i)?(e.exit(r),t(i)):n(i)}}}function qr(e,t){return e.marker?Jr(e.marker,t).repeat(3):Jr(e.fence,t)}function Jr(e,t){return typeof e==`string`?e:e[t]}function Yr(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function Xr(e){let t=Ur(e),n={},r={},i=-1;for(;++i<t.length;){let e=t[i];n[e.type]=Zr(e),r[e.type]=Qr,r[e.type+`Value`]=$r}return{enter:n,exit:r}}function Zr(e){return t;function t(t){this.enter({type:e.type,value:``},t),this.buffer()}}function Qr(e){let t=this.resume(),n=this.stack[this.stack.length-1];`value`in n,this.exit(e),n.value=t.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,``)}function $r(e){this.config.enter.data.call(this,e),this.config.exit.data.call(this,e)}function ei(e){let t=[],n={},r=Ur(e),i=-1;for(;++i<r.length;){let e=r[i];n[e.type]=ti(e);let a=ni(e,`open`);t.push({atBreak:!0,character:a.charAt(0),after:Yr(a.charAt(1))})}return{unsafe:t,handlers:n}}function ti(e){let t=ni(e,`open`),n=ni(e,`close`);return r;function r(e){return t+(e.value?`
|
|
1042
|
+
`.trim();var Fn=class{name=`help`;async execute(e){return console.log(Pn),{success:!0,filesAffected:0,dirsAffected:0,message:`Help displayed`}}};function In(e,t){let n=f.join(e,`.git`),r=d.existsSync(n);return r?t?.info(`version control detected`,{path:n}):t?.warn(`no version control detected, please use git to manage your shadow source project`,{path:e}),{hasGit:r,gitPath:n}}function Ln(e,t,n,r,i){if(n==null)return r;let a=f.relative(t,e),o=f.join(n,a);return d.existsSync(o)&&d.statSync(o).isFile()?(i?.debug(`copying from source`,{path:o}),d.readFileSync(o,`utf8`)):r}function Rn(e,t={}){let{sourceDir:n,logger:r}=t,i=[],a=[],o=[],s=[],c=new Set;d.existsSync(e)?(o.push(e),r?.debug(`directory exists`,{path:e})):(d.mkdirSync(e,{recursive:!0}),i.push(e),c.add(e),r?.info(`created directory`,{path:e}));for(let t of Object.values(Ut)){let o=t.path,l=f.join(e,o),u=f.dirname(l);if(!d.existsSync(u)){d.mkdirSync(u,{recursive:!0});let t=u;for(;t!==e&&!c.has(t);)c.add(t),i.push(t),r?.info(`created directory`,{path:t}),t=f.dirname(t)}if(d.existsSync(l))s.push(l),r?.debug(`file exists`,{path:l});else{let i=Ln(l,e,n,t.content,r);d.writeFileSync(l,i,`utf8`),a.push(l),r?.info(`created file`,{path:l})}}return{success:!0,rootPath:e,createdDirs:i,createdFiles:a,existedDirs:o,existedFiles:s}}function zn(e){let t=e;return t.startsWith(`~`)&&(t=f.join(p.homedir(),t.slice(1))),f.normalize(t)}var Bn=class{name=`init`;async execute(e){let{logger:t,userConfigOptions:n}=e;t.info(`initializing shadow source project structure`,{command:`init`});let r=zn(n.workspaceDir),i=Rn(f.join(r,n.shadowSourceProject.name),{logger:t}),a=i.createdDirs.length===0&&i.createdFiles.length===0?`All ${i.existedDirs.length} directories and ${i.existedFiles.length} files already exist`:`Created ${i.createdDirs.length} directories and ${i.createdFiles.length} files (${i.existedDirs.length} dirs, ${i.existedFiles.length} files already existed)`;return t.info(`initialization complete`,{dirsCreated:i.createdDirs.length,filesCreated:i.createdFiles.length,dirsExisted:i.existedDirs.length,filesExisted:i.existedFiles.length}),{success:i.success,filesAffected:i.createdFiles.length,dirsAffected:i.createdDirs.length,message:a}}},Vn=class{name;inner;constructor(e){this.inner=e,this.name=`json:${e.name}`}async execute(e){let t=await this.inner.execute(e),n=Hn(t);return u.default.stdout.write(`${JSON.stringify(n)}\n`),t}};function Hn(e){return{success:e.success,filesAffected:e.filesAffected,dirsAffected:e.dirsAffected,...e.message!=null&&{message:e.message},pluginResults:[],errors:[]}}function Un(){return`@truenine/memory-sync-cli`}function Wn(){return`https://registry.npmjs.org/${Un()}/latest`}function Gn(e){let t=e.replace(/^v/,``),n=/^(\d+)\.(\d+)\.(\d+)/.exec(t);return n==null?null:[Number.parseInt(n[1],10),Number.parseInt(n[2],10),Number.parseInt(n[3],10)]}function Kn(e,t){let n=Gn(e),r=Gn(t);if(n==null||r==null)return 0;for(let e=0;e<3;e++){if(n[e]<r[e])return-1;if(n[e]>r[e])return 1}return 0}const qn=3e3;async function Jn(){let e=new AbortController,t=setTimeout(()=>e.abort(),qn);typeof t==`object`&&`unref`in t&&t.unref();try{let n=await fetch(Wn(),{headers:{Accept:`application/json`},signal:e.signal});if(clearTimeout(t),!n.ok)return{error:`HTTP ${n.status}: ${n.statusText}`};let r=await n.json();return r.version==null?{error:`Invalid response: missing version field`}:{version:r.version}}catch(e){return clearTimeout(t),e instanceof Error?e.name===`TimeoutError`||e.name===`AbortError`?{error:`Request timeout after ${qn}ms`}:{error:e.message}:{error:`Unknown network error`}}}function Yn(){return`2026.10219.10049`}async function Xn(){let e=Yn();if(e===`dev`)return{status:`development`,localVersion:e,remoteVersion:null};let t=await Jn();if(`error`in t)return{status:`current`,localVersion:e,remoteVersion:null,error:t.error};let n=t.version,r=Kn(e,n);return r<0?{status:`outdated`,localVersion:e,remoteVersion:n}:r>0?{status:`development`,localVersion:e,remoteVersion:n}:{status:`current`,localVersion:e,remoteVersion:n}}function Zn(e,t){let{status:n,localVersion:r,remoteVersion:i}=e;switch(n){case`outdated`:t.warn(`Version outdated: ${r} → ${i}. Run 'npm i -g ${Un()}@latest' to update.`);break;case`current`:e.error==null?t.info(`Version ${r} is up to date.`):t.error(`Version check failed: ${e.error}`);break;case`development`:i==null?t.debug(`Running in development mode, version check skipped.`):t.info(`Development version detected: ${r} > ${i}. Thanks for contributing!`);break}}function Qn(){return new Date().getMinutes()%2==0}function $n(e){Qn()&&Xn().then(t=>{(t.status===`outdated`||t.error!=null)&&Zn(t,e)}).catch(t=>{let n=t instanceof Error?t.message:`Unknown error`;e.error(`Version check failed: ${n}`)})}var er=class{name=`outdated`;async execute(e){let t=await Xn();return Zn(t,e.logger),{success:!0,filesAffected:0,dirsAffected:0,message:`Version status: ${t.status}`}}},tr=class{name=`plugins`;async execute(e){let{logger:t,outputPlugins:n,userConfigOptions:r}=e,i=r.plugins,a=[];for(let e of i)a.push({name:e.name,kind:e.type===bt.Input?`Input`:`Output`,description:e.name,dependencies:[...e.dependsOn??[]]});let o=new Set(a.map(e=>e.name));for(let e of n)o.has(e.name)||a.push({name:e.name,kind:`Output`,description:e.name,dependencies:[...e.dependsOn??[]]});return u.default.stdout.write(`${JSON.stringify(a)}\n`),t.info(`plugins listed`,{count:a.length}),{success:!0,filesAffected:0,dirsAffected:0,message:`Listed ${a.length} plugin(s)`}}},nr=class{name=`unknown`;constructor(e){this.unknownCmd=e}async execute(e){return console.error(`Unknown command: ${this.unknownCmd}`),console.error(`Run "tnmsc help" for available commands.`),{success:!1,filesAffected:0,dirsAffected:0}}};const rr={default:{websearch:`web_search`,webfetch:`web_fetch`,readFile:`read_file`,writeFile:`write_file`,executeCommand:`execute_command`,todolistWrite:`todolist_write`,grep:`grep`,listDirectory:`list_directory`},claudeCode:{readFile:`Read`,writeFile:`Write`,executeCommand:`Execute`,todolistWrite:`TodoWrite`,listDirectory:`List`},kiro:{websearch:`remote_web_search`,webfetch:`webFetch`,readFile:`readFile`,writeFile:`fsWrite`,executeCommand:`executeBash`,todolistWrite:`todolistWrite`,grep:`grepSearch`,listDirectory:`listDir`}};let ir=function(e){return e.Bash=`bash`,e.Zsh=`zsh`,e.Fish=`fish`,e.Sh=`sh`,e.PowerShell=`powershell`,e.Pwsh=`pwsh`,e.Cmd=`cmd`,e.Unknown=`unknown`,e}({}),ar=function(e){return e.Win=`win`,e.Mac=`mac`,e.Linux=`linux`,e.Unknown=`unknown`,e}({});var or=class{userConfig;toolPreset;constructor(e={}){this.userConfig=e.userConfig,this.toolPreset=e.toolPreset??`default`}collect(){return{os:this.collectOsInfo(),env:this.collectEnvContext(),profile:this.collectProfile(),tool:this.collectToolReferences(),Md:this.createMdComponent()}}collectOsInfo(){let e=p.platform();return{platform:e,arch:p.arch(),hostname:p.hostname(),homedir:p.homedir(),tmpdir:p.tmpdir(),type:p.type(),release:p.release(),shellKind:this.detectShellKind(),kind:this.detectOsKind(e)}}detectOsKind(e){switch(e){case`win32`:return ar.Win;case`darwin`:return ar.Mac;case`linux`:case`freebsd`:case`openbsd`:case`sunos`:case`aix`:return ar.Linux;default:return ar.Unknown}}detectShellKind(){let e=(u.default.env.SHELL??u.default.env.ComSpec??``).toLowerCase();return e.includes(`bash`)?ir.Bash:e.includes(`zsh`)?ir.Zsh:e.includes(`fish`)?ir.Fish:e.includes(`pwsh`)?ir.Pwsh:e.includes(`powershell`)?ir.PowerShell:e.includes(`cmd`)?ir.Cmd:e.endsWith(`/sh`)?ir.Sh:ir.Unknown}collectEnvContext(){return{...u.default.env}}collectProfile(){return this.userConfig?.profile==null?{}:this.userConfig.profile}collectToolReferences(){let e={...rr.default};return this.toolPreset===`claudeCode`?{...e,...rr.claudeCode}:this.toolPreset===`kiro`?{...e,...rr.kiro}:e}createMdComponent(){let e=(e=>e.when===!1?null:e.children);return e.Line=e=>e.when===!1?null:e.children,e}};let sr=function(e){return e[e.SystemDefault=0]=`SystemDefault`,e[e.UserConfig=10]=`UserConfig`,e[e.PluginRegistered=20]=`PluginRegistered`,e[e.CompileTime=30]=`CompileTime`,e}({});var cr=class{registrations=[];globalScope=null;setGlobalScope(e){this.globalScope=e}getGlobalScope(){return this.globalScope}register(e,t,n=sr.PluginRegistered){this.registrations.push({namespace:e,values:t,priority:n})}getRegistrations(){return this.registrations}merge(e){let t={};this.globalScope!=null&&(t.os={...this.globalScope.os},t.env={...this.globalScope.env},t.profile={...this.globalScope.profile},t.tool={...this.globalScope.tool});let n=[...this.registrations].sort((e,t)=>e.priority-t.priority);for(let e of n)t[e.namespace]=this.deepMerge(t[e.namespace],e.values);if(e!=null)for(let[n,r]of Object.entries(e))t[n]=typeof r==`object`&&r&&!Array.isArray(r)?this.deepMerge(t[n],r):r;return t}deepMerge(e,t){if(e==null)return{...t};let n={...e};for(let[e,r]of Object.entries(t))n[e]=typeof r==`object`&&r&&!Array.isArray(r)&&typeof n[e]==`object`&&n[e]!==null&&!Array.isArray(n[e])?this.deepMerge(n[e],r):r;return n}clear(){this.registrations.length=0,this.globalScope=null}};function lr(e){let t=[...e],n=t[0];n!=null&&ur(n)&&t.shift();let r=t[0];return r!=null&&dr(r)&&t.shift(),t}function ur(e){let t=[`node`,`nodejs`,`bun`,`deno`,`tsx`,`ts-node`,`npx`,`pnpx`,`yarn`,`pnpm`],n=e.toLowerCase().replaceAll(`\\`,`/`);return t.some(e=>RegExp(`(?:^|/)${e}(?:\\.exe|\\.cmd|\\.ps1)?$`,`i`).test(n)||n===e)}function dr(e){return/\.(?:m?[jt]s|cjs)$/.test(e)||/[/\\]/.test(e)&&!e.startsWith(`-`)?!0:/^(?:@[\w-]+\/)?[\w-]+$/.test(e)&&!e.startsWith(`-`)}const fr=new Set([`help`,`version`,`outdated`,`init`,`dry-run`,`clean`,`config`,`plugins`]),pr=new Map([[`--trace`,`trace`],[`--debug`,`debug`],[`--info`,`info`],[`--warn`,`warn`],[`--error`,`error`]]),mr=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4]]);function hr(e){let{logLevelFlags:t}=e;if(t.length===0)return;let n=t[0],r=mr.get(n)??4;for(let e of t){let t=mr.get(e)??4;t<r&&(r=t,n=e)}return n}function gr(e){let{helpFlag:t,versionFlag:n,subcommand:r,dryRun:i,unknownCommand:a,setOption:o,positional:s,showFlag:c}=e;if(n)return new Mn;if(t)return new Fn;if(a!=null)return new nr(a);if(r===`version`)return new Mn;if(r===`help`)return new Fn;if(r===`outdated`)return new er;if(r===`init`)return new Bn;if(r===`dry-run`)return new kn;if(r===`clean`)return i?new On:new yt;if(r===`plugins`)return new tr;if(r===`config`&&c)return new Dn;if(r!==`config`||o.length>0)return new An;let l=[];for(let e of s){let t=e.indexOf(`=`);t>0&&l.push([e.slice(0,t),e.slice(t+1)])}return new En([...o,...l])}function _r(e){let t={subcommand:void 0,helpFlag:!1,versionFlag:!1,dryRun:!1,jsonFlag:!1,showFlag:!1,logLevel:void 0,logLevelFlags:[],setOption:[],unknownCommand:void 0,positional:[],unknown:[]},n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i!=null){if(i===`--`){t.positional.push(...e.slice(r+1).filter(e=>e!=null));break}if(i.startsWith(`--`)){let n=i.split(`=`),a=n[0]??``,o=pr.get(a);if(o!=null){t.logLevelFlags.push(o),t.logLevel=o;continue}switch(a){case`--help`:t.helpFlag=!0;break;case`--version`:t.versionFlag=!0;break;case`--dry-run`:t.dryRun=!0;break;case`--json`:t.jsonFlag=!0;break;case`--show`:t.showFlag=!0;break;case`--set`:if(n.length>1){let e=n.slice(1).join(`=`),r=e.indexOf(`=`);r>0&&t.setOption.push([e.slice(0,r),e.slice(r+1)])}else{let n=e[r+1];if(n!=null){let e=n.indexOf(`=`);e>0&&(t.setOption.push([n.slice(0,e),n.slice(e+1)]),r++)}}break;default:t.unknown.push(i)}continue}if(i.startsWith(`-`)&&i.length>1){let e=i.slice(1);for(let n of e)switch(n){case`h`:t.helpFlag=!0;break;case`v`:t.versionFlag=!0;break;case`n`:t.dryRun=!0;break;case`j`:t.jsonFlag=!0;break;default:t.unknown.push(`-${n}`)}continue}if(!n){n=!0,fr.has(i)?t.subcommand=i:t.unknownCommand=i;continue}t.positional.push(i)}}return t}var vr=class{logger;args;outputPlugins=[];constructor(...e){this.args=_r(lr(e.filter(e=>e!=null)));let t=hr(this.args);t!=null&&en(t),this.logger=nn(`PluginPipeline`,t),this.logger.debug(`initialized`,{args:this.args})}registerOutputPlugins(e){return this.outputPlugins.push(...e),this}async run(e){$n(this.logger);let{context:t,outputPlugins:n,userConfigOptions:r}=e;this.registerOutputPlugins([...n]);let i=this.resolveCommand();this.args.jsonFlag&&(en(`silent`),new Set([`config-show`,`plugins`]).has(i.name)||(i=new Vn(i)));let a=this.createCommandContext(t,r);await i.execute(a)}resolveCommand(){return gr(this.args)}createCommandContext(e,t){return{logger:this.logger,outputPlugins:this.outputPlugins,collectedInputContext:e,userConfigOptions:t,createCleanContext:t=>this.createCleanContext(e,t),createWriteContext:t=>this.createWriteContext(e,t)}}createCleanContext(e,t){return{logger:this.logger,fs:d,path:f,glob:Je.default,collectedInputContext:e,dryRun:t}}createWriteContext(e,t){return{logger:this.logger,fs:d,path:f,glob:Je.default,collectedInputContext:e,dryRun:t,registeredPluginNames:this.outputPlugins.map(e=>e.name)}}buildDependencyGraph(e){let t=new Map;for(let n of e){let e=n.dependsOn??[];t.set(n.name,[...e])}return t}validateDependencies(e){let t=new Set(e.map(e=>e.name));for(let n of e){let e=n.dependsOn??[];for(let r of e)if(!t.has(r))throw new Dt(n.name,r)}}topologicalSort(e){this.validateDependencies(e);let t=new Map;for(let n of e)t.set(n.name,n);let n=new Map;for(let t of e)n.set(t.name,0);let r=new Map;for(let t of e)r.set(t.name,[]);for(let t of e){let e=t.dependsOn??[];for(let i of e){n.set(t.name,(n.get(t.name)??0)+1);let e=r.get(i)??[];e.push(t.name),r.set(i,e)}}let i=[];for(let t of e)n.get(t.name)===0&&i.push(t.name);let a=[];for(;i.length>0;){let o=i.shift(),s=t.get(o);a.push(s);let c=(r.get(o)??[]).sort((t,n)=>e.findIndex(e=>e.name===t)-e.findIndex(e=>e.name===n));for(let e of c){let t=(n.get(e)??0)-1;n.set(e,t),t===0&&i.push(e)}}if(a.length===e.length)return a;throw new Et(this.findCyclePath(e,n))}findCyclePath(e,t){let n=new Set;for(let[e,r]of t)r>0&&n.add(e);let r=new Map;for(let t of e)if(n.has(t.name)){let e=(t.dependsOn??[]).filter(e=>n.has(e));r.set(t.name,e)}let i=new Set,a=[],o=e=>{if(a.includes(e))return a.push(e),!0;if(i.has(e))return!1;i.add(e),a.push(e);for(let t of r.get(e)??[])if(o(t))return!0;return a.pop(),!1};for(let e of n){if(o(e)){let e=a.indexOf(a.at(-1));return a.slice(e)}i.clear(),a.length=0}return[...n]}async executePluginsInOrder(e,t,n=!1,r){if(e.length===0)return{};let i=this.topologicalSort(e),a=new or({userConfig:r}).collect(),o=new cr;o.setGlobalScope(a),this.logger.debug(`global scope collected`,{osInfo:{platform:a.os.platform,arch:a.os.arch,shellKind:a.os.shellKind},hasProfile:Object.keys(a.profile).length>0,hasTool:Object.keys(a.tool).length>0});let s=new Map,c={};for(let e of i){let r=this.buildDependencyContext(e,s),i={...t,dependencyContext:r,globalScope:a,scopeRegistry:o},l=e;l.executeEffects!=null&&await l.executeEffects(i,n);let u=await e.collect(i);s.set(e.name,u),c=this.mergeContexts(c,u);let d=e;if(d.getRegisteredScopes!=null){let t=d.getRegisteredScopes();for(let{namespace:n,values:r}of t)o.register(n,r,sr.PluginRegistered),this.logger.debug(`plugin scope registered`,{plugin:e.name,namespace:n,keys:Object.keys(r)})}}return c}buildDependencyContext(e,t){if((e.dependsOn??[]).length===0)return{};let n=this.collectTransitiveDependencies(e,t),r={};for(let e of n){let n=t.get(e);n!=null&&(r=this.mergeContexts(r,n))}return r}collectTransitiveDependencies(e,t){let n=new Set,r=[];return(e=>{for(let i of e)n.has(i)||(n.add(i),t.get(i)!=null&&r.push(i))})(e.dependsOn??[]),r}mergeContexts(e,t){let{workspace:n}=e;if(t.workspace!=null)if(n!=null){let e=new Map;for(let t of n.projects)e.set(t.name,t);for(let n of t.workspace.projects)e.set(n.name,n);n={directory:t.workspace.directory??n.directory,projects:[...e.values()]}}else ({workspace:n}=t);let r=t.ideConfigFiles==null?e.ideConfigFiles:[...e.ideConfigFiles??[],...t.ideConfigFiles],i=t.fastCommands==null?e.fastCommands:[...e.fastCommands??[],...t.fastCommands],a=t.subAgents==null?e.subAgents:[...e.subAgents??[],...t.subAgents],o=t.skills==null?e.skills:[...e.skills??[],...t.skills],s=t.rules==null?e.rules:[...e.rules??[],...t.rules],c=t.aiAgentIgnoreConfigFiles==null?e.aiAgentIgnoreConfigFiles:[...e.aiAgentIgnoreConfigFiles??[],...t.aiAgentIgnoreConfigFiles],l=t.globalMemory??e.globalMemory,u=t.shadowSourceProjectDir??e.shadowSourceProjectDir,d=t.readmePrompts==null?e.readmePrompts:[...e.readmePrompts??[],...t.readmePrompts],f=t.globalGitIgnore??e.globalGitIgnore,p=t.shadowGitExclude??e.shadowGitExclude;return{...n==null?{}:{workspace:n},...r==null?{}:{ideConfigFiles:r},...i==null?{}:{fastCommands:i},...a==null?{}:{subAgents:a},...o==null?{}:{skills:o},...s==null?{}:{rules:s},...c==null?{}:{aiAgentIgnoreConfigFiles:c},...l==null?{}:{globalMemory:l},...u==null?{}:{shadowSourceProjectDir:u},...d==null?{}:{readmePrompts:d},...f==null?{}:{globalGitIgnore:f},...p==null?{}:{shadowGitExclude:p}}}};const yr={name:`tnmsc-shadow`,skill:{src:`src/skills`,dist:`dist/skills`},fastCommand:{src:`src/commands`,dist:`dist/commands`},subAgent:{src:`src/agents`,dist:`dist/agents`},rule:{src:`src/rules`,dist:`dist/rules`},globalMemory:{src:`app/global.cn.mdx`,dist:`dist/global.mdx`},workspaceMemory:{src:`app/workspace.cn.mdx`,dist:`dist/app/workspace.mdx`},project:{src:`app`,dist:`dist/app`}},br={...Wt,shadowSourceProject:yr,fastCommandSeriesOptions:{},plugins:[]};function xr(e){return{...e.version==null?{}:{version:e.version},...e.workspaceDir==null?{}:{workspaceDir:e.workspaceDir},...e.shadowSourceProject==null?{}:{shadowSourceProject:e.shadowSourceProject},...e.fastCommandSeriesOptions==null?{}:{fastCommandSeriesOptions:e.fastCommandSeriesOptions},...e.logLevel==null?{}:{logLevel:e.logLevel}}}function Sr(...e){return e.reduce((e,t)=>Cr(e,t),{...br})}function Cr(e,t){let n=t.plugins,r=t.fastCommandSeriesOptions;return{...e,...t,shadowSourceProject:wr(e.shadowSourceProject,t.shadowSourceProject),plugins:[...e.plugins,...n??[]],fastCommandSeriesOptions:Tr(e.fastCommandSeriesOptions,r)}}function wr(e,t){return t==null?e:{name:t.name??e.name,skill:{...e.skill,...t.skill},fastCommand:{...e.fastCommand,...t.fastCommand},subAgent:{...e.subAgent,...t.subAgent},rule:{...e.rule,...t.rule},globalMemory:{...e.globalMemory,...t.globalMemory},workspaceMemory:{...e.workspaceMemory,...t.workspaceMemory},project:{...e.project,...t.project}}}function Tr(e,t){if(t==null)return e??{};if(e==null)return t;let n={};if(e.pluginOverrides!=null)for(let[t,r]of Object.entries(e.pluginOverrides))n[t]={...r};if(t.pluginOverrides!=null)for(let[e,r]of Object.entries(t.pluginOverrides))n[e]={...n[e],...r};let r=t.includeSeriesPrefix??e.includeSeriesPrefix,i=Object.keys(n).length>0;return r!=null&&i?{includeSeriesPrefix:r,pluginOverrides:n}:r==null?i?{pluginOverrides:n}:{}:{includeSeriesPrefix:r}}function Er(e){return`pluginOptions`in e||`configLoaderOptions`in e||`loadUserConfig`in e}async function Dr(e={}){hn().shouldExit&&u.default.exit(1);let t,n,r;Er(e)?({pluginOptions:r={},cwd:n}={pluginOptions:e.pluginOptions,cwd:e.cwd},t=e.loadUserConfig??!0):(r=e,t=!0);let i={},a=!1,o=[],s;if(t){let e=mn(n);a=e.found,o=e.sources,e.found&&(i=xr(e.config),s=e.config)}let c=Sr(i,r),{plugins:l=[],logLevel:p}=c,m=nn(`defineConfig`,p);a?m.info(`user config loaded`,{sources:o}):m.info(`no user config found, using defaults`,{workspaceDir:br.workspaceDir,shadowSourceProjectName:br.shadowSourceProject.name,logLevel:br.logLevel});let h={logger:m,userConfigOptions:c,fs:d,path:f,glob:Je.default},g=l.filter(e=>e.type===bt.Input),_=l.filter(e=>e.type===bt.Output),v=await new vr().executePluginsInOrder(g,h,!1,s);if(v.workspace==null)throw Error(`Workspace not initialized by any plugin`);let y={workspace:v.workspace,ideConfigFiles:v.ideConfigFiles??[],...v.fastCommands!=null&&{fastCommands:v.fastCommands},...v.subAgents!=null&&{subAgents:v.subAgents},...v.skills!=null&&{skills:v.skills},...v.rules!=null&&{rules:v.rules},...v.globalMemory!=null&&{globalMemory:v.globalMemory},...v.aiAgentIgnoreConfigFiles!=null&&{aiAgentIgnoreConfigFiles:v.aiAgentIgnoreConfigFiles},...v.shadowSourceProjectDir!=null&&{shadowSourceProjectDir:v.shadowSourceProjectDir},...v.readmePrompts!=null&&{readmePrompts:v.readmePrompts},...v.globalGitIgnore!=null&&{globalGitIgnore:v.globalGitIgnore},...v.shadowGitExclude!=null&&{shadowGitExclude:v.shadowGitExclude}};return v.shadowSourceProjectDir!=null&&In(v.shadowSourceProjectDir,m),{context:y,outputPlugins:_,userConfigOptions:c}}const Or=Lr(/[A-Za-z]/),kr=Lr(/[\dA-Za-z]/),Ar=Lr(/[#-'*+\--9=?A-Z^-~]/);function jr(e){return e!==null&&(e<32||e===127)}const Mr=Lr(/\d/),Nr=Lr(/[\dA-Fa-f]/),Pr=Lr(/[!-/:-@[-`{-~]/);function B(e){return e!==null&&e<-2}function V(e){return e!==null&&(e<0||e===32)}function H(e){return e===-2||e===-1||e===32}const Fr=Lr(/\p{P}|\p{S}/u),Ir=Lr(/\s/);function Lr(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}var Rr=l(o(((e,t)=>{(function(){var e=t===void 0?function(){return this||(0,eval)(`this`)}():t.exports=i;e.format=i,e.vsprintf=r,typeof console<`u`&&typeof console.log==`function`&&(e.printf=n);function n(){console.log(i.apply(null,arguments))}function r(e,t){return i.apply(null,[e].concat(t))}function i(e){for(var t=1,n=[].slice.call(arguments),r=0,i=e.length,a=``,o,s=!1,c,l,u=!1,d,f=function(){return n[t++]},p=function(){for(var t=``;/\d/.test(e[r]);)t+=e[r++],o=e[r];return t.length>0?parseInt(t):null};r<i;++r)if(o=e[r],s)switch(s=!1,o==`.`?(u=!1,o=e[++r]):o==`0`&&e[r+1]==`.`?(u=!0,r+=2,o=e[r]):u=!0,d=p(),o){case`b`:a+=parseInt(f(),10).toString(2);break;case`c`:c=f(),typeof c==`string`||c instanceof String?a+=c:a+=String.fromCharCode(parseInt(c,10));break;case`d`:a+=parseInt(f(),10);break;case`f`:l=String(parseFloat(f()).toFixed(d||6)),a+=u?l:l.replace(/^0/,``);break;case`j`:a+=JSON.stringify(f());break;case`o`:a+=`0`+parseInt(f(),10).toString(8);break;case`s`:a+=f();break;case`x`:a+=`0x`+parseInt(f(),10).toString(16);break;case`X`:a+=`0x`+parseInt(f(),10).toString(16).toUpperCase();break;default:a+=o;break}else o===`%`?s=!0:a+=o;return a}})()}))(),1);const zr=Object.assign(Br(Error),{eval:Br(EvalError),range:Br(RangeError),reference:Br(ReferenceError),syntax:Br(SyntaxError),type:Br(TypeError),uri:Br(URIError)});function Br(e){return t.displayName=e.displayName||e.name,t;function t(t,...n){return new e(t&&(0,Rr.default)(t,...n))}}const Vr={}.hasOwnProperty,Hr={yaml:`-`,toml:`+`};function Ur(e){let t=[],n=-1,r=Array.isArray(e)?e:e?[e]:[`yaml`];for(;++n<r.length;)t[n]=Wr(r[n]);return t}function Wr(e){let t=e;if(typeof t==`string`){if(!Vr.call(Hr,t))throw zr("Missing matter definition for `%s`",t);t={type:t,marker:Hr[t]}}else if(typeof t!=`object`)throw zr("Expected matter to be an object, not `%j`",t);if(!Vr.call(t,`type`))throw zr("Missing `type` in matter `%j`",t);if(!Vr.call(t,`fence`)&&!Vr.call(t,`marker`))throw zr("Missing `marker` or `fence` in matter `%j`",t);return t}function Gr(e){let t=Ur(e),n={},r=-1;for(;++r<t.length;){let e=t[r],i=qr(e,`open`).charCodeAt(0),a=Kr(e),o=n[i];Array.isArray(o)?o.push(a):n[i]=[a]}return{flow:n}}function Kr(e){let t=e.anywhere,n=e.type,r=n+`Fence`,i=r+`Sequence`,a=n+`Value`,o={tokenize:u,partial:!0},s,c=0;return{tokenize:l,concrete:!0};function l(l,u,d){let f=this;return p;function p(a){let o=f.now();return o.column===1&&(o.line===1||t)&&(s=qr(e,`open`),c=0,a===s.charCodeAt(c))?(l.enter(n),l.enter(r),l.enter(i),m(a)):d(a)}function m(e){return c===s.length?(l.exit(i),H(e)?(l.enter(`whitespace`),h(e)):g(e)):e===s.charCodeAt(c++)?(l.consume(e),m):d(e)}function h(e){return H(e)?(l.consume(e),h):(l.exit(`whitespace`),g(e))}function g(t){return B(t)?(l.exit(r),l.enter(`lineEnding`),l.consume(t),l.exit(`lineEnding`),s=qr(e,`close`),c=0,l.attempt(o,b,_)):d(t)}function _(e){return e===null||B(e)?y(e):(l.enter(a),v(e))}function v(e){return e===null||B(e)?(l.exit(a),y(e)):(l.consume(e),v)}function y(e){return e===null?d(e):(l.enter(`lineEnding`),l.consume(e),l.exit(`lineEnding`),l.attempt(o,b,_))}function b(e){return l.exit(n),u(e)}}function u(e,t,n){let a=0;return o;function o(t){return t===s.charCodeAt(a)?(e.enter(r),e.enter(i),c(t)):n(t)}function c(t){return a===s.length?(e.exit(i),H(t)?(e.enter(`whitespace`),l(t)):u(t)):t===s.charCodeAt(a++)?(e.consume(t),c):n(t)}function l(t){return H(t)?(e.consume(t),l):(e.exit(`whitespace`),u(t))}function u(i){return i===null||B(i)?(e.exit(r),t(i)):n(i)}}}function qr(e,t){return e.marker?Jr(e.marker,t).repeat(3):Jr(e.fence,t)}function Jr(e,t){return typeof e==`string`?e:e[t]}function Yr(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function Xr(e){let t=Ur(e),n={},r={},i=-1;for(;++i<t.length;){let e=t[i];n[e.type]=Zr(e),r[e.type]=Qr,r[e.type+`Value`]=$r}return{enter:n,exit:r}}function Zr(e){return t;function t(t){this.enter({type:e.type,value:``},t),this.buffer()}}function Qr(e){let t=this.resume(),n=this.stack[this.stack.length-1];`value`in n,this.exit(e),n.value=t.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,``)}function $r(e){this.config.enter.data.call(this,e),this.config.exit.data.call(this,e)}function ei(e){let t=[],n={},r=Ur(e),i=-1;for(;++i<r.length;){let e=r[i];n[e.type]=ti(e);let a=ni(e,`open`);t.push({atBreak:!0,character:a.charAt(0),after:Yr(a.charAt(1))})}return{unsafe:t,handlers:n}}function ti(e){let t=ni(e,`open`),n=ni(e,`close`);return r;function r(e){return t+(e.value?`
|
|
1043
1043
|
`+e.value:``)+`
|
|
1044
1044
|
`+n}}function ni(e,t){return e.marker?ri(e.marker,t).repeat(3):ri(e.fence,t)}function ri(e,t){return typeof e==`string`?e:e[t]}function ii(e){let t=this,n=e||`yaml`,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(Gr(n)),a.push(Xr(n)),o.push(ei(n))}function ai(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}const oi=(function(e){if(e==null)return di;if(typeof e==`function`)return ui(e);if(typeof e==`object`)return Array.isArray(e)?si(e):ci(e);if(typeof e==`string`)return li(e);throw Error(`Expected function, string, or object as test`)});function si(e){let t=[],n=-1;for(;++n<e.length;)t[n]=oi(e[n]);return ui(r);function r(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}function ci(e){let t=e;return ui(n);function n(n){let r=n,i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function li(e){return ui(t);function t(t){return t&&t.type===e}}function ui(e){return t;function t(t,n,r){return!!(fi(t)&&e.call(this,t,typeof n==`number`?n:void 0,r||void 0))}}function di(){return!0}function fi(e){return typeof e==`object`&&!!e&&`type`in e}function pi(e){return`\x1B[33m`+e+`\x1B[39m`}const mi=[];function hi(e,t,n,r){let i;typeof t==`function`&&typeof n!=`function`?(r=n,n=t):i=t;let a=oi(i),o=r?-1:1;s(e,void 0,[])();function s(e,i,c){let l=e&&typeof e==`object`?e:{};if(typeof l.type==`string`){let t=typeof l.tagName==`string`?l.tagName:typeof l.name==`string`?l.name:void 0;Object.defineProperty(u,`name`,{value:`node (`+pi(e.type+(t?`<`+t+`>`:``))+`)`})}return u;function u(){let l=mi,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=gi(n(e,c)),l[0]===!1))return l;if(`children`in e&&e.children){let t=e;if(t.children&&l[0]!==`skip`)for(d=(r?t.children.length:-1)+o,f=c.concat(t);d>-1&&d<t.children.length;){let e=t.children[d];if(u=s(e,d,f)(),u[0]===!1)return u;d=typeof u[1]==`number`?u[1]:d+o}}return l}}}function gi(e){return Array.isArray(e)?e:typeof e==`number`?[!0,e]:e==null?mi:[e]}function _i(e,t,n){let r=oi((n||{}).ignore||[]),i=vi(t),a=-1;for(;++a<i.length;)hi(e,`text`,o);function o(e,t){let n=-1,i;for(;++n<t.length;){let e=t[n],a=i?i.children:void 0;if(r(e,a?a.indexOf(e):void 0,i))return;i=e}if(i)return s(e,t)}function s(e,t){let n=t[t.length-1],r=i[a][0],o=i[a][1],s=0,c=n.children.indexOf(e),l=!1,u=[];r.lastIndex=0;let d=r.exec(e.value);for(;d;){let n=d.index,i={index:d.index,input:d.input,stack:[...t,e]},a=o(...d,i);if(typeof a==`string`&&(a=a.length>0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s<e.value.length&&u.push({type:`text`,value:e.value.slice(s)}),n.children.splice(c,1,...u)):u=[e],c+u.length}}function vi(e){let t=[];if(!Array.isArray(e))throw TypeError(`Expected find and replace tuple or list of tuples`);let n=!e[0]||Array.isArray(e[0])?e:[e],r=-1;for(;++r<n.length;){let e=n[r];t.push([yi(e[0]),bi(e[1])])}return t}function yi(e){return typeof e==`string`?new RegExp(Yr(e),`g`):e}function bi(e){return typeof e==`function`?e:function(){return e}}const xi=`phrasing`,Si=[`autolink`,`link`,`image`,`label`];function Ci(){return{transforms:[ji],enter:{literalAutolink:Ti,literalAutolinkEmail:Ei,literalAutolinkHttp:Ei,literalAutolinkWww:Ei},exit:{literalAutolink:Ai,literalAutolinkEmail:ki,literalAutolinkHttp:Di,literalAutolinkWww:Oi}}}function wi(){return{unsafe:[{character:`@`,before:`[+\\-.\\w]`,after:`[\\-.\\w]`,inConstruct:xi,notInConstruct:Si},{character:`.`,before:`[Ww]`,after:`[\\-.\\w]`,inConstruct:xi,notInConstruct:Si},{character:`:`,before:`[ps]`,after:`\\/`,inConstruct:xi,notInConstruct:Si}]}}function Ti(e){this.enter({type:`link`,title:null,url:``,children:[]},e)}function Ei(e){this.config.enter.autolinkProtocol.call(this,e)}function Di(e){this.config.exit.autolinkProtocol.call(this,e)}function Oi(e){this.config.exit.data.call(this,e);let t=this.stack[this.stack.length-1];t.type,t.url=`http://`+this.sliceSerialize(e)}function ki(e){this.config.exit.autolinkEmail.call(this,e)}function Ai(e){this.exit(e)}function ji(e){_i(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Mi],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,Ni]],{ignore:[`link`,`linkReference`]})}function Mi(e,t,n,r,i){let a=``;if(!Ii(i)||(/^w/i.test(t)&&(n=t+n,t=``,a=`http://`),!Pi(n)))return!1;let o=Fi(n+r);if(!o[0])return!1;let s={type:`link`,title:null,url:a+t+o[0],children:[{type:`text`,value:t+o[0]}]};return o[1]?[s,{type:`text`,value:o[1]}]:s}function Ni(e,t,n,r){return!Ii(r,!0)||/[-\d_]$/.test(n)?!1:{type:`link`,title:null,url:`mailto:`+t+`@`+n,children:[{type:`text`,value:t+`@`+n}]}}function Pi(e){let t=e.split(`.`);return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function Fi(e){let t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(`)`),i=ai(e,`(`),a=ai(e,`)`);for(;r!==-1&&i>a;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(`)`),a++;return[e,n]}function Ii(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||Ir(n)||Fr(n))&&(!t||n!==47)}function Li(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}qi.peek=Ki;function Ri(){this.buffer()}function zi(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function Bi(){this.buffer()}function Vi(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function Hi(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Li(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Ui(e){this.exit(e)}function Wi(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Li(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Gi(e){this.exit(e)}function Ki(){return`[`}function qi(e,t,n,r){let i=n.createTracker(r),a=i.move(`[^`),o=n.enter(`footnoteReference`),s=n.enter(`reference`);return a+=i.move(n.safe(n.associationId(e),{after:`]`,before:a})),s(),o(),a+=i.move(`]`),a}function Ji(){return{enter:{gfmFootnoteCallString:Ri,gfmFootnoteCall:zi,gfmFootnoteDefinitionLabelString:Bi,gfmFootnoteDefinition:Vi},exit:{gfmFootnoteCallString:Hi,gfmFootnoteCall:Ui,gfmFootnoteDefinitionLabelString:Wi,gfmFootnoteDefinition:Gi}}}function Yi(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:qi},unsafe:[{character:`[`,inConstruct:[`label`,`phrasing`,`reference`]}]};function n(e,n,r,i){let a=r.createTracker(i),o=a.move(`[^`),s=r.enter(`footnoteDefinition`),c=r.enter(`label`);return o+=a.move(r.safe(r.associationId(e),{before:o,after:`]`})),c(),o+=a.move(`]:`),e.children&&e.children.length>0&&(a.shift(4),o+=a.move((t?`
|
|
1045
1045
|
`:` `)+r.indentLines(r.containerFlow(e,a.current()),t?Zi:Xi))),s(),o}}function Xi(e,t,n){return t===0?e:Zi(e,t,n)}function Zi(e,t,n){return(n?``:` `)+e}const Qi=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`];ra.peek=ia;function $i(){return{canContainEols:[`delete`],enter:{strikethrough:ta},exit:{strikethrough:na}}}function ea(){return{unsafe:[{character:`~`,inConstruct:`phrasing`,notInConstruct:Qi}],handlers:{delete:ra}}}function ta(e){this.enter({type:`delete`,children:[]},e)}function na(e){this.exit(e)}function ra(e,t,n,r){let i=n.createTracker(r),a=n.enter(`strikethrough`),o=i.move(`~~`);return o+=n.containerPhrasing(e,{...i.current(),before:o,after:`~`}),o+=i.move(`~~`),a(),o}function ia(){return`~`}function aa(e){return e.length}function oa(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||aa,a=[],o=[],s=[],c=[],l=0,u=-1;for(;++u<e.length;){let t=[],r=[],a=-1;for(e[u].length>l&&(l=e[u].length);++a<e[u].length;){let o=sa(e[u][a]);if(n.alignDelimiters!==!1){let e=i(o);r[a]=e,(c[a]===void 0||e>c[a])&&(c[a]=e)}t.push(o)}o[u]=t,s[u]=r}let d=-1;if(typeof r==`object`&&`length`in r)for(;++d<l;)a[d]=ca(r[d]);else{let e=ca(r);for(;++d<l;)a[d]=e}d=-1;let f=[],p=[];for(;++d<l;){let e=a[d],t=``,r=``;e===99?(t=`:`,r=`:`):e===108?t=`:`:e===114&&(r=`:`);let i=n.alignDelimiters===!1?1:Math.max(1,c[d]-t.length-r.length),o=t+`-`.repeat(i)+r;n.alignDelimiters!==!1&&(i=t.length+i+r.length,i>c[d]&&(c[d]=i),p[d]=i),f[d]=o}o.splice(1,0,f),s.splice(1,0,p),u=-1;let m=[];for(;++u<o.length;){let e=o[u],t=s[u];d=-1;let r=[];for(;++d<l;){let i=e[d]||``,o=``,s=``;if(n.alignDelimiters!==!1){let e=c[d]-(t[d]||0),n=a[d];n===114?o=` `.repeat(e):n===99?e%2?(o=` `.repeat(e/2+.5),s=` `.repeat(e/2-.5)):(o=` `.repeat(e/2),s=o):s=` `.repeat(e)}n.delimiterStart!==!1&&!d&&r.push(`|`),n.padding!==!1&&!(n.alignDelimiters===!1&&i===``)&&(n.delimiterStart!==!1||d)&&r.push(` `),n.alignDelimiters!==!1&&r.push(o),r.push(i),n.alignDelimiters!==!1&&r.push(s),n.padding!==!1&&r.push(` `),(n.delimiterEnd!==!1||d!==l-1)&&r.push(`|`)}m.push(n.delimiterEnd===!1?r.join(``).replace(/ +$/,``):r.join(``))}return m.join(`
|
|
@@ -1225,15 +1225,15 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
1225
1225
|
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Dg=o((e=>{var t=yg(),n=ng(),r=rg(),i=Dh(),a=$(),o=Tg(),s=Eg();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),Og=l(o((e=>{var t=yg(),n=ng(),r=eg(),i=rg(),a=vh(),o=$(),s=Ah(),c=yh(),l=Mh(),u=Ph();Cg();var d=wg(),f=Tg(),p=Eg(),m=Dg(),h=fh();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))(),1);function kg(e,t){let n=Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null));return Object.keys(n).length===0?`---
|
|
1226
1226
|
---`:`---\n${Og.stringify(n,{singleQuote:t?.singleQuote??!1,lineWidth:t?.lineWidth??0}).trimEnd()}\n---`}function Ag(e,t,n){return e==null||Object.keys(e).length===0?t:`${kg(e,n)}\n${t}`}function jg(e){let t=dh(e),n,r,i=[];for(let e of t.children)if(e.type===`yaml`){r=e.value;try{n=Og.parse(e.value??``)}catch{}}else i.push(e);let a=e;return r!=null&&(a=e.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,``)),{...n!=null&&{yamlFrontMatter:n},...r!=null&&{rawFrontMatter:r},markdownAst:t,markdownContents:i,contentWithoutFrontMatter:a}}function Mg(e){return e.replaceAll(/(!?\[)([^\]]*)(\]\()([^)]+)(\))/g,(e,t,n,r,i,a)=>{let o=n.replaceAll(/\.mdx$/g,`.md`).replaceAll(/\.mdx(?=#|\?|$)/g,`.md`);return/^(?:https?:)?\/\//.test(i)?`${t}${o}${r}${i}${a}`:`${t}${o}${r}${i.replace(/\.mdx$/,`.md`).replace(/\.mdx#/,`.md#`).replace(/\.mdx\?/,`.md?`)}${a}`})}var Ng=class{type;name;_log;get log(){return this._log??=nn(this.name),this._log}dependsOn;constructor(e,t,n){this.name=e,this.type=t,n!=null&&(this.dependsOn=n)}},Pg=class extends Ng{globalConfigDir;outputFileName;indexignore;registryWriterCache=new Map;writeEffects=[];cleanEffects=[];constructor(e,t){super(e,bt.Output,t?.dependsOn),this.globalConfigDir=t?.globalConfigDir??``,this.outputFileName=t?.outputFileName??``,this.indexignore=t?.indexignore}registerWriteEffect(e,t){this.writeEffects.push({name:e,handler:t})}registerCleanEffect(e,t){this.cleanEffects.push({name:e,handler:t})}async executeWriteEffects(e){let t=[];for(let n of this.writeEffects){if(e.dryRun===!0){this.log.trace({action:`dryRun`,type:`effect`,name:n.name}),t.push({success:!0,description:`Would execute write effect: ${n.name}`});continue}try{let r=await n.handler(e);if(r.success)this.log.trace({action:`effect`,name:n.name,status:`success`});else{let e=r.error instanceof Error?r.error.message:String(r.error);this.log.error({action:`effect`,name:n.name,status:`failed`,error:e})}t.push(r)}catch(e){let r=e instanceof Error?e.message:String(e);this.log.error({action:`effect`,name:n.name,status:`failed`,error:r}),t.push({success:!1,error:e,description:`Write effect failed: ${n.name}`})}}return t}async executeCleanEffects(e){let t=[];for(let n of this.cleanEffects){if(e.dryRun===!0){this.log.trace({action:`dryRun`,type:`effect`,name:n.name}),t.push({success:!0,description:`Would execute clean effect: ${n.name}`});continue}try{let r=await n.handler(e);if(r.success)this.log.trace({action:`effect`,name:n.name,status:`success`});else{let e=r.error instanceof Error?r.error.message:String(r.error);this.log.error({action:`effect`,name:n.name,status:`failed`,error:e})}t.push(r)}catch(e){let r=e instanceof Error?e.message:String(e);this.log.error({action:`effect`,name:n.name,status:`failed`,error:r}),t.push({success:!1,error:e,description:`Clean effect failed: ${n.name}`})}}return t}isRelativePath(e){return e.pathKind===L.Relative}toRelativePath(e){return this.isRelativePath(e)?e:{pathKind:L.Relative,path:e.path,basePath:``,getDirectoryName:e.getDirectoryName,getAbsolutePath:()=>e.path}}resolveFullPath(e,t){let n;n=e.pathKind===L.Absolute?e.path:this.isRelativePath(e)?f.resolve(e.basePath,e.path):f.resolve(u.default.cwd(),e.path);let r=t??this.outputFileName;return r?f.join(n,r):n}createRelativePath(e,t,n){return ct(e,t,n)}createFileRelativePath(e,t){return lt(e,t)}getGlobalConfigDir(){return f.join(this.getHomeDir(),this.globalConfigDir)}getHomeDir(){return p.homedir()}joinPath(...e){return f.join(...e)}resolvePath(...e){return f.resolve(...e)}dirname(e){return f.dirname(e)}basename(e,t){return f.basename(e,t)}writeFileSync(e,t,n=`utf8`){it(e,t,n)}writeFileSyncBuffer(e,t){it(e,t)}ensureDirectory(e){$e(e)}existsSync(e){return d.existsSync(e)}lstatSync(e){return Qe(e)}isSymlink(e){return Ze(e)}createSymlink(e,t,n=`dir`){tt(e,t,n)}removeSymlink(e){nt(e)}async writeDirectorySymlink(e,t,n,r){let i=f.dirname(n),a=ct(f.basename(n),i,()=>f.basename(i));if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`symlink`,target:t,link:n,label:r}),{path:a,success:!0,skipped:!1};try{return this.createSymlink(t,n,`dir`),this.log.trace({action:`write`,type:`symlink`,target:t,link:n,label:r}),{path:a,success:!0}}catch(e){let i=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`symlink`,target:t,link:n,label:r,error:i}),{path:a,success:!1,error:e}}}readdirSync(e,t){return t?.withFileTypes===!0?d.readdirSync(e,{withFileTypes:!0}):d.readdirSync(e)}getIgnoreOutputPath(){if(this.indexignore!=null)return this.indexignore===`.traeignore`?f.join(`.trae`,`.ignore`):this.indexignore}registerProjectIgnoreOutputFiles(e){let t=this.getIgnoreOutputPath();if(t==null)return[];let n=[];for(let r of e){let e=r.dirFromWorkspacePath;if(e==null||r.isPromptSourceProject===!0)continue;let i=f.join(e.path,t);n.push({pathKind:L.Relative,path:i,basePath:e.basePath,getDirectoryName:()=>f.basename(e.path),getAbsolutePath:()=>f.join(e.basePath,i)})}return n}async writeProjectIgnoreFiles(e){let t=this.getIgnoreOutputPath();if(t==null)return[];let{workspace:n,aiAgentIgnoreConfigFiles:r}=e.collectedInputContext,i=[];if(r==null||r.length===0)return i;let a=r.find(e=>e.fileName===this.indexignore);if(a==null)return i;for(let r of n.projects){let n=r.dirFromWorkspacePath;if(n==null||r.isPromptSourceProject===!0)continue;let o=`project:${r.name??`unknown`}/${a.fileName}`,s=f.join(n.path,t),c=f.join(n.basePath,s),l={pathKind:L.Relative,path:s,basePath:n.basePath,getDirectoryName:()=>f.basename(n.path),getAbsolutePath:()=>c};if(e.dryRun===!0){this.log.trace({action:`dryRun`,type:`ignoreFile`,path:c,label:o}),i.push({path:l,success:!0,skipped:!1});continue}try{if(t===f.join(`.trae`,`.ignore`)){let e=f.join(n.basePath,n.path,`.trae`);d.mkdirSync(e,{recursive:!0})}d.writeFileSync(c,a.content,`utf8`),this.log.trace({action:`write`,type:`ignoreFile`,path:c,label:o}),i.push({path:l,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`ignoreFile`,path:c,label:o,error:t}),i.push({path:l,success:!1,error:e})}}return i}async writeFile(e,t,n,r){let i=f.dirname(t),a=ct(f.basename(t),i,()=>f.basename(i));if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`file`,path:t,label:r}),{path:a,success:!0,skipped:!1};try{return it(t,n),this.log.trace({action:`write`,type:`file`,path:t,label:r}),{path:a,success:!0}}catch(e){let n=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`file`,path:t,label:r,error:n}),{path:a,success:!1,error:e}}}async writePromptFile(e,t,n,r){let i=this.resolveFullPath(t),a=this.toRelativePath(t);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`promptFile`,path:i,label:r}),{path:a,success:!0,skipped:!1};try{return it(i,n),this.log.trace({action:`write`,type:`promptFile`,path:i,label:r}),{path:a,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`promptFile`,path:i,label:r,error:t}),{path:a,success:!1,error:e}}}buildMarkdownContent(e,t){return Ag(t,e)}buildMarkdownContentWithRaw(e,t,n){return t!=null&&Object.keys(t).length>0?Ag(t,e):n!=null&&n.length>0?`---\n${n}\n---\n${e}`:e}extractGlobalMemoryContent(e){return e.collectedInputContext.globalMemory?.content}combineGlobalWithContent(e,t,n){let{separator:r=`
|
|
1227
1227
|
|
|
1228
|
-
`,skipIfEmpty:i=!0,position:a=`before`}=n??{};if(i&&(e==null||e.trim().length===0))return t;let o=e??``;return a===`after`?`${t}${r}${o}`:`${o}${r}${t}`}transformFastCommandName(e,t){let{includeSeriesPrefix:n=!0,seriesSeparator:r=`-`}=t??{};return!n||e.series==null?`${e.commandName}.md`:`${e.series}${r}${e.commandName}.md`}getFastCommandSeriesOptions(e){let t=e.pluginOptions?.fastCommandSeriesOptions,n=t?.pluginOverrides?.[this.name],r=n?.includeSeriesPrefix??t?.includeSeriesPrefix,i=n?.seriesSeparator;return r!=null&&i!=null?{includeSeriesPrefix:r,seriesSeparator:i}:r==null?i==null?{}:{seriesSeparator:i}:{includeSeriesPrefix:r}}getTransformOptionsFromContext(e,t){let n=this.getFastCommandSeriesOptions(e),r=n.includeSeriesPrefix??t?.includeSeriesPrefix,i=n.seriesSeparator??t?.seriesSeparator;return r!=null&&i!=null?{includeSeriesPrefix:r,seriesSeparator:i}:r==null?i==null?{}:{seriesSeparator:i}:{includeSeriesPrefix:r}}shouldSkipDueToPlugin(e,t){let n=e.registeredPluginNames;return n==null?!1:n.includes(t)}async onWriteComplete(e,t){let n=t.files.filter(e=>e.success).length,r=t.files.filter(e=>e.skipped).length,i=t.files.filter(e=>!e.success&&!e.skipped).length;this.log.trace({action:e.dryRun===!0?`dryRun`:`complete`,type:`writeSummary`,success:n,skipped:r,failed:i}),await this.executeWriteEffects(e)}async onCleanComplete(e){await this.executeCleanEffects(e)}getRegistryWriter(e){let t=e.name,n=this.registryWriterCache.get(t);if(n!=null)return n;let r=new e(this.log);return this.registryWriterCache.set(t,r),r}async registerInRegistry(e,t,n){return e.register(t,n.dryRun)}};const Fg=`AGENTS.md`;var Ig=class extends Pg{constructor(){super(`AgentsOutputPlugin`,{outputFileName:Fg})}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace;for(let e of n)if(e.rootMemoryPrompt!=null&&e.dirFromWorkspacePath!=null&&t.push(this.createFileRelativePath(e.dirFromWorkspacePath,Fg)),e.childMemoryPrompts!=null)for(let n of e.childMemoryPrompts)n.dir!=null&&this.isRelativePath(n.dir)&&t.push(this.createFileRelativePath(n.dir,Fg));return t}async canWrite(e){let{workspace:t}=e.collectedInputContext;return t.projects.some(e=>e.rootMemoryPrompt!=null||(e.childMemoryPrompts?.length??0)>0)?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,n=[],r=[];for(let r of t){let t=r.name??`unknown`,i=r.dirFromWorkspacePath;if(i!=null){if(r.rootMemoryPrompt!=null){let a=await this.writePromptFile(e,i,r.rootMemoryPrompt.content,`project:${t}/root`);n.push(a)}if(r.childMemoryPrompts!=null)for(let i of r.childMemoryPrompts){let r=await this.writePromptFile(e,i.dir,i.content,`project:${t}/child:${i.workingChildDirectoryPath?.path??`unknown`}`);n.push(r)}}}return{files:n,dirs:r}}},Lg=class extends Ng{inputEffects=[];registeredScopes=[];constructor(e,t){super(e,bt.Input,t)}registerEffect(e,t,n=0){this.inputEffects.push({name:e,handler:t,priority:n}),this.inputEffects.sort((e,t)=>(e.priority??0)-(t.priority??0))}async executeEffects(e,t=!1){let n=[];if(this.inputEffects.length===0)return n;let{workspaceDir:r,shadowProjectDir:i}=this.resolveBasePaths(e.userConfigOptions),a={logger:this.log,fs:e.fs,path:e.path,glob:e.glob,spawn:m.spawn,userConfigOptions:e.userConfigOptions,workspaceDir:r,shadowProjectDir:i,dryRun:t};for(let e of this.inputEffects){if(t){this.log.trace({action:`dryRun`,type:`inputEffect`,name:e.name}),n.push({success:!0,description:`Would execute input effect: ${e.name}`});continue}try{let t=await e.handler(a);if(t.success)this.log.trace({action:`inputEffect`,name:e.name,status:`success`,description:t.description}),t.modifiedFiles!=null&&t.modifiedFiles.length>0&&this.log.debug({action:`inputEffect`,name:e.name,modifiedFiles:t.modifiedFiles}),t.deletedFiles!=null&&t.deletedFiles.length>0&&this.log.debug({action:`inputEffect`,name:e.name,deletedFiles:t.deletedFiles});else{let n=t.error instanceof Error?t.error.message:String(t.error);this.log.error({action:`inputEffect`,name:e.name,status:`failed`,error:n})}n.push(t)}catch(t){let r=t instanceof Error?t.message:String(t);this.log.error({action:`inputEffect`,name:e.name,status:`failed`,error:r}),n.push({success:!1,error:t,description:`Input effect failed: ${e.name}`})}}return n}hasEffects(){return this.inputEffects.length>0}getEffectCount(){return this.inputEffects.length}registerScope(e,t){this.registeredScopes.push({namespace:e,values:t}),this.log.debug({action:`registerScope`,namespace:e,keys:Object.keys(t)})}getRegisteredScopes(){return this.registeredScopes}clearRegisteredScopes(){this.registeredScopes.length=0,this.log.debug({action:`clearRegisteredScopes`})}resolveBasePaths(e){let t=e.workspaceDir,n=this.resolvePath(t,``),r=e.shadowSourceProject.name;return{workspaceDir:n,shadowProjectDir:f.join(n,r)}}resolvePath(e,t){let n=e;return n.startsWith(R.USER_HOME)&&(n=n.replace(R.USER_HOME,p.homedir())),n.includes(R.WORKSPACE)&&(n=n.replace(R.WORKSPACE,t)),f.normalize(n)}resolveShadowPath(e,t){return f.join(t,e)}readAndParseMarkdown(e,t){return jg(t.readFileSync(e,`utf8`))}};const Rg=[`.qoderignore`,`.cursorignore`,`.kiroignore`,`.warpindexignore`,`.aiignore`,`.codeignore`,`.traeignore`];var zg=class extends Lg{constructor(){super(`AIAgentIgnoreConfigFileInputPlugin`)}collect(e){let{userConfigOptions:t,logger:n,fs:r,path:i}=e,{shadowProjectDir:a}=this.resolveBasePaths(t),o=[];for(let e of Rg){let t=i.join(a,e);if(r.existsSync(t)&&r.statSync(t).isFile())try{let i=r.readFileSync(t,`utf8`);o.push({fileName:e,content:i}),n.debug(`read ignore file`,{path:t})}catch(e){n.warn(`failed to read ignore file`,{path:t,error:e})}}return{aiAgentIgnoreConfigFiles:o}}};const Bg=`.agent`,Vg=`antigravity`,Hg=`skills`,Ug=`workflows`,Wg=`mcp_config.json`,Gg=[Hg,Ug];var Kg=class extends Pg{constructor(){super(`AntigravityOutputPlugin`,{globalConfigDir:Bg,outputFileName:``,dependsOn:[`GeminiCLIOutputPlugin`]}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=f.join(this.getAntigravityDir(),Wg),n=JSON.stringify({mcpServers:{}},null,2);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfigCleanup`,path:t}),{success:!0,description:`Would reset mcp_config.json`};let r=await this.writeFile(e,t,n,`mcpConfigCleanup`);return r.success?{success:!0,description:`Reset mcp_config.json`}:{success:!1,description:`Failed`,error:r.error??Error(`Cleanup failed`)}})}getAntigravityDir(){return f.join(p.homedir(),`.gemini`,Vg)}async registerProjectOutputDirs(e){let{projects:t}=e.collectedInputContext.workspace,n=[];for(let e of t)if(e.dirFromWorkspacePath!=null)for(let t of Gg)n.push(this.createRelativePath(f.join(e.dirFromWorkspacePath.path,Bg,t),e.dirFromWorkspacePath.basePath,()=>t));return n}async registerProjectOutputFiles(e){let{skills:t,fastCommands:n}=e.collectedInputContext,r=this.getAntigravityDir(),i=[];if(t!=null)for(let e of t){let t=e.yamlFrontMatter?.name??e.dir.getDirectoryName(),n=f.join(r,Hg,t);if(i.push(this.createRelativePath(`SKILL.md`,n,()=>t)),e.childDocs!=null)for(let r of e.childDocs)i.push(this.createRelativePath(r.dir.path.replace(/\.mdx$/,`.md`),n,()=>t));if(e.resources!=null)for(let r of e.resources)i.push(this.createRelativePath(r.relativePath,n,()=>t))}if(t?.some(e=>e.mcpConfig!=null)&&i.push(this.createRelativePath(Wg,r,()=>Vg)),n==null)return i;let a=this.getTransformOptionsFromContext(e),o=f.join(r,Ug);for(let e of n)i.push(this.createRelativePath(this.transformFastCommandName(e,a),o,()=>Ug));return i}async canWrite(e){let{fastCommands:t,skills:n}=e.collectedInputContext;return(t?.length??0)>0||(n?.length??0)>0?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{fastCommands:t,skills:n}=e.collectedInputContext,r=[],i=this.getAntigravityDir();if(t!=null){let n=f.join(i,Ug);for(let i of t)r.push(await this.writeFastCommand(e,n,i))}if(n!=null){let t=f.join(i,Hg);for(let i of n)r.push(...await this.writeSkill(e,t,i));let a=await this.writeGlobalMcpConfig(e,i,n);a!=null&&r.push(a)}return this.log.info({action:`write`,message:`Synced ${r.length} files`,globalDir:i}),{files:r,dirs:[]}}async writeGlobalMcpConfig(e,t,n){let r={};for(let e of n)if(e.mcpConfig!=null)for(let[t,n]of Object.entries(e.mcpConfig.mcpServers))r[t]=this.transformMcpConfig(n);if(Object.keys(r).length===0)return null;let i=f.join(t,Wg),a=JSON.stringify({mcpServers:r},null,2);return this.writeFile(e,i,a,`globalMcpConfig`)}transformMcpConfig(e){let t={};for(let[n,r]of Object.entries(e))if(n===`url`)t.serverUrl=r;else if(n===`type`||n===`enabled`||n===`autoApprove`)continue;else t[n]=r;return t}async writeFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),i=this.transformFastCommandName(n,r),a=f.join(t,i),o=typeof n.yamlFrontMatter?.description==`string`?{description:n.yamlFrontMatter.description}:{},s;if(n.rawMdxContent!=null){let e=n.rawMdxContent.replace(/^---\n[\s\S]*?\n---\n/,``);s=this.buildMarkdownContentWithRaw(e,o,n.rawFrontMatter)}else s=this.buildMarkdownContentWithRaw(n.content,o,n.rawFrontMatter);return this.writeFile(e,a,s,`fastCommand`)}async writeSkill(e,t,n){let r=[],i=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),a=f.join(t,i),o=f.join(a,`SKILL.md`),s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);if(r.push(await this.writeFile(e,o,s,`skill`)),n.childDocs!=null)for(let t of n.childDocs){let n=t.dir.path.replace(/\.mdx$/,`.md`);r.push(await this.writeFile(e,f.join(a,n),t.content,`skillRefDoc`))}if(n.resources!=null)for(let t of n.resources)r.push(await this.writeFile(e,f.join(a,t.relativePath),t.content,`skillResource`));return r}},qg=class extends Error{constructor(e,t,n){super(e),this.expression=t,this.filePath=n,this.name=`ScopeError`}},Jg=class extends qg{constructor(e,t,n){let r=n!=null&&n.length>0?`Undefined variable "${e}" in expression "${t}" (file: ${n})`:`Undefined variable "${e}" in expression "${t}"`;super(r,t,n),this.variableName=e,this.name=`UndefinedVariableError`}},Yg=class extends qg{constructor(e,t,n){let r=n!=null&&n.length>0?`Undefined namespace "${e}" in expression "${t}" (file: ${n})`:`Undefined namespace "${e}" in expression "${t}"`;super(r,t,n),this.namespace=e,this.name=`UndefinedNamespaceError`}},Xg=class extends Error{constructor(e,t){let n=t!=null&&t.length>0?`Missing required metadata fields: ${e.join(`, `)} (file: ${t})`:`Missing required metadata fields: ${e.join(`, `)}`;super(n),this.missingFields=e,this.filePath=t,this.name=`MetadataValidationError`}},Zg=Object.defineProperty,Qg=(e,t)=>{let n={};for(var r in e)Zg(n,r,{get:e[r],enumerable:!0});return t||Zg(n,Symbol.toStringTag,{value:`Module`}),n};const $g=new Map;function e_(e,t){$g.set(e,t)}function t_(){return new Map($g)}function n_(e){return $g.has(e)}function r_(e,t,n){let r=e.trim();return r===``?``:/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/i.test(r)?i_(r,t,n?.filePath):a_(r,t,n?.filePath)}function i_(e,t,n){let r=e.split(`.`),i=r[0];if(i==null||!(i in t))throw new Yg(i??``,e,n);let a=t[i];for(let t=1;t<r.length;t++){let i=r[t];if(i==null)continue;if(a==null)throw new Jg(i,e,n);if(typeof a!=`object`)throw TypeError(`Cannot read property "${i}" of ${typeof a} in expression "${e}"`);let o=a;if(!(i in o))throw new Jg(i,e,n);a=o[i]}return o_(a)}function a_(e,t,n){let r=Object.keys(t),i=r.map(e=>t[e]);try{return o_(Function(...r,`return (${e})`)(...i))}catch(t){let r=t instanceof Error?t.message:String(t);if(r.includes(`is not defined`)){let t=/(\w+) is not defined/.exec(r);if(t?.[1]!=null)throw new Yg(t[1],e,n)}let i=n==null?``:` (file: ${n})`;throw Error(`Failed to evaluate expression: "${e}"${i}\nCause: ${r}`)}}function o_(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(typeof e==`object`)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function s_(e,t){return e===null?!1:t.components.has(e)||n_(e)}async function c_(e){return async(t,n)=>(await e({type:`root`,children:t},n)).children}async function l_(e,t,n){let r=e.name;if(r==null||r===``)return[];let i=t.components.get(r);if(i==null)return[];if(t.processingStack.includes(r)){let e=[...t.processingStack,r].join(` → `);throw Error(`Circular dependency detected: ${e}`)}let a={scope:t.scope,components:t.components,processingStack:[...t.processingStack,r],...t.basePath==null?{}:{basePath:t.basePath}},o=await c_(n);try{return await i(e,a,o)}catch(e){let n=e instanceof Error?e.message:String(e),i=t.processingStack.join(` → `);throw Error(`Failed to process component "${r}"${i===``?``:` (called from: ${i})`}:\n${n}`,{cause:e})}}function u_(e,t){let n=e.name?.toLowerCase();if(n==null)return null;switch(n){case`pre`:return p_(e,t);case`a`:return m_(e,t);case`strong`:case`b`:return h_(e,t);case`em`:case`i`:return g_(e,t);case`img`:return __(e,t);case`blockquote`:return v_(e,t);default:return null}}function d_(e,t,n){let r=e.attributes.find(e=>e.type===`mdxJsxAttribute`&&e.name===t);return r==null?null:typeof r.value==`string`?r.value:r.value!=null&&typeof r.value==`object`&&r.value.type===`mdxJsxAttributeValueExpression`?r_(r.value.value,n.scope):r.value===null?``:null}function f_(e,t){let n=``;for(let r of e.children)r.type===`text`?n+=r.value:r.type===`mdxTextExpression`?n+=r_(r.value,t.scope):(r.type===`mdxJsxFlowElement`||r.type===`mdxJsxTextElement`)&&(n+=f_(r,t));return n}function p_(e,t){let n=null;for(let t of e.children){if((t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)&&t.name?.toLowerCase()===`code`){n=t;break}if(t.type===`paragraph`&&`children`in t){let e=t.children;for(let t of e)if((t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)&&t.name?.toLowerCase()===`code`){n=t;break}if(n!=null)break}}if(n==null)return null;let r=d_(n,`className`,t)??``,i=/language-(\w+)/.exec(r)?.[1],a=f_(n,t);return[{type:`code`,lang:i??null,value:a.trim()}]}function m_(e,t){let n=d_(e,`href`,t);if(n==null||n===``)return null;let r=f_(e,t);return[{type:`paragraph`,children:[{type:`link`,url:n,title:d_(e,`title`,t)??null,children:[{type:`text`,value:r}]}]}]}function h_(e,t){let n={type:`strong`,children:[{type:`text`,value:f_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function g_(e,t){let n={type:`emphasis`,children:[{type:`text`,value:f_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function __(e,t){let n=d_(e,`src`,t);if(n==null||n===``)return null;let r={type:`image`,url:n,alt:d_(e,`alt`,t)??``,title:d_(e,`title`,t)??null};return e.type,[{type:`paragraph`,children:[r]}]}function v_(e,t){return[{type:`blockquote`,children:[{type:`paragraph`,children:[{type:`text`,value:f_(e,t)}]}]}]}function y_(e){return e==null?!1:JSON.stringify(e).includes(`"JSX`)}async function b_(e,t,n){let r=e.data?.estree;if(r==null||r.body.length===0)return[];let i=r.body[0];return i?.type===`ExpressionStatement`?x_(i.expression,t,n):[]}async function x_(e,t,n){return e.type===`JSXElement`?D_(e,t,n):e.type===`JSXFragment`?O_(e,t,n):e.type===`LogicalExpression`?S_(e,t,n):e.type===`ConditionalExpression`?C_(e,t,n):e.type===`SequenceExpression`?w_(e,t,n):e.type===`ArrayExpression`?T_(e,t,n):L_(e,t)}async function S_(e,t,n){let r=await E_(e.left,t,n);return e.operator===`&&`?F_(r)?x_(e.right,t,n):[]:e.operator===`||`?F_(r)?P_(e.left)?x_(e.left,t,n):I_(r):x_(e.right,t,n):e.operator===`??`?r==null?x_(e.right,t,n):P_(e.left)?x_(e.left,t,n):I_(r):[]}async function C_(e,t,n){return F_(await E_(e.test,t,n))?x_(e.consequent,t,n):x_(e.alternate,t,n)}async function w_(e,t,n){let r=[];for(let i of e.expressions){let e=await x_(i,t,n);r.push(...e)}return r}async function T_(e,t,n){let r=[];for(let i of e.elements)if(i!=null)if(i.type===`SpreadElement`){let e=await x_(i.argument,t,n);r.push(...e)}else{let e=await x_(i,t,n);r.push(...e)}return r}async function E_(e,t,n){if(P_(e))return!0;if(e.type===`Literal`)return e.value;if(e.type===`Identifier`)return e.name===`undefined`?void 0:e.name===`NaN`?NaN:e.name===`Infinity`?1/0:t.scope[e.name];if(e.type===`UnaryExpression`){let r=await E_(e.argument,t,n);return e.operator===`!`?!F_(r):e.operator===`-`?-r:e.operator===`+`?+r:e.operator===`typeof`?typeof r:void 0}if(e.type===`BinaryExpression`){let r=await E_(e.left,t,n),i=await E_(e.right,t,n);return e.operator===`===`?r===i:e.operator===`!==`?r!==i:e.operator===`==`?r===i:e.operator===`!=`?r!==i:e.operator===`<`?r<i:e.operator===`<=`?r<=i:e.operator===`>`?r>i:e.operator===`>=`?r>=i:e.operator===`+`?r+i:e.operator===`-`?r-i:e.operator===`*`?r*i:e.operator===`/`?r/i:e.operator===`%`?r%i:void 0}if(e.type===`LogicalExpression`){let r=await E_(e.left,t,n);return e.operator===`&&`?F_(r)?E_(e.right,t,n):r:e.operator===`||`?F_(r)?r:E_(e.right,t,n):e.operator===`??`?r??E_(e.right,t,n):void 0}if(e.type===`MemberExpression`){let r=await E_(e.object,t,n);if(r==null)return;if(e.computed)return r[await E_(e.property,t,n)];let{name:i}=e.property;return r[i]}if(e.type===`ConditionalExpression`)return F_(await E_(e.test,t,n))?E_(e.consequent,t,n):E_(e.alternate,t,n);let r=N_(e);if(r!==``)try{let e=r_(r,t.scope);return e===`true`?!0:e===`false`?!1:e===`null`?null:e===`undefined`||e===``?void 0:/^-?\d+(?:\.\d+)?$/.test(e)?Number(e):e}catch{return}}async function D_(e,t,n){let r=A_(e,t);if(r.name!=null&&s_(r.name,t)){let{processAst:e}=await Promise.resolve().then(()=>R_);return l_(r,t,e)}return u_(r,t)??(r.children.length>0?n(r.children,t):[])}async function O_(e,t,n){let r=[];for(let i of e.children){let e=await k_(i,t,n);r.push(...e)}return r}async function k_(e,t,n){if(e.type===`JSXElement`)return D_(e,t,n);if(e.type===`JSXFragment`)return O_(e,t,n);if(e.type===`JSXText`){let t=e.value.trim();return t===``?[]:[{type:`paragraph`,children:[{type:`text`,value:t}]}]}return e.type===`JSXExpressionContainer`?e.expression.type===`JSXEmptyExpression`?[]:x_(e.expression,t,n):e.type===`JSXSpreadChild`?x_(e.expression,t,n):[]}function A_(e,t){let n=e.openingElement,r=null;n.name.type===`JSXIdentifier`?{name:r}=n.name:n.name.type===`JSXMemberExpression`?r=j_(n.name):n.name.type===`JSXNamespacedName`&&(r=`${n.name.namespace.name}:${n.name.name.name}`);let i=[];for(let e of n.attributes)if(e.type===`JSXAttribute`){let t=e.name.type===`JSXIdentifier`?e.name.name:`${e.name.namespace.name}:${e.name.name.name}`,n=null;e.value==null?n=null:e.value.type===`Literal`?n=String(e.value.value):e.value.type===`JSXExpressionContainer`&&e.value.expression.type!==`JSXEmptyExpression`&&(n={type:`mdxJsxAttributeValueExpression`,value:N_(e.value.expression)}),i.push({type:`mdxJsxAttribute`,name:t,value:n})}else e.type===`JSXSpreadAttribute`&&i.push({type:`mdxJsxExpressionAttribute`,value:`...${N_(e.argument)}`});let a=[];for(let n of e.children){let e=M_(n,t);e!=null&&a.push(...e)}return{type:`mdxJsxFlowElement`,name:r,attributes:i,children:a}}function j_(e){return e.object.type===`JSXIdentifier`?`${e.object.name}.${e.property.name}`:`${j_(e.object)}.${e.property.name}`}function M_(e,t){if(e.type===`JSXText`){let{value:t}=e;return t.trim()===``?null:[{type:`paragraph`,children:[{type:`text`,value:t}]}]}if(e.type===`JSXElement`)return[A_(e,t)];if(e.type===`JSXFragment`){let n=[];for(let r of e.children){let e=M_(r,t);e!=null&&n.push(...e)}return n}return e.type===`JSXExpressionContainer`?e.expression.type===`JSXEmptyExpression`?null:[{type:`paragraph`,children:[{type:`text`,value:N_(e.expression)}]}]:e.type===`JSXSpreadChild`?[{type:`paragraph`,children:[{type:`text`,value:`...${N_(e.expression)}`}]}]:null}function N_(e){if(e.type===`Identifier`)return e.name;if(e.type===`Literal`)return typeof e.value==`string`?JSON.stringify(e.value):String(e.value);if(e.type===`MemberExpression`){let t=N_(e.object);return e.computed?`${t}[${N_(e.property)}]`:`${t}.${e.property.name}`}if(e.type===`CallExpression`)return`${N_(e.callee)}(${e.arguments.map(e=>N_(e)).join(`, `)})`;if(e.type===`BinaryExpression`||e.type===`LogicalExpression`){let t=N_(e.left),n=N_(e.right);return`(${t} ${e.operator} ${n})`}if(e.type===`UnaryExpression`){let t=N_(e.argument);return`${e.operator}${t}`}if(e.type===`ConditionalExpression`)return`(${N_(e.test)} ? ${N_(e.consequent)} : ${N_(e.alternate)})`;if(e.type===`ArrayExpression`)return`[${e.elements.filter(e=>e!=null&&e.type!==`SpreadElement`).map(e=>N_(e)).join(`, `)}]`;if(e.type===`ObjectExpression`)return`{${e.properties.filter(e=>e.type===`Property`).map(e=>`${e.key.type===`Identifier`?e.key.name:N_(e.key)}: ${N_(e.value)}`).join(`, `)}}`;if(e.type===`TemplateLiteral`){let t="`";for(let n=0;n<e.quasis.length;n++)t+=e.quasis[n]?.value.raw??``,n<e.expressions.length&&(t+=`\${${N_(e.expressions[n])}}`);return t+="`",t}return e.type===`SpreadElement`?`...${N_(e.argument)}`:``}function P_(e){return e.type===`JSXElement`||e.type===`JSXFragment`}function F_(e){return!!e}function I_(e){if(e==null)return[];let t=typeof e==`string`?e:String(e);return t===``||t===`undefined`||t===`null`?[]:[{type:`paragraph`,children:[{type:`text`,value:t}]}]}function L_(e,t){let n=N_(e);if(n===``)return[];try{return I_(r_(n,t.scope))}catch{return[]}}var R_=Qg({processAst:()=>B_});function z_(e){if(!(e.includes(`/`)&&/\.\w+$/.test(e)))return e;let t=e.lastIndexOf(`/`);return e.slice(t+1)}async function B_(e,t){return V_(e,t)}async function V_(e,t){let n=[];for(let r of e.children){let e=await H_(r,t);n.push(...e)}return{type:`root`,children:n}}async function H_(e,t){if(e.type===`mdxjsEsm`)return[];if(e.type===`mdxFlowExpression`){let n=e,r=n.data?.estree,i=n.value.trim();if(i.startsWith(`/*`)&&i.endsWith(`*/`))return[];if(y_(r))return b_(n,t,async(e,t)=>(await B_({type:`root`,children:e},t)).children);let a=r_(n.value,t.scope);return a===``?[]:[{type:`paragraph`,children:[{type:`text`,value:a}]}]}if(e.type===`mdxJsxFlowElement`)return U_(e,t);if(e.type===`link`){let n=e,r=(await W_(n.children,t)).map(e=>e.type===`text`?{...e,value:z_(e.value)}:e);return[{...n,children:r}]}if(!(`children`in e&&Array.isArray(e.children)))return[e];let n=await W_(e.children,t);return[{...e,children:n}]}async function U_(e,t){return e.name!=null&&s_(e.name,t)?l_(e,t,B_):u_(e,t)??[]}async function W_(e,t){let n=[];for(let r of e){if(r.type===`mdxFlowExpression`){let e=r,i=e.data?.estree,a=e.value.trim();if(a.startsWith(`/*`)&&a.endsWith(`*/`))continue;if(y_(i)){let r=await b_(e,t,async(e,t)=>(await B_({type:`root`,children:e},t)).children);for(let e of r)n.push(e);continue}let o=r_(e.value,t.scope);o!==``&&n.push({type:`paragraph`,children:[{type:`text`,value:o}]});continue}if(r.type===`mdxTextExpression`){let e=r,i=e.value.trim();if(i.startsWith(`/*`)&&i.endsWith(`*/`))continue;let a={type:`text`,value:r_(e.value,t.scope)};n.push(a);continue}if(r.type===`mdxJsxTextElement`){let e=r;if(e.name!=null&&s_(e.name,t)){let r=await l_(e,t,B_);for(let e of r)e.type===`paragraph`&&`children`in e?n.push(...e.children):n.push(e);continue}let i=u_(e,t);if(i!=null)for(let e of i)e.type===`paragraph`&&`children`in e?n.push(...e.children):n.push(e);continue}if(`children`in r&&Array.isArray(r.children)){let e=await W_(r.children,t);if(r.type===`link`){let t=e.map(e=>e.type===`text`?{...e,value:z_(e.value)}:e);n.push({...r,children:t});continue}n.push({...r,children:e});continue}n.push(r)}return n}function G_(e){let t=this;t.compiler=n;function n(n){return Bo(n,{...t.data(`settings`),...e,extensions:t.data(`toMarkdownExtensions`)||[]})}}function K_(e,t={}){let n={},{yamlFrontMatter:r,scope:i,filePath:a}=t;for(let t of e){let e=q_(t,i,a);Object.assign(n,e)}let o=Object.keys(n).length>0,s=r!=null&&Object.keys(r).length>0,c;return c=o&&s?`mixed`:o?`export`:`yaml`,{fields:{...r,...n},source:c}}function q_(e,t,n){let r={},i=e.value.trim(),a=/^export\s+default\s+/.exec(i);if(a!=null){let e=a[0].length,o=J_(i,e);if(o!=null)try{let e=Y_(o.trim(),t,n);typeof e==`object`&&e&&!Array.isArray(e)&&Object.assign(r,e)}catch(e){let t=e instanceof Error?e.message:String(e),r=n==null?``:` in file "${n}"`;throw Error(`Cannot statically evaluate export default${r}: ${t}`)}return r}let o=/export\s+const\s+(\w+)\s*=\s*/g,s=o.exec(i);for(;s!==null;){let e=s[1];if(e==null){s=o.exec(i);continue}let a=J_(i,s.index+s[0].length);if(a==null){s=o.exec(i);continue}try{let i=Y_(a.trim(),t,n);e===`metadata`&&typeof i==`object`&&i&&!Array.isArray(i)?Object.assign(r,i):r[e]=i}catch(t){let r=t instanceof Error?t.message:String(t),i=n==null?``:` in file "${n}"`;throw Error(`Cannot statically evaluate export "${e}"${i}: ${r}`)}s=o.exec(i)}return r}function J_(e,t){let n=0,r=null,i=!1,a=t;for(let o=t;o<e.length;o++){let t=e[o];if(i){i=!1;continue}if(t===`\\`){i=!0;continue}if(r!=null){t===r&&(r=null);continue}if(t===`"`||t===`'`||t==="`"){r=t;continue}if(t===`{`||t===`[`){n++;continue}if(t===`}`||t===`]`){n--;continue}if(n===0){if(t===`;`||t===`
|
|
1228
|
+
`,skipIfEmpty:i=!0,position:a=`before`}=n??{};if(i&&(e==null||e.trim().length===0))return t;let o=e??``;return a===`after`?`${t}${r}${o}`:`${o}${r}${t}`}transformFastCommandName(e,t){let{includeSeriesPrefix:n=!0,seriesSeparator:r=`-`}=t??{};return!n||e.series==null?`${e.commandName}.md`:`${e.series}${r}${e.commandName}.md`}getFastCommandSeriesOptions(e){let t=e.pluginOptions?.fastCommandSeriesOptions,n=t?.pluginOverrides?.[this.name],r=n?.includeSeriesPrefix??t?.includeSeriesPrefix,i=n?.seriesSeparator;return r!=null&&i!=null?{includeSeriesPrefix:r,seriesSeparator:i}:r==null?i==null?{}:{seriesSeparator:i}:{includeSeriesPrefix:r}}getTransformOptionsFromContext(e,t){let n=this.getFastCommandSeriesOptions(e),r=n.includeSeriesPrefix??t?.includeSeriesPrefix,i=n.seriesSeparator??t?.seriesSeparator;return r!=null&&i!=null?{includeSeriesPrefix:r,seriesSeparator:i}:r==null?i==null?{}:{seriesSeparator:i}:{includeSeriesPrefix:r}}shouldSkipDueToPlugin(e,t){let n=e.registeredPluginNames;return n==null?!1:n.includes(t)}async onWriteComplete(e,t){let n=t.files.filter(e=>e.success).length,r=t.files.filter(e=>e.skipped).length,i=t.files.filter(e=>!e.success&&!e.skipped).length;this.log.trace({action:e.dryRun===!0?`dryRun`:`complete`,type:`writeSummary`,success:n,skipped:r,failed:i}),await this.executeWriteEffects(e)}async onCleanComplete(e){await this.executeCleanEffects(e)}getRegistryWriter(e){let t=e.name,n=this.registryWriterCache.get(t);if(n!=null)return n;let r=new e(this.log);return this.registryWriterCache.set(t,r),r}async registerInRegistry(e,t,n){return e.register(t,n.dryRun)}normalizeRuleScope(e){return e.scope??`project`}};const Fg=`AGENTS.md`;var Ig=class extends Pg{constructor(){super(`AgentsOutputPlugin`,{outputFileName:Fg})}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace;for(let e of n)if(e.rootMemoryPrompt!=null&&e.dirFromWorkspacePath!=null&&t.push(this.createFileRelativePath(e.dirFromWorkspacePath,Fg)),e.childMemoryPrompts!=null)for(let n of e.childMemoryPrompts)n.dir!=null&&this.isRelativePath(n.dir)&&t.push(this.createFileRelativePath(n.dir,Fg));return t}async canWrite(e){let{workspace:t}=e.collectedInputContext;return t.projects.some(e=>e.rootMemoryPrompt!=null||(e.childMemoryPrompts?.length??0)>0)?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,n=[],r=[];for(let r of t){let t=r.name??`unknown`,i=r.dirFromWorkspacePath;if(i!=null){if(r.rootMemoryPrompt!=null){let a=await this.writePromptFile(e,i,r.rootMemoryPrompt.content,`project:${t}/root`);n.push(a)}if(r.childMemoryPrompts!=null)for(let i of r.childMemoryPrompts){let r=await this.writePromptFile(e,i.dir,i.content,`project:${t}/child:${i.workingChildDirectoryPath?.path??`unknown`}`);n.push(r)}}}return{files:n,dirs:r}}},Lg=class extends Ng{inputEffects=[];registeredScopes=[];constructor(e,t){super(e,bt.Input,t)}registerEffect(e,t,n=0){this.inputEffects.push({name:e,handler:t,priority:n}),this.inputEffects.sort((e,t)=>(e.priority??0)-(t.priority??0))}async executeEffects(e,t=!1){let n=[];if(this.inputEffects.length===0)return n;let{workspaceDir:r,shadowProjectDir:i}=this.resolveBasePaths(e.userConfigOptions),a={logger:this.log,fs:e.fs,path:e.path,glob:e.glob,spawn:m.spawn,userConfigOptions:e.userConfigOptions,workspaceDir:r,shadowProjectDir:i,dryRun:t};for(let e of this.inputEffects){if(t){this.log.trace({action:`dryRun`,type:`inputEffect`,name:e.name}),n.push({success:!0,description:`Would execute input effect: ${e.name}`});continue}try{let t=await e.handler(a);if(t.success)this.log.trace({action:`inputEffect`,name:e.name,status:`success`,description:t.description}),t.modifiedFiles!=null&&t.modifiedFiles.length>0&&this.log.debug({action:`inputEffect`,name:e.name,modifiedFiles:t.modifiedFiles}),t.deletedFiles!=null&&t.deletedFiles.length>0&&this.log.debug({action:`inputEffect`,name:e.name,deletedFiles:t.deletedFiles});else{let n=t.error instanceof Error?t.error.message:String(t.error);this.log.error({action:`inputEffect`,name:e.name,status:`failed`,error:n})}n.push(t)}catch(t){let r=t instanceof Error?t.message:String(t);this.log.error({action:`inputEffect`,name:e.name,status:`failed`,error:r}),n.push({success:!1,error:t,description:`Input effect failed: ${e.name}`})}}return n}hasEffects(){return this.inputEffects.length>0}getEffectCount(){return this.inputEffects.length}registerScope(e,t){this.registeredScopes.push({namespace:e,values:t}),this.log.debug({action:`registerScope`,namespace:e,keys:Object.keys(t)})}getRegisteredScopes(){return this.registeredScopes}clearRegisteredScopes(){this.registeredScopes.length=0,this.log.debug({action:`clearRegisteredScopes`})}resolveBasePaths(e){let t=e.workspaceDir,n=this.resolvePath(t,``),r=e.shadowSourceProject.name;return{workspaceDir:n,shadowProjectDir:f.join(n,r)}}resolvePath(e,t){let n=e;return n.startsWith(R.USER_HOME)&&(n=n.replace(R.USER_HOME,p.homedir())),n.includes(R.WORKSPACE)&&(n=n.replace(R.WORKSPACE,t)),f.normalize(n)}resolveShadowPath(e,t){return f.join(t,e)}readAndParseMarkdown(e,t){return jg(t.readFileSync(e,`utf8`))}};const Rg=[`.qoderignore`,`.cursorignore`,`.kiroignore`,`.warpindexignore`,`.aiignore`,`.codeignore`,`.traeignore`];var zg=class extends Lg{constructor(){super(`AIAgentIgnoreConfigFileInputPlugin`)}collect(e){let{userConfigOptions:t,logger:n,fs:r,path:i}=e,{shadowProjectDir:a}=this.resolveBasePaths(t),o=[];for(let e of Rg){let t=i.join(a,e);if(r.existsSync(t)&&r.statSync(t).isFile())try{let i=r.readFileSync(t,`utf8`);o.push({fileName:e,content:i}),n.debug(`read ignore file`,{path:t})}catch(e){n.warn(`failed to read ignore file`,{path:t,error:e})}}return{aiAgentIgnoreConfigFiles:o}}};const Bg=`.agent`,Vg=`antigravity`,Hg=`skills`,Ug=`workflows`,Wg=`mcp_config.json`,Gg=[Hg,Ug];var Kg=class extends Pg{constructor(){super(`AntigravityOutputPlugin`,{globalConfigDir:Bg,outputFileName:``,dependsOn:[`GeminiCLIOutputPlugin`]}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=f.join(this.getAntigravityDir(),Wg),n=JSON.stringify({mcpServers:{}},null,2);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfigCleanup`,path:t}),{success:!0,description:`Would reset mcp_config.json`};let r=await this.writeFile(e,t,n,`mcpConfigCleanup`);return r.success?{success:!0,description:`Reset mcp_config.json`}:{success:!1,description:`Failed`,error:r.error??Error(`Cleanup failed`)}})}getAntigravityDir(){return f.join(p.homedir(),`.gemini`,Vg)}async registerProjectOutputDirs(e){let{projects:t}=e.collectedInputContext.workspace,n=[];for(let e of t)if(e.dirFromWorkspacePath!=null)for(let t of Gg)n.push(this.createRelativePath(f.join(e.dirFromWorkspacePath.path,Bg,t),e.dirFromWorkspacePath.basePath,()=>t));return n}async registerProjectOutputFiles(e){let{skills:t,fastCommands:n}=e.collectedInputContext,r=this.getAntigravityDir(),i=[];if(t!=null)for(let e of t){let t=e.yamlFrontMatter?.name??e.dir.getDirectoryName(),n=f.join(r,Hg,t);if(i.push(this.createRelativePath(`SKILL.md`,n,()=>t)),e.childDocs!=null)for(let r of e.childDocs)i.push(this.createRelativePath(r.dir.path.replace(/\.mdx$/,`.md`),n,()=>t));if(e.resources!=null)for(let r of e.resources)i.push(this.createRelativePath(r.relativePath,n,()=>t))}if(t?.some(e=>e.mcpConfig!=null)&&i.push(this.createRelativePath(Wg,r,()=>Vg)),n==null)return i;let a=this.getTransformOptionsFromContext(e),o=f.join(r,Ug);for(let e of n)i.push(this.createRelativePath(this.transformFastCommandName(e,a),o,()=>Ug));return i}async canWrite(e){let{fastCommands:t,skills:n}=e.collectedInputContext;return(t?.length??0)>0||(n?.length??0)>0?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{fastCommands:t,skills:n}=e.collectedInputContext,r=[],i=this.getAntigravityDir();if(t!=null){let n=f.join(i,Ug);for(let i of t)r.push(await this.writeFastCommand(e,n,i))}if(n!=null){let t=f.join(i,Hg);for(let i of n)r.push(...await this.writeSkill(e,t,i));let a=await this.writeGlobalMcpConfig(e,i,n);a!=null&&r.push(a)}return this.log.info({action:`write`,message:`Synced ${r.length} files`,globalDir:i}),{files:r,dirs:[]}}async writeGlobalMcpConfig(e,t,n){let r={};for(let e of n)if(e.mcpConfig!=null)for(let[t,n]of Object.entries(e.mcpConfig.mcpServers))r[t]=this.transformMcpConfig(n);if(Object.keys(r).length===0)return null;let i=f.join(t,Wg),a=JSON.stringify({mcpServers:r},null,2);return this.writeFile(e,i,a,`globalMcpConfig`)}transformMcpConfig(e){let t={};for(let[n,r]of Object.entries(e))if(n===`url`)t.serverUrl=r;else if(n===`type`||n===`enabled`||n===`autoApprove`)continue;else t[n]=r;return t}async writeFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),i=this.transformFastCommandName(n,r),a=f.join(t,i),o=typeof n.yamlFrontMatter?.description==`string`?{description:n.yamlFrontMatter.description}:{},s;if(n.rawMdxContent!=null){let e=n.rawMdxContent.replace(/^---\n[\s\S]*?\n---\n/,``);s=this.buildMarkdownContentWithRaw(e,o,n.rawFrontMatter)}else s=this.buildMarkdownContentWithRaw(n.content,o,n.rawFrontMatter);return this.writeFile(e,a,s,`fastCommand`)}async writeSkill(e,t,n){let r=[],i=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),a=f.join(t,i),o=f.join(a,`SKILL.md`),s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);if(r.push(await this.writeFile(e,o,s,`skill`)),n.childDocs!=null)for(let t of n.childDocs){let n=t.dir.path.replace(/\.mdx$/,`.md`);r.push(await this.writeFile(e,f.join(a,n),t.content,`skillRefDoc`))}if(n.resources!=null)for(let t of n.resources)r.push(await this.writeFile(e,f.join(a,t.relativePath),t.content,`skillResource`));return r}},qg=class extends Error{constructor(e,t,n){super(e),this.expression=t,this.filePath=n,this.name=`ScopeError`}},Jg=class extends qg{constructor(e,t,n){let r=n!=null&&n.length>0?`Undefined variable "${e}" in expression "${t}" (file: ${n})`:`Undefined variable "${e}" in expression "${t}"`;super(r,t,n),this.variableName=e,this.name=`UndefinedVariableError`}},Yg=class extends qg{constructor(e,t,n){let r=n!=null&&n.length>0?`Undefined namespace "${e}" in expression "${t}" (file: ${n})`:`Undefined namespace "${e}" in expression "${t}"`;super(r,t,n),this.namespace=e,this.name=`UndefinedNamespaceError`}},Xg=class extends Error{constructor(e,t){let n=t!=null&&t.length>0?`Missing required metadata fields: ${e.join(`, `)} (file: ${t})`:`Missing required metadata fields: ${e.join(`, `)}`;super(n),this.missingFields=e,this.filePath=t,this.name=`MetadataValidationError`}},Zg=Object.defineProperty,Qg=(e,t)=>{let n={};for(var r in e)Zg(n,r,{get:e[r],enumerable:!0});return t||Zg(n,Symbol.toStringTag,{value:`Module`}),n};const $g=new Map;function e_(e,t){$g.set(e,t)}function t_(){return new Map($g)}function n_(e){return $g.has(e)}function r_(e,t,n){let r=e.trim();return r===``?``:/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/i.test(r)?i_(r,t,n?.filePath):a_(r,t,n?.filePath)}function i_(e,t,n){let r=e.split(`.`),i=r[0];if(i==null||!(i in t))throw new Yg(i??``,e,n);let a=t[i];for(let t=1;t<r.length;t++){let i=r[t];if(i==null)continue;if(a==null)throw new Jg(i,e,n);if(typeof a!=`object`)throw TypeError(`Cannot read property "${i}" of ${typeof a} in expression "${e}"`);let o=a;if(!(i in o))throw new Jg(i,e,n);a=o[i]}return o_(a)}function a_(e,t,n){let r=Object.keys(t),i=r.map(e=>t[e]);try{return o_(Function(...r,`return (${e})`)(...i))}catch(t){let r=t instanceof Error?t.message:String(t);if(r.includes(`is not defined`)){let t=/(\w+) is not defined/.exec(r);if(t?.[1]!=null)throw new Yg(t[1],e,n)}let i=n==null?``:` (file: ${n})`;throw Error(`Failed to evaluate expression: "${e}"${i}\nCause: ${r}`)}}function o_(e){if(e==null)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(typeof e==`object`)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function s_(e,t){return e===null?!1:t.components.has(e)||n_(e)}async function c_(e){return async(t,n)=>(await e({type:`root`,children:t},n)).children}async function l_(e,t,n){let r=e.name;if(r==null||r===``)return[];let i=t.components.get(r);if(i==null)return[];if(t.processingStack.includes(r)){let e=[...t.processingStack,r].join(` → `);throw Error(`Circular dependency detected: ${e}`)}let a={scope:t.scope,components:t.components,processingStack:[...t.processingStack,r],...t.basePath==null?{}:{basePath:t.basePath}},o=await c_(n);try{return await i(e,a,o)}catch(e){let n=e instanceof Error?e.message:String(e),i=t.processingStack.join(` → `);throw Error(`Failed to process component "${r}"${i===``?``:` (called from: ${i})`}:\n${n}`,{cause:e})}}function u_(e,t){let n=e.name?.toLowerCase();if(n==null)return null;switch(n){case`pre`:return p_(e,t);case`a`:return m_(e,t);case`strong`:case`b`:return h_(e,t);case`em`:case`i`:return g_(e,t);case`img`:return __(e,t);case`blockquote`:return v_(e,t);default:return null}}function d_(e,t,n){let r=e.attributes.find(e=>e.type===`mdxJsxAttribute`&&e.name===t);return r==null?null:typeof r.value==`string`?r.value:r.value!=null&&typeof r.value==`object`&&r.value.type===`mdxJsxAttributeValueExpression`?r_(r.value.value,n.scope):r.value===null?``:null}function f_(e,t){let n=``;for(let r of e.children)r.type===`text`?n+=r.value:r.type===`mdxTextExpression`?n+=r_(r.value,t.scope):(r.type===`mdxJsxFlowElement`||r.type===`mdxJsxTextElement`)&&(n+=f_(r,t));return n}function p_(e,t){let n=null;for(let t of e.children){if((t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)&&t.name?.toLowerCase()===`code`){n=t;break}if(t.type===`paragraph`&&`children`in t){let e=t.children;for(let t of e)if((t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)&&t.name?.toLowerCase()===`code`){n=t;break}if(n!=null)break}}if(n==null)return null;let r=d_(n,`className`,t)??``,i=/language-(\w+)/.exec(r)?.[1],a=f_(n,t);return[{type:`code`,lang:i??null,value:a.trim()}]}function m_(e,t){let n=d_(e,`href`,t);if(n==null||n===``)return null;let r=f_(e,t);return[{type:`paragraph`,children:[{type:`link`,url:n,title:d_(e,`title`,t)??null,children:[{type:`text`,value:r}]}]}]}function h_(e,t){let n={type:`strong`,children:[{type:`text`,value:f_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function g_(e,t){let n={type:`emphasis`,children:[{type:`text`,value:f_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function __(e,t){let n=d_(e,`src`,t);if(n==null||n===``)return null;let r={type:`image`,url:n,alt:d_(e,`alt`,t)??``,title:d_(e,`title`,t)??null};return e.type,[{type:`paragraph`,children:[r]}]}function v_(e,t){return[{type:`blockquote`,children:[{type:`paragraph`,children:[{type:`text`,value:f_(e,t)}]}]}]}function y_(e){return e==null?!1:JSON.stringify(e).includes(`"JSX`)}async function b_(e,t,n){let r=e.data?.estree;if(r==null||r.body.length===0)return[];let i=r.body[0];return i?.type===`ExpressionStatement`?x_(i.expression,t,n):[]}async function x_(e,t,n){return e.type===`JSXElement`?D_(e,t,n):e.type===`JSXFragment`?O_(e,t,n):e.type===`LogicalExpression`?S_(e,t,n):e.type===`ConditionalExpression`?C_(e,t,n):e.type===`SequenceExpression`?w_(e,t,n):e.type===`ArrayExpression`?T_(e,t,n):L_(e,t)}async function S_(e,t,n){let r=await E_(e.left,t,n);return e.operator===`&&`?F_(r)?x_(e.right,t,n):[]:e.operator===`||`?F_(r)?P_(e.left)?x_(e.left,t,n):I_(r):x_(e.right,t,n):e.operator===`??`?r==null?x_(e.right,t,n):P_(e.left)?x_(e.left,t,n):I_(r):[]}async function C_(e,t,n){return F_(await E_(e.test,t,n))?x_(e.consequent,t,n):x_(e.alternate,t,n)}async function w_(e,t,n){let r=[];for(let i of e.expressions){let e=await x_(i,t,n);r.push(...e)}return r}async function T_(e,t,n){let r=[];for(let i of e.elements)if(i!=null)if(i.type===`SpreadElement`){let e=await x_(i.argument,t,n);r.push(...e)}else{let e=await x_(i,t,n);r.push(...e)}return r}async function E_(e,t,n){if(P_(e))return!0;if(e.type===`Literal`)return e.value;if(e.type===`Identifier`)return e.name===`undefined`?void 0:e.name===`NaN`?NaN:e.name===`Infinity`?1/0:t.scope[e.name];if(e.type===`UnaryExpression`){let r=await E_(e.argument,t,n);return e.operator===`!`?!F_(r):e.operator===`-`?-r:e.operator===`+`?+r:e.operator===`typeof`?typeof r:void 0}if(e.type===`BinaryExpression`){let r=await E_(e.left,t,n),i=await E_(e.right,t,n);return e.operator===`===`?r===i:e.operator===`!==`?r!==i:e.operator===`==`?r===i:e.operator===`!=`?r!==i:e.operator===`<`?r<i:e.operator===`<=`?r<=i:e.operator===`>`?r>i:e.operator===`>=`?r>=i:e.operator===`+`?r+i:e.operator===`-`?r-i:e.operator===`*`?r*i:e.operator===`/`?r/i:e.operator===`%`?r%i:void 0}if(e.type===`LogicalExpression`){let r=await E_(e.left,t,n);return e.operator===`&&`?F_(r)?E_(e.right,t,n):r:e.operator===`||`?F_(r)?r:E_(e.right,t,n):e.operator===`??`?r??E_(e.right,t,n):void 0}if(e.type===`MemberExpression`){let r=await E_(e.object,t,n);if(r==null)return;if(e.computed)return r[await E_(e.property,t,n)];let{name:i}=e.property;return r[i]}if(e.type===`ConditionalExpression`)return F_(await E_(e.test,t,n))?E_(e.consequent,t,n):E_(e.alternate,t,n);let r=N_(e);if(r!==``)try{let e=r_(r,t.scope);return e===`true`?!0:e===`false`?!1:e===`null`?null:e===`undefined`||e===``?void 0:/^-?\d+(?:\.\d+)?$/.test(e)?Number(e):e}catch{return}}async function D_(e,t,n){let r=A_(e,t);if(r.name!=null&&s_(r.name,t)){let{processAst:e}=await Promise.resolve().then(()=>R_);return l_(r,t,e)}return u_(r,t)??(r.children.length>0?n(r.children,t):[])}async function O_(e,t,n){let r=[];for(let i of e.children){let e=await k_(i,t,n);r.push(...e)}return r}async function k_(e,t,n){if(e.type===`JSXElement`)return D_(e,t,n);if(e.type===`JSXFragment`)return O_(e,t,n);if(e.type===`JSXText`){let t=e.value.trim();return t===``?[]:[{type:`paragraph`,children:[{type:`text`,value:t}]}]}return e.type===`JSXExpressionContainer`?e.expression.type===`JSXEmptyExpression`?[]:x_(e.expression,t,n):e.type===`JSXSpreadChild`?x_(e.expression,t,n):[]}function A_(e,t){let n=e.openingElement,r=null;n.name.type===`JSXIdentifier`?{name:r}=n.name:n.name.type===`JSXMemberExpression`?r=j_(n.name):n.name.type===`JSXNamespacedName`&&(r=`${n.name.namespace.name}:${n.name.name.name}`);let i=[];for(let e of n.attributes)if(e.type===`JSXAttribute`){let t=e.name.type===`JSXIdentifier`?e.name.name:`${e.name.namespace.name}:${e.name.name.name}`,n=null;e.value==null?n=null:e.value.type===`Literal`?n=String(e.value.value):e.value.type===`JSXExpressionContainer`&&e.value.expression.type!==`JSXEmptyExpression`&&(n={type:`mdxJsxAttributeValueExpression`,value:N_(e.value.expression)}),i.push({type:`mdxJsxAttribute`,name:t,value:n})}else e.type===`JSXSpreadAttribute`&&i.push({type:`mdxJsxExpressionAttribute`,value:`...${N_(e.argument)}`});let a=[];for(let n of e.children){let e=M_(n,t);e!=null&&a.push(...e)}return{type:`mdxJsxFlowElement`,name:r,attributes:i,children:a}}function j_(e){return e.object.type===`JSXIdentifier`?`${e.object.name}.${e.property.name}`:`${j_(e.object)}.${e.property.name}`}function M_(e,t){if(e.type===`JSXText`){let{value:t}=e;return t.trim()===``?null:[{type:`paragraph`,children:[{type:`text`,value:t}]}]}if(e.type===`JSXElement`)return[A_(e,t)];if(e.type===`JSXFragment`){let n=[];for(let r of e.children){let e=M_(r,t);e!=null&&n.push(...e)}return n}return e.type===`JSXExpressionContainer`?e.expression.type===`JSXEmptyExpression`?null:[{type:`paragraph`,children:[{type:`text`,value:N_(e.expression)}]}]:e.type===`JSXSpreadChild`?[{type:`paragraph`,children:[{type:`text`,value:`...${N_(e.expression)}`}]}]:null}function N_(e){if(e.type===`Identifier`)return e.name;if(e.type===`Literal`)return typeof e.value==`string`?JSON.stringify(e.value):String(e.value);if(e.type===`MemberExpression`){let t=N_(e.object);return e.computed?`${t}[${N_(e.property)}]`:`${t}.${e.property.name}`}if(e.type===`CallExpression`)return`${N_(e.callee)}(${e.arguments.map(e=>N_(e)).join(`, `)})`;if(e.type===`BinaryExpression`||e.type===`LogicalExpression`){let t=N_(e.left),n=N_(e.right);return`(${t} ${e.operator} ${n})`}if(e.type===`UnaryExpression`){let t=N_(e.argument);return`${e.operator}${t}`}if(e.type===`ConditionalExpression`)return`(${N_(e.test)} ? ${N_(e.consequent)} : ${N_(e.alternate)})`;if(e.type===`ArrayExpression`)return`[${e.elements.filter(e=>e!=null&&e.type!==`SpreadElement`).map(e=>N_(e)).join(`, `)}]`;if(e.type===`ObjectExpression`)return`{${e.properties.filter(e=>e.type===`Property`).map(e=>`${e.key.type===`Identifier`?e.key.name:N_(e.key)}: ${N_(e.value)}`).join(`, `)}}`;if(e.type===`TemplateLiteral`){let t="`";for(let n=0;n<e.quasis.length;n++)t+=e.quasis[n]?.value.raw??``,n<e.expressions.length&&(t+=`\${${N_(e.expressions[n])}}`);return t+="`",t}return e.type===`SpreadElement`?`...${N_(e.argument)}`:``}function P_(e){return e.type===`JSXElement`||e.type===`JSXFragment`}function F_(e){return!!e}function I_(e){if(e==null)return[];let t=typeof e==`string`?e:String(e);return t===``||t===`undefined`||t===`null`?[]:[{type:`paragraph`,children:[{type:`text`,value:t}]}]}function L_(e,t){let n=N_(e);if(n===``)return[];try{return I_(r_(n,t.scope))}catch{return[]}}var R_=Qg({processAst:()=>B_});function z_(e){if(!(e.includes(`/`)&&/\.\w+$/.test(e)))return e;let t=e.lastIndexOf(`/`);return e.slice(t+1)}async function B_(e,t){return V_(e,t)}async function V_(e,t){let n=[];for(let r of e.children){let e=await H_(r,t);n.push(...e)}return{type:`root`,children:n}}async function H_(e,t){if(e.type===`mdxjsEsm`)return[];if(e.type===`mdxFlowExpression`){let n=e,r=n.data?.estree,i=n.value.trim();if(i.startsWith(`/*`)&&i.endsWith(`*/`))return[];if(y_(r))return b_(n,t,async(e,t)=>(await B_({type:`root`,children:e},t)).children);let a=r_(n.value,t.scope);return a===``?[]:[{type:`paragraph`,children:[{type:`text`,value:a}]}]}if(e.type===`mdxJsxFlowElement`)return U_(e,t);if(e.type===`link`){let n=e,r=(await W_(n.children,t)).map(e=>e.type===`text`?{...e,value:z_(e.value)}:e);return[{...n,children:r}]}if(!(`children`in e&&Array.isArray(e.children)))return[e];let n=await W_(e.children,t);return[{...e,children:n}]}async function U_(e,t){return e.name!=null&&s_(e.name,t)?l_(e,t,B_):u_(e,t)??[]}async function W_(e,t){let n=[];for(let r of e){if(r.type===`mdxFlowExpression`){let e=r,i=e.data?.estree,a=e.value.trim();if(a.startsWith(`/*`)&&a.endsWith(`*/`))continue;if(y_(i)){let r=await b_(e,t,async(e,t)=>(await B_({type:`root`,children:e},t)).children);for(let e of r)n.push(e);continue}let o=r_(e.value,t.scope);o!==``&&n.push({type:`paragraph`,children:[{type:`text`,value:o}]});continue}if(r.type===`mdxTextExpression`){let e=r,i=e.value.trim();if(i.startsWith(`/*`)&&i.endsWith(`*/`))continue;let a={type:`text`,value:r_(e.value,t.scope)};n.push(a);continue}if(r.type===`mdxJsxTextElement`){let e=r;if(e.name!=null&&s_(e.name,t)){let r=await l_(e,t,B_);for(let e of r)e.type===`paragraph`&&`children`in e?n.push(...e.children):n.push(e);continue}let i=u_(e,t);if(i!=null)for(let e of i)e.type===`paragraph`&&`children`in e?n.push(...e.children):n.push(e);continue}if(`children`in r&&Array.isArray(r.children)){let e=await W_(r.children,t);if(r.type===`link`){let t=e.map(e=>e.type===`text`?{...e,value:z_(e.value)}:e);n.push({...r,children:t});continue}n.push({...r,children:e});continue}n.push(r)}return n}function G_(e){let t=this;t.compiler=n;function n(n){return Bo(n,{...t.data(`settings`),...e,extensions:t.data(`toMarkdownExtensions`)||[]})}}function K_(e,t={}){let n={},{yamlFrontMatter:r,scope:i,filePath:a}=t;for(let t of e){let e=q_(t,i,a);Object.assign(n,e)}let o=Object.keys(n).length>0,s=r!=null&&Object.keys(r).length>0,c;return c=o&&s?`mixed`:o?`export`:`yaml`,{fields:{...r,...n},source:c}}function q_(e,t,n){let r={},i=e.value.trim(),a=/^export\s+default\s+/.exec(i);if(a!=null){let e=a[0].length,o=J_(i,e);if(o!=null)try{let e=Y_(o.trim(),t,n);typeof e==`object`&&e&&!Array.isArray(e)&&Object.assign(r,e)}catch(e){let t=e instanceof Error?e.message:String(e),r=n==null?``:` in file "${n}"`;throw Error(`Cannot statically evaluate export default${r}: ${t}`)}return r}let o=/export\s+const\s+(\w+)\s*=\s*/g,s=o.exec(i);for(;s!==null;){let e=s[1];if(e==null){s=o.exec(i);continue}let a=J_(i,s.index+s[0].length);if(a==null){s=o.exec(i);continue}try{let i=Y_(a.trim(),t,n);e===`metadata`&&typeof i==`object`&&i&&!Array.isArray(i)?Object.assign(r,i):r[e]=i}catch(t){let r=t instanceof Error?t.message:String(t),i=n==null?``:` in file "${n}"`;throw Error(`Cannot statically evaluate export "${e}"${i}: ${r}`)}s=o.exec(i)}return r}function J_(e,t){let n=0,r=null,i=!1,a=t;for(let o=t;o<e.length;o++){let t=e[o];if(i){i=!1;continue}if(t===`\\`){i=!0;continue}if(r!=null){t===r&&(r=null);continue}if(t===`"`||t===`'`||t==="`"){r=t;continue}if(t===`{`||t===`[`){n++;continue}if(t===`}`||t===`]`){n--;continue}if(n===0){if(t===`;`||t===`
|
|
1229
1229
|
`){a=o;break}if(t===`/`&&o+1<e.length&&e[o+1]===`/`){a=o;break}}o===e.length-1&&(a=e.length)}a<=t&&(a=e.length);let o=e.slice(t,a).trim();return o.endsWith(`;`)?o.slice(0,-1).trim():o}function Y_(e,t,n){let r=e.trim();if(r===``)throw Error(`Empty value cannot be evaluated`);if(r===`true`)return!0;if(r===`false`)return!1;if(r===`null`)return null;if(/^-?\d+(?:\.\d+)?$/.test(r))return Number(r);if(r.startsWith(`"`)&&r.endsWith(`"`))return X_(r.slice(1,-1),`"`);if(r.startsWith(`'`)&&r.endsWith(`'`))return X_(r.slice(1,-1),`'`);if(r.startsWith("`")&&r.endsWith("`")){let e=r.slice(1,-1);if(e.includes("${"))throw Error(`Template literal with expressions cannot be statically evaluated: ${r}`);return X_(e,"`")}if(r.startsWith(`[`)&&r.endsWith(`]`))return Q_(r,t,n);if(r.startsWith(`{`)&&r.endsWith(`}`))return $_(r,t,n);if(/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/i.test(r))return Z_(r,t,n);let i=n==null?``:` in file "${n}"`;throw Error(`Expression "${r}" cannot be statically evaluated${i}`)}function X_(e,t){return e.replaceAll(`\\n`,`
|
|
1230
|
-
`).replaceAll(`\\r`,`\r`).replaceAll(`\\t`,` `).replaceAll(`\\"`,`"`).replaceAll(`\\'`,`'`).replaceAll(`\\\\`,`\\`)}function Z_(e,t,n){if(t==null){let t=n==null?``:` in file "${n}"`;throw Error(`Variable reference "${e}" cannot be resolved without scope${t}`)}let r=e.split(`.`),i=r[0];if(i==null||!(i in t)){let r=n==null?``:` in file "${n}"`,a=Object.keys(t).join(`, `);throw Error(`Undefined namespace "${i}" in expression "${e}"${r}. Available: ${a}`)}let a=t[i];for(let t=1;t<r.length;t++){let i=r[t];if(i==null)continue;if(a==null){let t=n==null?``:` in file "${n}"`;throw Error(`Cannot read property "${i}" of null/undefined in "${e}"${t}`)}if(typeof a!=`object`){let t=n==null?``:` in file "${n}"`;throw Error(`Cannot read property "${i}" of ${typeof a} in "${e}"${t}`)}let o=a;if(!(i in o)){let t=n==null?``:` in file "${n}"`,r=Object.keys(o).join(`, `);throw Error(`Undefined property "${i}" in "${e}"${t}. Available: ${r}`)}a=o[i]}if(typeof a==`string`||typeof a==`number`||typeof a==`boolean`||a===null||Array.isArray(a)||typeof a==`object`)return a;let o=n==null?``:` in file "${n}"`;throw Error(`Variable "${e}" resolved to unsupported type: ${typeof a}${o}`)}function Q_(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return[];if(t==null)try{let t=ev(e),n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return tv(r).map(e=>Y_(e.trim(),t,n))}function $_(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return{};if(t==null)try{let t=ev(e),n=JSON.parse(t);if(typeof n==`object`&&n&&!Array.isArray(n))return n}catch{}let i={},a=nv(r);for(let e of a){let r=rv(e);if(r===-1)continue;let a=e.slice(0,r).trim(),o=e.slice(r+1).trim();(a.startsWith(`"`)&&a.endsWith(`"`)||a.startsWith(`'`)&&a.endsWith(`'`))&&(a=a.slice(1,-1)),i[a]=Y_(o,t,n)}return i}function ev(e){let t=``,n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){t+=a,r=!1;continue}if(a===`\\`){t+=a,r=!0;continue}if(n!=null){a===n?(t+=`"`,n=null):a===`"`&&n===`'`?t+=`\\"`:t+=a;continue}if(a===`"`||a===`'`){t+=`"`,n=a;continue}if(a===`:`&&i>0){let e=t.length-1;for(;e>=0&&/\s/.test(t.charAt(e));)e--;let n=e+1;for(;e>=0&&/[\w$]/.test(t.charAt(e));)e--;if(e++,e>0&&t.charAt(e-1)!==`"`){let r=t.slice(e,n);r.length>0&&/^[\w$]+$/.test(r)&&(t=`${t.slice(0,e)}"${r}"`)}}t+=a}return t}function tv(e){let t=[],n=``,r=0,i=null,a=!1;for(let o of e){if(a){n+=o,a=!1;continue}if(o===`\\`){n+=o,a=!0;continue}if(i!=null){n+=o,o===i&&(i=null);continue}if(o===`"`||o===`'`||o==="`"){n+=o,i=o;continue}if(o===`[`||o===`{`){r++,n+=o;continue}if(o===`]`||o===`}`){r--,n+=o;continue}if(o===`,`&&r===0){n.trim()!==``&&t.push(n.trim()),n=``;continue}n+=o}return n.trim()!==``&&t.push(n.trim()),t}function nv(e){return tv(e)}function rv(e){let t=null,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){n=!1;continue}if(i===`\\`){n=!0;continue}if(t!=null){i===t&&(t=null);continue}if(i===`"`||i===`'`||i==="`"){t=i;continue}if(i===`:`)return r}return-1}function iv(e,t){let n=e.attributes.find(e=>e.type===`mdxJsxAttribute`&&e.name===`when`);if(n?.type!==`mdxJsxAttribute`)return!0;if(typeof n.value==`string`)return n.value===`true`;if(n.value!=null&&typeof n.value==`object`&&n.value.type===`mdxJsxAttributeValueExpression`)try{let e=r_(n.value.value,t.scope);return e===`true`||e===`1`}catch{return!1}return!1}async function av(e,t,n){return!iv(e,t)||e.children.length===0?[]:n(e.children,t)}async function ov(e,t){if(!iv(e,t)||e.children.length===0)return[];let n=sv(e.children,t);return n===``?[]:[{type:`text`,value:n}]}function sv(e,t){let n=``;for(let r of e)if(r.type===`text`)n+=r.value;else if(r.type===`mdxTextExpression`)try{n+=r_(r.value,t.scope)}catch{}else `children`in r&&Array.isArray(r.children)&&(n+=sv(r.children,t));return n}function cv(){e_(`Md`,av),e_(`Md.Line`,ov)}cv();function lv(e,t){let n={};if(e!=null&&(n.os={...e.os},n.env={...e.env},n.profile={...e.profile},n.tool={...e.tool}),t!=null)for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=typeof r==`object`&&r&&!Array.isArray(r)&&typeof t==`object`&&t&&!Array.isArray(t)?{...t,...r}:r}return n}async function uv(e,t){let n=dh(e),r=lv(t?.globalScope,t?.scope),i=t_(),a;if(t?.extractMetadata===!0){let e=n.children.find(e=>e.type===`yaml`),i;if(e!=null)try{i=Og.parse(e.value)}catch{}a=K_(n.children.filter(e=>e.type===`mdxjsEsm`),{...i!=null&&{yamlFrontMatter:i},scope:r,...t?.basePath!=null&&{filePath:t.basePath}}),n.children=n.children.filter(e=>e.type!==`yaml`&&e.type!==`mdxjsEsm`)}let o=await B_(n,{scope:r,components:i,processingStack:[],...t?.basePath!=null&&{basePath:t.basePath}}),s=pu().use(ii,[`yaml`]).use(ql).use(G_,{bullet:`-`,fence:"`",fences:!0,emphasis:`*`,strong:`*`,rule:`-`,handlers:{text(e){return e.value}}}).stringify(o).trim();return t?.extractMetadata===!0&&a!=null?{content:s,metadata:a}:s}var dv=class extends Pg{commandsSubDir;agentsSubDir;skillsSubDir;supportsFastCommands;supportsSubAgents;supportsSkills;toolPreset;constructor(e,t){super(e,t),this.commandsSubDir=t.commandsSubDir??`commands`,this.agentsSubDir=t.agentsSubDir??`agents`,this.skillsSubDir=t.skillsSubDir??`skills`,this.supportsFastCommands=t.supportsFastCommands??!0,this.supportsSubAgents=t.supportsSubAgents??!0,this.supportsSkills=t.supportsSkills??!0,t.toolPreset!==void 0&&(this.toolPreset=t.toolPreset)}async registerGlobalOutputDirs(e){let t=this.getGlobalConfigDir(),n=[],r=[];this.supportsFastCommands&&r.push(this.commandsSubDir),this.supportsSubAgents&&r.push(this.agentsSubDir),this.supportsSkills&&r.push(this.skillsSubDir);for(let e of r)n.push(this.createRelativePath(e,t,()=>e));return n}async registerProjectOutputDirs(e){let t=[],{projects:n}=e.collectedInputContext.workspace,r=[];if(this.supportsFastCommands&&r.push(this.commandsSubDir),this.supportsSubAgents&&r.push(this.agentsSubDir),this.supportsSkills&&r.push(this.skillsSubDir),r.length===0)return[];for(let e of n)if(e.dirFromWorkspacePath!=null)for(let n of r){let r=f.join(e.dirFromWorkspacePath.path,this.globalConfigDir,n);t.push(this.createRelativePath(r,e.dirFromWorkspacePath.basePath,()=>n))}return t}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace;for(let e of n)if(e.rootMemoryPrompt!=null&&e.dirFromWorkspacePath!=null&&t.push(this.createFileRelativePath(e.dirFromWorkspacePath,this.outputFileName)),e.childMemoryPrompts!=null)for(let n of e.childMemoryPrompts)n.dir!=null&&this.isRelativePath(n.dir)&&t.push(this.createFileRelativePath(n.dir,this.outputFileName));return t}async registerGlobalOutputFiles(e){let{globalMemory:t}=e.collectedInputContext;if(t==null)return[];let n=this.getGlobalConfigDir(),r=[this.createRelativePath(this.outputFileName,n,()=>this.globalConfigDir)],{fastCommands:i,subAgents:a,skills:o}=e.collectedInputContext,s={includeSeriesPrefix:!0};if(this.supportsFastCommands&&i!=null)for(let e of i){let t=this.transformFastCommandName(e,s);r.push(this.createRelativePath(f.join(this.commandsSubDir,t),n,()=>this.commandsSubDir))}if(this.supportsSubAgents&&a!=null)for(let e of a){let t=e.dir.path.replace(/\.mdx$/,`.md`);r.push(this.createRelativePath(f.join(this.agentsSubDir,t),n,()=>this.agentsSubDir))}if(this.supportsSkills&&o!=null)for(let e of o){let t=e.yamlFrontMatter?.name??e.dir.getDirectoryName(),i=f.join(this.skillsSubDir,t);if(r.push(this.createRelativePath(f.join(i,`SKILL.md`),n,()=>t)),e.childDocs!=null)for(let a of e.childDocs){let e=a.dir.path.replace(/\.mdx$/,`.md`),o=f.join(i,e);r.push(this.createRelativePath(o,n,()=>t))}if(e.resources!=null)for(let a of e.resources){let e=f.join(i,a.relativePath);r.push(this.createRelativePath(e,n,()=>t))}}return r}async canWrite(e){let{workspace:t,globalMemory:n,fastCommands:r,subAgents:i,skills:a}=e.collectedInputContext,o=t.projects.some(e=>e.rootMemoryPrompt!=null||(e.childMemoryPrompts?.length??0)>0),s=n!=null,c=this.supportsFastCommands&&(r?.length??0)>0,l=this.supportsSubAgents&&(i?.length??0)>0,u=this.supportsSkills&&(a?.length??0)>0;return o||s||c||l||u?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,n=[],r=[];for(let r of t){let t=r.name??`unknown`,i=r.dirFromWorkspacePath;if(i!=null){if(r.rootMemoryPrompt!=null){let a=await this.writePromptFile(e,i,r.rootMemoryPrompt.content,`project:${t}/root`);n.push(a)}if(r.childMemoryPrompts!=null)for(let i of r.childMemoryPrompts){let r=await this.writePromptFile(e,i.dir,i.content,`project:${t}/child:${i.workingChildDirectoryPath?.path??`unknown`}`);n.push(r)}}}return{files:n,dirs:r}}async writeGlobalOutputs(e){let{globalMemory:t}=e.collectedInputContext,n=[],r=[];if([{enabled:!0,data:t},{enabled:this.supportsFastCommands,data:e.collectedInputContext.fastCommands},{enabled:this.supportsSubAgents,data:e.collectedInputContext.subAgents},{enabled:this.supportsSkills,data:e.collectedInputContext.skills}].every(e=>!e.enabled||e.data==null))return{files:n,dirs:r};let{fastCommands:i,subAgents:a,skills:o}=e.collectedInputContext,s=this.getGlobalConfigDir();if(t!=null){let r=f.join(s,this.outputFileName),i=this.createRelativePath(this.outputFileName,s,()=>this.globalConfigDir);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`globalMemory`,path:r}),n.push({path:i,success:!0,skipped:!1});else try{it(r,t.content),this.log.trace({action:`write`,type:`globalMemory`,path:r}),n.push({path:i,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`globalMemory`,path:r,error:t}),n.push({path:i,success:!1,error:e})}}if(this.supportsFastCommands&&i!=null)for(let t of i){let r=await this.writeFastCommand(e,s,t);n.push(...r)}if(this.supportsSubAgents&&a!=null)for(let t of a){let r=await this.writeSubAgent(e,s,t);n.push(...r)}if(this.supportsSkills&&o!=null)for(let t of o){let r=await this.writeSkill(e,s,t);n.push(...r)}return{files:n,dirs:r}}async writeFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),i=this.transformFastCommandName(n,r),a=f.join(t,this.commandsSubDir),o=f.join(a,i),s=n.content,c=n.yamlFrontMatter,l=!1;if(n.rawMdxContent!=null&&this.toolPreset!=null){this.log.debug(`recompiling fast command with tool preset`,{file:n.dir.getAbsolutePath(),toolPreset:this.toolPreset,hasRawContent:!0});try{let e=new or({toolPreset:this.toolPreset}).collect(),t=await uv(n.rawMdxContent,{globalScope:e,extractMetadata:!0,basePath:n.dir.basePath});s=t.content,c=t.metadata.fields,l=!0}catch(e){this.log.warn(`failed to recompile fast command, using default`,{file:n.dir.getAbsolutePath(),error:e instanceof Error?e.message:String(e)})}}let u=l?this.buildMarkdownContent(s,c):this.buildMarkdownContentWithRaw(s,c,n.rawFrontMatter);return[await this.writeFile(e,o,u,`fastCommand`)]}async writeSubAgent(e,t,n){let r=n.dir.path.replace(/\.mdx$/,`.md`),i=f.join(t,this.agentsSubDir),a=f.join(i,r),o=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);return[await this.writeFile(e,a,o,`subAgent`)]}async writeSkill(e,t,n){let r=[],i=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),a=f.join(t,this.skillsSubDir,i),o=f.join(a,`SKILL.md`),s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter),c=await this.writeFile(e,o,s,`skill`);if(r.push(c),n.childDocs!=null)for(let o of n.childDocs){let n=await this.writeSkillReferenceDocument(e,a,i,o,t);r.push(...n)}if(n.resources!=null)for(let o of n.resources){let n=await this.writeSkillResource(e,a,i,o,t);r.push(...n)}return r}async writeSkillReferenceDocument(e,t,n,r,i){let a=r.dir.path.replace(/\.mdx$/,`.md`),o=f.join(t,a);return[await this.writeFile(e,o,r.content,`skillRefDoc`)]}async writeSkillResource(e,t,n,r,i){let a=f.join(t,r.relativePath);return[await this.writeFile(e,a,r.content,`skillResource`)]}},fv=class extends dv{constructor(){super(`ClaudeCodeCLIOutputPlugin`,{globalConfigDir:`.claude`,outputFileName:`CLAUDE.md`,toolPreset:`claudeCode`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0})}};const pv=`AGENTS.md`,mv=`.codex`,hv=`prompts`,gv=`skills`;var _v=class extends Pg{constructor(){super(`CodexCLIOutputPlugin`,{globalConfigDir:mv,outputFileName:pv,dependsOn:[`AgentsOutputPlugin`]})}async registerProjectOutputDirs(){return[]}async registerProjectOutputFiles(){return[]}async registerGlobalOutputDirs(e){let t=this.getGlobalConfigDir(),n=[this.createRelativePath(hv,t,()=>hv)],{skills:r}=e.collectedInputContext;if(r!=null&&r.length>0)for(let e of r){let r=e.yamlFrontMatter?.name??e.dir.getDirectoryName();n.push(this.createRelativePath(f.join(gv,r),t,()=>r))}return n}async registerGlobalOutputFiles(){let e=this.getGlobalConfigDir();return[this.createRelativePath(pv,e,()=>mv)]}async canWrite(e){let{globalMemory:t,fastCommands:n,skills:r}=e.collectedInputContext;return t!=null||(n?.length??0)>0||(r?.length??0)>0?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(){return{files:[],dirs:[]}}async writeGlobalOutputs(e){let{globalMemory:t,fastCommands:n,skills:r}=e.collectedInputContext,i=[],a=this.getGlobalConfigDir();if(t!=null){let n=f.join(a,pv),r=await this.writeFile(e,n,t.content,`globalMemory`);i.push(r)}if(n!=null&&n.length>0)for(let t of n){let n=await this.writeGlobalFastCommand(e,a,t);i.push(n)}if(r!=null&&r.length>0)for(let t of r){let n=await this.writeGlobalSkill(e,a,t);i.push(...n)}return{files:i,dirs:[]}}async writeGlobalFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),i=this.transformFastCommandName(n,r),a=f.join(t,hv,i),o=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);return this.writeFile(e,a,o,`globalFastCommand`)}async writeGlobalSkill(e,t,n){let r=[],i=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),a=f.join(t,gv,i),o=f.join(a,`SKILL.md`),s=this.buildCodexSkillContent(n),c=await this.writeFile(e,o,s,`globalSkill`);if(r.push(c),n.childDocs!=null)for(let t of n.childDocs){let n=t.dir.path.replace(/\.mdx$/,`.md`),i=f.join(a,n),o=await this.writeFile(e,i,t.content,`skillRefDoc`);r.push(o)}if(n.resources!=null)for(let t of n.resources){let n=f.join(a,t.relativePath),i=await this.writeFile(e,n,t.content,`skillResource`);r.push(i)}return r}buildCodexSkillContent(e){let t=e.yamlFrontMatter,n=this.normalizeSkillName(t.name,64),r=this.normalizeToSingleLine(t.description,1024),i={};t.displayName!=null&&(i[`short-description`]=t.displayName),t.version!=null&&(i.version=t.version),t.author!=null&&(i.author=t.author),t.keywords!=null&&t.keywords.length>0&&(i.keywords=[...t.keywords]);let a={name:n,description:r};return Object.keys(i).length>0&&(a.metadata=i),t.allowTools!=null&&t.allowTools.length>0&&(a[`allowed-tools`]=t.allowTools.join(` `)),Ag(a,e.content)}normalizeSkillName(e,t){let n=e.toLowerCase().replaceAll(/[^a-z0-9-]/g,`-`).replaceAll(/-+/g,`-`).replaceAll(/^-+|-+$/g,``);return n.length>t&&(n=n.slice(0,t).replace(/-+$/,``)),n}normalizeToSingleLine(e,t){let n=e.replaceAll(/[\r\n]+/g,` `).replaceAll(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-3)}...`:n}};const vv=`.cursor`,yv=`mcp.json`,bv=`commands`,xv=`rules`,Sv=`global.mdc`,Cv=`skills-cursor`,wv=`SKILL.md`,Tv=new Set([`create-rule`,`create-skill`,`create-subagent`,`migrate-to-skills`,`update-cursor-settings`]);var Ev=class extends Pg{constructor(){super(`CursorOutputPlugin`,{globalConfigDir:vv,outputFileName:``,dependsOn:[`AgentsOutputPlugin`],indexignore:`.cursorignore`}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=this.getGlobalConfigDir(),n=f.join(t,yv),r={mcpServers:{}};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfigCleanup`,path:n}),{success:!0,description:`Would reset mcp.json to empty shell`};try{return this.ensureDirectory(t),d.writeFileSync(n,JSON.stringify(r,null,2)),this.log.trace({action:`clean`,type:`mcpConfigCleanup`,path:n}),{success:!0,description:`Reset mcp.json to empty shell`}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`clean`,type:`mcpConfigCleanup`,path:n,error:t}),{success:!1,error:e,description:`Failed to reset mcp.json`}}})}async registerGlobalOutputDirs(e){let t=[],n=this.getGlobalConfigDir(),{fastCommands:r,skills:i,rules:a}=e.collectedInputContext;if(r!=null&&r.length>0){let e=this.getGlobalCommandsDir();t.push({pathKind:L.Relative,path:bv,basePath:n,getDirectoryName:()=>bv,getAbsolutePath:()=>e})}if(i!=null&&i.length>0)for(let e of i){let r=e.yamlFrontMatter.name;if(this.isPreservedSkill(r))continue;let i=f.join(n,Cv,r);t.push({pathKind:L.Relative,path:f.join(Cv,r),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i})}let o=a?.filter(e=>e.scope===`global`);if(o==null||o.length===0)return t;let s=f.join(n,xv);return t.push({pathKind:L.Relative,path:xv,basePath:n,getDirectoryName:()=>xv,getAbsolutePath:()=>s}),t}async registerGlobalOutputFiles(e){let t=[],n=this.getGlobalConfigDir(),{skills:r,fastCommands:i}=e.collectedInputContext;if(r?.some(e=>e.mcpConfig!=null)??!1){let e=f.join(n,yv);t.push({pathKind:L.Relative,path:yv,basePath:n,getDirectoryName:()=>vv,getAbsolutePath:()=>e})}if(i!=null&&i.length>0){let r=this.getGlobalCommandsDir(),a=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});for(let e of i){let i=this.transformFastCommandName(e,a),o=f.join(r,i);t.push({pathKind:L.Relative,path:f.join(bv,i),basePath:n,getDirectoryName:()=>bv,getAbsolutePath:()=>o})}}let a=e.collectedInputContext.rules?.filter(e=>e.scope===`global`);if(a!=null&&a.length>0){let e=f.join(n,xv);for(let r of a){let i=this.buildRuleFileName(r),a=f.join(e,i);t.push({pathKind:L.Relative,path:f.join(xv,i),basePath:n,getDirectoryName:()=>xv,getAbsolutePath:()=>a})}}if(r==null||r.length===0)return t;let o=this.getSkillsCursorDir();for(let e of r){let r=e.yamlFrontMatter.name;if(this.isPreservedSkill(r))continue;let i=f.join(o,r);if(t.push({pathKind:L.Relative,path:f.join(Cv,r,wv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,wv)}),e.mcpConfig!=null&&t.push({pathKind:L.Relative,path:f.join(Cv,r,yv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,yv)}),e.childDocs!=null)for(let a of e.childDocs){let e=a.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:f.join(Cv,r,e),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,e)})}if(e.resources!=null)for(let a of e.resources)t.push({pathKind:L.Relative,path:f.join(Cv,r,a.relativePath),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,a.relativePath)})}return t}async registerProjectOutputDirs(e){let t=[],{workspace:n,globalMemory:r,rules:i}=e.collectedInputContext,a=i?.some(e=>e.scope===`project`)??!1;if(r==null&&!a)return t;for(let e of n.projects){let n=e.dirFromWorkspacePath;n!=null&&t.push(this.createProjectRulesDirRelativePath(n))}return t}async registerProjectOutputFiles(e){let t=[],{workspace:n,globalMemory:r,rules:i}=e.collectedInputContext,a=i?.filter(e=>e.scope===`project`),o=a!=null&&a.length>0;if(r==null&&!o)return t;if(r!=null)for(let e of n.projects){let n=e.dirFromWorkspacePath;n!=null&&t.push(this.createProjectRuleFileRelativePath(n,Sv))}if(o)for(let e of n.projects){let n=e.dirFromWorkspacePath;if(n!=null)for(let e of a){let r=this.buildRuleFileName(e);t.push(this.createProjectRuleFileRelativePath(n,r))}}return t.push(...this.registerProjectIgnoreOutputFiles(n.projects)),t}async canWrite(e){let{workspace:t,skills:n,fastCommands:r,globalMemory:i,rules:a,aiAgentIgnoreConfigFiles:o}=e.collectedInputContext,s=(n?.length??0)>0,c=(r?.length??0)>0,l=(a?.length??0)>0,u=i!=null&&t.projects.some(e=>e.dirFromWorkspacePath!=null),d=o?.some(e=>e.fileName===`.cursorignore`)??!1;return s||c||u||l||d?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeGlobalOutputs(e){let{skills:t,fastCommands:n,rules:r}=e.collectedInputContext,i=[],a=[];if(t!=null&&t.length>0){let n=await this.writeGlobalMcpConfig(e,t);n!=null&&i.push(n);let r=this.getSkillsCursorDir();for(let n of t){let t=n.yamlFrontMatter.name;if(this.isPreservedSkill(t))continue;let a=await this.writeGlobalSkill(e,r,n);i.push(...a)}}if(n!=null&&n.length>0){let t=this.getGlobalCommandsDir();for(let r of n){let n=await this.writeGlobalFastCommand(e,t,r);i.push(n)}}let o=r?.filter(e=>e.scope===`global`);if(o==null||o.length===0)return{files:i,dirs:a};let s=f.join(this.getGlobalConfigDir(),xv);for(let t of o){let n=await this.writeRuleMdcFile(e,s,t,this.getGlobalConfigDir());i.push(n)}return{files:i,dirs:a}}async writeProjectOutputs(e){let t=[],n=[],{workspace:r,globalMemory:i,rules:a}=e.collectedInputContext;if(i!=null){let n=this.buildGlobalRuleContent(i.content);for(let i of r.projects){if(i.dirFromWorkspacePath==null)continue;let r=await this.writeProjectGlobalRule(e,i,n);t.push(r)}}let o=a?.filter(e=>e.scope===`project`);if(o!=null&&o.length>0)for(let n of r.projects){let r=n.dirFromWorkspacePath;if(r==null)continue;let i=f.join(r.basePath,r.path,vv,xv);for(let n of o){let a=await this.writeRuleMdcFile(e,i,n,r.basePath);t.push(a)}}let s=await this.writeProjectIgnoreFiles(e);return t.push(...s),{files:t,dirs:n}}createProjectRulesDirRelativePath(e){let t=f.join(e.path,vv,xv);return{pathKind:L.Relative,path:t,basePath:e.basePath,getDirectoryName:()=>xv,getAbsolutePath:()=>f.join(e.basePath,t)}}createProjectRuleFileRelativePath(e,t){let n=f.join(e.path,vv,xv,t);return{pathKind:L.Relative,path:n,basePath:e.basePath,getDirectoryName:()=>xv,getAbsolutePath:()=>f.join(e.basePath,n)}}buildGlobalRuleContent(e){return Ag({description:`Global prompt (synced)`,alwaysApply:!0},e)}async writeProjectGlobalRule(e,t,n){let r=t.dirFromWorkspacePath,i=f.join(r.basePath,r.path,vv,xv),a=f.join(i,Sv),o=this.createProjectRuleFileRelativePath(r,Sv);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalRule`,path:a}),{path:o,success:!0,skipped:!1};try{return this.ensureDirectory(i),this.writeFileSync(a,n),this.log.trace({action:`write`,type:`globalRule`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalRule`,path:a,error:t}),{path:o,success:!1,error:e}}}isPreservedSkill(e){return Tv.has(e)}getSkillsCursorDir(){return f.join(this.getGlobalConfigDir(),Cv)}getGlobalCommandsDir(){return f.join(this.getGlobalConfigDir(),bv)}async writeGlobalFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),i=this.transformFastCommandName(n,r),a=f.join(t,i),o={pathKind:L.Relative,path:f.join(bv,i),basePath:this.getGlobalConfigDir(),getDirectoryName:()=>bv,getAbsolutePath:()=>a},s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalFastCommand`,path:a}),{path:o,success:!0,skipped:!1};try{return this.ensureDirectory(t),d.writeFileSync(a,s),this.log.trace({action:`write`,type:`globalFastCommand`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalFastCommand`,path:a,error:t}),{path:o,success:!1,error:e}}}async writeGlobalMcpConfig(e,t){let n={};for(let e of t){if(e.mcpConfig==null)continue;let{mcpServers:t}=e.mcpConfig;for(let[e,r]of Object.entries(t))n[e]=this.transformMcpConfigForCursor({...r})}if(Object.keys(n).length===0)return null;let r=this.getGlobalConfigDir(),i=f.join(r,yv),a={pathKind:L.Relative,path:yv,basePath:r,getDirectoryName:()=>vv,getAbsolutePath:()=>i},o={};try{if(this.existsSync(i)){let e=d.readFileSync(i,`utf8`);o=JSON.parse(e)}}catch{o={}}let s={...o.mcpServers??{},...n};o.mcpServers=s;let c=JSON.stringify(o,null,2);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalMcpConfig`,path:i,serverCount:Object.keys(n).length}),{path:a,success:!0,skipped:!1};try{return this.ensureDirectory(r),d.writeFileSync(i,c),this.log.trace({action:`write`,type:`globalMcpConfig`,path:i,serverCount:Object.keys(n).length}),{path:a,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalMcpConfig`,path:i,error:t}),{path:a,success:!1,error:e}}}transformMcpConfigForCursor(e){let t={};if(e.command!=null)return t.command=e.command,e.args!=null&&(t.args=e.args),e.env!=null&&(t.env=e.env),t;let n=e.url??e.serverUrl;return n==null?t:(t.url=n,e.headers!=null&&(t.headers=e.headers),t)}async writeGlobalSkill(e,t,n){let r=[],i=n.yamlFrontMatter.name,a=f.join(t,i),o=f.join(a,wv),s=this.getGlobalConfigDir(),c={pathKind:L.Relative,path:f.join(Cv,i,wv),basePath:s,getDirectoryName:()=>i,getAbsolutePath:()=>o},l=this.buildSkillFrontMatter(n),u=n.content,d=Ag(l,u);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`skill`,path:o}),r.push({path:c,success:!0,skipped:!1});else try{this.ensureDirectory(a),this.writeFileSync(o,d),this.log.trace({action:`write`,type:`skill`,path:o}),r.push({path:c,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skill`,path:o,error:t}),r.push({path:c,success:!1,error:e})}if(n.mcpConfig!=null){let t=await this.writeSkillMcpConfig(e,n,a,s);r.push(t)}if(n.childDocs!=null)for(let t of n.childDocs){let n=await this.writeSkillChildDoc(e,t,a,i,s);r.push(n)}if(n.resources!=null)for(let t of n.resources){let n=await this.writeSkillResource(e,t,a,i,s);r.push(n)}return r}buildSkillFrontMatter(e){let t=e.yamlFrontMatter;return{name:t.name,description:t.description,...t.displayName!=null&&{displayName:t.displayName},...t.keywords!=null&&t.keywords.length>0&&{keywords:t.keywords},...t.author!=null&&{author:t.author},...t.version!=null&&{version:t.version},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}async writeSkillMcpConfig(e,t,n,r){let i=t.yamlFrontMatter.name,a=f.join(n,yv),o={pathKind:L.Relative,path:f.join(Cv,i,yv),basePath:r,getDirectoryName:()=>i,getAbsolutePath:()=>a},s=t.mcpConfig.rawContent;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfig`,path:a}),{path:o,success:!0,skipped:!1};try{return this.ensureDirectory(n),this.writeFileSync(a,s),this.log.trace({action:`write`,type:`mcpConfig`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`mcpConfig`,path:a,error:t}),{path:o,success:!1,error:e}}}async writeSkillChildDoc(e,t,n,r,i){let a=t.relativePath.replace(/\.mdx$/,`.md`),o=f.join(n,a),s={pathKind:L.Relative,path:f.join(Cv,r,a),basePath:i,getDirectoryName:()=>r,getAbsolutePath:()=>o},c=t.content;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`childDoc`,path:o}),{path:s,success:!0,skipped:!1};try{let e=f.dirname(o);return this.ensureDirectory(e),this.writeFileSync(o,c),this.log.trace({action:`write`,type:`childDoc`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`childDoc`,path:o,error:t}),{path:s,success:!1,error:e}}}async writeSkillResource(e,t,n,r,i){let a=f.join(n,t.relativePath),o={pathKind:L.Relative,path:f.join(Cv,r,t.relativePath),basePath:i,getDirectoryName:()=>r,getAbsolutePath:()=>a};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`resource`,path:a}),{path:o,success:!0,skipped:!1};try{let e=f.dirname(a);if(this.ensureDirectory(e),t.encoding===`base64`){let e=h.Buffer.from(t.content,`base64`);this.writeFileSyncBuffer(a,e)}else this.writeFileSync(a,t.content);return this.log.trace({action:`write`,type:`resource`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`resource`,path:a,error:t}),{path:o,success:!1,error:e}}}buildRuleFileName(e){return`rule-${e.series}-${e.ruleName}.mdc`}buildRuleMdcContent(e){return Ag({alwaysApply:!1,globs:e.globs.length>0?e.globs.join(`, `):``},e.content).split(`
|
|
1230
|
+
`).replaceAll(`\\r`,`\r`).replaceAll(`\\t`,` `).replaceAll(`\\"`,`"`).replaceAll(`\\'`,`'`).replaceAll(`\\\\`,`\\`)}function Z_(e,t,n){if(t==null){let t=n==null?``:` in file "${n}"`;throw Error(`Variable reference "${e}" cannot be resolved without scope${t}`)}let r=e.split(`.`),i=r[0];if(i==null||!(i in t)){let r=n==null?``:` in file "${n}"`,a=Object.keys(t).join(`, `);throw Error(`Undefined namespace "${i}" in expression "${e}"${r}. Available: ${a}`)}let a=t[i];for(let t=1;t<r.length;t++){let i=r[t];if(i==null)continue;if(a==null){let t=n==null?``:` in file "${n}"`;throw Error(`Cannot read property "${i}" of null/undefined in "${e}"${t}`)}if(typeof a!=`object`){let t=n==null?``:` in file "${n}"`;throw Error(`Cannot read property "${i}" of ${typeof a} in "${e}"${t}`)}let o=a;if(!(i in o)){let t=n==null?``:` in file "${n}"`,r=Object.keys(o).join(`, `);throw Error(`Undefined property "${i}" in "${e}"${t}. Available: ${r}`)}a=o[i]}if(typeof a==`string`||typeof a==`number`||typeof a==`boolean`||a===null||Array.isArray(a)||typeof a==`object`)return a;let o=n==null?``:` in file "${n}"`;throw Error(`Variable "${e}" resolved to unsupported type: ${typeof a}${o}`)}function Q_(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return[];if(t==null)try{let t=ev(e),n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return tv(r).map(e=>Y_(e.trim(),t,n))}function $_(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return{};if(t==null)try{let t=ev(e),n=JSON.parse(t);if(typeof n==`object`&&n&&!Array.isArray(n))return n}catch{}let i={},a=nv(r);for(let e of a){let r=rv(e);if(r===-1)continue;let a=e.slice(0,r).trim(),o=e.slice(r+1).trim();(a.startsWith(`"`)&&a.endsWith(`"`)||a.startsWith(`'`)&&a.endsWith(`'`))&&(a=a.slice(1,-1)),i[a]=Y_(o,t,n)}return i}function ev(e){let t=``,n=null,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){t+=a,r=!1;continue}if(a===`\\`){t+=a,r=!0;continue}if(n!=null){a===n?(t+=`"`,n=null):a===`"`&&n===`'`?t+=`\\"`:t+=a;continue}if(a===`"`||a===`'`){t+=`"`,n=a;continue}if(a===`:`&&i>0){let e=t.length-1;for(;e>=0&&/\s/.test(t.charAt(e));)e--;let n=e+1;for(;e>=0&&/[\w$]/.test(t.charAt(e));)e--;if(e++,e>0&&t.charAt(e-1)!==`"`){let r=t.slice(e,n);r.length>0&&/^[\w$]+$/.test(r)&&(t=`${t.slice(0,e)}"${r}"`)}}t+=a}return t}function tv(e){let t=[],n=``,r=0,i=null,a=!1;for(let o of e){if(a){n+=o,a=!1;continue}if(o===`\\`){n+=o,a=!0;continue}if(i!=null){n+=o,o===i&&(i=null);continue}if(o===`"`||o===`'`||o==="`"){n+=o,i=o;continue}if(o===`[`||o===`{`){r++,n+=o;continue}if(o===`]`||o===`}`){r--,n+=o;continue}if(o===`,`&&r===0){n.trim()!==``&&t.push(n.trim()),n=``;continue}n+=o}return n.trim()!==``&&t.push(n.trim()),t}function nv(e){return tv(e)}function rv(e){let t=null,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){n=!1;continue}if(i===`\\`){n=!0;continue}if(t!=null){i===t&&(t=null);continue}if(i===`"`||i===`'`||i==="`"){t=i;continue}if(i===`:`)return r}return-1}function iv(e,t){let n=e.attributes.find(e=>e.type===`mdxJsxAttribute`&&e.name===`when`);if(n?.type!==`mdxJsxAttribute`)return!0;if(typeof n.value==`string`)return n.value===`true`;if(n.value!=null&&typeof n.value==`object`&&n.value.type===`mdxJsxAttributeValueExpression`)try{let e=r_(n.value.value,t.scope);return e===`true`||e===`1`}catch{return!1}return!1}async function av(e,t,n){return!iv(e,t)||e.children.length===0?[]:n(e.children,t)}async function ov(e,t){if(!iv(e,t)||e.children.length===0)return[];let n=sv(e.children,t);return n===``?[]:[{type:`text`,value:n}]}function sv(e,t){let n=``;for(let r of e)if(r.type===`text`)n+=r.value;else if(r.type===`mdxTextExpression`)try{n+=r_(r.value,t.scope)}catch{}else `children`in r&&Array.isArray(r.children)&&(n+=sv(r.children,t));return n}function cv(){e_(`Md`,av),e_(`Md.Line`,ov)}cv();function lv(e,t){let n={};if(e!=null&&(n.os={...e.os},n.env={...e.env},n.profile={...e.profile},n.tool={...e.tool}),t!=null)for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=typeof r==`object`&&r&&!Array.isArray(r)&&typeof t==`object`&&t&&!Array.isArray(t)?{...t,...r}:r}return n}async function uv(e,t){let n=dh(e),r=lv(t?.globalScope,t?.scope),i=t_(),a;if(t?.extractMetadata===!0){let e=n.children.find(e=>e.type===`yaml`),i;if(e!=null)try{i=Og.parse(e.value)}catch{}a=K_(n.children.filter(e=>e.type===`mdxjsEsm`),{...i!=null&&{yamlFrontMatter:i},scope:r,...t?.basePath!=null&&{filePath:t.basePath}}),n.children=n.children.filter(e=>e.type!==`yaml`&&e.type!==`mdxjsEsm`)}let o=await B_(n,{scope:r,components:i,processingStack:[],...t?.basePath!=null&&{basePath:t.basePath}}),s=pu().use(ii,[`yaml`]).use(ql).use(G_,{bullet:`-`,fence:"`",fences:!0,emphasis:`*`,strong:`*`,rule:`-`,handlers:{text(e){return e.value}}}).stringify(o).trim();return t?.extractMetadata===!0&&a!=null?{content:s,metadata:a}:s}var dv=class extends Pg{commandsSubDir;agentsSubDir;skillsSubDir;supportsFastCommands;supportsSubAgents;supportsSkills;toolPreset;constructor(e,t){super(e,t),this.commandsSubDir=t.commandsSubDir??`commands`,this.agentsSubDir=t.agentsSubDir??`agents`,this.skillsSubDir=t.skillsSubDir??`skills`,this.supportsFastCommands=t.supportsFastCommands??!0,this.supportsSubAgents=t.supportsSubAgents??!0,this.supportsSkills=t.supportsSkills??!0,t.toolPreset!==void 0&&(this.toolPreset=t.toolPreset)}async registerGlobalOutputDirs(e){let t=this.getGlobalConfigDir(),n=[],r=[];this.supportsFastCommands&&r.push(this.commandsSubDir),this.supportsSubAgents&&r.push(this.agentsSubDir),this.supportsSkills&&r.push(this.skillsSubDir);for(let e of r)n.push(this.createRelativePath(e,t,()=>e));return n}async registerProjectOutputDirs(e){let t=[],{projects:n}=e.collectedInputContext.workspace,r=[];if(this.supportsFastCommands&&r.push(this.commandsSubDir),this.supportsSubAgents&&r.push(this.agentsSubDir),this.supportsSkills&&r.push(this.skillsSubDir),r.length===0)return[];for(let e of n)if(e.dirFromWorkspacePath!=null)for(let n of r){let r=f.join(e.dirFromWorkspacePath.path,this.globalConfigDir,n);t.push(this.createRelativePath(r,e.dirFromWorkspacePath.basePath,()=>n))}return t}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace;for(let e of n)if(e.rootMemoryPrompt!=null&&e.dirFromWorkspacePath!=null&&t.push(this.createFileRelativePath(e.dirFromWorkspacePath,this.outputFileName)),e.childMemoryPrompts!=null)for(let n of e.childMemoryPrompts)n.dir!=null&&this.isRelativePath(n.dir)&&t.push(this.createFileRelativePath(n.dir,this.outputFileName));return t}async registerGlobalOutputFiles(e){let{globalMemory:t}=e.collectedInputContext;if(t==null)return[];let n=this.getGlobalConfigDir(),r=[this.createRelativePath(this.outputFileName,n,()=>this.globalConfigDir)],{fastCommands:i,subAgents:a,skills:o}=e.collectedInputContext,s={includeSeriesPrefix:!0};if(this.supportsFastCommands&&i!=null)for(let e of i){let t=this.transformFastCommandName(e,s);r.push(this.createRelativePath(f.join(this.commandsSubDir,t),n,()=>this.commandsSubDir))}if(this.supportsSubAgents&&a!=null)for(let e of a){let t=e.dir.path.replace(/\.mdx$/,`.md`);r.push(this.createRelativePath(f.join(this.agentsSubDir,t),n,()=>this.agentsSubDir))}if(this.supportsSkills&&o!=null)for(let e of o){let t=e.yamlFrontMatter?.name??e.dir.getDirectoryName(),i=f.join(this.skillsSubDir,t);if(r.push(this.createRelativePath(f.join(i,`SKILL.md`),n,()=>t)),e.childDocs!=null)for(let a of e.childDocs){let e=a.dir.path.replace(/\.mdx$/,`.md`),o=f.join(i,e);r.push(this.createRelativePath(o,n,()=>t))}if(e.resources!=null)for(let a of e.resources){let e=f.join(i,a.relativePath);r.push(this.createRelativePath(e,n,()=>t))}}return r}async canWrite(e){let{workspace:t,globalMemory:n,fastCommands:r,subAgents:i,skills:a}=e.collectedInputContext,o=t.projects.some(e=>e.rootMemoryPrompt!=null||(e.childMemoryPrompts?.length??0)>0),s=n!=null,c=this.supportsFastCommands&&(r?.length??0)>0,l=this.supportsSubAgents&&(i?.length??0)>0,u=this.supportsSkills&&(a?.length??0)>0;return o||s||c||l||u?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,n=[],r=[];for(let r of t){let t=r.name??`unknown`,i=r.dirFromWorkspacePath;if(i!=null){if(r.rootMemoryPrompt!=null){let a=await this.writePromptFile(e,i,r.rootMemoryPrompt.content,`project:${t}/root`);n.push(a)}if(r.childMemoryPrompts!=null)for(let i of r.childMemoryPrompts){let r=await this.writePromptFile(e,i.dir,i.content,`project:${t}/child:${i.workingChildDirectoryPath?.path??`unknown`}`);n.push(r)}}}return{files:n,dirs:r}}async writeGlobalOutputs(e){let{globalMemory:t}=e.collectedInputContext,n=[],r=[];if([{enabled:!0,data:t},{enabled:this.supportsFastCommands,data:e.collectedInputContext.fastCommands},{enabled:this.supportsSubAgents,data:e.collectedInputContext.subAgents},{enabled:this.supportsSkills,data:e.collectedInputContext.skills}].every(e=>!e.enabled||e.data==null))return{files:n,dirs:r};let{fastCommands:i,subAgents:a,skills:o}=e.collectedInputContext,s=this.getGlobalConfigDir();if(t!=null){let r=f.join(s,this.outputFileName),i=this.createRelativePath(this.outputFileName,s,()=>this.globalConfigDir);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`globalMemory`,path:r}),n.push({path:i,success:!0,skipped:!1});else try{it(r,t.content),this.log.trace({action:`write`,type:`globalMemory`,path:r}),n.push({path:i,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`globalMemory`,path:r,error:t}),n.push({path:i,success:!1,error:e})}}if(this.supportsFastCommands&&i!=null)for(let t of i){let r=await this.writeFastCommand(e,s,t);n.push(...r)}if(this.supportsSubAgents&&a!=null)for(let t of a){let r=await this.writeSubAgent(e,s,t);n.push(...r)}if(this.supportsSkills&&o!=null)for(let t of o){let r=await this.writeSkill(e,s,t);n.push(...r)}return{files:n,dirs:r}}async writeFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),i=this.transformFastCommandName(n,r),a=f.join(t,this.commandsSubDir),o=f.join(a,i),s=n.content,c=n.yamlFrontMatter,l=!1;if(n.rawMdxContent!=null&&this.toolPreset!=null){this.log.debug(`recompiling fast command with tool preset`,{file:n.dir.getAbsolutePath(),toolPreset:this.toolPreset,hasRawContent:!0});try{let e=new or({toolPreset:this.toolPreset}).collect(),t=await uv(n.rawMdxContent,{globalScope:e,extractMetadata:!0,basePath:n.dir.basePath});s=t.content,c=t.metadata.fields,l=!0}catch(e){this.log.warn(`failed to recompile fast command, using default`,{file:n.dir.getAbsolutePath(),error:e instanceof Error?e.message:String(e)})}}let u=l?this.buildMarkdownContent(s,c):this.buildMarkdownContentWithRaw(s,c,n.rawFrontMatter);return[await this.writeFile(e,o,u,`fastCommand`)]}async writeSubAgent(e,t,n){let r=n.dir.path.replace(/\.mdx$/,`.md`),i=f.join(t,this.agentsSubDir),a=f.join(i,r),o=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);return[await this.writeFile(e,a,o,`subAgent`)]}async writeSkill(e,t,n){let r=[],i=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),a=f.join(t,this.skillsSubDir,i),o=f.join(a,`SKILL.md`),s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter),c=await this.writeFile(e,o,s,`skill`);if(r.push(c),n.childDocs!=null)for(let o of n.childDocs){let n=await this.writeSkillReferenceDocument(e,a,i,o,t);r.push(...n)}if(n.resources!=null)for(let o of n.resources){let n=await this.writeSkillResource(e,a,i,o,t);r.push(...n)}return r}async writeSkillReferenceDocument(e,t,n,r,i){let a=r.dir.path.replace(/\.mdx$/,`.md`),o=f.join(t,a);return[await this.writeFile(e,o,r.content,`skillRefDoc`)]}async writeSkillResource(e,t,n,r,i){let a=f.join(t,r.relativePath);return[await this.writeFile(e,a,r.content,`skillResource`)]}normalizeRuleScope(e){return e.scope??`project`}};const fv=`rules`;var pv=class extends dv{constructor(){super(`ClaudeCodeCLIOutputPlugin`,{globalConfigDir:`.claude`,outputFileName:`CLAUDE.md`,toolPreset:`claudeCode`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0})}buildRuleFileName(e){return`rule-${e.series}-${e.ruleName}.md`}buildRuleContent(e){return e.globs.length===0?e.content:this.buildMarkdownContent(e.content,{paths:[...e.globs]})}async registerGlobalOutputDirs(e){let t=await super.registerGlobalOutputDirs(e),n=e.collectedInputContext.rules?.filter(e=>this.normalizeRuleScope(e)===`global`);return n!=null&&n.length>0&&t.push(this.createRelativePath(fv,this.getGlobalConfigDir(),()=>fv)),t}async registerGlobalOutputFiles(e){let t=await super.registerGlobalOutputFiles(e),n=e.collectedInputContext.rules?.filter(e=>this.normalizeRuleScope(e)===`global`);if(n==null||n.length===0)return t;let r=f.join(this.getGlobalConfigDir(),fv);for(let e of n)t.push(this.createRelativePath(this.buildRuleFileName(e),r,()=>fv));return t}async registerProjectOutputDirs(e){let t=await super.registerProjectOutputDirs(e),n=e.collectedInputContext.rules?.filter(e=>this.normalizeRuleScope(e)===`project`);if(n==null||n.length===0)return t;for(let n of e.collectedInputContext.workspace.projects){if(n.dirFromWorkspacePath==null)continue;let e=f.join(n.dirFromWorkspacePath.path,this.globalConfigDir,fv);t.push(this.createRelativePath(e,n.dirFromWorkspacePath.basePath,()=>fv))}return t}async registerProjectOutputFiles(e){let t=await super.registerProjectOutputFiles(e),n=e.collectedInputContext.rules?.filter(e=>this.normalizeRuleScope(e)===`project`);if(n==null||n.length===0)return t;for(let r of e.collectedInputContext.workspace.projects)if(r.dirFromWorkspacePath!=null)for(let e of n){let n=f.join(r.dirFromWorkspacePath.path,this.globalConfigDir,fv,this.buildRuleFileName(e));t.push(this.createRelativePath(n,r.dirFromWorkspacePath.basePath,()=>fv))}return t}async canWrite(e){return(e.collectedInputContext.rules?.length??0)>0?!0:super.canWrite(e)}async writeGlobalOutputs(e){let t=await super.writeGlobalOutputs(e),n=e.collectedInputContext.rules?.filter(e=>this.normalizeRuleScope(e)===`global`);if(n==null||n.length===0)return t;let r=f.join(this.getGlobalConfigDir(),fv),i=[];for(let t of n)i.push(await this.writeFile(e,f.join(r,this.buildRuleFileName(t)),this.buildRuleContent(t),`rule`));return{files:[...t.files,...i],dirs:t.dirs}}async writeProjectOutputs(e){let t=await super.writeProjectOutputs(e),n=e.collectedInputContext.rules?.filter(e=>this.normalizeRuleScope(e)===`project`);if(n==null||n.length===0)return t;let r=[];for(let t of e.collectedInputContext.workspace.projects){if(t.dirFromWorkspacePath==null)continue;let i=f.join(t.dirFromWorkspacePath.basePath,t.dirFromWorkspacePath.path,this.globalConfigDir,fv);for(let t of n)r.push(await this.writeFile(e,f.join(i,this.buildRuleFileName(t)),this.buildRuleContent(t),`rule`))}return{files:[...t.files,...r],dirs:t.dirs}}};const mv=`AGENTS.md`,hv=`.codex`,gv=`prompts`,_v=`skills`;var vv=class extends Pg{constructor(){super(`CodexCLIOutputPlugin`,{globalConfigDir:hv,outputFileName:mv,dependsOn:[`AgentsOutputPlugin`]})}async registerProjectOutputDirs(){return[]}async registerProjectOutputFiles(){return[]}async registerGlobalOutputDirs(e){let t=this.getGlobalConfigDir(),n=[this.createRelativePath(gv,t,()=>gv)],{skills:r}=e.collectedInputContext;if(r!=null&&r.length>0)for(let e of r){let r=e.yamlFrontMatter?.name??e.dir.getDirectoryName();n.push(this.createRelativePath(f.join(_v,r),t,()=>r))}return n}async registerGlobalOutputFiles(){let e=this.getGlobalConfigDir();return[this.createRelativePath(mv,e,()=>hv)]}async canWrite(e){let{globalMemory:t,fastCommands:n,skills:r}=e.collectedInputContext;return t!=null||(n?.length??0)>0||(r?.length??0)>0?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(){return{files:[],dirs:[]}}async writeGlobalOutputs(e){let{globalMemory:t,fastCommands:n,skills:r}=e.collectedInputContext,i=[],a=this.getGlobalConfigDir();if(t!=null){let n=f.join(a,mv),r=await this.writeFile(e,n,t.content,`globalMemory`);i.push(r)}if(n!=null&&n.length>0)for(let t of n){let n=await this.writeGlobalFastCommand(e,a,t);i.push(n)}if(r!=null&&r.length>0)for(let t of r){let n=await this.writeGlobalSkill(e,a,t);i.push(...n)}return{files:i,dirs:[]}}async writeGlobalFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),i=this.transformFastCommandName(n,r),a=f.join(t,gv,i),o=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);return this.writeFile(e,a,o,`globalFastCommand`)}async writeGlobalSkill(e,t,n){let r=[],i=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),a=f.join(t,_v,i),o=f.join(a,`SKILL.md`),s=this.buildCodexSkillContent(n),c=await this.writeFile(e,o,s,`globalSkill`);if(r.push(c),n.childDocs!=null)for(let t of n.childDocs){let n=t.dir.path.replace(/\.mdx$/,`.md`),i=f.join(a,n),o=await this.writeFile(e,i,t.content,`skillRefDoc`);r.push(o)}if(n.resources!=null)for(let t of n.resources){let n=f.join(a,t.relativePath),i=await this.writeFile(e,n,t.content,`skillResource`);r.push(i)}return r}buildCodexSkillContent(e){let t=e.yamlFrontMatter,n=this.normalizeSkillName(t.name,64),r=this.normalizeToSingleLine(t.description,1024),i={};t.displayName!=null&&(i[`short-description`]=t.displayName),t.version!=null&&(i.version=t.version),t.author!=null&&(i.author=t.author),t.keywords!=null&&t.keywords.length>0&&(i.keywords=[...t.keywords]);let a={name:n,description:r};return Object.keys(i).length>0&&(a.metadata=i),t.allowTools!=null&&t.allowTools.length>0&&(a[`allowed-tools`]=t.allowTools.join(` `)),Ag(a,e.content)}normalizeSkillName(e,t){let n=e.toLowerCase().replaceAll(/[^a-z0-9-]/g,`-`).replaceAll(/-+/g,`-`).replaceAll(/^-+|-+$/g,``);return n.length>t&&(n=n.slice(0,t).replace(/-+$/,``)),n}normalizeToSingleLine(e,t){let n=e.replaceAll(/[\r\n]+/g,` `).replaceAll(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-3)}...`:n}};const yv=`.cursor`,bv=`mcp.json`,xv=`commands`,Sv=`rules`,Cv=`global.mdc`,wv=`skills-cursor`,Tv=`SKILL.md`,Ev=new Set([`create-rule`,`create-skill`,`create-subagent`,`migrate-to-skills`,`update-cursor-settings`]);var Dv=class extends Pg{constructor(){super(`CursorOutputPlugin`,{globalConfigDir:yv,outputFileName:``,dependsOn:[`AgentsOutputPlugin`],indexignore:`.cursorignore`}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=this.getGlobalConfigDir(),n=f.join(t,bv),r={mcpServers:{}};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfigCleanup`,path:n}),{success:!0,description:`Would reset mcp.json to empty shell`};try{return this.ensureDirectory(t),d.writeFileSync(n,JSON.stringify(r,null,2)),this.log.trace({action:`clean`,type:`mcpConfigCleanup`,path:n}),{success:!0,description:`Reset mcp.json to empty shell`}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`clean`,type:`mcpConfigCleanup`,path:n,error:t}),{success:!1,error:e,description:`Failed to reset mcp.json`}}})}async registerGlobalOutputDirs(e){let t=[],n=this.getGlobalConfigDir(),{fastCommands:r,skills:i,rules:a}=e.collectedInputContext;if(r!=null&&r.length>0){let e=this.getGlobalCommandsDir();t.push({pathKind:L.Relative,path:xv,basePath:n,getDirectoryName:()=>xv,getAbsolutePath:()=>e})}if(i!=null&&i.length>0)for(let e of i){let r=e.yamlFrontMatter.name;if(this.isPreservedSkill(r))continue;let i=f.join(n,wv,r);t.push({pathKind:L.Relative,path:f.join(wv,r),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i})}let o=a?.filter(e=>this.normalizeRuleScope(e)===`global`);if(o==null||o.length===0)return t;let s=f.join(n,Sv);return t.push({pathKind:L.Relative,path:Sv,basePath:n,getDirectoryName:()=>Sv,getAbsolutePath:()=>s}),t}async registerGlobalOutputFiles(e){let t=[],n=this.getGlobalConfigDir(),{skills:r,fastCommands:i}=e.collectedInputContext;if(r?.some(e=>e.mcpConfig!=null)??!1){let e=f.join(n,bv);t.push({pathKind:L.Relative,path:bv,basePath:n,getDirectoryName:()=>yv,getAbsolutePath:()=>e})}if(i!=null&&i.length>0){let r=this.getGlobalCommandsDir(),a=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});for(let e of i){let i=this.transformFastCommandName(e,a),o=f.join(r,i);t.push({pathKind:L.Relative,path:f.join(xv,i),basePath:n,getDirectoryName:()=>xv,getAbsolutePath:()=>o})}}let a=e.collectedInputContext.rules?.filter(e=>this.normalizeRuleScope(e)===`global`);if(a!=null&&a.length>0){let e=f.join(n,Sv);for(let r of a){let i=this.buildRuleFileName(r),a=f.join(e,i);t.push({pathKind:L.Relative,path:f.join(Sv,i),basePath:n,getDirectoryName:()=>Sv,getAbsolutePath:()=>a})}}if(r==null||r.length===0)return t;let o=this.getSkillsCursorDir();for(let e of r){let r=e.yamlFrontMatter.name;if(this.isPreservedSkill(r))continue;let i=f.join(o,r);if(t.push({pathKind:L.Relative,path:f.join(wv,r,Tv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,Tv)}),e.mcpConfig!=null&&t.push({pathKind:L.Relative,path:f.join(wv,r,bv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,bv)}),e.childDocs!=null)for(let a of e.childDocs){let e=a.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:f.join(wv,r,e),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,e)})}if(e.resources!=null)for(let a of e.resources)t.push({pathKind:L.Relative,path:f.join(wv,r,a.relativePath),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,a.relativePath)})}return t}async registerProjectOutputDirs(e){let t=[],{workspace:n,globalMemory:r,rules:i}=e.collectedInputContext,a=i?.some(e=>this.normalizeRuleScope(e)===`project`)??!1;if(r==null&&!a)return t;for(let e of n.projects){let n=e.dirFromWorkspacePath;n!=null&&t.push(this.createProjectRulesDirRelativePath(n))}return t}async registerProjectOutputFiles(e){let t=[],{workspace:n,globalMemory:r,rules:i}=e.collectedInputContext,a=i?.filter(e=>this.normalizeRuleScope(e)===`project`),o=a!=null&&a.length>0;if(r==null&&!o)return t;if(r!=null)for(let e of n.projects){let n=e.dirFromWorkspacePath;n!=null&&t.push(this.createProjectRuleFileRelativePath(n,Cv))}if(o)for(let e of n.projects){let n=e.dirFromWorkspacePath;if(n!=null)for(let e of a){let r=this.buildRuleFileName(e);t.push(this.createProjectRuleFileRelativePath(n,r))}}return t.push(...this.registerProjectIgnoreOutputFiles(n.projects)),t}async canWrite(e){let{workspace:t,skills:n,fastCommands:r,globalMemory:i,rules:a,aiAgentIgnoreConfigFiles:o}=e.collectedInputContext,s=(n?.length??0)>0,c=(r?.length??0)>0,l=(a?.length??0)>0,u=i!=null&&t.projects.some(e=>e.dirFromWorkspacePath!=null),d=o?.some(e=>e.fileName===`.cursorignore`)??!1;return s||c||u||l||d?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeGlobalOutputs(e){let{skills:t,fastCommands:n,rules:r}=e.collectedInputContext,i=[],a=[];if(t!=null&&t.length>0){let n=await this.writeGlobalMcpConfig(e,t);n!=null&&i.push(n);let r=this.getSkillsCursorDir();for(let n of t){let t=n.yamlFrontMatter.name;if(this.isPreservedSkill(t))continue;let a=await this.writeGlobalSkill(e,r,n);i.push(...a)}}if(n!=null&&n.length>0){let t=this.getGlobalCommandsDir();for(let r of n){let n=await this.writeGlobalFastCommand(e,t,r);i.push(n)}}let o=r?.filter(e=>this.normalizeRuleScope(e)===`global`);if(o==null||o.length===0)return{files:i,dirs:a};let s=f.join(this.getGlobalConfigDir(),Sv);for(let t of o){let n=await this.writeRuleMdcFile(e,s,t,this.getGlobalConfigDir());i.push(n)}return{files:i,dirs:a}}async writeProjectOutputs(e){let t=[],n=[],{workspace:r,globalMemory:i,rules:a}=e.collectedInputContext;if(i!=null){let n=this.buildGlobalRuleContent(i.content);for(let i of r.projects){if(i.dirFromWorkspacePath==null)continue;let r=await this.writeProjectGlobalRule(e,i,n);t.push(r)}}let o=a?.filter(e=>this.normalizeRuleScope(e)===`project`);if(o!=null&&o.length>0)for(let n of r.projects){let r=n.dirFromWorkspacePath;if(r==null)continue;let i=f.join(r.basePath,r.path,yv,Sv);for(let n of o){let a=await this.writeRuleMdcFile(e,i,n,r.basePath);t.push(a)}}let s=await this.writeProjectIgnoreFiles(e);return t.push(...s),{files:t,dirs:n}}createProjectRulesDirRelativePath(e){let t=f.join(e.path,yv,Sv);return{pathKind:L.Relative,path:t,basePath:e.basePath,getDirectoryName:()=>Sv,getAbsolutePath:()=>f.join(e.basePath,t)}}createProjectRuleFileRelativePath(e,t){let n=f.join(e.path,yv,Sv,t);return{pathKind:L.Relative,path:n,basePath:e.basePath,getDirectoryName:()=>Sv,getAbsolutePath:()=>f.join(e.basePath,n)}}buildGlobalRuleContent(e){return Ag({description:`Global prompt (synced)`,alwaysApply:!0},e)}async writeProjectGlobalRule(e,t,n){let r=t.dirFromWorkspacePath,i=f.join(r.basePath,r.path,yv,Sv),a=f.join(i,Cv),o=this.createProjectRuleFileRelativePath(r,Cv);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalRule`,path:a}),{path:o,success:!0,skipped:!1};try{return this.ensureDirectory(i),this.writeFileSync(a,n),this.log.trace({action:`write`,type:`globalRule`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalRule`,path:a,error:t}),{path:o,success:!1,error:e}}}isPreservedSkill(e){return Ev.has(e)}getSkillsCursorDir(){return f.join(this.getGlobalConfigDir(),wv)}getGlobalCommandsDir(){return f.join(this.getGlobalConfigDir(),xv)}async writeGlobalFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),i=this.transformFastCommandName(n,r),a=f.join(t,i),o={pathKind:L.Relative,path:f.join(xv,i),basePath:this.getGlobalConfigDir(),getDirectoryName:()=>xv,getAbsolutePath:()=>a},s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalFastCommand`,path:a}),{path:o,success:!0,skipped:!1};try{return this.ensureDirectory(t),d.writeFileSync(a,s),this.log.trace({action:`write`,type:`globalFastCommand`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalFastCommand`,path:a,error:t}),{path:o,success:!1,error:e}}}async writeGlobalMcpConfig(e,t){let n={};for(let e of t){if(e.mcpConfig==null)continue;let{mcpServers:t}=e.mcpConfig;for(let[e,r]of Object.entries(t))n[e]=this.transformMcpConfigForCursor({...r})}if(Object.keys(n).length===0)return null;let r=this.getGlobalConfigDir(),i=f.join(r,bv),a={pathKind:L.Relative,path:bv,basePath:r,getDirectoryName:()=>yv,getAbsolutePath:()=>i},o={};try{if(this.existsSync(i)){let e=d.readFileSync(i,`utf8`);o=JSON.parse(e)}}catch{o={}}let s={...o.mcpServers??{},...n};o.mcpServers=s;let c=JSON.stringify(o,null,2);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalMcpConfig`,path:i,serverCount:Object.keys(n).length}),{path:a,success:!0,skipped:!1};try{return this.ensureDirectory(r),d.writeFileSync(i,c),this.log.trace({action:`write`,type:`globalMcpConfig`,path:i,serverCount:Object.keys(n).length}),{path:a,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalMcpConfig`,path:i,error:t}),{path:a,success:!1,error:e}}}transformMcpConfigForCursor(e){let t={};if(e.command!=null)return t.command=e.command,e.args!=null&&(t.args=e.args),e.env!=null&&(t.env=e.env),t;let n=e.url??e.serverUrl;return n==null?t:(t.url=n,e.headers!=null&&(t.headers=e.headers),t)}async writeGlobalSkill(e,t,n){let r=[],i=n.yamlFrontMatter.name,a=f.join(t,i),o=f.join(a,Tv),s=this.getGlobalConfigDir(),c={pathKind:L.Relative,path:f.join(wv,i,Tv),basePath:s,getDirectoryName:()=>i,getAbsolutePath:()=>o},l=this.buildSkillFrontMatter(n),u=n.content,d=Ag(l,u);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`skill`,path:o}),r.push({path:c,success:!0,skipped:!1});else try{this.ensureDirectory(a),this.writeFileSync(o,d),this.log.trace({action:`write`,type:`skill`,path:o}),r.push({path:c,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skill`,path:o,error:t}),r.push({path:c,success:!1,error:e})}if(n.mcpConfig!=null){let t=await this.writeSkillMcpConfig(e,n,a,s);r.push(t)}if(n.childDocs!=null)for(let t of n.childDocs){let n=await this.writeSkillChildDoc(e,t,a,i,s);r.push(n)}if(n.resources!=null)for(let t of n.resources){let n=await this.writeSkillResource(e,t,a,i,s);r.push(n)}return r}buildSkillFrontMatter(e){let t=e.yamlFrontMatter;return{name:t.name,description:t.description,...t.displayName!=null&&{displayName:t.displayName},...t.keywords!=null&&t.keywords.length>0&&{keywords:t.keywords},...t.author!=null&&{author:t.author},...t.version!=null&&{version:t.version},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}async writeSkillMcpConfig(e,t,n,r){let i=t.yamlFrontMatter.name,a=f.join(n,bv),o={pathKind:L.Relative,path:f.join(wv,i,bv),basePath:r,getDirectoryName:()=>i,getAbsolutePath:()=>a},s=t.mcpConfig.rawContent;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfig`,path:a}),{path:o,success:!0,skipped:!1};try{return this.ensureDirectory(n),this.writeFileSync(a,s),this.log.trace({action:`write`,type:`mcpConfig`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`mcpConfig`,path:a,error:t}),{path:o,success:!1,error:e}}}async writeSkillChildDoc(e,t,n,r,i){let a=t.relativePath.replace(/\.mdx$/,`.md`),o=f.join(n,a),s={pathKind:L.Relative,path:f.join(wv,r,a),basePath:i,getDirectoryName:()=>r,getAbsolutePath:()=>o},c=t.content;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`childDoc`,path:o}),{path:s,success:!0,skipped:!1};try{let e=f.dirname(o);return this.ensureDirectory(e),this.writeFileSync(o,c),this.log.trace({action:`write`,type:`childDoc`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`childDoc`,path:o,error:t}),{path:s,success:!1,error:e}}}async writeSkillResource(e,t,n,r,i){let a=f.join(n,t.relativePath),o={pathKind:L.Relative,path:f.join(wv,r,t.relativePath),basePath:i,getDirectoryName:()=>r,getAbsolutePath:()=>a};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`resource`,path:a}),{path:o,success:!0,skipped:!1};try{let e=f.dirname(a);if(this.ensureDirectory(e),t.encoding===`base64`){let e=h.Buffer.from(t.content,`base64`);this.writeFileSyncBuffer(a,e)}else this.writeFileSync(a,t.content);return this.log.trace({action:`write`,type:`resource`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`resource`,path:a,error:t}),{path:o,success:!1,error:e}}}buildRuleFileName(e){return`rule-${e.series}-${e.ruleName}.mdc`}buildRuleMdcContent(e){return Ag({alwaysApply:!1,globs:e.globs.length>0?e.globs.join(`, `):``},e.content).split(`
|
|
1231
1231
|
`).map(e=>{let t=/^(\s*globs:\s*)(['"])(.*)\2\s*$/.exec(e);if(t==null)return e;let n=t[1]??`globs: `,r=t[3]??``;return r.trim().length===0?e:`${n}${r}`}).join(`
|
|
1232
|
-
`)}async writeRuleMdcFile(e,t,n,r){let i=this.buildRuleFileName(n),a=f.join(t,i),o={pathKind:L.Relative,path:f.join(vv,xv,i),basePath:r,getDirectoryName:()=>xv,getAbsolutePath:()=>a},s=this.buildRuleMdcContent(n);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`ruleFile`,path:a}),{path:o,success:!0,skipped:!1};try{return this.ensureDirectory(t),this.writeFileSync(a,s),this.log.trace({action:`write`,type:`ruleFile`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`ruleFile`,path:a,error:t}),{path:o,success:!1,error:e}}}},Dv=class extends dv{constructor(){super(`DroidCLIOutputPlugin`,{globalConfigDir:`.factory`,outputFileName:`AGENTS.md`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0})}async writeSkill(e,t,n){let r=[],i=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),a=f.join(t,this.skillsSubDir,i),o=f.join(a,`SKILL.md`),s=n.yamlFrontMatter==null?void 0:{name:n.yamlFrontMatter.name,description:n.yamlFrontMatter.description},c=this.buildMarkdownContent(n.content,s),l=await this.writeFile(e,o,c,`skill`);if(r.push(l),n.childDocs!=null)for(let o of n.childDocs){let n=await this.writeSkillReferenceDocument(e,a,i,o,t);r.push(...n)}if(n.resources!=null)for(let o of n.resources){let n=await this.writeSkillResource(e,a,i,o,t);r.push(...n)}return r}},Ov=class extends Lg{configKey;extension;constructor(e,t){super(e),this.configKey=t.configKey,this.extension=t.extension??`.mdx`}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i,globalScope:a}=e,o=this.resolveBasePaths(t),s=this.getTargetDir(t,o),c=[];if(!(i.existsSync(s)&&i.statSync(s).isDirectory()))return this.createResult(c);try{let e=i.readdirSync(s,{withFileTypes:!0});for(let t of e)if(t.isFile()&&t.name.endsWith(this.extension)){let e=r.join(s,t.name),o=i.readFileSync(e,`utf8`);try{let r=jg(o),i=await uv(o,{globalScope:a,extractMetadata:!0,basePath:s}),l=r.yamlFrontMatter!=null||Object.keys(i.metadata.fields).length>0?{...r.yamlFrontMatter,...i.metadata.fields}:void 0;if(l!=null){let t=this.validateMetadata(l,e);for(let e of t.warnings)n.debug(e);if(!t.valid)throw new Xg([...t.errors],e)}let{content:u}=i;n.debug(`${this.name} metadata extracted`,{file:t.name,source:i.metadata.source,hasYaml:r.yamlFrontMatter!=null,hasExport:Object.keys(i.metadata.fields).length>0});let d=this.createPrompt(t.name,e,u,l,r.rawFrontMatter,r,s,o);c.push(d)}catch(t){n.error(`failed to parse ${this.name} item`,{file:e,error:t})}}}catch(e){n.error(`Failed to scan directory at ${s}`,{error:e})}return this.createResult(c)}},kv=class extends Ov{constructor(){super(`FastCommandInputPlugin`,{configKey:`shadowSourceProject.fastCommand.dist`})}getTargetDir(e,t){return this.resolveShadowPath(e.shadowSourceProject.fastCommand.dist,t.shadowProjectDir)}validateMetadata(e,t){return jt(e,t)}createResult(e){return{fastCommands:e}}extractSeriesInfo(e,t){let n=e.replace(/\.mdx$/,``);if(t!=null)return{series:t,commandName:n};let r=n.indexOf(`_`);return r===-1?{commandName:n}:{series:n.slice(0,Math.max(0,r)),commandName:n.slice(Math.max(0,r+1))}}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i}=e,a=this.resolveBasePaths(t),o=this.getTargetDir(t,a),s=[];if(!(i.existsSync(o)&&i.statSync(o).isDirectory()))return this.createResult(s);try{let t=i.readdirSync(o,{withFileTypes:!0});for(let a of t)if(a.isFile()&&a.name.endsWith(this.extension)){let t=await this.processFile(a.name,r.join(o,a.name),o,void 0,e);t!=null&&s.push(t)}else if(a.isDirectory()){let t=r.join(o,a.name);try{let n=i.readdirSync(t,{withFileTypes:!0});for(let i of n)if(i.isFile()&&i.name.endsWith(this.extension)){let n=await this.processFile(i.name,r.join(t,i.name),o,a.name,e);n!=null&&s.push(n)}}catch(e){n.error(`Failed to scan subdirectory at ${t}`,{error:e})}}}catch(e){n.error(`Failed to scan directory at ${o}`,{error:e})}return this.createResult(s)}async processFile(e,t,n,r,i){let{logger:a,globalScope:o}=i,s=i.fs.readFileSync(t,`utf8`);try{let c=jg(s),l=await uv(s,{globalScope:o,extractMetadata:!0,basePath:r==null?n:i.path.join(n,r)}),u=c.yamlFrontMatter!=null||Object.keys(l.metadata.fields).length>0?{...c.yamlFrontMatter,...l.metadata.fields}:void 0;if(u!=null){let e=this.validateMetadata(u,t);for(let t of e.warnings)a.debug(t);if(!e.valid)throw new Xg([...e.errors],t)}let{content:d}=l,f=r==null?e:`${r}/${e}`;return a.debug(`${this.name} metadata extracted`,{file:f,source:l.metadata.source,hasYaml:c.yamlFrontMatter!=null,hasExport:Object.keys(l.metadata.fields).length>0}),this.createPrompt(f,t,d,u,c.rawFrontMatter,c,n,s)}catch(e){a.error(`failed to parse ${this.name} item`,{file:t,error:e});return}}createPrompt(e,t,n,r,i,a,o,s){let c=e.indexOf(`/`),l=c===-1?void 0:e.slice(0,c),u=c===-1?e:e.slice(c+1),d=this.extractSeriesInfo(u,l);return{type:xt.FastCommand,content:n,length:n.length,filePathKind:L.Relative,...r!=null&&{yamlFrontMatter:r},...i!=null&&{rawFrontMatter:i},markdownAst:a.markdownAst,markdownContents:a.markdownContents,dir:{pathKind:L.Relative,path:e,basePath:o,getDirectoryName:()=>e.replace(/\.mdx$/,``),getAbsolutePath:()=>t},...d.series!=null&&{series:d.series},commandName:d.commandName,rawMdxContent:s}}},Av=class extends dv{constructor(){super(`GeminiCLIOutputPlugin`,{globalConfigDir:`.gemini`,outputFileName:`GEMINI.md`,supportsFastCommands:!1,supportsSubAgents:!1,supportsSkills:!1})}};const jv=`.skills`,Mv=`.aindex/.skills`,Nv=`SKILL.md`,Pv=`mcp.json`;var Fv=class extends Pg{constructor(){super(`GenericSkillsOutputPlugin`,{globalConfigDir:Mv,outputFileName:Nv}),this.registerCleanEffect(`legacy-global-skills-cleanup`,async e=>{let t=this.joinPath(this.getHomeDir(),`.skills`);if(!this.existsSync(t))return{success:!0,description:`Legacy global skills dir does not exist, nothing to clean`};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`legacyCleanup`,path:t}),{success:!0,description:`Would clean legacy global skills dir: ${t}`};try{let e=this.readdirSync(t,{withFileTypes:!0}),n=0;for(let r of e)if(r.isDirectory()){let e=this.joinPath(t,r.name),i=this.joinPath(e,Nv);this.existsSync(i)&&(d.rmSync(e,{recursive:!0}),n++)}return this.readdirSync(t).length===0&&d.rmdirSync(t),this.log.trace({action:`clean`,type:`legacySkills`,dir:t,cleanedCount:n}),{success:!0,description:`Cleaned ${n} legacy skills from ${t}`}}catch(e){let n=e instanceof Error?e.message:String(e);return this.log.error({action:`clean`,type:`legacySkills`,dir:t,error:n}),{success:!1,description:`Failed to clean legacy skills dir`,error:e}}})}getGlobalSkillsDir(){return this.joinPath(this.getHomeDir(),Mv)}async registerProjectOutputDirs(e){let t=[],{projects:n}=e.collectedInputContext.workspace,{skills:r}=e.collectedInputContext;if(r==null||r.length===0)return t;for(let e of n){if(e.dirFromWorkspacePath==null)continue;let n=this.joinPath(e.dirFromWorkspacePath.path,jv);t.push({pathKind:L.Relative,path:n,basePath:e.dirFromWorkspacePath.basePath,getDirectoryName:()=>jv,getAbsolutePath:()=>this.joinPath(e.dirFromWorkspacePath.basePath,n)})}return t}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace,{skills:r}=e.collectedInputContext;if(r==null||r.length===0)return t;for(let e of n){if(e.dirFromWorkspacePath==null)continue;let n=this.joinPath(e.dirFromWorkspacePath.basePath,e.dirFromWorkspacePath.path,jv);for(let i of r){let r=i.yamlFrontMatter.name,a=this.joinPath(n,r);t.push({pathKind:L.Relative,path:this.joinPath(jv,r),basePath:this.joinPath(e.dirFromWorkspacePath.basePath,e.dirFromWorkspacePath.path),getDirectoryName:()=>r,getAbsolutePath:()=>a})}}return t}async registerGlobalOutputDirs(e){let{skills:t}=e.collectedInputContext;if(t==null||t.length===0)return[];let n=this.getGlobalSkillsDir();return[{pathKind:L.Relative,path:Mv,basePath:this.getHomeDir(),getDirectoryName:()=>Mv,getAbsolutePath:()=>n}]}async registerGlobalOutputFiles(e){let t=[],{skills:n}=e.collectedInputContext;if(n==null||n.length===0)return t;let r=this.getGlobalSkillsDir();for(let e of n){let n=e.yamlFrontMatter.name,i=this.joinPath(r,n);if(t.push({pathKind:L.Relative,path:this.joinPath(Mv,n,Nv),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,Nv)}),e.mcpConfig!=null&&t.push({pathKind:L.Relative,path:this.joinPath(Mv,n,Pv),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,Pv)}),e.childDocs!=null)for(let r of e.childDocs){let e=r.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:this.joinPath(Mv,n,e),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,e)})}if(e.resources!=null)for(let r of e.resources)t.push({pathKind:L.Relative,path:this.joinPath(Mv,n,r.relativePath),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,r.relativePath)})}return t}async canWrite(e){let{skills:t}=e.collectedInputContext,{projects:n}=e.collectedInputContext.workspace;return t==null||t.length===0?(this.log.trace({action:`skip`,reason:`noSkills`}),!1):n.length===0?(this.log.trace({action:`skip`,reason:`noProjects`}),!1):!0}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,{skills:n}=e.collectedInputContext,r=[],i=[];if(n==null||n.length===0)return{files:r,dirs:i};let a=this.getGlobalSkillsDir();for(let i of t){if(i.dirFromWorkspacePath==null)continue;let t=this.joinPath(i.dirFromWorkspacePath.basePath,i.dirFromWorkspacePath.path,jv);for(let o of n){let n=o.yamlFrontMatter.name,s=this.joinPath(a,n),c=this.joinPath(t,n),l={pathKind:L.Relative,path:this.joinPath(jv,n),basePath:this.joinPath(i.dirFromWorkspacePath.basePath,i.dirFromWorkspacePath.path),getDirectoryName:()=>n,getAbsolutePath:()=>c};if(e.dryRun===!0){this.log.trace({action:`dryRun`,type:`symlink`,target:s,link:c}),r.push({path:l,success:!0,skipped:!1});continue}try{this.createSymlink(s,c,`dir`),this.log.trace({action:`symlink`,type:`skill`,target:s,link:c}),r.push({path:l,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`symlink`,type:`skill`,target:s,link:c,error:t}),r.push({path:l,success:!1,error:e})}}}return{files:r,dirs:i}}async writeGlobalOutputs(e){let{skills:t}=e.collectedInputContext,n=[],r=[];if(t==null||t.length===0)return{files:n,dirs:r};let i=this.getGlobalSkillsDir();for(let r of t){let t=await this.writeSkill(e,r,i);n.push(...t)}return{files:n,dirs:r}}async writeSkill(e,t,n){let r=[],i=t.yamlFrontMatter.name,a=this.joinPath(n,i),o=this.joinPath(a,Nv),s={pathKind:L.Relative,path:Nv,basePath:a,getDirectoryName:()=>i,getAbsolutePath:()=>o},c=this.buildSkillFrontMatter(t),l=t.content,u=Ag(c,l);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`skill`,path:o}),r.push({path:s,success:!0,skipped:!1});else try{this.ensureDirectory(a),this.writeFileSync(o,u),this.log.trace({action:`write`,type:`skill`,path:o}),r.push({path:s,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skill`,path:o,error:t}),r.push({path:s,success:!1,error:e})}if(t.mcpConfig!=null){let n=await this.writeMcpConfig(e,t,a);r.push(n)}if(t.childDocs!=null)for(let n of t.childDocs){let t=await this.writeChildDoc(e,n,a,i);r.push(t)}if(t.resources!=null)for(let n of t.resources){let t=await this.writeResource(e,n,a,i);r.push(t)}return r}buildSkillFrontMatter(e){let t=e.yamlFrontMatter;return{name:t.name,description:t.description,...t.displayName!=null&&{displayName:t.displayName},...t.keywords!=null&&t.keywords.length>0&&{keywords:t.keywords},...t.author!=null&&{author:t.author},...t.version!=null&&{version:t.version},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}async writeMcpConfig(e,t,n){let r=t.yamlFrontMatter.name,i=this.joinPath(n,Pv),a={pathKind:L.Relative,path:Pv,basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i},o=t.mcpConfig.rawContent;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfig`,path:i}),{path:a,success:!0,skipped:!1};try{return this.ensureDirectory(n),this.writeFileSync(i,o),this.log.trace({action:`write`,type:`mcpConfig`,path:i}),{path:a,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`mcpConfig`,path:i,error:t}),{path:a,success:!1,error:e}}}async writeChildDoc(e,t,n,r){let i=t.relativePath.replace(/\.mdx$/,`.md`),a=this.joinPath(n,i),o={pathKind:L.Relative,path:i,basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>a},s=t.content;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`childDoc`,path:a}),{path:o,success:!0,skipped:!1};try{let e=this.dirname(a);return this.ensureDirectory(e),this.writeFileSync(a,s),this.log.trace({action:`write`,type:`childDoc`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`childDoc`,path:a,error:t}),{path:o,success:!1,error:e}}}async writeResource(e,t,n,r){let i=this.joinPath(n,t.relativePath),a={pathKind:L.Relative,path:t.relativePath,basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`resource`,path:i}),{path:a,success:!0,skipped:!1};try{let e=this.dirname(i);if(this.ensureDirectory(e),t.encoding===`base64`){let e=h.Buffer.from(t.content,`base64`);this.writeFileSyncBuffer(i,e)}else this.writeFileSync(i,t.content);return this.log.trace({action:`write`,type:`resource`,path:i}),{path:a,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`resource`,path:i,error:t}),{path:a,success:!1,error:e}}}},Iv=class extends Lg{options;constructor(e,t){super(e),this.options=t??{}}transformContent(e){return e}collect(e){let{shadowProjectDir:t}=this.resolveBasePaths(e.userConfigOptions),n=this.getFilePath(t);if(!e.fs.existsSync(n))return this.options.fallbackContent==null?(this.log.debug({action:`collect`,message:`File not found`,path:n}),{}):(this.log.debug({action:`collect`,message:`Using fallback content`,path:n}),{[this.getResultKey()]:this.transformContent(this.options.fallbackContent)});let r=e.fs.readFileSync(n,`utf8`);return r.length===0?this.options.fallbackContent==null?(this.log.debug({action:`collect`,message:`File is empty`,path:n}),{}):(this.log.debug({action:`collect`,message:`File empty, using fallback`,path:n}),{[this.getResultKey()]:this.transformContent(this.options.fallbackContent)}):(this.log.debug({action:`collect`,message:`Loaded file content`,path:n,length:r.length}),{[this.getResultKey()]:this.transformContent(r)})}},Lv=class extends Iv{constructor(){super(`GitExcludeInputPlugin`)}getFilePath(e){return f.join(e,`public`,`exclude`)}getResultKey(){return`shadowGitExclude`}};function Rv(e){let t=f.join(e,`.git`);if(!d.existsSync(t))return null;let n=d.lstatSync(t);if(n.isDirectory())return f.join(t,`info`);if(n.isFile())try{let n=d.readFileSync(t,`utf8`).trim(),r=/^gitdir: (.+)$/.exec(n);if(r?.[1]!=null){let t=f.resolve(e,r[1]);return f.join(t,`info`)}}catch{}return null}function zv(e,t=5){let n=[],r=new Set([`node_modules`,`.turbo`,`dist`,`build`,`out`,`.cache`]);function i(a,o){if(o>t)return;let s;try{let e=d.readdirSync(a,{withFileTypes:!0});if(!Array.isArray(e))return;s=e}catch{return}s.some(e=>e.name===`.git`)&&a!==e&&n.push(a);for(let e of s)e.isDirectory()&&(e.name===`.git`||r.has(e.name)||i(f.join(a,e.name),o+1))}return i(e,0),n}function Bv(e){let t=f.join(e,`modules`);if(!d.existsSync(t))return[];let n=[];function r(e){let t;try{let n=d.readdirSync(e,{withFileTypes:!0});if(!Array.isArray(n))return;t=n}catch{return}if(t.some(e=>e.name===`info`&&e.isDirectory())&&n.push(f.join(e,`info`)),t.find(e=>e.name===`modules`&&e.isDirectory())==null)return;let i;try{let t=d.readdirSync(f.join(e,`modules`),{withFileTypes:!0});if(!Array.isArray(t))return;i=t}catch{return}for(let t of i)t.isDirectory()&&r(f.join(e,`modules`,t.name))}let i;try{let e=d.readdirSync(t,{withFileTypes:!0});if(!Array.isArray(e))return n;i=e}catch{return n}for(let e of i)e.isDirectory()&&r(f.join(t,e.name));return n}var Vv=class extends Pg{constructor(){super(`GitExcludeOutputPlugin`)}async registerProjectOutputDirs(){return[]}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace;for(let e of n){if(e.dirFromWorkspacePath==null||e.isPromptSourceProject===!0)continue;let n=e.dirFromWorkspacePath,r=n.getAbsolutePath(),{basePath:i}=n,a=[r,...zv(r)];for(let e of a){let n=Rv(e);if(n==null)continue;let r=f.join(n,`exclude`),a=f.relative(i,r);t.push({pathKind:L.Relative,path:a,basePath:i,getDirectoryName:()=>f.basename(e),getAbsolutePath:()=>r})}}let r=e.collectedInputContext.workspace.directory.path,i=f.join(r,`.git`);if(d.existsSync(i)&&d.lstatSync(i).isDirectory())for(let e of Bv(i)){let n=f.join(e,`exclude`),i=f.relative(r,n);t.push({pathKind:L.Relative,path:i,basePath:r,getDirectoryName:()=>f.basename(f.dirname(e)),getAbsolutePath:()=>n})}return t}async registerGlobalOutputDirs(){return[]}async registerGlobalOutputFiles(){return[]}async canWrite(e){let{globalGitIgnore:t,shadowGitExclude:n}=e.collectedInputContext;if(!(t!=null&&t.length>0||n!=null&&n.length>0))return this.log.debug({action:`canWrite`,result:!1,reason:`No gitignore or exclude content found`}),!1;let{projects:r}=e.collectedInputContext.workspace,i=r.some(e=>{if(e.dirFromWorkspacePath==null)return!1;let t=e.dirFromWorkspacePath.getAbsolutePath();return Rv(t)==null?zv(t).some(e=>Rv(e)!=null):!0}),a=e.collectedInputContext.workspace.directory.path,o=Rv(a)!=null,s=i||o;return this.log.debug({action:`canWrite`,result:s,hasGitProjects:i,hasWorkspaceGit:o,reason:s?`Found git repositories to update`:`No git repositories found`}),s}async writeProjectOutputs(e){let t=[],{globalGitIgnore:n,shadowGitExclude:r}=e.collectedInputContext,i=this.buildManagedContent(n,r);if(i.length===0)return this.log.debug({action:`write`,message:`No gitignore or exclude content found, skipping`}),{files:[],dirs:[]};let{workspace:a}=e.collectedInputContext,{projects:o}=a,s=new Set;for(let n of o){if(n.dirFromWorkspacePath==null)continue;let r=n.dirFromWorkspacePath.getAbsolutePath(),a=[r,...zv(r)];for(let o of a){let a=Rv(o);if(a==null)continue;let c=f.join(a,`exclude`);if(s.has(c))continue;s.add(c);let l=o===r?`project:${n.name??`unknown`}`:`nested:${f.relative(r,o)}`;this.log.trace({action:`write`,path:c,label:l});let u=await this.writeGitExcludeFile(e,c,i,l);t.push(u)}}let c=a.directory.path,l=Rv(c);if(l!=null){let n=f.join(l,`exclude`);if(!s.has(n)){this.log.trace({action:`write`,path:n,target:`workspace`});let r=await this.writeGitExcludeFile(e,n,i,`workspace`);t.push(r),s.add(n)}}let u=zv(c);for(let n of u){let r=Rv(n);if(r==null)continue;let a=f.join(r,`exclude`);if(s.has(a))continue;s.add(a);let o=`workspace-nested:${f.relative(c,n)}`;this.log.trace({action:`write`,path:a,label:o});let l=await this.writeGitExcludeFile(e,a,i,o);t.push(l)}let p=f.join(c,`.git`);if(d.existsSync(p)&&d.lstatSync(p).isDirectory())for(let n of Bv(p)){let r=f.join(n,`exclude`);if(s.has(r))continue;s.add(r);let a=`git-module:${f.relative(p,n)}`;this.log.trace({action:`write`,path:r,label:a});let o=await this.writeGitExcludeFile(e,r,i,a);t.push(o)}return{files:t,dirs:[]}}buildManagedContent(e,t){let n=[];if(e!=null&&e.trim().length>0){let t=this.sanitizeContent(e);t.length>0&&n.push(t)}if(t!=null&&t.trim().length>0){let e=this.sanitizeContent(t);e.length>0&&n.push(e)}return n.length===0?``:n.join(`
|
|
1232
|
+
`)}async writeRuleMdcFile(e,t,n,r){let i=this.buildRuleFileName(n),a=f.join(t,i),o={pathKind:L.Relative,path:f.join(yv,Sv,i),basePath:r,getDirectoryName:()=>Sv,getAbsolutePath:()=>a},s=this.buildRuleMdcContent(n);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`ruleFile`,path:a}),{path:o,success:!0,skipped:!1};try{return this.ensureDirectory(t),this.writeFileSync(a,s),this.log.trace({action:`write`,type:`ruleFile`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`ruleFile`,path:a,error:t}),{path:o,success:!1,error:e}}}},Ov=class extends dv{constructor(){super(`DroidCLIOutputPlugin`,{globalConfigDir:`.factory`,outputFileName:`AGENTS.md`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0})}async writeSkill(e,t,n){let r=[],i=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),a=f.join(t,this.skillsSubDir,i),o=f.join(a,`SKILL.md`),s=n.yamlFrontMatter==null?void 0:{name:n.yamlFrontMatter.name,description:n.yamlFrontMatter.description},c=this.buildMarkdownContent(n.content,s),l=await this.writeFile(e,o,c,`skill`);if(r.push(l),n.childDocs!=null)for(let o of n.childDocs){let n=await this.writeSkillReferenceDocument(e,a,i,o,t);r.push(...n)}if(n.resources!=null)for(let o of n.resources){let n=await this.writeSkillResource(e,a,i,o,t);r.push(...n)}return r}},kv=class extends Lg{configKey;extension;constructor(e,t){super(e),this.configKey=t.configKey,this.extension=t.extension??`.mdx`}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i,globalScope:a}=e,o=this.resolveBasePaths(t),s=this.getTargetDir(t,o),c=[];if(!(i.existsSync(s)&&i.statSync(s).isDirectory()))return this.createResult(c);try{let e=i.readdirSync(s,{withFileTypes:!0});for(let t of e)if(t.isFile()&&t.name.endsWith(this.extension)){let e=r.join(s,t.name),o=i.readFileSync(e,`utf8`);try{let r=jg(o),i=await uv(o,{globalScope:a,extractMetadata:!0,basePath:s}),l=r.yamlFrontMatter!=null||Object.keys(i.metadata.fields).length>0?{...r.yamlFrontMatter,...i.metadata.fields}:void 0;if(l!=null){let t=this.validateMetadata(l,e);for(let e of t.warnings)n.debug(e);if(!t.valid)throw new Xg([...t.errors],e)}let{content:u}=i;n.debug(`${this.name} metadata extracted`,{file:t.name,source:i.metadata.source,hasYaml:r.yamlFrontMatter!=null,hasExport:Object.keys(i.metadata.fields).length>0});let d=this.createPrompt(t.name,e,u,l,r.rawFrontMatter,r,s,o);c.push(d)}catch(t){n.error(`failed to parse ${this.name} item`,{file:e,error:t})}}}catch(e){n.error(`Failed to scan directory at ${s}`,{error:e})}return this.createResult(c)}},Av=class extends kv{constructor(){super(`FastCommandInputPlugin`,{configKey:`shadowSourceProject.fastCommand.dist`})}getTargetDir(e,t){return this.resolveShadowPath(e.shadowSourceProject.fastCommand.dist,t.shadowProjectDir)}validateMetadata(e,t){return jt(e,t)}createResult(e){return{fastCommands:e}}extractSeriesInfo(e,t){let n=e.replace(/\.mdx$/,``);if(t!=null)return{series:t,commandName:n};let r=n.indexOf(`_`);return r===-1?{commandName:n}:{series:n.slice(0,Math.max(0,r)),commandName:n.slice(Math.max(0,r+1))}}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i}=e,a=this.resolveBasePaths(t),o=this.getTargetDir(t,a),s=[];if(!(i.existsSync(o)&&i.statSync(o).isDirectory()))return this.createResult(s);try{let t=i.readdirSync(o,{withFileTypes:!0});for(let a of t)if(a.isFile()&&a.name.endsWith(this.extension)){let t=await this.processFile(a.name,r.join(o,a.name),o,void 0,e);t!=null&&s.push(t)}else if(a.isDirectory()){let t=r.join(o,a.name);try{let n=i.readdirSync(t,{withFileTypes:!0});for(let i of n)if(i.isFile()&&i.name.endsWith(this.extension)){let n=await this.processFile(i.name,r.join(t,i.name),o,a.name,e);n!=null&&s.push(n)}}catch(e){n.error(`Failed to scan subdirectory at ${t}`,{error:e})}}}catch(e){n.error(`Failed to scan directory at ${o}`,{error:e})}return this.createResult(s)}async processFile(e,t,n,r,i){let{logger:a,globalScope:o}=i,s=i.fs.readFileSync(t,`utf8`);try{let c=jg(s),l=await uv(s,{globalScope:o,extractMetadata:!0,basePath:r==null?n:i.path.join(n,r)}),u=c.yamlFrontMatter!=null||Object.keys(l.metadata.fields).length>0?{...c.yamlFrontMatter,...l.metadata.fields}:void 0;if(u!=null){let e=this.validateMetadata(u,t);for(let t of e.warnings)a.debug(t);if(!e.valid)throw new Xg([...e.errors],t)}let{content:d}=l,f=r==null?e:`${r}/${e}`;return a.debug(`${this.name} metadata extracted`,{file:f,source:l.metadata.source,hasYaml:c.yamlFrontMatter!=null,hasExport:Object.keys(l.metadata.fields).length>0}),this.createPrompt(f,t,d,u,c.rawFrontMatter,c,n,s)}catch(e){a.error(`failed to parse ${this.name} item`,{file:t,error:e});return}}createPrompt(e,t,n,r,i,a,o,s){let c=e.indexOf(`/`),l=c===-1?void 0:e.slice(0,c),u=c===-1?e:e.slice(c+1),d=this.extractSeriesInfo(u,l);return{type:xt.FastCommand,content:n,length:n.length,filePathKind:L.Relative,...r!=null&&{yamlFrontMatter:r},...i!=null&&{rawFrontMatter:i},markdownAst:a.markdownAst,markdownContents:a.markdownContents,dir:{pathKind:L.Relative,path:e,basePath:o,getDirectoryName:()=>e.replace(/\.mdx$/,``),getAbsolutePath:()=>t},...d.series!=null&&{series:d.series},commandName:d.commandName,rawMdxContent:s}}},jv=class extends dv{constructor(){super(`GeminiCLIOutputPlugin`,{globalConfigDir:`.gemini`,outputFileName:`GEMINI.md`,supportsFastCommands:!1,supportsSubAgents:!1,supportsSkills:!1})}};const Mv=`.skills`,Nv=`.aindex/.skills`,Pv=`SKILL.md`,Fv=`mcp.json`;var Iv=class extends Pg{constructor(){super(`GenericSkillsOutputPlugin`,{globalConfigDir:Nv,outputFileName:Pv}),this.registerCleanEffect(`legacy-global-skills-cleanup`,async e=>{let t=this.joinPath(this.getHomeDir(),`.skills`);if(!this.existsSync(t))return{success:!0,description:`Legacy global skills dir does not exist, nothing to clean`};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`legacyCleanup`,path:t}),{success:!0,description:`Would clean legacy global skills dir: ${t}`};try{let e=this.readdirSync(t,{withFileTypes:!0}),n=0;for(let r of e)if(r.isDirectory()){let e=this.joinPath(t,r.name),i=this.joinPath(e,Pv);this.existsSync(i)&&(d.rmSync(e,{recursive:!0}),n++)}return this.readdirSync(t).length===0&&d.rmdirSync(t),this.log.trace({action:`clean`,type:`legacySkills`,dir:t,cleanedCount:n}),{success:!0,description:`Cleaned ${n} legacy skills from ${t}`}}catch(e){let n=e instanceof Error?e.message:String(e);return this.log.error({action:`clean`,type:`legacySkills`,dir:t,error:n}),{success:!1,description:`Failed to clean legacy skills dir`,error:e}}})}getGlobalSkillsDir(){return this.joinPath(this.getHomeDir(),Nv)}async registerProjectOutputDirs(e){let t=[],{projects:n}=e.collectedInputContext.workspace,{skills:r}=e.collectedInputContext;if(r==null||r.length===0)return t;for(let e of n){if(e.dirFromWorkspacePath==null)continue;let n=this.joinPath(e.dirFromWorkspacePath.path,Mv);t.push({pathKind:L.Relative,path:n,basePath:e.dirFromWorkspacePath.basePath,getDirectoryName:()=>Mv,getAbsolutePath:()=>this.joinPath(e.dirFromWorkspacePath.basePath,n)})}return t}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace,{skills:r}=e.collectedInputContext;if(r==null||r.length===0)return t;for(let e of n){if(e.dirFromWorkspacePath==null)continue;let n=this.joinPath(e.dirFromWorkspacePath.basePath,e.dirFromWorkspacePath.path,Mv);for(let i of r){let r=i.yamlFrontMatter.name,a=this.joinPath(n,r);t.push({pathKind:L.Relative,path:this.joinPath(Mv,r),basePath:this.joinPath(e.dirFromWorkspacePath.basePath,e.dirFromWorkspacePath.path),getDirectoryName:()=>r,getAbsolutePath:()=>a})}}return t}async registerGlobalOutputDirs(e){let{skills:t}=e.collectedInputContext;if(t==null||t.length===0)return[];let n=this.getGlobalSkillsDir();return[{pathKind:L.Relative,path:Nv,basePath:this.getHomeDir(),getDirectoryName:()=>Nv,getAbsolutePath:()=>n}]}async registerGlobalOutputFiles(e){let t=[],{skills:n}=e.collectedInputContext;if(n==null||n.length===0)return t;let r=this.getGlobalSkillsDir();for(let e of n){let n=e.yamlFrontMatter.name,i=this.joinPath(r,n);if(t.push({pathKind:L.Relative,path:this.joinPath(Nv,n,Pv),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,Pv)}),e.mcpConfig!=null&&t.push({pathKind:L.Relative,path:this.joinPath(Nv,n,Fv),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,Fv)}),e.childDocs!=null)for(let r of e.childDocs){let e=r.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:this.joinPath(Nv,n,e),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,e)})}if(e.resources!=null)for(let r of e.resources)t.push({pathKind:L.Relative,path:this.joinPath(Nv,n,r.relativePath),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,r.relativePath)})}return t}async canWrite(e){let{skills:t}=e.collectedInputContext,{projects:n}=e.collectedInputContext.workspace;return t==null||t.length===0?(this.log.trace({action:`skip`,reason:`noSkills`}),!1):n.length===0?(this.log.trace({action:`skip`,reason:`noProjects`}),!1):!0}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,{skills:n}=e.collectedInputContext,r=[],i=[];if(n==null||n.length===0)return{files:r,dirs:i};let a=this.getGlobalSkillsDir();for(let i of t){if(i.dirFromWorkspacePath==null)continue;let t=this.joinPath(i.dirFromWorkspacePath.basePath,i.dirFromWorkspacePath.path,Mv);for(let o of n){let n=o.yamlFrontMatter.name,s=this.joinPath(a,n),c=this.joinPath(t,n),l={pathKind:L.Relative,path:this.joinPath(Mv,n),basePath:this.joinPath(i.dirFromWorkspacePath.basePath,i.dirFromWorkspacePath.path),getDirectoryName:()=>n,getAbsolutePath:()=>c};if(e.dryRun===!0){this.log.trace({action:`dryRun`,type:`symlink`,target:s,link:c}),r.push({path:l,success:!0,skipped:!1});continue}try{this.createSymlink(s,c,`dir`),this.log.trace({action:`symlink`,type:`skill`,target:s,link:c}),r.push({path:l,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`symlink`,type:`skill`,target:s,link:c,error:t}),r.push({path:l,success:!1,error:e})}}}return{files:r,dirs:i}}async writeGlobalOutputs(e){let{skills:t}=e.collectedInputContext,n=[],r=[];if(t==null||t.length===0)return{files:n,dirs:r};let i=this.getGlobalSkillsDir();for(let r of t){let t=await this.writeSkill(e,r,i);n.push(...t)}return{files:n,dirs:r}}async writeSkill(e,t,n){let r=[],i=t.yamlFrontMatter.name,a=this.joinPath(n,i),o=this.joinPath(a,Pv),s={pathKind:L.Relative,path:Pv,basePath:a,getDirectoryName:()=>i,getAbsolutePath:()=>o},c=this.buildSkillFrontMatter(t),l=t.content,u=Ag(c,l);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`skill`,path:o}),r.push({path:s,success:!0,skipped:!1});else try{this.ensureDirectory(a),this.writeFileSync(o,u),this.log.trace({action:`write`,type:`skill`,path:o}),r.push({path:s,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skill`,path:o,error:t}),r.push({path:s,success:!1,error:e})}if(t.mcpConfig!=null){let n=await this.writeMcpConfig(e,t,a);r.push(n)}if(t.childDocs!=null)for(let n of t.childDocs){let t=await this.writeChildDoc(e,n,a,i);r.push(t)}if(t.resources!=null)for(let n of t.resources){let t=await this.writeResource(e,n,a,i);r.push(t)}return r}buildSkillFrontMatter(e){let t=e.yamlFrontMatter;return{name:t.name,description:t.description,...t.displayName!=null&&{displayName:t.displayName},...t.keywords!=null&&t.keywords.length>0&&{keywords:t.keywords},...t.author!=null&&{author:t.author},...t.version!=null&&{version:t.version},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}async writeMcpConfig(e,t,n){let r=t.yamlFrontMatter.name,i=this.joinPath(n,Fv),a={pathKind:L.Relative,path:Fv,basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i},o=t.mcpConfig.rawContent;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfig`,path:i}),{path:a,success:!0,skipped:!1};try{return this.ensureDirectory(n),this.writeFileSync(i,o),this.log.trace({action:`write`,type:`mcpConfig`,path:i}),{path:a,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`mcpConfig`,path:i,error:t}),{path:a,success:!1,error:e}}}async writeChildDoc(e,t,n,r){let i=t.relativePath.replace(/\.mdx$/,`.md`),a=this.joinPath(n,i),o={pathKind:L.Relative,path:i,basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>a},s=t.content;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`childDoc`,path:a}),{path:o,success:!0,skipped:!1};try{let e=this.dirname(a);return this.ensureDirectory(e),this.writeFileSync(a,s),this.log.trace({action:`write`,type:`childDoc`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`childDoc`,path:a,error:t}),{path:o,success:!1,error:e}}}async writeResource(e,t,n,r){let i=this.joinPath(n,t.relativePath),a={pathKind:L.Relative,path:t.relativePath,basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`resource`,path:i}),{path:a,success:!0,skipped:!1};try{let e=this.dirname(i);if(this.ensureDirectory(e),t.encoding===`base64`){let e=h.Buffer.from(t.content,`base64`);this.writeFileSyncBuffer(i,e)}else this.writeFileSync(i,t.content);return this.log.trace({action:`write`,type:`resource`,path:i}),{path:a,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`resource`,path:i,error:t}),{path:a,success:!1,error:e}}}},Lv=class extends Lg{options;constructor(e,t){super(e),this.options=t??{}}transformContent(e){return e}collect(e){let{shadowProjectDir:t}=this.resolveBasePaths(e.userConfigOptions),n=this.getFilePath(t);if(!e.fs.existsSync(n))return this.options.fallbackContent==null?(this.log.debug({action:`collect`,message:`File not found`,path:n}),{}):(this.log.debug({action:`collect`,message:`Using fallback content`,path:n}),{[this.getResultKey()]:this.transformContent(this.options.fallbackContent)});let r=e.fs.readFileSync(n,`utf8`);return r.length===0?this.options.fallbackContent==null?(this.log.debug({action:`collect`,message:`File is empty`,path:n}),{}):(this.log.debug({action:`collect`,message:`File empty, using fallback`,path:n}),{[this.getResultKey()]:this.transformContent(this.options.fallbackContent)}):(this.log.debug({action:`collect`,message:`Loaded file content`,path:n,length:r.length}),{[this.getResultKey()]:this.transformContent(r)})}},Rv=class extends Lv{constructor(){super(`GitExcludeInputPlugin`)}getFilePath(e){return f.join(e,`public`,`exclude`)}getResultKey(){return`shadowGitExclude`}};function zv(e){let t=f.join(e,`.git`);if(!d.existsSync(t))return null;let n=d.lstatSync(t);if(n.isDirectory())return f.join(t,`info`);if(n.isFile())try{let n=d.readFileSync(t,`utf8`).trim(),r=/^gitdir: (.+)$/.exec(n);if(r?.[1]!=null){let t=f.resolve(e,r[1]);return f.join(t,`info`)}}catch{}return null}function Bv(e,t=5){let n=[],r=new Set([`node_modules`,`.turbo`,`dist`,`build`,`out`,`.cache`]);function i(a,o){if(o>t)return;let s;try{let e=d.readdirSync(a,{withFileTypes:!0});if(!Array.isArray(e))return;s=e}catch{return}s.some(e=>e.name===`.git`)&&a!==e&&n.push(a);for(let e of s)e.isDirectory()&&(e.name===`.git`||r.has(e.name)||i(f.join(a,e.name),o+1))}return i(e,0),n}function Vv(e){let t=f.join(e,`modules`);if(!d.existsSync(t))return[];let n=[];function r(e){let t;try{let n=d.readdirSync(e,{withFileTypes:!0});if(!Array.isArray(n))return;t=n}catch{return}if(t.some(e=>e.name===`info`&&e.isDirectory())&&n.push(f.join(e,`info`)),t.find(e=>e.name===`modules`&&e.isDirectory())==null)return;let i;try{let t=d.readdirSync(f.join(e,`modules`),{withFileTypes:!0});if(!Array.isArray(t))return;i=t}catch{return}for(let t of i)t.isDirectory()&&r(f.join(e,`modules`,t.name))}let i;try{let e=d.readdirSync(t,{withFileTypes:!0});if(!Array.isArray(e))return n;i=e}catch{return n}for(let e of i)e.isDirectory()&&r(f.join(t,e.name));return n}var Hv=class extends Pg{constructor(){super(`GitExcludeOutputPlugin`)}async registerProjectOutputDirs(){return[]}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace;for(let e of n){if(e.dirFromWorkspacePath==null||e.isPromptSourceProject===!0)continue;let n=e.dirFromWorkspacePath,r=n.getAbsolutePath(),{basePath:i}=n,a=[r,...Bv(r)];for(let e of a){let n=zv(e);if(n==null)continue;let r=f.join(n,`exclude`),a=f.relative(i,r);t.push({pathKind:L.Relative,path:a,basePath:i,getDirectoryName:()=>f.basename(e),getAbsolutePath:()=>r})}}let r=e.collectedInputContext.workspace.directory.path,i=f.join(r,`.git`);if(d.existsSync(i)&&d.lstatSync(i).isDirectory())for(let e of Vv(i)){let n=f.join(e,`exclude`),i=f.relative(r,n);t.push({pathKind:L.Relative,path:i,basePath:r,getDirectoryName:()=>f.basename(f.dirname(e)),getAbsolutePath:()=>n})}return t}async registerGlobalOutputDirs(){return[]}async registerGlobalOutputFiles(){return[]}async canWrite(e){let{globalGitIgnore:t,shadowGitExclude:n}=e.collectedInputContext;if(!(t!=null&&t.length>0||n!=null&&n.length>0))return this.log.debug({action:`canWrite`,result:!1,reason:`No gitignore or exclude content found`}),!1;let{projects:r}=e.collectedInputContext.workspace,i=r.some(e=>{if(e.dirFromWorkspacePath==null)return!1;let t=e.dirFromWorkspacePath.getAbsolutePath();return zv(t)==null?Bv(t).some(e=>zv(e)!=null):!0}),a=e.collectedInputContext.workspace.directory.path,o=zv(a)!=null,s=i||o;return this.log.debug({action:`canWrite`,result:s,hasGitProjects:i,hasWorkspaceGit:o,reason:s?`Found git repositories to update`:`No git repositories found`}),s}async writeProjectOutputs(e){let t=[],{globalGitIgnore:n,shadowGitExclude:r}=e.collectedInputContext,i=this.buildManagedContent(n,r);if(i.length===0)return this.log.debug({action:`write`,message:`No gitignore or exclude content found, skipping`}),{files:[],dirs:[]};let{workspace:a}=e.collectedInputContext,{projects:o}=a,s=new Set;for(let n of o){if(n.dirFromWorkspacePath==null)continue;let r=n.dirFromWorkspacePath.getAbsolutePath(),a=[r,...Bv(r)];for(let o of a){let a=zv(o);if(a==null)continue;let c=f.join(a,`exclude`);if(s.has(c))continue;s.add(c);let l=o===r?`project:${n.name??`unknown`}`:`nested:${f.relative(r,o)}`;this.log.trace({action:`write`,path:c,label:l});let u=await this.writeGitExcludeFile(e,c,i,l);t.push(u)}}let c=a.directory.path,l=zv(c);if(l!=null){let n=f.join(l,`exclude`);if(!s.has(n)){this.log.trace({action:`write`,path:n,target:`workspace`});let r=await this.writeGitExcludeFile(e,n,i,`workspace`);t.push(r),s.add(n)}}let u=Bv(c);for(let n of u){let r=zv(n);if(r==null)continue;let a=f.join(r,`exclude`);if(s.has(a))continue;s.add(a);let o=`workspace-nested:${f.relative(c,n)}`;this.log.trace({action:`write`,path:a,label:o});let l=await this.writeGitExcludeFile(e,a,i,o);t.push(l)}let p=f.join(c,`.git`);if(d.existsSync(p)&&d.lstatSync(p).isDirectory())for(let n of Vv(p)){let r=f.join(n,`exclude`);if(s.has(r))continue;s.add(r);let a=`git-module:${f.relative(p,n)}`;this.log.trace({action:`write`,path:r,label:a});let o=await this.writeGitExcludeFile(e,r,i,a);t.push(o)}return{files:t,dirs:[]}}buildManagedContent(e,t){let n=[];if(e!=null&&e.trim().length>0){let t=this.sanitizeContent(e);t.length>0&&n.push(t)}if(t!=null&&t.trim().length>0){let e=this.sanitizeContent(t);e.length>0&&n.push(e)}return n.length===0?``:n.join(`
|
|
1233
1233
|
`)}sanitizeContent(e){return e.split(/\r?\n/).filter(e=>{let t=e.trim();return t.length===0?!0:!(t.startsWith(`#`)&&!t.startsWith(`\\#`))}).join(`
|
|
1234
|
-
`).trim()}normalizeContent(e){let t=e.trim();return t.length===0?``:`${t}\n`}async writeGitExcludeFile(e,t,n,r){let i=e.collectedInputContext.workspace.directory.path,a={pathKind:L.Relative,path:f.relative(i,t),basePath:i,getDirectoryName:()=>f.basename(f.dirname(t)),getAbsolutePath:()=>t};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`gitExclude`,path:t,label:r}),{path:a,success:!0,skipped:!1};try{let e=f.dirname(t);d.existsSync(e)||(d.mkdirSync(e,{recursive:!0}),this.log.debug({action:`mkdir`,path:e,message:`Created .git/info directory`}));let i=this.normalizeContent(n);return d.writeFileSync(t,i,`utf8`),this.log.trace({action:`write`,type:`gitExclude`,path:t,label:r}),{path:a,success:!0}}catch(e){let n=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`gitExclude`,path:t,label:r,error:n}),{path:a,success:!1,error:e}}}};const Hv=Ut;function Uv(){return Hv[`public/gitignore`]?.content??``}var Wv=class extends Iv{constructor(){super(`GitIgnoreInputPlugin`,{fallbackContent:Uv()})}getFilePath(e){return f.join(e,`public`,`gitignore`)}getResultKey(){return`globalGitIgnore`}},Gv=class extends Lg{constructor(){super(`GlobalMemoryInputPlugin`)}async collect(e){let{userConfigOptions:t,fs:n,path:r,globalScope:i}=e,{shadowProjectDir:a}=this.resolveBasePaths(t),o=this.resolveShadowPath(t.shadowSourceProject.globalMemory.dist,a);if(!n.existsSync(o))return this.log.warn({action:`collect`,reason:`fileNotFound`,path:o}),{};if(!n.statSync(o).isFile())return this.log.warn({action:`collect`,reason:`notAFile`,path:o}),{};let s=n.readFileSync(o,`utf8`),c=jg(s),l;if(i!=null)try{l=await uv(s,{globalScope:i,basePath:r.dirname(o)})}catch(e){throw e instanceof qg&&(this.log.error(`MDX compilation failed: ${e.message}`),this.log.error(`Please check your configuration file (~/.aindex/.tnmsc.json) and ensure all required variables are defined.`),this.log.error(`For example, if using {profile.name}, add a "profile" section with "name" field to your config.`),u.default.exit(1)),e}else l=c.contentWithoutFrontMatter;return this.log.debug({action:`collect`,path:o,contentLength:l.length}),{globalMemory:{type:xt.GlobalMemory,content:l,length:l.length,filePathKind:L.Relative,...c.rawFrontMatter!=null&&{rawFrontMatter:c.rawFrontMatter},markdownAst:c.markdownAst,markdownContents:c.markdownContents,dir:{pathKind:L.Relative,path:r.basename(o),basePath:r.dirname(o),getDirectoryName:()=>r.basename(o),getAbsolutePath:()=>o},parentDirectoryPath:{type:wt.UserHome,directory:{pathKind:L.Relative,path:``,basePath:p.homedir(),getDirectoryName:()=>r.basename(p.homedir()),getAbsolutePath:()=>p.homedir()}}}}}},Kv=class extends Lg{constructor(){super(`IdeConfigInputPlugin`)}collect(e){let{userConfigOptions:t,fs:n,path:r}=e,{shadowProjectDir:i}=this.resolveBasePaths(t),a=[`.editorconfig`,`.idea/codeStyles/Project.xml`,`.idea/codeStyles/codeStyleConfig.xml`,`.idea/.gitignore`,`.vscode/settings.json`,`.vscode/extensions.json`],o=[];for(let e of a){let t=r.join(i,e);if(n.existsSync(t)&&n.statSync(t).isFile()){let i=n.readFileSync(t,`utf8`),a=Tt.Original;e.includes(`.vscode`)?a=Tt.VSCode:e.includes(`.idea`)?a=Tt.IntellijIDEA:e.includes(`.editorconfig`)&&(a=Tt.EditorConfig),o.push({type:a,content:i,length:i.length,filePathKind:L.Absolute,dir:{pathKind:L.Absolute,path:t,getDirectoryName:()=>r.basename(t)}})}}return{ideConfigFiles:o}}};const qv=`AGENTS.md`,Jv=`prompts`,Yv=`skills`,Xv=`SKILL.md`,Zv=`.aiassistant`,Qv=`rules`,$v=`always.md`,ey=`codex`,ty=[`IntelliJIdea`,`WebStorm`,`RustRover`,`PyCharm`,`PyCharmCE`,`PhpStorm`,`GoLand`,`CLion`,`DataGrip`,`RubyMine`,`Rider`,`DataSpell`,`Aqua`];var ny=class extends Pg{constructor(){super(`JetBrainsAIAssistantCodexOutputPlugin`,{outputFileName:qv,dependsOn:[`AgentsOutputPlugin`],indexignore:`.aiignore`})}async registerProjectOutputDirs(e){let t=[],{projects:n}=e.collectedInputContext.workspace;for(let e of n)e.dirFromWorkspacePath!=null&&t.push(this.createProjectRulesDirRelativePath(e.dirFromWorkspacePath));return t}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace;for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null&&(e.rootMemoryPrompt!=null&&t.push(this.createProjectRuleFileRelativePath(n,$v)),e.childMemoryPrompts!=null))for(let r of e.childMemoryPrompts){let e=this.buildChildRuleFileName(r);t.push(this.createProjectRuleFileRelativePath(n,e))}}return t.push(...this.registerProjectIgnoreOutputFiles(n)),t}async registerGlobalOutputDirs(e){let t=[],n=this.resolveCodexDirs();for(let r of n){let n=f.join(r,Jv);t.push({pathKind:L.Relative,path:Jv,basePath:r,getDirectoryName:()=>Jv,getAbsolutePath:()=>n});let{skills:i}=e.collectedInputContext;if(!(i==null||i.length===0))for(let e of i){let n=e.yamlFrontMatter?.name??e.dir.getDirectoryName(),i=f.join(r,Yv,n);t.push({pathKind:L.Relative,path:f.join(Yv,n),basePath:r,getDirectoryName:()=>n,getAbsolutePath:()=>i})}}return t}async registerGlobalOutputFiles(){return this.resolveCodexDirs().map(e=>({pathKind:L.Relative,path:qv,basePath:e,getDirectoryName:()=>ey,getAbsolutePath:()=>f.join(e,qv)}))}async canWrite(e){let{globalMemory:t,fastCommands:n,skills:r,workspace:i,aiAgentIgnoreConfigFiles:a}=e.collectedInputContext,o=t!=null,s=(n?.length??0)>0,c=(r?.length??0)>0,l=i.projects.some(e=>e.rootMemoryPrompt!=null||(e.childMemoryPrompts?.length??0)>0),u=a?.some(e=>e.fileName===`.aiignore`)??!1;return o||s||c||l||u?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,n=[],r=[];for(let r of t)if(r.dirFromWorkspacePath!=null){if(r.rootMemoryPrompt!=null){let t=this.buildAlwaysRuleContent(r.rootMemoryPrompt.content),i=await this.writeProjectRuleFile(e,r,$v,t,`projectRootRule`);n.push(i)}if(r.childMemoryPrompts!=null)for(let t of r.childMemoryPrompts){let i=this.buildChildRuleFileName(t),a=this.buildGlobRuleContent(t),o=await this.writeProjectRuleFile(e,r,i,a,`projectChildRule`);n.push(o)}}let i=await this.writeProjectIgnoreFiles(e);return n.push(...i),{files:n,dirs:r}}async writeGlobalOutputs(e){let{globalMemory:t,fastCommands:n,skills:r}=e.collectedInputContext,i=[],a=[],o=this.resolveCodexDirs();if(o.length===0)return{files:i,dirs:a};for(let a of o){if(t!=null){let n=f.join(a,qv),r={pathKind:L.Relative,path:qv,basePath:a,getDirectoryName:()=>ey,getAbsolutePath:()=>n};if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`globalMemory`,path:n}),i.push({path:r,success:!0,skipped:!1});else try{this.ensureDirectory(a),d.writeFileSync(n,t.content,`utf8`),this.log.trace({action:`write`,type:`globalMemory`,path:n}),i.push({path:r,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`globalMemory`,path:n,error:t}),i.push({path:r,success:!1,error:e})}}if(n!=null&&n.length>0)for(let t of n){let n=await this.writeGlobalFastCommand(e,a,t);i.push(...n)}if(!(r==null||r.length===0))for(let t of r){let n=await this.writeGlobalSkill(e,a,t);i.push(...n)}}return{files:i,dirs:a}}resolveCodexDirs(){let e=f.join(Xe(),`JetBrains`);if(!this.existsSync(e))return[];try{return this.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()?this.isSupportedIdeDir(e.name):!1).map(t=>f.join(e,t.name,`aia`,ey))}catch(t){let n=t instanceof Error?t.message:String(t);return this.log.warn({action:`scan`,type:`jetbrains`,path:e,error:n}),[]}}createProjectRulesDirRelativePath(e){let t=f.join(e.path,Zv,Qv);return{pathKind:L.Relative,path:t,basePath:e.basePath,getDirectoryName:()=>Qv,getAbsolutePath:()=>f.join(e.basePath,t)}}createProjectRuleFileRelativePath(e,t){let n=f.join(e.path,Zv,Qv,t);return{pathKind:L.Relative,path:n,basePath:e.basePath,getDirectoryName:()=>Qv,getAbsolutePath:()=>f.join(e.basePath,n)}}buildChildRuleFileName(e){let t=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``).replaceAll(`/`,`-`);return`glob-${t.length>0?t:`root`}.md`}buildChildRulePattern(e){let t=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``);return t.length===0?`**/*`:`${t}/**`}buildAlwaysRuleContent(e){return Ag({apply:`始终`},e)}buildGlobRuleContent(e){return Ag({apply:`按文件模式`,模式:this.buildChildRulePattern(e)},e.content)}async writeProjectRuleFile(e,t,n,r,i){let a=t.dirFromWorkspacePath,o=f.join(a.basePath,a.path,Zv,Qv),s=f.join(o,n),c=this.createProjectRuleFileRelativePath(a,n);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:i,path:s}),{path:c,success:!0,skipped:!1};try{return this.ensureDirectory(o),d.writeFileSync(s,r,`utf8`),this.log.trace({action:`write`,type:i,path:s}),{path:c,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:i,path:s,error:t}),{path:c,success:!1,error:e}}}isSupportedIdeDir(e){return ty.some(t=>e.startsWith(t))}async writeGlobalFastCommand(e,t,n){let r=[],i=this.getTransformOptionsFromContext(e),a=this.transformFastCommandName(n,i),o=f.join(t,Jv),s=f.join(o,a),c={pathKind:L.Relative,path:f.join(Jv,a),basePath:t,getDirectoryName:()=>Jv,getAbsolutePath:()=>s},l=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalFastCommand`,path:s}),[{path:c,success:!0,skipped:!1}];try{this.ensureDirectory(o),d.writeFileSync(s,l,`utf8`),this.log.trace({action:`write`,type:`globalFastCommand`,path:s}),r.push({path:c,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`globalFastCommand`,path:s,error:t}),r.push({path:c,success:!1,error:e})}return r}async writeGlobalSkill(e,t,n){let r=[],i=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),a=f.join(t,Yv,i),o=f.join(a,Xv),s={pathKind:L.Relative,path:f.join(Yv,i,Xv),basePath:t,getDirectoryName:()=>i,getAbsolutePath:()=>o},c=this.buildCodexSkillContent(n);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalSkill`,path:o}),[{path:s,success:!0,skipped:!1}];try{if(this.ensureDirectory(a),d.writeFileSync(o,c,`utf8`),this.log.trace({action:`write`,type:`globalSkill`,path:o}),r.push({path:s,success:!0}),n.childDocs!=null)for(let o of n.childDocs){let n=await this.writeSkillReferenceDocument(e,a,i,o,t);r.push(...n)}if(n.resources!=null)for(let o of n.resources){let n=await this.writeSkillResource(e,a,i,o,t);r.push(...n)}}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`globalSkill`,path:o,error:t}),r.push({path:s,success:!1,error:e})}return r}buildCodexSkillContent(e){let t=e.yamlFrontMatter,n=this.normalizeSkillName(t.name,64),r=this.normalizeToSingleLine(t.description,1024),i={};t.displayName!=null&&(i[`short-description`]=t.displayName),t.version!=null&&(i.version=t.version),t.author!=null&&(i.author=t.author),t.keywords!=null&&t.keywords.length>0&&(i.keywords=[...t.keywords]);let a={name:n,description:r};return Object.keys(i).length>0&&(a.metadata=i),t.allowTools!=null&&t.allowTools.length>0&&(a[`allowed-tools`]=t.allowTools.join(` `)),Ag(a,e.content)}normalizeSkillName(e,t){let n=e.toLowerCase().replaceAll(/[^a-z0-9-]/g,`-`).replaceAll(/-+/g,`-`).replaceAll(/^-+|-+$/g,``);return n.length>t&&(n=n.slice(0,t).replace(/-+$/,``)),n}normalizeToSingleLine(e,t){let n=e.replaceAll(/[\r\n]+/g,` `).replaceAll(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-3)}...`:n}async writeSkillReferenceDocument(e,t,n,r,i){let a=[],o=r.dir.path.replace(/\.mdx$/,`.md`),s=f.join(t,o),c={pathKind:L.Relative,path:f.join(Yv,n,o),basePath:i,getDirectoryName:()=>n,getAbsolutePath:()=>s};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`skillRefDoc`,path:s}),[{path:c,success:!0,skipped:!1}];try{let e=f.dirname(s);this.ensureDirectory(e),d.writeFileSync(s,r.content,`utf8`),this.log.trace({action:`write`,type:`skillRefDoc`,path:s}),a.push({path:c,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skillRefDoc`,path:s,error:t}),a.push({path:c,success:!1,error:e})}return a}async writeSkillResource(e,t,n,r,i){let a=[],o=f.join(t,r.relativePath),s={pathKind:L.Relative,path:f.join(Yv,n,r.relativePath),basePath:i,getDirectoryName:()=>n,getAbsolutePath:()=>o};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`skillResource`,path:o}),[{path:s,success:!0,skipped:!1}];try{let e=f.dirname(o);this.ensureDirectory(e),d.writeFileSync(o,r.content,`utf8`),this.log.trace({action:`write`,type:`skillResource`,path:o}),a.push({path:s,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skillResource`,path:o,error:t}),a.push({path:s,success:!1,error:e})}return a}};const ry=`.idea`,iy=[`.editorconfig`,`.idea/codeStyles/Project.xml`,`.idea/codeStyles/codeStyleConfig.xml`,`.idea/.gitignore`];var ay=class extends Pg{constructor(){super(`JetBrainsIDECodeStyleConfigOutputPlugin`)}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace,{ideConfigFiles:r}=e.collectedInputContext;if(!r.some(e=>e.type===Tt.IntellijIDEA||e.type===Tt.EditorConfig))return t;for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null&&e.isPromptSourceProject!==!0)for(let e of iy){let r=this.joinPath(n.path,e);t.push({pathKind:L.Relative,path:r,basePath:n.basePath,getDirectoryName:()=>this.dirname(e),getAbsolutePath:()=>this.resolvePath(n.basePath,r)})}}return t}async canWrite(e){let{ideConfigFiles:t}=e.collectedInputContext;return t.some(e=>e.type===Tt.IntellijIDEA||e.type===Tt.EditorConfig)?!0:(this.log.debug(`skipped`,{reason:`no JetBrains IDE config files found`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,{ideConfigFiles:n}=e.collectedInputContext,r=[],i=[],a=n.filter(e=>e.type===Tt.IntellijIDEA||e.type===Tt.EditorConfig);for(let n of t){let t=n.dirFromWorkspacePath;if(t==null)continue;let i=n.name??`unknown`;for(let n of a){let a=await this.writeConfigFile(e,t,n,`project:${i}`);r.push(a)}}return{files:r,dirs:i}}async writeConfigFile(e,t,n,r){let i=this.getTargetRelativePath(n),a=this.resolvePath(t.basePath,t.path,i),o={pathKind:L.Relative,path:this.joinPath(t.path,i),basePath:t.basePath,getDirectoryName:()=>this.dirname(i),getAbsolutePath:()=>a};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`config`,path:a,label:r}),{path:o,success:!0,skipped:!1};try{let e=this.dirname(a);return this.ensureDirectory(e),this.writeFileSync(a,n.content),this.log.trace({action:`write`,type:`config`,path:a,label:r}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`config`,path:a,label:r,error:t}),{path:o,success:!1,error:e}}}getTargetRelativePath(e){let t=e.dir.path;if(e.type===Tt.EditorConfig)return`.editorconfig`;if(e.type!==Tt.IntellijIDEA)return this.basename(t);let n=t.indexOf(ry);return n===-1?this.joinPath(ry,`codeStyles`,this.basename(t)):t.slice(Math.max(0,n))}},oy=class extends Lg{constructor(){super(`MarkdownWhitespaceCleanupEffectInputPlugin`),this.registerEffect(`markdown-whitespace-cleanup`,this.cleanupWhitespace.bind(this),30)}async cleanupWhitespace(e){let{fs:t,path:n,shadowProjectDir:r,dryRun:i,logger:a}=e,o=[],s=[],c=[],l=[n.join(r,`src`),n.join(r,`app`),n.join(r,`dist`)];for(let n of l){if(!t.existsSync(n)){a.debug({action:`whitespace-cleanup`,message:`Directory does not exist, skipping`,dir:n});continue}this.processDirectory(e,n,o,s,c,i??!1)}let u=c.length>0;return u&&a.warn({action:`whitespace-cleanup`,errors:c.map(e=>({path:e.path,error:e.error.message}))}),{success:!u,description:i?`Would modify ${o.length} files, skip ${s.length} files`:`Modified ${o.length} files, skipped ${s.length} files`,modifiedFiles:o,skippedFiles:s,...u&&{error:Error(`${c.length} errors occurred during cleanup`)}}}processDirectory(e,t,n,r,i,a){let{fs:o,path:s,logger:c}=e,l;try{l=o.readdirSync(t,{withFileTypes:!0})}catch(e){i.push({path:t,error:e}),c.warn({action:`whitespace-cleanup`,message:`Failed to read directory`,path:t,error:e.message});return}for(let o of l){let c=s.join(t,o.name);o.isDirectory()?this.processDirectory(e,c,n,r,i,a):o.isFile()&&o.name.endsWith(`.md`)&&this.processMarkdownFile(e,c,n,r,i,a)}}processMarkdownFile(e,t,n,r,i,a){let{fs:o,logger:s}=e;try{let e=o.readFileSync(t,`utf8`),i=this.cleanMarkdownContent(e);if(e===i){r.push(t),s.debug({action:`whitespace-cleanup`,skipped:t,reason:`no changes needed`});return}a?(s.debug({action:`whitespace-cleanup`,dryRun:!0,wouldModify:t}),n.push(t)):(o.writeFileSync(t,i,`utf8`),n.push(t),s.debug({action:`whitespace-cleanup`,modified:t}))}catch(e){i.push({path:t,error:e}),s.warn({action:`whitespace-cleanup`,message:`Failed to process file`,path:t,error:e.message})}}cleanMarkdownContent(e){let t=this.detectLineEnding(e),n=e.split(/\r?\n/).map(e=>e.replace(/[ \t]+$/,``)),r=[],i=0;for(let e of n)e===``?(i++,i<=2&&r.push(e)):(i=0,r.push(e));return r.join(t)}detectLineEnding(e){return e.includes(`\r
|
|
1234
|
+
`).trim()}normalizeContent(e){let t=e.trim();return t.length===0?``:`${t}\n`}async writeGitExcludeFile(e,t,n,r){let i=e.collectedInputContext.workspace.directory.path,a={pathKind:L.Relative,path:f.relative(i,t),basePath:i,getDirectoryName:()=>f.basename(f.dirname(t)),getAbsolutePath:()=>t};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`gitExclude`,path:t,label:r}),{path:a,success:!0,skipped:!1};try{let e=f.dirname(t);d.existsSync(e)||(d.mkdirSync(e,{recursive:!0}),this.log.debug({action:`mkdir`,path:e,message:`Created .git/info directory`}));let i=this.normalizeContent(n);return d.writeFileSync(t,i,`utf8`),this.log.trace({action:`write`,type:`gitExclude`,path:t,label:r}),{path:a,success:!0}}catch(e){let n=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`gitExclude`,path:t,label:r,error:n}),{path:a,success:!1,error:e}}}};const Uv=Ut;function Wv(){return Uv[`public/gitignore`]?.content??``}var Gv=class extends Lv{constructor(){super(`GitIgnoreInputPlugin`,{fallbackContent:Wv()})}getFilePath(e){return f.join(e,`public`,`gitignore`)}getResultKey(){return`globalGitIgnore`}},Kv=class extends Lg{constructor(){super(`GlobalMemoryInputPlugin`)}async collect(e){let{userConfigOptions:t,fs:n,path:r,globalScope:i}=e,{shadowProjectDir:a}=this.resolveBasePaths(t),o=this.resolveShadowPath(t.shadowSourceProject.globalMemory.dist,a);if(!n.existsSync(o))return this.log.warn({action:`collect`,reason:`fileNotFound`,path:o}),{};if(!n.statSync(o).isFile())return this.log.warn({action:`collect`,reason:`notAFile`,path:o}),{};let s=n.readFileSync(o,`utf8`),c=jg(s),l;if(i!=null)try{l=await uv(s,{globalScope:i,basePath:r.dirname(o)})}catch(e){throw e instanceof qg&&(this.log.error(`MDX compilation failed: ${e.message}`),this.log.error(`Please check your configuration file (~/.aindex/.tnmsc.json) and ensure all required variables are defined.`),this.log.error(`For example, if using {profile.name}, add a "profile" section with "name" field to your config.`),u.default.exit(1)),e}else l=c.contentWithoutFrontMatter;return this.log.debug({action:`collect`,path:o,contentLength:l.length}),{globalMemory:{type:xt.GlobalMemory,content:l,length:l.length,filePathKind:L.Relative,...c.rawFrontMatter!=null&&{rawFrontMatter:c.rawFrontMatter},markdownAst:c.markdownAst,markdownContents:c.markdownContents,dir:{pathKind:L.Relative,path:r.basename(o),basePath:r.dirname(o),getDirectoryName:()=>r.basename(o),getAbsolutePath:()=>o},parentDirectoryPath:{type:wt.UserHome,directory:{pathKind:L.Relative,path:``,basePath:p.homedir(),getDirectoryName:()=>r.basename(p.homedir()),getAbsolutePath:()=>p.homedir()}}}}}},qv=class extends Lg{constructor(){super(`IdeConfigInputPlugin`)}collect(e){let{userConfigOptions:t,fs:n,path:r}=e,{shadowProjectDir:i}=this.resolveBasePaths(t),a=[`.editorconfig`,`.idea/codeStyles/Project.xml`,`.idea/codeStyles/codeStyleConfig.xml`,`.idea/.gitignore`,`.vscode/settings.json`,`.vscode/extensions.json`],o=[];for(let e of a){let t=r.join(i,e);if(n.existsSync(t)&&n.statSync(t).isFile()){let i=n.readFileSync(t,`utf8`),a=Tt.Original;e.includes(`.vscode`)?a=Tt.VSCode:e.includes(`.idea`)?a=Tt.IntellijIDEA:e.includes(`.editorconfig`)&&(a=Tt.EditorConfig),o.push({type:a,content:i,length:i.length,filePathKind:L.Absolute,dir:{pathKind:L.Absolute,path:t,getDirectoryName:()=>r.basename(t)}})}}return{ideConfigFiles:o}}};const Jv=`AGENTS.md`,Yv=`prompts`,Xv=`skills`,Zv=`SKILL.md`,Qv=`.aiassistant`,$v=`rules`,ey=`always.md`,ty=`codex`,ny=[`IntelliJIdea`,`WebStorm`,`RustRover`,`PyCharm`,`PyCharmCE`,`PhpStorm`,`GoLand`,`CLion`,`DataGrip`,`RubyMine`,`Rider`,`DataSpell`,`Aqua`];var ry=class extends Pg{constructor(){super(`JetBrainsAIAssistantCodexOutputPlugin`,{outputFileName:Jv,dependsOn:[`AgentsOutputPlugin`],indexignore:`.aiignore`})}async registerProjectOutputDirs(e){let t=[],{projects:n}=e.collectedInputContext.workspace;for(let e of n)e.dirFromWorkspacePath!=null&&t.push(this.createProjectRulesDirRelativePath(e.dirFromWorkspacePath));return t}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace;for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null&&(e.rootMemoryPrompt!=null&&t.push(this.createProjectRuleFileRelativePath(n,ey)),e.childMemoryPrompts!=null))for(let r of e.childMemoryPrompts){let e=this.buildChildRuleFileName(r);t.push(this.createProjectRuleFileRelativePath(n,e))}}return t.push(...this.registerProjectIgnoreOutputFiles(n)),t}async registerGlobalOutputDirs(e){let t=[],n=this.resolveCodexDirs();for(let r of n){let n=f.join(r,Yv);t.push({pathKind:L.Relative,path:Yv,basePath:r,getDirectoryName:()=>Yv,getAbsolutePath:()=>n});let{skills:i}=e.collectedInputContext;if(!(i==null||i.length===0))for(let e of i){let n=e.yamlFrontMatter?.name??e.dir.getDirectoryName(),i=f.join(r,Xv,n);t.push({pathKind:L.Relative,path:f.join(Xv,n),basePath:r,getDirectoryName:()=>n,getAbsolutePath:()=>i})}}return t}async registerGlobalOutputFiles(){return this.resolveCodexDirs().map(e=>({pathKind:L.Relative,path:Jv,basePath:e,getDirectoryName:()=>ty,getAbsolutePath:()=>f.join(e,Jv)}))}async canWrite(e){let{globalMemory:t,fastCommands:n,skills:r,workspace:i,aiAgentIgnoreConfigFiles:a}=e.collectedInputContext,o=t!=null,s=(n?.length??0)>0,c=(r?.length??0)>0,l=i.projects.some(e=>e.rootMemoryPrompt!=null||(e.childMemoryPrompts?.length??0)>0),u=a?.some(e=>e.fileName===`.aiignore`)??!1;return o||s||c||l||u?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,n=[],r=[];for(let r of t)if(r.dirFromWorkspacePath!=null){if(r.rootMemoryPrompt!=null){let t=this.buildAlwaysRuleContent(r.rootMemoryPrompt.content),i=await this.writeProjectRuleFile(e,r,ey,t,`projectRootRule`);n.push(i)}if(r.childMemoryPrompts!=null)for(let t of r.childMemoryPrompts){let i=this.buildChildRuleFileName(t),a=this.buildGlobRuleContent(t),o=await this.writeProjectRuleFile(e,r,i,a,`projectChildRule`);n.push(o)}}let i=await this.writeProjectIgnoreFiles(e);return n.push(...i),{files:n,dirs:r}}async writeGlobalOutputs(e){let{globalMemory:t,fastCommands:n,skills:r}=e.collectedInputContext,i=[],a=[],o=this.resolveCodexDirs();if(o.length===0)return{files:i,dirs:a};for(let a of o){if(t!=null){let n=f.join(a,Jv),r={pathKind:L.Relative,path:Jv,basePath:a,getDirectoryName:()=>ty,getAbsolutePath:()=>n};if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`globalMemory`,path:n}),i.push({path:r,success:!0,skipped:!1});else try{this.ensureDirectory(a),d.writeFileSync(n,t.content,`utf8`),this.log.trace({action:`write`,type:`globalMemory`,path:n}),i.push({path:r,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`globalMemory`,path:n,error:t}),i.push({path:r,success:!1,error:e})}}if(n!=null&&n.length>0)for(let t of n){let n=await this.writeGlobalFastCommand(e,a,t);i.push(...n)}if(!(r==null||r.length===0))for(let t of r){let n=await this.writeGlobalSkill(e,a,t);i.push(...n)}}return{files:i,dirs:a}}resolveCodexDirs(){let e=f.join(Xe(),`JetBrains`);if(!this.existsSync(e))return[];try{return this.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()?this.isSupportedIdeDir(e.name):!1).map(t=>f.join(e,t.name,`aia`,ty))}catch(t){let n=t instanceof Error?t.message:String(t);return this.log.warn({action:`scan`,type:`jetbrains`,path:e,error:n}),[]}}createProjectRulesDirRelativePath(e){let t=f.join(e.path,Qv,$v);return{pathKind:L.Relative,path:t,basePath:e.basePath,getDirectoryName:()=>$v,getAbsolutePath:()=>f.join(e.basePath,t)}}createProjectRuleFileRelativePath(e,t){let n=f.join(e.path,Qv,$v,t);return{pathKind:L.Relative,path:n,basePath:e.basePath,getDirectoryName:()=>$v,getAbsolutePath:()=>f.join(e.basePath,n)}}buildChildRuleFileName(e){let t=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``).replaceAll(`/`,`-`);return`glob-${t.length>0?t:`root`}.md`}buildChildRulePattern(e){let t=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``);return t.length===0?`**/*`:`${t}/**`}buildAlwaysRuleContent(e){return Ag({apply:`始终`},e)}buildGlobRuleContent(e){return Ag({apply:`按文件模式`,模式:this.buildChildRulePattern(e)},e.content)}async writeProjectRuleFile(e,t,n,r,i){let a=t.dirFromWorkspacePath,o=f.join(a.basePath,a.path,Qv,$v),s=f.join(o,n),c=this.createProjectRuleFileRelativePath(a,n);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:i,path:s}),{path:c,success:!0,skipped:!1};try{return this.ensureDirectory(o),d.writeFileSync(s,r,`utf8`),this.log.trace({action:`write`,type:i,path:s}),{path:c,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:i,path:s,error:t}),{path:c,success:!1,error:e}}}isSupportedIdeDir(e){return ny.some(t=>e.startsWith(t))}async writeGlobalFastCommand(e,t,n){let r=[],i=this.getTransformOptionsFromContext(e),a=this.transformFastCommandName(n,i),o=f.join(t,Yv),s=f.join(o,a),c={pathKind:L.Relative,path:f.join(Yv,a),basePath:t,getDirectoryName:()=>Yv,getAbsolutePath:()=>s},l=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalFastCommand`,path:s}),[{path:c,success:!0,skipped:!1}];try{this.ensureDirectory(o),d.writeFileSync(s,l,`utf8`),this.log.trace({action:`write`,type:`globalFastCommand`,path:s}),r.push({path:c,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`globalFastCommand`,path:s,error:t}),r.push({path:c,success:!1,error:e})}return r}async writeGlobalSkill(e,t,n){let r=[],i=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),a=f.join(t,Xv,i),o=f.join(a,Zv),s={pathKind:L.Relative,path:f.join(Xv,i,Zv),basePath:t,getDirectoryName:()=>i,getAbsolutePath:()=>o},c=this.buildCodexSkillContent(n);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalSkill`,path:o}),[{path:s,success:!0,skipped:!1}];try{if(this.ensureDirectory(a),d.writeFileSync(o,c,`utf8`),this.log.trace({action:`write`,type:`globalSkill`,path:o}),r.push({path:s,success:!0}),n.childDocs!=null)for(let o of n.childDocs){let n=await this.writeSkillReferenceDocument(e,a,i,o,t);r.push(...n)}if(n.resources!=null)for(let o of n.resources){let n=await this.writeSkillResource(e,a,i,o,t);r.push(...n)}}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`globalSkill`,path:o,error:t}),r.push({path:s,success:!1,error:e})}return r}buildCodexSkillContent(e){let t=e.yamlFrontMatter,n=this.normalizeSkillName(t.name,64),r=this.normalizeToSingleLine(t.description,1024),i={};t.displayName!=null&&(i[`short-description`]=t.displayName),t.version!=null&&(i.version=t.version),t.author!=null&&(i.author=t.author),t.keywords!=null&&t.keywords.length>0&&(i.keywords=[...t.keywords]);let a={name:n,description:r};return Object.keys(i).length>0&&(a.metadata=i),t.allowTools!=null&&t.allowTools.length>0&&(a[`allowed-tools`]=t.allowTools.join(` `)),Ag(a,e.content)}normalizeSkillName(e,t){let n=e.toLowerCase().replaceAll(/[^a-z0-9-]/g,`-`).replaceAll(/-+/g,`-`).replaceAll(/^-+|-+$/g,``);return n.length>t&&(n=n.slice(0,t).replace(/-+$/,``)),n}normalizeToSingleLine(e,t){let n=e.replaceAll(/[\r\n]+/g,` `).replaceAll(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-3)}...`:n}async writeSkillReferenceDocument(e,t,n,r,i){let a=[],o=r.dir.path.replace(/\.mdx$/,`.md`),s=f.join(t,o),c={pathKind:L.Relative,path:f.join(Xv,n,o),basePath:i,getDirectoryName:()=>n,getAbsolutePath:()=>s};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`skillRefDoc`,path:s}),[{path:c,success:!0,skipped:!1}];try{let e=f.dirname(s);this.ensureDirectory(e),d.writeFileSync(s,r.content,`utf8`),this.log.trace({action:`write`,type:`skillRefDoc`,path:s}),a.push({path:c,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skillRefDoc`,path:s,error:t}),a.push({path:c,success:!1,error:e})}return a}async writeSkillResource(e,t,n,r,i){let a=[],o=f.join(t,r.relativePath),s={pathKind:L.Relative,path:f.join(Xv,n,r.relativePath),basePath:i,getDirectoryName:()=>n,getAbsolutePath:()=>o};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`skillResource`,path:o}),[{path:s,success:!0,skipped:!1}];try{let e=f.dirname(o);this.ensureDirectory(e),d.writeFileSync(o,r.content,`utf8`),this.log.trace({action:`write`,type:`skillResource`,path:o}),a.push({path:s,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skillResource`,path:o,error:t}),a.push({path:s,success:!1,error:e})}return a}};const iy=`.idea`,ay=[`.editorconfig`,`.idea/codeStyles/Project.xml`,`.idea/codeStyles/codeStyleConfig.xml`,`.idea/.gitignore`];var oy=class extends Pg{constructor(){super(`JetBrainsIDECodeStyleConfigOutputPlugin`)}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace,{ideConfigFiles:r}=e.collectedInputContext;if(!r.some(e=>e.type===Tt.IntellijIDEA||e.type===Tt.EditorConfig))return t;for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null&&e.isPromptSourceProject!==!0)for(let e of ay){let r=this.joinPath(n.path,e);t.push({pathKind:L.Relative,path:r,basePath:n.basePath,getDirectoryName:()=>this.dirname(e),getAbsolutePath:()=>this.resolvePath(n.basePath,r)})}}return t}async canWrite(e){let{ideConfigFiles:t}=e.collectedInputContext;return t.some(e=>e.type===Tt.IntellijIDEA||e.type===Tt.EditorConfig)?!0:(this.log.debug(`skipped`,{reason:`no JetBrains IDE config files found`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,{ideConfigFiles:n}=e.collectedInputContext,r=[],i=[],a=n.filter(e=>e.type===Tt.IntellijIDEA||e.type===Tt.EditorConfig);for(let n of t){let t=n.dirFromWorkspacePath;if(t==null)continue;let i=n.name??`unknown`;for(let n of a){let a=await this.writeConfigFile(e,t,n,`project:${i}`);r.push(a)}}return{files:r,dirs:i}}async writeConfigFile(e,t,n,r){let i=this.getTargetRelativePath(n),a=this.resolvePath(t.basePath,t.path,i),o={pathKind:L.Relative,path:this.joinPath(t.path,i),basePath:t.basePath,getDirectoryName:()=>this.dirname(i),getAbsolutePath:()=>a};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`config`,path:a,label:r}),{path:o,success:!0,skipped:!1};try{let e=this.dirname(a);return this.ensureDirectory(e),this.writeFileSync(a,n.content),this.log.trace({action:`write`,type:`config`,path:a,label:r}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`config`,path:a,label:r,error:t}),{path:o,success:!1,error:e}}}getTargetRelativePath(e){let t=e.dir.path;if(e.type===Tt.EditorConfig)return`.editorconfig`;if(e.type!==Tt.IntellijIDEA)return this.basename(t);let n=t.indexOf(iy);return n===-1?this.joinPath(iy,`codeStyles`,this.basename(t)):t.slice(Math.max(0,n))}},sy=class extends Lg{constructor(){super(`MarkdownWhitespaceCleanupEffectInputPlugin`),this.registerEffect(`markdown-whitespace-cleanup`,this.cleanupWhitespace.bind(this),30)}async cleanupWhitespace(e){let{fs:t,path:n,shadowProjectDir:r,dryRun:i,logger:a}=e,o=[],s=[],c=[],l=[n.join(r,`src`),n.join(r,`app`),n.join(r,`dist`)];for(let n of l){if(!t.existsSync(n)){a.debug({action:`whitespace-cleanup`,message:`Directory does not exist, skipping`,dir:n});continue}this.processDirectory(e,n,o,s,c,i??!1)}let u=c.length>0;return u&&a.warn({action:`whitespace-cleanup`,errors:c.map(e=>({path:e.path,error:e.error.message}))}),{success:!u,description:i?`Would modify ${o.length} files, skip ${s.length} files`:`Modified ${o.length} files, skipped ${s.length} files`,modifiedFiles:o,skippedFiles:s,...u&&{error:Error(`${c.length} errors occurred during cleanup`)}}}processDirectory(e,t,n,r,i,a){let{fs:o,path:s,logger:c}=e,l;try{l=o.readdirSync(t,{withFileTypes:!0})}catch(e){i.push({path:t,error:e}),c.warn({action:`whitespace-cleanup`,message:`Failed to read directory`,path:t,error:e.message});return}for(let o of l){let c=s.join(t,o.name);o.isDirectory()?this.processDirectory(e,c,n,r,i,a):o.isFile()&&o.name.endsWith(`.md`)&&this.processMarkdownFile(e,c,n,r,i,a)}}processMarkdownFile(e,t,n,r,i,a){let{fs:o,logger:s}=e;try{let e=o.readFileSync(t,`utf8`),i=this.cleanMarkdownContent(e);if(e===i){r.push(t),s.debug({action:`whitespace-cleanup`,skipped:t,reason:`no changes needed`});return}a?(s.debug({action:`whitespace-cleanup`,dryRun:!0,wouldModify:t}),n.push(t)):(o.writeFileSync(t,i,`utf8`),n.push(t),s.debug({action:`whitespace-cleanup`,modified:t}))}catch(e){i.push({path:t,error:e}),s.warn({action:`whitespace-cleanup`,message:`Failed to process file`,path:t,error:e.message})}}cleanMarkdownContent(e){let t=this.detectLineEnding(e),n=e.split(/\r?\n/).map(e=>e.replace(/[ \t]+$/,``)),r=[],i=0;for(let e of n)e===``?(i++,i<=2&&r.push(e)):(i=0,r.push(e));return r.join(t)}detectLineEnding(e){return e.includes(`\r
|
|
1235
1235
|
`)?`\r
|
|
1236
1236
|
`:`
|
|
1237
|
-
`}collect(e){return{}}};const sy=`.config/opencode`,cy=`opencode.json`,ly=`opencode-rules@latest`;var uy=class extends dv{constructor(){super(`OpencodeCLIOutputPlugin`,{globalConfigDir:sy,outputFileName:`AGENTS.md`,commandsSubDir:`commands`,agentsSubDir:`agents`,skillsSubDir:`skills`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0,dependsOn:[`AgentsOutputPlugin`]}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=this.getGlobalConfigDir(),n=f.join(t,cy);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfigCleanup`,path:n}),{success:!0,description:`Would reset opencode.json mcp to empty`};try{if(d.existsSync(n)){let e=d.readFileSync(n,`utf8`),t=JSON.parse(e);t.mcp={};let r=t.plugin;if(Array.isArray(r)){let e=r.filter(e=>e!==ly);e.length>0?t.plugin=e:delete t.plugin}d.writeFileSync(n,JSON.stringify(t,null,2))}return this.log.trace({action:`clean`,type:`mcpConfigCleanup`,path:n}),{success:!0,description:`Reset opencode.json mcp to empty`}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`clean`,type:`mcpConfigCleanup`,path:n,error:t}),{success:!1,error:e,description:`Failed to reset opencode.json mcp`}}})}async registerGlobalOutputFiles(e){let t=await super.registerGlobalOutputFiles(e),n=this.getGlobalConfigDir();if(e.collectedInputContext.skills?.some(e=>e.mcpConfig!=null)??!1){let e=f.join(n,cy);t.push({pathKind:L.Relative,path:cy,basePath:n,getDirectoryName:()=>sy,getAbsolutePath:()=>e})}return t.map(e=>{let t=e.path.replaceAll(`\\`,`/`),r=`/${this.skillsSubDir}/`,i=`${this.skillsSubDir}/`;if(!(t.includes(r)||t.startsWith(i)))return e;let a=t.split(`/`),o=a.indexOf(this.skillsSubDir);if(o<0||o+1>=a.length)return e;let s=a[o+1];if(s==null)return e;let c=this.validateAndNormalizeSkillName(s),l=[...a];l[o+1]=c;let u=l.join(`/`);return{...e,path:u,getDirectoryName:()=>c,getAbsolutePath:()=>f.join(n,u.replaceAll(`/`,f.sep))}})}async writeGlobalOutputs(e){let t=await super.writeGlobalOutputs(e),n=[...t.files],{skills:r}=e.collectedInputContext;if(r==null)return{files:n,dirs:t.dirs};let i=await this.writeGlobalMcpConfig(e,r);return i!=null&&n.push(i),{files:n,dirs:t.dirs}}async writeGlobalMcpConfig(e,t){let n={};for(let e of t){if(e.mcpConfig==null)continue;let{mcpServers:t}=e.mcpConfig;for(let[e,r]of Object.entries(t))n[e]=this.transformMcpConfigForOpencode(r)}if(Object.keys(n).length===0)return null;let r=this.getGlobalConfigDir(),i=f.join(r,cy),a={pathKind:L.Relative,path:cy,basePath:r,getDirectoryName:()=>sy,getAbsolutePath:()=>i},o={};try{if(d.existsSync(i)){let e=d.readFileSync(i,`utf8`);o=JSON.parse(e)}}catch{o={}}o.$schema=`https://opencode.ai/config.json`,o.mcp=n;let s=o.plugin,c=Array.isArray(s)?s.map(e=>String(e)):[];c.includes(ly)||c.push(ly),o.plugin=c;let l=JSON.stringify(o,null,2);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalMcpConfig`,path:i,serverCount:Object.keys(n).length}),{path:a,success:!0,skipped:!1};try{return this.ensureDirectory(r),d.writeFileSync(i,l),this.log.trace({action:`write`,type:`globalMcpConfig`,path:i,serverCount:Object.keys(n).length}),{path:a,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalMcpConfig`,path:i,error:t}),{path:a,success:!1,error:e}}}transformMcpConfigForOpencode(e){let t={};if(e.command!=null){t.type=`local`;let n=[e.command];e.args!=null&&n.push(...e.args),t.command=n,e.env!=null&&(t.environment=e.env)}else{t.type=`remote`;let n=e;n.url==null?n.serverUrl!=null&&(t.url=n.serverUrl):t.url=n.url}return t.enabled=e.disabled!==!0,t}async writeSubAgent(e,t,n){let r=n.dir.path.replace(/\.mdx$/,`.md`),i=f.join(t,this.agentsSubDir),a=f.join(i,r),o=this.buildOpencodeAgentFrontMatter(n),s=this.buildMarkdownContent(n.content,o);return[await this.writeFile(e,a,s,`subAgent`)]}buildOpencodeAgentFrontMatter(e){let t={},n=e.yamlFrontMatter;if(n?.description!=null&&(t.description=n.description),t.mode=n?.mode??`subagent`,n?.model!=null&&(t.model=n.model),n?.temperature!=null&&(t.temperature=n.temperature),n?.maxSteps!=null&&(t.maxSteps=n.maxSteps),n?.hidden!=null&&(t.hidden=n.hidden),n?.allowTools!=null&&Array.isArray(n.allowTools)){let e={};for(let t of n.allowTools)e[String(t)]=!0;t.tools=e}n?.permission!=null&&typeof n.permission==`object`&&(t.permission=n.permission);for(let[e,r]of Object.entries(n??{}))[`description`,`mode`,`model`,`temperature`,`maxSteps`,`hidden`,`allowTools`,`permission`,`namingCase`,`name`,`color`].includes(e)||(t[e]=r);return t}async writeFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),i=this.transformFastCommandName(n,r),a=f.join(t,this.commandsSubDir),o=f.join(a,i),s=this.buildOpencodeCommandFrontMatter(n),c=this.buildMarkdownContent(n.content,s);return[await this.writeFile(e,o,c,`fastCommand`)]}buildOpencodeCommandFrontMatter(e){let t={},n=e.yamlFrontMatter;if(n?.description!=null&&(t.description=n.description),n?.agent!=null&&(t.agent=n.agent),n?.model!=null&&(t.model=n.model),n?.allowTools!=null&&Array.isArray(n.allowTools)){let e={};for(let t of n.allowTools)e[String(t)]=!0;t.tools=e}for(let[e,r]of Object.entries(n??{}))[`description`,`agent`,`model`,`allowTools`,`namingCase`,`argumentHint`].includes(e)||(t[e]=r);return t}async writeSkill(e,t,n){let r=[],i=this.validateAndNormalizeSkillName(n.yamlFrontMatter?.name??n.dir.getDirectoryName()),a=f.join(t,this.skillsSubDir,i),o=f.join(a,`SKILL.md`),s=this.buildOpencodeSkillFrontMatter(n,i),c=this.buildMarkdownContent(n.content,s),l=await this.writeFile(e,o,c,`skill`);if(r.push(l),n.childDocs!=null)for(let o of n.childDocs){let n=await this.writeSkillReferenceDocument(e,a,i,o,t);r.push(...n)}if(n.resources!=null)for(let o of n.resources){let n=await this.writeSkillResource(e,a,i,o,t);r.push(...n)}return r}buildOpencodeSkillFrontMatter(e,t){let n={},r=e.yamlFrontMatter;n.name=t,r?.description!=null&&(n.description=r.description),n.license=r?.license??`MIT`,n.compatibility=r?.compatibility??`opencode`;let i={};for(let e of[`author`,`version`,`keywords`,`category`,`repository`,`displayName`])r?.[e]!=null&&(i[e]=r[e]);let a=new Set([`name`,`description`,`license`,`compatibility`,`namingCase`,`allowTools`,`keywords`,`displayName`,`author`,`version`]);for(let[e,t]of Object.entries(r??{}))a.has(e)||(i[e]=t);return Object.keys(i).length>0&&(n.metadata=i),n}validateAndNormalizeSkillName(e){let t=e.toLowerCase();return t=t.replaceAll(/[^a-z0-9-]+/g,`-`),t=t.replaceAll(/-+/g,`-`),t=t.replaceAll(/^-|-$/g,``),t.length===0?t=`skill`:t.length>64&&(t=t.slice(0,64),t=t.replace(/-$/,``)),t}},dy=class extends Lg{constructor(){super(`OrphanFileCleanupEffectInputPlugin`),this.registerEffect(`orphan-file-cleanup`,this.cleanupOrphanFiles.bind(this),20)}async cleanupOrphanFiles(e){let{fs:t,path:n,shadowProjectDir:r,dryRun:i,logger:a}=e,o=n.join(r,`dist`),s=[],c=[],l=[];if(!t.existsSync(o))return a.debug({action:`orphan-cleanup`,message:`dist/ directory does not exist, skipping`,distDir:o}),{success:!0,description:`dist/ directory does not exist, nothing to clean`,deletedFiles:s,deletedDirs:c};for(let r of[`skills`,`commands`,`agents`,`app`]){let a=n.join(o,r);t.existsSync(a)&&this.cleanupDirectory(e,a,r,s,c,l,i??!1)}let u=l.length>0;return u&&a.warn({action:`orphan-cleanup`,errors:l.map(e=>({path:e.path,error:e.error.message}))}),{success:!u,description:i?`Would delete ${s.length} files and ${c.length} directories`:`Deleted ${s.length} files and ${c.length} directories`,deletedFiles:s,deletedDirs:c,...u&&{error:Error(`${l.length} errors occurred during cleanup`)}}}cleanupDirectory(e,t,n,r,i,a,o){let{fs:s,path:c,shadowProjectDir:l,logger:u}=e,d;try{d=s.readdirSync(t,{withFileTypes:!0})}catch(e){a.push({path:t,error:e}),u.warn({action:`orphan-cleanup`,message:`Failed to read directory`,path:t,error:e.message});return}for(let f of d){let d=c.join(t,f.name);if(f.isDirectory())this.cleanupDirectory(e,d,n,r,i,a,o),this.removeEmptyDirectory(e,d,i,a,o);else if(f.isFile()&&this.isOrphanFile(e,d,n,l))if(o)u.debug({action:`orphan-cleanup`,dryRun:!0,wouldDelete:d}),r.push(d);else try{s.unlinkSync(d),r.push(d),u.debug({action:`orphan-cleanup`,deleted:d})}catch(e){a.push({path:d,error:e}),u.warn({action:`orphan-cleanup`,message:`Failed to delete file`,path:d,error:e.message})}}}isOrphanFile(e,t,n,r){let{fs:i,path:a}=e,o=a.basename(t),s=o.endsWith(`.mdx`),c=a.join(r,`dist`,n),l=a.relative(c,t),u=a.dirname(l),d=o.replace(/\.mdx$/,``);if(s)return!this.getPossibleSourcePaths(a,r,n,d,u).some(e=>i.existsSync(e));let f=[];return n===`app`?f.push(a.join(r,`app`,l)):f.push(a.join(r,`src`,n,l)),!f.some(e=>i.existsSync(e))}getPossibleSourcePaths(e,t,n,r,i){switch(n){case`skills`:return i===`.`?[e.join(t,`src`,`skills`,r,`SKILL.cn.mdx`),e.join(t,`src`,`skills`,`${r}.cn.mdx`)]:[e.join(t,`src`,`skills`,i,`${r}.cn.mdx`)];case`commands`:return i===`.`?[e.join(t,`src`,`commands`,`${r}.cn.mdx`)]:[e.join(t,`src`,`commands`,i,`${r}.cn.mdx`)];case`agents`:return i===`.`?[e.join(t,`src`,`agents`,`${r}.cn.mdx`)]:[e.join(t,`src`,`agents`,i,`${r}.cn.mdx`)];case`app`:return i===`.`?[e.join(t,`app`,`${r}.cn.mdx`)]:[e.join(t,`app`,i,`${r}.cn.mdx`)];default:return[]}}removeEmptyDirectory(e,t,n,r,i){let{fs:a,logger:o}=e;try{a.readdirSync(t).length===0&&(i?(o.debug({action:`orphan-cleanup`,dryRun:!0,wouldDeleteDir:t}),n.push(t)):(a.rmdirSync(t),n.push(t),o.debug({action:`orphan-cleanup`,deletedDir:t})))}catch(e){r.push({path:t,error:e}),o.warn({action:`orphan-cleanup`,message:`Failed to check/remove directory`,path:t,error:e.message})}}collect(e){return{}}},fy=class{registryPath;log;constructor(e,t){this.registryPath=this.resolvePath(e),this.log=t??nn(this.constructor.name)}resolvePath(e){return e.startsWith(`~`)?f.join(p.homedir(),e.slice(1)):f.resolve(e)}getRegistryDir(){return f.dirname(this.registryPath)}ensureRegistryDir(){let e=this.getRegistryDir();d.existsSync(e)||d.mkdirSync(e,{recursive:!0})}read(){if(!d.existsSync(this.registryPath))return this.log.debug(`registry not found`,{path:this.registryPath}),this.createInitialRegistry();try{let e=d.readFileSync(this.registryPath,`utf8`);return JSON.parse(e)}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error(`parse failed`,{path:this.registryPath,error:t}),this.createInitialRegistry()}}write(e,t){let n={...e,lastUpdated:new Date().toISOString()};if(t===!0)return this.log.trace({action:`dryRun`,type:`registry`,path:this.registryPath}),!0;let r=`${this.registryPath}.tmp.${Date.now()}`;try{this.ensureRegistryDir();let e=JSON.stringify(n,null,2);return d.writeFileSync(r,e,`utf8`),d.renameSync(r,this.registryPath),this.log.trace({action:`write`,type:`registry`,path:this.registryPath}),!0}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`registry`,path:this.registryPath,error:t});try{d.existsSync(r)&&d.unlinkSync(r)}catch{}return!1}}register(e,t){let n=[],r=this.read(),i=this.merge(r,e),a=this.write(i,t);for(let r of e){let e=this.getEntryName(r);a?(n.push({success:!0,entryName:e}),t===!0?this.log.trace({action:`dryRun`,type:`registerEntry`,entryName:e}):this.log.trace({action:`register`,type:`entry`,entryName:e})):(n.push({success:!1,entryName:e,error:Error(`Failed to write registry file`)}),this.log.error(`register entry failed`,{entryName:e}))}return n}generateEntryId(e){let t=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return e==null?t:`${e}-${t}`}},py=class extends Lg{constructor(){super(`SkillNonSrcFileSyncEffectInputPlugin`),this.registerEffect(`skill-non-src-file-sync`,this.syncNonSrcFiles.bind(this),10)}async syncNonSrcFiles(e){let{fs:t,path:n,shadowProjectDir:r,dryRun:i,logger:a}=e,o=n.join(r,`src`,`skills`),s=n.join(r,`dist`,`skills`),c=[],l=[],u=[],d=[];if(!t.existsSync(o))return a.debug({action:`skill-sync`,message:`src/skills/ directory does not exist, skipping`,srcSkillsDir:o}),{success:!0,description:`src/skills/ directory does not exist, nothing to sync`,copiedFiles:c,skippedFiles:l,createdDirs:u};this.syncDirectoryRecursive(e,o,s,``,c,l,u,d,i??!1);let f=d.length>0;return f&&a.warn({action:`skill-sync`,errors:d.map(e=>({path:e.path,error:e.error.message}))}),{success:!f,description:i?`Would copy ${c.length} files, skip ${l.length} files`:`Copied ${c.length} files, skipped ${l.length} files`,copiedFiles:c,skippedFiles:l,createdDirs:u,...f&&{error:Error(`${d.length} errors occurred during sync`)},modifiedFiles:c}}syncDirectoryRecursive(e,t,n,r,i,a,o,s,c){let{fs:l,path:u,logger:d}=e,f=r?u.join(t,r):t;if(!l.existsSync(f))return;let p;try{p=l.readdirSync(f,{withFileTypes:!0})}catch(e){s.push({path:f,error:e}),d.warn({action:`skill-sync`,message:`Failed to read directory`,path:f,error:e.message});return}for(let f of p){let p=r?u.join(r,f.name):f.name,m=u.join(t,p),h=u.join(n,p);if(f.isDirectory())this.syncDirectoryRecursive(e,t,n,p,i,a,o,s,c);else if(f.isFile()){if(f.name.endsWith(`.cn.mdx`))continue;let e=u.dirname(h);if(!l.existsSync(e))if(c)d.debug({action:`skill-sync`,dryRun:!0,wouldCreateDir:e}),o.push(e);else try{l.mkdirSync(e,{recursive:!0}),o.push(e),d.debug({action:`skill-sync`,createdDir:e})}catch(t){s.push({path:e,error:t}),d.warn({action:`skill-sync`,message:`Failed to create directory`,path:e,error:t.message});continue}if(l.existsSync(h))try{let e=l.readFileSync(m),t=l.readFileSync(h);if(this.computeHash(e)===this.computeHash(t)){a.push(h),d.debug({action:`skill-sync`,skipped:h,reason:`identical content`});continue}}catch(e){d.debug({action:`skill-sync`,message:`Could not compare files, will copy`,path:h,error:e.message})}if(c)d.debug({action:`skill-sync`,dryRun:!0,wouldCopy:{from:m,to:h}}),i.push(h);else try{l.copyFileSync(m,h),i.push(h),d.debug({action:`skill-sync`,copied:{from:m,to:h}})}catch(e){s.push({path:h,error:e}),d.warn({action:`skill-sync`,message:`Failed to copy file`,from:m,to:h,error:e.message})}}}}computeHash(e){return(0,g.createHash)(`sha256`).update(e).digest(`hex`)}collect(e){return{}}};const my=`.codeium/windsurf`,hy=`global_workflows`,gy=`memories`,_y=`global_rules.md`,vy=`skills`,yy=`SKILL.md`,by=`.windsurf`,xy=`rules`;var Sy=class extends Pg{constructor(){super(`WindsurfOutputPlugin`,{globalConfigDir:my,outputFileName:``,dependsOn:[`AgentsOutputPlugin`],indexignore:`.codeignore`})}async registerGlobalOutputDirs(e){let t=[],{fastCommands:n,skills:r,rules:i}=e.collectedInputContext;if(n!=null&&n.length>0){let e=this.getGlobalWorkflowsDir();t.push({pathKind:L.Relative,path:hy,basePath:this.getCodeiumWindsurfDir(),getDirectoryName:()=>hy,getAbsolutePath:()=>e})}if(r!=null&&r.length>0)for(let e of r){let n=e.yamlFrontMatter.name,r=f.join(this.getCodeiumWindsurfDir(),vy,n);t.push({pathKind:L.Relative,path:f.join(vy,n),basePath:this.getCodeiumWindsurfDir(),getDirectoryName:()=>n,getAbsolutePath:()=>r})}let a=i?.filter(e=>e.scope===`global`);if(a==null||a.length===0)return t;let o=this.getCodeiumWindsurfDir(),s=f.join(o,gy);return t.push({pathKind:L.Relative,path:gy,basePath:o,getDirectoryName:()=>gy,getAbsolutePath:()=>s}),t}async registerGlobalOutputFiles(e){let t=[],{skills:n,fastCommands:r}=e.collectedInputContext;if(r!=null&&r.length>0){let n=this.getGlobalWorkflowsDir(),i=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});for(let e of r){let r=this.transformFastCommandName(e,i),a=f.join(n,r);t.push({pathKind:L.Relative,path:f.join(hy,r),basePath:this.getCodeiumWindsurfDir(),getDirectoryName:()=>hy,getAbsolutePath:()=>a})}}let i=e.collectedInputContext.rules?.filter(e=>e.scope===`global`);if(i!=null&&i.length>0){let e=this.getCodeiumWindsurfDir(),n=f.join(e,gy);for(let r of i){let i=this.buildRuleFileName(r),a=f.join(n,i);t.push({pathKind:L.Relative,path:f.join(gy,i),basePath:e,getDirectoryName:()=>gy,getAbsolutePath:()=>a})}}if(n==null||n.length===0)return t;let a=this.getSkillsDir(),o=this.getCodeiumWindsurfDir();for(let e of n){let n=e.yamlFrontMatter.name,r=f.join(a,n);if(t.push({pathKind:L.Relative,path:f.join(vy,n,yy),basePath:o,getDirectoryName:()=>n,getAbsolutePath:()=>f.join(r,yy)}),e.childDocs!=null)for(let i of e.childDocs){let e=i.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:f.join(vy,n,e),basePath:o,getDirectoryName:()=>n,getAbsolutePath:()=>f.join(r,e)})}if(e.resources!=null)for(let i of e.resources)t.push({pathKind:L.Relative,path:f.join(vy,n,i.relativePath),basePath:o,getDirectoryName:()=>n,getAbsolutePath:()=>f.join(r,i.relativePath)})}return t}async canWrite(e){let{skills:t,fastCommands:n,globalMemory:r,rules:i,aiAgentIgnoreConfigFiles:a}=e.collectedInputContext,o=(t?.length??0)>0,s=(n?.length??0)>0,c=(i?.length??0)>0,l=r!=null,u=a?.some(e=>e.fileName===`.codeignore`)??!1;return o||s||l||c||u?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeGlobalOutputs(e){let{skills:t,fastCommands:n,globalMemory:r,rules:i}=e.collectedInputContext,a=[],o=[];if(r!=null){let t=await this.writeGlobalMemory(e,r.content);a.push(t)}if(t!=null&&t.length>0){let n=this.getSkillsDir();for(let r of t){let t=await this.writeGlobalSkill(e,n,r);a.push(...t)}}if(n!=null&&n.length>0){let t=this.getGlobalWorkflowsDir();for(let r of n){let n=await this.writeGlobalWorkflow(e,t,r);a.push(n)}}let s=i?.filter(e=>e.scope===`global`);if(s==null||s.length===0)return{files:a,dirs:o};let c=this.getGlobalMemoriesDir();for(let t of s){let n=await this.writeRuleFile(e,c,t,this.getCodeiumWindsurfDir(),gy);a.push(n)}return{files:a,dirs:o}}async registerProjectOutputDirs(e){let t=[],{workspace:n,rules:r}=e.collectedInputContext,i=r?.filter(e=>e.scope===`project`);if(i==null||i.length===0)return t;for(let e of n.projects){let n=e.dirFromWorkspacePath;if(n==null)continue;let r=f.join(n.path,by,xy);t.push({pathKind:L.Relative,path:r,basePath:n.basePath,getDirectoryName:()=>xy,getAbsolutePath:()=>f.join(n.basePath,r)})}return t}async registerProjectOutputFiles(e){let t=[],{workspace:n,rules:r}=e.collectedInputContext,i=r?.filter(e=>e.scope===`project`);if(i!=null&&i.length>0)for(let e of n.projects){let n=e.dirFromWorkspacePath;if(n!=null)for(let e of i){let r=this.buildRuleFileName(e),i=f.join(n.path,by,xy,r);t.push({pathKind:L.Relative,path:i,basePath:n.basePath,getDirectoryName:()=>xy,getAbsolutePath:()=>f.join(n.basePath,i)})}}return t.push(...this.registerProjectIgnoreOutputFiles(n.projects)),t}async writeProjectOutputs(e){let t=[],{workspace:n,rules:r}=e.collectedInputContext,i=r?.filter(e=>e.scope===`project`);if(i!=null&&i.length>0)for(let r of n.projects){let n=r.dirFromWorkspacePath;if(n==null)continue;let a=f.join(n.basePath,n.path,by,xy);for(let r of i){let i=await this.writeRuleFile(e,a,r,n.basePath,f.join(n.path,by,xy));t.push(i)}}let a=await this.writeProjectIgnoreFiles(e);return t.push(...a),{files:t,dirs:[]}}getSkillsDir(){return f.join(this.getCodeiumWindsurfDir(),vy)}getCodeiumWindsurfDir(){return f.join(this.getHomeDir(),my)}getGlobalMemoriesDir(){return f.join(this.getCodeiumWindsurfDir(),gy)}getGlobalWorkflowsDir(){return f.join(this.getCodeiumWindsurfDir(),hy)}async writeGlobalMemory(e,t){let n=this.getGlobalMemoriesDir(),r=f.join(n,_y),i=this.getCodeiumWindsurfDir(),a={pathKind:L.Relative,path:f.join(gy,_y),basePath:i,getDirectoryName:()=>gy,getAbsolutePath:()=>r};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalMemory`,path:r}),{path:a,success:!0,skipped:!1};try{return this.ensureDirectory(n),this.writeFileSync(r,t),this.log.trace({action:`write`,type:`globalMemory`,path:r}),{path:a,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalMemory`,path:r,error:t}),{path:a,success:!1,error:e}}}async writeGlobalWorkflow(e,t,n){let r=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),i=this.transformFastCommandName(n,r),a=f.join(t,i),o={pathKind:L.Relative,path:f.join(hy,i),basePath:this.getCodeiumWindsurfDir(),getDirectoryName:()=>hy,getAbsolutePath:()=>a},s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalWorkflow`,path:a}),{path:o,success:!0,skipped:!1};try{return this.ensureDirectory(t),d.writeFileSync(a,s),this.log.trace({action:`write`,type:`globalWorkflow`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalWorkflow`,path:a,error:t}),{path:o,success:!1,error:e}}}async writeGlobalSkill(e,t,n){let r=[],i=n.yamlFrontMatter.name,a=f.join(t,i),o=f.join(a,yy),s=this.getCodeiumWindsurfDir(),c={pathKind:L.Relative,path:f.join(vy,i,yy),basePath:s,getDirectoryName:()=>i,getAbsolutePath:()=>o},l=this.buildSkillFrontMatter(n),u=n.content,d=Ag(l,u);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`skill`,path:o}),r.push({path:c,success:!0,skipped:!1});else try{this.ensureDirectory(a),this.writeFileSync(o,d),this.log.trace({action:`write`,type:`skill`,path:o}),r.push({path:c,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skill`,path:o,error:t}),r.push({path:c,success:!1,error:e})}if(n.childDocs!=null)for(let t of n.childDocs){let n=await this.writeSkillChildDoc(e,t,a,i,s);r.push(n)}if(n.resources!=null)for(let t of n.resources){let n=await this.writeSkillResource(e,t,a,i,s);r.push(n)}return r}buildSkillFrontMatter(e){let t=e.yamlFrontMatter;return{name:t.name,description:t.description,...t.displayName!=null&&{displayName:t.displayName},...t.keywords!=null&&t.keywords.length>0&&{keywords:t.keywords},...t.author!=null&&{author:t.author},...t.version!=null&&{version:t.version},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}async writeSkillChildDoc(e,t,n,r,i){let a=t.relativePath.replace(/\.mdx$/,`.md`),o=f.join(n,a),s={pathKind:L.Relative,path:f.join(vy,r,a),basePath:i,getDirectoryName:()=>r,getAbsolutePath:()=>o},c=t.content;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`childDoc`,path:o}),{path:s,success:!0,skipped:!1};try{let e=f.dirname(o);return this.ensureDirectory(e),this.writeFileSync(o,c),this.log.trace({action:`write`,type:`childDoc`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`childDoc`,path:o,error:t}),{path:s,success:!1,error:e}}}async writeSkillResource(e,t,n,r,i){let a=f.join(n,t.relativePath),o={pathKind:L.Relative,path:f.join(vy,r,t.relativePath),basePath:i,getDirectoryName:()=>r,getAbsolutePath:()=>a};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`resource`,path:a}),{path:o,success:!0,skipped:!1};try{let e=f.dirname(a);if(this.ensureDirectory(e),t.encoding===`base64`){let e=h.Buffer.from(t.content,`base64`);this.writeFileSyncBuffer(a,e)}else this.writeFileSync(a,t.content);return this.log.trace({action:`write`,type:`resource`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`resource`,path:a,error:t}),{path:o,success:!1,error:e}}}buildRuleFileName(e){return`rule-${e.series}-${e.ruleName}.md`}buildRuleContent(e){let t=e.yamlFrontMatter?.description??``;return`${[`<!-- Activation: Glob | Patterns: ${e.globs.join(`, `)} -->`,`<!-- Description: ${t} -->`,`<!-- Configure activation mode in Windsurf UI: Customizations > Rules -->`].join(`
|
|
1238
|
-
`)}\n\n${e.content}`}async writeRuleFile(e,t,n,r,i){let a=this.buildRuleFileName(n),o=f.join(t,a),s={pathKind:L.Relative,path:f.join(i,a),basePath:r,getDirectoryName:()=>xy,getAbsolutePath:()=>o},c=this.buildRuleContent(n);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`ruleFile`,path:o}),{path:s,success:!0,skipped:!1};try{return this.ensureDirectory(t),this.writeFileSync(o,c),this.log.trace({action:`write`,type:`ruleFile`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`ruleFile`,path:o,error:t}),{path:s,success:!1,error:e}}}},Cy=class e extends fy{static REGISTRY_PATH=`~/.kiro/powers/registry.json`;static DEFAULT_VERSION=`1.0.0`;constructor(t){super(e.REGISTRY_PATH,t)}createInitialRegistry(){return{version:e.DEFAULT_VERSION,powers:{},repoSources:{},lastUpdated:new Date().toISOString()}}getEntryName(e){return e.name}merge(e,t){let n={...e.powers},r={...e.repoSources};for(let e of t){n[e.name]=e;let t=this.buildRepoSource(e),i=e.source.repoId??e.name;r[i]=t}return{version:e.version,powers:n,repoSources:r,...e.kiroRecommendedRepo!=null&&{kiroRecommendedRepo:e.kiroRecommendedRepo},lastUpdated:e.lastUpdated}}buildPowerEntry(e,t){let{yamlFrontMatter:n,mcpConfig:r}=e,i={type:`repo`,repoId:this.generateEntryId(`local`),repoName:t},a=r==null?null:Object.keys(r.mcpServers);return{name:n.name,description:n.description,...a!=null&&a.length>0&&{mcpServers:a},...n.author!=null&&{author:n.author},keywords:n.keywords??[],...n.displayName!=null&&{displayName:n.displayName},installed:!0,installedAt:new Date().toISOString(),installPath:t,source:i,sourcePath:t}}getOfficialRegistry(){try{return JSON.parse({version:`1.0.0`,powers:{postman:{name:`postman`,description:`Automate API testing and collection management with Postman - create workspaces, collections, environments, and run tests programmatically`,displayName:`API Testing with Postman`,author:`Postman`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/postman.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/postman`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`postman`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},figma:{name:`figma`,description:`Connect Figma designs to code components - automatically generate design system rules, map UI components to Figma designs, and maintain design-code consistency`,displayName:`Design to Code with Figma`,author:`Figma`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/figma.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/figma`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`figma`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"netlify-deployment":{name:`netlify-deployment`,description:`Deploy React, Next.js, Vue, and other modern web apps to Netlify's global CDN with automatic builds.`,displayName:`Deploy web apps with Netlify`,author:`Netlify`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/netlify.png`,repositoryUrl:`https://github.com/netlify/context-and-tools/tree/main/context/steering/netlify-deployment-power`,license:``,repositoryCloneUrl:`git@github.com:netlify/context-and-tools.git`,pathInRepo:`context/steering/netlify-deployment-power`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"amazon-aurora-postgresql":{name:`amazon-aurora-postgresql`,description:`Build applications backed by Aurora PostgreSQL by leveraging Aurora PostgreSQL specific best practices.`,displayName:`Build applications with Aurora PostgreSQL`,author:`AWS`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/amazon-aurora.png`,repositoryUrl:`https://github.com/awslabs/mcp/tree/main/src/postgres-mcp-server/kiro_power`,license:``,repositoryCloneUrl:`git@github.com:awslabs/mcp.git`,pathInRepo:`src/postgres-mcp-server/kiro_power`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"supabase-hosted":{name:`supabase-hosted`,description:`Build applications with Supabase's Postgres database, authentication, storage, and real-time subscriptions`,displayName:`Build a backend with Supabase`,author:`Supabase`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/supabase.png`,repositoryUrl:`https://github.com/supabase-community/kiro-powers/tree/main/powers/supabase-hosted`,license:``,repositoryCloneUrl:`git@github.com:supabase-community/kiro-powers.git`,pathInRepo:`powers/supabase-hosted`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"supabase-local":{name:`supabase-local`,description:`Local development with Supabase allows you to work on your projects in a self-contained environment on your local machine.`,displayName:`Build a backend (local) with Supabase`,author:`Supabase`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/supabase.png`,repositoryUrl:`https://github.com/supabase-community/kiro-powers/tree/main/powers/supabase-local`,license:``,repositoryCloneUrl:`git@github.com:supabase-community/kiro-powers.git`,pathInRepo:`powers/supabase-local`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},terraform:{name:`terraform`,description:`Build and manage Infrastructure as Code with Terraform - access registry providers, modules, policies, and HCP Terraform workflow management`,displayName:`Deploy infrastructure with Terraform`,author:`HashiCorp`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/terraform.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/terraform`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`terraform`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},strands:{name:`strands`,description:`Build AI agents with Strands Agent SDK using Bedrock, Anthropic, OpenAI, Gemini, or Llama models`,displayName:`Build an agent with Strands`,author:`AWS`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/strands.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/strands`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`strands`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"aws-agentcore":{name:`aws-agentcore`,description:`Amazon Bedrock AgentCore is an agentic platform for building, deploying, and operating effective agents.`,displayName:`Build an agent with Amazon Bedrock AgentCore`,author:`AWS`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/agentcore.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/aws-agentcore`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`aws-agentcore`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},neon:{name:`neon`,description:`Serverless Postgres with database branching, autoscaling, and scale-to-zero - perfect for modern development workflows`,displayName:`Build a database with Neon`,author:`Neon`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/neon.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/neon`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`neon`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},datadog:{name:`datadog`,description:`Query logs, metrics, traces, RUM events, incidents, and monitors from Datadog for production debugging and performance analysis`,displayName:`Datadog Observability`,author:`Datadog`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/datadog.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/datadog`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`datadog`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},dynatrace:{name:`dynatrace`,description:`Query logs, metrics, traces, problems, and Kubernetes events from Dynatrace using DQL for production debugging and performance analysis`,displayName:`Dynatrace Observability`,author:`Dynatrace`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/dynatrace.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/dynatrace`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`dynatrace`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},stripe:{name:`stripe`,description:`Build payment integrations with Stripe - accept payments, manage subscriptions, handle billing, and process refunds`,displayName:`Stripe Payments`,author:`Stripe`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/stripe.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/stripe`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`stripe`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"aws-infrastructure-as-code":{name:`aws-infrastructure-as-code`,description:`Build well-architected AWS infrastructure with CDK using latest documentation, best practices, and code samples. Validate CloudFormation templates, check resource configuration security compliance, and troubleshoot deployments.`,displayName:`Build AWS infrastructure with CDK and CloudFormation`,author:`AWS`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/iac.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/aws-infrastructure-as-code`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`aws-infrastructure-as-code`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"power-builder":{name:`power-builder`,description:`Complete guide for building and testing new Kiro Powers with templates, best practices, and validation`,displayName:`Build a Power`,author:`Kiro Team`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/power.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/power-builder`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`power-builder`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"saas-builder":{name:`saas-builder`,description:`Build production ready multi-tenant SaaS applications with serverless architecture, integrated billing, and enterprise grade security`,displayName:`SaaS Builder`,author:`Allen Helton`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/power.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/saas-builder`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`saas-builder`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"cloud-architect":{name:`cloud-architect`,description:`Build AWS infrastructure with CDK in Python following AWS Well-Architected framework best practices`,displayName:`Build infrastructure on AWS`,author:`Christian Bonzelet`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/power.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/cloud-architect`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`cloud-architect`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"aurora-dsql":{name:`aurora-dsql`,description:`For PostgreSQL compatible serverless distributed SQL database with Aurora DSQL, manage schemas, execute queries, and handle migrations with DSQL-specific constraints`,displayName:`Deploy a distributed SQL database on AWS`,author:`Rolf Koski`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/power.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/aurora-dsql`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`aurora-dsql`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}}},repoSources:{},lastUpdated:`2025-12-28T20:19:10.824Z`,kiroRecommendedRepo:{url:`https://prod.download.desktop.kiro.dev/powers/default_registry.json`,lastFetch:`2025-12-28T20:19:10.823Z`,powerCount:18}})}catch{this.log.debug(`Failed to parse official registry, using empty registry`)}return this.createInitialRegistry()}unregisterLocalPowers(e){let t={...this.getOfficialRegistry(),lastUpdated:new Date().toISOString()};return this.log.trace({action:e===!0?`dryRun`:`reset`,type:`registry`,powerCount:Object.keys(t.powers).length}),this.write(t,e)}buildRepoSource(e){let t=new Date().toISOString();return{name:e.sourcePath??e.installPath??e.name,type:`local`,enabled:!0,addedAt:t,powerCount:1,...e.sourcePath!=null&&{path:e.sourcePath},lastSync:t}}};const wy=`GLOBAL.md`,Ty=`.kiro`,Ey=`steering`,Dy=`settings`,Oy=`mcp.json`,ky=`POWER.md`,Ay=`SKILL.md`;var jy=class extends Pg{constructor(){super(`KiroCLIOutputPlugin`,{globalConfigDir:Ty,outputFileName:wy,indexignore:`.kiroignore`}),this.registerCleanEffect(`registry-cleanup`,async e=>this.getRegistryWriter(Cy).unregisterLocalPowers(e.dryRun)?{success:!0,description:`Reset registry`}:{success:!1,description:`Failed`,error:Error(`Registry cleanup failed`)}),this.registerCleanEffect(`mcp-settings-cleanup`,async e=>{let t=this.joinPath(this.getGlobalSettingsDir(),Oy),n=JSON.stringify({mcpServers:{},powers:{mcpServers:{}}},null,2);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpSettingsCleanup`,path:t}),{success:!0,description:`Would reset mcp.json`};let r=await this.writeFile(e,t,n,`mcpSettingsCleanup`);return r.success?{success:!0,description:`Reset mcp.json`}:{success:!1,description:`Failed`,error:r.error??Error(`Cleanup failed`)}})}getGlobalSettingsDir(){return this.joinPath(this.getHomeDir(),Ty,Dy)}getGlobalSteeringDir(){return this.joinPath(this.getGlobalConfigDir(),Ey)}getKiroPowersDir(){return this.joinPath(this.getHomeDir(),`.kiro/powers/installed`)}getKiroSkillsDir(){return this.joinPath(this.getHomeDir(),`.kiro/skills`)}async registerProjectOutputDirs(e){let{projects:t}=e.collectedInputContext.workspace;return t.filter(e=>e.dirFromWorkspacePath!=null).map(e=>this.createRelativePath(this.joinPath(e.dirFromWorkspacePath.path,Ty,Ey),e.dirFromWorkspacePath.basePath,()=>Ey))}async registerProjectOutputFiles(e){let{projects:t}=e.collectedInputContext.workspace,{rules:n}=e.collectedInputContext,r=[];for(let e of t){if(e.dirFromWorkspacePath==null)continue;if(e.childMemoryPrompts!=null)for(let t of e.childMemoryPrompts)r.push(this.createRelativePath(this.joinPath(e.dirFromWorkspacePath.path,Ty,Ey,this.buildSteeringFileName(t)),e.dirFromWorkspacePath.basePath,()=>Ey));let t=n?.filter(e=>e.scope===`project`);if(t!=null&&t.length>0)for(let n of t){let t=this.buildRuleSteeringFileName(n);r.push(this.createRelativePath(this.joinPath(e.dirFromWorkspacePath.path,Ty,Ey,t),e.dirFromWorkspacePath.basePath,()=>Ey))}}return r.push(...this.registerProjectIgnoreOutputFiles(t)),r}async registerGlobalOutputDirs(){let e=[this.createRelativePath(Ey,this.getGlobalConfigDir(),()=>Ey)],t=this.getKiroPowersDir();for(let n of this.listInstalledPowers(t))e.push(this.createRelativePath(n,t,()=>n));let n=this.getKiroSkillsDir();for(let t of this.listInstalledPowers(n))e.push(this.createRelativePath(t,n,()=>t));return e.push(this.createRelativePath(`repos`,this.joinPath(this.getHomeDir(),`.kiro/powers`),()=>`repos`)),e}listInstalledPowers(e){try{return this.existsSync(e)?this.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name):[]}catch{return[]}}async registerGlobalOutputFiles(e){let{globalMemory:t,fastCommands:n,skills:r,rules:i}=e.collectedInputContext,a=this.getGlobalSteeringDir(),o=[];if(t!=null&&o.push(this.createRelativePath(wy,a,()=>Ey)),n!=null)for(let e of n)o.push(this.createRelativePath(this.buildFastCommandSteeringFileName(e),a,()=>Ey));let s=i?.filter(e=>e.scope===`global`);if(s!=null&&s.length>0)for(let e of s)o.push(this.createRelativePath(this.buildRuleSteeringFileName(e),a,()=>Ey));if(r==null)return o;let c=this.getKiroPowersDir(),l=this.getKiroSkillsDir();for(let e of r){let t=e.yamlFrontMatter.name;if(e.mcpConfig!=null){let n=this.joinPath(c,t);if(o.push(this.createRelativePath(ky,n,()=>t)),o.push(this.createRelativePath(Oy,n,()=>t)),e.childDocs!=null)for(let t of e.childDocs)o.push(this.createRelativePath(this.joinPath(Ey,t.dir.path.replace(/\.mdx$/,`.md`)),n,()=>Ey));if(e.resources!=null)for(let t of e.resources)o.push(this.createRelativePath(this.joinPath(Ey,t.relativePath),n,()=>Ey))}else{let n=this.joinPath(l,t);if(o.push(this.createRelativePath(Ay,n,()=>t)),e.childDocs!=null)for(let r of e.childDocs)o.push(this.createRelativePath(r.dir.path.replace(/\.mdx$/,`.md`),n,()=>t));if(e.resources!=null)for(let r of e.resources)o.push(this.createRelativePath(r.relativePath,n,()=>t))}}return r.some(e=>e.mcpConfig!=null)&&o.push(this.createRelativePath(Oy,this.getGlobalSettingsDir(),()=>Dy)),o}async canWrite(e){let{workspace:t,globalMemory:n,fastCommands:r,skills:i,rules:a,aiAgentIgnoreConfigFiles:o}=e.collectedInputContext,s=t.projects.some(e=>(e.childMemoryPrompts?.length??0)>0),c=(a?.length??0)>0,l=o?.some(e=>e.fileName===`.kiroignore`)??!1;return s||n!=null||(r?.length??0)>0||(i?.length??0)>0||c||l?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,{rules:n}=e.collectedInputContext,r=[];for(let i of t){if(i.dirFromWorkspacePath==null)continue;if(i.childMemoryPrompts!=null)for(let t of i.childMemoryPrompts)r.push(await this.writeSteeringFile(e,i,t));let t=n?.filter(e=>e.scope===`project`);if(t!=null&&t.length>0)for(let n of t)r.push(await this.writeRuleSteeringFile(e,i,n))}let i=await this.writeProjectIgnoreFiles(e);return r.push(...i),{files:r,dirs:[]}}async writeGlobalOutputs(e){let{globalMemory:t,fastCommands:n,skills:r,rules:i}=e.collectedInputContext,a=[],o=[],s=this.getGlobalSteeringDir();if(t!=null&&a.push(await this.writeFile(e,this.joinPath(s,wy),t.content,`globalMemory`)),n!=null)for(let t of n)a.push(await this.writeFastCommandSteeringFile(e,t));let c=i?.filter(e=>e.scope===`global`);if(c!=null&&c.length>0)for(let t of c){let n=this.buildRuleSteeringFileName(t),r=this.joinPath(s,n),i=this.buildRuleSteeringContent(t);a.push(await this.writeFile(e,r,i,`ruleSteeringFile`))}if(r==null||r.length===0)return{files:a,dirs:[]};let l=r.filter(e=>e.mcpConfig!=null),u=r.filter(e=>e.mcpConfig==null);for(let t of l){let{fileResults:n,registryResult:r}=await this.writeSkillAsPower(e,t);a.push(...n),o.push(r)}for(let t of u){let n=await this.writeSkillAsKiroSkill(e,t);a.push(...n)}let d=await this.writeGlobalMcpSettings(e,r);return d!=null&&a.push(d),this.logRegistryResults(o,e.dryRun),{files:a,dirs:[]}}async writeGlobalMcpSettings(e,t){let n={};for(let e of t)if(e.mcpConfig!=null)for(let[t,r]of Object.entries(e.mcpConfig.mcpServers))n[`power-${e.yamlFrontMatter.name}-${t}`]=r;if(Object.keys(n).length===0)return null;let r=JSON.stringify({mcpServers:{},powers:{mcpServers:n}},null,2);return this.writeFile(e,this.joinPath(this.getGlobalSettingsDir(),Oy),r,`globalMcpSettings`)}logRegistryResults(e,t){let n=e.filter(e=>e.success).length,r=e.filter(e=>!e.success).length;n>0&&this.log.trace({action:t===!0?`dryRun`:`register`,type:`registrySummary`,successCount:n}),r>0&&this.log.error({action:`register`,type:`registrySummary`,failCount:r})}async writeSkillAsPower(e,t){let n=[],r=t.yamlFrontMatter.name,i=this.joinPath(this.getKiroPowersDir(),r),a=this.joinPath(i,ky),o=`${this.buildPowerFrontMatter(t.yamlFrontMatter)}\n${t.content}`;if(n.push(await this.writeFile(e,a,o,`skillPower`)),t.childDocs!=null){let r=this.joinPath(i,Ey);for(let i of t.childDocs){let t=i.dir.path.replace(/\.mdx$/,`.md`);n.push(await this.writeFile(e,this.joinPath(r,t),i.content,`refDoc`))}}if(t.resources!=null){let r=this.joinPath(i,Ey);for(let i of t.resources)n.push(await this.writeFile(e,this.joinPath(r,i.relativePath),i.content,`resource`))}t.mcpConfig!=null&&n.push(await this.writeFile(e,this.joinPath(i,Oy),t.mcpConfig.rawContent,`mcpConfig`));let s=this.getRegistryWriter(Cy),c=s.buildPowerEntry(t,i);return{fileResults:n,registryResult:(await this.registerInRegistry(s,[c],e))[0]??{success:!1,entryName:r,error:Error(`No registry result`)}}}async writeSkillAsKiroSkill(e,t){let n=[],r=t.yamlFrontMatter.name,i=this.joinPath(this.getKiroSkillsDir(),r),a=this.joinPath(i,Ay),o=`${this.buildSkillFrontMatter(t.yamlFrontMatter)}\n${t.content}`;if(n.push(await this.writeFile(e,a,o,`kiroSkill`)),t.childDocs!=null)for(let r of t.childDocs){let t=r.dir.path.replace(/\.mdx$/,`.md`);n.push(await this.writeFile(e,this.joinPath(i,t),r.content,`refDoc`))}if(t.resources!=null)for(let r of t.resources)n.push(await this.writeFile(e,this.joinPath(i,r.relativePath),r.content,`resource`));return n}buildSkillFrontMatter(e){return this.buildMarkdownContent(``,{name:e.name,description:e.description,...e.displayName!=null&&{displayName:e.displayName},...e.keywords!=null&&e.keywords.length>0&&{keywords:e.keywords},...e.author!=null&&{author:e.author}}).trimEnd()}buildPowerFrontMatter(e){return this.buildMarkdownContent(``,{name:e.name,displayName:e.displayName,description:e.description,keywords:e.keywords,author:e.author}).trimEnd()}buildFastCommandSteeringFileName(e){return this.transformFastCommandName(e,{includeSeriesPrefix:!0,seriesSeparator:`-`})}async writeFastCommandSteeringFile(e,t){let n=this.buildFastCommandSteeringFileName(t),r=this.joinPath(this.getGlobalSteeringDir(),n),i=t.yamlFrontMatter?.description,a=this.buildMarkdownContent(t.content,{inclusion:`manual`,description:i!=null&&i.length>0?i:null});return this.writeFile(e,r,a,`fastCommandSteering`)}buildSteeringFileName(e){return`kiro-${(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``).replaceAll(`/`,`-`)}.md`}buildRuleSteeringFileName(e){return`rule-${e.series}-${e.ruleName}.md`}buildRuleSteeringContent(e){let t=e.globs.length===1?e.globs[0]:`{${e.globs.join(`,`)}}`;return this.buildMarkdownContent(e.content,{inclusion:`fileMatch`,fileMatchPattern:t})}async writeRuleSteeringFile(e,t,n){let r=t.dirFromWorkspacePath,i=this.buildRuleSteeringFileName(n),a=this.joinPath(r.basePath,r.path,Ty,Ey),o=this.joinPath(a,i),s=this.buildRuleSteeringContent(n);return this.writeFile(e,o,s,`ruleSteeringFile`)}async writeSteeringFile(e,t,n){let r=t.dirFromWorkspacePath,i=this.buildSteeringFileName(n),a=this.joinPath(r.basePath,r.path,Ty,Ey),o=this.joinPath(a,i),s=n.workingChildDirectoryPath?.path??n.dir.path,c=this.buildMarkdownContent(n.content,{inclusion:`fileMatch`,fileMatchPattern:`${s.replaceAll(`\\`,`/`)}/**`});return this.writeFile(e,o,c,`steeringFile`)}};const My=`agt.mdx`,Ny=[`node_modules`,`.git`];var Py=class extends Lg{constructor(){super(`ProjectPromptInputPlugin`,[`ShadowProjectInputPlugin`])}async collect(e){let{dependencyContext:t,fs:n,userConfigOptions:r,path:i,globalScope:a}=e,{shadowProjectDir:o}=this.resolveBasePaths(r),s=this.resolveShadowPath(r.shadowSourceProject.project.dist,o),c=t.workspace;if(c==null)return this.log.warn(`No workspace found in dependency context, skipping project prompt enhancement`),{};let l=c.projects??[],u=await Promise.all(l.map(async t=>{let r=t.name;if(r==null)return t;let o=i.join(s,r);if(!n.existsSync(o)||!n.statSync(o).isDirectory())return t;let c=t.dirFromWorkspacePath?.getAbsolutePath(),l=await this.readRootMemoryPrompt(e,o,a),u=c==null?[]:await this.scanChildMemoryPrompts(e,o,c,a);return{...t,...l!=null&&{rootMemoryPrompt:l},...u.length>0&&{childMemoryPrompts:u}}}));return{workspace:{directory:c.directory,projects:u}}}async readRootMemoryPrompt(e,t,n){let{fs:r,path:i,logger:a}=e,o=i.join(t,My);if(!(!r.existsSync(o)||!r.statSync(o).isFile()))try{let e=r.readFileSync(o,`utf8`),i=jg(e),s;try{s=await uv(e,{globalScope:n,basePath:t})}catch(e){throw e instanceof qg&&(a.error(`MDX compilation failed in ${o}: ${e.message}`),a.error(`Please check your configuration file (~/.aindex/.tnmsc.json) and ensure all required variables are defined.`),u.default.exit(1)),e}return{type:xt.ProjectRootMemory,content:s,length:s.length,filePathKind:L.Relative,...i.yamlFrontMatter!=null&&{yamlFrontMatter:i.yamlFrontMatter},...i.rawFrontMatter!=null&&{rawFrontMatter:i.rawFrontMatter},markdownAst:i.markdownAst,markdownContents:i.markdownContents,dir:{pathKind:L.Root,path:``,getDirectoryName:()=>``}}}catch(e){a.error(`Failed to read root memory prompt at ${o}`,{error:e});return}}async scanChildMemoryPrompts(e,t,n,r){let{logger:i}=e,a=[];try{await this.scanDirectoryRecursive(e,t,t,n,a,r)}catch(e){i.error(`Failed to scan child memory prompts at ${t}`,{error:e})}return a}async scanDirectoryRecursive(e,t,n,r,i,a){let{fs:o,path:s}=e,c=o.readdirSync(n,{withFileTypes:!0});for(let l of c){if(!l.isDirectory()||Ny.includes(l.name))continue;let c=s.join(n,l.name),u=s.join(c,My);if(o.existsSync(u)&&o.statSync(u).isFile()){let n=await this.readChildMemoryPrompt(e,t,c,r,a);n!=null&&i.push(n)}await this.scanDirectoryRecursive(e,t,c,r,i,a)}}async readChildMemoryPrompt(e,t,n,r,i){let{fs:a,path:o,logger:s}=e,c=o.join(n,My);try{let e=a.readFileSync(c,`utf8`),l=jg(e),d;try{d=await uv(e,{globalScope:i,basePath:n})}catch(e){throw e instanceof qg&&(s.error(`MDX compilation failed in ${c}: ${e.message}`),s.error(`Please check your configuration file (~/.aindex/.tnmsc.json) and ensure all required variables are defined.`),u.default.exit(1)),e}let f=o.relative(t,n),p=o.join(r,f),m=o.basename(n);return{type:xt.ProjectChildrenMemory,content:d,length:d.length,filePathKind:L.Relative,...l.yamlFrontMatter!=null&&{yamlFrontMatter:l.yamlFrontMatter},...l.rawFrontMatter!=null&&{rawFrontMatter:l.rawFrontMatter},markdownAst:l.markdownAst,markdownContents:l.markdownContents,dir:{pathKind:L.Relative,path:f,basePath:r,getDirectoryName:()=>m,getAbsolutePath:()=>p},workingChildDirectoryPath:{pathKind:L.Relative,path:f,basePath:r,getDirectoryName:()=>m,getAbsolutePath:()=>p}}}catch(e){s.error(`Failed to read child memory prompt at ${c}`,{error:e});return}}};const Fy=`.qoder`,Iy=`rules`,Ly=`commands`,Ry=`skills`,zy=`global.md`,By=`always.md`,Vy=`SKILL.md`,Hy=`mcp.json`;var Uy=class extends Pg{constructor(){super(`QoderIDEPluginOutputPlugin`,{globalConfigDir:Fy,indexignore:`.qoderignore`})}async registerProjectOutputDirs(e){let{projects:t}=e.collectedInputContext.workspace;return t.filter(e=>e.dirFromWorkspacePath!=null).map(e=>this.createProjectRulesDirPath(e.dirFromWorkspacePath))}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace,{globalMemory:r}=e.collectedInputContext;for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null&&(r!=null&&t.push(this.createProjectRuleFilePath(n,zy)),e.rootMemoryPrompt!=null&&t.push(this.createProjectRuleFilePath(n,By)),e.childMemoryPrompts!=null))for(let r of e.childMemoryPrompts)t.push(this.createProjectRuleFilePath(n,this.buildChildRuleFileName(r)))}return t.push(...this.registerProjectIgnoreOutputFiles(n)),t}async registerGlobalOutputDirs(e){let t=this.getGlobalConfigDir(),{fastCommands:n,skills:r}=e.collectedInputContext,i=[];if(n!=null&&n.length>0&&i.push(this.createRelativePath(Ly,t,()=>Ly)),r!=null&&r.length>0)for(let e of r){let n=e.yamlFrontMatter.name;i.push(this.createRelativePath(f.join(Ry,n),t,()=>n))}return i}async registerGlobalOutputFiles(e){let t=this.getGlobalConfigDir(),{fastCommands:n,skills:r}=e.collectedInputContext,i=[],a=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});if(n!=null&&n.length>0)for(let e of n){let n=this.transformFastCommandName(e,a);i.push(this.createRelativePath(f.join(Ly,n),t,()=>Ly))}if(r!=null&&r.length>0)for(let e of r){let n=e.yamlFrontMatter.name;if(i.push(this.createRelativePath(f.join(Ry,n,Vy),t,()=>n)),e.mcpConfig!=null&&i.push(this.createRelativePath(f.join(Ry,n,Hy),t,()=>n)),e.childDocs!=null)for(let r of e.childDocs)i.push(this.createRelativePath(f.join(Ry,n,r.relativePath.replace(/\.mdx$/,`.md`)),t,()=>n));if(e.resources!=null)for(let r of e.resources)i.push(this.createRelativePath(f.join(Ry,n,r.relativePath),t,()=>n))}return i}async canWrite(e){let{workspace:t,globalMemory:n,fastCommands:r,skills:i,aiAgentIgnoreConfigFiles:a}=e.collectedInputContext,o=t.projects.some(e=>e.rootMemoryPrompt!=null||(e.childMemoryPrompts?.length??0)>0),s=a?.some(e=>e.fileName===`.qoderignore`)??!1;return o||n!=null||(r?.length??0)>0||(i?.length??0)>0||s?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,{globalMemory:n}=e.collectedInputContext,r=[];for(let i of t){if(i.dirFromWorkspacePath==null)continue;let t=i.dirFromWorkspacePath;if(n!=null){let i=this.buildAlwaysRuleContent(n.content);r.push(await this.writeProjectRuleFile(e,t,zy,i,`globalRule`))}if(i.rootMemoryPrompt!=null){let n=this.buildAlwaysRuleContent(i.rootMemoryPrompt.content);r.push(await this.writeProjectRuleFile(e,t,By,n,`projectRootRule`))}if(i.childMemoryPrompts!=null)for(let n of i.childMemoryPrompts){let i=this.buildChildRuleFileName(n),a=this.buildGlobRuleContent(n);r.push(await this.writeProjectRuleFile(e,t,i,a,`projectChildRule`))}}let i=await this.writeProjectIgnoreFiles(e);return r.push(...i),{files:r,dirs:[]}}async writeGlobalOutputs(e){let{fastCommands:t,skills:n}=e.collectedInputContext,r=[],i=this.getGlobalConfigDir(),a=f.join(i,Ly),o=f.join(i,Ry);if(t!=null&&t.length>0)for(let n of t)r.push(await this.writeGlobalFastCommand(e,a,n));if(n!=null&&n.length>0)for(let t of n)r.push(...await this.writeGlobalSkill(e,o,t));return{files:r,dirs:[]}}createProjectRulesDirPath(e){return this.createRelativePath(f.join(e.path,Fy,Iy),e.basePath,()=>Iy)}createProjectRuleFilePath(e,t){return this.createRelativePath(f.join(e.path,Fy,Iy,t),e.basePath,()=>Iy)}buildChildRuleFileName(e){let t=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``).replaceAll(`/`,`-`);return`glob-${t.length>0?t:`root`}.md`}buildAlwaysRuleContent(e){return Ag({trigger:`always_on`,type:`user_command`},e)}buildGlobRuleContent(e){let t=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``);return Ag({trigger:`glob`,glob:t.length===0?`**/*`:`${t}/**`,type:`user_command`},e.content)}async writeProjectRuleFile(e,t,n,r,i){let a=f.join(t.basePath,t.path,Fy,Iy),o=f.join(a,n);return this.writeFile(e,o,r,i)}async writeGlobalFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),i=this.transformFastCommandName(n,r),a=f.join(t,i),o=Ag(this.buildFastCommandFrontMatter(n),n.content);return this.writeFile(e,a,o,`globalFastCommand`)}async writeGlobalSkill(e,t,n){let r=[],i=n.yamlFrontMatter.name,a=f.join(t,i),o=f.join(a,Vy),s=Ag(this.buildSkillFrontMatter(n),n.content);if(r.push(await this.writeFile(e,o,s,`skill`)),n.mcpConfig!=null){let t=f.join(a,Hy);r.push(await this.writeFile(e,t,n.mcpConfig.rawContent,`mcpConfig`))}if(n.childDocs!=null)for(let t of n.childDocs){let n=f.join(a,t.relativePath.replace(/\.mdx$/,`.md`));r.push(await this.writeFile(e,n,t.content,`childDoc`))}if(n.resources!=null)for(let t of n.resources){let n=f.join(a,t.relativePath);if(t.encoding===`base64`){let e=h.Buffer.from(t.content,`base64`),o=f.dirname(n);this.ensureDirectory(o),this.writeFileSyncBuffer(n,e),r.push({path:this.createRelativePath(t.relativePath,a,()=>i),success:!0})}else r.push(await this.writeFile(e,n,t.content,`resource`))}return r}buildSkillFrontMatter(e){let t=e.yamlFrontMatter;return{name:t.name,description:t.description,type:`user_command`,...t.displayName!=null&&{displayName:t.displayName},...t.keywords!=null&&t.keywords.length>0&&{keywords:t.keywords},...t.author!=null&&{author:t.author},...t.version!=null&&{version:t.version},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}buildFastCommandFrontMatter(e){let t=e.yamlFrontMatter;return t==null?{description:`Fast command`,type:`user_command`}:{description:t.description,type:`user_command`,...t.argumentHint!=null&&{argumentHint:t.argumentHint},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}};const Wy=`README.md`;var Gy=class extends Pg{constructor(){super(`ReadmeMdConfigFileOutputPlugin`,{outputFileName:Wy})}async registerProjectOutputFiles(e){let t=[],{readmePrompts:n}=e.collectedInputContext;if(n==null||n.length===0)return t;for(let e of n){let{targetDir:n}=e,r=f.join(n.path,Wy);t.push({pathKind:L.Relative,path:r,basePath:n.basePath,getDirectoryName:()=>n.getDirectoryName(),getAbsolutePath:()=>f.join(n.basePath,r)})}return t}async canWrite(e){let{readmePrompts:t}=e.collectedInputContext;return t?.length===0?(this.log.debug(`skipped`,{reason:`no README prompts to write`}),!1):!0}async writeProjectOutputs(e){let t=[],n=[],{readmePrompts:r}=e.collectedInputContext;if(r==null||r.length===0)return{files:t,dirs:n};for(let n of r){let r=await this.writeReadmeFile(e,n);t.push(r)}return{files:t,dirs:n}}async writeReadmeFile(e,t){let{targetDir:n}=t,r=f.join(n.path,Wy),i=f.join(n.basePath,r),a=t.content,o={pathKind:L.Relative,path:r,basePath:n.basePath,getDirectoryName:()=>n.getDirectoryName(),getAbsolutePath:()=>i},s=t.isRoot?`project:${t.projectName}/README.md`:`project:${t.projectName}/${n.path}/README.md`;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`readme`,path:i,label:s}),{path:o,success:!0,skipped:!1};try{let e=f.dirname(i);return d.existsSync(e)||d.mkdirSync(e,{recursive:!0}),d.writeFileSync(i,a,`utf8`),this.log.trace({action:`write`,type:`readme`,path:i,label:s}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`readme`,path:i,label:s,error:t}),{path:o,success:!1,error:e}}}},Ky=class extends Lg{constructor(){super(`ReadmeMdInputPlugin`,[`ShadowProjectInputPlugin`])}async collect(e){let{userConfigOptions:t,logger:n,fs:r,path:i,globalScope:a}=e,{workspaceDir:o,shadowProjectDir:s}=this.resolveBasePaths(t),c=this.resolveShadowPath(t.shadowSourceProject.project.dist,s),l=[];if(!r.existsSync(c)||!r.statSync(c).isDirectory())return n.debug(`shadow projects directory does not exist`,{path:c}),{readmePrompts:l};try{let t=r.readdirSync(c,{withFileTypes:!0});for(let n of t){if(!n.isDirectory())continue;let t=n.name,r=i.join(c,t);await this.collectReadmeFiles(e,r,t,o,``,l,a)}}catch(e){n.error(`failed to scan shadow projects`,{path:c,error:e})}return{readmePrompts:l}}async collectReadmeFiles(e,t,n,r,i,a,o){let{fs:s,path:c,logger:l}=e,d=i===``,f=c.join(t,`rdm.mdx`);if(s.existsSync(f)&&s.statSync(f).isFile())try{let e=s.readFileSync(f,`utf8`),p;if(o!=null)try{p=await uv(e,{globalScope:o,basePath:t})}catch(e){throw e instanceof qg&&(l.error(`MDX compilation failed in ${f}: ${e.message}`),l.error(`Please check your configuration file (~/.aindex/.tnmsc.json) and ensure all required variables are defined.`),u.default.exit(1)),e}else p=e;let m=d?n:c.join(n,i),h={pathKind:L.Relative,path:m,basePath:r,getDirectoryName:()=>d?n:c.basename(i),getAbsolutePath:()=>c.resolve(r,m)},g={pathKind:L.Relative,path:c.dirname(f),basePath:r,getDirectoryName:()=>c.basename(c.dirname(f)),getAbsolutePath:()=>c.dirname(f)};a.push({type:xt.Readme,content:p,length:p.length,filePathKind:L.Relative,projectName:n,targetDir:h,isRoot:d,markdownContents:[],dir:g})}catch(e){l.warn(`failed to read readme`,{path:f,error:e})}try{let l=s.readdirSync(t,{withFileTypes:!0});for(let s of l)if(s.isDirectory()){let l=d?s.name:c.join(i,s.name),u=c.join(t,s.name);await this.collectReadmeFiles(e,u,n,r,l,a,o)}}catch(e){l.warn(`failed to scan directory`,{path:t,error:e})}}},qy=class extends Ov{constructor(){super(`RuleInputPlugin`,{configKey:`shadowSourceProject.rule.dist`})}getTargetDir(e,t){return this.resolveShadowPath(e.shadowSourceProject.rule.dist,t.shadowProjectDir)}validateMetadata(e,t){return Nt(e,t)}createResult(e){return{rules:e}}createPrompt(e,t,n,r,i,a,o,s){let c=e.indexOf(`/`),l=c===-1?``:e.slice(0,c),u=(c===-1?e:e.slice(c+1)).replace(/\.mdx$/,``),d=r?.globs??[],f=r?.scope??`project`;return{type:xt.Rule,content:n,length:n.length,filePathKind:L.Relative,...r!=null&&{yamlFrontMatter:r},...i!=null&&{rawFrontMatter:i},markdownAst:a.markdownAst,markdownContents:a.markdownContents,dir:{pathKind:L.Relative,path:e,basePath:o,getDirectoryName:()=>e.replace(/\.mdx$/,``),getAbsolutePath:()=>t},series:l,ruleName:u,globs:d,scope:f,rawMdxContent:s}}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i}=e,a=this.resolveBasePaths(t),o=this.getTargetDir(t,a),s=[];if(!(i.existsSync(o)&&i.statSync(o).isDirectory()))return this.createResult(s);try{let t=i.readdirSync(o,{withFileTypes:!0});for(let a of t)if(a.isDirectory()){let t=r.join(o,a.name);try{let n=i.readdirSync(t,{withFileTypes:!0});for(let i of n)if(i.isFile()&&i.name.endsWith(this.extension)){let n=await this.processFile(i.name,r.join(t,i.name),o,a.name,e);n!=null&&s.push(n)}}catch(e){n.error(`Failed to scan subdirectory at ${t}`,{error:e})}}}catch(e){n.error(`Failed to scan directory at ${o}`,{error:e})}return this.createResult(s)}async processFile(e,t,n,r,i){let{logger:a,globalScope:o}=i,s=i.fs.readFileSync(t,`utf8`);try{let c=jg(s),l=await uv(s,{globalScope:o,extractMetadata:!0,basePath:i.path.join(n,r)}),u=c.yamlFrontMatter!=null||Object.keys(l.metadata.fields).length>0?{...c.yamlFrontMatter,...l.metadata.fields}:void 0;if(u!=null){let e=this.validateMetadata(u,t);for(let t of e.warnings)a.debug(t);if(!e.valid)throw new Xg([...e.errors],t)}let{content:d}=l,f=`${r}/${e}`;return a.debug(`${this.name} metadata extracted`,{file:f,source:l.metadata.source,hasYaml:c.yamlFrontMatter!=null,hasExport:Object.keys(l.metadata.fields).length>0}),this.createPrompt(f,t,d,u,c.rawFrontMatter,c,n,s)}catch(e){a.error(`failed to parse ${this.name} item`,{file:t,error:e});return}}},Jy=class extends Lg{constructor(){super(`ShadowProjectInputPlugin`)}collect(e){let{userConfigOptions:t,logger:n,fs:r,path:i}=e,{workspaceDir:a,shadowProjectDir:o}=this.resolveBasePaths(t),s=this.resolveShadowPath(t.shadowSourceProject.project.dist,o),c=i.basename(o),l=[];if(r.existsSync(s)&&r.statSync(s).isDirectory())try{let e=r.readdirSync(s,{withFileTypes:!0});for(let t of e)if(t.isDirectory()){let e=t.name===c;l.push({name:t.name,...e&&{isPromptSourceProject:!0},dirFromWorkspacePath:{pathKind:L.Relative,path:t.name,basePath:a,getDirectoryName:()=>t.name,getAbsolutePath:()=>i.resolve(a,t.name)}})}}catch(e){n.error(`failed to scan shadow projects`,{path:s,error:e})}if(l.length===0&&r.existsSync(a)&&r.statSync(a).isDirectory()){n.debug(`no projects in dist/app/, falling back to workspace scan`,{workspaceDir:a});try{let e=r.readdirSync(a,{withFileTypes:!0});for(let t of e)if(t.isDirectory()&&!t.name.startsWith(`.`)){let e=t.name===c;l.push({name:t.name,...e&&{isPromptSourceProject:!0},dirFromWorkspacePath:{pathKind:L.Relative,path:t.name,basePath:a,getDirectoryName:()=>t.name,getAbsolutePath:()=>i.resolve(a,t.name)}})}}catch(e){n.error(`failed to scan workspace directory`,{path:a,error:e})}}return{workspace:{directory:{pathKind:L.Absolute,path:a,getDirectoryName:()=>i.basename(a)},projects:l}}}};function Yy(e){return It.includes(e.toLowerCase())}function Xy(e){let t=e.toLowerCase();return[`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`,`.ico`,`.bmp`,`.tiff`,`.svg`].includes(t)?`image`:`.kt,.java,.py,.pyi,.pyx,.ts,.tsx,.js,.jsx,.mjs,.cjs,.go,.rs,.c,.cpp,.cc,.h,.hpp,.hxx,.cs,.fs,.fsx,.vb,.rb,.php,.swift,.scala,.groovy,.lua,.r,.jl,.ex,.exs,.erl,.clj,.cljs,.hs,.ml,.mli,.nim,.zig,.v,.dart,.vue,.svelte,.d.ts,.d.mts,.d.cts`.split(`,`).includes(t)?`code`:[`.sql`,`.json`,`.jsonc`,`.json5`,`.xml`,`.xsd`,`.xsl`,`.xslt`,`.yaml`,`.yml`,`.toml`,`.csv`,`.tsv`,`.graphql`,`.gql`,`.proto`].includes(t)?`data`:[`.txt`,`.text`,`.rtf`,`.log`,`.docx`,`.doc`,`.xlsx`,`.xls`,`.pptx`,`.ppt`,`.pdf`,`.odt`,`.ods`,`.odp`].includes(t)?`document`:[`.ini`,`.conf`,`.cfg`,`.config`,`.properties`,`.env`,`.envrc`,`.editorconfig`,`.gitignore`,`.gitattributes`,`.npmrc`,`.nvmrc`,`.npmignore`,`.eslintrc`,`.prettierrc`,`.stylelintrc`,`.babelrc`,`.browserslistrc`].includes(t)?`config`:[`.sh`,`.bash`,`.zsh`,`.fish`,`.ps1`,`.psm1`,`.psd1`,`.bat`,`.cmd`].includes(t)?`script`:`.exe,.dll,.so,.dylib,.bin,.wasm,.class,.jar,.war,.pyd,.pyc,.pyo,.zip,.tar,.gz,.bz2,.7z,.rar,.ttf,.otf,.woff,.woff2,.eot,.db,.sqlite,.sqlite3`.split(`,`).includes(t)?`binary`:`other`}function Zy(e){return{".ts":`text/typescript`,".tsx":`text/typescript`,".js":`text/javascript`,".jsx":`text/javascript`,".json":`application/json`,".py":`text/x-python`,".java":`text/x-java`,".kt":`text/x-kotlin`,".go":`text/x-go`,".rs":`text/x-rust`,".c":`text/x-c`,".cpp":`text/x-c++`,".cs":`text/x-csharp`,".rb":`text/x-ruby`,".php":`text/x-php`,".swift":`text/x-swift`,".scala":`text/x-scala`,".sql":`application/sql`,".xml":`application/xml`,".yaml":`text/yaml`,".yml":`text/yaml`,".toml":`text/toml`,".csv":`text/csv`,".graphql":`application/graphql`,".txt":`text/plain`,".pdf":`application/pdf`,".docx":`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,".xlsx":`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,".html":`text/html`,".css":`text/css`,".svg":`image/svg+xml`,".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".gif":`image/gif`,".webp":`image/webp`,".ico":`image/x-icon`,".bmp":`image/bmp`}[e.toLowerCase()]}var Qy=class extends Lg{constructor(){super(`SkillInputPlugin`)}readMcpConfig(e,t,n){let r=f.join(e,`mcp.json`);if(t.existsSync(r)){if(!t.statSync(r).isFile()){n.warn(`mcp.json is not a file`,{skillDir:e});return}try{let i=t.readFileSync(r,`utf8`),a=JSON.parse(i);if(a.mcpServers==null||typeof a.mcpServers!=`object`){n.warn(`mcp.json missing mcpServers field`,{skillDir:e});return}return{type:xt.SkillMcpConfig,mcpServers:a.mcpServers,rawContent:i}}catch(t){n.warn(`failed to parse mcp.json`,{skillDir:e,error:t});return}}}scanSkillDirectory(e,t,n,r=``){let i=[],a=[],o=r?f.join(e,r):e;try{let s=t.readdirSync(o,{withFileTypes:!0});for(let c of s){let s=r?`${r}/${c.name}`:c.name;if(c.isDirectory()){let r=this.scanSkillDirectory(e,t,n,s);i.push(...r.childDocs),a.push(...r.resources)}else if(c.isFile()){let l=f.join(o,c.name);if(c.name.endsWith(`.mdx`)){if(r===``&&c.name===`skill.mdx`)continue;try{let n=jg(t.readFileSync(l,`utf8`)),r=Mg(n.contentWithoutFrontMatter);i.push({type:xt.SkillChildDoc,content:r,length:r.length,filePathKind:L.Relative,markdownAst:n.markdownAst,markdownContents:n.markdownContents,...n.rawFrontMatter!=null&&{rawFrontMatter:n.rawFrontMatter},relativePath:s,dir:{pathKind:L.Relative,path:s,basePath:e,getDirectoryName:()=>f.dirname(s),getAbsolutePath:()=>l}})}catch(e){n.warn(`failed to read child doc`,{path:s,error:e})}}else{if(r===``&&c.name===`mcp.json`)continue;let e=f.extname(c.name),i,o,u;try{if(Yy(e)){let e=t.readFileSync(l);i=e.toString(`base64`),o=`base64`,{length:u}=e}else i=t.readFileSync(l,`utf8`),o=`text`,{length:u}=h.Buffer.from(i,`utf8`);let n=Zy(e),r={type:xt.SkillResource,extension:e,fileName:c.name,relativePath:s,content:i,encoding:o,category:Xy(e),length:u};n==null?a.push(r):a.push({...r,mimeType:n})}catch(e){n.warn(`failed to read resource file`,{path:s,error:e})}}}}}catch(e){n.warn(`failed to scan directory`,{path:o,error:e})}return{childDocs:i,resources:a}}async collect(e){let{userConfigOptions:t,logger:n,globalScope:r}=e,{shadowProjectDir:i}=this.resolveBasePaths(t),a=this.resolveShadowPath(t.shadowSourceProject.skill.dist,i),o=[];if(!(e.fs.existsSync(a)&&e.fs.statSync(a).isDirectory()))return{skills:o};let s=e.fs.readdirSync(a,{withFileTypes:!0});for(let t of s)if(t.isDirectory()){let i=e.path.join(a,t.name,`skill.mdx`);if(e.fs.existsSync(i)&&e.fs.statSync(i).isFile())try{let s=e.fs.readFileSync(i,`utf8`),c=jg(s),l=await uv(s,{globalScope:r,extractMetadata:!0,basePath:e.path.join(a,t.name)}),u={...c.yamlFrontMatter,...l.metadata.fields},d=At(u,i);for(let e of d.warnings)n.debug(e);if(!d.valid)throw new Xg(d.errors,i);let p=Mg(l.content),m=e.path.join(a,t.name),h=this.readMcpConfig(m,e.fs,n),{childDocs:g,resources:_}=this.scanSkillDirectory(m,e.fs,n);n.debug(`skill metadata extracted`,{skill:t.name,source:l.metadata.source,hasYaml:c.yamlFrontMatter!=null,hasExport:Object.keys(l.metadata.fields).length>0}),o.push({type:xt.Skill,content:p,length:p.length,filePathKind:L.Relative,yamlFrontMatter:u.name==null?{name:t.name,description:``}:u,...c.rawFrontMatter!=null&&{rawFrontMatter:c.rawFrontMatter},markdownAst:c.markdownAst,markdownContents:c.markdownContents,...h!=null&&{mcpConfig:h},...g.length>0&&{childDocs:g},..._.length>0&&{resources:_},dir:{pathKind:L.Relative,path:t.name,basePath:a,getDirectoryName:()=>t.name,getAbsolutePath:()=>f.join(a,t.name)}})}catch(e){n.error(`failed to parse skill`,{file:i,error:e})}}return{skills:o}}},$y=class extends Ov{constructor(){super(`SubAgentInputPlugin`,{configKey:`shadowSourceProject.subAgent.dist`})}getTargetDir(e,t){return this.resolveShadowPath(e.shadowSourceProject.subAgent.dist,t.shadowProjectDir)}validateMetadata(e,t){return Mt(e,t)}createResult(e){return{subAgents:e}}extractSeriesInfo(e,t){let n=e.replace(/\.mdx$/,``);if(t!=null)return{series:t,agentName:n};let r=n.indexOf(`_`);return r===-1?{agentName:n}:{series:n.slice(0,Math.max(0,r)),agentName:n.slice(Math.max(0,r+1))}}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i}=e,a=this.resolveBasePaths(t),o=this.getTargetDir(t,a),s=[];if(!(i.existsSync(o)&&i.statSync(o).isDirectory()))return this.createResult(s);try{let t=i.readdirSync(o,{withFileTypes:!0});for(let a of t)if(a.isFile()&&a.name.endsWith(this.extension)){let t=await this.processFile(a.name,r.join(o,a.name),o,void 0,e);t!=null&&s.push(t)}else if(a.isDirectory()){let t=r.join(o,a.name);try{let n=i.readdirSync(t,{withFileTypes:!0});for(let i of n)if(i.isFile()&&i.name.endsWith(this.extension)){let n=await this.processFile(i.name,r.join(t,i.name),o,a.name,e);n!=null&&s.push(n)}}catch(e){n.error(`Failed to scan subdirectory at ${t}`,{error:e})}}}catch(e){n.error(`Failed to scan directory at ${o}`,{error:e})}return this.createResult(s)}async processFile(e,t,n,r,i){let{logger:a,globalScope:o}=i,s=i.fs.readFileSync(t,`utf8`);try{let c=jg(s),l=await uv(s,{globalScope:o,extractMetadata:!0,basePath:r==null?n:i.path.join(n,r)}),u=c.yamlFrontMatter!=null||Object.keys(l.metadata.fields).length>0?{...c.yamlFrontMatter,...l.metadata.fields}:void 0;if(u!=null){let e=this.validateMetadata(u,t);for(let t of e.warnings)a.debug(t);if(!e.valid)throw new Xg([...e.errors],t)}let{content:d}=l,f=r==null?e:`${r}/${e}`;return a.debug(`${this.name} metadata extracted`,{file:f,source:l.metadata.source,hasYaml:c.yamlFrontMatter!=null,hasExport:Object.keys(l.metadata.fields).length>0}),this.createPrompt(f,t,d,u,c.rawFrontMatter,c,n,s)}catch(e){a.error(`failed to parse ${this.name} item`,{file:t,error:e});return}}createPrompt(e,t,n,r,i,a,o,s){let c=e.indexOf(`/`),l=c===-1?void 0:e.slice(0,c),u=c===-1?e:e.slice(c+1),d=this.extractSeriesInfo(u,l);return{type:xt.SubAgent,content:n,length:n.length,filePathKind:L.Relative,...r!=null&&{yamlFrontMatter:r},...i!=null&&{rawFrontMatter:i},markdownAst:a.markdownAst,markdownContents:a.markdownContents,dir:{pathKind:L.Relative,path:e,basePath:o,getDirectoryName:()=>e.replace(/\.mdx$/,``),getAbsolutePath:()=>t},...d.series!=null&&{series:d.series},agentName:d.agentName,rawMdxContent:s}}};const eb=`GLOBAL.md`,tb=`.trae`,nb=`steering`,rb=`rules`;var ib=class extends Pg{constructor(){super(`TraeIDEOutputPlugin`,{globalConfigDir:tb,outputFileName:eb,indexignore:`.traeignore`})}getGlobalSteeringDir(){return this.joinPath(this.getGlobalConfigDir(),nb)}async registerProjectOutputDirs(e){let{projects:t}=e.collectedInputContext.workspace;return t.filter(e=>e.dirFromWorkspacePath!=null).map(e=>this.createRelativePath(this.joinPath(e.dirFromWorkspacePath.path,tb,rb),e.dirFromWorkspacePath.basePath,()=>rb))}async registerProjectOutputFiles(e){let{projects:t}=e.collectedInputContext.workspace,n=[];for(let e of t)if(!(e.dirFromWorkspacePath==null||e.childMemoryPrompts==null))for(let t of e.childMemoryPrompts)n.push(this.createRelativePath(this.joinPath(e.dirFromWorkspacePath.path,tb,rb,this.buildSteeringFileName(t)),e.dirFromWorkspacePath.basePath,()=>rb));return n.push(...this.registerProjectIgnoreOutputFiles(t)),n}async registerGlobalOutputDirs(){return[this.createRelativePath(nb,this.getGlobalConfigDir(),()=>nb)]}async registerGlobalOutputFiles(e){let{globalMemory:t,fastCommands:n}=e.collectedInputContext,r=this.getGlobalSteeringDir(),i=[];if(t!=null&&i.push(this.createRelativePath(eb,r,()=>nb)),n!=null)for(let e of n)i.push(this.createRelativePath(this.buildFastCommandSteeringFileName(e),r,()=>nb));return i}async canWrite(e){let{workspace:t,globalMemory:n,fastCommands:r,aiAgentIgnoreConfigFiles:i}=e.collectedInputContext,a=t.projects.some(e=>(e.childMemoryPrompts?.length??0)>0),o=i?.some(e=>e.fileName===`.traeignore`)??!1;return a||n!=null||(r?.length??0)>0||o?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,n=[];for(let r of t)if(!(r.dirFromWorkspacePath==null||r.childMemoryPrompts==null))for(let t of r.childMemoryPrompts)n.push(await this.writeSteeringFile(e,r,t));let r=await this.writeProjectIgnoreFiles(e);return n.push(...r),{files:n,dirs:[]}}async writeGlobalOutputs(e){let{globalMemory:t,fastCommands:n}=e.collectedInputContext,r=[],i=this.getGlobalSteeringDir();if(t!=null&&r.push(await this.writeFile(e,this.joinPath(i,eb),t.content,`globalMemory`)),n!=null)for(let t of n)r.push(await this.writeFastCommandSteeringFile(e,t));return{files:r,dirs:[]}}buildFastCommandSteeringFileName(e){return this.transformFastCommandName(e,{includeSeriesPrefix:!0,seriesSeparator:`-`})}async writeFastCommandSteeringFile(e,t){let n=this.buildFastCommandSteeringFileName(t),r=this.joinPath(this.getGlobalSteeringDir(),n),i=t.yamlFrontMatter?.description,a=this.buildMarkdownContent(t.content,{inclusion:`manual`,description:i!=null&&i.length>0?i:null});return this.writeFile(e,r,a,`fastCommandSteering`)}buildSteeringFileName(e){return`trae-${(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``).replaceAll(`/`,`-`)}.md`}async writeSteeringFile(e,t,n){let r=t.dirFromWorkspacePath,i=this.buildSteeringFileName(n),a=this.joinPath(r.basePath,r.path,tb,rb),o=this.joinPath(a,i),s=[`---`,`alwaysApply: false`,`globs: ${`${(n.workingChildDirectoryPath?.path??n.dir.path).replaceAll(`\\`,`/`)}/**`}`,`---`,``,n.content].join(`
|
|
1239
|
-
`);return this.writeFile(e,o,s,`steeringFile`)}};const
|
|
1237
|
+
`}collect(e){return{}}};const cy=`.config/opencode`,ly=`opencode.json`,uy=`opencode-rules@latest`;var dy=class extends dv{constructor(){super(`OpencodeCLIOutputPlugin`,{globalConfigDir:cy,outputFileName:`AGENTS.md`,commandsSubDir:`commands`,agentsSubDir:`agents`,skillsSubDir:`skills`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0,dependsOn:[`AgentsOutputPlugin`]}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=this.getGlobalConfigDir(),n=f.join(t,ly);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfigCleanup`,path:n}),{success:!0,description:`Would reset opencode.json mcp to empty`};try{if(d.existsSync(n)){let e=d.readFileSync(n,`utf8`),t=JSON.parse(e);t.mcp={};let r=t.plugin;if(Array.isArray(r)){let e=r.filter(e=>e!==uy);e.length>0?t.plugin=e:delete t.plugin}d.writeFileSync(n,JSON.stringify(t,null,2))}return this.log.trace({action:`clean`,type:`mcpConfigCleanup`,path:n}),{success:!0,description:`Reset opencode.json mcp to empty`}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`clean`,type:`mcpConfigCleanup`,path:n,error:t}),{success:!1,error:e,description:`Failed to reset opencode.json mcp`}}})}async registerGlobalOutputFiles(e){let t=await super.registerGlobalOutputFiles(e),n=this.getGlobalConfigDir();if(e.collectedInputContext.skills?.some(e=>e.mcpConfig!=null)??!1){let e=f.join(n,ly);t.push({pathKind:L.Relative,path:ly,basePath:n,getDirectoryName:()=>cy,getAbsolutePath:()=>e})}return t.map(e=>{let t=e.path.replaceAll(`\\`,`/`),r=`/${this.skillsSubDir}/`,i=`${this.skillsSubDir}/`;if(!(t.includes(r)||t.startsWith(i)))return e;let a=t.split(`/`),o=a.indexOf(this.skillsSubDir);if(o<0||o+1>=a.length)return e;let s=a[o+1];if(s==null)return e;let c=this.validateAndNormalizeSkillName(s),l=[...a];l[o+1]=c;let u=l.join(`/`);return{...e,path:u,getDirectoryName:()=>c,getAbsolutePath:()=>f.join(n,u.replaceAll(`/`,f.sep))}})}async writeGlobalOutputs(e){let t=await super.writeGlobalOutputs(e),n=[...t.files],{skills:r}=e.collectedInputContext;if(r==null)return{files:n,dirs:t.dirs};let i=await this.writeGlobalMcpConfig(e,r);return i!=null&&n.push(i),{files:n,dirs:t.dirs}}async writeGlobalMcpConfig(e,t){let n={};for(let e of t){if(e.mcpConfig==null)continue;let{mcpServers:t}=e.mcpConfig;for(let[e,r]of Object.entries(t))n[e]=this.transformMcpConfigForOpencode(r)}if(Object.keys(n).length===0)return null;let r=this.getGlobalConfigDir(),i=f.join(r,ly),a={pathKind:L.Relative,path:ly,basePath:r,getDirectoryName:()=>cy,getAbsolutePath:()=>i},o={};try{if(d.existsSync(i)){let e=d.readFileSync(i,`utf8`);o=JSON.parse(e)}}catch{o={}}o.$schema=`https://opencode.ai/config.json`,o.mcp=n;let s=o.plugin,c=Array.isArray(s)?s.map(e=>String(e)):[];c.includes(uy)||c.push(uy),o.plugin=c;let l=JSON.stringify(o,null,2);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalMcpConfig`,path:i,serverCount:Object.keys(n).length}),{path:a,success:!0,skipped:!1};try{return this.ensureDirectory(r),d.writeFileSync(i,l),this.log.trace({action:`write`,type:`globalMcpConfig`,path:i,serverCount:Object.keys(n).length}),{path:a,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalMcpConfig`,path:i,error:t}),{path:a,success:!1,error:e}}}transformMcpConfigForOpencode(e){let t={};if(e.command!=null){t.type=`local`;let n=[e.command];e.args!=null&&n.push(...e.args),t.command=n,e.env!=null&&(t.environment=e.env)}else{t.type=`remote`;let n=e;n.url==null?n.serverUrl!=null&&(t.url=n.serverUrl):t.url=n.url}return t.enabled=e.disabled!==!0,t}async writeSubAgent(e,t,n){let r=n.dir.path.replace(/\.mdx$/,`.md`),i=f.join(t,this.agentsSubDir),a=f.join(i,r),o=this.buildOpencodeAgentFrontMatter(n),s=this.buildMarkdownContent(n.content,o);return[await this.writeFile(e,a,s,`subAgent`)]}buildOpencodeAgentFrontMatter(e){let t={},n=e.yamlFrontMatter;if(n?.description!=null&&(t.description=n.description),t.mode=n?.mode??`subagent`,n?.model!=null&&(t.model=n.model),n?.temperature!=null&&(t.temperature=n.temperature),n?.maxSteps!=null&&(t.maxSteps=n.maxSteps),n?.hidden!=null&&(t.hidden=n.hidden),n?.allowTools!=null&&Array.isArray(n.allowTools)){let e={};for(let t of n.allowTools)e[String(t)]=!0;t.tools=e}n?.permission!=null&&typeof n.permission==`object`&&(t.permission=n.permission);for(let[e,r]of Object.entries(n??{}))[`description`,`mode`,`model`,`temperature`,`maxSteps`,`hidden`,`allowTools`,`permission`,`namingCase`,`name`,`color`].includes(e)||(t[e]=r);return t}async writeFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),i=this.transformFastCommandName(n,r),a=f.join(t,this.commandsSubDir),o=f.join(a,i),s=this.buildOpencodeCommandFrontMatter(n),c=this.buildMarkdownContent(n.content,s);return[await this.writeFile(e,o,c,`fastCommand`)]}buildOpencodeCommandFrontMatter(e){let t={},n=e.yamlFrontMatter;if(n?.description!=null&&(t.description=n.description),n?.agent!=null&&(t.agent=n.agent),n?.model!=null&&(t.model=n.model),n?.allowTools!=null&&Array.isArray(n.allowTools)){let e={};for(let t of n.allowTools)e[String(t)]=!0;t.tools=e}for(let[e,r]of Object.entries(n??{}))[`description`,`agent`,`model`,`allowTools`,`namingCase`,`argumentHint`].includes(e)||(t[e]=r);return t}async writeSkill(e,t,n){let r=[],i=this.validateAndNormalizeSkillName(n.yamlFrontMatter?.name??n.dir.getDirectoryName()),a=f.join(t,this.skillsSubDir,i),o=f.join(a,`SKILL.md`),s=this.buildOpencodeSkillFrontMatter(n,i),c=this.buildMarkdownContent(n.content,s),l=await this.writeFile(e,o,c,`skill`);if(r.push(l),n.childDocs!=null)for(let o of n.childDocs){let n=await this.writeSkillReferenceDocument(e,a,i,o,t);r.push(...n)}if(n.resources!=null)for(let o of n.resources){let n=await this.writeSkillResource(e,a,i,o,t);r.push(...n)}return r}buildOpencodeSkillFrontMatter(e,t){let n={},r=e.yamlFrontMatter;n.name=t,r?.description!=null&&(n.description=r.description),n.license=r?.license??`MIT`,n.compatibility=r?.compatibility??`opencode`;let i={};for(let e of[`author`,`version`,`keywords`,`category`,`repository`,`displayName`])r?.[e]!=null&&(i[e]=r[e]);let a=new Set([`name`,`description`,`license`,`compatibility`,`namingCase`,`allowTools`,`keywords`,`displayName`,`author`,`version`]);for(let[e,t]of Object.entries(r??{}))a.has(e)||(i[e]=t);return Object.keys(i).length>0&&(n.metadata=i),n}validateAndNormalizeSkillName(e){let t=e.toLowerCase();return t=t.replaceAll(/[^a-z0-9-]+/g,`-`),t=t.replaceAll(/-+/g,`-`),t=t.replaceAll(/^-|-$/g,``),t.length===0?t=`skill`:t.length>64&&(t=t.slice(0,64),t=t.replace(/-$/,``)),t}},fy=class extends Lg{constructor(){super(`OrphanFileCleanupEffectInputPlugin`),this.registerEffect(`orphan-file-cleanup`,this.cleanupOrphanFiles.bind(this),20)}async cleanupOrphanFiles(e){let{fs:t,path:n,shadowProjectDir:r,dryRun:i,logger:a}=e,o=n.join(r,`dist`),s=[],c=[],l=[];if(!t.existsSync(o))return a.debug({action:`orphan-cleanup`,message:`dist/ directory does not exist, skipping`,distDir:o}),{success:!0,description:`dist/ directory does not exist, nothing to clean`,deletedFiles:s,deletedDirs:c};for(let r of[`skills`,`commands`,`agents`,`app`]){let a=n.join(o,r);t.existsSync(a)&&this.cleanupDirectory(e,a,r,s,c,l,i??!1)}let u=l.length>0;return u&&a.warn({action:`orphan-cleanup`,errors:l.map(e=>({path:e.path,error:e.error.message}))}),{success:!u,description:i?`Would delete ${s.length} files and ${c.length} directories`:`Deleted ${s.length} files and ${c.length} directories`,deletedFiles:s,deletedDirs:c,...u&&{error:Error(`${l.length} errors occurred during cleanup`)}}}cleanupDirectory(e,t,n,r,i,a,o){let{fs:s,path:c,shadowProjectDir:l,logger:u}=e,d;try{d=s.readdirSync(t,{withFileTypes:!0})}catch(e){a.push({path:t,error:e}),u.warn({action:`orphan-cleanup`,message:`Failed to read directory`,path:t,error:e.message});return}for(let f of d){let d=c.join(t,f.name);if(f.isDirectory())this.cleanupDirectory(e,d,n,r,i,a,o),this.removeEmptyDirectory(e,d,i,a,o);else if(f.isFile()&&this.isOrphanFile(e,d,n,l))if(o)u.debug({action:`orphan-cleanup`,dryRun:!0,wouldDelete:d}),r.push(d);else try{s.unlinkSync(d),r.push(d),u.debug({action:`orphan-cleanup`,deleted:d})}catch(e){a.push({path:d,error:e}),u.warn({action:`orphan-cleanup`,message:`Failed to delete file`,path:d,error:e.message})}}}isOrphanFile(e,t,n,r){let{fs:i,path:a}=e,o=a.basename(t),s=o.endsWith(`.mdx`),c=a.join(r,`dist`,n),l=a.relative(c,t),u=a.dirname(l),d=o.replace(/\.mdx$/,``);if(s)return!this.getPossibleSourcePaths(a,r,n,d,u).some(e=>i.existsSync(e));let f=[];return n===`app`?f.push(a.join(r,`app`,l)):f.push(a.join(r,`src`,n,l)),!f.some(e=>i.existsSync(e))}getPossibleSourcePaths(e,t,n,r,i){switch(n){case`skills`:return i===`.`?[e.join(t,`src`,`skills`,r,`SKILL.cn.mdx`),e.join(t,`src`,`skills`,`${r}.cn.mdx`)]:[e.join(t,`src`,`skills`,i,`${r}.cn.mdx`)];case`commands`:return i===`.`?[e.join(t,`src`,`commands`,`${r}.cn.mdx`)]:[e.join(t,`src`,`commands`,i,`${r}.cn.mdx`)];case`agents`:return i===`.`?[e.join(t,`src`,`agents`,`${r}.cn.mdx`)]:[e.join(t,`src`,`agents`,i,`${r}.cn.mdx`)];case`app`:return i===`.`?[e.join(t,`app`,`${r}.cn.mdx`)]:[e.join(t,`app`,i,`${r}.cn.mdx`)];default:return[]}}removeEmptyDirectory(e,t,n,r,i){let{fs:a,logger:o}=e;try{a.readdirSync(t).length===0&&(i?(o.debug({action:`orphan-cleanup`,dryRun:!0,wouldDeleteDir:t}),n.push(t)):(a.rmdirSync(t),n.push(t),o.debug({action:`orphan-cleanup`,deletedDir:t})))}catch(e){r.push({path:t,error:e}),o.warn({action:`orphan-cleanup`,message:`Failed to check/remove directory`,path:t,error:e.message})}}collect(e){return{}}},py=class{registryPath;log;constructor(e,t){this.registryPath=this.resolvePath(e),this.log=t??nn(this.constructor.name)}resolvePath(e){return e.startsWith(`~`)?f.join(p.homedir(),e.slice(1)):f.resolve(e)}getRegistryDir(){return f.dirname(this.registryPath)}ensureRegistryDir(){let e=this.getRegistryDir();d.existsSync(e)||d.mkdirSync(e,{recursive:!0})}read(){if(!d.existsSync(this.registryPath))return this.log.debug(`registry not found`,{path:this.registryPath}),this.createInitialRegistry();try{let e=d.readFileSync(this.registryPath,`utf8`);return JSON.parse(e)}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error(`parse failed`,{path:this.registryPath,error:t}),this.createInitialRegistry()}}write(e,t){let n={...e,lastUpdated:new Date().toISOString()};if(t===!0)return this.log.trace({action:`dryRun`,type:`registry`,path:this.registryPath}),!0;let r=`${this.registryPath}.tmp.${Date.now()}`;try{this.ensureRegistryDir();let e=JSON.stringify(n,null,2);return d.writeFileSync(r,e,`utf8`),d.renameSync(r,this.registryPath),this.log.trace({action:`write`,type:`registry`,path:this.registryPath}),!0}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`registry`,path:this.registryPath,error:t});try{d.existsSync(r)&&d.unlinkSync(r)}catch{}return!1}}register(e,t){let n=[],r=this.read(),i=this.merge(r,e),a=this.write(i,t);for(let r of e){let e=this.getEntryName(r);a?(n.push({success:!0,entryName:e}),t===!0?this.log.trace({action:`dryRun`,type:`registerEntry`,entryName:e}):this.log.trace({action:`register`,type:`entry`,entryName:e})):(n.push({success:!1,entryName:e,error:Error(`Failed to write registry file`)}),this.log.error(`register entry failed`,{entryName:e}))}return n}generateEntryId(e){let t=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return e==null?t:`${e}-${t}`}},my=class extends Lg{constructor(){super(`SkillNonSrcFileSyncEffectInputPlugin`),this.registerEffect(`skill-non-src-file-sync`,this.syncNonSrcFiles.bind(this),10)}async syncNonSrcFiles(e){let{fs:t,path:n,shadowProjectDir:r,dryRun:i,logger:a}=e,o=n.join(r,`src`,`skills`),s=n.join(r,`dist`,`skills`),c=[],l=[],u=[],d=[];if(!t.existsSync(o))return a.debug({action:`skill-sync`,message:`src/skills/ directory does not exist, skipping`,srcSkillsDir:o}),{success:!0,description:`src/skills/ directory does not exist, nothing to sync`,copiedFiles:c,skippedFiles:l,createdDirs:u};this.syncDirectoryRecursive(e,o,s,``,c,l,u,d,i??!1);let f=d.length>0;return f&&a.warn({action:`skill-sync`,errors:d.map(e=>({path:e.path,error:e.error.message}))}),{success:!f,description:i?`Would copy ${c.length} files, skip ${l.length} files`:`Copied ${c.length} files, skipped ${l.length} files`,copiedFiles:c,skippedFiles:l,createdDirs:u,...f&&{error:Error(`${d.length} errors occurred during sync`)},modifiedFiles:c}}syncDirectoryRecursive(e,t,n,r,i,a,o,s,c){let{fs:l,path:u,logger:d}=e,f=r?u.join(t,r):t;if(!l.existsSync(f))return;let p;try{p=l.readdirSync(f,{withFileTypes:!0})}catch(e){s.push({path:f,error:e}),d.warn({action:`skill-sync`,message:`Failed to read directory`,path:f,error:e.message});return}for(let f of p){let p=r?u.join(r,f.name):f.name,m=u.join(t,p),h=u.join(n,p);if(f.isDirectory())this.syncDirectoryRecursive(e,t,n,p,i,a,o,s,c);else if(f.isFile()){if(f.name.endsWith(`.cn.mdx`))continue;let e=u.dirname(h);if(!l.existsSync(e))if(c)d.debug({action:`skill-sync`,dryRun:!0,wouldCreateDir:e}),o.push(e);else try{l.mkdirSync(e,{recursive:!0}),o.push(e),d.debug({action:`skill-sync`,createdDir:e})}catch(t){s.push({path:e,error:t}),d.warn({action:`skill-sync`,message:`Failed to create directory`,path:e,error:t.message});continue}if(l.existsSync(h))try{let e=l.readFileSync(m),t=l.readFileSync(h);if(this.computeHash(e)===this.computeHash(t)){a.push(h),d.debug({action:`skill-sync`,skipped:h,reason:`identical content`});continue}}catch(e){d.debug({action:`skill-sync`,message:`Could not compare files, will copy`,path:h,error:e.message})}if(c)d.debug({action:`skill-sync`,dryRun:!0,wouldCopy:{from:m,to:h}}),i.push(h);else try{l.copyFileSync(m,h),i.push(h),d.debug({action:`skill-sync`,copied:{from:m,to:h}})}catch(e){s.push({path:h,error:e}),d.warn({action:`skill-sync`,message:`Failed to copy file`,from:m,to:h,error:e.message})}}}}computeHash(e){return(0,g.createHash)(`sha256`).update(e).digest(`hex`)}collect(e){return{}}};const hy=`.codeium/windsurf`,gy=`global_workflows`,_y=`memories`,vy=`global_rules.md`,yy=`skills`,by=`SKILL.md`,xy=`.windsurf`,Sy=`rules`;var Cy=class extends Pg{constructor(){super(`WindsurfOutputPlugin`,{globalConfigDir:hy,outputFileName:``,dependsOn:[`AgentsOutputPlugin`],indexignore:`.codeignore`})}async registerGlobalOutputDirs(e){let t=[],{fastCommands:n,skills:r,rules:i}=e.collectedInputContext;if(n!=null&&n.length>0){let e=this.getGlobalWorkflowsDir();t.push({pathKind:L.Relative,path:gy,basePath:this.getCodeiumWindsurfDir(),getDirectoryName:()=>gy,getAbsolutePath:()=>e})}if(r!=null&&r.length>0)for(let e of r){let n=e.yamlFrontMatter.name,r=f.join(this.getCodeiumWindsurfDir(),yy,n);t.push({pathKind:L.Relative,path:f.join(yy,n),basePath:this.getCodeiumWindsurfDir(),getDirectoryName:()=>n,getAbsolutePath:()=>r})}let a=i?.filter(e=>e.scope===`global`);if(a==null||a.length===0)return t;let o=this.getCodeiumWindsurfDir(),s=f.join(o,_y);return t.push({pathKind:L.Relative,path:_y,basePath:o,getDirectoryName:()=>_y,getAbsolutePath:()=>s}),t}async registerGlobalOutputFiles(e){let t=[],{skills:n,fastCommands:r}=e.collectedInputContext;if(r!=null&&r.length>0){let n=this.getGlobalWorkflowsDir(),i=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});for(let e of r){let r=this.transformFastCommandName(e,i),a=f.join(n,r);t.push({pathKind:L.Relative,path:f.join(gy,r),basePath:this.getCodeiumWindsurfDir(),getDirectoryName:()=>gy,getAbsolutePath:()=>a})}}let i=e.collectedInputContext.rules?.filter(e=>e.scope===`global`);if(i!=null&&i.length>0){let e=this.getCodeiumWindsurfDir(),n=f.join(e,_y);for(let r of i){let i=this.buildRuleFileName(r),a=f.join(n,i);t.push({pathKind:L.Relative,path:f.join(_y,i),basePath:e,getDirectoryName:()=>_y,getAbsolutePath:()=>a})}}if(n==null||n.length===0)return t;let a=this.getSkillsDir(),o=this.getCodeiumWindsurfDir();for(let e of n){let n=e.yamlFrontMatter.name,r=f.join(a,n);if(t.push({pathKind:L.Relative,path:f.join(yy,n,by),basePath:o,getDirectoryName:()=>n,getAbsolutePath:()=>f.join(r,by)}),e.childDocs!=null)for(let i of e.childDocs){let e=i.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:f.join(yy,n,e),basePath:o,getDirectoryName:()=>n,getAbsolutePath:()=>f.join(r,e)})}if(e.resources!=null)for(let i of e.resources)t.push({pathKind:L.Relative,path:f.join(yy,n,i.relativePath),basePath:o,getDirectoryName:()=>n,getAbsolutePath:()=>f.join(r,i.relativePath)})}return t}async canWrite(e){let{skills:t,fastCommands:n,globalMemory:r,rules:i,aiAgentIgnoreConfigFiles:a}=e.collectedInputContext,o=(t?.length??0)>0,s=(n?.length??0)>0,c=(i?.length??0)>0,l=r!=null,u=a?.some(e=>e.fileName===`.codeignore`)??!1;return o||s||l||c||u?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeGlobalOutputs(e){let{skills:t,fastCommands:n,globalMemory:r,rules:i}=e.collectedInputContext,a=[],o=[];if(r!=null){let t=await this.writeGlobalMemory(e,r.content);a.push(t)}if(t!=null&&t.length>0){let n=this.getSkillsDir();for(let r of t){let t=await this.writeGlobalSkill(e,n,r);a.push(...t)}}if(n!=null&&n.length>0){let t=this.getGlobalWorkflowsDir();for(let r of n){let n=await this.writeGlobalWorkflow(e,t,r);a.push(n)}}let s=i?.filter(e=>e.scope===`global`);if(s==null||s.length===0)return{files:a,dirs:o};let c=this.getGlobalMemoriesDir();for(let t of s){let n=await this.writeRuleFile(e,c,t,this.getCodeiumWindsurfDir(),_y);a.push(n)}return{files:a,dirs:o}}async registerProjectOutputDirs(e){let t=[],{workspace:n,rules:r}=e.collectedInputContext,i=r?.filter(e=>e.scope===`project`);if(i==null||i.length===0)return t;for(let e of n.projects){let n=e.dirFromWorkspacePath;if(n==null)continue;let r=f.join(n.path,xy,Sy);t.push({pathKind:L.Relative,path:r,basePath:n.basePath,getDirectoryName:()=>Sy,getAbsolutePath:()=>f.join(n.basePath,r)})}return t}async registerProjectOutputFiles(e){let t=[],{workspace:n,rules:r}=e.collectedInputContext,i=r?.filter(e=>e.scope===`project`);if(i!=null&&i.length>0)for(let e of n.projects){let n=e.dirFromWorkspacePath;if(n!=null)for(let e of i){let r=this.buildRuleFileName(e),i=f.join(n.path,xy,Sy,r);t.push({pathKind:L.Relative,path:i,basePath:n.basePath,getDirectoryName:()=>Sy,getAbsolutePath:()=>f.join(n.basePath,i)})}}return t.push(...this.registerProjectIgnoreOutputFiles(n.projects)),t}async writeProjectOutputs(e){let t=[],{workspace:n,rules:r}=e.collectedInputContext,i=r?.filter(e=>e.scope===`project`);if(i!=null&&i.length>0)for(let r of n.projects){let n=r.dirFromWorkspacePath;if(n==null)continue;let a=f.join(n.basePath,n.path,xy,Sy);for(let r of i){let i=await this.writeRuleFile(e,a,r,n.basePath,f.join(n.path,xy,Sy));t.push(i)}}let a=await this.writeProjectIgnoreFiles(e);return t.push(...a),{files:t,dirs:[]}}getSkillsDir(){return f.join(this.getCodeiumWindsurfDir(),yy)}getCodeiumWindsurfDir(){return f.join(this.getHomeDir(),hy)}getGlobalMemoriesDir(){return f.join(this.getCodeiumWindsurfDir(),_y)}getGlobalWorkflowsDir(){return f.join(this.getCodeiumWindsurfDir(),gy)}async writeGlobalMemory(e,t){let n=this.getGlobalMemoriesDir(),r=f.join(n,vy),i=this.getCodeiumWindsurfDir(),a={pathKind:L.Relative,path:f.join(_y,vy),basePath:i,getDirectoryName:()=>_y,getAbsolutePath:()=>r};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalMemory`,path:r}),{path:a,success:!0,skipped:!1};try{return this.ensureDirectory(n),this.writeFileSync(r,t),this.log.trace({action:`write`,type:`globalMemory`,path:r}),{path:a,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalMemory`,path:r,error:t}),{path:a,success:!1,error:e}}}async writeGlobalWorkflow(e,t,n){let r=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),i=this.transformFastCommandName(n,r),a=f.join(t,i),o={pathKind:L.Relative,path:f.join(gy,i),basePath:this.getCodeiumWindsurfDir(),getDirectoryName:()=>gy,getAbsolutePath:()=>a},s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalWorkflow`,path:a}),{path:o,success:!0,skipped:!1};try{return this.ensureDirectory(t),d.writeFileSync(a,s),this.log.trace({action:`write`,type:`globalWorkflow`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalWorkflow`,path:a,error:t}),{path:o,success:!1,error:e}}}async writeGlobalSkill(e,t,n){let r=[],i=n.yamlFrontMatter.name,a=f.join(t,i),o=f.join(a,by),s=this.getCodeiumWindsurfDir(),c={pathKind:L.Relative,path:f.join(yy,i,by),basePath:s,getDirectoryName:()=>i,getAbsolutePath:()=>o},l=this.buildSkillFrontMatter(n),u=n.content,d=Ag(l,u);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`skill`,path:o}),r.push({path:c,success:!0,skipped:!1});else try{this.ensureDirectory(a),this.writeFileSync(o,d),this.log.trace({action:`write`,type:`skill`,path:o}),r.push({path:c,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skill`,path:o,error:t}),r.push({path:c,success:!1,error:e})}if(n.childDocs!=null)for(let t of n.childDocs){let n=await this.writeSkillChildDoc(e,t,a,i,s);r.push(n)}if(n.resources!=null)for(let t of n.resources){let n=await this.writeSkillResource(e,t,a,i,s);r.push(n)}return r}buildSkillFrontMatter(e){let t=e.yamlFrontMatter;return{name:t.name,description:t.description,...t.displayName!=null&&{displayName:t.displayName},...t.keywords!=null&&t.keywords.length>0&&{keywords:t.keywords},...t.author!=null&&{author:t.author},...t.version!=null&&{version:t.version},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}async writeSkillChildDoc(e,t,n,r,i){let a=t.relativePath.replace(/\.mdx$/,`.md`),o=f.join(n,a),s={pathKind:L.Relative,path:f.join(yy,r,a),basePath:i,getDirectoryName:()=>r,getAbsolutePath:()=>o},c=t.content;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`childDoc`,path:o}),{path:s,success:!0,skipped:!1};try{let e=f.dirname(o);return this.ensureDirectory(e),this.writeFileSync(o,c),this.log.trace({action:`write`,type:`childDoc`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`childDoc`,path:o,error:t}),{path:s,success:!1,error:e}}}async writeSkillResource(e,t,n,r,i){let a=f.join(n,t.relativePath),o={pathKind:L.Relative,path:f.join(yy,r,t.relativePath),basePath:i,getDirectoryName:()=>r,getAbsolutePath:()=>a};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`resource`,path:a}),{path:o,success:!0,skipped:!1};try{let e=f.dirname(a);if(this.ensureDirectory(e),t.encoding===`base64`){let e=h.Buffer.from(t.content,`base64`);this.writeFileSyncBuffer(a,e)}else this.writeFileSync(a,t.content);return this.log.trace({action:`write`,type:`resource`,path:a}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`resource`,path:a,error:t}),{path:o,success:!1,error:e}}}buildRuleFileName(e){return`rule-${e.series}-${e.ruleName}.md`}buildRuleContent(e){let t=e.yamlFrontMatter?.description??``;return`${[`<!-- Activation: Glob | Patterns: ${e.globs.join(`, `)} -->`,`<!-- Description: ${t} -->`,`<!-- Configure activation mode in Windsurf UI: Customizations > Rules -->`].join(`
|
|
1238
|
+
`)}\n\n${e.content}`}async writeRuleFile(e,t,n,r,i){let a=this.buildRuleFileName(n),o=f.join(t,a),s={pathKind:L.Relative,path:f.join(i,a),basePath:r,getDirectoryName:()=>Sy,getAbsolutePath:()=>o},c=this.buildRuleContent(n);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`ruleFile`,path:o}),{path:s,success:!0,skipped:!1};try{return this.ensureDirectory(t),this.writeFileSync(o,c),this.log.trace({action:`write`,type:`ruleFile`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`ruleFile`,path:o,error:t}),{path:s,success:!1,error:e}}}},wy=class e extends py{static REGISTRY_PATH=`~/.kiro/powers/registry.json`;static DEFAULT_VERSION=`1.0.0`;constructor(t){super(e.REGISTRY_PATH,t)}createInitialRegistry(){return{version:e.DEFAULT_VERSION,powers:{},repoSources:{},lastUpdated:new Date().toISOString()}}getEntryName(e){return e.name}merge(e,t){let n={...e.powers},r={...e.repoSources};for(let e of t){n[e.name]=e;let t=this.buildRepoSource(e),i=e.source.repoId??e.name;r[i]=t}return{version:e.version,powers:n,repoSources:r,...e.kiroRecommendedRepo!=null&&{kiroRecommendedRepo:e.kiroRecommendedRepo},lastUpdated:e.lastUpdated}}buildPowerEntry(e,t){let{yamlFrontMatter:n,mcpConfig:r}=e,i={type:`repo`,repoId:this.generateEntryId(`local`),repoName:t},a=r==null?null:Object.keys(r.mcpServers);return{name:n.name,description:n.description,...a!=null&&a.length>0&&{mcpServers:a},...n.author!=null&&{author:n.author},keywords:n.keywords??[],...n.displayName!=null&&{displayName:n.displayName},installed:!0,installedAt:new Date().toISOString(),installPath:t,source:i,sourcePath:t}}getOfficialRegistry(){try{return JSON.parse({version:`1.0.0`,powers:{postman:{name:`postman`,description:`Automate API testing and collection management with Postman - create workspaces, collections, environments, and run tests programmatically`,displayName:`API Testing with Postman`,author:`Postman`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/postman.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/postman`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`postman`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},figma:{name:`figma`,description:`Connect Figma designs to code components - automatically generate design system rules, map UI components to Figma designs, and maintain design-code consistency`,displayName:`Design to Code with Figma`,author:`Figma`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/figma.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/figma`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`figma`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"netlify-deployment":{name:`netlify-deployment`,description:`Deploy React, Next.js, Vue, and other modern web apps to Netlify's global CDN with automatic builds.`,displayName:`Deploy web apps with Netlify`,author:`Netlify`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/netlify.png`,repositoryUrl:`https://github.com/netlify/context-and-tools/tree/main/context/steering/netlify-deployment-power`,license:``,repositoryCloneUrl:`git@github.com:netlify/context-and-tools.git`,pathInRepo:`context/steering/netlify-deployment-power`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"amazon-aurora-postgresql":{name:`amazon-aurora-postgresql`,description:`Build applications backed by Aurora PostgreSQL by leveraging Aurora PostgreSQL specific best practices.`,displayName:`Build applications with Aurora PostgreSQL`,author:`AWS`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/amazon-aurora.png`,repositoryUrl:`https://github.com/awslabs/mcp/tree/main/src/postgres-mcp-server/kiro_power`,license:``,repositoryCloneUrl:`git@github.com:awslabs/mcp.git`,pathInRepo:`src/postgres-mcp-server/kiro_power`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"supabase-hosted":{name:`supabase-hosted`,description:`Build applications with Supabase's Postgres database, authentication, storage, and real-time subscriptions`,displayName:`Build a backend with Supabase`,author:`Supabase`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/supabase.png`,repositoryUrl:`https://github.com/supabase-community/kiro-powers/tree/main/powers/supabase-hosted`,license:``,repositoryCloneUrl:`git@github.com:supabase-community/kiro-powers.git`,pathInRepo:`powers/supabase-hosted`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"supabase-local":{name:`supabase-local`,description:`Local development with Supabase allows you to work on your projects in a self-contained environment on your local machine.`,displayName:`Build a backend (local) with Supabase`,author:`Supabase`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/supabase.png`,repositoryUrl:`https://github.com/supabase-community/kiro-powers/tree/main/powers/supabase-local`,license:``,repositoryCloneUrl:`git@github.com:supabase-community/kiro-powers.git`,pathInRepo:`powers/supabase-local`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},terraform:{name:`terraform`,description:`Build and manage Infrastructure as Code with Terraform - access registry providers, modules, policies, and HCP Terraform workflow management`,displayName:`Deploy infrastructure with Terraform`,author:`HashiCorp`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/terraform.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/terraform`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`terraform`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},strands:{name:`strands`,description:`Build AI agents with Strands Agent SDK using Bedrock, Anthropic, OpenAI, Gemini, or Llama models`,displayName:`Build an agent with Strands`,author:`AWS`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/strands.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/strands`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`strands`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"aws-agentcore":{name:`aws-agentcore`,description:`Amazon Bedrock AgentCore is an agentic platform for building, deploying, and operating effective agents.`,displayName:`Build an agent with Amazon Bedrock AgentCore`,author:`AWS`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/agentcore.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/aws-agentcore`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`aws-agentcore`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},neon:{name:`neon`,description:`Serverless Postgres with database branching, autoscaling, and scale-to-zero - perfect for modern development workflows`,displayName:`Build a database with Neon`,author:`Neon`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/neon.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/neon`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`neon`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},datadog:{name:`datadog`,description:`Query logs, metrics, traces, RUM events, incidents, and monitors from Datadog for production debugging and performance analysis`,displayName:`Datadog Observability`,author:`Datadog`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/datadog.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/datadog`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`datadog`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},dynatrace:{name:`dynatrace`,description:`Query logs, metrics, traces, problems, and Kubernetes events from Dynatrace using DQL for production debugging and performance analysis`,displayName:`Dynatrace Observability`,author:`Dynatrace`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/dynatrace.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/dynatrace`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`dynatrace`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},stripe:{name:`stripe`,description:`Build payment integrations with Stripe - accept payments, manage subscriptions, handle billing, and process refunds`,displayName:`Stripe Payments`,author:`Stripe`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/stripe.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/stripe`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`stripe`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"aws-infrastructure-as-code":{name:`aws-infrastructure-as-code`,description:`Build well-architected AWS infrastructure with CDK using latest documentation, best practices, and code samples. Validate CloudFormation templates, check resource configuration security compliance, and troubleshoot deployments.`,displayName:`Build AWS infrastructure with CDK and CloudFormation`,author:`AWS`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/iac.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/aws-infrastructure-as-code`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`aws-infrastructure-as-code`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"power-builder":{name:`power-builder`,description:`Complete guide for building and testing new Kiro Powers with templates, best practices, and validation`,displayName:`Build a Power`,author:`Kiro Team`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/power.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/power-builder`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`power-builder`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"saas-builder":{name:`saas-builder`,description:`Build production ready multi-tenant SaaS applications with serverless architecture, integrated billing, and enterprise grade security`,displayName:`SaaS Builder`,author:`Allen Helton`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/power.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/saas-builder`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`saas-builder`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"cloud-architect":{name:`cloud-architect`,description:`Build AWS infrastructure with CDK in Python following AWS Well-Architected framework best practices`,displayName:`Build infrastructure on AWS`,author:`Christian Bonzelet`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/power.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/cloud-architect`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`cloud-architect`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}},"aurora-dsql":{name:`aurora-dsql`,description:`For PostgreSQL compatible serverless distributed SQL database with Aurora DSQL, manage schemas, execute queries, and handle migrations with DSQL-specific constraints`,displayName:`Deploy a distributed SQL database on AWS`,author:`Rolf Koski`,iconUrl:`https://prod.download.desktop.kiro.dev/powers/icons/power.png`,repositoryUrl:`https://github.com/kirodotdev/powers/tree/main/aurora-dsql`,license:``,repositoryCloneUrl:`git@github.com:kirodotdev/powers.git`,pathInRepo:`aurora-dsql`,repositoryBranch:`main`,installed:!1,keywords:[],source:{type:`registry`}}},repoSources:{},lastUpdated:`2025-12-28T20:19:10.824Z`,kiroRecommendedRepo:{url:`https://prod.download.desktop.kiro.dev/powers/default_registry.json`,lastFetch:`2025-12-28T20:19:10.823Z`,powerCount:18}})}catch{this.log.debug(`Failed to parse official registry, using empty registry`)}return this.createInitialRegistry()}unregisterLocalPowers(e){let t={...this.getOfficialRegistry(),lastUpdated:new Date().toISOString()};return this.log.trace({action:e===!0?`dryRun`:`reset`,type:`registry`,powerCount:Object.keys(t.powers).length}),this.write(t,e)}buildRepoSource(e){let t=new Date().toISOString();return{name:e.sourcePath??e.installPath??e.name,type:`local`,enabled:!0,addedAt:t,powerCount:1,...e.sourcePath!=null&&{path:e.sourcePath},lastSync:t}}};const Ty=`GLOBAL.md`,Ey=`.kiro`,Dy=`steering`,Oy=`settings`,ky=`mcp.json`,Ay=`POWER.md`,jy=`SKILL.md`;var My=class extends Pg{constructor(){super(`KiroCLIOutputPlugin`,{globalConfigDir:Ey,outputFileName:Ty,indexignore:`.kiroignore`}),this.registerCleanEffect(`registry-cleanup`,async e=>this.getRegistryWriter(wy).unregisterLocalPowers(e.dryRun)?{success:!0,description:`Reset registry`}:{success:!1,description:`Failed`,error:Error(`Registry cleanup failed`)}),this.registerCleanEffect(`mcp-settings-cleanup`,async e=>{let t=this.joinPath(this.getGlobalSettingsDir(),ky),n=JSON.stringify({mcpServers:{},powers:{mcpServers:{}}},null,2);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpSettingsCleanup`,path:t}),{success:!0,description:`Would reset mcp.json`};let r=await this.writeFile(e,t,n,`mcpSettingsCleanup`);return r.success?{success:!0,description:`Reset mcp.json`}:{success:!1,description:`Failed`,error:r.error??Error(`Cleanup failed`)}})}getGlobalSettingsDir(){return this.joinPath(this.getHomeDir(),Ey,Oy)}getGlobalSteeringDir(){return this.joinPath(this.getGlobalConfigDir(),Dy)}getKiroPowersDir(){return this.joinPath(this.getHomeDir(),`.kiro/powers/installed`)}getKiroSkillsDir(){return this.joinPath(this.getHomeDir(),`.kiro/skills`)}async registerProjectOutputDirs(e){let{projects:t}=e.collectedInputContext.workspace;return t.filter(e=>e.dirFromWorkspacePath!=null).map(e=>this.createRelativePath(this.joinPath(e.dirFromWorkspacePath.path,Ey,Dy),e.dirFromWorkspacePath.basePath,()=>Dy))}async registerProjectOutputFiles(e){let{projects:t}=e.collectedInputContext.workspace,{rules:n}=e.collectedInputContext,r=[];for(let e of t){if(e.dirFromWorkspacePath==null)continue;if(e.childMemoryPrompts!=null)for(let t of e.childMemoryPrompts)r.push(this.createRelativePath(this.joinPath(e.dirFromWorkspacePath.path,Ey,Dy,this.buildSteeringFileName(t)),e.dirFromWorkspacePath.basePath,()=>Dy));let t=n?.filter(e=>e.scope===`project`);if(t!=null&&t.length>0)for(let n of t){let t=this.buildRuleSteeringFileName(n);r.push(this.createRelativePath(this.joinPath(e.dirFromWorkspacePath.path,Ey,Dy,t),e.dirFromWorkspacePath.basePath,()=>Dy))}}return r.push(...this.registerProjectIgnoreOutputFiles(t)),r}async registerGlobalOutputDirs(){let e=[this.createRelativePath(Dy,this.getGlobalConfigDir(),()=>Dy)],t=this.getKiroPowersDir();for(let n of this.listInstalledPowers(t))e.push(this.createRelativePath(n,t,()=>n));let n=this.getKiroSkillsDir();for(let t of this.listInstalledPowers(n))e.push(this.createRelativePath(t,n,()=>t));return e.push(this.createRelativePath(`repos`,this.joinPath(this.getHomeDir(),`.kiro/powers`),()=>`repos`)),e}listInstalledPowers(e){try{return this.existsSync(e)?this.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name):[]}catch{return[]}}async registerGlobalOutputFiles(e){let{globalMemory:t,fastCommands:n,skills:r,rules:i}=e.collectedInputContext,a=this.getGlobalSteeringDir(),o=[];if(t!=null&&o.push(this.createRelativePath(Ty,a,()=>Dy)),n!=null)for(let e of n)o.push(this.createRelativePath(this.buildFastCommandSteeringFileName(e),a,()=>Dy));let s=i?.filter(e=>e.scope===`global`);if(s!=null&&s.length>0)for(let e of s)o.push(this.createRelativePath(this.buildRuleSteeringFileName(e),a,()=>Dy));if(r==null)return o;let c=this.getKiroPowersDir(),l=this.getKiroSkillsDir();for(let e of r){let t=e.yamlFrontMatter.name;if(e.mcpConfig!=null){let n=this.joinPath(c,t);if(o.push(this.createRelativePath(Ay,n,()=>t)),o.push(this.createRelativePath(ky,n,()=>t)),e.childDocs!=null)for(let t of e.childDocs)o.push(this.createRelativePath(this.joinPath(Dy,t.dir.path.replace(/\.mdx$/,`.md`)),n,()=>Dy));if(e.resources!=null)for(let t of e.resources)o.push(this.createRelativePath(this.joinPath(Dy,t.relativePath),n,()=>Dy))}else{let n=this.joinPath(l,t);if(o.push(this.createRelativePath(jy,n,()=>t)),e.childDocs!=null)for(let r of e.childDocs)o.push(this.createRelativePath(r.dir.path.replace(/\.mdx$/,`.md`),n,()=>t));if(e.resources!=null)for(let r of e.resources)o.push(this.createRelativePath(r.relativePath,n,()=>t))}}return r.some(e=>e.mcpConfig!=null)&&o.push(this.createRelativePath(ky,this.getGlobalSettingsDir(),()=>Oy)),o}async canWrite(e){let{workspace:t,globalMemory:n,fastCommands:r,skills:i,rules:a,aiAgentIgnoreConfigFiles:o}=e.collectedInputContext,s=t.projects.some(e=>(e.childMemoryPrompts?.length??0)>0),c=(a?.length??0)>0,l=o?.some(e=>e.fileName===`.kiroignore`)??!1;return s||n!=null||(r?.length??0)>0||(i?.length??0)>0||c||l?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,{rules:n}=e.collectedInputContext,r=[];for(let i of t){if(i.dirFromWorkspacePath==null)continue;if(i.childMemoryPrompts!=null)for(let t of i.childMemoryPrompts)r.push(await this.writeSteeringFile(e,i,t));let t=n?.filter(e=>e.scope===`project`);if(t!=null&&t.length>0)for(let n of t)r.push(await this.writeRuleSteeringFile(e,i,n))}let i=await this.writeProjectIgnoreFiles(e);return r.push(...i),{files:r,dirs:[]}}async writeGlobalOutputs(e){let{globalMemory:t,fastCommands:n,skills:r,rules:i}=e.collectedInputContext,a=[],o=[],s=this.getGlobalSteeringDir();if(t!=null&&a.push(await this.writeFile(e,this.joinPath(s,Ty),t.content,`globalMemory`)),n!=null)for(let t of n)a.push(await this.writeFastCommandSteeringFile(e,t));let c=i?.filter(e=>e.scope===`global`);if(c!=null&&c.length>0)for(let t of c){let n=this.buildRuleSteeringFileName(t),r=this.joinPath(s,n),i=this.buildRuleSteeringContent(t);a.push(await this.writeFile(e,r,i,`ruleSteeringFile`))}if(r==null||r.length===0)return{files:a,dirs:[]};let l=r.filter(e=>e.mcpConfig!=null),u=r.filter(e=>e.mcpConfig==null);for(let t of l){let{fileResults:n,registryResult:r}=await this.writeSkillAsPower(e,t);a.push(...n),o.push(r)}for(let t of u){let n=await this.writeSkillAsKiroSkill(e,t);a.push(...n)}let d=await this.writeGlobalMcpSettings(e,r);return d!=null&&a.push(d),this.logRegistryResults(o,e.dryRun),{files:a,dirs:[]}}async writeGlobalMcpSettings(e,t){let n={};for(let e of t)if(e.mcpConfig!=null)for(let[t,r]of Object.entries(e.mcpConfig.mcpServers))n[`power-${e.yamlFrontMatter.name}-${t}`]=r;if(Object.keys(n).length===0)return null;let r=JSON.stringify({mcpServers:{},powers:{mcpServers:n}},null,2);return this.writeFile(e,this.joinPath(this.getGlobalSettingsDir(),ky),r,`globalMcpSettings`)}logRegistryResults(e,t){let n=e.filter(e=>e.success).length,r=e.filter(e=>!e.success).length;n>0&&this.log.trace({action:t===!0?`dryRun`:`register`,type:`registrySummary`,successCount:n}),r>0&&this.log.error({action:`register`,type:`registrySummary`,failCount:r})}async writeSkillAsPower(e,t){let n=[],r=t.yamlFrontMatter.name,i=this.joinPath(this.getKiroPowersDir(),r),a=this.joinPath(i,Ay),o=`${this.buildPowerFrontMatter(t.yamlFrontMatter)}\n${t.content}`;if(n.push(await this.writeFile(e,a,o,`skillPower`)),t.childDocs!=null){let r=this.joinPath(i,Dy);for(let i of t.childDocs){let t=i.dir.path.replace(/\.mdx$/,`.md`);n.push(await this.writeFile(e,this.joinPath(r,t),i.content,`refDoc`))}}if(t.resources!=null){let r=this.joinPath(i,Dy);for(let i of t.resources)n.push(await this.writeFile(e,this.joinPath(r,i.relativePath),i.content,`resource`))}t.mcpConfig!=null&&n.push(await this.writeFile(e,this.joinPath(i,ky),t.mcpConfig.rawContent,`mcpConfig`));let s=this.getRegistryWriter(wy),c=s.buildPowerEntry(t,i);return{fileResults:n,registryResult:(await this.registerInRegistry(s,[c],e))[0]??{success:!1,entryName:r,error:Error(`No registry result`)}}}async writeSkillAsKiroSkill(e,t){let n=[],r=t.yamlFrontMatter.name,i=this.joinPath(this.getKiroSkillsDir(),r),a=this.joinPath(i,jy),o=`${this.buildSkillFrontMatter(t.yamlFrontMatter)}\n${t.content}`;if(n.push(await this.writeFile(e,a,o,`kiroSkill`)),t.childDocs!=null)for(let r of t.childDocs){let t=r.dir.path.replace(/\.mdx$/,`.md`);n.push(await this.writeFile(e,this.joinPath(i,t),r.content,`refDoc`))}if(t.resources!=null)for(let r of t.resources)n.push(await this.writeFile(e,this.joinPath(i,r.relativePath),r.content,`resource`));return n}buildSkillFrontMatter(e){return this.buildMarkdownContent(``,{name:e.name,description:e.description,...e.displayName!=null&&{displayName:e.displayName},...e.keywords!=null&&e.keywords.length>0&&{keywords:e.keywords},...e.author!=null&&{author:e.author}}).trimEnd()}buildPowerFrontMatter(e){return this.buildMarkdownContent(``,{name:e.name,displayName:e.displayName,description:e.description,keywords:e.keywords,author:e.author}).trimEnd()}buildFastCommandSteeringFileName(e){return this.transformFastCommandName(e,{includeSeriesPrefix:!0,seriesSeparator:`-`})}async writeFastCommandSteeringFile(e,t){let n=this.buildFastCommandSteeringFileName(t),r=this.joinPath(this.getGlobalSteeringDir(),n),i=t.yamlFrontMatter?.description,a=this.buildMarkdownContent(t.content,{inclusion:`manual`,description:i!=null&&i.length>0?i:null});return this.writeFile(e,r,a,`fastCommandSteering`)}buildSteeringFileName(e){return`kiro-${(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``).replaceAll(`/`,`-`)}.md`}buildRuleSteeringFileName(e){return`rule-${e.series}-${e.ruleName}.md`}buildRuleSteeringContent(e){let t=e.globs.length===1?e.globs[0]:`{${e.globs.join(`,`)}}`;return this.buildMarkdownContent(e.content,{inclusion:`fileMatch`,fileMatchPattern:t})}async writeRuleSteeringFile(e,t,n){let r=t.dirFromWorkspacePath,i=this.buildRuleSteeringFileName(n),a=this.joinPath(r.basePath,r.path,Ey,Dy),o=this.joinPath(a,i),s=this.buildRuleSteeringContent(n);return this.writeFile(e,o,s,`ruleSteeringFile`)}async writeSteeringFile(e,t,n){let r=t.dirFromWorkspacePath,i=this.buildSteeringFileName(n),a=this.joinPath(r.basePath,r.path,Ey,Dy),o=this.joinPath(a,i),s=n.workingChildDirectoryPath?.path??n.dir.path,c=this.buildMarkdownContent(n.content,{inclusion:`fileMatch`,fileMatchPattern:`${s.replaceAll(`\\`,`/`)}/**`});return this.writeFile(e,o,c,`steeringFile`)}};const Ny=`agt.mdx`,Py=[`node_modules`,`.git`];var Fy=class extends Lg{constructor(){super(`ProjectPromptInputPlugin`,[`ShadowProjectInputPlugin`])}async collect(e){let{dependencyContext:t,fs:n,userConfigOptions:r,path:i,globalScope:a}=e,{shadowProjectDir:o}=this.resolveBasePaths(r),s=this.resolveShadowPath(r.shadowSourceProject.project.dist,o),c=t.workspace;if(c==null)return this.log.warn(`No workspace found in dependency context, skipping project prompt enhancement`),{};let l=c.projects??[],u=await Promise.all(l.map(async t=>{let r=t.name;if(r==null)return t;let o=i.join(s,r);if(!n.existsSync(o)||!n.statSync(o).isDirectory())return t;let c=t.dirFromWorkspacePath?.getAbsolutePath(),l=await this.readRootMemoryPrompt(e,o,a),u=c==null?[]:await this.scanChildMemoryPrompts(e,o,c,a);return{...t,...l!=null&&{rootMemoryPrompt:l},...u.length>0&&{childMemoryPrompts:u}}}));return{workspace:{directory:c.directory,projects:u}}}async readRootMemoryPrompt(e,t,n){let{fs:r,path:i,logger:a}=e,o=i.join(t,Ny);if(!(!r.existsSync(o)||!r.statSync(o).isFile()))try{let e=r.readFileSync(o,`utf8`),i=jg(e),s;try{s=await uv(e,{globalScope:n,basePath:t})}catch(e){throw e instanceof qg&&(a.error(`MDX compilation failed in ${o}: ${e.message}`),a.error(`Please check your configuration file (~/.aindex/.tnmsc.json) and ensure all required variables are defined.`),u.default.exit(1)),e}return{type:xt.ProjectRootMemory,content:s,length:s.length,filePathKind:L.Relative,...i.yamlFrontMatter!=null&&{yamlFrontMatter:i.yamlFrontMatter},...i.rawFrontMatter!=null&&{rawFrontMatter:i.rawFrontMatter},markdownAst:i.markdownAst,markdownContents:i.markdownContents,dir:{pathKind:L.Root,path:``,getDirectoryName:()=>``}}}catch(e){a.error(`Failed to read root memory prompt at ${o}`,{error:e});return}}async scanChildMemoryPrompts(e,t,n,r){let{logger:i}=e,a=[];try{await this.scanDirectoryRecursive(e,t,t,n,a,r)}catch(e){i.error(`Failed to scan child memory prompts at ${t}`,{error:e})}return a}async scanDirectoryRecursive(e,t,n,r,i,a){let{fs:o,path:s}=e,c=o.readdirSync(n,{withFileTypes:!0});for(let l of c){if(!l.isDirectory()||Py.includes(l.name))continue;let c=s.join(n,l.name),u=s.join(c,Ny);if(o.existsSync(u)&&o.statSync(u).isFile()){let n=await this.readChildMemoryPrompt(e,t,c,r,a);n!=null&&i.push(n)}await this.scanDirectoryRecursive(e,t,c,r,i,a)}}async readChildMemoryPrompt(e,t,n,r,i){let{fs:a,path:o,logger:s}=e,c=o.join(n,Ny);try{let e=a.readFileSync(c,`utf8`),l=jg(e),d;try{d=await uv(e,{globalScope:i,basePath:n})}catch(e){throw e instanceof qg&&(s.error(`MDX compilation failed in ${c}: ${e.message}`),s.error(`Please check your configuration file (~/.aindex/.tnmsc.json) and ensure all required variables are defined.`),u.default.exit(1)),e}let f=o.relative(t,n),p=o.join(r,f),m=o.basename(n);return{type:xt.ProjectChildrenMemory,content:d,length:d.length,filePathKind:L.Relative,...l.yamlFrontMatter!=null&&{yamlFrontMatter:l.yamlFrontMatter},...l.rawFrontMatter!=null&&{rawFrontMatter:l.rawFrontMatter},markdownAst:l.markdownAst,markdownContents:l.markdownContents,dir:{pathKind:L.Relative,path:f,basePath:r,getDirectoryName:()=>m,getAbsolutePath:()=>p},workingChildDirectoryPath:{pathKind:L.Relative,path:f,basePath:r,getDirectoryName:()=>m,getAbsolutePath:()=>p}}}catch(e){s.error(`Failed to read child memory prompt at ${c}`,{error:e});return}}};const Iy=`.qoder`,Ly=`rules`,Ry=`commands`,zy=`skills`,By=`global.md`,Vy=`always.md`,Hy=`SKILL.md`,Uy=`mcp.json`;var Wy=class extends Pg{constructor(){super(`QoderIDEPluginOutputPlugin`,{globalConfigDir:Iy,indexignore:`.qoderignore`})}async registerProjectOutputDirs(e){let{projects:t}=e.collectedInputContext.workspace;return t.filter(e=>e.dirFromWorkspacePath!=null).map(e=>this.createProjectRulesDirPath(e.dirFromWorkspacePath))}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace,{globalMemory:r}=e.collectedInputContext;for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null&&(r!=null&&t.push(this.createProjectRuleFilePath(n,By)),e.rootMemoryPrompt!=null&&t.push(this.createProjectRuleFilePath(n,Vy)),e.childMemoryPrompts!=null))for(let r of e.childMemoryPrompts)t.push(this.createProjectRuleFilePath(n,this.buildChildRuleFileName(r)))}return t.push(...this.registerProjectIgnoreOutputFiles(n)),t}async registerGlobalOutputDirs(e){let t=this.getGlobalConfigDir(),{fastCommands:n,skills:r}=e.collectedInputContext,i=[];if(n!=null&&n.length>0&&i.push(this.createRelativePath(Ry,t,()=>Ry)),r!=null&&r.length>0)for(let e of r){let n=e.yamlFrontMatter.name;i.push(this.createRelativePath(f.join(zy,n),t,()=>n))}return i}async registerGlobalOutputFiles(e){let t=this.getGlobalConfigDir(),{fastCommands:n,skills:r}=e.collectedInputContext,i=[],a=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});if(n!=null&&n.length>0)for(let e of n){let n=this.transformFastCommandName(e,a);i.push(this.createRelativePath(f.join(Ry,n),t,()=>Ry))}if(r!=null&&r.length>0)for(let e of r){let n=e.yamlFrontMatter.name;if(i.push(this.createRelativePath(f.join(zy,n,Hy),t,()=>n)),e.mcpConfig!=null&&i.push(this.createRelativePath(f.join(zy,n,Uy),t,()=>n)),e.childDocs!=null)for(let r of e.childDocs)i.push(this.createRelativePath(f.join(zy,n,r.relativePath.replace(/\.mdx$/,`.md`)),t,()=>n));if(e.resources!=null)for(let r of e.resources)i.push(this.createRelativePath(f.join(zy,n,r.relativePath),t,()=>n))}return i}async canWrite(e){let{workspace:t,globalMemory:n,fastCommands:r,skills:i,aiAgentIgnoreConfigFiles:a}=e.collectedInputContext,o=t.projects.some(e=>e.rootMemoryPrompt!=null||(e.childMemoryPrompts?.length??0)>0),s=a?.some(e=>e.fileName===`.qoderignore`)??!1;return o||n!=null||(r?.length??0)>0||(i?.length??0)>0||s?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,{globalMemory:n}=e.collectedInputContext,r=[];for(let i of t){if(i.dirFromWorkspacePath==null)continue;let t=i.dirFromWorkspacePath;if(n!=null){let i=this.buildAlwaysRuleContent(n.content);r.push(await this.writeProjectRuleFile(e,t,By,i,`globalRule`))}if(i.rootMemoryPrompt!=null){let n=this.buildAlwaysRuleContent(i.rootMemoryPrompt.content);r.push(await this.writeProjectRuleFile(e,t,Vy,n,`projectRootRule`))}if(i.childMemoryPrompts!=null)for(let n of i.childMemoryPrompts){let i=this.buildChildRuleFileName(n),a=this.buildGlobRuleContent(n);r.push(await this.writeProjectRuleFile(e,t,i,a,`projectChildRule`))}}let i=await this.writeProjectIgnoreFiles(e);return r.push(...i),{files:r,dirs:[]}}async writeGlobalOutputs(e){let{fastCommands:t,skills:n}=e.collectedInputContext,r=[],i=this.getGlobalConfigDir(),a=f.join(i,Ry),o=f.join(i,zy);if(t!=null&&t.length>0)for(let n of t)r.push(await this.writeGlobalFastCommand(e,a,n));if(n!=null&&n.length>0)for(let t of n)r.push(...await this.writeGlobalSkill(e,o,t));return{files:r,dirs:[]}}createProjectRulesDirPath(e){return this.createRelativePath(f.join(e.path,Iy,Ly),e.basePath,()=>Ly)}createProjectRuleFilePath(e,t){return this.createRelativePath(f.join(e.path,Iy,Ly,t),e.basePath,()=>Ly)}buildChildRuleFileName(e){let t=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``).replaceAll(`/`,`-`);return`glob-${t.length>0?t:`root`}.md`}buildAlwaysRuleContent(e){return Ag({trigger:`always_on`,type:`user_command`},e)}buildGlobRuleContent(e){let t=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``);return Ag({trigger:`glob`,glob:t.length===0?`**/*`:`${t}/**`,type:`user_command`},e.content)}async writeProjectRuleFile(e,t,n,r,i){let a=f.join(t.basePath,t.path,Iy,Ly),o=f.join(a,n);return this.writeFile(e,o,r,i)}async writeGlobalFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),i=this.transformFastCommandName(n,r),a=f.join(t,i),o=Ag(this.buildFastCommandFrontMatter(n),n.content);return this.writeFile(e,a,o,`globalFastCommand`)}async writeGlobalSkill(e,t,n){let r=[],i=n.yamlFrontMatter.name,a=f.join(t,i),o=f.join(a,Hy),s=Ag(this.buildSkillFrontMatter(n),n.content);if(r.push(await this.writeFile(e,o,s,`skill`)),n.mcpConfig!=null){let t=f.join(a,Uy);r.push(await this.writeFile(e,t,n.mcpConfig.rawContent,`mcpConfig`))}if(n.childDocs!=null)for(let t of n.childDocs){let n=f.join(a,t.relativePath.replace(/\.mdx$/,`.md`));r.push(await this.writeFile(e,n,t.content,`childDoc`))}if(n.resources!=null)for(let t of n.resources){let n=f.join(a,t.relativePath);if(t.encoding===`base64`){let e=h.Buffer.from(t.content,`base64`),o=f.dirname(n);this.ensureDirectory(o),this.writeFileSyncBuffer(n,e),r.push({path:this.createRelativePath(t.relativePath,a,()=>i),success:!0})}else r.push(await this.writeFile(e,n,t.content,`resource`))}return r}buildSkillFrontMatter(e){let t=e.yamlFrontMatter;return{name:t.name,description:t.description,type:`user_command`,...t.displayName!=null&&{displayName:t.displayName},...t.keywords!=null&&t.keywords.length>0&&{keywords:t.keywords},...t.author!=null&&{author:t.author},...t.version!=null&&{version:t.version},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}buildFastCommandFrontMatter(e){let t=e.yamlFrontMatter;return t==null?{description:`Fast command`,type:`user_command`}:{description:t.description,type:`user_command`,...t.argumentHint!=null&&{argumentHint:t.argumentHint},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}};const Gy=`README.md`;var Ky=class extends Pg{constructor(){super(`ReadmeMdConfigFileOutputPlugin`,{outputFileName:Gy})}async registerProjectOutputFiles(e){let t=[],{readmePrompts:n}=e.collectedInputContext;if(n==null||n.length===0)return t;for(let e of n){let{targetDir:n}=e,r=f.join(n.path,Gy);t.push({pathKind:L.Relative,path:r,basePath:n.basePath,getDirectoryName:()=>n.getDirectoryName(),getAbsolutePath:()=>f.join(n.basePath,r)})}return t}async canWrite(e){let{readmePrompts:t}=e.collectedInputContext;return t?.length===0?(this.log.debug(`skipped`,{reason:`no README prompts to write`}),!1):!0}async writeProjectOutputs(e){let t=[],n=[],{readmePrompts:r}=e.collectedInputContext;if(r==null||r.length===0)return{files:t,dirs:n};for(let n of r){let r=await this.writeReadmeFile(e,n);t.push(r)}return{files:t,dirs:n}}async writeReadmeFile(e,t){let{targetDir:n}=t,r=f.join(n.path,Gy),i=f.join(n.basePath,r),a=t.content,o={pathKind:L.Relative,path:r,basePath:n.basePath,getDirectoryName:()=>n.getDirectoryName(),getAbsolutePath:()=>i},s=t.isRoot?`project:${t.projectName}/README.md`:`project:${t.projectName}/${n.path}/README.md`;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`readme`,path:i,label:s}),{path:o,success:!0,skipped:!1};try{let e=f.dirname(i);return d.existsSync(e)||d.mkdirSync(e,{recursive:!0}),d.writeFileSync(i,a,`utf8`),this.log.trace({action:`write`,type:`readme`,path:i,label:s}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`readme`,path:i,label:s,error:t}),{path:o,success:!1,error:e}}}},qy=class extends Lg{constructor(){super(`ReadmeMdInputPlugin`,[`ShadowProjectInputPlugin`])}async collect(e){let{userConfigOptions:t,logger:n,fs:r,path:i,globalScope:a}=e,{workspaceDir:o,shadowProjectDir:s}=this.resolveBasePaths(t),c=this.resolveShadowPath(t.shadowSourceProject.project.dist,s),l=[];if(!r.existsSync(c)||!r.statSync(c).isDirectory())return n.debug(`shadow projects directory does not exist`,{path:c}),{readmePrompts:l};try{let t=r.readdirSync(c,{withFileTypes:!0});for(let n of t){if(!n.isDirectory())continue;let t=n.name,r=i.join(c,t);await this.collectReadmeFiles(e,r,t,o,``,l,a)}}catch(e){n.error(`failed to scan shadow projects`,{path:c,error:e})}return{readmePrompts:l}}async collectReadmeFiles(e,t,n,r,i,a,o){let{fs:s,path:c,logger:l}=e,d=i===``,f=c.join(t,`rdm.mdx`);if(s.existsSync(f)&&s.statSync(f).isFile())try{let e=s.readFileSync(f,`utf8`),p;if(o!=null)try{p=await uv(e,{globalScope:o,basePath:t})}catch(e){throw e instanceof qg&&(l.error(`MDX compilation failed in ${f}: ${e.message}`),l.error(`Please check your configuration file (~/.aindex/.tnmsc.json) and ensure all required variables are defined.`),u.default.exit(1)),e}else p=e;let m=d?n:c.join(n,i),h={pathKind:L.Relative,path:m,basePath:r,getDirectoryName:()=>d?n:c.basename(i),getAbsolutePath:()=>c.resolve(r,m)},g={pathKind:L.Relative,path:c.dirname(f),basePath:r,getDirectoryName:()=>c.basename(c.dirname(f)),getAbsolutePath:()=>c.dirname(f)};a.push({type:xt.Readme,content:p,length:p.length,filePathKind:L.Relative,projectName:n,targetDir:h,isRoot:d,markdownContents:[],dir:g})}catch(e){l.warn(`failed to read readme`,{path:f,error:e})}try{let l=s.readdirSync(t,{withFileTypes:!0});for(let s of l)if(s.isDirectory()){let l=d?s.name:c.join(i,s.name),u=c.join(t,s.name);await this.collectReadmeFiles(e,u,n,r,l,a,o)}}catch(e){l.warn(`failed to scan directory`,{path:t,error:e})}}},Jy=class extends kv{constructor(){super(`RuleInputPlugin`,{configKey:`shadowSourceProject.rule.dist`})}getTargetDir(e,t){return this.resolveShadowPath(e.shadowSourceProject.rule.dist,t.shadowProjectDir)}validateMetadata(e,t){return Nt(e,t)}createResult(e){return{rules:e}}createPrompt(e,t,n,r,i,a,o,s){let c=e.indexOf(`/`),l=c===-1?``:e.slice(0,c),u=(c===-1?e:e.slice(c+1)).replace(/\.mdx$/,``),d=r?.globs??[],f=r?.scope??`project`;return{type:xt.Rule,content:n,length:n.length,filePathKind:L.Relative,...r!=null&&{yamlFrontMatter:r},...i!=null&&{rawFrontMatter:i},markdownAst:a.markdownAst,markdownContents:a.markdownContents,dir:{pathKind:L.Relative,path:e,basePath:o,getDirectoryName:()=>e.replace(/\.mdx$/,``),getAbsolutePath:()=>t},series:l,ruleName:u,globs:d,scope:f,rawMdxContent:s}}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i}=e,a=this.resolveBasePaths(t),o=this.getTargetDir(t,a),s=[];if(!(i.existsSync(o)&&i.statSync(o).isDirectory()))return this.createResult(s);try{let t=i.readdirSync(o,{withFileTypes:!0});for(let a of t)if(a.isDirectory()){let t=r.join(o,a.name);try{let n=i.readdirSync(t,{withFileTypes:!0});for(let i of n)if(i.isFile()&&i.name.endsWith(this.extension)){let n=await this.processFile(i.name,r.join(t,i.name),o,a.name,e);n!=null&&s.push(n)}}catch(e){n.error(`Failed to scan subdirectory at ${t}`,{error:e})}}}catch(e){n.error(`Failed to scan directory at ${o}`,{error:e})}return this.createResult(s)}async processFile(e,t,n,r,i){let{logger:a,globalScope:o}=i,s=i.fs.readFileSync(t,`utf8`);try{let c=jg(s),l=await uv(s,{globalScope:o,extractMetadata:!0,basePath:i.path.join(n,r)}),u=c.yamlFrontMatter!=null||Object.keys(l.metadata.fields).length>0?{...c.yamlFrontMatter,...l.metadata.fields}:void 0;if(u!=null){let e=this.validateMetadata(u,t);for(let t of e.warnings)a.debug(t);if(!e.valid)throw new Xg([...e.errors],t)}let{content:d}=l,f=`${r}/${e}`;return a.debug(`${this.name} metadata extracted`,{file:f,source:l.metadata.source,hasYaml:c.yamlFrontMatter!=null,hasExport:Object.keys(l.metadata.fields).length>0}),this.createPrompt(f,t,d,u,c.rawFrontMatter,c,n,s)}catch(e){a.error(`failed to parse ${this.name} item`,{file:t,error:e});return}}},Yy=class extends Lg{constructor(){super(`ShadowProjectInputPlugin`)}collect(e){let{userConfigOptions:t,logger:n,fs:r,path:i}=e,{workspaceDir:a,shadowProjectDir:o}=this.resolveBasePaths(t),s=this.resolveShadowPath(t.shadowSourceProject.project.dist,o),c=i.basename(o),l=[];if(r.existsSync(s)&&r.statSync(s).isDirectory())try{let e=r.readdirSync(s,{withFileTypes:!0});for(let t of e)if(t.isDirectory()){let e=t.name===c;l.push({name:t.name,...e&&{isPromptSourceProject:!0},dirFromWorkspacePath:{pathKind:L.Relative,path:t.name,basePath:a,getDirectoryName:()=>t.name,getAbsolutePath:()=>i.resolve(a,t.name)}})}}catch(e){n.error(`failed to scan shadow projects`,{path:s,error:e})}if(l.length===0&&r.existsSync(a)&&r.statSync(a).isDirectory()){n.debug(`no projects in dist/app/, falling back to workspace scan`,{workspaceDir:a});try{let e=r.readdirSync(a,{withFileTypes:!0});for(let t of e)if(t.isDirectory()&&!t.name.startsWith(`.`)){let e=t.name===c;l.push({name:t.name,...e&&{isPromptSourceProject:!0},dirFromWorkspacePath:{pathKind:L.Relative,path:t.name,basePath:a,getDirectoryName:()=>t.name,getAbsolutePath:()=>i.resolve(a,t.name)}})}}catch(e){n.error(`failed to scan workspace directory`,{path:a,error:e})}}return{workspace:{directory:{pathKind:L.Absolute,path:a,getDirectoryName:()=>i.basename(a)},projects:l}}}};function Xy(e){return It.includes(e.toLowerCase())}function Zy(e){let t=e.toLowerCase();return[`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`,`.ico`,`.bmp`,`.tiff`,`.svg`].includes(t)?`image`:`.kt,.java,.py,.pyi,.pyx,.ts,.tsx,.js,.jsx,.mjs,.cjs,.go,.rs,.c,.cpp,.cc,.h,.hpp,.hxx,.cs,.fs,.fsx,.vb,.rb,.php,.swift,.scala,.groovy,.lua,.r,.jl,.ex,.exs,.erl,.clj,.cljs,.hs,.ml,.mli,.nim,.zig,.v,.dart,.vue,.svelte,.d.ts,.d.mts,.d.cts`.split(`,`).includes(t)?`code`:[`.sql`,`.json`,`.jsonc`,`.json5`,`.xml`,`.xsd`,`.xsl`,`.xslt`,`.yaml`,`.yml`,`.toml`,`.csv`,`.tsv`,`.graphql`,`.gql`,`.proto`].includes(t)?`data`:[`.txt`,`.text`,`.rtf`,`.log`,`.docx`,`.doc`,`.xlsx`,`.xls`,`.pptx`,`.ppt`,`.pdf`,`.odt`,`.ods`,`.odp`].includes(t)?`document`:[`.ini`,`.conf`,`.cfg`,`.config`,`.properties`,`.env`,`.envrc`,`.editorconfig`,`.gitignore`,`.gitattributes`,`.npmrc`,`.nvmrc`,`.npmignore`,`.eslintrc`,`.prettierrc`,`.stylelintrc`,`.babelrc`,`.browserslistrc`].includes(t)?`config`:[`.sh`,`.bash`,`.zsh`,`.fish`,`.ps1`,`.psm1`,`.psd1`,`.bat`,`.cmd`].includes(t)?`script`:`.exe,.dll,.so,.dylib,.bin,.wasm,.class,.jar,.war,.pyd,.pyc,.pyo,.zip,.tar,.gz,.bz2,.7z,.rar,.ttf,.otf,.woff,.woff2,.eot,.db,.sqlite,.sqlite3`.split(`,`).includes(t)?`binary`:`other`}function Qy(e){return{".ts":`text/typescript`,".tsx":`text/typescript`,".js":`text/javascript`,".jsx":`text/javascript`,".json":`application/json`,".py":`text/x-python`,".java":`text/x-java`,".kt":`text/x-kotlin`,".go":`text/x-go`,".rs":`text/x-rust`,".c":`text/x-c`,".cpp":`text/x-c++`,".cs":`text/x-csharp`,".rb":`text/x-ruby`,".php":`text/x-php`,".swift":`text/x-swift`,".scala":`text/x-scala`,".sql":`application/sql`,".xml":`application/xml`,".yaml":`text/yaml`,".yml":`text/yaml`,".toml":`text/toml`,".csv":`text/csv`,".graphql":`application/graphql`,".txt":`text/plain`,".pdf":`application/pdf`,".docx":`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,".xlsx":`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,".html":`text/html`,".css":`text/css`,".svg":`image/svg+xml`,".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".gif":`image/gif`,".webp":`image/webp`,".ico":`image/x-icon`,".bmp":`image/bmp`}[e.toLowerCase()]}var $y=class extends Lg{constructor(){super(`SkillInputPlugin`)}readMcpConfig(e,t,n){let r=f.join(e,`mcp.json`);if(t.existsSync(r)){if(!t.statSync(r).isFile()){n.warn(`mcp.json is not a file`,{skillDir:e});return}try{let i=t.readFileSync(r,`utf8`),a=JSON.parse(i);if(a.mcpServers==null||typeof a.mcpServers!=`object`){n.warn(`mcp.json missing mcpServers field`,{skillDir:e});return}return{type:xt.SkillMcpConfig,mcpServers:a.mcpServers,rawContent:i}}catch(t){n.warn(`failed to parse mcp.json`,{skillDir:e,error:t});return}}}scanSkillDirectory(e,t,n,r=``){let i=[],a=[],o=r?f.join(e,r):e;try{let s=t.readdirSync(o,{withFileTypes:!0});for(let c of s){let s=r?`${r}/${c.name}`:c.name;if(c.isDirectory()){let r=this.scanSkillDirectory(e,t,n,s);i.push(...r.childDocs),a.push(...r.resources)}else if(c.isFile()){let l=f.join(o,c.name);if(c.name.endsWith(`.mdx`)){if(r===``&&c.name===`skill.mdx`)continue;try{let n=jg(t.readFileSync(l,`utf8`)),r=Mg(n.contentWithoutFrontMatter);i.push({type:xt.SkillChildDoc,content:r,length:r.length,filePathKind:L.Relative,markdownAst:n.markdownAst,markdownContents:n.markdownContents,...n.rawFrontMatter!=null&&{rawFrontMatter:n.rawFrontMatter},relativePath:s,dir:{pathKind:L.Relative,path:s,basePath:e,getDirectoryName:()=>f.dirname(s),getAbsolutePath:()=>l}})}catch(e){n.warn(`failed to read child doc`,{path:s,error:e})}}else{if(r===``&&c.name===`mcp.json`)continue;let e=f.extname(c.name),i,o,u;try{if(Xy(e)){let e=t.readFileSync(l);i=e.toString(`base64`),o=`base64`,{length:u}=e}else i=t.readFileSync(l,`utf8`),o=`text`,{length:u}=h.Buffer.from(i,`utf8`);let n=Qy(e),r={type:xt.SkillResource,extension:e,fileName:c.name,relativePath:s,content:i,encoding:o,category:Zy(e),length:u};n==null?a.push(r):a.push({...r,mimeType:n})}catch(e){n.warn(`failed to read resource file`,{path:s,error:e})}}}}}catch(e){n.warn(`failed to scan directory`,{path:o,error:e})}return{childDocs:i,resources:a}}async collect(e){let{userConfigOptions:t,logger:n,globalScope:r}=e,{shadowProjectDir:i}=this.resolveBasePaths(t),a=this.resolveShadowPath(t.shadowSourceProject.skill.dist,i),o=[];if(!(e.fs.existsSync(a)&&e.fs.statSync(a).isDirectory()))return{skills:o};let s=e.fs.readdirSync(a,{withFileTypes:!0});for(let t of s)if(t.isDirectory()){let i=e.path.join(a,t.name,`skill.mdx`);if(e.fs.existsSync(i)&&e.fs.statSync(i).isFile())try{let s=e.fs.readFileSync(i,`utf8`),c=jg(s),l=await uv(s,{globalScope:r,extractMetadata:!0,basePath:e.path.join(a,t.name)}),u={...c.yamlFrontMatter,...l.metadata.fields},d=At(u,i);for(let e of d.warnings)n.debug(e);if(!d.valid)throw new Xg(d.errors,i);let p=Mg(l.content),m=e.path.join(a,t.name),h=this.readMcpConfig(m,e.fs,n),{childDocs:g,resources:_}=this.scanSkillDirectory(m,e.fs,n);n.debug(`skill metadata extracted`,{skill:t.name,source:l.metadata.source,hasYaml:c.yamlFrontMatter!=null,hasExport:Object.keys(l.metadata.fields).length>0}),o.push({type:xt.Skill,content:p,length:p.length,filePathKind:L.Relative,yamlFrontMatter:u.name==null?{name:t.name,description:``}:u,...c.rawFrontMatter!=null&&{rawFrontMatter:c.rawFrontMatter},markdownAst:c.markdownAst,markdownContents:c.markdownContents,...h!=null&&{mcpConfig:h},...g.length>0&&{childDocs:g},..._.length>0&&{resources:_},dir:{pathKind:L.Relative,path:t.name,basePath:a,getDirectoryName:()=>t.name,getAbsolutePath:()=>f.join(a,t.name)}})}catch(e){n.error(`failed to parse skill`,{file:i,error:e})}}return{skills:o}}},eb=class extends kv{constructor(){super(`SubAgentInputPlugin`,{configKey:`shadowSourceProject.subAgent.dist`})}getTargetDir(e,t){return this.resolveShadowPath(e.shadowSourceProject.subAgent.dist,t.shadowProjectDir)}validateMetadata(e,t){return Mt(e,t)}createResult(e){return{subAgents:e}}extractSeriesInfo(e,t){let n=e.replace(/\.mdx$/,``);if(t!=null)return{series:t,agentName:n};let r=n.indexOf(`_`);return r===-1?{agentName:n}:{series:n.slice(0,Math.max(0,r)),agentName:n.slice(Math.max(0,r+1))}}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i}=e,a=this.resolveBasePaths(t),o=this.getTargetDir(t,a),s=[];if(!(i.existsSync(o)&&i.statSync(o).isDirectory()))return this.createResult(s);try{let t=i.readdirSync(o,{withFileTypes:!0});for(let a of t)if(a.isFile()&&a.name.endsWith(this.extension)){let t=await this.processFile(a.name,r.join(o,a.name),o,void 0,e);t!=null&&s.push(t)}else if(a.isDirectory()){let t=r.join(o,a.name);try{let n=i.readdirSync(t,{withFileTypes:!0});for(let i of n)if(i.isFile()&&i.name.endsWith(this.extension)){let n=await this.processFile(i.name,r.join(t,i.name),o,a.name,e);n!=null&&s.push(n)}}catch(e){n.error(`Failed to scan subdirectory at ${t}`,{error:e})}}}catch(e){n.error(`Failed to scan directory at ${o}`,{error:e})}return this.createResult(s)}async processFile(e,t,n,r,i){let{logger:a,globalScope:o}=i,s=i.fs.readFileSync(t,`utf8`);try{let c=jg(s),l=await uv(s,{globalScope:o,extractMetadata:!0,basePath:r==null?n:i.path.join(n,r)}),u=c.yamlFrontMatter!=null||Object.keys(l.metadata.fields).length>0?{...c.yamlFrontMatter,...l.metadata.fields}:void 0;if(u!=null){let e=this.validateMetadata(u,t);for(let t of e.warnings)a.debug(t);if(!e.valid)throw new Xg([...e.errors],t)}let{content:d}=l,f=r==null?e:`${r}/${e}`;return a.debug(`${this.name} metadata extracted`,{file:f,source:l.metadata.source,hasYaml:c.yamlFrontMatter!=null,hasExport:Object.keys(l.metadata.fields).length>0}),this.createPrompt(f,t,d,u,c.rawFrontMatter,c,n,s)}catch(e){a.error(`failed to parse ${this.name} item`,{file:t,error:e});return}}createPrompt(e,t,n,r,i,a,o,s){let c=e.indexOf(`/`),l=c===-1?void 0:e.slice(0,c),u=c===-1?e:e.slice(c+1),d=this.extractSeriesInfo(u,l);return{type:xt.SubAgent,content:n,length:n.length,filePathKind:L.Relative,...r!=null&&{yamlFrontMatter:r},...i!=null&&{rawFrontMatter:i},markdownAst:a.markdownAst,markdownContents:a.markdownContents,dir:{pathKind:L.Relative,path:e,basePath:o,getDirectoryName:()=>e.replace(/\.mdx$/,``),getAbsolutePath:()=>t},...d.series!=null&&{series:d.series},agentName:d.agentName,rawMdxContent:s}}};const tb=`GLOBAL.md`,nb=`.trae`,rb=`steering`,ib=`rules`;var ab=class extends Pg{constructor(){super(`TraeIDEOutputPlugin`,{globalConfigDir:nb,outputFileName:tb,indexignore:`.traeignore`})}getGlobalSteeringDir(){return this.joinPath(this.getGlobalConfigDir(),rb)}async registerProjectOutputDirs(e){let{projects:t}=e.collectedInputContext.workspace;return t.filter(e=>e.dirFromWorkspacePath!=null).map(e=>this.createRelativePath(this.joinPath(e.dirFromWorkspacePath.path,nb,ib),e.dirFromWorkspacePath.basePath,()=>ib))}async registerProjectOutputFiles(e){let{projects:t}=e.collectedInputContext.workspace,n=[];for(let e of t)if(!(e.dirFromWorkspacePath==null||e.childMemoryPrompts==null))for(let t of e.childMemoryPrompts)n.push(this.createRelativePath(this.joinPath(e.dirFromWorkspacePath.path,nb,ib,this.buildSteeringFileName(t)),e.dirFromWorkspacePath.basePath,()=>ib));return n.push(...this.registerProjectIgnoreOutputFiles(t)),n}async registerGlobalOutputDirs(){return[this.createRelativePath(rb,this.getGlobalConfigDir(),()=>rb)]}async registerGlobalOutputFiles(e){let{globalMemory:t,fastCommands:n}=e.collectedInputContext,r=this.getGlobalSteeringDir(),i=[];if(t!=null&&i.push(this.createRelativePath(tb,r,()=>rb)),n!=null)for(let e of n)i.push(this.createRelativePath(this.buildFastCommandSteeringFileName(e),r,()=>rb));return i}async canWrite(e){let{workspace:t,globalMemory:n,fastCommands:r,aiAgentIgnoreConfigFiles:i}=e.collectedInputContext,a=t.projects.some(e=>(e.childMemoryPrompts?.length??0)>0),o=i?.some(e=>e.fileName===`.traeignore`)??!1;return a||n!=null||(r?.length??0)>0||o?!0:(this.log.trace({action:`skip`,reason:`noOutputs`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,n=[];for(let r of t)if(!(r.dirFromWorkspacePath==null||r.childMemoryPrompts==null))for(let t of r.childMemoryPrompts)n.push(await this.writeSteeringFile(e,r,t));let r=await this.writeProjectIgnoreFiles(e);return n.push(...r),{files:n,dirs:[]}}async writeGlobalOutputs(e){let{globalMemory:t,fastCommands:n}=e.collectedInputContext,r=[],i=this.getGlobalSteeringDir();if(t!=null&&r.push(await this.writeFile(e,this.joinPath(i,tb),t.content,`globalMemory`)),n!=null)for(let t of n)r.push(await this.writeFastCommandSteeringFile(e,t));return{files:r,dirs:[]}}buildFastCommandSteeringFileName(e){return this.transformFastCommandName(e,{includeSeriesPrefix:!0,seriesSeparator:`-`})}async writeFastCommandSteeringFile(e,t){let n=this.buildFastCommandSteeringFileName(t),r=this.joinPath(this.getGlobalSteeringDir(),n),i=t.yamlFrontMatter?.description,a=this.buildMarkdownContent(t.content,{inclusion:`manual`,description:i!=null&&i.length>0?i:null});return this.writeFile(e,r,a,`fastCommandSteering`)}buildSteeringFileName(e){return`trae-${(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``).replaceAll(`/`,`-`)}.md`}async writeSteeringFile(e,t,n){let r=t.dirFromWorkspacePath,i=this.buildSteeringFileName(n),a=this.joinPath(r.basePath,r.path,nb,ib),o=this.joinPath(a,i),s=[`---`,`alwaysApply: false`,`globs: ${`${(n.workingChildDirectoryPath?.path??n.dir.path).replaceAll(`\\`,`/`)}/**`}`,`---`,``,n.content].join(`
|
|
1239
|
+
`);return this.writeFile(e,o,s,`steeringFile`)}};const ob=`.vscode`,sb=[`.vscode/settings.json`,`.vscode/extensions.json`];var cb=class extends Pg{constructor(){super(`VisualStudioCodeIDEConfigOutputPlugin`)}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace,{ideConfigFiles:r}=e.collectedInputContext;if(!r.some(e=>e.type===Tt.VSCode))return t;for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null&&e.isPromptSourceProject!==!0)for(let e of sb){let r=this.joinPath(n.path,e);t.push({pathKind:L.Relative,path:r,basePath:n.basePath,getDirectoryName:()=>this.dirname(e),getAbsolutePath:()=>this.resolvePath(n.basePath,r)})}}return t}async canWrite(e){let{ideConfigFiles:t}=e.collectedInputContext;return t.some(e=>e.type===Tt.VSCode)?!0:(this.log.debug(`skipped`,{reason:`no VS Code config files found`}),!1)}async writeProjectOutputs(e){let{projects:t}=e.collectedInputContext.workspace,{ideConfigFiles:n}=e.collectedInputContext,r=[],i=[],a=n.filter(e=>e.type===Tt.VSCode);for(let n of t){let t=n.dirFromWorkspacePath;if(t==null)continue;let i=n.name??`unknown`;for(let n of a){let a=await this.writeConfigFile(e,t,n,`project:${i}`);r.push(a)}}return{files:r,dirs:i}}async writeConfigFile(e,t,n,r){let i=this.getTargetRelativePath(n),a=this.resolvePath(t.basePath,t.path,i),o={pathKind:L.Relative,path:this.joinPath(t.path,i),basePath:t.basePath,getDirectoryName:()=>this.dirname(i),getAbsolutePath:()=>a};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`config`,path:a,label:r}),{path:o,success:!0,skipped:!1};try{let e=this.dirname(a);return this.ensureDirectory(e),this.writeFileSync(a,n.content),this.log.trace({action:`write`,type:`config`,path:a,label:r}),{path:o,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`config`,path:a,label:r,error:t}),{path:o,success:!1,error:e}}}getTargetRelativePath(e){let t=e.dir.path;if(e.type!==Tt.VSCode)return this.basename(t);let n=t.indexOf(ob);return n===-1?this.joinPath(ob,this.basename(t)):t.slice(Math.max(0,n))}};const lb=`WARP.md`;var ub=class extends Pg{constructor(){super(`WarpIDEOutputPlugin`,{outputFileName:lb,indexignore:`.warpindexignore`})}isAgentsPluginRegistered(e){return`registeredPluginNames`in e&&e.registeredPluginNames!=null?e.registeredPluginNames.includes(`AgentsOutputPlugin`):!1}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace,r=this.isAgentsPluginRegistered(e);for(let e of n)if(e.dirFromWorkspacePath!=null){if(r)t.push(this.createFileRelativePath(e.dirFromWorkspacePath,lb));else if(e.rootMemoryPrompt!=null&&t.push(this.createFileRelativePath(e.dirFromWorkspacePath,lb)),e.childMemoryPrompts!=null)for(let n of e.childMemoryPrompts)n.dir!=null&&this.isRelativePath(n.dir)&&t.push(this.createFileRelativePath(n.dir,lb))}return t.push(...this.registerProjectIgnoreOutputFiles(n)),t}async canWrite(e){let t=this.isAgentsPluginRegistered(e),{workspace:n,globalMemory:r,aiAgentIgnoreConfigFiles:i}=e.collectedInputContext;if(t)return r==null?(this.log.debug(`skipped`,{reason:`AgentsOutputPlugin registered but no global memory`}),!1):!0;let a=n.projects.some(e=>e.rootMemoryPrompt!=null||(e.childMemoryPrompts?.length??0)>0),o=i?.some(e=>e.fileName===`.warpindexignore`)??!1;return a||o?!0:(this.log.debug(`skipped`,{reason:`no outputs to write`}),!1)}async writeProjectOutputs(e){let t=this.isAgentsPluginRegistered(e),{workspace:n,globalMemory:r}=e.collectedInputContext,{projects:i}=n,a=[],o=[];if(t){if(r!=null)for(let t of i){let n=t.dirFromWorkspacePath;if(n==null)continue;let i=t.name??`unknown`,o=await this.writePromptFile(e,n,r.content,`project:${i}/global-warp`);a.push(o)}let t=await this.writeProjectIgnoreFiles(e);return a.push(...t),{files:a,dirs:o}}let s=this.extractGlobalMemoryContent(e);for(let t of i){let n=t.name??`unknown`,r=t.dirFromWorkspacePath;if(r!=null){if(t.rootMemoryPrompt!=null){let i=this.combineGlobalWithContent(s,t.rootMemoryPrompt.content),o=await this.writePromptFile(e,r,i,`project:${n}/root`);a.push(o)}if(t.childMemoryPrompts!=null)for(let r of t.childMemoryPrompts){let t=await this.writePromptFile(e,r.dir,r.content,`project:${n}/child:${r.workingChildDirectoryPath?.path??`unknown`}`);a.push(t)}}}let c=await this.writeProjectIgnoreFiles(e);return a.push(...c),{files:a,dirs:o}}},db=class extends Lg{constructor(){super(`WorkspaceInputPlugin`)}collect(e){let{userConfigOptions:t}=e,{workspaceDir:n,shadowProjectDir:r}=this.resolveBasePaths(t);return{workspace:{directory:{pathKind:L.Absolute,path:n,getDirectoryName:()=>f.basename(n)},projects:[]},shadowSourceProjectDir:r}}},fb=Dr({plugins:[new Ig,new Kg,new pv,new vv,new ry,new Ov,new jv,new Iv,new My,new dy,new Wy,new ab,new ub,new Cy,new Dv,new Hv,new oy,new cb,new Ky,new my,new fy,new sy,new db,new Yy,new zg,new qv,new $y,new Av,new eb,new Jy,new Kv,new Fy,new qy,new Gv,new Rv]});async function pb(){let e=await fb;await new vr(...u.default.argv).run(e)}pb().catch(e=>console.error(e)),exports.CircularDependencyError=Et,exports.ClaudeCodeCLISubAgentColors=I,exports.CodingAgentTools=St,exports.ConfigLoader=dn,exports.ConfigValidationError=Ot,exports.DEFAULT_CONFIG_FILE_NAME=rn,exports.DEFAULT_GLOBAL_CONFIG_DIR=an,exports.DEFAULT_SHADOW_SOURCE_PROJECT_STRUCTURE=Bt,exports.DEFAULT_USER_CONFIG=Wt,exports.FilePathKind=L,exports.GlobalConfigDirectoryType=wt,exports.IDEKind=Tt,exports.MissingDependencyError=Dt,exports.NamingCaseKind=Ct,exports.PathPlaceholders=R,exports.PluginKind=bt,exports.PromptKind=xt,exports.SHADOW_SOURCE_DIR_NAMES=Lt,exports.SHADOW_SOURCE_FILE_NAMES=Rt,exports.SHADOW_SOURCE_RELATIVE_PATHS=zt,exports.SKILL_RESOURCE_BINARY_EXTENSIONS=It,exports.SKILL_RESOURCE_TEXT_EXTENSIONS=Ft,exports.applyMetadataDefaults=Pt,exports.checkCanClean=dt,exports.checkCanWrite=pt,exports.checkVersionControl=In,exports.collectAllPluginOutputs=ut,exports.createLogger=nn,exports.default=fb,exports.defineConfig=Dr,exports.executeOnCleanComplete=ft,exports.executeWriteOutputs=mt,exports.generateShadowSourceProject=Rn,exports.getConfigLoader=pn,exports.getDefaultUserConfig=sn,exports.getGlobalConfigPath=on,exports.getGlobalLogLevel=tn,exports.loadUserConfig=mn,exports.mergeConfig=Sr,exports.setGlobalLogLevel=en,exports.validateAndEnsureGlobalConfig=hn,exports.validateExportMetadata=kt,exports.validateFastCommandMetadata=jt,exports.validateRuleMetadata=Nt,exports.validateSkillMetadata=At,exports.validateSubAgentMetadata=Mt;
|