@truenine/memory-sync-cli 2026.10327.10010 → 2026.10328.106
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.d.mts +9 -4
- package/dist/index.mjs +56 -56
- package/dist/plugin-runtime.mjs +126 -126
- package/package.json +17 -15
package/dist/index.mjs
CHANGED
|
@@ -192,57 +192,57 @@ var n=kp(),r={"{":`}`,"(":`)`,"[":`]`},i=function(e){if(e[0]===`!`)return!0;for(
|
|
|
192
192
|
let n;t.exports=typeof queueMicrotask==`function`?queueMicrotask.bind(typeof window<`u`?window:global):e=>(n||=Promise.resolve()).then(e).catch(e=>setTimeout(()=>{throw e},0))})),sm=n(((e,t)=>{
|
|
193
193
|
/*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
194
194
|
t.exports=r;let n=om();function r(e,t){let r,i,a,o=!0;Array.isArray(e)?(r=[],i=e.length):(a=Object.keys(e),r={},i=a.length);function s(e){function i(){t&&t(e,r),t=null}o?n(i):i()}function c(e,t,n){r[e]=n,(--i===0||t)&&s(t)}i?a?a.forEach(function(t){e[t](function(e,n){c(t,e,n)})}):e.forEach(function(e,t){e(function(e,n){c(t,e,n)})}):s(null),o=!1}})),cm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;let t=process.versions.node.split(`.`);if(t[0]===void 0||t[1]===void 0)throw Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);let n=Number.parseInt(t[0],10),r=Number.parseInt(t[1],10);e.IS_SUPPORT_READDIR_WITH_FILE_TYPES=n>10||n===10&&r>=10})),lm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDirentFromStats=void 0;var t=class{constructor(e,t){this.name=e,this.isBlockDevice=t.isBlockDevice.bind(t),this.isCharacterDevice=t.isCharacterDevice.bind(t),this.isDirectory=t.isDirectory.bind(t),this.isFIFO=t.isFIFO.bind(t),this.isFile=t.isFile.bind(t),this.isSocket=t.isSocket.bind(t),this.isSymbolicLink=t.isSymbolicLink.bind(t)}};function n(e,n){return new t(e,n)}e.createDirentFromStats=n})),um=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.fs=void 0,e.fs=lm()})),dm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.joinPathSegments=void 0;function t(e,t,n){return e.endsWith(n)?e+t:e+n+t}e.joinPathSegments=t})),fm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.readdir=e.readdirWithFileTypes=e.read=void 0;let t=am(),n=sm(),r=cm(),i=um(),a=dm();function o(e,t,n){if(!t.stats&&r.IS_SUPPORT_READDIR_WITH_FILE_TYPES){s(e,t,n);return}l(e,t,n)}e.read=o;function s(e,t,r){t.fs.readdir(e,{withFileTypes:!0},(i,o)=>{if(i!==null){u(r,i);return}let s=o.map(n=>({dirent:n,name:n.name,path:a.joinPathSegments(e,n.name,t.pathSegmentSeparator)}));if(!t.followSymbolicLinks){d(r,s);return}n(s.map(e=>c(e,t)),(e,t)=>{if(e!==null){u(r,e);return}d(r,t)})})}e.readdirWithFileTypes=s;function c(e,t){return n=>{if(!e.dirent.isSymbolicLink()){n(null,e);return}t.fs.stat(e.path,(r,a)=>{if(r!==null){if(t.throwErrorOnBrokenSymbolicLink){n(r);return}n(null,e);return}e.dirent=i.fs.createDirentFromStats(e.name,a),n(null,e)})}}function l(e,r,o){r.fs.readdir(e,(s,c)=>{if(s!==null){u(o,s);return}n(c.map(n=>{let o=a.joinPathSegments(e,n,r.pathSegmentSeparator);return e=>{t.stat(o,r.fsStatSettings,(t,a)=>{if(t!==null){e(t);return}let s={name:n,path:o,dirent:i.fs.createDirentFromStats(n,a)};r.stats&&(s.stats=a),e(null,s)})}}),(e,t)=>{if(e!==null){u(o,e);return}d(o,t)})})}e.readdir=l;function u(e,t){e(t)}function d(e,t){e(null,t)}})),pm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.readdir=e.readdirWithFileTypes=e.read=void 0;let t=am(),n=cm(),r=um(),i=dm();function a(e,t){return!t.stats&&n.IS_SUPPORT_READDIR_WITH_FILE_TYPES?o(e,t):s(e,t)}e.read=a;function o(e,t){return t.fs.readdirSync(e,{withFileTypes:!0}).map(n=>{let a={dirent:n,name:n.name,path:i.joinPathSegments(e,n.name,t.pathSegmentSeparator)};if(a.dirent.isSymbolicLink()&&t.followSymbolicLinks)try{let e=t.fs.statSync(a.path);a.dirent=r.fs.createDirentFromStats(a.name,e)}catch(e){if(t.throwErrorOnBrokenSymbolicLink)throw e}return a})}e.readdirWithFileTypes=o;function s(e,n){return n.fs.readdirSync(e).map(a=>{let o=i.joinPathSegments(e,a,n.pathSegmentSeparator),s=t.statSync(o,n.fsStatSettings),c={name:a,path:o,dirent:r.fs.createDirentFromStats(a,s)};return n.stats&&(c.stats=s),c})}e.readdir=s})),mm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createFileSystemAdapter=e.FILE_SYSTEM_ADAPTER=void 0;let n=t(`fs`);e.FILE_SYSTEM_ADAPTER={lstat:n.lstat,stat:n.stat,lstatSync:n.lstatSync,statSync:n.statSync,readdir:n.readdir,readdirSync:n.readdirSync};function r(t){return t===void 0?e.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},e.FILE_SYSTEM_ADAPTER),t)}e.createFileSystemAdapter=r})),hm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=t(`path`),r=am(),i=mm();e.default=class{constructor(e={}){this._options=e,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=i.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,n.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new r.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue(e,t){return e??t}}})),gm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Settings=e.scandirSync=e.scandir=void 0;let t=fm(),n=pm(),r=hm();e.Settings=r.default;function i(e,n,r){if(typeof n==`function`){t.read(e,o(),n);return}t.read(e,o(n),r)}e.scandir=i;function a(e,t){let r=o(t);return n.read(e,r)}e.scandirSync=a;function o(e={}){return e instanceof r.default?e:new r.default(e)}})),_m=n(((e,t)=>{function n(e){var t=new e,n=t;function r(){var r=t;return r.next?t=r.next:(t=new e,n=t),r.next=null,r}function i(e){n.next=e,n=e}return{get:r,release:i}}t.exports=n})),vm=n(((e,t)=>{var n=_m();function r(e,t,r){if(typeof e==`function`&&(r=t,t=e,e=null),!(r>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);var o=n(a),s=null,c=null,l=0,u=null,d={push:v,drain:i,saturated:i,pause:p,paused:!1,get concurrency(){return r},set concurrency(e){if(!(e>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);if(r=e,!d.paused)for(;s&&l<r;)l++,b()},running:f,resume:g,idle:_,length:m,getQueue:h,unshift:y,empty:i,kill:x,killAndDrain:S,error:w,abort:C};return d;function f(){return l}function p(){d.paused=!0}function m(){for(var e=s,t=0;e;)e=e.next,t++;return t}function h(){for(var e=s,t=[];e;)t.push(e.value),e=e.next;return t}function g(){if(d.paused){if(d.paused=!1,s===null){l++,b();return}for(;s&&l<r;)l++,b()}}function _(){return l===0&&d.length()===0}function v(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?c?(c.next=f,c=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function y(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?s?(f.next=s,s=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function b(n){n&&o.release(n);var i=s;i&&l<=r?d.paused?l--:(c===s&&(c=null),s=i.next,i.next=null,t.call(e,i.value,i.worked),c===null&&d.empty()):--l===0&&d.drain()}function x(){s=null,c=null,d.drain=i}function S(){s=null,c=null,d.drain(),d.drain=i}function C(){var e=s;for(s=null,c=null;e;){var t=e.next,n=e.callback,r=e.errorHandler,a=e.value,o=e.context;e.value=null,e.callback=i,e.errorHandler=null,r&&r(Error(`abort`),a),n.call(o,Error(`abort`)),e.release(e),e=t}d.drain=i}function w(e){u=e}}function i(){}function a(){this.value=null,this.callback=i,this.next=null,this.release=i,this.context=null,this.errorHandler=null;var e=this;this.worked=function(t,n){var r=e.callback,a=e.errorHandler,o=e.value;e.value=null,e.callback=i,e.errorHandler&&a(t,o),r.call(e.context,t,n),e.release(e)}}function o(e,t,n){typeof e==`function`&&(n=t,t=e,e=null);function a(e,n){t.call(this,e).then(function(e){n(null,e)},n)}var o=r(e,a,n),s=o.push,c=o.unshift;return o.push=l,o.unshift=u,o.drained=d,o;function l(e){var t=new Promise(function(t,n){s(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function u(e){var t=new Promise(function(t,n){c(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function d(){return new Promise(function(e){process.nextTick(function(){if(o.idle())e();else{var t=o.drain;o.drain=function(){typeof t==`function`&&t(),e(),o.drain=t}}})})}}t.exports=r,t.exports.promise=o})),ym=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.joinPathSegments=e.replacePathSegmentSeparator=e.isAppliedFilter=e.isFatalError=void 0;function t(e,t){return e.errorFilter===null?!0:!e.errorFilter(t)}e.isFatalError=t;function n(e,t){return e===null||e(t)}e.isAppliedFilter=n;function r(e,t){return e.split(/[/\\]/).join(t)}e.replacePathSegmentSeparator=r;function i(e,t,n){return e===``?t:e.endsWith(n)?e+t:e+n+t}e.joinPathSegments=i})),bm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ym();e.default=class{constructor(e,n){this._root=e,this._settings=n,this._root=t.replacePathSegmentSeparator(e,n.pathSegmentSeparator)}}})),xm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=t(`events`),r=gm(),i=vm(),a=ym(),o=bm();e.default=class extends o.default{constructor(e,t){super(e,t),this._settings=t,this._scandir=r.scandir,this._emitter=new n.EventEmitter,this._queue=i(this._worker.bind(this),this._settings.concurrency),this._isFatalError=!1,this._isDestroyed=!1,this._queue.drain=()=>{this._isFatalError||this._emitter.emit(`end`)}}read(){return this._isFatalError=!1,this._isDestroyed=!1,setImmediate(()=>{this._pushToQueue(this._root,this._settings.basePath)}),this._emitter}get isDestroyed(){return this._isDestroyed}destroy(){if(this._isDestroyed)throw Error(`The reader is already destroyed`);this._isDestroyed=!0,this._queue.killAndDrain()}onEntry(e){this._emitter.on(`entry`,e)}onError(e){this._emitter.once(`error`,e)}onEnd(e){this._emitter.once(`end`,e)}_pushToQueue(e,t){let n={directory:e,base:t};this._queue.push(n,e=>{e!==null&&this._handleError(e)})}_worker(e,t){this._scandir(e.directory,this._settings.fsScandirSettings,(n,r)=>{if(n!==null){t(n,void 0);return}for(let t of r)this._handleEntry(t,e.base);t(null,void 0)})}_handleError(e){this._isDestroyed||!a.isFatalError(this._settings,e)||(this._isFatalError=!0,this._isDestroyed=!0,this._emitter.emit(`error`,e))}_handleEntry(e,t){if(this._isDestroyed||this._isFatalError)return;let n=e.path;t!==void 0&&(e.path=a.joinPathSegments(t,e.name,this._settings.pathSegmentSeparator)),a.isAppliedFilter(this._settings.entryFilter,e)&&this._emitEntry(e),e.dirent.isDirectory()&&a.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(n,t===void 0?void 0:e.path)}_emitEntry(e){this._emitter.emit(`entry`,e)}}})),Sm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=xm();e.default=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new t.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(t=>{n(e,t)}),this._reader.onEntry(e=>{this._storage.push(e)}),this._reader.onEnd(()=>{r(e,this._storage)}),this._reader.read()}};function n(e,t){e(t)}function r(e,t){e(null,t)}})),Cm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=t(`stream`),r=xm();e.default=class{constructor(e,t){this._root=e,this._settings=t,this._reader=new r.default(this._root,this._settings),this._stream=new n.Readable({objectMode:!0,read:()=>{},destroy:()=>{this._reader.isDestroyed||this._reader.destroy()}})}read(){return this._reader.onError(e=>{this._stream.emit(`error`,e)}),this._reader.onEntry(e=>{this._stream.push(e)}),this._reader.onEnd(()=>{this._stream.push(null)}),this._reader.read(),this._stream}}})),wm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=gm(),n=ym(),r=bm();e.default=class extends r.default{constructor(){super(...arguments),this._scandir=t.scandirSync,this._storage=[],this._queue=new Set}read(){return this._pushToQueue(this._root,this._settings.basePath),this._handleQueue(),this._storage}_pushToQueue(e,t){this._queue.add({directory:e,base:t})}_handleQueue(){for(let e of this._queue.values())this._handleDirectory(e.directory,e.base)}_handleDirectory(e,t){try{let n=this._scandir(e,this._settings.fsScandirSettings);for(let e of n)this._handleEntry(e,t)}catch(e){this._handleError(e)}}_handleError(e){if(n.isFatalError(this._settings,e))throw e}_handleEntry(e,t){let r=e.path;t!==void 0&&(e.path=n.joinPathSegments(t,e.name,this._settings.pathSegmentSeparator)),n.isAppliedFilter(this._settings.entryFilter,e)&&this._pushToStorage(e),e.dirent.isDirectory()&&n.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(r,t===void 0?void 0:e.path)}_pushToStorage(e){this._storage.push(e)}}})),Tm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=wm();e.default=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new t.default(this._root,this._settings)}read(){return this._reader.read()}}})),Em=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=t(`path`),r=gm();e.default=class{constructor(e={}){this._options=e,this.basePath=this._getValue(this._options.basePath,void 0),this.concurrency=this._getValue(this._options.concurrency,1/0),this.deepFilter=this._getValue(this._options.deepFilter,null),this.entryFilter=this._getValue(this._options.entryFilter,null),this.errorFilter=this._getValue(this._options.errorFilter,null),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,n.sep),this.fsScandirSettings=new r.Settings({followSymbolicLinks:this._options.followSymbolicLinks,fs:this._options.fs,pathSegmentSeparator:this._options.pathSegmentSeparator,stats:this._options.stats,throwErrorOnBrokenSymbolicLink:this._options.throwErrorOnBrokenSymbolicLink})}_getValue(e,t){return e??t}}})),Dm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Settings=e.walkStream=e.walkSync=e.walk=void 0;let t=Sm(),n=Cm(),r=Tm(),i=Em();e.Settings=i.default;function a(e,n,r){if(typeof n==`function`){new t.default(e,c()).read(n);return}new t.default(e,c(n)).read(r)}e.walk=a;function o(e,t){let n=c(t);return new r.default(e,n).read()}e.walkSync=o;function s(e,t){let r=c(t);return new n.default(e,r).read()}e.walkStream=s;function c(e={}){return e instanceof i.default?e:new i.default(e)}})),Om=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=t(`path`),r=am(),i=$p();e.default=class{constructor(e){this._settings=e,this._fsStatSettings=new r.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return n.resolve(this._settings.cwd,e)}_makeEntry(e,t){let n={name:t,path:t,dirent:i.fs.createDirentFromStats(t,e)};return this._settings.stats&&(n.stats=e),n}_isFatalError(e){return!i.errno.isEnoentCodeError(e)&&!this._settings.suppressErrors}}})),km=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=t(`stream`),r=am(),i=Dm(),a=Om();e.default=class extends a.default{constructor(){super(...arguments),this._walkStream=i.walkStream,this._stat=r.stat}dynamic(e,t){return this._walkStream(e,t)}static(e,t){let r=e.map(this._getFullEntryPath,this),i=new n.PassThrough({objectMode:!0});i._write=(n,a,o)=>this._getEntry(r[n],e[n],t).then(e=>{e!==null&&t.entryFilter(e)&&i.push(e),n===r.length-1&&i.end(),o()}).catch(o);for(let e=0;e<r.length;e++)i.write(e);return i}_getEntry(e,t,n){return this._getStat(e).then(e=>this._makeEntry(e,t)).catch(e=>{if(n.errorFilter(e))return null;throw e})}_getStat(e){return new Promise((t,n)=>{this._stat(e,this._fsStatSettings,(e,r)=>e===null?t(r):n(e))})}}})),Am=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Dm(),n=Om(),r=km();e.default=class extends n.default{constructor(){super(...arguments),this._walkAsync=t.walk,this._readerStream=new r.default(this._settings)}dynamic(e,t){return new Promise((n,r)=>{this._walkAsync(e,t,(e,t)=>{e===null?n(t):r(e)})})}async static(e,t){let n=[],r=this._readerStream.static(e,t);return new Promise((e,t)=>{r.once(`error`,t),r.on(`data`,e=>n.push(e)),r.once(`end`,()=>e(n))})}}})),jm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$p();e.default=class{constructor(e,t,n){this._patterns=e,this._settings=t,this._micromatchOptions=n,this._storage=[],this._fillStorage()}_fillStorage(){for(let e of this._patterns){let t=this._getPatternSegments(e),n=this._splitSegmentsIntoSections(t);this._storage.push({complete:n.length<=1,pattern:e,segments:t,sections:n})}}_getPatternSegments(e){return t.pattern.getPatternParts(e,this._micromatchOptions).map(e=>t.pattern.isDynamicPattern(e,this._settings)?{dynamic:!0,pattern:e,patternRe:t.pattern.makeRe(e,this._micromatchOptions)}:{dynamic:!1,pattern:e})}_splitSegmentsIntoSections(e){return t.array.splitWhen(e,e=>e.dynamic&&t.pattern.hasGlobStar(e.pattern))}}})),Mm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=jm();e.default=class extends t.default{match(e){let t=e.split(`/`),n=t.length,r=this._storage.filter(e=>!e.complete||e.segments.length>n);for(let e of r){let r=e.sections[0];if(!e.complete&&n>r.length||t.every((t,n)=>{let r=e.segments[n];return!!(r.dynamic&&r.patternRe.test(t)||!r.dynamic&&r.pattern===t)}))return!0}return!1}}})),Nm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$p(),n=Mm();e.default=class{constructor(e,t){this._settings=e,this._micromatchOptions=t}getFilter(e,t,n){let r=this._getMatcher(t),i=this._getNegativePatternsRe(n);return t=>this._filter(e,t,r,i)}_getMatcher(e){return new n.default(e,this._settings,this._micromatchOptions)}_getNegativePatternsRe(e){let n=e.filter(t.pattern.isAffectDepthOfReadingPattern);return t.pattern.convertPatternsToRe(n,this._micromatchOptions)}_filter(e,n,r,i){if(this._isSkippedByDeep(e,n.path)||this._isSkippedSymbolicLink(n))return!1;let a=t.path.removeLeadingDotSegment(n.path);return this._isSkippedByPositivePatterns(a,r)?!1:this._isSkippedByNegativePatterns(a,i)}_isSkippedByDeep(e,t){return this._settings.deep===1/0?!1:this._getEntryLevel(e,t)>=this._settings.deep}_getEntryLevel(e,t){let n=t.split(`/`).length;return e===``?n:n-e.split(`/`).length}_isSkippedSymbolicLink(e){return!this._settings.followSymbolicLinks&&e.dirent.isSymbolicLink()}_isSkippedByPositivePatterns(e,t){return!this._settings.baseNameMatch&&!t.match(e)}_isSkippedByNegativePatterns(e,n){return!t.pattern.matchAny(e,n)}}})),Pm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$p();e.default=class{constructor(e,t){this._settings=e,this._micromatchOptions=t,this.index=new Map}getFilter(e,n){let[r,i]=t.pattern.partitionAbsoluteAndRelative(n),a={positive:{all:t.pattern.convertPatternsToRe(e,this._micromatchOptions)},negative:{absolute:t.pattern.convertPatternsToRe(r,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:t.pattern.convertPatternsToRe(i,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return e=>this._filter(e,a)}_filter(e,n){let r=t.path.removeLeadingDotSegment(e.path);if(this._settings.unique&&this._isDuplicateEntry(r)||this._onlyFileFilter(e)||this._onlyDirectoryFilter(e))return!1;let i=this._isMatchToPatternsSet(r,n,e.dirent.isDirectory());return this._settings.unique&&i&&this._createIndexRecord(r),i}_isDuplicateEntry(e){return this.index.has(e)}_createIndexRecord(e){this.index.set(e,void 0)}_onlyFileFilter(e){return this._settings.onlyFiles&&!e.dirent.isFile()}_onlyDirectoryFilter(e){return this._settings.onlyDirectories&&!e.dirent.isDirectory()}_isMatchToPatternsSet(e,t,n){return!(!this._isMatchToPatterns(e,t.positive.all,n)||this._isMatchToPatterns(e,t.negative.relative,n)||this._isMatchToAbsoluteNegative(e,t.negative.absolute,n))}_isMatchToAbsoluteNegative(e,n,r){if(n.length===0)return!1;let i=t.path.makeAbsolute(this._settings.cwd,e);return this._isMatchToPatterns(i,n,r)}_isMatchToPatterns(e,n,r){if(n.length===0)return!1;let i=t.pattern.matchAny(e,n);return!i&&r?t.pattern.matchAny(e+`/`,n):i}}})),Fm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$p();e.default=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return t.errno.isEnoentCodeError(e)||this._settings.suppressErrors}}})),Im=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=$p();e.default=class{constructor(e){this._settings=e}getTransformer(){return e=>this._transform(e)}_transform(e){let n=e.path;return this._settings.absolute&&(n=t.path.makeAbsolute(this._settings.cwd,n),n=t.path.unixify(n)),this._settings.markDirectories&&e.dirent.isDirectory()&&(n+=`/`),this._settings.objectMode?Object.assign(Object.assign({},e),{path:n}):n}}})),Lm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=t(`path`),r=Nm(),i=Pm(),a=Fm(),o=Im();e.default=class{constructor(e){this._settings=e,this.errorFilter=new a.default(this._settings),this.entryFilter=new i.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new r.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new o.default(this._settings)}_getRootDirectory(e){return n.resolve(this._settings.cwd,e.base)}_getReaderOptions(e){let t=e.base===`.`?``:e.base;return{basePath:t,pathSegmentSeparator:`/`,concurrency:this._settings.concurrency,deepFilter:this.deepFilter.getFilter(t,e.positive,e.negative),entryFilter:this.entryFilter.getFilter(e.positive,e.negative),errorFilter:this.errorFilter.getFilter(),followSymbolicLinks:this._settings.followSymbolicLinks,fs:this._settings.fs,stats:this._settings.stats,throwErrorOnBrokenSymbolicLink:this._settings.throwErrorOnBrokenSymbolicLink,transform:this.entryTransformer.getTransformer()}}_getMicromatchOptions(){return{dot:this._settings.dot,matchBase:this._settings.baseNameMatch,nobrace:!this._settings.braceExpansion,nocase:!this._settings.caseSensitiveMatch,noext:!this._settings.extglob,noglobstar:!this._settings.globstar,posix:!0,strictSlashes:!1}}}})),Rm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Am(),n=Lm();e.default=class extends n.default{constructor(){super(...arguments),this._reader=new t.default(this._settings)}async read(e){let t=this._getRootDirectory(e),n=this._getReaderOptions(e);return(await this.api(t,e,n)).map(e=>n.transform(e))}api(e,t,n){return t.dynamic?this._reader.dynamic(e,n):this._reader.static(t.patterns,n)}}})),zm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=t(`stream`),r=km(),i=Lm();e.default=class extends i.default{constructor(){super(...arguments),this._reader=new r.default(this._settings)}read(e){let t=this._getRootDirectory(e),r=this._getReaderOptions(e),i=this.api(t,e,r),a=new n.Readable({objectMode:!0,read:()=>{}});return i.once(`error`,e=>a.emit(`error`,e)).on(`data`,e=>a.emit(`data`,r.transform(e))).once(`end`,()=>a.emit(`end`)),a.once(`close`,()=>i.destroy()),a}api(e,t,n){return t.dynamic?this._reader.dynamic(e,n):this._reader.static(t.patterns,n)}}})),Bm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=am(),n=Dm(),r=Om();e.default=class extends r.default{constructor(){super(...arguments),this._walkSync=n.walkSync,this._statSync=t.statSync}dynamic(e,t){return this._walkSync(e,t)}static(e,t){let n=[];for(let r of e){let e=this._getFullEntryPath(r),i=this._getEntry(e,r,t);i===null||!t.entryFilter(i)||n.push(i)}return n}_getEntry(e,t,n){try{let n=this._getStat(e);return this._makeEntry(n,t)}catch(e){if(n.errorFilter(e))return null;throw e}}_getStat(e){return this._statSync(e,this._fsStatSettings)}}})),Vm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Bm(),n=Lm();e.default=class extends n.default{constructor(){super(...arguments),this._reader=new t.default(this._settings)}read(e){let t=this._getRootDirectory(e),n=this._getReaderOptions(e);return this.api(t,e,n).map(n.transform)}api(e,t,n){return t.dynamic?this._reader.dynamic(e,n):this._reader.static(t.patterns,n)}}})),Hm=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;let n=t(`fs`),r=t(`os`),i=Math.max(r.cpus().length,1);e.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:n.lstat,lstatSync:n.lstatSync,stat:n.stat,statSync:n.statSync,readdir:n.readdir,readdirSync:n.readdirSync},e.default=class{constructor(e={}){this._options=e,this.absolute=this._getValue(this._options.absolute,!1),this.baseNameMatch=this._getValue(this._options.baseNameMatch,!1),this.braceExpansion=this._getValue(this._options.braceExpansion,!0),this.caseSensitiveMatch=this._getValue(this._options.caseSensitiveMatch,!0),this.concurrency=this._getValue(this._options.concurrency,i),this.cwd=this._getValue(this._options.cwd,process.cwd()),this.deep=this._getValue(this._options.deep,1/0),this.dot=this._getValue(this._options.dot,!1),this.extglob=this._getValue(this._options.extglob,!0),this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!0),this.fs=this._getFileSystemMethods(this._options.fs),this.globstar=this._getValue(this._options.globstar,!0),this.ignore=this._getValue(this._options.ignore,[]),this.markDirectories=this._getValue(this._options.markDirectories,!1),this.objectMode=this._getValue(this._options.objectMode,!1),this.onlyDirectories=this._getValue(this._options.onlyDirectories,!1),this.onlyFiles=this._getValue(this._options.onlyFiles,!0),this.stats=this._getValue(this._options.stats,!1),this.suppressErrors=this._getValue(this._options.suppressErrors,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!1),this.unique=this._getValue(this._options.unique,!0),this.onlyDirectories&&(this.onlyFiles=!1),this.stats&&(this.objectMode=!0),this.ignore=[].concat(this.ignore)}_getValue(e,t){return e===void 0?t:e}_getFileSystemMethods(t={}){return Object.assign(Object.assign({},e.DEFAULT_FILE_SYSTEM_ADAPTER),t)}}})),Um=e(n(((e,t)=>{let n=em(),r=Rm(),i=zm(),a=Vm(),o=Hm(),s=$p();async function c(e,t){u(e);let n=l(e,r.default,t),i=await Promise.all(n);return s.array.flatten(i)}(function(e){e.glob=e,e.globSync=t,e.globStream=r,e.async=e;function t(e,t){u(e);let n=l(e,a.default,t);return s.array.flatten(n)}e.sync=t;function r(e,t){u(e);let n=l(e,i.default,t);return s.stream.merge(n)}e.stream=r;function c(e,t){u(e);let r=[].concat(e),i=new o.default(t);return n.generate(r,i)}e.generateTasks=c;function d(e,t){u(e);let n=new o.default(t);return s.pattern.isDynamicPattern(e,n)}e.isDynamicPattern=d;function f(e){return u(e),s.path.escape(e)}e.escapePath=f;function p(e){return u(e),s.path.convertPathToPattern(e)}e.convertPathToPattern=p,(function(e){function t(e){return u(e),s.path.escapePosixPath(e)}e.escapePath=t;function n(e){return u(e),s.path.convertPosixPathToPattern(e)}e.convertPathToPattern=n})(e.posix||={}),(function(e){function t(e){return u(e),s.path.escapeWindowsPath(e)}e.escapePath=t;function n(e){return u(e),s.path.convertWindowsPathToPattern(e)}e.convertPathToPattern=n})(e.win32||={})})(c||={});function l(e,t,r){let i=[].concat(e),a=new o.default(r),s=n.generate(i,a),c=new t(a);return s.map(c.read,c)}function u(e){if(![].concat(e).every(e=>s.string.isString(e)&&!s.string.isEmpty(e)))throw TypeError(`Patterns must be a string (non empty) or an array of strings`)}t.exports=c}))(),1);const Wm={"win32-x64":{local:`napi-script-runtime.win32-x64-msvc`,suffix:`win32-x64-msvc`},"linux-x64":{local:`napi-script-runtime.linux-x64-gnu`,suffix:`linux-x64-gnu`},"linux-arm64":{local:`napi-script-runtime.linux-arm64-gnu`,suffix:`linux-arm64-gnu`},"darwin-arm64":{local:`napi-script-runtime.darwin-arm64`,suffix:`darwin-arm64`},"darwin-x64":{local:`napi-script-runtime.darwin-x64`,suffix:`darwin-x64`}};let Gm,Km;function qm(){let e=Wm[`${c.platform}-${c.arch}`];if(e!=null)return e;throw Error(`Unsupported platform for @truenine/script-runtime native binding: ${c.platform}-${c.arch}`)}function Jm(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.validate_public_path==`function`||typeof t.validatePublicPath==`function`||typeof t.resolve_public_path==`function`||typeof t.resolvePublicPath==`function`}function Ym(e,t,n){let r=e instanceof Error?e.message:String(e),i=t instanceof Error?t.message:String(t);return Error([`Failed to load @truenine/script-runtime native binding.`,`Tried local binary "./${Wm[`${c.platform}-${c.arch}`]?.local??`unknown`}.node" and package "@truenine/memory-sync-cli-${n}".`,`Local error: ${r}`,`Package error: ${i}`,"Run `pnpm -F @truenine/script-runtime run build` to build the native module."].join(`
|
|
195
|
-
`))}function Xm(e,t){let n=`@truenine/memory-sync-cli-${t}`;try{let t=e(n).scriptRuntime;if(Jm(t))return t}catch{}let r=f(e.resolve(`${n}/package.json`)),a=i.readdirSync(r).filter(e=>e.startsWith(`napi-script-runtime.`)&&e.endsWith(`.node`)).sort();for(let t of a){let n=e(p(r,t));if(Jm(n))return n}throw Error(`Package "${n}" does not export a scriptRuntime binding or contain a compatible native module`)}function Zm(){let e=r(import.meta.url),{local:t,suffix:n}=qm();try{return e(`./${t}.node`)}catch(t){try{return Xm(e,n)}catch(e){throw Ym(t,e,n)}}}function Qm(){if(Gm!=null)return Gm;if(Km!=null)throw Km;try{return Gm=Zm(),Gm}catch(e){throw Km=e instanceof Error?e:Error(String(e)),Km}}function $m(e,t,n){let r=Qm(),i=r.resolve_public_path??r.resolvePublicPath;if(i==null)throw Error(`resolve_public_path native binding is unavailable`);return i(e,t,n)}function eh(){let e=[l(new URL(`./resolve-proxy-worker.mjs`,import.meta.url)),l(new URL(`./script-runtime-worker.mjs`,import.meta.url))];for(let t of e)if(i.existsSync(t))return t;return e[0]}function th(e,t,n,r=5e3){return $m(e,JSON.stringify({...t,workerPath:eh(),timeoutMs:r}),n)}const nh={SRC:`src`,DIST:`dist`,SKILLS:`skills`,COMMANDS:`commands`,AGENTS:`agents`,RULES:`rules`,APP:`app`,IDEA:`.idea`,IDEA_CODE_STYLES:`.idea/codeStyles`,VSCODE:`.vscode`,ZED:`.zed`},rh={GLOBAL_MEMORY:`global.mdx`,GLOBAL_MEMORY_SRC:`global.src.mdx`,WORKSPACE_MEMORY:`workspace.mdx`,WORKSPACE_MEMORY_SRC:`workspace.src.mdx`,EDITOR_CONFIG:`.editorconfig`,IDEA_GITIGNORE:`.idea/.gitignore`,IDEA_PROJECT_XML:`.idea/codeStyles/Project.xml`,IDEA_CODE_STYLE_CONFIG_XML:`.idea/codeStyles/codeStyleConfig.xml`,VSCODE_SETTINGS:`.vscode/settings.json`,VSCODE_EXTENSIONS:`.vscode/extensions.json`,ZED_SETTINGS:`.zed/settings.json`,QODER_IGNORE:`.qoderignore`,CURSOR_IGNORE:`.cursorignore`,WARP_INDEX_IGNORE:`.warpindexignore`,AI_IGNORE:`.aiignore`,CODEIUM_IGNORE:`.codeiumignore`};nh.SKILLS,nh.COMMANDS,nh.AGENTS,nh.RULES,rh.GLOBAL_MEMORY_SRC,rh.WORKSPACE_MEMORY_SRC,nh.SKILLS,nh.COMMANDS,nh.AGENTS,nh.RULES,rh.GLOBAL_MEMORY,rh.WORKSPACE_MEMORY,nh.APP,nh.APP,nh.IDEA,nh.IDEA_CODE_STYLES,nh.VSCODE,nh.ZED,rh.EDITOR_CONFIG,rh.IDEA_GITIGNORE,rh.IDEA_PROJECT_XML,rh.IDEA_CODE_STYLE_CONFIG_XML,rh.VSCODE_SETTINGS,rh.VSCODE_EXTENSIONS,rh.ZED_SETTINGS,rh.QODER_IGNORE,rh.CURSOR_IGNORE,rh.WARP_INDEX_IGNORE,rh.AI_IGNORE,rh.CODEIUM_IGNORE;let ih=function(e){return e.Output=`output`,e}({}),ah=function(e){return e.GlobalMemory=`globalMemory`,e.ProjectRootMemory=`projectRootMemory`,e.ProjectChildrenMemory=`projectChildrenMemory`,e.Command=`command`,e.SubAgent=`subAgent`,e.Skill=`skill`,e.SkillChildDoc=`skillChildDoc`,e.SkillResource=`skillResource`,e.SkillMcpConfig=`skillMcpConfig`,e.Readme=`readme`,e.Rule=`rule`,e}({}),oh=function(e){return e.Relative=`relative`,e.Absolute=`absolute`,e.Root=`root`,e}({}),sh=function(e){return e.VSCode=`vscode`,e.Zed=`zed`,e.IntellijIDEA=`intellijIdea`,e.Git=`git`,e.EditorConfig=`editorconfig`,e.Original=`original`,e}({}),ch=function(e){return e.UserHome=`userHome`,e.External=`external`,e}({});const lh=`proxy.ts`,uh=`.gitignore`,dh=`.git/info/exclude`,fh=[rh.QODER_IGNORE,rh.CURSOR_IGNORE,rh.WARP_INDEX_IGNORE,rh.AI_IGNORE,rh.CODEIUM_IGNORE,`.kiroignore`,`.traeignore`],ph=[uh,dh,rh.EDITOR_CONFIG,rh.VSCODE_SETTINGS,rh.VSCODE_EXTENSIONS,rh.ZED_SETTINGS,rh.IDEA_PROJECT_XML,rh.IDEA_CODE_STYLE_CONFIG_XML,rh.IDEA_GITIGNORE,...fh],mh=new Map;function hh(e){let t=e.split(/[\\/]+/).filter(e=>e.length>0).join(`/`);if(t.length===0)throw Error(`public target relative path cannot be empty`);return t}function gh(e){return u.join(e,`public`)}function _h(e){return u.join(gh(e),lh)}function vh(e){return e?.command??`execute`}function yh(e,t){return u.resolve(t?.workspaceDir??u.dirname(e))}function bh(e,t,n){return{cwd:t,workspaceDir:t,aindexDir:u.resolve(e),command:n,platform:c.platform}}function xh(e,t,n){return th(e,t,n)}function Sh(e,t,n){let r=hh(t);if(r===`proxy.ts`)return lh;let a=_h(e);if(!(i.existsSync(a)&&i.statSync(a).isFile()))return r;let o=vh(n),s=yh(e,n),c=[a,s,o,r].join(`::`),l=mh.get(c);if(l!=null)return l;let u=xh(a,bh(e,s,o),r);return mh.set(c,u),u}function Ch(e,t,n){let r=Sh(e,t,n);return u.join(gh(e),...r.split(/[\\/]+/))}function wh(e,t){let n=new Set([Ch(e,lh)]);for(let r of ph)n.add(Ch(e,r,t));return[...n]}function Th(e,t,n,r,i){let a=Ch(n,t,i);if(!(r.existsSync(a)&&r.statSync(a).isFile()))return;let o=r.readFileSync(a,`utf8`);return{type:e,content:o,length:o.length,filePathKind:oh.Absolute,dir:{pathKind:oh.Absolute,path:a,getDirectoryName:()=>u.basename(a)}}}const Eh=`.aindex`,Dh=`.tnmsc.json`,Oh=/^[A-Za-z]:[\\/]/u,kh=/%([^%]+)%/gu,Ah=/\$\{([A-Za-z_]\w*)\}/gu,jh=/\$([A-Za-z_]\w*)/gu;function Mh(e){return e!=null&&`effectiveHomeDir`in e&&`expandedEnv`in e}function Nh(e){return e?.fs??i}function Ph(e){return e?.platform??c.platform}function Fh(e){return e?.release??g.release()}function Ih(e){return e?.homedir??g.homedir()}function Lh(e){return e?.env??c.env}function Rh(e){return e?.windowsUsersRoot??`/mnt/c/Users`}function zh(e){return u.posix.normalize(e.replaceAll(`\\`,`/`))}function Bh(e,t){let n=zh(e),r=zh(t);return n===r?!0:n.startsWith(`${r}/`)}function Vh(e,t){if(typeof e!=`string`)return;let n=e.trim();if(n.length===0)return;let r=[Zh(n),zh(n)];for(let e of r)if(e!=null&&Bh(e,t))return zh(e)}function Hh(e){let t=Lh(e),n=zh(Rh(e)),r=t.HOMEDRIVE,i=t.HOMEPATH,a=[Vh(t.USERPROFILE,n),typeof r==`string`&&r.length>0&&typeof i==`string`&&i.length>0?Vh(`${r}${i}`,n):void 0,Vh(t.HOME,n)];return[...new Set(a.filter(e=>e!=null))]}function Uh(e){let t=zh(e);return u.posix.dirname(u.posix.dirname(t))}function Wh(e,t){let n=Hh(t);if(n.length<=0)return e.length===1?e[0]:void 0;for(let t of n){let n=e.find(e=>Uh(e)===t);if(n!=null)return n}}function Gh(e,t){try{return e.statSync(t).isDirectory()}catch{return!1}}function Kh(e,t){try{return e.statSync(t).isFile()}catch{return!1}}function qh(e){return e===`win32`?u.win32:u.posix}function Jh(e,t,n){let r={};for(let[t,n]of Object.entries(e))typeof n==`string`&&(r[t]=n);if(n===t)return r;r.HOME=n,r.USERPROFILE=n;let i=/^\/mnt\/([a-zA-Z])\/(.+)$/u.exec(n);if(i==null)return r;let a=i[1],o=i[2];return a==null||o==null?r:(r.HOMEDRIVE=`${a.toUpperCase()}:`,r.HOMEPATH=`\\${o.replaceAll(`/`,`\\`)}`,r)}function Yh(e,t){let n=(e,n)=>t[n]??e;return e.replaceAll(kh,n).replaceAll(Ah,n).replaceAll(jh,n)}function Xh(e,t,n){if(e===`~`)return t;if(!(e.startsWith(`~/`)||e.startsWith(`~\\`)))return e;let r=qh(n),i=n===`win32`?e.slice(2).replaceAll(`/`,`\\`):e.slice(2).replaceAll(`\\`,`/`);return r.resolve(t,i)}function Zh(e){if(!Oh.test(e))return;let t=e.slice(0,1).toLowerCase(),n=e.slice(2).replaceAll(`\\`,`/`).replace(/^\/+/u,``),r=`/mnt/${t}`;return n.length===0?r:u.posix.join(r,n)}function Qh(e,t){return t===`win32`?u.win32.normalize(e.replaceAll(`/`,`\\`)):u.posix.normalize(e)}function $h(e){if(Ph(e)!==`linux`)return!1;let t=Lh(e);return typeof t.WSL_DISTRO_NAME==`string`&&t.WSL_DISTRO_NAME.length>0||typeof t.WSL_INTEROP==`string`&&t.WSL_INTEROP.length>0?!0:Fh(e).toLowerCase().includes(`microsoft`)}function eg(e){let t=Nh(e),n=Rh(e);if(!Gh(t,n))return[];try{let e=t.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>u.join(n,e.name,Eh,Dh)).filter(e=>t.existsSync(e)&&Kh(t,e));return e.sort((e,t)=>e.localeCompare(t)),e}catch{return[]}}function tg(e){let t=Ph(e),n=Ih(e),r=$h(e),i=r?eg(e):[],a=r?Wh(i,e):void 0,o=a==null?n:Uh(a);return{platform:t,isWsl:r,nativeHomeDir:n,effectiveHomeDir:o,globalConfigCandidates:i,...a!=null&&{selectedGlobalConfigPath:a},...a!=null&&{wslHostHomeDir:o},windowsUsersRoot:Rh(e),expandedEnv:Jh(Lh(e),n,o)}}function ng(e){return tg(e).effectiveHomeDir}function rg(e){let t=tg(e);return t.selectedGlobalConfigPath==null?u.join(t.effectiveHomeDir,Eh,Dh):t.selectedGlobalConfigPath}function ig(e){let t=tg(e);if(!t.isWsl||t.selectedGlobalConfigPath!=null)return rg(e);let n=`"${t.windowsUsersRoot}/*/${Eh}/${Dh}"`;throw t.globalConfigCandidates.length===0?Error(`WSL host config file not found under ${n}.`):Hh(e).length>0?Error(`WSL host config file for the current Windows user was not found under ${n}.`):Error(`WSL host config file could not be matched to the current Windows user under ${n}.`)}function ag(e,t){let n=Mh(t)?t:tg(t),r=Yh(e,n.expandedEnv);if(r=Xh(r,n.effectiveHomeDir,n.platform),!n.isWsl)return Qh(r,n.platform);let i=Zh(r);return i==null?(r.startsWith(n.effectiveHomeDir)||r.startsWith(`/mnt/`)||r.startsWith(`/`))&&(r=r.replaceAll(`\\`,`/`)):r=i,Qh(r,n.platform)}var og=class extends Error{operation;violations;constructor(e,t){super(zg(e,t)),this.name=`ProtectedDeletionGuardError`,this.operation=e,this.violations=t}};const sg=[`skills`,`commands`,`subAgents`,`rules`,`app`,`ext`,`arch`],cg=[`globalPrompt`,`workspacePrompt`];function lg(e){let t=c.env.XDG_CONFIG_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.config`)}function ug(e){let t=c.env.XDG_DATA_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.local`,`share`)}function dg(e){let t=c.env.XDG_STATE_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.local`,`state`)}function fg(e){let t=c.env.XDG_CACHE_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.cache`)}function pg(e){if(e!=null){if(typeof e.getAbsolutePath==`function`)try{let t=e.getAbsolutePath();if(t.length>0)return u.resolve(t)}catch{}if(e.pathKind===`absolute`)return u.resolve(e.path);if(typeof e.basePath==`string`&&e.basePath.length>0)return u.resolve(e.basePath,e.path)}}function mg(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?ag(e):e}function hg(e){return u.resolve(mg(e))}function gg(e){let t=u.normalize(hg(e));return c.platform===`win32`?t.toLowerCase():t}function _g(e){let{root:t}=u.parse(e);return e===t?e:e.endsWith(u.sep)?e.slice(0,-1):e}function vg(e,t){let n=_g(e),r=_g(t);return n===r?!0:n.startsWith(`${r}${u.sep}`)}function yg(e){let t=hg(e),n=new Set([gg(t)]);try{if(i.existsSync(t)){let e=i.realpathSync.native(t);n.add(gg(e))}}catch{}return[...n]}function bg(e,t,n,r,i=`path`){return{path:hg(e),protectionMode:t,reason:n,source:r,matcher:i}}function xg(e){let t=gg(e.path);return{...e,path:hg(e.path),comparisonKeys:yg(e.path),normalizedPath:t,specificity:_g(t).length}}function Sg(e){let t=new Map;for(let n of e){let e=xg(n);t.set(`${e.protectionMode}:${e.normalizedPath}`,e)}return[...t.values()].sort((e,t)=>{let n=t.specificity-e.specificity;return n===0?e.protectionMode===t.protectionMode?e.path.localeCompare(t.path):e.protectionMode===`recursive`?-1:1:n})}function Cg(e){return hg(e).replaceAll(`\\`,`/`)}function wg(e){let t=[];for(let n of e){if(n.matcher!==`glob`){t.push(bg(n.path,n.protectionMode,n.reason,n.source));continue}let e=Um.default.sync(Cg(n.path),{onlyFiles:!1,dot:!0,absolute:!0,followSymbolicLinks:!1});for(let r of e)t.push(bg(r,n.protectionMode,n.reason,n.source))}return t}function Tg(e,t,n){return n===`direct`?vg(t,e):vg(e,t)||vg(t,e)}function Eg(e,t){let n=hg(e);try{if(i.existsSync(n)&&i.lstatSync(n).isDirectory())return`recursive`}catch{}return t}function Dg(){let e=ng();return[bg(u.parse(e).root,`direct`,`built-in dangerous root path`,`built-in-dangerous-root`),bg(e,`direct`,`built-in dangerous home directory`,`built-in-dangerous-root`),bg(lg(e),`direct`,`built-in dangerous config directory`,`built-in-dangerous-root`),bg(ug(e),`direct`,`built-in dangerous data directory`,`built-in-dangerous-root`),bg(dg(e),`direct`,`built-in dangerous state directory`,`built-in-dangerous-root`),bg(fg(e),`direct`,`built-in dangerous cache directory`,`built-in-dangerous-root`),bg(u.join(e,`.aindex`),`direct`,`built-in global aindex directory`,`built-in-dangerous-root`),bg(u.join(e,`.aindex`,`.tnmsc.json`),`direct`,`built-in global config file`,`built-in-config`)]}function Og(e,t,n){let r=[bg(e,`direct`,`workspace root`,`workspace-reserved`),bg(u.join(e,`aindex`),`direct`,`reserved workspace aindex root`,`workspace-reserved`),bg(u.join(e,`knowladge`),`direct`,`reserved workspace knowladge root`,`workspace-reserved`)];for(let e of t)r.push(bg(e,`direct`,`workspace project root`,`workspace-project-root`));return n&&r.push(bg(u.join(e,`aindex`,`dist`,`**`,`*.mdx`),`direct`,`reserved workspace aindex dist mdx files`,`workspace-reserved`,`glob`),bg(u.join(e,`aindex`,`app`,`**`,`*.mdx`),`direct`,`reserved workspace aindex app mdx files`,`workspace-reserved`,`glob`)),r}function kg(e){return[bg(e,`direct`,`resolved aindex root`,`aindex-root`)]}function Ag(e,t){return wh(e,t)}function jg(e,t,n){let r=[];for(let n of sg)r.push(bg(u.join(t,e.aindex[n].src),`recursive`,`configured aindex ${n} source directory`,`configured-aindex-source`));for(let n of cg)r.push(bg(u.join(t,e.aindex[n].src),`direct`,`configured aindex ${n} source file`,`configured-aindex-source`));for(let e of Ag(t,n))r.push(bg(e,`direct`,`known aindex input config file`,`known-aindex-config`));return r}function Mg(e){let t=[],n=new Set,r=(e,r,i,a)=>{if(e==null||e.length===0)return;let o=bg(e,r,i,a),s=`${o.protectionMode}:${gg(o.path)}`;n.has(s)||(n.add(s),t.push(o))},i=(e,t,n,i)=>{let a=pg(e);a!=null&&r(a,t,n,i)};i(e.globalMemory?.dir,`recursive`,`global memory source directory`,`collected-input-source`);for(let t of e.commands??[])i(t.dir,`recursive`,`command source directory`,`collected-input-source`);for(let t of e.subAgents??[])i(t.dir,`recursive`,`sub-agent source directory`,`collected-input-source`);for(let t of e.rules??[])i(t.dir,`recursive`,`rule source directory`,`collected-input-source`);for(let t of e.skills??[]){i(t.dir,`recursive`,`skill source directory`,`collected-input-source`);for(let e of t.childDocs??[])i(e.dir,`recursive`,`skill child document directory`,`collected-input-source`);for(let e of t.resources??[])e.sourcePath==null||e.sourcePath.length===0||r(e.sourcePath,Eg(e.sourcePath,`direct`),`skill resource source path`,`collected-input-source`)}for(let t of e.vscodeConfigFiles??[])i(t.dir,`direct`,`vscode input config file`,`collected-input-config`);for(let t of e.zedConfigFiles??[])i(t.dir,`direct`,`zed input config file`,`collected-input-config`);for(let t of e.jetbrainsConfigFiles??[])i(t.dir,`direct`,`jetbrains input config file`,`collected-input-config`);for(let t of e.editorConfigFiles??[])i(t.dir,`direct`,`editorconfig input file`,`collected-input-config`);for(let t of e.aiAgentIgnoreConfigFiles??[])r(t.sourcePath,`direct`,`AI agent ignore config file`,`collected-input-config`);if(e.aindexDir!=null)for(let t of Ag(e.aindexDir,{workspaceDir:e.workspace.directory.path}))r(t,`direct`,`known aindex input config file`,`known-aindex-config`);return t}function Ng(e){let t=[];for(let n of e.exactProtectedPaths??[])t.push(bg(n,`direct`,`legacy direct protected path`,`legacy-direct`));for(let n of e.subtreeProtectedPaths??[])t.push(bg(n,`recursive`,`legacy recursive protected path`,`legacy-recursive`));return t}function Pg(e={}){let t=e.includeReservedWorkspaceContentRoots??!0,n=Sg(wg([...Dg(),...Ng(e),...e.workspaceDir==null?[]:Og(e.workspaceDir,e.projectRoots??[],t),...e.aindexDir==null?[]:kg(e.aindexDir),...e.rules??[]]));return{rules:n.map(e=>({path:e.path,protectionMode:e.protectionMode,reason:e.reason,source:e.source,...e.matcher==null?{}:{matcher:e.matcher}})),exactProtectedPaths:n.filter(e=>e.protectionMode===`direct`).map(e=>e.path),subtreeProtectedPaths:n.filter(e=>e.protectionMode===`recursive`).map(e=>e.path),compiledRules:n}}function Fg(e){let t=new Set;for(let n of e.workspace.projects){if(n.isWorkspaceRootProject===!0)continue;let e=n.dirFromWorkspacePath?.getAbsolutePath?.();e!=null&&e.length>0&&t.add(hg(e))}return[...t]}function Ig(e,t){return t==null?e:e.specificity===t.specificity?e.protectionMode===t.protectionMode?e.path.localeCompare(t.path)<0?e:t:e.protectionMode===`recursive`?e:t:e.specificity>t.specificity?e:t}function Lg(e,t){let n=hg(e),r=yg(n),i;for(let e of t.compiledRules){let t=!1;for(let n of r){for(let r of e.comparisonKeys)if(Tg(n,r,e.protectionMode)){i=Ig(e,i),t=!0;break}if(t)break}}if(i!=null)return{targetPath:n,protectedPath:i.path,protectionMode:i.protectionMode,reason:i.reason,source:i.source}}function Rg(e,t){let n=[],r=new Map;for(let i of e){let e=hg(i),a=Lg(e,t);if(a==null){n.push(e);continue}r.has(a.targetPath)||r.set(a.targetPath,a)}return{safePaths:n,violations:[...r.values()].sort((e,t)=>e.targetPath.localeCompare(t.targetPath))}}function zg(e,t){let n=t.map(e=>e.targetPath).join(`, `);return`Protected deletion guard blocked ${e} for ${t.length} path(s): ${n}`}function Bg(e,t,n){e.error(ne(t,n))}var Vg=class{inputEffects=[];registeredScopes=[];name;dependsOn;_log;get log(){return this._log??=be(this.name),this._log}constructor(e,t){this.name=e,t!=null&&(this.dependsOn=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,aindexDir:i}=this.resolveBasePaths(e.userConfigOptions),a={logger:this.log,fs:e.fs,path:e.path,glob:e.glob,spawn:m,userConfigOptions:e.userConfigOptions,workspaceDir:r,aindexDir: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,modifiedFileCount:t.modifiedFiles.length}),t.deletedFiles!=null&&t.deletedFiles.length>0&&this.log.debug({action:`inputEffect`,name:e.name,deletedFileCount:t.deletedFiles.length});else throw t.error??Error(`Input effect failed: ${e.name}`);n.push(t)}catch(t){let r=t instanceof Error?t:Error(String(t));throw this.logInputEffectFailure(e.name,r),n.push({success:!1,error:r,description:`Input effect failed: ${e.name}`}),r}}return n}logInputEffectFailure(e,t){if(t instanceof og){Bg(this.log,t.operation,t.violations);return}this.log.error(C({code:`INPUT_EFFECT_FAILED`,title:`Input effect failed: ${e}`,rootCause:b(`The input effect "${e}" failed before tnmsc could finish preprocessing.`,`Underlying error: ${t.message}`),exactFix:b(`Inspect the effect inputs and fix the failing file, path, or environment condition before retrying tnmsc.`),possibleFixes:[b(`Re-run the command after fixing the referenced path or generated artifact.`),b(`Add a focused regression test if this effect should handle the failure more gracefully.`)],details:{effectName:e,errorMessage:t.message}}))}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.aindex?.dir??`aindex`;return{workspaceDir:n,aindexDir:u.join(n,r)}}resolvePath(e,t){let n=e;return n.includes(ux.WORKSPACE)&&(n=n.replace(ux.WORKSPACE,t)),n.startsWith(ux.USER_HOME)?ag(n):u.normalize(ag(n))}resolveAindexPath(e,t){return u.join(t,e)}readAndParseMarkdown(e,t){return Cp(t.readFileSync(e,`utf8`))}};const Hg=/\r?\n/u;function Ug(e={}){let{filePath:t,position:n,sourceText:r,expression:i,exportName:a,nodeType:o,phase:s,hint:c,cause:l}=e,u=n?.start.line,d=n?.start.column,f=n?.end?.line,p=n?.end?.column,m=n?.start.offset,h=n?.end?.offset,g=u!=null&&r!=null?Wg(r,u):void 0,_=Gg(r,m,h,g),v=u!=null&&d!=null&&g!=null?Kg(u,d,p,g):void 0,y={};return t!=null&&t.length>0&&Object.assign(y,{filePath:t}),u!=null&&Object.assign(y,{line:u}),d!=null&&Object.assign(y,{column:d}),f!=null&&Object.assign(y,{endLine:f}),p!=null&&Object.assign(y,{endColumn:p}),m!=null&&Object.assign(y,{offset:m}),h!=null&&Object.assign(y,{endOffset:h}),_!=null&&_.length>0&&Object.assign(y,{snippet:_}),g!=null&&g.length>0&&Object.assign(y,{sourceLine:g}),v!=null&&v.length>0&&Object.assign(y,{codeFrame:v}),i!=null&&i.length>0&&Object.assign(y,{expression:i}),a!=null&&a.length>0&&Object.assign(y,{exportName:a}),o!=null&&o.length>0&&Object.assign(y,{nodeType:o}),s!=null&&s.length>0&&Object.assign(y,{phase:s}),c!=null&&c.length>0&&Object.assign(y,{hint:c}),l!=null&&l.length>0&&Object.assign(y,{cause:l}),y}function Wg(e,t){return e.split(Hg)[t-1]}function Gg(e,t,n,r){if(e!=null&&t!=null){let r=n!=null&&n>=t?n:t+1,i=e.slice(t,r).trim();if(i.length>0)return i.length>240?`${i.slice(0,240)}...`:i}let i=r?.trim();if(i!=null&&i.length>0)return i}function Kg(e,t,n,r){let i=`${e} | `,a=` `.repeat(i.length+Math.max(0,t-1)),o=Math.max(1,(n??t+1)-t);return`${i}${r}\n${a}${`^`.repeat(o)}`}function qg(e){if(!(e.line==null||e.column==null))return e.endLine!=null&&e.endColumn!=null?`${e.line}:${e.column}-${e.endLine}:${e.endColumn}`:`${e.line}:${e.column}`}function Jg(e,t){let n=[e];t.phase!=null&&n.push(`phase: ${t.phase}`),t.nodeType!=null&&n.push(`node: ${t.nodeType}`),t.filePath!=null&&n.push(`file: ${t.filePath}`);let r=qg(t);return r!=null&&n.push(`location: ${r}`),t.expression!=null&&n.push(`expression: ${t.expression}`),t.exportName!=null&&n.push(`export: ${t.exportName}`),t.sourceLine!=null&&n.push(`source line: ${t.sourceLine.trimEnd()}`),t.codeFrame!=null&&(n.push(`code frame:`),n.push(t.codeFrame)),t.hint!=null&&n.push(`hint: ${t.hint}`),t.cause!=null&&n.push(`cause: ${t.cause}`),n.join(`
|
|
196
|
-
`)}function
|
|
197
|
-
`))}}function f_(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 p_(e,t){return e===null?!1:t.components.has(e)||a_(e)}async function m_(e){return async(t,n)=>(await e({type:`root`,children:t},n)).children}async function h_(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 m_(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})}}const g_=/language-(\w+)/u;function __(e,t,n){return{...e.filePath!=null&&{filePath:e.filePath},...e.sourceText!=null&&{sourceText:e.sourceText},...n?.position!=null&&{position:n.position},nodeType:t}}function v_(e,t){let n=e.name?.toLowerCase();if(n==null)return null;switch(n){case`pre`:return x_(e,t);case`a`:return S_(e,t);case`strong`:case`b`:return C_(e,t);case`em`:case`i`:return w_(e,t);case`img`:return T_(e,t);case`blockquote`:return E_(e,t);default:return null}}function y_(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`?c_(r.value.value,n.scope,__(n,`mdxJsxAttributeValueExpression`,r)):r.value===null?``:null}function b_(e,t){let n=``;for(let r of e.children){if(r.type===`text`){n+=r.value;continue}if(r.type===`mdxTextExpression`){n+=c_(r.value,t.scope,__(t,`mdxTextExpression`,r));continue}(r.type===`mdxJsxFlowElement`||r.type===`mdxJsxTextElement`)&&(n+=b_(r,t))}return n}function x_(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=y_(n,`className`,t)??``,i=g_.exec(r)?.[1],a=b_(n,t);return[{type:`code`,lang:i??null,value:a.trim()}]}function S_(e,t){let n=y_(e,`href`,t);if(n==null||n===``)return null;let r=b_(e,t);return[{type:`paragraph`,children:[{type:`link`,url:n,title:y_(e,`title`,t)??null,children:[{type:`text`,value:r}]}]}]}function C_(e,t){let n={type:`strong`,children:[{type:`text`,value:b_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function w_(e,t){let n={type:`emphasis`,children:[{type:`text`,value:b_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function T_(e,t){let n=y_(e,`src`,t);if(n==null||n===``)return null;let r={type:`image`,url:n,alt:y_(e,`alt`,t)??``,title:y_(e,`title`,t)??null};return e.type,[{type:`paragraph`,children:[r]}]}function E_(e,t){return[{type:`blockquote`,children:[{type:`paragraph`,children:[{type:`text`,value:b_(e,t)}]}]}]}const D_=/^-?\d+(?:\.\d+)?$/u;function O_(e,t){return{...e.filePath!=null&&{filePath:e.filePath},...e.sourceText!=null&&{sourceText:e.sourceText},...t.position!=null&&{position:t.position},nodeType:t.type}}function k_(e){return e==null?!1:JSON.stringify(e).includes(`"JSX`)}async function A_(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`?j_(i.expression,t,n,e):[]}async function j_(e,t,n,r){return e.type===`JSXElement`?L_(e,t,n):e.type===`JSXFragment`?R_(e,t,n,r):e.type===`LogicalExpression`?M_(e,t,n,r):e.type===`ConditionalExpression`?N_(e,t,n,r):e.type===`SequenceExpression`?P_(e,t,n,r):e.type===`ArrayExpression`?F_(e,t,n,r):q_(e,t,r)}async function M_(e,t,n,r){let i=await I_(e.left,t,n,r);return e.operator===`&&`?G_(i)?j_(e.right,t,n,r):[]:e.operator===`||`?G_(i)?W_(e.left)?j_(e.left,t,n,r):K_(i):j_(e.right,t,n,r):e.operator===`??`?i==null?j_(e.right,t,n,r):W_(e.left)?j_(e.left,t,n,r):K_(i):[]}async function N_(e,t,n,r){return G_(await I_(e.test,t,n,r))?j_(e.consequent,t,n,r):j_(e.alternate,t,n,r)}async function P_(e,t,n,r){let i=[];for(let a of e.expressions){let e=await j_(a,t,n,r);i.push(...e)}return i}async function F_(e,t,n,r){let i=[];for(let a of e.elements)if(a!=null)if(a.type===`SpreadElement`){let e=await j_(a.argument,t,n,r);i.push(...e)}else{let e=await j_(a,t,n,r);i.push(...e)}return i}async function I_(e,t,n,r){if(W_(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 i=await I_(e.argument,t,n,r);return e.operator===`!`?!G_(i):e.operator===`-`?-i:e.operator===`+`?+i:e.operator===`typeof`?typeof i:void 0}if(e.type===`BinaryExpression`){let i=await I_(e.left,t,n,r),a=await I_(e.right,t,n,r);return e.operator===`===`?i===a:e.operator===`!==`?i!==a:e.operator===`==`?i===a:e.operator===`!=`?i!==a:e.operator===`<`?i<a:e.operator===`<=`?i<=a:e.operator===`>`?i>a:e.operator===`>=`?i>=a:e.operator===`+`?i+a:e.operator===`-`?i-a:e.operator===`*`?i*a:e.operator===`/`?i/a:e.operator===`%`?i%a:void 0}if(e.type===`LogicalExpression`){let i=await I_(e.left,t,n,r);return e.operator===`&&`?G_(i)?I_(e.right,t,n,r):i:e.operator===`||`?G_(i)?i:I_(e.right,t,n,r):e.operator===`??`?i??I_(e.right,t,n,r):void 0}if(e.type===`MemberExpression`){let i=await I_(e.object,t,n,r);if(i==null)return;if(e.computed)return i[await I_(e.property,t,n,r)];let{name:a}=e.property;return i[a]}if(e.type===`ConditionalExpression`)return G_(await I_(e.test,t,n,r))?I_(e.consequent,t,n,r):I_(e.alternate,t,n,r);let i=U_(e);if(i!==``)try{let e=c_(i,t.scope,O_(t,r));return e===`true`?!0:e===`false`?!1:e===`null`?null:e===`undefined`||e===``?void 0:D_.test(e)?Number(e):e}catch{return}}async function L_(e,t,n){let r=B_(e,t);if(r.name!=null&&p_(r.name,t)){let{processAst:e}=await Promise.resolve().then(()=>J_);return h_(r,t,e)}return v_(r,t)??(r.children.length>0?n(r.children,t):[])}async function R_(e,t,n,r){let i=[];for(let a of e.children){let e=await z_(a,t,n,r);i.push(...e)}return i}async function z_(e,t,n,r){if(e.type===`JSXElement`)return L_(e,t,n);if(e.type===`JSXFragment`)return R_(e,t,n,r);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`?[]:j_(e.expression,t,n,r):e.type===`JSXSpreadChild`?j_(e.expression,t,n,r):[]}function B_(e,t){let n=e.openingElement,r=null;n.name.type===`JSXIdentifier`?{name:r}=n.name:n.name.type===`JSXMemberExpression`?r=V_(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:U_(e.value.expression)}),i.push({type:`mdxJsxAttribute`,name:t,value:n})}else e.type===`JSXSpreadAttribute`&&i.push({type:`mdxJsxExpressionAttribute`,value:`...${U_(e.argument)}`});let a=[];for(let n of e.children){let e=H_(n,t);e!=null&&a.push(...e)}return{type:`mdxJsxFlowElement`,name:r,attributes:i,children:a}}function V_(e){return e.object.type===`JSXIdentifier`?`${e.object.name}.${e.property.name}`:`${V_(e.object)}.${e.property.name}`}function H_(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[B_(e,t)];if(e.type===`JSXFragment`){let n=[];for(let r of e.children){let e=H_(r,t);e!=null&&n.push(...e)}return n}return e.type===`JSXExpressionContainer`?e.expression.type===`JSXEmptyExpression`?null:[{type:`paragraph`,children:[{type:`text`,value:U_(e.expression)}]}]:e.type===`JSXSpreadChild`?[{type:`paragraph`,children:[{type:`text`,value:`...${U_(e.expression)}`}]}]:null}function U_(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=U_(e.object);return e.computed?`${t}[${U_(e.property)}]`:`${t}.${e.property.name}`}if(e.type===`CallExpression`)return`${U_(e.callee)}(${e.arguments.map(e=>U_(e)).join(`, `)})`;if(e.type===`BinaryExpression`||e.type===`LogicalExpression`){let t=U_(e.left),n=U_(e.right);return`(${t} ${e.operator} ${n})`}if(e.type===`UnaryExpression`){let t=U_(e.argument);return`${e.operator}${t}`}if(e.type===`ConditionalExpression`)return`(${U_(e.test)} ? ${U_(e.consequent)} : ${U_(e.alternate)})`;if(e.type===`ArrayExpression`)return`[${e.elements.filter(e=>e!=null&&e.type!==`SpreadElement`).map(e=>U_(e)).join(`, `)}]`;if(e.type===`ObjectExpression`)return`{${e.properties.filter(e=>e.type===`Property`).map(e=>`${e.key.type===`Identifier`?e.key.name:U_(e.key)}: ${U_(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+=`\${${U_(e.expressions[n])}}`);return t+="`",t}return e.type===`SpreadElement`?`...${U_(e.argument)}`:``}function W_(e){return e.type===`JSXElement`||e.type===`JSXFragment`}function G_(e){return!!e}function K_(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 q_(e,t,n){let r=U_(e);if(r===``)return[];try{return K_(c_(r,t.scope,O_(t,n)))}catch{return[]}}var J_=De({processAst:()=>Q_});const Y_=/\.\w+$/u;function X_(e,t,n){return{...e.filePath!=null&&{filePath:e.filePath},...e.sourceText!=null&&{sourceText:e.sourceText},...t.position!=null&&{position:t.position},nodeType:n}}function Z_(e){if(!(e.includes(`/`)&&Y_.test(e)))return e;let t=e.lastIndexOf(`/`);return e.slice(t+1)}async function Q_(e,t){return $_(e,t)}async function $_(e,t){let n=[];for(let r of e.children){let e=await ev(r,t);n.push(...e)}return{type:`root`,children:n}}async function ev(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(k_(r))return A_(n,t,async(e,t)=>(await Q_({type:`root`,children:e},t)).children);let a=c_(n.value,t.scope,X_(t,n,`mdxFlowExpression`));return a===``?[]:[{type:`paragraph`,children:[{type:`text`,value:a}]}]}if(e.type===`mdxJsxFlowElement`)return tv(e,t);if(e.type===`link`){let n=e,r=(await nv(n.children,t)).map(e=>e.type===`text`?{...e,value:Z_(e.value)}:e);return[{...n,children:r}]}if(!(`children`in e&&Array.isArray(e.children)))return[e];let n=await nv(e.children,t);return[{...e,children:n}]}async function tv(e,t){return e.name!=null&&p_(e.name,t)?h_(e,t,Q_):v_(e,t)??[]}async function nv(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(k_(i)){let r=await A_(e,t,async(e,t)=>(await Q_({type:`root`,children:e},t)).children);for(let e of r)n.push(e);continue}let o=c_(e.value,t.scope,X_(t,e,`mdxFlowExpression`));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:c_(e.value,t.scope,X_(t,e,`mdxTextExpression`))};n.push(a);continue}if(r.type===`mdxJsxTextElement`){let e=r;if(e.name!=null&&p_(e.name,t)){let r=await h_(e,t,Q_);for(let e of r)e.type===`paragraph`&&`children`in e?n.push(...e.children):n.push(e);continue}let i=v_(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 nv(r.children,t);if(r.type===`link`){let t=e.map(e=>e.type===`text`?{...e,value:Z_(e.value)}:e);n.push({...r,children:t});continue}n.push({...r,children:e});continue}n.push(r)}return n}const rv=/^export\s+default\s+/u,iv=/export\s+const\s+(\w+)\s*=\s*/gu,av=/^-?\d+(?:\.\d+)?$/u,ov=/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/iu,sv=/\s/u,cv=/[\w$]/u,lv=/^[\w$]+$/u;function uv(e,t={}){let n={},{yamlFrontMatter:r,scope:i,filePath:a,sourceText:o}=t;for(let t of e){let e=dv(t,i,{...a!=null&&{filePath:a},...o!=null&&{sourceText:o}});Object.assign(n,e)}let s=Object.keys(n).length>0,c=r!=null&&Object.keys(r).length>0,l;return l=s&&c?`mixed`:s?`export`:`yaml`,{fields:{...r,...n},source:l}}function dv(e,t,n={}){let r={},{filePath:i,sourceText:a}=n,o=e.value.trim(),s=rv.exec(o);if(s!=null){let n=s[0].length,c=fv(o,n);if(c!=null)try{let e=pv(c.trim(),t,i);typeof e==`object`&&e&&!Array.isArray(e)&&Object.assign(r,e)}catch(t){let n=t instanceof Error?t.message:String(t);throw new t_(`Cannot statically evaluate export default`,`default`,{...i!=null&&{filePath:i},...a!=null&&{sourceText:a},...e.position!=null&&{position:e.position},nodeType:`mdxjsEsm`,phase:`export-parsing`,cause:n})}return r}let c=iv.exec(o);for(;c!==null;){let n=c[1];if(n==null){c=iv.exec(o);continue}let s=fv(o,c.index+c[0].length);if(s==null){c=iv.exec(o);continue}try{let e=pv(s.trim(),t,i);n===`metadata`&&typeof e==`object`&&e&&!Array.isArray(e)?Object.assign(r,e):r[n]=e}catch(t){let r=t instanceof Error?t.message:String(t);throw new t_(`Cannot statically evaluate export "${n}"`,n,{...i!=null&&{filePath:i},...a!=null&&{sourceText:a},...e.position!=null&&{position:e.position},nodeType:`mdxjsEsm`,phase:`export-parsing`,cause:r})}c=iv.exec(o)}return r}function fv(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===`
|
|
198
|
-
`){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
|
|
199
|
-
`).replaceAll(`\\r`,`\r`).replaceAll(`\\t`,` `).replaceAll(`\\"`,`"`).replaceAll(`\\'`,`'`).replaceAll(`\\\\`,`\\`)}function
|
|
200
|
-
`,inConstruct:[`codeFencedLangGraveAccent`,`codeFencedLangTilde`,`codeFencedMetaGraveAccent`,`codeFencedMetaTilde`,`destinationLiteral`,`headingAtx`]},{character:` `,after:`[\\r\\n]`,inConstruct:`phrasing`},{character:` `,before:`[\\r\\n]`,inConstruct:`phrasing`},{character:` `,inConstruct:[`codeFencedLangGraveAccent`,`codeFencedLangTilde`]},{character:`!`,after:`\\[`,inConstruct:`phrasing`,notInConstruct:
|
|
201
|
-
]|$)`},{character:`&`,after:`[#A-Za-z]`,inConstruct:`phrasing`},{character:`'`,inConstruct:`titleApostrophe`},{character:`(`,inConstruct:`destinationRaw`},{before:`\\]`,character:`(`,inConstruct:`phrasing`,notInConstruct:
|
|
202
|
-
*])`},{character:`*`,inConstruct:`phrasing`,notInConstruct:
|
|
195
|
+
`))}function Xm(e,t){let n=`@truenine/memory-sync-cli-${t}`;try{let t=e(n).scriptRuntime;if(Jm(t))return t}catch{}let r=f(e.resolve(`${n}/package.json`)),a=i.readdirSync(r).filter(e=>e.startsWith(`napi-script-runtime.`)&&e.endsWith(`.node`)).sort();for(let t of a){let n=e(p(r,t));if(Jm(n))return n}throw Error(`Package "${n}" does not export a scriptRuntime binding or contain a compatible native module`)}function Zm(){let e=r(import.meta.url),{local:t,suffix:n}=qm();try{return e(`./${t}.node`)}catch(t){try{return Xm(e,n)}catch(e){throw Ym(t,e,n)}}}function Qm(){if(Gm!=null)return Gm;if(Km!=null)throw Km;try{return Gm=Zm(),Gm}catch(e){throw Km=e instanceof Error?e:Error(String(e)),Km}}function $m(e,t,n){let r=Qm(),i=r.resolve_public_path??r.resolvePublicPath;if(i==null)throw Error(`resolve_public_path native binding is unavailable`);return i(e,t,n)}function eh(){let e=[l(new URL(`./resolve-proxy-worker.mjs`,import.meta.url)),l(new URL(`./script-runtime-worker.mjs`,import.meta.url))];for(let t of e)if(i.existsSync(t))return t;return e[0]}function th(e,t,n,r=5e3){return $m(e,JSON.stringify({...t,workerPath:eh(),timeoutMs:r}),n)}const nh=[`app`,`ext`,`arch`],rh={SRC:`src`,DIST:`dist`,SKILLS:`skills`,COMMANDS:`commands`,AGENTS:`agents`,RULES:`rules`,APP:`app`,EXT:`ext`,ARCH:`arch`,IDEA:`.idea`,IDEA_CODE_STYLES:`.idea/codeStyles`,VSCODE:`.vscode`,ZED:`.zed`},ih={GLOBAL_MEMORY:`global.mdx`,GLOBAL_MEMORY_SRC:`global.src.mdx`,WORKSPACE_MEMORY:`workspace.mdx`,WORKSPACE_MEMORY_SRC:`workspace.src.mdx`,EDITOR_CONFIG:`.editorconfig`,IDEA_GITIGNORE:`.idea/.gitignore`,IDEA_PROJECT_XML:`.idea/codeStyles/Project.xml`,IDEA_CODE_STYLE_CONFIG_XML:`.idea/codeStyles/codeStyleConfig.xml`,VSCODE_SETTINGS:`.vscode/settings.json`,VSCODE_EXTENSIONS:`.vscode/extensions.json`,ZED_SETTINGS:`.zed/settings.json`,QODER_IGNORE:`.qoderignore`,CURSOR_IGNORE:`.cursorignore`,WARP_INDEX_IGNORE:`.warpindexignore`,AI_IGNORE:`.aiignore`,CODEIUM_IGNORE:`.codeiumignore`};rh.SKILLS,rh.COMMANDS,rh.AGENTS,rh.RULES,ih.GLOBAL_MEMORY_SRC,ih.WORKSPACE_MEMORY_SRC,rh.SKILLS,rh.COMMANDS,rh.AGENTS,rh.RULES,ih.GLOBAL_MEMORY,ih.WORKSPACE_MEMORY,rh.APP,rh.EXT,rh.ARCH,rh.APP,rh.EXT,rh.ARCH,rh.IDEA,rh.IDEA_CODE_STYLES,rh.VSCODE,rh.ZED,ih.EDITOR_CONFIG,ih.IDEA_GITIGNORE,ih.IDEA_PROJECT_XML,ih.IDEA_CODE_STYLE_CONFIG_XML,ih.VSCODE_SETTINGS,ih.VSCODE_EXTENSIONS,ih.ZED_SETTINGS,ih.QODER_IGNORE,ih.CURSOR_IGNORE,ih.WARP_INDEX_IGNORE,ih.AI_IGNORE,ih.CODEIUM_IGNORE;let ah=function(e){return e.Output=`output`,e}({}),oh=function(e){return e.GlobalMemory=`globalMemory`,e.ProjectRootMemory=`projectRootMemory`,e.ProjectChildrenMemory=`projectChildrenMemory`,e.Command=`command`,e.SubAgent=`subAgent`,e.Skill=`skill`,e.SkillChildDoc=`skillChildDoc`,e.SkillResource=`skillResource`,e.SkillMcpConfig=`skillMcpConfig`,e.Readme=`readme`,e.Rule=`rule`,e}({}),sh=function(e){return e.Relative=`relative`,e.Absolute=`absolute`,e.Root=`root`,e}({}),ch=function(e){return e.VSCode=`vscode`,e.Zed=`zed`,e.IntellijIDEA=`intellijIdea`,e.Git=`git`,e.EditorConfig=`editorconfig`,e.Original=`original`,e}({}),lh=function(e){return e.UserHome=`userHome`,e.External=`external`,e}({});const uh=`proxy.ts`,dh=`.gitignore`,fh=`.git/info/exclude`,ph=[ih.QODER_IGNORE,ih.CURSOR_IGNORE,ih.WARP_INDEX_IGNORE,ih.AI_IGNORE,ih.CODEIUM_IGNORE,`.kiroignore`,`.traeignore`],mh=[dh,fh,ih.EDITOR_CONFIG,ih.VSCODE_SETTINGS,ih.VSCODE_EXTENSIONS,ih.ZED_SETTINGS,ih.IDEA_PROJECT_XML,ih.IDEA_CODE_STYLE_CONFIG_XML,ih.IDEA_GITIGNORE,...ph],hh=new Map;function gh(e){let t=e.split(/[\\/]+/).filter(e=>e.length>0).join(`/`);if(t.length===0)throw Error(`public target relative path cannot be empty`);return t}function _h(e){return u.join(e,`public`)}function vh(e){return u.join(_h(e),uh)}function yh(e){return e?.command??`execute`}function bh(e,t){return u.resolve(t?.workspaceDir??u.dirname(e))}function xh(e,t,n){return{cwd:t,workspaceDir:t,aindexDir:u.resolve(e),command:n,platform:c.platform}}function Sh(e,t,n){return th(e,t,n)}function Ch(e,t,n){let r=gh(t);if(r===`proxy.ts`)return uh;let a=vh(e);if(!(i.existsSync(a)&&i.statSync(a).isFile()))return r;let o=yh(n),s=bh(e,n),c=[a,s,o,r].join(`::`),l=hh.get(c);if(l!=null)return l;let u=Sh(a,xh(e,s,o),r);return hh.set(c,u),u}function wh(e,t,n){let r=Ch(e,t,n);return u.join(_h(e),...r.split(/[\\/]+/))}function Th(e,t){let n=new Set([wh(e,uh)]);for(let r of mh)n.add(wh(e,r,t));return[...n]}function Eh(e,t,n,r,i){let a=wh(n,t,i);if(!(r.existsSync(a)&&r.statSync(a).isFile()))return;let o=r.readFileSync(a,`utf8`);return{type:e,content:o,length:o.length,filePathKind:sh.Absolute,dir:{pathKind:sh.Absolute,path:a,getDirectoryName:()=>u.basename(a)}}}const Dh=`.aindex`,Oh=`.tnmsc.json`,kh=/^[A-Za-z]:[\\/]/u,Ah=/%([^%]+)%/gu,jh=/\$\{([A-Za-z_]\w*)\}/gu,Mh=/\$([A-Za-z_]\w*)/gu;function Nh(e){return e!=null&&`effectiveHomeDir`in e&&`expandedEnv`in e}function Ph(e){return e?.fs??i}function Fh(e){return e?.platform??c.platform}function Ih(e){return e?.release??g.release()}function Lh(e){return e?.homedir??g.homedir()}function Rh(e){return e?.env??c.env}function zh(e){return e?.windowsUsersRoot??`/mnt/c/Users`}function Bh(e){return u.posix.normalize(e.replaceAll(`\\`,`/`))}function Vh(e,t){let n=Bh(e),r=Bh(t);return n===r?!0:n.startsWith(`${r}/`)}function Hh(e,t){if(typeof e!=`string`)return;let n=e.trim();if(n.length===0)return;let r=[Qh(n),Bh(n)];for(let e of r)if(e!=null&&Vh(e,t))return Bh(e)}function Uh(e){let t=Rh(e),n=Bh(zh(e)),r=t.HOMEDRIVE,i=t.HOMEPATH,a=[Hh(t.USERPROFILE,n),typeof r==`string`&&r.length>0&&typeof i==`string`&&i.length>0?Hh(`${r}${i}`,n):void 0,Hh(t.HOME,n)];return[...new Set(a.filter(e=>e!=null))]}function Wh(e){let t=Bh(e);return u.posix.dirname(u.posix.dirname(t))}function Gh(e,t){let n=Uh(t);if(n.length<=0)return e.length===1?e[0]:void 0;for(let t of n){let n=e.find(e=>Wh(e)===t);if(n!=null)return n}}function Kh(e,t){try{return e.statSync(t).isDirectory()}catch{return!1}}function qh(e,t){try{return e.statSync(t).isFile()}catch{return!1}}function Jh(e){return e===`win32`?u.win32:u.posix}function Yh(e,t,n){let r={};for(let[t,n]of Object.entries(e))typeof n==`string`&&(r[t]=n);if(n===t)return r;r.HOME=n,r.USERPROFILE=n;let i=/^\/mnt\/([a-zA-Z])\/(.+)$/u.exec(n);if(i==null)return r;let a=i[1],o=i[2];return a==null||o==null?r:(r.HOMEDRIVE=`${a.toUpperCase()}:`,r.HOMEPATH=`\\${o.replaceAll(`/`,`\\`)}`,r)}function Xh(e,t){let n=(e,n)=>t[n]??e;return e.replaceAll(Ah,n).replaceAll(jh,n).replaceAll(Mh,n)}function Zh(e,t,n){if(e===`~`)return t;if(!(e.startsWith(`~/`)||e.startsWith(`~\\`)))return e;let r=Jh(n),i=n===`win32`?e.slice(2).replaceAll(`/`,`\\`):e.slice(2).replaceAll(`\\`,`/`);return r.resolve(t,i)}function Qh(e){if(!kh.test(e))return;let t=e.slice(0,1).toLowerCase(),n=e.slice(2).replaceAll(`\\`,`/`).replace(/^\/+/u,``),r=`/mnt/${t}`;return n.length===0?r:u.posix.join(r,n)}function $h(e,t){return t===`win32`?u.win32.normalize(e.replaceAll(`/`,`\\`)):u.posix.normalize(e)}function eg(e){if(Fh(e)!==`linux`)return!1;let t=Rh(e);return typeof t.WSL_DISTRO_NAME==`string`&&t.WSL_DISTRO_NAME.length>0||typeof t.WSL_INTEROP==`string`&&t.WSL_INTEROP.length>0?!0:Ih(e).toLowerCase().includes(`microsoft`)}function tg(e){let t=Ph(e),n=zh(e);if(!Kh(t,n))return[];try{let e=t.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>u.join(n,e.name,Dh,Oh)).filter(e=>t.existsSync(e)&&qh(t,e));return e.sort((e,t)=>e.localeCompare(t)),e}catch{return[]}}function ng(e){let t=Fh(e),n=Lh(e),r=eg(e),i=r?tg(e):[],a=r?Gh(i,e):void 0,o=a==null?n:Wh(a);return{platform:t,isWsl:r,nativeHomeDir:n,effectiveHomeDir:o,globalConfigCandidates:i,...a!=null&&{selectedGlobalConfigPath:a},...a!=null&&{wslHostHomeDir:o},windowsUsersRoot:zh(e),expandedEnv:Yh(Rh(e),n,o)}}function rg(e){return ng(e).effectiveHomeDir}function ig(e){let t=ng(e);return t.selectedGlobalConfigPath==null?u.join(t.effectiveHomeDir,Dh,Oh):t.selectedGlobalConfigPath}function ag(e){let t=ng(e);if(!t.isWsl||t.selectedGlobalConfigPath!=null)return ig(e);let n=`"${t.windowsUsersRoot}/*/${Dh}/${Oh}"`;throw t.globalConfigCandidates.length===0?Error(`WSL host config file not found under ${n}.`):Uh(e).length>0?Error(`WSL host config file for the current Windows user was not found under ${n}.`):Error(`WSL host config file could not be matched to the current Windows user under ${n}.`)}function og(e,t){let n=Nh(t)?t:ng(t),r=Xh(e,n.expandedEnv);if(r=Zh(r,n.effectiveHomeDir,n.platform),!n.isWsl)return $h(r,n.platform);let i=Qh(r);return i==null?(r.startsWith(n.effectiveHomeDir)||r.startsWith(`/mnt/`)||r.startsWith(`/`))&&(r=r.replaceAll(`\\`,`/`)):r=i,$h(r,n.platform)}var sg=class extends Error{operation;violations;constructor(e,t){super(Bg(e,t)),this.name=`ProtectedDeletionGuardError`,this.operation=e,this.violations=t}};const cg=[`skills`,`commands`,`subAgents`,`rules`,`app`,`ext`,`arch`],lg=[`globalPrompt`,`workspacePrompt`];function ug(e){let t=c.env.XDG_CONFIG_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.config`)}function dg(e){let t=c.env.XDG_DATA_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.local`,`share`)}function fg(e){let t=c.env.XDG_STATE_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.local`,`state`)}function pg(e){let t=c.env.XDG_CACHE_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.cache`)}function mg(e){if(e!=null){if(typeof e.getAbsolutePath==`function`)try{let t=e.getAbsolutePath();if(t.length>0)return u.resolve(t)}catch{}if(e.pathKind===`absolute`)return u.resolve(e.path);if(typeof e.basePath==`string`&&e.basePath.length>0)return u.resolve(e.basePath,e.path)}}function hg(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?og(e):e}function gg(e){return u.resolve(hg(e))}function _g(e){let t=u.normalize(gg(e));return c.platform===`win32`?t.toLowerCase():t}function vg(e){let{root:t}=u.parse(e);return e===t?e:e.endsWith(u.sep)?e.slice(0,-1):e}function yg(e,t){let n=vg(e),r=vg(t);return n===r?!0:n.startsWith(`${r}${u.sep}`)}function bg(e){let t=gg(e),n=new Set([_g(t)]);try{if(i.existsSync(t)){let e=i.realpathSync.native(t);n.add(_g(e))}}catch{}return[...n]}function xg(e,t,n,r,i=`path`){return{path:gg(e),protectionMode:t,reason:n,source:r,matcher:i}}function Sg(e){let t=_g(e.path);return{...e,path:gg(e.path),comparisonKeys:bg(e.path),normalizedPath:t,specificity:vg(t).length}}function Cg(e){let t=new Map;for(let n of e){let e=Sg(n);t.set(`${e.protectionMode}:${e.normalizedPath}`,e)}return[...t.values()].sort((e,t)=>{let n=t.specificity-e.specificity;return n===0?e.protectionMode===t.protectionMode?e.path.localeCompare(t.path):e.protectionMode===`recursive`?-1:1:n})}function wg(e){return gg(e).replaceAll(`\\`,`/`)}function Tg(e){let t=[];for(let n of e){if(n.matcher!==`glob`){t.push(xg(n.path,n.protectionMode,n.reason,n.source));continue}let e=Um.default.sync(wg(n.path),{onlyFiles:!1,dot:!0,absolute:!0,followSymbolicLinks:!1});for(let r of e)t.push(xg(r,n.protectionMode,n.reason,n.source))}return t}function Eg(e,t,n){return n===`direct`?yg(t,e):yg(e,t)||yg(t,e)}function Dg(e,t){let n=gg(e);try{if(i.existsSync(n)&&i.lstatSync(n).isDirectory())return`recursive`}catch{}return t}function Og(){let e=rg();return[xg(u.parse(e).root,`direct`,`built-in dangerous root path`,`built-in-dangerous-root`),xg(e,`direct`,`built-in dangerous home directory`,`built-in-dangerous-root`),xg(ug(e),`direct`,`built-in dangerous config directory`,`built-in-dangerous-root`),xg(dg(e),`direct`,`built-in dangerous data directory`,`built-in-dangerous-root`),xg(fg(e),`direct`,`built-in dangerous state directory`,`built-in-dangerous-root`),xg(pg(e),`direct`,`built-in dangerous cache directory`,`built-in-dangerous-root`),xg(u.join(e,`.aindex`),`direct`,`built-in global aindex directory`,`built-in-dangerous-root`),xg(u.join(e,`.aindex`,`.tnmsc.json`),`direct`,`built-in global config file`,`built-in-config`)]}function kg(e,t,n){let r=[xg(e,`direct`,`workspace root`,`workspace-reserved`),xg(u.join(e,`aindex`),`direct`,`reserved workspace aindex root`,`workspace-reserved`),xg(u.join(e,`knowladge`),`direct`,`reserved workspace knowladge root`,`workspace-reserved`)];for(let e of t)r.push(xg(e,`direct`,`workspace project root`,`workspace-project-root`));if(!n)return r;r.push(xg(u.join(e,`aindex`,`dist`,`**`,`*.mdx`),`direct`,`reserved workspace aindex dist mdx files`,`workspace-reserved`,`glob`));for(let t of[`app`,`ext`,`arch`])r.push(xg(u.join(e,`aindex`,t,`**`,`*.mdx`),`direct`,`reserved workspace aindex ${t} mdx files`,`workspace-reserved`,`glob`));return r}function Ag(e){return[xg(e,`direct`,`resolved aindex root`,`aindex-root`)]}function jg(e,t){return Th(e,t)}function Mg(e,t,n){let r=[];for(let n of cg)r.push(xg(u.join(t,e.aindex[n].src),`recursive`,`configured aindex ${n} source directory`,`configured-aindex-source`));for(let n of lg)r.push(xg(u.join(t,e.aindex[n].src),`direct`,`configured aindex ${n} source file`,`configured-aindex-source`));for(let e of jg(t,n))r.push(xg(e,`direct`,`known aindex input config file`,`known-aindex-config`));return r}function Ng(e){let t=[],n=new Set,r=(e,r,i,a)=>{if(e==null||e.length===0)return;let o=xg(e,r,i,a),s=`${o.protectionMode}:${_g(o.path)}`;n.has(s)||(n.add(s),t.push(o))},i=(e,t,n,i)=>{let a=mg(e);a!=null&&r(a,t,n,i)};i(e.globalMemory?.dir,`recursive`,`global memory source directory`,`collected-input-source`);for(let t of e.commands??[])i(t.dir,`recursive`,`command source directory`,`collected-input-source`);for(let t of e.subAgents??[])i(t.dir,`recursive`,`sub-agent source directory`,`collected-input-source`);for(let t of e.rules??[])i(t.dir,`recursive`,`rule source directory`,`collected-input-source`);for(let t of e.skills??[]){i(t.dir,`recursive`,`skill source directory`,`collected-input-source`);for(let e of t.childDocs??[])i(e.dir,`recursive`,`skill child document directory`,`collected-input-source`);for(let e of t.resources??[])e.sourcePath==null||e.sourcePath.length===0||r(e.sourcePath,Dg(e.sourcePath,`direct`),`skill resource source path`,`collected-input-source`)}for(let t of e.vscodeConfigFiles??[])i(t.dir,`direct`,`vscode input config file`,`collected-input-config`);for(let t of e.zedConfigFiles??[])i(t.dir,`direct`,`zed input config file`,`collected-input-config`);for(let t of e.jetbrainsConfigFiles??[])i(t.dir,`direct`,`jetbrains input config file`,`collected-input-config`);for(let t of e.editorConfigFiles??[])i(t.dir,`direct`,`editorconfig input file`,`collected-input-config`);for(let t of e.aiAgentIgnoreConfigFiles??[])r(t.sourcePath,`direct`,`AI agent ignore config file`,`collected-input-config`);if(e.aindexDir!=null)for(let t of jg(e.aindexDir,{workspaceDir:e.workspace.directory.path}))r(t,`direct`,`known aindex input config file`,`known-aindex-config`);return t}function Pg(e){let t=[];for(let n of e.exactProtectedPaths??[])t.push(xg(n,`direct`,`legacy direct protected path`,`legacy-direct`));for(let n of e.subtreeProtectedPaths??[])t.push(xg(n,`recursive`,`legacy recursive protected path`,`legacy-recursive`));return t}function Fg(e={}){let t=e.includeReservedWorkspaceContentRoots??!0,n=Cg(Tg([...Og(),...Pg(e),...e.workspaceDir==null?[]:kg(e.workspaceDir,e.projectRoots??[],t),...e.aindexDir==null?[]:Ag(e.aindexDir),...e.rules??[]]));return{rules:n.map(e=>({path:e.path,protectionMode:e.protectionMode,reason:e.reason,source:e.source,...e.matcher==null?{}:{matcher:e.matcher}})),exactProtectedPaths:n.filter(e=>e.protectionMode===`direct`).map(e=>e.path),subtreeProtectedPaths:n.filter(e=>e.protectionMode===`recursive`).map(e=>e.path),compiledRules:n}}function Ig(e){let t=new Set;for(let n of e.workspace.projects){if(n.isWorkspaceRootProject===!0)continue;let e=n.dirFromWorkspacePath?.getAbsolutePath?.();e!=null&&e.length>0&&t.add(gg(e))}return[...t]}function Lg(e,t){return t==null?e:e.specificity===t.specificity?e.protectionMode===t.protectionMode?e.path.localeCompare(t.path)<0?e:t:e.protectionMode===`recursive`?e:t:e.specificity>t.specificity?e:t}function Rg(e,t){let n=gg(e),r=bg(n),i;for(let e of t.compiledRules){let t=!1;for(let n of r){for(let r of e.comparisonKeys)if(Eg(n,r,e.protectionMode)){i=Lg(e,i),t=!0;break}if(t)break}}if(i!=null)return{targetPath:n,protectedPath:i.path,protectionMode:i.protectionMode,reason:i.reason,source:i.source}}function zg(e,t){let n=[],r=new Map;for(let i of e){let e=gg(i),a=Rg(e,t);if(a==null){n.push(e);continue}r.has(a.targetPath)||r.set(a.targetPath,a)}return{safePaths:n,violations:[...r.values()].sort((e,t)=>e.targetPath.localeCompare(t.targetPath))}}function Bg(e,t){let n=t.map(e=>e.targetPath).join(`, `);return`Protected deletion guard blocked ${e} for ${t.length} path(s): ${n}`}function Vg(e,t,n){e.error(ne(t,n))}var Hg=class{inputEffects=[];registeredScopes=[];name;dependsOn;_log;get log(){return this._log??=be(this.name),this._log}constructor(e,t){this.name=e,t!=null&&(this.dependsOn=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,aindexDir:i}=this.resolveBasePaths(e.userConfigOptions),a={logger:this.log,fs:e.fs,path:e.path,glob:e.glob,spawn:m,userConfigOptions:e.userConfigOptions,workspaceDir:r,aindexDir: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,modifiedFileCount:t.modifiedFiles.length}),t.deletedFiles!=null&&t.deletedFiles.length>0&&this.log.debug({action:`inputEffect`,name:e.name,deletedFileCount:t.deletedFiles.length});else throw t.error??Error(`Input effect failed: ${e.name}`);n.push(t)}catch(t){let r=t instanceof Error?t:Error(String(t));throw this.logInputEffectFailure(e.name,r),n.push({success:!1,error:r,description:`Input effect failed: ${e.name}`}),r}}return n}logInputEffectFailure(e,t){if(t instanceof sg){Vg(this.log,t.operation,t.violations);return}this.log.error(C({code:`INPUT_EFFECT_FAILED`,title:`Input effect failed: ${e}`,rootCause:b(`The input effect "${e}" failed before tnmsc could finish preprocessing.`,`Underlying error: ${t.message}`),exactFix:b(`Inspect the effect inputs and fix the failing file, path, or environment condition before retrying tnmsc.`),possibleFixes:[b(`Re-run the command after fixing the referenced path or generated artifact.`),b(`Add a focused regression test if this effect should handle the failure more gracefully.`)],details:{effectName:e,errorMessage:t.message}}))}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.aindex?.dir??`aindex`;return{workspaceDir:n,aindexDir:u.join(n,r)}}resolvePath(e,t){let n=e;return n.includes(dx.WORKSPACE)&&(n=n.replace(dx.WORKSPACE,t)),n.startsWith(dx.USER_HOME)?og(n):u.normalize(og(n))}resolveAindexPath(e,t){return u.join(t,e)}readAndParseMarkdown(e,t){return Cp(t.readFileSync(e,`utf8`))}};const Ug=/\r?\n/u;function Wg(e={}){let{filePath:t,position:n,sourceText:r,expression:i,exportName:a,nodeType:o,phase:s,hint:c,cause:l}=e,u=n?.start.line,d=n?.start.column,f=n?.end?.line,p=n?.end?.column,m=n?.start.offset,h=n?.end?.offset,g=u!=null&&r!=null?Gg(r,u):void 0,_=Kg(r,m,h,g),v=u!=null&&d!=null&&g!=null?qg(u,d,p,g):void 0,y={};return t!=null&&t.length>0&&Object.assign(y,{filePath:t}),u!=null&&Object.assign(y,{line:u}),d!=null&&Object.assign(y,{column:d}),f!=null&&Object.assign(y,{endLine:f}),p!=null&&Object.assign(y,{endColumn:p}),m!=null&&Object.assign(y,{offset:m}),h!=null&&Object.assign(y,{endOffset:h}),_!=null&&_.length>0&&Object.assign(y,{snippet:_}),g!=null&&g.length>0&&Object.assign(y,{sourceLine:g}),v!=null&&v.length>0&&Object.assign(y,{codeFrame:v}),i!=null&&i.length>0&&Object.assign(y,{expression:i}),a!=null&&a.length>0&&Object.assign(y,{exportName:a}),o!=null&&o.length>0&&Object.assign(y,{nodeType:o}),s!=null&&s.length>0&&Object.assign(y,{phase:s}),c!=null&&c.length>0&&Object.assign(y,{hint:c}),l!=null&&l.length>0&&Object.assign(y,{cause:l}),y}function Gg(e,t){return e.split(Ug)[t-1]}function Kg(e,t,n,r){if(e!=null&&t!=null){let r=n!=null&&n>=t?n:t+1,i=e.slice(t,r).trim();if(i.length>0)return i.length>240?`${i.slice(0,240)}...`:i}let i=r?.trim();if(i!=null&&i.length>0)return i}function qg(e,t,n,r){let i=`${e} | `,a=` `.repeat(i.length+Math.max(0,t-1)),o=Math.max(1,(n??t+1)-t);return`${i}${r}\n${a}${`^`.repeat(o)}`}function Jg(e){if(!(e.line==null||e.column==null))return e.endLine!=null&&e.endColumn!=null?`${e.line}:${e.column}-${e.endLine}:${e.endColumn}`:`${e.line}:${e.column}`}function Yg(e,t){let n=[e];t.phase!=null&&n.push(`phase: ${t.phase}`),t.nodeType!=null&&n.push(`node: ${t.nodeType}`),t.filePath!=null&&n.push(`file: ${t.filePath}`);let r=Jg(t);return r!=null&&n.push(`location: ${r}`),t.expression!=null&&n.push(`expression: ${t.expression}`),t.exportName!=null&&n.push(`export: ${t.exportName}`),t.sourceLine!=null&&n.push(`source line: ${t.sourceLine.trimEnd()}`),t.codeFrame!=null&&(n.push(`code frame:`),n.push(t.codeFrame)),t.hint!=null&&n.push(`hint: ${t.hint}`),t.cause!=null&&n.push(`cause: ${t.cause}`),n.join(`
|
|
196
|
+
`)}function Xg(e,t={}){return e instanceof Zg||e instanceof Error?e.message:Yg(t.summary??`Compiler diagnostic`,e)}var Zg=class extends Error{diagnostic;filePath;line;column;endLine;endColumn;snippet;sourceLine;codeFrame;phase;nodeType;constructor(e,t,n){super(Yg(t,n)),this.name=e,this.diagnostic=n,n.filePath!=null&&(this.filePath=n.filePath),n.line!=null&&(this.line=n.line),n.column!=null&&(this.column=n.column),n.endLine!=null&&(this.endLine=n.endLine),n.endColumn!=null&&(this.endColumn=n.endColumn),n.snippet!=null&&(this.snippet=n.snippet),n.sourceLine!=null&&(this.sourceLine=n.sourceLine),n.codeFrame!=null&&(this.codeFrame=n.codeFrame),n.phase!=null&&(this.phase=n.phase),n.nodeType!=null&&(this.nodeType=n.nodeType)}};function Qg(e){if(e===`mdxTextExpression`||e===`mdxFlowExpression`)return`Literal braces in MDX text are parsed as expressions. Escape the braces or wrap the placeholder in code if you meant plain text.`;if(e===`mdxJsxAttributeValueExpression`)return`JSX attribute expressions must reference values that exist in scope.`}var $g=class extends Zg{expression;constructor(e,t){super(`ScopeError`,e,t),t.expression!=null&&(this.expression=t.expression)}},e_=class extends $g{variableName;constructor(e,t,n={}){let r=Wg({...n,expression:t,phase:n.phase??`expression-evaluation`,hint:n.hint??Qg(n.nodeType)}),i=`Undefined variable "${e}" in expression "${t??``}"`;super(i,r),this.name=`UndefinedVariableError`,this.variableName=e}},t_=class extends $g{namespace;constructor(e,t,n={}){let r=Wg({...n,expression:t,phase:n.phase??`expression-evaluation`,hint:n.hint??Qg(n.nodeType)}),i=`Undefined namespace "${e}" in expression "${t??``}"`;super(i,r),this.name=`UndefinedNamespaceError`,this.namespace=e}},n_=class extends Zg{exportName;constructor(e,t,n={}){let r=Wg({...n,exportName:t,phase:n.phase??`export-parsing`,hint:n.hint??`Export metadata must be statically evaluable. Use plain literals, arrays, objects, or scope-backed references only.`});super(`ExportParseError`,e,r),t!=null&&(this.exportName=t)}};const r_=new Map;function i_(e,t){r_.set(e,t)}function a_(){return new Map(r_)}function o_(e){return r_.has(e)}const s_=/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/iu,c_=/(\w+) is not defined/u;function l_(e,t,n){let r=e.trim(),i=u_(n,e);return r===``?``:s_.test(r)?d_(r,t,i):f_(r,t,i)}function u_(e,t){return{expression:t,...e?.filePath!=null&&{filePath:e.filePath},...e?.sourceText!=null&&{sourceText:e.sourceText},...e?.position!=null&&{position:e.position},...e?.nodeType!=null&&{nodeType:e.nodeType}}}function d_(e,t,n){let r=e.split(`.`),i=r[0];if(i==null||!(i in t))throw new t_(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 e_(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 e_(i,e,n);a=o[i]}return p_(a)}function f_(e,t,n){let r=Object.keys(t),i=r.map(e=>t[e]);try{return p_(Function(...r,`return (${e})`)(...i))}catch(t){let r=t instanceof Error?t.message:String(t);if(r.includes(`is not defined`)){let t=c_.exec(r);if(t?.[1]!=null)throw new t_(t[1],e,{...n,cause:r})}let i=n?.filePath==null?[]:[`file: ${n.filePath}`],a=n?.position?.start==null?[]:[`location: ${n.position.start.line}:${n.position.start.column}`];throw Error([`Failed to evaluate expression: "${e}"`,...i,...a,`Cause: ${r}`].join(`
|
|
197
|
+
`))}}function p_(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 m_(e,t){return e===null?!1:t.components.has(e)||o_(e)}async function h_(e){return async(t,n)=>(await e({type:`root`,children:t},n)).children}async function g_(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 h_(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})}}const __=/language-(\w+)/u;function v_(e,t,n){return{...e.filePath!=null&&{filePath:e.filePath},...e.sourceText!=null&&{sourceText:e.sourceText},...n?.position!=null&&{position:n.position},nodeType:t}}function y_(e,t){let n=e.name?.toLowerCase();if(n==null)return null;switch(n){case`pre`:return S_(e,t);case`a`:return C_(e,t);case`strong`:case`b`:return w_(e,t);case`em`:case`i`:return T_(e,t);case`img`:return E_(e,t);case`blockquote`:return D_(e,t);default:return null}}function b_(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`?l_(r.value.value,n.scope,v_(n,`mdxJsxAttributeValueExpression`,r)):r.value===null?``:null}function x_(e,t){let n=``;for(let r of e.children){if(r.type===`text`){n+=r.value;continue}if(r.type===`mdxTextExpression`){n+=l_(r.value,t.scope,v_(t,`mdxTextExpression`,r));continue}(r.type===`mdxJsxFlowElement`||r.type===`mdxJsxTextElement`)&&(n+=x_(r,t))}return n}function S_(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=b_(n,`className`,t)??``,i=__.exec(r)?.[1],a=x_(n,t);return[{type:`code`,lang:i??null,value:a.trim()}]}function C_(e,t){let n=b_(e,`href`,t);if(n==null||n===``)return null;let r=x_(e,t);return[{type:`paragraph`,children:[{type:`link`,url:n,title:b_(e,`title`,t)??null,children:[{type:`text`,value:r}]}]}]}function w_(e,t){let n={type:`strong`,children:[{type:`text`,value:x_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function T_(e,t){let n={type:`emphasis`,children:[{type:`text`,value:x_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function E_(e,t){let n=b_(e,`src`,t);if(n==null||n===``)return null;let r={type:`image`,url:n,alt:b_(e,`alt`,t)??``,title:b_(e,`title`,t)??null};return e.type,[{type:`paragraph`,children:[r]}]}function D_(e,t){return[{type:`blockquote`,children:[{type:`paragraph`,children:[{type:`text`,value:x_(e,t)}]}]}]}const O_=/^-?\d+(?:\.\d+)?$/u;function k_(e,t){return{...e.filePath!=null&&{filePath:e.filePath},...e.sourceText!=null&&{sourceText:e.sourceText},...t.position!=null&&{position:t.position},nodeType:t.type}}function A_(e){return e==null?!1:JSON.stringify(e).includes(`"JSX`)}async function j_(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`?M_(i.expression,t,n,e):[]}async function M_(e,t,n,r){return e.type===`JSXElement`?R_(e,t,n):e.type===`JSXFragment`?z_(e,t,n,r):e.type===`LogicalExpression`?N_(e,t,n,r):e.type===`ConditionalExpression`?P_(e,t,n,r):e.type===`SequenceExpression`?F_(e,t,n,r):e.type===`ArrayExpression`?I_(e,t,n,r):J_(e,t,r)}async function N_(e,t,n,r){let i=await L_(e.left,t,n,r);return e.operator===`&&`?K_(i)?M_(e.right,t,n,r):[]:e.operator===`||`?K_(i)?G_(e.left)?M_(e.left,t,n,r):q_(i):M_(e.right,t,n,r):e.operator===`??`?i==null?M_(e.right,t,n,r):G_(e.left)?M_(e.left,t,n,r):q_(i):[]}async function P_(e,t,n,r){return K_(await L_(e.test,t,n,r))?M_(e.consequent,t,n,r):M_(e.alternate,t,n,r)}async function F_(e,t,n,r){let i=[];for(let a of e.expressions){let e=await M_(a,t,n,r);i.push(...e)}return i}async function I_(e,t,n,r){let i=[];for(let a of e.elements)if(a!=null)if(a.type===`SpreadElement`){let e=await M_(a.argument,t,n,r);i.push(...e)}else{let e=await M_(a,t,n,r);i.push(...e)}return i}async function L_(e,t,n,r){if(G_(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 i=await L_(e.argument,t,n,r);return e.operator===`!`?!K_(i):e.operator===`-`?-i:e.operator===`+`?+i:e.operator===`typeof`?typeof i:void 0}if(e.type===`BinaryExpression`){let i=await L_(e.left,t,n,r),a=await L_(e.right,t,n,r);return e.operator===`===`?i===a:e.operator===`!==`?i!==a:e.operator===`==`?i===a:e.operator===`!=`?i!==a:e.operator===`<`?i<a:e.operator===`<=`?i<=a:e.operator===`>`?i>a:e.operator===`>=`?i>=a:e.operator===`+`?i+a:e.operator===`-`?i-a:e.operator===`*`?i*a:e.operator===`/`?i/a:e.operator===`%`?i%a:void 0}if(e.type===`LogicalExpression`){let i=await L_(e.left,t,n,r);return e.operator===`&&`?K_(i)?L_(e.right,t,n,r):i:e.operator===`||`?K_(i)?i:L_(e.right,t,n,r):e.operator===`??`?i??L_(e.right,t,n,r):void 0}if(e.type===`MemberExpression`){let i=await L_(e.object,t,n,r);if(i==null)return;if(e.computed)return i[await L_(e.property,t,n,r)];let{name:a}=e.property;return i[a]}if(e.type===`ConditionalExpression`)return K_(await L_(e.test,t,n,r))?L_(e.consequent,t,n,r):L_(e.alternate,t,n,r);let i=W_(e);if(i!==``)try{let e=l_(i,t.scope,k_(t,r));return e===`true`?!0:e===`false`?!1:e===`null`?null:e===`undefined`||e===``?void 0:O_.test(e)?Number(e):e}catch{return}}async function R_(e,t,n){let r=V_(e,t);if(r.name!=null&&m_(r.name,t)){let{processAst:e}=await Promise.resolve().then(()=>Y_);return g_(r,t,e)}return y_(r,t)??(r.children.length>0?n(r.children,t):[])}async function z_(e,t,n,r){let i=[];for(let a of e.children){let e=await B_(a,t,n,r);i.push(...e)}return i}async function B_(e,t,n,r){if(e.type===`JSXElement`)return R_(e,t,n);if(e.type===`JSXFragment`)return z_(e,t,n,r);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`?[]:M_(e.expression,t,n,r):e.type===`JSXSpreadChild`?M_(e.expression,t,n,r):[]}function V_(e,t){let n=e.openingElement,r=null;n.name.type===`JSXIdentifier`?{name:r}=n.name:n.name.type===`JSXMemberExpression`?r=H_(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:W_(e.value.expression)}),i.push({type:`mdxJsxAttribute`,name:t,value:n})}else e.type===`JSXSpreadAttribute`&&i.push({type:`mdxJsxExpressionAttribute`,value:`...${W_(e.argument)}`});let a=[];for(let n of e.children){let e=U_(n,t);e!=null&&a.push(...e)}return{type:`mdxJsxFlowElement`,name:r,attributes:i,children:a}}function H_(e){return e.object.type===`JSXIdentifier`?`${e.object.name}.${e.property.name}`:`${H_(e.object)}.${e.property.name}`}function U_(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[V_(e,t)];if(e.type===`JSXFragment`){let n=[];for(let r of e.children){let e=U_(r,t);e!=null&&n.push(...e)}return n}return e.type===`JSXExpressionContainer`?e.expression.type===`JSXEmptyExpression`?null:[{type:`paragraph`,children:[{type:`text`,value:W_(e.expression)}]}]:e.type===`JSXSpreadChild`?[{type:`paragraph`,children:[{type:`text`,value:`...${W_(e.expression)}`}]}]:null}function W_(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=W_(e.object);return e.computed?`${t}[${W_(e.property)}]`:`${t}.${e.property.name}`}if(e.type===`CallExpression`)return`${W_(e.callee)}(${e.arguments.map(e=>W_(e)).join(`, `)})`;if(e.type===`BinaryExpression`||e.type===`LogicalExpression`){let t=W_(e.left),n=W_(e.right);return`(${t} ${e.operator} ${n})`}if(e.type===`UnaryExpression`){let t=W_(e.argument);return`${e.operator}${t}`}if(e.type===`ConditionalExpression`)return`(${W_(e.test)} ? ${W_(e.consequent)} : ${W_(e.alternate)})`;if(e.type===`ArrayExpression`)return`[${e.elements.filter(e=>e!=null&&e.type!==`SpreadElement`).map(e=>W_(e)).join(`, `)}]`;if(e.type===`ObjectExpression`)return`{${e.properties.filter(e=>e.type===`Property`).map(e=>`${e.key.type===`Identifier`?e.key.name:W_(e.key)}: ${W_(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+=`\${${W_(e.expressions[n])}}`);return t+="`",t}return e.type===`SpreadElement`?`...${W_(e.argument)}`:``}function G_(e){return e.type===`JSXElement`||e.type===`JSXFragment`}function K_(e){return!!e}function q_(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 J_(e,t,n){let r=W_(e);if(r===``)return[];try{return q_(l_(r,t.scope,k_(t,n)))}catch{return[]}}var Y_=De({processAst:()=>$_});const X_=/\.\w+$/u;function Z_(e,t,n){return{...e.filePath!=null&&{filePath:e.filePath},...e.sourceText!=null&&{sourceText:e.sourceText},...t.position!=null&&{position:t.position},nodeType:n}}function Q_(e){if(!(e.includes(`/`)&&X_.test(e)))return e;let t=e.lastIndexOf(`/`);return e.slice(t+1)}async function $_(e,t){return ev(e,t)}async function ev(e,t){let n=[];for(let r of e.children){let e=await tv(r,t);n.push(...e)}return{type:`root`,children:n}}async function tv(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(A_(r))return j_(n,t,async(e,t)=>(await $_({type:`root`,children:e},t)).children);let a=l_(n.value,t.scope,Z_(t,n,`mdxFlowExpression`));return a===``?[]:[{type:`paragraph`,children:[{type:`text`,value:a}]}]}if(e.type===`mdxJsxFlowElement`)return nv(e,t);if(e.type===`link`){let n=e,r=(await rv(n.children,t)).map(e=>e.type===`text`?{...e,value:Q_(e.value)}:e);return[{...n,children:r}]}if(!(`children`in e&&Array.isArray(e.children)))return[e];let n=await rv(e.children,t);return[{...e,children:n}]}async function nv(e,t){return e.name!=null&&m_(e.name,t)?g_(e,t,$_):y_(e,t)??[]}async function rv(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(A_(i)){let r=await j_(e,t,async(e,t)=>(await $_({type:`root`,children:e},t)).children);for(let e of r)n.push(e);continue}let o=l_(e.value,t.scope,Z_(t,e,`mdxFlowExpression`));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:l_(e.value,t.scope,Z_(t,e,`mdxTextExpression`))};n.push(a);continue}if(r.type===`mdxJsxTextElement`){let e=r;if(e.name!=null&&m_(e.name,t)){let r=await g_(e,t,$_);for(let e of r)e.type===`paragraph`&&`children`in e?n.push(...e.children):n.push(e);continue}let i=y_(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 rv(r.children,t);if(r.type===`link`){let t=e.map(e=>e.type===`text`?{...e,value:Q_(e.value)}:e);n.push({...r,children:t});continue}n.push({...r,children:e});continue}n.push(r)}return n}const iv=/^export\s+default\s+/u,av=/export\s+const\s+(\w+)\s*=\s*/gu,ov=/^-?\d+(?:\.\d+)?$/u,sv=/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/iu,cv=/\s/u,lv=/[\w$]/u,uv=/^[\w$]+$/u;function dv(e,t={}){let n={},{yamlFrontMatter:r,scope:i,filePath:a,sourceText:o}=t;for(let t of e){let e=fv(t,i,{...a!=null&&{filePath:a},...o!=null&&{sourceText:o}});Object.assign(n,e)}let s=Object.keys(n).length>0,c=r!=null&&Object.keys(r).length>0,l;return l=s&&c?`mixed`:s?`export`:`yaml`,{fields:{...r,...n},source:l}}function fv(e,t,n={}){let r={},{filePath:i,sourceText:a}=n,o=e.value.trim(),s=iv.exec(o);if(s!=null){let n=s[0].length,c=pv(o,n);if(c!=null)try{let e=mv(c.trim(),t,i);typeof e==`object`&&e&&!Array.isArray(e)&&Object.assign(r,e)}catch(t){let n=t instanceof Error?t.message:String(t);throw new n_(`Cannot statically evaluate export default`,`default`,{...i!=null&&{filePath:i},...a!=null&&{sourceText:a},...e.position!=null&&{position:e.position},nodeType:`mdxjsEsm`,phase:`export-parsing`,cause:n})}return r}let c=av.exec(o);for(;c!==null;){let n=c[1];if(n==null){c=av.exec(o);continue}let s=pv(o,c.index+c[0].length);if(s==null){c=av.exec(o);continue}try{let e=mv(s.trim(),t,i);n===`metadata`&&typeof e==`object`&&e&&!Array.isArray(e)?Object.assign(r,e):r[n]=e}catch(t){let r=t instanceof Error?t.message:String(t);throw new n_(`Cannot statically evaluate export "${n}"`,n,{...i!=null&&{filePath:i},...a!=null&&{sourceText:a},...e.position!=null&&{position:e.position},nodeType:`mdxjsEsm`,phase:`export-parsing`,cause:r})}c=av.exec(o)}return r}function pv(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===`
|
|
198
|
+
`){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 mv(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(ov.test(r))return Number(r);if(r.startsWith(`"`)&&r.endsWith(`"`)||r.startsWith(`'`)&&r.endsWith(`'`))return hv(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 hv(e)}if(r.startsWith(`[`)&&r.endsWith(`]`))return _v(r,t,n);if(r.startsWith(`{`)&&r.endsWith(`}`))return vv(r,t,n);if(sv.test(r))return gv(r,t,n);let i=n==null?``:` in file "${n}"`;throw Error(`Expression "${r}" cannot be statically evaluated${i}`)}function hv(e){return e.replaceAll(`\\n`,`
|
|
199
|
+
`).replaceAll(`\\r`,`\r`).replaceAll(`\\t`,` `).replaceAll(`\\"`,`"`).replaceAll(`\\'`,`'`).replaceAll(`\\\\`,`\\`)}function gv(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 _v(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return[];if(t==null)try{let t=yv(e),n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return bv(r).map(e=>mv(e.trim(),t,n))}function vv(e,t,n){let r=e.slice(1,-1).trim();if(r===``)return{};if(t==null)try{let t=yv(e),n=JSON.parse(t);if(typeof n==`object`&&n&&!Array.isArray(n))return n}catch{}let i={},a=xv(r);for(let e of a){let r=Sv(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]=mv(o,t,n)}return i}function yv(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&&cv.test(t.charAt(e));)e--;let n=e+1;for(;e>=0&&lv.test(t.charAt(e));)e--;if(e++,e>0&&t.charAt(e-1)!==`"`){let r=t.slice(e,n);r.length>0&&uv.test(r)&&(t=`${t.slice(0,e)}"${r}"`)}}t+=a}return t}function bv(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 xv(e){return bv(e)}function Sv(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}const Cv={}.hasOwnProperty;function wv(e,t){let n=t||{};function r(t,...n){let i=r.invalid,a=r.handlers;if(t&&Cv.call(t,e)){let n=String(t[e]);i=Cv.call(a,n)?a[n]:r.unknown}if(i)return i.call(this,t,...n)}return r.handlers=n.handlers||{},r.invalid=n.invalid,r.unknown=n.unknown,r}const Tv={}.hasOwnProperty;function Ev(e,t){let n=-1,r;if(t.extensions)for(;++n<t.extensions.length;)Ev(e,t.extensions[n]);for(r in t)if(Tv.call(t,r))switch(r){case`extensions`:break;case`unsafe`:Dv(e[r],t[r]);break;case`join`:Dv(e[r],t[r]);break;case`handlers`:Ov(e[r],t[r]);break;default:e.options[r]=t[r]}return e}function Dv(e,t){t&&e.push(...t)}function Ov(e,t){t&&Object.assign(e,t)}const kv=[Av];function Av(e,t,n,r){if(t.type===`code`&&hn(t,r)&&(e.type===`list`||e.type===t.type&&hn(e,r)))return!1;if(`spread`in n&&typeof n.spread==`boolean`)return e.type===`paragraph`&&(e.type===t.type||t.type===`definition`||t.type===`heading`&&Nn(t,r))?void 0:n.spread?1:0}const jv=[`autolink`,`destinationLiteral`,`destinationRaw`,`reference`,`titleQuote`,`titleApostrophe`],Mv=[{character:` `,after:`[\\r\\n]`,inConstruct:`phrasing`},{character:` `,before:`[\\r\\n]`,inConstruct:`phrasing`},{character:` `,inConstruct:[`codeFencedLangGraveAccent`,`codeFencedLangTilde`]},{character:`\r`,inConstruct:[`codeFencedLangGraveAccent`,`codeFencedLangTilde`,`codeFencedMetaGraveAccent`,`codeFencedMetaTilde`,`destinationLiteral`,`headingAtx`]},{character:`
|
|
200
|
+
`,inConstruct:[`codeFencedLangGraveAccent`,`codeFencedLangTilde`,`codeFencedMetaGraveAccent`,`codeFencedMetaTilde`,`destinationLiteral`,`headingAtx`]},{character:` `,after:`[\\r\\n]`,inConstruct:`phrasing`},{character:` `,before:`[\\r\\n]`,inConstruct:`phrasing`},{character:` `,inConstruct:[`codeFencedLangGraveAccent`,`codeFencedLangTilde`]},{character:`!`,after:`\\[`,inConstruct:`phrasing`,notInConstruct:jv},{character:`"`,inConstruct:`titleQuote`},{atBreak:!0,character:`#`},{character:`#`,inConstruct:`headingAtx`,after:`(?:[\r
|
|
201
|
+
]|$)`},{character:`&`,after:`[#A-Za-z]`,inConstruct:`phrasing`},{character:`'`,inConstruct:`titleApostrophe`},{character:`(`,inConstruct:`destinationRaw`},{before:`\\]`,character:`(`,inConstruct:`phrasing`,notInConstruct:jv},{atBreak:!0,before:`\\d+`,character:`)`},{character:`)`,inConstruct:`destinationRaw`},{atBreak:!0,character:`*`,after:`(?:[ \r
|
|
202
|
+
*])`},{character:`*`,inConstruct:`phrasing`,notInConstruct:jv},{atBreak:!0,character:`+`,after:`(?:[ \r
|
|
203
203
|
])`},{atBreak:!0,character:`-`,after:`(?:[ \r
|
|
204
204
|
-])`},{atBreak:!0,before:`\\d+`,character:`.`,after:`(?:[ \r
|
|
205
|
-
]|$)`},{atBreak:!0,character:`<`,after:`[!/?A-Za-z]`},{character:`<`,after:`[!/?A-Za-z]`,inConstruct:`phrasing`,notInConstruct:
|
|
206
|
-
`)&&u.type===`html`&&(a[a.length-1]=a[a.length-1].replace(/(\r?\n|\r)$/,` `),s=` `,l=t.createTracker(n),l.move(a.join(``)));let f=t.handle(u,e,t,{...l.current(),after:d,before:s});c&&c===f.slice(0,1)&&(f=Sn(c.charCodeAt(0))+f.slice(1));let p=t.attentionEncodeSurroundingInfo;t.attentionEncodeSurroundingInfo=void 0,c=void 0,p&&(a.length>0&&p.before&&s===a[a.length-1].slice(-1)&&(a[a.length-1]=a[a.length-1].slice(0,-1)+Sn(s.charCodeAt(0))),p.after&&(c=d)),l.move(f),a.push(f),s=f.slice(-1)}return r.pop(),a.join(``)}function
|
|
205
|
+
]|$)`},{atBreak:!0,character:`<`,after:`[!/?A-Za-z]`},{character:`<`,after:`[!/?A-Za-z]`,inConstruct:`phrasing`,notInConstruct:jv},{character:`<`,inConstruct:`destinationLiteral`},{atBreak:!0,character:`=`},{atBreak:!0,character:`>`},{character:`>`,inConstruct:`destinationLiteral`},{atBreak:!0,character:`[`},{character:`[`,inConstruct:`phrasing`,notInConstruct:jv},{character:`[`,inConstruct:[`label`,`reference`]},{character:`\\`,after:`[\\r\\n]`,inConstruct:`phrasing`},{character:`]`,inConstruct:[`label`,`reference`]},{atBreak:!0,character:`_`},{character:`_`,inConstruct:`phrasing`,notInConstruct:jv},{atBreak:!0,character:"`"},{character:"`",inConstruct:[`codeFencedLangGraveAccent`,`codeFencedMetaGraveAccent`]},{character:"`",inConstruct:`phrasing`,notInConstruct:jv},{atBreak:!0,character:`~`}];function Nv(e){return e.label||!e.identifier?e.label||``:gr(e.identifier)}function Pv(e){if(!e._compiled){let t=(e.atBreak?`[\\r\\n][\\t ]*`:``)+(e.before?`(?:`+e.before+`)`:``);e._compiled=RegExp((t?`(`+t+`)`:``)+(/[|\\{}()[\]^$+*?.-]/.test(e.character)?`\\`:``)+e.character+(e.after?`(?:`+e.after+`)`:``),`g`)}return e._compiled}function Fv(e,t,n){let r=t.indexStack,i=e.children||[],a=[],o=-1,s=n.before,c;r.push(-1);let l=t.createTracker(n);for(;++o<i.length;){let u=i[o],d;if(r[r.length-1]=o,o+1<i.length){let n=t.handle.handlers[i[o+1].type];n&&n.peek&&(n=n.peek),d=n?n(i[o+1],e,t,{before:``,after:``,...l.current()}).charAt(0):``}else d=n.after;a.length>0&&(s===`\r`||s===`
|
|
206
|
+
`)&&u.type===`html`&&(a[a.length-1]=a[a.length-1].replace(/(\r?\n|\r)$/,` `),s=` `,l=t.createTracker(n),l.move(a.join(``)));let f=t.handle(u,e,t,{...l.current(),after:d,before:s});c&&c===f.slice(0,1)&&(f=Sn(c.charCodeAt(0))+f.slice(1));let p=t.attentionEncodeSurroundingInfo;t.attentionEncodeSurroundingInfo=void 0,c=void 0,p&&(a.length>0&&p.before&&s===a[a.length-1].slice(-1)&&(a[a.length-1]=a[a.length-1].slice(0,-1)+Sn(s.charCodeAt(0))),p.after&&(c=d)),l.move(f),a.push(f),s=f.slice(-1)}return r.pop(),a.join(``)}function Iv(e,t,n){let r=t.indexStack,i=e.children||[],a=t.createTracker(n),o=[],s=-1;for(r.push(-1);++s<i.length;){let n=i[s];r[r.length-1]=s,o.push(a.move(t.handle(n,e,t,{before:`
|
|
207
207
|
`,after:`
|
|
208
|
-
`,...a.current()}))),n.type!==`list`&&(t.bulletLastUsed=void 0),s<i.length-1&&o.push(a.move(
|
|
208
|
+
`,...a.current()}))),n.type!==`list`&&(t.bulletLastUsed=void 0),s<i.length-1&&o.push(a.move(Lv(n,i[s+1],e,t)))}return r.pop(),o.join(``)}function Lv(e,t,n,r){let i=r.join.length;for(;i--;){let a=r.join[i](e,t,n,r);if(a===!0||a===1)break;if(typeof a==`number`)return`
|
|
209
209
|
`.repeat(1+a);if(a===!1)return`
|
|
210
210
|
|
|
211
211
|
<!---->
|
|
212
212
|
|
|
213
213
|
`}return`
|
|
214
214
|
|
|
215
|
-
`}const
|
|
215
|
+
`}const Rv=/\r?\n|\r/g;function zv(e,t){let n=[],r=0,i=0,a;for(;a=Rv.exec(e);)o(e.slice(r,a.index)),n.push(a[0]),r=a.index+a[0].length,i++;return o(e.slice(r)),n.join(``);function o(e){n.push(t(e,i,!e))}}function Bv(e,t,n){let r=(n.before||``)+(t||``)+(n.after||``),i=[],a=[],o={},s=-1;for(;++s<e.unsafe.length;){let t=e.unsafe[s];if(!dn(e.stack,t))continue;let n=e.compilePattern(t),a;for(;a=n.exec(r);){let e=`before`in t||!!t.atBreak,n=`after`in t,r=a.index+(e?a[1].length:0);i.includes(r)?(o[r].before&&!e&&(o[r].before=!1),o[r].after&&!n&&(o[r].after=!1)):(i.push(r),o[r]={before:e,after:n})}}i.sort(Vv);let c=n.before?n.before.length:0,l=r.length-(n.after?n.after.length:0);for(s=-1;++s<i.length;){let e=i[s];e<c||e>=l||e+1<l&&i[s+1]===e+1&&o[e].after&&!o[e+1].before&&!o[e+1].after||i[s-1]===e-1&&o[e].before&&!o[e-1].before&&!o[e-1].after||(c!==e&&a.push(Hv(r.slice(c,e),`\\`)),c=e,/[!-/:-@[-`{-~]/.test(r.charAt(e))&&(!n.encode||!n.encode.includes(r.charAt(e)))?a.push(`\\`):(a.push(Sn(r.charCodeAt(e))),c++))}return a.push(Hv(r.slice(c,l),n.after)),a.join(``)}function Vv(e,t){return e-t}function Hv(e,t){let n=/\\(?=[!-/:-@[-`{-~])/g,r=[],i=[],a=e+t,o=-1,s=0,c;for(;c=n.exec(a);)r.push(c.index);for(;++o<r.length;)s!==r[o]&&i.push(e.slice(s,r[o])),i.push(`\\`),s=r[o];return i.push(e.slice(s)),i.join(``)}function Uv(e){let t=e||{},n=t.now||{},r=t.lineShift||0,i=n.line||1,a=n.column||1;return{move:c,current:o,shift:s};function o(){return{now:{line:i,column:a},lineShift:r}}function s(e){r+=e}function c(e){let t=e||``,n=t.split(/\r?\n|\r/g),o=n[n.length-1];return i+=n.length-1,a=n.length===1?a+o.length:1+o.length+r,t}}function Wv(e,t){let n=t||{},r={associationId:Nv,containerPhrasing:Jv,containerFlow:Yv,createTracker:Uv,compilePattern:Pv,enter:a,handlers:{...ur},handle:void 0,indentLines:zv,indexStack:[],join:[...kv],options:{},safe:Xv,stack:[],unsafe:[...Mv]};Ev(r,n),r.options.tightDefinitions&&r.join.push(qv),r.handle=wv(`type`,{invalid:Gv,unknown:Kv,handlers:r.handlers});let i=r.handle(e,void 0,r,{before:`
|
|
216
216
|
`,after:`
|
|
217
217
|
`,now:{line:1,column:1},lineShift:0});return i&&i.charCodeAt(i.length-1)!==10&&i.charCodeAt(i.length-1)!==13&&(i+=`
|
|
218
|
-
`),i;function a(e){return r.stack.push(e),t;function t(){r.stack.pop()}}}function
|
|
218
|
+
`),i;function a(e){return r.stack.push(e),t;function t(){r.stack.pop()}}}function Gv(e){throw Error("Cannot handle value `"+e+"`, expected node")}function Kv(e){throw Error("Cannot handle unknown node `"+e.type+"`")}function qv(e,t){if(e.type===`definition`&&e.type===t.type)return 0}function Jv(e,t){return Fv(e,this,t)}function Yv(e,t){return Iv(e,this,t)}function Xv(e,t){return Bv(this,e,t)}function Zv(e,t,n){return{...e.filePath!=null&&{filePath:e.filePath},...e.sourceText!=null&&{sourceText:e.sourceText},...n?.position!=null&&{position:n.position},nodeType:t}}function Qv(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=l_(n.value.value,t.scope,Zv(t,`mdxJsxAttributeValueExpression`,n));return e===`true`||e===`1`}catch{return!1}return!1}async function $v(e,t,n){return!Qv(e,t)||e.children.length===0?[]:n(e.children,t)}async function ey(e,t){if(!Qv(e,t)||e.children.length===0)return[];let n=ty(e.children,t);return n===``?[]:[{type:`text`,value:n}]}function ty(e,t){let n=``;for(let r of e)if(r.type===`text`)n+=r.value;else if(r.type===`mdxTextExpression`)try{n+=l_(r.value,t.scope,Zv(t,`mdxTextExpression`,r))}catch{}else `children`in r&&Array.isArray(r.children)&&(n+=ty(r.children,t));return n}function ny(){i_(`Md`,$v),i_(`Md.Line`,ey)}function ry(e){let t=this;t.compiler=n;function n(n){return Wv(n,{...t.data(`settings`),...e,extensions:t.data(`toMarkdownExtensions`)||[]})}}var iy=R(ip(),1);ny();function ay(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 oy(e,t){let n=zd(e),r=ay(t?.globalScope,t?.scope),i=a_(),a;if(t?.extractMetadata===!0){let i=n.children.find(e=>e.type===`yaml`),o;if(i!=null)try{o=iy.parse(i.value)}catch{}a=dv(n.children.filter(e=>e.type===`mdxjsEsm`),{...o!=null&&{yamlFrontMatter:o},scope:r,...t?.filePath!=null&&{filePath:t.filePath},sourceText:e}),n.children=n.children.filter(e=>e.type!==`yaml`&&e.type!==`mdxjsEsm`)}let o=await $_(n,{scope:r,components:i,processingStack:[],...t?.basePath!=null&&{basePath:t.basePath},...t?.filePath!=null&&{filePath:t.filePath},sourceText:e}),s=kd().use(at,[`yaml`]).use(yo).use(ry,{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}const sy=/^\s*(```|~~~)/u,cy=/\r?\n/u,ly=[/^\s*export\s+default\b/u,/^\s*export\s+const\b/u,/^\s*import\b/u];let uy=null;function dy(e){return typeof e!=`object`||!e?!1:typeof e.compileMdxToMd==`function`}function fy(e,t){let n=`@truenine/memory-sync-cli-${t}`;try{let t=e(n).mdCompiler;if(dy(t))return t}catch{}try{let t=f(e.resolve(`${n}/package.json`)),r=o(t).filter(e=>e.startsWith(`napi-md-compiler.`)&&e.endsWith(`.node`)).sort();for(let n of r){let r=e(p(t,n));if(dy(r))return r}}catch{return null}return null}try{let e=r(import.meta.url),{platform:t,arch:n}=c,i={"win32-x64":[`napi-md-compiler.win32-x64-msvc`,`win32-x64-msvc`],"linux-x64":[`napi-md-compiler.linux-x64-gnu`,`linux-x64-gnu`],"linux-arm64":[`napi-md-compiler.linux-arm64-gnu`,`linux-arm64-gnu`],"darwin-arm64":[`napi-md-compiler.darwin-arm64`,`darwin-arm64`],"darwin-x64":[`napi-md-compiler.darwin-x64`,`darwin-x64`]}[`${t}-${n}`];if(i!=null){let[t,n]=i;try{uy=e(`./${t}.node`)}catch{uy=fy(e,n)}}}catch{}async function py(e,t){let n=t?.extractMetadata===!0?{...t,extractMetadata:!0}:null,r=my(e,t);if(r!=null){if(n!=null){let{metadata:t}=r;return t==null||gy(r.content)?oy(e,n):{content:r.content,metadata:t}}return r.content}return n==null?t==null?oy(e):oy(e,{...t,extractMetadata:!1}):oy(e,n)}function my(e,t){if(uy==null)return null;try{let n=uy.compileMdxToMd(e,hy(t)),r=JSON.parse(n);return t?.extractMetadata===!0&&r.metadata==null?null:r}catch{return null}}function hy(e){if(e==null)return null;let t={...e,...e.globalScope==null?{}:{globalScope:{os:e.globalScope.os,env:e.globalScope.env,profile:e.globalScope.profile,tool:e.globalScope.tool}}};return JSON.stringify(t)}function gy(e){let t;for(let n of e.split(cy)){let e=sy.exec(n);if(e?.[1]!=null){let n=e[1];t==null?t=n:t===n&&(t=void 0);continue}if(t==null&&ly.some(e=>e.test(n)))return!0}return!1}const _y=/^[\w-]+$/u,vy=/\r\n?/gu;function yy(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function by(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||e instanceof Date}function xy(e){return e.length>0&&e.every(e=>yy(e))}function Sy(e){if(e==null)return;if(e instanceof Date)return e.toISOString();if(typeof e==`bigint`)return e.toString();if(Array.isArray(e))return e.map(e=>Sy(e)).filter(e=>e!==void 0);if(!yy(e))return e;let t={};for(let[n,r]of Object.entries(e)){let e=Sy(r);e!==void 0&&(t[n]=e)}return t}function Cy(e){return _y.test(e)}function wy(e){return Cy(e)?e:JSON.stringify(e)}function Ty(e){return e.map(e=>wy(e)).join(`.`)}function Ey(e){let t=e.replaceAll(vy,`
|
|
219
219
|
`),n=``;for(let e of t)switch(e){case`\\`:n+=`\\\\`;break;case`"`:n+=`\\"`;break;case`\b`:n+=`\\b`;break;case` `:n+=`\\t`;break;case`\f`:n+=`\\f`;break;case`
|
|
220
220
|
`:n+=`
|
|
221
|
-
`;break;default:{let t=e.codePointAt(0);if(t!=null&&t<32){n+=`\\u${t.toString(16).padStart(4,`0`)}`;break}n+=e}}return`"""\n${n}"""`}function
|
|
222
|
-
`)||e.includes(`\r`)?
|
|
223
|
-
`)}function
|
|
224
|
-
`&&(a=!1);continue}if(o){c===`*`&&l===`/`&&(o=!1,s++);continue}if(i){i=!1;continue}if(r!=null){if(c===`\\`){i=!0;continue}c===r&&(r=void 0);continue}if(c===`"`||c===`'`||c==="`"){r=c;continue}if(c===`/`&&l===`/`){a=!0,s++;continue}if(c===`/`&&l===`*`){o=!0,s++;continue}if(c===`{`){n++;continue}if(c===`}`&&(n--,n===0))return{value:e.slice(t,s+1),endIndex:s+1}}return null}function ub(e){let t=e.trimStart(),n=nb.exec(t);if(n==null)return null;let r=n[0].length,i=lb(t,r);if(i==null)return null;let a;try{a=v.parse(i.value)}catch{return null}return cb(a)?{content:sb(t.slice(i.endIndex)),metadata:a}:null}async function db(e,t){let n=t.rawMdx??i.readFileSync(e,`utf8`),r=t.lastModified??i.statSync(e).mtime,a=Cp(n);if(t.mode===`dist`){let e=ub(n);if(e!=null)return{rawMdx:n,parsed:a,content:e.content,metadata:e.metadata,lastModified:r}}let o=await fy(n,{globalScope:t.globalScope,extractMetadata:!0,basePath:u.dirname(e),filePath:e});return{rawMdx:n,parsed:a,content:o.content,metadata:o.metadata.fields,lastModified:r}}async function fb(e,t){let n=t.lastModified??i.statSync(e).mtime,r=n.getTime(),a=ab(e,r,t),o=eb.get(a);if(o!=null)return(await o).artifact;let s=db(e,{...t,lastModified:n}).then(e=>({artifact:e,stamp:r}));eb.set(a,s);try{return(await s).artifact}catch(e){throw eb.delete(a),e}}async function pb(e){let t=ob(e),n=tb.get(t);if(n!=null)return n;let r=fy(e.rawMdx,{globalScope:e.globalScope,extractMetadata:!0,basePath:u.dirname(e.filePath),filePath:e.filePath}).then(e=>({content:e.content,metadata:e.metadata.fields}));tb.set(t,r);try{return await r}catch(e){throw tb.delete(t),e}}function mb(e){return e.replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/gu,``)}function hb(e){let t=mb(e);return t.length===0?``:t.split(`/`).filter(e=>e.length>0).join(`-`)}function gb(e){let t=mb(e),n=t.split(`/`).filter(e=>e.length>0),r=n.at(-1)??t,i=n.slice(0,-1),a=hb(t),o=i.length>0?i.join(`-`):void 0;return{...o!=null&&{agentPrefix:o},agentName:r,canonicalName:a.length>0?a:r}}function _b(e){return e.skillName.trim().length>0?e.skillName:e.dir.getDirectoryName()}function vb(e){return e.canonicalName.trim().length>0?e.canonicalName:hb(e.agentPrefix!=null&&e.agentPrefix.length>0?`${e.agentPrefix}-${e.agentName}`:e.agentName)}const yb=[`project`,`global`];function bb(e){if(e==null)return[];if(typeof e==`string`)return[e];let t=[];for(let n of e)t.includes(n)||t.push(n);return t}function xb(e,t){let n=new Map;for(let[e,r]of t.entries())n.set(r,e);return[...e].sort((e,t)=>(n.get(e)??2**53-1)-(n.get(t)??2**53-1))}function Sb(e){let{requestedScopes:t,defaultScopes:n,supportedScopes:r,singleScope:i,availableScopes:a,priority:o=yb}=e,s=bb(t),c=bb(n),l=new Set(bb(r)),u=(s.length>0?s:c).filter(e=>l.has(e));if(u.length===0)return[];let d=xb(u,o);if(!i)return d;if(a!=null&&a.length>0){let e=new Set(a),t=d.find(t=>e.has(t));return t==null?[]:[t]}let[f]=d;return f==null?[]:[f]}const Cb=y.object({src:y.string(),dist:y.string()}),wb=y.object({dir:y.string().default(`aindex`),skills:Cb,commands:Cb,subAgents:Cb,rules:Cb,globalPrompt:Cb,workspacePrompt:Cb,app:Cb,ext:Cb,arch:Cb}),Tb=y.object({includeSeriesPrefix:y.boolean().optional(),seriesSeparator:y.string().optional()}),Eb=y.object({includeSeriesPrefix:y.boolean().optional(),pluginOverrides:y.record(y.string(),Tb).optional()}),Db=y.enum([`project`,`global`]),Ob=y.union([Db,y.array(Db).min(1)]),kb=y.object({prompt:Ob.optional(),rules:Ob.optional(),commands:Ob.optional(),subagents:Ob.optional(),skills:Ob.optional(),mcp:Ob.optional()}),Ab=y.object({plugins:y.record(y.string(),kb).optional()}),jb=y.object({blankLineAfter:y.boolean().optional()}),Mb=y.enum([`direct`,`recursive`]),Nb=y.enum([`path`,`glob`]),Pb=y.object({path:y.string(),protectionMode:Mb,matcher:Nb.optional(),reason:y.string().optional()}),Fb=y.object({rules:y.array(Pb).optional()}),Ib=y.union([y.string(),y.array(y.string()).min(1)]),Lb=y.object({instances:Ib.optional()}),Rb=y.object({wsl2:Lb.optional()}),zb=y.object({name:y.string().optional(),username:y.string().optional(),gender:y.string().optional(),birthday:y.string().optional()}).catchall(y.unknown()),Bb=y.object({version:y.string().optional(),workspaceDir:y.string().optional(),aindex:wb.optional(),logLevel:y.enum([`trace`,`debug`,`info`,`warn`,`error`]).optional(),commandSeriesOptions:Eb.optional(),outputScopes:Ab.optional(),frontMatter:jb.optional(),cleanupProtection:Fb.optional(),windows:Rb.optional(),profile:zb.optional()}),Vb=y.object({names:y.array(y.string()).optional()}),Hb=y.object({includeSeries:y.array(y.string()).optional(),subSeries:y.record(y.string(),y.array(y.string())).optional()});y.object({mcp:Vb.optional(),includeSeries:y.array(y.string()).optional(),subSeries:y.record(y.string(),y.array(y.string())).optional(),rules:Hb.optional(),skills:Hb.optional(),subAgents:Hb.optional(),commands:Hb.optional()}),y.object({});function Ub(e,t){let n=t==null?``:` in ${t}`;return e==null||e===`project`||e===`global`?{valid:!0,errors:[],warnings:[]}:{valid:!1,errors:[`Field "scope" must be "project" or "global"${n}`],warnings:[]}}function Wb(e,t){let{requiredFields:n,optionalDefaults:r,filePath:i}=t,a=[],o=[];for(let t of n){let n=String(t);if(!(n in e)||e[n]==null){let e=i==null?`Missing required field "${n}"`:`Missing required field "${n}" in ${i}`;a.push(e)}}if(r!=null){for(let[t,n]of Object.entries(r))if(!(t in e)||e[t]==null){let e=i==null?`Using default value for optional field "${t}": ${JSON.stringify(n)}`:`Using default value for optional field "${t}": ${JSON.stringify(n)} in ${i}`;o.push(e)}}return{valid:a.length===0,errors:a,warnings:o}}function Gb(e,t){let n=t==null?``:` in ${t}`,r=[],i=[];!(`description`in e)||e.description==null?r.push(`Missing required field "description"${n}`):(typeof e.description!=`string`||e.description.trim().length===0)&&r.push(`Required field "description" cannot be empty${n}`),e.enabled??i.push(`Using default value for optional field "enabled": true${n}`),e.keywords??i.push(`Using default value for optional field "keywords": []${n}`);let a=Ub(e.scope,t);return r.push(...a.errors),{valid:r.length===0,errors:r,warnings:i}}function Kb(e,t){let n=Wb(e,{requiredFields:[],optionalDefaults:{},filePath:t}),r=Ub(e.scope,t);return{valid:n.valid&&r.valid,errors:[...n.errors,...r.errors],warnings:n.warnings}}function qb(e,t){let n=Wb(e,{requiredFields:[`description`],optionalDefaults:{},filePath:t}),r=Ub(e.scope,t);return{valid:n.valid&&r.valid,errors:[...n.errors,...r.errors],warnings:n.warnings}}function Jb(e,t){let n=[],r=[],i=t==null?``:` in ${t}`;!Array.isArray(e.globs)||e.globs.length===0?n.push(`Missing or empty required field "globs"${i}`):e.globs.every(e=>typeof e==`string`)||n.push(`Field "globs" must be an array of strings${i}`),(typeof e.description!=`string`||e.description.length===0)&&n.push(`Missing or empty required field "description"${i}`);let{scope:a,seriName:o}=e,s=Ub(a,t);return n.push(...s.errors),a??r.push(`Using default value for optional field "scope": "project"${i}`),o!=null&&typeof o!=`string`&&!Array.isArray(o)&&n.push(`Field "seriName" must be a string or string array${i}`),{valid:n.length===0,errors:n,warnings:r}}function Yb(e){return{workspace:{directory:e.workspace.directory,projects:[...e.workspace.projects]},...e.skills!=null&&{skills:[...e.skills]},...e.commands!=null&&{commands:[...e.commands]},...e.subAgents!=null&&{subAgents:[...e.subAgents]},...e.rules!=null&&{rules:[...e.rules]},...e.readmePrompts!=null&&{readmePrompts:[...e.readmePrompts]},...e.globalMemory!=null&&{globalMemory:e.globalMemory},...e.vscodeConfigFiles!=null&&{vscodeConfigFiles:[...e.vscodeConfigFiles]},...e.zedConfigFiles!=null&&{zedConfigFiles:[...e.zedConfigFiles]},...e.jetbrainsConfigFiles!=null&&{jetbrainsConfigFiles:[...e.jetbrainsConfigFiles]},...e.editorConfigFiles!=null&&{editorConfigFiles:[...e.editorConfigFiles]},...e.aiAgentIgnoreConfigFiles!=null&&{aiAgentIgnoreConfigFiles:[...e.aiAgentIgnoreConfigFiles]},...e.globalGitIgnore!=null&&{globalGitIgnore:e.globalGitIgnore},...e.shadowGitExclude!=null&&{shadowGitExclude:e.shadowGitExclude},...e.aindexDir!=null&&{aindexDir:e.aindexDir}}}const Xb={Readme:{src:`rdm.mdx`,out:`README.md`},CodeOfConduct:{src:`coc.mdx`,out:`CODE_OF_CONDUCT.md`},Security:{src:`security.mdx`,out:`SECURITY.md`}},Zb=[`prompt`,`rules`,`commands`,`subagents`,`skills`,`mcp`];function Qb(e){return _.isBuffer(e)}function $b(e){if(typeof e==`string`)return[e];let t=[];for(let n of e)t.includes(n)||t.push(n);return t}function ex(e,t){return t?.outputScopes?.plugins?.[e]}function tx(e){for(let t of Zb){let n=e.outputCapabilities[t];if(n!=null&&n.scopes.length===0)throw Error(`Plugin ${e.name} declares empty scopes for topic "${t}"`)}}function nx(e,t){let n=ex(e.name,t);if(n!=null)for(let t of Zb){let r=n[t];if(r==null)continue;let i=e.outputCapabilities[t];if(i==null)throw Error(`Invalid outputScopes configuration: outputScopes.plugins.${e.name}.${t} is set, but plugin ${e.name} does not support topic "${t}".`);let a=$b(r);if(i.singleScope&&a.length>1){let n=a.join(`, `);throw Error(`Invalid outputScopes configuration: outputScopes.plugins.${e.name}.${t} is single-scope and cannot request multiple scopes [${n}].`)}let o=new Set(i.scopes),s=a.filter(e=>!o.has(e));if(s.length>0){let n=i.scopes.join(`, `),r=s.join(`, `);throw Error(`Invalid outputScopes configuration: outputScopes.plugins.${e.name}.${t} requests unsupported scopes [${r}]. Allowed scopes: [${n}].`)}}}function rx(e,t){for(let n of e)tx(n),nx(n,t)}async function ix(e,t){rx(e,t.pluginOptions);let n=await Promise.all(e.map(async e=>[e,await e.declareOutputFiles(t)]));return new Map(n)}async function ax(e,t,n){let r=new Map,a=n??await ix(e,t);for(let n of e){let e=a.get(n)??[],o=[];for(let r of e){if(t.dryRun===!0){o.push({path:r.path,success:!0,skipped:!1});continue}try{let e=u.dirname(r.path);if(i.mkdirSync(e,{recursive:!0}),r.ifExists===`skip`&&i.existsSync(r.path)){o.push({path:r.path,success:!0,skipped:!0});continue}if(r.ifExists===`error`&&i.existsSync(r.path))throw Error(`Refusing to overwrite existing file: ${r.path}`);let a=await n.convertContent(r,t);Qb(a)?i.writeFileSync(r.path,a):i.writeFileSync(r.path,a,`utf8`),o.push({path:r.path,success:!0})}catch(e){o.push({path:r.path,success:!1,error:e})}}let s={files:o,dirs:[]};r.set(n.name,s)}return r}async function ox(e,t,n){let r=[],i=[],a=[],o=[],s=n==null?Array.from(await ix(e,{...t,dryRun:!0}),([,e])=>e):[...n.values()];for(let e of s)for(let t of e)t.scope===`global`?o.push(t.path):i.push(t.path);return{projectDirs:r,projectFiles:i,globalDirs:a,globalFiles:o}}var sx=class extends Error{nodeName;missingDependency;constructor(e,t){super(`Node "${e}" depends on missing dependency "${t}"`),this.name=`MissingDependencyError`,this.nodeName=e,this.missingDependency=t}},cx=class extends Error{cyclePath;constructor(e){super(`Circular dependency detected: ${e.join(` -> `)}`),this.name=`CircularDependencyError`,this.cyclePath=[...e]}},lx=class extends Ny{declarativeOutput=!0;outputCapabilities;globalConfigDir;outputFileName;treatWorkspaceRootProjectAsProject;indexignore;commandsConfig;subAgentsConfig;commandOutputEnabled;subAgentOutputEnabled;skillsConfig;skillOutputEnabled;toolPreset;rulesConfig;ruleOutputEnabled;cleanupConfig;wslMirrorPaths;supportsBlankLineAfterFrontMatter;registryWriterCache=new Map;warnedDeprecatedSubAgentFileNameSource=!1;constructor(e,t){super(e,ih.Output,t?.dependsOn),this.globalConfigDir=t?.globalConfigDir??``,this.outputFileName=t?.outputFileName??``,this.treatWorkspaceRootProjectAsProject=t?.treatWorkspaceRootProjectAsProject??!1,this.indexignore=t?.indexignore,this.commandOutputEnabled=t?.commands!=null,this.commandsConfig=this.createCommandsConfig(t?.commands),this.subAgentOutputEnabled=t?.subagents!=null,this.subAgentsConfig=this.createSubAgentsConfig(t?.subagents),this.skillOutputEnabled=t?.skills!=null,this.skillsConfig=this.createSkillsConfig(t?.skills),this.toolPreset=t?.toolPreset,this.ruleOutputEnabled=t?.rules!=null,this.rulesConfig={...t?.rules,sourceScopes:t?.rules?.sourceScopes??[`project`,`global`]},this.cleanupConfig=t?.cleanup??{},this.wslMirrorPaths=t?.wslMirrors??[],this.supportsBlankLineAfterFrontMatter=t?.supportsBlankLineAfterFrontMatter??!0,this.outputCapabilities=t?.capabilities==null?this.buildInferredCapabilities():this.normalizeCapabilities(t.capabilities)}createCommandsConfig(e){return{subDir:e?.subDir??`commands`,sourceScopes:e?.sourceScopes??[`project`,`global`],...e?.scopeRemap!=null&&{scopeRemap:e.scopeRemap},...e?.transformFrontMatter!=null&&{transformFrontMatter:e.transformFrontMatter}}}createSubAgentsConfig(e){return{subDir:e?.subDir??`agents`,sourceScopes:e?.sourceScopes??[`project`,`global`],includePrefix:e?.includePrefix??!0,linkSymbol:e?.linkSymbol??`-`,ext:e?.ext??`.md`,artifactFormat:e?.artifactFormat??`markdown`,fileNameSource:e?.fileNameSource??`derivedPath`,...e?.bodyFieldName!=null&&{bodyFieldName:e.bodyFieldName},...e?.fieldNameMap!=null&&{fieldNameMap:e.fieldNameMap},...e?.excludedFrontMatterFields!=null&&{excludedFrontMatterFields:e.excludedFrontMatterFields},...e?.extraFields!=null&&{extraFields:e.extraFields},...e?.fieldOrder!=null&&{fieldOrder:e.fieldOrder},...e?.scopeRemap!=null&&{scopeRemap:e.scopeRemap},...e?.transformFrontMatter!=null&&{transformFrontMatter:e.transformFrontMatter}}}createSkillsConfig(e){return{subDir:e?.subDir??`skills`,sourceScopes:e?.sourceScopes??[`project`,`global`],...e?.scopeRemap!=null&&{scopeRemap:e.scopeRemap}}}buildInferredCapabilities(){let e={};return this.outputFileName.length>0&&(e.prompt={scopes:[`project`,`global`],singleScope:!1}),this.ruleOutputEnabled&&(e.rules={scopes:this.rulesConfig.sourceScopes??[`project`,`global`],singleScope:!1}),this.commandOutputEnabled&&(e.commands={scopes:this.commandsConfig.sourceScopes,singleScope:!0}),this.subAgentOutputEnabled&&(e.subagents={scopes:this.subAgentsConfig.sourceScopes,singleScope:!0}),this.skillOutputEnabled&&(e.skills={scopes:this.skillsConfig.sourceScopes,singleScope:!0}),e}normalizeCapabilities(e){let t={};for(let n of Zb){let r=e[n];if(r==null)continue;let i=this.normalizeCapability(r);i!=null&&(t[n]=i)}return t}normalizeCapability(e){let t=[];for(let n of e.scopes)t.includes(n)||t.push(n);if(t.length!==0)return{scopes:t,singleScope:e.singleScope}}resolvePromptSourceProjectConfig(e){let t=this.getConcreteProjects(e);return t.find(e=>e.isPromptSourceProject===!0)?.projectConfig??t[0]?.projectConfig}getConcreteProjects(e){return e.collectedOutputContext.workspace.projects.filter(e=>e.isWorkspaceRootProject!==!0)}isProjectPromptOutputTarget(e){return e.isPromptSourceProject!==!0}getProjectOutputProjects(e){let t=[...this.getConcreteProjects(e)];if(!this.treatWorkspaceRootProjectAsProject)return t;let n=this.getWorkspaceRootProject(e);return n!=null&&t.push(n),t}getProjectPromptOutputProjects(e){return this.getProjectOutputProjects(e).filter(e=>this.isProjectPromptOutputTarget(e))}getWorkspaceRootProject(e){return e.collectedOutputContext.workspace.projects.find(e=>e.isWorkspaceRootProject===!0)}resolveProjectRootDir(e,t){if(t.isWorkspaceRootProject===!0)return this.resolveDirectoryPath(e.collectedOutputContext.workspace.directory);let n=t.dirFromWorkspacePath;if(n!=null)return this.resolveDirectoryPath(n)}resolveProjectConfigDir(e,t){let n=this.resolveProjectRootDir(e,t);if(n!=null)return this.globalConfigDir.length===0?n:u.join(n,this.globalConfigDir)}isRelativePath(e){return e.pathKind===oh.Relative}toRelativePath(e){return e.path}resolveFullPath(e,t){let n=this.resolveDirectoryPath(e),r=t??this.outputFileName;return r?u.join(n,r):n}resolveDirectoryPath(e){return e.pathKind===oh.Absolute?e.path:`basePath`in e?u.resolve(e.basePath,e.path):u.resolve(c.cwd(),e.path)}getWorkspaceConfigDir(e){let t=this.resolveDirectoryPath(e.collectedOutputContext.workspace.directory);return u.join(t,this.globalConfigDir)}createRelativePath(e,t,n){return u.join(t,e)}createFileRelativePath(e,t){return u.join(e,t)}getGlobalConfigDir(){return u.join(this.getHomeDir(),this.globalConfigDir)}getXdgConfigHomeDir(){let e=c.env.XDG_CONFIG_HOME;return typeof e==`string`&&e.trim().length>0?e:u.join(this.getHomeDir(),`.config`)}getHomeDir(){return ng()}joinPath(...e){return u.join(...e)}resolvePath(...e){return u.resolve(...e)}dirname(e){return u.dirname(e)}basename(e,t){return u.basename(e,t)}getIgnoreOutputPath(){if(this.indexignore!=null)return this.indexignore}resolveCleanupScopeBasePaths(e,t){if(e===`global`)return[this.getHomeDir()];if(e===`xdgConfig`)return[this.getXdgConfigHomeDir()];let n=[];for(let e of this.getProjectOutputProjects(t)){let r=this.resolveProjectRootDir(t,e);r!=null&&n.push(r)}return n}resolveCleanupDeclaredPath(e,t){return u.isAbsolute(t)?u.resolve(t):t===`~`?this.getHomeDir():t.startsWith(`~/`)||t.startsWith(`~\\`)?u.resolve(this.getHomeDir(),t.slice(2)):u.resolve(e,t)}normalizeGlobPattern(e){return e.replaceAll(`\\`,`/`)}buildCleanupTargetsFromScopeConfig(e,t,n){if(e==null)return[];let r=[],i=[`project`,`global`,`xdgConfig`],a=(e,i,a)=>{if(a==null||a.length===0)return;let o=this.resolveCleanupScopeBasePaths(e,n);for(let n of a)for(let a of o){let o=u.isAbsolute(n)?u.resolve(n):this.resolveCleanupDeclaredPath(a,n);r.push({path:i===`glob`?this.normalizeGlobPattern(o):o,kind:i,scope:e,label:`${t}.${e}`})}};for(let t of i){let n=e[t];n!=null&&(a(t,`file`,n.files),a(t,`directory`,n.dirs),a(t,`glob`,n.globs))}return r}resolveFrontMatterBlankLineAfter(e){return this.supportsBlankLineAfterFrontMatter?e?.pluginOptions?.frontMatter?.blankLineAfter??!0:!0}buildMarkdownContent(e,t,n){return yp(t,e,{blankLineAfter:this.resolveFrontMatterBlankLineAfter(n)})}buildMarkdownContentWithRaw(e,t,n,r){return t!=null&&Object.keys(t).length>0?this.buildMarkdownContent(e,t,r):n!=null&&n.length>0?xp(n,e,{blankLineAfter:this.resolveFrontMatterBlankLineAfter(r)}):e}buildTomlContent(e){return My(e)}extractGlobalMemoryContent(e){return e.collectedOutputContext.globalMemory?.content}combineGlobalWithContent(e,t,n){let{separator:r=`
|
|
221
|
+
`;break;default:{let t=e.codePointAt(0);if(t!=null&&t<32){n+=`\\u${t.toString(16).padStart(4,`0`)}`;break}n+=e}}return`"""\n${n}"""`}function Dy(e){if(typeof e==`string`)return e.includes(`
|
|
222
|
+
`)||e.includes(`\r`)?Ey(e):JSON.stringify(e);if(typeof e==`number`){if(!Number.isFinite(e))throw TypeError(`Unsupported TOML number value: ${e}`);return String(e)}return typeof e==`boolean`?e?`true`:`false`:typeof e==`bigint`?e.toString():JSON.stringify(e.toISOString())}function Oy(e){if(e==null)throw TypeError(`TOML inline value cannot be null or undefined`);if(by(e))return Dy(e);if(Array.isArray(e)){if(xy(e))throw TypeError(`TOML inline arrays of tables are not supported`);let t=[],n=e;for(let e of n)t.push(Oy(e));return`[${t.join(`, `)}]`}let t=[];for(let[n,r]of Object.entries(e))t.push(`${wy(n)} = ${Oy(r)}`);return`{ ${t.join(`, `)} }`}function ky(e,t){if(t==null||t.length===0)return[...e];let n=new Map;for(let[e,r]of t.entries())n.set(r,e);return[...e].sort(([e],[t])=>{let r=n.get(e),i=n.get(t);return r!=null&&i!=null?r-i:r==null?i==null?e.localeCompare(t):1:-1})}function Ay(e,t){let n=ky(Object.entries(e),t),r=[],i=[],a=[];for(let[e,t]of n)if(t!=null){if(Array.isArray(t)){if(xy(t)){a.push([e,t]);continue}r.push([e,t]);continue}if(yy(t)){i.push([e,t]);continue}r.push([e,t])}return{scalarEntries:r,tableEntries:i,arrayTableEntries:a}}function jy(e,t,n,r=!0){let i=[],{scalarEntries:a,tableEntries:o,arrayTableEntries:s}=Ay(t,n?.fieldOrder);r&&e.length>0&&i.push(`[${Ty(e)}]`);for(let[e,t]of a)i.push(`${wy(e)} = ${Oy(t)}`);for(let[t,r]of o)i.length>0&&i.push(``),i.push(...jy([...e,t],r,n));for(let[t,r]of s)for(let a of r){i.length>0&&i.push(``),i.push(`[[${Ty([...e,t])}]]`);let r=jy([...e,t],a,n,!1);i.push(...r)}return i}function My(e,t){let n=Sy(e);if(!yy(n))throw TypeError(`TOML document root must be an object`);return jy([],n,t).join(`
|
|
223
|
+
`)}function Ny(e){let{content:t,bodyFieldName:n,frontMatter:r,fieldNameMap:i,excludedKeys:a,extraFields:o,fieldOrder:s}=e,c=new Set(a??[]),l={};for(let[e,t]of Object.entries(r??{})){if(c.has(e))continue;let n=i?.[e]??e;l[n]=t}if(o!=null)for(let[e,t]of Object.entries(o))l[e]=t;return l[n]=t,My(l,{...s!=null&&{fieldOrder:s}})}var Py=class{type;name;_log;get log(){return this._log??=be(this.name),this._log}dependsOn;constructor(e,t,n){this.name=e,this.type=t,n!=null&&(this.dependsOn=n)}};function Fy(e,t){return e==null&&t==null?[]:[...new Set([...e??[],...t??[]])]}function Iy(e,t){return e==null||t.length===0?!0:typeof e==`string`?t.includes(e):e.some(e=>t.includes(e))}function Ly(e,t){if(e==null&&t==null)return{};let n={};for(let[t,r]of Object.entries(e??{}))n[t]=[...r];for(let[e,r]of Object.entries(t??{})){let t=n[e]??[];n[e]=Object.hasOwn(n,e)?[...new Set([...t,...r])]:[...r]}return n}function Ry(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.matchesSeries==`function`&&typeof t.resolveEffectiveIncludeSeries==`function`&&typeof t.resolveSubSeries==`function`}function zy(){let e={"win32-x64":`win32-x64-msvc`,"linux-x64":`linux-x64-gnu`,"linux-arm64":`linux-arm64-gnu`,"darwin-arm64":`darwin-arm64`,"darwin-x64":`darwin-x64`}[`${c.platform}-${c.arch}`];if(e==null)return;let t=`@truenine/memory-sync-cli-${e}`,n=`napi-memory-sync-cli.${e}.node`;try{let e=r(import.meta.url),i=[t,`${t}/${n}`,`./${n}`];for(let t of i)try{let n=e(t),r=[n,n?.default,n?.config];for(let e of r)if(Ry(e))return e}catch{}}catch{}}const{resolveEffectiveIncludeSeries:By,matchesSeries:Vy,resolveSubSeries:Hy}=zy()??{resolveEffectiveIncludeSeries:Fy,matchesSeries:Iy,resolveSubSeries:Ly};function $(e,t,n){let r=By(t?.includeSeries,t?.[n]?.includeSeries);return e.filter(e=>Vy(e.seriName,r))}function Uy(e){let t=e.replaceAll(/\.\/+/g,``);return t=t.replaceAll(/\/+$/g,``),t}function Wy(e,t){return t.startsWith(`**/`)?`${e}/${t}`:t.startsWith(`*`)?`${e}/**/${t}`:`${e}/${t}`}function Gy(e,t){for(let n of t){let t=n.replaceAll(/\/+$/g,``),r=[{prefix:t,pattern:`${t}/`},{prefix:t,pattern:`${t}\\`}];for(let{prefix:t,pattern:n}of r)if(e.startsWith(n))return{prefix:t,baseGlob:e.slice(n.length)};if(e===t)return{prefix:t,baseGlob:`**/*`}}return{prefix:null,baseGlob:e}}function Ky(e,t){let n=Hy(t?.subSeries,t?.rules?.subSeries);if(Object.keys(n).length===0)return e;let r={};for(let[e,t]of Object.entries(n)){let n=Uy(e);r[n]=t}let i=Object.keys(r);return e.map(e=>{if(e.seriName==null)return e;let t=[];for(let[n,i]of Object.entries(r))(Array.isArray(e.seriName)?e.seriName.some(e=>i.includes(e)):i.includes(e.seriName))&&t.push(n);if(t.length===0)return e;let n=[];for(let r of e.globs){let{prefix:e,baseGlob:a}=Gy(r,i);e!=null&&n.push(r);for(let r of t){if(r===e)continue;let t=Wy(r,a);n.includes(t)||n.push(t)}}return{...e,globs:n}})}function qy(e){let t=u.join(e,`.git`);if(!i.existsSync(t))return null;let n=i.lstatSync(t);if(n.isDirectory())return u.join(t,`info`);if(n.isFile())try{let n=i.readFileSync(t,`utf8`).trim(),r=/^gitdir: (.+)$/.exec(n);if(r?.[1]!=null){let t=u.resolve(e,r[1]);return u.join(t,`info`)}}catch{}return null}function Jy(e,t=5){let n=[],r=new Set([`node_modules`,`.turbo`,`dist`,`build`,`out`,`.cache`]);function a(o,s){if(s>t)return;let c;try{let e=i.readdirSync(o,{withFileTypes:!0});if(!Array.isArray(e))return;c=e}catch{return}c.some(e=>e.name===`.git`)&&o!==e&&n.push(o);for(let e of c)e.isDirectory()&&(e.name===`.git`||r.has(e.name)||a(u.join(o,e.name),s+1))}return a(e,0),n}const Yy={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 Xy=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}({}),Zy=function(e){return e.Win=`win`,e.Mac=`mac`,e.Linux=`linux`,e.Unknown=`unknown`,e}({});var Qy=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=g.platform();return{platform:e,arch:g.arch(),hostname:g.hostname(),homedir:rg(),tmpdir:g.tmpdir(),type:g.type(),release:g.release(),shellKind:this.detectShellKind(),kind:this.detectOsKind(e)}}detectOsKind(e){switch(e){case`win32`:return Zy.Win;case`darwin`:return Zy.Mac;case`linux`:case`freebsd`:case`openbsd`:case`sunos`:case`aix`:return Zy.Linux;default:return Zy.Unknown}}detectShellKind(){let e=(c.env.SHELL??c.env.ComSpec??``).toLowerCase();return e.includes(`bash`)?Xy.Bash:e.includes(`zsh`)?Xy.Zsh:e.includes(`fish`)?Xy.Fish:e.includes(`pwsh`)?Xy.Pwsh:e.includes(`powershell`)?Xy.PowerShell:e.includes(`cmd`)?Xy.Cmd:e.endsWith(`/sh`)?Xy.Sh:Xy.Unknown}collectEnvContext(){return{...c.env}}collectProfile(){return this.userConfig?.profile==null?{}:this.userConfig.profile}collectToolReferences(){let e={...Yy.default};return this.toolPreset===`claudeCode`?{...e,...Yy.claudeCode}:this.toolPreset===`kiro`?{...e,...Yy.kiro}:e}createMdComponent(){let e=(e=>e.when===!1?null:e.children);return e.Line=e=>e.when===!1?null:e.children,e}};let $y=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 eb=class{registrations=[];globalScope=null;setGlobalScope(e){this.globalScope=e}getGlobalScope(){return this.globalScope}register(e,t,n=$y.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}resolve(e){let t=this.merge();return e.replaceAll(/\$\{([^}]+)\}/g,(e,n)=>{let r=n.split(`.`),i=t;for(let e of r)i=i?.[e];return i==null?`\${${n}}`:String(i)})}clear(){this.registrations.length=0,this.globalScope=null}};const tb=new Map,nb=new Map,rb=/^export\s+default\s*/u;function ib(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(ib);let t=Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ib(t)]);return Object.fromEntries(t)}function ab(e){return JSON.stringify(ib(e))}function ob(e,t,n){return[u.resolve(e),t,n.mode,ab(n.globalScope??{})].join(`::`)}function sb(e){return[u.resolve(e.filePath),e.cacheMtimeMs??e.rawMdx.length,ab(e.globalScope??{}),ab(e.rawMdx)].join(`::`)}function cb(e){return e.replace(/^\s*;?\s*/u,``).trim()}function lb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ub(e,t){if(e[t]!==`{`)return null;let n=0,r,i=!1,a=!1,o=!1;for(let s=t;s<e.length;s++){let c=e[s],l=e[s+1];if(c==null)break;if(a){c===`
|
|
224
|
+
`&&(a=!1);continue}if(o){c===`*`&&l===`/`&&(o=!1,s++);continue}if(i){i=!1;continue}if(r!=null){if(c===`\\`){i=!0;continue}c===r&&(r=void 0);continue}if(c===`"`||c===`'`||c==="`"){r=c;continue}if(c===`/`&&l===`/`){a=!0,s++;continue}if(c===`/`&&l===`*`){o=!0,s++;continue}if(c===`{`){n++;continue}if(c===`}`&&(n--,n===0))return{value:e.slice(t,s+1),endIndex:s+1}}return null}function db(e){let t=e.trimStart(),n=rb.exec(t);if(n==null)return null;let r=n[0].length,i=ub(t,r);if(i==null)return null;let a;try{a=v.parse(i.value)}catch{return null}return lb(a)?{content:cb(t.slice(i.endIndex)),metadata:a}:null}async function fb(e,t){let n=t.rawMdx??i.readFileSync(e,`utf8`),r=t.lastModified??i.statSync(e).mtime,a=Cp(n);if(t.mode===`dist`){let e=db(n);if(e!=null)return{rawMdx:n,parsed:a,content:e.content,metadata:e.metadata,lastModified:r}}let o=await py(n,{globalScope:t.globalScope,extractMetadata:!0,basePath:u.dirname(e),filePath:e});return{rawMdx:n,parsed:a,content:o.content,metadata:o.metadata.fields,lastModified:r}}async function pb(e,t){let n=t.lastModified??i.statSync(e).mtime,r=n.getTime(),a=ob(e,r,t),o=tb.get(a);if(o!=null)return(await o).artifact;let s=fb(e,{...t,lastModified:n}).then(e=>({artifact:e,stamp:r}));tb.set(a,s);try{return(await s).artifact}catch(e){throw tb.delete(a),e}}async function mb(e){let t=sb(e),n=nb.get(t);if(n!=null)return n;let r=py(e.rawMdx,{globalScope:e.globalScope,extractMetadata:!0,basePath:u.dirname(e.filePath),filePath:e.filePath}).then(e=>({content:e.content,metadata:e.metadata.fields}));nb.set(t,r);try{return await r}catch(e){throw nb.delete(t),e}}function hb(e){return e.replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/gu,``)}function gb(e){let t=hb(e);return t.length===0?``:t.split(`/`).filter(e=>e.length>0).join(`-`)}function _b(e){let t=hb(e),n=t.split(`/`).filter(e=>e.length>0),r=n.at(-1)??t,i=n.slice(0,-1),a=gb(t),o=i.length>0?i.join(`-`):void 0;return{...o!=null&&{agentPrefix:o},agentName:r,canonicalName:a.length>0?a:r}}function vb(e){return e.skillName.trim().length>0?e.skillName:e.dir.getDirectoryName()}function yb(e){return e.canonicalName.trim().length>0?e.canonicalName:gb(e.agentPrefix!=null&&e.agentPrefix.length>0?`${e.agentPrefix}-${e.agentName}`:e.agentName)}const bb=[`project`,`global`];function xb(e){if(e==null)return[];if(typeof e==`string`)return[e];let t=[];for(let n of e)t.includes(n)||t.push(n);return t}function Sb(e,t){let n=new Map;for(let[e,r]of t.entries())n.set(r,e);return[...e].sort((e,t)=>(n.get(e)??2**53-1)-(n.get(t)??2**53-1))}function Cb(e){let{requestedScopes:t,defaultScopes:n,supportedScopes:r,singleScope:i,availableScopes:a,priority:o=bb}=e,s=xb(t),c=xb(n),l=new Set(xb(r)),u=(s.length>0?s:c).filter(e=>l.has(e));if(u.length===0)return[];let d=Sb(u,o);if(!i)return d;if(a!=null&&a.length>0){let e=new Set(a),t=d.find(t=>e.has(t));return t==null?[]:[t]}let[f]=d;return f==null?[]:[f]}const wb=y.object({src:y.string(),dist:y.string()}),Tb=y.object({dir:y.string().default(`aindex`),skills:wb,commands:wb,subAgents:wb,rules:wb,globalPrompt:wb,workspacePrompt:wb,app:wb,ext:wb,arch:wb}),Eb=y.object({includeSeriesPrefix:y.boolean().optional(),seriesSeparator:y.string().optional()}),Db=y.object({includeSeriesPrefix:y.boolean().optional(),pluginOverrides:y.record(y.string(),Eb).optional()}),Ob=y.enum([`project`,`global`]),kb=y.union([Ob,y.array(Ob).min(1)]),Ab=y.object({prompt:kb.optional(),rules:kb.optional(),commands:kb.optional(),subagents:kb.optional(),skills:kb.optional(),mcp:kb.optional()}),jb=y.object({plugins:y.record(y.string(),Ab).optional()}),Mb=y.object({blankLineAfter:y.boolean().optional()}),Nb=y.enum([`direct`,`recursive`]),Pb=y.enum([`path`,`glob`]),Fb=y.object({path:y.string(),protectionMode:Nb,matcher:Pb.optional(),reason:y.string().optional()}),Ib=y.object({rules:y.array(Fb).optional()}),Lb=y.union([y.string(),y.array(y.string()).min(1)]),Rb=y.object({instances:Lb.optional()}),zb=y.object({wsl2:Rb.optional()}),Bb=y.object({name:y.string().optional(),username:y.string().optional(),gender:y.string().optional(),birthday:y.string().optional()}).catchall(y.unknown()),Vb=y.object({version:y.string().optional(),workspaceDir:y.string().optional(),aindex:Tb.optional(),logLevel:y.enum([`trace`,`debug`,`info`,`warn`,`error`]).optional(),commandSeriesOptions:Db.optional(),outputScopes:jb.optional(),frontMatter:Mb.optional(),cleanupProtection:Ib.optional(),windows:zb.optional(),profile:Bb.optional()}),Hb=y.object({names:y.array(y.string()).optional()}),Ub=y.object({includeSeries:y.array(y.string()).optional(),subSeries:y.record(y.string(),y.array(y.string())).optional()});y.object({mcp:Hb.optional(),includeSeries:y.array(y.string()).optional(),subSeries:y.record(y.string(),y.array(y.string())).optional(),rules:Ub.optional(),skills:Ub.optional(),subAgents:Ub.optional(),commands:Ub.optional()}),y.object({});function Wb(e,t){let n=t==null?``:` in ${t}`;return e==null||e===`project`||e===`global`?{valid:!0,errors:[],warnings:[]}:{valid:!1,errors:[`Field "scope" must be "project" or "global"${n}`],warnings:[]}}function Gb(e,t){let{requiredFields:n,optionalDefaults:r,filePath:i}=t,a=[],o=[];for(let t of n){let n=String(t);if(!(n in e)||e[n]==null){let e=i==null?`Missing required field "${n}"`:`Missing required field "${n}" in ${i}`;a.push(e)}}if(r!=null){for(let[t,n]of Object.entries(r))if(!(t in e)||e[t]==null){let e=i==null?`Using default value for optional field "${t}": ${JSON.stringify(n)}`:`Using default value for optional field "${t}": ${JSON.stringify(n)} in ${i}`;o.push(e)}}return{valid:a.length===0,errors:a,warnings:o}}function Kb(e,t){let n=t==null?``:` in ${t}`,r=[],i=[];!(`description`in e)||e.description==null?r.push(`Missing required field "description"${n}`):(typeof e.description!=`string`||e.description.trim().length===0)&&r.push(`Required field "description" cannot be empty${n}`),e.enabled??i.push(`Using default value for optional field "enabled": true${n}`),e.keywords??i.push(`Using default value for optional field "keywords": []${n}`);let a=Wb(e.scope,t);return r.push(...a.errors),{valid:r.length===0,errors:r,warnings:i}}function qb(e,t){let n=Gb(e,{requiredFields:[],optionalDefaults:{},filePath:t}),r=Wb(e.scope,t);return{valid:n.valid&&r.valid,errors:[...n.errors,...r.errors],warnings:n.warnings}}function Jb(e,t){let n=Gb(e,{requiredFields:[`description`],optionalDefaults:{},filePath:t}),r=Wb(e.scope,t);return{valid:n.valid&&r.valid,errors:[...n.errors,...r.errors],warnings:n.warnings}}function Yb(e,t){let n=[],r=[],i=t==null?``:` in ${t}`;!Array.isArray(e.globs)||e.globs.length===0?n.push(`Missing or empty required field "globs"${i}`):e.globs.every(e=>typeof e==`string`)||n.push(`Field "globs" must be an array of strings${i}`),(typeof e.description!=`string`||e.description.length===0)&&n.push(`Missing or empty required field "description"${i}`);let{scope:a,seriName:o}=e,s=Wb(a,t);return n.push(...s.errors),a??r.push(`Using default value for optional field "scope": "project"${i}`),o!=null&&typeof o!=`string`&&!Array.isArray(o)&&n.push(`Field "seriName" must be a string or string array${i}`),{valid:n.length===0,errors:n,warnings:r}}function Xb(e){return{workspace:{directory:e.workspace.directory,projects:[...e.workspace.projects]},...e.skills!=null&&{skills:[...e.skills]},...e.commands!=null&&{commands:[...e.commands]},...e.subAgents!=null&&{subAgents:[...e.subAgents]},...e.rules!=null&&{rules:[...e.rules]},...e.readmePrompts!=null&&{readmePrompts:[...e.readmePrompts]},...e.globalMemory!=null&&{globalMemory:e.globalMemory},...e.vscodeConfigFiles!=null&&{vscodeConfigFiles:[...e.vscodeConfigFiles]},...e.zedConfigFiles!=null&&{zedConfigFiles:[...e.zedConfigFiles]},...e.jetbrainsConfigFiles!=null&&{jetbrainsConfigFiles:[...e.jetbrainsConfigFiles]},...e.editorConfigFiles!=null&&{editorConfigFiles:[...e.editorConfigFiles]},...e.aiAgentIgnoreConfigFiles!=null&&{aiAgentIgnoreConfigFiles:[...e.aiAgentIgnoreConfigFiles]},...e.globalGitIgnore!=null&&{globalGitIgnore:e.globalGitIgnore},...e.shadowGitExclude!=null&&{shadowGitExclude:e.shadowGitExclude},...e.aindexDir!=null&&{aindexDir:e.aindexDir}}}const Zb={Readme:{src:`rdm.mdx`,out:`README.md`},CodeOfConduct:{src:`coc.mdx`,out:`CODE_OF_CONDUCT.md`},Security:{src:`security.mdx`,out:`SECURITY.md`}},Qb=[`prompt`,`rules`,`commands`,`subagents`,`skills`,`mcp`];function $b(e){return _.isBuffer(e)}function ex(e){if(typeof e==`string`)return[e];let t=[];for(let n of e)t.includes(n)||t.push(n);return t}function tx(e,t){return t?.outputScopes?.plugins?.[e]}function nx(e){for(let t of Qb){let n=e.outputCapabilities[t];if(n!=null&&n.scopes.length===0)throw Error(`Plugin ${e.name} declares empty scopes for topic "${t}"`)}}function rx(e,t){let n=tx(e.name,t);if(n!=null)for(let t of Qb){let r=n[t];if(r==null)continue;let i=e.outputCapabilities[t];if(i==null)throw Error(`Invalid outputScopes configuration: outputScopes.plugins.${e.name}.${t} is set, but plugin ${e.name} does not support topic "${t}".`);let a=ex(r);if(i.singleScope&&a.length>1){let n=a.join(`, `);throw Error(`Invalid outputScopes configuration: outputScopes.plugins.${e.name}.${t} is single-scope and cannot request multiple scopes [${n}].`)}let o=new Set(i.scopes),s=a.filter(e=>!o.has(e));if(s.length>0){let n=i.scopes.join(`, `),r=s.join(`, `);throw Error(`Invalid outputScopes configuration: outputScopes.plugins.${e.name}.${t} requests unsupported scopes [${r}]. Allowed scopes: [${n}].`)}}}function ix(e,t){for(let n of e)nx(n),rx(n,t)}async function ax(e,t){ix(e,t.pluginOptions);let n=await Promise.all(e.map(async e=>[e,await e.declareOutputFiles(t)]));return new Map(n)}async function ox(e,t,n){let r=new Map,a=n??await ax(e,t);for(let n of e){let e=a.get(n)??[],o=[];for(let r of e){if(t.dryRun===!0){o.push({path:r.path,success:!0,skipped:!1});continue}try{let e=u.dirname(r.path);if(i.mkdirSync(e,{recursive:!0}),r.ifExists===`skip`&&i.existsSync(r.path)){o.push({path:r.path,success:!0,skipped:!0});continue}if(r.ifExists===`error`&&i.existsSync(r.path))throw Error(`Refusing to overwrite existing file: ${r.path}`);let a=await n.convertContent(r,t);$b(a)?i.writeFileSync(r.path,a):i.writeFileSync(r.path,a,`utf8`),o.push({path:r.path,success:!0})}catch(e){o.push({path:r.path,success:!1,error:e})}}let s={files:o,dirs:[]};r.set(n.name,s)}return r}async function sx(e,t,n){let r=[],i=[],a=[],o=[],s=n==null?Array.from(await ax(e,{...t,dryRun:!0}),([,e])=>e):[...n.values()];for(let e of s)for(let t of e)t.scope===`global`?o.push(t.path):i.push(t.path);return{projectDirs:r,projectFiles:i,globalDirs:a,globalFiles:o}}var cx=class extends Error{nodeName;missingDependency;constructor(e,t){super(`Node "${e}" depends on missing dependency "${t}"`),this.name=`MissingDependencyError`,this.nodeName=e,this.missingDependency=t}},lx=class extends Error{cyclePath;constructor(e){super(`Circular dependency detected: ${e.join(` -> `)}`),this.name=`CircularDependencyError`,this.cyclePath=[...e]}},ux=class extends Py{declarativeOutput=!0;outputCapabilities;globalConfigDir;outputFileName;treatWorkspaceRootProjectAsProject;indexignore;commandsConfig;subAgentsConfig;commandOutputEnabled;subAgentOutputEnabled;skillsConfig;skillOutputEnabled;toolPreset;rulesConfig;ruleOutputEnabled;cleanupConfig;wslMirrorPaths;supportsBlankLineAfterFrontMatter;registryWriterCache=new Map;warnedDeprecatedSubAgentFileNameSource=!1;constructor(e,t){super(e,ah.Output,t?.dependsOn),this.globalConfigDir=t?.globalConfigDir??``,this.outputFileName=t?.outputFileName??``,this.treatWorkspaceRootProjectAsProject=t?.treatWorkspaceRootProjectAsProject??!1,this.indexignore=t?.indexignore,this.commandOutputEnabled=t?.commands!=null,this.commandsConfig=this.createCommandsConfig(t?.commands),this.subAgentOutputEnabled=t?.subagents!=null,this.subAgentsConfig=this.createSubAgentsConfig(t?.subagents),this.skillOutputEnabled=t?.skills!=null,this.skillsConfig=this.createSkillsConfig(t?.skills),this.toolPreset=t?.toolPreset,this.ruleOutputEnabled=t?.rules!=null,this.rulesConfig={...t?.rules,sourceScopes:t?.rules?.sourceScopes??[`project`,`global`]},this.cleanupConfig=t?.cleanup??{},this.wslMirrorPaths=t?.wslMirrors??[],this.supportsBlankLineAfterFrontMatter=t?.supportsBlankLineAfterFrontMatter??!0,this.outputCapabilities=t?.capabilities==null?this.buildInferredCapabilities():this.normalizeCapabilities(t.capabilities)}createCommandsConfig(e){return{subDir:e?.subDir??`commands`,sourceScopes:e?.sourceScopes??[`project`,`global`],...e?.scopeRemap!=null&&{scopeRemap:e.scopeRemap},...e?.transformFrontMatter!=null&&{transformFrontMatter:e.transformFrontMatter}}}createSubAgentsConfig(e){return{subDir:e?.subDir??`agents`,sourceScopes:e?.sourceScopes??[`project`,`global`],includePrefix:e?.includePrefix??!0,linkSymbol:e?.linkSymbol??`-`,ext:e?.ext??`.md`,artifactFormat:e?.artifactFormat??`markdown`,fileNameSource:e?.fileNameSource??`derivedPath`,...e?.bodyFieldName!=null&&{bodyFieldName:e.bodyFieldName},...e?.fieldNameMap!=null&&{fieldNameMap:e.fieldNameMap},...e?.excludedFrontMatterFields!=null&&{excludedFrontMatterFields:e.excludedFrontMatterFields},...e?.extraFields!=null&&{extraFields:e.extraFields},...e?.fieldOrder!=null&&{fieldOrder:e.fieldOrder},...e?.scopeRemap!=null&&{scopeRemap:e.scopeRemap},...e?.transformFrontMatter!=null&&{transformFrontMatter:e.transformFrontMatter}}}createSkillsConfig(e){return{subDir:e?.subDir??`skills`,sourceScopes:e?.sourceScopes??[`project`,`global`],...e?.scopeRemap!=null&&{scopeRemap:e.scopeRemap}}}buildInferredCapabilities(){let e={};return this.outputFileName.length>0&&(e.prompt={scopes:[`project`,`global`],singleScope:!1}),this.ruleOutputEnabled&&(e.rules={scopes:this.rulesConfig.sourceScopes??[`project`,`global`],singleScope:!1}),this.commandOutputEnabled&&(e.commands={scopes:this.commandsConfig.sourceScopes,singleScope:!0}),this.subAgentOutputEnabled&&(e.subagents={scopes:this.subAgentsConfig.sourceScopes,singleScope:!0}),this.skillOutputEnabled&&(e.skills={scopes:this.skillsConfig.sourceScopes,singleScope:!0}),e}normalizeCapabilities(e){let t={};for(let n of Qb){let r=e[n];if(r==null)continue;let i=this.normalizeCapability(r);i!=null&&(t[n]=i)}return t}normalizeCapability(e){let t=[];for(let n of e.scopes)t.includes(n)||t.push(n);if(t.length!==0)return{scopes:t,singleScope:e.singleScope}}resolvePromptSourceProjectConfig(e){let t=this.getConcreteProjects(e);return t.find(e=>e.isPromptSourceProject===!0)?.projectConfig??t[0]?.projectConfig}getConcreteProjects(e){return e.collectedOutputContext.workspace.projects.filter(e=>e.isWorkspaceRootProject!==!0)}isProjectPromptOutputTarget(e){return e.isPromptSourceProject!==!0}getProjectOutputProjects(e){let t=[...this.getConcreteProjects(e)];if(!this.treatWorkspaceRootProjectAsProject)return t;let n=this.getWorkspaceRootProject(e);return n!=null&&t.push(n),t}getProjectPromptOutputProjects(e){return this.getProjectOutputProjects(e).filter(e=>this.isProjectPromptOutputTarget(e))}getWorkspaceRootProject(e){return e.collectedOutputContext.workspace.projects.find(e=>e.isWorkspaceRootProject===!0)}resolveProjectRootDir(e,t){if(t.isWorkspaceRootProject===!0)return this.resolveDirectoryPath(e.collectedOutputContext.workspace.directory);let n=t.dirFromWorkspacePath;if(n!=null)return this.resolveDirectoryPath(n)}resolveProjectConfigDir(e,t){let n=this.resolveProjectRootDir(e,t);if(n!=null)return this.globalConfigDir.length===0?n:u.join(n,this.globalConfigDir)}isRelativePath(e){return e.pathKind===sh.Relative}toRelativePath(e){return e.path}resolveFullPath(e,t){let n=this.resolveDirectoryPath(e),r=t??this.outputFileName;return r?u.join(n,r):n}resolveDirectoryPath(e){return e.pathKind===sh.Absolute?e.path:`basePath`in e?u.resolve(e.basePath,e.path):u.resolve(c.cwd(),e.path)}getWorkspaceConfigDir(e){let t=this.resolveDirectoryPath(e.collectedOutputContext.workspace.directory);return u.join(t,this.globalConfigDir)}createRelativePath(e,t,n){return u.join(t,e)}createFileRelativePath(e,t){return u.join(e,t)}getGlobalConfigDir(){return u.join(this.getHomeDir(),this.globalConfigDir)}getXdgConfigHomeDir(){let e=c.env.XDG_CONFIG_HOME;return typeof e==`string`&&e.trim().length>0?e:u.join(this.getHomeDir(),`.config`)}getHomeDir(){return rg()}joinPath(...e){return u.join(...e)}resolvePath(...e){return u.resolve(...e)}dirname(e){return u.dirname(e)}buildProjectPromptCleanupTargets(e,t=this.outputFileName){if(t.length===0)return[];let n=[],r=new Set,i=(e,t)=>{r.has(e)||(r.add(e),n.push({path:e,kind:`file`,scope:`project`,label:t}))};for(let n of this.getProjectPromptOutputProjects(e)){let r=this.resolveProjectRootDir(e,n);if(r!=null&&(i(this.resolvePath(r,t),`delete.project`),n.childMemoryPrompts!=null))for(let e of n.childMemoryPrompts)i(this.resolveFullPath(e.dir,t),`delete.project.child`)}return n}basename(e,t){return u.basename(e,t)}getIgnoreOutputPath(){if(this.indexignore!=null)return this.indexignore}resolveCleanupScopeBasePaths(e,t){if(e===`global`)return[this.getHomeDir()];if(e===`xdgConfig`)return[this.getXdgConfigHomeDir()];let n=[];for(let e of this.getProjectOutputProjects(t)){let r=this.resolveProjectRootDir(t,e);r!=null&&n.push(r)}return n}resolveCleanupDeclaredPath(e,t){return u.isAbsolute(t)?u.resolve(t):t===`~`?this.getHomeDir():t.startsWith(`~/`)||t.startsWith(`~\\`)?u.resolve(this.getHomeDir(),t.slice(2)):u.resolve(e,t)}normalizeGlobPattern(e){return e.replaceAll(`\\`,`/`)}buildCleanupTargetsFromScopeConfig(e,t,n){if(e==null)return[];let r=[],i=[`project`,`global`,`xdgConfig`],a=(e,i,a)=>{if(a==null||a.length===0)return;let o=this.resolveCleanupScopeBasePaths(e,n);for(let n of a)for(let a of o){let o=u.isAbsolute(n)?u.resolve(n):this.resolveCleanupDeclaredPath(a,n);r.push({path:i===`glob`?this.normalizeGlobPattern(o):o,kind:i,scope:e,label:`${t}.${e}`})}};for(let t of i){let n=e[t];n!=null&&(a(t,`file`,n.files),a(t,`directory`,n.dirs),a(t,`glob`,n.globs))}return r}resolveFrontMatterBlankLineAfter(e){return this.supportsBlankLineAfterFrontMatter?e?.pluginOptions?.frontMatter?.blankLineAfter??!0:!0}buildMarkdownContent(e,t,n){return yp(t,e,{blankLineAfter:this.resolveFrontMatterBlankLineAfter(n)})}buildMarkdownContentWithRaw(e,t,n,r){return t!=null&&Object.keys(t).length>0?this.buildMarkdownContent(e,t,r):n!=null&&n.length>0?xp(n,e,{blankLineAfter:this.resolveFrontMatterBlankLineAfter(r)}):e}buildTomlContent(e){return Ny(e)}extractGlobalMemoryContent(e){return e.collectedOutputContext.globalMemory?.content}combineGlobalWithContent(e,t,n){let{separator:r=`
|
|
225
225
|
|
|
226
|
-
`,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}`}getSkillName(e){return _b(e)}getSubAgentCanonicalName(e){return vb(e)}transformCommandName(e,t){let{includeSeriesPrefix:n=!0,seriesSeparator:r=`-`}=t??{};return!n||e.commandPrefix==null?`${e.commandName}.md`:`${e.commandPrefix}${r}${e.commandName}.md`}transformSubAgentName(e,t){let{fileNameSource:n}=this.subAgentsConfig,r=t?.includePrefix??this.subAgentsConfig.includePrefix,i=t?.linkSymbol??this.subAgentsConfig.linkSymbol,a=t?.ext??this.subAgentsConfig.ext,o=a.startsWith(`.`)?a:`.${a}`;return n===`frontMatterName`&&this.warnDeprecatedSubAgentFileNameSource(),r&&e.agentPrefix!=null&&e.agentPrefix.length>0?`${e.agentPrefix}${i}${e.agentName}${o}`:`${e.agentName}${o}`}normalizeOutputFileStem(e){let t=Array.from(e.trim(),e=>(e.codePointAt(0)??0)<=31||`<>:"/\\|?*`.includes(e)?`-`:e).join(``);for(;t.endsWith(`.`)||t.endsWith(` `);)t=t.slice(0,-1);if(t.length===0)throw Error(`Cannot derive a valid output file name from "${e}"`);return t}warnDeprecatedSubAgentFileNameSource(){this.warnedDeprecatedSubAgentFileNameSource||(this.warnedDeprecatedSubAgentFileNameSource=!0,this.log.warn(O({code:`SUBAGENT_FRONTMATTER_NAME_SOURCE_DEPRECATED`,title:`Sub-agent fileNameSource="frontMatterName" now resolves from derived names`,reason:b(`The ${this.name} plugin no longer reads authored sub-agent front matter names.`,`tnmsc now derives sub-agent names from the sub-agent path.`),exactFix:b("Remove authored `name` fields from sub-agent sources.",'Keep using `fileNameSource="frontMatterName"` only as a temporary alias for the derived-path naming behavior.'),details:{plugin:this.name}})))}appendSubAgentDeclarations(e,t,n,r){let i=new Map;for(let a of r){let r=this.transformSubAgentName(a),o=u.join(t,this.subAgentsConfig.subDir,r),s=i.get(o);if(s!=null)throw Error(`Sub-agent output collision in ${this.name}: "${this.getSubAgentCanonicalName(a)}" and "${s}" both resolve to ${o}`);i.set(o,this.getSubAgentCanonicalName(a)),e.push({path:o,scope:n,source:{kind:`subAgent`,subAgent:a}})}}appendCommandDeclarations(e,t,n,r,i){for(let a of r){let r=this.transformCommandName(a,i);e.push({path:u.join(t,this.commandsConfig.subDir,r),scope:n,source:{kind:`command`,command:a}})}}appendSkillDeclarations(e,t,n,r){for(let i of r){let r=this.getSkillName(i),a=u.join(t,this.skillsConfig.subDir,r);if(e.push({path:u.join(a,`SKILL.md`),scope:n,source:{kind:`skillMain`,skill:i}}),i.childDocs!=null)for(let t of i.childDocs)e.push({path:u.join(a,t.dir.path.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillReference`,content:t.content}});if(i.resources!=null)for(let t of i.resources)e.push({path:u.join(a,t.relativePath),scope:n,source:{kind:`skillResource`,content:t.content,encoding:t.encoding}})}}appendRuleDeclarations(e,t,n,r){let i=u.join(t,this.rulesConfig.subDir??`rules`);for(let t of r)e.push({path:u.join(i,this.buildRuleFileName(t)),scope:n,source:{kind:`rule`,rule:t}})}buildSubAgentTomlContent(e,t){let{bodyFieldName:n}=this.subAgentsConfig;if(n==null||n.length===0)throw Error(`subagents.bodyFieldName is required when artifactFormat="toml" for ${this.name}`);return this.buildTomlContent({content:e.content,bodyFieldName:n,...t!=null&&{frontMatter:t},...this.subAgentsConfig.fieldNameMap!=null&&{fieldNameMap:this.subAgentsConfig.fieldNameMap},...this.subAgentsConfig.excludedFrontMatterFields!=null&&{excludedKeys:this.subAgentsConfig.excludedFrontMatterFields},...this.subAgentsConfig.extraFields!=null&&{extraFields:this.subAgentsConfig.extraFields},...this.subAgentsConfig.fieldOrder!=null&&{fieldOrder:this.subAgentsConfig.fieldOrder}})}getCommandSeriesOptions(e){let t=e.pluginOptions?.commandSeriesOptions,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.getCommandSeriesOptions(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)}getRegistryWriter(e){let t=e.name,n=this.registryWriterCache.get(t);if(n!=null)return n;let r=new e(this.log);return this.registryWriterCache.set(t,r),r}async registerInRegistry(e,t,n){return e.register(t,n.dryRun)}normalizeRuleScope(e){return e.scope??`project`}normalizeSourceScope(e){return e===`global`||e===`project`?e:`project`}remapDeclarationScope(e,t){return t?.[e]??e}resolveCommandSourceScope(e){if(e.globalOnly===!0)return`global`;let t=e.yamlFrontMatter?.scope;return this.remapDeclarationScope(this.normalizeSourceScope(t),this.commandsConfig.scopeRemap)}resolveSubAgentSourceScope(e){let t=e.yamlFrontMatter?.scope;return this.remapDeclarationScope(this.normalizeSourceScope(t),this.subAgentsConfig.scopeRemap)}resolveSkillSourceScope(e){let t=e.yamlFrontMatter?.scope;return this.remapDeclarationScope(this.normalizeSourceScope(t),this.skillsConfig.scopeRemap)}selectSingleScopeItems(e,t,n,r){if(e.length===0)return{items:[]};let[i]=Sb({requestedScopes:r,defaultScopes:t,supportedScopes:t,singleScope:!0,availableScopes:[...new Set(e.map(n))]});return i==null?{items:[]}:{selectedScope:i,items:e.filter(e=>n(e)===i)}}selectRuleScopes(e,t){let n=[...new Set(t.map(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))))];return Sb({requestedScopes:this.getTopicScopeOverride(e,`rules`),defaultScopes:this.rulesConfig.sourceScopes??[`project`,`global`],supportedScopes:this.rulesConfig.sourceScopes??[`project`,`global`],singleScope:!1,availableScopes:n}).filter(e=>n.includes(e))}selectPromptScopes(e,t=[`project`,`global`],n=t){return Sb({requestedScopes:this.getTopicScopeOverride(e,`prompt`),defaultScopes:n,supportedScopes:t,singleScope:!1})}getTopicScopeOverride(e,t){return e.pluginOptions?.outputScopes?.plugins?.[this.name]?.[t]}buildSkillFrontMatter(e,t){let n=e.yamlFrontMatter,r={name:this.getSkillName(e),description:n.description};return`displayName`in n&&n.displayName!=null&&(r.displayName=n.displayName),`keywords`in n&&n.keywords!=null&&n.keywords.length>0&&(r.keywords=n.keywords),`author`in n&&n.author!=null&&(r.author=n.author),`version`in n&&n.version!=null&&(r.version=n.version),(t?.includeTools??!0)&&`allowTools`in n&&n.allowTools!=null&&n.allowTools.length>0&&(r.allowTools=(t?.toolFormat??`array`)===`string`?n.allowTools.join(`,`):n.allowTools),t?.additionalFields!=null&&Object.assign(r,t.additionalFields),r}buildRuleContent(e,t){let n=this.rulesConfig.transformFrontMatter?this.rulesConfig.transformFrontMatter(e):{globs:e.globs.join(`, `)},r=n==null||Object.keys(n).length===0?void 0:n;return this.buildMarkdownContent(e.content,r,t)}buildRuleFileName(e){let t=`${`${this.rulesConfig.prefix??`rule`}${this.rulesConfig.linkSymbol??`-`}`}${e.prefix}${this.rulesConfig.linkSymbol??`-`}${e.ruleName}${this.rulesConfig.ext??`.md`}`;return this.log.trace(`buildRuleFileName`,{plugin:this.name,rulePrefix:e.prefix,ruleName:e.ruleName,prefix:this.rulesConfig.prefix??`rule`,linkSymbol:this.rulesConfig.linkSymbol??`-`,ext:this.rulesConfig.ext??`.md`,result:t}),t}async declareOutputFiles(e){return this.buildDefaultOutputDeclarations(e)}async declareCleanupPaths(e){let t=this.buildCleanupTargetsFromScopeConfig(this.cleanupConfig.delete,`delete`,e),n=this.buildCleanupTargetsFromScopeConfig(this.cleanupConfig.protect,`protect`,e),{excludeScanGlobs:r}=this.cleanupConfig;return t.length===0&&n.length===0&&(r==null||r.length===0)?{}:{...t.length>0&&{delete:t},...n.length>0&&{protect:n},...r!=null&&r.length>0&&{excludeScanGlobs:r}}}async declareWslMirrorFiles(e){return this.wslMirrorPaths.map(e=>({sourcePath:e}))}async convertContent(e,t){let n=e.source;switch(n.kind){case`projectRootMemory`:case`projectChildMemory`:case`globalMemory`:case`skillReference`:case`ignoreFile`:return n.content;case`command`:return this.buildCommandContent(n.command,t);case`subAgent`:return this.buildSubAgentContent(n.subAgent,t);case`skillMain`:return this.buildSkillMainContent(n.skill,t);case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;case`rule`:return this.buildRuleContent(n.rule,t);default:throw Error(`Unsupported declaration source for plugin ${this.name}`)}}async buildDefaultOutputDeclarations(e){let t=[],{globalMemory:n,commands:r,subAgents:i,skills:a,rules:o,aiAgentIgnoreConfigFiles:s}=e.collectedOutputContext,c=this.getTransformOptionsFromContext(e),l=this.getIgnoreOutputPath(),d=this.indexignore==null?void 0:s?.find(e=>e.fileName===this.indexignore),f=this.commandOutputEnabled&&r!=null?this.selectSingleScopeItems(r,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)):{items:[]},p=this.subAgentOutputEnabled&&i!=null?this.selectSingleScopeItems(i,this.subAgentsConfig.sourceScopes,e=>this.resolveSubAgentSourceScope(e),this.getTopicScopeOverride(e,`subagents`)):{items:[]},m=this.skillOutputEnabled&&a!=null?this.selectSingleScopeItems(a,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)):{items:[]},h=o??[],g=this.ruleOutputEnabled&&h.length>0?new Set(this.selectRuleScopes(e,h)):new Set,_=new Set(this.selectPromptScopes(e,this.outputCapabilities.prompt?.scopes??[`project`,`global`])),v={project:[],global:[]};for(let e of h)v[this.normalizeSourceScope(this.normalizeRuleScope(e))].push(e);for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectRootDir(e,n),i=this.resolveProjectConfigDir(e,n);if(r==null||i==null)continue;if(this.outputFileName.length>0&&_.has(`project`)&&this.isProjectPromptOutputTarget(n)&&(n.rootMemoryPrompt!=null&&t.push({path:u.join(r,this.outputFileName),scope:`project`,source:{kind:`projectRootMemory`,content:n.rootMemoryPrompt.content}}),n.childMemoryPrompts!=null))for(let e of n.childMemoryPrompts)t.push({path:this.resolveFullPath(e.dir),scope:`project`,source:{kind:`projectChildMemory`,content:e.content}});let{projectConfig:a}=n;if(f.selectedScope===`project`&&f.items.length>0){let e=$(f.items,a,`commands`);this.appendCommandDeclarations(t,i,`project`,e,c)}if(p.selectedScope===`project`&&p.items.length>0){let e=$(p.items,a,`subAgents`);this.appendSubAgentDeclarations(t,i,`project`,e)}if(m.selectedScope===`project`&&m.items.length>0){let e=$(m.items,a,`skills`);this.appendSkillDeclarations(t,i,`project`,e)}if(g.has(`project`)){let e=Gy($(v.project,a,`rules`),a);this.appendRuleDeclarations(t,i,`project`,e)}l!=null&&d!=null&&n.isWorkspaceRootProject!==!0&&n.isPromptSourceProject!==!0&&n.dirFromWorkspacePath!=null&&t.push({path:u.join(n.dirFromWorkspacePath.basePath,n.dirFromWorkspacePath.path,l),scope:`project`,source:{kind:`ignoreFile`,content:d.content}})}let y=this.resolvePromptSourceProjectConfig(e);if(f.selectedScope===`global`&&f.items.length>0){let e=$(f.items,y,`commands`),n=this.getGlobalConfigDir();this.appendCommandDeclarations(t,n,`global`,e,c)}if(p.selectedScope===`global`&&p.items.length>0){let e=$(p.items,y,`subAgents`),n=this.getGlobalConfigDir();this.appendSubAgentDeclarations(t,n,`global`,e)}if(m.selectedScope===`global`&&m.items.length>0){let e=$(m.items,y,`skills`),n=this.getGlobalConfigDir();this.appendSkillDeclarations(t,n,`global`,e)}for(let e of[`global`]){if(!g.has(e))continue;let n=this.getGlobalConfigDir(),r=Gy($(v[e],y,`rules`),y);this.appendRuleDeclarations(t,n,e,r)}return n!=null&&this.outputFileName.length>0&&_.has(`global`)&&t.push({path:u.join(this.getGlobalConfigDir(),this.outputFileName),scope:`global`,source:{kind:`globalMemory`,content:n.content}}),t}async buildCommandContent(e,t){let n=e.content,r=e.yamlFrontMatter,i=!1;if(e.rawMdxContent!=null&&this.toolPreset!=null){this.log.debug(`recompiling command with tool preset`,{file:e.dir.getAbsolutePath(),toolPreset:this.toolPreset,hasRawContent:!0});let t=new Zy({toolPreset:this.toolPreset}).collect(),a=await pb({filePath:e.dir.getAbsolutePath(),globalScope:t,rawMdx:e.rawMdxContent});n=a.content,r=a.metadata,i=!0}let a=this.commandsConfig.transformFrontMatter;if(a==null)throw Error(`commands.transformFrontMatter is required for command output plugin: ${this.name}`);let o=a(e,{isRecompiled:i,...r!=null&&{sourceFrontMatter:r}});return this.buildMarkdownContent(n,o,t)}buildSubAgentContent(e,t){let n=this.subAgentsConfig.transformFrontMatter,r=n?.(e,{...e.yamlFrontMatter!=null&&{sourceFrontMatter:e.yamlFrontMatter}});if(this.subAgentsConfig.artifactFormat===`toml`){let t=r??e.yamlFrontMatter;return this.buildSubAgentTomlContent(e,t)}return r==null?this.buildMarkdownContentWithRaw(e.content,e.yamlFrontMatter,e.rawFrontMatter,t):this.buildMarkdownContent(e.content,r,t)}buildSkillMainContent(e,t){return this.buildMarkdownContentWithRaw(e.content,e.yamlFrontMatter,e.rawFrontMatter,t)}};const ux={USER_HOME:`~`,WORKSPACE:`$WORKSPACE`},dx={},fx={AgentsOutput:`AgentsOutputPlugin`,GeminiCLIOutput:`GeminiCLIOutputPlugin`,CursorOutput:`CursorOutputPlugin`,WindsurfOutput:`WindsurfOutputPlugin`,ClaudeCodeCLIOutput:`ClaudeCodeCLIOutputPlugin`,KiroIDEOutput:`KiroCLIOutputPlugin`,OpencodeCLIOutput:`OpencodeCLIOutputPlugin`,OpenAICodexCLIOutput:`CodexCLIOutputPlugin`,DroidCLIOutput:`DroidCLIOutputPlugin`,WarpIDEOutput:`WarpIDEOutputPlugin`,TraeIDEOutput:`TraeIDEOutputPlugin`,TraeCNIDEOutput:`TraeCNIDEOutputPlugin`,QoderIDEOutput:`QoderIDEPluginOutputPlugin`,JetBrainsCodeStyleOutput:`JetBrainsIDECodeStyleConfigOutputPlugin`,JetBrainsAICodexOutput:`JetBrainsAIAssistantCodexOutputPlugin`,AgentSkillsCompactOutput:`GenericSkillsOutputPlugin`,GitExcludeOutput:`GitExcludeOutputPlugin`,ReadmeOutput:`ReadmeMdConfigFileOutputPlugin`,VSCodeOutput:`VisualStudioCodeIDEConfigOutputPlugin`,ZedOutput:`ZedIDEConfigOutputPlugin`,EditorConfigOutput:`EditorConfigOutputPlugin`,AntigravityOutput:`AntigravityOutputPlugin`},px={SKILL:`SKILL.md`,CURSOR_GLOBAL_RULE:`global.mdc`,CURSOR_PROJECT_RULE:`always.md`,MCP_CONFIG:`mcp.json`,CLAUDE_MEMORY:`CLAUDE.md`,WINDSURF_GLOBAL_RULE:`global_rules.md`},mx={RULES:`rules`,COMMANDS:`commands`,SKILLS:`skills`,AGENTS:`agents`,CURSOR_SKILLS:`skills-cursor`},hx={MD:`.md`,MDC:`.mdc`,MDX:`.mdx`,JSON:`.json`},gx=[{PRIMARY:`.src.mdx`}.PRIMARY],_x={zh:gx,en:hx.MDX};function vx(e){return gx.some(t=>e.endsWith(t))}const yx={CURSOR:`.cursor`,CLAUDE:`.claude`,WINDSURF:`.codeium/windsurf`,WINDSURF_RULES:`.windsurf`},bx={CURSOR:`.cursorignore`,WINDSURF:`.codeiumignore`},xx={CURSOR:new Set([`create-rule`,`create-skill`,`create-subagent`,`migrate-to-skills`,`update-cursor-settings`])};var Sx=class extends Error{kind;nameOfPrompt;sourcePath;expectedDistPath;constructor(e){let{kind:t,name:n,sourcePath:r,expectedDistPath:i}=e;super([`Missing compiled dist prompt for ${t} "${n}".`,...r==null?[]:[`source: ${r}`],`expected dist: ${i}`].join(` `)),this.name=`MissingCompiledPromptError`,this.kind=t,this.nameOfPrompt=n,r!=null&&(this.sourcePath=r),this.expectedDistPath=i}},Cx=class extends Error{filePath;lineNumber;constructor(e,t,n){super(`Compiled prompt still contains residual module syntax at ${e}:${t}: ${n.trim()}`),this.name=`ResidualModuleSyntaxError`,this.filePath=e,this.lineNumber=t}};const wx=/^\s*(```|~~~)/u,Tx=[/^\s*export\s+default\b/u,/^\s*export\s+const\b/u,/^\s*import\b/u];function Ex(e,t){let n,r=e.split(/\r?\n/u);for(let[e,i]of r.entries()){let r=wx.exec(i);if(r?.[1]!=null){let e=r[1];n==null?n=e:n===e&&(n=void 0);continue}if(n==null&&Tx.some(e=>e.test(i)))throw new Cx(t,e+1,i)}}function Dx(e,t,n={}){let{preferredSourcePath:r,distRootDir:i,srcRootDir:a}=n;if(t==null||t.length===0||r!=null&&r.length>0)return r;if(i==null||a==null)return;let o=e.relative(i,t);if(!(o.startsWith(`..`)||e.isAbsolute(o)))return e.join(a,o.replace(/\.mdx$/u,`.src.mdx`))}function Ox(e){if(e instanceof Xg&&e.filePath!=null)return e.filePath;if(!(e instanceof Error)||!(`filePath`in e))return;let{filePath:t}=e;if(typeof t==`string`&&t.length>0)return t}function kx(e,t){let n=Ox(e)??t.distPath,r=[t.operation??`Prompt compilation failed.`,`prompt kind: ${t.promptKind}`,`logical name: ${t.logicalName}`];return t.entryDistPath!=null&&t.entryDistPath.length>0&&t.entryDistPath!==n&&r.push(`entry dist file: ${t.entryDistPath}`),n!=null&&n.length>0&&r.push(`dist file: ${n}`),r.push(`src file: ${t.srcPath??`<unresolved>`}`),r.push(`diagnostic:`),r.push(e instanceof Error?Yg(e):String(e)),r.join(`
|
|
227
|
-
`)}function Ax(e){return e instanceof Sx||e instanceof Cx}var jx=class{constructor(e,t,n,r){this.fs=e,this.path=t,this.logger=n,this.globalScope=r}async readDirectoryStructure(e,t,n){let r=[],i=[];if(!this.exists(e))return{prompts:r,errors:i};try{let a=this.fs.readdirSync(e,{withFileTypes:!0});for(let o of a){if(!o.isDirectory())continue;let{name:a}=o,s=this.path.join(e,a),c=this.path.join(t,a);try{let e=await this.readEntry(a,s,c,n,!0);e&&r.push(e)}catch(e){if(i.push({path:s,error:e,phase:`read`}),this.logger.error(D({code:`LOCALIZED_PROMPT_ENTRY_READ_FAILED`,title:`Failed to read localized prompt entry`,operation:`read`,targetKind:`${String(n.kind)} prompt entry`,path:s,error:e,details:{entryName:a,promptKind:String(n.kind)}})),Ax(e))throw e}}}catch(t){if(i.push({path:e,error:t,phase:`scan`}),this.logger.error(D({code:`LOCALIZED_PROMPT_DIRECTORY_SCAN_FAILED`,title:`Failed to scan localized prompt source directory`,operation:`scan`,targetKind:`${String(n.kind)} prompt source directory`,path:e,error:t,details:{promptKind:String(n.kind)}})),Ax(t))throw t}return{prompts:r,errors:i}}async readFlatFiles(e,t,n){let r=[],i=[],a=this.exists(e),o=this.exists(t);if(this.logger.debug(`readFlatFiles: srcDir=${e}, exists=${a}`),this.logger.debug(`readFlatFiles: distDir=${t}, exists=${o}`),!a&&!o)return{prompts:r,errors:i};let s=this.normalizeExtensions(n.localeExtensions.zh),c=new Set,l=async(a,o)=>{if(!c.has(a)){c.add(a);try{let i=await this.readFlatEntry(a,e,t,a,n);i&&r.push(i)}catch(e){if(i.push({path:o,error:e,phase:`read`}),this.logger.error(D({code:`LOCALIZED_PROMPT_FILE_READ_FAILED`,title:`Failed to read localized prompt file`,operation:`read`,targetKind:`${String(n.kind)} prompt file`,path:o,error:e,details:{promptKind:String(n.kind),logicalName:a}})),Ax(e))throw e}}},u=async(e,t=``)=>{if(this.exists(e))try{let n=this.fs.readdirSync(e,{withFileTypes:!0});for(let r of n){let n=t?this.path.join(t,r.name):r.name;if(r.isDirectory()){await u(this.path.join(e,r.name),n);continue}let i=this.findMatchingExtension(r.name,s);if(!r.isFile()||i==null)continue;let a=r.name.slice(0,-i.length);await l(t?this.path.join(t,a):a,this.path.join(e,r.name))}}catch(t){if(i.push({path:e,error:t,phase:`scan`}),this.logger.error(D({code:`LOCALIZED_SOURCE_DIRECTORY_SCAN_FAILED`,title:`Failed to scan localized source directory`,operation:`scan`,targetKind:`${String(n.kind)} source directory`,path:e,error:t,details:{promptKind:String(n.kind)}})),Ax(t))throw t}},d=async(e,t=``)=>{if(this.exists(e))try{let n=this.fs.readdirSync(e,{withFileTypes:!0});for(let r of n){let n=t?this.path.join(t,r.name):r.name;if(r.isDirectory()){await d(this.path.join(e,r.name),n);continue}if(!r.isFile()||!r.name.endsWith(`.mdx`))continue;let i=r.name.slice(0,-4);await l(t?this.path.join(t,i):i,this.path.join(e,r.name))}}catch(t){if(i.push({path:e,error:t,phase:`scan`}),this.logger.error(D({code:`LOCALIZED_DIST_DIRECTORY_SCAN_FAILED`,title:`Failed to scan localized dist directory`,operation:`scan`,targetKind:`${String(n.kind)} dist directory`,path:e,error:t,details:{promptKind:String(n.kind)}})),Ax(t))throw t}};return a&&await u(e),o&&await d(t),{prompts:r,errors:i}}async readSingleFile(e,t,n){let r=this.path.basename(e);return this.readFlatEntry(r,this.path.dirname(e),this.path.dirname(t),e,n,!0)}async readEntry(e,t,n,r,i=!0){let{localeExtensions:a,entryFileName:o,createPrompt:s,kind:c}=r,l=r.hydrateSourceContents??!0,u=o??e,d=this.normalizeExtensions(a.zh),f=this.normalizeExtensions(a.en),p=this.resolveLocalizedPath(t,u,d),m=this.resolveLocalizedPath(t,u,f),h=this.path.join(n,`${u}.mdx`),g=this.exists(p),_=this.exists(m),v=g?p:_?m:void 0,y={promptKind:String(c),logicalName:e,entryDistPath:h,...v!=null&&{srcPath:v}},x=await this.readDistContent(h,s,e,y),S=g&&l?await this.readLocaleContent(p,`zh`,s,e,String(c)):null,w=_&&l?await this.readLocaleContent(m,`en`,s,e,String(c)):null,T=x!=null,E=g?p:_?m:void 0;if(!T&&!g&&!_)return this.logger.warn(C({code:`LOCALIZED_PROMPT_ARTIFACTS_MISSING`,title:`Missing source and dist prompt artifacts for ${e}`,rootCause:b(`tnmsc could not find either the source prompt or the compiled dist prompt for "${e}".`),exactFix:b(`Create the source prompt and rebuild the compiled dist prompt before retrying tnmsc.`),details:{promptKind:String(c),name:e,srcZhPath:p,srcEnPath:m,distPath:h}})),null;if(!T)throw new Sx({kind:String(c),name:e,...E!=null&&{sourcePath:E},expectedDistPath:h});let D=l&&S!=null?{zh:S,...w!=null&&{en:w},default:S,defaultLocale:`zh`}:void 0,O=i?this.scanChildren(n,u,[`.mdx`]):void 0;return{name:e,type:c,...D!=null&&{src:D},...T&&{dist:x},metadata:{hasDist:T,hasMultipleLocales:_,isDirectoryStructure:i,...O&&O.length>0&&{children:O}},paths:{...g&&{zh:p},..._&&{en:m},...T&&{dist:h}}}}async readFlatEntry(e,t,n,r,i,a=!1){let{localeExtensions:o,createPrompt:s,kind:c}=i,l=i.hydrateSourceContents??!0,u=this.normalizeExtensions(o.zh),d=this.normalizeExtensions(o.en),f=this.resolveLocalizedPath(``,r,u),p=this.resolveLocalizedPath(``,r,d),m=this.path.join(n,`${e}.mdx`),h=a?f:this.path.join(t,f),g=a?p:this.path.join(t,p),_=this.exists(h),v=this.exists(g),y=_?h:v?g:void 0,x={promptKind:String(c),logicalName:e,entryDistPath:m,...y!=null&&{srcPath:y}},S=await this.readDistContent(m,s,e,x),w=_&&l?await this.readLocaleContent(h,`zh`,s,e,String(c)):null,T=v&&l?await this.readLocaleContent(g,`en`,s,e,String(c)):null,E=S!=null,D=_?h:v?g:void 0;if(!E&&!_&&!v)return this.logger.warn(C({code:`LOCALIZED_PROMPT_ARTIFACTS_MISSING`,title:`Missing source and dist prompt artifacts for ${e}`,rootCause:b(`tnmsc could not find either the source prompt or the compiled dist prompt for "${e}".`),exactFix:b(`Create the source prompt and rebuild the compiled dist prompt before retrying tnmsc.`),details:{promptKind:String(c),name:e,srcZhPath:h,srcEnPath:g,distPath:m}})),null;if(!E)throw new Sx({kind:String(c),name:e,...D!=null&&{sourcePath:D},expectedDistPath:m});let O=l&&w!=null?{zh:w,...T!=null&&{en:T},default:w,defaultLocale:`zh`}:void 0;return{name:e,type:c,...O!=null&&{src:O},...E&&{dist:S},metadata:{hasDist:E,hasMultipleLocales:v,isDirectoryStructure:!1},paths:{..._&&{zh:h},...v&&{en:g},...E&&{dist:m}}}}async readLocaleContent(e,t,n,r,i){if(!this.exists(e))return null;try{let i=await fb(e,{mode:`source`,globalScope:this.globalScope});Ex(i.content,e);let a=await n(i.content,t,r,i.metadata),o={content:i.content,lastModified:i.lastModified,filePath:e};return i.rawMdx.length>0&&Object.assign(o,{rawMdx:i.rawMdx}),i.parsed.yamlFrontMatter!=null&&Object.assign(o,{frontMatter:i.parsed.yamlFrontMatter}),a!=null&&Object.assign(o,{prompt:a}),o}catch(n){throw this.logger.error(te({code:`LOCALIZED_SOURCE_PROMPT_READ_FAILED`,title:`Failed to read localized source prompt`,diagnosticText:kx(n,{operation:`Failed to read localized source prompt.`,promptKind:i,logicalName:r,distPath:e}),details:{promptKind:i,locale:t,filePath:e}})),n}}async readDistContent(e,t,n,r){if(!this.exists(e))return null;try{let r=await fb(e,{mode:`dist`,globalScope:this.globalScope});Ex(r.content,e);let i=await t(r.content,`zh`,n,r.metadata),a={content:r.content,lastModified:r.lastModified,prompt:i,filePath:e,rawMdx:r.rawMdx};return r.parsed.yamlFrontMatter!=null&&Object.assign(a,{frontMatter:r.parsed.yamlFrontMatter}),a}catch(t){throw this.logger.error(this.buildDistReadDiagnostic(t,e,r)),t}}buildDistReadDiagnostic(e,t,n){let r=Dx(this.path,t,{preferredSourcePath:t===n.entryDistPath?n.srcPath:void 0,distRootDir:this.path.dirname(n.entryDistPath),srcRootDir:n.srcPath==null?void 0:this.path.dirname(n.srcPath)});return te({code:`LOCALIZED_DIST_PROMPT_READ_FAILED`,title:`Failed to read localized dist prompt`,diagnosticText:kx(e,{operation:`Failed to read dist content.`,promptKind:n.promptKind,logicalName:n.logicalName,entryDistPath:n.entryDistPath,distPath:t,srcPath:r}),details:{promptKind:n.promptKind,logicalName:n.logicalName,filePath:t,srcPath:r}})}scanChildren(e,t,n){let r=[];if(!this.exists(e))return r;let i=new Set(n.map(e=>`${t}${e}`));try{let t=(e,a)=>{let o=this.fs.readdirSync(e,{withFileTypes:!0});for(let s of o){let o=this.path.join(e,s.name),c=a?this.path.join(a,s.name):s.name;if(s.isDirectory())t(o,c);else{let e=this.findMatchingExtension(s.name,n);if(e==null||i.has(s.name))continue;let t=s.name.slice(0,-e.length),a=this.path.dirname(c),o=a===`.`?t:this.path.join(a,t);r.push(o)}}};t(e,``)}catch(t){this.logger.warn(D({code:`LOCALIZED_PROMPT_CHILD_SCAN_FAILED`,title:`Failed to scan localized prompt child documents`,operation:`scan`,targetKind:`localized prompt child directory`,path:e,error:t}))}return r}exists(e){try{return this.fs.existsSync(e)}catch{return!1}}normalizeExtensions(e){return typeof e==`string`?[e]:e}findMatchingExtension(e,t){return t.find(t=>e.endsWith(t))}resolveLocalizedPath(e,t,n){let r=e===``?`${t}${n[0]}`:this.path.join(e,`${t}${n[0]}`);for(let r of n){let n=e===``?`${t}${r}`:this.path.join(e,`${t}${r}`);if(this.exists(n))return n}return r}};function Mx(e,t,n,r){return new jx(e,t,n,r)}function Nx(e,t){let n=new Map;for(let r of e)if(r.mcpConfig!=null)for(let[e,i]of Object.entries(r.mcpConfig.mcpServers))n.set(e,i),t?.debug(`mcp server collected`,{skill:_b(r),mcpName:e});return n}function Px(e,t){let n={};for(let[r,i]of e)n[r]=t(i);return n}function Fx(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,r=n.url??n.serverUrl;if(r==null)return t;t.url=r;let{headers:i}=n;return i!=null&&(t.headers=i),t}function Ix(e){let t={};if(e.command!=null){t.type=`local`;let n=[e.command];e.args!=null&&n.push(...e.args),t.command=n,e.env!=null&&(t.environment=e.env)}else{t.type=`remote`;let n=e;n.url==null?n.serverUrl!=null&&(t.url=n.serverUrl):t.url=n.url}return t.enabled=e.disabled!==!0,t}function Lx(){ve()}function Rx(e,t){return be(e,t)}function zx(){return ye()}function Bx(e){_e(e)}var Vx=class{name;inner;constructor(e){this.inner=e,this.name=`json:${e.name}`}async execute(e){Lx();let t=await this.inner.execute(e),n=Hx(t,zx());return c.stdout.write(`${JSON.stringify(n)}\n`),t}};function Hx(e,t=zx()){let{warnings:n,errors:r}=re(t);return{success:e.success,filesAffected:e.filesAffected,dirsAffected:e.dirsAffected,...e.message!=null&&{message:e.message},pluginResults:[],warnings:n,errors:r}}let Ux=function(e){return e[e.Flags=0]=`Flags`,e[e.Unknown=1]=`Unknown`,e[e.Subcommand=2]=`Subcommand`,e}({});var Wx=class{factories=[];register(e){this.factories.push(e),this.factories.sort((e,t)=>e.priority-t.priority)}registerWithPriority(e,t){let n={priority:t,canHandle:t=>e.canHandle(t),createCommand:t=>e.createCommand(t)};this.factories.push(n),this.factories.sort((e,t)=>e.priority-t.priority)}resolve(e){for(let t of this.factories)if(t.priority<=Ux.Unknown&&t.canHandle(e))return t.createCommand(e);for(let t of this.factories)if(t.priority===Ux.Subcommand&&t.canHandle(e))return t.createCommand(e);for(let t of this.factories)if(t.canHandle(e))return t.createCommand(e);throw Error(`No command factory found for the given arguments`)}};function Gx(e){let{root:t}=u.parse(e);return e===t?e:e.endsWith(u.sep)?e.slice(0,-1):e}function Kx(e,t){let n=Gx(e),r=Gx(t);return n===r?!0:n.startsWith(`${r}${u.sep}`)}function qx(e,t){let n=new Map,r=new Map;for(let t of e){let e=hg(t);n.set(e,e)}for(let e of t){let t=hg(e);r.set(t,t)}let i=new Map,a=[...r.entries()].sort((e,t)=>e[0].length-t[0].length);for(let[e,t]of a){let n=!1;for(let t of i.keys())if(Kx(e,t)){n=!0;break}n||i.set(e,t)}let o=[];for(let[e,t]of n){let n=!1;for(let t of i.keys())if(Kx(e,t)){n=!0;break}n||o.push(t)}return o.sort((e,t)=>e.localeCompare(t)),{files:o,dirs:[...i.values()].sort((e,t)=>e.localeCompare(t))}}function Jx(e){let t=c.env.XDG_DATA_HOME;return typeof t==`string`&&t.trim().length>0?ag(t):d.join(e,`.local`,`share`)}function Yx(){let e=tg(),t=e.isWsl?`win32`:e.platform,n=e.effectiveHomeDir;if(t===`win32`)return ag(c.env.LOCALAPPDATA??d.join(n,`AppData`,`Local`));if(t===`darwin`)return d.join(n,`Library`,`Application Support`);if(t===`linux`)return Jx(n);throw Error(`Unsupported platform: ${c.platform}`)}async function Xx(e){try{let t=await i.promises.lstat(e);return t.isSymbolicLink()?(await(c.platform===`win32`?i.promises.rm(e,{recursive:!0,force:!0}):i.promises.unlink(e)),!0):t.isDirectory()?(await i.promises.rm(e,{recursive:!0,force:!0}),!0):(await i.promises.unlink(e),!0)}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Zx(e,t,n){if(e.length===0)return[];let r=[],i=0,a=async()=>{for(;;){let t=i;if(t>=e.length)return;i+=1,r[t]=await n(e[t])}},o=Math.min(t,e.length),s=[];for(let e=0;e<o;e+=1)s.push(a());return await Promise.all(s),r}async function Qx(e,t){let n=await Zx(t?.sortByDepthDescending===!0?[...e].sort((e,t)=>t.length-e.length||t.localeCompare(e)):[...e],32,async e=>{try{return{path:e,deleted:await Xx(e)}}catch(t){return{path:e,error:t}}}),r=[],i=[];for(let e of n){if(`error`in e){i.push({path:e.path,error:e.error});continue}e.deleted&&r.push(e.path)}return{deleted:r.length,deletedPaths:r,errors:i}}async function $x(e){return Qx(e)}async function eS(e){return Qx(e,{sortByDepthDescending:!0})}async function tS(e){let[t,n]=await Promise.all([$x(e.files??[]),eS(e.dirs??[])]);return{deletedFiles:t.deletedPaths,deletedDirs:n.deletedPaths,fileErrors:t.errors,dirErrors:n.errors}}function nS(){return c.env.NODE_ENV===`test`||c.env.VITEST!=null||c.env.VITEST_WORKER_ID!=null}function rS(){if(nS())return;let e={"win32-x64":`win32-x64-msvc`,"linux-x64":`linux-x64-gnu`,"linux-arm64":`linux-arm64-gnu`,"darwin-arm64":`darwin-arm64`,"darwin-x64":`darwin-x64`}[`${c.platform}-${c.arch}`];if(e!=null)try{let t=r(import.meta.url),n=`@truenine/memory-sync-cli-${e}`,i=`napi-memory-sync-cli.${e}.node`,a=[n,`${n}/${i}`,`./${i}`];for(let e of a)try{let n=t(e),r=[n,n?.default,n?.config,n?.default?.config];for(let e of r)if(typeof e==`object`&&e)return e}catch{}}catch{}}const iS=rS();function aS(e){return{deletedFiles:e.deletedFiles??e.deleted_files??[],deletedDirs:e.deletedDirs??e.deleted_dirs??[],fileErrors:e.fileErrors??e.file_errors??[],dirErrors:e.dirErrors??e.dir_errors??[]}}function oS(){return Yx()}async function sS(e){return iS?.deleteTargets==null?tS(e):aS(await Promise.resolve(iS.deleteTargets({files:e.files??[],dirs:e.dirs??[]})))}var cS=class extends Error{conflicts;constructor(e){super(hS(e)),this.name=`CleanupProtectionConflictError`,this.conflicts=e}};const lS=[`**/node_modules/**`,`**/.git/**`,`**/.turbo/**`,`**/.pnpm-store/**`,`**/.yarn/**`,`**/.next/**`];function uS(e){return hg(e).replaceAll(`\\`,`/`)}function dS(e,t){let n=uS(e);return Um.default.sync(n,{onlyFiles:!1,dot:!0,absolute:!0,followSymbolicLinks:!1,ignore:[...t]})}function fS(e,t){if(t.excludeBasenames==null||t.excludeBasenames.length===0)return!1;let n=u.basename(e);return t.excludeBasenames.includes(n)}async function pS(e,t){return e.declareCleanupPaths==null?{}:e.declareCleanupPaths({...t,dryRun:!0})}async function mS(e,t,n){let r=n?.get(e),[i,a]=await Promise.all([r==null?e.declareOutputFiles({...t,dryRun:!0}):Promise.resolve(r),pS(e,t)]);return{plugin:e,outputs:i,cleanup:a}}function hS(e){let t=e.map(e=>e.outputPath).join(`, `);return`Cleanup protection conflict: ${e.length} output path(s) are also protected: ${t}`}function gS(e,t){let n=[];for(let[r,i]of e.entries()){let e=new Set(yg(r));for(let a of t.compiledRules)if(a.comparisonKeys.some(t=>e.has(t)))for(let e of i)n.push({outputPath:r,outputPlugin:e,protectedPath:a.path,protectionMode:a.protectionMode,protectedBy:a.source,reason:a.reason})}return n.sort((e,t)=>{let n=e.outputPath.localeCompare(t.outputPath);return n===0?e.protectedPath.localeCompare(t.protectedPath):n})}function _S(e,t){let n=t[0];e.error(C({code:`CLEANUP_PROTECTION_CONFLICT_DETECTED`,title:`Cleanup output paths conflict with protected inputs`,rootCause:b(`tnmsc found ${t.length} output path(s) that also match protected cleanup rules.`,n==null?`No conflict details were captured.`:`Example conflict: "${n.outputPath}" is protected by "${n.protectedPath}".`),exactFix:b(`Separate generated output paths from protected source or reserved workspace paths before running cleanup again.`),possibleFixes:[b(`Update cleanup protect declarations so they do not overlap generated outputs.`),b(`Move the conflicting output target to a generated-only directory.`)],details:{count:t.length,conflicts:t.map(e=>({outputPath:e.outputPath,outputPlugin:e.outputPlugin,protectedPath:e.protectedPath,protectionMode:e.protectionMode,protectedBy:e.protectedBy,reason:e.reason}))}}))}async function vS(e,t,n){let r=new Set,a=new Set,o=new Map,s=new Set(lS),c=new Map,l=await Promise.all(e.map(async e=>mS(e,t,n))),u=(e,t)=>{t===`directory`?a.add(hg(e)):r.add(hg(e))},d=(e,t,n,r,i=`path`)=>{let a=hg(e);o.set(`${i}:${t}:${a}`,{path:a,protectionMode:t,reason:n,source:r,matcher:i})},f=e=>e.protectionMode==null?e.kind===`file`?`direct`:`recursive`:e.protectionMode;for(let e of Mg(t.collectedOutputContext))d(e.path,e.protectionMode,e.reason,e.source);if(t.collectedOutputContext.aindexDir!=null&&t.pluginOptions!=null)for(let e of jg(t.pluginOptions,t.collectedOutputContext.aindexDir,{workspaceDir:t.collectedOutputContext.workspace.directory.path}))d(e.path,e.protectionMode,e.reason,e.source,e.matcher);for(let e of t.pluginOptions?.cleanupProtection?.rules??[])d(e.path,e.protectionMode,e.reason??`configured cleanup protection rule`,`configured-cleanup-protection`,e.matcher??`path`);for(let e of l){for(let t of e.outputs){let n=hg(t.path);u(n,`file`);let r=c.get(n);r==null?c.set(n,[e.plugin.name]):r.includes(e.plugin.name)||r.push(e.plugin.name)}for(let t of e.cleanup.excludeScanGlobs??[])s.add(uS(t))}let p=[...s],m=e=>{for(let t of dS(e.path,p))if(!fS(t,e))try{i.lstatSync(t).isDirectory()?u(t,`directory`):u(t,`file`)}catch{}},h=(e,t)=>{let n=f(e),r=e.label==null?`plugin cleanup protect declaration`:`plugin cleanup protect declaration (${e.label})`;for(let i of dS(e.path,p))d(i,n,r,`plugin-cleanup-protect:${t}`)};for(let{plugin:e,cleanup:t}of l){for(let n of t.protect??[]){if(n.kind===`glob`){h(n,e.name);continue}d(n.path,f(n),n.label==null?`plugin cleanup protect declaration`:`plugin cleanup protect declaration (${n.label})`,`plugin-cleanup-protect:${e.name}`)}for(let e of t.delete??[]){if(e.kind===`glob`){m(e);continue}e.kind===`directory`?u(e.path,`directory`):u(e.path,`file`)}}let g=Pg({workspaceDir:t.collectedOutputContext.workspace.directory.path,projectRoots:Fg(t.collectedOutputContext),rules:[...o.values()],...t.collectedOutputContext.aindexDir==null?{}:{aindexDir:t.collectedOutputContext.aindexDir}}),_=gS(c,g);if(_.length>0)throw new cS(_);let v=Rg([...r],g),y=Rg([...a],g),b=qx(v.safePaths,y.safePaths);return{filesToDelete:b.files,dirsToDelete:b.dirs,violations:[...v.violations,...y.violations].sort((e,t)=>e.targetPath.localeCompare(t.targetPath)),conflicts:[],excludedScanGlobs:[...s].sort((e,t)=>e.localeCompare(t))}}function yS(e,t,n){return t.map(t=>{let r=t.error instanceof Error?t.error.message:String(t.error);return e.warn(D({code:n===`file`?`CLEANUP_FILE_DELETE_FAILED`:`CLEANUP_DIRECTORY_DELETE_FAILED`,title:n===`file`?`Cleanup could not delete a file`:`Cleanup could not delete a directory`,operation:`delete`,targetKind:n,path:t.path,error:r,details:{phase:`cleanup`}})),{path:t.path,type:n,error:t.error}})}async function bS(e,t){t.debug(`cleanup delete execution started`,{filesToDelete:e.filesToDelete.length,dirsToDelete:e.dirsToDelete.length});let n=await sS({files:e.filesToDelete,dirs:e.dirsToDelete}),r=yS(t,n.fileErrors,`file`),i=yS(t,n.dirErrors,`directory`),a=[...r,...i];return t.debug(`cleanup delete execution complete`,{deletedFiles:n.deletedFiles.length,deletedDirs:n.deletedDirs.length,errors:a.length}),{deletedFiles:n.deletedFiles.length,deletedDirs:n.deletedDirs.length,errors:a}}function xS(e,t){e.debug(`cleanup plan built`,{filesToDelete:t.filesToDelete.length,dirsToDelete:t.dirsToDelete.length,violations:t.violations.length,conflicts:t.conflicts.length,excludedScanGlobs:t.excludedScanGlobs})}async function SS(e,t,n,r){if(r!=null){let i=await ox(e,t,r);n.debug(`Collected outputs for cleanup`,{projectDirs:i.projectDirs.length,projectFiles:i.projectFiles.length,globalDirs:i.globalDirs.length,globalFiles:i.globalFiles.length})}let i;try{i=await vS(e,t,r)}catch(e){if(e instanceof cS)return _S(n,e.conflicts),{deletedFiles:0,deletedDirs:0,errors:[],violations:[],conflicts:e.conflicts,message:e.message};throw e}let a={filesToDelete:i.filesToDelete,dirsToDelete:i.dirsToDelete,violations:i.violations,conflicts:i.conflicts,excludedScanGlobs:i.excludedScanGlobs};if(xS(n,a),a.violations.length>0)return Bg(n,`cleanup`,a.violations),{deletedFiles:0,deletedDirs:0,errors:[],violations:a.violations,conflicts:[],message:`Protected deletion guard blocked cleanup for ${a.violations.length} path(s)`};let o=await bS(a,n);return{deletedFiles:o.deletedFiles,deletedDirs:o.deletedDirs,errors:o.errors,violations:[],conflicts:[]}}var CS=class{name=`clean`;async execute(e){let{logger:t,outputPlugins:n,createCleanContext:r}=e;t.info(`running clean pipeline`,{command:`clean`});let i=await SS(n,r(!1),t);return i.violations.length>0||i.conflicts.length>0?{success:!1,filesAffected:0,dirsAffected:0,...i.message==null?{}:{message:i.message}}:(t.info(`clean complete`,{deletedFiles:i.deletedFiles,deletedDirs:i.deletedDirs}),{success:!0,filesAffected:i.deletedFiles,dirsAffected:i.deletedDirs})}},wS=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 ox(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,violations:c,excludedScanGlobs:l}=await vS(n,i);return c.length>0?(Bg(t,`dry-run-cleanup`,c),{success:!1,filesAffected:0,dirsAffected:0,message:`Protected deletion guard blocked cleanup for ${c.length} path(s)`}):(this.logDryRunFiles(o,t),this.logDryRunDirectories(s,t),t.info(`clean complete`,{dryRun:!0,filesAffected:o.length,dirsAffected:s.length,violations:0,excludedScanGlobs:l}),{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=u.isAbsolute(n)?n:u.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=u.isAbsolute(e)?e:u.resolve(e);t.info(`would delete directory`,{path:n,dryRun:!0})}}},TS=class{canHandle(e){return e.subcommand===`clean`}createCommand(e){return e.dryRun?new wS:new CS}};const ES=[`workspaceDir`,`aindex.skills.src`,`aindex.skills.dist`,`aindex.commands.src`,`aindex.commands.dist`,`aindex.subAgents.src`,`aindex.subAgents.dist`,`aindex.rules.src`,`aindex.rules.dist`,`aindex.globalPrompt.src`,`aindex.globalPrompt.dist`,`aindex.workspacePrompt.src`,`aindex.workspacePrompt.dist`,`aindex.app.src`,`aindex.app.dist`,`aindex.ext.src`,`aindex.ext.dist`,`aindex.arch.src`,`aindex.arch.dist`,`logLevel`];function DS(e){return ES.includes(e)}function OS(e){return[`trace`,`debug`,`info`,`warn`,`error`].includes(e)}function kS(){return ig()}function AS(){let e=kS();if(!i.existsSync(e))return{};try{let t=i.readFileSync(e,`utf8`);return JSON.parse(t)}catch{return{}}}function jS(e){let t=kS(),n=u.dirname(t);i.existsSync(n)||i.mkdirSync(n,{recursive:!0}),i.writeFileSync(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)}function MS(e,t,n){let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++){let t=r[e];if(t==null)continue;let n=i[t];(typeof n!=`object`||!n||Array.isArray(n))&&(i[t]={}),i=i[t]}let a=r.at(-1);a!=null&&(i[a]=n)}function NS(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r||Array.isArray(r))return;r=r[e]}return r}var PS=class{name=`config`;constructor(e){this.options=e}async execute(e){let{logger:t}=e;if(this.options.length===0)return t.error(ee({code:`CONFIG_COMMAND_ARGUMENTS_MISSING`,title:`Config command requires at least one key=value pair`,rootCause:b(`tnmsc config was invoked without any configuration assignments.`),exactFix:b("Run `tnmsc config key=value` with at least one supported configuration key."),possibleFixes:[b(`Use one of the supported keys: ${ES.join(`, `)}`)],details:{validKeys:[...ES]}})),t.info(`Usage: tnmsc config key=value`),t.info(`Valid keys: ${ES.join(`, `)}`),{success:!1,filesAffected:0,dirsAffected:0,message:`No options provided`};let n;try{n=AS()}catch(e){return{success:!1,filesAffected:0,dirsAffected:0,message:e instanceof Error?e.message:String(e)}}let r=[],i=[];for(let[e,a]of this.options){if(!DS(e)){r.push(`Invalid key: ${e}`),t.error(ee({code:`CONFIG_COMMAND_KEY_INVALID`,title:`Unsupported config key: ${e}`,rootCause:b(`The config command received "${e}", which is not a supported configuration key.`),exactFix:b(`Use one of the supported config keys and rerun the command.`),possibleFixes:[b(`Supported keys: ${ES.join(`, `)}`)],details:{key:e,validKeys:[...ES]}}));continue}if(e===`logLevel`&&!OS(a)){r.push(`Invalid logLevel value: ${a}`),t.error(ee({code:`CONFIG_COMMAND_LOG_LEVEL_INVALID`,title:`Unsupported logLevel value: ${a}`,rootCause:b(`The config command received "${a}" for logLevel, but tnmsc does not support that level.`),exactFix:b(`Set logLevel to one of: trace, debug, info, warn, or error.`),details:{key:e,value:a,validLevels:[`trace`,`debug`,`info`,`warn`,`error`]}}));continue}let o=NS(n,e);MS(n,e,a),o!==a&&i.push(`${e}=${a}`),t.info(`configuration updated`,{key:e,value:a})}if(i.length>0){try{jS(n)}catch(e){return{success:!1,filesAffected:0,dirsAffected:0,message:e instanceof Error?e.message:String(e)}}t.info(`global config written`,{path:kS()})}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}}};const FS=`.tnmsc.json`,IS=`.aindex`;function LS(){return ig()}var RS=class{logger;constructor(e={}){this.logger=Rx(`ConfigLoader`)}getSearchPaths(e=c.cwd()){let t=tg();if(!t.isWsl)return[ig()];if(this.logger.info(`wsl environment detected`,{effectiveHomeDir:t.effectiveHomeDir}),t.selectedGlobalConfigPath==null)throw Error(`WSL host config file not found under "${t.windowsUsersRoot}/*/${IS}/${FS}".`);return this.logger.info(`using wsl host global config`,{path:t.selectedGlobalConfigPath}),[ig()]}loadFromFile(e){let t=this.resolveTilde(e);try{if(!i.existsSync(t))return{config:{},source:null,found:!1};let e=i.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(D({code:`CONFIG_FILE_LOAD_FAILED`,title:`Failed to load config file`,operation:`read`,targetKind:`config file`,path:t,error:e})),{config:{},source:null,found:!1}}}load(e=c.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){let n;try{n=JSON.parse(e)}catch(e){throw e instanceof SyntaxError?Error(`Invalid JSON in ${t}: ${e.message}`):e}let r=Bb.safeParse(n);if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`);throw Error(`Config validation failed in ${t}:\n${i.join(`
|
|
228
|
-
`)}`)}mergeConfigs(e){if(e.length===0)return{};let t=e[0];return e.length===1&&t!=null?t:[...e].reverse().reduce((e,t)=>{let n=this.mergeAindex(e.aindex,t.aindex),r=this.mergeOutputScopeOptions(e.outputScopes,t.outputScopes),i=this.mergeFrontMatterOptions(e.frontMatter,t.frontMatter),a=this.mergeCleanupProtectionOptions(e.cleanupProtection,t.cleanupProtection),o=this.mergeWindowsOptions(e.windows,t.windows);return{...e,...t,...n==null?{}:{aindex:n},...r==null?{}:{outputScopes:r},...i==null?{}:{frontMatter:i},...a==null?{}:{cleanupProtection:a},...o==null?{}:{windows:o}}},{})}mergeAindex(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{dir:t.dir??e.dir,skills:{...e.skills,...t.skills},commands:{...e.commands,...t.commands},subAgents:{...e.subAgents,...t.subAgents},rules:{...e.rules,...t.rules},globalPrompt:{...e.globalPrompt,...t.globalPrompt},workspacePrompt:{...e.workspacePrompt,...t.workspacePrompt},app:{...e.app,...t.app},ext:{...e.ext,...t.ext},arch:{...e.arch,...t.arch}}}mergeOutputScopeTopics(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{...e,...t}}mergeOutputScopeOptions(e,t){if(e==null&&t==null)return;if(e==null)return t;if(t==null)return e;let n={};for(let[t,r]of Object.entries(e.plugins??{}))r!=null&&(n[t]={...r});for(let[e,r]of Object.entries(t.plugins??{})){let t=this.mergeOutputScopeTopics(n[e],r);t!=null&&(n[e]=t)}return Object.keys(n).length===0?{}:{plugins:n}}mergeFrontMatterOptions(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{...e,...t}}mergeCleanupProtectionOptions(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{rules:[...e.rules??[],...t.rules??[]]}}mergeWindowsOptions(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{...e,...t,...e.wsl2!=null||t.wsl2!=null?{wsl2:{...e.wsl2,...t.wsl2}}:{}}}resolveTilde(e){return e.startsWith(`~`)?
|
|
229
|
-
`).toLowerCase();if(t.length!==0)return[`windows subsystem for linux has no installed distributions`,`windows subsystem for linux has not been enabled`,`the windows subsystem for linux optional component is not enabled`,`wsl is not installed`,`run 'wsl.exe --install'`,`run "wsl.exe --install"`,`wslregisterdistribution failed with error: 0x8007019e`].some(e=>t.includes(e))?t:void 0}async function
|
|
230
|
-
`)}:(s+=l.mirroredFiles,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`})}},
|
|
231
|
-
`)};let f=await
|
|
232
|
-
`)}:(l+=f.mirroredFiles,t.info(`complete`,{command:`execute`,pluginCount:c.size}),{success:!0,filesAffected:l,dirsAffected:u})}},
|
|
233
|
-
${
|
|
226
|
+
`,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}`}getSkillName(e){return vb(e)}getSubAgentCanonicalName(e){return yb(e)}transformCommandName(e,t){let{includeSeriesPrefix:n=!0,seriesSeparator:r=`-`}=t??{};return!n||e.commandPrefix==null?`${e.commandName}.md`:`${e.commandPrefix}${r}${e.commandName}.md`}transformSubAgentName(e,t){let{fileNameSource:n}=this.subAgentsConfig,r=t?.includePrefix??this.subAgentsConfig.includePrefix,i=t?.linkSymbol??this.subAgentsConfig.linkSymbol,a=t?.ext??this.subAgentsConfig.ext,o=a.startsWith(`.`)?a:`.${a}`;return n===`frontMatterName`&&this.warnDeprecatedSubAgentFileNameSource(),r&&e.agentPrefix!=null&&e.agentPrefix.length>0?`${e.agentPrefix}${i}${e.agentName}${o}`:`${e.agentName}${o}`}normalizeOutputFileStem(e){let t=Array.from(e.trim(),e=>(e.codePointAt(0)??0)<=31||`<>:"/\\|?*`.includes(e)?`-`:e).join(``);for(;t.endsWith(`.`)||t.endsWith(` `);)t=t.slice(0,-1);if(t.length===0)throw Error(`Cannot derive a valid output file name from "${e}"`);return t}warnDeprecatedSubAgentFileNameSource(){this.warnedDeprecatedSubAgentFileNameSource||(this.warnedDeprecatedSubAgentFileNameSource=!0,this.log.warn(O({code:`SUBAGENT_FRONTMATTER_NAME_SOURCE_DEPRECATED`,title:`Sub-agent fileNameSource="frontMatterName" now resolves from derived names`,reason:b(`The ${this.name} plugin no longer reads authored sub-agent front matter names.`,`tnmsc now derives sub-agent names from the sub-agent path.`),exactFix:b("Remove authored `name` fields from sub-agent sources.",'Keep using `fileNameSource="frontMatterName"` only as a temporary alias for the derived-path naming behavior.'),details:{plugin:this.name}})))}appendSubAgentDeclarations(e,t,n,r){let i=new Map;for(let a of r){let r=this.transformSubAgentName(a),o=u.join(t,this.subAgentsConfig.subDir,r),s=i.get(o);if(s!=null)throw Error(`Sub-agent output collision in ${this.name}: "${this.getSubAgentCanonicalName(a)}" and "${s}" both resolve to ${o}`);i.set(o,this.getSubAgentCanonicalName(a)),e.push({path:o,scope:n,source:{kind:`subAgent`,subAgent:a}})}}appendCommandDeclarations(e,t,n,r,i){for(let a of r){let r=this.transformCommandName(a,i);e.push({path:u.join(t,this.commandsConfig.subDir,r),scope:n,source:{kind:`command`,command:a}})}}appendSkillDeclarations(e,t,n,r){for(let i of r){let r=this.getSkillName(i),a=u.join(t,this.skillsConfig.subDir,r);if(e.push({path:u.join(a,`SKILL.md`),scope:n,source:{kind:`skillMain`,skill:i}}),i.childDocs!=null)for(let t of i.childDocs)e.push({path:u.join(a,t.dir.path.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillReference`,content:t.content}});if(i.resources!=null)for(let t of i.resources)e.push({path:u.join(a,t.relativePath),scope:n,source:{kind:`skillResource`,content:t.content,encoding:t.encoding}})}}appendRuleDeclarations(e,t,n,r){let i=u.join(t,this.rulesConfig.subDir??`rules`);for(let t of r)e.push({path:u.join(i,this.buildRuleFileName(t)),scope:n,source:{kind:`rule`,rule:t}})}buildSubAgentTomlContent(e,t){let{bodyFieldName:n}=this.subAgentsConfig;if(n==null||n.length===0)throw Error(`subagents.bodyFieldName is required when artifactFormat="toml" for ${this.name}`);return this.buildTomlContent({content:e.content,bodyFieldName:n,...t!=null&&{frontMatter:t},...this.subAgentsConfig.fieldNameMap!=null&&{fieldNameMap:this.subAgentsConfig.fieldNameMap},...this.subAgentsConfig.excludedFrontMatterFields!=null&&{excludedKeys:this.subAgentsConfig.excludedFrontMatterFields},...this.subAgentsConfig.extraFields!=null&&{extraFields:this.subAgentsConfig.extraFields},...this.subAgentsConfig.fieldOrder!=null&&{fieldOrder:this.subAgentsConfig.fieldOrder}})}getCommandSeriesOptions(e){let t=e.pluginOptions?.commandSeriesOptions,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.getCommandSeriesOptions(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)}getRegistryWriter(e){let t=e.name,n=this.registryWriterCache.get(t);if(n!=null)return n;let r=new e(this.log);return this.registryWriterCache.set(t,r),r}async registerInRegistry(e,t,n){return e.register(t,n.dryRun)}normalizeRuleScope(e){return e.scope??`project`}normalizeSourceScope(e){return e===`global`||e===`project`?e:`project`}remapDeclarationScope(e,t){return t?.[e]??e}resolveCommandSourceScope(e){if(e.globalOnly===!0)return`global`;let t=e.yamlFrontMatter?.scope;return this.remapDeclarationScope(this.normalizeSourceScope(t),this.commandsConfig.scopeRemap)}resolveSubAgentSourceScope(e){let t=e.yamlFrontMatter?.scope;return this.remapDeclarationScope(this.normalizeSourceScope(t),this.subAgentsConfig.scopeRemap)}resolveSkillSourceScope(e){let t=e.yamlFrontMatter?.scope;return this.remapDeclarationScope(this.normalizeSourceScope(t),this.skillsConfig.scopeRemap)}selectSingleScopeItems(e,t,n,r){if(e.length===0)return{items:[]};let[i]=Cb({requestedScopes:r,defaultScopes:t,supportedScopes:t,singleScope:!0,availableScopes:[...new Set(e.map(n))]});return i==null?{items:[]}:{selectedScope:i,items:e.filter(e=>n(e)===i)}}selectRuleScopes(e,t){let n=[...new Set(t.map(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))))];return Cb({requestedScopes:this.getTopicScopeOverride(e,`rules`),defaultScopes:this.rulesConfig.sourceScopes??[`project`,`global`],supportedScopes:this.rulesConfig.sourceScopes??[`project`,`global`],singleScope:!1,availableScopes:n}).filter(e=>n.includes(e))}selectPromptScopes(e,t=[`project`,`global`],n=t){return Cb({requestedScopes:this.getTopicScopeOverride(e,`prompt`),defaultScopes:n,supportedScopes:t,singleScope:!1})}getTopicScopeOverride(e,t){return e.pluginOptions?.outputScopes?.plugins?.[this.name]?.[t]}buildSkillFrontMatter(e,t){let n=e.yamlFrontMatter,r={name:this.getSkillName(e),description:n.description};return`displayName`in n&&n.displayName!=null&&(r.displayName=n.displayName),`keywords`in n&&n.keywords!=null&&n.keywords.length>0&&(r.keywords=n.keywords),`author`in n&&n.author!=null&&(r.author=n.author),`version`in n&&n.version!=null&&(r.version=n.version),(t?.includeTools??!0)&&`allowTools`in n&&n.allowTools!=null&&n.allowTools.length>0&&(r.allowTools=(t?.toolFormat??`array`)===`string`?n.allowTools.join(`,`):n.allowTools),t?.additionalFields!=null&&Object.assign(r,t.additionalFields),r}buildRuleContent(e,t){let n=this.rulesConfig.transformFrontMatter?this.rulesConfig.transformFrontMatter(e):{globs:e.globs.join(`, `)},r=n==null||Object.keys(n).length===0?void 0:n;return this.buildMarkdownContent(e.content,r,t)}buildRuleFileName(e){let t=`${`${this.rulesConfig.prefix??`rule`}${this.rulesConfig.linkSymbol??`-`}`}${e.prefix}${this.rulesConfig.linkSymbol??`-`}${e.ruleName}${this.rulesConfig.ext??`.md`}`;return this.log.trace(`buildRuleFileName`,{plugin:this.name,rulePrefix:e.prefix,ruleName:e.ruleName,prefix:this.rulesConfig.prefix??`rule`,linkSymbol:this.rulesConfig.linkSymbol??`-`,ext:this.rulesConfig.ext??`.md`,result:t}),t}async declareOutputFiles(e){return this.buildDefaultOutputDeclarations(e)}async declareCleanupPaths(e){let t=this.buildCleanupTargetsFromScopeConfig(this.cleanupConfig.delete,`delete`,e),n=this.buildCleanupTargetsFromScopeConfig(this.cleanupConfig.protect,`protect`,e),{excludeScanGlobs:r}=this.cleanupConfig;return t.length===0&&n.length===0&&(r==null||r.length===0)?{}:{...t.length>0&&{delete:t},...n.length>0&&{protect:n},...r!=null&&r.length>0&&{excludeScanGlobs:r}}}async declareWslMirrorFiles(e){return this.wslMirrorPaths.map(e=>({sourcePath:e}))}async convertContent(e,t){let n=e.source;switch(n.kind){case`projectRootMemory`:case`projectChildMemory`:case`globalMemory`:case`skillReference`:case`ignoreFile`:return n.content;case`command`:return this.buildCommandContent(n.command,t);case`subAgent`:return this.buildSubAgentContent(n.subAgent,t);case`skillMain`:return this.buildSkillMainContent(n.skill,t);case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;case`rule`:return this.buildRuleContent(n.rule,t);default:throw Error(`Unsupported declaration source for plugin ${this.name}`)}}async buildDefaultOutputDeclarations(e){let t=[],{globalMemory:n,commands:r,subAgents:i,skills:a,rules:o,aiAgentIgnoreConfigFiles:s}=e.collectedOutputContext,c=this.getTransformOptionsFromContext(e),l=this.getIgnoreOutputPath(),d=this.indexignore==null?void 0:s?.find(e=>e.fileName===this.indexignore),f=this.commandOutputEnabled&&r!=null?this.selectSingleScopeItems(r,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)):{items:[]},p=this.subAgentOutputEnabled&&i!=null?this.selectSingleScopeItems(i,this.subAgentsConfig.sourceScopes,e=>this.resolveSubAgentSourceScope(e),this.getTopicScopeOverride(e,`subagents`)):{items:[]},m=this.skillOutputEnabled&&a!=null?this.selectSingleScopeItems(a,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)):{items:[]},h=o??[],g=this.ruleOutputEnabled&&h.length>0?new Set(this.selectRuleScopes(e,h)):new Set,_=new Set(this.selectPromptScopes(e,this.outputCapabilities.prompt?.scopes??[`project`,`global`])),v={project:[],global:[]};for(let e of h)v[this.normalizeSourceScope(this.normalizeRuleScope(e))].push(e);for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectRootDir(e,n),i=this.resolveProjectConfigDir(e,n);if(r==null||i==null)continue;if(this.outputFileName.length>0&&_.has(`project`)&&this.isProjectPromptOutputTarget(n)&&(n.rootMemoryPrompt!=null&&t.push({path:u.join(r,this.outputFileName),scope:`project`,source:{kind:`projectRootMemory`,content:n.rootMemoryPrompt.content}}),n.childMemoryPrompts!=null))for(let e of n.childMemoryPrompts)t.push({path:this.resolveFullPath(e.dir),scope:`project`,source:{kind:`projectChildMemory`,content:e.content}});let{projectConfig:a}=n;if(f.selectedScope===`project`&&f.items.length>0){let e=$(f.items,a,`commands`);this.appendCommandDeclarations(t,i,`project`,e,c)}if(p.selectedScope===`project`&&p.items.length>0){let e=$(p.items,a,`subAgents`);this.appendSubAgentDeclarations(t,i,`project`,e)}if(m.selectedScope===`project`&&m.items.length>0){let e=$(m.items,a,`skills`);this.appendSkillDeclarations(t,i,`project`,e)}if(g.has(`project`)){let e=Ky($(v.project,a,`rules`),a);this.appendRuleDeclarations(t,i,`project`,e)}l!=null&&d!=null&&n.isWorkspaceRootProject!==!0&&n.isPromptSourceProject!==!0&&n.dirFromWorkspacePath!=null&&t.push({path:u.join(n.dirFromWorkspacePath.basePath,n.dirFromWorkspacePath.path,l),scope:`project`,source:{kind:`ignoreFile`,content:d.content}})}let y=this.resolvePromptSourceProjectConfig(e);if(f.selectedScope===`global`&&f.items.length>0){let e=$(f.items,y,`commands`),n=this.getGlobalConfigDir();this.appendCommandDeclarations(t,n,`global`,e,c)}if(p.selectedScope===`global`&&p.items.length>0){let e=$(p.items,y,`subAgents`),n=this.getGlobalConfigDir();this.appendSubAgentDeclarations(t,n,`global`,e)}if(m.selectedScope===`global`&&m.items.length>0){let e=$(m.items,y,`skills`),n=this.getGlobalConfigDir();this.appendSkillDeclarations(t,n,`global`,e)}for(let e of[`global`]){if(!g.has(e))continue;let n=this.getGlobalConfigDir(),r=Ky($(v[e],y,`rules`),y);this.appendRuleDeclarations(t,n,e,r)}return n!=null&&this.outputFileName.length>0&&_.has(`global`)&&t.push({path:u.join(this.getGlobalConfigDir(),this.outputFileName),scope:`global`,source:{kind:`globalMemory`,content:n.content}}),t}async buildCommandContent(e,t){let n=e.content,r=e.yamlFrontMatter,i=!1;if(e.rawMdxContent!=null&&this.toolPreset!=null){this.log.debug(`recompiling command with tool preset`,{file:e.dir.getAbsolutePath(),toolPreset:this.toolPreset,hasRawContent:!0});let t=new Qy({toolPreset:this.toolPreset}).collect(),a=await mb({filePath:e.dir.getAbsolutePath(),globalScope:t,rawMdx:e.rawMdxContent});n=a.content,r=a.metadata,i=!0}let a=this.commandsConfig.transformFrontMatter;if(a==null)throw Error(`commands.transformFrontMatter is required for command output plugin: ${this.name}`);let o=a(e,{isRecompiled:i,...r!=null&&{sourceFrontMatter:r}});return this.buildMarkdownContent(n,o,t)}buildSubAgentContent(e,t){let n=this.subAgentsConfig.transformFrontMatter,r=n?.(e,{...e.yamlFrontMatter!=null&&{sourceFrontMatter:e.yamlFrontMatter}});if(this.subAgentsConfig.artifactFormat===`toml`){let t=r??e.yamlFrontMatter;return this.buildSubAgentTomlContent(e,t)}return r==null?this.buildMarkdownContentWithRaw(e.content,e.yamlFrontMatter,e.rawFrontMatter,t):this.buildMarkdownContent(e.content,r,t)}buildSkillMainContent(e,t){return this.buildMarkdownContentWithRaw(e.content,e.yamlFrontMatter,e.rawFrontMatter,t)}};const dx={USER_HOME:`~`,WORKSPACE:`$WORKSPACE`},fx={},px={AgentsOutput:`AgentsOutputPlugin`,GeminiCLIOutput:`GeminiCLIOutputPlugin`,CursorOutput:`CursorOutputPlugin`,WindsurfOutput:`WindsurfOutputPlugin`,ClaudeCodeCLIOutput:`ClaudeCodeCLIOutputPlugin`,KiroIDEOutput:`KiroCLIOutputPlugin`,OpencodeCLIOutput:`OpencodeCLIOutputPlugin`,OpenAICodexCLIOutput:`CodexCLIOutputPlugin`,DroidCLIOutput:`DroidCLIOutputPlugin`,WarpIDEOutput:`WarpIDEOutputPlugin`,TraeIDEOutput:`TraeIDEOutputPlugin`,TraeCNIDEOutput:`TraeCNIDEOutputPlugin`,QoderIDEOutput:`QoderIDEPluginOutputPlugin`,JetBrainsCodeStyleOutput:`JetBrainsIDECodeStyleConfigOutputPlugin`,JetBrainsAICodexOutput:`JetBrainsAIAssistantCodexOutputPlugin`,AgentSkillsCompactOutput:`GenericSkillsOutputPlugin`,GitExcludeOutput:`GitExcludeOutputPlugin`,ReadmeOutput:`ReadmeMdConfigFileOutputPlugin`,VSCodeOutput:`VisualStudioCodeIDEConfigOutputPlugin`,ZedOutput:`ZedIDEConfigOutputPlugin`,EditorConfigOutput:`EditorConfigOutputPlugin`,AntigravityOutput:`AntigravityOutputPlugin`},mx={SKILL:`SKILL.md`,CURSOR_GLOBAL_RULE:`global.mdc`,CURSOR_PROJECT_RULE:`always.md`,MCP_CONFIG:`mcp.json`,CLAUDE_MEMORY:`CLAUDE.md`,WINDSURF_GLOBAL_RULE:`global_rules.md`},hx={RULES:`rules`,COMMANDS:`commands`,SKILLS:`skills`,AGENTS:`agents`,CURSOR_SKILLS:`skills-cursor`},gx={MD:`.md`,MDC:`.mdc`,MDX:`.mdx`,JSON:`.json`},_x=[{PRIMARY:`.src.mdx`}.PRIMARY],vx={zh:_x,en:gx.MDX};function yx(e){return _x.some(t=>e.endsWith(t))}const bx={CURSOR:`.cursor`,CLAUDE:`.claude`,WINDSURF:`.codeium/windsurf`,WINDSURF_RULES:`.windsurf`},xx={CURSOR:`.cursorignore`,WINDSURF:`.codeiumignore`},Sx={CURSOR:new Set([`create-rule`,`create-skill`,`create-subagent`,`migrate-to-skills`,`update-cursor-settings`])};var Cx=class extends Error{kind;nameOfPrompt;sourcePath;expectedDistPath;constructor(e){let{kind:t,name:n,sourcePath:r,expectedDistPath:i}=e;super([`Missing compiled dist prompt for ${t} "${n}".`,...r==null?[]:[`source: ${r}`],`expected dist: ${i}`].join(` `)),this.name=`MissingCompiledPromptError`,this.kind=t,this.nameOfPrompt=n,r!=null&&(this.sourcePath=r),this.expectedDistPath=i}},wx=class extends Error{filePath;lineNumber;constructor(e,t,n){super(`Compiled prompt still contains residual module syntax at ${e}:${t}: ${n.trim()}`),this.name=`ResidualModuleSyntaxError`,this.filePath=e,this.lineNumber=t}};const Tx=/^\s*(```|~~~)/u,Ex=[/^\s*export\s+default\b/u,/^\s*export\s+const\b/u,/^\s*import\b/u];function Dx(e,t){let n,r=e.split(/\r?\n/u);for(let[e,i]of r.entries()){let r=Tx.exec(i);if(r?.[1]!=null){let e=r[1];n==null?n=e:n===e&&(n=void 0);continue}if(n==null&&Ex.some(e=>e.test(i)))throw new wx(t,e+1,i)}}function Ox(e,t,n={}){let{preferredSourcePath:r,distRootDir:i,srcRootDir:a}=n;if(t==null||t.length===0||r!=null&&r.length>0)return r;if(i==null||a==null)return;let o=e.relative(i,t);if(!(o.startsWith(`..`)||e.isAbsolute(o)))return e.join(a,o.replace(/\.mdx$/u,`.src.mdx`))}function kx(e){if(e instanceof Zg&&e.filePath!=null)return e.filePath;if(!(e instanceof Error)||!(`filePath`in e))return;let{filePath:t}=e;if(typeof t==`string`&&t.length>0)return t}function Ax(e,t){let n=kx(e)??t.distPath,r=[t.operation??`Prompt compilation failed.`,`prompt kind: ${t.promptKind}`,`logical name: ${t.logicalName}`];return t.entryDistPath!=null&&t.entryDistPath.length>0&&t.entryDistPath!==n&&r.push(`entry dist file: ${t.entryDistPath}`),n!=null&&n.length>0&&r.push(`dist file: ${n}`),r.push(`src file: ${t.srcPath??`<unresolved>`}`),r.push(`diagnostic:`),r.push(e instanceof Error?Xg(e):String(e)),r.join(`
|
|
227
|
+
`)}function jx(e){return e instanceof Cx||e instanceof wx}var Mx=class{constructor(e,t,n,r){this.fs=e,this.path=t,this.logger=n,this.globalScope=r}async readDirectoryStructure(e,t,n){let r=[],i=[];if(!this.exists(e))return{prompts:r,errors:i};try{let a=this.fs.readdirSync(e,{withFileTypes:!0});for(let o of a){if(!o.isDirectory())continue;let{name:a}=o,s=this.path.join(e,a),c=this.path.join(t,a);try{let e=await this.readEntry(a,s,c,n,!0);e&&r.push(e)}catch(e){if(i.push({path:s,error:e,phase:`read`}),this.logger.error(D({code:`LOCALIZED_PROMPT_ENTRY_READ_FAILED`,title:`Failed to read localized prompt entry`,operation:`read`,targetKind:`${String(n.kind)} prompt entry`,path:s,error:e,details:{entryName:a,promptKind:String(n.kind)}})),jx(e))throw e}}}catch(t){if(i.push({path:e,error:t,phase:`scan`}),this.logger.error(D({code:`LOCALIZED_PROMPT_DIRECTORY_SCAN_FAILED`,title:`Failed to scan localized prompt source directory`,operation:`scan`,targetKind:`${String(n.kind)} prompt source directory`,path:e,error:t,details:{promptKind:String(n.kind)}})),jx(t))throw t}return{prompts:r,errors:i}}async readFlatFiles(e,t,n){let r=[],i=[],a=this.exists(e),o=this.exists(t);if(this.logger.debug(`readFlatFiles: srcDir=${e}, exists=${a}`),this.logger.debug(`readFlatFiles: distDir=${t}, exists=${o}`),!a&&!o)return{prompts:r,errors:i};let s=this.normalizeExtensions(n.localeExtensions.zh),c=new Set,l=async(a,o)=>{if(!c.has(a)){c.add(a);try{let i=await this.readFlatEntry(a,e,t,a,n);i&&r.push(i)}catch(e){if(i.push({path:o,error:e,phase:`read`}),this.logger.error(D({code:`LOCALIZED_PROMPT_FILE_READ_FAILED`,title:`Failed to read localized prompt file`,operation:`read`,targetKind:`${String(n.kind)} prompt file`,path:o,error:e,details:{promptKind:String(n.kind),logicalName:a}})),jx(e))throw e}}},u=async(e,t=``)=>{if(this.exists(e))try{let n=this.fs.readdirSync(e,{withFileTypes:!0});for(let r of n){let n=t?this.path.join(t,r.name):r.name;if(r.isDirectory()){await u(this.path.join(e,r.name),n);continue}let i=this.findMatchingExtension(r.name,s);if(!r.isFile()||i==null)continue;let a=r.name.slice(0,-i.length);await l(t?this.path.join(t,a):a,this.path.join(e,r.name))}}catch(t){if(i.push({path:e,error:t,phase:`scan`}),this.logger.error(D({code:`LOCALIZED_SOURCE_DIRECTORY_SCAN_FAILED`,title:`Failed to scan localized source directory`,operation:`scan`,targetKind:`${String(n.kind)} source directory`,path:e,error:t,details:{promptKind:String(n.kind)}})),jx(t))throw t}},d=async(e,t=``)=>{if(this.exists(e))try{let n=this.fs.readdirSync(e,{withFileTypes:!0});for(let r of n){let n=t?this.path.join(t,r.name):r.name;if(r.isDirectory()){await d(this.path.join(e,r.name),n);continue}if(!r.isFile()||!r.name.endsWith(`.mdx`))continue;let i=r.name.slice(0,-4);await l(t?this.path.join(t,i):i,this.path.join(e,r.name))}}catch(t){if(i.push({path:e,error:t,phase:`scan`}),this.logger.error(D({code:`LOCALIZED_DIST_DIRECTORY_SCAN_FAILED`,title:`Failed to scan localized dist directory`,operation:`scan`,targetKind:`${String(n.kind)} dist directory`,path:e,error:t,details:{promptKind:String(n.kind)}})),jx(t))throw t}};return a&&await u(e),o&&await d(t),{prompts:r,errors:i}}async readSingleFile(e,t,n){let r=this.path.basename(e);return this.readFlatEntry(r,this.path.dirname(e),this.path.dirname(t),e,n,!0)}async readEntry(e,t,n,r,i=!0){let{localeExtensions:a,entryFileName:o,createPrompt:s,kind:c}=r,l=r.hydrateSourceContents??!0,u=o??e,d=this.normalizeExtensions(a.zh),f=this.normalizeExtensions(a.en),p=this.resolveLocalizedPath(t,u,d),m=this.resolveLocalizedPath(t,u,f),h=this.path.join(n,`${u}.mdx`),g=this.exists(p),_=this.exists(m),v=g?p:_?m:void 0,y={promptKind:String(c),logicalName:e,entryDistPath:h,...v!=null&&{srcPath:v}},x=await this.readDistContent(h,s,e,y),S=g&&l?await this.readLocaleContent(p,`zh`,s,e,String(c)):null,w=_&&l?await this.readLocaleContent(m,`en`,s,e,String(c)):null,T=x!=null,E=g?p:_?m:void 0;if(!T&&!g&&!_)return this.logger.warn(C({code:`LOCALIZED_PROMPT_ARTIFACTS_MISSING`,title:`Missing source and dist prompt artifacts for ${e}`,rootCause:b(`tnmsc could not find either the source prompt or the compiled dist prompt for "${e}".`),exactFix:b(`Create the source prompt and rebuild the compiled dist prompt before retrying tnmsc.`),details:{promptKind:String(c),name:e,srcZhPath:p,srcEnPath:m,distPath:h}})),null;if(!T)throw new Cx({kind:String(c),name:e,...E!=null&&{sourcePath:E},expectedDistPath:h});let D=l&&S!=null?{zh:S,...w!=null&&{en:w},default:S,defaultLocale:`zh`}:void 0,O=i?this.scanChildren(n,u,[`.mdx`]):void 0;return{name:e,type:c,...D!=null&&{src:D},...T&&{dist:x},metadata:{hasDist:T,hasMultipleLocales:_,isDirectoryStructure:i,...O&&O.length>0&&{children:O}},paths:{...g&&{zh:p},..._&&{en:m},...T&&{dist:h}}}}async readFlatEntry(e,t,n,r,i,a=!1){let{localeExtensions:o,createPrompt:s,kind:c}=i,l=i.hydrateSourceContents??!0,u=this.normalizeExtensions(o.zh),d=this.normalizeExtensions(o.en),f=this.resolveLocalizedPath(``,r,u),p=this.resolveLocalizedPath(``,r,d),m=this.path.join(n,`${e}.mdx`),h=a?f:this.path.join(t,f),g=a?p:this.path.join(t,p),_=this.exists(h),v=this.exists(g),y=_?h:v?g:void 0,x={promptKind:String(c),logicalName:e,entryDistPath:m,...y!=null&&{srcPath:y}},S=await this.readDistContent(m,s,e,x),w=_&&l?await this.readLocaleContent(h,`zh`,s,e,String(c)):null,T=v&&l?await this.readLocaleContent(g,`en`,s,e,String(c)):null,E=S!=null,D=_?h:v?g:void 0;if(!E&&!_&&!v)return this.logger.warn(C({code:`LOCALIZED_PROMPT_ARTIFACTS_MISSING`,title:`Missing source and dist prompt artifacts for ${e}`,rootCause:b(`tnmsc could not find either the source prompt or the compiled dist prompt for "${e}".`),exactFix:b(`Create the source prompt and rebuild the compiled dist prompt before retrying tnmsc.`),details:{promptKind:String(c),name:e,srcZhPath:h,srcEnPath:g,distPath:m}})),null;if(!E)throw new Cx({kind:String(c),name:e,...D!=null&&{sourcePath:D},expectedDistPath:m});let O=l&&w!=null?{zh:w,...T!=null&&{en:T},default:w,defaultLocale:`zh`}:void 0;return{name:e,type:c,...O!=null&&{src:O},...E&&{dist:S},metadata:{hasDist:E,hasMultipleLocales:v,isDirectoryStructure:!1},paths:{..._&&{zh:h},...v&&{en:g},...E&&{dist:m}}}}async readLocaleContent(e,t,n,r,i){if(!this.exists(e))return null;try{let i=await pb(e,{mode:`source`,globalScope:this.globalScope});Dx(i.content,e);let a=await n(i.content,t,r,i.metadata),o={content:i.content,lastModified:i.lastModified,filePath:e};return i.rawMdx.length>0&&Object.assign(o,{rawMdx:i.rawMdx}),i.parsed.yamlFrontMatter!=null&&Object.assign(o,{frontMatter:i.parsed.yamlFrontMatter}),a!=null&&Object.assign(o,{prompt:a}),o}catch(n){throw this.logger.error(te({code:`LOCALIZED_SOURCE_PROMPT_READ_FAILED`,title:`Failed to read localized source prompt`,diagnosticText:Ax(n,{operation:`Failed to read localized source prompt.`,promptKind:i,logicalName:r,distPath:e}),details:{promptKind:i,locale:t,filePath:e}})),n}}async readDistContent(e,t,n,r){if(!this.exists(e))return null;try{let r=await pb(e,{mode:`dist`,globalScope:this.globalScope});Dx(r.content,e);let i=await t(r.content,`zh`,n,r.metadata),a={content:r.content,lastModified:r.lastModified,prompt:i,filePath:e,rawMdx:r.rawMdx};return r.parsed.yamlFrontMatter!=null&&Object.assign(a,{frontMatter:r.parsed.yamlFrontMatter}),a}catch(t){throw this.logger.error(this.buildDistReadDiagnostic(t,e,r)),t}}buildDistReadDiagnostic(e,t,n){let r=Ox(this.path,t,{preferredSourcePath:t===n.entryDistPath?n.srcPath:void 0,distRootDir:this.path.dirname(n.entryDistPath),srcRootDir:n.srcPath==null?void 0:this.path.dirname(n.srcPath)});return te({code:`LOCALIZED_DIST_PROMPT_READ_FAILED`,title:`Failed to read localized dist prompt`,diagnosticText:Ax(e,{operation:`Failed to read dist content.`,promptKind:n.promptKind,logicalName:n.logicalName,entryDistPath:n.entryDistPath,distPath:t,srcPath:r}),details:{promptKind:n.promptKind,logicalName:n.logicalName,filePath:t,srcPath:r}})}scanChildren(e,t,n){let r=[];if(!this.exists(e))return r;let i=new Set(n.map(e=>`${t}${e}`));try{let t=(e,a)=>{let o=this.fs.readdirSync(e,{withFileTypes:!0});for(let s of o){let o=this.path.join(e,s.name),c=a?this.path.join(a,s.name):s.name;if(s.isDirectory())t(o,c);else{let e=this.findMatchingExtension(s.name,n);if(e==null||i.has(s.name))continue;let t=s.name.slice(0,-e.length),a=this.path.dirname(c),o=a===`.`?t:this.path.join(a,t);r.push(o)}}};t(e,``)}catch(t){this.logger.warn(D({code:`LOCALIZED_PROMPT_CHILD_SCAN_FAILED`,title:`Failed to scan localized prompt child documents`,operation:`scan`,targetKind:`localized prompt child directory`,path:e,error:t}))}return r}exists(e){try{return this.fs.existsSync(e)}catch{return!1}}normalizeExtensions(e){return typeof e==`string`?[e]:e}findMatchingExtension(e,t){return t.find(t=>e.endsWith(t))}resolveLocalizedPath(e,t,n){let r=e===``?`${t}${n[0]}`:this.path.join(e,`${t}${n[0]}`);for(let r of n){let n=e===``?`${t}${r}`:this.path.join(e,`${t}${r}`);if(this.exists(n))return n}return r}};function Nx(e,t,n,r){return new Mx(e,t,n,r)}function Px(e,t){let n=new Map;for(let r of e)if(r.mcpConfig!=null)for(let[e,i]of Object.entries(r.mcpConfig.mcpServers))n.set(e,i),t?.debug(`mcp server collected`,{skill:vb(r),mcpName:e});return n}function Fx(e,t){let n={};for(let[r,i]of e)n[r]=t(i);return n}function Ix(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,r=n.url??n.serverUrl;if(r==null)return t;t.url=r;let{headers:i}=n;return i!=null&&(t.headers=i),t}function Lx(e){let t={};if(e.command!=null){t.type=`local`;let n=[e.command];e.args!=null&&n.push(...e.args),t.command=n,e.env!=null&&(t.environment=e.env)}else{t.type=`remote`;let n=e;n.url==null?n.serverUrl!=null&&(t.url=n.serverUrl):t.url=n.url}return t.enabled=e.disabled!==!0,t}function Rx(){ve()}function zx(e,t){return be(e,t)}function Bx(){return ye()}function Vx(e){_e(e)}var Hx=class{name;inner;constructor(e){this.inner=e,this.name=`json:${e.name}`}async execute(e){Rx();let t=await this.inner.execute(e),n=Ux(t,Bx());return c.stdout.write(`${JSON.stringify(n)}\n`),t}};function Ux(e,t=Bx()){let{warnings:n,errors:r}=re(t);return{success:e.success,filesAffected:e.filesAffected,dirsAffected:e.dirsAffected,...e.message!=null&&{message:e.message},pluginResults:[],warnings:n,errors:r}}let Wx=function(e){return e[e.Flags=0]=`Flags`,e[e.Unknown=1]=`Unknown`,e[e.Subcommand=2]=`Subcommand`,e}({});var Gx=class{factories=[];register(e){this.factories.push(e),this.factories.sort((e,t)=>e.priority-t.priority)}registerWithPriority(e,t){let n={priority:t,canHandle:t=>e.canHandle(t),createCommand:t=>e.createCommand(t)};this.factories.push(n),this.factories.sort((e,t)=>e.priority-t.priority)}resolve(e){for(let t of this.factories)if(t.priority<=Wx.Unknown&&t.canHandle(e))return t.createCommand(e);for(let t of this.factories)if(t.priority===Wx.Subcommand&&t.canHandle(e))return t.createCommand(e);for(let t of this.factories)if(t.canHandle(e))return t.createCommand(e);throw Error(`No command factory found for the given arguments`)}};function Kx(){return c.env.TNMSC_FORCE_NATIVE_BINDING===`1`?!1:c.env.TNMSC_DISABLE_NATIVE_BINDING===`1`?!0:c.env.NODE_ENV===`test`||c.env.VITEST!=null||c.env.VITEST_WORKER_ID!=null}function qx(){if(Kx())return;let e={"win32-x64":`win32-x64-msvc`,"linux-x64":`linux-x64-gnu`,"linux-arm64":`linux-arm64-gnu`,"darwin-arm64":`darwin-arm64`,"darwin-x64":`darwin-x64`}[`${c.platform}-${c.arch}`];if(e!=null)try{let t=r(import.meta.url),n=`@truenine/memory-sync-cli-${e}`,i=`napi-memory-sync-cli.${e}.node`,a=[n,`${n}/${i}`,`./${i}`,`../npm/${e}`,`../npm/${e}/${i}`,`../../npm/${e}`,`../../npm/${e}/${i}`];for(let e of a)try{let n=t(e),r=[n?.config,n?.default?.config,n?.default,n];for(let e of r)if(typeof e==`object`&&e)return e}catch{}}catch{}}function Jx(){return qx()}function Yx(e){let{root:t}=u.parse(e);return e===t?e:e.endsWith(u.sep)?e.slice(0,-1):e}function Xx(e,t){let n=Yx(e),r=Yx(t);return n===r?!0:n.startsWith(`${r}${u.sep}`)}function Zx(e,t){let n=new Map,r=new Map;for(let t of e){let e=gg(t);n.set(e,e)}for(let e of t){let t=gg(e);r.set(t,t)}let i=new Map,a=[...r.entries()].sort((e,t)=>e[0].length-t[0].length);for(let[e,t]of a){let n=!1;for(let t of i.keys())if(Xx(e,t)){n=!0;break}n||i.set(e,t)}let o=[];for(let[e,t]of n){let n=!1;for(let t of i.keys())if(Xx(e,t)){n=!0;break}n||o.push(t)}return o.sort((e,t)=>e.localeCompare(t)),{files:o,dirs:[...i.values()].sort((e,t)=>e.localeCompare(t))}}function Qx(e){let t=c.env.XDG_DATA_HOME;return typeof t==`string`&&t.trim().length>0?og(t):d.join(e,`.local`,`share`)}function $x(){let e=ng(),t=e.isWsl?`win32`:e.platform,n=e.effectiveHomeDir;if(t===`win32`)return og(c.env.LOCALAPPDATA??d.join(n,`AppData`,`Local`));if(t===`darwin`)return d.join(n,`Library`,`Application Support`);if(t===`linux`)return Qx(n);throw Error(`Unsupported platform: ${c.platform}`)}async function eS(e){try{let t=await i.promises.lstat(e);return t.isSymbolicLink()?(await(c.platform===`win32`?i.promises.rm(e,{recursive:!0,force:!0}):i.promises.unlink(e)),!0):t.isDirectory()?(await i.promises.rm(e,{recursive:!0,force:!0}),!0):(await i.promises.unlink(e),!0)}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function tS(e,t,n){if(e.length===0)return[];let r=[],i=0,a=async()=>{for(;;){let t=i;if(t>=e.length)return;i+=1,r[t]=await n(e[t])}},o=Math.min(t,e.length),s=[];for(let e=0;e<o;e+=1)s.push(a());return await Promise.all(s),r}async function nS(e,t){let n=await tS(t?.sortByDepthDescending===!0?[...e].sort((e,t)=>t.length-e.length||t.localeCompare(e)):[...e],32,async e=>{try{return{path:e,deleted:await eS(e)}}catch(t){return{path:e,error:t}}}),r=[],i=[];for(let e of n){if(`error`in e){i.push({path:e.path,error:e.error});continue}e.deleted&&r.push(e.path)}return{deleted:r.length,deletedPaths:r,errors:i}}async function rS(e){return nS(e)}async function iS(e){return nS(e,{sortByDepthDescending:!0})}async function aS(e){let[t,n]=await Promise.all([rS(e.files??[]),iS(e.dirs??[])]);return{deletedFiles:t.deletedPaths,deletedDirs:n.deletedPaths,fileErrors:t.errors,dirErrors:n.errors}}const oS=Jx();function sS(e){return{deletedFiles:e.deletedFiles??e.deleted_files??[],deletedDirs:e.deletedDirs??e.deleted_dirs??[],fileErrors:e.fileErrors??e.file_errors??[],dirErrors:e.dirErrors??e.dir_errors??[]}}function cS(){return $x()}async function lS(e){return oS?.deleteTargets==null?aS(e):sS(await Promise.resolve(oS.deleteTargets({files:e.files??[],dirs:e.dirs??[]})))}var uS=class extends Error{conflicts;constructor(e){super(_S(e)),this.name=`CleanupProtectionConflictError`,this.conflicts=e}};const dS=[`**/node_modules/**`,`**/.git/**`,`**/.turbo/**`,`**/.pnpm-store/**`,`**/.yarn/**`,`**/.next/**`];function fS(e){return gg(e).replaceAll(`\\`,`/`)}function pS(e,t){let n=fS(e);return Um.default.sync(n,{onlyFiles:!1,dot:!0,absolute:!0,followSymbolicLinks:!1,ignore:[...t]})}function mS(e,t){if(t.excludeBasenames==null||t.excludeBasenames.length===0)return!1;let n=u.basename(e);return t.excludeBasenames.includes(n)}async function hS(e,t){return e.declareCleanupPaths==null?{}:e.declareCleanupPaths({...t,dryRun:!0})}async function gS(e,t,n){let r=n?.get(e),[i,a]=await Promise.all([r==null?e.declareOutputFiles({...t,dryRun:!0}):Promise.resolve(r),hS(e,t)]);return{plugin:e,outputs:i,cleanup:a}}function _S(e){let t=e.map(e=>e.outputPath).join(`, `);return`Cleanup protection conflict: ${e.length} output path(s) are also protected: ${t}`}function vS(e,t){let n=[];for(let[r,i]of e.entries()){let e=new Set(bg(r));for(let a of t.compiledRules)if(a.comparisonKeys.some(t=>e.has(t)))for(let e of i)n.push({outputPath:r,outputPlugin:e,protectedPath:a.path,protectionMode:a.protectionMode,protectedBy:a.source,reason:a.reason})}return n.sort((e,t)=>{let n=e.outputPath.localeCompare(t.outputPath);return n===0?e.protectedPath.localeCompare(t.protectedPath):n})}function yS(e,t){let n=t[0];e.error(C({code:`CLEANUP_PROTECTION_CONFLICT_DETECTED`,title:`Cleanup output paths conflict with protected inputs`,rootCause:b(`tnmsc found ${t.length} output path(s) that also match protected cleanup rules.`,n==null?`No conflict details were captured.`:`Example conflict: "${n.outputPath}" is protected by "${n.protectedPath}".`),exactFix:b(`Separate generated output paths from protected source or reserved workspace paths before running cleanup again.`),possibleFixes:[b(`Update cleanup protect declarations so they do not overlap generated outputs.`),b(`Move the conflicting output target to a generated-only directory.`)],details:{count:t.length,conflicts:t.map(e=>({outputPath:e.outputPath,outputPlugin:e.outputPlugin,protectedPath:e.protectedPath,protectionMode:e.protectionMode,protectedBy:e.protectedBy,reason:e.reason}))}}))}async function bS(e,t,n){let r=new Set,a=new Set,o=new Map,s=new Set(dS),c=new Map,l=await Promise.all(e.map(async e=>gS(e,t,n))),u=(e,t)=>{t===`directory`?a.add(gg(e)):r.add(gg(e))},d=(e,t,n,r,i=`path`)=>{let a=gg(e);o.set(`${i}:${t}:${a}`,{path:a,protectionMode:t,reason:n,source:r,matcher:i})},f=e=>e.protectionMode==null?e.kind===`file`?`direct`:`recursive`:e.protectionMode;for(let e of Ng(t.collectedOutputContext))d(e.path,e.protectionMode,e.reason,e.source);if(t.collectedOutputContext.aindexDir!=null&&t.pluginOptions!=null)for(let e of Mg(t.pluginOptions,t.collectedOutputContext.aindexDir,{workspaceDir:t.collectedOutputContext.workspace.directory.path}))d(e.path,e.protectionMode,e.reason,e.source,e.matcher);for(let e of t.pluginOptions?.cleanupProtection?.rules??[])d(e.path,e.protectionMode,e.reason??`configured cleanup protection rule`,`configured-cleanup-protection`,e.matcher??`path`);for(let e of l){for(let t of e.outputs){let n=gg(t.path);u(n,`file`);let r=c.get(n);r==null?c.set(n,[e.plugin.name]):r.includes(e.plugin.name)||r.push(e.plugin.name)}for(let t of e.cleanup.excludeScanGlobs??[])s.add(fS(t))}let p=[...s],m=e=>{for(let t of pS(e.path,p))if(!mS(t,e))try{i.lstatSync(t).isDirectory()?u(t,`directory`):u(t,`file`)}catch{}},h=(e,t)=>{let n=f(e),r=e.label==null?`plugin cleanup protect declaration`:`plugin cleanup protect declaration (${e.label})`;for(let i of pS(e.path,p))d(i,n,r,`plugin-cleanup-protect:${t}`)};for(let{plugin:e,cleanup:t}of l){for(let n of t.protect??[]){if(n.kind===`glob`){h(n,e.name);continue}d(n.path,f(n),n.label==null?`plugin cleanup protect declaration`:`plugin cleanup protect declaration (${n.label})`,`plugin-cleanup-protect:${e.name}`)}for(let e of t.delete??[]){if(e.kind===`glob`){m(e);continue}e.kind===`directory`?u(e.path,`directory`):u(e.path,`file`)}}let g=Fg({workspaceDir:t.collectedOutputContext.workspace.directory.path,projectRoots:Ig(t.collectedOutputContext),rules:[...o.values()],...t.collectedOutputContext.aindexDir==null?{}:{aindexDir:t.collectedOutputContext.aindexDir}}),_=vS(c,g);if(_.length>0)throw new uS(_);let v=zg([...r],g),y=zg([...a],g),b=Zx(v.safePaths,y.safePaths);return{filesToDelete:b.files,dirsToDelete:b.dirs,violations:[...v.violations,...y.violations].sort((e,t)=>e.targetPath.localeCompare(t.targetPath)),conflicts:[],excludedScanGlobs:[...s].sort((e,t)=>e.localeCompare(t))}}function xS(e,t,n){return t.map(t=>{let r=t.error instanceof Error?t.error.message:String(t.error);return e.warn(D({code:n===`file`?`CLEANUP_FILE_DELETE_FAILED`:`CLEANUP_DIRECTORY_DELETE_FAILED`,title:n===`file`?`Cleanup could not delete a file`:`Cleanup could not delete a directory`,operation:`delete`,targetKind:n,path:t.path,error:r,details:{phase:`cleanup`}})),{path:t.path,type:n,error:t.error}})}async function SS(e,t){t.debug(`cleanup delete execution started`,{filesToDelete:e.filesToDelete.length,dirsToDelete:e.dirsToDelete.length});let n=await lS({files:e.filesToDelete,dirs:e.dirsToDelete}),r=xS(t,n.fileErrors,`file`),i=xS(t,n.dirErrors,`directory`),a=[...r,...i];return t.debug(`cleanup delete execution complete`,{deletedFiles:n.deletedFiles.length,deletedDirs:n.deletedDirs.length,errors:a.length}),{deletedFiles:n.deletedFiles.length,deletedDirs:n.deletedDirs.length,errors:a}}function CS(e,t){e.debug(`cleanup plan built`,{filesToDelete:t.filesToDelete.length,dirsToDelete:t.dirsToDelete.length,violations:t.violations.length,conflicts:t.conflicts.length,excludedScanGlobs:t.excludedScanGlobs})}async function wS(e,t,n,r){if(r!=null){let i=await sx(e,t,r);n.debug(`Collected outputs for cleanup`,{projectDirs:i.projectDirs.length,projectFiles:i.projectFiles.length,globalDirs:i.globalDirs.length,globalFiles:i.globalFiles.length})}let i;try{i=await bS(e,t,r)}catch(e){if(e instanceof uS)return yS(n,e.conflicts),{deletedFiles:0,deletedDirs:0,errors:[],violations:[],conflicts:e.conflicts,message:e.message};throw e}let a={filesToDelete:i.filesToDelete,dirsToDelete:i.dirsToDelete,violations:i.violations,conflicts:i.conflicts,excludedScanGlobs:i.excludedScanGlobs};if(CS(n,a),a.violations.length>0)return Vg(n,`cleanup`,a.violations),{deletedFiles:0,deletedDirs:0,errors:[],violations:a.violations,conflicts:[],message:`Protected deletion guard blocked cleanup for ${a.violations.length} path(s)`};let o=await SS(a,n);return{deletedFiles:o.deletedFiles,deletedDirs:o.deletedDirs,errors:o.errors,violations:[],conflicts:[]}}const TS=Jx();function ES(){return TS?.planCleanup!=null&&TS.performCleanup!=null}function DS(e){return e}function OS(e){return e}function kS(e){return{path:e.path,kind:e.kind,...e.excludeBasenames!=null&&e.excludeBasenames.length>0?{excludeBasenames:[...e.excludeBasenames]}:{},...e.protectionMode==null?{}:{protectionMode:DS(e.protectionMode)},...e.scope==null?{}:{scope:e.scope},...e.label==null?{}:{label:e.label}}}async function AS(e,t){return e.declareCleanupPaths==null?{}:e.declareCleanupPaths({...t,dryRun:!0})}async function jS(e,t,n){let r=n?.get(e),[i,a]=await Promise.all([r==null?e.declareOutputFiles({...t,dryRun:!0}):Promise.resolve(r),AS(e,t)]);return{pluginName:e.name,outputs:i.map(e=>e.path),cleanup:{...a.delete!=null&&a.delete.length>0?{delete:a.delete.map(kS)}:{},...a.protect!=null&&a.protect.length>0?{protect:a.protect.map(kS)}:{},...a.excludeScanGlobs!=null&&a.excludeScanGlobs.length>0?{excludeScanGlobs:[...a.excludeScanGlobs]}:{}}}}function MS(e){return(e.pluginOptions?.cleanupProtection?.rules??[]).map(e=>({path:e.path,protectionMode:DS(e.protectionMode),reason:e.reason??`configured cleanup protection rule`,source:`configured-cleanup-protection`,matcher:OS(e.matcher??`path`)}))}function NS(e){let t=e.map(e=>e.outputPath).join(`, `);return`Cleanup protection conflict: ${e.length} output path(s) are also protected: ${t}`}function PS(e,t){let n=t[0];e.error(C({code:`CLEANUP_PROTECTION_CONFLICT_DETECTED`,title:`Cleanup output paths conflict with protected inputs`,rootCause:b(`tnmsc found ${t.length} output path(s) that also match protected cleanup rules.`,n==null?`No conflict details were captured.`:`Example conflict: "${n.outputPath}" is protected by "${n.protectedPath}".`),exactFix:b(`Separate generated output paths from protected source or reserved workspace paths before running cleanup again.`),possibleFixes:[b(`Update cleanup protect declarations so they do not overlap generated outputs.`),b(`Move the conflicting output target to a generated-only directory.`)],details:{count:t.length,conflicts:t}}))}function FS(e,t){e.debug(`cleanup plan built`,{filesToDelete:t.filesToDelete.length,dirsToDelete:t.dirsToDelete.length,violations:t.violations.length,conflicts:t.conflicts.length,excludedScanGlobs:t.excludedScanGlobs})}function IS(e,t){return t.map(t=>{let n=t.kind===`directory`?`directory`:`file`;return e.warn(D({code:n===`file`?`CLEANUP_FILE_DELETE_FAILED`:`CLEANUP_DIRECTORY_DELETE_FAILED`,title:n===`file`?`Cleanup could not delete a file`:`Cleanup could not delete a directory`,operation:`delete`,targetKind:n,path:t.path,error:t.error,details:{phase:`cleanup`}})),{path:t.path,type:n,error:t.error}})}async function LS(e,t,n){let r=await Promise.all(e.map(async e=>jS(e,t,n))),i=[];for(let e of Ng(t.collectedOutputContext))i.push({path:e.path,protectionMode:DS(e.protectionMode),reason:e.reason,source:e.source,...e.matcher==null?{}:{matcher:OS(e.matcher)}});if(t.collectedOutputContext.aindexDir!=null&&t.pluginOptions!=null)for(let e of Mg(t.pluginOptions,t.collectedOutputContext.aindexDir,{workspaceDir:t.collectedOutputContext.workspace.directory.path}))i.push({path:e.path,protectionMode:DS(e.protectionMode),reason:e.reason,source:e.source,...e.matcher==null?{}:{matcher:OS(e.matcher)}});return i.push(...MS(t)),{workspaceDir:t.collectedOutputContext.workspace.directory.path,...t.collectedOutputContext.aindexDir==null?{}:{aindexDir:t.collectedOutputContext.aindexDir},projectRoots:Ig(t.collectedOutputContext),protectedRules:i,pluginSnapshots:r}}function RS(e){return JSON.parse(e)}async function zS(e){if(TS?.planCleanup==null)throw Error(`Native cleanup planning is unavailable`);return RS(await Promise.resolve(TS.planCleanup(JSON.stringify(e))))}async function BS(e){if(TS?.performCleanup==null)throw Error(`Native cleanup execution is unavailable`);return RS(await Promise.resolve(TS.performCleanup(JSON.stringify(e))))}async function VS(e,t,n){if(!ES())return bS(e,t,n);let r=await zS(await LS(e,t,n));if(r.conflicts.length>0)throw new uS(r.conflicts);return{filesToDelete:r.filesToDelete,dirsToDelete:r.dirsToDelete,violations:[...r.violations],conflicts:[],excludedScanGlobs:r.excludedScanGlobs}}async function HS(e,t,n,r){if(!ES())return wS(e,t,n,r);if(r!=null){let i=await sx(e,t,r);n.debug(`Collected outputs for cleanup`,{projectDirs:i.projectDirs.length,projectFiles:i.projectFiles.length,globalDirs:i.globalDirs.length,globalFiles:i.globalFiles.length})}let i=await BS(await LS(e,t,r));if(FS(n,i),i.conflicts.length>0)return PS(n,i.conflicts),{deletedFiles:0,deletedDirs:0,errors:[],violations:[],conflicts:i.conflicts,message:NS(i.conflicts)};if(i.violations.length>0)return Vg(n,`cleanup`,i.violations),{deletedFiles:0,deletedDirs:0,errors:[],violations:i.violations,conflicts:[],message:`Protected deletion guard blocked cleanup for ${i.violations.length} path(s)`};n.debug(`cleanup delete execution started`,{filesToDelete:i.filesToDelete.length,dirsToDelete:i.dirsToDelete.length});let a=IS(n,i.errors);return n.debug(`cleanup delete execution complete`,{deletedFiles:i.deletedFiles,deletedDirs:i.deletedDirs,errors:a.length}),{deletedFiles:i.deletedFiles,deletedDirs:i.deletedDirs,errors:a,violations:[],conflicts:[]}}var US=class{name=`clean`;async execute(e){let{logger:t,outputPlugins:n,createCleanContext:r}=e;t.info(`running clean pipeline`,{command:`clean`});let i=await HS(n,r(!1),t);return i.violations.length>0||i.conflicts.length>0?{success:!1,filesAffected:0,dirsAffected:0,...i.message==null?{}:{message:i.message}}:(t.info(`clean complete`,{deletedFiles:i.deletedFiles,deletedDirs:i.deletedDirs}),{success:!0,filesAffected:i.deletedFiles,dirsAffected:i.deletedDirs})}},WS=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 sx(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,violations:c,excludedScanGlobs:l}=await VS(n,i);return c.length>0?(Vg(t,`dry-run-cleanup`,c),{success:!1,filesAffected:0,dirsAffected:0,message:`Protected deletion guard blocked cleanup for ${c.length} path(s)`}):(this.logDryRunFiles(o,t),this.logDryRunDirectories(s,t),t.info(`clean complete`,{dryRun:!0,filesAffected:o.length,dirsAffected:s.length,violations:0,excludedScanGlobs:l}),{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=u.isAbsolute(n)?n:u.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=u.isAbsolute(e)?e:u.resolve(e);t.info(`would delete directory`,{path:n,dryRun:!0})}}},GS=class{canHandle(e){return e.subcommand===`clean`}createCommand(e){return e.dryRun?new WS:new US}};const KS=[`workspaceDir`,`aindex.skills.src`,`aindex.skills.dist`,`aindex.commands.src`,`aindex.commands.dist`,`aindex.subAgents.src`,`aindex.subAgents.dist`,`aindex.rules.src`,`aindex.rules.dist`,`aindex.globalPrompt.src`,`aindex.globalPrompt.dist`,`aindex.workspacePrompt.src`,`aindex.workspacePrompt.dist`,`aindex.app.src`,`aindex.app.dist`,`aindex.ext.src`,`aindex.ext.dist`,`aindex.arch.src`,`aindex.arch.dist`,`logLevel`];function qS(e){return KS.includes(e)}function JS(e){return[`trace`,`debug`,`info`,`warn`,`error`].includes(e)}function YS(){return ag()}function XS(){let e=YS();if(!i.existsSync(e))return{};try{let t=i.readFileSync(e,`utf8`);return JSON.parse(t)}catch{return{}}}function ZS(e){let t=YS(),n=u.dirname(t);i.existsSync(n)||i.mkdirSync(n,{recursive:!0}),i.writeFileSync(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)}function QS(e,t,n){let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++){let t=r[e];if(t==null)continue;let n=i[t];(typeof n!=`object`||!n||Array.isArray(n))&&(i[t]={}),i=i[t]}let a=r.at(-1);a!=null&&(i[a]=n)}function $S(e,t){let n=t.split(`.`),r=e;for(let e of n){if(typeof r!=`object`||!r||Array.isArray(r))return;r=r[e]}return r}var eC=class{name=`config`;constructor(e){this.options=e}async execute(e){let{logger:t}=e;if(this.options.length===0)return t.error(ee({code:`CONFIG_COMMAND_ARGUMENTS_MISSING`,title:`Config command requires at least one key=value pair`,rootCause:b(`tnmsc config was invoked without any configuration assignments.`),exactFix:b("Run `tnmsc config key=value` with at least one supported configuration key."),possibleFixes:[b(`Use one of the supported keys: ${KS.join(`, `)}`)],details:{validKeys:[...KS]}})),t.info(`Usage: tnmsc config key=value`),t.info(`Valid keys: ${KS.join(`, `)}`),{success:!1,filesAffected:0,dirsAffected:0,message:`No options provided`};let n;try{n=XS()}catch(e){return{success:!1,filesAffected:0,dirsAffected:0,message:e instanceof Error?e.message:String(e)}}let r=[],i=[];for(let[e,a]of this.options){if(!qS(e)){r.push(`Invalid key: ${e}`),t.error(ee({code:`CONFIG_COMMAND_KEY_INVALID`,title:`Unsupported config key: ${e}`,rootCause:b(`The config command received "${e}", which is not a supported configuration key.`),exactFix:b(`Use one of the supported config keys and rerun the command.`),possibleFixes:[b(`Supported keys: ${KS.join(`, `)}`)],details:{key:e,validKeys:[...KS]}}));continue}if(e===`logLevel`&&!JS(a)){r.push(`Invalid logLevel value: ${a}`),t.error(ee({code:`CONFIG_COMMAND_LOG_LEVEL_INVALID`,title:`Unsupported logLevel value: ${a}`,rootCause:b(`The config command received "${a}" for logLevel, but tnmsc does not support that level.`),exactFix:b(`Set logLevel to one of: trace, debug, info, warn, or error.`),details:{key:e,value:a,validLevels:[`trace`,`debug`,`info`,`warn`,`error`]}}));continue}let o=$S(n,e);QS(n,e,a),o!==a&&i.push(`${e}=${a}`),t.info(`configuration updated`,{key:e,value:a})}if(i.length>0){try{ZS(n)}catch(e){return{success:!1,filesAffected:0,dirsAffected:0,message:e instanceof Error?e.message:String(e)}}t.info(`global config written`,{path:YS()})}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}}};const tC=`.tnmsc.json`,nC=`.aindex`;function rC(){return ag()}var iC=class{logger;constructor(e={}){this.logger=zx(`ConfigLoader`)}getSearchPaths(e=c.cwd()){let t=ng();if(!t.isWsl)return[ag()];if(this.logger.info(`wsl environment detected`,{effectiveHomeDir:t.effectiveHomeDir}),t.selectedGlobalConfigPath==null)throw Error(`WSL host config file not found under "${t.windowsUsersRoot}/*/${nC}/${tC}".`);return this.logger.info(`using wsl host global config`,{path:t.selectedGlobalConfigPath}),[ag()]}loadFromFile(e){let t=this.resolveTilde(e);try{if(!i.existsSync(t))return{config:{},source:null,found:!1};let e=i.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(D({code:`CONFIG_FILE_LOAD_FAILED`,title:`Failed to load config file`,operation:`read`,targetKind:`config file`,path:t,error:e})),{config:{},source:null,found:!1}}}load(e=c.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){let n;try{n=JSON.parse(e)}catch(e){throw e instanceof SyntaxError?Error(`Invalid JSON in ${t}: ${e.message}`):e}let r=Vb.safeParse(n);if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`);throw Error(`Config validation failed in ${t}:\n${i.join(`
|
|
228
|
+
`)}`)}mergeConfigs(e){if(e.length===0)return{};let t=e[0];return e.length===1&&t!=null?t:[...e].reverse().reduce((e,t)=>{let n=this.mergeAindex(e.aindex,t.aindex),r=this.mergeOutputScopeOptions(e.outputScopes,t.outputScopes),i=this.mergeFrontMatterOptions(e.frontMatter,t.frontMatter),a=this.mergeCleanupProtectionOptions(e.cleanupProtection,t.cleanupProtection),o=this.mergeWindowsOptions(e.windows,t.windows);return{...e,...t,...n==null?{}:{aindex:n},...r==null?{}:{outputScopes:r},...i==null?{}:{frontMatter:i},...a==null?{}:{cleanupProtection:a},...o==null?{}:{windows:o}}},{})}mergeAindex(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{dir:t.dir??e.dir,skills:{...e.skills,...t.skills},commands:{...e.commands,...t.commands},subAgents:{...e.subAgents,...t.subAgents},rules:{...e.rules,...t.rules},globalPrompt:{...e.globalPrompt,...t.globalPrompt},workspacePrompt:{...e.workspacePrompt,...t.workspacePrompt},app:{...e.app,...t.app},ext:{...e.ext,...t.ext},arch:{...e.arch,...t.arch}}}mergeOutputScopeTopics(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{...e,...t}}mergeOutputScopeOptions(e,t){if(e==null&&t==null)return;if(e==null)return t;if(t==null)return e;let n={};for(let[t,r]of Object.entries(e.plugins??{}))r!=null&&(n[t]={...r});for(let[e,r]of Object.entries(t.plugins??{})){let t=this.mergeOutputScopeTopics(n[e],r);t!=null&&(n[e]=t)}return Object.keys(n).length===0?{}:{plugins:n}}mergeFrontMatterOptions(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{...e,...t}}mergeCleanupProtectionOptions(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{rules:[...e.rules??[],...t.rules??[]]}}mergeWindowsOptions(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{...e,...t,...e.wsl2!=null||t.wsl2!=null?{wsl2:{...e.wsl2,...t.wsl2}}:{}}}resolveTilde(e){return e.startsWith(`~`)?og(e):e}};let aC=null;function oC(e){return(e||!aC)&&(aC=new iC(e)),aC}function sC(e){return oC().load(e)}function cC(){let e=zx(`ConfigLoader`),t;try{t=ag()}catch(t){let n=t instanceof Error?t.message:String(t);return e.error(O({code:`GLOBAL_CONFIG_PATH_RESOLUTION_FAILED`,title:`Failed to resolve global config path`,reason:b(n),configPath:`${Dh}/${Oh}`,exactFix:b(`Ensure the required global config exists in the expected runtime-specific location before running tnmsc again.`)})),{valid:!1,exists:!1,errors:[n],shouldExit:!0}}if(!i.existsSync(t)){let n=`Global config not found at ${t}. Please create it manually.`;return e.error(O({code:`GLOBAL_CONFIG_MISSING`,title:`Global config file is missing`,reason:b(`tnmsc could not find the required global config file at "${t}".`),configPath:t,exactFix:b(`Create the global config file manually before running tnmsc again.`),possibleFixes:[b("Initialize the file with a valid JSON object, for example `{}`.")]})),{valid:!1,exists:!1,errors:[n],shouldExit:!0}}let n;try{n=i.readFileSync(t,`utf8`)}catch(n){let r=n instanceof Error?n.message:String(n);return e.error(D({code:`GLOBAL_CONFIG_READ_FAILED`,title:`Failed to read global config file`,operation:`read`,targetKind:`global config file`,path:t,error:r})),{valid:!1,exists:!0,errors:[`Failed to read config: ${r}`],shouldExit:!0}}let r;try{r=JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return e.error(O({code:`GLOBAL_CONFIG_JSON_INVALID`,title:`Global config contains invalid JSON`,reason:b(`tnmsc could not parse the JSON in "${t}".`,`Parser error: ${r}`),configPath:t,exactFix:b(`Fix the JSON syntax in the global config file so it parses as a single JSON object.`),possibleFixes:[b(`Validate the file with a JSON parser and remove trailing commas or invalid tokens.`)]})),{valid:!1,exists:!0,errors:[`Invalid JSON: ${r}`],shouldExit:!0}}if(typeof r!=`object`||!r||Array.isArray(r))return e.error(O({code:`GLOBAL_CONFIG_NOT_OBJECT`,title:`Global config must be a JSON object`,reason:b(`tnmsc parsed "${t}" successfully, but the top-level value is not a JSON object.`),configPath:t,exactFix:b("Replace the top-level JSON value with an object like `{}` or a valid config object.")})),{valid:!1,exists:!0,errors:[`Config must be a JSON object`],shouldExit:!0};let a=Vb.safeParse(r);if(!a.success){let n=a.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`);for(let r of n)e.error(O({code:`GLOBAL_CONFIG_VALIDATION_FAILED`,title:`Global config validation failed`,reason:S(r),configPath:t,exactFix:b(`Update the invalid config field so it matches the tnmsc schema.`),possibleFixes:[b(`Compare the field name and value against the current config schema or examples.`)],details:{validationError:r}}));return{valid:!1,exists:!0,errors:n,shouldExit:!0}}return{valid:!0,exists:!0,errors:[],shouldExit:!1}}var lC=class{name=`config-show`;async execute(e){let{logger:t}=e,n=new iC,r=n.load(),i=r.sources.map(e=>({path:e,layer:`global`,config:n.loadFromFile(e).config})),a={merged:r.config,sources:i};return c.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))`}}},uC=class{canHandle(e){return e.subcommand===`config`}createCommand(e){if(e.showFlag)return new lC;let t=[];for(let n of e.positional){let e=n.indexOf(`=`);e>0&&t.push([n.slice(0,e),n.slice(e+1)])}return new eC([...e.setOption,...t])}},dC=class extends Error{};function fC(e){return e?.fs??i}function pC(e){return e?.spawnSync??h}function mC(e){return e?.platform??c.platform}function hC(e){return e?.effectiveHomeDir??rg()}function gC(e){return e?.nativeHomeDir??ng().nativeHomeDir}function _C(e){return e?.isWsl??ng().isWsl}function vC(e){return e===`win32`?u.win32:u.posix}function yC(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))]}function bC(e){let t=e?.windows?.wsl2?.instances;return yC(t==null?[]:Array.isArray(t)?t:[t])}function xC(e,t){if(!t.startsWith(`/`))throw Error(`WSL instance "${e}" returned a non-absolute home path: "${t}".`);let n=t.split(`/`).filter(e=>e.length>0);return u.win32.join(`\\\\wsl$\\${e}`,...n)}function SC(e,t,n){let r=vC(n),i=r.normalize(t),a=r.normalize(e),o=r.relative(i,a);if(o.length===0||o.startsWith(`..`)||r.isAbsolute(o))throw Error(`WSL mirror source "${e}" must stay under the host home directory "${t}".`);return o.split(/[\\/]+/u).filter(e=>e.length>0)}function CC(e){if(typeof e==`string`)return e;if(!_.isBuffer(e)||e.length===0)return``;let t=e.length>=2&&e[0]===255&&e[1]===254,n=e.length>=2&&e[0]===254&&e[1]===255;if(t||n)return e.toString(`utf16le`).replace(/^\uFEFF/u,``);let r=e.toString(`utf8`);return r.includes(`\0`)?e.toString(`utf16le`).replace(/^\uFEFF/u,``):r}function wC(e){return CC(e).replaceAll(`\0`,``)}function TC(e){let{error:t}=e;if(!(typeof t!=`object`||!t))return`code`in t&&typeof t.code==`string`?t.code:void 0}function EC(e){if(TC(e)===`ENOENT`)return`wsl.exe is not available on PATH.`;let t=[e.stderr,e.stdout].map(e=>wC(e).trim()).filter(e=>e.length>0).join(`
|
|
229
|
+
`).toLowerCase();if(t.length!==0)return[`windows subsystem for linux has no installed distributions`,`windows subsystem for linux has not been enabled`,`the windows subsystem for linux optional component is not enabled`,`wsl is not installed`,`run 'wsl.exe --install'`,`run "wsl.exe --install"`,`wslregisterdistribution failed with error: 0x8007019e`].some(e=>t.includes(e))?t:void 0}async function DC(e,t){let n=await Promise.all(e.map(async e=>e.declareWslMirrorFiles==null?[]:e.declareWslMirrorFiles(t))),r=new Map;for(let e of n)for(let t of e)r.set(t.sourcePath,t);return[...r.values()]}function OC(e){return{platform:`win32`,isWsl:!1,nativeHomeDir:e,effectiveHomeDir:e,globalConfigCandidates:[],windowsUsersRoot:``,expandedEnv:{HOME:e,USERPROFILE:e}}}function kC(e,t){return{platform:`linux`,isWsl:!0,nativeHomeDir:t,effectiveHomeDir:e,globalConfigCandidates:[],windowsUsersRoot:``,expandedEnv:{HOME:e,USERPROFILE:e}}}function AC(e){return yC(e.split(/\r?\n/u).map(e=>e.replace(/^\*/u,``).trim()).filter(e=>e.length>0))}function jC(e,t){let n=pC(t)(`wsl.exe`,[`--list`,`--quiet`],{shell:!1,windowsHide:!0}),r=EC(n);if(r!=null)throw new dC(r);if(n.status!==0){let e=wC(n.stderr).trim();throw Error(`Failed to enumerate WSL instances. ${e.length>0?e:`wsl.exe returned a non-zero exit status.`}`)}let i=AC(wC(n.stdout));return e.info(`discovered wsl instances`,{instances:i}),i}function MC(e,t,n){let r=bC(e);return r.length>0?r:jC(t,n)}function NC(e,t,n){if(e.scope!==`global`)return;let r=vC(n).normalize(e.path),i;try{i=SC(r,t,n)}catch{return}let[a]=i;if(a?.startsWith(`.`))return{kind:`generated`,sourcePath:r,relativePathSegments:i}}function PC(e,t,n){if(e==null)return[];let r=new Map;for(let i of e.values())for(let e of i){let i=NC(e,t,n);i!=null&&r.set(i.sourcePath,i)}return[...r.values()]}function FC(e,t,n,r){let i=vC(r).normalize(og(e.sourcePath,t));return{kind:`declared`,sourcePath:i,relativePathSegments:SC(i,n,r)}}function IC(e,t,n,r,i){let a=new Map,o=[];for(let t of e)try{let e=FC(t,n,r,i);a.set(e.sourcePath,e)}catch(e){o.push(e instanceof Error?e.message:String(e))}for(let e of t)a.set(e.sourcePath,e);return{sources:[...a.values()],errors:o}}function LC(e,t,n){if(mC(n)!==`win32`)return[];let r=MC(e,t,n);if(r.length===0)return[];let i=fC(n),a=pC(n),o=[];for(let e of r){let n=a(`wsl.exe`,[`-d`,e,`sh`,`-lc`,`printf %s "$HOME"`],{shell:!1,windowsHide:!0}),r=EC(n);if(r!=null)throw new dC(r);if(n.status!==0){let t=wC(n.stderr).trim();throw Error(`Failed to probe WSL instance "${e}". ${t.length>0?t:`wsl.exe returned a non-zero exit status.`}`)}let s=wC(n.stdout).trim();if(s.length===0)throw Error(`WSL instance "${e}" returned an empty home directory.`);let c=xC(e,s);if(!i.existsSync(c))throw Error(`WSL instance "${e}" home directory is unavailable at "${c}".`);t.info(`resolved wsl instance home`,{instance:e,linuxHomeDir:s,windowsHomeDir:c}),o.push({instance:e,linuxHomeDir:s,windowsHomeDir:c})}return o}function RC(e,t,n){let r=fC(n),i=u.posix.normalize(gC(n)),a=0,o=[],s=[];for(let n of e){if(n.kind===`declared`&&!r.existsSync(n.sourcePath)){let e=`Skipping missing WSL mirror source file: ${n.sourcePath}`;o.push(e),t.logger.warn({code:`WSL_MIRROR_SOURCE_MISSING`,title:`WSL mirror source file is missing`,rootCause:[e],exactFix:[`Create the source file on the Windows host or remove the WSL mirror declaration before retrying tnmsc.`]});continue}let e=u.posix.join(i,...n.relativePathSegments);try{if(t.dryRun===!0)t.logger.info(`would mirror host config into wsl runtime home`,{sourcePath:n.sourcePath,targetPath:e,dryRun:!0});else{let i=r.readFileSync(n.sourcePath);r.mkdirSync(u.posix.dirname(e),{recursive:!0}),r.writeFileSync(e,i),t.logger.info(`mirrored host config into wsl runtime home`,{sourcePath:n.sourcePath,targetPath:e})}a+=1}catch(t){s.push(`Failed to mirror "${n.sourcePath}" into the current WSL home at "${e}": ${t instanceof Error?t.message:String(t)}`)}}return{mirroredFiles:a,warnings:o,errors:s}}async function zC(e,t,n,r){let i=mC(n),a=i===`linux`&&_C(n);if(i!==`win32`&&!a)return{mirroredFiles:0,warnings:[],errors:[]};let o=a?u.posix.normalize(hC(n)):u.win32.normalize(hC(n)),s=await DC(e,t),c=PC(r,o,i);if(s.length===0&&c.length===0)return{mirroredFiles:0,warnings:[],errors:[]};let l=t.pluginOptions??{},d=a?u.posix.normalize(gC(n)):void 0,f=IC(s,c,a?kC(o,d??o):OC(o),o,i);if(a){if(f.sources.length===0||d==null||o===d)return{mirroredFiles:0,warnings:[],errors:[...f.errors]};let e=RC(f.sources,t,n);return{mirroredFiles:e.mirroredFiles,warnings:[...e.warnings],errors:[...f.errors,...e.errors]}}let p;try{p=LC(l,t.logger,n)}catch(e){return e instanceof dC?(t.logger.info(`wsl is unavailable, skipping WSL mirror sync`,{reason:e.message}),{mirroredFiles:0,warnings:[],errors:[]}):{mirroredFiles:0,warnings:[],errors:[e instanceof Error?e.message:String(e)]}}if(p.length===0||f.sources.length===0)return{mirroredFiles:0,warnings:[],errors:[...f.errors]};let m=fC(n),h=0,g=[],_=[...f.errors];for(let e of f.sources){if(e.kind===`declared`&&!m.existsSync(e.sourcePath)){let n=`Skipping missing WSL mirror source file: ${e.sourcePath}`;g.push(n),t.logger.warn({code:`WSL_MIRROR_SOURCE_MISSING`,title:`WSL mirror source file is missing`,rootCause:[n],exactFix:[`Create the source file on the Windows host or remove the WSL mirror declaration before retrying tnmsc.`]});continue}let{relativePathSegments:n,sourcePath:r}=e;for(let e of p){let i=u.win32.join(e.windowsHomeDir,...n);try{if(t.dryRun===!0)t.logger.info(`would mirror windows config into wsl`,{instance:e.instance,sourcePath:r,targetPath:i,dryRun:!0});else{let n=m.readFileSync(r);m.mkdirSync(u.win32.dirname(i),{recursive:!0}),m.writeFileSync(i,n),t.logger.info(`mirrored windows config into wsl`,{instance:e.instance,sourcePath:r,targetPath:i})}h+=1}catch(t){_.push(`Failed to mirror "${r}" into WSL instance "${e.instance}" at "${i}": ${t instanceof Error?t.message:String(t)}`)}}}return{mirroredFiles:h,warnings:g,errors:_}}var BC=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 ax(n,i),o=await ox(n,i,a),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});let l=await zC(n,i,void 0,a);return l.errors.length>0?{success:!1,filesAffected:s,dirsAffected:c,message:l.errors.join(`
|
|
230
|
+
`)}:(s+=l.mirroredFiles,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`})}},VC=class{canHandle(e){return e.subcommand===`dry-run`}createCommand(e){return new BC}},HC=class{name=`execute`;async execute(e){let{logger:t,outputPlugins:n,createCleanContext:r,createWriteContext:i}=e;t.info(`started`,{command:`execute`});let a=i(!1),o=await ax(n,a),s=await HS(n,r(!1),t,o);if(s.violations.length>0||s.conflicts.length>0)return{success:!1,filesAffected:0,dirsAffected:0,...s.message==null?{}:{message:s.message}};t.info(`cleanup complete`,{deletedFiles:s.deletedFiles,deletedDirs:s.deletedDirs});let c=await ox(n,a,o),l=0,u=0,d=[];for(let e of c.values()){l+=e.files.length,u+=e.dirs.length;for(let t of e.files)t.success||d.push(t.error?.message??`Failed to write ${t.path}`)}if(d.length>0)return{success:!1,filesAffected:l,dirsAffected:u,message:d.join(`
|
|
231
|
+
`)};let f=await zC(n,a,void 0,o);return f.errors.length>0?{success:!1,filesAffected:l,dirsAffected:u,message:f.errors.join(`
|
|
232
|
+
`)}:(l+=f.mirroredFiles,t.info(`complete`,{command:`execute`,pluginCount:c.size}),{success:!0,filesAffected:l,dirsAffected:u})}},UC=class{canHandle(e){return!0}createCommand(e){return new HC}};function WC(){return`2026.10328.106`}var GC=class{name=`version`;async execute(e){return e.logger.info(`tnmsc v${WC()}`),{success:!0,filesAffected:0,dirsAffected:0,message:`Version displayed`}}};const KC=`tnmsc`,qC=`
|
|
233
|
+
${KC} v${WC()} - Memory Sync CLI
|
|
234
234
|
|
|
235
235
|
Synchronize AI memory and configuration files across projects.
|
|
236
236
|
|
|
237
237
|
USAGE:
|
|
238
|
-
${
|
|
239
|
-
${
|
|
240
|
-
${
|
|
241
|
-
${
|
|
242
|
-
${
|
|
243
|
-
${
|
|
244
|
-
${
|
|
245
|
-
${
|
|
238
|
+
${KC} Run the sync pipeline (default)
|
|
239
|
+
${KC} help Show this help message
|
|
240
|
+
${KC} version Show version information
|
|
241
|
+
${KC} init Deprecated; no longer initializes aindex
|
|
242
|
+
${KC} dry-run Preview what would be written
|
|
243
|
+
${KC} clean Remove all generated files
|
|
244
|
+
${KC} clean --dry-run Preview what would be cleaned
|
|
245
|
+
${KC} config key=value Set configuration value
|
|
246
246
|
|
|
247
247
|
SUBCOMMANDS:
|
|
248
248
|
help Show this help message
|
|
@@ -253,10 +253,10 @@ SUBCOMMANDS:
|
|
|
253
253
|
config Set configuration values in global config file (~/.aindex/.tnmsc.json)
|
|
254
254
|
|
|
255
255
|
ALIASES:
|
|
256
|
-
${
|
|
257
|
-
${
|
|
258
|
-
${
|
|
259
|
-
${
|
|
256
|
+
${KC} --help, ${KC} -h Same as '${KC} help'
|
|
257
|
+
${KC} --version, ${KC} -v Same as '${KC} version'
|
|
258
|
+
${KC} clean -n Same as '${KC} clean --dry-run'
|
|
259
|
+
${KC} config key=value Set config value in global config file
|
|
260
260
|
|
|
261
261
|
LOG LEVEL OPTIONS:
|
|
262
262
|
--trace Most verbose output
|
|
@@ -282,31 +282,31 @@ CONFIG OPTIONS:
|
|
|
282
282
|
aindex.arch.src, aindex.arch.dist
|
|
283
283
|
|
|
284
284
|
Examples:
|
|
285
|
-
${
|
|
286
|
-
${
|
|
287
|
-
${
|
|
285
|
+
${KC} config workspaceDir=~/my-project
|
|
286
|
+
${KC} config aindex.skills.src=skills
|
|
287
|
+
${KC} config logLevel=debug
|
|
288
288
|
|
|
289
289
|
CONFIGURATION:
|
|
290
290
|
Configure via plugin.config.ts in your project root.
|
|
291
291
|
See documentation for detailed configuration options.
|
|
292
|
-
`.trim();var
|
|
293
|
-
`)=>{if(p(u.dirname(e)),i.existsSync(e)){f.has(e)||(f.add(e),c.push(e),n?.debug(`file exists`,{path:e}));return}i.writeFileSync(e,t,`utf8`),o.push(e),n?.info(`created file`,{path:e})};if(p(e),r!=null){for(let[t,n]of Object.entries(r))if(!(t===`dir`||typeof n!=`object`||!n))for(let t of[n.src,n.dist]){let n=u.join(e,t);
|
|
292
|
+
`.trim();var JC=class{name=`help`;async execute(e){return e.logger.info(qC),{success:!0,filesAffected:0,dirsAffected:0,message:`Help displayed`}}},YC=class{priority=Wx.Flags;canHandle(e){return e.helpFlag||e.subcommand===`help`}createCommand(e){return new JC}},XC=class{name=`init`;async execute(e){let{logger:t}=e;return t.warn(ee({code:`INIT_COMMAND_DEPRECATED`,title:`The init command is deprecated`,rootCause:b("`tnmsc init` no longer initializes aindex content or project definitions."),exactFix:b("Maintain the target-relative definitions manually under `~/workspace/aindex/public/`."),possibleFixes:[b("Run `tnmsc help` to find a supported replacement command for your workflow.")],details:{command:`init`}})),{success:!1,filesAffected:0,dirsAffected:0,message:"`tnmsc init` is deprecated and no longer initializes aindex. Maintain the public target-relative definitions manually under `~/workspace/aindex/public/`."}}},ZC=class{canHandle(e){return e.subcommand===`init`}createCommand(e){return new XC}},QC=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:`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 c.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)`}}},$C=class{canHandle(e){return e.subcommand===`plugins`}createCommand(e){return new QC}},ew=class{name=`unknown`;constructor(e){this.unknownCmd=e}async execute(e){return e.logger.error(ee({code:`UNKNOWN_COMMAND`,title:`Unknown tnmsc command: ${this.unknownCmd}`,rootCause:b(`tnmsc does not recognize the "${this.unknownCmd}" subcommand.`),exactFix:b("Run `tnmsc help` and invoke one of the supported commands."),possibleFixes:[b(`Check the command spelling and remove unsupported aliases or flags.`)],details:{command:this.unknownCmd}})),e.logger.info(`run "tnmsc help" for available commands`),{success:!1,filesAffected:0,dirsAffected:0,message:`Unknown command: ${this.unknownCmd}`}}},tw=class{priority=Wx.Unknown;canHandle(e){return e.unknownCommand!=null}createCommand(e){return e.unknownCommand==null?new ew(``):new ew(e.unknownCommand)}},nw=class{priority=Wx.Flags;canHandle(e){return e.versionFlag||e.subcommand===`version`}createCommand(e){return new GC}};const rw=new Set([`help`,`version`,`init`,`dry-run`,`clean`,`config`,`plugins`]),iw=new Map([[`--trace`,`trace`],[`--debug`,`debug`],[`--info`,`info`],[`--warn`,`warn`],[`--error`,`error`]]),aw=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4]]);function ow(e){let t=[...e],n=t[0];n!=null&&sw(n)&&t.shift();let r=t[0];return r!=null&&cw(r)&&t.shift(),t}function sw(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 cw(e){return/\.(?:m?[jt]s|cjs)$/.test(e)||/[/\\]/.test(e)&&!e.startsWith(`-`)?!0:/^(?:@[\w-]+\/)?[\w-]+$/.test(e)&&!e.startsWith(`-`)}function lw(e,t){if(e==null)return t;let n=aw.get(e)??4;return(aw.get(t)??4)<n?t:e}function uw(e){let t={subcommand:void 0,helpFlag:!1,versionFlag:!1,dryRun:!1,jsonFlag:!1,showFlag:!1,logLevel:void 0,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=iw.get(a);if(o!=null){t.logLevel=lw(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,rw.has(i)?t.subcommand=i:t.unknownCommand=i;continue}t.positional.push(i)}}return t}let dw;function fw(){let e=new Gx;return e.register(new nw),e.register(new YC),e.register(new tw),e.registerWithPriority(new ZC,Wx.Subcommand),e.registerWithPriority(new VC,Wx.Subcommand),e.registerWithPriority(new GS,Wx.Subcommand),e.registerWithPriority(new $C,Wx.Subcommand),e.registerWithPriority(new uC,Wx.Subcommand),e.registerWithPriority(new UC,Wx.Subcommand),e}function pw(){return dw??=fw(),dw}function mw(e){return pw().resolve(e)}const hw=[`IntelliJIdea`,`WebStorm`,`RustRover`,`PyCharm`,`PyCharmCE`,`PhpStorm`,`GoLand`,`CLion`,`DataGrip`,`RubyMine`,`Rider`,`DataSpell`,`Aqua`];function gw(e){return hw.some(t=>e.startsWith(t))}function _w(e){let t=u.join(cS(),`JetBrains`);try{return i.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&gw(e.name)).map(e=>u.join(t,e.name,`aia`,`codex`))}catch(n){return e.debug(D({code:`JETBRAINS_CODEX_DIRECTORY_SCAN_SKIPPED`,title:`JetBrains Codex directories are unavailable`,operation:`scan`,targetKind:`JetBrains IDE directory`,path:t,error:n})),[]}}function vw(e){return{jetbrainsCodexDirs:_w(e)}}var yw=class{logger;args;outputPlugins=[];runtimeTargets;constructor(...e){this.args=uw(ow(e.filter(e=>e!=null)));let t=this.args.logLevel;t!=null&&Vx(t),this.logger=zx(`PluginPipeline`,t),this.logger.debug(`initialized`,{args:this.args})}registerOutputPlugins(e){return this.outputPlugins.push(...e),this}async run(e){let{context:t,outputPlugins:n,userConfigOptions:r}=e;this.registerOutputPlugins([...n]);let i=mw(this.args);this.args.jsonFlag&&(Vx(`silent`),new Set([`config-show`,`plugins`]).has(i.name)||(i=new Hx(i)));let a=this.createCommandContext(t,r);return i.execute(a)}createCommandContext(e,t){return{logger:this.logger,outputPlugins:this.outputPlugins,collectedOutputContext:e,userConfigOptions:t,createCleanContext:n=>this.createCleanContext(e,t,n),createWriteContext:n=>this.createWriteContext(e,t,n)}}createCleanContext(e,t,n){return{logger:this.logger,collectedOutputContext:e,pluginOptions:t,runtimeTargets:this.getRuntimeTargets(),dryRun:n}}createWriteContext(e,t,n){return{logger:this.logger,collectedOutputContext:e,pluginOptions:t,runtimeTargets:this.getRuntimeTargets(),dryRun:n,registeredPluginNames:this.outputPlugins.map(e=>e.name)}}getRuntimeTargets(){return this.runtimeTargets??=vw(this.logger),this.runtimeTargets}};function bw(e,t){let n=u.join(e,`.git`),r=i.existsSync(n);return r?t?.info(`version control detected`,{path:n}):t?.warn(ee({code:`AINDEX_VERSION_CONTROL_MISSING`,title:`Aindex root is not under version control`,rootCause:b(`tnmsc did not find a .git directory under "${e}".`),exactFix:b(`Initialize git in "${e}" or place the aindex inside an existing git repository.`),possibleFixes:[b("Run `git init` in the aindex root if the directory should be versioned.")],details:{rootPath:e,gitPath:n}})),{hasGit:r,gitPath:n}}function xw(e){return u.extname(e).length>0}function Sw(e,t={}){let{logger:n,config:r}=t,a=[],o=[],s=[],c=[],l=new Set,d=new Set,f=new Set,p=t=>{if(i.existsSync(t)){d.has(t)||(d.add(t),s.push(t),n?.debug(`directory exists`,{path:t}));return}i.mkdirSync(t,{recursive:!0});let r=t;for(;!l.has(r)&&(l.add(r),a.push(r),n?.info(`created directory`,{path:r}),r!==e);)r=u.dirname(r)},m=(e,t=`# Generated by tnmsc init
|
|
293
|
+
`)=>{if(p(u.dirname(e)),i.existsSync(e)){f.has(e)||(f.add(e),c.push(e),n?.debug(`file exists`,{path:e}));return}i.writeFileSync(e,t,`utf8`),o.push(e),n?.info(`created file`,{path:e})};if(p(e),r!=null){for(let[t,n]of Object.entries(r))if(!(t===`dir`||typeof n!=`object`||!n))for(let t of[n.src,n.dist]){let n=u.join(e,t);xw(t)?m(n):p(n)}}return{success:!0,rootPath:e,createdDirs:a,createdFiles:o,existedDirs:s,existedFiles:c}}function Cw(e){return nh.includes(e)}function ww(e){return nh.map(t=>Dw(e.aindex,t))}function Tw(e,t){return Dw(e.aindex,t)}function Ew(e){let t=new Map;for(let n of e){let e=t.get(n.projectName);e==null?t.set(n.projectName,[n]):e.push(n)}return Array.from(t.entries(),([e,t])=>({projectName:e,refs:[...t].sort((e,t)=>e.seriesName.localeCompare(t.seriesName))})).filter(e=>new Set(e.refs.map(e=>e.seriesName)).size>1).sort((e,t)=>e.projectName.localeCompare(t.projectName))}function Dw(e,t){return{name:t,src:e[t].src,dist:e[t].dist}}var Ow=class extends Hg{constructor(){super(`MarkdownWhitespaceCleanupEffectInputCapability`),this.registerEffect(`markdown-whitespace-cleanup`,this.cleanupWhitespace.bind(this),30)}async cleanupWhitespace(e){let{fs:t,path:n,aindexDir:r,dryRun:i,logger:a,userConfigOptions:o}=e,s=[],c=[],l=[],u=ww(o).map(e=>n.join(r,e.src)),d=[n.join(r,`src`),...u,n.join(r,`dist`)];for(let n of d){if(!t.existsSync(n)){a.debug({action:`whitespace-cleanup`,message:`Directory does not exist, skipping`,dir:n});continue}this.processDirectory(e,n,s,c,l,i??!1)}let f=l.length>0;return{success:!f,description:i?`Would modify ${s.length} files, skip ${c.length} files`:`Modified ${s.length} files, skipped ${c.length} files`,modifiedFiles:s,skippedFiles:c,...f&&{error:Error(`${l.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(D({code:`WHITESPACE_CLEANUP_DIRECTORY_READ_FAILED`,title:`Whitespace cleanup could not read a directory`,operation:`read`,targetKind:`cleanup directory`,path:t,error:e}));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(D({code:`WHITESPACE_CLEANUP_FILE_PROCESS_FAILED`,title:`Whitespace cleanup could not process a markdown file`,operation:`process`,targetKind:`markdown file`,path:t,error:e}))}}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
|
|
294
294
|
`)?`\r
|
|
295
295
|
`:`
|
|
296
|
-
`}collect(e){return{}}};const iw=[`skills`,`commands`,`agents`,`app`];var aw=class extends Vg{constructor(){super(`OrphanFileCleanupEffectInputCapability`),this.registerEffect(`orphan-file-cleanup`,this.cleanupOrphanFiles.bind(this),20)}buildProtectedDeletionGuard(e){return Pg({workspaceDir:e.workspaceDir,aindexDir:e.aindexDir,rules:[...jg(e.userConfigOptions,e.aindexDir,{workspaceDir:e.workspaceDir}),...(e.userConfigOptions.cleanupProtection?.rules??[]).map(e=>({path:e.path,protectionMode:e.protectionMode,reason:e.reason??`configured cleanup protection rule`,source:`configured-cleanup-protection`,matcher:e.matcher??`path`}))]})}buildDeletionPlan(e,t,n){let r=[],i=[],a=[];for(let o of iw){let s=e.path.join(t,o);e.fs.existsSync(s)&&e.fs.statSync(s).isDirectory()&&this.collectDirectoryPlan(e,s,o,n[o],r,i,a)&&i.push(s)}return{filesToDelete:r,dirsToDelete:i,errors:a}}async cleanupOrphanFiles(e){let{fs:t,path:n,aindexDir:r,logger:i,userConfigOptions:a,dryRun:o}=e,s=n.join(r,`dist`);if(!t.existsSync(s))return i.debug({action:`orphan-cleanup`,message:`dist/ directory does not exist, skipping`,distDir:s}),{success:!0,description:`dist/ directory does not exist, nothing to clean`,deletedFiles:[],deletedDirs:[]};let c=a.aindex,l={skills:c?.skills?.src??`skills`,commands:c?.commands?.src??`commands`,agents:c?.subAgents?.src??`subagents`,app:c?.app?.src??`app`},u=this.buildDeletionPlan(e,s,l),d=this.buildProtectedDeletionGuard(e),f=Rg(u.filesToDelete,d),p=Rg(u.dirsToDelete,d),m=qx(f.safePaths,p.safePaths),h=[...f.violations,...p.violations].sort((e,t)=>e.targetPath.localeCompare(t.targetPath));if(h.length>0)return{success:!1,description:`Protected deletion guard blocked orphan cleanup for ${h.length} path(s)`,deletedFiles:[],deletedDirs:[],error:new og(`orphan-file-cleanup`,h)};if(o)return{success:!0,description:`Would delete ${m.files.length} files and ${m.dirs.length} directories`,deletedFiles:[...m.files],deletedDirs:[...m.dirs]};let g=[...u.errors];i.debug(`orphan cleanup delete execution started`,{filesToDelete:m.files.length,dirsToDelete:m.dirs.length});let _=await sS({files:m.files,dirs:m.dirs});for(let e of _.fileErrors){let t=e.error instanceof Error?e.error:Error(String(e.error));g.push({path:e.path,error:t}),i.warn(D({code:`ORPHAN_CLEANUP_FILE_DELETE_FAILED`,title:`Orphan cleanup could not delete a file`,operation:`delete`,targetKind:`orphan file`,path:e.path,error:t}))}for(let e of _.dirErrors){let t=e.error instanceof Error?e.error:Error(String(e.error));g.push({path:e.path,error:t}),i.warn(D({code:`ORPHAN_CLEANUP_DIRECTORY_DELETE_FAILED`,title:`Orphan cleanup could not delete a directory`,operation:`delete`,targetKind:`orphan directory`,path:e.path,error:t}))}i.debug(`orphan cleanup delete execution complete`,{deletedFiles:_.deletedFiles.length,deletedDirs:_.deletedDirs.length,errors:g.length});let v=g.length>0;return{success:!v,description:`Deleted ${_.deletedFiles.length} files and ${_.deletedDirs.length} directories`,deletedFiles:[..._.deletedFiles],deletedDirs:[..._.deletedDirs],...v&&{error:Error(`${g.length} errors occurred during cleanup`)}}}collectDirectoryPlan(e,t,n,r,i,a,o){let{fs:s,path:c,aindexDir:l,logger:u}=e,d;try{d=s.readdirSync(t,{withFileTypes:!0})}catch(e){return o.push({path:t,error:e}),u.warn(D({code:`ORPHAN_CLEANUP_DIRECTORY_READ_FAILED`,title:`Orphan cleanup could not read a directory`,operation:`read`,targetKind:`dist cleanup directory`,path:t,error:e})),!1}let f=!1;for(let s of d){let u=c.join(t,s.name);if(s.isDirectory()){this.collectDirectoryPlan(e,u,n,r,i,a,o)?a.push(u):f=!0;continue}if(!s.isFile()){f=!0;continue}this.isOrphanFile(e,u,n,r,l)?i.push(u):f=!0}return!f}isOrphanFile(e,t,n,r,i){let{fs:a,path:o}=e,s=o.basename(t),c=s.endsWith(`.mdx`),l=o.join(i,`dist`,n),u=o.relative(l,t),d=o.dirname(u),f=s.replace(/\.mdx$/,``);return c?!this.getPossibleSourcePaths(o,i,n,r,f,d).some(e=>a.existsSync(e)):!a.existsSync(o.join(i,r,u))}getPossibleSourcePaths(e,t,n,r,i,a){switch(n){case`skills`:{let n=(a===`.`?[i]:a.split(e.sep))[0]??i,o=a===`.`?``:a.slice(n.length+1);return o===``?[...gx.map(i=>e.join(t,r,n,`SKILL${i}`)),...gx.map(i=>e.join(t,r,n,`skill${i}`))]:gx.map(a=>e.join(t,r,n,o,`${i}${a}`))}case`commands`:case`agents`:case`app`:return a===`.`?gx.map(n=>e.join(t,r,`${i}${n}`)):gx.map(n=>e.join(t,r,a,`${i}${n}`));default:return[]}}collect(e){return{}}},ow=class extends Vg{constructor(){super(`SkillDistCleanupEffectInputCapability`),this.registerEffect(`skill-dist-cleanup`,this.cleanupDistSkillArtifacts.bind(this),10)}async cleanupDistSkillArtifacts(e){let{fs:t,logger:n,userConfigOptions:r,aindexDir:i,dryRun:a}=e,o=this.resolveAindexPath(r.aindex.skills.src,i),s=this.resolveAindexPath(r.aindex.skills.dist,i);if(!t.existsSync(s))return n.debug({action:`skill-dist-cleanup`,message:`dist skills directory does not exist, skipping`,srcSkillsDir:o,distSkillsDir:s}),{success:!0,description:`dist skills directory does not exist, nothing to clean`,deletedFiles:[],deletedDirs:[]};let c=this.buildCleanupPlan(e,s),l=qx(c.filesToDelete,c.dirsToDelete);if(a)return{success:!0,description:`Would delete ${l.files.length} files and ${l.dirs.length} directories`,deletedFiles:[...l.files],deletedDirs:[...l.dirs]};let u=[...c.errors];n.debug(`skill dist cleanup delete execution started`,{filesToDelete:l.files.length,dirsToDelete:l.dirs.length});let d=await sS({files:l.files,dirs:l.dirs});for(let e of d.fileErrors){let t=e.error instanceof Error?e.error:Error(String(e.error));u.push({path:e.path,error:t}),n.warn(D({code:`SKILL_DIST_CLEANUP_FILE_DELETE_FAILED`,title:`Skill dist cleanup could not delete a file`,operation:`delete`,targetKind:`skill dist file`,path:e.path,error:t}))}for(let e of d.dirErrors){let t=e.error instanceof Error?e.error:Error(String(e.error));u.push({path:e.path,error:t}),n.warn(D({code:`SKILL_DIST_CLEANUP_DIRECTORY_DELETE_FAILED`,title:`Skill dist cleanup could not delete a directory`,operation:`delete`,targetKind:`skill dist directory`,path:e.path,error:t}))}n.debug(`skill dist cleanup delete execution complete`,{deletedFiles:d.deletedFiles.length,deletedDirs:d.deletedDirs.length,errors:u.length});let f=u.length>0;return{success:!f,description:`Deleted ${d.deletedFiles.length} files and ${d.deletedDirs.length} directories`,deletedFiles:[...d.deletedFiles],deletedDirs:[...d.deletedDirs],...f&&{error:Error(`${u.length} errors occurred during cleanup`)}}}buildCleanupPlan(e,t){let n=[],r=[],i=[];return this.collectCleanupPlan(e,t,n,r,i)&&r.push(t),{filesToDelete:n,dirsToDelete:r,errors:i}}collectCleanupPlan(e,t,n,r,i){let{fs:a,path:o,logger:s}=e,c;try{c=a.readdirSync(t,{withFileTypes:!0})}catch(e){return i.push({path:t,error:e}),s.warn(D({code:`SKILL_DIST_CLEANUP_DIRECTORY_READ_FAILED`,title:`Skill dist cleanup could not read a directory`,operation:`read`,targetKind:`skill dist directory`,path:t,error:e})),!1}let l=!1;for(let a of c){let s=o.join(t,a.name);if(a.isDirectory()){this.collectCleanupPlan(e,s,n,r,i)?r.push(s):l=!0;continue}if(!a.isFile()){l=!0;continue}if(this.shouldRetainCompiledSkillFile(a.name)){l=!0;continue}n.push(s)}return!l}shouldRetainCompiledSkillFile(e){return e.endsWith(`.mdx`)&&!vx(e)}collect(e){return{}}};const sw=/export\s+default\s*\{([\s\S]*?)\}/u,cw=/description\s*:\s*['"`]([^'"`]+)['"`]/u,lw=/name\s*:\s*['"`]([^'"`]+)['"`]/u,uw=/displayName\s*:\s*['"`]([^'"`]+)['"`]/u,dw=/keywords\s*:\s*\[([^\]]+)\]/u,fw=/author\s*:\s*['"`]([^'"`]+)['"`]/u,pw=/version\s*:\s*['"`]([^'"`]+)['"`]/u;function mw(e){let t={},n=sw.exec(e);if(n?.[1]==null)return t;let r=n[1],i=cw.exec(r);i?.[1]!=null&&(t.description=i[1]);let a=lw.exec(r);a?.[1]!=null&&(t.name=a[1]);let o=uw.exec(r);o?.[1]!=null&&(t.displayName=o[1]);let s=dw.exec(r);s?.[1]!=null&&(t.keywords=s[1].split(`,`).map(e=>e.trim().replaceAll(/['"]/gu,``)).filter(e=>e.length>0));let c=fw.exec(r);c?.[1]!=null&&(t.author=c[1]);let l=pw.exec(r);return l?.[1]!=null&&(t.version=l[1]),t}function hw(...e){let t={};for(let n of e)if(n!=null)for(let[e,r]of Object.entries(n))r!==void 0&&(t[e]=r);return t}function gw(e){let{logger:t,warnedDerivedNames:n,sourcePath:r,authoredName:i,skillName:a}=e;n?.has(r)!==!0&&(n?.add(r),t.warn(O({code:`SKILL_NAME_IGNORED`,title:`Skill authored name is ignored`,reason:b(`tnmsc ignores the authored skill name "${i}" in favor of the directory-derived name "${a}".`),configPath:r,exactFix:b("Remove the `name` field from the skill front matter or exported metadata.",`Rename the skill directory if you need a different skill name.`),details:{authoredName:i,derivedName:a}})))}const _w={".ts":`text/typescript`,".tsx":`text/typescript`,".js":`text/javascript`,".jsx":`text/javascript`,".json":`application/json`,".py":`text/x-python`,".java":`text/x-java`,".kt":`text/x-kotlin`,".go":`text/x-go`,".rs":`text/x-rust`,".c":`text/x-c`,".cpp":`text/x-c++`,".cs":`text/x-csharp`,".rb":`text/x-ruby`,".php":`text/x-php`,".swift":`text/x-swift`,".scala":`text/x-scala`,".sql":`application/sql`,".xml":`application/xml`,".yaml":`text/yaml`,".yml":`text/yaml`,".toml":`text/toml`,".csv":`text/csv`,".graphql":`application/graphql`,".txt":`text/plain`,".pdf":`application/pdf`,".docx":`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,".xlsx":`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,".html":`text/html`,".css":`text/css`,".svg":`image/svg+xml`,".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".gif":`image/gif`,".webp":`image/webp`,".ico":`image/x-icon`,".bmp":`image/bmp`},vw=new Set(`.png,.jpg,.jpeg,.gif,.webp,.ico,.bmp,.tiff,.svg,.exe,.dll,.so,.dylib,.bin,.wasm,.class,.jar,.war,.pyd,.pyc,.pyo,.zip,.tar,.gz,.bz2,.7z,.rar,.ttf,.otf,.woff,.woff2,.eot,.db,.sqlite,.sqlite3,.pdf,.docx,.doc,.xlsx,.xls,.pptx,.ppt,.odt,.ods,.odp`.split(`,`));function yw(e){return vw.has(e.toLowerCase())}function bw(e){return _w[e.toLowerCase()]}function xw(...e){return u.join(...e).replaceAll(`\\`,`/`)}var Sw=class{ctx;constructor(e){this.ctx=e}async processDirectory(e,t,n){let r=t?`${t}/${e.name}`:e.name;return this.scanSkillDirectoryAsync(n,r)}async processFile(e,t,n){let r=t?`${t}/${e.name}`:e.name;if(this.ctx.scanMode===`distChildDocs`){if(t===``&&e.name===`skill.mdx`||vx(e.name)||!e.name.endsWith(`.mdx`))return{childDocs:[],resources:[]};let i=await this.processChildDoc(r,n);return{childDocs:i?[i]:[],resources:[]}}if(t===``&&e.name===`mcp.json`||vx(e.name)||e.name.endsWith(`.mdx`))return{childDocs:[],resources:[]};let i=this.processResourceFile(e.name,r,n);return{childDocs:[],resources:i?[i]:[]}}async processChildDoc(e,t){try{let n=await fb(t,{mode:`dist`,globalScope:this.ctx.globalScope}),r=wp(n.content);return Ex(r,t),{type:ah.SkillChildDoc,content:r,length:r.length,filePathKind:oh.Relative,markdownAst:n.parsed.markdownAst,markdownContents:n.parsed.markdownContents,...n.parsed.rawFrontMatter!=null&&{rawFrontMatter:n.parsed.rawFrontMatter},relativePath:e,dir:{pathKind:oh.Relative,path:e,basePath:this.ctx.skillDir,getDirectoryName:()=>u.dirname(e),getAbsolutePath:()=>t}}}catch(n){throw this.ctx.logger.error(te({code:`SKILL_CHILD_DOC_COMPILE_FAILED`,title:`Failed to compile skill child doc`,diagnosticText:kx(n,{operation:`Failed to compile skill child doc.`,promptKind:`skill-child-doc`,logicalName:`${u.basename(this.ctx.skillDir)}/${e.replace(/\.mdx$/u,``)}`,distPath:t,srcPath:Dx(u,t,{distRootDir:this.ctx.skillDir,srcRootDir:this.ctx.sourceSkillDir})}),details:{skillDir:this.ctx.skillDir,relativePath:e,filePath:t}})),n}}processResourceFile(e,t,n){let r=u.extname(e);try{let{content:i,encoding:a,length:o}=this.readFileContent(n,r),s=bw(r);return{type:ah.SkillResource,extension:r,fileName:e,relativePath:t,sourcePath:n,content:i,encoding:a,length:o,...s!=null&&{mimeType:s}}}catch(r){return this.ctx.logger.warn(D({code:`SKILL_RESOURCE_READ_FAILED`,title:`Failed to read skill resource file`,operation:`read`,targetKind:`skill resource file`,path:n,error:r,details:{relativePath:t,fileName:e,skillDir:this.ctx.skillDir}})),null}}readFileContent(e,t){if(yw(t)){let t=this.ctx.fs.readFileSync(e);return{content:t.toString(`base64`),encoding:`base64`,length:t.length}}let n=this.ctx.fs.readFileSync(e,`utf8`);return{content:n,encoding:`text`,length:_.from(n,`utf8`).length}}async scanSkillDirectoryAsync(e,t=``){let n=[],r=[],i;try{i=this.ctx.fs.readdirSync(e,{withFileTypes:!0})}catch(t){return this.ctx.logger.warn(D({code:`SKILL_DIRECTORY_SCAN_FAILED`,title:`Failed to scan skill directory`,operation:`scan`,targetKind:`skill directory`,path:e,error:t,details:{skillDir:this.ctx.skillDir,scanMode:this.ctx.scanMode}})),{childDocs:n,resources:r}}for(let a of i){let i=xw(e,a.name);if(a.isDirectory()){let e=await this.processDirectory(a,t,i);n.push(...e.childDocs),r.push(...e.resources);continue}if(!a.isFile())continue;let o=await this.processFile(a,t,i);n.push(...o.childDocs),r.push(...o.resources)}return{childDocs:n,resources:r}}};function Cw(e,t,n,r=``){let i=[],a=r===``?e:xw(e,r),o;try{o=t.readdirSync(a,{withFileTypes:!0})}catch(e){return n.warn(D({code:`SKILL_SOURCE_CHILD_SCAN_FAILED`,title:`Failed to scan skill source child docs`,operation:`scan`,targetKind:`skill source child doc directory`,path:a,error:e})),i}for(let a of o){let o=r?`${r}/${a.name}`:a.name;if(a.isDirectory()){i.push(...Cw(e,t,n,o));continue}!a.isFile()||!vx(a.name)||r===``&&a.name===`skill.src.mdx`||i.push(o.replace(/\.src\.mdx$/u,`.mdx`))}return i}function ww(e,t,n,r,i){if(r.existsSync(t))for(let a of Cw(t,r,i)){let i=u.join(n,a);if(!r.existsSync(i))throw new Sx({kind:`skill child doc`,name:`${e}/${a}`,sourcePath:u.join(t,a.replace(/\.mdx$/u,`.src.mdx`)),expectedDistPath:i})}}function Tw(e,t,n){let r=u.join(e,`mcp.json`);if(t.existsSync(r)){if(!t.statSync(r).isFile()){n.warn(k({code:`SKILL_MCP_CONFIG_NOT_FILE`,title:`Skill MCP config path is not a file`,path:r,expectedKind:`mcp.json file`,actualState:`path exists but is not a regular file`,details:{skillDir:e}}));return}try{let i=t.readFileSync(r,`utf8`),a=JSON.parse(i);if(a.mcpServers==null||typeof a.mcpServers!=`object`){n.warn(O({code:`SKILL_MCP_CONFIG_INVALID`,title:`Skill MCP config is missing mcpServers`,reason:b(`The skill MCP config at "${r}" does not contain a top-level mcpServers object.`),configPath:r,exactFix:b("Add a top-level `mcpServers` object to mcp.json before retrying tnmsc."),details:{skillDir:e}}));return}return{type:ah.SkillMcpConfig,mcpServers:a.mcpServers,rawContent:i}}catch(t){n.warn(O({code:`SKILL_MCP_CONFIG_PARSE_FAILED`,title:`Failed to parse skill MCP config`,reason:b(`tnmsc could not parse the MCP config file at "${r}".`,`Underlying error: ${t instanceof Error?t.message:String(t)}`),configPath:r,exactFix:b(`Fix the JSON syntax in mcp.json and rerun tnmsc.`),details:{skillDir:e,errorMessage:t instanceof Error?t.message:String(t)}}));return}}}async function Ew(e,t,n,r,i,a,o,s,c=[],l=[],d,f,p){let{logger:m,fs:h}=o,g=u.join(i,`skill.mdx`),_=h.existsSync(u.join(a,`skill.src.mdx`))?u.join(a,`skill.src.mdx`):g,v=e,y,x;if(h.existsSync(g)){let t=await fb(g,{mode:`dist`,globalScope:o.globalScope});v=t.rawMdx,y=t.parsed,e=wp(t.content),Ex(e,g),x=t.metadata}let S=hw(mw(v),f,x),w=new Set,T=y?.yamlFrontMatter?.name;typeof T==`string`&&T.trim().length>0&&w.add(T);let E=S.name;typeof E==`string`&&E.trim().length>0&&w.add(E);for(let e of w)gw({logger:m,sourcePath:_,authoredName:e,skillName:n,...p!=null&&{warnedDerivedNames:p}});let D=y?.yamlFrontMatter?.description??S?.description;if(D==null||D.trim().length===0)throw m.error(C({code:`SKILL_VALIDATION_FAILED`,title:`Skill description is required`,rootCause:b(`The skill "${n}" does not provide a non-empty description in its compiled metadata or front matter.`),exactFix:b(`Add a non-empty description field to the skill front matter or exported metadata and rebuild the skill.`),possibleFixes:[b("Set `description` in `SKILL.md` front matter."),b(`If you export metadata from code, ensure the exported description is non-empty.`)],details:{skill:n,skillDir:r,yamlDescription:y?.yamlFrontMatter?.description,exportDescription:S?.description}})),Error(`Skill "${n}" validation failed: description is required and cannot be empty`);let O={...S,...y?.yamlFrontMatter??{},name:n,description:D},ee=Gb(O,g);if(!ee.valid)throw Error(ee.errors.join(`
|
|
297
|
-
`));return{type:
|
|
298
|
-
`));for(let e of m){let t=e.dist?.prompt;t!=null&&l.push(t)}return{skills:l}}}
|
|
299
|
-
`));return Object.assign(_,{yamlFrontMatter:g}),g.seriName!=null&&Object.assign(_,{seriName:g.seriName}),g.scope===`global`&&Object.assign(_,{globalOnly:!0}),_}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i,globalScope:a}=e,o=this.resolveBasePaths(t),s=this.resolveAindexPath(t.aindex.commands.src,o.aindexDir),c=this.resolveAindexPath(t.aindex.commands.dist,o.aindexDir);n.debug(`CommandInputCapability collecting`,{srcDir:s,distDir:c,aindexDir:o.aindexDir});let{prompts:l,errors:u}=await
|
|
300
|
-
`));let d=[];for(let e of l){let t=e.dist;if(t?.prompt==null)continue;let{prompt:n,rawMdx:r}=t;d.push(r==null?n:{...n,rawMdxContent:r})}return n.debug(`CommandInputCapability flattened commands`,{count:d.length,commands:d.map(e=>e.commandName)}),{commands:d}}},Aw=class extends Vg{constructor(){super(`EditorConfigInputCapability`)}collect(e){let{userConfigOptions:t,fs:n}=e,{workspaceDir:r,aindexDir:i}=this.resolveBasePaths(t),a=[],o=Th(sh.EditorConfig,`.editorconfig`,i,n,{command:e.runtimeCommand,workspaceDir:r});return o!=null&&a.push(o),{editorConfigFiles:a}}},jw=class extends Vg{constructor(){super(`GitExcludeInputCapability`)}collect(e){let{workspaceDir:t,aindexDir:n}=this.resolveBasePaths(e.userConfigOptions),r=Ch(n,dh,{command:e.runtimeCommand,workspaceDir:t});if(!e.fs.existsSync(r))return this.log.debug({action:`collect`,message:`File not found`,path:r}),{};let i=e.fs.readFileSync(r,`utf8`);return i.length===0?(this.log.debug({action:`collect`,message:`File is empty`,path:r}),{}):(this.log.debug({action:`collect`,message:`Loaded file content`,path:r,length:i.length}),{shadowGitExclude:i})}},Mw=class extends Vg{constructor(){super(`GitIgnoreInputCapability`)}collect(e){let{workspaceDir:t,aindexDir:n}=this.resolveBasePaths(e.userConfigOptions),r=Ch(n,uh,{command:e.runtimeCommand,workspaceDir:t});if(!e.fs.existsSync(r))return this.log.debug({action:`collect`,message:`File not found`,path:r}),{};let i=e.fs.readFileSync(r,`utf8`);return i.length===0?(this.log.debug({action:`collect`,message:`File is empty`,path:r}),{}):(this.log.debug({action:`collect`,message:`Loaded file content`,path:r,length:i.length}),{globalGitIgnore:i})}},Nw=class extends Vg{constructor(){super(`GlobalMemoryInputCapability`)}async collect(e){let{userConfigOptions:t,fs:n,path:r,globalScope:i}=e,{aindexDir:a}=this.resolveBasePaths(t),o=LS(),s=ng(),l=this.resolveAindexPath(t.aindex.globalPrompt.dist,a);if(!n.existsSync(l))return this.log.warn(k({code:`GLOBAL_MEMORY_PROMPT_MISSING`,title:`Global memory prompt is missing`,path:l,expectedKind:`compiled global memory prompt file`,actualState:`path does not exist`})),{};if(!n.statSync(l).isFile())return this.log.warn(k({code:`GLOBAL_MEMORY_PROMPT_NOT_FILE`,title:`Global memory prompt path is not a file`,path:l,expectedKind:`compiled global memory prompt file`,actualState:`path exists but is not a regular file`})),{};let u,d;try{d=await fb(l,{mode:`dist`,globalScope:i}),u=d.content,Ex(u,l)}catch(e){throw e instanceof Xg&&(this.log.error(te({code:`GLOBAL_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile global memory prompt`,diagnosticText:kx(e,{operation:`Failed to compile global memory prompt.`,promptKind:`global-memory`,logicalName:`global-memory`,distPath:l}),details:{promptKind:`global-memory`,distPath:l}})),e instanceof Qg&&this.log.error(O({code:`GLOBAL_MEMORY_SCOPE_VARIABLES_MISSING`,title:`Global memory prompt references missing config variables`,reason:b(`The global memory prompt uses scope variables that are not defined in "${o}".`),configPath:o,exactFix:b(`Add the missing variables to "${o}" and rerun tnmsc.`),possibleFixes:[b("If you reference `{profile.name}`, define `profile.name` in the config file.")],details:{promptPath:l,errorMessage:e.message}})),c.exit(1)),e}return this.log.debug({action:`collect`,path:l,contentLength:u.length}),{globalMemory:{type:ah.GlobalMemory,content:u,length:u.length,filePathKind:oh.Relative,...d.parsed.rawFrontMatter!=null&&{rawFrontMatter:d.parsed.rawFrontMatter},markdownAst:d.parsed.markdownAst,markdownContents:d.parsed.markdownContents,dir:{pathKind:oh.Relative,path:r.basename(l),basePath:r.dirname(l),getDirectoryName:()=>r.basename(l),getAbsolutePath:()=>l},parentDirectoryPath:{type:ch.UserHome,directory:{pathKind:oh.Relative,path:``,basePath:s,getDirectoryName:()=>r.basename(s),getAbsolutePath:()=>s}}}}}},Pw=class extends Vg{constructor(){super(`JetBrainsConfigInputCapability`)}collect(e){let{userConfigOptions:t,fs:n}=e,{workspaceDir:r,aindexDir:i}=this.resolveBasePaths(t),a=[`.idea/codeStyles/Project.xml`,`.idea/codeStyles/codeStyleConfig.xml`,`.idea/.gitignore`],o=[];for(let t of a){let a=Th(sh.IntellijIDEA,t,i,n,{command:e.runtimeCommand,workspaceDir:r});a!=null&&o.push(a)}return{jetbrainsConfigFiles:o}}};const Fw=`agt.mdx`,Iw=[`node_modules`,`.git`];var Lw=class extends Vg{constructor(){super(`ProjectPromptInputCapability`,[`AindexInputCapability`])}async collect(e){let{dependencyContext:t,fs:n,userConfigOptions:r,path:i,globalScope:a}=e,{aindexDir:o}=this.resolveBasePaths(r),s=this.resolveAindexPath(r.aindex.app.dist,o),c=this.resolveAindexPath(r.aindex.workspacePrompt.dist,o),l=t.workspace;if(l==null)return this.log.info(`No workspace found in dependency context, skipping project prompt enhancement`),{};let u=l.projects??[],d=await Promise.all(u.map(async t=>{let r=t.name;if(r==null||t.isWorkspaceRootProject===!0)return t;let o=i.join(s,r);if(!n.existsSync(o)||!n.statSync(o).isDirectory())return t;let c=t.dirFromWorkspacePath?.getAbsolutePath(),l=await this.readRootMemoryPrompt(e,o,a),u=c==null?[]:await this.scanChildMemoryPrompts(e,o,c,a);return{...t,...l!=null&&{rootMemoryPrompt:l},...u.length>0&&{childMemoryPrompts:u}}})),f=await this.readWorkspaceRootProjectPrompt(e,c,a,this.resolveWorkspaceRootProjectConfig(u));return{workspace:{directory:l.directory,projects:f==null?d:[...d,f]}}}async readWorkspaceRootProjectPrompt(e,t,n,r){let{fs:i,logger:a}=e;if(!(!i.existsSync(t)||!i.statSync(t).isFile()))try{let e;try{e=await fb(t,{mode:`dist`,globalScope:n}),Ex(e.content,t)}catch(e){if(e instanceof Xg){if(a.error(te({code:`WORKSPACE_ROOT_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile workspace root memory prompt`,diagnosticText:kx(e,{operation:`Failed to compile workspace root memory prompt.`,promptKind:`workspace-root-memory`,logicalName:t,distPath:t}),details:{promptKind:`workspace-root-memory`,distPath:t}})),e instanceof Qg){let n=LS();a.error(O({code:`WORKSPACE_ROOT_MEMORY_SCOPE_VARIABLES_MISSING`,title:`Workspace root memory prompt references missing config variables`,reason:b(`The workspace root memory prompt uses scope variables that are not defined in "${n}".`),configPath:n,exactFix:b(`Define the missing variables in "${n}" and rerun tnmsc.`),details:{promptPath:t,errorMessage:e.message}}))}c.exit(1)}throw e}let i={type:ah.ProjectRootMemory,content:e.content,length:e.content.length,filePathKind:oh.Relative,...e.parsed.yamlFrontMatter!=null&&{yamlFrontMatter:e.parsed.yamlFrontMatter},...e.parsed.rawFrontMatter!=null&&{rawFrontMatter:e.parsed.rawFrontMatter},markdownAst:e.parsed.markdownAst,markdownContents:e.parsed.markdownContents,dir:{pathKind:oh.Root,path:``,getDirectoryName:()=>``}};return{name:`__workspace__`,isWorkspaceRootProject:!0,...r!=null&&{projectConfig:r},rootMemoryPrompt:i}}catch(e){a.error(D({code:`WORKSPACE_ROOT_MEMORY_PROMPT_READ_FAILED`,title:`Failed to read workspace root memory prompt`,operation:`read`,targetKind:`workspace root memory prompt`,path:t,error:e}));return}}resolveWorkspaceRootProjectConfig(e){let t=e.filter(e=>e.isWorkspaceRootProject!==!0);return t.find(e=>e.isPromptSourceProject===!0)?.projectConfig??t[0]?.projectConfig}async readRootMemoryPrompt(e,t,n){let{fs:r,path:i,logger:a}=e,o=i.join(t,Fw);if(!(!r.existsSync(o)||!r.statSync(o).isFile()))try{let e;try{e=await fb(o,{mode:`dist`,globalScope:n}),Ex(e.content,o)}catch(e){if(e instanceof Xg){if(a.error(te({code:`PROJECT_ROOT_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile project root memory prompt`,diagnosticText:kx(e,{operation:`Failed to compile project root memory prompt.`,promptKind:`project-root-memory`,logicalName:o,distPath:o}),details:{promptKind:`project-root-memory`,distPath:o}})),e instanceof Qg){let t=LS();a.error(O({code:`PROJECT_ROOT_MEMORY_SCOPE_VARIABLES_MISSING`,title:`Project root memory prompt references missing config variables`,reason:b(`The project root memory prompt uses scope variables that are not defined in "${t}".`),configPath:t,exactFix:b(`Define the missing variables in "${t}" and rerun tnmsc.`),details:{promptPath:o,errorMessage:e.message}}))}c.exit(1)}throw e}return{type:ah.ProjectRootMemory,content:e.content,length:e.content.length,filePathKind:oh.Relative,...e.parsed.yamlFrontMatter!=null&&{yamlFrontMatter:e.parsed.yamlFrontMatter},...e.parsed.rawFrontMatter!=null&&{rawFrontMatter:e.parsed.rawFrontMatter},markdownAst:e.parsed.markdownAst,markdownContents:e.parsed.markdownContents,dir:{pathKind:oh.Root,path:``,getDirectoryName:()=>``}}}catch(e){a.error(D({code:`PROJECT_ROOT_MEMORY_PROMPT_READ_FAILED`,title:`Failed to read project root memory prompt`,operation:`read`,targetKind:`project root memory prompt`,path:o,error:e}));return}}async scanChildMemoryPrompts(e,t,n,r){let{logger:i}=e,a=[];try{await this.scanDirectoryRecursive(e,t,t,n,a,r)}catch(e){i.error(D({code:`PROJECT_CHILD_MEMORY_SCAN_FAILED`,title:`Failed to scan project child memory prompts`,operation:`scan`,targetKind:`project child memory prompt directory`,path:t,error:e}))}return a}async scanDirectoryRecursive(e,t,n,r,i,a){let{fs:o,path:s}=e,c=o.readdirSync(n,{withFileTypes:!0});for(let l of c){if(!l.isDirectory()||Iw.includes(l.name))continue;let c=s.join(n,l.name),u=s.join(c,Fw);if(o.existsSync(u)&&o.statSync(u).isFile()){let n=await this.readChildMemoryPrompt(e,t,c,r,a);n!=null&&i.push(n)}await this.scanDirectoryRecursive(e,t,c,r,i,a)}}async readChildMemoryPrompt(e,t,n,r,i){let{path:a,logger:o}=e,s=a.join(n,Fw);try{let e;try{e=await fb(s,{mode:`dist`,globalScope:i}),Ex(e.content,s)}catch(e){if(e instanceof Xg){if(o.error(te({code:`PROJECT_CHILD_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile project child memory prompt`,diagnosticText:kx(e,{operation:`Failed to compile project child memory prompt.`,promptKind:`project-child-memory`,logicalName:s,distPath:s}),details:{promptKind:`project-child-memory`,distPath:s}})),e instanceof Qg){let t=LS();o.error(O({code:`PROJECT_CHILD_MEMORY_SCOPE_VARIABLES_MISSING`,title:`Project child memory prompt references missing config variables`,reason:b(`The project child memory prompt uses scope variables that are not defined in "${t}".`),configPath:t,exactFix:b(`Define the missing variables in "${t}" and rerun tnmsc.`),details:{promptPath:s,errorMessage:e.message}}))}c.exit(1)}throw e}let l=a.relative(t,n),u=a.join(r,l),d=a.basename(n);return{type:ah.ProjectChildrenMemory,content:e.content,length:e.content.length,filePathKind:oh.Relative,...e.parsed.yamlFrontMatter!=null&&{yamlFrontMatter:e.parsed.yamlFrontMatter},...e.parsed.rawFrontMatter!=null&&{rawFrontMatter:e.parsed.rawFrontMatter},markdownAst:e.parsed.markdownAst,markdownContents:e.parsed.markdownContents,dir:{pathKind:oh.Relative,path:l,basePath:r,getDirectoryName:()=>d,getAbsolutePath:()=>u},workingChildDirectoryPath:{pathKind:oh.Relative,path:l,basePath:r,getDirectoryName:()=>d,getAbsolutePath:()=>u}}}catch(e){o.error(D({code:`PROJECT_CHILD_MEMORY_PROMPT_READ_FAILED`,title:`Failed to read project child memory prompt`,operation:`read`,targetKind:`project child memory prompt`,path:s,error:e}));return}}};const Rw=Object.entries(Xb);var zw=class extends Vg{constructor(){super(`ReadmeMdInputCapability`,[`AindexInputCapability`])}async collect(e){let{userConfigOptions:t,logger:n,fs:r,path:i,globalScope:a}=e,{workspaceDir:o,aindexDir:s}=this.resolveBasePaths(t),c=this.resolveAindexPath(t.aindex.app.dist,s),l=[];if(!r.existsSync(c)||!r.statSync(c).isDirectory())return n.debug(`aindex projects directory does not exist`,{path:c}),{readmePrompts:l};try{let t=r.readdirSync(c,{withFileTypes:!0});for(let n of t){if(!n.isDirectory())continue;let t=n.name,r=i.join(c,t);await this.collectReadmeFiles(e,r,t,o,``,l,a)}}catch(e){n.error(D({code:`README_PROJECT_SCAN_FAILED`,title:`Failed to scan aindex projects for readme prompts`,operation:`scan`,targetKind:`aindex project directory`,path:c,error:e}))}return{readmePrompts:l}}async collectReadmeFiles(e,t,n,r,i,a,o){let{fs:s,path:l,logger:u}=e,d=i===``;for(let[e,{src:f}]of Rw){let p=l.join(t,f);if(!(!s.existsSync(p)||!s.statSync(p).isFile()))try{let t;try{let{content:e}=await fb(p,{mode:`dist`,globalScope:o});t=e,Ex(t,p)}catch(t){if(t instanceof Xg){if(u.error(te({code:`README_PROMPT_COMPILE_FAILED`,title:`Failed to compile readme-family prompt`,diagnosticText:kx(t,{operation:`Failed to compile readme-family prompt.`,promptKind:`readme-family`,logicalName:`${n}/${f}`,distPath:p}),details:{promptKind:`readme-family`,distPath:p,projectName:n,fileKind:e}})),t instanceof Qg){let e=LS();u.error(O({code:`README_SCOPE_VARIABLES_MISSING`,title:`Readme-family prompt references missing config variables`,reason:b(`The readme-family prompt uses scope variables that are not defined in "${e}".`),configPath:e,exactFix:b(`Define the missing variables in "${e}" and rerun tnmsc.`),details:{promptPath:p,errorMessage:t.message}}))}c.exit(1)}throw t}let s=d?n:l.join(n,i),m={pathKind:oh.Relative,path:s,basePath:r,getDirectoryName:()=>d?n:l.basename(i),getAbsolutePath:()=>l.resolve(r,s)},h={pathKind:oh.Relative,path:l.dirname(p),basePath:r,getDirectoryName:()=>l.basename(l.dirname(p)),getAbsolutePath:()=>l.dirname(p)};a.push({type:ah.Readme,content:t,length:t.length,filePathKind:oh.Relative,projectName:n,targetDir:m,isRoot:d,fileKind:e,markdownContents:[],dir:h})}catch(t){u.warn(D({code:`README_PROMPT_READ_FAILED`,title:`Failed to read readme-family file`,operation:`read`,targetKind:`readme-family prompt file`,path:p,error:t,details:{fileKind:e}}))}}try{let c=s.readdirSync(t,{withFileTypes:!0});for(let s of c)if(s.isDirectory()){let c=d?s.name:l.join(i,s.name),u=l.join(t,s.name);await this.collectReadmeFiles(e,u,n,r,c,a,o)}}catch(e){u.warn(D({code:`README_DIRECTORY_SCAN_FAILED`,title:`Failed to scan readme-family directory`,operation:`scan`,targetKind:`readme-family directory`,path:t,error:e}))}}},Bw=class extends Vg{constructor(){super(`RuleInputCapability`)}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i,globalScope:a}=e,o=this.resolveBasePaths(t),s=this.resolveAindexPath(t.aindex.rules.src,o.aindexDir),c=this.resolveAindexPath(t.aindex.rules.dist,o.aindexDir),{prompts:l,errors:u}=await Mx(i,r,n,a).readFlatFiles(s,c,{kind:ah.Rule,localeExtensions:_x,hydrateSourceContents:!1,isDirectoryStructure:!1,createPrompt:async(e,t,n,i)=>{let a=i,o=r.join(c,`${n}.mdx`);if(a!=null){let e=Jb(a,o);if(!e.valid)throw Error(e.errors.join(`
|
|
301
|
-
`))}let s=a?.globs??[],l=a?.scope??`project`,u=a?.seriName,d=n.replaceAll(`\\`,`/`),f=d.includes(`/`)?d.split(`/`)[0]??``:``,p=d.split(`/`).pop()??d,m={type:
|
|
302
|
-
`));return{rules:l.map(e=>e.dist?.prompt).filter(e=>e!=null)}}},
|
|
303
|
-
`));return Object.assign(v,{yamlFrontMatter:_}),_.seriName!=null&&Object.assign(v,{seriName:_.seriName}),v}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i,globalScope:a}=e,o=this.resolveBasePaths(t),s=this.resolveAindexPath(t.aindex.subAgents.src,o.aindexDir),c=this.resolveAindexPath(t.aindex.subAgents.dist,o.aindexDir);n.debug(`SubAgentInputCapability collecting`,{srcDir:s,distDir:c,aindexDir:o.aindexDir});let l=
|
|
304
|
-
`));let p=[];for(let e of d){let t=e.dist;if(t?.prompt==null)continue;let{prompt:n,rawMdx:r}=t;p.push(r==null?n:{...n,rawMdxContent:r})}return n.debug(`SubAgentInputCapability flattened subAgents`,{count:p.length,agents:p.map(e=>e.canonicalName)}),{subAgents:p}}},Uw=class extends Vg{constructor(){super(`VSCodeConfigInputCapability`)}collect(e){let{userConfigOptions:t,fs:n}=e,{workspaceDir:r,aindexDir:i}=this.resolveBasePaths(t),a=[`.vscode/settings.json`,`.vscode/extensions.json`],o=[];for(let t of a){let a=Th(sh.VSCode,t,i,n,{command:e.runtimeCommand,workspaceDir:r});a!=null&&o.push(a)}return{vscodeConfigFiles:o}}},Ww=class extends Vg{constructor(){super(`WorkspaceInputCapability`)}collect(e){let{userConfigOptions:t}=e,{workspaceDir:n,aindexDir:r}=this.resolveBasePaths(t);return{workspace:{directory:{pathKind:oh.Absolute,path:n,getDirectoryName:()=>u.basename(n)},projects:[]},aindexDir:r}}},Gw=class extends Vg{constructor(){super(`ZedConfigInputCapability`)}collect(e){let{userConfigOptions:t,fs:n}=e,{workspaceDir:r,aindexDir:i}=this.resolveBasePaths(t),a=[],o=Th(sh.Zed,`.zed/settings.json`,i,n,{command:e.runtimeCommand,workspaceDir:r});return o!=null&&a.push(o),{zedConfigFiles:a}}};const Kw={workspace:{strategy:`mergeProjects`,getter:e=>e.workspace},vscodeConfigFiles:{strategy:`concat`,getter:e=>e.vscodeConfigFiles},zedConfigFiles:{strategy:`concat`,getter:e=>e.zedConfigFiles},jetbrainsConfigFiles:{strategy:`concat`,getter:e=>e.jetbrainsConfigFiles},editorConfigFiles:{strategy:`concat`,getter:e=>e.editorConfigFiles},commands:{strategy:`concat`,getter:e=>e.commands},subAgents:{strategy:`concat`,getter:e=>e.subAgents},skills:{strategy:`concat`,getter:e=>e.skills},rules:{strategy:`concat`,getter:e=>e.rules},aiAgentIgnoreConfigFiles:{strategy:`concat`,getter:e=>e.aiAgentIgnoreConfigFiles},readmePrompts:{strategy:`concat`,getter:e=>e.readmePrompts},globalMemory:{strategy:`override`,getter:e=>e.globalMemory},aindexDir:{strategy:`override`,getter:e=>e.aindexDir},globalGitIgnore:{strategy:`override`,getter:e=>e.globalGitIgnore},shadowGitExclude:{strategy:`override`,getter:e=>e.shadowGitExclude}};function qw(e,t){return t==null?e??[]:e==null?t:[...e,...t]}function Jw(e,t){let n=new Map;for(let t of e.projects)n.set(t.name,t);for(let e of t.projects)n.set(e.name,e);return{directory:t.directory??e.directory,projects:[...n.values()]}}function Yw(e,t){return t==null?e:e==null?t:Jw(e,t)}function Xw(e,t,n){switch(n){case`concat`:return qw(e,t);case`override`:return t??e;case`mergeProjects`:return Yw(e,t);default:return t??e}}function Zw(e,t){let n={};for(let[r,i]of Object.entries(Kw)){let a=Xw(i.getter(e),i.getter(t),i.strategy);a!=null&&(n[r]=a)}return n}function Qw(e,t,n){let r=e.dependsOn??[];if(r.length===0)return{};let i=new Set,a={};for(let e of r){if(i.has(e))continue;i.add(e);let r=t.get(e);r!=null&&(a=n(a,r))}return a}function $w(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.at(-1);if(e==null)return[...n];let t=a.indexOf(e);return a.slice(t)}i.clear(),a.length=0}return[...n]}function eT(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 sx(n.name,r)}let n=new Map;for(let t of e)n.set(t.name,t);let r=new Map;for(let t of e)r.set(t.name,0);let i=new Map;for(let t of e)i.set(t.name,[]);for(let t of e){let e=t.dependsOn??[];for(let n of e){r.set(t.name,(r.get(t.name)??0)+1);let e=i.get(n)??[];e.push(t.name),i.set(n,e)}}let a=[];for(let t of e)r.get(t.name)===0&&a.push(t.name);let o=[],s=new Map;for(let t=0;t<e.length;t++){let n=e[t];n!=null&&s.set(n.name,t)}for(;a.length>0;){let e=a.shift();if(e==null)continue;let t=n.get(e);if(t==null)continue;o.push(t);let c=(i.get(e)??[]).sort((e,t)=>(s.get(e)??-1)-(s.get(t)??-1));for(let e of c){let t=(r.get(e)??0)-1;r.set(e,t),t===0&&a.push(e)}}if(o.length===e.length)return o;throw new cx($w(e,r))}function tT(){return[new ow,new aw,new rw]}function nT(){return[new Ww,new Ow,new Uw,new Gw,new Pw,new Aw,new Dw,new kw,new Hw,new Bw,new Nw,new Lw,new zw,new Mw,new jw,new Vw]}function rT(e){if(e==null||e.length===0)return`execute`;let t=WC(BC(e.filter(e=>e!=null)));if(!(t.helpFlag||t.versionFlag||t.unknownCommand!=null)){if(t.subcommand===`clean`)return`clean`;if(t.subcommand===`plugins`)return`plugins`;if(t.subcommand===`dry-run`||t.dryRun)return`dry-run`;if(t.subcommand==null)return`execute`}}async function iT(e){let{pipelineArgs:t,userConfigOptions:n,userConfig:r,capabilities:a,includeBuiltinEffects:o=!0}=e,s=be(`InputRuntime`,n.logLevel),c=rT(t),l={logger:s,userConfigOptions:n,fs:i,path:u,glob:Um.default},d=eT([...o?tT():[],...a??nT()]),f=new Zy({userConfig:r}).collect(),p=new $y;p.setGlobalScope(f),s.debug(`global scope collected`,{osInfo:{platform:f.os.platform,arch:f.os.arch,shellKind:f.os.shellKind},hasProfile:Object.keys(f.profile).length>0,hasTool:Object.keys(f.tool).length>0});let m=new Map,h={};for(let e of d){let t=Qw(e,m,Zw),n={...l,dependencyContext:t,...c==null?{}:{runtimeCommand:c},globalScope:f,scopeRegistry:p},r=e;r.executeEffects!=null&&await r.executeEffects(n,!1);let i=await e.collect(n);m.set(e.name,i),h=Zw(h,i);let a=e;if(a.getRegisteredScopes!=null){let t=a.getRegisteredScopes();for(let{namespace:n,values:r}of t)p.register(n,r,Qy.PluginRegistered),s.debug(`input capability scope registered`,{capability:e.name,namespace:n,keys:Object.keys(r)})}}return h}function aT(e){return`declarativeOutput`in e}function oT(e){return`collect`in e&&!aT(e)}const sT={version:`0.0.0`,workspaceDir:`~/project`,logLevel:`info`,aindex:{dir:`aindex`,skills:{src:`skills`,dist:`dist/skills`},commands:{src:`commands`,dist:`dist/commands`},subAgents:{src:`subagents`,dist:`dist/subagents`},rules:{src:`rules`,dist:`dist/rules`},globalPrompt:{src:`app/global.src.mdx`,dist:`dist/global.mdx`},workspacePrompt:{src:`app/workspace.src.mdx`,dist:`dist/workspace.mdx`},app:{src:`app`,dist:`dist/app`},ext:{src:`ext`,dist:`dist/ext`},arch:{src:`arch`,dist:`dist/arch`}},commandSeriesOptions:{},outputScopes:{},frontMatter:{blankLineAfter:!0},cleanupProtection:{},windows:{},plugins:[]};function cT(e){return{...e.version==null?{}:{version:e.version},...e.workspaceDir==null?{}:{workspaceDir:e.workspaceDir},...e.aindex==null?{}:{aindex:e.aindex},...e.commandSeriesOptions==null?{}:{commandSeriesOptions:e.commandSeriesOptions},...e.outputScopes==null?{}:{outputScopes:e.outputScopes},...e.frontMatter==null?{}:{frontMatter:e.frontMatter},...e.cleanupProtection==null?{}:{cleanupProtection:e.cleanupProtection},...e.windows==null?{}:{windows:e.windows},...e.logLevel==null?{}:{logLevel:e.logLevel}}}function lT(...e){let t={...sT};return e.reduce((e,t)=>uT(e,t),t)}function uT(e,t){let n=t.plugins,r=t.commandSeriesOptions,i=t.outputScopes,a=t.frontMatter,o=t.cleanupProtection,s=t.windows;return{...e,...t,aindex:dT(e.aindex,t.aindex),plugins:[...e.plugins,...n??[]],commandSeriesOptions:fT(e.commandSeriesOptions,r),outputScopes:mT(e.outputScopes,i),frontMatter:hT(e.frontMatter,a),cleanupProtection:gT(e.cleanupProtection,o),windows:_T(e.windows,s)}}function dT(e,t){return t==null?e:{dir:t.dir??e.dir,skills:{...e.skills,...t.skills},commands:{...e.commands,...t.commands},subAgents:{...e.subAgents,...t.subAgents},rules:{...e.rules,...t.rules},globalPrompt:{...e.globalPrompt,...t.globalPrompt},workspacePrompt:{...e.workspacePrompt,...t.workspacePrompt},app:{...e.app,...t.app},ext:{...e.ext,...t.ext},arch:{...e.arch,...t.arch}}}function fT(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 pT(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{...e,...t}}function mT(e,t){if(t==null)return e??{};if(e==null)return t;let n={};if(e.plugins!=null)for(let[t,r]of Object.entries(e.plugins))r!=null&&(n[t]={...r});if(t.plugins!=null)for(let[e,r]of Object.entries(t.plugins)){let t=pT(n[e],r);t!=null&&(n[e]=t)}return Object.keys(n).length===0?{}:{plugins:n}}function hT(e,t){return t==null?e:{...e,...t}}function gT(e,t){return t==null?e??{}:e==null?t:{rules:[...e.rules??[],...t.rules??[]]}}function _T(e,t){if(t==null)return e??{};if(e==null)return t;let n=e.wsl2,r=t.wsl2;return{...e,...t,...n!=null||r!=null?{wsl2:{...n,...r}}:{}}}function vT(e){return`pluginOptions`in e||`configLoaderOptions`in e||`loadUserConfig`in e||`cwd`in e||`pipelineArgs`in e}function yT(e){return vT(e)?{hasExplicitProgrammaticPlugins:Object.hasOwn(e.pluginOptions??{},`plugins`),explicitProgrammaticPlugins:e.pluginOptions?.plugins}:{hasExplicitProgrammaticPlugins:Object.hasOwn(e,`plugins`),explicitProgrammaticPlugins:e.plugins}}function bT(e,t){let n=e;return n.includes(ux.WORKSPACE)&&(n=n.replace(ux.WORKSPACE,t)),u.normalize(ag(n))}function xT(e){let t=bT(e.workspaceDir,``),n=u.join(t,e.aindex.dir);return Yb({workspace:{directory:{pathKind:oh.Absolute,path:t,getDirectoryName:()=>u.basename(t)},projects:[]},aindexDir:n})}function ST(e){return rT(e)===`plugins`}async function CT(e={}){let t,n,r,i,a;vT(e)?({pluginOptions:r={},cwd:n,configLoaderOptions:i,pipelineArgs:a}={pluginOptions:e.pluginOptions,cwd:e.cwd,configLoaderOptions:e.configLoaderOptions,pipelineArgs:e.pipelineArgs},t=e.loadUserConfig??!0):(r=e,t=!0,i=void 0,a=void 0);let o={},s=!1,c=[],l;if(t)try{let e=BS(i).load(n);s=e.found,c=e.sources,e.found&&(o=cT(e.config),l=e.config)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load user config: ${t}`)}let u=lT(o,r),{plugins:d=[],logLevel:f}=u,p=be(`defineConfig`,f);s?p.info(`user config loaded`,{sources:c}):p.info(`no user config found, using defaults/programmatic options`,{workspaceDir:u.workspaceDir,aindexDir:u.aindex.dir,logLevel:u.logLevel});let m=d.filter(aT),h=d.filter(oT);return rx(m,u),{mergedOptions:u,outputPlugins:m,inputCapabilities:h,...l!=null&&{userConfigFile:l},...a!=null&&{pipelineArgs:a},userConfigFound:s,userConfigSources:c}}async function wT(e={}){let{hasExplicitProgrammaticPlugins:t,explicitProgrammaticPlugins:n}=yT(e),{mergedOptions:r,outputPlugins:i,inputCapabilities:a,userConfigFile:o,pipelineArgs:s}=await CT(e),c=be(`defineConfig`,r.logLevel);if(ST(s))return{context:xT(r),outputPlugins:i,userConfigOptions:r};let l=await iT({userConfigOptions:r,...a.length>0?{capabilities:a}:{},includeBuiltinEffects:!(a.length>0||t&&(n?.length??0)===0),...s==null?{}:{pipelineArgs:s},...o==null?{}:{userConfig:o}});if(l.workspace==null)throw Error(`Workspace not initialized by any plugin`);let u=Yb({workspace:l.workspace,...l.vscodeConfigFiles!=null&&{vscodeConfigFiles:l.vscodeConfigFiles},...l.zedConfigFiles!=null&&{zedConfigFiles:l.zedConfigFiles},...l.jetbrainsConfigFiles!=null&&{jetbrainsConfigFiles:l.jetbrainsConfigFiles},...l.editorConfigFiles!=null&&{editorConfigFiles:l.editorConfigFiles},...l.commands!=null&&{commands:l.commands},...l.subAgents!=null&&{subAgents:l.subAgents},...l.skills!=null&&{skills:l.skills},...l.rules!=null&&{rules:l.rules},...l.globalMemory!=null&&{globalMemory:l.globalMemory},...l.aiAgentIgnoreConfigFiles!=null&&{aiAgentIgnoreConfigFiles:l.aiAgentIgnoreConfigFiles},...l.aindexDir!=null&&{aindexDir:l.aindexDir},...l.readmePrompts!=null&&{readmePrompts:l.readmePrompts},...l.globalGitIgnore!=null&&{globalGitIgnore:l.globalGitIgnore},...l.shadowGitExclude!=null&&{shadowGitExclude:l.shadowGitExclude}});return l.aindexDir!=null&&ew(l.aindexDir,c),{context:u,outputPlugins:i,userConfigOptions:r}}const TT=`.agents/skills`,ET=`SKILL.md`;var DT=class extends lx{constructor(){super(`GenericSkillsOutputPlugin`,{outputFileName:ET,treatWorkspaceRootProjectAsProject:!0,skills:{},cleanup:{delete:{project:{dirs:[TT]},global:{dirs:[TT]}}},capabilities:{skills:{scopes:[`project`,`global`],singleScope:!0},mcp:{scopes:[`project`,`global`],singleScope:!0}}})}async declareOutputFiles(e){let t=[],{skills:n}=e.collectedOutputContext;if(n==null||n.length===0)return t;let r=this.selectSingleScopeItems(n,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),i=this.selectSingleScopeItems(n,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`mcp`)??this.getTopicScopeOverride(e,`skills`)),a=(e,n,r)=>{for(let i of r){let r=this.getSkillName(i),a=this.joinPath(e,r);if(t.push({path:this.joinPath(a,ET),scope:n,source:{kind:`skillMain`,skill:i}}),i.childDocs!=null)for(let e of i.childDocs)t.push({path:this.joinPath(a,e.relativePath.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillChildDoc`,content:e.content}});if(i.resources!=null)for(let e of i.resources)t.push({path:this.joinPath(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})}},o=(e,n,r)=>{for(let i of r)i.mcpConfig!=null&&t.push({path:this.joinPath(e,this.getSkillName(i),`mcp.json`),scope:n,source:{kind:`skillMcp`,rawContent:i.mcpConfig.rawContent}})};if(r.selectedScope===`project`||i.selectedScope===`project`)for(let t of this.getProjectOutputProjects(e)){let n=this.resolveProjectRootDir(e,t);if(n==null)continue;let s=$(r.items,t.projectConfig,`skills`),c=$(i.items,t.projectConfig,`skills`),l=this.joinPath(n,TT);r.selectedScope===`project`&&s.length>0&&a(l,`project`,s),i.selectedScope===`project`&&o(l,`project`,c)}if(r.selectedScope!==`global`&&i.selectedScope!==`global`)return t;let s=this.joinPath(this.getHomeDir(),TT),c=this.resolvePromptSourceProjectConfig(e);if(r.selectedScope===`global`){let e=$(r.items,c,`skills`);e.length>0&&a(s,`global`,e)}return i.selectedScope===`global`&&o(s,`global`,$(i.items,c,`skills`)),t}async convertContent(e,t){let n=e.source;switch(n.kind){case`skillMain`:{let e=this.buildSkillFrontMatter(n.skill);return this.buildMarkdownContent(n.skill.content,e,t)}case`skillMcp`:return n.rawContent;case`skillChildDoc`:return n.content;case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;default:throw Error(`Unsupported declaration source for ${this.name}`)}}};const OT=`AGENTS.md`;var kT=class extends lx{constructor(){super(`AgentsOutputPlugin`,{outputFileName:OT,treatWorkspaceRootProjectAsProject:!0,cleanup:{delete:{project:{files:[OT]}}},capabilities:{prompt:{scopes:[`project`],singleScope:!1}}})}async declareOutputFiles(e){let t=[],n=this.getProjectPromptOutputProjects(e);if(!new Set(this.selectPromptScopes(e,[`project`])).has(`project`))return t;for(let[r,i]of n.entries()){let n=this.resolveProjectRootDir(e,i);if(i.rootMemoryPrompt!=null&&n!=null&&t.push({path:this.resolvePath(n,OT),scope:`project`,source:{type:`projectRootMemory`,projectIndex:r}}),i.childMemoryPrompts!=null)for(let[e,n]of i.childMemoryPrompts.entries())t.push({path:this.resolveFullPath(n.dir),scope:`project`,source:{type:`projectChildMemory`,projectIndex:r,childIndex:e}})}return t}async convertContent(e,t){let n=this.getProjectPromptOutputProjects(t),r=e.source,i=r.projectIndex??-1;if(i<0||i>=n.length)throw Error(`Invalid project index in declaration for ${this.name}`);let a=n[i];if(a==null)throw Error(`Project not found for declaration in ${this.name}`);if(r.type===`projectRootMemory`){if(a.rootMemoryPrompt==null)throw Error(`Root memory prompt missing for project index ${i}`);return a.rootMemoryPrompt.content}if(r.type===`projectChildMemory`){let e=r.childIndex??-1,t=a.childMemoryPrompts?.[e];if(t==null)throw Error(`Child memory prompt missing for project ${i}, child ${e}`);return t.content}throw Error(`Unsupported declaration source for ${this.name}`)}};const AT=`CLAUDE.md`;var jT=class extends lx{constructor(){super(`ClaudeCodeCLIOutputPlugin`,{globalConfigDir:`.claude`,outputFileName:AT,treatWorkspaceRootProjectAsProject:!0,toolPreset:`claudeCode`,commands:{subDir:`commands`,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},subagents:{subDir:`agents`,sourceScopes:[`project`],includePrefix:!0,linkSymbol:`-`,ext:`.md`},skills:{subDir:`skills`},rules:{transformFrontMatter:e=>({paths:e.globs.map(Sp)})},cleanup:{delete:{project:{files:[AT],dirs:[`.claude/rules`,`.claude/commands`,`.claude/agents`,`.claude/skills`]},global:{files:[`.claude/CLAUDE.md`],dirs:[`.claude/rules`,`.claude/commands`,`.claude/agents`,`.claude/skills`]}}},wslMirrors:[`~/.claude/settings.json`,`~/.claude/config.json`],capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1},rules:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},subagents:{scopes:[`project`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0}}})}};const MT=yx.CURSOR,NT=px.MCP_CONFIG,PT=mx.COMMANDS,FT=mx.RULES,IT=px.CURSOR_GLOBAL_RULE,LT=mx.CURSOR_SKILLS,RT=px.SKILL,zT=xx.CURSOR;var BT=class extends lx{constructor(){super(`CursorOutputPlugin`,{globalConfigDir:MT,outputFileName:``,treatWorkspaceRootProjectAsProject:!0,dependsOn:[fx.AgentsOutput],indexignore:bx.CURSOR,commands:{subDir:PT,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:LT},rules:{subDir:FT,prefix:`rule`,sourceScopes:[`project`,`global`]},cleanup:{delete:{project:{files:[`.cursor/mcp.json`],dirs:[`.cursor/commands`,`.cursor/rules`],globs:[`.cursor/skills-cursor/*`]},global:{files:[`.cursor/mcp.json`],dirs:[`.cursor/commands`,`.cursor/rules`],globs:[`.cursor/skills-cursor/*`]}},protect:{project:{dirs:Array.from(zT,e=>`.cursor/skills-cursor/${e}`)},global:{dirs:Array.from(zT,e=>`.cursor/skills-cursor/${e}`)}}},capabilities:{prompt:{scopes:[`global`],singleScope:!1},rules:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0},mcp:{scopes:[`project`,`global`],singleScope:!0}}})}async declareCleanupPaths(e){let t=await super.declareCleanupPaths(e);return{...t,delete:(t.delete??[]).map(e=>e.kind!==`glob`||!e.path.replaceAll(`\\`,`/`).endsWith(`/.cursor/${LT}/*`)?e:{...e,excludeBasenames:[...zT]})}}async declareOutputFiles(e){let t=[],{globalMemory:n,commands:r,skills:i,rules:a,aiAgentIgnoreConfigFiles:o}=e.collectedOutputContext,s=this.getGlobalConfigDir(),c=this.resolvePromptSourceProjectConfig(e),l=this.getConcreteProjects(e),d=this.getProjectPromptOutputProjects(e),f=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),p=new Set(this.selectPromptScopes(e,[`global`])),m=new Set(a==null?[]:this.selectRuleScopes(e,a)),h=i==null?{items:[]}:this.selectSingleScopeItems(i,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),g=i==null?{items:[]}:this.selectSingleScopeItems(i,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`mcp`)??this.getTopicScopeOverride(e,`skills`)),_=r==null?{items:[]}:this.selectSingleScopeItems(r,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)),v=(e,n,r)=>{for(let i of r){let r=this.getSkillName(i);if(this.isPreservedSkill(r))continue;let a=u.join(e,LT,r);if(t.push({path:u.join(a,RT),scope:n,source:{kind:`skill`,skill:i}}),i.childDocs!=null)for(let e of i.childDocs)t.push({path:u.join(a,e.relativePath.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillChildDoc`,content:e.content}});if(i.resources!=null)for(let e of i.resources)t.push({path:u.join(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})}},y=(e,n,r)=>{for(let i of r){if(i.mcpConfig==null)continue;let r=u.join(e,LT,this.getSkillName(i));t.push({path:u.join(r,NT),scope:n,source:{kind:`skillMcpConfig`,rawContent:i.mcpConfig.rawContent}})}},b=(e,n,r)=>{if(r.length===0)return;let i=Nx(r,this.log);i.size!==0&&t.push({path:u.join(e,NT),scope:n,source:{kind:`mcpConfig`,mcpServers:Px(i,Fx)}})};if(h.selectedScope===`project`||g.selectedScope===`project`)for(let t of this.getProjectOutputProjects(e)){let n=this.resolveProjectConfigDir(e,t);if(n!=null&&(h.selectedScope===`project`&&v(n,`project`,$(h.items,t.projectConfig,`skills`)),g.selectedScope===`project`)){let e=$(g.items,t.projectConfig,`skills`);y(n,`project`,e),b(n,`project`,e)}}if((h.selectedScope===`global`||g.selectedScope===`global`)&&(h.selectedScope===`global`&&v(s,`global`,$(h.items,c,`skills`)),g.selectedScope===`global`)){let e=$(g.items,c,`skills`);y(s,`global`,e),b(s,`global`,e)}if(_.selectedScope===`project`)for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectConfigDir(e,n);if(r==null)continue;let i=$(_.items,n.projectConfig,`commands`);for(let e of i)t.push({path:u.join(r,PT,this.transformCommandName(e,f)),scope:`project`,source:{kind:`command`,command:e}})}if(_.selectedScope===`global`){let e=$(_.items,c,`commands`);for(let n of e)t.push({path:u.join(s,PT,this.transformCommandName(n,f)),scope:`global`,source:{kind:`command`,command:n}})}if(a!=null&&a.length>0){let n=a.filter(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))===`global`);if(m.has(`global`))for(let e of n)t.push({path:u.join(s,FT,this.buildRuleFileName(e)),scope:`global`,source:{kind:`ruleMdc`,rule:e}});if(m.has(`project`))for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectConfigDir(e,n);if(r==null)continue;let i=Gy($(a.filter(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))===`project`),n.projectConfig,`rules`),n.projectConfig);for(let e of i)t.push({path:u.join(r,FT,this.buildRuleFileName(e)),scope:`project`,source:{kind:`ruleMdc`,rule:e}})}}if(n!=null&&p.has(`global`)){let r=this.buildGlobalRuleContent(n.content,e);for(let n of d){let i=this.resolveProjectConfigDir(e,n);i!=null&&t.push({path:u.join(i,FT,IT),scope:`project`,source:{kind:`globalRuleContent`,content:r}})}}let x=this.getIgnoreOutputPath(),S=this.indexignore==null?void 0:o?.find(e=>e.fileName===this.indexignore);if(x!=null&&S!=null)for(let e of l){let n=e.dirFromWorkspacePath;n==null||e.isPromptSourceProject===!0||t.push({path:u.join(n.basePath,n.path,x),scope:`project`,source:{kind:`ignoreFile`,content:S.content}})}return t}async convertContent(e,t){let n=e.source;switch(n.kind){case`command`:return this.buildCommandContent(n.command,t);case`mcpConfig`:return JSON.stringify({mcpServers:n.mcpServers},null,2);case`skill`:{let e=this.buildSkillFrontMatter(n.skill);return this.buildMarkdownContent(n.skill.content,e,t)}case`skillMcpConfig`:return n.rawContent;case`skillChildDoc`:case`globalRuleContent`:case`ignoreFile`:return n.content;case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;case`ruleMdc`:return this.buildRuleMdcContent(n.rule,t);default:throw Error(`Unsupported declaration source for ${this.name}`)}}buildGlobalRuleContent(e,t){return this.buildMarkdownContent(e,{description:`Global prompt (synced)`,alwaysApply:!0},t)}isPreservedSkill(e){return zT.has(e)}buildRuleMdcContent(e,t){let n={alwaysApply:!1,globs:e.globs.length>0?e.globs.join(`, `):``};return this.buildMarkdownContent(e.content,n,t).split(`
|
|
296
|
+
`}collect(e){return{}}};const kw=[`skills`,`commands`,`agents`,`app`,`ext`,`arch`];var Aw=class extends Hg{constructor(){super(`OrphanFileCleanupEffectInputCapability`),this.registerEffect(`orphan-file-cleanup`,this.cleanupOrphanFiles.bind(this),20)}buildProtectedDeletionGuard(e){return Fg({workspaceDir:e.workspaceDir,aindexDir:e.aindexDir,includeReservedWorkspaceContentRoots:!1,rules:[...Mg(e.userConfigOptions,e.aindexDir,{workspaceDir:e.workspaceDir}),...(e.userConfigOptions.cleanupProtection?.rules??[]).map(e=>({path:e.path,protectionMode:e.protectionMode,reason:e.reason??`configured cleanup protection rule`,source:`configured-cleanup-protection`,matcher:e.matcher??`path`}))]})}buildDeletionPlan(e,t,n){let r=[],i=[],a=[];for(let o of kw){let s=e.path.join(t,o);e.fs.existsSync(s)&&e.fs.statSync(s).isDirectory()&&this.collectDirectoryPlan(e,s,o,n[o],r,i,a)&&i.push(s)}return{filesToDelete:r,dirsToDelete:i,errors:a}}async cleanupOrphanFiles(e){let{fs:t,path:n,aindexDir:r,logger:i,userConfigOptions:a,dryRun:o}=e,s=n.join(r,`dist`);if(!t.existsSync(s))return i.debug({action:`orphan-cleanup`,message:`dist/ directory does not exist, skipping`,distDir:s}),{success:!0,description:`dist/ directory does not exist, nothing to clean`,deletedFiles:[],deletedDirs:[]};let c=a.aindex,l=ww(a),u={skills:c?.skills?.src??`skills`,commands:c?.commands?.src??`commands`,agents:c?.subAgents?.src??`subagents`,app:l.find(e=>e.name===`app`)?.src??`app`,ext:l.find(e=>e.name===`ext`)?.src??`ext`,arch:l.find(e=>e.name===`arch`)?.src??`arch`},d=this.buildDeletionPlan(e,s,u),f=this.buildProtectedDeletionGuard(e),p=zg(d.filesToDelete,f),m=zg(d.dirsToDelete,f),h=Zx(p.safePaths,m.safePaths),g=[...p.violations,...m.violations].sort((e,t)=>e.targetPath.localeCompare(t.targetPath));if(g.length>0)return{success:!1,description:`Protected deletion guard blocked orphan cleanup for ${g.length} path(s)`,deletedFiles:[],deletedDirs:[],error:new sg(`orphan-file-cleanup`,g)};if(o)return{success:!0,description:`Would delete ${h.files.length} files and ${h.dirs.length} directories`,deletedFiles:[...h.files],deletedDirs:[...h.dirs]};let _=[...d.errors];i.debug(`orphan cleanup delete execution started`,{filesToDelete:h.files.length,dirsToDelete:h.dirs.length});let v=await lS({files:h.files,dirs:h.dirs});for(let e of v.fileErrors){let t=e.error instanceof Error?e.error:Error(String(e.error));_.push({path:e.path,error:t}),i.warn(D({code:`ORPHAN_CLEANUP_FILE_DELETE_FAILED`,title:`Orphan cleanup could not delete a file`,operation:`delete`,targetKind:`orphan file`,path:e.path,error:t}))}for(let e of v.dirErrors){let t=e.error instanceof Error?e.error:Error(String(e.error));_.push({path:e.path,error:t}),i.warn(D({code:`ORPHAN_CLEANUP_DIRECTORY_DELETE_FAILED`,title:`Orphan cleanup could not delete a directory`,operation:`delete`,targetKind:`orphan directory`,path:e.path,error:t}))}i.debug(`orphan cleanup delete execution complete`,{deletedFiles:v.deletedFiles.length,deletedDirs:v.deletedDirs.length,errors:_.length});let y=_.length>0;return{success:!y,description:`Deleted ${v.deletedFiles.length} files and ${v.deletedDirs.length} directories`,deletedFiles:[...v.deletedFiles],deletedDirs:[...v.deletedDirs],...y&&{error:Error(`${_.length} errors occurred during cleanup`)}}}collectDirectoryPlan(e,t,n,r,i,a,o){let{fs:s,path:c,aindexDir:l,logger:u}=e,d;try{d=s.readdirSync(t,{withFileTypes:!0})}catch(e){return o.push({path:t,error:e}),u.warn(D({code:`ORPHAN_CLEANUP_DIRECTORY_READ_FAILED`,title:`Orphan cleanup could not read a directory`,operation:`read`,targetKind:`dist cleanup directory`,path:t,error:e})),!1}let f=!1;for(let s of d){let u=c.join(t,s.name);if(s.isDirectory()){this.collectDirectoryPlan(e,u,n,r,i,a,o)?a.push(u):f=!0;continue}if(!s.isFile()){f=!0;continue}this.isOrphanFile(e,u,n,r,l)?i.push(u):f=!0}return!f}isOrphanFile(e,t,n,r,i){let{fs:a,path:o}=e,s=o.basename(t),c=s.endsWith(`.mdx`),l=o.join(i,`dist`,n),u=o.relative(l,t),d=o.dirname(u),f=s.replace(/\.mdx$/,``);return c?!this.getPossibleSourcePaths(o,i,n,r,f,d).some(e=>a.existsSync(e)):!a.existsSync(o.join(i,r,u))}getPossibleSourcePaths(e,t,n,r,i,a){switch(n){case`skills`:{let n=(a===`.`?[i]:a.split(e.sep))[0]??i,o=a===`.`?``:a.slice(n.length+1);return o===``?[..._x.map(i=>e.join(t,r,n,`SKILL${i}`)),..._x.map(i=>e.join(t,r,n,`skill${i}`))]:_x.map(a=>e.join(t,r,n,o,`${i}${a}`))}case`commands`:case`agents`:case`app`:case`ext`:case`arch`:return a===`.`?_x.map(n=>e.join(t,r,`${i}${n}`)):_x.map(n=>e.join(t,r,a,`${i}${n}`));default:return[]}}collect(e){return{}}},jw=class extends Hg{constructor(){super(`SkillDistCleanupEffectInputCapability`),this.registerEffect(`skill-dist-cleanup`,this.cleanupDistSkillArtifacts.bind(this),10)}async cleanupDistSkillArtifacts(e){let{fs:t,logger:n,userConfigOptions:r,aindexDir:i,dryRun:a}=e,o=this.resolveAindexPath(r.aindex.skills.src,i),s=this.resolveAindexPath(r.aindex.skills.dist,i);if(!t.existsSync(s))return n.debug({action:`skill-dist-cleanup`,message:`dist skills directory does not exist, skipping`,srcSkillsDir:o,distSkillsDir:s}),{success:!0,description:`dist skills directory does not exist, nothing to clean`,deletedFiles:[],deletedDirs:[]};let c=this.buildCleanupPlan(e,s),l=Zx(c.filesToDelete,c.dirsToDelete);if(a)return{success:!0,description:`Would delete ${l.files.length} files and ${l.dirs.length} directories`,deletedFiles:[...l.files],deletedDirs:[...l.dirs]};let u=[...c.errors];n.debug(`skill dist cleanup delete execution started`,{filesToDelete:l.files.length,dirsToDelete:l.dirs.length});let d=await lS({files:l.files,dirs:l.dirs});for(let e of d.fileErrors){let t=e.error instanceof Error?e.error:Error(String(e.error));u.push({path:e.path,error:t}),n.warn(D({code:`SKILL_DIST_CLEANUP_FILE_DELETE_FAILED`,title:`Skill dist cleanup could not delete a file`,operation:`delete`,targetKind:`skill dist file`,path:e.path,error:t}))}for(let e of d.dirErrors){let t=e.error instanceof Error?e.error:Error(String(e.error));u.push({path:e.path,error:t}),n.warn(D({code:`SKILL_DIST_CLEANUP_DIRECTORY_DELETE_FAILED`,title:`Skill dist cleanup could not delete a directory`,operation:`delete`,targetKind:`skill dist directory`,path:e.path,error:t}))}n.debug(`skill dist cleanup delete execution complete`,{deletedFiles:d.deletedFiles.length,deletedDirs:d.deletedDirs.length,errors:u.length});let f=u.length>0;return{success:!f,description:`Deleted ${d.deletedFiles.length} files and ${d.deletedDirs.length} directories`,deletedFiles:[...d.deletedFiles],deletedDirs:[...d.deletedDirs],...f&&{error:Error(`${u.length} errors occurred during cleanup`)}}}buildCleanupPlan(e,t){let n=[],r=[],i=[];return this.collectCleanupPlan(e,t,n,r,i)&&r.push(t),{filesToDelete:n,dirsToDelete:r,errors:i}}collectCleanupPlan(e,t,n,r,i){let{fs:a,path:o,logger:s}=e,c;try{c=a.readdirSync(t,{withFileTypes:!0})}catch(e){return i.push({path:t,error:e}),s.warn(D({code:`SKILL_DIST_CLEANUP_DIRECTORY_READ_FAILED`,title:`Skill dist cleanup could not read a directory`,operation:`read`,targetKind:`skill dist directory`,path:t,error:e})),!1}let l=!1;for(let a of c){let s=o.join(t,a.name);if(a.isDirectory()){this.collectCleanupPlan(e,s,n,r,i)?r.push(s):l=!0;continue}if(!a.isFile()){l=!0;continue}if(this.shouldRetainCompiledSkillFile(a.name)){l=!0;continue}n.push(s)}return!l}shouldRetainCompiledSkillFile(e){return e.endsWith(`.mdx`)&&!yx(e)}collect(e){return{}}};const Mw=/export\s+default\s*\{([\s\S]*?)\}/u,Nw=/description\s*:\s*['"`]([^'"`]+)['"`]/u,Pw=/name\s*:\s*['"`]([^'"`]+)['"`]/u,Fw=/displayName\s*:\s*['"`]([^'"`]+)['"`]/u,Iw=/keywords\s*:\s*\[([^\]]+)\]/u,Lw=/author\s*:\s*['"`]([^'"`]+)['"`]/u,Rw=/version\s*:\s*['"`]([^'"`]+)['"`]/u;function zw(e){let t={},n=Mw.exec(e);if(n?.[1]==null)return t;let r=n[1],i=Nw.exec(r);i?.[1]!=null&&(t.description=i[1]);let a=Pw.exec(r);a?.[1]!=null&&(t.name=a[1]);let o=Fw.exec(r);o?.[1]!=null&&(t.displayName=o[1]);let s=Iw.exec(r);s?.[1]!=null&&(t.keywords=s[1].split(`,`).map(e=>e.trim().replaceAll(/['"]/gu,``)).filter(e=>e.length>0));let c=Lw.exec(r);c?.[1]!=null&&(t.author=c[1]);let l=Rw.exec(r);return l?.[1]!=null&&(t.version=l[1]),t}function Bw(...e){let t={};for(let n of e)if(n!=null)for(let[e,r]of Object.entries(n))r!==void 0&&(t[e]=r);return t}function Vw(e){let{logger:t,warnedDerivedNames:n,sourcePath:r,authoredName:i,skillName:a}=e;n?.has(r)!==!0&&(n?.add(r),t.warn(O({code:`SKILL_NAME_IGNORED`,title:`Skill authored name is ignored`,reason:b(`tnmsc ignores the authored skill name "${i}" in favor of the directory-derived name "${a}".`),configPath:r,exactFix:b("Remove the `name` field from the skill front matter or exported metadata.",`Rename the skill directory if you need a different skill name.`),details:{authoredName:i,derivedName:a}})))}const Hw={".ts":`text/typescript`,".tsx":`text/typescript`,".js":`text/javascript`,".jsx":`text/javascript`,".json":`application/json`,".py":`text/x-python`,".java":`text/x-java`,".kt":`text/x-kotlin`,".go":`text/x-go`,".rs":`text/x-rust`,".c":`text/x-c`,".cpp":`text/x-c++`,".cs":`text/x-csharp`,".rb":`text/x-ruby`,".php":`text/x-php`,".swift":`text/x-swift`,".scala":`text/x-scala`,".sql":`application/sql`,".xml":`application/xml`,".yaml":`text/yaml`,".yml":`text/yaml`,".toml":`text/toml`,".csv":`text/csv`,".graphql":`application/graphql`,".txt":`text/plain`,".pdf":`application/pdf`,".docx":`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,".xlsx":`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,".html":`text/html`,".css":`text/css`,".svg":`image/svg+xml`,".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".gif":`image/gif`,".webp":`image/webp`,".ico":`image/x-icon`,".bmp":`image/bmp`},Uw=new Set(`.png,.jpg,.jpeg,.gif,.webp,.ico,.bmp,.tiff,.svg,.exe,.dll,.so,.dylib,.bin,.wasm,.class,.jar,.war,.pyd,.pyc,.pyo,.zip,.tar,.gz,.bz2,.7z,.rar,.ttf,.otf,.woff,.woff2,.eot,.db,.sqlite,.sqlite3,.pdf,.docx,.doc,.xlsx,.xls,.pptx,.ppt,.odt,.ods,.odp`.split(`,`));function Ww(e){return Uw.has(e.toLowerCase())}function Gw(e){return Hw[e.toLowerCase()]}function Kw(...e){return u.join(...e).replaceAll(`\\`,`/`)}var qw=class{ctx;constructor(e){this.ctx=e}async processDirectory(e,t,n){let r=t?`${t}/${e.name}`:e.name;return this.scanSkillDirectoryAsync(n,r)}async processFile(e,t,n){let r=t?`${t}/${e.name}`:e.name;if(this.ctx.scanMode===`distChildDocs`){if(t===``&&e.name===`skill.mdx`||yx(e.name)||!e.name.endsWith(`.mdx`))return{childDocs:[],resources:[]};let i=await this.processChildDoc(r,n);return{childDocs:i?[i]:[],resources:[]}}if(t===``&&e.name===`mcp.json`||yx(e.name)||e.name.endsWith(`.mdx`))return{childDocs:[],resources:[]};let i=this.processResourceFile(e.name,r,n);return{childDocs:[],resources:i?[i]:[]}}async processChildDoc(e,t){try{let n=await pb(t,{mode:`dist`,globalScope:this.ctx.globalScope}),r=wp(n.content);return Dx(r,t),{type:oh.SkillChildDoc,content:r,length:r.length,filePathKind:sh.Relative,markdownAst:n.parsed.markdownAst,markdownContents:n.parsed.markdownContents,...n.parsed.rawFrontMatter!=null&&{rawFrontMatter:n.parsed.rawFrontMatter},relativePath:e,dir:{pathKind:sh.Relative,path:e,basePath:this.ctx.skillDir,getDirectoryName:()=>u.dirname(e),getAbsolutePath:()=>t}}}catch(n){throw this.ctx.logger.error(te({code:`SKILL_CHILD_DOC_COMPILE_FAILED`,title:`Failed to compile skill child doc`,diagnosticText:Ax(n,{operation:`Failed to compile skill child doc.`,promptKind:`skill-child-doc`,logicalName:`${u.basename(this.ctx.skillDir)}/${e.replace(/\.mdx$/u,``)}`,distPath:t,srcPath:Ox(u,t,{distRootDir:this.ctx.skillDir,srcRootDir:this.ctx.sourceSkillDir})}),details:{skillDir:this.ctx.skillDir,relativePath:e,filePath:t}})),n}}processResourceFile(e,t,n){let r=u.extname(e);try{let{content:i,encoding:a,length:o}=this.readFileContent(n,r),s=Gw(r);return{type:oh.SkillResource,extension:r,fileName:e,relativePath:t,sourcePath:n,content:i,encoding:a,length:o,...s!=null&&{mimeType:s}}}catch(r){return this.ctx.logger.warn(D({code:`SKILL_RESOURCE_READ_FAILED`,title:`Failed to read skill resource file`,operation:`read`,targetKind:`skill resource file`,path:n,error:r,details:{relativePath:t,fileName:e,skillDir:this.ctx.skillDir}})),null}}readFileContent(e,t){if(Ww(t)){let t=this.ctx.fs.readFileSync(e);return{content:t.toString(`base64`),encoding:`base64`,length:t.length}}let n=this.ctx.fs.readFileSync(e,`utf8`);return{content:n,encoding:`text`,length:_.from(n,`utf8`).length}}async scanSkillDirectoryAsync(e,t=``){let n=[],r=[],i;try{i=this.ctx.fs.readdirSync(e,{withFileTypes:!0})}catch(t){return this.ctx.logger.warn(D({code:`SKILL_DIRECTORY_SCAN_FAILED`,title:`Failed to scan skill directory`,operation:`scan`,targetKind:`skill directory`,path:e,error:t,details:{skillDir:this.ctx.skillDir,scanMode:this.ctx.scanMode}})),{childDocs:n,resources:r}}for(let a of i){let i=Kw(e,a.name);if(a.isDirectory()){let e=await this.processDirectory(a,t,i);n.push(...e.childDocs),r.push(...e.resources);continue}if(!a.isFile())continue;let o=await this.processFile(a,t,i);n.push(...o.childDocs),r.push(...o.resources)}return{childDocs:n,resources:r}}};function Jw(e,t,n,r=``){let i=[],a=r===``?e:Kw(e,r),o;try{o=t.readdirSync(a,{withFileTypes:!0})}catch(e){return n.warn(D({code:`SKILL_SOURCE_CHILD_SCAN_FAILED`,title:`Failed to scan skill source child docs`,operation:`scan`,targetKind:`skill source child doc directory`,path:a,error:e})),i}for(let a of o){let o=r?`${r}/${a.name}`:a.name;if(a.isDirectory()){i.push(...Jw(e,t,n,o));continue}!a.isFile()||!yx(a.name)||r===``&&a.name===`skill.src.mdx`||i.push(o.replace(/\.src\.mdx$/u,`.mdx`))}return i}function Yw(e,t,n,r,i){if(r.existsSync(t))for(let a of Jw(t,r,i)){let i=u.join(n,a);if(!r.existsSync(i))throw new Cx({kind:`skill child doc`,name:`${e}/${a}`,sourcePath:u.join(t,a.replace(/\.mdx$/u,`.src.mdx`)),expectedDistPath:i})}}function Xw(e,t,n){let r=u.join(e,`mcp.json`);if(t.existsSync(r)){if(!t.statSync(r).isFile()){n.warn(k({code:`SKILL_MCP_CONFIG_NOT_FILE`,title:`Skill MCP config path is not a file`,path:r,expectedKind:`mcp.json file`,actualState:`path exists but is not a regular file`,details:{skillDir:e}}));return}try{let i=t.readFileSync(r,`utf8`),a=JSON.parse(i);if(a.mcpServers==null||typeof a.mcpServers!=`object`){n.warn(O({code:`SKILL_MCP_CONFIG_INVALID`,title:`Skill MCP config is missing mcpServers`,reason:b(`The skill MCP config at "${r}" does not contain a top-level mcpServers object.`),configPath:r,exactFix:b("Add a top-level `mcpServers` object to mcp.json before retrying tnmsc."),details:{skillDir:e}}));return}return{type:oh.SkillMcpConfig,mcpServers:a.mcpServers,rawContent:i}}catch(t){n.warn(O({code:`SKILL_MCP_CONFIG_PARSE_FAILED`,title:`Failed to parse skill MCP config`,reason:b(`tnmsc could not parse the MCP config file at "${r}".`,`Underlying error: ${t instanceof Error?t.message:String(t)}`),configPath:r,exactFix:b(`Fix the JSON syntax in mcp.json and rerun tnmsc.`),details:{skillDir:e,errorMessage:t instanceof Error?t.message:String(t)}}));return}}}async function Zw(e,t,n,r,i,a,o,s,c=[],l=[],d,f,p){let{logger:m,fs:h}=o,g=u.join(i,`skill.mdx`),_=h.existsSync(u.join(a,`skill.src.mdx`))?u.join(a,`skill.src.mdx`):g,v=e,y,x;if(h.existsSync(g)){let t=await pb(g,{mode:`dist`,globalScope:o.globalScope});v=t.rawMdx,y=t.parsed,e=wp(t.content),Dx(e,g),x=t.metadata}let S=Bw(zw(v),f,x),w=new Set,T=y?.yamlFrontMatter?.name;typeof T==`string`&&T.trim().length>0&&w.add(T);let E=S.name;typeof E==`string`&&E.trim().length>0&&w.add(E);for(let e of w)Vw({logger:m,sourcePath:_,authoredName:e,skillName:n,...p!=null&&{warnedDerivedNames:p}});let D=y?.yamlFrontMatter?.description??S?.description;if(D==null||D.trim().length===0)throw m.error(C({code:`SKILL_VALIDATION_FAILED`,title:`Skill description is required`,rootCause:b(`The skill "${n}" does not provide a non-empty description in its compiled metadata or front matter.`),exactFix:b(`Add a non-empty description field to the skill front matter or exported metadata and rebuild the skill.`),possibleFixes:[b("Set `description` in `SKILL.md` front matter."),b(`If you export metadata from code, ensure the exported description is non-empty.`)],details:{skill:n,skillDir:r,yamlDescription:y?.yamlFrontMatter?.description,exportDescription:S?.description}})),Error(`Skill "${n}" validation failed: description is required and cannot be empty`);let O={...S,...y?.yamlFrontMatter??{},name:n,description:D},ee=Kb(O,g);if(!ee.valid)throw Error(ee.errors.join(`
|
|
297
|
+
`));return{type:oh.Skill,content:e,length:e.length,filePathKind:sh.Relative,skillName:n,yamlFrontMatter:O,markdownAst:y?.markdownAst,markdownContents:y?.markdownContents??[],dir:{pathKind:sh.Relative,path:n,basePath:r,getDirectoryName:()=>n,getAbsolutePath:()=>u.join(r,n)},...y?.rawFrontMatter!=null&&{rawFrontMatter:y.rawFrontMatter},...s!=null&&{mcpConfig:s},...c!=null&&c.length>0&&{childDocs:c},...l!=null&&l.length>0&&{resources:l},...d!=null&&{seriName:d}}}var Qw=class extends Hg{constructor(){super(`SkillInputCapability`)}readMcpConfig(e,t,n){return Xw(e,t,n)}async scanSkillDirectory(e,t,n,r=``,i=`srcResources`,a,o){return new qw({fs:t,logger:n,skillDir:e,scanMode:i,...a!=null&&{globalScope:a},...o!=null&&{sourceSkillDir:o}}).scanSkillDirectoryAsync(e,r)}async collect(e){let{userConfigOptions:t,logger:n,fs:r,path:i,globalScope:a}=e,{aindexDir:o}=this.resolveBasePaths(t),s=this.resolveAindexPath(t.aindex.skills.src,o),c=this.resolveAindexPath(t.aindex.skills.dist,o),l=[],u=Nx(r,i,n,a),d=new Set,f=new Map,p=async e=>{let t=f.get(e);if(t!=null)return t;let o=i.join(s,e),l=i.join(c,e),u=r.existsSync(l)?(await this.scanSkillDirectory(l,r,n,``,`distChildDocs`,a,o)).childDocs:[],d=r.existsSync(o)?(await this.scanSkillDirectory(o,r,n,``,`srcResources`,a)).resources:[],p=Xw(o,r,n);Yw(e,o,l,r,n);let m={childDocs:u,resources:d,...p!=null&&{mcpConfig:p}};return f.set(e,m),m},{prompts:m,errors:h}=await u.readDirectoryStructure(s,c,{kind:oh.Skill,entryFileName:`skill`,localeExtensions:vx,hydrateSourceContents:!1,isDirectoryStructure:!0,createPrompt:async(t,n,r,a)=>{let o=i.join(c,r),{childDocs:l,resources:u,mcpConfig:f}=await p(r);return Zw(t,n,r,c,o,i.join(s,r),e,f,l,u,void 0,a,d)}});for(let e of h)n.warn(D({code:`SKILL_PROMPT_READ_FAILED`,title:`Failed to read skill prompt`,operation:e.phase===`scan`?`scan`:`read`,targetKind:`skill prompt`,path:e.path,error:e.error,details:{phase:e.phase}}));if(h.length>0)throw Error(h.map(e=>e.error instanceof Error?e.error.message:String(e.error)).join(`
|
|
298
|
+
`));for(let e of m){let t=e.dist?.prompt;t!=null&&l.push(t)}return{skills:l}}},$w=class e extends Hg{static projectConfigFileName=`project.json5`;static conflictingProjectSeriesCode=`AINDEX_PROJECT_SERIES_NAME_CONFLICT`;constructor(){super(`AindexInputCapability`)}loadProjectConfig(t,n,r,i,a,o){let s=a.join(n,r,t,e.projectConfigFileName);if(i.existsSync(s))try{let n=i.readFileSync(s,`utf8`);try{return v.parse(n)}catch(n){o.warn(O({code:`AINDEX_PROJECT_JSON5_INVALID`,title:`Failed to parse ${e.projectConfigFileName} for ${t}`,reason:b(`tnmsc could not parse the ${e.projectConfigFileName} file for "${t}".`,`Underlying error: ${n instanceof Error?n.message:String(n)}`),configPath:s,exactFix:b(`Fix the JSON5 syntax in ${e.projectConfigFileName} and rerun tnmsc.`),details:{projectName:t,errorMessage:n instanceof Error?n.message:String(n)}}));return}}catch(n){o.warn(O({code:`AINDEX_PROJECT_JSON5_READ_FAILED`,title:`Failed to load ${e.projectConfigFileName} for ${t}`,reason:b(`tnmsc could not read the ${e.projectConfigFileName} file for "${t}".`,`Underlying error: ${n instanceof Error?n.message:String(n)}`),configPath:s,exactFix:b(`Ensure ${e.projectConfigFileName} exists, is readable, and contains valid JSON5.`),details:{projectName:t,errorMessage:n instanceof Error?n.message:String(n)}}));return}}async scanSeriesProjects(e,t,n,r,i){let{logger:a,fs:o,path:s}=e;return(await Promise.all(i.map(async e=>{let i=this.resolveAindexPath(e.dist,n);if((await o.promises.stat(i).catch(()=>void 0))?.isDirectory()!==!0)return[];try{let c=(await o.promises.readdir(i,{withFileTypes:!0})).filter(e=>e.isDirectory()).sort((e,t)=>e.name.localeCompare(t.name)),l=[];for(let i of c){let c=i.name===r,u=this.loadProjectConfig(i.name,n,e.src,o,s,a);l.push({name:i.name,promptSeries:e.name,...c&&{isPromptSourceProject:!0},...u!=null&&{projectConfig:u},dirFromWorkspacePath:{pathKind:sh.Relative,path:i.name,basePath:t,getDirectoryName:()=>i.name,getAbsolutePath:()=>s.resolve(t,i.name)}})}return l}catch(t){return a.error(D({code:`AINDEX_PROJECT_DIRECTORY_SCAN_FAILED`,title:`Failed to scan aindex ${e.name} projects directory`,operation:`scan`,targetKind:`aindex ${e.name} projects directory`,path:i,error:t})),[]}}))).flat()}loadFallbackProjectConfig(e,t,n){for(let r of ww(n.userConfigOptions)){let i=this.loadProjectConfig(e,t,r.src,n.fs,n.path,n.logger);if(i!=null)return i}}assertNoCrossSeriesProjectNameConflicts(t,n,r){let{logger:i,fs:a,path:o}=t,s=Ew(r.flatMap(e=>{let t=o.join(n,e.src);return a.existsSync(t)&&a.statSync(t).isDirectory()?a.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(n=>({projectName:n.name,seriesName:e.name,seriesDir:o.join(t,n.name)})):[]}));if(s.length!==0)throw i.error(O({code:e.conflictingProjectSeriesCode,title:`Project names must be unique across app, ext, and arch`,reason:b(`tnmsc maps project-scoped outputs back to workspace project names, so app/ext/arch cannot reuse the same directory name.`,`Conflicting project names: ${s.map(e=>e.projectName).join(`, `)}`),exactFix:b(`Rename the conflicting project directory in one of the app/ext/arch source trees and rerun tnmsc.`),possibleFixes:s.map(e=>b(`"${e.projectName}" is currently declared in: ${e.refs.map(e=>`${e.seriesName} (${e.seriesDir})`).join(`, `)}`)),details:{aindexDir:n,conflicts:s.map(e=>({projectName:e.projectName,refs:e.refs.map(e=>({seriesName:e.seriesName,seriesDir:e.seriesDir}))}))}})),Error(`Aindex project series name conflict`)}async collect(e){let{userConfigOptions:t,logger:n,fs:r,path:i}=e,{workspaceDir:a,aindexDir:o}=this.resolveBasePaths(t),s=i.basename(o),c=ww(t);this.assertNoCrossSeriesProjectNameConflicts(e,o,c);let l=await this.scanSeriesProjects(e,a,o,s,c);if(l.length===0&&r.existsSync(a)&&r.statSync(a).isDirectory()){n.debug(`no projects in dist/app, dist/ext, or dist/arch; falling back to workspace scan`,{workspaceDir:a});try{let t=r.readdirSync(a,{withFileTypes:!0}).filter(e=>e.isDirectory()).sort((e,t)=>e.name.localeCompare(t.name));for(let n of t){if(n.name.startsWith(`.`))continue;let t=n.name===s,r=this.loadFallbackProjectConfig(n.name,o,e);l.push({name:n.name,...t&&{isPromptSourceProject:!0},...r!=null&&{projectConfig:r},dirFromWorkspacePath:{pathKind:sh.Relative,path:n.name,basePath:a,getDirectoryName:()=>n.name,getAbsolutePath:()=>i.resolve(a,n.name)}})}}catch(e){n.error(D({code:`WORKSPACE_DIRECTORY_SCAN_FAILED`,title:`Failed to scan workspace directory`,operation:`scan`,targetKind:`workspace directory`,path:a,error:e}))}}return{workspace:{directory:{pathKind:sh.Absolute,path:a,getDirectoryName:()=>i.basename(a)},projects:l}}}},eT=class extends Hg{constructor(){super(`CommandInputCapability`)}createCommandPrompt(e,t,n,r,i,a){let{path:o}=i,s=n.replaceAll(`\\`,`/`),c=s.indexOf(`/`),l=c===-1?void 0:s.slice(0,c),u=(c===-1?s:s.slice(c+1)).replace(/\.mdx$/,``),d=u.indexOf(`_`),f=l??(d===-1?void 0:u.slice(0,Math.max(0,d))),p=l!=null||d===-1?u:u.slice(Math.max(0,d+1)),m=o.join(r,`${n}.mdx`),h=`${n}.mdx`,g=a,_={type:oh.Command,content:e,length:e.length,filePathKind:sh.Relative,dir:{pathKind:sh.Relative,path:h,basePath:r,getDirectoryName:()=>h.replace(/\.mdx$/,``),getAbsolutePath:()=>m},...f!=null&&{commandPrefix:f},commandName:p};if(g==null)return _;let v=qb(g,m);if(!v.valid)throw Error(v.errors.join(`
|
|
299
|
+
`));return Object.assign(_,{yamlFrontMatter:g}),g.seriName!=null&&Object.assign(_,{seriName:g.seriName}),g.scope===`global`&&Object.assign(_,{globalOnly:!0}),_}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i,globalScope:a}=e,o=this.resolveBasePaths(t),s=this.resolveAindexPath(t.aindex.commands.src,o.aindexDir),c=this.resolveAindexPath(t.aindex.commands.dist,o.aindexDir);n.debug(`CommandInputCapability collecting`,{srcDir:s,distDir:c,aindexDir:o.aindexDir});let{prompts:l,errors:u}=await Nx(i,r,n,a).readFlatFiles(s,c,{kind:oh.Command,localeExtensions:vx,hydrateSourceContents:!1,isDirectoryStructure:!1,createPrompt:(t,n,r,i)=>this.createCommandPrompt(t,n,r,c,e,i)});n.debug(`CommandInputCapability read complete`,{commandCount:l.length,errorCount:u.length});for(let e of u)n.warn(D({code:`COMMAND_PROMPT_READ_FAILED`,title:`Failed to read command prompt`,operation:e.phase===`scan`?`scan`:`read`,targetKind:`command prompt`,path:e.path,error:e.error,details:{phase:e.phase}}));if(u.length>0)throw Error(u.map(e=>e.error instanceof Error?e.error.message:String(e.error)).join(`
|
|
300
|
+
`));let d=[];for(let e of l){let t=e.dist;if(t?.prompt==null)continue;let{prompt:n,rawMdx:r}=t;d.push(r==null?n:{...n,rawMdxContent:r})}return n.debug(`CommandInputCapability flattened commands`,{count:d.length,commands:d.map(e=>e.commandName)}),{commands:d}}},tT=class extends Hg{constructor(){super(`EditorConfigInputCapability`)}collect(e){let{userConfigOptions:t,fs:n}=e,{workspaceDir:r,aindexDir:i}=this.resolveBasePaths(t),a=[],o=Eh(ch.EditorConfig,`.editorconfig`,i,n,{command:e.runtimeCommand,workspaceDir:r});return o!=null&&a.push(o),{editorConfigFiles:a}}},nT=class extends Hg{constructor(){super(`GitExcludeInputCapability`)}collect(e){let{workspaceDir:t,aindexDir:n}=this.resolveBasePaths(e.userConfigOptions),r=wh(n,fh,{command:e.runtimeCommand,workspaceDir:t});if(!e.fs.existsSync(r))return this.log.debug({action:`collect`,message:`File not found`,path:r}),{};let i=e.fs.readFileSync(r,`utf8`);return i.length===0?(this.log.debug({action:`collect`,message:`File is empty`,path:r}),{}):(this.log.debug({action:`collect`,message:`Loaded file content`,path:r,length:i.length}),{shadowGitExclude:i})}},rT=class extends Hg{constructor(){super(`GitIgnoreInputCapability`)}collect(e){let{workspaceDir:t,aindexDir:n}=this.resolveBasePaths(e.userConfigOptions),r=wh(n,dh,{command:e.runtimeCommand,workspaceDir:t});if(!e.fs.existsSync(r))return this.log.debug({action:`collect`,message:`File not found`,path:r}),{};let i=e.fs.readFileSync(r,`utf8`);return i.length===0?(this.log.debug({action:`collect`,message:`File is empty`,path:r}),{}):(this.log.debug({action:`collect`,message:`Loaded file content`,path:r,length:i.length}),{globalGitIgnore:i})}},iT=class extends Hg{constructor(){super(`GlobalMemoryInputCapability`)}async collect(e){let{userConfigOptions:t,fs:n,path:r,globalScope:i}=e,{aindexDir:a}=this.resolveBasePaths(t),o=rC(),s=rg(),l=this.resolveAindexPath(t.aindex.globalPrompt.dist,a);if(!n.existsSync(l))return this.log.warn(k({code:`GLOBAL_MEMORY_PROMPT_MISSING`,title:`Global memory prompt is missing`,path:l,expectedKind:`compiled global memory prompt file`,actualState:`path does not exist`})),{};if(!n.statSync(l).isFile())return this.log.warn(k({code:`GLOBAL_MEMORY_PROMPT_NOT_FILE`,title:`Global memory prompt path is not a file`,path:l,expectedKind:`compiled global memory prompt file`,actualState:`path exists but is not a regular file`})),{};let u,d;try{d=await pb(l,{mode:`dist`,globalScope:i}),u=d.content,Dx(u,l)}catch(e){throw e instanceof Zg&&(this.log.error(te({code:`GLOBAL_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile global memory prompt`,diagnosticText:Ax(e,{operation:`Failed to compile global memory prompt.`,promptKind:`global-memory`,logicalName:`global-memory`,distPath:l}),details:{promptKind:`global-memory`,distPath:l}})),e instanceof $g&&this.log.error(O({code:`GLOBAL_MEMORY_SCOPE_VARIABLES_MISSING`,title:`Global memory prompt references missing config variables`,reason:b(`The global memory prompt uses scope variables that are not defined in "${o}".`),configPath:o,exactFix:b(`Add the missing variables to "${o}" and rerun tnmsc.`),possibleFixes:[b("If you reference `{profile.name}`, define `profile.name` in the config file.")],details:{promptPath:l,errorMessage:e.message}})),c.exit(1)),e}return this.log.debug({action:`collect`,path:l,contentLength:u.length}),{globalMemory:{type:oh.GlobalMemory,content:u,length:u.length,filePathKind:sh.Relative,...d.parsed.rawFrontMatter!=null&&{rawFrontMatter:d.parsed.rawFrontMatter},markdownAst:d.parsed.markdownAst,markdownContents:d.parsed.markdownContents,dir:{pathKind:sh.Relative,path:r.basename(l),basePath:r.dirname(l),getDirectoryName:()=>r.basename(l),getAbsolutePath:()=>l},parentDirectoryPath:{type:lh.UserHome,directory:{pathKind:sh.Relative,path:``,basePath:s,getDirectoryName:()=>r.basename(s),getAbsolutePath:()=>s}}}}}},aT=class extends Hg{constructor(){super(`JetBrainsConfigInputCapability`)}collect(e){let{userConfigOptions:t,fs:n}=e,{workspaceDir:r,aindexDir:i}=this.resolveBasePaths(t),a=[`.idea/codeStyles/Project.xml`,`.idea/codeStyles/codeStyleConfig.xml`,`.idea/.gitignore`],o=[];for(let t of a){let a=Eh(ch.IntellijIDEA,t,i,n,{command:e.runtimeCommand,workspaceDir:r});a!=null&&o.push(a)}return{jetbrainsConfigFiles:o}}};const oT=`agt.mdx`,sT=[`node_modules`,`.git`];var cT=class extends Hg{constructor(){super(`ProjectPromptInputCapability`,[`AindexInputCapability`])}async collect(e){let{dependencyContext:t,fs:n,userConfigOptions:r,path:i,globalScope:a}=e,{aindexDir:o}=this.resolveBasePaths(r),s=this.resolveAindexPath(r.aindex.workspacePrompt.dist,o),c=t.workspace;if(c==null)return this.log.info(`No workspace found in dependency context, skipping project prompt enhancement`),{};let l=c.projects??[],u=await Promise.all(l.map(async t=>{let s=t.name;if(s==null||t.isWorkspaceRootProject===!0)return t;let c=(t.promptSeries==null?ww(r):[Tw(r,t.promptSeries)]).find(e=>{let t=i.join(o,e.dist,s);return n.existsSync(t)&&n.statSync(t).isDirectory()});if(c==null)return t;let l=i.join(o,c.dist,s),u=t.dirFromWorkspacePath?.getAbsolutePath(),d=await this.readRootMemoryPrompt(e,l,a),f=u==null?[]:await this.scanChildMemoryPrompts(e,l,u,a);return{...t,...t.promptSeries==null?{promptSeries:c.name}:{},...d!=null&&{rootMemoryPrompt:d},...f.length>0&&{childMemoryPrompts:f}}})),d=await this.readWorkspaceRootProjectPrompt(e,s,a,this.resolveWorkspaceRootProjectConfig(l));return{workspace:{directory:c.directory,projects:d==null?u:[...u,d]}}}async readWorkspaceRootProjectPrompt(e,t,n,r){let{fs:i,logger:a}=e;if(!(!i.existsSync(t)||!i.statSync(t).isFile()))try{let e;try{e=await pb(t,{mode:`dist`,globalScope:n}),Dx(e.content,t)}catch(e){if(e instanceof Zg){if(a.error(te({code:`WORKSPACE_ROOT_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile workspace root memory prompt`,diagnosticText:Ax(e,{operation:`Failed to compile workspace root memory prompt.`,promptKind:`workspace-root-memory`,logicalName:t,distPath:t}),details:{promptKind:`workspace-root-memory`,distPath:t}})),e instanceof $g){let n=rC();a.error(O({code:`WORKSPACE_ROOT_MEMORY_SCOPE_VARIABLES_MISSING`,title:`Workspace root memory prompt references missing config variables`,reason:b(`The workspace root memory prompt uses scope variables that are not defined in "${n}".`),configPath:n,exactFix:b(`Define the missing variables in "${n}" and rerun tnmsc.`),details:{promptPath:t,errorMessage:e.message}}))}c.exit(1)}throw e}let i={type:oh.ProjectRootMemory,content:e.content,length:e.content.length,filePathKind:sh.Relative,...e.parsed.yamlFrontMatter!=null&&{yamlFrontMatter:e.parsed.yamlFrontMatter},...e.parsed.rawFrontMatter!=null&&{rawFrontMatter:e.parsed.rawFrontMatter},markdownAst:e.parsed.markdownAst,markdownContents:e.parsed.markdownContents,dir:{pathKind:sh.Root,path:``,getDirectoryName:()=>``}};return{name:`__workspace__`,isWorkspaceRootProject:!0,...r!=null&&{projectConfig:r},rootMemoryPrompt:i}}catch(e){a.error(D({code:`WORKSPACE_ROOT_MEMORY_PROMPT_READ_FAILED`,title:`Failed to read workspace root memory prompt`,operation:`read`,targetKind:`workspace root memory prompt`,path:t,error:e}));return}}resolveWorkspaceRootProjectConfig(e){let t=e.filter(e=>e.isWorkspaceRootProject!==!0);return t.find(e=>e.isPromptSourceProject===!0)?.projectConfig??t[0]?.projectConfig}async readRootMemoryPrompt(e,t,n){let{fs:r,path:i,logger:a}=e,o=i.join(t,oT);if(!(!r.existsSync(o)||!r.statSync(o).isFile()))try{let e;try{e=await pb(o,{mode:`dist`,globalScope:n}),Dx(e.content,o)}catch(e){if(e instanceof Zg){if(a.error(te({code:`PROJECT_ROOT_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile project root memory prompt`,diagnosticText:Ax(e,{operation:`Failed to compile project root memory prompt.`,promptKind:`project-root-memory`,logicalName:o,distPath:o}),details:{promptKind:`project-root-memory`,distPath:o}})),e instanceof $g){let t=rC();a.error(O({code:`PROJECT_ROOT_MEMORY_SCOPE_VARIABLES_MISSING`,title:`Project root memory prompt references missing config variables`,reason:b(`The project root memory prompt uses scope variables that are not defined in "${t}".`),configPath:t,exactFix:b(`Define the missing variables in "${t}" and rerun tnmsc.`),details:{promptPath:o,errorMessage:e.message}}))}c.exit(1)}throw e}return{type:oh.ProjectRootMemory,content:e.content,length:e.content.length,filePathKind:sh.Relative,...e.parsed.yamlFrontMatter!=null&&{yamlFrontMatter:e.parsed.yamlFrontMatter},...e.parsed.rawFrontMatter!=null&&{rawFrontMatter:e.parsed.rawFrontMatter},markdownAst:e.parsed.markdownAst,markdownContents:e.parsed.markdownContents,dir:{pathKind:sh.Root,path:``,getDirectoryName:()=>``}}}catch(e){a.error(D({code:`PROJECT_ROOT_MEMORY_PROMPT_READ_FAILED`,title:`Failed to read project root memory prompt`,operation:`read`,targetKind:`project root memory prompt`,path:o,error:e}));return}}async scanChildMemoryPrompts(e,t,n,r){let{logger:i}=e,a=[];try{await this.scanDirectoryRecursive(e,t,t,n,a,r)}catch(e){i.error(D({code:`PROJECT_CHILD_MEMORY_SCAN_FAILED`,title:`Failed to scan project child memory prompts`,operation:`scan`,targetKind:`project child memory prompt directory`,path:t,error:e}))}return a}async scanDirectoryRecursive(e,t,n,r,i,a){let{fs:o,path:s}=e,c=o.readdirSync(n,{withFileTypes:!0});for(let l of c){if(!l.isDirectory()||sT.includes(l.name))continue;let c=s.join(n,l.name),u=s.join(c,oT);if(o.existsSync(u)&&o.statSync(u).isFile()){let n=await this.readChildMemoryPrompt(e,t,c,r,a);n!=null&&i.push(n)}await this.scanDirectoryRecursive(e,t,c,r,i,a)}}async readChildMemoryPrompt(e,t,n,r,i){let{path:a,logger:o}=e,s=a.join(n,oT);try{let e;try{e=await pb(s,{mode:`dist`,globalScope:i}),Dx(e.content,s)}catch(e){if(e instanceof Zg){if(o.error(te({code:`PROJECT_CHILD_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile project child memory prompt`,diagnosticText:Ax(e,{operation:`Failed to compile project child memory prompt.`,promptKind:`project-child-memory`,logicalName:s,distPath:s}),details:{promptKind:`project-child-memory`,distPath:s}})),e instanceof $g){let t=rC();o.error(O({code:`PROJECT_CHILD_MEMORY_SCOPE_VARIABLES_MISSING`,title:`Project child memory prompt references missing config variables`,reason:b(`The project child memory prompt uses scope variables that are not defined in "${t}".`),configPath:t,exactFix:b(`Define the missing variables in "${t}" and rerun tnmsc.`),details:{promptPath:s,errorMessage:e.message}}))}c.exit(1)}throw e}let l=a.relative(t,n),u=a.join(r,l),d=a.basename(n);return{type:oh.ProjectChildrenMemory,content:e.content,length:e.content.length,filePathKind:sh.Relative,...e.parsed.yamlFrontMatter!=null&&{yamlFrontMatter:e.parsed.yamlFrontMatter},...e.parsed.rawFrontMatter!=null&&{rawFrontMatter:e.parsed.rawFrontMatter},markdownAst:e.parsed.markdownAst,markdownContents:e.parsed.markdownContents,dir:{pathKind:sh.Relative,path:l,basePath:r,getDirectoryName:()=>d,getAbsolutePath:()=>u},workingChildDirectoryPath:{pathKind:sh.Relative,path:l,basePath:r,getDirectoryName:()=>d,getAbsolutePath:()=>u}}}catch(e){o.error(D({code:`PROJECT_CHILD_MEMORY_PROMPT_READ_FAILED`,title:`Failed to read project child memory prompt`,operation:`read`,targetKind:`project child memory prompt`,path:s,error:e}));return}}};const lT=Object.entries(Zb);var uT=class extends Hg{constructor(){super(`ReadmeMdInputCapability`,[`AindexInputCapability`])}async collect(e){let{userConfigOptions:t,logger:n,fs:r,path:i,globalScope:a}=e,{workspaceDir:o,aindexDir:s}=this.resolveBasePaths(t),c=[],l=ww(t),u=Ew(l.flatMap(e=>{let t=this.resolveAindexPath(e.src,s);return r.existsSync(t)&&r.statSync(t).isDirectory()?r.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(n=>({projectName:n.name,seriesName:e.name,seriesDir:i.join(t,n.name)})):[]}));if(u.length>0)throw n.error(O({code:`README_PROJECT_SERIES_NAME_CONFLICT`,title:`Readme project names must be unique across app, ext, and arch`,reason:b(`Readme-family outputs target bare workspace project directories, so app/ext/arch cannot reuse the same project directory name.`,`Conflicting project names: ${u.map(e=>e.projectName).join(`, `)}`),exactFix:b(`Rename the conflicting project directory in one of the app/ext/arch source trees and rerun tnmsc.`),possibleFixes:u.map(e=>b(`"${e.projectName}" is currently declared in: ${e.refs.map(e=>`${e.seriesName} (${e.seriesDir})`).join(`, `)}`)),details:{aindexDir:s,conflicts:u.map(e=>({projectName:e.projectName,refs:e.refs.map(e=>({seriesName:e.seriesName,seriesDir:e.seriesDir}))}))}})),Error(`Readme project series name conflict`);return await Promise.all(l.map(async t=>{let l=this.resolveAindexPath(t.dist,s);if(!(r.existsSync(l)&&r.statSync(l).isDirectory())){n.debug(`aindex project series directory does not exist`,{path:l,series:t.name});return}try{let t=r.readdirSync(l,{withFileTypes:!0}).filter(e=>e.isDirectory()).sort((e,t)=>e.name.localeCompare(t.name));for(let n of t){let t=n.name,r=i.join(l,t);await this.collectReadmeFiles(e,r,t,o,``,c,a)}}catch(e){n.error(D({code:`README_PROJECT_SCAN_FAILED`,title:`Failed to scan aindex ${t.name} projects for readme prompts`,operation:`scan`,targetKind:`aindex ${t.name} project directory`,path:l,error:e}))}})),c.sort((e,t)=>{let n=e.projectName.localeCompare(t.projectName);if(n!==0)return n;let r=e.targetDir.path.localeCompare(t.targetDir.path);return r===0?e.fileKind.localeCompare(t.fileKind):r}),{readmePrompts:c}}async collectReadmeFiles(e,t,n,r,i,a,o){let{fs:s,path:l,logger:u}=e,d=i===``;for(let[e,{src:f}]of lT){let p=l.join(t,f);if(!(!s.existsSync(p)||!s.statSync(p).isFile()))try{let t;try{let{content:e}=await pb(p,{mode:`dist`,globalScope:o});t=e,Dx(t,p)}catch(t){if(t instanceof Zg){if(u.error(te({code:`README_PROMPT_COMPILE_FAILED`,title:`Failed to compile readme-family prompt`,diagnosticText:Ax(t,{operation:`Failed to compile readme-family prompt.`,promptKind:`readme-family`,logicalName:`${n}/${f}`,distPath:p}),details:{promptKind:`readme-family`,distPath:p,projectName:n,fileKind:e}})),t instanceof $g){let e=rC();u.error(O({code:`README_SCOPE_VARIABLES_MISSING`,title:`Readme-family prompt references missing config variables`,reason:b(`The readme-family prompt uses scope variables that are not defined in "${e}".`),configPath:e,exactFix:b(`Define the missing variables in "${e}" and rerun tnmsc.`),details:{promptPath:p,errorMessage:t.message}}))}c.exit(1)}throw t}let s=d?n:l.join(n,i),m={pathKind:sh.Relative,path:s,basePath:r,getDirectoryName:()=>d?n:l.basename(i),getAbsolutePath:()=>l.resolve(r,s)},h={pathKind:sh.Relative,path:l.dirname(p),basePath:r,getDirectoryName:()=>l.basename(l.dirname(p)),getAbsolutePath:()=>l.dirname(p)};a.push({type:oh.Readme,content:t,length:t.length,filePathKind:sh.Relative,projectName:n,targetDir:m,isRoot:d,fileKind:e,markdownContents:[],dir:h})}catch(t){u.warn(D({code:`README_PROMPT_READ_FAILED`,title:`Failed to read readme-family file`,operation:`read`,targetKind:`readme-family prompt file`,path:p,error:t,details:{fileKind:e}}))}}try{let c=s.readdirSync(t,{withFileTypes:!0});for(let s of c)if(s.isDirectory()){let c=d?s.name:l.join(i,s.name),u=l.join(t,s.name);await this.collectReadmeFiles(e,u,n,r,c,a,o)}}catch(e){u.warn(D({code:`README_DIRECTORY_SCAN_FAILED`,title:`Failed to scan readme-family directory`,operation:`scan`,targetKind:`readme-family directory`,path:t,error:e}))}}},dT=class extends Hg{constructor(){super(`RuleInputCapability`)}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i,globalScope:a}=e,o=this.resolveBasePaths(t),s=this.resolveAindexPath(t.aindex.rules.src,o.aindexDir),c=this.resolveAindexPath(t.aindex.rules.dist,o.aindexDir),{prompts:l,errors:u}=await Nx(i,r,n,a).readFlatFiles(s,c,{kind:oh.Rule,localeExtensions:vx,hydrateSourceContents:!1,isDirectoryStructure:!1,createPrompt:async(e,t,n,i)=>{let a=i,o=r.join(c,`${n}.mdx`);if(a!=null){let e=Yb(a,o);if(!e.valid)throw Error(e.errors.join(`
|
|
301
|
+
`))}let s=a?.globs??[],l=a?.scope??`project`,u=a?.seriName,d=n.replaceAll(`\\`,`/`),f=d.includes(`/`)?d.split(`/`)[0]??``:``,p=d.split(`/`).pop()??d,m={type:oh.Rule,content:e,length:e.length,filePathKind:sh.Relative,dir:{pathKind:sh.Relative,path:`${n}.mdx`,basePath:c,getDirectoryName:()=>p,getAbsolutePath:()=>o},prefix:f,ruleName:p,globs:s,scope:l,markdownContents:[]};return a!=null&&Object.assign(m,{yamlFrontMatter:a}),u!=null&&Object.assign(m,{seriName:u}),m}});for(let e of u)n.warn(D({code:`RULE_PROMPT_READ_FAILED`,title:`Failed to read rule prompt`,operation:e.phase===`scan`?`scan`:`read`,targetKind:`rule prompt`,path:e.path,error:e.error,details:{phase:e.phase}}));if(u.length>0)throw Error(u.map(e=>e.error instanceof Error?e.error.message:String(e.error)).join(`
|
|
302
|
+
`));return{rules:l.map(e=>e.dist?.prompt).filter(e=>e!=null)}}},fT=class extends Hg{constructor(){super(`AIAgentIgnoreInputCapability`)}collect(e){let{workspaceDir:t,aindexDir:n}=this.resolveBasePaths(e.userConfigOptions),r=[];for(let i of ph){let a=wh(n,i,{command:e.runtimeCommand,workspaceDir:t});if(!e.fs.existsSync(a)){this.log.debug({action:`collect`,message:`Ignore file not found`,path:a});continue}let o=e.fs.readFileSync(a,`utf8`);if(o.length===0){this.log.debug({action:`collect`,message:`Ignore file is empty`,path:a});continue}r.push({fileName:i,content:o,sourcePath:a}),this.log.debug({action:`collect`,message:`Loaded ignore file`,path:a,fileName:i})}return r.length===0?{}:{aiAgentIgnoreConfigFiles:r}}},pT=class extends Hg{constructor(){super(`SubAgentInputCapability`)}createSubAgentPrompt(e,t,n,r,i,a,o,s){let{fs:c,logger:l,path:u}=a,{agentPrefix:d,agentName:f,canonicalName:p}=_b(n),m=u.join(i,`${n}.mdx`),h=`${n}.mdx`,g=c.existsSync(u.join(r,`${n}.src.mdx`))?u.join(r,`${n}.src.mdx`):m,_=o==null?void 0:(()=>{let e={...o},t=e.name;return typeof t==`string`&&t.trim().length>0&&s?.has(g)!==!0&&(s?.add(g),l.warn(O({code:`SUBAGENT_NAME_IGNORED`,title:`Sub-agent authored name is ignored`,reason:b(`tnmsc ignores the authored sub-agent name "${t}" in favor of the derived path name "${p}".`),configPath:g,exactFix:b("Remove the `name` field from the sub-agent front matter or exported metadata.",`Rename the sub-agent directory or file if you need a different sub-agent name.`),details:{authoredName:t,derivedName:p,logicalName:n}}))),delete e.name,e})(),v={type:oh.SubAgent,content:e,length:e.length,filePathKind:sh.Relative,dir:{pathKind:sh.Relative,path:h,basePath:i,getDirectoryName:()=>h.replace(/\.mdx$/,``),getAbsolutePath:()=>m},...d!=null&&{agentPrefix:d},agentName:f,canonicalName:p};if(_==null)return v;let y=Jb(_,m);if(!y.valid)throw Error(y.errors.join(`
|
|
303
|
+
`));return Object.assign(v,{yamlFrontMatter:_}),_.seriName!=null&&Object.assign(v,{seriName:_.seriName}),v}async collect(e){let{userConfigOptions:t,logger:n,path:r,fs:i,globalScope:a}=e,o=this.resolveBasePaths(t),s=this.resolveAindexPath(t.aindex.subAgents.src,o.aindexDir),c=this.resolveAindexPath(t.aindex.subAgents.dist,o.aindexDir);n.debug(`SubAgentInputCapability collecting`,{srcDir:s,distDir:c,aindexDir:o.aindexDir});let l=Nx(i,r,n,a),u=new Set,{prompts:d,errors:f}=await l.readFlatFiles(s,c,{kind:oh.SubAgent,localeExtensions:vx,hydrateSourceContents:!1,isDirectoryStructure:!1,createPrompt:(t,n,r,i)=>this.createSubAgentPrompt(t,n,r,s,c,e,i,u)});n.debug(`SubAgentInputCapability read complete`,{subAgentCount:d.length,errorCount:f.length});for(let e of f)n.warn(D({code:`SUBAGENT_PROMPT_READ_FAILED`,title:`Failed to read sub-agent prompt`,operation:e.phase===`scan`?`scan`:`read`,targetKind:`sub-agent prompt`,path:e.path,error:e.error,details:{phase:e.phase}}));if(f.length>0)throw Error(f.map(e=>e.error instanceof Error?e.error.message:String(e.error)).join(`
|
|
304
|
+
`));let p=[];for(let e of d){let t=e.dist;if(t?.prompt==null)continue;let{prompt:n,rawMdx:r}=t;p.push(r==null?n:{...n,rawMdxContent:r})}return n.debug(`SubAgentInputCapability flattened subAgents`,{count:p.length,agents:p.map(e=>e.canonicalName)}),{subAgents:p}}},mT=class extends Hg{constructor(){super(`VSCodeConfigInputCapability`)}collect(e){let{userConfigOptions:t,fs:n}=e,{workspaceDir:r,aindexDir:i}=this.resolveBasePaths(t),a=[`.vscode/settings.json`,`.vscode/extensions.json`],o=[];for(let t of a){let a=Eh(ch.VSCode,t,i,n,{command:e.runtimeCommand,workspaceDir:r});a!=null&&o.push(a)}return{vscodeConfigFiles:o}}},hT=class extends Hg{constructor(){super(`WorkspaceInputCapability`)}collect(e){let{userConfigOptions:t}=e,{workspaceDir:n,aindexDir:r}=this.resolveBasePaths(t);return{workspace:{directory:{pathKind:sh.Absolute,path:n,getDirectoryName:()=>u.basename(n)},projects:[]},aindexDir:r}}},gT=class extends Hg{constructor(){super(`ZedConfigInputCapability`)}collect(e){let{userConfigOptions:t,fs:n}=e,{workspaceDir:r,aindexDir:i}=this.resolveBasePaths(t),a=[],o=Eh(ch.Zed,`.zed/settings.json`,i,n,{command:e.runtimeCommand,workspaceDir:r});return o!=null&&a.push(o),{zedConfigFiles:a}}};const _T={workspace:{strategy:`mergeProjects`,getter:e=>e.workspace},vscodeConfigFiles:{strategy:`concat`,getter:e=>e.vscodeConfigFiles},zedConfigFiles:{strategy:`concat`,getter:e=>e.zedConfigFiles},jetbrainsConfigFiles:{strategy:`concat`,getter:e=>e.jetbrainsConfigFiles},editorConfigFiles:{strategy:`concat`,getter:e=>e.editorConfigFiles},commands:{strategy:`concat`,getter:e=>e.commands},subAgents:{strategy:`concat`,getter:e=>e.subAgents},skills:{strategy:`concat`,getter:e=>e.skills},rules:{strategy:`concat`,getter:e=>e.rules},aiAgentIgnoreConfigFiles:{strategy:`concat`,getter:e=>e.aiAgentIgnoreConfigFiles},readmePrompts:{strategy:`concat`,getter:e=>e.readmePrompts},globalMemory:{strategy:`override`,getter:e=>e.globalMemory},aindexDir:{strategy:`override`,getter:e=>e.aindexDir},globalGitIgnore:{strategy:`override`,getter:e=>e.globalGitIgnore},shadowGitExclude:{strategy:`override`,getter:e=>e.shadowGitExclude}};function vT(e,t){return t==null?e??[]:e==null?t:[...e,...t]}function yT(e){return e.isWorkspaceRootProject===!0?`workspace-root:${e.name??``}`:`${e.promptSeries??`workspace`}:${e.name??``}`}function bT(e,t){let n=new Map;for(let t of e.projects)n.set(yT(t),t);for(let e of t.projects)n.set(yT(e),e);return{directory:t.directory??e.directory,projects:[...n.values()]}}function xT(e,t){return t==null?e:e==null?t:bT(e,t)}function ST(e,t,n){switch(n){case`concat`:return vT(e,t);case`override`:return t??e;case`mergeProjects`:return xT(e,t);default:return t??e}}function CT(e,t){let n={};for(let[r,i]of Object.entries(_T)){let a=ST(i.getter(e),i.getter(t),i.strategy);a!=null&&(n[r]=a)}return n}function wT(e,t,n){let r=e.dependsOn??[];if(r.length===0)return{};let i=new Set,a={};for(let e of r){if(i.has(e))continue;i.add(e);let r=t.get(e);r!=null&&(a=n(a,r))}return a}function TT(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.at(-1);if(e==null)return[...n];let t=a.indexOf(e);return a.slice(t)}i.clear(),a.length=0}return[...n]}function ET(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 cx(n.name,r)}let n=new Map;for(let t of e)n.set(t.name,t);let r=new Map;for(let t of e)r.set(t.name,0);let i=new Map;for(let t of e)i.set(t.name,[]);for(let t of e){let e=t.dependsOn??[];for(let n of e){r.set(t.name,(r.get(t.name)??0)+1);let e=i.get(n)??[];e.push(t.name),i.set(n,e)}}let a=[];for(let t of e)r.get(t.name)===0&&a.push(t.name);let o=[],s=new Map;for(let t=0;t<e.length;t++){let n=e[t];n!=null&&s.set(n.name,t)}for(;a.length>0;){let e=a.shift();if(e==null)continue;let t=n.get(e);if(t==null)continue;o.push(t);let c=(i.get(e)??[]).sort((e,t)=>(s.get(e)??-1)-(s.get(t)??-1));for(let e of c){let t=(r.get(e)??0)-1;r.set(e,t),t===0&&a.push(e)}}if(o.length===e.length)return o;throw new lx(TT(e,r))}function DT(){return[new jw,new Aw,new Ow]}function OT(){return[new hT,new $w,new mT,new gT,new aT,new tT,new Qw,new eT,new pT,new dT,new iT,new cT,new uT,new rT,new nT,new fT]}function kT(e){if(e==null||e.length===0)return`execute`;let t=uw(ow(e.filter(e=>e!=null)));if(!(t.helpFlag||t.versionFlag||t.unknownCommand!=null)){if(t.subcommand===`clean`)return`clean`;if(t.subcommand===`plugins`)return`plugins`;if(t.subcommand===`dry-run`||t.dryRun)return`dry-run`;if(t.subcommand==null)return`execute`}}async function AT(e){let{pipelineArgs:t,userConfigOptions:n,userConfig:r,capabilities:a,includeBuiltinEffects:o=!0}=e,s=be(`InputRuntime`,n.logLevel),c=kT(t),l={logger:s,userConfigOptions:n,fs:i,path:u,glob:Um.default},d=ET([...o?DT():[],...a??OT()]),f=new Qy({userConfig:r}).collect(),p=new eb;p.setGlobalScope(f),s.debug(`global scope collected`,{osInfo:{platform:f.os.platform,arch:f.os.arch,shellKind:f.os.shellKind},hasProfile:Object.keys(f.profile).length>0,hasTool:Object.keys(f.tool).length>0});let m=new Map,h={};for(let e of d){let t=wT(e,m,CT),n={...l,dependencyContext:t,...c==null?{}:{runtimeCommand:c},globalScope:f,scopeRegistry:p},r=e;r.executeEffects!=null&&await r.executeEffects(n,!1);let i=await e.collect(n);m.set(e.name,i),h=CT(h,i);let a=e;if(a.getRegisteredScopes!=null){let t=a.getRegisteredScopes();for(let{namespace:n,values:r}of t)p.register(n,r,$y.PluginRegistered),s.debug(`input capability scope registered`,{capability:e.name,namespace:n,keys:Object.keys(r)})}}return h}function jT(e){return`declarativeOutput`in e}function MT(e){return`collect`in e&&!jT(e)}const NT={version:`0.0.0`,workspaceDir:`~/project`,logLevel:`info`,aindex:{dir:`aindex`,skills:{src:`skills`,dist:`dist/skills`},commands:{src:`commands`,dist:`dist/commands`},subAgents:{src:`subagents`,dist:`dist/subagents`},rules:{src:`rules`,dist:`dist/rules`},globalPrompt:{src:`global.src.mdx`,dist:`dist/global.mdx`},workspacePrompt:{src:`workspace.src.mdx`,dist:`dist/workspace.mdx`},app:{src:`app`,dist:`dist/app`},ext:{src:`ext`,dist:`dist/ext`},arch:{src:`arch`,dist:`dist/arch`}},commandSeriesOptions:{},outputScopes:{},frontMatter:{blankLineAfter:!0},cleanupProtection:{},windows:{},plugins:[]};function PT(e){return{...e.version==null?{}:{version:e.version},...e.workspaceDir==null?{}:{workspaceDir:e.workspaceDir},...e.aindex==null?{}:{aindex:e.aindex},...e.commandSeriesOptions==null?{}:{commandSeriesOptions:e.commandSeriesOptions},...e.outputScopes==null?{}:{outputScopes:e.outputScopes},...e.frontMatter==null?{}:{frontMatter:e.frontMatter},...e.cleanupProtection==null?{}:{cleanupProtection:e.cleanupProtection},...e.windows==null?{}:{windows:e.windows},...e.logLevel==null?{}:{logLevel:e.logLevel}}}function FT(...e){let t={...NT};return e.reduce((e,t)=>IT(e,t),t)}function IT(e,t){let n=t.plugins,r=t.commandSeriesOptions,i=t.outputScopes,a=t.frontMatter,o=t.cleanupProtection,s=t.windows;return{...e,...t,aindex:LT(e.aindex,t.aindex),plugins:[...e.plugins,...n??[]],commandSeriesOptions:RT(e.commandSeriesOptions,r),outputScopes:BT(e.outputScopes,i),frontMatter:VT(e.frontMatter,a),cleanupProtection:HT(e.cleanupProtection,o),windows:UT(e.windows,s)}}function LT(e,t){return t==null?e:{dir:t.dir??e.dir,skills:{...e.skills,...t.skills},commands:{...e.commands,...t.commands},subAgents:{...e.subAgents,...t.subAgents},rules:{...e.rules,...t.rules},globalPrompt:{...e.globalPrompt,...t.globalPrompt},workspacePrompt:{...e.workspacePrompt,...t.workspacePrompt},app:{...e.app,...t.app},ext:{...e.ext,...t.ext},arch:{...e.arch,...t.arch}}}function RT(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 zT(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{...e,...t}}function BT(e,t){if(t==null)return e??{};if(e==null)return t;let n={};if(e.plugins!=null)for(let[t,r]of Object.entries(e.plugins))r!=null&&(n[t]={...r});if(t.plugins!=null)for(let[e,r]of Object.entries(t.plugins)){let t=zT(n[e],r);t!=null&&(n[e]=t)}return Object.keys(n).length===0?{}:{plugins:n}}function VT(e,t){return t==null?e:{...e,...t}}function HT(e,t){return t==null?e??{}:e==null?t:{rules:[...e.rules??[],...t.rules??[]]}}function UT(e,t){if(t==null)return e??{};if(e==null)return t;let n=e.wsl2,r=t.wsl2;return{...e,...t,...n!=null||r!=null?{wsl2:{...n,...r}}:{}}}function WT(e){return`pluginOptions`in e||`configLoaderOptions`in e||`loadUserConfig`in e||`cwd`in e||`pipelineArgs`in e}function GT(e){return WT(e)?{hasExplicitProgrammaticPlugins:Object.hasOwn(e.pluginOptions??{},`plugins`),explicitProgrammaticPlugins:e.pluginOptions?.plugins}:{hasExplicitProgrammaticPlugins:Object.hasOwn(e,`plugins`),explicitProgrammaticPlugins:e.plugins}}function KT(e,t){let n=e;return n.includes(dx.WORKSPACE)&&(n=n.replace(dx.WORKSPACE,t)),u.normalize(og(n))}function qT(e){let t=KT(e.workspaceDir,``),n=u.join(t,e.aindex.dir);return Xb({workspace:{directory:{pathKind:sh.Absolute,path:t,getDirectoryName:()=>u.basename(t)},projects:[]},aindexDir:n})}function JT(e){return kT(e)===`plugins`}async function YT(e={}){let t,n,r,i,a;WT(e)?({pluginOptions:r={},cwd:n,configLoaderOptions:i,pipelineArgs:a}={pluginOptions:e.pluginOptions,cwd:e.cwd,configLoaderOptions:e.configLoaderOptions,pipelineArgs:e.pipelineArgs},t=e.loadUserConfig??!0):(r=e,t=!0,i=void 0,a=void 0);let o={},s=!1,c=[],l;if(t)try{let e=oC(i).load(n);s=e.found,c=e.sources,e.found&&(o=PT(e.config),l=e.config)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load user config: ${t}`)}let u=FT(o,r),{plugins:d=[],logLevel:f}=u,p=be(`defineConfig`,f);s?p.info(`user config loaded`,{sources:c}):p.info(`no user config found, using defaults/programmatic options`,{workspaceDir:u.workspaceDir,aindexDir:u.aindex.dir,logLevel:u.logLevel});let m=d.filter(jT),h=d.filter(MT);return ix(m,u),{mergedOptions:u,outputPlugins:m,inputCapabilities:h,...l!=null&&{userConfigFile:l},...a!=null&&{pipelineArgs:a},userConfigFound:s,userConfigSources:c}}async function XT(e={}){let{hasExplicitProgrammaticPlugins:t,explicitProgrammaticPlugins:n}=GT(e),{mergedOptions:r,outputPlugins:i,inputCapabilities:a,userConfigFile:o,pipelineArgs:s}=await YT(e),c=be(`defineConfig`,r.logLevel);if(JT(s))return{context:qT(r),outputPlugins:i,userConfigOptions:r};let l=await AT({userConfigOptions:r,...a.length>0?{capabilities:a}:{},includeBuiltinEffects:!(a.length>0||t&&(n?.length??0)===0),...s==null?{}:{pipelineArgs:s},...o==null?{}:{userConfig:o}});if(l.workspace==null)throw Error(`Workspace not initialized by any plugin`);let u=Xb({workspace:l.workspace,...l.vscodeConfigFiles!=null&&{vscodeConfigFiles:l.vscodeConfigFiles},...l.zedConfigFiles!=null&&{zedConfigFiles:l.zedConfigFiles},...l.jetbrainsConfigFiles!=null&&{jetbrainsConfigFiles:l.jetbrainsConfigFiles},...l.editorConfigFiles!=null&&{editorConfigFiles:l.editorConfigFiles},...l.commands!=null&&{commands:l.commands},...l.subAgents!=null&&{subAgents:l.subAgents},...l.skills!=null&&{skills:l.skills},...l.rules!=null&&{rules:l.rules},...l.globalMemory!=null&&{globalMemory:l.globalMemory},...l.aiAgentIgnoreConfigFiles!=null&&{aiAgentIgnoreConfigFiles:l.aiAgentIgnoreConfigFiles},...l.aindexDir!=null&&{aindexDir:l.aindexDir},...l.readmePrompts!=null&&{readmePrompts:l.readmePrompts},...l.globalGitIgnore!=null&&{globalGitIgnore:l.globalGitIgnore},...l.shadowGitExclude!=null&&{shadowGitExclude:l.shadowGitExclude}});return l.aindexDir!=null&&bw(l.aindexDir,c),{context:u,outputPlugins:i,userConfigOptions:r}}const ZT=`.agents/skills`,QT=`SKILL.md`;var $T=class extends ux{constructor(){super(`GenericSkillsOutputPlugin`,{outputFileName:QT,treatWorkspaceRootProjectAsProject:!0,skills:{},cleanup:{delete:{project:{dirs:[ZT]},global:{dirs:[ZT]}}},capabilities:{skills:{scopes:[`project`,`global`],singleScope:!0},mcp:{scopes:[`project`,`global`],singleScope:!0}}})}async declareOutputFiles(e){let t=[],{skills:n}=e.collectedOutputContext;if(n==null||n.length===0)return t;let r=this.selectSingleScopeItems(n,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),i=this.selectSingleScopeItems(n,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`mcp`)??this.getTopicScopeOverride(e,`skills`)),a=(e,n,r)=>{for(let i of r){let r=this.getSkillName(i),a=this.joinPath(e,r);if(t.push({path:this.joinPath(a,QT),scope:n,source:{kind:`skillMain`,skill:i}}),i.childDocs!=null)for(let e of i.childDocs)t.push({path:this.joinPath(a,e.relativePath.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillChildDoc`,content:e.content}});if(i.resources!=null)for(let e of i.resources)t.push({path:this.joinPath(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})}},o=(e,n,r)=>{for(let i of r)i.mcpConfig!=null&&t.push({path:this.joinPath(e,this.getSkillName(i),`mcp.json`),scope:n,source:{kind:`skillMcp`,rawContent:i.mcpConfig.rawContent}})};if(r.selectedScope===`project`||i.selectedScope===`project`)for(let t of this.getProjectOutputProjects(e)){let n=this.resolveProjectRootDir(e,t);if(n==null)continue;let s=$(r.items,t.projectConfig,`skills`),c=$(i.items,t.projectConfig,`skills`),l=this.joinPath(n,ZT);r.selectedScope===`project`&&s.length>0&&a(l,`project`,s),i.selectedScope===`project`&&o(l,`project`,c)}if(r.selectedScope!==`global`&&i.selectedScope!==`global`)return t;let s=this.joinPath(this.getHomeDir(),ZT),c=this.resolvePromptSourceProjectConfig(e);if(r.selectedScope===`global`){let e=$(r.items,c,`skills`);e.length>0&&a(s,`global`,e)}return i.selectedScope===`global`&&o(s,`global`,$(i.items,c,`skills`)),t}async convertContent(e,t){let n=e.source;switch(n.kind){case`skillMain`:{let e=this.buildSkillFrontMatter(n.skill);return this.buildMarkdownContent(n.skill.content,e,t)}case`skillMcp`:return n.rawContent;case`skillChildDoc`:return n.content;case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;default:throw Error(`Unsupported declaration source for ${this.name}`)}}};const eE=`AGENTS.md`;var tE=class extends ux{constructor(){super(`AgentsOutputPlugin`,{outputFileName:eE,treatWorkspaceRootProjectAsProject:!0,capabilities:{prompt:{scopes:[`project`],singleScope:!1}}})}async declareCleanupPaths(e){let t=await super.declareCleanupPaths(e);return{...t,delete:[...t.delete??[],...this.buildProjectPromptCleanupTargets(e,eE)]}}async declareOutputFiles(e){let t=[],n=this.getProjectPromptOutputProjects(e);if(!new Set(this.selectPromptScopes(e,[`project`])).has(`project`))return t;for(let[r,i]of n.entries()){let n=this.resolveProjectRootDir(e,i);if(i.rootMemoryPrompt!=null&&n!=null&&t.push({path:this.resolvePath(n,eE),scope:`project`,source:{type:`projectRootMemory`,projectIndex:r}}),i.childMemoryPrompts!=null)for(let[e,n]of i.childMemoryPrompts.entries())t.push({path:this.resolveFullPath(n.dir),scope:`project`,source:{type:`projectChildMemory`,projectIndex:r,childIndex:e}})}return t}async convertContent(e,t){let n=this.getProjectPromptOutputProjects(t),r=e.source,i=r.projectIndex??-1;if(i<0||i>=n.length)throw Error(`Invalid project index in declaration for ${this.name}`);let a=n[i];if(a==null)throw Error(`Project not found for declaration in ${this.name}`);if(r.type===`projectRootMemory`){if(a.rootMemoryPrompt==null)throw Error(`Root memory prompt missing for project index ${i}`);return a.rootMemoryPrompt.content}if(r.type===`projectChildMemory`){let e=r.childIndex??-1,t=a.childMemoryPrompts?.[e];if(t==null)throw Error(`Child memory prompt missing for project ${i}, child ${e}`);return t.content}throw Error(`Unsupported declaration source for ${this.name}`)}};const nE=`CLAUDE.md`;var rE=class extends ux{constructor(){super(`ClaudeCodeCLIOutputPlugin`,{globalConfigDir:`.claude`,outputFileName:nE,treatWorkspaceRootProjectAsProject:!0,toolPreset:`claudeCode`,commands:{subDir:`commands`,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},subagents:{subDir:`agents`,sourceScopes:[`project`],includePrefix:!0,linkSymbol:`-`,ext:`.md`},skills:{subDir:`skills`},rules:{transformFrontMatter:e=>({paths:e.globs.map(Sp)})},cleanup:{delete:{project:{dirs:[`.claude/rules`,`.claude/commands`,`.claude/agents`,`.claude/skills`]},global:{files:[`.claude/CLAUDE.md`],dirs:[`.claude/rules`,`.claude/commands`,`.claude/agents`,`.claude/skills`]}}},wslMirrors:[`~/.claude/settings.json`,`~/.claude/config.json`],capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1},rules:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},subagents:{scopes:[`project`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0}}})}async declareCleanupPaths(e){let t=await super.declareCleanupPaths(e);return{...t,delete:[...t.delete??[],...this.buildProjectPromptCleanupTargets(e,nE)]}}};const iE=bx.CURSOR,aE=mx.MCP_CONFIG,oE=hx.COMMANDS,sE=hx.RULES,cE=mx.CURSOR_GLOBAL_RULE,lE=hx.CURSOR_SKILLS,uE=mx.SKILL,dE=Sx.CURSOR;var fE=class extends ux{constructor(){super(`CursorOutputPlugin`,{globalConfigDir:iE,outputFileName:``,treatWorkspaceRootProjectAsProject:!0,dependsOn:[px.AgentsOutput],indexignore:xx.CURSOR,commands:{subDir:oE,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:lE},rules:{subDir:sE,prefix:`rule`,sourceScopes:[`project`,`global`]},cleanup:{delete:{project:{files:[`.cursor/mcp.json`],dirs:[`.cursor/commands`,`.cursor/rules`],globs:[`.cursor/skills-cursor/*`]},global:{files:[`.cursor/mcp.json`],dirs:[`.cursor/commands`,`.cursor/rules`],globs:[`.cursor/skills-cursor/*`]}},protect:{project:{dirs:Array.from(dE,e=>`.cursor/skills-cursor/${e}`)},global:{dirs:Array.from(dE,e=>`.cursor/skills-cursor/${e}`)}}},capabilities:{prompt:{scopes:[`global`],singleScope:!1},rules:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0},mcp:{scopes:[`project`,`global`],singleScope:!0}}})}async declareCleanupPaths(e){let t=await super.declareCleanupPaths(e);return{...t,delete:(t.delete??[]).map(e=>e.kind!==`glob`||!e.path.replaceAll(`\\`,`/`).endsWith(`/.cursor/${lE}/*`)?e:{...e,excludeBasenames:[...dE]})}}async declareOutputFiles(e){let t=[],{globalMemory:n,commands:r,skills:i,rules:a,aiAgentIgnoreConfigFiles:o}=e.collectedOutputContext,s=this.getGlobalConfigDir(),c=this.resolvePromptSourceProjectConfig(e),l=this.getConcreteProjects(e),d=this.getProjectPromptOutputProjects(e),f=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),p=new Set(this.selectPromptScopes(e,[`global`])),m=new Set(a==null?[]:this.selectRuleScopes(e,a)),h=i==null?{items:[]}:this.selectSingleScopeItems(i,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),g=i==null?{items:[]}:this.selectSingleScopeItems(i,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`mcp`)??this.getTopicScopeOverride(e,`skills`)),_=r==null?{items:[]}:this.selectSingleScopeItems(r,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)),v=(e,n,r)=>{for(let i of r){let r=this.getSkillName(i);if(this.isPreservedSkill(r))continue;let a=u.join(e,lE,r);if(t.push({path:u.join(a,uE),scope:n,source:{kind:`skill`,skill:i}}),i.childDocs!=null)for(let e of i.childDocs)t.push({path:u.join(a,e.relativePath.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillChildDoc`,content:e.content}});if(i.resources!=null)for(let e of i.resources)t.push({path:u.join(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})}},y=(e,n,r)=>{for(let i of r){if(i.mcpConfig==null)continue;let r=u.join(e,lE,this.getSkillName(i));t.push({path:u.join(r,aE),scope:n,source:{kind:`skillMcpConfig`,rawContent:i.mcpConfig.rawContent}})}},b=(e,n,r)=>{if(r.length===0)return;let i=Px(r,this.log);i.size!==0&&t.push({path:u.join(e,aE),scope:n,source:{kind:`mcpConfig`,mcpServers:Fx(i,Ix)}})};if(h.selectedScope===`project`||g.selectedScope===`project`)for(let t of this.getProjectOutputProjects(e)){let n=this.resolveProjectConfigDir(e,t);if(n!=null&&(h.selectedScope===`project`&&v(n,`project`,$(h.items,t.projectConfig,`skills`)),g.selectedScope===`project`)){let e=$(g.items,t.projectConfig,`skills`);y(n,`project`,e),b(n,`project`,e)}}if((h.selectedScope===`global`||g.selectedScope===`global`)&&(h.selectedScope===`global`&&v(s,`global`,$(h.items,c,`skills`)),g.selectedScope===`global`)){let e=$(g.items,c,`skills`);y(s,`global`,e),b(s,`global`,e)}if(_.selectedScope===`project`)for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectConfigDir(e,n);if(r==null)continue;let i=$(_.items,n.projectConfig,`commands`);for(let e of i)t.push({path:u.join(r,oE,this.transformCommandName(e,f)),scope:`project`,source:{kind:`command`,command:e}})}if(_.selectedScope===`global`){let e=$(_.items,c,`commands`);for(let n of e)t.push({path:u.join(s,oE,this.transformCommandName(n,f)),scope:`global`,source:{kind:`command`,command:n}})}if(a!=null&&a.length>0){let n=a.filter(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))===`global`);if(m.has(`global`))for(let e of n)t.push({path:u.join(s,sE,this.buildRuleFileName(e)),scope:`global`,source:{kind:`ruleMdc`,rule:e}});if(m.has(`project`))for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectConfigDir(e,n);if(r==null)continue;let i=Ky($(a.filter(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))===`project`),n.projectConfig,`rules`),n.projectConfig);for(let e of i)t.push({path:u.join(r,sE,this.buildRuleFileName(e)),scope:`project`,source:{kind:`ruleMdc`,rule:e}})}}if(n!=null&&p.has(`global`)){let r=this.buildGlobalRuleContent(n.content,e);for(let n of d){let i=this.resolveProjectConfigDir(e,n);i!=null&&t.push({path:u.join(i,sE,cE),scope:`project`,source:{kind:`globalRuleContent`,content:r}})}}let x=this.getIgnoreOutputPath(),S=this.indexignore==null?void 0:o?.find(e=>e.fileName===this.indexignore);if(x!=null&&S!=null)for(let e of l){let n=e.dirFromWorkspacePath;n==null||e.isPromptSourceProject===!0||t.push({path:u.join(n.basePath,n.path,x),scope:`project`,source:{kind:`ignoreFile`,content:S.content}})}return t}async convertContent(e,t){let n=e.source;switch(n.kind){case`command`:return this.buildCommandContent(n.command,t);case`mcpConfig`:return JSON.stringify({mcpServers:n.mcpServers},null,2);case`skill`:{let e=this.buildSkillFrontMatter(n.skill);return this.buildMarkdownContent(n.skill.content,e,t)}case`skillMcpConfig`:return n.rawContent;case`skillChildDoc`:case`globalRuleContent`:case`ignoreFile`:return n.content;case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;case`ruleMdc`:return this.buildRuleMdcContent(n.rule,t);default:throw Error(`Unsupported declaration source for ${this.name}`)}}buildGlobalRuleContent(e,t){return this.buildMarkdownContent(e,{description:`Global prompt (synced)`,alwaysApply:!0},t)}isPreservedSkill(e){return dE.has(e)}buildRuleMdcContent(e,t){let n={alwaysApply:!1,globs:e.globs.length>0?e.globs.join(`, `):``};return this.buildMarkdownContent(e.content,n,t).split(`
|
|
305
305
|
`).map(e=>{let t=/^(\s*globs:\s*)(['"])(.*)\2\s*$/.exec(e);if(t==null)return e;let n=t[1]??`globs: `,r=t[3]??``;return r.trim().length===0?e:`${n}${r}`}).join(`
|
|
306
|
-
`)}};const
|
|
306
|
+
`)}};const pE=`AGENTS.md`;var mE=class extends ux{constructor(){super(`DroidCLIOutputPlugin`,{globalConfigDir:`.factory`,outputFileName:pE,treatWorkspaceRootProjectAsProject:!0,commands:{transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{},cleanup:{delete:{project:{files:[pE],dirs:[`.factory/commands`,`.factory/skills`]},global:{files:[`.factory/AGENTS.md`],dirs:[`.factory/commands`,`.factory/skills`]}}},capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0}}})}buildSkillMainContent(e,t){let n=e.yamlFrontMatter==null?void 0:{name:this.getSkillName(e),description:e.yamlFrontMatter.description};return this.buildMarkdownContent(e.content,n,t)}};const hE=`.editorconfig`;var gE=class extends ux{constructor(){super(`EditorConfigOutputPlugin`,{cleanup:{delete:{project:{files:[hE]}}},capabilities:{}})}async declareOutputFiles(e){let t=[],{projects:n}=e.collectedOutputContext.workspace,{editorConfigFiles:r}=e.collectedOutputContext;if(r==null||r.length===0)return t;for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null)for(let e of r)t.push({path:this.resolvePath(n.basePath,n.path,hE),scope:`project`,source:{content:e.content}})}return t}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}};const _E=`GEMINI.md`;var vE=class extends ux{constructor(){super(`GeminiCLIOutputPlugin`,{globalConfigDir:`.gemini`,outputFileName:_E,treatWorkspaceRootProjectAsProject:!0,cleanup:{delete:{global:{files:[`.gemini/GEMINI.md`]}}},capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1}}})}async declareCleanupPaths(e){let t=await super.declareCleanupPaths(e);return{...t,delete:[...t.delete??[],...this.buildProjectPromptCleanupTargets(e,_E)]}}},yE=class extends ux{constructor(){super(`GitExcludeOutputPlugin`,{capabilities:{}})}async declareOutputFiles(e){let t=[],{workspace:n,globalGitIgnore:r,shadowGitExclude:i}=e.collectedOutputContext,a=this.buildManagedContent(r,i);if(a.length===0)return t;let o=this.normalizeContent(a),s=new Set,{projects:c}=n;for(let e of c){if(e.dirFromWorkspacePath==null)continue;let n=e.dirFromWorkspacePath.getAbsolutePath(),r=[n,...Jy(n)];for(let e of r){let n=qy(e);if(n==null)continue;let r=u.join(n,`exclude`);s.has(r)||(s.add(r),t.push({path:r,scope:`project`,source:{content:o}}))}}return t}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}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(`
|
|
307
307
|
`)}sanitizeContent(e){return e.split(/\r?\n/).filter(e=>{let t=e.trim();return t.length===0?!0:!(t.startsWith(`#`)&&!t.startsWith(`\\#`))}).join(`
|
|
308
|
-
`).trim()}normalizeContent(e){let t=e.trim();return t.length===0?``:`${t}\n`}};const JT=`AGENTS.md`,YT=`prompts`,XT=`skills`,ZT=`.aiassistant`;var QT=class extends lx{constructor(){super(`JetBrainsAIAssistantCodexOutputPlugin`,{outputFileName:JT,treatWorkspaceRootProjectAsProject:!0,commands:{subDir:YT,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:XT},dependsOn:[fx.AgentsOutput],indexignore:`.aiignore`,cleanup:{delete:{project:{dirs:[`.aiassistant/rules`,`.aiassistant/codex/prompts`,`.aiassistant/codex/skills`]}}},capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0}}})}async declareOutputFiles(e){let t=[],{globalMemory:n,commands:r,skills:i,aiAgentIgnoreConfigFiles:a}=e.collectedOutputContext,o=this.getConcreteProjects(e),s=this.getProjectPromptOutputProjects(e),c=this.getJetBrainsCodexDirs(e),l=new Set(this.selectPromptScopes(e,[`project`,`global`])),d=this.resolvePromptSourceProjectConfig(e),f=r==null?{items:[]}:this.selectSingleScopeItems(r,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)),p=i==null?{items:[]}:this.selectSingleScopeItems(i,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),m=this.getTransformOptionsFromContext(e);if(l.has(`project`))for(let n of s){let r=this.resolveProjectRootDir(e,n);if(r==null)continue;let i=u.join(r,ZT,`rules`);if(n.rootMemoryPrompt!=null&&t.push({path:u.join(i,`always.md`),scope:`project`,source:{kind:`projectRuleContent`,content:this.buildAlwaysRuleContent(n.rootMemoryPrompt.content,e)}}),n.childMemoryPrompts!=null)for(let r of n.childMemoryPrompts)t.push({path:u.join(i,this.buildChildRuleFileName(r)),scope:`project`,source:{kind:`projectRuleContent`,content:this.buildGlobRuleContent(r,e)}})}let h=(e,n,r)=>{for(let i of r){let r=this.getSkillName(i),a=u.join(e,XT,r);if(t.push({path:u.join(a,`SKILL.md`),scope:n,source:{kind:`skill`,skill:i}}),i.childDocs!=null)for(let e of i.childDocs)t.push({path:u.join(a,e.dir.path.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillReference`,content:e.content}});if(i.resources!=null)for(let e of i.resources)t.push({path:u.join(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})}};if(f.selectedScope===`project`||p.selectedScope===`project`)for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectRootDir(e,n);if(r==null)continue;let i=u.join(r,ZT,`codex`);if(f.selectedScope===`project`){let e=$(f.items,n.projectConfig,`commands`);for(let n of e)t.push({path:u.join(i,YT,this.transformCommandName(n,m)),scope:`project`,source:{kind:`command`,command:n}})}p.selectedScope===`project`&&h(i,`project`,$(p.items,n.projectConfig,`skills`))}if(c.length>0){if(n!=null&&l.has(`global`))for(let e of c)t.push({path:u.join(e,JT),scope:`global`,source:{kind:`globalMemory`,content:n.content}});let e=f.selectedScope===`global`?$(f.items,d,`commands`):[],r=p.selectedScope===`global`?$(p.items,d,`skills`):[];for(let n of c){for(let r of e)t.push({path:u.join(n,YT,this.transformCommandName(r,m)),scope:`global`,source:{kind:`command`,command:r}});h(n,`global`,r)}}let g=this.getIgnoreOutputPath(),_=this.indexignore==null?void 0:a?.find(e=>e.fileName===this.indexignore);if(g!=null&&_!=null)for(let e of o){let n=e.dirFromWorkspacePath;n==null||e.isPromptSourceProject===!0||t.push({path:u.join(n.basePath,n.path,g),scope:`project`,source:{kind:`ignoreFile`,content:_.content}})}return t}async convertContent(e,t){let n=e.source;switch(n.kind){case`projectRuleContent`:case`globalMemory`:case`skillReference`:case`ignoreFile`:return n.content;case`command`:return this.buildCommandContent(n.command,t);case`skill`:return this.buildCodexSkillContent(n.skill,t);case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;default:throw Error(`Unsupported declaration source for ${this.name}`)}}async declareCleanupPaths(e){let t=await super.declareCleanupPaths(e),n=this.getJetBrainsCodexDirs(e);if(n.length===0)return t;let r=n.flatMap(e=>[{path:u.join(e,JT),kind:`file`,scope:`global`},{path:u.join(e,YT),kind:`directory`,scope:`global`},{path:u.join(e,XT),kind:`directory`,scope:`global`}]),i=t.delete??[];return{...t,delete:[...i,...r]}}getJetBrainsCodexDirs(e){return e.runtimeTargets.jetbrainsCodexDirs}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,t){return this.buildMarkdownContent(e,{apply:`始终`},t)}buildGlobRuleContent(e,t){let n={apply:`按文件模式`,模式:this.buildChildRulePattern(e)};return this.buildMarkdownContent(e.content,n,t)}buildCodexSkillContent(e,t){let n=e.yamlFrontMatter,r=this.normalizeSkillName(this.getSkillName(e),64),i=this.normalizeToSingleLine(n.description,1024),a={};n.displayName!=null&&(a[`short-description`]=n.displayName),n.version!=null&&(a.version=n.version),n.author!=null&&(a.author=n.author),n.keywords!=null&&n.keywords.length>0&&(a.keywords=[...n.keywords]);let o={name:r,description:i};return Object.keys(a).length>0&&(o.metadata=a),n.allowTools!=null&&n.allowTools.length>0&&(o[`allowed-tools`]=n.allowTools.join(` `)),this.buildMarkdownContent(e.content,o,t)}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 $T=`.idea`;var eE=class extends lx{constructor(){super(`JetBrainsIDECodeStyleConfigOutputPlugin`,{cleanup:{delete:{project:{files:[`.editorconfig`,`.idea/codeStyles/Project.xml`,`.idea/codeStyles/codeStyleConfig.xml`,`.idea/.gitignore`]}}},capabilities:{}})}async declareOutputFiles(e){let t=[],{projects:n}=e.collectedOutputContext.workspace,{jetbrainsConfigFiles:r,editorConfigFiles:i}=e.collectedOutputContext,a=[...r??[],...i??[]];for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null)for(let e of a){let r=this.getTargetRelativePath(e);t.push({path:this.resolvePath(n.basePath,n.path,r),scope:`project`,source:{content:e.content}})}}return t}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}getTargetRelativePath(e){let t=e.dir.path;if(e.type===sh.EditorConfig)return`.editorconfig`;if(e.type!==sh.IntellijIDEA)return this.basename(t);let n=t.indexOf($T);return n===-1?this.joinPath($T,`codeStyles`,this.basename(t)):t.slice(Math.max(0,n))}};const tE=`skills`,nE=`.system`,rE=[`name`,`description`,`developer_instructions`],iE=[`scope`,`seriName`,`argumentHint`,`color`,`namingCase`,`model`];function aE(e){let t={...e};return delete t.allowTools,delete t.allowedTools,t}function oE(e,t){let n=aE(t);return n.name=e,n}const sE={globalConfigDir:`.codex`,outputFileName:`AGENTS.md`,commands:{subDir:`prompts`,scopeRemap:{project:`global`},transformFrontMatter:(e,t)=>aE(t.sourceFrontMatter)},subagents:{subDir:`agents`,sourceScopes:[`project`],scopeRemap:{global:`project`},ext:`.toml`,artifactFormat:`toml`,bodyFieldName:`developer_instructions`,excludedFrontMatterFields:iE,transformFrontMatter:(e,t)=>oE(vb(e),t.sourceFrontMatter),fieldOrder:rE},cleanup:{delete:{project:{dirs:[`.codex/agents`]},global:{files:[`.codex/AGENTS.md`],dirs:[`.codex/prompts`],globs:[`.codex/skills/*`]}},protect:{global:{dirs:[`.codex/${tE}/${nE}`]}}},wslMirrors:[`~/.codex/config.toml`,`~/.codex/auth.json`],dependsOn:[fx.AgentsOutput],capabilities:{prompt:{scopes:[`global`],singleScope:!1},commands:{scopes:[`global`],singleScope:!0},subagents:{scopes:[`project`],singleScope:!0}}};var cE=class extends lx{constructor(){super(`CodexCLIOutputPlugin`,sE)}async declareCleanupPaths(e){let t=await super.declareCleanupPaths(e);return{...t,delete:(t.delete??[]).map(e=>e.kind!==`glob`||!e.path.replaceAll(`\\`,`/`).endsWith(`/.codex/${tE}/*`)?e:{...e,excludeBasenames:[nE]})}}};const lE=`AGENTS.md`,uE=`commands`,dE=`agents`,fE=`skills`;function pE(e,t){let n={},r=t.sourceFrontMatter;if(r?.description!=null&&(n.description=r.description),r?.agent!=null&&(n.agent=r.agent),r?.model!=null&&(n.model=r.model),r?.allowTools!=null&&Array.isArray(r.allowTools)){let e={};for(let t of r.allowTools)e[String(t)]=!0;n.tools=e}for(let[e,t]of Object.entries(r??{}))[`description`,`agent`,`model`,`allowTools`,`namingCase`,`argumentHint`].includes(e)||(n[e]=t);return n}var mE=class extends lx{constructor(){super(`OpencodeCLIOutputPlugin`,{globalConfigDir:`.config/opencode`,outputFileName:lE,treatWorkspaceRootProjectAsProject:!0,commands:{subDir:uE,transformFrontMatter:pE},subagents:{subDir:dE},skills:{subDir:fE},cleanup:{delete:{project:{files:[lE,`.opencode/opencode.json`],dirs:[`.opencode/commands`,`.opencode/agents`,`.opencode/skills`]},global:{files:[`.config/opencode/AGENTS.md`,`.config/opencode/opencode.json`],dirs:[`.config/opencode/commands`,`.config/opencode/agents`,`.config/opencode/skills`]},xdgConfig:{files:[`opencode/AGENTS.md`,`opencode/opencode.json`],dirs:[`opencode/commands`,`opencode/agents`,`opencode/skills`]}}},dependsOn:[fx.AgentsOutput],capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},subagents:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0},mcp:{scopes:[`project`,`global`],singleScope:!0}}})}async declareOutputFiles(e){let t=[],{globalMemory:n,commands:r,subAgents:i,skills:a}=e.collectedOutputContext,o=this.getGlobalConfigDir(),s=new Set(this.selectPromptScopes(e,[`project`,`global`])),c=this.getProjectPromptOutputProjects(e),l=this.resolvePromptSourceProjectConfig(e),d=r==null?{items:[]}:this.selectSingleScopeItems(r,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)),f=i==null?{items:[]}:this.selectSingleScopeItems(i,this.subAgentsConfig.sourceScopes,e=>this.resolveSubAgentSourceScope(e),this.getTopicScopeOverride(e,`subagents`)),p=a==null?{items:[]}:this.selectSingleScopeItems(a,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),m=a==null?{items:[]}:this.selectSingleScopeItems(a,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`mcp`)??this.getTopicScopeOverride(e,`skills`));n!=null&&s.has(`global`)&&t.push({path:u.join(o,lE),scope:`global`,source:{kind:`globalMemory`,content:n.content}});let h=(e,n,r)=>{if(r.length===0)return;let i=Nx(r,this.log);i.size!==0&&t.push({path:u.join(e,`opencode.json`),scope:n,source:{kind:`mcpConfig`,mcpServers:Px(i,Ix)}})},g=(e,n,r)=>{for(let i of r){let r=this.validateAndNormalizeSkillName(this.getSkillName(i)),a=u.join(e,fE,r);if(t.push({path:u.join(a,`SKILL.md`),scope:n,source:{kind:`skillMain`,skill:i,normalizedSkillName:r}}),i.childDocs!=null)for(let e of i.childDocs)t.push({path:u.join(a,e.dir.path.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillReference`,content:e.content}});if(i.resources!=null)for(let e of i.resources)t.push({path:u.join(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})}},_=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});for(let n of c){let r=this.resolveProjectRootDir(e,n);if(r!=null&&(n.rootMemoryPrompt!=null&&s.has(`project`)&&t.push({path:u.join(r,lE),scope:`project`,source:{kind:`projectRootMemory`,content:n.rootMemoryPrompt.content}}),n.childMemoryPrompts!=null&&s.has(`project`)))for(let e of n.childMemoryPrompts)t.push({path:this.resolveFullPath(e.dir),scope:`project`,source:{kind:`projectChildMemory`,content:e.content}})}if(d.selectedScope===`project`||f.selectedScope===`project`||p.selectedScope===`project`||m.selectedScope===`project`)for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectRootDir(e,n);if(r==null)continue;let i=u.join(r,`.opencode`),a=$(d.items,n.projectConfig,`commands`);if(d.selectedScope===`project`)for(let e of a)t.push({path:u.join(i,uE,this.transformCommandName(e,_)),scope:`project`,source:{kind:`command`,command:e}});let o=$(f.items,n.projectConfig,`subAgents`);if(f.selectedScope===`project`)for(let e of o)t.push({path:u.join(i,dE,this.transformSubAgentName(e)),scope:`project`,source:{kind:`subAgent`,agent:e}});let s=$(p.items,n.projectConfig,`skills`);p.selectedScope===`project`&&g(i,`project`,s);let c=$(m.items,n.projectConfig,`skills`);m.selectedScope===`project`&&h(i,`project`,c)}if(d.selectedScope===`global`){let e=$(d.items,l,`commands`);for(let n of e)t.push({path:u.join(o,uE,this.transformCommandName(n,_)),scope:`global`,source:{kind:`command`,command:n}})}if(f.selectedScope===`global`){let e=$(f.items,l,`subAgents`);for(let n of e)t.push({path:u.join(o,dE,this.transformSubAgentName(n)),scope:`global`,source:{kind:`subAgent`,agent:n}})}return p.selectedScope===`global`&&g(o,`global`,$(p.items,l,`skills`)),m.selectedScope===`global`&&h(o,`global`,$(m.items,l,`skills`)),t}async convertContent(e,t){let n=e.source;switch(n.kind){case`globalMemory`:case`projectRootMemory`:case`projectChildMemory`:case`skillReference`:return n.content;case`command`:return this.buildCommandContent(n.command,t);case`subAgent`:{let e=this.buildOpencodeAgentFrontMatter(n.agent);return this.buildMarkdownContent(n.agent.content,e,t)}case`skillMain`:{let e=this.buildOpencodeSkillFrontMatter(n.skill,n.normalizedSkillName);return this.buildMarkdownContent(n.skill.content,e,t)}case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;case`mcpConfig`:return JSON.stringify({$schema:`https://opencode.ai/config.json`,plugin:[`opencode-rules@latest`],mcp:n.mcpServers},null,2);default:throw Error(`Unsupported declaration source for ${this.name}`)}}buildOpencodeAgentFrontMatter(e){let t={},n=e.yamlFrontMatter;if(n?.description!=null&&(t.description=n.description),t.mode=n?.mode??`subagent`,n?.model!=null&&(t.model=n.model),n?.temperature!=null&&(t.temperature=n.temperature),n?.maxSteps!=null&&(t.maxSteps=n.maxSteps),n?.hidden!=null&&(t.hidden=n.hidden),n?.allowTools!=null&&Array.isArray(n.allowTools)){let e={};for(let t of n.allowTools)e[String(t)]=!0;t.tools=e}n?.permission!=null&&typeof n.permission==`object`&&(t.permission=n.permission);for(let[e,r]of Object.entries(n??{}))[`description`,`mode`,`model`,`temperature`,`maxSteps`,`hidden`,`allowTools`,`permission`,`namingCase`,`name`,`color`].includes(e)||(t[e]=r);return t}buildOpencodeSkillFrontMatter(e,t){let n={},r=e.yamlFrontMatter;n.name=t,r?.description!=null&&(n.description=r.description),n.license=r?.license??`MIT`,n.compatibility=r?.compatibility??`opencode`;let i={};for(let e of[`author`,`version`,`keywords`,`category`,`repository`,`displayName`])r?.[e]!=null&&(i[e]=r[e]);let a=new Set([`name`,`description`,`license`,`compatibility`,`namingCase`,`allowTools`,`keywords`,`displayName`,`author`,`version`]);for(let[e,t]of Object.entries(r??{}))a.has(e)||(i[e]=t);return Object.keys(i).length>0&&(n.metadata=i),n}validateAndNormalizeSkillName(e){let t=e.toLowerCase();return t=t.replaceAll(/[^a-z0-9-]+/g,`-`),t=t.replaceAll(/-+/g,`-`),t=t.replaceAll(/^-|-$/g,``),t.length===0?t=`skill`:t.length>64&&(t=t.slice(0,64),t=t.replace(/-$/,``)),t}};const hE=`rules`,gE=`commands`,_E=`skills`,vE=`glob`,yE=`glob`;function bE(e,t){let n=t.sourceFrontMatter,r={description:`Fast command`,type:`user_command`};return n?.description!=null&&(r.description=n.description),n?.argumentHint!=null&&(r.argumentHint=n.argumentHint),n?.allowTools!=null&&Array.isArray(n.allowTools)&&n.allowTools.length>0&&(r.allowTools=n.allowTools),r}var xE=class extends lx{constructor(){super(`QoderIDEPluginOutputPlugin`,{globalConfigDir:`.qoder`,treatWorkspaceRootProjectAsProject:!0,indexignore:`.qoderignore`,commands:{subDir:gE,transformFrontMatter:bE},skills:{subDir:_E},rules:{subDir:hE,sourceScopes:[`project`,`global`]},cleanup:{delete:{project:{dirs:[`.qoder/commands`,`.qoder/rules`,`.qoder/skills`]},global:{dirs:[`.qoder/commands`,`.qoder/rules`,`.qoder/skills`]}}},capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1},rules:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0},mcp:{scopes:[`project`,`global`],singleScope:!0}}})}async declareOutputFiles(e){let t=[],{globalMemory:n,commands:r,skills:i,rules:a,aiAgentIgnoreConfigFiles:o}=e.collectedOutputContext,s=this.getGlobalConfigDir(),c=this.resolvePromptSourceProjectConfig(e),l=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),d=new Set(a==null?[]:this.selectRuleScopes(e,a)),f=new Set(this.selectPromptScopes(e,[`project`,`global`])),p=this.getProjectPromptOutputProjects(e),m=r==null?{items:[]}:this.selectSingleScopeItems(r,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)),h=i==null?{items:[]}:this.selectSingleScopeItems(i,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),g=i==null?{items:[]}:this.selectSingleScopeItems(i,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`mcp`)??this.getTopicScopeOverride(e,`skills`)),_=(e,n,r)=>{for(let i of r){let r=this.getSkillName(i),a=u.join(e,_E,r);if(t.push({path:u.join(a,`SKILL.md`),scope:n,source:{kind:`skillMain`,skill:i}}),i.childDocs!=null)for(let e of i.childDocs)t.push({path:u.join(a,e.relativePath.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillChildDoc`,content:e.content}});if(i.resources!=null)for(let e of i.resources)t.push({path:u.join(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})}},v=(e,n,r)=>{for(let i of r){if(i.mcpConfig==null)continue;let r=u.join(e,_E,this.getSkillName(i));t.push({path:u.join(r,`mcp.json`),scope:n,source:{kind:`skillMcpConfig`,rawContent:i.mcpConfig.rawContent}})}};if(m.selectedScope===`project`)for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectConfigDir(e,n);if(r==null)continue;let i=$(m.items,n.projectConfig,`commands`);for(let e of i)t.push({path:u.join(r,gE,this.transformCommandName(e,l)),scope:`project`,source:{kind:`command`,command:e}})}if(m.selectedScope===`global`){let e=$(m.items,c,`commands`);for(let n of e)t.push({path:u.join(s,gE,this.transformCommandName(n,l)),scope:`global`,source:{kind:`command`,command:n}})}if(h.selectedScope===`project`||g.selectedScope===`project`)for(let t of this.getProjectOutputProjects(e)){let n=this.resolveProjectConfigDir(e,t);n!=null&&(h.selectedScope===`project`&&_(n,`project`,$(h.items,t.projectConfig,`skills`)),g.selectedScope===`project`&&v(n,`project`,$(g.items,t.projectConfig,`skills`)))}if((h.selectedScope===`global`||g.selectedScope===`global`)&&(h.selectedScope===`global`&&_(s,`global`,$(h.items,c,`skills`)),g.selectedScope===`global`&&v(s,`global`,$(g.items,c,`skills`))),n!=null&&f.has(`global`))for(let r of p){let i=this.resolveProjectConfigDir(e,r);i!=null&&t.push({path:u.join(i,hE,`global.md`),scope:`project`,source:{kind:`ruleContent`,content:this.buildAlwaysRuleContent(n.content,e)}})}if(f.has(`project`))for(let n of p){let r=this.resolveProjectConfigDir(e,n);if(r!=null&&(n.rootMemoryPrompt!=null&&t.push({path:u.join(r,hE,`always.md`),scope:`project`,source:{kind:`ruleContent`,content:this.buildAlwaysRuleContent(n.rootMemoryPrompt.content,e)}}),n.childMemoryPrompts!=null))for(let i of n.childMemoryPrompts)t.push({path:u.join(r,hE,this.buildChildRuleFileName(i)),scope:`project`,source:{kind:`ruleContent`,content:this.buildGlobRuleContent(i,e)}})}if(a!=null&&a.length>0&&d.has(`project`))for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectConfigDir(e,n);if(r==null)continue;let i=Gy($(a.filter(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))===`project`),n.projectConfig,`rules`),n.projectConfig);for(let e of i)t.push({path:u.join(r,hE,this.buildRuleFileName(e)),scope:`project`,source:{kind:`rulePrompt`,rule:e}})}if(a!=null&&a.length>0&&d.has(`global`)){let e=a.filter(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))===`global`);for(let n of e)t.push({path:u.join(s,hE,this.buildRuleFileName(n)),scope:`global`,source:{kind:`rulePrompt`,rule:n}})}let y=this.getIgnoreOutputPath(),b=this.indexignore==null?void 0:o?.find(e=>e.fileName===this.indexignore);if(y!=null&&b!=null)for(let n of this.getConcreteProjects(e)){let e=n.dirFromWorkspacePath;e==null||n.isPromptSourceProject===!0||t.push({path:u.join(e.basePath,e.path,y),scope:`project`,source:{kind:`ignoreFile`,content:b.content}})}return t}async convertContent(e,t){let n=e.source;switch(n.kind){case`command`:return this.buildCommandContent(n.command,t);case`ruleContent`:return n.content;case`rulePrompt`:return this.buildRuleContent(n.rule,t);case`skillMain`:{let e=this.buildSkillFrontMatter(n.skill);return this.buildMarkdownContent(n.skill.content,e,t)}case`skillMcpConfig`:return n.rawContent;case`skillChildDoc`:case`ignoreFile`:return n.content;case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;default:throw Error(`Unsupported declaration source for ${this.name}`)}}buildChildRuleFileName(e){let t=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``).replaceAll(`/`,`-`);return`glob-${t.length>0?t:`root`}.md`}buildAlwaysRuleContent(e,t){return this.buildMarkdownContent(e,{trigger:`always_on`,type:`user_command`},t)}buildGlobRuleContent(e,t){let n=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``),r=n.length===0?`**/*`:`${n}/**`;return this.buildMarkdownContent(e.content,{trigger:vE,[yE]:r,type:`user_command`},t)}buildSkillFrontMatter(e){let t=e.yamlFrontMatter;return{name:this.getSkillName(e),description:t.description,type:`user_command`,...t.displayName!=null&&{displayName:t.displayName},...t.keywords!=null&&t.keywords.length>0&&{keywords:t.keywords},...t.author!=null&&{author:t.author},...t.version!=null&&{version:t.version},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}buildRuleFileName(e,t=`rule-`){return`${t}${e.prefix}-${e.ruleName}.md`}buildRuleContent(e,t){let n={trigger:vE,[yE]:e.globs.length>0?e.globs.join(`, `):`**/*`,type:`user_command`};return this.buildMarkdownContent(e.content,n,t)}normalizeRuleScope(e){return e.scope??`global`}};function SE(e){return Xb[e??`Readme`].out}var CE=class extends lx{constructor(){super(`ReadmeMdConfigFileOutputPlugin`,{outputFileName:`README.md`,cleanup:{delete:{project:{files:[`README.md`,`CODE_OF_CONDUCT.md`,`SECURITY.md`]}}},capabilities:{}})}async declareOutputFiles(e){let t=[],{readmePrompts:n}=e.collectedOutputContext;if(n==null||n.length===0)return t;for(let e of n){let n=SE(e.fileKind),r=u.join(e.targetDir.basePath,e.targetDir.path,n);t.push({path:r,scope:`project`,source:{content:e.content}})}return t}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}};const wE=`GLOBAL.md`,TE=`.trae`,EE=`commands`,DE=`skills`;var OE=class extends lx{constructor(){super(`TraeIDEOutputPlugin`,{globalConfigDir:TE,outputFileName:wE,treatWorkspaceRootProjectAsProject:!0,indexignore:`.traeignore`,commands:{subDir:EE,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:DE},cleanup:{delete:{project:{dirs:[`.trae/rules`,`.trae/commands`,`.trae/skills`]},global:{dirs:[`.trae/steering`,`.trae/commands`,`.trae/skills`]}}},capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0}}})}getIgnoreOutputPath(){if(this.indexignore!=null)return u.join(`.trae`,`.ignore`)}getGlobalSteeringDir(){return this.joinPath(this.getGlobalConfigDir(),`steering`)}async declareOutputFiles(e){let t=[],{commands:n,skills:r,globalMemory:i,aiAgentIgnoreConfigFiles:a}=e.collectedOutputContext,o=this.getConcreteProjects(e),s=this.getProjectPromptOutputProjects(e),c=this.resolvePromptSourceProjectConfig(e),l=new Set(this.selectPromptScopes(e,[`project`,`global`])),d=n==null?{items:[]}:this.selectSingleScopeItems(n,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)),f=r==null?{items:[]}:this.selectSingleScopeItems(r,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),p=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});i!=null&&l.has(`global`)&&t.push({path:this.joinPath(this.getGlobalSteeringDir(),wE),scope:`global`,source:{kind:`globalMemory`,content:i.content}});for(let n of s){let r=this.resolveProjectRootDir(e,n);if(r!=null&&n.childMemoryPrompts!=null&&l.has(`project`))for(let i of n.childMemoryPrompts){let n=(i.workingChildDirectoryPath?.path??i.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``),a=this.buildProjectRelativeGlobPattern(n),o=this.buildMarkdownContent([this.buildPathGuardHint(n),``,i.content].join(`
|
|
309
|
-
`),{alwaysApply:!1,globs:a},e);t.push({path:u.join(r,
|
|
310
|
-
`)}buildProjectRelativeGlobPattern(e){return e.length===0?`**/*`:`${e}/**`}};const
|
|
308
|
+
`).trim()}normalizeContent(e){let t=e.trim();return t.length===0?``:`${t}\n`}};const bE=`AGENTS.md`,xE=`prompts`,SE=`skills`,CE=`.aiassistant`;var wE=class extends ux{constructor(){super(`JetBrainsAIAssistantCodexOutputPlugin`,{outputFileName:bE,treatWorkspaceRootProjectAsProject:!0,commands:{subDir:xE,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:SE},dependsOn:[px.AgentsOutput],indexignore:`.aiignore`,cleanup:{delete:{project:{dirs:[`.aiassistant/rules`,`.aiassistant/codex/prompts`,`.aiassistant/codex/skills`]}}},capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0}}})}async declareOutputFiles(e){let t=[],{globalMemory:n,commands:r,skills:i,aiAgentIgnoreConfigFiles:a}=e.collectedOutputContext,o=this.getConcreteProjects(e),s=this.getProjectPromptOutputProjects(e),c=this.getJetBrainsCodexDirs(e),l=new Set(this.selectPromptScopes(e,[`project`,`global`])),d=this.resolvePromptSourceProjectConfig(e),f=r==null?{items:[]}:this.selectSingleScopeItems(r,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)),p=i==null?{items:[]}:this.selectSingleScopeItems(i,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),m=this.getTransformOptionsFromContext(e);if(l.has(`project`))for(let n of s){let r=this.resolveProjectRootDir(e,n);if(r==null)continue;let i=u.join(r,CE,`rules`);if(n.rootMemoryPrompt!=null&&t.push({path:u.join(i,`always.md`),scope:`project`,source:{kind:`projectRuleContent`,content:this.buildAlwaysRuleContent(n.rootMemoryPrompt.content,e)}}),n.childMemoryPrompts!=null)for(let r of n.childMemoryPrompts)t.push({path:u.join(i,this.buildChildRuleFileName(r)),scope:`project`,source:{kind:`projectRuleContent`,content:this.buildGlobRuleContent(r,e)}})}let h=(e,n,r)=>{for(let i of r){let r=this.getSkillName(i),a=u.join(e,SE,r);if(t.push({path:u.join(a,`SKILL.md`),scope:n,source:{kind:`skill`,skill:i}}),i.childDocs!=null)for(let e of i.childDocs)t.push({path:u.join(a,e.dir.path.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillReference`,content:e.content}});if(i.resources!=null)for(let e of i.resources)t.push({path:u.join(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})}};if(f.selectedScope===`project`||p.selectedScope===`project`)for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectRootDir(e,n);if(r==null)continue;let i=u.join(r,CE,`codex`);if(f.selectedScope===`project`){let e=$(f.items,n.projectConfig,`commands`);for(let n of e)t.push({path:u.join(i,xE,this.transformCommandName(n,m)),scope:`project`,source:{kind:`command`,command:n}})}p.selectedScope===`project`&&h(i,`project`,$(p.items,n.projectConfig,`skills`))}if(c.length>0){if(n!=null&&l.has(`global`))for(let e of c)t.push({path:u.join(e,bE),scope:`global`,source:{kind:`globalMemory`,content:n.content}});let e=f.selectedScope===`global`?$(f.items,d,`commands`):[],r=p.selectedScope===`global`?$(p.items,d,`skills`):[];for(let n of c){for(let r of e)t.push({path:u.join(n,xE,this.transformCommandName(r,m)),scope:`global`,source:{kind:`command`,command:r}});h(n,`global`,r)}}let g=this.getIgnoreOutputPath(),_=this.indexignore==null?void 0:a?.find(e=>e.fileName===this.indexignore);if(g!=null&&_!=null)for(let e of o){let n=e.dirFromWorkspacePath;n==null||e.isPromptSourceProject===!0||t.push({path:u.join(n.basePath,n.path,g),scope:`project`,source:{kind:`ignoreFile`,content:_.content}})}return t}async convertContent(e,t){let n=e.source;switch(n.kind){case`projectRuleContent`:case`globalMemory`:case`skillReference`:case`ignoreFile`:return n.content;case`command`:return this.buildCommandContent(n.command,t);case`skill`:return this.buildCodexSkillContent(n.skill,t);case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;default:throw Error(`Unsupported declaration source for ${this.name}`)}}async declareCleanupPaths(e){let t=await super.declareCleanupPaths(e),n=this.getJetBrainsCodexDirs(e);if(n.length===0)return t;let r=n.flatMap(e=>[{path:u.join(e,bE),kind:`file`,scope:`global`},{path:u.join(e,xE),kind:`directory`,scope:`global`},{path:u.join(e,SE),kind:`directory`,scope:`global`}]),i=t.delete??[];return{...t,delete:[...i,...r]}}getJetBrainsCodexDirs(e){return e.runtimeTargets.jetbrainsCodexDirs}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,t){return this.buildMarkdownContent(e,{apply:`始终`},t)}buildGlobRuleContent(e,t){let n={apply:`按文件模式`,模式:this.buildChildRulePattern(e)};return this.buildMarkdownContent(e.content,n,t)}buildCodexSkillContent(e,t){let n=e.yamlFrontMatter,r=this.normalizeSkillName(this.getSkillName(e),64),i=this.normalizeToSingleLine(n.description,1024),a={};n.displayName!=null&&(a[`short-description`]=n.displayName),n.version!=null&&(a.version=n.version),n.author!=null&&(a.author=n.author),n.keywords!=null&&n.keywords.length>0&&(a.keywords=[...n.keywords]);let o={name:r,description:i};return Object.keys(a).length>0&&(o.metadata=a),n.allowTools!=null&&n.allowTools.length>0&&(o[`allowed-tools`]=n.allowTools.join(` `)),this.buildMarkdownContent(e.content,o,t)}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 TE=`.idea`;var EE=class extends ux{constructor(){super(`JetBrainsIDECodeStyleConfigOutputPlugin`,{cleanup:{delete:{project:{files:[`.editorconfig`,`.idea/codeStyles/Project.xml`,`.idea/codeStyles/codeStyleConfig.xml`,`.idea/.gitignore`]}}},capabilities:{}})}async declareOutputFiles(e){let t=[],{projects:n}=e.collectedOutputContext.workspace,{jetbrainsConfigFiles:r,editorConfigFiles:i}=e.collectedOutputContext,a=[...r??[],...i??[]];for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null)for(let e of a){let r=this.getTargetRelativePath(e);t.push({path:this.resolvePath(n.basePath,n.path,r),scope:`project`,source:{content:e.content}})}}return t}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}getTargetRelativePath(e){let t=e.dir.path;if(e.type===ch.EditorConfig)return`.editorconfig`;if(e.type!==ch.IntellijIDEA)return this.basename(t);let n=t.indexOf(TE);return n===-1?this.joinPath(TE,`codeStyles`,this.basename(t)):t.slice(Math.max(0,n))}};const DE=`skills`,OE=`.system`,kE=[`name`,`description`,`developer_instructions`],AE=[`scope`,`seriName`,`argumentHint`,`color`,`namingCase`,`model`];function jE(e){let t={...e};return delete t.allowTools,delete t.allowedTools,t}function ME(e,t){let n=jE(t);return n.name=e,n}const NE={globalConfigDir:`.codex`,outputFileName:`AGENTS.md`,commands:{subDir:`prompts`,scopeRemap:{project:`global`},transformFrontMatter:(e,t)=>jE(t.sourceFrontMatter)},subagents:{subDir:`agents`,sourceScopes:[`project`],scopeRemap:{global:`project`},ext:`.toml`,artifactFormat:`toml`,bodyFieldName:`developer_instructions`,excludedFrontMatterFields:AE,transformFrontMatter:(e,t)=>ME(yb(e),t.sourceFrontMatter),fieldOrder:kE},cleanup:{delete:{project:{dirs:[`.codex/agents`]},global:{files:[`.codex/AGENTS.md`],dirs:[`.codex/prompts`],globs:[`.codex/skills/*`]}},protect:{global:{dirs:[`.codex/${DE}/${OE}`]}}},wslMirrors:[`~/.codex/config.toml`,`~/.codex/auth.json`],dependsOn:[px.AgentsOutput],capabilities:{prompt:{scopes:[`global`],singleScope:!1},commands:{scopes:[`global`],singleScope:!0},subagents:{scopes:[`project`],singleScope:!0}}};var PE=class extends ux{constructor(){super(`CodexCLIOutputPlugin`,NE)}async declareCleanupPaths(e){let t=await super.declareCleanupPaths(e);return{...t,delete:(t.delete??[]).map(e=>e.kind!==`glob`||!e.path.replaceAll(`\\`,`/`).endsWith(`/.codex/${DE}/*`)?e:{...e,excludeBasenames:[OE]})}}};const FE=`AGENTS.md`,IE=`commands`,LE=`agents`,RE=`skills`;function zE(e,t){let n={},r=t.sourceFrontMatter;if(r?.description!=null&&(n.description=r.description),r?.agent!=null&&(n.agent=r.agent),r?.model!=null&&(n.model=r.model),r?.allowTools!=null&&Array.isArray(r.allowTools)){let e={};for(let t of r.allowTools)e[String(t)]=!0;n.tools=e}for(let[e,t]of Object.entries(r??{}))[`description`,`agent`,`model`,`allowTools`,`namingCase`,`argumentHint`].includes(e)||(n[e]=t);return n}var BE=class extends ux{constructor(){super(`OpencodeCLIOutputPlugin`,{globalConfigDir:`.config/opencode`,outputFileName:FE,treatWorkspaceRootProjectAsProject:!0,commands:{subDir:IE,transformFrontMatter:zE},subagents:{subDir:LE},skills:{subDir:RE},cleanup:{delete:{project:{files:[FE,`.opencode/opencode.json`],dirs:[`.opencode/commands`,`.opencode/agents`,`.opencode/skills`]},global:{files:[`.config/opencode/AGENTS.md`,`.config/opencode/opencode.json`],dirs:[`.config/opencode/commands`,`.config/opencode/agents`,`.config/opencode/skills`]},xdgConfig:{files:[`opencode/AGENTS.md`,`opencode/opencode.json`],dirs:[`opencode/commands`,`opencode/agents`,`opencode/skills`]}}},dependsOn:[px.AgentsOutput],capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},subagents:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0},mcp:{scopes:[`project`,`global`],singleScope:!0}}})}async declareOutputFiles(e){let t=[],{globalMemory:n,commands:r,subAgents:i,skills:a}=e.collectedOutputContext,o=this.getGlobalConfigDir(),s=new Set(this.selectPromptScopes(e,[`project`,`global`])),c=this.getProjectPromptOutputProjects(e),l=this.resolvePromptSourceProjectConfig(e),d=r==null?{items:[]}:this.selectSingleScopeItems(r,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)),f=i==null?{items:[]}:this.selectSingleScopeItems(i,this.subAgentsConfig.sourceScopes,e=>this.resolveSubAgentSourceScope(e),this.getTopicScopeOverride(e,`subagents`)),p=a==null?{items:[]}:this.selectSingleScopeItems(a,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),m=a==null?{items:[]}:this.selectSingleScopeItems(a,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`mcp`)??this.getTopicScopeOverride(e,`skills`));n!=null&&s.has(`global`)&&t.push({path:u.join(o,FE),scope:`global`,source:{kind:`globalMemory`,content:n.content}});let h=(e,n,r)=>{if(r.length===0)return;let i=Px(r,this.log);i.size!==0&&t.push({path:u.join(e,`opencode.json`),scope:n,source:{kind:`mcpConfig`,mcpServers:Fx(i,Lx)}})},g=(e,n,r)=>{for(let i of r){let r=this.validateAndNormalizeSkillName(this.getSkillName(i)),a=u.join(e,RE,r);if(t.push({path:u.join(a,`SKILL.md`),scope:n,source:{kind:`skillMain`,skill:i,normalizedSkillName:r}}),i.childDocs!=null)for(let e of i.childDocs)t.push({path:u.join(a,e.dir.path.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillReference`,content:e.content}});if(i.resources!=null)for(let e of i.resources)t.push({path:u.join(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})}},_=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});for(let n of c){let r=this.resolveProjectRootDir(e,n);if(r!=null&&(n.rootMemoryPrompt!=null&&s.has(`project`)&&t.push({path:u.join(r,FE),scope:`project`,source:{kind:`projectRootMemory`,content:n.rootMemoryPrompt.content}}),n.childMemoryPrompts!=null&&s.has(`project`)))for(let e of n.childMemoryPrompts)t.push({path:this.resolveFullPath(e.dir),scope:`project`,source:{kind:`projectChildMemory`,content:e.content}})}if(d.selectedScope===`project`||f.selectedScope===`project`||p.selectedScope===`project`||m.selectedScope===`project`)for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectRootDir(e,n);if(r==null)continue;let i=u.join(r,`.opencode`),a=$(d.items,n.projectConfig,`commands`);if(d.selectedScope===`project`)for(let e of a)t.push({path:u.join(i,IE,this.transformCommandName(e,_)),scope:`project`,source:{kind:`command`,command:e}});let o=$(f.items,n.projectConfig,`subAgents`);if(f.selectedScope===`project`)for(let e of o)t.push({path:u.join(i,LE,this.transformSubAgentName(e)),scope:`project`,source:{kind:`subAgent`,agent:e}});let s=$(p.items,n.projectConfig,`skills`);p.selectedScope===`project`&&g(i,`project`,s);let c=$(m.items,n.projectConfig,`skills`);m.selectedScope===`project`&&h(i,`project`,c)}if(d.selectedScope===`global`){let e=$(d.items,l,`commands`);for(let n of e)t.push({path:u.join(o,IE,this.transformCommandName(n,_)),scope:`global`,source:{kind:`command`,command:n}})}if(f.selectedScope===`global`){let e=$(f.items,l,`subAgents`);for(let n of e)t.push({path:u.join(o,LE,this.transformSubAgentName(n)),scope:`global`,source:{kind:`subAgent`,agent:n}})}return p.selectedScope===`global`&&g(o,`global`,$(p.items,l,`skills`)),m.selectedScope===`global`&&h(o,`global`,$(m.items,l,`skills`)),t}async convertContent(e,t){let n=e.source;switch(n.kind){case`globalMemory`:case`projectRootMemory`:case`projectChildMemory`:case`skillReference`:return n.content;case`command`:return this.buildCommandContent(n.command,t);case`subAgent`:{let e=this.buildOpencodeAgentFrontMatter(n.agent);return this.buildMarkdownContent(n.agent.content,e,t)}case`skillMain`:{let e=this.buildOpencodeSkillFrontMatter(n.skill,n.normalizedSkillName);return this.buildMarkdownContent(n.skill.content,e,t)}case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;case`mcpConfig`:return JSON.stringify({$schema:`https://opencode.ai/config.json`,plugin:[`opencode-rules@latest`],mcp:n.mcpServers},null,2);default:throw Error(`Unsupported declaration source for ${this.name}`)}}buildOpencodeAgentFrontMatter(e){let t={},n=e.yamlFrontMatter;if(n?.description!=null&&(t.description=n.description),t.mode=n?.mode??`subagent`,n?.model!=null&&(t.model=n.model),n?.temperature!=null&&(t.temperature=n.temperature),n?.maxSteps!=null&&(t.maxSteps=n.maxSteps),n?.hidden!=null&&(t.hidden=n.hidden),n?.allowTools!=null&&Array.isArray(n.allowTools)){let e={};for(let t of n.allowTools)e[String(t)]=!0;t.tools=e}n?.permission!=null&&typeof n.permission==`object`&&(t.permission=n.permission);for(let[e,r]of Object.entries(n??{}))[`description`,`mode`,`model`,`temperature`,`maxSteps`,`hidden`,`allowTools`,`permission`,`namingCase`,`name`,`color`].includes(e)||(t[e]=r);return t}buildOpencodeSkillFrontMatter(e,t){let n={},r=e.yamlFrontMatter;n.name=t,r?.description!=null&&(n.description=r.description),n.license=r?.license??`MIT`,n.compatibility=r?.compatibility??`opencode`;let i={};for(let e of[`author`,`version`,`keywords`,`category`,`repository`,`displayName`])r?.[e]!=null&&(i[e]=r[e]);let a=new Set([`name`,`description`,`license`,`compatibility`,`namingCase`,`allowTools`,`keywords`,`displayName`,`author`,`version`]);for(let[e,t]of Object.entries(r??{}))a.has(e)||(i[e]=t);return Object.keys(i).length>0&&(n.metadata=i),n}validateAndNormalizeSkillName(e){let t=e.toLowerCase();return t=t.replaceAll(/[^a-z0-9-]+/g,`-`),t=t.replaceAll(/-+/g,`-`),t=t.replaceAll(/^-|-$/g,``),t.length===0?t=`skill`:t.length>64&&(t=t.slice(0,64),t=t.replace(/-$/,``)),t}};const VE=`rules`,HE=`commands`,UE=`skills`,WE=`glob`,GE=`glob`;function KE(e,t){let n=t.sourceFrontMatter,r={description:`Fast command`,type:`user_command`};return n?.description!=null&&(r.description=n.description),n?.argumentHint!=null&&(r.argumentHint=n.argumentHint),n?.allowTools!=null&&Array.isArray(n.allowTools)&&n.allowTools.length>0&&(r.allowTools=n.allowTools),r}var qE=class extends ux{constructor(){super(`QoderIDEPluginOutputPlugin`,{globalConfigDir:`.qoder`,treatWorkspaceRootProjectAsProject:!0,indexignore:`.qoderignore`,commands:{subDir:HE,transformFrontMatter:KE},skills:{subDir:UE},rules:{subDir:VE,sourceScopes:[`project`,`global`]},cleanup:{delete:{project:{dirs:[`.qoder/commands`,`.qoder/rules`,`.qoder/skills`]},global:{dirs:[`.qoder/commands`,`.qoder/rules`,`.qoder/skills`]}}},capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1},rules:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0},mcp:{scopes:[`project`,`global`],singleScope:!0}}})}async declareOutputFiles(e){let t=[],{globalMemory:n,commands:r,skills:i,rules:a,aiAgentIgnoreConfigFiles:o}=e.collectedOutputContext,s=this.getGlobalConfigDir(),c=this.resolvePromptSourceProjectConfig(e),l=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0}),d=new Set(a==null?[]:this.selectRuleScopes(e,a)),f=new Set(this.selectPromptScopes(e,[`project`,`global`])),p=this.getProjectPromptOutputProjects(e),m=r==null?{items:[]}:this.selectSingleScopeItems(r,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)),h=i==null?{items:[]}:this.selectSingleScopeItems(i,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),g=i==null?{items:[]}:this.selectSingleScopeItems(i,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`mcp`)??this.getTopicScopeOverride(e,`skills`)),_=(e,n,r)=>{for(let i of r){let r=this.getSkillName(i),a=u.join(e,UE,r);if(t.push({path:u.join(a,`SKILL.md`),scope:n,source:{kind:`skillMain`,skill:i}}),i.childDocs!=null)for(let e of i.childDocs)t.push({path:u.join(a,e.relativePath.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillChildDoc`,content:e.content}});if(i.resources!=null)for(let e of i.resources)t.push({path:u.join(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})}},v=(e,n,r)=>{for(let i of r){if(i.mcpConfig==null)continue;let r=u.join(e,UE,this.getSkillName(i));t.push({path:u.join(r,`mcp.json`),scope:n,source:{kind:`skillMcpConfig`,rawContent:i.mcpConfig.rawContent}})}};if(m.selectedScope===`project`)for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectConfigDir(e,n);if(r==null)continue;let i=$(m.items,n.projectConfig,`commands`);for(let e of i)t.push({path:u.join(r,HE,this.transformCommandName(e,l)),scope:`project`,source:{kind:`command`,command:e}})}if(m.selectedScope===`global`){let e=$(m.items,c,`commands`);for(let n of e)t.push({path:u.join(s,HE,this.transformCommandName(n,l)),scope:`global`,source:{kind:`command`,command:n}})}if(h.selectedScope===`project`||g.selectedScope===`project`)for(let t of this.getProjectOutputProjects(e)){let n=this.resolveProjectConfigDir(e,t);n!=null&&(h.selectedScope===`project`&&_(n,`project`,$(h.items,t.projectConfig,`skills`)),g.selectedScope===`project`&&v(n,`project`,$(g.items,t.projectConfig,`skills`)))}if((h.selectedScope===`global`||g.selectedScope===`global`)&&(h.selectedScope===`global`&&_(s,`global`,$(h.items,c,`skills`)),g.selectedScope===`global`&&v(s,`global`,$(g.items,c,`skills`))),n!=null&&f.has(`global`))for(let r of p){let i=this.resolveProjectConfigDir(e,r);i!=null&&t.push({path:u.join(i,VE,`global.md`),scope:`project`,source:{kind:`ruleContent`,content:this.buildAlwaysRuleContent(n.content,e)}})}if(f.has(`project`))for(let n of p){let r=this.resolveProjectConfigDir(e,n);if(r!=null&&(n.rootMemoryPrompt!=null&&t.push({path:u.join(r,VE,`always.md`),scope:`project`,source:{kind:`ruleContent`,content:this.buildAlwaysRuleContent(n.rootMemoryPrompt.content,e)}}),n.childMemoryPrompts!=null))for(let i of n.childMemoryPrompts)t.push({path:u.join(r,VE,this.buildChildRuleFileName(i)),scope:`project`,source:{kind:`ruleContent`,content:this.buildGlobRuleContent(i,e)}})}if(a!=null&&a.length>0&&d.has(`project`))for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectConfigDir(e,n);if(r==null)continue;let i=Ky($(a.filter(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))===`project`),n.projectConfig,`rules`),n.projectConfig);for(let e of i)t.push({path:u.join(r,VE,this.buildRuleFileName(e)),scope:`project`,source:{kind:`rulePrompt`,rule:e}})}if(a!=null&&a.length>0&&d.has(`global`)){let e=a.filter(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))===`global`);for(let n of e)t.push({path:u.join(s,VE,this.buildRuleFileName(n)),scope:`global`,source:{kind:`rulePrompt`,rule:n}})}let y=this.getIgnoreOutputPath(),b=this.indexignore==null?void 0:o?.find(e=>e.fileName===this.indexignore);if(y!=null&&b!=null)for(let n of this.getConcreteProjects(e)){let e=n.dirFromWorkspacePath;e==null||n.isPromptSourceProject===!0||t.push({path:u.join(e.basePath,e.path,y),scope:`project`,source:{kind:`ignoreFile`,content:b.content}})}return t}async convertContent(e,t){let n=e.source;switch(n.kind){case`command`:return this.buildCommandContent(n.command,t);case`ruleContent`:return n.content;case`rulePrompt`:return this.buildRuleContent(n.rule,t);case`skillMain`:{let e=this.buildSkillFrontMatter(n.skill);return this.buildMarkdownContent(n.skill.content,e,t)}case`skillMcpConfig`:return n.rawContent;case`skillChildDoc`:case`ignoreFile`:return n.content;case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;default:throw Error(`Unsupported declaration source for ${this.name}`)}}buildChildRuleFileName(e){let t=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``).replaceAll(`/`,`-`);return`glob-${t.length>0?t:`root`}.md`}buildAlwaysRuleContent(e,t){return this.buildMarkdownContent(e,{trigger:`always_on`,type:`user_command`},t)}buildGlobRuleContent(e,t){let n=(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``),r=n.length===0?`**/*`:`${n}/**`;return this.buildMarkdownContent(e.content,{trigger:WE,[GE]:r,type:`user_command`},t)}buildSkillFrontMatter(e){let t=e.yamlFrontMatter;return{name:this.getSkillName(e),description:t.description,type:`user_command`,...t.displayName!=null&&{displayName:t.displayName},...t.keywords!=null&&t.keywords.length>0&&{keywords:t.keywords},...t.author!=null&&{author:t.author},...t.version!=null&&{version:t.version},...t.allowTools!=null&&t.allowTools.length>0&&{allowTools:t.allowTools}}}buildRuleFileName(e,t=`rule-`){return`${t}${e.prefix}-${e.ruleName}.md`}buildRuleContent(e,t){let n={trigger:WE,[GE]:e.globs.length>0?e.globs.join(`, `):`**/*`,type:`user_command`};return this.buildMarkdownContent(e.content,n,t)}normalizeRuleScope(e){return e.scope??`global`}};function JE(e){return Zb[e??`Readme`].out}var YE=class extends ux{constructor(){super(`ReadmeMdConfigFileOutputPlugin`,{outputFileName:`README.md`,cleanup:{delete:{project:{files:[`README.md`,`CODE_OF_CONDUCT.md`,`SECURITY.md`]}}},capabilities:{}})}async declareOutputFiles(e){let t=[],{readmePrompts:n}=e.collectedOutputContext;if(n==null||n.length===0)return t;for(let e of n){let n=JE(e.fileKind),r=u.join(e.targetDir.basePath,e.targetDir.path,n);t.push({path:r,scope:`project`,source:{content:e.content}})}return t}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}};const XE=`GLOBAL.md`,ZE=`.trae`,QE=`commands`,$E=`skills`;var eD=class extends ux{constructor(){super(`TraeIDEOutputPlugin`,{globalConfigDir:ZE,outputFileName:XE,treatWorkspaceRootProjectAsProject:!0,indexignore:`.traeignore`,commands:{subDir:QE,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:$E},cleanup:{delete:{project:{dirs:[`.trae/rules`,`.trae/commands`,`.trae/skills`]},global:{dirs:[`.trae/steering`,`.trae/commands`,`.trae/skills`]}}},capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0}}})}getIgnoreOutputPath(){if(this.indexignore!=null)return u.join(`.trae`,`.ignore`)}getGlobalSteeringDir(){return this.joinPath(this.getGlobalConfigDir(),`steering`)}async declareOutputFiles(e){let t=[],{commands:n,skills:r,globalMemory:i,aiAgentIgnoreConfigFiles:a}=e.collectedOutputContext,o=this.getConcreteProjects(e),s=this.getProjectPromptOutputProjects(e),c=this.resolvePromptSourceProjectConfig(e),l=new Set(this.selectPromptScopes(e,[`project`,`global`])),d=n==null?{items:[]}:this.selectSingleScopeItems(n,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)),f=r==null?{items:[]}:this.selectSingleScopeItems(r,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),p=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});i!=null&&l.has(`global`)&&t.push({path:this.joinPath(this.getGlobalSteeringDir(),XE),scope:`global`,source:{kind:`globalMemory`,content:i.content}});for(let n of s){let r=this.resolveProjectRootDir(e,n);if(r!=null&&n.childMemoryPrompts!=null&&l.has(`project`))for(let i of n.childMemoryPrompts){let n=(i.workingChildDirectoryPath?.path??i.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``),a=this.buildProjectRelativeGlobPattern(n),o=this.buildMarkdownContent([this.buildPathGuardHint(n),``,i.content].join(`
|
|
309
|
+
`),{alwaysApply:!1,globs:a},e);t.push({path:u.join(r,ZE,`rules`,this.buildSteeringFileName(i)),scope:`project`,source:{kind:`steeringRule`,content:o}})}}if(d.selectedScope===`project`)for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectConfigDir(e,n);if(r==null)continue;let i=$(d.items,n.projectConfig,`commands`);for(let e of i)t.push({path:u.join(r,QE,this.transformCommandName(e,p)),scope:`project`,source:{kind:`command`,command:e}})}if(d.selectedScope===`global`){let e=this.getGlobalConfigDir(),n=$(d.items,c,`commands`);for(let r of n)t.push({path:u.join(e,QE,this.transformCommandName(r,p)),scope:`global`,source:{kind:`command`,command:r}})}let m=(e,n,r)=>{for(let i of r){let r=this.getSkillName(i),a=u.join(e,$E,r);if(t.push({path:u.join(a,`SKILL.md`),scope:n,source:{kind:`skillMain`,skill:i}}),i.childDocs!=null)for(let e of i.childDocs)t.push({path:u.join(a,e.relativePath.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillChildDoc`,content:e.content}});if(i.resources!=null)for(let e of i.resources)t.push({path:u.join(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})}};if(f.selectedScope===`project`)for(let t of this.getProjectOutputProjects(e)){let n=this.resolveProjectConfigDir(e,t);n!=null&&m(n,`project`,$(f.items,t.projectConfig,`skills`))}f.selectedScope===`global`&&m(this.getGlobalConfigDir(),`global`,$(f.items,c,`skills`));let h=this.getIgnoreOutputPath(),g=this.indexignore==null?void 0:a?.find(e=>e.fileName===this.indexignore);if(h!=null&&g!=null)for(let e of o){let n=e.dirFromWorkspacePath;n==null||e.isPromptSourceProject===!0||t.push({path:u.join(n.basePath,n.path,h),scope:`project`,source:{kind:`ignoreFile`,content:g.content}})}return t}async convertContent(e,t){let n=e.source;switch(n.kind){case`globalMemory`:case`steeringRule`:case`skillChildDoc`:case`ignoreFile`:return n.content;case`command`:return this.buildCommandContent(n.command,t);case`skillMain`:{let e=this.buildSkillFrontMatter(n.skill);return this.buildMarkdownContent(n.skill.content,e,t)}case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;default:throw Error(`Unsupported declaration source for ${this.name}`)}}buildSkillFrontMatter(e){let t={description:e.yamlFrontMatter.description??``};return e.yamlFrontMatter.displayName!=null&&(t.name=e.yamlFrontMatter.displayName),t}buildSteeringFileName(e){return`trae-${(e.workingChildDirectoryPath?.path??e.dir.path).replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/g,``).replaceAll(`/`,`-`)}.md`}buildPathGuardHint(e){return e.length===0?`Scope guard: apply this rule to project source files only; do not apply to generated output directories (for example dist/, build/, out/, .next/, target/).`:[`Scope guard: this rule is for the project-root path "${e}/" only.`,`Do not apply this rule to generated output paths such as "dist/${e}/", "build/${e}/", "out/${e}/", ".next/${e}/", or "target/${e}/".`].join(`
|
|
310
|
+
`)}buildProjectRelativeGlobPattern(e){return e.length===0?`**/*`:`${e}/**`}};const tD=`.vscode`;var nD=class extends ux{constructor(){super(`VisualStudioCodeIDEConfigOutputPlugin`,{cleanup:{delete:{project:{files:[`.vscode/settings.json`,`.vscode/extensions.json`]}}},capabilities:{}})}async declareOutputFiles(e){let t=[],{projects:n}=e.collectedOutputContext.workspace,{vscodeConfigFiles:r}=e.collectedOutputContext,i=r??[];for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null)for(let e of i){let r=this.getTargetRelativePath(e);t.push({path:this.resolvePath(n.basePath,n.path,r),scope:`project`,source:{content:e.content}})}}return t}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}getTargetRelativePath(e){let t=e.dir.path;if(e.type!==ch.VSCode)return this.basename(t);let n=t.indexOf(tD);return n===-1?this.joinPath(tD,this.basename(t)):t.slice(Math.max(0,n))}};const rD=`WARP.md`;var iD=class extends ux{constructor(){super(`WarpIDEOutputPlugin`,{outputFileName:rD,treatWorkspaceRootProjectAsProject:!0,indexignore:`.warpindexignore`,cleanup:{delete:{project:{files:[rD]}}},capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1}}})}async declareOutputFiles(e){let t=[],{globalMemory:n,aiAgentIgnoreConfigFiles:r}=e.collectedOutputContext,i=this.getConcreteProjects(e),a=this.getProjectPromptOutputProjects(e),o=this.shouldSkipDueToPlugin(e,px.AgentsOutput),s=new Set(this.selectPromptScopes(e,[`project`,`global`])),c=this.extractGlobalMemoryContent(e);if(o){if(n!=null&&s.has(`global`))for(let r of a){let i=this.resolveProjectRootDir(e,r);i!=null&&t.push({path:u.join(i,rD),scope:`project`,source:{content:n.content}})}}else for(let n of a){let r=this.resolveProjectRootDir(e,n);if(r!=null){if(n.rootMemoryPrompt!=null&&s.has(`project`)){let e=this.combineGlobalWithContent(c,n.rootMemoryPrompt.content);t.push({path:u.join(r,rD),scope:`project`,source:{content:e}})}if(n.childMemoryPrompts!=null&&s.has(`project`))for(let e of n.childMemoryPrompts)t.push({path:this.resolveFullPath(e.dir),scope:`project`,source:{content:e.content}})}}let l=this.getIgnoreOutputPath(),d=this.indexignore==null?void 0:r?.find(e=>e.fileName===this.indexignore);if(l!=null&&d!=null)for(let e of i){let n=e.dirFromWorkspacePath;n==null||e.isPromptSourceProject===!0||t.push({path:this.resolvePath(n.basePath,n.path,l),scope:`project`,source:{content:d.content}})}return t}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}};const aD=`.codeium/windsurf`,oD=`global_workflows`,sD=`memories`,cD=`skills`,lD=`.windsurf`;var uD=class extends ux{constructor(){super(`WindsurfOutputPlugin`,{globalConfigDir:aD,outputFileName:``,treatWorkspaceRootProjectAsProject:!0,dependsOn:[px.AgentsOutput],indexignore:`.codeiumignore`,commands:{subDir:oD,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:cD},rules:{sourceScopes:[`project`,`global`]},cleanup:{delete:{project:{dirs:[`.windsurf/rules`,`.windsurf/workflows`,`.windsurf/global_workflows`,`.windsurf/skills`,`.codeium/windsurf/global_workflows`,`.codeium/windsurf/skills`]},global:{dirs:[`.codeium/windsurf/global_workflows`,`.codeium/windsurf/memories`,`.codeium/windsurf/skills`]}}},capabilities:{prompt:{scopes:[`global`],singleScope:!1},rules:{scopes:[`project`,`global`],singleScope:!1},commands:{scopes:[`project`,`global`],singleScope:!0},skills:{scopes:[`project`,`global`],singleScope:!0}}})}async declareOutputFiles(e){let t=[],{commands:n,skills:r,globalMemory:i,rules:a,aiAgentIgnoreConfigFiles:o}=e.collectedOutputContext,s=this.resolvePromptSourceProjectConfig(e),c=this.getCodeiumWindsurfDir(),l=new Set(this.selectPromptScopes(e,[`global`])),d=n==null?{items:[]}:this.selectSingleScopeItems(n,this.commandsConfig.sourceScopes,e=>this.resolveCommandSourceScope(e),this.getTopicScopeOverride(e,`commands`)),f=r==null?{items:[]}:this.selectSingleScopeItems(r,this.skillsConfig.sourceScopes,e=>this.resolveSkillSourceScope(e),this.getTopicScopeOverride(e,`skills`)),p=this.getConcreteProjects(e);i!=null&&l.has(`global`)&&t.push({path:u.join(c,sD,`global_rules.md`),scope:`global`,source:{kind:`globalMemory`,content:i.content}});let m=(e,n,r)=>{let i=this.getSkillName(r),a=u.join(e,cD,i);if(t.push({path:u.join(a,`SKILL.md`),scope:n,source:{kind:`skillMain`,skill:r}}),r.childDocs!=null)for(let e of r.childDocs)t.push({path:u.join(a,e.relativePath.replace(/\.mdx$/,`.md`)),scope:n,source:{kind:`skillChildDoc`,content:e.content}});if(r.resources!=null)for(let e of r.resources)t.push({path:u.join(a,e.relativePath),scope:n,source:{kind:`skillResource`,content:e.content,encoding:e.encoding}})};if(f.selectedScope===`project`)for(let t of this.getProjectOutputProjects(e)){let n=this.resolveProjectRootDir(e,t),r=n==null?void 0:u.join(n,lD);if(r==null)continue;let i=$(f.items,t.projectConfig,`skills`);for(let e of i)m(r,`project`,e)}if(f.selectedScope===`global`){let e=$(f.items,s,`skills`);for(let t of e)m(c,`global`,t)}let h=this.getTransformOptionsFromContext(e,{includeSeriesPrefix:!0});if(d.selectedScope===`project`)for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectRootDir(e,n),i=r==null?void 0:u.join(r,lD);if(i==null)continue;let a=$(d.items,n.projectConfig,`commands`);for(let e of a)t.push({path:u.join(i,`workflows`,this.transformCommandName(e,h)),scope:`project`,source:{kind:`command`,command:e}})}if(d.selectedScope===`global`){let e=$(d.items,s,`commands`);for(let n of e)t.push({path:u.join(c,oD,this.transformCommandName(n,h)),scope:`global`,source:{kind:`command`,command:n}})}if(a!=null&&a.length>0){let n=new Set(this.selectRuleScopes(e,a)),r=a.filter(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))===`global`);if(n.has(`global`))for(let e of r)t.push({path:u.join(c,sD,this.buildRuleFileName(e)),scope:`global`,source:{kind:`rule`,rule:e}});if(n.has(`project`))for(let n of this.getProjectOutputProjects(e)){let r=this.resolveProjectRootDir(e,n);if(r==null)continue;let i=Ky($(a.filter(e=>this.normalizeSourceScope(this.normalizeRuleScope(e))===`project`),n.projectConfig,`rules`),n.projectConfig);for(let e of i)t.push({path:u.join(r,lD,`rules`,this.buildRuleFileName(e)),scope:`project`,source:{kind:`rule`,rule:e}})}}let g=this.getIgnoreOutputPath(),_=this.indexignore==null?void 0:o?.find(e=>e.fileName===this.indexignore);if(g!=null&&_!=null)for(let e of p){let n=e.dirFromWorkspacePath;n==null||e.isPromptSourceProject===!0||t.push({path:u.join(n.basePath,n.path,g),scope:`project`,source:{kind:`ignoreFile`,content:_.content}})}return t}async convertContent(e,t){let n=e.source;switch(n.kind){case`globalMemory`:case`skillChildDoc`:case`ignoreFile`:return n.content;case`command`:return this.buildCommandContent(n.command,t);case`skillMain`:{let e=this.buildSkillFrontMatter(n.skill);return this.buildMarkdownContent(n.skill.content,e,t)}case`skillResource`:return n.encoding===`base64`?_.from(n.content,`base64`):n.content;case`rule`:return this.buildRuleContent(n.rule,t);default:throw Error(`Unsupported declaration source for ${this.name}`)}}getCodeiumWindsurfDir(){return u.join(this.getHomeDir(),aD)}buildRuleFileName(e,t=`rule-`){return`${t}${e.prefix}-${e.ruleName}.md`}buildRuleContent(e,t){let n={trigger:`glob`,globs:e.globs.length>0?e.globs.join(`, `):``};return this.buildMarkdownContent(e.content,n,t).split(`
|
|
311
311
|
`).map(e=>{let t=/^(\s*globs:\s*)(['"])(.*)\2\s*$/.exec(e);if(t==null)return e;let n=t[1]??`globs: `,r=t[3]??``;return r.trim().length===0?e:`${n}${r}`}).join(`
|
|
312
|
-
`)}};const zE=`.zed`;var BE=class extends lx{constructor(){super(`ZedIDEConfigOutputPlugin`,{cleanup:{delete:{project:{files:[`.zed/settings.json`]}}},capabilities:{}})}async declareOutputFiles(e){let t=[],{projects:n}=e.collectedOutputContext.workspace,r=e.collectedOutputContext.zedConfigFiles??[];for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null)for(let e of r){let r=this.getTargetRelativePath(e);t.push({path:this.resolvePath(n.basePath,n.path,r),scope:`project`,source:{content:e.content}})}}return t}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}getTargetRelativePath(e){let t=e.dir.path;if(e.type!==sh.Zed)return this.basename(t);let n=t.indexOf(zE);return n===-1?this.joinPath(zE,`settings.json`):t.slice(Math.max(0,n))}};const VE=`GLOBAL.md`;var HE=class extends lx{constructor(){super(`TraeCNIDEOutputPlugin`,{globalConfigDir:`.trae-cn`,outputFileName:VE,dependsOn:[`TraeIDEOutputPlugin`],cleanup:{delete:{global:{dirs:[`.trae-cn/user_rules`]}}},capabilities:{prompt:{scopes:[`global`],singleScope:!1}}})}getGlobalUserRulesDir(){return this.joinPath(this.getGlobalConfigDir(),`user_rules`)}async declareOutputFiles(e){if(!new Set(this.selectPromptScopes(e,[`global`])).has(`global`))return[];let{globalMemory:t}=e.collectedOutputContext;return t==null?[]:[{path:this.joinPath(this.getGlobalUserRulesDir(),VE),scope:`global`,source:{content:t.content}}]}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}};async function UE(e=c.argv){return wT({pipelineArgs:e,pluginOptions:{plugins:[new kT,new jT,new cE,new QT,new HT,new KT,new DT,new mE,new xE,new OE,new HE,new ME,new RE,new BT,new qT,new eE,new WT,new AE,new BE,new CE]}})}const WE=new Set([`help`,`version`,`unknown`]);function GE(e){return e.some(e=>e===`--json`||e===`-j`||/^-[^-]*j/.test(e))}function KE(e){let t=e instanceof Error?e.message:String(e);Rx(`main`,`silent`).error(A(`main`,e)),c.stdout.write(`${JSON.stringify(Hx({success:!1,filesAffected:0,dirsAffected:0,message:t},zx()))}\n`)}function qE(e){throw Error(`${e} context is unavailable for lightweight commands`)}function JE(e){let t=c.cwd(),n=lT({workspaceDir:t,...e==null?{}:{logLevel:e}});return{logger:Rx(`PluginPipeline`,e),outputPlugins:[],collectedOutputContext:{workspace:{directory:{pathKind:oh.Absolute,path:t,getDirectoryName:()=>u.basename(t)},projects:[]}},userConfigOptions:n,createCleanContext:()=>qE(`cleanup`),createWriteContext:()=>qE(`write`)}}function YE(e){let t=WC(BC(e.filter(e=>e!=null))),n=JC(t);if(WE.has(n.name))return t.logLevel!=null&&Bx(t.logLevel),t.jsonFlag&&(Bx(`silent`),n=new Vx(n)),{command:n,context:JE(t.logLevel)}}async function XE(e=c.argv){try{let t=YE(e);if(t!=null)return(await t.command.execute(t.context)).success?0:1;let n=new $C(...e),r=await UE(e);return(await n.run(r)).success?0:1}catch(t){return GE(e)?(KE(t),1):(Rx(`main`,`error`).error(A(`main`,t)),1)}}const ZE=`.src.mdx`,QE=`.mdx`,$E=`skill`,eD=new Set([`project-memory`,`project-child-memory`]);function tD(e){return e.replaceAll(`\\`,`/`)}function nD(e,t){let n=tD(e).trim();if(n.length===0)throw Error(`${t} cannot be empty`);let r=n.split(`/`);for(let e of r)if(e.length===0||e===`.`||e===`..`)throw Error(`${t} contains an invalid path segment`);return r.join(`/`)}function rD(e){return!tD(e).includes(`/`)}function iD(e,t){let n=e;return n.includes(ux.WORKSPACE)&&(n=n.replace(ux.WORKSPACE,t)),ag(n)}function aD(e={}){let{cwd:t,loadUserConfig:n=!0,pluginOptions:r={}}=e,i={};if(n){let e=BS().load(t);e.found&&(i=cT(e.config))}let a=lT(i,r),o=iD(a.workspaceDir,``);return{options:a,workspaceDir:o,aindexDir:u.join(o,a.aindex.dir)}}function oD(e){return e.endsWith(ZE)?`${e.slice(0,-8)}${QE}`:u.extname(e)===QE?e:`${e}${QE}`}function sD(e){return e.endsWith(ZE)?e.slice(0,-8):e.endsWith(QE)?e.slice(0,-4):e}function cD(e,t){return i.existsSync(e)&&i.statSync(e).isDirectory()?Um.default.sync([...t],{cwd:e,dot:!0,onlyFiles:!0}).map(tD):[]}function lD(e){let t=u.join(e.aindexDir,e.options.aindex.globalPrompt.src);return{promptId:`global-memory`,kind:`global-memory`,logicalName:`global-memory`,paths:{zh:t,en:oD(t),dist:u.join(e.aindexDir,e.options.aindex.globalPrompt.dist)}}}function uD(e){let t=u.join(e.aindexDir,e.options.aindex.workspacePrompt.src);return{promptId:`workspace-memory`,kind:`workspace-memory`,logicalName:`workspace-memory`,paths:{zh:t,en:oD(t),dist:u.join(e.aindexDir,e.options.aindex.workspacePrompt.dist)}}}function dD(e,t,n){let r=nD(t,`projectName`);if(!rD(r))throw Error(`projectName must be a single path segment`);let i=n==null?``:nD(n,`relativeName`),a=i.length===0?u.join(e.aindexDir,e.options.aindex.app.src,r):u.join(e.aindexDir,e.options.aindex.app.src,r,i),o=i.length===0?u.join(e.aindexDir,e.options.aindex.app.dist,r):u.join(e.aindexDir,e.options.aindex.app.dist,r,i),s=u.join(a,`agt${QE}`),c=i.length===0?r:`${r}/${i}`;return{promptId:i.length===0?`project-memory:${r}`:`project-child-memory:${c}`,kind:i.length===0?`project-memory`:`project-child-memory`,logicalName:c,paths:{zh:u.join(a,`agt${ZE}`),en:s,dist:u.join(o,`agt${QE}`)},legacyZhPath:s}}function fD(e,t){let n=nD(t,`skillName`);if(!rD(n))throw Error(`skillName must be a single path segment`);let r=u.join(e.aindexDir,e.options.aindex.skills.src,n),i=u.join(e.aindexDir,e.options.aindex.skills.dist,n);return{promptId:`skill:${n}`,kind:`skill`,logicalName:n,paths:{zh:u.join(r,`${$E}${ZE}`),en:u.join(r,`${$E}${QE}`),dist:u.join(i,`${$E}${QE}`)}}}function pD(e,t,n){let r=nD(t,`skillName`),i=nD(n,`relativeName`);if(!rD(r))throw Error(`skillName must be a single path segment`);let a=u.join(e.aindexDir,e.options.aindex.skills.src,r),o=u.join(e.aindexDir,e.options.aindex.skills.dist,r);return{promptId:`skill-child-doc:${r}/${i}`,kind:`skill-child-doc`,logicalName:`${r}/${i}`,paths:{zh:u.join(a,`${i}${ZE}`),en:u.join(a,`${i}${QE}`),dist:u.join(o,`${i}${QE}`)}}}function mD(e,t,n){let r=nD(n,`relativeName`),i=t===`command`?u.join(e.aindexDir,e.options.aindex.commands.src):t===`subagent`?u.join(e.aindexDir,e.options.aindex.subAgents.src):u.join(e.aindexDir,e.options.aindex.rules.src),a=t===`command`?u.join(e.aindexDir,e.options.aindex.commands.dist):t===`subagent`?u.join(e.aindexDir,e.options.aindex.subAgents.dist):u.join(e.aindexDir,e.options.aindex.rules.dist);return{promptId:`${t}:${r}`,kind:t,logicalName:r,paths:{zh:u.join(i,`${r}${ZE}`),en:u.join(i,`${r}${QE}`),dist:u.join(a,`${r}${QE}`)}}}function hD(e){switch(e){case`global-memory`:return{kind:`global-memory`};case`workspace-memory`:return{kind:`workspace-memory`};default:break}let t=e.indexOf(`:`);if(t===-1)throw Error(`Unsupported promptId: ${e}`);let n=e.slice(0,t),r=nD(e.slice(t+1),`promptId`);switch(n){case`project-memory`:if(!rD(r))throw Error(`project-memory promptId must include a single project name`);return{kind:n,projectName:r};case`project-child-memory`:{let[e,...t]=r.split(`/`),i=t.join(`/`);if(e==null||i.length===0)throw Error(`project-child-memory promptId must include project and child path`);return{kind:n,projectName:e,relativeName:i}}case`skill`:if(!rD(r))throw Error(`skill promptId must include a single skill name`);return{kind:n,skillName:r};case`skill-child-doc`:{let[e,...t]=r.split(`/`),i=t.join(`/`);if(e==null||i.length===0)throw Error(`skill-child-doc promptId must include skill and child path`);return{kind:n,skillName:e,relativeName:i}}case`command`:case`subagent`:case`rule`:return{kind:n,relativeName:r};default:throw Error(`Unsupported promptId: ${e}`)}}function gD(e,t){let n=hD(e);switch(n.kind){case`global-memory`:return lD(t);case`workspace-memory`:return uD(t);case`project-memory`:if(n.projectName==null)throw Error(`project-memory promptId must include a project name`);return dD(t,n.projectName);case`project-child-memory`:if(n.projectName==null||n.relativeName==null)throw Error(`project-child-memory promptId must include project and child path`);return dD(t,n.projectName,n.relativeName);case`skill`:if(n.skillName==null)throw Error(`skill promptId must include a skill name`);return fD(t,n.skillName);case`skill-child-doc`:if(n.skillName==null||n.relativeName==null)throw Error(`skill-child-doc promptId must include skill and child path`);return pD(t,n.skillName,n.relativeName);case`command`:case`subagent`:case`rule`:if(n.relativeName==null)throw Error(`${n.kind} promptId must include a relative path`);return mD(t,n.kind,n.relativeName)}}function _D(e,t){let n=t===`command`?u.join(e.aindexDir,e.options.aindex.commands.src):t===`subagent`?u.join(e.aindexDir,e.options.aindex.subAgents.src):u.join(e.aindexDir,e.options.aindex.rules.src),r=t===`command`?u.join(e.aindexDir,e.options.aindex.commands.dist):t===`subagent`?u.join(e.aindexDir,e.options.aindex.subAgents.dist):u.join(e.aindexDir,e.options.aindex.rules.dist),i=new Set;for(let e of cD(n,[`**/*${ZE}`,`**/*${QE}`]))i.add(sD(e));for(let e of cD(r,[`**/*${QE}`]))i.add(sD(e));return[...i].sort().map(e=>`${t}:${e}`)}function vD(e){let t=u.join(e.aindexDir,e.options.aindex.skills.src),n=u.join(e.aindexDir,e.options.aindex.skills.dist),r=new Set;if(i.existsSync(t)&&i.statSync(t).isDirectory())for(let e of i.readdirSync(t,{withFileTypes:!0}))e.isDirectory()&&r.add(e.name);if(i.existsSync(n)&&i.statSync(n).isDirectory())for(let e of i.readdirSync(n,{withFileTypes:!0}))e.isDirectory()&&r.add(e.name);let a=[];for(let e of[...r].sort()){a.push(`skill:${e}`);let r=u.join(t,e),i=u.join(n,e),o=new Set;for(let e of cD(r,[`**/*${ZE}`,`**/*${QE}`])){let t=sD(e);t!==$E&&o.add(t)}for(let e of cD(i,[`**/*${QE}`])){let t=sD(e);t!==$E&&o.add(t)}for(let t of[...o].sort())a.push(`skill-child-doc:${e}/${t}`)}return a}function yD(e){let t=u.join(e.aindexDir,e.options.aindex.app.src),n=u.join(e.aindexDir,e.options.aindex.app.dist),r=new Set;for(let e of cD(t,[`**/agt${ZE}`,`**/agt${QE}`])){let t=tD(u.posix.dirname(tD(e)));t!==`.`&&r.add(t)}for(let e of cD(n,[`**/agt${QE}`])){let t=tD(u.posix.dirname(tD(e)));t!==`.`&&r.add(t)}let i=[];for(let e of[...r].sort()){let[t,...n]=e.split(`/`),r=n.join(`/`);t==null||t.length===0||i.push(r.length===0?`project-memory:${t}`:`project-child-memory:${t}/${r}`)}return i}function bD(e){let t=new Set,n=lD(e),r=uD(e);(i.existsSync(n.paths.zh)||i.existsSync(n.paths.en)||i.existsSync(n.paths.dist))&&t.add(n.promptId),(i.existsSync(r.paths.zh)||i.existsSync(r.paths.en)||i.existsSync(r.paths.dist))&&t.add(r.promptId);for(let n of yD(e))t.add(n);for(let n of vD(e))t.add(n);for(let n of _D(e,`command`))t.add(n);for(let n of _D(e,`subagent`))t.add(n);for(let n of _D(e,`rule`))t.add(n);return[...t].sort()}function xD(e){try{return Cp(e).yamlFrontMatter}catch{return}}function SD(e,t,n=!1){if(!(i.existsSync(e)&&i.statSync(e).isFile()))return;let r=i.statSync(e),a=t?i.readFileSync(e,`utf8`):void 0,o={path:e,exists:!0,mtime:r.mtime.toISOString(),mtimeMs:r.mtimeMs,size:r.size,...n?{legacySource:!0}:{},...a==null?{}:{content:a}},s=a==null?void 0:xD(a);return s!=null&&Object.assign(o,{frontMatter:s}),o}function CD(e,t){return t==null?`missing`:e!=null&&t.mtimeMs<e.mtimeMs?`stale`:`ready`}function wD(e,t){let n=i.existsSync(e.paths.zh),{legacyZhPath:r}=e,a=!n&&r!=null&&i.existsSync(r),o=n?e.paths.zh:a?r:void 0,s=o==null?void 0:SD(o,t,a),c=n||r!==e.paths.en?SD(e.paths.en,t):void 0,l=SD(e.paths.dist,t);if(s==null&&c==null&&l==null)return null;let u=[s,c,l].filter(e=>e!=null).sort((e,t)=>t.mtimeMs-e.mtimeMs)[0]?.mtime,d={promptId:e.promptId,kind:e.kind,logicalName:e.logicalName,paths:e.paths,exists:{zh:s!=null,en:c!=null,dist:l!=null},enStatus:CD(s,c),distStatus:CD(s,l),...u==null?{}:{updatedAt:u},...s?.legacySource===!0?{legacyZhSource:!0}:{},src:{...s==null?{}:{zh:s},...c==null?{}:{en:c}}};l!=null&&Object.assign(d,{dist:l});let f=s?.frontMatter??c?.frontMatter??l?.frontMatter;return f!=null&&Object.assign(d,{frontMatter:f}),d}function TD(e,t){return t==null||t.length===0?!0:t.includes(e)}function ED(e,t){if(t==null||t.trim().length===0)return!0;let n=t.trim().toLowerCase();return e.promptId.toLowerCase().includes(n)||e.logicalName.toLowerCase().includes(n)}function DD(e){return{promptId:e.promptId,kind:e.kind,logicalName:e.logicalName,paths:e.paths,exists:e.exists,enStatus:e.enStatus,distStatus:e.distStatus,...e.updatedAt==null?{}:{updatedAt:e.updatedAt},...e.legacyZhSource===!0?{legacyZhSource:!0}:{}}}function OD(e){return eD.has(e.kind)}function kD(e,t){i.mkdirSync(u.dirname(e),{recursive:!0}),i.writeFileSync(e,t,`utf8`)}function AD(e){if(!OD(e)||i.existsSync(e.paths.zh)||e.legacyZhPath==null||!i.existsSync(e.legacyZhPath))return;let t=i.readFileSync(e.legacyZhPath,`utf8`);kD(e.paths.zh,t)}function jD(e){OD(e)&&(e.legacyZhPath==null||e.legacyZhPath===e.paths.zh||i.existsSync(e.legacyZhPath)&&i.rmSync(e.legacyZhPath,{force:!0}))}async function MD(e={}){let t=aD(e);return bD(t).map(e=>wD(gD(e,t),!1)).filter(e=>e!=null).map(DD).filter(t=>TD(t.kind,e.kinds)).filter(t=>TD(t.enStatus,e.enStatus)).filter(t=>TD(t.distStatus,e.distStatus)).filter(t=>ED(t,e.query)).sort((e,t)=>e.promptId.localeCompare(t.promptId))}async function ND(e,t={}){return wD(gD(e,aD(t)),!0)}async function PD(e){let t=aD(e),n=e.locale??`zh`,r=gD(e.promptId,t);n===`zh`?(kD(r.paths.zh,e.content),jD(r)):(AD(r),kD(r.paths.en,e.content));let i=wD(r,!0);if(i==null)throw Error(`Failed to load prompt after write: ${e.promptId}`);return i}async function FD(e){if(e.enContent==null&&e.distContent==null)throw Error(`writePromptArtifacts requires enContent or distContent`);let t=aD(e),n=gD(e.promptId,t);e.enContent!=null&&(AD(n),kD(n.paths.en,e.enContent)),e.distContent!=null&&kD(n.paths.dist,e.distContent);let r=wD(n,!0);if(r==null)throw Error(`Failed to load prompt after write: ${e.promptId}`);return r}async function ID(e,t={}){return gD(e,aD(t)).paths}function LD(e=c.argv){let t=e[1];if(t==null||t.length===0||!a(t))return!1;try{return s(t)===s(l(import.meta.url))}catch{return!1}}LD()&&XE(c.argv).then(e=>c.exit(e));export{RS as ConfigLoader,FS as DEFAULT_CONFIG_FILE_NAME,IS as DEFAULT_GLOBAL_CONFIG_DIR,dx as DEFAULT_USER_CONFIG,ux as PathPlaceholders,$C as PluginPipeline,ew as checkVersionControl,UE as createDefaultPluginConfig,wT as defineConfig,nw as generateAindex,BS as getConfigLoader,LS as getGlobalConfigPath,ND as getPrompt,GE as isJsonMode,MD as listPrompts,VS as loadUserConfig,lT as mergeConfig,ID as resolvePromptDefinition,XE as runCli,PD as upsertPromptSource,cT as userConfigToPluginOptions,HS as validateGlobalConfig,FD as writePromptArtifacts};
|
|
312
|
+
`)}};const dD=`.zed`;var fD=class extends ux{constructor(){super(`ZedIDEConfigOutputPlugin`,{cleanup:{delete:{project:{files:[`.zed/settings.json`]}}},capabilities:{}})}async declareOutputFiles(e){let t=[],{projects:n}=e.collectedOutputContext.workspace,r=e.collectedOutputContext.zedConfigFiles??[];for(let e of n){let n=e.dirFromWorkspacePath;if(n!=null)for(let e of r){let r=this.getTargetRelativePath(e);t.push({path:this.resolvePath(n.basePath,n.path,r),scope:`project`,source:{content:e.content}})}}return t}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}getTargetRelativePath(e){let t=e.dir.path;if(e.type!==ch.Zed)return this.basename(t);let n=t.indexOf(dD);return n===-1?this.joinPath(dD,`settings.json`):t.slice(Math.max(0,n))}};const pD=`GLOBAL.md`;var mD=class extends ux{constructor(){super(`TraeCNIDEOutputPlugin`,{globalConfigDir:`.trae-cn`,outputFileName:pD,dependsOn:[`TraeIDEOutputPlugin`],cleanup:{delete:{global:{dirs:[`.trae-cn/user_rules`]}}},capabilities:{prompt:{scopes:[`global`],singleScope:!1}}})}getGlobalUserRulesDir(){return this.joinPath(this.getGlobalConfigDir(),`user_rules`)}async declareOutputFiles(e){if(!new Set(this.selectPromptScopes(e,[`global`])).has(`global`))return[];let{globalMemory:t}=e.collectedOutputContext;return t==null?[]:[{path:this.joinPath(this.getGlobalUserRulesDir(),pD),scope:`global`,source:{content:t.content}}]}async convertContent(e,t){let n=e.source;if(n.content==null)throw Error(`Unsupported declaration source for ${this.name}`);return n.content}};async function hD(e=c.argv){return XT({pipelineArgs:e,pluginOptions:{plugins:[new tE,new rE,new PE,new wE,new mE,new vE,new $T,new BE,new qE,new eD,new mD,new iD,new uD,new fE,new yE,new EE,new gE,new nD,new fD,new YE]}})}const gD=new Set([`help`,`version`,`unknown`]);function _D(e){return e.some(e=>e===`--json`||e===`-j`||/^-[^-]*j/.test(e))}function vD(e){let t=e instanceof Error?e.message:String(e);zx(`main`,`silent`).error(A(`main`,e)),c.stdout.write(`${JSON.stringify(Ux({success:!1,filesAffected:0,dirsAffected:0,message:t},Bx()))}\n`)}function yD(e){throw Error(`${e} context is unavailable for lightweight commands`)}function bD(e){let t=c.cwd(),n=FT({workspaceDir:t,...e==null?{}:{logLevel:e}});return{logger:zx(`PluginPipeline`,e),outputPlugins:[],collectedOutputContext:{workspace:{directory:{pathKind:sh.Absolute,path:t,getDirectoryName:()=>u.basename(t)},projects:[]}},userConfigOptions:n,createCleanContext:()=>yD(`cleanup`),createWriteContext:()=>yD(`write`)}}function xD(e){let t=uw(ow(e.filter(e=>e!=null))),n=mw(t);if(gD.has(n.name))return t.logLevel!=null&&Vx(t.logLevel),t.jsonFlag&&(Vx(`silent`),n=new Hx(n)),{command:n,context:bD(t.logLevel)}}async function SD(e=c.argv){try{let t=xD(e);if(t!=null)return(await t.command.execute(t.context)).success?0:1;let n=new yw(...e),r=await hD(e);return(await n.run(r)).success?0:1}catch(t){return _D(e)?(vD(t),1):(zx(`main`,`error`).error(A(`main`,t)),1)}}const CD=`.src.mdx`,wD=`.mdx`,TD=`skill`,ED=new Set([`project-memory`,`project-child-memory`]);function DD(e){return e.replaceAll(`\\`,`/`)}function OD(e,t){let n=DD(e).trim();if(n.length===0)throw Error(`${t} cannot be empty`);let r=n.split(`/`);for(let e of r)if(e.length===0||e===`.`||e===`..`)throw Error(`${t} contains an invalid path segment`);return r.join(`/`)}function kD(e){return!DD(e).includes(`/`)}function AD(e,t){let n=e;return n.includes(dx.WORKSPACE)&&(n=n.replace(dx.WORKSPACE,t)),og(n)}function jD(e={}){let{cwd:t,loadUserConfig:n=!0,pluginOptions:r={}}=e,i={};if(n){let e=oC().load(t);e.found&&(i=PT(e.config))}let a=FT(i,r),o=AD(a.workspaceDir,``);return{options:a,workspaceDir:o,aindexDir:u.join(o,a.aindex.dir)}}function MD(e){return e.endsWith(CD)?`${e.slice(0,-8)}${wD}`:u.extname(e)===wD?e:`${e}${wD}`}function ND(e){return e.endsWith(CD)?e.slice(0,-8):e.endsWith(wD)?e.slice(0,-4):e}function PD(e,t){return i.existsSync(e)&&i.statSync(e).isDirectory()?Um.default.sync([...t],{cwd:e,dot:!0,onlyFiles:!0}).map(DD):[]}function FD(e){let t=u.join(e.aindexDir,e.options.aindex.globalPrompt.src);return{promptId:`global-memory`,kind:`global-memory`,logicalName:`global-memory`,paths:{zh:t,en:MD(t),dist:u.join(e.aindexDir,e.options.aindex.globalPrompt.dist)}}}function ID(e){let t=u.join(e.aindexDir,e.options.aindex.workspacePrompt.src);return{promptId:`workspace-memory`,kind:`workspace-memory`,logicalName:`workspace-memory`,paths:{zh:t,en:MD(t),dist:u.join(e.aindexDir,e.options.aindex.workspacePrompt.dist)}}}function LD(e,t,n,r){let i=OD(n,`projectName`);if(!kD(i))throw Error(`projectName must be a single path segment`);let a=r==null?``:OD(r,`relativeName`),o=Tw(e.options,t),s=a.length===0?u.join(e.aindexDir,o.src,i):u.join(e.aindexDir,o.src,i,a),c=a.length===0?u.join(e.aindexDir,o.dist,i):u.join(e.aindexDir,o.dist,i,a),l=u.join(s,`agt${wD}`),d=a.length===0?`${t}/${i}`:`${t}/${i}/${a}`;return{promptId:a.length===0?`project-memory:${d}`:`project-child-memory:${d}`,kind:a.length===0?`project-memory`:`project-child-memory`,logicalName:d,paths:{zh:u.join(s,`agt${CD}`),en:l,dist:u.join(c,`agt${wD}`)},legacyZhPath:l}}function RD(e,t){let n=OD(t,`skillName`);if(!kD(n))throw Error(`skillName must be a single path segment`);let r=u.join(e.aindexDir,e.options.aindex.skills.src,n),i=u.join(e.aindexDir,e.options.aindex.skills.dist,n);return{promptId:`skill:${n}`,kind:`skill`,logicalName:n,paths:{zh:u.join(r,`${TD}${CD}`),en:u.join(r,`${TD}${wD}`),dist:u.join(i,`${TD}${wD}`)}}}function zD(e,t,n){let r=OD(t,`skillName`),i=OD(n,`relativeName`);if(!kD(r))throw Error(`skillName must be a single path segment`);let a=u.join(e.aindexDir,e.options.aindex.skills.src,r),o=u.join(e.aindexDir,e.options.aindex.skills.dist,r);return{promptId:`skill-child-doc:${r}/${i}`,kind:`skill-child-doc`,logicalName:`${r}/${i}`,paths:{zh:u.join(a,`${i}${CD}`),en:u.join(a,`${i}${wD}`),dist:u.join(o,`${i}${wD}`)}}}function BD(e,t,n){let r=OD(n,`relativeName`),i=t===`command`?u.join(e.aindexDir,e.options.aindex.commands.src):t===`subagent`?u.join(e.aindexDir,e.options.aindex.subAgents.src):u.join(e.aindexDir,e.options.aindex.rules.src),a=t===`command`?u.join(e.aindexDir,e.options.aindex.commands.dist):t===`subagent`?u.join(e.aindexDir,e.options.aindex.subAgents.dist):u.join(e.aindexDir,e.options.aindex.rules.dist);return{promptId:`${t}:${r}`,kind:t,logicalName:r,paths:{zh:u.join(i,`${r}${CD}`),en:u.join(i,`${r}${wD}`),dist:u.join(a,`${r}${wD}`)}}}function VD(e){switch(e){case`global-memory`:return{kind:`global-memory`};case`workspace-memory`:return{kind:`workspace-memory`};default:break}let t=e.indexOf(`:`);if(t===-1)throw Error(`Unsupported promptId: ${e}`);let n=e.slice(0,t),r=OD(e.slice(t+1),`promptId`);switch(n){case`project-memory`:return HD(n,r);case`project-child-memory`:return HD(n,r);case`skill`:if(!kD(r))throw Error(`skill promptId must include a single skill name`);return{kind:n,skillName:r};case`skill-child-doc`:{let[e,...t]=r.split(`/`),i=t.join(`/`);if(e==null||i.length===0)throw Error(`skill-child-doc promptId must include skill and child path`);return{kind:n,skillName:e,relativeName:i}}case`command`:case`subagent`:case`rule`:return{kind:n,relativeName:r};default:throw Error(`Unsupported promptId: ${e}`)}}function HD(e,t){let n=t.split(`/`),r=n[0],i=r!=null&&Cw(r);if(e===`project-memory`){if(i){let t=n[1];if(t==null||n.length!==2)throw Error(`project-memory promptId must include exactly one project name after the series`);return{kind:e,seriesName:r,projectName:t}}if(!kD(t))throw Error(`project-memory promptId must include a single project name`);return{kind:e,seriesName:`app`,projectName:t}}if(i){let t=n[1],i=n.slice(2).join(`/`);if(t==null||i.length===0)throw Error(`project-child-memory promptId must include series, project, and child path`);return{kind:e,seriesName:r,projectName:t,relativeName:i}}let[a,...o]=n,s=o.join(`/`);if(a==null||s.length===0)throw Error(`project-child-memory promptId must include project and child path`);return{kind:e,seriesName:`app`,projectName:a,relativeName:s}}function UD(e,t){let n=VD(e);switch(n.kind){case`global-memory`:return FD(t);case`workspace-memory`:return ID(t);case`project-memory`:if(n.projectName==null)throw Error(`project-memory promptId must include a project name`);return LD(t,n.seriesName??`app`,n.projectName);case`project-child-memory`:if(n.projectName==null||n.relativeName==null)throw Error(`project-child-memory promptId must include project and child path`);return LD(t,n.seriesName??`app`,n.projectName,n.relativeName);case`skill`:if(n.skillName==null)throw Error(`skill promptId must include a skill name`);return RD(t,n.skillName);case`skill-child-doc`:if(n.skillName==null||n.relativeName==null)throw Error(`skill-child-doc promptId must include skill and child path`);return zD(t,n.skillName,n.relativeName);case`command`:case`subagent`:case`rule`:if(n.relativeName==null)throw Error(`${n.kind} promptId must include a relative path`);return BD(t,n.kind,n.relativeName)}}function WD(e,t){let n=t===`command`?u.join(e.aindexDir,e.options.aindex.commands.src):t===`subagent`?u.join(e.aindexDir,e.options.aindex.subAgents.src):u.join(e.aindexDir,e.options.aindex.rules.src),r=t===`command`?u.join(e.aindexDir,e.options.aindex.commands.dist):t===`subagent`?u.join(e.aindexDir,e.options.aindex.subAgents.dist):u.join(e.aindexDir,e.options.aindex.rules.dist),i=new Set;for(let e of PD(n,[`**/*${CD}`,`**/*${wD}`]))i.add(ND(e));for(let e of PD(r,[`**/*${wD}`]))i.add(ND(e));return[...i].sort().map(e=>`${t}:${e}`)}function GD(e){let t=u.join(e.aindexDir,e.options.aindex.skills.src),n=u.join(e.aindexDir,e.options.aindex.skills.dist),r=new Set;if(i.existsSync(t)&&i.statSync(t).isDirectory())for(let e of i.readdirSync(t,{withFileTypes:!0}))e.isDirectory()&&r.add(e.name);if(i.existsSync(n)&&i.statSync(n).isDirectory())for(let e of i.readdirSync(n,{withFileTypes:!0}))e.isDirectory()&&r.add(e.name);let a=[];for(let e of[...r].sort()){a.push(`skill:${e}`);let r=u.join(t,e),i=u.join(n,e),o=new Set;for(let e of PD(r,[`**/*${CD}`,`**/*${wD}`])){let t=ND(e);t!==TD&&o.add(t)}for(let e of PD(i,[`**/*${wD}`])){let t=ND(e);t!==TD&&o.add(t)}for(let t of[...o].sort())a.push(`skill-child-doc:${e}/${t}`)}return a}function KD(e){let t=[];for(let n of ww(e.options)){let r=u.join(e.aindexDir,n.src),i=u.join(e.aindexDir,n.dist),a=new Set;for(let e of PD(r,[`**/agt${CD}`,`**/agt${wD}`])){let t=DD(u.posix.dirname(DD(e)));t!==`.`&&a.add(t)}for(let e of PD(i,[`**/agt${wD}`])){let t=DD(u.posix.dirname(DD(e)));t!==`.`&&a.add(t)}for(let e of[...a].sort()){let[r,...i]=e.split(`/`),a=i.join(`/`);r==null||r.length===0||t.push(a.length===0?`project-memory:${n.name}/${r}`:`project-child-memory:${n.name}/${r}/${a}`)}}return t}function qD(e){let t=new Set,n=FD(e),r=ID(e);(i.existsSync(n.paths.zh)||i.existsSync(n.paths.en)||i.existsSync(n.paths.dist))&&t.add(n.promptId),(i.existsSync(r.paths.zh)||i.existsSync(r.paths.en)||i.existsSync(r.paths.dist))&&t.add(r.promptId);for(let n of KD(e))t.add(n);for(let n of GD(e))t.add(n);for(let n of WD(e,`command`))t.add(n);for(let n of WD(e,`subagent`))t.add(n);for(let n of WD(e,`rule`))t.add(n);return[...t].sort()}function JD(e){try{return Cp(e).yamlFrontMatter}catch{return}}function YD(e,t,n=!1){if(!(i.existsSync(e)&&i.statSync(e).isFile()))return;let r=i.statSync(e),a=t?i.readFileSync(e,`utf8`):void 0,o={path:e,exists:!0,mtime:r.mtime.toISOString(),mtimeMs:r.mtimeMs,size:r.size,...n?{legacySource:!0}:{},...a==null?{}:{content:a}},s=a==null?void 0:JD(a);return s!=null&&Object.assign(o,{frontMatter:s}),o}function XD(e,t){return t==null?`missing`:e!=null&&t.mtimeMs<e.mtimeMs?`stale`:`ready`}function ZD(e,t){let n=i.existsSync(e.paths.zh),{legacyZhPath:r}=e,a=!n&&r!=null&&i.existsSync(r),o=n?e.paths.zh:a?r:void 0,s=o==null?void 0:YD(o,t,a),c=n||r!==e.paths.en?YD(e.paths.en,t):void 0,l=YD(e.paths.dist,t);if(s==null&&c==null&&l==null)return null;let u=[s,c,l].filter(e=>e!=null).sort((e,t)=>t.mtimeMs-e.mtimeMs)[0]?.mtime,d={promptId:e.promptId,kind:e.kind,logicalName:e.logicalName,paths:e.paths,exists:{zh:s!=null,en:c!=null,dist:l!=null},enStatus:XD(s,c),distStatus:XD(s,l),...u==null?{}:{updatedAt:u},...s?.legacySource===!0?{legacyZhSource:!0}:{},src:{...s==null?{}:{zh:s},...c==null?{}:{en:c}}};l!=null&&Object.assign(d,{dist:l});let f=s?.frontMatter??c?.frontMatter??l?.frontMatter;return f!=null&&Object.assign(d,{frontMatter:f}),d}function QD(e,t){return t==null||t.length===0?!0:t.includes(e)}function $D(e,t){if(t==null||t.trim().length===0)return!0;let n=t.trim().toLowerCase();return e.promptId.toLowerCase().includes(n)||e.logicalName.toLowerCase().includes(n)}function eO(e){return{promptId:e.promptId,kind:e.kind,logicalName:e.logicalName,paths:e.paths,exists:e.exists,enStatus:e.enStatus,distStatus:e.distStatus,...e.updatedAt==null?{}:{updatedAt:e.updatedAt},...e.legacyZhSource===!0?{legacyZhSource:!0}:{}}}function tO(e){return ED.has(e.kind)}function nO(e,t){i.mkdirSync(u.dirname(e),{recursive:!0}),i.writeFileSync(e,t,`utf8`)}function rO(e){if(!tO(e)||i.existsSync(e.paths.zh)||e.legacyZhPath==null||!i.existsSync(e.legacyZhPath))return;let t=i.readFileSync(e.legacyZhPath,`utf8`);nO(e.paths.zh,t)}function iO(e){tO(e)&&(e.legacyZhPath==null||e.legacyZhPath===e.paths.zh||i.existsSync(e.legacyZhPath)&&i.rmSync(e.legacyZhPath,{force:!0}))}async function aO(e={}){let t=jD(e);return qD(t).map(e=>ZD(UD(e,t),!1)).filter(e=>e!=null).map(eO).filter(t=>QD(t.kind,e.kinds)).filter(t=>QD(t.enStatus,e.enStatus)).filter(t=>QD(t.distStatus,e.distStatus)).filter(t=>$D(t,e.query)).sort((e,t)=>e.promptId.localeCompare(t.promptId))}async function oO(e,t={}){return ZD(UD(e,jD(t)),!0)}async function sO(e){let t=jD(e),n=e.locale??`zh`,r=UD(e.promptId,t);n===`zh`?(nO(r.paths.zh,e.content),iO(r)):(rO(r),nO(r.paths.en,e.content));let i=ZD(r,!0);if(i==null)throw Error(`Failed to load prompt after write: ${e.promptId}`);return i}async function cO(e){if(e.enContent==null&&e.distContent==null)throw Error(`writePromptArtifacts requires enContent or distContent`);let t=jD(e),n=UD(e.promptId,t);e.enContent!=null&&(rO(n),nO(n.paths.en,e.enContent)),e.distContent!=null&&nO(n.paths.dist,e.distContent);let r=ZD(n,!0);if(r==null)throw Error(`Failed to load prompt after write: ${e.promptId}`);return r}async function lO(e,t={}){return UD(e,jD(t)).paths}function uO(e=c.argv){let t=e[1];if(t==null||t.length===0||!a(t))return!1;try{return s(t)===s(l(import.meta.url))}catch{return!1}}uO()&&SD(c.argv).then(e=>c.exit(e));export{iC as ConfigLoader,tC as DEFAULT_CONFIG_FILE_NAME,nC as DEFAULT_GLOBAL_CONFIG_DIR,fx as DEFAULT_USER_CONFIG,dx as PathPlaceholders,yw as PluginPipeline,bw as checkVersionControl,hD as createDefaultPluginConfig,XT as defineConfig,Sw as generateAindex,oC as getConfigLoader,rC as getGlobalConfigPath,oO as getPrompt,_D as isJsonMode,aO as listPrompts,sC as loadUserConfig,FT as mergeConfig,lO as resolvePromptDefinition,SD as runCli,sO as upsertPromptSource,PT as userConfigToPluginOptions,cC as validateGlobalConfig,cO as writePromptArtifacts};
|