@truenine/memory-sync-cli 2026.10218.11313 → 2026.10218.11905
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 +5 -3
- package/dist/index.mjs +5 -3
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -955,7 +955,7 @@ API 接口 (Spring WebFlux 6.2)
|
|
|
955
955
|
- \`controllers/\`: 控制器
|
|
956
956
|
- \`dto/\`: 数据传输对象
|
|
957
957
|
\`\`\`
|
|
958
|
-
`};const Ut=Object.fromEntries(Vt.map(e=>[e,{path:e,content:Ht[e]??``}])),R={USER_HOME:`~`,WORKSPACE:`$WORKSPACE`,SHADOW_SOURCE_PROJECT:`$SHADOW_SOURCE_PROJECT`},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})}var ln=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=[];for(let t of[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`])t in e&&(typeof e[t]==`string`?n[t]=e[t]:r.push(`${t} must be a string`));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(`externalProjects`in e){let t=e.externalProjects;Array.isArray(t)?t.every(e=>typeof e==`string`)?n.externalProjects=t:r.push(`externalProjects must be an array of strings`):r.push(`externalProjects must be an array`)}if(`excludePatterns`in e){let t=e.excludePatterns;if(typeof t==`object`&&t){let e=t,i={},a=!0;for(let[t,n]of Object.entries(e))Array.isArray(n)&&n.every(e=>typeof e==`string`)?i[t]=n:(r.push(`excludePatterns.${t} must be an array of strings`),a=!1);a&&(n.excludePatterns=i)}else r.push(`excludePatterns must be an object`)}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`)}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=[...e.externalProjects??[],...t.externalProjects??[]],r=this.mergeExcludePatterns(e.excludePatterns,t.excludePatterns);return{...e,...t,...n.length>0?{externalProjects:n}:{},...r==null?{}:{excludePatterns:r}}},{})}mergeExcludePatterns(e,t){if(e==null&&t==null)return null;if(e==null)return t??null;if(t==null)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]=[...n[e]??[],...r];return n}resolveTilde(e){return e.startsWith(`~`)?f.join(p.homedir(),e.slice(1)):e}};let un=null;function dn(e){return(e||!un)&&(un=new ln(e)),un}function fn(e){return dn().load(e)}function pn(){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}),hn(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}),hn(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}),hn(t,e,[`Config must be a JSON object`]);let i=mn(r);if(i.length>0){for(let n of i)e.error(`config validation error`,{path:t,error:n});return hn(t,e,i)}return{valid:!0,exists:!0,errors:[],shouldExit:!1}}function mn(e){let t=[];for(let n of[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`])n in e&&typeof e[n]!=`string`&&t.push(`${n} must be a string`);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(`externalProjects`in e){let n=e.externalProjects;Array.isArray(n)?n.every(e=>typeof e==`string`)||t.push(`externalProjects must be an array of strings`):t.push(`externalProjects must be an array`)}if(`excludePatterns`in e){let n=e.excludePatterns;if(typeof n!=`object`||!n||Array.isArray(n))t.push(`excludePatterns must be an object`);else{let e=n;for(let[n,r]of Object.entries(e))(!Array.isArray(r)||!r.every(e=>typeof e==`string`))&&t.push(`excludePatterns.${n} must be an array of strings`)}}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 hn(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 gn=[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`,`logLevel`];function _n(e){return gn.includes(e)}function vn(e){return[`trace`,`debug`,`info`,`warn`,`error`].includes(e)}function yn(){return f.join(p.homedir(),an,rn)}function bn(){let e=yn();if(!d.existsSync(e))return{};try{let t=d.readFileSync(e,`utf8`);return JSON.parse(t)}catch{return{}}}function xn(e){let t=yn(),n=f.dirname(t);d.existsSync(n)||d.mkdirSync(n,{recursive:!0}),d.writeFileSync(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)}var Sn=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: ${gn.join(`, `)}`),{success:!1,filesAffected:0,dirsAffected:0,message:`No options provided`};let n=bn(),r=[],i=[];for(let[e,a]of this.options){if(!_n(e)){r.push(`Invalid key: ${e} (valid keys: ${gn.join(`, `)})`);continue}if(e===`logLevel`&&!vn(a)){r.push(`Invalid logLevel value: ${a} (must be: trace, debug, info, warn, or error)`);continue}let o=n[e];n[e]=a,o!==a&&i.push(`${e}=${a}`),t.info(`configuration updated`,{key:e,value:a})}if(i.length>0&&(xn(n),t.info(`global config written`,{path:yn()})),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}}},Cn=class{name=`config-show`;async execute(e){let{logger:t}=e,n=new ln,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`}},wn=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})}}},Tn=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`}}},En=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 Dn(){return`2026.10218.11313`}var On=class{name=`version`;async execute(e){return e.logger.error(`tnmsc v${Dn()}`),{success:!0,filesAffected:0,dirsAffected:0,message:`Version displayed`}}};const kn=`tnmsc`,An=`
|
|
958
|
+
`};const Ut=Object.fromEntries(Vt.map(e=>[e,{path:e,content:Ht[e]??``}])),R={USER_HOME:`~`,WORKSPACE:`$WORKSPACE`,SHADOW_SOURCE_PROJECT:`$SHADOW_SOURCE_PROJECT`},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})}var ln=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=[];for(let t of[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`])t in e&&(typeof e[t]==`string`?n[t]=e[t]:r.push(`${t} must be a string`));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(`externalProjects`in e){let t=e.externalProjects;Array.isArray(t)?t.every(e=>typeof e==`string`)?n.externalProjects=t:r.push(`externalProjects must be an array of strings`):r.push(`externalProjects must be an array`)}if(`excludePatterns`in e){let t=e.excludePatterns;if(typeof t==`object`&&t){let e=t,i={},a=!0;for(let[t,n]of Object.entries(e))Array.isArray(n)&&n.every(e=>typeof e==`string`)?i[t]=n:(r.push(`excludePatterns.${t} must be an array of strings`),a=!1);a&&(n.excludePatterns=i)}else r.push(`excludePatterns must be an object`)}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`)}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=[...e.externalProjects??[],...t.externalProjects??[]],r=this.mergeExcludePatterns(e.excludePatterns,t.excludePatterns);return{...e,...t,...n.length>0?{externalProjects:n}:{},...r==null?{}:{excludePatterns:r}}},{})}mergeExcludePatterns(e,t){if(e==null&&t==null)return null;if(e==null)return t??null;if(t==null)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]=[...n[e]??[],...r];return n}resolveTilde(e){return e.startsWith(`~`)?f.join(p.homedir(),e.slice(1)):e}};let un=null;function dn(e){return(e||!un)&&(un=new ln(e)),un}function fn(e){return dn().load(e)}function pn(){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}),hn(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}),hn(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}),hn(t,e,[`Config must be a JSON object`]);let i=mn(r);if(i.length>0){for(let n of i)e.error(`config validation error`,{path:t,error:n});return hn(t,e,i)}return{valid:!0,exists:!0,errors:[],shouldExit:!1}}function mn(e){let t=[];for(let n of[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`])n in e&&typeof e[n]!=`string`&&t.push(`${n} must be a string`);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(`externalProjects`in e){let n=e.externalProjects;Array.isArray(n)?n.every(e=>typeof e==`string`)||t.push(`externalProjects must be an array of strings`):t.push(`externalProjects must be an array`)}if(`excludePatterns`in e){let n=e.excludePatterns;if(typeof n!=`object`||!n||Array.isArray(n))t.push(`excludePatterns must be an object`);else{let e=n;for(let[n,r]of Object.entries(e))(!Array.isArray(r)||!r.every(e=>typeof e==`string`))&&t.push(`excludePatterns.${n} must be an array of strings`)}}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 hn(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 gn=[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`,`logLevel`];function _n(e){return gn.includes(e)}function vn(e){return[`trace`,`debug`,`info`,`warn`,`error`].includes(e)}function yn(){return f.join(p.homedir(),an,rn)}function bn(){let e=yn();if(!d.existsSync(e))return{};try{let t=d.readFileSync(e,`utf8`);return JSON.parse(t)}catch{return{}}}function xn(e){let t=yn(),n=f.dirname(t);d.existsSync(n)||d.mkdirSync(n,{recursive:!0}),d.writeFileSync(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)}var Sn=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: ${gn.join(`, `)}`),{success:!1,filesAffected:0,dirsAffected:0,message:`No options provided`};let n=bn(),r=[],i=[];for(let[e,a]of this.options){if(!_n(e)){r.push(`Invalid key: ${e} (valid keys: ${gn.join(`, `)})`);continue}if(e===`logLevel`&&!vn(a)){r.push(`Invalid logLevel value: ${a} (must be: trace, debug, info, warn, or error)`);continue}let o=n[e];n[e]=a,o!==a&&i.push(`${e}=${a}`),t.info(`configuration updated`,{key:e,value:a})}if(i.length>0&&(xn(n),t.info(`global config written`,{path:yn()})),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}}},Cn=class{name=`config-show`;async execute(e){let{logger:t}=e,n=new ln,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`}},wn=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})}}},Tn=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`}}},En=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 Dn(){return`2026.10218.11905`}var On=class{name=`version`;async execute(e){return e.logger.error(`tnmsc v${Dn()}`),{success:!0,filesAffected:0,dirsAffected:0,message:`Version displayed`}}};const kn=`tnmsc`,An=`
|
|
959
959
|
${kn} v${Dn()} - Memory Sync CLI
|
|
960
960
|
|
|
961
961
|
Synchronize AI memory and configuration files across projects.
|
|
@@ -1009,7 +1009,7 @@ CONFIG OPTIONS:
|
|
|
1009
1009
|
CONFIGURATION:
|
|
1010
1010
|
Configure via plugin.config.ts in your project root.
|
|
1011
1011
|
See documentation for detailed configuration options.
|
|
1012
|
-
`.trim();var jn=class{name=`help`;async execute(e){return console.log(An),{success:!0,filesAffected:0,dirsAffected:0,message:`Help displayed`}}};function Mn(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 Nn(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 Pn(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=Nn(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 Fn(e,t,n){let r=e;return r=r.replace(R.SHADOW_SOURCE_PROJECT,n),r=r.replace(R.WORKSPACE,t),r.startsWith(`~`)&&(r=f.join(p.homedir(),r.slice(1))),f.normalize(r)}var In=class{name=`init`;async execute(e){let{logger:t,userConfigOptions:n}=e;t.info(`initializing shadow source project structure`,{command:`init`});let r=Fn(n.workspaceDir,``,``),i=Pn(Fn(n.shadowSourceProjectDir,r,``),{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}}},Ln=class{name;inner;constructor(e){this.inner=e,this.name=`json:${e.name}`}async execute(e){let t=await this.inner.execute(e),n=Rn(t);return u.default.stdout.write(`${JSON.stringify(n)}\n`),t}};function Rn(e){return{success:e.success,filesAffected:e.filesAffected,dirsAffected:e.dirsAffected,...e.message!=null&&{message:e.message},pluginResults:[],errors:[]}}function zn(){return`@truenine/memory-sync-cli`}function Bn(){return`https://registry.npmjs.org/${zn()}/latest`}function Vn(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 Hn(e,t){let n=Vn(e),r=Vn(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 Un=3e3;async function Wn(){let e=new AbortController,t=setTimeout(()=>e.abort(),Un);typeof t==`object`&&`unref`in t&&t.unref();try{let n=await fetch(Bn(),{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 ${Un}ms`}:{error:e.message}:{error:`Unknown network error`}}}function Gn(){return`2026.10218.11313`}async function Kn(){let e=Gn();if(e===`dev`)return{status:`development`,localVersion:e,remoteVersion:null};let t=await Wn();if(`error`in t)return{status:`current`,localVersion:e,remoteVersion:null,error:t.error};let n=t.version,r=Hn(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 qn(e,t){let{status:n,localVersion:r,remoteVersion:i}=e;switch(n){case`outdated`:t.warn(`Version outdated: ${r} → ${i}. Run 'npm i -g ${zn()}@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 Jn(){return new Date().getMinutes()%2==0}function Yn(e){Jn()&&Kn().then(t=>{(t.status===`outdated`||t.error!=null)&&qn(t,e)}).catch(t=>{let n=t instanceof Error?t.message:`Unknown error`;e.error(`Version check failed: ${n}`)})}var Xn=class{name=`outdated`;async execute(e){let t=await Kn();return qn(t,e.logger),{success:!0,filesAffected:0,dirsAffected:0,message:`Version status: ${t.status}`}}},Zn=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)`}}},Qn=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 $n={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 er=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}({}),tr=function(e){return e.Win=`win`,e.Mac=`mac`,e.Linux=`linux`,e.Unknown=`unknown`,e}({});var nr=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 tr.Win;case`darwin`:return tr.Mac;case`linux`:case`freebsd`:case`openbsd`:case`sunos`:case`aix`:return tr.Linux;default:return tr.Unknown}}detectShellKind(){let e=(u.default.env.SHELL??u.default.env.ComSpec??``).toLowerCase();return e.includes(`bash`)?er.Bash:e.includes(`zsh`)?er.Zsh:e.includes(`fish`)?er.Fish:e.includes(`pwsh`)?er.Pwsh:e.includes(`powershell`)?er.PowerShell:e.includes(`cmd`)?er.Cmd:e.endsWith(`/sh`)?er.Sh:er.Unknown}collectEnvContext(){return{...u.default.env}}collectProfile(){return this.userConfig?.profile==null?{}:this.userConfig.profile}collectToolReferences(){let e={...$n.default};return this.toolPreset===`claudeCode`?{...e,...$n.claudeCode}:this.toolPreset===`kiro`?{...e,...$n.kiro}:e}createMdComponent(){let e=(e=>e.when===!1?null:e.children);return e.Line=e=>e.when===!1?null:e.children,e}};let rr=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 ir=class{registrations=[];globalScope=null;setGlobalScope(e){this.globalScope=e}getGlobalScope(){return this.globalScope}register(e,t,n=rr.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 ar(e){let t=[...e],n=t[0];n!=null&&or(n)&&t.shift();let r=t[0];return r!=null&&sr(r)&&t.shift(),t}function or(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 sr(e){return/\.(?:m?[jt]s|cjs)$/.test(e)||/[/\\]/.test(e)&&!e.startsWith(`-`)?!0:/^(?:@[\w-]+\/)?[\w-]+$/.test(e)&&!e.startsWith(`-`)}const cr=new Set([`help`,`version`,`outdated`,`init`,`dry-run`,`clean`,`config`,`plugins`]),lr=new Map([[`--trace`,`trace`],[`--debug`,`debug`],[`--info`,`info`],[`--warn`,`warn`],[`--error`,`error`]]),ur=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4]]);function dr(e){let{logLevelFlags:t}=e;if(t.length===0)return;let n=t[0],r=ur.get(n)??4;for(let e of t){let t=ur.get(e)??4;t<r&&(r=t,n=e)}return n}function fr(e){let{helpFlag:t,versionFlag:n,subcommand:r,dryRun:i,unknownCommand:a,setOption:o,positional:s,showFlag:c}=e;if(n)return new On;if(t)return new jn;if(a!=null)return new Qn(a);if(r===`version`)return new On;if(r===`help`)return new jn;if(r===`outdated`)return new Xn;if(r===`init`)return new In;if(r===`dry-run`)return new Tn;if(r===`clean`)return i?new wn:new yt;if(r===`plugins`)return new Zn;if(r===`config`&&c)return new Cn;if(r!==`config`||o.length>0)return new En;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 Sn([...o,...l])}function pr(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=lr.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,cr.has(i)?t.subcommand=i:t.unknownCommand=i;continue}t.positional.push(i)}}return t}var mr=class{logger;args;outputPlugins=[];constructor(...e){this.args=pr(ar(e.filter(e=>e!=null)));let t=dr(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){Yn(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 Ln(i)));let a=this.createCommandContext(t,r);await i.execute(a)}resolveCommand(){return fr(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 nr({userConfig:r}).collect(),o=new ir;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,rr.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.externalProjects==null?e.externalProjects:[...e.externalProjects??[],...t.externalProjects],i=t.ideConfigFiles==null?e.ideConfigFiles:[...e.ideConfigFiles??[],...t.ideConfigFiles],a=t.fastCommands==null?e.fastCommands:[...e.fastCommands??[],...t.fastCommands],o=t.subAgents==null?e.subAgents:[...e.subAgents??[],...t.subAgents],s=t.skills==null?e.skills:[...e.skills??[],...t.skills],c=t.rules==null?e.rules:[...e.rules??[],...t.rules],l=t.aiAgentIgnoreConfigFiles==null?e.aiAgentIgnoreConfigFiles:[...e.aiAgentIgnoreConfigFiles??[],...t.aiAgentIgnoreConfigFiles],u=t.globalMemory??e.globalMemory,d=t.shadowSourceProjectDir??e.shadowSourceProjectDir,f=t.readmePrompts==null?e.readmePrompts:[...e.readmePrompts??[],...t.readmePrompts],p=t.globalGitIgnore??e.globalGitIgnore,m=t.shadowGitExclude??e.shadowGitExclude;return{...n==null?{}:{workspace:n},...r==null?{}:{externalProjects:r},...i==null?{}:{ideConfigFiles:i},...a==null?{}:{fastCommands:a},...o==null?{}:{subAgents:o},...s==null?{}:{skills:s},...c==null?{}:{rules:c},...l==null?{}:{aiAgentIgnoreConfigFiles:l},...u==null?{}:{globalMemory:u},...d==null?{}:{shadowSourceProjectDir:d},...f==null?{}:{readmePrompts:f},...p==null?{}:{globalGitIgnore:p},...m==null?{}:{shadowGitExclude:m}}}};const hr={...Wt,externalProjects:[],excludePatterns:{},fastCommandSeriesOptions:{},plugins:[]};function gr(e){return{...e.workspaceDir==null?{}:{workspaceDir:e.workspaceDir},...e.shadowSourceProjectDir==null?{}:{shadowSourceProjectDir:e.shadowSourceProjectDir},...e.shadowSkillSourceDir==null?{}:{shadowSkillSourceDir:e.shadowSkillSourceDir},...e.shadowFastCommandDir==null?{}:{shadowFastCommandDir:e.shadowFastCommandDir},...e.shadowSubAgentDir==null?{}:{shadowSubAgentDir:e.shadowSubAgentDir},...e.shadowRulesDir==null?{}:{shadowRulesDir:e.shadowRulesDir},...e.globalMemoryFile==null?{}:{globalMemoryFile:e.globalMemoryFile},...e.shadowProjectsDir==null?{}:{shadowProjectsDir:e.shadowProjectsDir},...e.externalProjects==null?{}:{externalProjects:e.externalProjects},...e.excludePatterns==null?{}:{excludePatterns:e.excludePatterns},...e.fastCommandSeriesOptions==null?{}:{fastCommandSeriesOptions:e.fastCommandSeriesOptions},...e.logLevel==null?{}:{logLevel:e.logLevel}}}function _r(...e){return e.reduce((e,t)=>vr(e,t),{...hr})}function vr(e,t){let n=t.externalProjects,r=t.plugins,i=t.excludePatterns,a=t.fastCommandSeriesOptions;return{...e,...t,externalProjects:[...e.externalProjects,...n??[]],plugins:[...e.plugins,...r??[]],excludePatterns:yr(e.excludePatterns,i),fastCommandSeriesOptions:br(e.fastCommandSeriesOptions,a)}}function yr(e,t){let n={...e};if(t)for(let[e,r]of Object.entries(t))n[e]=[...n[e]??[],...r];return n}function br(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 xr(e){return`pluginOptions`in e||`configLoaderOptions`in e||`loadUserConfig`in e}async function Sr(e={}){pn().shouldExit&&u.default.exit(1);let t,n,r;xr(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=fn(n);a=e.found,o=e.sources,e.found&&(i=gr(e.config),s=e.config)}let c=_r(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:hr.workspaceDir,shadowSourceProjectDir:hr.shadowSourceProjectDir,shadowSkillSourceDir:hr.shadowSkillSourceDir,shadowFastCommandDir:hr.shadowFastCommandDir,shadowSubAgentDir:hr.shadowSubAgentDir,globalMemoryFile:hr.globalMemoryFile,shadowProjectsDir:hr.shadowProjectsDir,logLevel:hr.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 mr().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.externalProjects!=null&&{externalProjects:v.externalProjects},...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&&Mn(v.shadowSourceProjectDir,m),{context:y,outputPlugins:_,userConfigOptions:c}}const Cr=Mr(/[A-Za-z]/),wr=Mr(/[\dA-Za-z]/),Tr=Mr(/[#-'*+\--9=?A-Z^-~]/);function Er(e){return e!==null&&(e<32||e===127)}const Dr=Mr(/\d/),Or=Mr(/[\dA-Fa-f]/),kr=Mr(/[!-/:-@[-`{-~]/);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 Ar=Mr(/\p{P}|\p{S}/u),jr=Mr(/\s/);function Mr(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}var Nr=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 Pr=Object.assign(Fr(Error),{eval:Fr(EvalError),range:Fr(RangeError),reference:Fr(ReferenceError),syntax:Fr(SyntaxError),type:Fr(TypeError),uri:Fr(URIError)});function Fr(e){return t.displayName=e.displayName||e.name,t;function t(t,...n){return new e(t&&(0,Nr.default)(t,...n))}}const Ir={}.hasOwnProperty,Lr={yaml:`-`,toml:`+`};function Rr(e){let t=[],n=-1,r=Array.isArray(e)?e:e?[e]:[`yaml`];for(;++n<r.length;)t[n]=zr(r[n]);return t}function zr(e){let t=e;if(typeof t==`string`){if(!Ir.call(Lr,t))throw Pr("Missing matter definition for `%s`",t);t={type:t,marker:Lr[t]}}else if(typeof t!=`object`)throw Pr("Expected matter to be an object, not `%j`",t);if(!Ir.call(t,`type`))throw Pr("Missing `type` in matter `%j`",t);if(!Ir.call(t,`fence`)&&!Ir.call(t,`marker`))throw Pr("Missing `marker` or `fence` in matter `%j`",t);return t}function Br(e){let t=Rr(e),n={},r=-1;for(;++r<t.length;){let e=t[r],i=Hr(e,`open`).charCodeAt(0),a=Vr(e),o=n[i];Array.isArray(o)?o.push(a):n[i]=[a]}return{flow:n}}function Vr(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=Hr(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=Hr(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 Hr(e,t){return e.marker?Ur(e.marker,t).repeat(3):Ur(e.fence,t)}function Ur(e,t){return typeof e==`string`?e:e[t]}function Wr(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function Gr(e){let t=Rr(e),n={},r={},i=-1;for(;++i<t.length;){let e=t[i];n[e.type]=Kr(e),r[e.type]=qr,r[e.type+`Value`]=Jr}return{enter:n,exit:r}}function Kr(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 Jr(e){this.config.enter.data.call(this,e),this.config.exit.data.call(this,e)}function Yr(e){let t=[],n={},r=Rr(e),i=-1;for(;++i<r.length;){let e=r[i];n[e.type]=Xr(e);let a=Zr(e,`open`);t.push({atBreak:!0,character:a.charAt(0),after:Wr(a.charAt(1))})}return{unsafe:t,handlers:n}}function Xr(e){let t=Zr(e,`open`),n=Zr(e,`close`);return r;function r(e){return t+(e.value?`
|
|
1012
|
+
`.trim();var jn=class{name=`help`;async execute(e){return console.log(An),{success:!0,filesAffected:0,dirsAffected:0,message:`Help displayed`}}};function Mn(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 Nn(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 Pn(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=Nn(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 Fn(e,t,n){let r=e;return r=r.replace(R.SHADOW_SOURCE_PROJECT,n),r=r.replace(R.WORKSPACE,t),r.startsWith(`~`)&&(r=f.join(p.homedir(),r.slice(1))),f.normalize(r)}var In=class{name=`init`;async execute(e){let{logger:t,userConfigOptions:n}=e;t.info(`initializing shadow source project structure`,{command:`init`});let r=Fn(n.workspaceDir,``,``),i=Pn(Fn(n.shadowSourceProjectDir,r,``),{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}}},Ln=class{name;inner;constructor(e){this.inner=e,this.name=`json:${e.name}`}async execute(e){let t=await this.inner.execute(e),n=Rn(t);return u.default.stdout.write(`${JSON.stringify(n)}\n`),t}};function Rn(e){return{success:e.success,filesAffected:e.filesAffected,dirsAffected:e.dirsAffected,...e.message!=null&&{message:e.message},pluginResults:[],errors:[]}}function zn(){return`@truenine/memory-sync-cli`}function Bn(){return`https://registry.npmjs.org/${zn()}/latest`}function Vn(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 Hn(e,t){let n=Vn(e),r=Vn(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 Un=3e3;async function Wn(){let e=new AbortController,t=setTimeout(()=>e.abort(),Un);typeof t==`object`&&`unref`in t&&t.unref();try{let n=await fetch(Bn(),{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 ${Un}ms`}:{error:e.message}:{error:`Unknown network error`}}}function Gn(){return`2026.10218.11905`}async function Kn(){let e=Gn();if(e===`dev`)return{status:`development`,localVersion:e,remoteVersion:null};let t=await Wn();if(`error`in t)return{status:`current`,localVersion:e,remoteVersion:null,error:t.error};let n=t.version,r=Hn(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 qn(e,t){let{status:n,localVersion:r,remoteVersion:i}=e;switch(n){case`outdated`:t.warn(`Version outdated: ${r} → ${i}. Run 'npm i -g ${zn()}@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 Jn(){return new Date().getMinutes()%2==0}function Yn(e){Jn()&&Kn().then(t=>{(t.status===`outdated`||t.error!=null)&&qn(t,e)}).catch(t=>{let n=t instanceof Error?t.message:`Unknown error`;e.error(`Version check failed: ${n}`)})}var Xn=class{name=`outdated`;async execute(e){let t=await Kn();return qn(t,e.logger),{success:!0,filesAffected:0,dirsAffected:0,message:`Version status: ${t.status}`}}},Zn=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)`}}},Qn=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 $n={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 er=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}({}),tr=function(e){return e.Win=`win`,e.Mac=`mac`,e.Linux=`linux`,e.Unknown=`unknown`,e}({});var nr=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 tr.Win;case`darwin`:return tr.Mac;case`linux`:case`freebsd`:case`openbsd`:case`sunos`:case`aix`:return tr.Linux;default:return tr.Unknown}}detectShellKind(){let e=(u.default.env.SHELL??u.default.env.ComSpec??``).toLowerCase();return e.includes(`bash`)?er.Bash:e.includes(`zsh`)?er.Zsh:e.includes(`fish`)?er.Fish:e.includes(`pwsh`)?er.Pwsh:e.includes(`powershell`)?er.PowerShell:e.includes(`cmd`)?er.Cmd:e.endsWith(`/sh`)?er.Sh:er.Unknown}collectEnvContext(){return{...u.default.env}}collectProfile(){return this.userConfig?.profile==null?{}:this.userConfig.profile}collectToolReferences(){let e={...$n.default};return this.toolPreset===`claudeCode`?{...e,...$n.claudeCode}:this.toolPreset===`kiro`?{...e,...$n.kiro}:e}createMdComponent(){let e=(e=>e.when===!1?null:e.children);return e.Line=e=>e.when===!1?null:e.children,e}};let rr=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 ir=class{registrations=[];globalScope=null;setGlobalScope(e){this.globalScope=e}getGlobalScope(){return this.globalScope}register(e,t,n=rr.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 ar(e){let t=[...e],n=t[0];n!=null&&or(n)&&t.shift();let r=t[0];return r!=null&&sr(r)&&t.shift(),t}function or(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 sr(e){return/\.(?:m?[jt]s|cjs)$/.test(e)||/[/\\]/.test(e)&&!e.startsWith(`-`)?!0:/^(?:@[\w-]+\/)?[\w-]+$/.test(e)&&!e.startsWith(`-`)}const cr=new Set([`help`,`version`,`outdated`,`init`,`dry-run`,`clean`,`config`,`plugins`]),lr=new Map([[`--trace`,`trace`],[`--debug`,`debug`],[`--info`,`info`],[`--warn`,`warn`],[`--error`,`error`]]),ur=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4]]);function dr(e){let{logLevelFlags:t}=e;if(t.length===0)return;let n=t[0],r=ur.get(n)??4;for(let e of t){let t=ur.get(e)??4;t<r&&(r=t,n=e)}return n}function fr(e){let{helpFlag:t,versionFlag:n,subcommand:r,dryRun:i,unknownCommand:a,setOption:o,positional:s,showFlag:c}=e;if(n)return new On;if(t)return new jn;if(a!=null)return new Qn(a);if(r===`version`)return new On;if(r===`help`)return new jn;if(r===`outdated`)return new Xn;if(r===`init`)return new In;if(r===`dry-run`)return new Tn;if(r===`clean`)return i?new wn:new yt;if(r===`plugins`)return new Zn;if(r===`config`&&c)return new Cn;if(r!==`config`||o.length>0)return new En;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 Sn([...o,...l])}function pr(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=lr.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,cr.has(i)?t.subcommand=i:t.unknownCommand=i;continue}t.positional.push(i)}}return t}var mr=class{logger;args;outputPlugins=[];constructor(...e){this.args=pr(ar(e.filter(e=>e!=null)));let t=dr(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){Yn(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 Ln(i)));let a=this.createCommandContext(t,r);await i.execute(a)}resolveCommand(){return fr(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 nr({userConfig:r}).collect(),o=new ir;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,rr.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.externalProjects==null?e.externalProjects:[...e.externalProjects??[],...t.externalProjects],i=t.ideConfigFiles==null?e.ideConfigFiles:[...e.ideConfigFiles??[],...t.ideConfigFiles],a=t.fastCommands==null?e.fastCommands:[...e.fastCommands??[],...t.fastCommands],o=t.subAgents==null?e.subAgents:[...e.subAgents??[],...t.subAgents],s=t.skills==null?e.skills:[...e.skills??[],...t.skills],c=t.rules==null?e.rules:[...e.rules??[],...t.rules],l=t.aiAgentIgnoreConfigFiles==null?e.aiAgentIgnoreConfigFiles:[...e.aiAgentIgnoreConfigFiles??[],...t.aiAgentIgnoreConfigFiles],u=t.globalMemory??e.globalMemory,d=t.shadowSourceProjectDir??e.shadowSourceProjectDir,f=t.readmePrompts==null?e.readmePrompts:[...e.readmePrompts??[],...t.readmePrompts],p=t.globalGitIgnore??e.globalGitIgnore,m=t.shadowGitExclude??e.shadowGitExclude;return{...n==null?{}:{workspace:n},...r==null?{}:{externalProjects:r},...i==null?{}:{ideConfigFiles:i},...a==null?{}:{fastCommands:a},...o==null?{}:{subAgents:o},...s==null?{}:{skills:s},...c==null?{}:{rules:c},...l==null?{}:{aiAgentIgnoreConfigFiles:l},...u==null?{}:{globalMemory:u},...d==null?{}:{shadowSourceProjectDir:d},...f==null?{}:{readmePrompts:f},...p==null?{}:{globalGitIgnore:p},...m==null?{}:{shadowGitExclude:m}}}};const hr={...Wt,externalProjects:[],excludePatterns:{},fastCommandSeriesOptions:{},plugins:[]};function gr(e){return{...e.workspaceDir==null?{}:{workspaceDir:e.workspaceDir},...e.shadowSourceProjectDir==null?{}:{shadowSourceProjectDir:e.shadowSourceProjectDir},...e.shadowSkillSourceDir==null?{}:{shadowSkillSourceDir:e.shadowSkillSourceDir},...e.shadowFastCommandDir==null?{}:{shadowFastCommandDir:e.shadowFastCommandDir},...e.shadowSubAgentDir==null?{}:{shadowSubAgentDir:e.shadowSubAgentDir},...e.shadowRulesDir==null?{}:{shadowRulesDir:e.shadowRulesDir},...e.globalMemoryFile==null?{}:{globalMemoryFile:e.globalMemoryFile},...e.shadowProjectsDir==null?{}:{shadowProjectsDir:e.shadowProjectsDir},...e.externalProjects==null?{}:{externalProjects:e.externalProjects},...e.excludePatterns==null?{}:{excludePatterns:e.excludePatterns},...e.fastCommandSeriesOptions==null?{}:{fastCommandSeriesOptions:e.fastCommandSeriesOptions},...e.logLevel==null?{}:{logLevel:e.logLevel}}}function _r(...e){return e.reduce((e,t)=>vr(e,t),{...hr})}function vr(e,t){let n=t.externalProjects,r=t.plugins,i=t.excludePatterns,a=t.fastCommandSeriesOptions;return{...e,...t,externalProjects:[...e.externalProjects,...n??[]],plugins:[...e.plugins,...r??[]],excludePatterns:yr(e.excludePatterns,i),fastCommandSeriesOptions:br(e.fastCommandSeriesOptions,a)}}function yr(e,t){let n={...e};if(t)for(let[e,r]of Object.entries(t))n[e]=[...n[e]??[],...r];return n}function br(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 xr(e){return`pluginOptions`in e||`configLoaderOptions`in e||`loadUserConfig`in e}async function Sr(e={}){pn().shouldExit&&u.default.exit(1);let t,n,r;xr(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=fn(n);a=e.found,o=e.sources,e.found&&(i=gr(e.config),s=e.config)}let c=_r(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:hr.workspaceDir,shadowSourceProjectDir:hr.shadowSourceProjectDir,shadowSkillSourceDir:hr.shadowSkillSourceDir,shadowFastCommandDir:hr.shadowFastCommandDir,shadowSubAgentDir:hr.shadowSubAgentDir,globalMemoryFile:hr.globalMemoryFile,shadowProjectsDir:hr.shadowProjectsDir,logLevel:hr.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 mr().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.externalProjects!=null&&{externalProjects:v.externalProjects},...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&&Mn(v.shadowSourceProjectDir,m),{context:y,outputPlugins:_,userConfigOptions:c}}const Cr=Mr(/[A-Za-z]/),wr=Mr(/[\dA-Za-z]/),Tr=Mr(/[#-'*+\--9=?A-Z^-~]/);function Er(e){return e!==null&&(e<32||e===127)}const Dr=Mr(/\d/),Or=Mr(/[\dA-Fa-f]/),kr=Mr(/[!-/:-@[-`{-~]/);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 Ar=Mr(/\p{P}|\p{S}/u),jr=Mr(/\s/);function Mr(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}var Nr=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 Pr=Object.assign(Fr(Error),{eval:Fr(EvalError),range:Fr(RangeError),reference:Fr(ReferenceError),syntax:Fr(SyntaxError),type:Fr(TypeError),uri:Fr(URIError)});function Fr(e){return t.displayName=e.displayName||e.name,t;function t(t,...n){return new e(t&&(0,Nr.default)(t,...n))}}const Ir={}.hasOwnProperty,Lr={yaml:`-`,toml:`+`};function Rr(e){let t=[],n=-1,r=Array.isArray(e)?e:e?[e]:[`yaml`];for(;++n<r.length;)t[n]=zr(r[n]);return t}function zr(e){let t=e;if(typeof t==`string`){if(!Ir.call(Lr,t))throw Pr("Missing matter definition for `%s`",t);t={type:t,marker:Lr[t]}}else if(typeof t!=`object`)throw Pr("Expected matter to be an object, not `%j`",t);if(!Ir.call(t,`type`))throw Pr("Missing `type` in matter `%j`",t);if(!Ir.call(t,`fence`)&&!Ir.call(t,`marker`))throw Pr("Missing `marker` or `fence` in matter `%j`",t);return t}function Br(e){let t=Rr(e),n={},r=-1;for(;++r<t.length;){let e=t[r],i=Hr(e,`open`).charCodeAt(0),a=Vr(e),o=n[i];Array.isArray(o)?o.push(a):n[i]=[a]}return{flow:n}}function Vr(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=Hr(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=Hr(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 Hr(e,t){return e.marker?Ur(e.marker,t).repeat(3):Ur(e.fence,t)}function Ur(e,t){return typeof e==`string`?e:e[t]}function Wr(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function Gr(e){let t=Rr(e),n={},r={},i=-1;for(;++i<t.length;){let e=t[i];n[e.type]=Kr(e),r[e.type]=qr,r[e.type+`Value`]=Jr}return{enter:n,exit:r}}function Kr(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 Jr(e){this.config.enter.data.call(this,e),this.config.exit.data.call(this,e)}function Yr(e){let t=[],n={},r=Rr(e),i=-1;for(;++i<r.length;){let e=r[i];n[e.type]=Xr(e);let a=Zr(e,`open`);t.push({atBreak:!0,character:a.charAt(0),after:Wr(a.charAt(1))})}return{unsafe:t,handlers:n}}function Xr(e){let t=Zr(e,`open`),n=Zr(e,`close`);return r;function r(e){return t+(e.value?`
|
|
1013
1013
|
`+e.value:``)+`
|
|
1014
1014
|
`+n}}function Zr(e,t){return e.marker?Qr(e.marker,t).repeat(3):Qr(e.fence,t)}function Qr(e,t){return typeof e==`string`?e:e[t]}function $r(e){let t=this,n=e||`yaml`,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(Br(n)),a.push(Gr(n)),o.push(Yr(n))}function ei(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 ti=(function(e){if(e==null)return oi;if(typeof e==`function`)return ai(e);if(typeof e==`object`)return Array.isArray(e)?ni(e):ri(e);if(typeof e==`string`)return ii(e);throw Error(`Expected function, string, or object as test`)});function ni(e){let t=[],n=-1;for(;++n<e.length;)t[n]=ti(e[n]);return ai(r);function r(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}function ri(e){let t=e;return ai(n);function n(n){let r=n,i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function ii(e){return ai(t);function t(t){return t&&t.type===e}}function ai(e){return t;function t(t,n,r){return!!(si(t)&&e.call(this,t,typeof n==`number`?n:void 0,r||void 0))}}function oi(){return!0}function si(e){return typeof e==`object`&&!!e&&`type`in e}function ci(e){return`\x1B[33m`+e+`\x1B[39m`}const li=[];function ui(e,t,n,r){let i;typeof t==`function`&&typeof n!=`function`?(r=n,n=t):i=t;let a=ti(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 (`+ci(e.type+(t?`<`+t+`>`:``))+`)`})}return u;function u(){let l=li,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=di(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 di(e){return Array.isArray(e)?e:typeof e==`number`?[!0,e]:e==null?li:[e]}function fi(e,t,n){let r=ti((n||{}).ignore||[]),i=pi(t),a=-1;for(;++a<i.length;)ui(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 pi(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([mi(e[0]),hi(e[1])])}return t}function mi(e){return typeof e==`string`?new RegExp(Wr(e),`g`):e}function hi(e){return typeof e==`function`?e:function(){return e}}const gi=`phrasing`,_i=[`autolink`,`link`,`image`,`label`];function vi(){return{transforms:[Ei],enter:{literalAutolink:bi,literalAutolinkEmail:xi,literalAutolinkHttp:xi,literalAutolinkWww:xi},exit:{literalAutolink:Ti,literalAutolinkEmail:wi,literalAutolinkHttp:Si,literalAutolinkWww:Ci}}}function yi(){return{unsafe:[{character:`@`,before:`[+\\-.\\w]`,after:`[\\-.\\w]`,inConstruct:gi,notInConstruct:_i},{character:`.`,before:`[Ww]`,after:`[\\-.\\w]`,inConstruct:gi,notInConstruct:_i},{character:`:`,before:`[ps]`,after:`\\/`,inConstruct:gi,notInConstruct:_i}]}}function bi(e){this.enter({type:`link`,title:null,url:``,children:[]},e)}function xi(e){this.config.enter.autolinkProtocol.call(this,e)}function Si(e){this.config.exit.autolinkProtocol.call(this,e)}function Ci(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 wi(e){this.config.exit.autolinkEmail.call(this,e)}function Ti(e){this.exit(e)}function Ei(e){fi(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Di],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,Oi]],{ignore:[`link`,`linkReference`]})}function Di(e,t,n,r,i){let a=``;if(!ji(i)||(/^w/i.test(t)&&(n=t+n,t=``,a=`http://`),!ki(n)))return!1;let o=Ai(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 Oi(e,t,n,r){return!ji(r,!0)||/[-\d_]$/.test(n)?!1:{type:`link`,title:null,url:`mailto:`+t+`@`+n,children:[{type:`text`,value:t+`@`+n}]}}function ki(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 Ai(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=ei(e,`(`),a=ei(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 ji(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||jr(n)||Ar(n))&&(!t||n!==47)}function Mi(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}Hi.peek=Vi;function Ni(){this.buffer()}function Pi(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function Fi(){this.buffer()}function Ii(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function Li(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Mi(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Ri(e){this.exit(e)}function zi(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Mi(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Bi(e){this.exit(e)}function Vi(){return`[`}function Hi(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 Ui(){return{enter:{gfmFootnoteCallString:Ni,gfmFootnoteCall:Pi,gfmFootnoteDefinitionLabelString:Fi,gfmFootnoteDefinition:Ii},exit:{gfmFootnoteCallString:Li,gfmFootnoteCall:Ri,gfmFootnoteDefinitionLabelString:zi,gfmFootnoteDefinition:Bi}}}function Wi(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Hi},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?`
|
|
1015
1015
|
`:` `)+r.indentLines(r.containerFlow(e,a.current()),t?Ki:Gi))),s(),o}}function Gi(e,t,n){return t===0?e:Ki(e,t,n)}function Ki(e,t,n){return(n?``:` `)+e}const qi=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`];Qi.peek=$i;function Ji(){return{canContainEols:[`delete`],enter:{strikethrough:Xi},exit:{strikethrough:Zi}}}function Yi(){return{unsafe:[{character:`~`,inConstruct:`phrasing`,notInConstruct:qi}],handlers:{delete:Qi}}}function Xi(e){this.enter({type:`delete`,children:[]},e)}function Zi(e){this.exit(e)}function Qi(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 $i(){return`~`}function ea(e){return e.length}function ta(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||ea,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=na(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]=ra(r[d]);else{let e=ra(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(`
|
|
@@ -1197,7 +1197,9 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
1197
1197
|
|
|
1198
1198
|
`,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 Ag=`AGENTS.md`;var jg=class extends kg{constructor(){super(`AgentsOutputPlugin`,{outputFileName:Ag})}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,Ag)),e.childMemoryPrompts!=null)for(let n of e.childMemoryPrompts)n.dir!=null&&this.isRelativePath(n.dir)&&t.push(this.createFileRelativePath(n.dir,Ag));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}}},Mg=class extends Og{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.shadowSourceProjectDir;return{workspaceDir:n,shadowProjectDir:this.resolvePath(r,n,``)}}resolvePath(e,t,n){let r=e;return r.startsWith(R.USER_HOME)&&(r=r.replace(R.USER_HOME,p.homedir())),r.includes(R.SHADOW_SOURCE_PROJECT)&&(r=r.replace(R.SHADOW_SOURCE_PROJECT,n)),r.includes(R.WORKSPACE)&&(r=r.replace(R.WORKSPACE,t)),f.normalize(r)}readAndParseMarkdown(e,t){return Eg(t.readFileSync(e,`utf8`))}};const Ng=[`.qoderignore`,`.cursorignore`,`.kiroignore`,`.warpindexignore`,`.aiignore`,`.codeignore`,`.traeignore`];var Pg=class extends Mg{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 Ng){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 Fg=`.agent`,Ig=`antigravity`,Lg=`skills`,Rg=`workflows`,zg=`mcp_config.json`,Bg=[Lg,Rg];var Vg=class extends kg{constructor(){super(`AntigravityOutputPlugin`,{globalConfigDir:Fg,outputFileName:``,dependsOn:[`GeminiCLIOutputPlugin`]}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=f.join(this.getAntigravityDir(),zg),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`,Ig)}async registerProjectOutputDirs(e){let{projects:t}=e.collectedInputContext.workspace,n=[];for(let e of t)if(e.dirFromWorkspacePath!=null)for(let t of Bg)n.push(this.createRelativePath(f.join(e.dirFromWorkspacePath.path,Fg,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,Lg,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(zg,r,()=>Ig)),n==null)return i;let a=this.getTransformOptionsFromContext(e),o=f.join(r,Rg);for(let e of n)i.push(this.createRelativePath(this.transformFastCommandName(e,a),o,()=>Rg));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,Rg);for(let i of t)r.push(await this.writeFastCommand(e,n,i))}if(n!=null){let t=f.join(i,Lg);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,zg),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}},Hg=class extends Error{constructor(e,t,n){super(e),this.expression=t,this.filePath=n,this.name=`ScopeError`}},Ug=class extends Hg{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`}},Wg=class extends Hg{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`}},Gg=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`}},Kg=Object.defineProperty,qg=(e,t)=>{let n={};for(var r in e)Kg(n,r,{get:e[r],enumerable:!0});return t||Kg(n,Symbol.toStringTag,{value:`Module`}),n};const Jg=new Map;function Yg(e,t){Jg.set(e,t)}function Xg(){return new Map(Jg)}function Zg(e){return Jg.has(e)}function Qg(e,t,n){let r=e.trim();return r===``?``:/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/i.test(r)?$g(r,t,n?.filePath):e_(r,t,n?.filePath)}function $g(e,t,n){let r=e.split(`.`),i=r[0];if(i==null||!(i in t))throw new Wg(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 Ug(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 Ug(i,e,n);a=o[i]}return t_(a)}function e_(e,t,n){let r=Object.keys(t),i=r.map(e=>t[e]);try{return t_(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 Wg(t[1],e,n)}let i=n==null?``:` (file: ${n})`;throw Error(`Failed to evaluate expression: "${e}"${i}\nCause: ${r}`)}}function t_(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 n_(e,t){return e===null?!1:t.components.has(e)||Zg(e)}async function r_(e){return async(t,n)=>(await e({type:`root`,children:t},n)).children}async function i_(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 r_(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 a_(e,t){let n=e.name?.toLowerCase();if(n==null)return null;switch(n){case`pre`:return c_(e,t);case`a`:return l_(e,t);case`strong`:case`b`:return u_(e,t);case`em`:case`i`:return d_(e,t);case`img`:return f_(e,t);case`blockquote`:return p_(e,t);default:return null}}function o_(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`?Qg(r.value.value,n.scope):r.value===null?``:null}function s_(e,t){let n=``;for(let r of e.children)r.type===`text`?n+=r.value:r.type===`mdxTextExpression`?n+=Qg(r.value,t.scope):(r.type===`mdxJsxFlowElement`||r.type===`mdxJsxTextElement`)&&(n+=s_(r,t));return n}function c_(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=o_(n,`className`,t)??``,i=/language-(\w+)/.exec(r)?.[1],a=s_(n,t);return[{type:`code`,lang:i??null,value:a.trim()}]}function l_(e,t){let n=o_(e,`href`,t);if(n==null||n===``)return null;let r=s_(e,t);return[{type:`paragraph`,children:[{type:`link`,url:n,title:o_(e,`title`,t)??null,children:[{type:`text`,value:r}]}]}]}function u_(e,t){let n={type:`strong`,children:[{type:`text`,value:s_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function d_(e,t){let n={type:`emphasis`,children:[{type:`text`,value:s_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function f_(e,t){let n=o_(e,`src`,t);if(n==null||n===``)return null;let r={type:`image`,url:n,alt:o_(e,`alt`,t)??``,title:o_(e,`title`,t)??null};return e.type,[{type:`paragraph`,children:[r]}]}function p_(e,t){return[{type:`blockquote`,children:[{type:`paragraph`,children:[{type:`text`,value:s_(e,t)}]}]}]}function m_(e){return e==null?!1:JSON.stringify(e).includes(`"JSX`)}async function h_(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`?g_(i.expression,t,n):[]}async function g_(e,t,n){return e.type===`JSXElement`?S_(e,t,n):e.type===`JSXFragment`?C_(e,t,n):e.type===`LogicalExpression`?__(e,t,n):e.type===`ConditionalExpression`?v_(e,t,n):e.type===`SequenceExpression`?y_(e,t,n):e.type===`ArrayExpression`?b_(e,t,n):M_(e,t)}async function __(e,t,n){let r=await x_(e.left,t,n);return e.operator===`&&`?A_(r)?g_(e.right,t,n):[]:e.operator===`||`?A_(r)?k_(e.left)?g_(e.left,t,n):j_(r):g_(e.right,t,n):e.operator===`??`?r==null?g_(e.right,t,n):k_(e.left)?g_(e.left,t,n):j_(r):[]}async function v_(e,t,n){return A_(await x_(e.test,t,n))?g_(e.consequent,t,n):g_(e.alternate,t,n)}async function y_(e,t,n){let r=[];for(let i of e.expressions){let e=await g_(i,t,n);r.push(...e)}return r}async function b_(e,t,n){let r=[];for(let i of e.elements)if(i!=null)if(i.type===`SpreadElement`){let e=await g_(i.argument,t,n);r.push(...e)}else{let e=await g_(i,t,n);r.push(...e)}return r}async function x_(e,t,n){if(k_(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 x_(e.argument,t,n);return e.operator===`!`?!A_(r):e.operator===`-`?-r:e.operator===`+`?+r:e.operator===`typeof`?typeof r:void 0}if(e.type===`BinaryExpression`){let r=await x_(e.left,t,n),i=await x_(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 x_(e.left,t,n);return e.operator===`&&`?A_(r)?x_(e.right,t,n):r:e.operator===`||`?A_(r)?r:x_(e.right,t,n):e.operator===`??`?r??x_(e.right,t,n):void 0}if(e.type===`MemberExpression`){let r=await x_(e.object,t,n);if(r==null)return;if(e.computed)return r[await x_(e.property,t,n)];let{name:i}=e.property;return r[i]}if(e.type===`ConditionalExpression`)return A_(await x_(e.test,t,n))?x_(e.consequent,t,n):x_(e.alternate,t,n);let r=O_(e);if(r!==``)try{let e=Qg(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 S_(e,t,n){let r=T_(e,t);if(r.name!=null&&n_(r.name,t)){let{processAst:e}=await Promise.resolve().then(()=>N_);return i_(r,t,e)}return a_(r,t)??(r.children.length>0?n(r.children,t):[])}async function C_(e,t,n){let r=[];for(let i of e.children){let e=await w_(i,t,n);r.push(...e)}return r}async function w_(e,t,n){if(e.type===`JSXElement`)return S_(e,t,n);if(e.type===`JSXFragment`)return C_(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`?[]:g_(e.expression,t,n):e.type===`JSXSpreadChild`?g_(e.expression,t,n):[]}function T_(e,t){let n=e.openingElement,r=null;n.name.type===`JSXIdentifier`?{name:r}=n.name:n.name.type===`JSXMemberExpression`?r=E_(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:O_(e.value.expression)}),i.push({type:`mdxJsxAttribute`,name:t,value:n})}else e.type===`JSXSpreadAttribute`&&i.push({type:`mdxJsxExpressionAttribute`,value:`...${O_(e.argument)}`});let a=[];for(let n of e.children){let e=D_(n,t);e!=null&&a.push(...e)}return{type:`mdxJsxFlowElement`,name:r,attributes:i,children:a}}function E_(e){return e.object.type===`JSXIdentifier`?`${e.object.name}.${e.property.name}`:`${E_(e.object)}.${e.property.name}`}function D_(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[T_(e,t)];if(e.type===`JSXFragment`){let n=[];for(let r of e.children){let e=D_(r,t);e!=null&&n.push(...e)}return n}return e.type===`JSXExpressionContainer`?e.expression.type===`JSXEmptyExpression`?null:[{type:`paragraph`,children:[{type:`text`,value:O_(e.expression)}]}]:e.type===`JSXSpreadChild`?[{type:`paragraph`,children:[{type:`text`,value:`...${O_(e.expression)}`}]}]:null}function O_(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=O_(e.object);return e.computed?`${t}[${O_(e.property)}]`:`${t}.${e.property.name}`}if(e.type===`CallExpression`)return`${O_(e.callee)}(${e.arguments.map(e=>O_(e)).join(`, `)})`;if(e.type===`BinaryExpression`||e.type===`LogicalExpression`){let t=O_(e.left),n=O_(e.right);return`(${t} ${e.operator} ${n})`}if(e.type===`UnaryExpression`){let t=O_(e.argument);return`${e.operator}${t}`}if(e.type===`ConditionalExpression`)return`(${O_(e.test)} ? ${O_(e.consequent)} : ${O_(e.alternate)})`;if(e.type===`ArrayExpression`)return`[${e.elements.filter(e=>e!=null&&e.type!==`SpreadElement`).map(e=>O_(e)).join(`, `)}]`;if(e.type===`ObjectExpression`)return`{${e.properties.filter(e=>e.type===`Property`).map(e=>`${e.key.type===`Identifier`?e.key.name:O_(e.key)}: ${O_(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+=`\${${O_(e.expressions[n])}}`);return t+="`",t}return e.type===`SpreadElement`?`...${O_(e.argument)}`:``}function k_(e){return e.type===`JSXElement`||e.type===`JSXFragment`}function A_(e){return!!e}function j_(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 M_(e,t){let n=O_(e);if(n===``)return[];try{return j_(Qg(n,t.scope))}catch{return[]}}var N_=qg({processAst:()=>F_});function P_(e){if(!(e.includes(`/`)&&/\.\w+$/.test(e)))return e;let t=e.lastIndexOf(`/`);return e.slice(t+1)}async function F_(e,t){return I_(e,t)}async function I_(e,t){let n=[];for(let r of e.children){let e=await L_(r,t);n.push(...e)}return{type:`root`,children:n}}async function L_(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(m_(r))return h_(n,t,async(e,t)=>(await F_({type:`root`,children:e},t)).children);let a=Qg(n.value,t.scope);return a===``?[]:[{type:`paragraph`,children:[{type:`text`,value:a}]}]}if(e.type===`mdxJsxFlowElement`)return R_(e,t);if(e.type===`link`){let n=e,r=(await z_(n.children,t)).map(e=>e.type===`text`?{...e,value:P_(e.value)}:e);return[{...n,children:r}]}if(!(`children`in e&&Array.isArray(e.children)))return[e];let n=await z_(e.children,t);return[{...e,children:n}]}async function R_(e,t){return e.name!=null&&n_(e.name,t)?i_(e,t,F_):a_(e,t)??[]}async function z_(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(m_(i)){let r=await h_(e,t,async(e,t)=>(await F_({type:`root`,children:e},t)).children);for(let e of r)n.push(e);continue}let o=Qg(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:Qg(e.value,t.scope)};n.push(a);continue}if(r.type===`mdxJsxTextElement`){let e=r;if(e.name!=null&&n_(e.name,t)){let r=await i_(e,t,F_);for(let e of r)e.type===`paragraph`&&`children`in e?n.push(...e.children):n.push(e);continue}let i=a_(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 z_(r.children,t);if(r.type===`link`){let t=e.map(e=>e.type===`text`?{...e,value:P_(e.value)}:e);n.push({...r,children:t});continue}n.push({...r,children:e});continue}n.push(r)}return n}function B_(e){let t=this;t.compiler=n;function n(n){return Fo(n,{...t.data(`settings`),...e,extensions:t.data(`toMarkdownExtensions`)||[]})}}function V_(e,t={}){let n={},{yamlFrontMatter:r,scope:i,filePath:a}=t;for(let t of e){let e=H_(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 H_(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=U_(i,e);if(o!=null)try{let e=W_(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=U_(i,s.index+s[0].length);if(a==null){s=o.exec(i);continue}try{let i=W_(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 U_(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===`
|
|
1199
1199
|
`){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 W_(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 G_(r.slice(1,-1),`"`);if(r.startsWith(`'`)&&r.endsWith(`'`))return G_(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 G_(e,"`")}if(r.startsWith(`[`)&&r.endsWith(`]`))return q_(r,t,n);if(r.startsWith(`{`)&&r.endsWith(`}`))return J_(r,t,n);if(/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/i.test(r))return K_(r,t,n);let i=n==null?``:` in file "${n}"`;throw Error(`Expression "${r}" cannot be statically evaluated${i}`)}function G_(e,t){return e.replaceAll(`\\n`,`
|
|
1200
|
-
`).replaceAll(`\\r`,`\r`).replaceAll(`\\t`,` `).replaceAll(`\\"`,`"`).replaceAll(`\\'`,`'`).replaceAll(`\\\\`,`\\`)}function K_(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=Y_(e),n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return X_(r).map(e=>W_(e.trim(),t,n))}function J_(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return{};if(t==null)try{let t=Y_(e),n=JSON.parse(t);if(typeof n==`object`&&n&&!Array.isArray(n))return n}catch{}let i={},a=Z_(r);for(let e of a){let r=Q_(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]=W_(o,t,n)}return i}function Y_(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 X_(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 Z_(e){return X_(e)}function Q_(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 $_(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=Qg(n.value.value,t.scope);return e===`true`||e===`1`}catch{return!1}return!1}async function ev(e,t,n){return!$_(e,t)||e.children.length===0?[]:n(e.children,t)}async function tv(e,t){if(!$_(e,t)||e.children.length===0)return[];let n=nv(e.children,t);return n===``?[]:[{type:`text`,value:n}]}function nv(e,t){let n=``;for(let r of e)if(r.type===`text`)n+=r.value;else if(r.type===`mdxTextExpression`)try{n+=Qg(r.value,t.scope)}catch{}else `children`in r&&Array.isArray(r.children)&&(n+=nv(r.children,t));return n}function rv(){Yg(`Md`,ev),Yg(`Md.Line`,tv)}rv();function iv(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 av(e,t){let n=oh(e),r=iv(t?.globalScope,t?.scope),i=Xg(),a;if(t?.extractMetadata===!0){let e=n.children.find(e=>e.type===`yaml`),i;if(e!=null)try{i=Cg.parse(e.value)}catch{}a=V_(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 F_(n,{scope:r,components:i,processingStack:[],...t?.basePath!=null&&{basePath:t.basePath}}),s=cu().use($r,[`yaml`]).use(Hl).use(B_,{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 ov=class extends kg{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 nr({toolPreset:this.toolPreset}).collect(),t=await av(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`)]}},sv=class extends ov{constructor(){super(`ClaudeCodeCLIOutputPlugin`,{globalConfigDir:`.claude`,outputFileName:`CLAUDE.md`,toolPreset:`claudeCode`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0})}};const cv=`AGENTS.md`,lv=`.codex`,uv=`prompts`,dv=`skills`;var fv=class extends kg{constructor(){super(`CodexCLIOutputPlugin`,{globalConfigDir:lv,outputFileName:cv,dependsOn:[`AgentsOutputPlugin`]})}async registerProjectOutputDirs(){return[]}async registerProjectOutputFiles(){return[]}async registerGlobalOutputDirs(e){let t=this.getGlobalConfigDir(),n=[this.createRelativePath(uv,t,()=>uv)],{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(dv,r),t,()=>r))}return n}async registerGlobalOutputFiles(){let e=this.getGlobalConfigDir();return[this.createRelativePath(cv,e,()=>lv)]}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,cv),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,uv,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,dv,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(` `)),Tg(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 pv=`.cursor`,mv=`mcp.json`,hv=`commands`,gv=`rules`,_v=`global.mdc`,vv=`skills-cursor`,yv=`SKILL.md`,bv=new Set([`create-rule`,`create-skill`,`create-subagent`,`migrate-to-skills`,`update-cursor-settings`]);var xv=class extends kg{constructor(){super(`CursorOutputPlugin`,{globalConfigDir:pv,outputFileName:``,dependsOn:[`AgentsOutputPlugin`],indexignore:`.cursorignore`}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=this.getGlobalConfigDir(),n=f.join(t,mv),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:hv,basePath:n,getDirectoryName:()=>hv,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,vv,r);t.push({pathKind:L.Relative,path:f.join(vv,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,gv);return t.push({pathKind:L.Relative,path:gv,basePath:n,getDirectoryName:()=>gv,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,mv);t.push({pathKind:L.Relative,path:mv,basePath:n,getDirectoryName:()=>pv,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(hv,i),basePath:n,getDirectoryName:()=>hv,getAbsolutePath:()=>o})}}let a=e.collectedInputContext.rules?.filter(e=>e.scope===`global`);if(a!=null&&a.length>0){let e=f.join(n,gv);for(let r of a){let i=this.buildRuleFileName(r),a=f.join(e,i);t.push({pathKind:L.Relative,path:f.join(gv,i),basePath:n,getDirectoryName:()=>gv,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(vv,r,yv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,yv)}),e.mcpConfig!=null&&t.push({pathKind:L.Relative,path:f.join(vv,r,mv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,mv)}),e.childDocs!=null)for(let a of e.childDocs){let e=a.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:f.join(vv,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(vv,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,_v))}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(),gv);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,pv,gv);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,pv,gv);return{pathKind:L.Relative,path:t,basePath:e.basePath,getDirectoryName:()=>gv,getAbsolutePath:()=>f.join(e.basePath,t)}}createProjectRuleFileRelativePath(e,t){let n=f.join(e.path,pv,gv,t);return{pathKind:L.Relative,path:n,basePath:e.basePath,getDirectoryName:()=>gv,getAbsolutePath:()=>f.join(e.basePath,n)}}buildGlobalRuleContent(e){return Tg({description:`Global prompt (synced)`,alwaysApply:!0},e)}async writeProjectGlobalRule(e,t,n){let r=t.dirFromWorkspacePath,i=f.join(r.basePath,r.path,pv,gv),a=f.join(i,_v),o=this.createProjectRuleFileRelativePath(r,_v);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 bv.has(e)}getSkillsCursorDir(){return f.join(this.getGlobalConfigDir(),vv)}getGlobalCommandsDir(){return f.join(this.getGlobalConfigDir(),hv)}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(hv,i),basePath:this.getGlobalConfigDir(),getDirectoryName:()=>hv,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,mv),a={pathKind:L.Relative,path:mv,basePath:r,getDirectoryName:()=>pv,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,yv),s=this.getGlobalConfigDir(),c={pathKind:L.Relative,path:f.join(vv,i,yv),basePath:s,getDirectoryName:()=>i,getAbsolutePath:()=>o},l=this.buildSkillFrontMatter(n),u=n.content,d=Tg(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,mv),o={pathKind:L.Relative,path:f.join(vv,i,mv),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(vv,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(vv,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 Tg({alwaysApply:!1,globs:e.globs.length>0?e.globs.join(`, `):``},e.content)}async writeRuleMdcFile(e,t,n,r){let i=this.buildRuleFileName(n),a=f.join(t,i),o={pathKind:L.Relative,path:f.join(pv,gv,i),basePath:r,getDirectoryName:()=>gv,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}}}},Sv=class extends ov{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}},Cv=class extends Mg{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=Eg(o),i=await av(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 Gg([...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)}},wv=class extends Cv{constructor(){super(`FastCommandInputPlugin`,{configKey:`shadowFastCommandDir`})}getTargetDir(e,t){let n=e.shadowFastCommandDir,{workspaceDir:r,shadowProjectDir:i}=t;return this.resolvePath(n,r,i)}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=Eg(s),l=await av(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 Gg([...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}}},Tv=class extends ov{constructor(){super(`GeminiCLIOutputPlugin`,{globalConfigDir:`.gemini`,outputFileName:`GEMINI.md`,supportsFastCommands:!1,supportsSubAgents:!1,supportsSkills:!1})}};const Ev=`.skills`,Dv=`.aindex/.skills`,Ov=`SKILL.md`,kv=`mcp.json`;var Av=class extends kg{constructor(){super(`GenericSkillsOutputPlugin`,{globalConfigDir:Dv,outputFileName:Ov}),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,Ov);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(),Dv)}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,Ev);t.push({pathKind:L.Relative,path:n,basePath:e.dirFromWorkspacePath.basePath,getDirectoryName:()=>Ev,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,Ev);for(let i of r){let r=i.yamlFrontMatter.name,a=this.joinPath(n,r);t.push({pathKind:L.Relative,path:this.joinPath(Ev,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:Dv,basePath:this.getHomeDir(),getDirectoryName:()=>Dv,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(Dv,n,Ov),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,Ov)}),e.mcpConfig!=null&&t.push({pathKind:L.Relative,path:this.joinPath(Dv,n,kv),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,kv)}),e.childDocs!=null)for(let r of e.childDocs){let e=r.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:this.joinPath(Dv,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(Dv,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,Ev);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(Ev,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,Ov),s={pathKind:L.Relative,path:Ov,basePath:a,getDirectoryName:()=>i,getAbsolutePath:()=>o},c=this.buildSkillFrontMatter(t),l=t.content,u=Tg(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,kv),a={pathKind:L.Relative,path:kv,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}}}},jv=class extends Mg{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)})}},Mv=class extends jv{constructor(){super(`GitExcludeInputPlugin`)}getFilePath(e){return f.join(e,`public`,`exclude`)}getResultKey(){return`shadowGitExclude`}};function Nv(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 Pv(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 Fv(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 Iv=class extends kg{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,...Pv(r)];for(let e of a){let n=Nv(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 Fv(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 Nv(t)==null?Pv(t).some(e=>Nv(e)!=null):!0}),a=e.collectedInputContext.workspace.directory.path,o=Nv(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,...Pv(r)];for(let o of a){let a=Nv(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=Nv(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=Pv(c);for(let n of u){let r=Nv(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 Fv(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(`
|
|
1200
|
+
`).replaceAll(`\\r`,`\r`).replaceAll(`\\t`,` `).replaceAll(`\\"`,`"`).replaceAll(`\\'`,`'`).replaceAll(`\\\\`,`\\`)}function K_(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=Y_(e),n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return X_(r).map(e=>W_(e.trim(),t,n))}function J_(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return{};if(t==null)try{let t=Y_(e),n=JSON.parse(t);if(typeof n==`object`&&n&&!Array.isArray(n))return n}catch{}let i={},a=Z_(r);for(let e of a){let r=Q_(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]=W_(o,t,n)}return i}function Y_(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 X_(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 Z_(e){return X_(e)}function Q_(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 $_(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=Qg(n.value.value,t.scope);return e===`true`||e===`1`}catch{return!1}return!1}async function ev(e,t,n){return!$_(e,t)||e.children.length===0?[]:n(e.children,t)}async function tv(e,t){if(!$_(e,t)||e.children.length===0)return[];let n=nv(e.children,t);return n===``?[]:[{type:`text`,value:n}]}function nv(e,t){let n=``;for(let r of e)if(r.type===`text`)n+=r.value;else if(r.type===`mdxTextExpression`)try{n+=Qg(r.value,t.scope)}catch{}else `children`in r&&Array.isArray(r.children)&&(n+=nv(r.children,t));return n}function rv(){Yg(`Md`,ev),Yg(`Md.Line`,tv)}rv();function iv(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 av(e,t){let n=oh(e),r=iv(t?.globalScope,t?.scope),i=Xg(),a;if(t?.extractMetadata===!0){let e=n.children.find(e=>e.type===`yaml`),i;if(e!=null)try{i=Cg.parse(e.value)}catch{}a=V_(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 F_(n,{scope:r,components:i,processingStack:[],...t?.basePath!=null&&{basePath:t.basePath}}),s=cu().use($r,[`yaml`]).use(Hl).use(B_,{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 ov=class extends kg{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 nr({toolPreset:this.toolPreset}).collect(),t=await av(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`)]}},sv=class extends ov{constructor(){super(`ClaudeCodeCLIOutputPlugin`,{globalConfigDir:`.claude`,outputFileName:`CLAUDE.md`,toolPreset:`claudeCode`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0})}};const cv=`AGENTS.md`,lv=`.codex`,uv=`prompts`,dv=`skills`;var fv=class extends kg{constructor(){super(`CodexCLIOutputPlugin`,{globalConfigDir:lv,outputFileName:cv,dependsOn:[`AgentsOutputPlugin`]})}async registerProjectOutputDirs(){return[]}async registerProjectOutputFiles(){return[]}async registerGlobalOutputDirs(e){let t=this.getGlobalConfigDir(),n=[this.createRelativePath(uv,t,()=>uv)],{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(dv,r),t,()=>r))}return n}async registerGlobalOutputFiles(){let e=this.getGlobalConfigDir();return[this.createRelativePath(cv,e,()=>lv)]}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,cv),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,uv,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,dv,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(` `)),Tg(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 pv=`.cursor`,mv=`mcp.json`,hv=`commands`,gv=`rules`,_v=`global.mdc`,vv=`skills-cursor`,yv=`SKILL.md`,bv=new Set([`create-rule`,`create-skill`,`create-subagent`,`migrate-to-skills`,`update-cursor-settings`]);var xv=class extends kg{constructor(){super(`CursorOutputPlugin`,{globalConfigDir:pv,outputFileName:``,dependsOn:[`AgentsOutputPlugin`],indexignore:`.cursorignore`}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=this.getGlobalConfigDir(),n=f.join(t,mv),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:hv,basePath:n,getDirectoryName:()=>hv,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,vv,r);t.push({pathKind:L.Relative,path:f.join(vv,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,gv);return t.push({pathKind:L.Relative,path:gv,basePath:n,getDirectoryName:()=>gv,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,mv);t.push({pathKind:L.Relative,path:mv,basePath:n,getDirectoryName:()=>pv,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(hv,i),basePath:n,getDirectoryName:()=>hv,getAbsolutePath:()=>o})}}let a=e.collectedInputContext.rules?.filter(e=>e.scope===`global`);if(a!=null&&a.length>0){let e=f.join(n,gv);for(let r of a){let i=this.buildRuleFileName(r),a=f.join(e,i);t.push({pathKind:L.Relative,path:f.join(gv,i),basePath:n,getDirectoryName:()=>gv,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(vv,r,yv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,yv)}),e.mcpConfig!=null&&t.push({pathKind:L.Relative,path:f.join(vv,r,mv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>f.join(i,mv)}),e.childDocs!=null)for(let a of e.childDocs){let e=a.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:f.join(vv,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(vv,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,_v))}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(),gv);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,pv,gv);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,pv,gv);return{pathKind:L.Relative,path:t,basePath:e.basePath,getDirectoryName:()=>gv,getAbsolutePath:()=>f.join(e.basePath,t)}}createProjectRuleFileRelativePath(e,t){let n=f.join(e.path,pv,gv,t);return{pathKind:L.Relative,path:n,basePath:e.basePath,getDirectoryName:()=>gv,getAbsolutePath:()=>f.join(e.basePath,n)}}buildGlobalRuleContent(e){return Tg({description:`Global prompt (synced)`,alwaysApply:!0},e)}async writeProjectGlobalRule(e,t,n){let r=t.dirFromWorkspacePath,i=f.join(r.basePath,r.path,pv,gv),a=f.join(i,_v),o=this.createProjectRuleFileRelativePath(r,_v);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 bv.has(e)}getSkillsCursorDir(){return f.join(this.getGlobalConfigDir(),vv)}getGlobalCommandsDir(){return f.join(this.getGlobalConfigDir(),hv)}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(hv,i),basePath:this.getGlobalConfigDir(),getDirectoryName:()=>hv,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,mv),a={pathKind:L.Relative,path:mv,basePath:r,getDirectoryName:()=>pv,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,yv),s=this.getGlobalConfigDir(),c={pathKind:L.Relative,path:f.join(vv,i,yv),basePath:s,getDirectoryName:()=>i,getAbsolutePath:()=>o},l=this.buildSkillFrontMatter(n),u=n.content,d=Tg(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,mv),o={pathKind:L.Relative,path:f.join(vv,i,mv),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(vv,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(vv,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 Tg({alwaysApply:!1,globs:e.globs.length>0?e.globs.join(`, `):``},e.content).split(`
|
|
1201
|
+
`).map(e=>{let t=/^globs:\s*"(.*)"\s*$/.exec(e);if(t==null)return e;let n=t[1]??``;return n.trim().length===0?e:`globs: ${n}`}).join(`
|
|
1202
|
+
`)}async writeRuleMdcFile(e,t,n,r){let i=this.buildRuleFileName(n),a=f.join(t,i),o={pathKind:L.Relative,path:f.join(pv,gv,i),basePath:r,getDirectoryName:()=>gv,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}}}},Sv=class extends ov{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}},Cv=class extends Mg{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=Eg(o),i=await av(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 Gg([...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)}},wv=class extends Cv{constructor(){super(`FastCommandInputPlugin`,{configKey:`shadowFastCommandDir`})}getTargetDir(e,t){let n=e.shadowFastCommandDir,{workspaceDir:r,shadowProjectDir:i}=t;return this.resolvePath(n,r,i)}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=Eg(s),l=await av(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 Gg([...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}}},Tv=class extends ov{constructor(){super(`GeminiCLIOutputPlugin`,{globalConfigDir:`.gemini`,outputFileName:`GEMINI.md`,supportsFastCommands:!1,supportsSubAgents:!1,supportsSkills:!1})}};const Ev=`.skills`,Dv=`.aindex/.skills`,Ov=`SKILL.md`,kv=`mcp.json`;var Av=class extends kg{constructor(){super(`GenericSkillsOutputPlugin`,{globalConfigDir:Dv,outputFileName:Ov}),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,Ov);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(),Dv)}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,Ev);t.push({pathKind:L.Relative,path:n,basePath:e.dirFromWorkspacePath.basePath,getDirectoryName:()=>Ev,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,Ev);for(let i of r){let r=i.yamlFrontMatter.name,a=this.joinPath(n,r);t.push({pathKind:L.Relative,path:this.joinPath(Ev,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:Dv,basePath:this.getHomeDir(),getDirectoryName:()=>Dv,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(Dv,n,Ov),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,Ov)}),e.mcpConfig!=null&&t.push({pathKind:L.Relative,path:this.joinPath(Dv,n,kv),basePath:this.getHomeDir(),getDirectoryName:()=>n,getAbsolutePath:()=>this.joinPath(i,kv)}),e.childDocs!=null)for(let r of e.childDocs){let e=r.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:this.joinPath(Dv,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(Dv,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,Ev);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(Ev,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,Ov),s={pathKind:L.Relative,path:Ov,basePath:a,getDirectoryName:()=>i,getAbsolutePath:()=>o},c=this.buildSkillFrontMatter(t),l=t.content,u=Tg(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,kv),a={pathKind:L.Relative,path:kv,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}}}},jv=class extends Mg{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)})}},Mv=class extends jv{constructor(){super(`GitExcludeInputPlugin`)}getFilePath(e){return f.join(e,`public`,`exclude`)}getResultKey(){return`shadowGitExclude`}};function Nv(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 Pv(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 Fv(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 Iv=class extends kg{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,...Pv(r)];for(let e of a){let n=Nv(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 Fv(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 Nv(t)==null?Pv(t).some(e=>Nv(e)!=null):!0}),a=e.collectedInputContext.workspace.directory.path,o=Nv(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,...Pv(r)];for(let o of a){let a=Nv(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=Nv(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=Pv(c);for(let n of u){let r=Nv(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 Fv(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(`
|
|
1201
1203
|
`)}sanitizeContent(e){return e.split(/\r?\n/).filter(e=>{let t=e.trim();return t.length===0?!0:!(t.startsWith(`#`)&&!t.startsWith(`\\#`))}).join(`
|
|
1202
1204
|
`).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 Lv=Ut;function Rv(){return Lv[`public/gitignore`]?.content??``}var zv=class extends jv{constructor(){super(`GitIgnoreInputPlugin`,{fallbackContent:Rv()})}getFilePath(e){return f.join(e,`public`,`gitignore`)}getResultKey(){return`globalGitIgnore`}},Bv=class extends Mg{constructor(){super(`GlobalMemoryInputPlugin`)}async collect(e){let{userConfigOptions:t,fs:n,path:r,globalScope:i}=e,{workspaceDir:a,shadowProjectDir:o}=this.resolveBasePaths(t),s=t.globalMemoryFile,c=this.resolvePath(s,a,o);if(!n.existsSync(c))return this.log.warn({action:`collect`,reason:`fileNotFound`,path:c}),{};if(!n.statSync(c).isFile())return this.log.warn({action:`collect`,reason:`notAFile`,path:c}),{};let l=n.readFileSync(c,`utf8`),d=Eg(l),f;if(i!=null)try{f=await av(l,{globalScope:i,basePath:r.dirname(c)})}catch(e){throw e instanceof Hg&&(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 f=d.contentWithoutFrontMatter;return this.log.debug({action:`collect`,path:c,contentLength:f.length}),{globalMemory:{type:xt.GlobalMemory,content:f,length:f.length,filePathKind:L.Relative,...d.rawFrontMatter!=null&&{rawFrontMatter:d.rawFrontMatter},markdownAst:d.markdownAst,markdownContents:d.markdownContents,dir:{pathKind:L.Relative,path:r.basename(c),basePath:r.dirname(c),getDirectoryName:()=>r.basename(c),getAbsolutePath:()=>c},parentDirectoryPath:{type:wt.UserHome,directory:{pathKind:L.Relative,path:``,basePath:p.homedir(),getDirectoryName:()=>r.basename(p.homedir()),getAbsolutePath:()=>p.homedir()}}}}}},Vv=class extends Mg{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 Hv=`AGENTS.md`,Uv=`prompts`,Wv=`skills`,Gv=`SKILL.md`,Kv=`.aiassistant`,qv=`rules`,Jv=`always.md`,Yv=`codex`,Xv=[`IntelliJIdea`,`WebStorm`,`RustRover`,`PyCharm`,`PyCharmCE`,`PhpStorm`,`GoLand`,`CLion`,`DataGrip`,`RubyMine`,`Rider`,`DataSpell`,`Aqua`];var Zv=class extends kg{constructor(){super(`JetBrainsAIAssistantCodexOutputPlugin`,{outputFileName:Hv,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,Jv)),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,Uv);t.push({pathKind:L.Relative,path:Uv,basePath:r,getDirectoryName:()=>Uv,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,Wv,n);t.push({pathKind:L.Relative,path:f.join(Wv,n),basePath:r,getDirectoryName:()=>n,getAbsolutePath:()=>i})}}return t}async registerGlobalOutputFiles(){return this.resolveCodexDirs().map(e=>({pathKind:L.Relative,path:Hv,basePath:e,getDirectoryName:()=>Yv,getAbsolutePath:()=>f.join(e,Hv)}))}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,Jv,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,Hv),r={pathKind:L.Relative,path:Hv,basePath:a,getDirectoryName:()=>Yv,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`,Yv))}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,Kv,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,Kv,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 Tg({apply:`始终`},e)}buildGlobRuleContent(e){return Tg({apply:`按文件模式`,模式:this.buildChildRulePattern(e)},e.content)}async writeProjectRuleFile(e,t,n,r,i){let a=t.dirFromWorkspacePath,o=f.join(a.basePath,a.path,Kv,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 Xv.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,Uv),s=f.join(o,a),c={pathKind:L.Relative,path:f.join(Uv,a),basePath:t,getDirectoryName:()=>Uv,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,Wv,i),o=f.join(a,Gv),s={pathKind:L.Relative,path:f.join(Wv,i,Gv),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(` `)),Tg(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(Wv,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(Wv,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 Qv=`.idea`,$v=[`.editorconfig`,`.idea/codeStyles/Project.xml`,`.idea/codeStyles/codeStyleConfig.xml`,`.idea/.gitignore`];var ey=class extends kg{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 $v){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(Qv);return n===-1?this.joinPath(Qv,`codeStyles`,this.basename(t)):t.slice(Math.max(0,n))}},ty=class extends Mg{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
|
|
1203
1205
|
`)?`\r
|
package/dist/index.mjs
CHANGED
|
@@ -955,7 +955,7 @@ API 接口 (Spring WebFlux 6.2)
|
|
|
955
955
|
- \`controllers/\`: 控制器
|
|
956
956
|
- \`dto/\`: 数据传输对象
|
|
957
957
|
\`\`\`
|
|
958
|
-
`};const qt=Object.fromEntries(Gt.map(e=>[e,{path:e,content:Kt[e]??``}])),Jt={USER_HOME:`~`,WORKSPACE:`$WORKSPACE`,SHADOW_SOURCE_PROJECT:`$SHADOW_SOURCE_PROJECT`},Yt=JSON.parse(qt[`public/tnmsc.example.json`].content),Xt={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`},Zt={red:e=>`${Xt.red}${e}${Xt.reset}`,yellow:e=>`${Xt.yellow}${e}${Xt.reset}`,cyan:e=>`${Xt.cyan}${e}${Xt.reset}`,magenta:e=>`${Xt.magenta}${e}${Xt.reset}`,gray:e=>`${Xt.gray}${e}${Xt.reset}`,blue:e=>`${Xt.blue}${e}${Xt.reset}`,green:e=>`${Xt.green}${e}${Xt.reset}`,white:e=>`${Xt.white}${e}${Xt.reset}`,dim:e=>`${Xt.dim}${e}${Xt.reset}`,bgRed:e=>`${Xt.bgRed}${e}${Xt.reset}`};let Qt;const $t={error:Zt.red,warn:Zt.yellow,info:Zt.cyan,debug:Zt.magenta,trace:Zt.gray,fatal:Zt.bgRed},en={silent:0,fatal:1,error:2,warn:3,info:4,debug:5,trace:6};function tn(e){if(e===null)return Zt.dim(`null`);if(e===void 0)return Zt.dim(`undefined`);if(typeof e==`boolean`)return Zt.yellow(String(e));if(typeof e==`number`)return Zt.blue(String(e));if(typeof e==`string`)return Zt.green(`"${e}"`);if(Array.isArray(e))return e.length===0?`[]`:`[${e.map(e=>tn(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 nn(t)}return typeof e==`object`?nn(e):String(e)}function nn(e){let t=Object.entries(e);return t.length===0?`{}`:`{${t.map(([e,t])=>`${/^[\w$]+$/.test(e)?Zt.magenta(e):Zt.yellow(`"${e}"`)}:${tn(t)}`).join(`,`)}}`}function rn(){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 an(e,t,n,r){let i=rn(),a=$t[e]??Zt.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=nn({...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 on(e,t,n){let r=en[e],i=en[n];return(n,...a)=>r>i?{$:[rn(),e,t],_:n}:typeof n==`string`?an(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?an(e,t,``,n):an(e,t,n)}function sn(e){Qt=e}function cn(){return Qt}function ln(e,t){let n=t??Qt??process.env.LOG_LEVEL??`info`;return{error:on(`error`,e,n),warn:on(`warn`,e,n),info:on(`info`,e,n),debug:on(`debug`,e,n),trace:on(`trace`,e,n),fatal:on(`fatal`,e,n)}}const un=`.tnmsc.json`,dn=`.aindex`;function fn(){return i.join(s.homedir(),dn,un)}function pn(){return{...Yt}}function mn(e,t){let n=fn(),a=i.dirname(n);r.existsSync(a)||r.mkdirSync(a,{recursive:!0}),r.writeFileSync(n,`${JSON.stringify(e,null,2)}\n`,`utf8`),t.info(`global config created`,{path:n})}var hn=class{configFileName;searchCwd;searchGlobal;customSearchPaths;logger;constructor(e={}){this.configFileName=e.configFileName??un,this.searchCwd=e.searchCwd??!0,this.searchGlobal=e.searchGlobal??!0,this.customSearchPaths=e.searchPaths??[],this.logger=ln(`ConfigLoader`)}getSearchPaths(e=n.cwd()){let t=[];for(let e of this.customSearchPaths)t.push(this.resolveTilde(e));return this.searchCwd&&t.push(i.join(e,this.configFileName)),this.searchGlobal&&t.push(i.join(s.homedir(),dn,this.configFileName)),t}loadFromFile(e){let t=this.resolveTilde(e);try{if(!r.existsSync(t))return{config:{},source:null,found:!1};let e=r.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=n.cwd()){let t=this.getSearchPaths(e),r=[];for(let e of t){let t=this.loadFromFile(e);t.found&&r.push(t)}return{config:this.mergeConfigs(r.map(e=>e.config)),sources:r.map(e=>e.source).filter(e=>e!==null),found:r.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=[];for(let t of[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`])t in e&&(typeof e[t]==`string`?n[t]=e[t]:r.push(`${t} must be a string`));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(`externalProjects`in e){let t=e.externalProjects;Array.isArray(t)?t.every(e=>typeof e==`string`)?n.externalProjects=t:r.push(`externalProjects must be an array of strings`):r.push(`externalProjects must be an array`)}if(`excludePatterns`in e){let t=e.excludePatterns;if(typeof t==`object`&&t){let e=t,i={},a=!0;for(let[t,n]of Object.entries(e))Array.isArray(n)&&n.every(e=>typeof e==`string`)?i[t]=n:(r.push(`excludePatterns.${t} must be an array of strings`),a=!1);a&&(n.excludePatterns=i)}else r.push(`excludePatterns must be an object`)}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`)}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=[...e.externalProjects??[],...t.externalProjects??[]],r=this.mergeExcludePatterns(e.excludePatterns,t.excludePatterns);return{...e,...t,...n.length>0?{externalProjects:n}:{},...r==null?{}:{excludePatterns:r}}},{})}mergeExcludePatterns(e,t){if(e==null&&t==null)return null;if(e==null)return t??null;if(t==null)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]=[...n[e]??[],...r];return n}resolveTilde(e){return e.startsWith(`~`)?i.join(s.homedir(),e.slice(1)):e}};let gn=null;function _n(e){return(e||!gn)&&(gn=new hn(e)),gn}function vn(e){return _n().load(e)}function yn(){let e=ln(`ConfigLoader`),t=fn();if(!r.existsSync(t))return e.warn(`global config not found, creating default config`,{path:t}),mn(pn(),e),{valid:!0,exists:!1,errors:[],shouldExit:!1};let n;try{n=r.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}),xn(t,e,[`Failed to read config: ${r}`])}let i;try{i=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}),xn(t,e,[`Invalid JSON: ${r}`])}if(typeof i!=`object`||!i||Array.isArray(i))return e.error(`global config must be a JSON object`,{path:t}),xn(t,e,[`Config must be a JSON object`]);let a=bn(i);if(a.length>0){for(let n of a)e.error(`config validation error`,{path:t,error:n});return xn(t,e,a)}return{valid:!0,exists:!0,errors:[],shouldExit:!1}}function bn(e){let t=[];for(let n of[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`])n in e&&typeof e[n]!=`string`&&t.push(`${n} must be a string`);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(`externalProjects`in e){let n=e.externalProjects;Array.isArray(n)?n.every(e=>typeof e==`string`)||t.push(`externalProjects must be an array of strings`):t.push(`externalProjects must be an array`)}if(`excludePatterns`in e){let n=e.excludePatterns;if(typeof n!=`object`||!n||Array.isArray(n))t.push(`excludePatterns must be an object`);else{let e=n;for(let[n,r]of Object.entries(e))(!Array.isArray(r)||!r.every(e=>typeof e==`string`))&&t.push(`excludePatterns.${n} must be an array of strings`)}}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 xn(e,t,n){try{r.unlinkSync(e),t.info(`deleted invalid config`,{path:e})}catch{t.warn(`failed to delete invalid config`,{path:e})}return mn(pn(),t),t.error(`recreated default config, please review and restart`,{path:e}),{valid:!1,exists:!0,errors:n,shouldExit:!0}}const Sn=[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`,`logLevel`];function Cn(e){return Sn.includes(e)}function wn(e){return[`trace`,`debug`,`info`,`warn`,`error`].includes(e)}function Tn(){return i.join(s.homedir(),dn,un)}function En(){let e=Tn();if(!r.existsSync(e))return{};try{let t=r.readFileSync(e,`utf8`);return JSON.parse(t)}catch{return{}}}function Dn(e){let t=Tn(),n=i.dirname(t);r.existsSync(n)||r.mkdirSync(n,{recursive:!0}),r.writeFileSync(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)}var On=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: ${Sn.join(`, `)}`),{success:!1,filesAffected:0,dirsAffected:0,message:`No options provided`};let n=En(),r=[],i=[];for(let[e,a]of this.options){if(!Cn(e)){r.push(`Invalid key: ${e} (valid keys: ${Sn.join(`, `)})`);continue}if(e===`logLevel`&&!wn(a)){r.push(`Invalid logLevel value: ${a} (must be: trace, debug, info, warn, or error)`);continue}let o=n[e];n[e]=a,o!==a&&i.push(`${e}=${a}`),t.info(`configuration updated`,{key:e,value:a})}if(i.length>0&&(Dn(n),t.info(`global config written`,{path:Tn()})),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}}},kn=class{name=`config-show`;async execute(e){let{logger:t}=e,r=new hn,i=r.load(),a=i.sources.map(e=>{let t=r.loadFromFile(e);return{path:e,layer:this.inferLayer(e),config:t.config}}),o={merged:i.config,sources:a};return n.stdout.write(`${JSON.stringify(o)}\n`),t.info(`config shown`,{sources:i.sources.length}),{success:!0,filesAffected:0,dirsAffected:0,message:`Configuration displayed (${a.length} source(s))`}}inferLayer(e){let t=n.cwd();return e.startsWith(t)?`cwd`:`global`}},An=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 gt(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 xt(n,await _t(n,i),i);return this.logDryRunFiles(o,t),this.logDryRunDirectories(s,t),await vt(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=i.isAbsolute(n)?n:i.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=i.isAbsolute(e)?e:i.resolve(e);t.info(`would delete directory`,{path:n,dryRun:!0})}}},jn=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 yt(n,i),o=await bt(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`}}},Mn=class{name=`execute`;async execute(e){let{logger:t,outputPlugins:n,createCleanContext:r,createWriteContext:i}=e;t.info(`started`,{command:`execute`});let a=await Ct(n,r(!1),t,{executeHooks:!1});t.info(`cleanup complete`,{deletedFiles:a.deletedFiles,deletedDirs:a.deletedDirs});let o=i(!1),s=await yt(n,o),c=await bt(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 Nn(){return`2026.10218.11313`}var Pn=class{name=`version`;async execute(e){return e.logger.error(`tnmsc v${Nn()}`),{success:!0,filesAffected:0,dirsAffected:0,message:`Version displayed`}}};const Fn=`tnmsc`,In=`
|
|
958
|
+
`};const qt=Object.fromEntries(Gt.map(e=>[e,{path:e,content:Kt[e]??``}])),Jt={USER_HOME:`~`,WORKSPACE:`$WORKSPACE`,SHADOW_SOURCE_PROJECT:`$SHADOW_SOURCE_PROJECT`},Yt=JSON.parse(qt[`public/tnmsc.example.json`].content),Xt={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`},Zt={red:e=>`${Xt.red}${e}${Xt.reset}`,yellow:e=>`${Xt.yellow}${e}${Xt.reset}`,cyan:e=>`${Xt.cyan}${e}${Xt.reset}`,magenta:e=>`${Xt.magenta}${e}${Xt.reset}`,gray:e=>`${Xt.gray}${e}${Xt.reset}`,blue:e=>`${Xt.blue}${e}${Xt.reset}`,green:e=>`${Xt.green}${e}${Xt.reset}`,white:e=>`${Xt.white}${e}${Xt.reset}`,dim:e=>`${Xt.dim}${e}${Xt.reset}`,bgRed:e=>`${Xt.bgRed}${e}${Xt.reset}`};let Qt;const $t={error:Zt.red,warn:Zt.yellow,info:Zt.cyan,debug:Zt.magenta,trace:Zt.gray,fatal:Zt.bgRed},en={silent:0,fatal:1,error:2,warn:3,info:4,debug:5,trace:6};function tn(e){if(e===null)return Zt.dim(`null`);if(e===void 0)return Zt.dim(`undefined`);if(typeof e==`boolean`)return Zt.yellow(String(e));if(typeof e==`number`)return Zt.blue(String(e));if(typeof e==`string`)return Zt.green(`"${e}"`);if(Array.isArray(e))return e.length===0?`[]`:`[${e.map(e=>tn(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 nn(t)}return typeof e==`object`?nn(e):String(e)}function nn(e){let t=Object.entries(e);return t.length===0?`{}`:`{${t.map(([e,t])=>`${/^[\w$]+$/.test(e)?Zt.magenta(e):Zt.yellow(`"${e}"`)}:${tn(t)}`).join(`,`)}}`}function rn(){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 an(e,t,n,r){let i=rn(),a=$t[e]??Zt.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=nn({...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 on(e,t,n){let r=en[e],i=en[n];return(n,...a)=>r>i?{$:[rn(),e,t],_:n}:typeof n==`string`?an(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?an(e,t,``,n):an(e,t,n)}function sn(e){Qt=e}function cn(){return Qt}function ln(e,t){let n=t??Qt??process.env.LOG_LEVEL??`info`;return{error:on(`error`,e,n),warn:on(`warn`,e,n),info:on(`info`,e,n),debug:on(`debug`,e,n),trace:on(`trace`,e,n),fatal:on(`fatal`,e,n)}}const un=`.tnmsc.json`,dn=`.aindex`;function fn(){return i.join(s.homedir(),dn,un)}function pn(){return{...Yt}}function mn(e,t){let n=fn(),a=i.dirname(n);r.existsSync(a)||r.mkdirSync(a,{recursive:!0}),r.writeFileSync(n,`${JSON.stringify(e,null,2)}\n`,`utf8`),t.info(`global config created`,{path:n})}var hn=class{configFileName;searchCwd;searchGlobal;customSearchPaths;logger;constructor(e={}){this.configFileName=e.configFileName??un,this.searchCwd=e.searchCwd??!0,this.searchGlobal=e.searchGlobal??!0,this.customSearchPaths=e.searchPaths??[],this.logger=ln(`ConfigLoader`)}getSearchPaths(e=n.cwd()){let t=[];for(let e of this.customSearchPaths)t.push(this.resolveTilde(e));return this.searchCwd&&t.push(i.join(e,this.configFileName)),this.searchGlobal&&t.push(i.join(s.homedir(),dn,this.configFileName)),t}loadFromFile(e){let t=this.resolveTilde(e);try{if(!r.existsSync(t))return{config:{},source:null,found:!1};let e=r.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=n.cwd()){let t=this.getSearchPaths(e),r=[];for(let e of t){let t=this.loadFromFile(e);t.found&&r.push(t)}return{config:this.mergeConfigs(r.map(e=>e.config)),sources:r.map(e=>e.source).filter(e=>e!==null),found:r.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=[];for(let t of[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`])t in e&&(typeof e[t]==`string`?n[t]=e[t]:r.push(`${t} must be a string`));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(`externalProjects`in e){let t=e.externalProjects;Array.isArray(t)?t.every(e=>typeof e==`string`)?n.externalProjects=t:r.push(`externalProjects must be an array of strings`):r.push(`externalProjects must be an array`)}if(`excludePatterns`in e){let t=e.excludePatterns;if(typeof t==`object`&&t){let e=t,i={},a=!0;for(let[t,n]of Object.entries(e))Array.isArray(n)&&n.every(e=>typeof e==`string`)?i[t]=n:(r.push(`excludePatterns.${t} must be an array of strings`),a=!1);a&&(n.excludePatterns=i)}else r.push(`excludePatterns must be an object`)}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`)}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=[...e.externalProjects??[],...t.externalProjects??[]],r=this.mergeExcludePatterns(e.excludePatterns,t.excludePatterns);return{...e,...t,...n.length>0?{externalProjects:n}:{},...r==null?{}:{excludePatterns:r}}},{})}mergeExcludePatterns(e,t){if(e==null&&t==null)return null;if(e==null)return t??null;if(t==null)return e;let n={...e};for(let[e,r]of Object.entries(t))n[e]=[...n[e]??[],...r];return n}resolveTilde(e){return e.startsWith(`~`)?i.join(s.homedir(),e.slice(1)):e}};let gn=null;function _n(e){return(e||!gn)&&(gn=new hn(e)),gn}function vn(e){return _n().load(e)}function yn(){let e=ln(`ConfigLoader`),t=fn();if(!r.existsSync(t))return e.warn(`global config not found, creating default config`,{path:t}),mn(pn(),e),{valid:!0,exists:!1,errors:[],shouldExit:!1};let n;try{n=r.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}),xn(t,e,[`Failed to read config: ${r}`])}let i;try{i=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}),xn(t,e,[`Invalid JSON: ${r}`])}if(typeof i!=`object`||!i||Array.isArray(i))return e.error(`global config must be a JSON object`,{path:t}),xn(t,e,[`Config must be a JSON object`]);let a=bn(i);if(a.length>0){for(let n of a)e.error(`config validation error`,{path:t,error:n});return xn(t,e,a)}return{valid:!0,exists:!0,errors:[],shouldExit:!1}}function bn(e){let t=[];for(let n of[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`])n in e&&typeof e[n]!=`string`&&t.push(`${n} must be a string`);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(`externalProjects`in e){let n=e.externalProjects;Array.isArray(n)?n.every(e=>typeof e==`string`)||t.push(`externalProjects must be an array of strings`):t.push(`externalProjects must be an array`)}if(`excludePatterns`in e){let n=e.excludePatterns;if(typeof n!=`object`||!n||Array.isArray(n))t.push(`excludePatterns must be an object`);else{let e=n;for(let[n,r]of Object.entries(e))(!Array.isArray(r)||!r.every(e=>typeof e==`string`))&&t.push(`excludePatterns.${n} must be an array of strings`)}}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 xn(e,t,n){try{r.unlinkSync(e),t.info(`deleted invalid config`,{path:e})}catch{t.warn(`failed to delete invalid config`,{path:e})}return mn(pn(),t),t.error(`recreated default config, please review and restart`,{path:e}),{valid:!1,exists:!0,errors:n,shouldExit:!0}}const Sn=[`workspaceDir`,`shadowSourceProjectDir`,`shadowSkillSourceDir`,`shadowFastCommandDir`,`shadowSubAgentDir`,`globalMemoryFile`,`shadowProjectsDir`,`logLevel`];function Cn(e){return Sn.includes(e)}function wn(e){return[`trace`,`debug`,`info`,`warn`,`error`].includes(e)}function Tn(){return i.join(s.homedir(),dn,un)}function En(){let e=Tn();if(!r.existsSync(e))return{};try{let t=r.readFileSync(e,`utf8`);return JSON.parse(t)}catch{return{}}}function Dn(e){let t=Tn(),n=i.dirname(t);r.existsSync(n)||r.mkdirSync(n,{recursive:!0}),r.writeFileSync(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)}var On=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: ${Sn.join(`, `)}`),{success:!1,filesAffected:0,dirsAffected:0,message:`No options provided`};let n=En(),r=[],i=[];for(let[e,a]of this.options){if(!Cn(e)){r.push(`Invalid key: ${e} (valid keys: ${Sn.join(`, `)})`);continue}if(e===`logLevel`&&!wn(a)){r.push(`Invalid logLevel value: ${a} (must be: trace, debug, info, warn, or error)`);continue}let o=n[e];n[e]=a,o!==a&&i.push(`${e}=${a}`),t.info(`configuration updated`,{key:e,value:a})}if(i.length>0&&(Dn(n),t.info(`global config written`,{path:Tn()})),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}}},kn=class{name=`config-show`;async execute(e){let{logger:t}=e,r=new hn,i=r.load(),a=i.sources.map(e=>{let t=r.loadFromFile(e);return{path:e,layer:this.inferLayer(e),config:t.config}}),o={merged:i.config,sources:a};return n.stdout.write(`${JSON.stringify(o)}\n`),t.info(`config shown`,{sources:i.sources.length}),{success:!0,filesAffected:0,dirsAffected:0,message:`Configuration displayed (${a.length} source(s))`}}inferLayer(e){let t=n.cwd();return e.startsWith(t)?`cwd`:`global`}},An=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 gt(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 xt(n,await _t(n,i),i);return this.logDryRunFiles(o,t),this.logDryRunDirectories(s,t),await vt(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=i.isAbsolute(n)?n:i.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=i.isAbsolute(e)?e:i.resolve(e);t.info(`would delete directory`,{path:n,dryRun:!0})}}},jn=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 yt(n,i),o=await bt(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`}}},Mn=class{name=`execute`;async execute(e){let{logger:t,outputPlugins:n,createCleanContext:r,createWriteContext:i}=e;t.info(`started`,{command:`execute`});let a=await Ct(n,r(!1),t,{executeHooks:!1});t.info(`cleanup complete`,{deletedFiles:a.deletedFiles,deletedDirs:a.deletedDirs});let o=i(!1),s=await yt(n,o),c=await bt(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 Nn(){return`2026.10218.11905`}var Pn=class{name=`version`;async execute(e){return e.logger.error(`tnmsc v${Nn()}`),{success:!0,filesAffected:0,dirsAffected:0,message:`Version displayed`}}};const Fn=`tnmsc`,In=`
|
|
959
959
|
${Fn} v${Nn()} - Memory Sync CLI
|
|
960
960
|
|
|
961
961
|
Synchronize AI memory and configuration files across projects.
|
|
@@ -1009,7 +1009,7 @@ CONFIG OPTIONS:
|
|
|
1009
1009
|
CONFIGURATION:
|
|
1010
1010
|
Configure via plugin.config.ts in your project root.
|
|
1011
1011
|
See documentation for detailed configuration options.
|
|
1012
|
-
`.trim();var Ln=class{name=`help`;async execute(e){return console.log(In),{success:!0,filesAffected:0,dirsAffected:0,message:`Help displayed`}}};function Rn(e,t){let n=i.join(e,`.git`),a=r.existsSync(n);return a?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:a,gitPath:n}}function zn(e,t,n,a,o){if(n==null)return a;let s=i.relative(t,e),c=i.join(n,s);return r.existsSync(c)&&r.statSync(c).isFile()?(o?.debug(`copying from source`,{path:c}),r.readFileSync(c,`utf8`)):a}function Bn(e,t={}){let{sourceDir:n,logger:a}=t,o=[],s=[],c=[],l=[],u=new Set;r.existsSync(e)?(c.push(e),a?.debug(`directory exists`,{path:e})):(r.mkdirSync(e,{recursive:!0}),o.push(e),u.add(e),a?.info(`created directory`,{path:e}));for(let t of Object.values(qt)){let c=t.path,d=i.join(e,c),f=i.dirname(d);if(!r.existsSync(f)){r.mkdirSync(f,{recursive:!0});let t=f;for(;t!==e&&!u.has(t);)u.add(t),o.push(t),a?.info(`created directory`,{path:t}),t=i.dirname(t)}if(r.existsSync(d))l.push(d),a?.debug(`file exists`,{path:d});else{let i=zn(d,e,n,t.content,a);r.writeFileSync(d,i,`utf8`),s.push(d),a?.info(`created file`,{path:d})}}return{success:!0,rootPath:e,createdDirs:o,createdFiles:s,existedDirs:c,existedFiles:l}}function Vn(e,t,n){let r=e;return r=r.replace(Jt.SHADOW_SOURCE_PROJECT,n),r=r.replace(Jt.WORKSPACE,t),r.startsWith(`~`)&&(r=i.join(s.homedir(),r.slice(1))),i.normalize(r)}var Hn=class{name=`init`;async execute(e){let{logger:t,userConfigOptions:n}=e;t.info(`initializing shadow source project structure`,{command:`init`});let r=Vn(n.workspaceDir,``,``),i=Bn(Vn(n.shadowSourceProjectDir,r,``),{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}}},Un=class{name;inner;constructor(e){this.inner=e,this.name=`json:${e.name}`}async execute(e){let t=await this.inner.execute(e),r=Wn(t);return n.stdout.write(`${JSON.stringify(r)}\n`),t}};function Wn(e){return{success:e.success,filesAffected:e.filesAffected,dirsAffected:e.dirsAffected,...e.message!=null&&{message:e.message},pluginResults:[],errors:[]}}function Gn(){return`@truenine/memory-sync-cli`}function Kn(){return`https://registry.npmjs.org/${Gn()}/latest`}function qn(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 Jn(e,t){let n=qn(e),r=qn(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 Yn=3e3;async function Xn(){let e=new AbortController,t=setTimeout(()=>e.abort(),Yn);typeof t==`object`&&`unref`in t&&t.unref();try{let n=await fetch(Kn(),{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 ${Yn}ms`}:{error:e.message}:{error:`Unknown network error`}}}function Zn(){return`2026.10218.11313`}async function Qn(){let e=Zn();if(e===`dev`)return{status:`development`,localVersion:e,remoteVersion:null};let t=await Xn();if(`error`in t)return{status:`current`,localVersion:e,remoteVersion:null,error:t.error};let n=t.version,r=Jn(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 $n(e,t){let{status:n,localVersion:r,remoteVersion:i}=e;switch(n){case`outdated`:t.warn(`Version outdated: ${r} → ${i}. Run 'npm i -g ${Gn()}@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 er(){return new Date().getMinutes()%2==0}function tr(e){er()&&Qn().then(t=>{(t.status===`outdated`||t.error!=null)&&$n(t,e)}).catch(t=>{let n=t instanceof Error?t.message:`Unknown error`;e.error(`Version check failed: ${n}`)})}var nr=class{name=`outdated`;async execute(e){let t=await Qn();return $n(t,e.logger),{success:!0,filesAffected:0,dirsAffected:0,message:`Version status: ${t.status}`}}},rr=class{name=`plugins`;async execute(e){let{logger:t,outputPlugins:r,userConfigOptions:i}=e,a=i.plugins,o=[];for(let e of a)o.push({name:e.name,kind:e.type===Tt.Input?`Input`:`Output`,description:e.name,dependencies:[...e.dependsOn??[]]});let s=new Set(o.map(e=>e.name));for(let e of r)s.has(e.name)||o.push({name:e.name,kind:`Output`,description:e.name,dependencies:[...e.dependsOn??[]]});return n.stdout.write(`${JSON.stringify(o)}\n`),t.info(`plugins listed`,{count:o.length}),{success:!0,filesAffected:0,dirsAffected:0,message:`Listed ${o.length} plugin(s)`}}},ir=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 ar={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 or=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}({}),sr=function(e){return e.Win=`win`,e.Mac=`mac`,e.Linux=`linux`,e.Unknown=`unknown`,e}({});var cr=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=s.platform();return{platform:e,arch:s.arch(),hostname:s.hostname(),homedir:s.homedir(),tmpdir:s.tmpdir(),type:s.type(),release:s.release(),shellKind:this.detectShellKind(),kind:this.detectOsKind(e)}}detectOsKind(e){switch(e){case`win32`:return sr.Win;case`darwin`:return sr.Mac;case`linux`:case`freebsd`:case`openbsd`:case`sunos`:case`aix`:return sr.Linux;default:return sr.Unknown}}detectShellKind(){let e=(n.env.SHELL??n.env.ComSpec??``).toLowerCase();return e.includes(`bash`)?or.Bash:e.includes(`zsh`)?or.Zsh:e.includes(`fish`)?or.Fish:e.includes(`pwsh`)?or.Pwsh:e.includes(`powershell`)?or.PowerShell:e.includes(`cmd`)?or.Cmd:e.endsWith(`/sh`)?or.Sh:or.Unknown}collectEnvContext(){return{...n.env}}collectProfile(){return this.userConfig?.profile==null?{}:this.userConfig.profile}collectToolReferences(){let e={...ar.default};return this.toolPreset===`claudeCode`?{...e,...ar.claudeCode}:this.toolPreset===`kiro`?{...e,...ar.kiro}:e}createMdComponent(){let e=(e=>e.when===!1?null:e.children);return e.Line=e=>e.when===!1?null:e.children,e}};let lr=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 ur=class{registrations=[];globalScope=null;setGlobalScope(e){this.globalScope=e}getGlobalScope(){return this.globalScope}register(e,t,n=lr.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 dr(e){let t=[...e],n=t[0];n!=null&&fr(n)&&t.shift();let r=t[0];return r!=null&&pr(r)&&t.shift(),t}function fr(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 pr(e){return/\.(?:m?[jt]s|cjs)$/.test(e)||/[/\\]/.test(e)&&!e.startsWith(`-`)?!0:/^(?:@[\w-]+\/)?[\w-]+$/.test(e)&&!e.startsWith(`-`)}const mr=new Set([`help`,`version`,`outdated`,`init`,`dry-run`,`clean`,`config`,`plugins`]),hr=new Map([[`--trace`,`trace`],[`--debug`,`debug`],[`--info`,`info`],[`--warn`,`warn`],[`--error`,`error`]]),gr=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4]]);function _r(e){let{logLevelFlags:t}=e;if(t.length===0)return;let n=t[0],r=gr.get(n)??4;for(let e of t){let t=gr.get(e)??4;t<r&&(r=t,n=e)}return n}function vr(e){let{helpFlag:t,versionFlag:n,subcommand:r,dryRun:i,unknownCommand:a,setOption:o,positional:s,showFlag:c}=e;if(n)return new Pn;if(t)return new Ln;if(a!=null)return new ir(a);if(r===`version`)return new Pn;if(r===`help`)return new Ln;if(r===`outdated`)return new nr;if(r===`init`)return new Hn;if(r===`dry-run`)return new jn;if(r===`clean`)return i?new An:new wt;if(r===`plugins`)return new rr;if(r===`config`&&c)return new kn;if(r!==`config`||o.length>0)return new Mn;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 On([...o,...l])}function yr(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=hr.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,mr.has(i)?t.subcommand=i:t.unknownCommand=i;continue}t.positional.push(i)}}return t}var br=class{logger;args;outputPlugins=[];constructor(...e){this.args=yr(dr(e.filter(e=>e!=null)));let t=_r(this.args);t!=null&&sn(t),this.logger=ln(`PluginPipeline`,t),this.logger.debug(`initialized`,{args:this.args})}registerOutputPlugins(e){return this.outputPlugins.push(...e),this}async run(e){tr(this.logger);let{context:t,outputPlugins:n,userConfigOptions:r}=e;this.registerOutputPlugins([...n]);let i=this.resolveCommand();this.args.jsonFlag&&(sn(`silent`),new Set([`config-show`,`plugins`]).has(i.name)||(i=new Un(i)));let a=this.createCommandContext(t,r);await i.execute(a)}resolveCommand(){return vr(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:r,path:i,glob:et.default,collectedInputContext:e,dryRun:t}}createWriteContext(e,t){return{logger:this.logger,fs:r,path:i,glob:et.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 Mt(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 jt(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 cr({userConfig:r}).collect(),o=new ur;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,lr.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.externalProjects==null?e.externalProjects:[...e.externalProjects??[],...t.externalProjects],i=t.ideConfigFiles==null?e.ideConfigFiles:[...e.ideConfigFiles??[],...t.ideConfigFiles],a=t.fastCommands==null?e.fastCommands:[...e.fastCommands??[],...t.fastCommands],o=t.subAgents==null?e.subAgents:[...e.subAgents??[],...t.subAgents],s=t.skills==null?e.skills:[...e.skills??[],...t.skills],c=t.rules==null?e.rules:[...e.rules??[],...t.rules],l=t.aiAgentIgnoreConfigFiles==null?e.aiAgentIgnoreConfigFiles:[...e.aiAgentIgnoreConfigFiles??[],...t.aiAgentIgnoreConfigFiles],u=t.globalMemory??e.globalMemory,d=t.shadowSourceProjectDir??e.shadowSourceProjectDir,f=t.readmePrompts==null?e.readmePrompts:[...e.readmePrompts??[],...t.readmePrompts],p=t.globalGitIgnore??e.globalGitIgnore,m=t.shadowGitExclude??e.shadowGitExclude;return{...n==null?{}:{workspace:n},...r==null?{}:{externalProjects:r},...i==null?{}:{ideConfigFiles:i},...a==null?{}:{fastCommands:a},...o==null?{}:{subAgents:o},...s==null?{}:{skills:s},...c==null?{}:{rules:c},...l==null?{}:{aiAgentIgnoreConfigFiles:l},...u==null?{}:{globalMemory:u},...d==null?{}:{shadowSourceProjectDir:d},...f==null?{}:{readmePrompts:f},...p==null?{}:{globalGitIgnore:p},...m==null?{}:{shadowGitExclude:m}}}};const xr={...Yt,externalProjects:[],excludePatterns:{},fastCommandSeriesOptions:{},plugins:[]};function Sr(e){return{...e.workspaceDir==null?{}:{workspaceDir:e.workspaceDir},...e.shadowSourceProjectDir==null?{}:{shadowSourceProjectDir:e.shadowSourceProjectDir},...e.shadowSkillSourceDir==null?{}:{shadowSkillSourceDir:e.shadowSkillSourceDir},...e.shadowFastCommandDir==null?{}:{shadowFastCommandDir:e.shadowFastCommandDir},...e.shadowSubAgentDir==null?{}:{shadowSubAgentDir:e.shadowSubAgentDir},...e.shadowRulesDir==null?{}:{shadowRulesDir:e.shadowRulesDir},...e.globalMemoryFile==null?{}:{globalMemoryFile:e.globalMemoryFile},...e.shadowProjectsDir==null?{}:{shadowProjectsDir:e.shadowProjectsDir},...e.externalProjects==null?{}:{externalProjects:e.externalProjects},...e.excludePatterns==null?{}:{excludePatterns:e.excludePatterns},...e.fastCommandSeriesOptions==null?{}:{fastCommandSeriesOptions:e.fastCommandSeriesOptions},...e.logLevel==null?{}:{logLevel:e.logLevel}}}function Cr(...e){return e.reduce((e,t)=>wr(e,t),{...xr})}function wr(e,t){let n=t.externalProjects,r=t.plugins,i=t.excludePatterns,a=t.fastCommandSeriesOptions;return{...e,...t,externalProjects:[...e.externalProjects,...n??[]],plugins:[...e.plugins,...r??[]],excludePatterns:Tr(e.excludePatterns,i),fastCommandSeriesOptions:Er(e.fastCommandSeriesOptions,a)}}function Tr(e,t){let n={...e};if(t)for(let[e,r]of Object.entries(t))n[e]=[...n[e]??[],...r];return n}function Er(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 Dr(e){return`pluginOptions`in e||`configLoaderOptions`in e||`loadUserConfig`in e}async function Or(e={}){yn().shouldExit&&n.exit(1);let t,a,o;Dr(e)?({pluginOptions:o={},cwd:a}={pluginOptions:e.pluginOptions,cwd:e.cwd},t=e.loadUserConfig??!0):(o=e,t=!0);let s={},c=!1,l=[],u;if(t){let e=vn(a);c=e.found,l=e.sources,e.found&&(s=Sr(e.config),u=e.config)}let d=Cr(s,o),{plugins:f=[],logLevel:p}=d,m=ln(`defineConfig`,p);c?m.info(`user config loaded`,{sources:l}):m.info(`no user config found, using defaults`,{workspaceDir:xr.workspaceDir,shadowSourceProjectDir:xr.shadowSourceProjectDir,shadowSkillSourceDir:xr.shadowSkillSourceDir,shadowFastCommandDir:xr.shadowFastCommandDir,shadowSubAgentDir:xr.shadowSubAgentDir,globalMemoryFile:xr.globalMemoryFile,shadowProjectsDir:xr.shadowProjectsDir,logLevel:xr.logLevel});let h={logger:m,userConfigOptions:d,fs:r,path:i,glob:et.default},g=f.filter(e=>e.type===Tt.Input),_=f.filter(e=>e.type===Tt.Output),v=await new br().executePluginsInOrder(g,h,!1,u);if(v.workspace==null)throw Error(`Workspace not initialized by any plugin`);let y={workspace:v.workspace,ideConfigFiles:v.ideConfigFiles??[],...v.externalProjects!=null&&{externalProjects:v.externalProjects},...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&&Rn(v.shadowSourceProjectDir,m),{context:y,outputPlugins:_,userConfigOptions:d}}const kr=Rr(/[A-Za-z]/),Ar=Rr(/[\dA-Za-z]/),jr=Rr(/[#-'*+\--9=?A-Z^-~]/);function Mr(e){return e!==null&&(e<32||e===127)}const Nr=Rr(/\d/),Pr=Rr(/[\dA-Fa-f]/),Fr=Rr(/[!-/:-@[-`{-~]/);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 Ir=Rr(/\p{P}|\p{S}/u),Lr=Rr(/\s/);function Rr(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}var zr=S(y(((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 Br=Object.assign(Vr(Error),{eval:Vr(EvalError),range:Vr(RangeError),reference:Vr(ReferenceError),syntax:Vr(SyntaxError),type:Vr(TypeError),uri:Vr(URIError)});function Vr(e){return t.displayName=e.displayName||e.name,t;function t(t,...n){return new e(t&&(0,zr.default)(t,...n))}}const Hr={}.hasOwnProperty,Ur={yaml:`-`,toml:`+`};function Wr(e){let t=[],n=-1,r=Array.isArray(e)?e:e?[e]:[`yaml`];for(;++n<r.length;)t[n]=Gr(r[n]);return t}function Gr(e){let t=e;if(typeof t==`string`){if(!Hr.call(Ur,t))throw Br("Missing matter definition for `%s`",t);t={type:t,marker:Ur[t]}}else if(typeof t!=`object`)throw Br("Expected matter to be an object, not `%j`",t);if(!Hr.call(t,`type`))throw Br("Missing `type` in matter `%j`",t);if(!Hr.call(t,`fence`)&&!Hr.call(t,`marker`))throw Br("Missing `marker` or `fence` in matter `%j`",t);return t}function Kr(e){let t=Wr(e),n={},r=-1;for(;++r<t.length;){let e=t[r],i=Jr(e,`open`).charCodeAt(0),a=qr(e),o=n[i];Array.isArray(o)?o.push(a):n[i]=[a]}return{flow:n}}function qr(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=Jr(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=Jr(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 Jr(e,t){return e.marker?Yr(e.marker,t).repeat(3):Yr(e.fence,t)}function Yr(e,t){return typeof e==`string`?e:e[t]}function Xr(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function Zr(e){let t=Wr(e),n={},r={},i=-1;for(;++i<t.length;){let e=t[i];n[e.type]=Qr(e),r[e.type]=$r,r[e.type+`Value`]=ei}return{enter:n,exit:r}}function Qr(e){return t;function t(t){this.enter({type:e.type,value:``},t),this.buffer()}}function $r(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 ei(e){this.config.enter.data.call(this,e),this.config.exit.data.call(this,e)}function ti(e){let t=[],n={},r=Wr(e),i=-1;for(;++i<r.length;){let e=r[i];n[e.type]=ni(e);let a=ri(e,`open`);t.push({atBreak:!0,character:a.charAt(0),after:Xr(a.charAt(1))})}return{unsafe:t,handlers:n}}function ni(e){let t=ri(e,`open`),n=ri(e,`close`);return r;function r(e){return t+(e.value?`
|
|
1012
|
+
`.trim();var Ln=class{name=`help`;async execute(e){return console.log(In),{success:!0,filesAffected:0,dirsAffected:0,message:`Help displayed`}}};function Rn(e,t){let n=i.join(e,`.git`),a=r.existsSync(n);return a?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:a,gitPath:n}}function zn(e,t,n,a,o){if(n==null)return a;let s=i.relative(t,e),c=i.join(n,s);return r.existsSync(c)&&r.statSync(c).isFile()?(o?.debug(`copying from source`,{path:c}),r.readFileSync(c,`utf8`)):a}function Bn(e,t={}){let{sourceDir:n,logger:a}=t,o=[],s=[],c=[],l=[],u=new Set;r.existsSync(e)?(c.push(e),a?.debug(`directory exists`,{path:e})):(r.mkdirSync(e,{recursive:!0}),o.push(e),u.add(e),a?.info(`created directory`,{path:e}));for(let t of Object.values(qt)){let c=t.path,d=i.join(e,c),f=i.dirname(d);if(!r.existsSync(f)){r.mkdirSync(f,{recursive:!0});let t=f;for(;t!==e&&!u.has(t);)u.add(t),o.push(t),a?.info(`created directory`,{path:t}),t=i.dirname(t)}if(r.existsSync(d))l.push(d),a?.debug(`file exists`,{path:d});else{let i=zn(d,e,n,t.content,a);r.writeFileSync(d,i,`utf8`),s.push(d),a?.info(`created file`,{path:d})}}return{success:!0,rootPath:e,createdDirs:o,createdFiles:s,existedDirs:c,existedFiles:l}}function Vn(e,t,n){let r=e;return r=r.replace(Jt.SHADOW_SOURCE_PROJECT,n),r=r.replace(Jt.WORKSPACE,t),r.startsWith(`~`)&&(r=i.join(s.homedir(),r.slice(1))),i.normalize(r)}var Hn=class{name=`init`;async execute(e){let{logger:t,userConfigOptions:n}=e;t.info(`initializing shadow source project structure`,{command:`init`});let r=Vn(n.workspaceDir,``,``),i=Bn(Vn(n.shadowSourceProjectDir,r,``),{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}}},Un=class{name;inner;constructor(e){this.inner=e,this.name=`json:${e.name}`}async execute(e){let t=await this.inner.execute(e),r=Wn(t);return n.stdout.write(`${JSON.stringify(r)}\n`),t}};function Wn(e){return{success:e.success,filesAffected:e.filesAffected,dirsAffected:e.dirsAffected,...e.message!=null&&{message:e.message},pluginResults:[],errors:[]}}function Gn(){return`@truenine/memory-sync-cli`}function Kn(){return`https://registry.npmjs.org/${Gn()}/latest`}function qn(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 Jn(e,t){let n=qn(e),r=qn(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 Yn=3e3;async function Xn(){let e=new AbortController,t=setTimeout(()=>e.abort(),Yn);typeof t==`object`&&`unref`in t&&t.unref();try{let n=await fetch(Kn(),{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 ${Yn}ms`}:{error:e.message}:{error:`Unknown network error`}}}function Zn(){return`2026.10218.11905`}async function Qn(){let e=Zn();if(e===`dev`)return{status:`development`,localVersion:e,remoteVersion:null};let t=await Xn();if(`error`in t)return{status:`current`,localVersion:e,remoteVersion:null,error:t.error};let n=t.version,r=Jn(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 $n(e,t){let{status:n,localVersion:r,remoteVersion:i}=e;switch(n){case`outdated`:t.warn(`Version outdated: ${r} → ${i}. Run 'npm i -g ${Gn()}@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 er(){return new Date().getMinutes()%2==0}function tr(e){er()&&Qn().then(t=>{(t.status===`outdated`||t.error!=null)&&$n(t,e)}).catch(t=>{let n=t instanceof Error?t.message:`Unknown error`;e.error(`Version check failed: ${n}`)})}var nr=class{name=`outdated`;async execute(e){let t=await Qn();return $n(t,e.logger),{success:!0,filesAffected:0,dirsAffected:0,message:`Version status: ${t.status}`}}},rr=class{name=`plugins`;async execute(e){let{logger:t,outputPlugins:r,userConfigOptions:i}=e,a=i.plugins,o=[];for(let e of a)o.push({name:e.name,kind:e.type===Tt.Input?`Input`:`Output`,description:e.name,dependencies:[...e.dependsOn??[]]});let s=new Set(o.map(e=>e.name));for(let e of r)s.has(e.name)||o.push({name:e.name,kind:`Output`,description:e.name,dependencies:[...e.dependsOn??[]]});return n.stdout.write(`${JSON.stringify(o)}\n`),t.info(`plugins listed`,{count:o.length}),{success:!0,filesAffected:0,dirsAffected:0,message:`Listed ${o.length} plugin(s)`}}},ir=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 ar={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 or=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}({}),sr=function(e){return e.Win=`win`,e.Mac=`mac`,e.Linux=`linux`,e.Unknown=`unknown`,e}({});var cr=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=s.platform();return{platform:e,arch:s.arch(),hostname:s.hostname(),homedir:s.homedir(),tmpdir:s.tmpdir(),type:s.type(),release:s.release(),shellKind:this.detectShellKind(),kind:this.detectOsKind(e)}}detectOsKind(e){switch(e){case`win32`:return sr.Win;case`darwin`:return sr.Mac;case`linux`:case`freebsd`:case`openbsd`:case`sunos`:case`aix`:return sr.Linux;default:return sr.Unknown}}detectShellKind(){let e=(n.env.SHELL??n.env.ComSpec??``).toLowerCase();return e.includes(`bash`)?or.Bash:e.includes(`zsh`)?or.Zsh:e.includes(`fish`)?or.Fish:e.includes(`pwsh`)?or.Pwsh:e.includes(`powershell`)?or.PowerShell:e.includes(`cmd`)?or.Cmd:e.endsWith(`/sh`)?or.Sh:or.Unknown}collectEnvContext(){return{...n.env}}collectProfile(){return this.userConfig?.profile==null?{}:this.userConfig.profile}collectToolReferences(){let e={...ar.default};return this.toolPreset===`claudeCode`?{...e,...ar.claudeCode}:this.toolPreset===`kiro`?{...e,...ar.kiro}:e}createMdComponent(){let e=(e=>e.when===!1?null:e.children);return e.Line=e=>e.when===!1?null:e.children,e}};let lr=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 ur=class{registrations=[];globalScope=null;setGlobalScope(e){this.globalScope=e}getGlobalScope(){return this.globalScope}register(e,t,n=lr.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 dr(e){let t=[...e],n=t[0];n!=null&&fr(n)&&t.shift();let r=t[0];return r!=null&&pr(r)&&t.shift(),t}function fr(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 pr(e){return/\.(?:m?[jt]s|cjs)$/.test(e)||/[/\\]/.test(e)&&!e.startsWith(`-`)?!0:/^(?:@[\w-]+\/)?[\w-]+$/.test(e)&&!e.startsWith(`-`)}const mr=new Set([`help`,`version`,`outdated`,`init`,`dry-run`,`clean`,`config`,`plugins`]),hr=new Map([[`--trace`,`trace`],[`--debug`,`debug`],[`--info`,`info`],[`--warn`,`warn`],[`--error`,`error`]]),gr=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4]]);function _r(e){let{logLevelFlags:t}=e;if(t.length===0)return;let n=t[0],r=gr.get(n)??4;for(let e of t){let t=gr.get(e)??4;t<r&&(r=t,n=e)}return n}function vr(e){let{helpFlag:t,versionFlag:n,subcommand:r,dryRun:i,unknownCommand:a,setOption:o,positional:s,showFlag:c}=e;if(n)return new Pn;if(t)return new Ln;if(a!=null)return new ir(a);if(r===`version`)return new Pn;if(r===`help`)return new Ln;if(r===`outdated`)return new nr;if(r===`init`)return new Hn;if(r===`dry-run`)return new jn;if(r===`clean`)return i?new An:new wt;if(r===`plugins`)return new rr;if(r===`config`&&c)return new kn;if(r!==`config`||o.length>0)return new Mn;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 On([...o,...l])}function yr(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=hr.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,mr.has(i)?t.subcommand=i:t.unknownCommand=i;continue}t.positional.push(i)}}return t}var br=class{logger;args;outputPlugins=[];constructor(...e){this.args=yr(dr(e.filter(e=>e!=null)));let t=_r(this.args);t!=null&&sn(t),this.logger=ln(`PluginPipeline`,t),this.logger.debug(`initialized`,{args:this.args})}registerOutputPlugins(e){return this.outputPlugins.push(...e),this}async run(e){tr(this.logger);let{context:t,outputPlugins:n,userConfigOptions:r}=e;this.registerOutputPlugins([...n]);let i=this.resolveCommand();this.args.jsonFlag&&(sn(`silent`),new Set([`config-show`,`plugins`]).has(i.name)||(i=new Un(i)));let a=this.createCommandContext(t,r);await i.execute(a)}resolveCommand(){return vr(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:r,path:i,glob:et.default,collectedInputContext:e,dryRun:t}}createWriteContext(e,t){return{logger:this.logger,fs:r,path:i,glob:et.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 Mt(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 jt(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 cr({userConfig:r}).collect(),o=new ur;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,lr.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.externalProjects==null?e.externalProjects:[...e.externalProjects??[],...t.externalProjects],i=t.ideConfigFiles==null?e.ideConfigFiles:[...e.ideConfigFiles??[],...t.ideConfigFiles],a=t.fastCommands==null?e.fastCommands:[...e.fastCommands??[],...t.fastCommands],o=t.subAgents==null?e.subAgents:[...e.subAgents??[],...t.subAgents],s=t.skills==null?e.skills:[...e.skills??[],...t.skills],c=t.rules==null?e.rules:[...e.rules??[],...t.rules],l=t.aiAgentIgnoreConfigFiles==null?e.aiAgentIgnoreConfigFiles:[...e.aiAgentIgnoreConfigFiles??[],...t.aiAgentIgnoreConfigFiles],u=t.globalMemory??e.globalMemory,d=t.shadowSourceProjectDir??e.shadowSourceProjectDir,f=t.readmePrompts==null?e.readmePrompts:[...e.readmePrompts??[],...t.readmePrompts],p=t.globalGitIgnore??e.globalGitIgnore,m=t.shadowGitExclude??e.shadowGitExclude;return{...n==null?{}:{workspace:n},...r==null?{}:{externalProjects:r},...i==null?{}:{ideConfigFiles:i},...a==null?{}:{fastCommands:a},...o==null?{}:{subAgents:o},...s==null?{}:{skills:s},...c==null?{}:{rules:c},...l==null?{}:{aiAgentIgnoreConfigFiles:l},...u==null?{}:{globalMemory:u},...d==null?{}:{shadowSourceProjectDir:d},...f==null?{}:{readmePrompts:f},...p==null?{}:{globalGitIgnore:p},...m==null?{}:{shadowGitExclude:m}}}};const xr={...Yt,externalProjects:[],excludePatterns:{},fastCommandSeriesOptions:{},plugins:[]};function Sr(e){return{...e.workspaceDir==null?{}:{workspaceDir:e.workspaceDir},...e.shadowSourceProjectDir==null?{}:{shadowSourceProjectDir:e.shadowSourceProjectDir},...e.shadowSkillSourceDir==null?{}:{shadowSkillSourceDir:e.shadowSkillSourceDir},...e.shadowFastCommandDir==null?{}:{shadowFastCommandDir:e.shadowFastCommandDir},...e.shadowSubAgentDir==null?{}:{shadowSubAgentDir:e.shadowSubAgentDir},...e.shadowRulesDir==null?{}:{shadowRulesDir:e.shadowRulesDir},...e.globalMemoryFile==null?{}:{globalMemoryFile:e.globalMemoryFile},...e.shadowProjectsDir==null?{}:{shadowProjectsDir:e.shadowProjectsDir},...e.externalProjects==null?{}:{externalProjects:e.externalProjects},...e.excludePatterns==null?{}:{excludePatterns:e.excludePatterns},...e.fastCommandSeriesOptions==null?{}:{fastCommandSeriesOptions:e.fastCommandSeriesOptions},...e.logLevel==null?{}:{logLevel:e.logLevel}}}function Cr(...e){return e.reduce((e,t)=>wr(e,t),{...xr})}function wr(e,t){let n=t.externalProjects,r=t.plugins,i=t.excludePatterns,a=t.fastCommandSeriesOptions;return{...e,...t,externalProjects:[...e.externalProjects,...n??[]],plugins:[...e.plugins,...r??[]],excludePatterns:Tr(e.excludePatterns,i),fastCommandSeriesOptions:Er(e.fastCommandSeriesOptions,a)}}function Tr(e,t){let n={...e};if(t)for(let[e,r]of Object.entries(t))n[e]=[...n[e]??[],...r];return n}function Er(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 Dr(e){return`pluginOptions`in e||`configLoaderOptions`in e||`loadUserConfig`in e}async function Or(e={}){yn().shouldExit&&n.exit(1);let t,a,o;Dr(e)?({pluginOptions:o={},cwd:a}={pluginOptions:e.pluginOptions,cwd:e.cwd},t=e.loadUserConfig??!0):(o=e,t=!0);let s={},c=!1,l=[],u;if(t){let e=vn(a);c=e.found,l=e.sources,e.found&&(s=Sr(e.config),u=e.config)}let d=Cr(s,o),{plugins:f=[],logLevel:p}=d,m=ln(`defineConfig`,p);c?m.info(`user config loaded`,{sources:l}):m.info(`no user config found, using defaults`,{workspaceDir:xr.workspaceDir,shadowSourceProjectDir:xr.shadowSourceProjectDir,shadowSkillSourceDir:xr.shadowSkillSourceDir,shadowFastCommandDir:xr.shadowFastCommandDir,shadowSubAgentDir:xr.shadowSubAgentDir,globalMemoryFile:xr.globalMemoryFile,shadowProjectsDir:xr.shadowProjectsDir,logLevel:xr.logLevel});let h={logger:m,userConfigOptions:d,fs:r,path:i,glob:et.default},g=f.filter(e=>e.type===Tt.Input),_=f.filter(e=>e.type===Tt.Output),v=await new br().executePluginsInOrder(g,h,!1,u);if(v.workspace==null)throw Error(`Workspace not initialized by any plugin`);let y={workspace:v.workspace,ideConfigFiles:v.ideConfigFiles??[],...v.externalProjects!=null&&{externalProjects:v.externalProjects},...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&&Rn(v.shadowSourceProjectDir,m),{context:y,outputPlugins:_,userConfigOptions:d}}const kr=Rr(/[A-Za-z]/),Ar=Rr(/[\dA-Za-z]/),jr=Rr(/[#-'*+\--9=?A-Z^-~]/);function Mr(e){return e!==null&&(e<32||e===127)}const Nr=Rr(/\d/),Pr=Rr(/[\dA-Fa-f]/),Fr=Rr(/[!-/:-@[-`{-~]/);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 Ir=Rr(/\p{P}|\p{S}/u),Lr=Rr(/\s/);function Rr(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}var zr=S(y(((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 Br=Object.assign(Vr(Error),{eval:Vr(EvalError),range:Vr(RangeError),reference:Vr(ReferenceError),syntax:Vr(SyntaxError),type:Vr(TypeError),uri:Vr(URIError)});function Vr(e){return t.displayName=e.displayName||e.name,t;function t(t,...n){return new e(t&&(0,zr.default)(t,...n))}}const Hr={}.hasOwnProperty,Ur={yaml:`-`,toml:`+`};function Wr(e){let t=[],n=-1,r=Array.isArray(e)?e:e?[e]:[`yaml`];for(;++n<r.length;)t[n]=Gr(r[n]);return t}function Gr(e){let t=e;if(typeof t==`string`){if(!Hr.call(Ur,t))throw Br("Missing matter definition for `%s`",t);t={type:t,marker:Ur[t]}}else if(typeof t!=`object`)throw Br("Expected matter to be an object, not `%j`",t);if(!Hr.call(t,`type`))throw Br("Missing `type` in matter `%j`",t);if(!Hr.call(t,`fence`)&&!Hr.call(t,`marker`))throw Br("Missing `marker` or `fence` in matter `%j`",t);return t}function Kr(e){let t=Wr(e),n={},r=-1;for(;++r<t.length;){let e=t[r],i=Jr(e,`open`).charCodeAt(0),a=qr(e),o=n[i];Array.isArray(o)?o.push(a):n[i]=[a]}return{flow:n}}function qr(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=Jr(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=Jr(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 Jr(e,t){return e.marker?Yr(e.marker,t).repeat(3):Yr(e.fence,t)}function Yr(e,t){return typeof e==`string`?e:e[t]}function Xr(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function Zr(e){let t=Wr(e),n={},r={},i=-1;for(;++i<t.length;){let e=t[i];n[e.type]=Qr(e),r[e.type]=$r,r[e.type+`Value`]=ei}return{enter:n,exit:r}}function Qr(e){return t;function t(t){this.enter({type:e.type,value:``},t),this.buffer()}}function $r(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 ei(e){this.config.enter.data.call(this,e),this.config.exit.data.call(this,e)}function ti(e){let t=[],n={},r=Wr(e),i=-1;for(;++i<r.length;){let e=r[i];n[e.type]=ni(e);let a=ri(e,`open`);t.push({atBreak:!0,character:a.charAt(0),after:Xr(a.charAt(1))})}return{unsafe:t,handlers:n}}function ni(e){let t=ri(e,`open`),n=ri(e,`close`);return r;function r(e){return t+(e.value?`
|
|
1013
1013
|
`+e.value:``)+`
|
|
1014
1014
|
`+n}}function ri(e,t){return e.marker?ii(e.marker,t).repeat(3):ii(e.fence,t)}function ii(e,t){return typeof e==`string`?e:e[t]}function ai(e){let t=this,n=e||`yaml`,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(Kr(n)),a.push(Zr(n)),o.push(ti(n))}function oi(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 si=(function(e){if(e==null)return fi;if(typeof e==`function`)return di(e);if(typeof e==`object`)return Array.isArray(e)?ci(e):li(e);if(typeof e==`string`)return ui(e);throw Error(`Expected function, string, or object as test`)});function ci(e){let t=[],n=-1;for(;++n<e.length;)t[n]=si(e[n]);return di(r);function r(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}function li(e){let t=e;return di(n);function n(n){let r=n,i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function ui(e){return di(t);function t(t){return t&&t.type===e}}function di(e){return t;function t(t,n,r){return!!(pi(t)&&e.call(this,t,typeof n==`number`?n:void 0,r||void 0))}}function fi(){return!0}function pi(e){return typeof e==`object`&&!!e&&`type`in e}function mi(e){return`\x1B[33m`+e+`\x1B[39m`}const hi=[];function gi(e,t,n,r){let i;typeof t==`function`&&typeof n!=`function`?(r=n,n=t):i=t;let a=si(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 (`+mi(e.type+(t?`<`+t+`>`:``))+`)`})}return u;function u(){let l=hi,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=_i(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 _i(e){return Array.isArray(e)?e:typeof e==`number`?[!0,e]:e==null?hi:[e]}function vi(e,t,n){let r=si((n||{}).ignore||[]),i=yi(t),a=-1;for(;++a<i.length;)gi(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 yi(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([bi(e[0]),xi(e[1])])}return t}function bi(e){return typeof e==`string`?new RegExp(Xr(e),`g`):e}function xi(e){return typeof e==`function`?e:function(){return e}}const Si=`phrasing`,Ci=[`autolink`,`link`,`image`,`label`];function wi(){return{transforms:[Mi],enter:{literalAutolink:Ei,literalAutolinkEmail:Di,literalAutolinkHttp:Di,literalAutolinkWww:Di},exit:{literalAutolink:ji,literalAutolinkEmail:Ai,literalAutolinkHttp:Oi,literalAutolinkWww:ki}}}function Ti(){return{unsafe:[{character:`@`,before:`[+\\-.\\w]`,after:`[\\-.\\w]`,inConstruct:Si,notInConstruct:Ci},{character:`.`,before:`[Ww]`,after:`[\\-.\\w]`,inConstruct:Si,notInConstruct:Ci},{character:`:`,before:`[ps]`,after:`\\/`,inConstruct:Si,notInConstruct:Ci}]}}function Ei(e){this.enter({type:`link`,title:null,url:``,children:[]},e)}function Di(e){this.config.enter.autolinkProtocol.call(this,e)}function Oi(e){this.config.exit.autolinkProtocol.call(this,e)}function ki(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 Ai(e){this.config.exit.autolinkEmail.call(this,e)}function ji(e){this.exit(e)}function Mi(e){vi(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Ni],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,Pi]],{ignore:[`link`,`linkReference`]})}function Ni(e,t,n,r,i){let a=``;if(!Li(i)||(/^w/i.test(t)&&(n=t+n,t=``,a=`http://`),!Fi(n)))return!1;let o=Ii(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 Pi(e,t,n,r){return!Li(r,!0)||/[-\d_]$/.test(n)?!1:{type:`link`,title:null,url:`mailto:`+t+`@`+n,children:[{type:`text`,value:t+`@`+n}]}}function Fi(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 Ii(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=oi(e,`(`),a=oi(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 Li(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||Lr(n)||Ir(n))&&(!t||n!==47)}function Ri(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}Ji.peek=qi;function zi(){this.buffer()}function Bi(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function Vi(){this.buffer()}function Hi(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function Ui(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ri(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Wi(e){this.exit(e)}function Gi(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ri(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Ki(e){this.exit(e)}function qi(){return`[`}function Ji(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 Yi(){return{enter:{gfmFootnoteCallString:zi,gfmFootnoteCall:Bi,gfmFootnoteDefinitionLabelString:Vi,gfmFootnoteDefinition:Hi},exit:{gfmFootnoteCallString:Ui,gfmFootnoteCall:Wi,gfmFootnoteDefinitionLabelString:Gi,gfmFootnoteDefinition:Ki}}}function Xi(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Ji},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?`
|
|
1015
1015
|
`:` `)+r.indentLines(r.containerFlow(e,a.current()),t?Qi:Zi))),s(),o}}function Zi(e,t,n){return t===0?e:Qi(e,t,n)}function Qi(e,t,n){return(n?``:` `)+e}const $i=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`];ia.peek=aa;function ea(){return{canContainEols:[`delete`],enter:{strikethrough:na},exit:{strikethrough:ra}}}function ta(){return{unsafe:[{character:`~`,inConstruct:`phrasing`,notInConstruct:$i}],handlers:{delete:ia}}}function na(e){this.enter({type:`delete`,children:[]},e)}function ra(e){this.exit(e)}function ia(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 aa(){return`~`}function oa(e){return e.length}function sa(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||oa,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=ca(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]=la(r[d]);else{let e=la(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(`
|
|
@@ -1197,7 +1197,9 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
1197
1197
|
|
|
1198
1198
|
`,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 Ig=`AGENTS.md`;var Lg=class extends Fg{constructor(){super(`AgentsOutputPlugin`,{outputFileName:Ig})}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,Ig)),e.childMemoryPrompts!=null)for(let n of e.childMemoryPrompts)n.dir!=null&&this.isRelativePath(n.dir)&&t.push(this.createFileRelativePath(n.dir,Ig));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}}},Rg=class extends Pg{inputEffects=[];registeredScopes=[];constructor(e,t){super(e,Tt.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:u,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.shadowSourceProjectDir;return{workspaceDir:n,shadowProjectDir:this.resolvePath(r,n,``)}}resolvePath(e,t,n){let r=e;return r.startsWith(Jt.USER_HOME)&&(r=r.replace(Jt.USER_HOME,s.homedir())),r.includes(Jt.SHADOW_SOURCE_PROJECT)&&(r=r.replace(Jt.SHADOW_SOURCE_PROJECT,n)),r.includes(Jt.WORKSPACE)&&(r=r.replace(Jt.WORKSPACE,t)),i.normalize(r)}readAndParseMarkdown(e,t){return Mg(t.readFileSync(e,`utf8`))}};const zg=[`.qoderignore`,`.cursorignore`,`.kiroignore`,`.warpindexignore`,`.aiignore`,`.codeignore`,`.traeignore`];var Bg=class extends Rg{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 zg){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 Vg=`.agent`,Hg=`antigravity`,Ug=`skills`,Wg=`workflows`,Gg=`mcp_config.json`,Kg=[Ug,Wg];var qg=class extends Fg{constructor(){super(`AntigravityOutputPlugin`,{globalConfigDir:Vg,outputFileName:``,dependsOn:[`GeminiCLIOutputPlugin`]}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=i.join(this.getAntigravityDir(),Gg),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 i.join(s.homedir(),`.gemini`,Hg)}async registerProjectOutputDirs(e){let{projects:t}=e.collectedInputContext.workspace,n=[];for(let e of t)if(e.dirFromWorkspacePath!=null)for(let t of Kg)n.push(this.createRelativePath(i.join(e.dirFromWorkspacePath.path,Vg,t),e.dirFromWorkspacePath.basePath,()=>t));return n}async registerProjectOutputFiles(e){let{skills:t,fastCommands:n}=e.collectedInputContext,r=this.getAntigravityDir(),a=[];if(t!=null)for(let e of t){let t=e.yamlFrontMatter?.name??e.dir.getDirectoryName(),n=i.join(r,Ug,t);if(a.push(this.createRelativePath(`SKILL.md`,n,()=>t)),e.childDocs!=null)for(let r of e.childDocs)a.push(this.createRelativePath(r.dir.path.replace(/\.mdx$/,`.md`),n,()=>t));if(e.resources!=null)for(let r of e.resources)a.push(this.createRelativePath(r.relativePath,n,()=>t))}if(t?.some(e=>e.mcpConfig!=null)&&a.push(this.createRelativePath(Gg,r,()=>Hg)),n==null)return a;let o=this.getTransformOptionsFromContext(e),s=i.join(r,Wg);for(let e of n)a.push(this.createRelativePath(this.transformFastCommandName(e,o),s,()=>Wg));return a}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=[],a=this.getAntigravityDir();if(t!=null){let n=i.join(a,Wg);for(let i of t)r.push(await this.writeFastCommand(e,n,i))}if(n!=null){let t=i.join(a,Ug);for(let i of n)r.push(...await this.writeSkill(e,t,i));let o=await this.writeGlobalMcpConfig(e,a,n);o!=null&&r.push(o)}return this.log.info({action:`write`,message:`Synced ${r.length} files`,globalDir:a}),{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 a=i.join(t,Gg),o=JSON.stringify({mcpServers:r},null,2);return this.writeFile(e,a,o,`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),a=this.transformFastCommandName(n,r),o=i.join(t,a),s=typeof n.yamlFrontMatter?.description==`string`?{description:n.yamlFrontMatter.description}:{},c;if(n.rawMdxContent!=null){let e=n.rawMdxContent.replace(/^---\n[\s\S]*?\n---\n/,``);c=this.buildMarkdownContentWithRaw(e,s,n.rawFrontMatter)}else c=this.buildMarkdownContentWithRaw(n.content,s,n.rawFrontMatter);return this.writeFile(e,o,c,`fastCommand`)}async writeSkill(e,t,n){let r=[],a=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),o=i.join(t,a),s=i.join(o,`SKILL.md`),c=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);if(r.push(await this.writeFile(e,s,c,`skill`)),n.childDocs!=null)for(let t of n.childDocs){let n=t.dir.path.replace(/\.mdx$/,`.md`);r.push(await this.writeFile(e,i.join(o,n),t.content,`skillRefDoc`))}if(n.resources!=null)for(let t of n.resources)r.push(await this.writeFile(e,i.join(o,t.relativePath),t.content,`skillResource`));return r}},Jg=class extends Error{constructor(e,t,n){super(e),this.expression=t,this.filePath=n,this.name=`ScopeError`}},Yg=class extends Jg{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`}},Xg=class extends Jg{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`}},Zg=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`}},Qg=Object.defineProperty,$g=(e,t)=>{let n={};for(var r in e)Qg(n,r,{get:e[r],enumerable:!0});return t||Qg(n,Symbol.toStringTag,{value:`Module`}),n};const e_=new Map;function t_(e,t){e_.set(e,t)}function n_(){return new Map(e_)}function r_(e){return e_.has(e)}function i_(e,t,n){let r=e.trim();return r===``?``:/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/i.test(r)?a_(r,t,n?.filePath):o_(r,t,n?.filePath)}function a_(e,t,n){let r=e.split(`.`),i=r[0];if(i==null||!(i in t))throw new Xg(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 Yg(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 Yg(i,e,n);a=o[i]}return s_(a)}function o_(e,t,n){let r=Object.keys(t),i=r.map(e=>t[e]);try{return s_(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 Xg(t[1],e,n)}let i=n==null?``:` (file: ${n})`;throw Error(`Failed to evaluate expression: "${e}"${i}\nCause: ${r}`)}}function s_(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 c_(e,t){return e===null?!1:t.components.has(e)||r_(e)}async function l_(e){return async(t,n)=>(await e({type:`root`,children:t},n)).children}async function u_(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 l_(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 d_(e,t){let n=e.name?.toLowerCase();if(n==null)return null;switch(n){case`pre`:return m_(e,t);case`a`:return h_(e,t);case`strong`:case`b`:return g_(e,t);case`em`:case`i`:return __(e,t);case`img`:return v_(e,t);case`blockquote`:return y_(e,t);default:return null}}function f_(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`?i_(r.value.value,n.scope):r.value===null?``:null}function p_(e,t){let n=``;for(let r of e.children)r.type===`text`?n+=r.value:r.type===`mdxTextExpression`?n+=i_(r.value,t.scope):(r.type===`mdxJsxFlowElement`||r.type===`mdxJsxTextElement`)&&(n+=p_(r,t));return n}function m_(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=f_(n,`className`,t)??``,i=/language-(\w+)/.exec(r)?.[1],a=p_(n,t);return[{type:`code`,lang:i??null,value:a.trim()}]}function h_(e,t){let n=f_(e,`href`,t);if(n==null||n===``)return null;let r=p_(e,t);return[{type:`paragraph`,children:[{type:`link`,url:n,title:f_(e,`title`,t)??null,children:[{type:`text`,value:r}]}]}]}function g_(e,t){let n={type:`strong`,children:[{type:`text`,value:p_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function __(e,t){let n={type:`emphasis`,children:[{type:`text`,value:p_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function v_(e,t){let n=f_(e,`src`,t);if(n==null||n===``)return null;let r={type:`image`,url:n,alt:f_(e,`alt`,t)??``,title:f_(e,`title`,t)??null};return e.type,[{type:`paragraph`,children:[r]}]}function y_(e,t){return[{type:`blockquote`,children:[{type:`paragraph`,children:[{type:`text`,value:p_(e,t)}]}]}]}function b_(e){return e==null?!1:JSON.stringify(e).includes(`"JSX`)}async function x_(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`?S_(i.expression,t,n):[]}async function S_(e,t,n){return e.type===`JSXElement`?O_(e,t,n):e.type===`JSXFragment`?k_(e,t,n):e.type===`LogicalExpression`?C_(e,t,n):e.type===`ConditionalExpression`?w_(e,t,n):e.type===`SequenceExpression`?T_(e,t,n):e.type===`ArrayExpression`?E_(e,t,n):R_(e,t)}async function C_(e,t,n){let r=await D_(e.left,t,n);return e.operator===`&&`?I_(r)?S_(e.right,t,n):[]:e.operator===`||`?I_(r)?F_(e.left)?S_(e.left,t,n):L_(r):S_(e.right,t,n):e.operator===`??`?r==null?S_(e.right,t,n):F_(e.left)?S_(e.left,t,n):L_(r):[]}async function w_(e,t,n){return I_(await D_(e.test,t,n))?S_(e.consequent,t,n):S_(e.alternate,t,n)}async function T_(e,t,n){let r=[];for(let i of e.expressions){let e=await S_(i,t,n);r.push(...e)}return r}async function E_(e,t,n){let r=[];for(let i of e.elements)if(i!=null)if(i.type===`SpreadElement`){let e=await S_(i.argument,t,n);r.push(...e)}else{let e=await S_(i,t,n);r.push(...e)}return r}async function D_(e,t,n){if(F_(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 D_(e.argument,t,n);return e.operator===`!`?!I_(r):e.operator===`-`?-r:e.operator===`+`?+r:e.operator===`typeof`?typeof r:void 0}if(e.type===`BinaryExpression`){let r=await D_(e.left,t,n),i=await D_(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 D_(e.left,t,n);return e.operator===`&&`?I_(r)?D_(e.right,t,n):r:e.operator===`||`?I_(r)?r:D_(e.right,t,n):e.operator===`??`?r??D_(e.right,t,n):void 0}if(e.type===`MemberExpression`){let r=await D_(e.object,t,n);if(r==null)return;if(e.computed)return r[await D_(e.property,t,n)];let{name:i}=e.property;return r[i]}if(e.type===`ConditionalExpression`)return I_(await D_(e.test,t,n))?D_(e.consequent,t,n):D_(e.alternate,t,n);let r=P_(e);if(r!==``)try{let e=i_(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 O_(e,t,n){let r=j_(e,t);if(r.name!=null&&c_(r.name,t)){let{processAst:e}=await Promise.resolve().then(()=>z_);return u_(r,t,e)}return d_(r,t)??(r.children.length>0?n(r.children,t):[])}async function k_(e,t,n){let r=[];for(let i of e.children){let e=await A_(i,t,n);r.push(...e)}return r}async function A_(e,t,n){if(e.type===`JSXElement`)return O_(e,t,n);if(e.type===`JSXFragment`)return k_(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`?[]:S_(e.expression,t,n):e.type===`JSXSpreadChild`?S_(e.expression,t,n):[]}function j_(e,t){let n=e.openingElement,r=null;n.name.type===`JSXIdentifier`?{name:r}=n.name:n.name.type===`JSXMemberExpression`?r=M_(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:P_(e.value.expression)}),i.push({type:`mdxJsxAttribute`,name:t,value:n})}else e.type===`JSXSpreadAttribute`&&i.push({type:`mdxJsxExpressionAttribute`,value:`...${P_(e.argument)}`});let a=[];for(let n of e.children){let e=N_(n,t);e!=null&&a.push(...e)}return{type:`mdxJsxFlowElement`,name:r,attributes:i,children:a}}function M_(e){return e.object.type===`JSXIdentifier`?`${e.object.name}.${e.property.name}`:`${M_(e.object)}.${e.property.name}`}function N_(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[j_(e,t)];if(e.type===`JSXFragment`){let n=[];for(let r of e.children){let e=N_(r,t);e!=null&&n.push(...e)}return n}return e.type===`JSXExpressionContainer`?e.expression.type===`JSXEmptyExpression`?null:[{type:`paragraph`,children:[{type:`text`,value:P_(e.expression)}]}]:e.type===`JSXSpreadChild`?[{type:`paragraph`,children:[{type:`text`,value:`...${P_(e.expression)}`}]}]:null}function P_(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=P_(e.object);return e.computed?`${t}[${P_(e.property)}]`:`${t}.${e.property.name}`}if(e.type===`CallExpression`)return`${P_(e.callee)}(${e.arguments.map(e=>P_(e)).join(`, `)})`;if(e.type===`BinaryExpression`||e.type===`LogicalExpression`){let t=P_(e.left),n=P_(e.right);return`(${t} ${e.operator} ${n})`}if(e.type===`UnaryExpression`){let t=P_(e.argument);return`${e.operator}${t}`}if(e.type===`ConditionalExpression`)return`(${P_(e.test)} ? ${P_(e.consequent)} : ${P_(e.alternate)})`;if(e.type===`ArrayExpression`)return`[${e.elements.filter(e=>e!=null&&e.type!==`SpreadElement`).map(e=>P_(e)).join(`, `)}]`;if(e.type===`ObjectExpression`)return`{${e.properties.filter(e=>e.type===`Property`).map(e=>`${e.key.type===`Identifier`?e.key.name:P_(e.key)}: ${P_(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+=`\${${P_(e.expressions[n])}}`);return t+="`",t}return e.type===`SpreadElement`?`...${P_(e.argument)}`:``}function F_(e){return e.type===`JSXElement`||e.type===`JSXFragment`}function I_(e){return!!e}function L_(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 R_(e,t){let n=P_(e);if(n===``)return[];try{return L_(i_(n,t.scope))}catch{return[]}}var z_=$g({processAst:()=>V_});function B_(e){if(!(e.includes(`/`)&&/\.\w+$/.test(e)))return e;let t=e.lastIndexOf(`/`);return e.slice(t+1)}async function V_(e,t){return H_(e,t)}async function H_(e,t){let n=[];for(let r of e.children){let e=await U_(r,t);n.push(...e)}return{type:`root`,children:n}}async function U_(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(b_(r))return x_(n,t,async(e,t)=>(await V_({type:`root`,children:e},t)).children);let a=i_(n.value,t.scope);return a===``?[]:[{type:`paragraph`,children:[{type:`text`,value:a}]}]}if(e.type===`mdxJsxFlowElement`)return W_(e,t);if(e.type===`link`){let n=e,r=(await G_(n.children,t)).map(e=>e.type===`text`?{...e,value:B_(e.value)}:e);return[{...n,children:r}]}if(!(`children`in e&&Array.isArray(e.children)))return[e];let n=await G_(e.children,t);return[{...e,children:n}]}async function W_(e,t){return e.name!=null&&c_(e.name,t)?u_(e,t,V_):d_(e,t)??[]}async function G_(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(b_(i)){let r=await x_(e,t,async(e,t)=>(await V_({type:`root`,children:e},t)).children);for(let e of r)n.push(e);continue}let o=i_(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:i_(e.value,t.scope)};n.push(a);continue}if(r.type===`mdxJsxTextElement`){let e=r;if(e.name!=null&&c_(e.name,t)){let r=await u_(e,t,V_);for(let e of r)e.type===`paragraph`&&`children`in e?n.push(...e.children):n.push(e);continue}let i=d_(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 G_(r.children,t);if(r.type===`link`){let t=e.map(e=>e.type===`text`?{...e,value:B_(e.value)}:e);n.push({...r,children:t});continue}n.push({...r,children:e});continue}n.push(r)}return n}function K_(e){let t=this;t.compiler=n;function n(n){return Vo(n,{...t.data(`settings`),...e,extensions:t.data(`toMarkdownExtensions`)||[]})}}function q_(e,t={}){let n={},{yamlFrontMatter:r,scope:i,filePath:a}=t;for(let t of e){let e=J_(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 J_(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=Y_(i,e);if(o!=null)try{let e=X_(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=Y_(i,s.index+s[0].length);if(a==null){s=o.exec(i);continue}try{let i=X_(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 Y_(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===`
|
|
1199
1199
|
`){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 X_(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 Z_(r.slice(1,-1),`"`);if(r.startsWith(`'`)&&r.endsWith(`'`))return Z_(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 Z_(e,"`")}if(r.startsWith(`[`)&&r.endsWith(`]`))return $_(r,t,n);if(r.startsWith(`{`)&&r.endsWith(`}`))return ev(r,t,n);if(/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/i.test(r))return Q_(r,t,n);let i=n==null?``:` in file "${n}"`;throw Error(`Expression "${r}" cannot be statically evaluated${i}`)}function Z_(e,t){return e.replaceAll(`\\n`,`
|
|
1200
|
-
`).replaceAll(`\\r`,`\r`).replaceAll(`\\t`,` `).replaceAll(`\\"`,`"`).replaceAll(`\\'`,`'`).replaceAll(`\\\\`,`\\`)}function Q_(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 $_(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return[];if(t==null)try{let t=tv(e),n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return nv(r).map(e=>X_(e.trim(),t,n))}function ev(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return{};if(t==null)try{let t=tv(e),n=JSON.parse(t);if(typeof n==`object`&&n&&!Array.isArray(n))return n}catch{}let i={},a=rv(r);for(let e of a){let r=iv(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]=X_(o,t,n)}return i}function tv(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 nv(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 rv(e){return nv(e)}function iv(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 av(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=i_(n.value.value,t.scope);return e===`true`||e===`1`}catch{return!1}return!1}async function ov(e,t,n){return!av(e,t)||e.children.length===0?[]:n(e.children,t)}async function sv(e,t){if(!av(e,t)||e.children.length===0)return[];let n=cv(e.children,t);return n===``?[]:[{type:`text`,value:n}]}function cv(e,t){let n=``;for(let r of e)if(r.type===`text`)n+=r.value;else if(r.type===`mdxTextExpression`)try{n+=i_(r.value,t.scope)}catch{}else `children`in r&&Array.isArray(r.children)&&(n+=cv(r.children,t));return n}function lv(){t_(`Md`,ov),t_(`Md.Line`,sv)}lv();function uv(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 dv(e,t){let n=fh(e),r=uv(t?.globalScope,t?.scope),i=n_(),a;if(t?.extractMetadata===!0){let e=n.children.find(e=>e.type===`yaml`),i;if(e!=null)try{i=kg.parse(e.value)}catch{}a=q_(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 V_(n,{scope:r,components:i,processingStack:[],...t?.basePath!=null&&{basePath:t.basePath}}),s=mu().use(ai,[`yaml`]).use(Jl).use(K_,{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 fv=class extends Fg{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=i.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:a,subAgents:o,skills:s}=e.collectedInputContext,c={includeSeriesPrefix:!0};if(this.supportsFastCommands&&a!=null)for(let e of a){let t=this.transformFastCommandName(e,c);r.push(this.createRelativePath(i.join(this.commandsSubDir,t),n,()=>this.commandsSubDir))}if(this.supportsSubAgents&&o!=null)for(let e of o){let t=e.dir.path.replace(/\.mdx$/,`.md`);r.push(this.createRelativePath(i.join(this.agentsSubDir,t),n,()=>this.agentsSubDir))}if(this.supportsSkills&&s!=null)for(let e of s){let t=e.yamlFrontMatter?.name??e.dir.getDirectoryName(),a=i.join(this.skillsSubDir,t);if(r.push(this.createRelativePath(i.join(a,`SKILL.md`),n,()=>t)),e.childDocs!=null)for(let o of e.childDocs){let e=o.dir.path.replace(/\.mdx$/,`.md`),s=i.join(a,e);r.push(this.createRelativePath(s,n,()=>t))}if(e.resources!=null)for(let o of e.resources){let e=i.join(a,o.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:a,subAgents:o,skills:s}=e.collectedInputContext,c=this.getGlobalConfigDir();if(t!=null){let r=i.join(c,this.outputFileName),a=this.createRelativePath(this.outputFileName,c,()=>this.globalConfigDir);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`globalMemory`,path:r}),n.push({path:a,success:!0,skipped:!1});else try{ut(r,t.content),this.log.trace({action:`write`,type:`globalMemory`,path:r}),n.push({path:a,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:a,success:!1,error:e})}}if(this.supportsFastCommands&&a!=null)for(let t of a){let r=await this.writeFastCommand(e,c,t);n.push(...r)}if(this.supportsSubAgents&&o!=null)for(let t of o){let r=await this.writeSubAgent(e,c,t);n.push(...r)}if(this.supportsSkills&&s!=null)for(let t of s){let r=await this.writeSkill(e,c,t);n.push(...r)}return{files:n,dirs:r}}async writeFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),a=this.transformFastCommandName(n,r),o=i.join(t,this.commandsSubDir),s=i.join(o,a),c=n.content,l=n.yamlFrontMatter,u=!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 cr({toolPreset:this.toolPreset}).collect(),t=await dv(n.rawMdxContent,{globalScope:e,extractMetadata:!0,basePath:n.dir.basePath});c=t.content,l=t.metadata.fields,u=!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 d=u?this.buildMarkdownContent(c,l):this.buildMarkdownContentWithRaw(c,l,n.rawFrontMatter);return[await this.writeFile(e,s,d,`fastCommand`)]}async writeSubAgent(e,t,n){let r=n.dir.path.replace(/\.mdx$/,`.md`),a=i.join(t,this.agentsSubDir),o=i.join(a,r),s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);return[await this.writeFile(e,o,s,`subAgent`)]}async writeSkill(e,t,n){let r=[],a=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),o=i.join(t,this.skillsSubDir,a),s=i.join(o,`SKILL.md`),c=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter),l=await this.writeFile(e,s,c,`skill`);if(r.push(l),n.childDocs!=null)for(let i of n.childDocs){let n=await this.writeSkillReferenceDocument(e,o,a,i,t);r.push(...n)}if(n.resources!=null)for(let i of n.resources){let n=await this.writeSkillResource(e,o,a,i,t);r.push(...n)}return r}async writeSkillReferenceDocument(e,t,n,r,a){let o=r.dir.path.replace(/\.mdx$/,`.md`),s=i.join(t,o);return[await this.writeFile(e,s,r.content,`skillRefDoc`)]}async writeSkillResource(e,t,n,r,a){let o=i.join(t,r.relativePath);return[await this.writeFile(e,o,r.content,`skillResource`)]}},pv=class extends fv{constructor(){super(`ClaudeCodeCLIOutputPlugin`,{globalConfigDir:`.claude`,outputFileName:`CLAUDE.md`,toolPreset:`claudeCode`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0})}};const mv=`AGENTS.md`,hv=`.codex`,gv=`prompts`,_v=`skills`;var vv=class extends Fg{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(i.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,a=[],o=this.getGlobalConfigDir();if(t!=null){let n=i.join(o,mv),r=await this.writeFile(e,n,t.content,`globalMemory`);a.push(r)}if(n!=null&&n.length>0)for(let t of n){let n=await this.writeGlobalFastCommand(e,o,t);a.push(n)}if(r!=null&&r.length>0)for(let t of r){let n=await this.writeGlobalSkill(e,o,t);a.push(...n)}return{files:a,dirs:[]}}async writeGlobalFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),a=this.transformFastCommandName(n,r),o=i.join(t,gv,a),s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);return this.writeFile(e,o,s,`globalFastCommand`)}async writeGlobalSkill(e,t,n){let r=[],a=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),o=i.join(t,_v,a),s=i.join(o,`SKILL.md`),c=this.buildCodexSkillContent(n),l=await this.writeFile(e,s,c,`globalSkill`);if(r.push(l),n.childDocs!=null)for(let t of n.childDocs){let n=t.dir.path.replace(/\.mdx$/,`.md`),a=i.join(o,n),s=await this.writeFile(e,a,t.content,`skillRefDoc`);r.push(s)}if(n.resources!=null)for(let t of n.resources){let n=i.join(o,t.relativePath),a=await this.writeFile(e,n,t.content,`skillResource`);r.push(a)}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(` `)),jg(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 Fg{constructor(){super(`CursorOutputPlugin`,{globalConfigDir:yv,outputFileName:``,dependsOn:[`AgentsOutputPlugin`],indexignore:`.cursorignore`}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=this.getGlobalConfigDir(),n=i.join(t,bv),a={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),r.writeFileSync(n,JSON.stringify(a,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:a,rules:o}=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(a!=null&&a.length>0)for(let e of a){let r=e.yamlFrontMatter.name;if(this.isPreservedSkill(r))continue;let a=i.join(n,wv,r);t.push({pathKind:L.Relative,path:i.join(wv,r),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>a})}let s=o?.filter(e=>e.scope===`global`);if(s==null||s.length===0)return t;let c=i.join(n,Sv);return t.push({pathKind:L.Relative,path:Sv,basePath:n,getDirectoryName:()=>Sv,getAbsolutePath:()=>c}),t}async registerGlobalOutputFiles(e){let t=[],n=this.getGlobalConfigDir(),{skills:r,fastCommands:a}=e.collectedInputContext;if(r?.some(e=>e.mcpConfig!=null)??!1){let e=i.join(n,bv);t.push({pathKind:L.Relative,path:bv,basePath:n,getDirectoryName:()=>yv,getAbsolutePath:()=>e})}if(a!=null&&a.length>0){let r=this.getGlobalCommandsDir(),o=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});for(let e of a){let a=this.transformFastCommandName(e,o),s=i.join(r,a);t.push({pathKind:L.Relative,path:i.join(xv,a),basePath:n,getDirectoryName:()=>xv,getAbsolutePath:()=>s})}}let o=e.collectedInputContext.rules?.filter(e=>e.scope===`global`);if(o!=null&&o.length>0){let e=i.join(n,Sv);for(let r of o){let a=this.buildRuleFileName(r),o=i.join(e,a);t.push({pathKind:L.Relative,path:i.join(Sv,a),basePath:n,getDirectoryName:()=>Sv,getAbsolutePath:()=>o})}}if(r==null||r.length===0)return t;let s=this.getSkillsCursorDir();for(let e of r){let r=e.yamlFrontMatter.name;if(this.isPreservedSkill(r))continue;let a=i.join(s,r);if(t.push({pathKind:L.Relative,path:i.join(wv,r,Tv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i.join(a,Tv)}),e.mcpConfig!=null&&t.push({pathKind:L.Relative,path:i.join(wv,r,bv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i.join(a,bv)}),e.childDocs!=null)for(let o of e.childDocs){let e=o.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:i.join(wv,r,e),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i.join(a,e)})}if(e.resources!=null)for(let o of e.resources)t.push({pathKind:L.Relative,path:i.join(wv,r,o.relativePath),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i.join(a,o.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,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,a=[],o=[];if(t!=null&&t.length>0){let n=await this.writeGlobalMcpConfig(e,t);n!=null&&a.push(n);let r=this.getSkillsCursorDir();for(let n of t){let t=n.yamlFrontMatter.name;if(this.isPreservedSkill(t))continue;let i=await this.writeGlobalSkill(e,r,n);a.push(...i)}}if(n!=null&&n.length>0){let t=this.getGlobalCommandsDir();for(let r of n){let n=await this.writeGlobalFastCommand(e,t,r);a.push(n)}}let s=r?.filter(e=>e.scope===`global`);if(s==null||s.length===0)return{files:a,dirs:o};let c=i.join(this.getGlobalConfigDir(),Sv);for(let t of s){let n=await this.writeRuleMdcFile(e,c,t,this.getGlobalConfigDir());a.push(n)}return{files:a,dirs:o}}async writeProjectOutputs(e){let t=[],n=[],{workspace:r,globalMemory:a,rules:o}=e.collectedInputContext;if(a!=null){let n=this.buildGlobalRuleContent(a.content);for(let i of r.projects){if(i.dirFromWorkspacePath==null)continue;let r=await this.writeProjectGlobalRule(e,i,n);t.push(r)}}let s=o?.filter(e=>e.scope===`project`);if(s!=null&&s.length>0)for(let n of r.projects){let r=n.dirFromWorkspacePath;if(r==null)continue;let a=i.join(r.basePath,r.path,yv,Sv);for(let n of s){let i=await this.writeRuleMdcFile(e,a,n,r.basePath);t.push(i)}}let c=await this.writeProjectIgnoreFiles(e);return t.push(...c),{files:t,dirs:n}}createProjectRulesDirRelativePath(e){let t=i.join(e.path,yv,Sv);return{pathKind:L.Relative,path:t,basePath:e.basePath,getDirectoryName:()=>Sv,getAbsolutePath:()=>i.join(e.basePath,t)}}createProjectRuleFileRelativePath(e,t){let n=i.join(e.path,yv,Sv,t);return{pathKind:L.Relative,path:n,basePath:e.basePath,getDirectoryName:()=>Sv,getAbsolutePath:()=>i.join(e.basePath,n)}}buildGlobalRuleContent(e){return jg({description:`Global prompt (synced)`,alwaysApply:!0},e)}async writeProjectGlobalRule(e,t,n){let r=t.dirFromWorkspacePath,a=i.join(r.basePath,r.path,yv,Sv),o=i.join(a,Cv),s=this.createProjectRuleFileRelativePath(r,Cv);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalRule`,path:o}),{path:s,success:!0,skipped:!1};try{return this.ensureDirectory(a),this.writeFileSync(o,n),this.log.trace({action:`write`,type:`globalRule`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalRule`,path:o,error:t}),{path:s,success:!1,error:e}}}isPreservedSkill(e){return Ev.has(e)}getSkillsCursorDir(){return i.join(this.getGlobalConfigDir(),wv)}getGlobalCommandsDir(){return i.join(this.getGlobalConfigDir(),xv)}async writeGlobalFastCommand(e,t,n){let a=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),o=this.transformFastCommandName(n,a),s=i.join(t,o),c={pathKind:L.Relative,path:i.join(xv,o),basePath:this.getGlobalConfigDir(),getDirectoryName:()=>xv,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{return this.ensureDirectory(t),r.writeFileSync(s,l),this.log.trace({action:`write`,type:`globalFastCommand`,path:s}),{path:c,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalFastCommand`,path:s,error:t}),{path:c,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 a=this.getGlobalConfigDir(),o=i.join(a,bv),s={pathKind:L.Relative,path:bv,basePath:a,getDirectoryName:()=>yv,getAbsolutePath:()=>o},c={};try{if(this.existsSync(o)){let e=r.readFileSync(o,`utf8`);c=JSON.parse(e)}}catch{c={}}let l={...c.mcpServers??{},...n};c.mcpServers=l;let u=JSON.stringify(c,null,2);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalMcpConfig`,path:o,serverCount:Object.keys(n).length}),{path:s,success:!0,skipped:!1};try{return this.ensureDirectory(a),r.writeFileSync(o,u),this.log.trace({action:`write`,type:`globalMcpConfig`,path:o,serverCount:Object.keys(n).length}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalMcpConfig`,path:o,error:t}),{path:s,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=[],a=n.yamlFrontMatter.name,o=i.join(t,a),s=i.join(o,Tv),c=this.getGlobalConfigDir(),l={pathKind:L.Relative,path:i.join(wv,a,Tv),basePath:c,getDirectoryName:()=>a,getAbsolutePath:()=>s},u=this.buildSkillFrontMatter(n),d=n.content,f=jg(u,d);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`skill`,path:s}),r.push({path:l,success:!0,skipped:!1});else try{this.ensureDirectory(o),this.writeFileSync(s,f),this.log.trace({action:`write`,type:`skill`,path:s}),r.push({path:l,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skill`,path:s,error:t}),r.push({path:l,success:!1,error:e})}if(n.mcpConfig!=null){let t=await this.writeSkillMcpConfig(e,n,o,c);r.push(t)}if(n.childDocs!=null)for(let t of n.childDocs){let n=await this.writeSkillChildDoc(e,t,o,a,c);r.push(n)}if(n.resources!=null)for(let t of n.resources){let n=await this.writeSkillResource(e,t,o,a,c);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 a=t.yamlFrontMatter.name,o=i.join(n,bv),s={pathKind:L.Relative,path:i.join(wv,a,bv),basePath:r,getDirectoryName:()=>a,getAbsolutePath:()=>o},c=t.mcpConfig.rawContent;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfig`,path:o}),{path:s,success:!0,skipped:!1};try{return this.ensureDirectory(n),this.writeFileSync(o,c),this.log.trace({action:`write`,type:`mcpConfig`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`mcpConfig`,path:o,error:t}),{path:s,success:!1,error:e}}}async writeSkillChildDoc(e,t,n,r,a){let o=t.relativePath.replace(/\.mdx$/,`.md`),s=i.join(n,o),c={pathKind:L.Relative,path:i.join(wv,r,o),basePath:a,getDirectoryName:()=>r,getAbsolutePath:()=>s},l=t.content;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`childDoc`,path:s}),{path:c,success:!0,skipped:!1};try{let e=i.dirname(s);return this.ensureDirectory(e),this.writeFileSync(s,l),this.log.trace({action:`write`,type:`childDoc`,path:s}),{path:c,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`childDoc`,path:s,error:t}),{path:c,success:!1,error:e}}}async writeSkillResource(e,t,n,r,a){let o=i.join(n,t.relativePath),s={pathKind:L.Relative,path:i.join(wv,r,t.relativePath),basePath:a,getDirectoryName:()=>r,getAbsolutePath:()=>o};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`resource`,path:o}),{path:s,success:!0,skipped:!1};try{let e=i.dirname(o);if(this.ensureDirectory(e),t.encoding===`base64`){let e=d.from(t.content,`base64`);this.writeFileSyncBuffer(o,e)}else this.writeFileSync(o,t.content);return this.log.trace({action:`write`,type:`resource`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`resource`,path:o,error:t}),{path:s,success:!1,error:e}}}buildRuleFileName(e){return`rule-${e.series}-${e.ruleName}.mdc`}buildRuleMdcContent(e){return jg({alwaysApply:!1,globs:e.globs.length>0?e.globs.join(`, `):``},e.content)}async writeRuleMdcFile(e,t,n,r){let a=this.buildRuleFileName(n),o=i.join(t,a),s={pathKind:L.Relative,path:i.join(yv,Sv,a),basePath:r,getDirectoryName:()=>Sv,getAbsolutePath:()=>o},c=this.buildRuleMdcContent(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}}}},Ov=class extends fv{constructor(){super(`DroidCLIOutputPlugin`,{globalConfigDir:`.factory`,outputFileName:`AGENTS.md`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0})}async writeSkill(e,t,n){let r=[],a=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),o=i.join(t,this.skillsSubDir,a),s=i.join(o,`SKILL.md`),c=n.yamlFrontMatter==null?void 0:{name:n.yamlFrontMatter.name,description:n.yamlFrontMatter.description},l=this.buildMarkdownContent(n.content,c),u=await this.writeFile(e,s,l,`skill`);if(r.push(u),n.childDocs!=null)for(let i of n.childDocs){let n=await this.writeSkillReferenceDocument(e,o,a,i,t);r.push(...n)}if(n.resources!=null)for(let i of n.resources){let n=await this.writeSkillResource(e,o,a,i,t);r.push(...n)}return r}},kv=class extends Rg{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=Mg(o),i=await dv(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 Zg([...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:`shadowFastCommandDir`})}getTargetDir(e,t){let n=e.shadowFastCommandDir,{workspaceDir:r,shadowProjectDir:i}=t;return this.resolvePath(n,r,i)}validateMetadata(e,t){return It(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=Mg(s),l=await dv(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 Zg([...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:Et.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 fv{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 Fg{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 i of e)if(i.isDirectory()){let e=this.joinPath(t,i.name),a=this.joinPath(e,Pv);this.existsSync(a)&&(r.rmSync(e,{recursive:!0}),n++)}return this.readdirSync(t).length===0&&r.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=jg(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=d.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 Rg{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 i.join(e,`public`,`exclude`)}getResultKey(){return`shadowGitExclude`}};function zv(e){let t=i.join(e,`.git`);if(!r.existsSync(t))return null;let n=r.lstatSync(t);if(n.isDirectory())return i.join(t,`info`);if(n.isFile())try{let n=r.readFileSync(t,`utf8`).trim(),a=/^gitdir: (.+)$/.exec(n);if(a?.[1]!=null){let t=i.resolve(e,a[1]);return i.join(t,`info`)}}catch{}return null}function Bv(e,t=5){let n=[],a=new Set([`node_modules`,`.turbo`,`dist`,`build`,`out`,`.cache`]);function o(s,c){if(c>t)return;let l;try{let e=r.readdirSync(s,{withFileTypes:!0});if(!Array.isArray(e))return;l=e}catch{return}l.some(e=>e.name===`.git`)&&s!==e&&n.push(s);for(let e of l)e.isDirectory()&&(e.name===`.git`||a.has(e.name)||o(i.join(s,e.name),c+1))}return o(e,0),n}function Vv(e){let t=i.join(e,`modules`);if(!r.existsSync(t))return[];let n=[];function a(e){let t;try{let n=r.readdirSync(e,{withFileTypes:!0});if(!Array.isArray(n))return;t=n}catch{return}if(t.some(e=>e.name===`info`&&e.isDirectory())&&n.push(i.join(e,`info`)),t.find(e=>e.name===`modules`&&e.isDirectory())==null)return;let o;try{let t=r.readdirSync(i.join(e,`modules`),{withFileTypes:!0});if(!Array.isArray(t))return;o=t}catch{return}for(let t of o)t.isDirectory()&&a(i.join(e,`modules`,t.name))}let o;try{let e=r.readdirSync(t,{withFileTypes:!0});if(!Array.isArray(e))return n;o=e}catch{return n}for(let e of o)e.isDirectory()&&a(i.join(t,e.name));return n}var Hv=class extends Fg{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:a}=n,o=[r,...Bv(r)];for(let e of o){let n=zv(e);if(n==null)continue;let r=i.join(n,`exclude`),o=i.relative(a,r);t.push({pathKind:L.Relative,path:o,basePath:a,getDirectoryName:()=>i.basename(e),getAbsolutePath:()=>r})}}let a=e.collectedInputContext.workspace.directory.path,o=i.join(a,`.git`);if(r.existsSync(o)&&r.lstatSync(o).isDirectory())for(let e of Vv(o)){let n=i.join(e,`exclude`),r=i.relative(a,n);t.push({pathKind:L.Relative,path:r,basePath:a,getDirectoryName:()=>i.basename(i.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:a}=e.collectedInputContext,o=this.buildManagedContent(n,a);if(o.length===0)return this.log.debug({action:`write`,message:`No gitignore or exclude content found, skipping`}),{files:[],dirs:[]};let{workspace:s}=e.collectedInputContext,{projects:c}=s,l=new Set;for(let n of c){if(n.dirFromWorkspacePath==null)continue;let r=n.dirFromWorkspacePath.getAbsolutePath(),a=[r,...Bv(r)];for(let s of a){let a=zv(s);if(a==null)continue;let c=i.join(a,`exclude`);if(l.has(c))continue;l.add(c);let u=s===r?`project:${n.name??`unknown`}`:`nested:${i.relative(r,s)}`;this.log.trace({action:`write`,path:c,label:u});let d=await this.writeGitExcludeFile(e,c,o,u);t.push(d)}}let u=s.directory.path,d=zv(u);if(d!=null){let n=i.join(d,`exclude`);if(!l.has(n)){this.log.trace({action:`write`,path:n,target:`workspace`});let r=await this.writeGitExcludeFile(e,n,o,`workspace`);t.push(r),l.add(n)}}let f=Bv(u);for(let n of f){let r=zv(n);if(r==null)continue;let a=i.join(r,`exclude`);if(l.has(a))continue;l.add(a);let s=`workspace-nested:${i.relative(u,n)}`;this.log.trace({action:`write`,path:a,label:s});let c=await this.writeGitExcludeFile(e,a,o,s);t.push(c)}let p=i.join(u,`.git`);if(r.existsSync(p)&&r.lstatSync(p).isDirectory())for(let n of Vv(p)){let r=i.join(n,`exclude`);if(l.has(r))continue;l.add(r);let a=`git-module:${i.relative(p,n)}`;this.log.trace({action:`write`,path:r,label:a});let s=await this.writeGitExcludeFile(e,r,o,a);t.push(s)}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(`
|
|
1200
|
+
`).replaceAll(`\\r`,`\r`).replaceAll(`\\t`,` `).replaceAll(`\\"`,`"`).replaceAll(`\\'`,`'`).replaceAll(`\\\\`,`\\`)}function Q_(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 $_(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return[];if(t==null)try{let t=tv(e),n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return nv(r).map(e=>X_(e.trim(),t,n))}function ev(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return{};if(t==null)try{let t=tv(e),n=JSON.parse(t);if(typeof n==`object`&&n&&!Array.isArray(n))return n}catch{}let i={},a=rv(r);for(let e of a){let r=iv(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]=X_(o,t,n)}return i}function tv(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 nv(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 rv(e){return nv(e)}function iv(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 av(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=i_(n.value.value,t.scope);return e===`true`||e===`1`}catch{return!1}return!1}async function ov(e,t,n){return!av(e,t)||e.children.length===0?[]:n(e.children,t)}async function sv(e,t){if(!av(e,t)||e.children.length===0)return[];let n=cv(e.children,t);return n===``?[]:[{type:`text`,value:n}]}function cv(e,t){let n=``;for(let r of e)if(r.type===`text`)n+=r.value;else if(r.type===`mdxTextExpression`)try{n+=i_(r.value,t.scope)}catch{}else `children`in r&&Array.isArray(r.children)&&(n+=cv(r.children,t));return n}function lv(){t_(`Md`,ov),t_(`Md.Line`,sv)}lv();function uv(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 dv(e,t){let n=fh(e),r=uv(t?.globalScope,t?.scope),i=n_(),a;if(t?.extractMetadata===!0){let e=n.children.find(e=>e.type===`yaml`),i;if(e!=null)try{i=kg.parse(e.value)}catch{}a=q_(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 V_(n,{scope:r,components:i,processingStack:[],...t?.basePath!=null&&{basePath:t.basePath}}),s=mu().use(ai,[`yaml`]).use(Jl).use(K_,{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 fv=class extends Fg{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=i.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:a,subAgents:o,skills:s}=e.collectedInputContext,c={includeSeriesPrefix:!0};if(this.supportsFastCommands&&a!=null)for(let e of a){let t=this.transformFastCommandName(e,c);r.push(this.createRelativePath(i.join(this.commandsSubDir,t),n,()=>this.commandsSubDir))}if(this.supportsSubAgents&&o!=null)for(let e of o){let t=e.dir.path.replace(/\.mdx$/,`.md`);r.push(this.createRelativePath(i.join(this.agentsSubDir,t),n,()=>this.agentsSubDir))}if(this.supportsSkills&&s!=null)for(let e of s){let t=e.yamlFrontMatter?.name??e.dir.getDirectoryName(),a=i.join(this.skillsSubDir,t);if(r.push(this.createRelativePath(i.join(a,`SKILL.md`),n,()=>t)),e.childDocs!=null)for(let o of e.childDocs){let e=o.dir.path.replace(/\.mdx$/,`.md`),s=i.join(a,e);r.push(this.createRelativePath(s,n,()=>t))}if(e.resources!=null)for(let o of e.resources){let e=i.join(a,o.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:a,subAgents:o,skills:s}=e.collectedInputContext,c=this.getGlobalConfigDir();if(t!=null){let r=i.join(c,this.outputFileName),a=this.createRelativePath(this.outputFileName,c,()=>this.globalConfigDir);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`globalMemory`,path:r}),n.push({path:a,success:!0,skipped:!1});else try{ut(r,t.content),this.log.trace({action:`write`,type:`globalMemory`,path:r}),n.push({path:a,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:a,success:!1,error:e})}}if(this.supportsFastCommands&&a!=null)for(let t of a){let r=await this.writeFastCommand(e,c,t);n.push(...r)}if(this.supportsSubAgents&&o!=null)for(let t of o){let r=await this.writeSubAgent(e,c,t);n.push(...r)}if(this.supportsSkills&&s!=null)for(let t of s){let r=await this.writeSkill(e,c,t);n.push(...r)}return{files:n,dirs:r}}async writeFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),a=this.transformFastCommandName(n,r),o=i.join(t,this.commandsSubDir),s=i.join(o,a),c=n.content,l=n.yamlFrontMatter,u=!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 cr({toolPreset:this.toolPreset}).collect(),t=await dv(n.rawMdxContent,{globalScope:e,extractMetadata:!0,basePath:n.dir.basePath});c=t.content,l=t.metadata.fields,u=!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 d=u?this.buildMarkdownContent(c,l):this.buildMarkdownContentWithRaw(c,l,n.rawFrontMatter);return[await this.writeFile(e,s,d,`fastCommand`)]}async writeSubAgent(e,t,n){let r=n.dir.path.replace(/\.mdx$/,`.md`),a=i.join(t,this.agentsSubDir),o=i.join(a,r),s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);return[await this.writeFile(e,o,s,`subAgent`)]}async writeSkill(e,t,n){let r=[],a=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),o=i.join(t,this.skillsSubDir,a),s=i.join(o,`SKILL.md`),c=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter),l=await this.writeFile(e,s,c,`skill`);if(r.push(l),n.childDocs!=null)for(let i of n.childDocs){let n=await this.writeSkillReferenceDocument(e,o,a,i,t);r.push(...n)}if(n.resources!=null)for(let i of n.resources){let n=await this.writeSkillResource(e,o,a,i,t);r.push(...n)}return r}async writeSkillReferenceDocument(e,t,n,r,a){let o=r.dir.path.replace(/\.mdx$/,`.md`),s=i.join(t,o);return[await this.writeFile(e,s,r.content,`skillRefDoc`)]}async writeSkillResource(e,t,n,r,a){let o=i.join(t,r.relativePath);return[await this.writeFile(e,o,r.content,`skillResource`)]}},pv=class extends fv{constructor(){super(`ClaudeCodeCLIOutputPlugin`,{globalConfigDir:`.claude`,outputFileName:`CLAUDE.md`,toolPreset:`claudeCode`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0})}};const mv=`AGENTS.md`,hv=`.codex`,gv=`prompts`,_v=`skills`;var vv=class extends Fg{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(i.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,a=[],o=this.getGlobalConfigDir();if(t!=null){let n=i.join(o,mv),r=await this.writeFile(e,n,t.content,`globalMemory`);a.push(r)}if(n!=null&&n.length>0)for(let t of n){let n=await this.writeGlobalFastCommand(e,o,t);a.push(n)}if(r!=null&&r.length>0)for(let t of r){let n=await this.writeGlobalSkill(e,o,t);a.push(...n)}return{files:a,dirs:[]}}async writeGlobalFastCommand(e,t,n){let r=this.getTransformOptionsFromContext(e),a=this.transformFastCommandName(n,r),o=i.join(t,gv,a),s=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);return this.writeFile(e,o,s,`globalFastCommand`)}async writeGlobalSkill(e,t,n){let r=[],a=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),o=i.join(t,_v,a),s=i.join(o,`SKILL.md`),c=this.buildCodexSkillContent(n),l=await this.writeFile(e,s,c,`globalSkill`);if(r.push(l),n.childDocs!=null)for(let t of n.childDocs){let n=t.dir.path.replace(/\.mdx$/,`.md`),a=i.join(o,n),s=await this.writeFile(e,a,t.content,`skillRefDoc`);r.push(s)}if(n.resources!=null)for(let t of n.resources){let n=i.join(o,t.relativePath),a=await this.writeFile(e,n,t.content,`skillResource`);r.push(a)}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(` `)),jg(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 Fg{constructor(){super(`CursorOutputPlugin`,{globalConfigDir:yv,outputFileName:``,dependsOn:[`AgentsOutputPlugin`],indexignore:`.cursorignore`}),this.registerCleanEffect(`mcp-config-cleanup`,async e=>{let t=this.getGlobalConfigDir(),n=i.join(t,bv),a={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),r.writeFileSync(n,JSON.stringify(a,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:a,rules:o}=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(a!=null&&a.length>0)for(let e of a){let r=e.yamlFrontMatter.name;if(this.isPreservedSkill(r))continue;let a=i.join(n,wv,r);t.push({pathKind:L.Relative,path:i.join(wv,r),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>a})}let s=o?.filter(e=>e.scope===`global`);if(s==null||s.length===0)return t;let c=i.join(n,Sv);return t.push({pathKind:L.Relative,path:Sv,basePath:n,getDirectoryName:()=>Sv,getAbsolutePath:()=>c}),t}async registerGlobalOutputFiles(e){let t=[],n=this.getGlobalConfigDir(),{skills:r,fastCommands:a}=e.collectedInputContext;if(r?.some(e=>e.mcpConfig!=null)??!1){let e=i.join(n,bv);t.push({pathKind:L.Relative,path:bv,basePath:n,getDirectoryName:()=>yv,getAbsolutePath:()=>e})}if(a!=null&&a.length>0){let r=this.getGlobalCommandsDir(),o=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});for(let e of a){let a=this.transformFastCommandName(e,o),s=i.join(r,a);t.push({pathKind:L.Relative,path:i.join(xv,a),basePath:n,getDirectoryName:()=>xv,getAbsolutePath:()=>s})}}let o=e.collectedInputContext.rules?.filter(e=>e.scope===`global`);if(o!=null&&o.length>0){let e=i.join(n,Sv);for(let r of o){let a=this.buildRuleFileName(r),o=i.join(e,a);t.push({pathKind:L.Relative,path:i.join(Sv,a),basePath:n,getDirectoryName:()=>Sv,getAbsolutePath:()=>o})}}if(r==null||r.length===0)return t;let s=this.getSkillsCursorDir();for(let e of r){let r=e.yamlFrontMatter.name;if(this.isPreservedSkill(r))continue;let a=i.join(s,r);if(t.push({pathKind:L.Relative,path:i.join(wv,r,Tv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i.join(a,Tv)}),e.mcpConfig!=null&&t.push({pathKind:L.Relative,path:i.join(wv,r,bv),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i.join(a,bv)}),e.childDocs!=null)for(let o of e.childDocs){let e=o.relativePath.replace(/\.mdx$/,`.md`);t.push({pathKind:L.Relative,path:i.join(wv,r,e),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i.join(a,e)})}if(e.resources!=null)for(let o of e.resources)t.push({pathKind:L.Relative,path:i.join(wv,r,o.relativePath),basePath:n,getDirectoryName:()=>r,getAbsolutePath:()=>i.join(a,o.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,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,a=[],o=[];if(t!=null&&t.length>0){let n=await this.writeGlobalMcpConfig(e,t);n!=null&&a.push(n);let r=this.getSkillsCursorDir();for(let n of t){let t=n.yamlFrontMatter.name;if(this.isPreservedSkill(t))continue;let i=await this.writeGlobalSkill(e,r,n);a.push(...i)}}if(n!=null&&n.length>0){let t=this.getGlobalCommandsDir();for(let r of n){let n=await this.writeGlobalFastCommand(e,t,r);a.push(n)}}let s=r?.filter(e=>e.scope===`global`);if(s==null||s.length===0)return{files:a,dirs:o};let c=i.join(this.getGlobalConfigDir(),Sv);for(let t of s){let n=await this.writeRuleMdcFile(e,c,t,this.getGlobalConfigDir());a.push(n)}return{files:a,dirs:o}}async writeProjectOutputs(e){let t=[],n=[],{workspace:r,globalMemory:a,rules:o}=e.collectedInputContext;if(a!=null){let n=this.buildGlobalRuleContent(a.content);for(let i of r.projects){if(i.dirFromWorkspacePath==null)continue;let r=await this.writeProjectGlobalRule(e,i,n);t.push(r)}}let s=o?.filter(e=>e.scope===`project`);if(s!=null&&s.length>0)for(let n of r.projects){let r=n.dirFromWorkspacePath;if(r==null)continue;let a=i.join(r.basePath,r.path,yv,Sv);for(let n of s){let i=await this.writeRuleMdcFile(e,a,n,r.basePath);t.push(i)}}let c=await this.writeProjectIgnoreFiles(e);return t.push(...c),{files:t,dirs:n}}createProjectRulesDirRelativePath(e){let t=i.join(e.path,yv,Sv);return{pathKind:L.Relative,path:t,basePath:e.basePath,getDirectoryName:()=>Sv,getAbsolutePath:()=>i.join(e.basePath,t)}}createProjectRuleFileRelativePath(e,t){let n=i.join(e.path,yv,Sv,t);return{pathKind:L.Relative,path:n,basePath:e.basePath,getDirectoryName:()=>Sv,getAbsolutePath:()=>i.join(e.basePath,n)}}buildGlobalRuleContent(e){return jg({description:`Global prompt (synced)`,alwaysApply:!0},e)}async writeProjectGlobalRule(e,t,n){let r=t.dirFromWorkspacePath,a=i.join(r.basePath,r.path,yv,Sv),o=i.join(a,Cv),s=this.createProjectRuleFileRelativePath(r,Cv);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalRule`,path:o}),{path:s,success:!0,skipped:!1};try{return this.ensureDirectory(a),this.writeFileSync(o,n),this.log.trace({action:`write`,type:`globalRule`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalRule`,path:o,error:t}),{path:s,success:!1,error:e}}}isPreservedSkill(e){return Ev.has(e)}getSkillsCursorDir(){return i.join(this.getGlobalConfigDir(),wv)}getGlobalCommandsDir(){return i.join(this.getGlobalConfigDir(),xv)}async writeGlobalFastCommand(e,t,n){let a=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),o=this.transformFastCommandName(n,a),s=i.join(t,o),c={pathKind:L.Relative,path:i.join(xv,o),basePath:this.getGlobalConfigDir(),getDirectoryName:()=>xv,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{return this.ensureDirectory(t),r.writeFileSync(s,l),this.log.trace({action:`write`,type:`globalFastCommand`,path:s}),{path:c,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalFastCommand`,path:s,error:t}),{path:c,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 a=this.getGlobalConfigDir(),o=i.join(a,bv),s={pathKind:L.Relative,path:bv,basePath:a,getDirectoryName:()=>yv,getAbsolutePath:()=>o},c={};try{if(this.existsSync(o)){let e=r.readFileSync(o,`utf8`);c=JSON.parse(e)}}catch{c={}}let l={...c.mcpServers??{},...n};c.mcpServers=l;let u=JSON.stringify(c,null,2);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalMcpConfig`,path:o,serverCount:Object.keys(n).length}),{path:s,success:!0,skipped:!1};try{return this.ensureDirectory(a),r.writeFileSync(o,u),this.log.trace({action:`write`,type:`globalMcpConfig`,path:o,serverCount:Object.keys(n).length}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`globalMcpConfig`,path:o,error:t}),{path:s,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=[],a=n.yamlFrontMatter.name,o=i.join(t,a),s=i.join(o,Tv),c=this.getGlobalConfigDir(),l={pathKind:L.Relative,path:i.join(wv,a,Tv),basePath:c,getDirectoryName:()=>a,getAbsolutePath:()=>s},u=this.buildSkillFrontMatter(n),d=n.content,f=jg(u,d);if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`skill`,path:s}),r.push({path:l,success:!0,skipped:!1});else try{this.ensureDirectory(o),this.writeFileSync(s,f),this.log.trace({action:`write`,type:`skill`,path:s}),r.push({path:l,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skill`,path:s,error:t}),r.push({path:l,success:!1,error:e})}if(n.mcpConfig!=null){let t=await this.writeSkillMcpConfig(e,n,o,c);r.push(t)}if(n.childDocs!=null)for(let t of n.childDocs){let n=await this.writeSkillChildDoc(e,t,o,a,c);r.push(n)}if(n.resources!=null)for(let t of n.resources){let n=await this.writeSkillResource(e,t,o,a,c);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 a=t.yamlFrontMatter.name,o=i.join(n,bv),s={pathKind:L.Relative,path:i.join(wv,a,bv),basePath:r,getDirectoryName:()=>a,getAbsolutePath:()=>o},c=t.mcpConfig.rawContent;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`mcpConfig`,path:o}),{path:s,success:!0,skipped:!1};try{return this.ensureDirectory(n),this.writeFileSync(o,c),this.log.trace({action:`write`,type:`mcpConfig`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`mcpConfig`,path:o,error:t}),{path:s,success:!1,error:e}}}async writeSkillChildDoc(e,t,n,r,a){let o=t.relativePath.replace(/\.mdx$/,`.md`),s=i.join(n,o),c={pathKind:L.Relative,path:i.join(wv,r,o),basePath:a,getDirectoryName:()=>r,getAbsolutePath:()=>s},l=t.content;if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`childDoc`,path:s}),{path:c,success:!0,skipped:!1};try{let e=i.dirname(s);return this.ensureDirectory(e),this.writeFileSync(s,l),this.log.trace({action:`write`,type:`childDoc`,path:s}),{path:c,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`childDoc`,path:s,error:t}),{path:c,success:!1,error:e}}}async writeSkillResource(e,t,n,r,a){let o=i.join(n,t.relativePath),s={pathKind:L.Relative,path:i.join(wv,r,t.relativePath),basePath:a,getDirectoryName:()=>r,getAbsolutePath:()=>o};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`resource`,path:o}),{path:s,success:!0,skipped:!1};try{let e=i.dirname(o);if(this.ensureDirectory(e),t.encoding===`base64`){let e=d.from(t.content,`base64`);this.writeFileSyncBuffer(o,e)}else this.writeFileSync(o,t.content);return this.log.trace({action:`write`,type:`resource`,path:o}),{path:s,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`resource`,path:o,error:t}),{path:s,success:!1,error:e}}}buildRuleFileName(e){return`rule-${e.series}-${e.ruleName}.mdc`}buildRuleMdcContent(e){return jg({alwaysApply:!1,globs:e.globs.length>0?e.globs.join(`, `):``},e.content).split(`
|
|
1201
|
+
`).map(e=>{let t=/^globs:\s*"(.*)"\s*$/.exec(e);if(t==null)return e;let n=t[1]??``;return n.trim().length===0?e:`globs: ${n}`}).join(`
|
|
1202
|
+
`)}async writeRuleMdcFile(e,t,n,r){let a=this.buildRuleFileName(n),o=i.join(t,a),s={pathKind:L.Relative,path:i.join(yv,Sv,a),basePath:r,getDirectoryName:()=>Sv,getAbsolutePath:()=>o},c=this.buildRuleMdcContent(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}}}},Ov=class extends fv{constructor(){super(`DroidCLIOutputPlugin`,{globalConfigDir:`.factory`,outputFileName:`AGENTS.md`,supportsFastCommands:!0,supportsSubAgents:!0,supportsSkills:!0})}async writeSkill(e,t,n){let r=[],a=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),o=i.join(t,this.skillsSubDir,a),s=i.join(o,`SKILL.md`),c=n.yamlFrontMatter==null?void 0:{name:n.yamlFrontMatter.name,description:n.yamlFrontMatter.description},l=this.buildMarkdownContent(n.content,c),u=await this.writeFile(e,s,l,`skill`);if(r.push(u),n.childDocs!=null)for(let i of n.childDocs){let n=await this.writeSkillReferenceDocument(e,o,a,i,t);r.push(...n)}if(n.resources!=null)for(let i of n.resources){let n=await this.writeSkillResource(e,o,a,i,t);r.push(...n)}return r}},kv=class extends Rg{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=Mg(o),i=await dv(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 Zg([...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:`shadowFastCommandDir`})}getTargetDir(e,t){let n=e.shadowFastCommandDir,{workspaceDir:r,shadowProjectDir:i}=t;return this.resolvePath(n,r,i)}validateMetadata(e,t){return It(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=Mg(s),l=await dv(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 Zg([...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:Et.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 fv{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 Fg{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 i of e)if(i.isDirectory()){let e=this.joinPath(t,i.name),a=this.joinPath(e,Pv);this.existsSync(a)&&(r.rmSync(e,{recursive:!0}),n++)}return this.readdirSync(t).length===0&&r.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=jg(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=d.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 Rg{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 i.join(e,`public`,`exclude`)}getResultKey(){return`shadowGitExclude`}};function zv(e){let t=i.join(e,`.git`);if(!r.existsSync(t))return null;let n=r.lstatSync(t);if(n.isDirectory())return i.join(t,`info`);if(n.isFile())try{let n=r.readFileSync(t,`utf8`).trim(),a=/^gitdir: (.+)$/.exec(n);if(a?.[1]!=null){let t=i.resolve(e,a[1]);return i.join(t,`info`)}}catch{}return null}function Bv(e,t=5){let n=[],a=new Set([`node_modules`,`.turbo`,`dist`,`build`,`out`,`.cache`]);function o(s,c){if(c>t)return;let l;try{let e=r.readdirSync(s,{withFileTypes:!0});if(!Array.isArray(e))return;l=e}catch{return}l.some(e=>e.name===`.git`)&&s!==e&&n.push(s);for(let e of l)e.isDirectory()&&(e.name===`.git`||a.has(e.name)||o(i.join(s,e.name),c+1))}return o(e,0),n}function Vv(e){let t=i.join(e,`modules`);if(!r.existsSync(t))return[];let n=[];function a(e){let t;try{let n=r.readdirSync(e,{withFileTypes:!0});if(!Array.isArray(n))return;t=n}catch{return}if(t.some(e=>e.name===`info`&&e.isDirectory())&&n.push(i.join(e,`info`)),t.find(e=>e.name===`modules`&&e.isDirectory())==null)return;let o;try{let t=r.readdirSync(i.join(e,`modules`),{withFileTypes:!0});if(!Array.isArray(t))return;o=t}catch{return}for(let t of o)t.isDirectory()&&a(i.join(e,`modules`,t.name))}let o;try{let e=r.readdirSync(t,{withFileTypes:!0});if(!Array.isArray(e))return n;o=e}catch{return n}for(let e of o)e.isDirectory()&&a(i.join(t,e.name));return n}var Hv=class extends Fg{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:a}=n,o=[r,...Bv(r)];for(let e of o){let n=zv(e);if(n==null)continue;let r=i.join(n,`exclude`),o=i.relative(a,r);t.push({pathKind:L.Relative,path:o,basePath:a,getDirectoryName:()=>i.basename(e),getAbsolutePath:()=>r})}}let a=e.collectedInputContext.workspace.directory.path,o=i.join(a,`.git`);if(r.existsSync(o)&&r.lstatSync(o).isDirectory())for(let e of Vv(o)){let n=i.join(e,`exclude`),r=i.relative(a,n);t.push({pathKind:L.Relative,path:r,basePath:a,getDirectoryName:()=>i.basename(i.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:a}=e.collectedInputContext,o=this.buildManagedContent(n,a);if(o.length===0)return this.log.debug({action:`write`,message:`No gitignore or exclude content found, skipping`}),{files:[],dirs:[]};let{workspace:s}=e.collectedInputContext,{projects:c}=s,l=new Set;for(let n of c){if(n.dirFromWorkspacePath==null)continue;let r=n.dirFromWorkspacePath.getAbsolutePath(),a=[r,...Bv(r)];for(let s of a){let a=zv(s);if(a==null)continue;let c=i.join(a,`exclude`);if(l.has(c))continue;l.add(c);let u=s===r?`project:${n.name??`unknown`}`:`nested:${i.relative(r,s)}`;this.log.trace({action:`write`,path:c,label:u});let d=await this.writeGitExcludeFile(e,c,o,u);t.push(d)}}let u=s.directory.path,d=zv(u);if(d!=null){let n=i.join(d,`exclude`);if(!l.has(n)){this.log.trace({action:`write`,path:n,target:`workspace`});let r=await this.writeGitExcludeFile(e,n,o,`workspace`);t.push(r),l.add(n)}}let f=Bv(u);for(let n of f){let r=zv(n);if(r==null)continue;let a=i.join(r,`exclude`);if(l.has(a))continue;l.add(a);let s=`workspace-nested:${i.relative(u,n)}`;this.log.trace({action:`write`,path:a,label:s});let c=await this.writeGitExcludeFile(e,a,o,s);t.push(c)}let p=i.join(u,`.git`);if(r.existsSync(p)&&r.lstatSync(p).isDirectory())for(let n of Vv(p)){let r=i.join(n,`exclude`);if(l.has(r))continue;l.add(r);let a=`git-module:${i.relative(p,n)}`;this.log.trace({action:`write`,path:r,label:a});let s=await this.writeGitExcludeFile(e,r,o,a);t.push(s)}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(`
|
|
1201
1203
|
`)}sanitizeContent(e){return e.split(/\r?\n/).filter(e=>{let t=e.trim();return t.length===0?!0:!(t.startsWith(`#`)&&!t.startsWith(`\\#`))}).join(`
|
|
1202
1204
|
`).trim()}normalizeContent(e){let t=e.trim();return t.length===0?``:`${t}\n`}async writeGitExcludeFile(e,t,n,a){let o=e.collectedInputContext.workspace.directory.path,s={pathKind:L.Relative,path:i.relative(o,t),basePath:o,getDirectoryName:()=>i.basename(i.dirname(t)),getAbsolutePath:()=>t};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`gitExclude`,path:t,label:a}),{path:s,success:!0,skipped:!1};try{let e=i.dirname(t);r.existsSync(e)||(r.mkdirSync(e,{recursive:!0}),this.log.debug({action:`mkdir`,path:e,message:`Created .git/info directory`}));let o=this.normalizeContent(n);return r.writeFileSync(t,o,`utf8`),this.log.trace({action:`write`,type:`gitExclude`,path:t,label:a}),{path:s,success:!0}}catch(e){let n=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:`gitExclude`,path:t,label:a,error:n}),{path:s,success:!1,error:e}}}};const Uv=qt;function Wv(){return Uv[`public/gitignore`]?.content??``}var Gv=class extends Lv{constructor(){super(`GitIgnoreInputPlugin`,{fallbackContent:Wv()})}getFilePath(e){return i.join(e,`public`,`gitignore`)}getResultKey(){return`globalGitIgnore`}},Kv=class extends Rg{constructor(){super(`GlobalMemoryInputPlugin`)}async collect(e){let{userConfigOptions:t,fs:r,path:i,globalScope:a}=e,{workspaceDir:o,shadowProjectDir:c}=this.resolveBasePaths(t),l=t.globalMemoryFile,u=this.resolvePath(l,o,c);if(!r.existsSync(u))return this.log.warn({action:`collect`,reason:`fileNotFound`,path:u}),{};if(!r.statSync(u).isFile())return this.log.warn({action:`collect`,reason:`notAFile`,path:u}),{};let d=r.readFileSync(u,`utf8`),f=Mg(d),p;if(a!=null)try{p=await dv(d,{globalScope:a,basePath:i.dirname(u)})}catch(e){throw e instanceof Jg&&(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.`),n.exit(1)),e}else p=f.contentWithoutFrontMatter;return this.log.debug({action:`collect`,path:u,contentLength:p.length}),{globalMemory:{type:Et.GlobalMemory,content:p,length:p.length,filePathKind:L.Relative,...f.rawFrontMatter!=null&&{rawFrontMatter:f.rawFrontMatter},markdownAst:f.markdownAst,markdownContents:f.markdownContents,dir:{pathKind:L.Relative,path:i.basename(u),basePath:i.dirname(u),getDirectoryName:()=>i.basename(u),getAbsolutePath:()=>u},parentDirectoryPath:{type:At.UserHome,directory:{pathKind:L.Relative,path:``,basePath:s.homedir(),getDirectoryName:()=>i.basename(s.homedir()),getAbsolutePath:()=>s.homedir()}}}}}},qv=class extends Rg{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=R.Original;e.includes(`.vscode`)?a=R.VSCode:e.includes(`.idea`)?a=R.IntellijIDEA:e.includes(`.editorconfig`)&&(a=R.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 Fg{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=i.join(r,Yv);t.push({pathKind:L.Relative,path:Yv,basePath:r,getDirectoryName:()=>Yv,getAbsolutePath:()=>n});let{skills:a}=e.collectedInputContext;if(!(a==null||a.length===0))for(let e of a){let n=e.yamlFrontMatter?.name??e.dir.getDirectoryName(),a=i.join(r,Xv,n);t.push({pathKind:L.Relative,path:i.join(Xv,n),basePath:r,getDirectoryName:()=>n,getAbsolutePath:()=>a})}}return t}async registerGlobalOutputFiles(){return this.resolveCodexDirs().map(e=>({pathKind:L.Relative,path:Jv,basePath:e,getDirectoryName:()=>ty,getAbsolutePath:()=>i.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:a}=e.collectedInputContext,o=[],s=[],c=this.resolveCodexDirs();if(c.length===0)return{files:o,dirs:s};for(let s of c){if(t!=null){let n=i.join(s,Jv),a={pathKind:L.Relative,path:Jv,basePath:s,getDirectoryName:()=>ty,getAbsolutePath:()=>n};if(e.dryRun===!0)this.log.trace({action:`dryRun`,type:`globalMemory`,path:n}),o.push({path:a,success:!0,skipped:!1});else try{this.ensureDirectory(s),r.writeFileSync(n,t.content,`utf8`),this.log.trace({action:`write`,type:`globalMemory`,path:n}),o.push({path:a,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`globalMemory`,path:n,error:t}),o.push({path:a,success:!1,error:e})}}if(n!=null&&n.length>0)for(let t of n){let n=await this.writeGlobalFastCommand(e,s,t);o.push(...n)}if(!(a==null||a.length===0))for(let t of a){let n=await this.writeGlobalSkill(e,s,t);o.push(...n)}}return{files:o,dirs:s}}resolveCodexDirs(){let e=i.join(nt(),`JetBrains`);if(!this.existsSync(e))return[];try{return this.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()?this.isSupportedIdeDir(e.name):!1).map(t=>i.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=i.join(e.path,Qv,$v);return{pathKind:L.Relative,path:t,basePath:e.basePath,getDirectoryName:()=>$v,getAbsolutePath:()=>i.join(e.basePath,t)}}createProjectRuleFileRelativePath(e,t){let n=i.join(e.path,Qv,$v,t);return{pathKind:L.Relative,path:n,basePath:e.basePath,getDirectoryName:()=>$v,getAbsolutePath:()=>i.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 jg({apply:`始终`},e)}buildGlobRuleContent(e){return jg({apply:`按文件模式`,模式:this.buildChildRulePattern(e)},e.content)}async writeProjectRuleFile(e,t,n,a,o){let s=t.dirFromWorkspacePath,c=i.join(s.basePath,s.path,Qv,$v),l=i.join(c,n),u=this.createProjectRuleFileRelativePath(s,n);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:o,path:l}),{path:u,success:!0,skipped:!1};try{return this.ensureDirectory(c),r.writeFileSync(l,a,`utf8`),this.log.trace({action:`write`,type:o,path:l}),{path:u,success:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return this.log.error({action:`write`,type:o,path:l,error:t}),{path:u,success:!1,error:e}}}isSupportedIdeDir(e){return ny.some(t=>e.startsWith(t))}async writeGlobalFastCommand(e,t,n){let a=[],o=this.getTransformOptionsFromContext(e),s=this.transformFastCommandName(n,o),c=i.join(t,Yv),l=i.join(c,s),u={pathKind:L.Relative,path:i.join(Yv,s),basePath:t,getDirectoryName:()=>Yv,getAbsolutePath:()=>l},d=this.buildMarkdownContentWithRaw(n.content,n.yamlFrontMatter,n.rawFrontMatter);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalFastCommand`,path:l}),[{path:u,success:!0,skipped:!1}];try{this.ensureDirectory(c),r.writeFileSync(l,d,`utf8`),this.log.trace({action:`write`,type:`globalFastCommand`,path:l}),a.push({path:u,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`globalFastCommand`,path:l,error:t}),a.push({path:u,success:!1,error:e})}return a}async writeGlobalSkill(e,t,n){let a=[],o=n.yamlFrontMatter?.name??n.dir.getDirectoryName(),s=i.join(t,Xv,o),c=i.join(s,Zv),l={pathKind:L.Relative,path:i.join(Xv,o,Zv),basePath:t,getDirectoryName:()=>o,getAbsolutePath:()=>c},u=this.buildCodexSkillContent(n);if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`globalSkill`,path:c}),[{path:l,success:!0,skipped:!1}];try{if(this.ensureDirectory(s),r.writeFileSync(c,u,`utf8`),this.log.trace({action:`write`,type:`globalSkill`,path:c}),a.push({path:l,success:!0}),n.childDocs!=null)for(let r of n.childDocs){let n=await this.writeSkillReferenceDocument(e,s,o,r,t);a.push(...n)}if(n.resources!=null)for(let r of n.resources){let n=await this.writeSkillResource(e,s,o,r,t);a.push(...n)}}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`globalSkill`,path:c,error:t}),a.push({path:l,success:!1,error:e})}return a}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(` `)),jg(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,a,o){let s=[],c=a.dir.path.replace(/\.mdx$/,`.md`),l=i.join(t,c),u={pathKind:L.Relative,path:i.join(Xv,n,c),basePath:o,getDirectoryName:()=>n,getAbsolutePath:()=>l};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`skillRefDoc`,path:l}),[{path:u,success:!0,skipped:!1}];try{let e=i.dirname(l);this.ensureDirectory(e),r.writeFileSync(l,a.content,`utf8`),this.log.trace({action:`write`,type:`skillRefDoc`,path:l}),s.push({path:u,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skillRefDoc`,path:l,error:t}),s.push({path:u,success:!1,error:e})}return s}async writeSkillResource(e,t,n,a,o){let s=[],c=i.join(t,a.relativePath),l={pathKind:L.Relative,path:i.join(Xv,n,a.relativePath),basePath:o,getDirectoryName:()=>n,getAbsolutePath:()=>c};if(e.dryRun===!0)return this.log.trace({action:`dryRun`,type:`skillResource`,path:c}),[{path:l,success:!0,skipped:!1}];try{let e=i.dirname(c);this.ensureDirectory(e),r.writeFileSync(c,a.content,`utf8`),this.log.trace({action:`write`,type:`skillResource`,path:c}),s.push({path:l,success:!0})}catch(e){let t=e instanceof Error?e.message:String(e);this.log.error({action:`write`,type:`skillResource`,path:c,error:t}),s.push({path:l,success:!1,error:e})}return s}};const iy=`.idea`,ay=[`.editorconfig`,`.idea/codeStyles/Project.xml`,`.idea/codeStyles/codeStyleConfig.xml`,`.idea/.gitignore`];var oy=class extends Fg{constructor(){super(`JetBrainsIDECodeStyleConfigOutputPlugin`)}async registerProjectOutputFiles(e){let t=[],{projects:n}=e.collectedInputContext.workspace,{ideConfigFiles:r}=e.collectedInputContext;if(!r.some(e=>e.type===R.IntellijIDEA||e.type===R.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===R.IntellijIDEA||e.type===R.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===R.IntellijIDEA||e.type===R.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===R.EditorConfig)return`.editorconfig`;if(e.type!==R.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 Rg{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
|
|
1203
1205
|
`)?`\r
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@truenine/memory-sync-cli",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "2026.10218.
|
|
4
|
+
"version": "2026.10218.11905",
|
|
5
5
|
"description": "TrueNine Memory Synchronization CLI",
|
|
6
6
|
"author": "TrueNine",
|
|
7
7
|
"license": "AGPL-3.0-only",
|
|
@@ -54,9 +54,9 @@
|
|
|
54
54
|
"tsx": "^4.21.0",
|
|
55
55
|
"typescript": "^5.9.3",
|
|
56
56
|
"@truenine/desk-paths": "1.0.0",
|
|
57
|
-
"@truenine/init-bundle": "1.0.0",
|
|
58
57
|
"@truenine/logger": "1.0.0",
|
|
59
|
-
"@truenine/md-compiler": "1.0.0"
|
|
58
|
+
"@truenine/md-compiler": "1.0.0",
|
|
59
|
+
"@truenine/init-bundle": "1.0.0"
|
|
60
60
|
},
|
|
61
61
|
"scripts": {
|
|
62
62
|
"build": "run-s build:deps check bundle",
|