@truenine/memory-sync-cli 2026.10324.10015 → 2026.10324.11958
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.mjs +42 -41
- package/dist/plugin-runtime.mjs +41 -40
- package/package.json +9 -9
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{i as e,r as t,t as n}from"./chunk-tuRmWmEN.mjs";import{createRequire as r}from"node:module";import*as i from"node:fs";import{existsSync as a,readdirSync as o,realpathSync as s}from"node:fs";import c from"node:process";import{fileURLToPath as l}from"node:url";import*as u from"node:path";import d,{dirname as f,join as p}from"node:path";import{spawn as m,spawnSync as h}from"node:child_process";import*as g from"node:os";import{Buffer as _}from"node:buffer";import{z as
|
|
2
|
+
import{i as e,r as t,t as n}from"./chunk-tuRmWmEN.mjs";import{createRequire as r}from"node:module";import*as i from"node:fs";import{existsSync as a,readdirSync as o,realpathSync as s}from"node:fs";import c from"node:process";import{fileURLToPath as l}from"node:url";import*as u from"node:path";import d,{dirname as f,join as p}from"node:path";import{spawn as m,spawnSync as h}from"node:child_process";import*as g from"node:os";import{Buffer as _}from"node:buffer";import v from"json5";import{z as y}from"zod/v3";function b(e,...t){return[e,...t]}function x(e){return e instanceof Error?e.message:String(e)}function S(e){let t=e.split(/\r?\n/u).map(e=>e.trimEnd()).filter(e=>e.length>0);if(t.length===0)return b(`No diagnostic details were provided.`);let[n,...r]=t;return n==null?b(`No diagnostic details were provided.`):b(n,...r)}function C(e){return e}function w(e){return x(e).toLowerCase()}function T(e){if(e.platform!==`win32`||e.operation!==`delete`||e.targetKind!==`directory`)return!1;let t=w(e.error);return t.includes(`eperm`)||t.includes(`permission denied`)}function E(e){return T(e)?{exactFix:b(`Close any process that is using "${e.path}", delete the stale directory, and rerun tnmsc.`,`Common lockers on Windows include editors, terminals, antivirus scanners, sync clients, and AI tools watching generated files.`),possibleFixes:[b(`Use Resource Monitor or Process Explorer to find which process holds a handle under "${e.path}".`),b(`Make sure no shell, editor tab, or file watcher is currently opened inside "${e.path}" or one of its children.`),b(`If antivirus or cloud sync is scanning generated outputs, wait for it to release the directory or exclude this output path.`)]}:{exactFix:b(`Verify that "${e.path}" exists, has the expected type, and is accessible to tnmsc.`),possibleFixes:[b(`Check file permissions and ownership for the target path.`),b(`Confirm that another process did not delete, move, or lock the target path.`)]}}function D(e){let{code:t,title:n,operation:r,targetKind:i,path:a,error:o,platform:s,exactFix:l,possibleFixes:u,details:d}=e,f=x(o),p=E({operation:r,targetKind:i,path:a,error:o,platform:s??c.platform});return C({code:t,title:n,rootCause:b(`tnmsc could not ${r} the ${i} at "${a}".`,`Underlying error: ${f}`),exactFix:l??p.exactFix,possibleFixes:u??p.possibleFixes,details:{operation:r,targetKind:i,path:a,errorMessage:f,platform:s??c.platform,...d??{}}})}function O(e){let{code:t,title:n,reason:r,configPath:i,exactFix:a,possibleFixes:o,details:s}=e;return C({code:t,title:n,rootCause:i==null?r:b(r[0],...r.slice(1),`Config path: ${i}`),exactFix:a,possibleFixes:o,details:{...i==null?{}:{configPath:i},...s??{}}})}function k(e){return C(e)}function A(e){let{code:t,title:n,path:r,expectedKind:i,actualState:a,exactFix:o,possibleFixes:s,details:c}=e;return C({code:t,title:n,rootCause:b(`tnmsc expected a ${i} at "${r}".`,`Actual state: ${a}`),exactFix:o??b(`Create or replace "${r}" with a valid ${i} before retrying tnmsc.`),possibleFixes:s??[b(`Check whether the path was moved, deleted, or replaced with the wrong file type.`),b(`Update your configuration so tnmsc points to the intended source path.`)],details:{path:r,expectedKind:i,actualState:a,...c??{}}})}function ee(e){let{code:t,title:n,diagnosticText:r,exactFix:i,possibleFixes:a,details:o}=e;return C({code:t,title:n,rootCause:S(r),exactFix:i??b(`Fix the referenced prompt source or compiled dist file so the compiler diagnostic no longer triggers.`),possibleFixes:a??[b(`Open the file referenced in the diagnostic and correct the reported syntax or metadata issue.`),b(`Rebuild the prompt output so the dist file matches the current source tree.`)],details:{diagnosticText:r,...o??{}}})}function te(e,t){let n=t[0];return C({code:`PROTECTED_DELETION_GUARD_TRIGGERED`,title:`Protected deletion guard blocked a destructive operation`,rootCause:b(`The "${e}" operation targeted ${t.length} protected path(s).`,n==null?`No violation details were captured.`:`Example protected path: ${n.protectedPath}`),exactFix:b(`Remove protected inputs or reserved workspace paths from the delete plan before running tnmsc again.`),possibleFixes:[b(`Update cleanup declarations so they only target generated output paths.`),b(`Move source inputs outside of the cleanup target set if they are currently overlapping.`)],details:{operation:e,count:t.length,violations:t.map(e=>({targetPath:e.targetPath,protectedPath:e.protectedPath,protectionMode:e.protectionMode,source:e.source,reason:e.reason}))}})}function j(e,t){let n=x(t);return C({code:`UNHANDLED_EXCEPTION`,title:`Unhandled exception in ${e}`,rootCause:b(`tnmsc terminated because an unhandled exception escaped the ${e} flow.`,`Underlying error: ${n}`),exactFix:b(`Inspect the error context and add the missing guard, validation, or recovery path before retrying the command.`),possibleFixes:[b(`Re-run the command with the same inputs after fixing the referenced file or configuration.`),b(`Add a focused test that reproduces this failure so the regression stays covered.`)],details:{context:e,errorMessage:n}})}function ne(e){let t=[],n=[];for(let r of e)r.level===`warn`?t.push(r):n.push(r);return{warnings:t,errors:n}}const re={"win32-x64":{local:`napi-logger.win32-x64-msvc`,suffix:`win32-x64-msvc`},"linux-x64":{local:`napi-logger.linux-x64-gnu`,suffix:`linux-x64-gnu`},"linux-arm64":{local:`napi-logger.linux-arm64-gnu`,suffix:`linux-arm64-gnu`},"darwin-arm64":{local:`napi-logger.darwin-arm64`,suffix:`darwin-arm64`},"darwin-x64":{local:`napi-logger.darwin-x64`,suffix:`darwin-x64`}},ie=[`error`,`warn`,`fatal`],M=[`info`,`debug`,`trace`];let ae,oe;function se(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.createLogger==`function`&&typeof t.setGlobalLogLevel==`function`&&typeof t.getGlobalLogLevel==`function`&&typeof t.clearBufferedDiagnostics==`function`&&typeof t.drainBufferedDiagnostics==`function`}function N(){let e=re[`${c.platform}-${c.arch}`];if(e!=null)return e;throw Error(`Unsupported platform for @truenine/logger native binding: ${c.platform}-${c.arch}`)}function P(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/logger native binding.`,`Tried local binary "./${re[`${c.platform}-${c.arch}`]?.local??`unknown`}.node" and package "@truenine/memory-sync-cli-${n}".`,`Local error: ${r}`,`Package error: ${i}`,"Run `pnpm -F @truenine/logger run build` to build the native module."].join(`
|
|
3
3
|
`))}function F(e,t){let n=`@truenine/memory-sync-cli-${t}`;try{let t=e(n).logger;if(se(t))return t}catch{}let r=f(e.resolve(`${n}/package.json`)),i=o(r).filter(e=>e.startsWith(`napi-logger.`)&&e.endsWith(`.node`)).sort();for(let t of i){let n=e(p(r,t));if(se(n))return n}throw Error(`Package "${n}" does not export a logger binding or contain a compatible native module`)}function ce(){let e=import.meta.url,t=r(e),{local:n,suffix:i}=N();try{return t(`./${n}.node`)}catch(e){try{return F(t,i)}catch(t){throw P(e,t,i)}}}function le(){if(ae!=null)return ae;if(oe!=null)throw oe;try{return ae=ce(),ae}catch(e){throw oe=e instanceof Error?e:Error(String(e)),oe}}function ue(e){let t={name:e.name,message:e.message,stack:e.stack};for(let n of Object.getOwnPropertyNames(e))n===`name`||n===`message`||n===`stack`||(t[n]=e[n]);return t}function I(){let e=new WeakSet;return function(t,n){return n instanceof Error?ue(n):typeof n==`bigint`?n.toString():typeof n==`function`?`[Function ${n.name||`anonymous`}]`:typeof n==`symbol`?n.toString():typeof n!=`object`||!n?n:e.has(n)?`[Circular]`:(e.add(n),n)}}function de(e){return JSON.stringify(e,I())??`null`}function fe(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function pe(e,t){if(typeof e!=`string`)return{message:``,metaJson:de(e)};let n=t.length===1&&typeof t[0]==`object`&&t[0]!==null?t[0]:t.length>0?{args:t}:void 0;return{message:e,metaJson:n==null?void 0:de(n)}}function me(e,t){return(n,...r)=>{let{message:i,metaJson:a}=pe(n,r);e.log(t,i,a)}}function L(e,t){return n=>e.logDiagnostic(t,de(n))}function he(e){let t=M.reduce((t,n)=>(t[n]=me(e,n),t),{}),n=ie.reduce((t,n)=>(t[n]=L(e,n),t),{});return{error:n.error,warn:n.warn,info:t.info,debug:t.debug,trace:t.trace,fatal:n.fatal}}function ge(e){le().setGlobalLogLevel(e)}function _e(){le().clearBufferedDiagnostics()}function ve(){return fe(le().drainBufferedDiagnostics())}function ye(e,t){return he(le().createLogger(e,t))}var be=Object.create,xe=Object.defineProperty,Se=Object.getOwnPropertyDescriptor,Ce=Object.getOwnPropertyNames,we=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty,R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ee=(e,t)=>{let n={};for(var r in e)xe(n,r,{get:e[r],enumerable:!0});return t||xe(n,Symbol.toStringTag,{value:`Module`}),n},De=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ce(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Te.call(e,s)&&s!==n&&xe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Se(t,s))||r.enumerable});return e},z=(e,t,n)=>(n=e==null?{}:be(we(e)),De(t||!e||!e.__esModule?xe(n,`default`,{value:e,enumerable:!0}):n,e)),Oe=r(import.meta.url);const ke=Le(/[A-Za-z]/),Ae=Le(/[\dA-Za-z]/),je=Le(/[#-'*+\--9=?A-Z^-~]/);function Me(e){return e!==null&&(e<32||e===127)}const Ne=Le(/\d/),Pe=Le(/[\dA-Fa-f]/),Fe=Le(/[!-/:-@[-`{-~]/);function B(e){return e!==null&&e<-2}function V(e){return e!==null&&(e<0||e===32)}function H(e){return e===-2||e===-1||e===32}const Ie=Le(/\p{P}|\p{S}/u),U=Le(/\s/);function Le(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}var Re=z(R(((e,t)=>{(function(){var e=t===void 0?function(){return this||(0,eval)(`this`)}():t.exports=i;e.format=i,e.vsprintf=r,typeof console<`u`&&typeof console.log==`function`&&(e.printf=n);function n(){console.log(i.apply(null,arguments))}function r(e,t){return i.apply(null,[e].concat(t))}function i(e){for(var t=1,n=[].slice.call(arguments),r=0,i=e.length,a=``,o,s=!1,c,l,u=!1,d,f=function(){return n[t++]},p=function(){for(var t=``;/\d/.test(e[r]);)t+=e[r++],o=e[r];return t.length>0?parseInt(t):null};r<i;++r)if(o=e[r],s)switch(s=!1,o==`.`?(u=!1,o=e[++r]):o==`0`&&e[r+1]==`.`?(u=!0,r+=2,o=e[r]):u=!0,d=p(),o){case`b`:a+=parseInt(f(),10).toString(2);break;case`c`:c=f(),typeof c==`string`||c instanceof String?a+=c:a+=String.fromCharCode(parseInt(c,10));break;case`d`:a+=parseInt(f(),10);break;case`f`:l=String(parseFloat(f()).toFixed(d||6)),a+=u?l:l.replace(/^0/,``);break;case`j`:a+=JSON.stringify(f());break;case`o`:a+=`0`+parseInt(f(),10).toString(8);break;case`s`:a+=f();break;case`x`:a+=`0x`+parseInt(f(),10).toString(16);break;case`X`:a+=`0x`+parseInt(f(),10).toString(16).toUpperCase();break;default:a+=o;break}else o===`%`?s=!0:a+=o;return a}})()}))(),1);const ze=Object.assign(Be(Error),{eval:Be(EvalError),range:Be(RangeError),reference:Be(ReferenceError),syntax:Be(SyntaxError),type:Be(TypeError),uri:Be(URIError)});function Be(e){return t.displayName=e.displayName||e.name,t;function t(t,...n){return new e(t&&(0,Re.default)(t,...n))}}const Ve={}.hasOwnProperty,He={yaml:`-`,toml:`+`};function Ue(e){let t=[],n=-1,r=Array.isArray(e)?e:e?[e]:[`yaml`];for(;++n<r.length;)t[n]=We(r[n]);return t}function We(e){let t=e;if(typeof t==`string`){if(!Ve.call(He,t))throw ze("Missing matter definition for `%s`",t);t={type:t,marker:He[t]}}else if(typeof t!=`object`)throw ze("Expected matter to be an object, not `%j`",t);if(!Ve.call(t,`type`))throw ze("Missing `type` in matter `%j`",t);if(!Ve.call(t,`fence`)&&!Ve.call(t,`marker`))throw ze("Missing `marker` or `fence` in matter `%j`",t);return t}function Ge(e){let t=Ue(e),n={},r=-1;for(;++r<t.length;){let e=t[r],i=qe(e,`open`).charCodeAt(0),a=Ke(e),o=n[i];Array.isArray(o)?o.push(a):n[i]=[a]}return{flow:n}}function Ke(e){let t=e.anywhere,n=e.type,r=n+`Fence`,i=r+`Sequence`,a=n+`Value`,o={tokenize:u,partial:!0},s,c=0;return{tokenize:l,concrete:!0};function l(l,u,d){let f=this;return p;function p(a){let o=f.now();return o.column===1&&(o.line===1||t)&&(s=qe(e,`open`),c=0,a===s.charCodeAt(c))?(l.enter(n),l.enter(r),l.enter(i),m(a)):d(a)}function m(e){return c===s.length?(l.exit(i),H(e)?(l.enter(`whitespace`),h(e)):g(e)):e===s.charCodeAt(c++)?(l.consume(e),m):d(e)}function h(e){return H(e)?(l.consume(e),h):(l.exit(`whitespace`),g(e))}function g(t){return B(t)?(l.exit(r),l.enter(`lineEnding`),l.consume(t),l.exit(`lineEnding`),s=qe(e,`close`),c=0,l.attempt(o,b,_)):d(t)}function _(e){return e===null||B(e)?y(e):(l.enter(a),v(e))}function v(e){return e===null||B(e)?(l.exit(a),y(e)):(l.consume(e),v)}function y(e){return e===null?d(e):(l.enter(`lineEnding`),l.consume(e),l.exit(`lineEnding`),l.attempt(o,b,_))}function b(e){return l.exit(n),u(e)}}function u(e,t,n){let a=0;return o;function o(t){return t===s.charCodeAt(a)?(e.enter(r),e.enter(i),c(t)):n(t)}function c(t){return a===s.length?(e.exit(i),H(t)?(e.enter(`whitespace`),l(t)):u(t)):t===s.charCodeAt(a++)?(e.consume(t),c):n(t)}function l(t){return H(t)?(e.consume(t),l):(e.exit(`whitespace`),u(t))}function u(i){return i===null||B(i)?(e.exit(r),t(i)):n(i)}}}function qe(e,t){return e.marker?Je(e.marker,t).repeat(3):Je(e.fence,t)}function Je(e,t){return typeof e==`string`?e:e[t]}function Ye(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function Xe(e){let t=Ue(e),n={},r={},i=-1;for(;++i<t.length;){let e=t[i];n[e.type]=Ze(e),r[e.type]=Qe,r[e.type+`Value`]=$e}return{enter:n,exit:r}}function Ze(e){return t;function t(t){this.enter({type:e.type,value:``},t),this.buffer()}}function Qe(e){let t=this.resume(),n=this.stack[this.stack.length-1];`value`in n,this.exit(e),n.value=t.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,``)}function $e(e){this.config.enter.data.call(this,e),this.config.exit.data.call(this,e)}function et(e){let t=[],n={},r=Ue(e),i=-1;for(;++i<r.length;){let e=r[i];n[e.type]=tt(e);let a=nt(e,`open`);t.push({atBreak:!0,character:a.charAt(0),after:Ye(a.charAt(1))})}return{unsafe:t,handlers:n}}function tt(e){let t=nt(e,`open`),n=nt(e,`close`);return r;function r(e){return t+(e.value?`
|
|
4
4
|
`+e.value:``)+`
|
|
5
5
|
`+n}}function nt(e,t){return e.marker?rt(e.marker,t).repeat(3):rt(e.fence,t)}function rt(e,t){return typeof e==`string`?e:e[t]}function it(e){let t=this,n=e||`yaml`,r=t.data(),i=r.micromarkExtensions||=[],a=r.fromMarkdownExtensions||=[],o=r.toMarkdownExtensions||=[];i.push(Ge(n)),a.push(Xe(n)),o.push(et(n))}function at(e,t){let n=String(e);if(typeof t!=`string`)throw TypeError(`Expected character`);let r=0,i=n.indexOf(t);for(;i!==-1;)r++,i=n.indexOf(t,i+t.length);return r}const ot=(function(e){if(e==null)return dt;if(typeof e==`function`)return ut(e);if(typeof e==`object`)return Array.isArray(e)?st(e):ct(e);if(typeof e==`string`)return lt(e);throw Error(`Expected function, string, or object as test`)});function st(e){let t=[],n=-1;for(;++n<e.length;)t[n]=ot(e[n]);return ut(r);function r(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}function ct(e){let t=e;return ut(n);function n(n){let r=n,i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function lt(e){return ut(t);function t(t){return t&&t.type===e}}function ut(e){return t;function t(t,n,r){return!!(ft(t)&&e.call(this,t,typeof n==`number`?n:void 0,r||void 0))}}function dt(){return!0}function ft(e){return typeof e==`object`&&!!e&&`type`in e}function pt(e){return`\x1B[33m`+e+`\x1B[39m`}const mt=[];function W(e,t,n,r){let i;typeof t==`function`&&typeof n!=`function`?(r=n,n=t):i=t;let a=ot(i),o=r?-1:1;s(e,void 0,[])();function s(e,i,c){let l=e&&typeof e==`object`?e:{};if(typeof l.type==`string`){let t=typeof l.tagName==`string`?l.tagName:typeof l.name==`string`?l.name:void 0;Object.defineProperty(u,`name`,{value:`node (`+pt(e.type+(t?`<`+t+`>`:``))+`)`})}return u;function u(){let l=mt,u,d,f;if((!t||a(e,i,c[c.length-1]||void 0))&&(l=ht(n(e,c)),l[0]===!1))return l;if(`children`in e&&e.children){let t=e;if(t.children&&l[0]!==`skip`)for(d=(r?t.children.length:-1)+o,f=c.concat(t);d>-1&&d<t.children.length;){let e=t.children[d];if(u=s(e,d,f)(),u[0]===!1)return u;d=typeof u[1]==`number`?u[1]:d+o}}return l}}}function ht(e){return Array.isArray(e)?e:typeof e==`number`?[!0,e]:e==null?mt:[e]}function gt(e,t,n){let r=ot((n||{}).ignore||[]),i=_t(t),a=-1;for(;++a<i.length;)W(e,`text`,o);function o(e,t){let n=-1,i;for(;++n<t.length;){let e=t[n],a=i?i.children:void 0;if(r(e,a?a.indexOf(e):void 0,i))return;i=e}if(i)return s(e,t)}function s(e,t){let n=t[t.length-1],r=i[a][0],o=i[a][1],s=0,c=n.children.indexOf(e),l=!1,u=[];r.lastIndex=0;let d=r.exec(e.value);for(;d;){let n=d.index,i={index:d.index,input:d.input,stack:[...t,e]},a=o(...d,i);if(typeof a==`string`&&(a=a.length>0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s<e.value.length&&u.push({type:`text`,value:e.value.slice(s)}),n.children.splice(c,1,...u)):u=[e],c+u.length}}function _t(e){let t=[];if(!Array.isArray(e))throw TypeError(`Expected find and replace tuple or list of tuples`);let n=!e[0]||Array.isArray(e[0])?e:[e],r=-1;for(;++r<n.length;){let e=n[r];t.push([vt(e[0]),yt(e[1])])}return t}function vt(e){return typeof e==`string`?new RegExp(Ye(e),`g`):e}function yt(e){return typeof e==`function`?e:function(){return e}}const bt=`phrasing`,xt=[`autolink`,`link`,`image`,`label`];function St(){return{transforms:[At],enter:{literalAutolink:wt,literalAutolinkEmail:Tt,literalAutolinkHttp:Tt,literalAutolinkWww:Tt},exit:{literalAutolink:kt,literalAutolinkEmail:Ot,literalAutolinkHttp:Et,literalAutolinkWww:Dt}}}function Ct(){return{unsafe:[{character:`@`,before:`[+\\-.\\w]`,after:`[\\-.\\w]`,inConstruct:bt,notInConstruct:xt},{character:`.`,before:`[Ww]`,after:`[\\-.\\w]`,inConstruct:bt,notInConstruct:xt},{character:`:`,before:`[ps]`,after:`\\/`,inConstruct:bt,notInConstruct:xt}]}}function wt(e){this.enter({type:`link`,title:null,url:``,children:[]},e)}function Tt(e){this.config.enter.autolinkProtocol.call(this,e)}function Et(e){this.config.exit.autolinkProtocol.call(this,e)}function Dt(e){this.config.exit.data.call(this,e);let t=this.stack[this.stack.length-1];t.type,t.url=`http://`+this.sliceSerialize(e)}function Ot(e){this.config.exit.autolinkEmail.call(this,e)}function kt(e){this.exit(e)}function At(e){gt(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,jt],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,Mt]],{ignore:[`link`,`linkReference`]})}function jt(e,t,n,r,i){let a=``;if(!Ft(i)||(/^w/i.test(t)&&(n=t+n,t=``,a=`http://`),!Nt(n)))return!1;let o=Pt(n+r);if(!o[0])return!1;let s={type:`link`,title:null,url:a+t+o[0],children:[{type:`text`,value:t+o[0]}]};return o[1]?[s,{type:`text`,value:o[1]}]:s}function Mt(e,t,n,r){return!Ft(r,!0)||/[-\d_]$/.test(n)?!1:{type:`link`,title:null,url:`mailto:`+t+`@`+n,children:[{type:`text`,value:t+`@`+n}]}}function Nt(e){let t=e.split(`.`);return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function Pt(e){let t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(`)`),i=at(e,`(`),a=at(e,`)`);for(;r!==-1&&i>a;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(`)`),a++;return[e,n]}function Ft(e,t){let n=e.input.charCodeAt(e.index-1);return(e.index===0||U(n)||Ie(n))&&(!t||n!==47)}function It(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}Gt.peek=Wt;function Lt(){this.buffer()}function G(e){this.enter({type:`footnoteReference`,identifier:``,label:``},e)}function Rt(){this.buffer()}function zt(e){this.enter({type:`footnoteDefinition`,identifier:``,label:``,children:[]},e)}function Bt(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=It(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Vt(e){this.exit(e)}function Ht(e){let t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=It(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Ut(e){this.exit(e)}function Wt(){return`[`}function Gt(e,t,n,r){let i=n.createTracker(r),a=i.move(`[^`),o=n.enter(`footnoteReference`),s=n.enter(`reference`);return a+=i.move(n.safe(n.associationId(e),{after:`]`,before:a})),s(),o(),a+=i.move(`]`),a}function Kt(){return{enter:{gfmFootnoteCallString:Lt,gfmFootnoteCall:G,gfmFootnoteDefinitionLabelString:Rt,gfmFootnoteDefinition:zt},exit:{gfmFootnoteCallString:Bt,gfmFootnoteCall:Vt,gfmFootnoteDefinitionLabelString:Ht,gfmFootnoteDefinition:Ut}}}function qt(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:Gt},unsafe:[{character:`[`,inConstruct:[`label`,`phrasing`,`reference`]}]};function n(e,n,r,i){let a=r.createTracker(i),o=a.move(`[^`),s=r.enter(`footnoteDefinition`),c=r.enter(`label`);return o+=a.move(r.safe(r.associationId(e),{before:o,after:`]`})),c(),o+=a.move(`]:`),e.children&&e.children.length>0&&(a.shift(4),o+=a.move((t?`
|
|
@@ -192,7 +192,7 @@ 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`},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`,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,rh.EDITOR_CONFIG,rh.IDEA_GITIGNORE,rh.IDEA_PROJECT_XML,rh.IDEA_CODE_STYLE_CONFIG_XML,rh.VSCODE_SETTINGS,rh.VSCODE_EXTENSIONS,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.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.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){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=th(a,bh(e,s,o),r);return mh.set(c,u),u}function Sh(e,t,n){let r=xh(e,t,n);return u.join(gh(e),...r.split(/[\\/]+/))}function Ch(e,t){let n=new Set([Sh(e,lh)]);for(let r of ph)n.add(Sh(e,r,t));return[...n]}function wh(e,t,n,r,i){let a=Sh(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 Th=`.aindex`,Eh=`.tnmsc.json`,Dh=/^[A-Za-z]:[\\/]/u,Oh=/%([^%]+)%/gu,kh=/\$\{([A-Za-z_]\w*)\}/gu,Ah=/\$([A-Za-z_]\w*)/gu;function jh(e){return e!=null&&`effectiveHomeDir`in e&&`expandedEnv`in e}function Mh(e){return e?.fs??i}function Nh(e){return e?.platform??c.platform}function Ph(e){return e?.release??g.release()}function Fh(e){return e?.homedir??g.homedir()}function Ih(e){return e?.env??c.env}function Lh(e){return e?.windowsUsersRoot??`/mnt/c/Users`}function Rh(e){return u.posix.normalize(e.replaceAll(`\\`,`/`))}function zh(e,t){let n=Rh(e),r=Rh(t);return n===r?!0:n.startsWith(`${r}/`)}function Bh(e,t){if(typeof e!=`string`)return;let n=e.trim();if(n.length===0)return;let r=[Xh(n),Rh(n)];for(let e of r)if(e!=null&&zh(e,t))return Rh(e)}function Vh(e){let t=Ih(e),n=Rh(Lh(e)),r=t.HOMEDRIVE,i=t.HOMEPATH,a=[Bh(t.USERPROFILE,n),typeof r==`string`&&r.length>0&&typeof i==`string`&&i.length>0?Bh(`${r}${i}`,n):void 0,Bh(t.HOME,n)];return[...new Set(a.filter(e=>e!=null))]}function Hh(e){let t=Rh(e);return u.posix.dirname(u.posix.dirname(t))}function Uh(e,t){let n=Vh(t);if(n.length<=0)return e.length===1?e[0]:void 0;for(let t of n){let n=e.find(e=>Hh(e)===t);if(n!=null)return n}}function Wh(e,t){try{return e.statSync(t).isDirectory()}catch{return!1}}function Gh(e,t){try{return e.statSync(t).isFile()}catch{return!1}}function Kh(e){return e===`win32`?u.win32:u.posix}function qh(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 Jh(e,t){let n=(e,n)=>t[n]??e;return e.replaceAll(Oh,n).replaceAll(kh,n).replaceAll(Ah,n)}function Yh(e,t,n){if(e===`~`)return t;if(!(e.startsWith(`~/`)||e.startsWith(`~\\`)))return e;let r=Kh(n),i=n===`win32`?e.slice(2).replaceAll(`/`,`\\`):e.slice(2).replaceAll(`\\`,`/`);return r.resolve(t,i)}function Xh(e){if(!Dh.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 Zh(e,t){return t===`win32`?u.win32.normalize(e.replaceAll(`/`,`\\`)):u.posix.normalize(e)}function Qh(e){if(Nh(e)!==`linux`)return!1;let t=Ih(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:Ph(e).toLowerCase().includes(`microsoft`)}function $h(e){let t=Mh(e),n=Lh(e);if(!Wh(t,n))return[];try{let e=t.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>u.join(n,e.name,Th,Eh)).filter(e=>t.existsSync(e)&&Gh(t,e));return e.sort((e,t)=>e.localeCompare(t)),e}catch{return[]}}function eg(e){let t=Nh(e),n=Fh(e),r=Qh(e),i=r?$h(e):[],a=r?Uh(i,e):void 0,o=a==null?n:Hh(a);return{platform:t,isWsl:r,nativeHomeDir:n,effectiveHomeDir:o,globalConfigCandidates:i,...a!=null&&{selectedGlobalConfigPath:a},...a!=null&&{wslHostHomeDir:o},windowsUsersRoot:Lh(e),expandedEnv:qh(Ih(e),n,o)}}function tg(e){return eg(e).effectiveHomeDir}function ng(e){let t=eg(e);return t.selectedGlobalConfigPath==null?u.join(t.effectiveHomeDir,Th,Eh):t.selectedGlobalConfigPath}function rg(e){let t=eg(e);if(!t.isWsl||t.selectedGlobalConfigPath!=null)return ng(e);let n=`"${t.windowsUsersRoot}/*/${Th}/${Eh}"`;throw t.globalConfigCandidates.length===0?Error(`WSL host config file not found under ${n}.`):Vh(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 ig(e,t){let n=jh(t)?t:eg(t),r=Jh(e,n.expandedEnv);if(r=Yh(r,n.effectiveHomeDir,n.platform),!n.isWsl)return Zh(r,n.platform);let i=Xh(r);return i==null?(r.startsWith(n.effectiveHomeDir)||r.startsWith(`/mnt/`)||r.startsWith(`/`))&&(r=r.replaceAll(`\\`,`/`)):r=i,Zh(r,n.platform)}var ag=class extends Error{operation;violations;constructor(e,t){super(Rg(e,t)),this.name=`ProtectedDeletionGuardError`,this.operation=e,this.violations=t}};const og=[`skills`,`commands`,`subAgents`,`rules`,`app`,`ext`,`arch`],sg=[`globalPrompt`,`workspacePrompt`];function cg(e){let t=c.env.XDG_CONFIG_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.config`)}function lg(e){let t=c.env.XDG_DATA_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.local`,`share`)}function ug(e){let t=c.env.XDG_STATE_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.local`,`state`)}function dg(e){let t=c.env.XDG_CACHE_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.cache`)}function fg(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 pg(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?ig(e):e}function mg(e){return u.resolve(pg(e))}function hg(e){let t=u.normalize(mg(e));return c.platform===`win32`?t.toLowerCase():t}function gg(e){let{root:t}=u.parse(e);return e===t?e:e.endsWith(u.sep)?e.slice(0,-1):e}function _g(e,t){let n=gg(e),r=gg(t);return n===r?!0:n.startsWith(`${r}${u.sep}`)}function vg(e){let t=mg(e),n=new Set([hg(t)]);try{if(i.existsSync(t)){let e=i.realpathSync.native(t);n.add(hg(e))}}catch{}return[...n]}function yg(e,t,n,r,i=`path`){return{path:mg(e),protectionMode:t,reason:n,source:r,matcher:i}}function bg(e){let t=hg(e.path);return{...e,path:mg(e.path),comparisonKeys:vg(e.path),normalizedPath:t,specificity:gg(t).length}}function xg(e){let t=new Map;for(let n of e){let e=bg(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 Sg(e){return mg(e).replaceAll(`\\`,`/`)}function Cg(e){let t=[];for(let n of e){if(n.matcher!==`glob`){t.push(yg(n.path,n.protectionMode,n.reason,n.source));continue}let e=Um.default.sync(Sg(n.path),{onlyFiles:!1,dot:!0,absolute:!0,followSymbolicLinks:!1});for(let r of e)t.push(yg(r,n.protectionMode,n.reason,n.source))}return t}function wg(e,t,n){return n===`direct`?_g(t,e):_g(e,t)||_g(t,e)}function Tg(e,t){let n=mg(e);try{if(i.existsSync(n)&&i.lstatSync(n).isDirectory())return`recursive`}catch{}return t}function Eg(){let e=tg();return[yg(u.parse(e).root,`direct`,`built-in dangerous root path`,`built-in-dangerous-root`),yg(e,`direct`,`built-in dangerous home directory`,`built-in-dangerous-root`),yg(cg(e),`direct`,`built-in dangerous config directory`,`built-in-dangerous-root`),yg(lg(e),`direct`,`built-in dangerous data directory`,`built-in-dangerous-root`),yg(ug(e),`direct`,`built-in dangerous state directory`,`built-in-dangerous-root`),yg(dg(e),`direct`,`built-in dangerous cache directory`,`built-in-dangerous-root`),yg(u.join(e,`.aindex`),`direct`,`built-in global aindex directory`,`built-in-dangerous-root`),yg(u.join(e,`.aindex`,`.tnmsc.json`),`direct`,`built-in global config file`,`built-in-config`)]}function Dg(e,t,n){let r=[yg(e,`direct`,`workspace root`,`workspace-reserved`),yg(u.join(e,`aindex`),`direct`,`reserved workspace aindex root`,`workspace-reserved`),yg(u.join(e,`knowladge`),`direct`,`reserved workspace knowladge root`,`workspace-reserved`)];for(let e of t)r.push(yg(e,`direct`,`workspace project root`,`workspace-project-root`));return n&&r.push(yg(u.join(e,`aindex`,`dist`,`**`,`*.mdx`),`direct`,`reserved workspace aindex dist mdx files`,`workspace-reserved`,`glob`),yg(u.join(e,`aindex`,`app`,`**`,`*.mdx`),`direct`,`reserved workspace aindex app mdx files`,`workspace-reserved`,`glob`)),r}function Og(e){return[yg(e,`direct`,`resolved aindex root`,`aindex-root`)]}function kg(e,t){return Ch(e,t)}function Ag(e,t,n){let r=[];for(let n of og)r.push(yg(u.join(t,e.aindex[n].src),`recursive`,`configured aindex ${n} source directory`,`configured-aindex-source`));for(let n of sg)r.push(yg(u.join(t,e.aindex[n].src),`direct`,`configured aindex ${n} source file`,`configured-aindex-source`));for(let e of kg(t,n))r.push(yg(e,`direct`,`known aindex input config file`,`known-aindex-config`));return r}function jg(e){let t=[],n=new Set,r=(e,r,i,a)=>{if(e==null||e.length===0)return;let o=yg(e,r,i,a),s=`${o.protectionMode}:${hg(o.path)}`;n.has(s)||(n.add(s),t.push(o))},i=(e,t,n,i)=>{let a=fg(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,Tg(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.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 kg(e.aindexDir,{workspaceDir:e.workspace.directory.path}))r(t,`direct`,`known aindex input config file`,`known-aindex-config`);return t}function Mg(e){let t=[];for(let n of e.exactProtectedPaths??[])t.push(yg(n,`direct`,`legacy direct protected path`,`legacy-direct`));for(let n of e.subtreeProtectedPaths??[])t.push(yg(n,`recursive`,`legacy recursive protected path`,`legacy-recursive`));return t}function Ng(e={}){let t=e.includeReservedWorkspaceContentRoots??!0,n=xg(Cg([...Eg(),...Mg(e),...e.workspaceDir==null?[]:Dg(e.workspaceDir,e.projectRoots??[],t),...e.aindexDir==null?[]:Og(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 Pg(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(mg(e))}return[...t]}function Fg(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 Ig(e,t){let n=mg(e),r=vg(n),i;for(let e of t.compiledRules){let t=!1;for(let n of r){for(let r of e.comparisonKeys)if(wg(n,r,e.protectionMode)){i=Fg(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 Lg(e,t){let n=[],r=new Map;for(let i of e){let e=mg(i),a=Ig(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 Rg(e,t){let n=t.map(e=>e.targetPath).join(`, `);return`Protected deletion guard blocked ${e} for ${t.length} path(s): ${n}`}function zg(e,t,n){e.error(te(t,n))}var Bg=class{inputEffects=[];registeredScopes=[];name;dependsOn;_log;get log(){return this._log??=ye(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,modifiedFiles:t.modifiedFiles}),t.deletedFiles!=null&&t.deletedFiles.length>0&&this.log.debug({action:`inputEffect`,name:e.name,deletedFiles:t.deletedFiles});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 ag){zg(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(Yb.WORKSPACE)&&(n=n.replace(Yb.WORKSPACE,t)),n.startsWith(Yb.USER_HOME)?ig(n):u.normalize(ig(n))}resolveAindexPath(e,t){return u.join(t,e)}readAndParseMarkdown(e,t){return Cp(t.readFileSync(e,`utf8`))}};const Vg=/\r?\n/u;function Hg(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?Ug(r,u):void 0,_=Wg(r,m,h,g),v=u!=null&&d!=null&&g!=null?Gg(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 Ug(e,t){return e.split(Vg)[t-1]}function Wg(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 Gg(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 Kg(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 qg(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=Kg(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(`
|
|
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`},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`,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,rh.EDITOR_CONFIG,rh.IDEA_GITIGNORE,rh.IDEA_PROJECT_XML,rh.IDEA_CODE_STYLE_CONFIG_XML,rh.VSCODE_SETTINGS,rh.VSCODE_EXTENSIONS,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.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.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){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=th(a,bh(e,s,o),r);return mh.set(c,u),u}function Sh(e,t,n){let r=xh(e,t,n);return u.join(gh(e),...r.split(/[\\/]+/))}function Ch(e,t){let n=new Set([Sh(e,lh)]);for(let r of ph)n.add(Sh(e,r,t));return[...n]}function wh(e,t,n,r,i){let a=Sh(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 Th=`.aindex`,Eh=`.tnmsc.json`,Dh=/^[A-Za-z]:[\\/]/u,Oh=/%([^%]+)%/gu,kh=/\$\{([A-Za-z_]\w*)\}/gu,Ah=/\$([A-Za-z_]\w*)/gu;function jh(e){return e!=null&&`effectiveHomeDir`in e&&`expandedEnv`in e}function Mh(e){return e?.fs??i}function Nh(e){return e?.platform??c.platform}function Ph(e){return e?.release??g.release()}function Fh(e){return e?.homedir??g.homedir()}function Ih(e){return e?.env??c.env}function Lh(e){return e?.windowsUsersRoot??`/mnt/c/Users`}function Rh(e){return u.posix.normalize(e.replaceAll(`\\`,`/`))}function zh(e,t){let n=Rh(e),r=Rh(t);return n===r?!0:n.startsWith(`${r}/`)}function Bh(e,t){if(typeof e!=`string`)return;let n=e.trim();if(n.length===0)return;let r=[Xh(n),Rh(n)];for(let e of r)if(e!=null&&zh(e,t))return Rh(e)}function Vh(e){let t=Ih(e),n=Rh(Lh(e)),r=t.HOMEDRIVE,i=t.HOMEPATH,a=[Bh(t.USERPROFILE,n),typeof r==`string`&&r.length>0&&typeof i==`string`&&i.length>0?Bh(`${r}${i}`,n):void 0,Bh(t.HOME,n)];return[...new Set(a.filter(e=>e!=null))]}function Hh(e){let t=Rh(e);return u.posix.dirname(u.posix.dirname(t))}function Uh(e,t){let n=Vh(t);if(n.length<=0)return e.length===1?e[0]:void 0;for(let t of n){let n=e.find(e=>Hh(e)===t);if(n!=null)return n}}function Wh(e,t){try{return e.statSync(t).isDirectory()}catch{return!1}}function Gh(e,t){try{return e.statSync(t).isFile()}catch{return!1}}function Kh(e){return e===`win32`?u.win32:u.posix}function qh(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 Jh(e,t){let n=(e,n)=>t[n]??e;return e.replaceAll(Oh,n).replaceAll(kh,n).replaceAll(Ah,n)}function Yh(e,t,n){if(e===`~`)return t;if(!(e.startsWith(`~/`)||e.startsWith(`~\\`)))return e;let r=Kh(n),i=n===`win32`?e.slice(2).replaceAll(`/`,`\\`):e.slice(2).replaceAll(`\\`,`/`);return r.resolve(t,i)}function Xh(e){if(!Dh.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 Zh(e,t){return t===`win32`?u.win32.normalize(e.replaceAll(`/`,`\\`)):u.posix.normalize(e)}function Qh(e){if(Nh(e)!==`linux`)return!1;let t=Ih(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:Ph(e).toLowerCase().includes(`microsoft`)}function $h(e){let t=Mh(e),n=Lh(e);if(!Wh(t,n))return[];try{let e=t.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>u.join(n,e.name,Th,Eh)).filter(e=>t.existsSync(e)&&Gh(t,e));return e.sort((e,t)=>e.localeCompare(t)),e}catch{return[]}}function eg(e){let t=Nh(e),n=Fh(e),r=Qh(e),i=r?$h(e):[],a=r?Uh(i,e):void 0,o=a==null?n:Hh(a);return{platform:t,isWsl:r,nativeHomeDir:n,effectiveHomeDir:o,globalConfigCandidates:i,...a!=null&&{selectedGlobalConfigPath:a},...a!=null&&{wslHostHomeDir:o},windowsUsersRoot:Lh(e),expandedEnv:qh(Ih(e),n,o)}}function tg(e){return eg(e).effectiveHomeDir}function ng(e){let t=eg(e);return t.selectedGlobalConfigPath==null?u.join(t.effectiveHomeDir,Th,Eh):t.selectedGlobalConfigPath}function rg(e){let t=eg(e);if(!t.isWsl||t.selectedGlobalConfigPath!=null)return ng(e);let n=`"${t.windowsUsersRoot}/*/${Th}/${Eh}"`;throw t.globalConfigCandidates.length===0?Error(`WSL host config file not found under ${n}.`):Vh(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 ig(e,t){let n=jh(t)?t:eg(t),r=Jh(e,n.expandedEnv);if(r=Yh(r,n.effectiveHomeDir,n.platform),!n.isWsl)return Zh(r,n.platform);let i=Xh(r);return i==null?(r.startsWith(n.effectiveHomeDir)||r.startsWith(`/mnt/`)||r.startsWith(`/`))&&(r=r.replaceAll(`\\`,`/`)):r=i,Zh(r,n.platform)}var ag=class extends Error{operation;violations;constructor(e,t){super(Rg(e,t)),this.name=`ProtectedDeletionGuardError`,this.operation=e,this.violations=t}};const og=[`skills`,`commands`,`subAgents`,`rules`,`app`,`ext`,`arch`],sg=[`globalPrompt`,`workspacePrompt`];function cg(e){let t=c.env.XDG_CONFIG_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.config`)}function lg(e){let t=c.env.XDG_DATA_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.local`,`share`)}function ug(e){let t=c.env.XDG_STATE_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.local`,`state`)}function dg(e){let t=c.env.XDG_CACHE_HOME;return typeof t==`string`&&t.trim().length>0?t:u.join(e,`.cache`)}function fg(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 pg(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?ig(e):e}function mg(e){return u.resolve(pg(e))}function hg(e){let t=u.normalize(mg(e));return c.platform===`win32`?t.toLowerCase():t}function gg(e){let{root:t}=u.parse(e);return e===t?e:e.endsWith(u.sep)?e.slice(0,-1):e}function _g(e,t){let n=gg(e),r=gg(t);return n===r?!0:n.startsWith(`${r}${u.sep}`)}function vg(e){let t=mg(e),n=new Set([hg(t)]);try{if(i.existsSync(t)){let e=i.realpathSync.native(t);n.add(hg(e))}}catch{}return[...n]}function yg(e,t,n,r,i=`path`){return{path:mg(e),protectionMode:t,reason:n,source:r,matcher:i}}function bg(e){let t=hg(e.path);return{...e,path:mg(e.path),comparisonKeys:vg(e.path),normalizedPath:t,specificity:gg(t).length}}function xg(e){let t=new Map;for(let n of e){let e=bg(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 Sg(e){return mg(e).replaceAll(`\\`,`/`)}function Cg(e){let t=[];for(let n of e){if(n.matcher!==`glob`){t.push(yg(n.path,n.protectionMode,n.reason,n.source));continue}let e=Um.default.sync(Sg(n.path),{onlyFiles:!1,dot:!0,absolute:!0,followSymbolicLinks:!1});for(let r of e)t.push(yg(r,n.protectionMode,n.reason,n.source))}return t}function wg(e,t,n){return n===`direct`?_g(t,e):_g(e,t)||_g(t,e)}function Tg(e,t){let n=mg(e);try{if(i.existsSync(n)&&i.lstatSync(n).isDirectory())return`recursive`}catch{}return t}function Eg(){let e=tg();return[yg(u.parse(e).root,`direct`,`built-in dangerous root path`,`built-in-dangerous-root`),yg(e,`direct`,`built-in dangerous home directory`,`built-in-dangerous-root`),yg(cg(e),`direct`,`built-in dangerous config directory`,`built-in-dangerous-root`),yg(lg(e),`direct`,`built-in dangerous data directory`,`built-in-dangerous-root`),yg(ug(e),`direct`,`built-in dangerous state directory`,`built-in-dangerous-root`),yg(dg(e),`direct`,`built-in dangerous cache directory`,`built-in-dangerous-root`),yg(u.join(e,`.aindex`),`direct`,`built-in global aindex directory`,`built-in-dangerous-root`),yg(u.join(e,`.aindex`,`.tnmsc.json`),`direct`,`built-in global config file`,`built-in-config`)]}function Dg(e,t,n){let r=[yg(e,`direct`,`workspace root`,`workspace-reserved`),yg(u.join(e,`aindex`),`direct`,`reserved workspace aindex root`,`workspace-reserved`),yg(u.join(e,`knowladge`),`direct`,`reserved workspace knowladge root`,`workspace-reserved`)];for(let e of t)r.push(yg(e,`direct`,`workspace project root`,`workspace-project-root`));return n&&r.push(yg(u.join(e,`aindex`,`dist`,`**`,`*.mdx`),`direct`,`reserved workspace aindex dist mdx files`,`workspace-reserved`,`glob`),yg(u.join(e,`aindex`,`app`,`**`,`*.mdx`),`direct`,`reserved workspace aindex app mdx files`,`workspace-reserved`,`glob`)),r}function Og(e){return[yg(e,`direct`,`resolved aindex root`,`aindex-root`)]}function kg(e,t){return Ch(e,t)}function Ag(e,t,n){let r=[];for(let n of og)r.push(yg(u.join(t,e.aindex[n].src),`recursive`,`configured aindex ${n} source directory`,`configured-aindex-source`));for(let n of sg)r.push(yg(u.join(t,e.aindex[n].src),`direct`,`configured aindex ${n} source file`,`configured-aindex-source`));for(let e of kg(t,n))r.push(yg(e,`direct`,`known aindex input config file`,`known-aindex-config`));return r}function jg(e){let t=[],n=new Set,r=(e,r,i,a)=>{if(e==null||e.length===0)return;let o=yg(e,r,i,a),s=`${o.protectionMode}:${hg(o.path)}`;n.has(s)||(n.add(s),t.push(o))},i=(e,t,n,i)=>{let a=fg(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,Tg(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.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 kg(e.aindexDir,{workspaceDir:e.workspace.directory.path}))r(t,`direct`,`known aindex input config file`,`known-aindex-config`);return t}function Mg(e){let t=[];for(let n of e.exactProtectedPaths??[])t.push(yg(n,`direct`,`legacy direct protected path`,`legacy-direct`));for(let n of e.subtreeProtectedPaths??[])t.push(yg(n,`recursive`,`legacy recursive protected path`,`legacy-recursive`));return t}function Ng(e={}){let t=e.includeReservedWorkspaceContentRoots??!0,n=xg(Cg([...Eg(),...Mg(e),...e.workspaceDir==null?[]:Dg(e.workspaceDir,e.projectRoots??[],t),...e.aindexDir==null?[]:Og(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 Pg(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(mg(e))}return[...t]}function Fg(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 Ig(e,t){let n=mg(e),r=vg(n),i;for(let e of t.compiledRules){let t=!1;for(let n of r){for(let r of e.comparisonKeys)if(wg(n,r,e.protectionMode)){i=Fg(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 Lg(e,t){let n=[],r=new Map;for(let i of e){let e=mg(i),a=Ig(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 Rg(e,t){let n=t.map(e=>e.targetPath).join(`, `);return`Protected deletion guard blocked ${e} for ${t.length} path(s): ${n}`}function zg(e,t,n){e.error(te(t,n))}var Bg=class{inputEffects=[];registeredScopes=[];name;dependsOn;_log;get log(){return this._log??=ye(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,modifiedFiles:t.modifiedFiles}),t.deletedFiles!=null&&t.deletedFiles.length>0&&this.log.debug({action:`inputEffect`,name:e.name,deletedFiles:t.deletedFiles});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 ag){zg(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(lx.WORKSPACE)&&(n=n.replace(lx.WORKSPACE,t)),n.startsWith(lx.USER_HOME)?ig(n):u.normalize(ig(n))}resolveAindexPath(e,t){return u.join(t,e)}readAndParseMarkdown(e,t){return Cp(t.readFileSync(e,`utf8`))}};const Vg=/\r?\n/u;function Hg(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?Ug(r,u):void 0,_=Wg(r,m,h,g),v=u!=null&&d!=null&&g!=null?Gg(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 Ug(e,t){return e.split(Vg)[t-1]}function Wg(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 Gg(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 Kg(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 qg(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=Kg(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
196
|
`)}function Jg(e,t={}){return e instanceof Yg||e instanceof Error?e.message:qg(t.summary??`Compiler diagnostic`,e)}var Yg=class extends Error{diagnostic;filePath;line;column;endLine;endColumn;snippet;sourceLine;codeFrame;phase;nodeType;constructor(e,t,n){super(qg(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 Xg(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 Zg=class extends Yg{expression;constructor(e,t){super(`ScopeError`,e,t),t.expression!=null&&(this.expression=t.expression)}},Qg=class extends Zg{variableName;constructor(e,t,n={}){let r=Hg({...n,expression:t,phase:n.phase??`expression-evaluation`,hint:n.hint??Xg(n.nodeType)}),i=`Undefined variable "${e}" in expression "${t??``}"`;super(i,r),this.name=`UndefinedVariableError`,this.variableName=e}},$g=class extends Zg{namespace;constructor(e,t,n={}){let r=Hg({...n,expression:t,phase:n.phase??`expression-evaluation`,hint:n.hint??Xg(n.nodeType)}),i=`Undefined namespace "${e}" in expression "${t??``}"`;super(i,r),this.name=`UndefinedNamespaceError`,this.namespace=e}},e_=class extends Yg{exportName;constructor(e,t,n={}){let r=Hg({...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 t_=new Map;function n_(e,t){t_.set(e,t)}function r_(){return new Map(t_)}function i_(e){return t_.has(e)}const a_=/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/iu,o_=/(\w+) is not defined/u;function s_(e,t,n){let r=e.trim(),i=c_(n,e);return r===``?``:a_.test(r)?l_(r,t,i):u_(r,t,i)}function c_(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 l_(e,t,n){let r=e.split(`.`),i=r[0];if(i==null||!(i in t))throw new $g(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 Qg(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 Qg(i,e,n);a=o[i]}return d_(a)}function u_(e,t,n){let r=Object.keys(t),i=r.map(e=>t[e]);try{return d_(Function(...r,`return (${e})`)(...i))}catch(t){let r=t instanceof Error?t.message:String(t);if(r.includes(`is not defined`)){let t=o_.exec(r);if(t?.[1]!=null)throw new $g(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
197
|
`))}}function d_(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 f_(e,t){return e===null?!1:t.components.has(e)||i_(e)}async function p_(e){return async(t,n)=>(await e({type:`root`,children:t},n)).children}async function m_(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 p_(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 h_=/language-(\w+)/u;function g_(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 __(e,t){let n=e.name?.toLowerCase();if(n==null)return null;switch(n){case`pre`:return b_(e,t);case`a`:return x_(e,t);case`strong`:case`b`:return S_(e,t);case`em`:case`i`:return C_(e,t);case`img`:return w_(e,t);case`blockquote`:return T_(e,t);default:return null}}function v_(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`?s_(r.value.value,n.scope,g_(n,`mdxJsxAttributeValueExpression`,r)):r.value===null?``:null}function y_(e,t){let n=``;for(let r of e.children){if(r.type===`text`){n+=r.value;continue}if(r.type===`mdxTextExpression`){n+=s_(r.value,t.scope,g_(t,`mdxTextExpression`,r));continue}(r.type===`mdxJsxFlowElement`||r.type===`mdxJsxTextElement`)&&(n+=y_(r,t))}return n}function b_(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=v_(n,`className`,t)??``,i=h_.exec(r)?.[1],a=y_(n,t);return[{type:`code`,lang:i??null,value:a.trim()}]}function x_(e,t){let n=v_(e,`href`,t);if(n==null||n===``)return null;let r=y_(e,t);return[{type:`paragraph`,children:[{type:`link`,url:n,title:v_(e,`title`,t)??null,children:[{type:`text`,value:r}]}]}]}function S_(e,t){let n={type:`strong`,children:[{type:`text`,value:y_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function C_(e,t){let n={type:`emphasis`,children:[{type:`text`,value:y_(e,t)}]};return e.type,[{type:`paragraph`,children:[n]}]}function w_(e,t){let n=v_(e,`src`,t);if(n==null||n===``)return null;let r={type:`image`,url:n,alt:v_(e,`alt`,t)??``,title:v_(e,`title`,t)??null};return e.type,[{type:`paragraph`,children:[r]}]}function T_(e,t){return[{type:`blockquote`,children:[{type:`paragraph`,children:[{type:`text`,value:y_(e,t)}]}]}]}const E_=/^-?\d+(?:\.\d+)?$/u;function D_(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 O_(e){return e==null?!1:JSON.stringify(e).includes(`"JSX`)}async function k_(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`?A_(i.expression,t,n,e):[]}async function A_(e,t,n,r){return e.type===`JSXElement`?I_(e,t,n):e.type===`JSXFragment`?L_(e,t,n,r):e.type===`LogicalExpression`?j_(e,t,n,r):e.type===`ConditionalExpression`?M_(e,t,n,r):e.type===`SequenceExpression`?N_(e,t,n,r):e.type===`ArrayExpression`?P_(e,t,n,r):K_(e,t,r)}async function j_(e,t,n,r){let i=await F_(e.left,t,n,r);return e.operator===`&&`?W_(i)?A_(e.right,t,n,r):[]:e.operator===`||`?W_(i)?U_(e.left)?A_(e.left,t,n,r):G_(i):A_(e.right,t,n,r):e.operator===`??`?i==null?A_(e.right,t,n,r):U_(e.left)?A_(e.left,t,n,r):G_(i):[]}async function M_(e,t,n,r){return W_(await F_(e.test,t,n,r))?A_(e.consequent,t,n,r):A_(e.alternate,t,n,r)}async function N_(e,t,n,r){let i=[];for(let a of e.expressions){let e=await A_(a,t,n,r);i.push(...e)}return i}async function P_(e,t,n,r){let i=[];for(let a of e.elements)if(a!=null)if(a.type===`SpreadElement`){let e=await A_(a.argument,t,n,r);i.push(...e)}else{let e=await A_(a,t,n,r);i.push(...e)}return i}async function F_(e,t,n,r){if(U_(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 F_(e.argument,t,n,r);return e.operator===`!`?!W_(i):e.operator===`-`?-i:e.operator===`+`?+i:e.operator===`typeof`?typeof i:void 0}if(e.type===`BinaryExpression`){let i=await F_(e.left,t,n,r),a=await F_(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 F_(e.left,t,n,r);return e.operator===`&&`?W_(i)?F_(e.right,t,n,r):i:e.operator===`||`?W_(i)?i:F_(e.right,t,n,r):e.operator===`??`?i??F_(e.right,t,n,r):void 0}if(e.type===`MemberExpression`){let i=await F_(e.object,t,n,r);if(i==null)return;if(e.computed)return i[await F_(e.property,t,n,r)];let{name:a}=e.property;return i[a]}if(e.type===`ConditionalExpression`)return W_(await F_(e.test,t,n,r))?F_(e.consequent,t,n,r):F_(e.alternate,t,n,r);let i=H_(e);if(i!==``)try{let e=s_(i,t.scope,D_(t,r));return e===`true`?!0:e===`false`?!1:e===`null`?null:e===`undefined`||e===``?void 0:E_.test(e)?Number(e):e}catch{return}}async function I_(e,t,n){let r=z_(e,t);if(r.name!=null&&f_(r.name,t)){let{processAst:e}=await Promise.resolve().then(()=>q_);return m_(r,t,e)}return __(r,t)??(r.children.length>0?n(r.children,t):[])}async function L_(e,t,n,r){let i=[];for(let a of e.children){let e=await R_(a,t,n,r);i.push(...e)}return i}async function R_(e,t,n,r){if(e.type===`JSXElement`)return I_(e,t,n);if(e.type===`JSXFragment`)return L_(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`?[]:A_(e.expression,t,n,r):e.type===`JSXSpreadChild`?A_(e.expression,t,n,r):[]}function z_(e,t){let n=e.openingElement,r=null;n.name.type===`JSXIdentifier`?{name:r}=n.name:n.name.type===`JSXMemberExpression`?r=B_(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:H_(e.value.expression)}),i.push({type:`mdxJsxAttribute`,name:t,value:n})}else e.type===`JSXSpreadAttribute`&&i.push({type:`mdxJsxExpressionAttribute`,value:`...${H_(e.argument)}`});let a=[];for(let n of e.children){let e=V_(n,t);e!=null&&a.push(...e)}return{type:`mdxJsxFlowElement`,name:r,attributes:i,children:a}}function B_(e){return e.object.type===`JSXIdentifier`?`${e.object.name}.${e.property.name}`:`${B_(e.object)}.${e.property.name}`}function V_(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[z_(e,t)];if(e.type===`JSXFragment`){let n=[];for(let r of e.children){let e=V_(r,t);e!=null&&n.push(...e)}return n}return e.type===`JSXExpressionContainer`?e.expression.type===`JSXEmptyExpression`?null:[{type:`paragraph`,children:[{type:`text`,value:H_(e.expression)}]}]:e.type===`JSXSpreadChild`?[{type:`paragraph`,children:[{type:`text`,value:`...${H_(e.expression)}`}]}]:null}function H_(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=H_(e.object);return e.computed?`${t}[${H_(e.property)}]`:`${t}.${e.property.name}`}if(e.type===`CallExpression`)return`${H_(e.callee)}(${e.arguments.map(e=>H_(e)).join(`, `)})`;if(e.type===`BinaryExpression`||e.type===`LogicalExpression`){let t=H_(e.left),n=H_(e.right);return`(${t} ${e.operator} ${n})`}if(e.type===`UnaryExpression`){let t=H_(e.argument);return`${e.operator}${t}`}if(e.type===`ConditionalExpression`)return`(${H_(e.test)} ? ${H_(e.consequent)} : ${H_(e.alternate)})`;if(e.type===`ArrayExpression`)return`[${e.elements.filter(e=>e!=null&&e.type!==`SpreadElement`).map(e=>H_(e)).join(`, `)}]`;if(e.type===`ObjectExpression`)return`{${e.properties.filter(e=>e.type===`Property`).map(e=>`${e.key.type===`Identifier`?e.key.name:H_(e.key)}: ${H_(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+=`\${${H_(e.expressions[n])}}`);return t+="`",t}return e.type===`SpreadElement`?`...${H_(e.argument)}`:``}function U_(e){return e.type===`JSXElement`||e.type===`JSXFragment`}function W_(e){return!!e}function G_(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 K_(e,t,n){let r=H_(e);if(r===``)return[];try{return G_(s_(r,t.scope,D_(t,n)))}catch{return[]}}var q_=Ee({processAst:()=>Z_});const J_=/\.\w+$/u;function Y_(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 X_(e){if(!(e.includes(`/`)&&J_.test(e)))return e;let t=e.lastIndexOf(`/`);return e.slice(t+1)}async function Z_(e,t){return Q_(e,t)}async function Q_(e,t){let n=[];for(let r of e.children){let e=await $_(r,t);n.push(...e)}return{type:`root`,children:n}}async function $_(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(O_(r))return k_(n,t,async(e,t)=>(await Z_({type:`root`,children:e},t)).children);let a=s_(n.value,t.scope,Y_(t,n,`mdxFlowExpression`));return a===``?[]:[{type:`paragraph`,children:[{type:`text`,value:a}]}]}if(e.type===`mdxJsxFlowElement`)return ev(e,t);if(e.type===`link`){let n=e,r=(await tv(n.children,t)).map(e=>e.type===`text`?{...e,value:X_(e.value)}:e);return[{...n,children:r}]}if(!(`children`in e&&Array.isArray(e.children)))return[e];let n=await tv(e.children,t);return[{...e,children:n}]}async function ev(e,t){return e.name!=null&&f_(e.name,t)?m_(e,t,Z_):__(e,t)??[]}async function tv(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(O_(i)){let r=await k_(e,t,async(e,t)=>(await Z_({type:`root`,children:e},t)).children);for(let e of r)n.push(e);continue}let o=s_(e.value,t.scope,Y_(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:s_(e.value,t.scope,Y_(t,e,`mdxTextExpression`))};n.push(a);continue}if(r.type===`mdxJsxTextElement`){let e=r;if(e.name!=null&&f_(e.name,t)){let r=await m_(e,t,Z_);for(let e of r)e.type===`paragraph`&&`children`in e?n.push(...e.children):n.push(e);continue}let i=__(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 tv(r.children,t);if(r.type===`link`){let t=e.map(e=>e.type===`text`?{...e,value:X_(e.value)}:e);n.push({...r,children:t});continue}n.push({...r,children:e});continue}n.push(r)}return n}const nv=/^export\s+default\s+/u,rv=/export\s+const\s+(\w+)\s*=\s*/gu,iv=/^-?\d+(?:\.\d+)?$/u,av=/^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/iu,ov=/\s/u,sv=/[\w$]/u,cv=/^[\w$]+$/u;function lv(e,t={}){let n={},{yamlFrontMatter:r,scope:i,filePath:a,sourceText:o}=t;for(let t of e){let e=uv(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 uv(e,t,n={}){let r={},{filePath:i,sourceText:a}=n,o=e.value.trim(),s=nv.exec(o);if(s!=null){let n=s[0].length,c=dv(o,n);if(c!=null)try{let e=fv(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 e_(`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=rv.exec(o);for(;c!==null;){let n=c[1];if(n==null){c=rv.exec(o);continue}let s=dv(o,c.index+c[0].length);if(s==null){c=rv.exec(o);continue}try{let e=fv(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 e_(`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=rv.exec(o)}return r}function dv(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
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 fv(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(iv.test(r))return Number(r);if(r.startsWith(`"`)&&r.endsWith(`"`)||r.startsWith(`'`)&&r.endsWith(`'`))return pv(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 pv(e)}if(r.startsWith(`[`)&&r.endsWith(`]`))return hv(r,t,n);if(r.startsWith(`{`)&&r.endsWith(`}`))return gv(r,t,n);if(av.test(r))return mv(r,t,n);let i=n==null?``:` in file "${n}"`;throw Error(`Expression "${r}" cannot be statically evaluated${i}`)}function pv(e){return e.replaceAll(`\\n`,`
|
|
@@ -220,28 +220,29 @@ t.exports=r;let n=om();function r(e,t){let r,i,a,o=!0;Array.isArray(e)?(r=[],i=e
|
|
|
220
220
|
`:n+=`
|
|
221
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 Ty(e){if(typeof e==`string`)return e.includes(`
|
|
222
222
|
`)||e.includes(`\r`)?wy(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 Ey(e){if(e==null)throw TypeError(`TOML inline value cannot be null or undefined`);if(vy(e))return Ty(e);if(Array.isArray(e)){if(yy(e))throw TypeError(`TOML inline arrays of tables are not supported`);let t=[],n=e;for(let e of n)t.push(Ey(e));return`[${t.join(`, `)}]`}let t=[];for(let[n,r]of Object.entries(e))t.push(`${Sy(n)} = ${Ey(r)}`);return`{ ${t.join(`, `)} }`}function Dy(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 Oy(e,t){let n=Dy(Object.entries(e),t),r=[],i=[],a=[];for(let[e,t]of n)if(t!=null){if(Array.isArray(t)){if(yy(t)){a.push([e,t]);continue}r.push([e,t]);continue}if(_y(t)){i.push([e,t]);continue}r.push([e,t])}return{scalarEntries:r,tableEntries:i,arrayTableEntries:a}}function ky(e,t,n,r=!0){let i=[],{scalarEntries:a,tableEntries:o,arrayTableEntries:s}=Oy(t,n?.fieldOrder);r&&e.length>0&&i.push(`[${Cy(e)}]`);for(let[e,t]of a)i.push(`${Sy(e)} = ${Ey(t)}`);for(let[t,r]of o)i.length>0&&i.push(``),i.push(...ky([...e,t],r,n));for(let[t,r]of s)for(let a of r){i.length>0&&i.push(``),i.push(`[[${Cy([...e,t])}]]`);let r=ky([...e,t],a,n,!1);i.push(...r)}return i}function Ay(e,t){let n=by(e);if(!_y(n))throw TypeError(`TOML document root must be an object`);return ky([],n,t).join(`
|
|
223
|
-
`)}function jy(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,Ay(l,{...s!=null&&{fieldOrder:s}})}var My=class{type;name;_log;get log(){return this._log??=ye(this.name),this._log}dependsOn;constructor(e,t,n){this.name=e,this.type=t,n!=null&&(this.dependsOn=n)}};function Ny(e,t){return e==null&&t==null?[]:[...new Set([...e??[],...t??[]])]}function Py(e,t){return e==null||t.length===0?!0:typeof e==`string`?t.includes(e):e.some(e=>t.includes(e))}function Fy(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 Iy(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 Ly(){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(Iy(e))return e}catch{}}catch{}}const{resolveEffectiveIncludeSeries:Ry,matchesSeries:zy,resolveSubSeries:By}=Ly()??{resolveEffectiveIncludeSeries:Ny,matchesSeries:Py,resolveSubSeries:Fy};function $(e,t,n){let r=Ry(t?.includeSeries,t?.[n]?.includeSeries);return e.filter(e=>zy(e.seriName,r))}function Vy(e){let t=e.replaceAll(/\.\/+/g,``);return t=t.replaceAll(/\/+$/g,``),t}function Hy(e,t){return t.startsWith(`**/`)?`${e}/${t}`:t.startsWith(`*`)?`${e}/**/${t}`:`${e}/${t}`}function Uy(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 Wy(e,t){let n=By(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=Vy(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}=Uy(r,i);e!=null&&n.push(r);for(let r of t){if(r===e)continue;let t=Hy(r,a);n.includes(t)||n.push(t)}}return{...e,globs:n}})}function Gy(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 Ky(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 qy={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 Jy=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}({}),Yy=function(e){return e.Win=`win`,e.Mac=`mac`,e.Linux=`linux`,e.Unknown=`unknown`,e}({});var Xy=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:tg(),tmpdir:g.tmpdir(),type:g.type(),release:g.release(),shellKind:this.detectShellKind(),kind:this.detectOsKind(e)}}detectOsKind(e){switch(e){case`win32`:return Yy.Win;case`darwin`:return Yy.Mac;case`linux`:case`freebsd`:case`openbsd`:case`sunos`:case`aix`:return Yy.Linux;default:return Yy.Unknown}}detectShellKind(){let e=(c.env.SHELL??c.env.ComSpec??``).toLowerCase();return e.includes(`bash`)?Jy.Bash:e.includes(`zsh`)?Jy.Zsh:e.includes(`fish`)?Jy.Fish:e.includes(`pwsh`)?Jy.Pwsh:e.includes(`powershell`)?Jy.PowerShell:e.includes(`cmd`)?Jy.Cmd:e.endsWith(`/sh`)?Jy.Sh:Jy.Unknown}collectEnvContext(){return{...c.env}}collectProfile(){return this.userConfig?.profile==null?{}:this.userConfig.profile}collectToolReferences(){let e={...qy.default};return this.toolPreset===`claudeCode`?{...e,...qy.claudeCode}:this.toolPreset===`kiro`?{...e,...qy.kiro}:e}createMdComponent(){let e=(e=>e.when===!1?null:e.children);return e.Line=e=>e.when===!1?null:e.children,e}};let Zy=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 Qy=class{registrations=[];globalScope=null;setGlobalScope(e){this.globalScope=e}getGlobalScope(){return this.globalScope}register(e,t,n=Zy.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}};function $y(e){return e.replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/gu,``)}function eb(e){let t=$y(e);return t.length===0?``:t.split(`/`).filter(e=>e.length>0).join(`-`)}function tb(e){let t=$y(e),n=t.split(`/`).filter(e=>e.length>0),r=n.at(-1)??t,i=n.slice(0,-1),a=eb(t),o=i.length>0?i.join(`-`):void 0;return{...o!=null&&{agentPrefix:o},agentName:r,canonicalName:a.length>0?a:r}}function nb(e){return e.skillName.trim().length>0?e.skillName:e.dir.getDirectoryName()}function rb(e){return e.canonicalName.trim().length>0?e.canonicalName:eb(e.agentPrefix!=null&&e.agentPrefix.length>0?`${e.agentPrefix}-${e.agentName}`:e.agentName)}const ib=[`project`,`global`];function ab(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 ob(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=ib}=e,s=ab(t),c=ab(n),l=new Set(ab(r)),u=(s.length>0?s:c).filter(e=>l.has(e));if(u.length===0)return[];let d=ob(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=v.object({src:v.string(),dist:v.string()}),lb=v.object({dir:v.string().default(`aindex`),skills:cb,commands:cb,subAgents:cb,rules:cb,globalPrompt:cb,workspacePrompt:cb,app:cb,ext:cb,arch:cb}),ub=v.object({includeSeriesPrefix:v.boolean().optional(),seriesSeparator:v.string().optional()}),db=v.object({includeSeriesPrefix:v.boolean().optional(),pluginOverrides:v.record(v.string(),ub).optional()}),fb=v.enum([`project`,`global`]),pb=v.union([fb,v.array(fb).min(1)]),mb=v.object({prompt:pb.optional(),rules:pb.optional(),commands:pb.optional(),subagents:pb.optional(),skills:pb.optional(),mcp:pb.optional()}),hb=v.object({plugins:v.record(v.string(),mb).optional()}),gb=v.object({blankLineAfter:v.boolean().optional()}),_b=v.enum([`direct`,`recursive`]),vb=v.enum([`path`,`glob`]),yb=v.object({path:v.string(),protectionMode:_b,matcher:vb.optional(),reason:v.string().optional()}),bb=v.object({rules:v.array(yb).optional()}),xb=v.union([v.string(),v.array(v.string()).min(1)]),Sb=v.object({instances:xb.optional()}),Cb=v.object({wsl2:Sb.optional()}),wb=v.object({name:v.string().optional(),username:v.string().optional(),gender:v.string().optional(),birthday:v.string().optional()}).catchall(v.unknown()),Tb=v.object({version:v.string().optional(),workspaceDir:v.string().optional(),aindex:lb.optional(),logLevel:v.enum([`trace`,`debug`,`info`,`warn`,`error`]).optional(),commandSeriesOptions:db.optional(),outputScopes:hb.optional(),frontMatter:gb.optional(),cleanupProtection:bb.optional(),windows:Cb.optional(),profile:wb.optional()}),Eb=v.object({names:v.array(v.string()).optional()}),Db=v.object({includeSeries:v.array(v.string()).optional(),subSeries:v.record(v.string(),v.array(v.string())).optional()});v.object({mcp:Eb.optional(),includeSeries:v.array(v.string()).optional(),subSeries:v.record(v.string(),v.array(v.string())).optional(),rules:Db.optional(),skills:Db.optional(),subAgents:Db.optional(),commands:Db.optional()}),v.object({});function Ob(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 kb(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 Ab(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=Ob(e.scope,t);return r.push(...a.errors),{valid:r.length===0,errors:r,warnings:i}}function jb(e,t){let n=kb(e,{requiredFields:[],optionalDefaults:{},filePath:t}),r=Ob(e.scope,t);return{valid:n.valid&&r.valid,errors:[...n.errors,...r.errors],warnings:n.warnings}}function Mb(e,t){let n=kb(e,{requiredFields:[`description`],optionalDefaults:{},filePath:t}),r=Ob(e.scope,t);return{valid:n.valid&&r.valid,errors:[...n.errors,...r.errors],warnings:n.warnings}}function Nb(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=Ob(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 Pb(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.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 Fb={Readme:{src:`rdm.mdx`,out:`README.md`},CodeOfConduct:{src:`coc.mdx`,out:`CODE_OF_CONDUCT.md`},Security:{src:`security.mdx`,out:`SECURITY.md`}},Ib=[`prompt`,`rules`,`commands`,`subagents`,`skills`,`mcp`];function Lb(e){return _.isBuffer(e)}function Rb(e){if(typeof e==`string`)return[e];let t=[];for(let n of e)t.includes(n)||t.push(n);return t}function zb(e,t){return t?.outputScopes?.plugins?.[e]}function Bb(e){for(let t of Ib){let n=e.outputCapabilities[t];if(n!=null&&n.scopes.length===0)throw Error(`Plugin ${e.name} declares empty scopes for topic "${t}"`)}}function Vb(e,t){let n=zb(e.name,t);if(n!=null)for(let t of Ib){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=Rb(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 Hb(e,t){for(let n of e)Bb(n),Vb(n,t)}async function Ub(e,t){Hb(e,t.pluginOptions);let n=await Promise.all(e.map(async e=>[e,await e.declareOutputFiles(t)]));return new Map(n)}async function Wb(e,t,n){let r=new Map,a=n??await Ub(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}`);if(r.symlinkTarget!=null){i.existsSync(r.path)&&i.rmSync(r.path,{force:!0,recursive:!1}),i.symlinkSync(r.symlinkTarget,r.path,`file`),o.push({path:r.path,success:!0});continue}let a=await n.convertContent(r,t);Lb(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 Gb(e,t,n){let r=[],i=[],a=[],o=[],s=n==null?Array.from(await Ub(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 Kb=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}},qb=class extends Error{cyclePath;constructor(e){super(`Circular dependency detected: ${e.join(` -> `)}`),this.name=`CircularDependencyError`,this.cyclePath=[...e]}},Jb=class extends My{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 Ib){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 tg()}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 jy(e)}extractGlobalMemoryContent(e){return e.collectedOutputContext.globalMemory?.content}combineGlobalWithContent(e,t,n){let{separator:r=`
|
|
223
|
+
`)}function jy(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,Ay(l,{...s!=null&&{fieldOrder:s}})}var My=class{type;name;_log;get log(){return this._log??=ye(this.name),this._log}dependsOn;constructor(e,t,n){this.name=e,this.type=t,n!=null&&(this.dependsOn=n)}};function Ny(e,t){return e==null&&t==null?[]:[...new Set([...e??[],...t??[]])]}function Py(e,t){return e==null||t.length===0?!0:typeof e==`string`?t.includes(e):e.some(e=>t.includes(e))}function Fy(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 Iy(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 Ly(){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(Iy(e))return e}catch{}}catch{}}const{resolveEffectiveIncludeSeries:Ry,matchesSeries:zy,resolveSubSeries:By}=Ly()??{resolveEffectiveIncludeSeries:Ny,matchesSeries:Py,resolveSubSeries:Fy};function $(e,t,n){let r=Ry(t?.includeSeries,t?.[n]?.includeSeries);return e.filter(e=>zy(e.seriName,r))}function Vy(e){let t=e.replaceAll(/\.\/+/g,``);return t=t.replaceAll(/\/+$/g,``),t}function Hy(e,t){return t.startsWith(`**/`)?`${e}/${t}`:t.startsWith(`*`)?`${e}/**/${t}`:`${e}/${t}`}function Uy(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 Wy(e,t){let n=By(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=Vy(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}=Uy(r,i);e!=null&&n.push(r);for(let r of t){if(r===e)continue;let t=Hy(r,a);n.includes(t)||n.push(t)}}return{...e,globs:n}})}function Gy(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 Ky(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 qy={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 Jy=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}({}),Yy=function(e){return e.Win=`win`,e.Mac=`mac`,e.Linux=`linux`,e.Unknown=`unknown`,e}({});var Xy=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:tg(),tmpdir:g.tmpdir(),type:g.type(),release:g.release(),shellKind:this.detectShellKind(),kind:this.detectOsKind(e)}}detectOsKind(e){switch(e){case`win32`:return Yy.Win;case`darwin`:return Yy.Mac;case`linux`:case`freebsd`:case`openbsd`:case`sunos`:case`aix`:return Yy.Linux;default:return Yy.Unknown}}detectShellKind(){let e=(c.env.SHELL??c.env.ComSpec??``).toLowerCase();return e.includes(`bash`)?Jy.Bash:e.includes(`zsh`)?Jy.Zsh:e.includes(`fish`)?Jy.Fish:e.includes(`pwsh`)?Jy.Pwsh:e.includes(`powershell`)?Jy.PowerShell:e.includes(`cmd`)?Jy.Cmd:e.endsWith(`/sh`)?Jy.Sh:Jy.Unknown}collectEnvContext(){return{...c.env}}collectProfile(){return this.userConfig?.profile==null?{}:this.userConfig.profile}collectToolReferences(){let e={...qy.default};return this.toolPreset===`claudeCode`?{...e,...qy.claudeCode}:this.toolPreset===`kiro`?{...e,...qy.kiro}:e}createMdComponent(){let e=(e=>e.when===!1?null:e.children);return e.Line=e=>e.when===!1?null:e.children,e}};let Zy=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 Qy=class{registrations=[];globalScope=null;setGlobalScope(e){this.globalScope=e}getGlobalScope(){return this.globalScope}register(e,t,n=Zy.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 $y=new Map,eb=new Map,tb=/^export\s+default\s*/u;function nb(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(nb);let t=Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,nb(t)]);return Object.fromEntries(t)}function rb(e){return JSON.stringify(nb(e))}function ib(e,t,n){return[u.resolve(e),t,n.mode,rb(n.globalScope??{})].join(`::`)}function ab(e){return[u.resolve(e.filePath),e.cacheMtimeMs??e.rawMdx.length,rb(e.globalScope??{}),rb(e.rawMdx)].join(`::`)}function ob(e){return e.replace(/^\s*;?\s*/u,``).trim()}function sb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cb(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 lb(e){let t=e.trimStart(),n=tb.exec(t);if(n==null)return null;let r=n[0].length,i=cb(t,r);if(i==null)return null;let a;try{a=v.parse(i.value)}catch{return null}return sb(a)?{content:ob(t.slice(i.endIndex)),metadata:a}:null}async function ub(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=lb(n);if(e!=null)return{rawMdx:n,parsed:a,content:e.content,metadata:e.metadata,lastModified:r}}let o=await dy(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 db(e,t){let n=t.lastModified??i.statSync(e).mtime,r=n.getTime(),a=ib(e,r,t),o=$y.get(a);if(o!=null)return(await o).artifact;let s=ub(e,{...t,lastModified:n}).then(e=>({artifact:e,stamp:r}));$y.set(a,s);try{return(await s).artifact}catch(e){throw $y.delete(a),e}}async function fb(e){let t=ab(e),n=eb.get(t);if(n!=null)return n;let r=dy(e.rawMdx,{globalScope:e.globalScope,extractMetadata:!0,basePath:u.dirname(e.filePath),filePath:e.filePath}).then(e=>({content:e.content,metadata:e.metadata.fields}));eb.set(t,r);try{return await r}catch(e){throw eb.delete(t),e}}function pb(e){return e.replaceAll(`\\`,`/`).replaceAll(/^\/+|\/+$/gu,``)}function mb(e){let t=pb(e);return t.length===0?``:t.split(`/`).filter(e=>e.length>0).join(`-`)}function hb(e){let t=pb(e),n=t.split(`/`).filter(e=>e.length>0),r=n.at(-1)??t,i=n.slice(0,-1),a=mb(t),o=i.length>0?i.join(`-`):void 0;return{...o!=null&&{agentPrefix:o},agentName:r,canonicalName:a.length>0?a:r}}function gb(e){return e.skillName.trim().length>0?e.skillName:e.dir.getDirectoryName()}function _b(e){return e.canonicalName.trim().length>0?e.canonicalName:mb(e.agentPrefix!=null&&e.agentPrefix.length>0?`${e.agentPrefix}-${e.agentName}`:e.agentName)}const vb=[`project`,`global`];function yb(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 bb(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 xb(e){let{requestedScopes:t,defaultScopes:n,supportedScopes:r,singleScope:i,availableScopes:a,priority:o=vb}=e,s=yb(t),c=yb(n),l=new Set(yb(r)),u=(s.length>0?s:c).filter(e=>l.has(e));if(u.length===0)return[];let d=bb(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 Sb=y.object({src:y.string(),dist:y.string()}),Cb=y.object({dir:y.string().default(`aindex`),skills:Sb,commands:Sb,subAgents:Sb,rules:Sb,globalPrompt:Sb,workspacePrompt:Sb,app:Sb,ext:Sb,arch:Sb}),wb=y.object({includeSeriesPrefix:y.boolean().optional(),seriesSeparator:y.string().optional()}),Tb=y.object({includeSeriesPrefix:y.boolean().optional(),pluginOverrides:y.record(y.string(),wb).optional()}),Eb=y.enum([`project`,`global`]),Db=y.union([Eb,y.array(Eb).min(1)]),Ob=y.object({prompt:Db.optional(),rules:Db.optional(),commands:Db.optional(),subagents:Db.optional(),skills:Db.optional(),mcp:Db.optional()}),kb=y.object({plugins:y.record(y.string(),Ob).optional()}),Ab=y.object({blankLineAfter:y.boolean().optional()}),jb=y.enum([`direct`,`recursive`]),Mb=y.enum([`path`,`glob`]),Nb=y.object({path:y.string(),protectionMode:jb,matcher:Mb.optional(),reason:y.string().optional()}),Pb=y.object({rules:y.array(Nb).optional()}),Fb=y.union([y.string(),y.array(y.string()).min(1)]),Ib=y.object({instances:Fb.optional()}),Lb=y.object({wsl2:Ib.optional()}),Rb=y.object({name:y.string().optional(),username:y.string().optional(),gender:y.string().optional(),birthday:y.string().optional()}).catchall(y.unknown()),zb=y.object({version:y.string().optional(),workspaceDir:y.string().optional(),aindex:Cb.optional(),logLevel:y.enum([`trace`,`debug`,`info`,`warn`,`error`]).optional(),commandSeriesOptions:Tb.optional(),outputScopes:kb.optional(),frontMatter:Ab.optional(),cleanupProtection:Pb.optional(),windows:Lb.optional(),profile:Rb.optional()}),Bb=y.object({names:y.array(y.string()).optional()}),Vb=y.object({includeSeries:y.array(y.string()).optional(),subSeries:y.record(y.string(),y.array(y.string())).optional()});y.object({mcp:Bb.optional(),includeSeries:y.array(y.string()).optional(),subSeries:y.record(y.string(),y.array(y.string())).optional(),rules:Vb.optional(),skills:Vb.optional(),subAgents:Vb.optional(),commands:Vb.optional()}),y.object({});function Hb(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 Ub(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 Wb(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=Hb(e.scope,t);return r.push(...a.errors),{valid:r.length===0,errors:r,warnings:i}}function Gb(e,t){let n=Ub(e,{requiredFields:[],optionalDefaults:{},filePath:t}),r=Hb(e.scope,t);return{valid:n.valid&&r.valid,errors:[...n.errors,...r.errors],warnings:n.warnings}}function Kb(e,t){let n=Ub(e,{requiredFields:[`description`],optionalDefaults:{},filePath:t}),r=Hb(e.scope,t);return{valid:n.valid&&r.valid,errors:[...n.errors,...r.errors],warnings:n.warnings}}function qb(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=Hb(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 Jb(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.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 Yb={Readme:{src:`rdm.mdx`,out:`README.md`},CodeOfConduct:{src:`coc.mdx`,out:`CODE_OF_CONDUCT.md`},Security:{src:`security.mdx`,out:`SECURITY.md`}},Xb=[`prompt`,`rules`,`commands`,`subagents`,`skills`,`mcp`];function Zb(e){return _.isBuffer(e)}function Qb(e){if(typeof e==`string`)return[e];let t=[];for(let n of e)t.includes(n)||t.push(n);return t}function $b(e,t){return t?.outputScopes?.plugins?.[e]}function ex(e){for(let t of Xb){let n=e.outputCapabilities[t];if(n!=null&&n.scopes.length===0)throw Error(`Plugin ${e.name} declares empty scopes for topic "${t}"`)}}function tx(e,t){let n=$b(e.name,t);if(n!=null)for(let t of Xb){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=Qb(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 nx(e,t){for(let n of e)ex(n),tx(n,t)}async function rx(e,t){nx(e,t.pluginOptions);let n=await Promise.all(e.map(async e=>[e,await e.declareOutputFiles(t)]));return new Map(n)}async function ix(e,t,n){let r=new Map,a=n??await rx(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}`);if(r.symlinkTarget!=null){i.existsSync(r.path)&&i.rmSync(r.path,{force:!0,recursive:!1}),i.symlinkSync(r.symlinkTarget,r.path,`file`),o.push({path:r.path,success:!0});continue}let a=await n.convertContent(r,t);Zb(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 ax(e,t,n){let r=[],i=[],a=[],o=[],s=n==null?Array.from(await rx(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 ox=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}},sx=class extends Error{cyclePath;constructor(e){super(`Circular dependency detected: ${e.join(` -> `)}`),this.name=`CircularDependencyError`,this.cyclePath=[...e]}},cx=class extends My{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 Xb){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 tg()}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 jy(e)}extractGlobalMemoryContent(e){return e.collectedOutputContext.globalMemory?.content}combineGlobalWithContent(e,t,n){let{separator:r=`
|
|
224
225
|
|
|
225
|
-
`,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 nb(e)}getSubAgentCanonicalName(e){return rb(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=Wy($(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=Wy($(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 Xy({toolPreset:this.toolPreset}).collect(),a=await dy(e.rawMdxContent,{globalScope:t,extractMetadata:!0,basePath:e.dir.basePath,filePath:e.dir.getAbsolutePath()});n=a.content,r=a.metadata.fields,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 Yb={USER_HOME:`~`,WORKSPACE:`$WORKSPACE`},Xb={},Zb={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`,EditorConfigOutput:`EditorConfigOutputPlugin`,AntigravityOutput:`AntigravityOutputPlugin`},Qb={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`},$b={RULES:`rules`,COMMANDS:`commands`,SKILLS:`skills`,AGENTS:`agents`,CURSOR_SKILLS:`skills-cursor`},ex={MD:`.md`,MDC:`.mdc`,MDX:`.mdx`,JSON:`.json`},tx=[{PRIMARY:`.src.mdx`}.PRIMARY],nx={zh:tx,en:ex.MDX};function rx(e){return tx.some(t=>e.endsWith(t))}const ix={CURSOR:`.cursor`,CLAUDE:`.claude`,WINDSURF:`.codeium/windsurf`,WINDSURF_RULES:`.windsurf`},ax={CURSOR:`.cursorignore`,WINDSURF:`.codeiumignore`},ox={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 lx=/^\s*(```|~~~)/u,ux=[/^\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=lx.exec(i);if(r?.[1]!=null){let e=r[1];n==null?n=e:n===e&&(n=void 0);continue}if(n==null&&ux.some(e=>e.test(i)))throw new cx(t,e+1,i)}}function fx(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 px(e){if(e instanceof Yg&&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 mx(e,t){let n=px(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?Jg(e):String(e)),r.join(`
|
|
226
|
-
`)}function hx(e){return e instanceof sx||e instanceof cx}var gx=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)}})),hx(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)}})),hx(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}})),hx(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)}})),hx(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)}})),hx(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=o??e,u=this.normalizeExtensions(a.zh),d=this.normalizeExtensions(a.en),f=this.resolveLocalizedPath(t,l,u),p=this.resolveLocalizedPath(t,l,d),m=this.path.join(n,`${l}.mdx`),h=this.exists(f)?f:this.exists(p)?p:void 0,g={promptKind:String(c),logicalName:e,entryDistPath:m,...h!=null&&{srcPath:h}},_=await this.readDistContent(m,s,e,g),v=await this.readLocaleContent(f,`zh`,s,e,String(c)),y=await this.readLocaleContent(p,`en`,s,e,String(c)),x=_!=null,S=v!=null,w=y!=null,T=S?f:w?p:void 0;if(!x&&!S&&!w)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:f,srcEnPath:p,distPath:m}})),null;if(!x)throw new sx({kind:String(c),name:e,...T!=null&&{sourcePath:T},expectedDistPath:m});let E=S?{zh:v,...w&&{en:y},default:v,defaultLocale:`zh`}:void 0,D=i?this.scanChildren(n,l,[`.mdx`]):void 0;return{name:e,type:c,...E!=null&&{src:E},...x&&{dist:_},metadata:{hasDist:x,hasMultipleLocales:w,isDirectoryStructure:i,...D&&D.length>0&&{children:D}},paths:{...S&&{zh:f},...w&&{en:p},...x&&{dist:m}}}}async readFlatEntry(e,t,n,r,i,a=!1){let{localeExtensions:o,createPrompt:s,kind:c}=i,l=this.normalizeExtensions(o.zh),u=this.normalizeExtensions(o.en),d=this.resolveLocalizedPath(``,r,l),f=this.resolveLocalizedPath(``,r,u),p=this.path.join(n,`${e}.mdx`),m=a?d:this.path.join(t,d),h=a?f:this.path.join(t,f),g=this.exists(m)?m:this.exists(h)?h:void 0,_={promptKind:String(c),logicalName:e,entryDistPath:p,...g!=null&&{srcPath:g}},v=await this.readDistContent(p,s,e,_),y=await this.readLocaleContent(m,`zh`,s,e,String(c)),x=await this.readLocaleContent(h,`en`,s,e,String(c)),S=v!=null,w=y!=null,T=x!=null,E=w?m:T?h:void 0;if(!S&&!w&&!T)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:m,srcEnPath:h,distPath:p}})),null;if(!S)throw new sx({kind:String(c),name:e,...E!=null&&{sourcePath:E},expectedDistPath:p});let D=w?{zh:y,...T&&{en:x},default:y,defaultLocale:`zh`}:void 0;return{name:e,type:c,...D!=null&&{src:D},...S&&{dist:v},metadata:{hasDist:S,hasMultipleLocales:T,isDirectoryStructure:!1},paths:{...w&&{zh:m},...T&&{en:h},...S&&{dist:p}}}}async readLocaleContent(e,t,n,r,i){if(!this.exists(e))return null;try{let i=this.fs.readFileSync(e,`utf8`),a=this.fs.statSync(e),o=await dy(i,{globalScope:this.globalScope,extractMetadata:!0,basePath:this.path.dirname(e),filePath:e});dx(o.content,e);let s=Cp(i),c=await n(o.content,t,r,o.metadata.fields),l={content:o.content,lastModified:a.mtime,filePath:e};return i.length>0&&Object.assign(l,{rawMdx:i}),s.yamlFrontMatter!=null&&Object.assign(l,{frontMatter:s.yamlFrontMatter}),c!=null&&Object.assign(l,{prompt:c}),l}catch(n){throw this.logger.error(ee({code:`LOCALIZED_SOURCE_PROMPT_READ_FAILED`,title:`Failed to read localized source prompt`,diagnosticText:mx(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=this.fs.readFileSync(e,`utf8`),i=this.fs.statSync(e),a=await dy(r,{globalScope:this.globalScope,extractMetadata:!0,basePath:this.path.dirname(e),filePath:e});dx(a.content,e);let o=Cp(r),s=await t(a.content,`zh`,n,a.metadata.fields),c={content:a.content,lastModified:i.mtime,prompt:s,filePath:e,rawMdx:r};return o.yamlFrontMatter!=null&&Object.assign(c,{frontMatter:o.yamlFrontMatter}),c}catch(t){throw this.logger.error(this.buildDistReadDiagnostic(t,e,r)),t}}buildDistReadDiagnostic(e,t,n){let r=fx(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 ee({code:`LOCALIZED_DIST_PROMPT_READ_FAILED`,title:`Failed to read localized dist prompt`,diagnosticText:mx(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 _x(e,t,n,r){return new gx(e,t,n,r)}function vx(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:nb(r),mcpName:e});return n}function yx(e,t){let n={};for(let[r,i]of e)n[r]=t(i);return n}function bx(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 xx(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}var Sx=class{name;inner;constructor(e){this.inner=e,this.name=`json:${e.name}`}async execute(e){_e();let t=await this.inner.execute(e),n=Cx(t,ve());return c.stdout.write(`${JSON.stringify(n)}\n`),t}};function Cx(e,t=ve()){let{warnings:n,errors:r}=ne(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 Tx=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 Ex(e){let t=c.env.XDG_DATA_HOME;return typeof t==`string`&&t.trim().length>0?ig(t):d.join(e,`.local`,`share`)}function Dx(){let e=eg(),t=e.isWsl?`win32`:e.platform,n=e.effectiveHomeDir;if(t===`win32`)return ig(c.env.LOCALAPPDATA??d.join(n,`AppData`,`Local`));if(t===`darwin`)return d.join(n,`Library`,`Application Support`);if(t===`linux`)return Ex(n);throw Error(`Unsupported platform: ${c.platform}`)}async function Ox(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 kx(e){let t=await Promise.all(e.map(async e=>{try{return{path:e,deleted:await Ox(e)}}catch(t){return{path:e,error:t}}})),n=[],r=0;for(let e of t){if(`error`in e){n.push({path:e.path,error:e.error});continue}e.deleted&&r++}return{deleted:r,errors:n}}async function Ax(e){let t=[...e].sort((e,t)=>t.length-e.length),n=await Promise.all(t.map(async e=>{try{return{path:e,deleted:await Ox(e)}}catch(t){return{path:e,error:t}}})),r=[],i=0;for(let e of n){if(`error`in e){r.push({path:e.path,error:e.error});continue}e.deleted&&i++}return{deleted:i,errors:r}}var jx=class extends Error{conflicts;constructor(e){super(Vx(e)),this.name=`CleanupProtectionConflictError`,this.conflicts=e}};const Mx=[`**/node_modules/**`,`**/.git/**`,`**/.turbo/**`,`**/.pnpm-store/**`,`**/.yarn/**`,`**/.next/**`];function Nx(e){return mg(e).replaceAll(`\\`,`/`)}function Px(e){let{root:t}=u.parse(e);return e===t?e:e.endsWith(u.sep)?e.slice(0,-1):e}function Fx(e,t){let n=Px(e),r=Px(t);return n===r?!0:n.startsWith(`${r}${u.sep}`)}function Ix(e,t){let n=Nx(e);return Um.default.sync(n,{onlyFiles:!1,dot:!0,absolute:!0,followSymbolicLinks:!1,ignore:[...t]})}function Lx(e,t){if(t.excludeBasenames==null||t.excludeBasenames.length===0)return!1;let n=u.basename(e);return t.excludeBasenames.includes(n)}async function Rx(e,t){return e.declareCleanupPaths==null?{}:e.declareCleanupPaths({...t,dryRun:!0})}async function zx(e,t,n){let r=n?.get(e),[i,a]=await Promise.all([r==null?e.declareOutputFiles({...t,dryRun:!0}):Promise.resolve(r),Rx(e,t)]);return{plugin:e,outputs:i,cleanup:a}}function Bx(e,t){let n=new Map,r=[...t.entries()].sort((e,t)=>e[0].length-t[0].length);for(let[e,t]of r){let r=!1;for(let t of n.keys())if(Fx(e,t)){r=!0;break}r||n.set(e,t)}let i=[];for(let[t,r]of e){let e=!1;for(let r of n.keys())if(Fx(t,r)){e=!0;break}e||i.push(r)}return i.sort((e,t)=>e.localeCompare(t)),{files:i,dirs:[...n.values()].sort((e,t)=>e.localeCompare(t))}}function Vx(e){let t=e.map(e=>e.outputPath).join(`, `);return`Cleanup protection conflict: ${e.length} output path(s) are also protected: ${t}`}function Hx(e,t){let n=[];for(let[r,i]of e.entries()){let e=new Set(vg(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 Ux(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 Wx(e,t,n){let r=new Set,a=new Set,o=new Map,s=new Set(Mx),c=new Map,l=await Promise.all(e.map(async e=>zx(e,t,n))),u=(e,t)=>{t===`directory`?a.add(mg(e)):r.add(mg(e))},d=(e,t,n,r,i=`path`)=>{let a=mg(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 jg(t.collectedOutputContext))d(e.path,e.protectionMode,e.reason,e.source);if(t.collectedOutputContext.aindexDir!=null&&t.pluginOptions!=null)for(let e of Ag(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=mg(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(Nx(t))}let p=[...s],m=e=>{for(let t of Ix(e.path,p))if(!Lx(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 Ix(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=Ng({workspaceDir:t.collectedOutputContext.workspace.directory.path,projectRoots:Pg(t.collectedOutputContext),rules:[...o.values()],...t.collectedOutputContext.aindexDir==null?{}:{aindexDir:t.collectedOutputContext.aindexDir}}),_=Hx(c,g);if(_.length>0)throw new jx(_);let v=Lg([...r],g),y=Lg([...a],g),b=Bx(new Map(v.safePaths.map(e=>[e,e])),new Map(y.safePaths.map(e=>[e,e])));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))}}async function Gx(e,t){let n=e.map(e=>u.isAbsolute(e)?e:u.resolve(e)),r=await kx(n);for(let e of n)r.errors.some(t=>t.path===e)||t.debug({action:`delete`,type:`file`,path:e});let i=r.errors.map(e=>{let n=e.error instanceof Error?e.error.message:String(e.error);return t.warn(D({code:`CLEANUP_FILE_DELETE_FAILED`,title:`Cleanup could not delete a file`,operation:`delete`,targetKind:`file`,path:e.path,error:n,details:{phase:`cleanup`}})),{path:e.path,type:`file`,error:e.error}});return{deleted:r.deleted,errors:i}}async function Kx(e,t){let n=e.map(e=>u.isAbsolute(e)?e:u.resolve(e)),r=await Ax(n);for(let e of n)r.errors.some(t=>t.path===e)||t.debug({action:`delete`,type:`directory`,path:e});let i=r.errors.map(e=>{let n=e.error instanceof Error?e.error.message:String(e.error);return t.warn(D({code:`CLEANUP_DIRECTORY_DELETE_FAILED`,title:`Cleanup could not delete a directory`,operation:`delete`,targetKind:`directory`,path:e.path,error:n,details:{phase:`cleanup`}})),{path:e.path,type:`directory`,error:e.error}});return{deleted:r.deleted,errors:i}}function qx(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 Jx(e,t,n,r){if(r!=null){let i=await Gb(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 Wx(e,t,r)}catch(e){if(e instanceof jx)return Ux(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(qx(n,a),a.violations.length>0)return zg(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,s]=await Promise.all([Gx(a.filesToDelete,n),Kx(a.dirsToDelete,n)]);return{deletedFiles:o.deleted,deletedDirs:s.deleted,errors:[...o.errors,...s.errors],violations:[],conflicts:[]}}var Yx=class{name=`clean`;async execute(e){let{logger:t,outputPlugins:n,createCleanContext:r}=e;t.info(`running clean pipeline`,{command:`clean`});let i=await Jx(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})}},Xx=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 Gb(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 Wx(n,i);return c.length>0?(zg(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})}}},Zx=class{canHandle(e){return e.subcommand===`clean`}createCommand(e){return e.dryRun?new Xx:new Yx}};const Qx=[`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 $x(e){return Qx.includes(e)}function eS(e){return[`trace`,`debug`,`info`,`warn`,`error`].includes(e)}function tS(){return rg()}function nS(){let e=tS();if(!i.existsSync(e))return{};try{let t=i.readFileSync(e,`utf8`);return JSON.parse(t)}catch{return{}}}function rS(e){let t=tS(),n=u.dirname(t);i.existsSync(n)||i.mkdirSync(n,{recursive:!0}),i.writeFileSync(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)}function iS(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 aS(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 oS=class{name=`config`;constructor(e){this.options=e}async execute(e){let{logger:t}=e;if(this.options.length===0)return t.error(k({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: ${Qx.join(`, `)}`)],details:{validKeys:[...Qx]}})),t.info(`Usage: tnmsc config key=value`),t.info(`Valid keys: ${Qx.join(`, `)}`),{success:!1,filesAffected:0,dirsAffected:0,message:`No options provided`};let n;try{n=nS()}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(!$x(e)){r.push(`Invalid key: ${e}`),t.error(k({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: ${Qx.join(`, `)}`)],details:{key:e,validKeys:[...Qx]}}));continue}if(e===`logLevel`&&!eS(a)){r.push(`Invalid logLevel value: ${a}`),t.error(k({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=aS(n,e);iS(n,e,a),o!==a&&i.push(`${e}=${a}`),t.info(`configuration updated`,{key:e,value:a})}if(i.length>0){try{rS(n)}catch(e){return{success:!1,filesAffected:0,dirsAffected:0,message:e instanceof Error?e.message:String(e)}}t.info(`global config written`,{path:tS()})}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 sS=`.tnmsc.json`,cS=`.aindex`;function lS(){return rg()}var uS=class{logger;constructor(e={}){this.logger=ye(`ConfigLoader`)}getSearchPaths(e=c.cwd()){let t=eg();if(!t.isWsl)return[rg()];if(this.logger.info(`wsl environment detected`,{effectiveHomeDir:t.effectiveHomeDir}),t.selectedGlobalConfigPath==null)throw Error(`WSL host config file not found under "${t.windowsUsersRoot}/*/${cS}/${sS}".`);return this.logger.info(`using wsl host global config`,{path:t.selectedGlobalConfigPath}),[rg()]}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=Tb.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(`
|
|
227
|
-
`)}`)}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(`~`)?ig(e):e}};let
|
|
228
|
-
`).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
|
|
229
|
-
`)}:(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`})}},
|
|
230
|
-
`)};let f=await
|
|
231
|
-
`)}:(l+=f.mirroredFiles,t.info(`complete`,{command:`execute`,pluginCount:c.size}),{success:!0,filesAffected:l,dirsAffected:u})}},
|
|
232
|
-
${
|
|
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 gb(e)}getSubAgentCanonicalName(e){return _b(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]=xb({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 xb({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 xb({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=Wy($(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=Wy($(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 Xy({toolPreset:this.toolPreset}).collect(),a=await fb({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 lx={USER_HOME:`~`,WORKSPACE:`$WORKSPACE`},ux={},dx={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`,EditorConfigOutput:`EditorConfigOutputPlugin`,AntigravityOutput:`AntigravityOutputPlugin`},fx={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`},px={RULES:`rules`,COMMANDS:`commands`,SKILLS:`skills`,AGENTS:`agents`,CURSOR_SKILLS:`skills-cursor`},mx={MD:`.md`,MDC:`.mdc`,MDX:`.mdx`,JSON:`.json`},hx=[{PRIMARY:`.src.mdx`}.PRIMARY],gx={zh:hx,en:mx.MDX};function _x(e){return hx.some(t=>e.endsWith(t))}const vx={CURSOR:`.cursor`,CLAUDE:`.claude`,WINDSURF:`.codeium/windsurf`,WINDSURF_RULES:`.windsurf`},yx={CURSOR:`.cursorignore`,WINDSURF:`.codeiumignore`},bx={CURSOR:new Set([`create-rule`,`create-skill`,`create-subagent`,`migrate-to-skills`,`update-cursor-settings`])};var xx=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}},Sx=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 Cx=/^\s*(```|~~~)/u,wx=[/^\s*export\s+default\b/u,/^\s*export\s+const\b/u,/^\s*import\b/u];function Tx(e,t){let n,r=e.split(/\r?\n/u);for(let[e,i]of r.entries()){let r=Cx.exec(i);if(r?.[1]!=null){let e=r[1];n==null?n=e:n===e&&(n=void 0);continue}if(n==null&&wx.some(e=>e.test(i)))throw new Sx(t,e+1,i)}}function Ex(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 Dx(e){if(e instanceof Yg&&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 Ox(e,t){let n=Dx(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?Jg(e):String(e)),r.join(`
|
|
227
|
+
`)}function kx(e){return e instanceof xx||e instanceof Sx}var Ax=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)}})),kx(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)}})),kx(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}})),kx(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)}})),kx(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)}})),kx(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 xx({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 xx({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 db(e,{mode:`source`,globalScope:this.globalScope});Tx(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(ee({code:`LOCALIZED_SOURCE_PROMPT_READ_FAILED`,title:`Failed to read localized source prompt`,diagnosticText:Ox(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 db(e,{mode:`dist`,globalScope:this.globalScope});Tx(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=Ex(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 ee({code:`LOCALIZED_DIST_PROMPT_READ_FAILED`,title:`Failed to read localized dist prompt`,diagnosticText:Ox(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 jx(e,t,n,r){return new Ax(e,t,n,r)}function Mx(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:gb(r),mcpName:e});return n}function Nx(e,t){let n={};for(let[r,i]of e)n[r]=t(i);return n}function Px(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 Fx(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}var Ix=class{name;inner;constructor(e){this.inner=e,this.name=`json:${e.name}`}async execute(e){_e();let t=await this.inner.execute(e),n=Lx(t,ve());return c.stdout.write(`${JSON.stringify(n)}\n`),t}};function Lx(e,t=ve()){let{warnings:n,errors:r}=ne(t);return{success:e.success,filesAffected:e.filesAffected,dirsAffected:e.dirsAffected,...e.message!=null&&{message:e.message},pluginResults:[],warnings:n,errors:r}}let Rx=function(e){return e[e.Flags=0]=`Flags`,e[e.Unknown=1]=`Unknown`,e[e.Subcommand=2]=`Subcommand`,e}({});var zx=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<=Rx.Unknown&&t.canHandle(e))return t.createCommand(e);for(let t of this.factories)if(t.priority===Rx.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 Bx(e){let t=c.env.XDG_DATA_HOME;return typeof t==`string`&&t.trim().length>0?ig(t):d.join(e,`.local`,`share`)}function Vx(){let e=eg(),t=e.isWsl?`win32`:e.platform,n=e.effectiveHomeDir;if(t===`win32`)return ig(c.env.LOCALAPPDATA??d.join(n,`AppData`,`Local`));if(t===`darwin`)return d.join(n,`Library`,`Application Support`);if(t===`linux`)return Bx(n);throw Error(`Unsupported platform: ${c.platform}`)}async function Hx(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 Ux(e){let t=await Promise.all(e.map(async e=>{try{return{path:e,deleted:await Hx(e)}}catch(t){return{path:e,error:t}}})),n=[],r=0;for(let e of t){if(`error`in e){n.push({path:e.path,error:e.error});continue}e.deleted&&r++}return{deleted:r,errors:n}}async function Wx(e){let t=[...e].sort((e,t)=>t.length-e.length),n=await Promise.all(t.map(async e=>{try{return{path:e,deleted:await Hx(e)}}catch(t){return{path:e,error:t}}})),r=[],i=0;for(let e of n){if(`error`in e){r.push({path:e.path,error:e.error});continue}e.deleted&&i++}return{deleted:i,errors:r}}var Gx=class extends Error{conflicts;constructor(e){super(tS(e)),this.name=`CleanupProtectionConflictError`,this.conflicts=e}};const Kx=[`**/node_modules/**`,`**/.git/**`,`**/.turbo/**`,`**/.pnpm-store/**`,`**/.yarn/**`,`**/.next/**`];function qx(e){return mg(e).replaceAll(`\\`,`/`)}function Jx(e){let{root:t}=u.parse(e);return e===t?e:e.endsWith(u.sep)?e.slice(0,-1):e}function Yx(e,t){let n=Jx(e),r=Jx(t);return n===r?!0:n.startsWith(`${r}${u.sep}`)}function Xx(e,t){let n=qx(e);return Um.default.sync(n,{onlyFiles:!1,dot:!0,absolute:!0,followSymbolicLinks:!1,ignore:[...t]})}function Zx(e,t){if(t.excludeBasenames==null||t.excludeBasenames.length===0)return!1;let n=u.basename(e);return t.excludeBasenames.includes(n)}async function Qx(e,t){return e.declareCleanupPaths==null?{}:e.declareCleanupPaths({...t,dryRun:!0})}async function $x(e,t,n){let r=n?.get(e),[i,a]=await Promise.all([r==null?e.declareOutputFiles({...t,dryRun:!0}):Promise.resolve(r),Qx(e,t)]);return{plugin:e,outputs:i,cleanup:a}}function eS(e,t){let n=new Map,r=[...t.entries()].sort((e,t)=>e[0].length-t[0].length);for(let[e,t]of r){let r=!1;for(let t of n.keys())if(Yx(e,t)){r=!0;break}r||n.set(e,t)}let i=[];for(let[t,r]of e){let e=!1;for(let r of n.keys())if(Yx(t,r)){e=!0;break}e||i.push(r)}return i.sort((e,t)=>e.localeCompare(t)),{files:i,dirs:[...n.values()].sort((e,t)=>e.localeCompare(t))}}function tS(e){let t=e.map(e=>e.outputPath).join(`, `);return`Cleanup protection conflict: ${e.length} output path(s) are also protected: ${t}`}function nS(e,t){let n=[];for(let[r,i]of e.entries()){let e=new Set(vg(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 rS(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 iS(e,t,n){let r=new Set,a=new Set,o=new Map,s=new Set(Kx),c=new Map,l=await Promise.all(e.map(async e=>$x(e,t,n))),u=(e,t)=>{t===`directory`?a.add(mg(e)):r.add(mg(e))},d=(e,t,n,r,i=`path`)=>{let a=mg(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 jg(t.collectedOutputContext))d(e.path,e.protectionMode,e.reason,e.source);if(t.collectedOutputContext.aindexDir!=null&&t.pluginOptions!=null)for(let e of Ag(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=mg(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(qx(t))}let p=[...s],m=e=>{for(let t of Xx(e.path,p))if(!Zx(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 Xx(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=Ng({workspaceDir:t.collectedOutputContext.workspace.directory.path,projectRoots:Pg(t.collectedOutputContext),rules:[...o.values()],...t.collectedOutputContext.aindexDir==null?{}:{aindexDir:t.collectedOutputContext.aindexDir}}),_=nS(c,g);if(_.length>0)throw new Gx(_);let v=Lg([...r],g),y=Lg([...a],g),b=eS(new Map(v.safePaths.map(e=>[e,e])),new Map(y.safePaths.map(e=>[e,e])));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))}}async function aS(e,t){let n=e.map(e=>u.isAbsolute(e)?e:u.resolve(e)),r=await Ux(n);for(let e of n)r.errors.some(t=>t.path===e)||t.debug({action:`delete`,type:`file`,path:e});let i=r.errors.map(e=>{let n=e.error instanceof Error?e.error.message:String(e.error);return t.warn(D({code:`CLEANUP_FILE_DELETE_FAILED`,title:`Cleanup could not delete a file`,operation:`delete`,targetKind:`file`,path:e.path,error:n,details:{phase:`cleanup`}})),{path:e.path,type:`file`,error:e.error}});return{deleted:r.deleted,errors:i}}async function oS(e,t){let n=e.map(e=>u.isAbsolute(e)?e:u.resolve(e)),r=await Wx(n);for(let e of n)r.errors.some(t=>t.path===e)||t.debug({action:`delete`,type:`directory`,path:e});let i=r.errors.map(e=>{let n=e.error instanceof Error?e.error.message:String(e.error);return t.warn(D({code:`CLEANUP_DIRECTORY_DELETE_FAILED`,title:`Cleanup could not delete a directory`,operation:`delete`,targetKind:`directory`,path:e.path,error:n,details:{phase:`cleanup`}})),{path:e.path,type:`directory`,error:e.error}});return{deleted:r.deleted,errors:i}}function sS(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 cS(e,t,n,r){if(r!=null){let i=await ax(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 iS(e,t,r)}catch(e){if(e instanceof Gx)return rS(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(sS(n,a),a.violations.length>0)return zg(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,s]=await Promise.all([aS(a.filesToDelete,n),oS(a.dirsToDelete,n)]);return{deletedFiles:o.deleted,deletedDirs:s.deleted,errors:[...o.errors,...s.errors],violations:[],conflicts:[]}}var lS=class{name=`clean`;async execute(e){let{logger:t,outputPlugins:n,createCleanContext:r}=e;t.info(`running clean pipeline`,{command:`clean`});let i=await cS(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})}},uS=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 ax(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 iS(n,i);return c.length>0?(zg(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})}}},dS=class{canHandle(e){return e.subcommand===`clean`}createCommand(e){return e.dryRun?new uS:new lS}};const fS=[`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 pS(e){return fS.includes(e)}function mS(e){return[`trace`,`debug`,`info`,`warn`,`error`].includes(e)}function hS(){return rg()}function gS(){let e=hS();if(!i.existsSync(e))return{};try{let t=i.readFileSync(e,`utf8`);return JSON.parse(t)}catch{return{}}}function _S(e){let t=hS(),n=u.dirname(t);i.existsSync(n)||i.mkdirSync(n,{recursive:!0}),i.writeFileSync(t,`${JSON.stringify(e,null,2)}\n`,`utf8`)}function vS(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 yS(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 bS=class{name=`config`;constructor(e){this.options=e}async execute(e){let{logger:t}=e;if(this.options.length===0)return t.error(k({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: ${fS.join(`, `)}`)],details:{validKeys:[...fS]}})),t.info(`Usage: tnmsc config key=value`),t.info(`Valid keys: ${fS.join(`, `)}`),{success:!1,filesAffected:0,dirsAffected:0,message:`No options provided`};let n;try{n=gS()}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(!pS(e)){r.push(`Invalid key: ${e}`),t.error(k({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: ${fS.join(`, `)}`)],details:{key:e,validKeys:[...fS]}}));continue}if(e===`logLevel`&&!mS(a)){r.push(`Invalid logLevel value: ${a}`),t.error(k({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=yS(n,e);vS(n,e,a),o!==a&&i.push(`${e}=${a}`),t.info(`configuration updated`,{key:e,value:a})}if(i.length>0){try{_S(n)}catch(e){return{success:!1,filesAffected:0,dirsAffected:0,message:e instanceof Error?e.message:String(e)}}t.info(`global config written`,{path:hS()})}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 xS=`.tnmsc.json`,SS=`.aindex`;function CS(){return rg()}var wS=class{logger;constructor(e={}){this.logger=ye(`ConfigLoader`)}getSearchPaths(e=c.cwd()){let t=eg();if(!t.isWsl)return[rg()];if(this.logger.info(`wsl environment detected`,{effectiveHomeDir:t.effectiveHomeDir}),t.selectedGlobalConfigPath==null)throw Error(`WSL host config file not found under "${t.windowsUsersRoot}/*/${SS}/${xS}".`);return this.logger.info(`using wsl host global config`,{path:t.selectedGlobalConfigPath}),[rg()]}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=zb.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(`~`)?ig(e):e}};let TS=null;function ES(e){return(e||!TS)&&(TS=new wS(e)),TS}function DS(e){return ES().load(e)}function OS(){let e=ye(`ConfigLoader`),t;try{t=rg()}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:`${Th}/${Eh}`,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=zb.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 kS=class{name=`config-show`;async execute(e){let{logger:t}=e,n=new wS,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))`}}},AS=class{canHandle(e){return e.subcommand===`config`}createCommand(e){if(e.showFlag)return new kS;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 bS([...e.setOption,...t])}},jS=class extends Error{};function MS(e){return e?.fs??i}function NS(e){return e?.spawnSync??h}function PS(e){return e?.platform??c.platform}function FS(e){return e?.effectiveHomeDir??tg()}function IS(e){return e?.nativeHomeDir??eg().nativeHomeDir}function LS(e){return e?.isWsl??eg().isWsl}function RS(e){return e===`win32`?u.win32:u.posix}function zS(e){return[...new Set(e.map(e=>e.trim()).filter(e=>e.length>0))]}function BS(e){let t=e?.windows?.wsl2?.instances;return zS(t==null?[]:Array.isArray(t)?t:[t])}function VS(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 HS(e,t,n){let r=RS(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 US(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 WS(e){return US(e).replaceAll(`\0`,``)}function GS(e){let{error:t}=e;if(!(typeof t!=`object`||!t))return`code`in t&&typeof t.code==`string`?t.code:void 0}function KS(e){if(GS(e)===`ENOENT`)return`wsl.exe is not available on PATH.`;let t=[e.stderr,e.stdout].map(e=>WS(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 qS(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 JS(e){return{platform:`win32`,isWsl:!1,nativeHomeDir:e,effectiveHomeDir:e,globalConfigCandidates:[],windowsUsersRoot:``,expandedEnv:{HOME:e,USERPROFILE:e}}}function YS(e,t){return{platform:`linux`,isWsl:!0,nativeHomeDir:t,effectiveHomeDir:e,globalConfigCandidates:[],windowsUsersRoot:``,expandedEnv:{HOME:e,USERPROFILE:e}}}function XS(e){return zS(e.split(/\r?\n/u).map(e=>e.replace(/^\*/u,``).trim()).filter(e=>e.length>0))}function ZS(e,t){let n=NS(t)(`wsl.exe`,[`--list`,`--quiet`],{shell:!1,windowsHide:!0}),r=KS(n);if(r!=null)throw new jS(r);if(n.status!==0){let e=WS(n.stderr).trim();throw Error(`Failed to enumerate WSL instances. ${e.length>0?e:`wsl.exe returned a non-zero exit status.`}`)}let i=XS(WS(n.stdout));return e.info(`discovered wsl instances`,{instances:i}),i}function QS(e,t,n){let r=BS(e);return r.length>0?r:ZS(t,n)}function $S(e,t,n){if(e.scope!==`global`)return;let r=RS(n).normalize(e.path),i;try{i=HS(r,t,n)}catch{return}let[a]=i;if(a?.startsWith(`.`))return{kind:`generated`,sourcePath:r,relativePathSegments:i}}function eC(e,t,n){if(e==null)return[];let r=new Map;for(let i of e.values())for(let e of i){let i=$S(e,t,n);i!=null&&r.set(i.sourcePath,i)}return[...r.values()]}function tC(e,t,n,r){let i=RS(r).normalize(ig(e.sourcePath,t));return{kind:`declared`,sourcePath:i,relativePathSegments:HS(i,n,r)}}function nC(e,t,n,r,i){let a=new Map,o=[];for(let t of e)try{let e=tC(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 rC(e,t,n){if(PS(n)!==`win32`)return[];let r=QS(e,t,n);if(r.length===0)return[];let i=MS(n),a=NS(n),o=[];for(let e of r){let n=a(`wsl.exe`,[`-d`,e,`sh`,`-lc`,`printf %s "$HOME"`],{shell:!1,windowsHide:!0}),r=KS(n);if(r!=null)throw new jS(r);if(n.status!==0){let t=WS(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=WS(n.stdout).trim();if(s.length===0)throw Error(`WSL instance "${e}" returned an empty home directory.`);let c=VS(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 iC(e,t,n){let r=MS(n),i=u.posix.normalize(IS(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 aC(e,t,n,r){let i=PS(n),a=i===`linux`&&LS(n);if(i!==`win32`&&!a)return{mirroredFiles:0,warnings:[],errors:[]};let o=a?u.posix.normalize(FS(n)):u.win32.normalize(FS(n)),s=await qS(e,t),c=eC(r,o,i);if(s.length===0&&c.length===0)return{mirroredFiles:0,warnings:[],errors:[]};let l=t.pluginOptions??{},d=a?u.posix.normalize(IS(n)):void 0,f=nC(s,c,a?YS(o,d??o):JS(o),o,i);if(a){if(f.sources.length===0||d==null||o===d)return{mirroredFiles:0,warnings:[],errors:[...f.errors]};let e=iC(f.sources,t,n);return{mirroredFiles:e.mirroredFiles,warnings:[...e.warnings],errors:[...f.errors,...e.errors]}}let p;try{p=rC(l,t.logger,n)}catch(e){return e instanceof jS?(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=MS(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 oC=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 rx(n,i),o=await ix(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 aC(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`})}},sC=class{canHandle(e){return e.subcommand===`dry-run`}createCommand(e){return new oC}},cC=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 rx(n,a),s=await cS(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 ix(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 aC(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})}},lC=class{canHandle(e){return!0}createCommand(e){return new cC}};function uC(){return`2026.10324.11958`}var dC=class{name=`version`;async execute(e){return e.logger.info(`tnmsc v${uC()}`),{success:!0,filesAffected:0,dirsAffected:0,message:`Version displayed`}}};const fC=`tnmsc`,pC=`
|
|
233
|
+
${fC} v${uC()} - Memory Sync CLI
|
|
233
234
|
|
|
234
235
|
Synchronize AI memory and configuration files across projects.
|
|
235
236
|
|
|
236
237
|
USAGE:
|
|
237
|
-
${
|
|
238
|
-
${
|
|
239
|
-
${
|
|
240
|
-
${
|
|
241
|
-
${
|
|
242
|
-
${
|
|
243
|
-
${
|
|
244
|
-
${
|
|
238
|
+
${fC} Run the sync pipeline (default)
|
|
239
|
+
${fC} help Show this help message
|
|
240
|
+
${fC} version Show version information
|
|
241
|
+
${fC} init Deprecated; no longer initializes aindex
|
|
242
|
+
${fC} dry-run Preview what would be written
|
|
243
|
+
${fC} clean Remove all generated files
|
|
244
|
+
${fC} clean --dry-run Preview what would be cleaned
|
|
245
|
+
${fC} config key=value Set configuration value
|
|
245
246
|
|
|
246
247
|
SUBCOMMANDS:
|
|
247
248
|
help Show this help message
|
|
@@ -252,10 +253,10 @@ SUBCOMMANDS:
|
|
|
252
253
|
config Set configuration values in global config file (~/.aindex/.tnmsc.json)
|
|
253
254
|
|
|
254
255
|
ALIASES:
|
|
255
|
-
${
|
|
256
|
-
${
|
|
257
|
-
${
|
|
258
|
-
${
|
|
256
|
+
${fC} --help, ${fC} -h Same as '${fC} help'
|
|
257
|
+
${fC} --version, ${fC} -v Same as '${fC} version'
|
|
258
|
+
${fC} clean -n Same as '${fC} clean --dry-run'
|
|
259
|
+
${fC} config key=value Set config value in global config file
|
|
259
260
|
|
|
260
261
|
LOG LEVEL OPTIONS:
|
|
261
262
|
--trace Most verbose output
|
|
@@ -281,31 +282,31 @@ CONFIG OPTIONS:
|
|
|
281
282
|
aindex.arch.src, aindex.arch.dist
|
|
282
283
|
|
|
283
284
|
Examples:
|
|
284
|
-
${
|
|
285
|
-
${
|
|
286
|
-
${
|
|
285
|
+
${fC} config workspaceDir=~/my-project
|
|
286
|
+
${fC} config aindex.skills.src=skills
|
|
287
|
+
${fC} config logLevel=debug
|
|
287
288
|
|
|
288
289
|
CONFIGURATION:
|
|
289
290
|
Configure via plugin.config.ts in your project root.
|
|
290
291
|
See documentation for detailed configuration options.
|
|
291
|
-
`.trim();var
|
|
292
|
-
`)=>{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 mC=class{name=`help`;async execute(e){return e.logger.info(pC),{success:!0,filesAffected:0,dirsAffected:0,message:`Help displayed`}}},hC=class{priority=Rx.Flags;canHandle(e){return e.helpFlag||e.subcommand===`help`}createCommand(e){return new mC}},gC=class{name=`init`;async execute(e){let{logger:t}=e;return t.warn(k({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/`."}}},_C=class{canHandle(e){return e.subcommand===`init`}createCommand(e){return new gC}},vC=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)`}}},yC=class{canHandle(e){return e.subcommand===`plugins`}createCommand(e){return new vC}},bC=class{name=`unknown`;constructor(e){this.unknownCmd=e}async execute(e){return e.logger.error(k({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}`}}},xC=class{priority=Rx.Unknown;canHandle(e){return e.unknownCommand!=null}createCommand(e){return e.unknownCommand==null?new bC(``):new bC(e.unknownCommand)}},SC=class{priority=Rx.Flags;canHandle(e){return e.versionFlag||e.subcommand===`version`}createCommand(e){return new dC}};const CC=new Set([`help`,`version`,`init`,`dry-run`,`clean`,`config`,`plugins`]),wC=new Map([[`--trace`,`trace`],[`--debug`,`debug`],[`--info`,`info`],[`--warn`,`warn`],[`--error`,`error`]]),TC=new Map([[`trace`,0],[`debug`,1],[`info`,2],[`warn`,3],[`error`,4]]);function EC(e){let t=[...e],n=t[0];n!=null&&DC(n)&&t.shift();let r=t[0];return r!=null&&OC(r)&&t.shift(),t}function DC(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 OC(e){return/\.(?:m?[jt]s|cjs)$/.test(e)||/[/\\]/.test(e)&&!e.startsWith(`-`)?!0:/^(?:@[\w-]+\/)?[\w-]+$/.test(e)&&!e.startsWith(`-`)}function kC(e,t){if(e==null)return t;let n=TC.get(e)??4;return(TC.get(t)??4)<n?t:e}function AC(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=wC.get(a);if(o!=null){t.logLevel=kC(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,CC.has(i)?t.subcommand=i:t.unknownCommand=i;continue}t.positional.push(i)}}return t}let jC;function MC(){let e=new zx;return e.register(new SC),e.register(new hC),e.register(new xC),e.registerWithPriority(new _C,Rx.Subcommand),e.registerWithPriority(new sC,Rx.Subcommand),e.registerWithPriority(new dS,Rx.Subcommand),e.registerWithPriority(new yC,Rx.Subcommand),e.registerWithPriority(new AS,Rx.Subcommand),e.registerWithPriority(new lC,Rx.Subcommand),e}function NC(){return jC??=MC(),jC}function PC(e){return NC().resolve(e)}const FC=[`IntelliJIdea`,`WebStorm`,`RustRover`,`PyCharm`,`PyCharmCE`,`PhpStorm`,`GoLand`,`CLion`,`DataGrip`,`RubyMine`,`Rider`,`DataSpell`,`Aqua`];function IC(e){return FC.some(t=>e.startsWith(t))}function LC(e){let t=u.join(Vx(),`JetBrains`);try{return i.readdirSync(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&IC(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 RC(e){return{jetbrainsCodexDirs:LC(e)}}var zC=class{logger;args;outputPlugins=[];runtimeTargets;constructor(...e){this.args=AC(EC(e.filter(e=>e!=null)));let t=this.args.logLevel;t!=null&&ge(t),this.logger=ye(`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=PC(this.args);this.args.jsonFlag&&(ge(`silent`),new Set([`config-show`,`plugins`]).has(i.name)||(i=new Ix(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??=RC(this.logger),this.runtimeTargets}};function BC(e,t){let n=u.join(e,`.git`),r=i.existsSync(n);return r?t?.info(`version control detected`,{path:n}):t?.warn(k({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 VC(e){return u.extname(e).length>0}function HC(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);VC(t)?m(n):p(n)}}return{success:!0,rootPath:e,createdDirs:a,createdFiles:o,existedDirs:s,existedFiles:c}}var UC=class extends Bg{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}=e,o=[],s=[],c=[],l=[n.join(r,`src`),n.join(r,`app`),n.join(r,`dist`)];for(let n of l){if(!t.existsSync(n)){a.debug({action:`whitespace-cleanup`,message:`Directory does not exist, skipping`,dir:n});continue}this.processDirectory(e,n,o,s,c,i??!1)}let u=c.length>0;return{success:!u,description:i?`Would modify ${o.length} files, skip ${s.length} files`:`Modified ${o.length} files, skipped ${s.length} files`,modifiedFiles:o,skippedFiles:s,...u&&{error:Error(`${c.length} errors occurred during cleanup`)}}}processDirectory(e,t,n,r,i,a){let{fs:o,path:s,logger:c}=e,l;try{l=o.readdirSync(t,{withFileTypes:!0})}catch(e){i.push({path:t,error:e}),c.warn(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
|
|
293
294
|
`)?`\r
|
|
294
295
|
`:`
|
|
295
|
-
`}collect(e){return{}}};const AC=[`skills`,`commands`,`agents`,`app`];var jC=class extends Bg{constructor(){super(`OrphanFileCleanupEffectInputCapability`),this.registerEffect(`orphan-file-cleanup`,this.cleanupOrphanFiles.bind(this),20)}buildProtectedDeletionGuard(e){return Ng({workspaceDir:e.workspaceDir,aindexDir:e.aindexDir,rules:[...Ag(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 AC){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)}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=Lg(u.filesToDelete,d),p=Lg(u.dirsToDelete,d),m=[...f.violations,...p.violations].sort((e,t)=>e.targetPath.localeCompare(t.targetPath));if(m.length>0)return{success:!1,description:`Protected deletion guard blocked orphan cleanup for ${m.length} path(s)`,deletedFiles:[],deletedDirs:[],error:new ag(`orphan-file-cleanup`,m)};if(o)return{success:!0,description:`Would delete ${f.safePaths.length} files and ${p.safePaths.length} directories`,deletedFiles:[...f.safePaths],deletedDirs:[...p.safePaths].sort((e,t)=>t.length-e.length)};let h=[],g=[],_=[...u.errors];for(let e of f.safePaths)try{t.unlinkSync(e),h.push(e),i.debug({action:`orphan-cleanup`,deleted:e})}catch(t){_.push({path:e,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,error:t}))}for(let e of[...p.safePaths].sort((e,t)=>t.length-e.length))try{t.rmdirSync(e),g.push(e),i.debug({action:`orphan-cleanup`,deletedDir:e})}catch(t){_.push({path:e,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,error:t}))}let v=_.length>0;return{success:!v,description:`Deleted ${h.length} files and ${g.length} directories`,deletedFiles:h,deletedDirs:g,...v&&{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===``?[...tx.map(i=>e.join(t,r,n,`SKILL${i}`)),...tx.map(i=>e.join(t,r,n,`skill${i}`))]:tx.map(a=>e.join(t,r,n,o,`${i}${a}`))}case`commands`:case`agents`:case`app`:return a===`.`?tx.map(n=>e.join(t,r,`${i}${n}`)):tx.map(n=>e.join(t,r,a,`${i}${n}`));default:return[]}}collect(e){return{}}},MC=class extends Bg{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);if(a)return{success:!0,description:`Would delete ${c.filesToDelete.length} files and ${c.dirsToDelete.length} directories`,deletedFiles:[...c.filesToDelete],deletedDirs:[...c.dirsToDelete].sort((e,t)=>t.length-e.length)};let l=[],u=[],d=[...c.errors];for(let e of c.filesToDelete)try{t.unlinkSync(e),l.push(e),n.debug({action:`skill-dist-cleanup`,deleted:e})}catch(t){d.push({path:e,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,error:t}))}for(let e of[...c.dirsToDelete].sort((e,t)=>t.length-e.length))try{t.rmdirSync(e),u.push(e),n.debug({action:`skill-dist-cleanup`,deletedDir:e})}catch(t){d.push({path:e,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,error:t}))}let f=d.length>0;return{success:!f,description:`Deleted ${l.length} files and ${u.length} directories`,deletedFiles:l,deletedDirs:u,...f&&{error:Error(`${d.length} errors occurred during cleanup`)}}}buildCleanupPlan(e,t){let n=[],r=[],i=[];return this.collectCleanupPlan(e,t,n,r,i),{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`)&&!rx(e)}collect(e){return{}}};const NC=/export\s+default\s*\{([\s\S]*?)\}/u,PC=/description\s*:\s*['"`]([^'"`]+)['"`]/u,FC=/name\s*:\s*['"`]([^'"`]+)['"`]/u,IC=/displayName\s*:\s*['"`]([^'"`]+)['"`]/u,LC=/keywords\s*:\s*\[([^\]]+)\]/u,RC=/author\s*:\s*['"`]([^'"`]+)['"`]/u,zC=/version\s*:\s*['"`]([^'"`]+)['"`]/u;function BC(e){let t={},n=NC.exec(e);if(n?.[1]==null)return t;let r=n[1],i=PC.exec(r);i?.[1]!=null&&(t.description=i[1]);let a=FC.exec(r);a?.[1]!=null&&(t.name=a[1]);let o=IC.exec(r);o?.[1]!=null&&(t.displayName=o[1]);let s=LC.exec(r);s?.[1]!=null&&(t.keywords=s[1].split(`,`).map(e=>e.trim().replaceAll(/['"]/gu,``)).filter(e=>e.length>0));let c=RC.exec(r);c?.[1]!=null&&(t.author=c[1]);let l=zC.exec(r);return l?.[1]!=null&&(t.version=l[1]),t}function VC(...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 HC(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 UC={".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`},WC=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 GC(e){return WC.has(e.toLowerCase())}function KC(e){return UC[e.toLowerCase()]}function qC(...e){return u.join(...e).replaceAll(`\\`,`/`)}var JC=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`||rx(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`||rx(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=this.ctx.fs.readFileSync(t,`utf8`),r=Cp(n),i=wp((await dy(n,{globalScope:this.ctx.globalScope,extractMetadata:!0,basePath:u.dirname(t),filePath:t})).content);return dx(i,t),{type:ah.SkillChildDoc,content:i,length:i.length,filePathKind:oh.Relative,markdownAst:r.markdownAst,markdownContents:r.markdownContents,...r.rawFrontMatter!=null&&{rawFrontMatter:r.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(ee({code:`SKILL_CHILD_DOC_COMPILE_FAILED`,title:`Failed to compile skill child doc`,diagnosticText:mx(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:fx(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=KC(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(GC(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=qC(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 YC(e,t,n,r=``){let i=[],a=r===``?e:qC(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(...YC(e,t,n,o));continue}!a.isFile()||!rx(a.name)||r===``&&a.name===`skill.src.mdx`||i.push(o.replace(/\.src\.mdx$/u,`.mdx`))}return i}function XC(e,t,n,r,i){if(r.existsSync(t))for(let a of YC(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 ZC(e,t,n){let r=u.join(e,`mcp.json`);if(t.existsSync(r)){if(!t.statSync(r).isFile()){n.warn(A({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 QC(e,t,n,r,i,a,o,s,c=[],l=[],d,f,p){let{logger:m,globalScope:h,fs:g}=o,_=u.join(i,`skill.mdx`),v=g.existsSync(u.join(a,`skill.src.mdx`))?u.join(a,`skill.src.mdx`):_,y=e,x,S;if(g.existsSync(_)){y=g.readFileSync(_,`utf8`),x=Cp(y);let t=await dy(y,{globalScope:h,extractMetadata:!0,basePath:i,filePath:_});e=wp(t.content),dx(e,_),S=t.metadata.fields}let w=VC(BC(y),f,S),T=new Set,E=x?.yamlFrontMatter?.name;typeof E==`string`&&E.trim().length>0&&T.add(E);let D=w.name;typeof D==`string`&&D.trim().length>0&&T.add(D);for(let e of T)HC({logger:m,sourcePath:v,authoredName:e,skillName:n,...p!=null&&{warnedDerivedNames:p}});let O=x?.yamlFrontMatter?.description??w?.description;if(O==null||O.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:x?.yamlFrontMatter?.description,exportDescription:w?.description}})),Error(`Skill "${n}" validation failed: description is required and cannot be empty`);let k={...w,...x?.yamlFrontMatter??{},name:n,description:O},A=Ab(k,_);if(!A.valid)throw Error(A.errors.join(`
|
|
296
|
-
`));return{type:ah.Skill,content:e,length:e.length,filePathKind:oh.Relative,skillName:n,yamlFrontMatter:
|
|
297
|
-
`));for(let e of m){let t=e.dist?.prompt;t!=null&&l.push(t)}return{skills:l}}},
|
|
298
|
-
`));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
|
|
299
|
-
`));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}}},nw=class extends Bg{constructor(){super(`EditorConfigInputCapability`)}collect(e){let{userConfigOptions:t,fs:n}=e,{workspaceDir:r,aindexDir:i}=this.resolveBasePaths(t),a=[],o=wh(sh.EditorConfig,`.editorconfig`,i,n,{command:e.runtimeCommand,workspaceDir:r});return o!=null&&a.push(o),{editorConfigFiles:a}}},rw=class extends Bg{constructor(){super(`GitExcludeInputCapability`)}collect(e){let{workspaceDir:t,aindexDir:n}=this.resolveBasePaths(e.userConfigOptions),r=Sh(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})}},iw=class extends Bg{constructor(){super(`GitIgnoreInputCapability`)}collect(e){let{workspaceDir:t,aindexDir:n}=this.resolveBasePaths(e.userConfigOptions),r=Sh(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})}},aw=class extends Bg{constructor(){super(`GlobalMemoryInputCapability`)}async collect(e){let{userConfigOptions:t,fs:n,path:r,globalScope:i}=e,{aindexDir:a}=this.resolveBasePaths(t),o=lS(),s=tg(),l=this.resolveAindexPath(t.aindex.globalPrompt.dist,a);if(!n.existsSync(l))return this.log.warn(A({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(A({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=n.readFileSync(l,`utf8`),d=Cp(u),f;try{f=(await dy(u,{...i!=null&&{globalScope:i},extractMetadata:!0,basePath:r.dirname(l),filePath:l})).content,dx(f,l)}catch(e){throw e instanceof Yg&&(this.log.error(ee({code:`GLOBAL_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile global memory prompt`,diagnosticText:mx(e,{operation:`Failed to compile global memory prompt.`,promptKind:`global-memory`,logicalName:`global-memory`,distPath:l}),details:{promptKind:`global-memory`,distPath:l}})),e instanceof Zg&&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:f.length}),{globalMemory:{type:ah.GlobalMemory,content:f,length:f.length,filePathKind:oh.Relative,...d.rawFrontMatter!=null&&{rawFrontMatter:d.rawFrontMatter},markdownAst:d.markdownAst,markdownContents:d.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}}}}}},ow=class extends Bg{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=wh(sh.IntellijIDEA,t,i,n,{command:e.runtimeCommand,workspaceDir:r});a!=null&&o.push(a)}return{jetbrainsConfigFiles:o}}};const sw=`agt.mdx`,cw=[`node_modules`,`.git`];var lw=class extends Bg{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,path:a,logger:o}=e;if(!(!i.existsSync(t)||!i.statSync(t).isFile()))try{let e=i.readFileSync(t,`utf8`),s=Cp(e),l;try{let{content:r}=await dy(e,{globalScope:n,extractMetadata:!0,basePath:a.dirname(t),filePath:t});l=r,dx(l,t)}catch(e){if(e instanceof Yg){if(o.error(ee({code:`WORKSPACE_ROOT_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile workspace root memory prompt`,diagnosticText:mx(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 Zg){let n=lS();o.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 u={type:ah.ProjectRootMemory,content:l,length:l.length,filePathKind:oh.Relative,...s.yamlFrontMatter!=null&&{yamlFrontMatter:s.yamlFrontMatter},...s.rawFrontMatter!=null&&{rawFrontMatter:s.rawFrontMatter},markdownAst:s.markdownAst,markdownContents:s.markdownContents,dir:{pathKind:oh.Root,path:``,getDirectoryName:()=>``}};return{name:`__workspace__`,isWorkspaceRootProject:!0,...r!=null&&{projectConfig:r},rootMemoryPrompt:u}}catch(e){o.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,sw);if(!(!r.existsSync(o)||!r.statSync(o).isFile()))try{let e=r.readFileSync(o,`utf8`),i=Cp(e),s;try{let{content:r}=await dy(e,{globalScope:n,extractMetadata:!0,basePath:t,filePath:o});s=r,dx(s,o)}catch(e){if(e instanceof Yg){if(a.error(ee({code:`PROJECT_ROOT_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile project root memory prompt`,diagnosticText:mx(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 Zg){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:s,length:s.length,filePathKind:oh.Relative,...i.yamlFrontMatter!=null&&{yamlFrontMatter:i.yamlFrontMatter},...i.rawFrontMatter!=null&&{rawFrontMatter:i.rawFrontMatter},markdownAst:i.markdownAst,markdownContents:i.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()||cw.includes(l.name))continue;let c=s.join(n,l.name),u=s.join(c,sw);if(o.existsSync(u)&&o.statSync(u).isFile()){let n=await this.readChildMemoryPrompt(e,t,c,r,a);n!=null&&i.push(n)}await this.scanDirectoryRecursive(e,t,c,r,i,a)}}async readChildMemoryPrompt(e,t,n,r,i){let{fs:a,path:o,logger:s}=e,l=o.join(n,sw);try{let e=a.readFileSync(l,`utf8`),u=Cp(e),d;try{let{content:t}=await dy(e,{globalScope:i,extractMetadata:!0,basePath:n,filePath:l});d=t,dx(d,l)}catch(e){if(e instanceof Yg){if(s.error(ee({code:`PROJECT_CHILD_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile project child memory prompt`,diagnosticText:mx(e,{operation:`Failed to compile project child memory prompt.`,promptKind:`project-child-memory`,logicalName:l,distPath:l}),details:{promptKind:`project-child-memory`,distPath:l}})),e instanceof Zg){let t=lS();s.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:l,errorMessage:e.message}}))}c.exit(1)}throw e}let f=o.relative(t,n),p=o.join(r,f),m=o.basename(n);return{type:ah.ProjectChildrenMemory,content:d,length:d.length,filePathKind:oh.Relative,...u.yamlFrontMatter!=null&&{yamlFrontMatter:u.yamlFrontMatter},...u.rawFrontMatter!=null&&{rawFrontMatter:u.rawFrontMatter},markdownAst:u.markdownAst,markdownContents:u.markdownContents,dir:{pathKind:oh.Relative,path:f,basePath:r,getDirectoryName:()=>m,getAbsolutePath:()=>p},workingChildDirectoryPath:{pathKind:oh.Relative,path:f,basePath:r,getDirectoryName:()=>m,getAbsolutePath:()=>p}}}catch(e){s.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:l,error:e}));return}}};const uw=Object.entries(Fb);var dw=class extends Bg{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 uw){let p=l.join(t,f);if(!(!s.existsSync(p)||!s.statSync(p).isFile()))try{let m=s.readFileSync(p,`utf8`),h;try{let{content:e}=await dy(m,{...o!=null&&{globalScope:o},extractMetadata:!0,basePath:t,filePath:p});h=e,dx(h,p)}catch(t){if(t instanceof Yg){if(u.error(ee({code:`README_PROMPT_COMPILE_FAILED`,title:`Failed to compile readme-family prompt`,diagnosticText:mx(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 Zg){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 g=d?n:l.join(n,i),_={pathKind:oh.Relative,path:g,basePath:r,getDirectoryName:()=>d?n:l.basename(i),getAbsolutePath:()=>l.resolve(r,g)},v={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:h,length:h.length,filePathKind:oh.Relative,projectName:n,targetDir:_,isRoot:d,fileKind:e,markdownContents:[],dir:v})}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}))}}},fw=class extends Bg{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 _x(i,r,n,a).readFlatFiles(s,c,{kind:ah.Rule,localeExtensions:nx,isDirectoryStructure:!1,createPrompt:async(e,t,n,i)=>{let a=i,o=r.join(c,`${n}.mdx`);if(a!=null){let e=Nb(a,o);if(!e.valid)throw Error(e.errors.join(`
|
|
296
|
+
`}collect(e){return{}}};const WC=[`skills`,`commands`,`agents`,`app`];var GC=class extends Bg{constructor(){super(`OrphanFileCleanupEffectInputCapability`),this.registerEffect(`orphan-file-cleanup`,this.cleanupOrphanFiles.bind(this),20)}buildProtectedDeletionGuard(e){return Ng({workspaceDir:e.workspaceDir,aindexDir:e.aindexDir,rules:[...Ag(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 WC){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)}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=Lg(u.filesToDelete,d),p=Lg(u.dirsToDelete,d),m=[...f.violations,...p.violations].sort((e,t)=>e.targetPath.localeCompare(t.targetPath));if(m.length>0)return{success:!1,description:`Protected deletion guard blocked orphan cleanup for ${m.length} path(s)`,deletedFiles:[],deletedDirs:[],error:new ag(`orphan-file-cleanup`,m)};if(o)return{success:!0,description:`Would delete ${f.safePaths.length} files and ${p.safePaths.length} directories`,deletedFiles:[...f.safePaths],deletedDirs:[...p.safePaths].sort((e,t)=>t.length-e.length)};let h=[],g=[],_=[...u.errors];for(let e of f.safePaths)try{t.unlinkSync(e),h.push(e),i.debug({action:`orphan-cleanup`,deleted:e})}catch(t){_.push({path:e,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,error:t}))}for(let e of[...p.safePaths].sort((e,t)=>t.length-e.length))try{t.rmdirSync(e),g.push(e),i.debug({action:`orphan-cleanup`,deletedDir:e})}catch(t){_.push({path:e,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,error:t}))}let v=_.length>0;return{success:!v,description:`Deleted ${h.length} files and ${g.length} directories`,deletedFiles:h,deletedDirs:g,...v&&{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===``?[...hx.map(i=>e.join(t,r,n,`SKILL${i}`)),...hx.map(i=>e.join(t,r,n,`skill${i}`))]:hx.map(a=>e.join(t,r,n,o,`${i}${a}`))}case`commands`:case`agents`:case`app`:return a===`.`?hx.map(n=>e.join(t,r,`${i}${n}`)):hx.map(n=>e.join(t,r,a,`${i}${n}`));default:return[]}}collect(e){return{}}},KC=class extends Bg{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);if(a)return{success:!0,description:`Would delete ${c.filesToDelete.length} files and ${c.dirsToDelete.length} directories`,deletedFiles:[...c.filesToDelete],deletedDirs:[...c.dirsToDelete].sort((e,t)=>t.length-e.length)};let l=[],u=[],d=[...c.errors];for(let e of c.filesToDelete)try{t.unlinkSync(e),l.push(e),n.debug({action:`skill-dist-cleanup`,deleted:e})}catch(t){d.push({path:e,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,error:t}))}for(let e of[...c.dirsToDelete].sort((e,t)=>t.length-e.length))try{t.rmdirSync(e),u.push(e),n.debug({action:`skill-dist-cleanup`,deletedDir:e})}catch(t){d.push({path:e,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,error:t}))}let f=d.length>0;return{success:!f,description:`Deleted ${l.length} files and ${u.length} directories`,deletedFiles:l,deletedDirs:u,...f&&{error:Error(`${d.length} errors occurred during cleanup`)}}}buildCleanupPlan(e,t){let n=[],r=[],i=[];return this.collectCleanupPlan(e,t,n,r,i),{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`)&&!_x(e)}collect(e){return{}}};const qC=/export\s+default\s*\{([\s\S]*?)\}/u,JC=/description\s*:\s*['"`]([^'"`]+)['"`]/u,YC=/name\s*:\s*['"`]([^'"`]+)['"`]/u,XC=/displayName\s*:\s*['"`]([^'"`]+)['"`]/u,ZC=/keywords\s*:\s*\[([^\]]+)\]/u,QC=/author\s*:\s*['"`]([^'"`]+)['"`]/u,$C=/version\s*:\s*['"`]([^'"`]+)['"`]/u;function ew(e){let t={},n=qC.exec(e);if(n?.[1]==null)return t;let r=n[1],i=JC.exec(r);i?.[1]!=null&&(t.description=i[1]);let a=YC.exec(r);a?.[1]!=null&&(t.name=a[1]);let o=XC.exec(r);o?.[1]!=null&&(t.displayName=o[1]);let s=ZC.exec(r);s?.[1]!=null&&(t.keywords=s[1].split(`,`).map(e=>e.trim().replaceAll(/['"]/gu,``)).filter(e=>e.length>0));let c=QC.exec(r);c?.[1]!=null&&(t.author=c[1]);let l=$C.exec(r);return l?.[1]!=null&&(t.version=l[1]),t}function tw(...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 nw(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 rw={".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`},iw=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 aw(e){return iw.has(e.toLowerCase())}function ow(e){return rw[e.toLowerCase()]}function sw(...e){return u.join(...e).replaceAll(`\\`,`/`)}var cw=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`||_x(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`||_x(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 db(t,{mode:`dist`,globalScope:this.ctx.globalScope}),r=wp(n.content);return Tx(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(ee({code:`SKILL_CHILD_DOC_COMPILE_FAILED`,title:`Failed to compile skill child doc`,diagnosticText:Ox(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:Ex(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=ow(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(aw(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=sw(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 lw(e,t,n,r=``){let i=[],a=r===``?e:sw(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(...lw(e,t,n,o));continue}!a.isFile()||!_x(a.name)||r===``&&a.name===`skill.src.mdx`||i.push(o.replace(/\.src\.mdx$/u,`.mdx`))}return i}function uw(e,t,n,r,i){if(r.existsSync(t))for(let a of lw(t,r,i)){let i=u.join(n,a);if(!r.existsSync(i))throw new xx({kind:`skill child doc`,name:`${e}/${a}`,sourcePath:u.join(t,a.replace(/\.mdx$/u,`.src.mdx`)),expectedDistPath:i})}}function dw(e,t,n){let r=u.join(e,`mcp.json`);if(t.existsSync(r)){if(!t.statSync(r).isFile()){n.warn(A({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 fw(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 db(g,{mode:`dist`,globalScope:o.globalScope});v=t.rawMdx,y=t.parsed,e=wp(t.content),Tx(e,g),x=t.metadata}let S=tw(ew(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)nw({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},k=Wb(O,g);if(!k.valid)throw Error(k.errors.join(`
|
|
297
|
+
`));return{type:ah.Skill,content:e,length:e.length,filePathKind:oh.Relative,skillName:n,yamlFrontMatter:O,markdownAst:y?.markdownAst,markdownContents:y?.markdownContents??[],dir:{pathKind:oh.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 pw=class extends Bg{constructor(){super(`SkillInputCapability`)}readMcpConfig(e,t,n){return dw(e,t,n)}async scanSkillDirectory(e,t,n,r=``,i=`srcResources`,a,o){return new cw({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=jx(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=dw(o,r,n);uw(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:ah.Skill,entryFileName:`skill`,localeExtensions:gx,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 fw(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}}},mw=class e extends Bg{static projectConfigFileName=`project.json5`;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}}collect(e){let{userConfigOptions:t,logger:n,fs:r,path:i}=e,{workspaceDir:a,aindexDir:o}=this.resolveBasePaths(t),s=this.resolveAindexPath(t.aindex.app.dist,o),c=i.basename(o),l=[];if(r.existsSync(s)&&r.statSync(s).isDirectory())try{let e=r.readdirSync(s,{withFileTypes:!0});for(let s of e)if(s.isDirectory()){let e=s.name===c,u=this.loadProjectConfig(s.name,o,t.aindex.app.src,r,i,n);l.push({name:s.name,...e&&{isPromptSourceProject:!0},...u!=null&&{projectConfig:u},dirFromWorkspacePath:{pathKind:oh.Relative,path:s.name,basePath:a,getDirectoryName:()=>s.name,getAbsolutePath:()=>i.resolve(a,s.name)}})}}catch(e){n.error(D({code:`AINDEX_PROJECT_DIRECTORY_SCAN_FAILED`,title:`Failed to scan aindex projects directory`,operation:`scan`,targetKind:`aindex projects directory`,path:s,error:e}))}if(l.length===0&&r.existsSync(a)&&r.statSync(a).isDirectory()){n.debug(`no projects in dist/app/, falling back to workspace scan`,{workspaceDir:a});try{let e=r.readdirSync(a,{withFileTypes:!0});for(let s of e)if(s.isDirectory()&&!s.name.startsWith(`.`)){let e=s.name===c,u=this.loadProjectConfig(s.name,o,t.aindex.app.src,r,i,n);l.push({name:s.name,...e&&{isPromptSourceProject:!0},...u!=null&&{projectConfig:u},dirFromWorkspacePath:{pathKind:oh.Relative,path:s.name,basePath:a,getDirectoryName:()=>s.name,getAbsolutePath:()=>i.resolve(a,s.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:oh.Absolute,path:a,getDirectoryName:()=>i.basename(a)},projects:l}}}},hw=class extends Bg{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:ah.Command,content:e,length:e.length,filePathKind:oh.Relative,dir:{pathKind:oh.Relative,path:h,basePath:r,getDirectoryName:()=>h.replace(/\.mdx$/,``),getAbsolutePath:()=>m},...f!=null&&{commandPrefix:f},commandName:p};if(g==null)return _;let v=Gb(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 jx(i,r,n,a).readFlatFiles(s,c,{kind:ah.Command,localeExtensions:gx,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}}},gw=class extends Bg{constructor(){super(`EditorConfigInputCapability`)}collect(e){let{userConfigOptions:t,fs:n}=e,{workspaceDir:r,aindexDir:i}=this.resolveBasePaths(t),a=[],o=wh(sh.EditorConfig,`.editorconfig`,i,n,{command:e.runtimeCommand,workspaceDir:r});return o!=null&&a.push(o),{editorConfigFiles:a}}},_w=class extends Bg{constructor(){super(`GitExcludeInputCapability`)}collect(e){let{workspaceDir:t,aindexDir:n}=this.resolveBasePaths(e.userConfigOptions),r=Sh(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})}},vw=class extends Bg{constructor(){super(`GitIgnoreInputCapability`)}collect(e){let{workspaceDir:t,aindexDir:n}=this.resolveBasePaths(e.userConfigOptions),r=Sh(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})}},yw=class extends Bg{constructor(){super(`GlobalMemoryInputCapability`)}async collect(e){let{userConfigOptions:t,fs:n,path:r,globalScope:i}=e,{aindexDir:a}=this.resolveBasePaths(t),o=CS(),s=tg(),l=this.resolveAindexPath(t.aindex.globalPrompt.dist,a);if(!n.existsSync(l))return this.log.warn(A({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(A({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 db(l,{mode:`dist`,globalScope:i}),u=d.content,Tx(u,l)}catch(e){throw e instanceof Yg&&(this.log.error(ee({code:`GLOBAL_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile global memory prompt`,diagnosticText:Ox(e,{operation:`Failed to compile global memory prompt.`,promptKind:`global-memory`,logicalName:`global-memory`,distPath:l}),details:{promptKind:`global-memory`,distPath:l}})),e instanceof Zg&&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}}}}}},bw=class extends Bg{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=wh(sh.IntellijIDEA,t,i,n,{command:e.runtimeCommand,workspaceDir:r});a!=null&&o.push(a)}return{jetbrainsConfigFiles:o}}};const xw=`agt.mdx`,Sw=[`node_modules`,`.git`];var Cw=class extends Bg{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 db(t,{mode:`dist`,globalScope:n}),Tx(e.content,t)}catch(e){if(e instanceof Yg){if(a.error(ee({code:`WORKSPACE_ROOT_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile workspace root memory prompt`,diagnosticText:Ox(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 Zg){let n=CS();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,xw);if(!(!r.existsSync(o)||!r.statSync(o).isFile()))try{let e;try{e=await db(o,{mode:`dist`,globalScope:n}),Tx(e.content,o)}catch(e){if(e instanceof Yg){if(a.error(ee({code:`PROJECT_ROOT_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile project root memory prompt`,diagnosticText:Ox(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 Zg){let t=CS();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()||Sw.includes(l.name))continue;let c=s.join(n,l.name),u=s.join(c,xw);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,xw);try{let e;try{e=await db(s,{mode:`dist`,globalScope:i}),Tx(e.content,s)}catch(e){if(e instanceof Yg){if(o.error(ee({code:`PROJECT_CHILD_MEMORY_PROMPT_COMPILE_FAILED`,title:`Failed to compile project child memory prompt`,diagnosticText:Ox(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 Zg){let t=CS();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 ww=Object.entries(Yb);var Tw=class extends Bg{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 ww){let p=l.join(t,f);if(!(!s.existsSync(p)||!s.statSync(p).isFile()))try{let t;try{let{content:e}=await db(p,{mode:`dist`,globalScope:o});t=e,Tx(t,p)}catch(t){if(t instanceof Yg){if(u.error(ee({code:`README_PROMPT_COMPILE_FAILED`,title:`Failed to compile readme-family prompt`,diagnosticText:Ox(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 Zg){let e=CS();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}))}}},Ew=class extends Bg{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 jx(i,r,n,a).readFlatFiles(s,c,{kind:ah.Rule,localeExtensions:gx,hydrateSourceContents:!1,isDirectoryStructure:!1,createPrompt:async(e,t,n,i)=>{let a=i,o=r.join(c,`${n}.mdx`);if(a!=null){let e=qb(a,o);if(!e.valid)throw Error(e.errors.join(`
|
|
300
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:ah.Rule,content:e,length:e.length,filePathKind:oh.Relative,dir:{pathKind:oh.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(`
|
|
301
|
-
`));return{rules:l.map(e=>e.dist?.prompt).filter(e=>e!=null)}}},
|
|
302
|
-
`));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=
|
|
303
|
-
`));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}}},hw=class extends Bg{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=wh(sh.VSCode,t,i,n,{command:e.runtimeCommand,workspaceDir:r});a!=null&&o.push(a)}return{vscodeConfigFiles:o}}},gw=class extends Bg{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}}};const _w={workspace:{strategy:`mergeProjects`,getter:e=>e.workspace},vscodeConfigFiles:{strategy:`concat`,getter:e=>e.vscodeConfigFiles},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 vw(e,t){return t==null?e??[]:e==null?t:[...e,...t]}function yw(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 bw(e,t){return t==null?e:e==null?t:yw(e,t)}function xw(e,t,n){switch(n){case`concat`:return vw(e,t);case`override`:return t??e;case`mergeProjects`:return bw(e,t);default:return t??e}}function Sw(e,t){let n={};for(let[r,i]of Object.entries(_w)){let a=xw(i.getter(e),i.getter(t),i.strategy);a!=null&&(n[r]=a)}return n}function Cw(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 ww(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 Tw(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 Kb(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 qb(ww(e,r))}function Ew(){return[new MC,new jC,new kC]}function Dw(){return[new gw,new ew,new hw,new ow,new nw,new $C,new tw,new mw,new fw,new aw,new lw,new dw,new iw,new rw,new pw]}function Ow(e){if(e==null||e.length===0)return`execute`;let t=gC(fC(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 kw(e){let{pipelineArgs:t,userConfigOptions:n,userConfig:r,capabilities:a,includeBuiltinEffects:o=!0}=e,s=ye(`InputRuntime`,n.logLevel),c=Ow(t),l={logger:s,userConfigOptions:n,fs:i,path:u,glob:Um.default},d=Tw([...o?Ew():[],...a??Dw()]),f=new Xy({userConfig:r}).collect(),p=new Qy;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=Cw(e,m,Sw),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=Sw(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,Zy.PluginRegistered),s.debug(`input capability scope registered`,{capability:e.name,namespace:n,keys:Object.keys(r)})}}return h}function Aw(e){return`declarativeOutput`in e}function jw(e){return`collect`in e&&!Aw(e)}const Mw={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 Nw(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 Pw(...e){return e.reduce((e,t)=>Fw(e,t),{...Mw})}function Fw(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:Iw(e.aindex,t.aindex),plugins:[...e.plugins,...n??[]],commandSeriesOptions:Lw(e.commandSeriesOptions,r),outputScopes:zw(e.outputScopes,i),frontMatter:Bw(e.frontMatter,a),cleanupProtection:Vw(e.cleanupProtection,o),windows:Hw(e.windows,s)}}function Iw(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 Lw(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 Rw(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{...e,...t}}function zw(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=Rw(n[e],r);t!=null&&(n[e]=t)}return Object.keys(n).length===0?{}:{plugins:n}}function Bw(e,t){return t==null?e:{...e,...t}}function Vw(e,t){return t==null?e??{}:e==null?t:{rules:[...e.rules??[],...t.rules??[]]}}function Hw(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 Uw(e){return`pluginOptions`in e||`configLoaderOptions`in e||`loadUserConfig`in e||`cwd`in e||`pipelineArgs`in e}async function Ww(e={}){let t,n,r,i,a;Uw(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=Object.hasOwn(r,`plugins`),s=r.plugins,c={},l=!1,u=[],d;if(t)try{let e=fS(i).load(n);l=e.found,u=e.sources,e.found&&(c=Nw(e.config),d=e.config)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load user config: ${t}`)}let f=Pw(c,r),{plugins:p=[],logLevel:m}=f,h=ye(`defineConfig`,m);l?h.info(`user config loaded`,{sources:u}):h.info(`no user config found, using defaults/programmatic options`,{workspaceDir:f.workspaceDir,aindexDir:f.aindex.dir,logLevel:f.logLevel});let g=p.filter(Aw),_=p.filter(jw);Hb(g,f);let v=await kw({userConfigOptions:f,..._.length>0?{capabilities:_}:{},includeBuiltinEffects:!(_.length>0||o&&(s?.length??0)===0),...a==null?{}:{pipelineArgs:a},...d==null?{}:{userConfig:d}});if(v.workspace==null)throw Error(`Workspace not initialized by any plugin`);let y=Pb({workspace:v.workspace,...v.vscodeConfigFiles!=null&&{vscodeConfigFiles:v.vscodeConfigFiles},...v.jetbrainsConfigFiles!=null&&{jetbrainsConfigFiles:v.jetbrainsConfigFiles},...v.editorConfigFiles!=null&&{editorConfigFiles:v.editorConfigFiles},...v.commands!=null&&{commands:v.commands},...v.subAgents!=null&&{subAgents:v.subAgents},...v.skills!=null&&{skills:v.skills},...v.rules!=null&&{rules:v.rules},...v.globalMemory!=null&&{globalMemory:v.globalMemory},...v.aiAgentIgnoreConfigFiles!=null&&{aiAgentIgnoreConfigFiles:v.aiAgentIgnoreConfigFiles},...v.aindexDir!=null&&{aindexDir:v.aindexDir},...v.readmePrompts!=null&&{readmePrompts:v.readmePrompts},...v.globalGitIgnore!=null&&{globalGitIgnore:v.globalGitIgnore},...v.shadowGitExclude!=null&&{shadowGitExclude:v.shadowGitExclude}});return v.aindexDir!=null&&EC(v.aindexDir,h),{context:y,outputPlugins:g,userConfigOptions:f}}const Gw=`.agents/skills`,Kw=`SKILL.md`;var qw=class extends Jb{constructor(){super(`GenericSkillsOutputPlugin`,{outputFileName:Kw,treatWorkspaceRootProjectAsProject:!0,skills:{},cleanup:{delete:{project:{dirs:[Gw]},global:{dirs:[Gw]}}},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,Kw),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,Gw);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(),Gw),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 Jw=`AGENTS.md`;var Yw=class extends Jb{constructor(){super(`AgentsOutputPlugin`,{outputFileName:Jw,treatWorkspaceRootProjectAsProject:!0,cleanup:{delete:{project:{files:[Jw]}}},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,Jw),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 Xw=`CLAUDE.md`;var Zw=class extends Jb{constructor(){super(`ClaudeCodeCLIOutputPlugin`,{globalConfigDir:`.claude`,outputFileName:Xw,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:[Xw],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 Qw=ix.CURSOR,$w=Qb.MCP_CONFIG,eT=$b.COMMANDS,tT=$b.RULES,nT=Qb.CURSOR_GLOBAL_RULE,rT=$b.CURSOR_SKILLS,iT=Qb.SKILL,aT=ox.CURSOR;var oT=class extends Jb{constructor(){super(`CursorOutputPlugin`,{globalConfigDir:Qw,outputFileName:``,treatWorkspaceRootProjectAsProject:!0,dependsOn:[Zb.AgentsOutput],indexignore:ax.CURSOR,commands:{subDir:eT,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:rT},rules:{subDir:tT,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(aT,e=>`.cursor/skills-cursor/${e}`)},global:{dirs:Array.from(aT,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/${rT}/*`)?e:{...e,excludeBasenames:[...aT]})}}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,rT,r);if(t.push({path:u.join(a,iT),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,rT,this.getSkillName(i));t.push({path:u.join(r,$w),scope:n,source:{kind:`skillMcpConfig`,rawContent:i.mcpConfig.rawContent}})}},b=(e,n,r)=>{if(r.length===0)return;let i=vx(r,this.log);i.size!==0&&t.push({path:u.join(e,$w),scope:n,source:{kind:`mcpConfig`,mcpServers:yx(i,bx)}})};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,eT,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,eT,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,tT,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=Wy($(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,tT,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,tT,nT),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 aT.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(`
|
|
302
|
+
`));return{rules:l.map(e=>e.dist?.prompt).filter(e=>e!=null)}}},Dw=class extends Bg{constructor(){super(`AIAgentIgnoreInputCapability`)}collect(e){let{workspaceDir:t,aindexDir:n}=this.resolveBasePaths(e.userConfigOptions),r=[];for(let i of fh){let a=Sh(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}}},Ow=class extends Bg{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}=hb(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:ah.SubAgent,content:e,length:e.length,filePathKind:oh.Relative,dir:{pathKind:oh.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=Kb(_,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=jx(i,r,n,a),u=new Set,{prompts:d,errors:f}=await l.readFlatFiles(s,c,{kind:ah.SubAgent,localeExtensions:gx,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}}},kw=class extends Bg{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=wh(sh.VSCode,t,i,n,{command:e.runtimeCommand,workspaceDir:r});a!=null&&o.push(a)}return{vscodeConfigFiles:o}}},Aw=class extends Bg{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}}};const jw={workspace:{strategy:`mergeProjects`,getter:e=>e.workspace},vscodeConfigFiles:{strategy:`concat`,getter:e=>e.vscodeConfigFiles},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 Mw(e,t){return t==null?e??[]:e==null?t:[...e,...t]}function Nw(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 Pw(e,t){return t==null?e:e==null?t:Nw(e,t)}function Fw(e,t,n){switch(n){case`concat`:return Mw(e,t);case`override`:return t??e;case`mergeProjects`:return Pw(e,t);default:return t??e}}function Iw(e,t){let n={};for(let[r,i]of Object.entries(jw)){let a=Fw(i.getter(e),i.getter(t),i.strategy);a!=null&&(n[r]=a)}return n}function Lw(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 Rw(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 zw(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 ox(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 sx(Rw(e,r))}function Bw(){return[new KC,new GC,new UC]}function Vw(){return[new Aw,new mw,new kw,new bw,new gw,new pw,new hw,new Ow,new Ew,new yw,new Cw,new Tw,new vw,new _w,new Dw]}function Hw(e){if(e==null||e.length===0)return`execute`;let t=AC(EC(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 Uw(e){let{pipelineArgs:t,userConfigOptions:n,userConfig:r,capabilities:a,includeBuiltinEffects:o=!0}=e,s=ye(`InputRuntime`,n.logLevel),c=Hw(t),l={logger:s,userConfigOptions:n,fs:i,path:u,glob:Um.default},d=zw([...o?Bw():[],...a??Vw()]),f=new Xy({userConfig:r}).collect(),p=new Qy;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=Lw(e,m,Iw),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=Iw(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,Zy.PluginRegistered),s.debug(`input capability scope registered`,{capability:e.name,namespace:n,keys:Object.keys(r)})}}return h}function Ww(e){return`declarativeOutput`in e}function Gw(e){return`collect`in e&&!Ww(e)}const Kw={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 qw(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 Jw(...e){return e.reduce((e,t)=>Yw(e,t),{...Kw})}function Yw(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:Xw(e.aindex,t.aindex),plugins:[...e.plugins,...n??[]],commandSeriesOptions:Zw(e.commandSeriesOptions,r),outputScopes:$w(e.outputScopes,i),frontMatter:eT(e.frontMatter,a),cleanupProtection:tT(e.cleanupProtection,o),windows:nT(e.windows,s)}}function Xw(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 Zw(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 Qw(e,t){if(!(e==null&&t==null))return e==null?t:t==null?e:{...e,...t}}function $w(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=Qw(n[e],r);t!=null&&(n[e]=t)}return Object.keys(n).length===0?{}:{plugins:n}}function eT(e,t){return t==null?e:{...e,...t}}function tT(e,t){return t==null?e??{}:e==null?t:{rules:[...e.rules??[],...t.rules??[]]}}function nT(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 rT(e){return`pluginOptions`in e||`configLoaderOptions`in e||`loadUserConfig`in e||`cwd`in e||`pipelineArgs`in e}function iT(e){return rT(e)?{hasExplicitProgrammaticPlugins:Object.hasOwn(e.pluginOptions??{},`plugins`),explicitProgrammaticPlugins:e.pluginOptions?.plugins}:{hasExplicitProgrammaticPlugins:Object.hasOwn(e,`plugins`),explicitProgrammaticPlugins:e.plugins}}function aT(e,t){let n=e;return n.includes(lx.WORKSPACE)&&(n=n.replace(lx.WORKSPACE,t)),u.normalize(ig(n))}function oT(e){let t=aT(e.workspaceDir,``),n=u.join(t,e.aindex.dir);return Jb({workspace:{directory:{pathKind:oh.Absolute,path:t,getDirectoryName:()=>u.basename(t)},projects:[]},aindexDir:n})}function sT(e){return Hw(e)===`plugins`}async function cT(e={}){let t,n,r,i,a;rT(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=ES(i).load(n);s=e.found,c=e.sources,e.found&&(o=qw(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=Jw(o,r),{plugins:d=[],logLevel:f}=u,p=ye(`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(Ww),h=d.filter(Gw);return nx(m,u),{mergedOptions:u,outputPlugins:m,inputCapabilities:h,...l!=null&&{userConfigFile:l},...a!=null&&{pipelineArgs:a},userConfigFound:s,userConfigSources:c}}async function lT(e={}){let{hasExplicitProgrammaticPlugins:t,explicitProgrammaticPlugins:n}=iT(e),{mergedOptions:r,outputPlugins:i,inputCapabilities:a,userConfigFile:o,pipelineArgs:s}=await cT(e),c=ye(`defineConfig`,r.logLevel);if(sT(s))return{context:oT(r),outputPlugins:i,userConfigOptions:r};let l=await Uw({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=Jb({workspace:l.workspace,...l.vscodeConfigFiles!=null&&{vscodeConfigFiles:l.vscodeConfigFiles},...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&&BC(l.aindexDir,c),{context:u,outputPlugins:i,userConfigOptions:r}}const uT=`.agents/skills`,dT=`SKILL.md`;var fT=class extends cx{constructor(){super(`GenericSkillsOutputPlugin`,{outputFileName:dT,treatWorkspaceRootProjectAsProject:!0,skills:{},cleanup:{delete:{project:{dirs:[uT]},global:{dirs:[uT]}}},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,dT),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,uT);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(),uT),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 pT=`AGENTS.md`;var mT=class extends cx{constructor(){super(`AgentsOutputPlugin`,{outputFileName:pT,treatWorkspaceRootProjectAsProject:!0,cleanup:{delete:{project:{files:[pT]}}},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,pT),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 hT=`CLAUDE.md`;var gT=class extends cx{constructor(){super(`ClaudeCodeCLIOutputPlugin`,{globalConfigDir:`.claude`,outputFileName:hT,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:[hT],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 _T=vx.CURSOR,vT=fx.MCP_CONFIG,yT=px.COMMANDS,bT=px.RULES,xT=fx.CURSOR_GLOBAL_RULE,ST=px.CURSOR_SKILLS,CT=fx.SKILL,wT=bx.CURSOR;var TT=class extends cx{constructor(){super(`CursorOutputPlugin`,{globalConfigDir:_T,outputFileName:``,treatWorkspaceRootProjectAsProject:!0,dependsOn:[dx.AgentsOutput],indexignore:yx.CURSOR,commands:{subDir:yT,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:ST},rules:{subDir:bT,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(wT,e=>`.cursor/skills-cursor/${e}`)},global:{dirs:Array.from(wT,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/${ST}/*`)?e:{...e,excludeBasenames:[...wT]})}}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,ST,r);if(t.push({path:u.join(a,CT),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,ST,this.getSkillName(i));t.push({path:u.join(r,vT),scope:n,source:{kind:`skillMcpConfig`,rawContent:i.mcpConfig.rawContent}})}},b=(e,n,r)=>{if(r.length===0)return;let i=Mx(r,this.log);i.size!==0&&t.push({path:u.join(e,vT),scope:n,source:{kind:`mcpConfig`,mcpServers:Nx(i,Px)}})};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,yT,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,yT,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,bT,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=Wy($(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,bT,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,bT,xT),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 wT.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(`
|
|
304
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(`
|
|
305
|
-
`)}};const
|
|
306
|
+
`)}};const ET=`AGENTS.md`;var DT=class extends cx{constructor(){super(`DroidCLIOutputPlugin`,{globalConfigDir:`.factory`,outputFileName:ET,treatWorkspaceRootProjectAsProject:!0,commands:{transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{},cleanup:{delete:{project:{files:[ET],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 OT=`.editorconfig`;var kT=class extends cx{constructor(){super(`EditorConfigOutputPlugin`,{cleanup:{delete:{project:{files:[OT]}}},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,OT),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 AT=`GEMINI.md`;var jT=class extends cx{constructor(){super(`GeminiCLIOutputPlugin`,{globalConfigDir:`.gemini`,outputFileName:AT,treatWorkspaceRootProjectAsProject:!0,cleanup:{delete:{project:{globs:[AT]},global:{files:[`.gemini/GEMINI.md`]}}},capabilities:{prompt:{scopes:[`project`,`global`],singleScope:!1}}})}},MT=class extends cx{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,...Ky(n)];for(let e of r){let n=Gy(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(`
|
|
306
307
|
`)}sanitizeContent(e){return e.split(/\r?\n/).filter(e=>{let t=e.trim();return t.length===0?!0:!(t.startsWith(`#`)&&!t.startsWith(`\\#`))}).join(`
|
|
307
|
-
`).trim()}normalizeContent(e){let t=e.trim();return t.length===0?``:`${t}\n`}};const mT=`AGENTS.md`,hT=`prompts`,gT=`skills`,_T=`.aiassistant`;var vT=class extends Jb{constructor(){super(`JetBrainsAIAssistantCodexOutputPlugin`,{outputFileName:mT,treatWorkspaceRootProjectAsProject:!0,commands:{subDir:hT,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:gT},dependsOn:[Zb.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,_T,`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,gT,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,_T,`codex`);if(f.selectedScope===`project`){let e=$(f.items,n.projectConfig,`commands`);for(let n of e)t.push({path:u.join(i,hT,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,mT),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,hT,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,mT),kind:`file`,scope:`global`},{path:u.join(e,hT),kind:`directory`,scope:`global`},{path:u.join(e,gT),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 yT=`.idea`;var bT=class extends Jb{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(yT);return n===-1?this.joinPath(yT,`codeStyles`,this.basename(t)):t.slice(Math.max(0,n))}};const xT=[`name`,`description`,`developer_instructions`],ST=[`scope`,`seriName`,`argumentHint`,`color`,`namingCase`,`model`];function CT(e,t){let n={...t};return n.name=e,delete n.allowTools,n}const wT={globalConfigDir:`.codex`,outputFileName:`AGENTS.md`,commands:{subDir:`prompts`,scopeRemap:{project:`global`},transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},subagents:{subDir:`agents`,sourceScopes:[`project`],scopeRemap:{global:`project`},ext:`.toml`,artifactFormat:`toml`,bodyFieldName:`developer_instructions`,excludedFrontMatterFields:ST,transformFrontMatter:(e,t)=>CT(rb(e),t.sourceFrontMatter),fieldOrder:xT},cleanup:{delete:{project:{dirs:[`.codex/agents`]},global:{files:[`.codex/AGENTS.md`],dirs:[`.codex/prompts`]}},protect:{global:{dirs:[`.codex/skills/.system`]}}},wslMirrors:[`~/.codex/config.toml`,`~/.codex/auth.json`],dependsOn:[Zb.AgentsOutput],capabilities:{prompt:{scopes:[`global`],singleScope:!1},commands:{scopes:[`global`],singleScope:!0},subagents:{scopes:[`project`],singleScope:!0}}};var TT=class extends Jb{constructor(){super(`CodexCLIOutputPlugin`,wT)}};const ET=`AGENTS.md`,DT=`commands`,OT=`agents`,kT=`skills`;function AT(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 jT=class extends Jb{constructor(){super(`OpencodeCLIOutputPlugin`,{globalConfigDir:`.config/opencode`,outputFileName:ET,treatWorkspaceRootProjectAsProject:!0,commands:{subDir:DT,transformFrontMatter:AT},subagents:{subDir:OT},skills:{subDir:kT},cleanup:{delete:{project:{files:[ET,`.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:[Zb.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,ET),scope:`global`,source:{kind:`globalMemory`,content:n.content}});let h=(e,n,r)=>{if(r.length===0)return;let i=vx(r,this.log);i.size!==0&&t.push({path:u.join(e,`opencode.json`),scope:n,source:{kind:`mcpConfig`,mcpServers:yx(i,xx)}})},g=(e,n,r)=>{for(let i of r){let r=this.validateAndNormalizeSkillName(this.getSkillName(i)),a=u.join(e,kT,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,ET),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,DT,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,OT,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,DT,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,OT,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 MT=`rules`,NT=`commands`,PT=`skills`,FT=`glob`,IT=`glob`;function LT(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 RT=class extends Jb{constructor(){super(`QoderIDEPluginOutputPlugin`,{globalConfigDir:`.qoder`,treatWorkspaceRootProjectAsProject:!0,indexignore:`.qoderignore`,commands:{subDir:NT,transformFrontMatter:LT},skills:{subDir:PT},rules:{subDir:MT,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,PT,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,PT,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,NT,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,NT,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,MT,`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,MT,`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,MT,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=Wy($(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,MT,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,MT,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:FT,[IT]: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:FT,[IT]:e.globs.length>0?e.globs.join(`, `):`**/*`,type:`user_command`};return this.buildMarkdownContent(e.content,n,t)}normalizeRuleScope(e){return e.scope??`global`}};function zT(e){return Fb[e??`Readme`].out}var BT=class extends Jb{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=zT(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 VT=`GLOBAL.md`,HT=`.trae`,UT=`commands`,WT=`skills`;var GT=class extends Jb{constructor(){super(`TraeIDEOutputPlugin`,{globalConfigDir:HT,outputFileName:VT,treatWorkspaceRootProjectAsProject:!0,indexignore:`.traeignore`,commands:{subDir:UT,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:WT},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(),VT),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(`
|
|
308
|
-
`),{alwaysApply:!1,globs:a},e);t.push({path:u.join(r,
|
|
309
|
-
`)}buildProjectRelativeGlobPattern(e){return e.length===0?`**/*`:`${e}/**`}};const
|
|
308
|
+
`).trim()}normalizeContent(e){let t=e.trim();return t.length===0?``:`${t}\n`}};const NT=`AGENTS.md`,PT=`prompts`,FT=`skills`,IT=`.aiassistant`;var LT=class extends cx{constructor(){super(`JetBrainsAIAssistantCodexOutputPlugin`,{outputFileName:NT,treatWorkspaceRootProjectAsProject:!0,commands:{subDir:PT,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:FT},dependsOn:[dx.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,IT,`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,FT,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,IT,`codex`);if(f.selectedScope===`project`){let e=$(f.items,n.projectConfig,`commands`);for(let n of e)t.push({path:u.join(i,PT,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,NT),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,PT,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,NT),kind:`file`,scope:`global`},{path:u.join(e,PT),kind:`directory`,scope:`global`},{path:u.join(e,FT),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 RT=`.idea`;var zT=class extends cx{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(RT);return n===-1?this.joinPath(RT,`codeStyles`,this.basename(t)):t.slice(Math.max(0,n))}};const BT=[`name`,`description`,`developer_instructions`],VT=[`scope`,`seriName`,`argumentHint`,`color`,`namingCase`,`model`];function HT(e){let t={...e};return delete t.allowTools,delete t.allowedTools,t}function UT(e,t){let n=HT(t);return n.name=e,n}const WT={globalConfigDir:`.codex`,outputFileName:`AGENTS.md`,commands:{subDir:`prompts`,scopeRemap:{project:`global`},transformFrontMatter:(e,t)=>HT(t.sourceFrontMatter)},subagents:{subDir:`agents`,sourceScopes:[`project`],scopeRemap:{global:`project`},ext:`.toml`,artifactFormat:`toml`,bodyFieldName:`developer_instructions`,excludedFrontMatterFields:VT,transformFrontMatter:(e,t)=>UT(_b(e),t.sourceFrontMatter),fieldOrder:BT},cleanup:{delete:{project:{dirs:[`.codex/agents`]},global:{files:[`.codex/AGENTS.md`],dirs:[`.codex/prompts`]}},protect:{global:{dirs:[`.codex/skills/.system`]}}},wslMirrors:[`~/.codex/config.toml`,`~/.codex/auth.json`],dependsOn:[dx.AgentsOutput],capabilities:{prompt:{scopes:[`global`],singleScope:!1},commands:{scopes:[`global`],singleScope:!0},subagents:{scopes:[`project`],singleScope:!0}}};var GT=class extends cx{constructor(){super(`CodexCLIOutputPlugin`,WT)}};const KT=`AGENTS.md`,qT=`commands`,JT=`agents`,YT=`skills`;function XT(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 ZT=class extends cx{constructor(){super(`OpencodeCLIOutputPlugin`,{globalConfigDir:`.config/opencode`,outputFileName:KT,treatWorkspaceRootProjectAsProject:!0,commands:{subDir:qT,transformFrontMatter:XT},subagents:{subDir:JT},skills:{subDir:YT},cleanup:{delete:{project:{files:[KT,`.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:[dx.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,KT),scope:`global`,source:{kind:`globalMemory`,content:n.content}});let h=(e,n,r)=>{if(r.length===0)return;let i=Mx(r,this.log);i.size!==0&&t.push({path:u.join(e,`opencode.json`),scope:n,source:{kind:`mcpConfig`,mcpServers:Nx(i,Fx)}})},g=(e,n,r)=>{for(let i of r){let r=this.validateAndNormalizeSkillName(this.getSkillName(i)),a=u.join(e,YT,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,KT),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,qT,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,JT,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,qT,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,JT,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 QT=`rules`,$T=`commands`,eE=`skills`,tE=`glob`,nE=`glob`;function rE(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 iE=class extends cx{constructor(){super(`QoderIDEPluginOutputPlugin`,{globalConfigDir:`.qoder`,treatWorkspaceRootProjectAsProject:!0,indexignore:`.qoderignore`,commands:{subDir:$T,transformFrontMatter:rE},skills:{subDir:eE},rules:{subDir:QT,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,eE,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,eE,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,$T,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,$T,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,QT,`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,QT,`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,QT,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=Wy($(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,QT,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,QT,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:tE,[nE]: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:tE,[nE]:e.globs.length>0?e.globs.join(`, `):`**/*`,type:`user_command`};return this.buildMarkdownContent(e.content,n,t)}normalizeRuleScope(e){return e.scope??`global`}};function aE(e){return Yb[e??`Readme`].out}var oE=class extends cx{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=aE(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 sE=`GLOBAL.md`,cE=`.trae`,lE=`commands`,uE=`skills`;var dE=class extends cx{constructor(){super(`TraeIDEOutputPlugin`,{globalConfigDir:cE,outputFileName:sE,treatWorkspaceRootProjectAsProject:!0,indexignore:`.traeignore`,commands:{subDir:lE,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:uE},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(),sE),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,cE,`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,lE,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,lE,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,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}})}};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 fE=`.vscode`;var pE=class extends cx{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!==sh.VSCode)return this.basename(t);let n=t.indexOf(fE);return n===-1?this.joinPath(fE,this.basename(t)):t.slice(Math.max(0,n))}};const mE=`WARP.md`;var hE=class extends cx{constructor(){super(`WarpIDEOutputPlugin`,{outputFileName:mE,treatWorkspaceRootProjectAsProject:!0,indexignore:`.warpindexignore`,cleanup:{delete:{project:{files:[mE]}}},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,dx.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,mE),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,mE),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 gE=`.codeium/windsurf`,_E=`global_workflows`,vE=`memories`,yE=`skills`,bE=`.windsurf`;var xE=class extends cx{constructor(){super(`WindsurfOutputPlugin`,{globalConfigDir:gE,outputFileName:``,treatWorkspaceRootProjectAsProject:!0,dependsOn:[dx.AgentsOutput],indexignore:`.codeiumignore`,commands:{subDir:_E,transformFrontMatter:(e,t)=>t.sourceFrontMatter??{}},skills:{subDir:yE},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,vE,`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,yE,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,bE);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,bE);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,_E,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,vE,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=Wy($(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,bE,`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(),gE)}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(`
|
|
310
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(`
|
|
311
|
-
`)}};const nE=`GLOBAL.md`;var rE=class extends Jb{constructor(){super(`TraeCNIDEOutputPlugin`,{globalConfigDir:`.trae-cn`,outputFileName:nE,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(),nE),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 iE(e=c.argv){return Ww({pipelineArgs:e,pluginOptions:{plugins:[new Yw,new Zw,new TT,new vT,new cT,new fT,new qw,new jT,new RT,new GT,new rE,new YT,new tE,new oT,new pT,new bT,new uT,new qT,new BT]}})}const aE=new Set([`help`,`version`,`unknown`]);function oE(e){return e.some(e=>e===`--json`||e===`-j`||/^-[^-]*j/.test(e))}function sE(e){let t=e instanceof Error?e.message:String(e);ye(`main`,`silent`).error(j(`main`,e)),c.stdout.write(`${JSON.stringify(Cx({success:!1,filesAffected:0,dirsAffected:0,message:t},ve()))}\n`)}function cE(e){throw Error(`${e} context is unavailable for lightweight commands`)}function lE(e){let t=c.cwd(),n=Pw({workspaceDir:t,...e==null?{}:{logLevel:e}});return{logger:ye(`PluginPipeline`,e),outputPlugins:[],collectedOutputContext:{workspace:{directory:{pathKind:oh.Absolute,path:t,getDirectoryName:()=>u.basename(t)},projects:[]}},userConfigOptions:n,createCleanContext:()=>cE(`cleanup`),createWriteContext:()=>cE(`write`)}}function uE(e){let t=gC(fC(e.filter(e=>e!=null))),n=bC(t);if(aE.has(n.name))return t.logLevel!=null&&ge(t.logLevel),t.jsonFlag&&(ge(`silent`),n=new Sx(n)),{command:n,context:lE(t.logLevel)}}async function dE(e=c.argv){try{let t=uE(e);if(t!=null)return(await t.command.execute(t.context)).success?0:1;let n=new TC(...e),r=await iE(e);return(await n.run(r)).success?0:1}catch(t){return oE(e)?(sE(t),1):(ye(`main`,`error`).error(j(`main`,t)),1)}}const fE=`.src.mdx`,pE=`.mdx`,mE=`skill`,hE=new Set([`project-memory`,`project-child-memory`]);function gE(e){return e.replaceAll(`\\`,`/`)}function _E(e,t){let n=gE(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 vE(e){return!gE(e).includes(`/`)}function yE(e,t){let n=e;return n.includes(Yb.WORKSPACE)&&(n=n.replace(Yb.WORKSPACE,t)),ig(n)}function bE(e={}){let{cwd:t,loadUserConfig:n=!0,pluginOptions:r={}}=e,i={};if(n){let e=fS().load(t);e.found&&(i=Nw(e.config))}let a=Pw(i,r),o=yE(a.workspaceDir,``);return{options:a,workspaceDir:o,aindexDir:u.join(o,a.aindex.dir)}}function xE(e){return e.endsWith(fE)?`${e.slice(0,-8)}${pE}`:u.extname(e)===pE?e:`${e}${pE}`}function SE(e){return e.endsWith(fE)?e.slice(0,-8):e.endsWith(pE)?e.slice(0,-4):e}function CE(e,t){return i.existsSync(e)&&i.statSync(e).isDirectory()?Um.default.sync([...t],{cwd:e,dot:!0,onlyFiles:!0}).map(gE):[]}function wE(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:xE(t),dist:u.join(e.aindexDir,e.options.aindex.globalPrompt.dist)}}}function TE(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:xE(t),dist:u.join(e.aindexDir,e.options.aindex.workspacePrompt.dist)}}}function EE(e,t,n){let r=_E(t,`projectName`);if(!vE(r))throw Error(`projectName must be a single path segment`);let i=n==null?``:_E(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${pE}`),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${fE}`),en:s,dist:u.join(o,`agt${pE}`)},legacyZhPath:s}}function DE(e,t){let n=_E(t,`skillName`);if(!vE(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,`${mE}${fE}`),en:u.join(r,`${mE}${pE}`),dist:u.join(i,`${mE}${pE}`)}}}function OE(e,t,n){let r=_E(t,`skillName`),i=_E(n,`relativeName`);if(!vE(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}${fE}`),en:u.join(a,`${i}${pE}`),dist:u.join(o,`${i}${pE}`)}}}function kE(e,t,n){let r=_E(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}${fE}`),en:u.join(i,`${r}${pE}`),dist:u.join(a,`${r}${pE}`)}}}function AE(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=_E(e.slice(t+1),`promptId`);switch(n){case`project-memory`:if(!vE(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(!vE(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 jE(e,t){let n=AE(e);switch(n.kind){case`global-memory`:return wE(t);case`workspace-memory`:return TE(t);case`project-memory`:if(n.projectName==null)throw Error(`project-memory promptId must include a project name`);return EE(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 EE(t,n.projectName,n.relativeName);case`skill`:if(n.skillName==null)throw Error(`skill promptId must include a skill name`);return DE(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 OE(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 kE(t,n.kind,n.relativeName)}}function ME(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 CE(n,[`**/*${fE}`,`**/*${pE}`]))i.add(SE(e));for(let e of CE(r,[`**/*${pE}`]))i.add(SE(e));return[...i].sort().map(e=>`${t}:${e}`)}function NE(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 CE(r,[`**/*${fE}`,`**/*${pE}`])){let t=SE(e);t!==mE&&o.add(t)}for(let e of CE(i,[`**/*${pE}`])){let t=SE(e);t!==mE&&o.add(t)}for(let t of[...o].sort())a.push(`skill-child-doc:${e}/${t}`)}return a}function PE(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 CE(t,[`**/agt${fE}`,`**/agt${pE}`])){let t=gE(u.posix.dirname(gE(e)));t!==`.`&&r.add(t)}for(let e of CE(n,[`**/agt${pE}`])){let t=gE(u.posix.dirname(gE(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 FE(e){let t=new Set,n=wE(e),r=TE(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 PE(e))t.add(n);for(let n of NE(e))t.add(n);for(let n of ME(e,`command`))t.add(n);for(let n of ME(e,`subagent`))t.add(n);for(let n of ME(e,`rule`))t.add(n);return[...t].sort()}function IE(e){try{return Cp(e).yamlFrontMatter}catch{return}}function LE(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:IE(a);return s!=null&&Object.assign(o,{frontMatter:s}),o}function RE(e,t){return t==null?`missing`:e!=null&&t.mtimeMs<e.mtimeMs?`stale`:`ready`}function zE(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:LE(o,t,a),c=n||r!==e.paths.en?LE(e.paths.en,t):void 0,l=LE(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:RE(s,c),distStatus:RE(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 BE(e,t){return t==null||t.length===0?!0:t.includes(e)}function VE(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 HE(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 UE(e){return hE.has(e.kind)}function WE(e,t){i.mkdirSync(u.dirname(e),{recursive:!0}),i.writeFileSync(e,t,`utf8`)}function GE(e){if(!UE(e)||i.existsSync(e.paths.zh)||e.legacyZhPath==null||!i.existsSync(e.legacyZhPath))return;let t=i.readFileSync(e.legacyZhPath,`utf8`);WE(e.paths.zh,t)}function KE(e){UE(e)&&(e.legacyZhPath==null||e.legacyZhPath===e.paths.zh||i.existsSync(e.legacyZhPath)&&i.rmSync(e.legacyZhPath,{force:!0}))}async function qE(e={}){let t=bE(e);return FE(t).map(e=>zE(jE(e,t),!1)).filter(e=>e!=null).map(HE).filter(t=>BE(t.kind,e.kinds)).filter(t=>BE(t.enStatus,e.enStatus)).filter(t=>BE(t.distStatus,e.distStatus)).filter(t=>VE(t,e.query)).sort((e,t)=>e.promptId.localeCompare(t.promptId))}async function JE(e,t={}){return zE(jE(e,bE(t)),!0)}async function YE(e){let t=bE(e),n=e.locale??`zh`,r=jE(e.promptId,t);n===`zh`?(WE(r.paths.zh,e.content),KE(r)):(GE(r),WE(r.paths.en,e.content));let i=zE(r,!0);if(i==null)throw Error(`Failed to load prompt after write: ${e.promptId}`);return i}async function XE(e){if(e.enContent==null&&e.distContent==null)throw Error(`writePromptArtifacts requires enContent or distContent`);let t=bE(e),n=jE(e.promptId,t);e.enContent!=null&&(GE(n),WE(n.paths.en,e.enContent)),e.distContent!=null&&WE(n.paths.dist,e.distContent);let r=zE(n,!0);if(r==null)throw Error(`Failed to load prompt after write: ${e.promptId}`);return r}async function ZE(e,t={}){return jE(e,bE(t)).paths}function QE(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}}QE()&&dE(c.argv).then(e=>c.exit(e));export{uS as ConfigLoader,sS as DEFAULT_CONFIG_FILE_NAME,cS as DEFAULT_GLOBAL_CONFIG_DIR,Xb as DEFAULT_USER_CONFIG,Yb as PathPlaceholders,TC as PluginPipeline,EC as checkVersionControl,iE as createDefaultPluginConfig,Ww as defineConfig,OC as generateAindex,fS as getConfigLoader,lS as getGlobalConfigPath,JE as getPrompt,oE as isJsonMode,qE as listPrompts,pS as loadUserConfig,Pw as mergeConfig,ZE as resolvePromptDefinition,dE as runCli,YE as upsertPromptSource,Nw as userConfigToPluginOptions,mS as validateGlobalConfig,XE as writePromptArtifacts};
|
|
312
|
+
`)}};const SE=`GLOBAL.md`;var CE=class extends cx{constructor(){super(`TraeCNIDEOutputPlugin`,{globalConfigDir:`.trae-cn`,outputFileName:SE,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(),SE),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 wE(e=c.argv){return lT({pipelineArgs:e,pluginOptions:{plugins:[new mT,new gT,new GT,new LT,new DT,new jT,new fT,new ZT,new iE,new dE,new CE,new hE,new xE,new TT,new MT,new zT,new kT,new pE,new oE]}})}const TE=new Set([`help`,`version`,`unknown`]);function EE(e){return e.some(e=>e===`--json`||e===`-j`||/^-[^-]*j/.test(e))}function DE(e){let t=e instanceof Error?e.message:String(e);ye(`main`,`silent`).error(j(`main`,e)),c.stdout.write(`${JSON.stringify(Lx({success:!1,filesAffected:0,dirsAffected:0,message:t},ve()))}\n`)}function OE(e){throw Error(`${e} context is unavailable for lightweight commands`)}function kE(e){let t=c.cwd(),n=Jw({workspaceDir:t,...e==null?{}:{logLevel:e}});return{logger:ye(`PluginPipeline`,e),outputPlugins:[],collectedOutputContext:{workspace:{directory:{pathKind:oh.Absolute,path:t,getDirectoryName:()=>u.basename(t)},projects:[]}},userConfigOptions:n,createCleanContext:()=>OE(`cleanup`),createWriteContext:()=>OE(`write`)}}function AE(e){let t=AC(EC(e.filter(e=>e!=null))),n=PC(t);if(TE.has(n.name))return t.logLevel!=null&&ge(t.logLevel),t.jsonFlag&&(ge(`silent`),n=new Ix(n)),{command:n,context:kE(t.logLevel)}}async function jE(e=c.argv){try{let t=AE(e);if(t!=null)return(await t.command.execute(t.context)).success?0:1;let n=new zC(...e),r=await wE(e);return(await n.run(r)).success?0:1}catch(t){return EE(e)?(DE(t),1):(ye(`main`,`error`).error(j(`main`,t)),1)}}const ME=`.src.mdx`,NE=`.mdx`,PE=`skill`,FE=new Set([`project-memory`,`project-child-memory`]);function IE(e){return e.replaceAll(`\\`,`/`)}function LE(e,t){let n=IE(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 RE(e){return!IE(e).includes(`/`)}function zE(e,t){let n=e;return n.includes(lx.WORKSPACE)&&(n=n.replace(lx.WORKSPACE,t)),ig(n)}function BE(e={}){let{cwd:t,loadUserConfig:n=!0,pluginOptions:r={}}=e,i={};if(n){let e=ES().load(t);e.found&&(i=qw(e.config))}let a=Jw(i,r),o=zE(a.workspaceDir,``);return{options:a,workspaceDir:o,aindexDir:u.join(o,a.aindex.dir)}}function VE(e){return e.endsWith(ME)?`${e.slice(0,-8)}${NE}`:u.extname(e)===NE?e:`${e}${NE}`}function HE(e){return e.endsWith(ME)?e.slice(0,-8):e.endsWith(NE)?e.slice(0,-4):e}function UE(e,t){return i.existsSync(e)&&i.statSync(e).isDirectory()?Um.default.sync([...t],{cwd:e,dot:!0,onlyFiles:!0}).map(IE):[]}function WE(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:VE(t),dist:u.join(e.aindexDir,e.options.aindex.globalPrompt.dist)}}}function GE(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:VE(t),dist:u.join(e.aindexDir,e.options.aindex.workspacePrompt.dist)}}}function KE(e,t,n){let r=LE(t,`projectName`);if(!RE(r))throw Error(`projectName must be a single path segment`);let i=n==null?``:LE(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${NE}`),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${ME}`),en:s,dist:u.join(o,`agt${NE}`)},legacyZhPath:s}}function qE(e,t){let n=LE(t,`skillName`);if(!RE(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,`${PE}${ME}`),en:u.join(r,`${PE}${NE}`),dist:u.join(i,`${PE}${NE}`)}}}function JE(e,t,n){let r=LE(t,`skillName`),i=LE(n,`relativeName`);if(!RE(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}${ME}`),en:u.join(a,`${i}${NE}`),dist:u.join(o,`${i}${NE}`)}}}function YE(e,t,n){let r=LE(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}${ME}`),en:u.join(i,`${r}${NE}`),dist:u.join(a,`${r}${NE}`)}}}function XE(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=LE(e.slice(t+1),`promptId`);switch(n){case`project-memory`:if(!RE(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(!RE(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 ZE(e,t){let n=XE(e);switch(n.kind){case`global-memory`:return WE(t);case`workspace-memory`:return GE(t);case`project-memory`:if(n.projectName==null)throw Error(`project-memory promptId must include a project name`);return KE(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 KE(t,n.projectName,n.relativeName);case`skill`:if(n.skillName==null)throw Error(`skill promptId must include a skill name`);return qE(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 JE(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 YE(t,n.kind,n.relativeName)}}function QE(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 UE(n,[`**/*${ME}`,`**/*${NE}`]))i.add(HE(e));for(let e of UE(r,[`**/*${NE}`]))i.add(HE(e));return[...i].sort().map(e=>`${t}:${e}`)}function $E(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 UE(r,[`**/*${ME}`,`**/*${NE}`])){let t=HE(e);t!==PE&&o.add(t)}for(let e of UE(i,[`**/*${NE}`])){let t=HE(e);t!==PE&&o.add(t)}for(let t of[...o].sort())a.push(`skill-child-doc:${e}/${t}`)}return a}function eD(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 UE(t,[`**/agt${ME}`,`**/agt${NE}`])){let t=IE(u.posix.dirname(IE(e)));t!==`.`&&r.add(t)}for(let e of UE(n,[`**/agt${NE}`])){let t=IE(u.posix.dirname(IE(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 tD(e){let t=new Set,n=WE(e),r=GE(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 eD(e))t.add(n);for(let n of $E(e))t.add(n);for(let n of QE(e,`command`))t.add(n);for(let n of QE(e,`subagent`))t.add(n);for(let n of QE(e,`rule`))t.add(n);return[...t].sort()}function nD(e){try{return Cp(e).yamlFrontMatter}catch{return}}function rD(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:nD(a);return s!=null&&Object.assign(o,{frontMatter:s}),o}function iD(e,t){return t==null?`missing`:e!=null&&t.mtimeMs<e.mtimeMs?`stale`:`ready`}function aD(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:rD(o,t,a),c=n||r!==e.paths.en?rD(e.paths.en,t):void 0,l=rD(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:iD(s,c),distStatus:iD(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 oD(e,t){return t==null||t.length===0?!0:t.includes(e)}function sD(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 cD(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 lD(e){return FE.has(e.kind)}function uD(e,t){i.mkdirSync(u.dirname(e),{recursive:!0}),i.writeFileSync(e,t,`utf8`)}function dD(e){if(!lD(e)||i.existsSync(e.paths.zh)||e.legacyZhPath==null||!i.existsSync(e.legacyZhPath))return;let t=i.readFileSync(e.legacyZhPath,`utf8`);uD(e.paths.zh,t)}function fD(e){lD(e)&&(e.legacyZhPath==null||e.legacyZhPath===e.paths.zh||i.existsSync(e.legacyZhPath)&&i.rmSync(e.legacyZhPath,{force:!0}))}async function pD(e={}){let t=BE(e);return tD(t).map(e=>aD(ZE(e,t),!1)).filter(e=>e!=null).map(cD).filter(t=>oD(t.kind,e.kinds)).filter(t=>oD(t.enStatus,e.enStatus)).filter(t=>oD(t.distStatus,e.distStatus)).filter(t=>sD(t,e.query)).sort((e,t)=>e.promptId.localeCompare(t.promptId))}async function mD(e,t={}){return aD(ZE(e,BE(t)),!0)}async function hD(e){let t=BE(e),n=e.locale??`zh`,r=ZE(e.promptId,t);n===`zh`?(uD(r.paths.zh,e.content),fD(r)):(dD(r),uD(r.paths.en,e.content));let i=aD(r,!0);if(i==null)throw Error(`Failed to load prompt after write: ${e.promptId}`);return i}async function gD(e){if(e.enContent==null&&e.distContent==null)throw Error(`writePromptArtifacts requires enContent or distContent`);let t=BE(e),n=ZE(e.promptId,t);e.enContent!=null&&(dD(n),uD(n.paths.en,e.enContent)),e.distContent!=null&&uD(n.paths.dist,e.distContent);let r=aD(n,!0);if(r==null)throw Error(`Failed to load prompt after write: ${e.promptId}`);return r}async function _D(e,t={}){return ZE(e,BE(t)).paths}function vD(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}}vD()&&jE(c.argv).then(e=>c.exit(e));export{wS as ConfigLoader,xS as DEFAULT_CONFIG_FILE_NAME,SS as DEFAULT_GLOBAL_CONFIG_DIR,ux as DEFAULT_USER_CONFIG,lx as PathPlaceholders,zC as PluginPipeline,BC as checkVersionControl,wE as createDefaultPluginConfig,lT as defineConfig,HC as generateAindex,ES as getConfigLoader,CS as getGlobalConfigPath,mD as getPrompt,EE as isJsonMode,pD as listPrompts,DS as loadUserConfig,Jw as mergeConfig,_D as resolvePromptDefinition,jE as runCli,hD as upsertPromptSource,qw as userConfigToPluginOptions,OS as validateGlobalConfig,gD as writePromptArtifacts};
|