agentsmesh 0.27.0 → 0.28.0

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/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {resolve,join,sep,dirname,relative,basename,extname,normalize,win32,posix,isAbsolute}from'path';import {rm as rm$1,readFile,readdir,stat,mkdir,writeFile,rename,lstat,unlink,chmod,access,realpath,readlink,symlink,mkdtemp,cp as cp$1,copyFile}from'fs/promises';import {setTimeout as setTimeout$1}from'timers/promises';import {realpathSync,rmSync,existsSync,mkdtempSync,readdirSync,symlinkSync,mkdirSync,readFileSync,writeFileSync,renameSync,constants,statSync,appendFileSync}from'fs';import {z as z$1}from'zod';import {stringify,parse,parseDocument,YAMLSeq,YAMLMap}from'yaml';import {homedir,tmpdir,hostname}from'os';import {fileURLToPath,URL,pathToFileURL}from'url';import {execFile}from'child_process';import {promisify}from'util';import*as aO from'tar';import {createHash}from'crypto';import {parse as parse$1}from'smol-toml';import {Buffer as Buffer$1}from'buffer';import {createRequire}from'module';import*as Yt from'@clack/prompts';import b7 from'picomatch';import {createTwoFilesPatch}from'diff';import bte from'chokidar';import*as QH from'readline';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListToolsRequestSchema,CallToolRequestSchema,ListResourcesRequestSchema,ReadResourceRequestSchema}from'@modelcontextprotocol/sdk/types.js';import {toJSONSchema}from'zod/v4/core';var EE=Object.defineProperty;var s=(e,t)=>EE(e,"name",{value:t,configurable:true});var d=(e,t)=>()=>(e&&(t=e(e=0)),t);var s_=(e,t)=>{for(var r in t)EE(e,r,{get:t[r],enumerable:true});};function fJ(){let e=process.env.NO_COLOR;return e!==void 0&&e!==""}function gJ(){let e=process.env.FORCE_COLOR;if(e!==void 0)return e!=="0"&&e!=="false"}function ki(e=process.stdout){let t=gJ();return t!==void 0?t:fJ()?false:e.isTTY===true}var fp=d(()=>{s(fJ,"noColorRequested");s(gJ,"forceColorRequested");s(ki,"colorEnabled");});function bE(){xa=true;}function AE(){wE=true;}function Gd(){return wE?process.stderr:process.stdout}function sc(e){Gd().write(e);}function gp(e,t,r){return ki(r)?`${e}${t}${ic.reset}`:t}function hJ(e,t){let r=[...e].length;return e+" ".repeat(Math.max(0,t-r))}var ic,xa,wE,S,fe=d(()=>{fp();ic={green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",reset:"\x1B[0m"},xa=false,wE=false;s(bE,"muteLogger");s(AE,"redirectLoggerToStderr");s(Gd,"outStream");s(sc,"out");s(gp,"c");s(hJ,"pad");S={info(e){xa||sc(gp(ic.cyan,e,Gd())+`
2
+ import {resolve,join,sep,dirname,relative,basename,extname,normalize,win32,posix,isAbsolute}from'path';import {rm as rm$1,readFile,readdir,stat,mkdir,writeFile,rename,lstat,unlink,chmod,access,realpath,readlink,symlink,mkdtemp,cp as cp$1,copyFile}from'fs/promises';import {setTimeout as setTimeout$1}from'timers/promises';import {realpathSync,rmSync,existsSync,mkdtempSync,readdirSync,symlinkSync,mkdirSync,readFileSync,writeFileSync,renameSync,constants,statSync,appendFileSync}from'fs';import {z as z$1}from'zod';import {stringify,parse,parseDocument,YAMLSeq,YAMLMap}from'yaml';import {homedir,tmpdir,hostname}from'os';import {fileURLToPath,URL,pathToFileURL}from'url';import {execFile}from'child_process';import {promisify}from'util';import*as aO from'tar';import {createHash}from'crypto';import {parse as parse$1}from'smol-toml';import {Buffer as Buffer$1}from'buffer';import {createRequire}from'module';import*as Yt from'@clack/prompts';import b7 from'picomatch';import {createTwoFilesPatch}from'diff';import Tte from'chokidar';import*as QH from'readline';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListToolsRequestSchema,CallToolRequestSchema,ListResourcesRequestSchema,ReadResourceRequestSchema}from'@modelcontextprotocol/sdk/types.js';import {toJSONSchema}from'zod/v4/core';var EE=Object.defineProperty;var s=(e,t)=>EE(e,"name",{value:t,configurable:true});var d=(e,t)=>()=>(e&&(t=e(e=0)),t);var s_=(e,t)=>{for(var r in t)EE(e,r,{get:t[r],enumerable:true});};function fJ(){let e=process.env.NO_COLOR;return e!==void 0&&e!==""}function gJ(){let e=process.env.FORCE_COLOR;if(e!==void 0)return e!=="0"&&e!=="false"}function ki(e=process.stdout){let t=gJ();return t!==void 0?t:fJ()?false:e.isTTY===true}var fp=d(()=>{s(fJ,"noColorRequested");s(gJ,"forceColorRequested");s(ki,"colorEnabled");});function bE(){xa=true;}function AE(){wE=true;}function Gd(){return wE?process.stderr:process.stdout}function sc(e){Gd().write(e);}function gp(e,t,r){return ki(r)?`${e}${t}${ic.reset}`:t}function hJ(e,t){let r=[...e].length;return e+" ".repeat(Math.max(0,t-r))}var ic,xa,wE,S,fe=d(()=>{fp();ic={green:"\x1B[32m",red:"\x1B[31m",yellow:"\x1B[33m",cyan:"\x1B[36m",reset:"\x1B[0m"},xa=false,wE=false;s(bE,"muteLogger");s(AE,"redirectLoggerToStderr");s(Gd,"outStream");s(sc,"out");s(gp,"c");s(hJ,"pad");S={info(e){xa||sc(gp(ic.cyan,e,Gd())+`
3
3
  `);},warn(e){xa||process.stderr.write(gp(ic.yellow,"\u26A0 ",process.stderr)+e+`
4
4
  `);},error(e){xa||process.stderr.write(gp(ic.red,"\u2717 ",process.stderr)+e+`
5
5
  `);},success(e){xa||sc(gp(ic.green,"\u2713 ",Gd())+e+`
@@ -219,16 +219,16 @@ Fix: add a precise --trigger-file <glob> (preferred) or a valid --trigger-cmd <r
219
219
  `).filter(i=>i.trim().length>0);if(r.length<=t)return;let n=r.slice(r.length-t),o=`${e}.${process.pid}.tmp`;writeFileSync(o,`${n.join(`
220
220
  `)}
221
221
  `,"utf8"),renameSync(o,e);}s(jK,"capJsonl");function ey(e){if(!existsSync(e))return [];let t=[];for(let r of readFileSync(e,"utf8").split(`
222
- `))if(r.trim().length!==0)try{t.push(JSON.parse(r));}catch{}return t}s(ey,"readJsonl");var cee=5e3,mee=2e6,pee="AGENTSMESH_LESSONS_TELEMETRY",uee="AGENTSMESH_SESSION_ID";function Wm(e=process.env){let t=e[uee];return t!==void 0&&t.trim().length>0?t:void 0}s(Wm,"sessionId");function cd(e){return join(je(e).base,"recall-log.jsonl")}s(cd,"recallLogPath");function Ra(e=process.env){return e[pee]==="1"}s(Ra,"isTelemetryEnabled");function UK(e,t,r=process.env){Ra(r)&&Zh(cd(e),t,{maxRecords:cee,trimTriggerBytes:mee});}s(UK,"appendRecallRecord");function BK(e){return qh(cd(e))}s(BK,"recallLogExists");function KK(e){return ey(cd(e))}s(KK,"readRecallLog");var fee=5e3,gee=2e6;function md(e){return join(je(e).base,"capture-log.jsonl")}s(md,"captureLogPath");function hee(e,t,r=process.env){Ra(r)&&Zh(md(e),t,{maxRecords:fee,trimTriggerBytes:gee});}s(hee,"appendCaptureRecord");function WK(e){return qh(md(e))}s(WK,"captureLogExists");function HK(e){return ey(md(e))}s(HK,"readCaptureLog");function GL(e,t,r,n=process.env){if(!Ra(n))return;let o=Wm(n);hee(e,{ts:new Date().toISOString(),isNewLesson:r?.isNewLesson??false,isNewTopic:r?.isNewTopic??false,newTriggerCount:r?.newTriggerIds.length??0,triggerKinds:t,blocked:r===null,warningCodes:r?.warnings.map(i=>i.code)??[],...o!==void 0?{session:o}:{},...r!==null?{lessonId:r.id}:{}},n);}s(GL,"recordCapture");function yee(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>0)}s(yee,"splitTokens");function _ee(e){let t=[];return e.file!==void 0&&t.push(e.file),e.command!==void 0&&t.push(e.command),t.length===0?[]:yee(t.join(" "))}s(_ee,"deriveHaystackTokens");function See(e,t){if(e.length===0)return false;for(let r=0;r+e.length<=t.length;r+=1){let n=true;for(let o=0;o<e.length;o+=1)if(t[r+o]!==e[o]){n=false;break}if(n)return true}return false}s(See,"containsRun");function zK(e,t){return t.keyword!==void 0&&t.keyword.toLowerCase().includes(e.toLowerCase())?true:See(jt(e),_ee(t))}s(zK,"keywordMatches");var Iee=5e6;function Hm(e,t){if(t.file===void 0&&t.command===void 0&&t.keyword===void 0)return [];let r=jL(e,t),n=[];for(let[o,i]of Object.entries(e.lessons))i.status==="active"&&i.triggers.some(a=>r.has(a))&&n.push({id:o,lesson:i});return n.sort((o,i)=>o.id<i.id?-1:1),n}s(Hm,"queryLessons");function $L(e,t){let r={file_glob:new Set,command_pattern:new Set,keyword:new Set},n={remaining:Iee};for(let[o,i]of Object.entries(e.triggers))kee(i,t,n)&&r[i.kind].add(o);return r}s($L,"collectMatchedTriggersByKind");function jL(e,t){let{file_glob:r,command_pattern:n,keyword:o}=$L(e,t);return new Set([...r,...n,...o])}s(jL,"collectMatchedTriggerIds");function kee(e,t,r){switch(e.kind){case "file_glob":return t.file===void 0?false:b7(e.pattern,{dot:true})(t.file);case "command_pattern":{if(t.command===void 0)return false;let n=LK(e.pattern);return n!==null&&n.test(t.command,r)}case "keyword":return zK(e.pattern,t)}}s(kee,"triggerMatches");function ty(e){let t=new Map;for(let r of Object.values(e.lessons))if(r.status==="active")for(let n of r.triggers)t.set(n,(t.get(n)??0)+1);return t}s(ty,"buildFanout");function VK(e){let t=new Map;for(let{lesson:n}of e)for(let o of n.topics)t.set(o,(t.get(o)??0)+1);let r=new Map;for(let{id:n,lesson:o}of e){let i=0;for(let a of o.topics)i=Math.max(i,t.get(a));r.set(n,i);}return r}s(VK,"buildTopicCoherence");var pd=10,ry=400,UL=60,Lee=3,Cee=2,Eee=1;function BL(e){let t=[...e].sort((i,a)=>a.value!==i.value?a.value-i.value:i.id<a.id?-1:1),r=new Map,n=null,o=0;return t.forEach((i,a)=>{let l=n!==null&&i.value===n?o:a+1;r.set(i.id,l),n=i.value,o=l;}),r}s(BL,"rankMap");function Yl(e){return Math.ceil(e.length/4)}s(Yl,"estTokens");function zm(e,t,r,n={}){if(r.length===0)return [];let o=eK(t),i=tK(e),a=ty(e),l=VK(r),c=jL(e,t),m=r.map(({id:h,lesson:y})=>{let _=y.triggers.filter(k=>c.has(k)),R=0;for(let k of _)R=Math.max(R,1/a.get(k));return {id:h,lesson:y,bm25:rK(o,y.rule,i),specificity:R,topicCoherence:l.get(h),matchedTriggers:_}}),p=BL(m.map(h=>({id:h.id,value:h.bm25}))),u=BL(m.map(h=>({id:h.id,value:h.specificity}))),f=BL(m.map(h=>({id:h.id,value:h.topicCoherence}))),g=m.map(h=>({id:h.id,lesson:h.lesson,score:Lee/(UL+u.get(h.id))+Cee/(UL+f.get(h.id))+Eee/(UL+p.get(h.id)),reason:{matchedTriggers:h.matchedTriggers,bm25:h.bm25,specificity:h.specificity,topicCoherence:h.topicCoherence}})).sort((h,y)=>{if(y.score!==h.score)return y.score-h.score;let _=h.lesson.createdAt,R=y.lesson.createdAt;return _!==R?_<R?1:-1:h.id<y.id?-1:1});return Oee(g,n)}s(zm,"rankLessons");function Oee(e,t){let r=e;if(t.limit!==void 0&&t.limit>=0&&(r=r.slice(0,t.limit)),t.maxTokens!==void 0&&r.length>0){let n=[r[0]],o=Yl(r[0].lesson.rule);for(let i of r.slice(1)){let a=Yl(i.lesson.rule);if(o+a>t.maxTokens)break;o+=a,n.push(i);}r=n;}return r}s(Oee,"applyCaps");function XK(){return {recallLimit:pd,recallMaxTokens:ry,autoPrune:false}}s(XK,"defaultLessonsConfig");function ny(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}s(ny,"positiveInt");function QK(e){let t=je(e).config;if(!existsSync(t))return null;let r;try{r=JSON.parse(readFileSync(t,"utf8"));}catch{return "lessons config.json is not valid JSON \u2014 using built-in recall defaults. Fix or delete .agentsmesh/lessons/config.json."}if(typeof r!="object"||r===null)return "lessons config.json is not a JSON object \u2014 using built-in recall defaults.";let n=r,o=[];return "recallLimit"in n&&ny(n.recallLimit)===null&&o.push("recallLimit"),"recallMaxTokens"in n&&ny(n.recallMaxTokens)===null&&o.push("recallMaxTokens"),o.length>0?`lessons config.json has invalid ${o.join(" and ")} (expected a positive integer) \u2014 using the default for ${o.length===1?"it":"them"}.`:null}s(QK,"lessonsConfigWarning");function oy(e){let t={limit:pd,maxTokens:ry},r=je(e).config;if(!existsSync(r))return t;try{let n=JSON.parse(readFileSync(r,"utf8"));if(typeof n!="object"||n===null)return t;let o=n;return {limit:ny(o.recallLimit)??t.limit,maxTokens:ny(o.recallMaxTokens)??t.maxTokens}}catch{return t}}s(oy,"loadRecallConfig");var ZK="agentsmesh lessons hook",Dee="Edit|Write|Bash";function eW(e){let t=join(e,".agentsmesh","hooks.yaml");if(!existsSync(t))return false;let r=parseDocument(readFileSync(t,"utf8")),n=r.get("PostToolUse"),o=n instanceof YAMLSeq?n:new YAMLSeq;return o.items.some(a=>a instanceof YAMLMap&&a.get("command")===ZK)?false:(o.add(r.createNode({matcher:Dee,type:"command",command:ZK})),r.set("PostToolUse",o),writeFileSync(t,String(r),"utf8"),true)}s(eW,"injectRecallHook");b();async function sy(e,t){let r=join(e,".gitignore"),n=await I(r)??"",o=new Set(n.split(`
223
- `).map(l=>l.trim()).filter(l=>l.length>0&&!l.startsWith("#"))),i=t.filter(l=>!vee(l,o));if(i.length===0)return false;let a=n.endsWith(`
222
+ `))if(r.trim().length!==0)try{t.push(JSON.parse(r));}catch{}return t}s(ey,"readJsonl");var cee=5e3,mee=2e6,pee="AGENTSMESH_LESSONS_TELEMETRY",uee="AGENTSMESH_SESSION_ID";function Wm(e=process.env){let t=e[uee];return t!==void 0&&t.trim().length>0?t:void 0}s(Wm,"sessionId");function cd(e){return join(je(e).base,"recall-log.jsonl")}s(cd,"recallLogPath");function Ra(e=process.env){return e[pee]==="1"}s(Ra,"isTelemetryEnabled");function UK(e,t,r=process.env){Ra(r)&&Zh(cd(e),t,{maxRecords:cee,trimTriggerBytes:mee});}s(UK,"appendRecallRecord");function BK(e){return qh(cd(e))}s(BK,"recallLogExists");function KK(e){return ey(cd(e))}s(KK,"readRecallLog");var fee=5e3,gee=2e6;function md(e){return join(je(e).base,"capture-log.jsonl")}s(md,"captureLogPath");function hee(e,t,r=process.env){Ra(r)&&Zh(md(e),t,{maxRecords:fee,trimTriggerBytes:gee});}s(hee,"appendCaptureRecord");function WK(e){return qh(md(e))}s(WK,"captureLogExists");function HK(e){return ey(md(e))}s(HK,"readCaptureLog");function GL(e,t,r,n=process.env){if(!Ra(n))return;let o=Wm(n);hee(e,{ts:new Date().toISOString(),isNewLesson:r?.isNewLesson??false,isNewTopic:r?.isNewTopic??false,newTriggerCount:r?.newTriggerIds.length??0,triggerKinds:t,blocked:r===null,warningCodes:r?.warnings.map(i=>i.code)??[],...o!==void 0?{session:o}:{},...r!==null?{lessonId:r.id}:{}},n);}s(GL,"recordCapture");function yee(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>0)}s(yee,"splitTokens");function _ee(e){let t=[];return e.file!==void 0&&t.push(e.file),e.command!==void 0&&t.push(e.command),t.length===0?[]:yee(t.join(" "))}s(_ee,"deriveHaystackTokens");function See(e,t){if(e.length===0)return false;for(let r=0;r+e.length<=t.length;r+=1){let n=true;for(let o=0;o<e.length;o+=1)if(t[r+o]!==e[o]){n=false;break}if(n)return true}return false}s(See,"containsRun");function zK(e,t){return t.keyword!==void 0&&t.keyword.toLowerCase().includes(e.toLowerCase())?true:See(jt(e),_ee(t))}s(zK,"keywordMatches");var Iee=5e6;function Hm(e,t){if(t.file===void 0&&t.command===void 0&&t.keyword===void 0)return [];let r=jL(e,t),n=[];for(let[o,i]of Object.entries(e.lessons))i.status==="active"&&i.triggers.some(a=>r.has(a))&&n.push({id:o,lesson:i});return n.sort((o,i)=>o.id<i.id?-1:1),n}s(Hm,"queryLessons");function $L(e,t){let r={file_glob:new Set,command_pattern:new Set,keyword:new Set},n={remaining:Iee};for(let[o,i]of Object.entries(e.triggers))kee(i,t,n)&&r[i.kind].add(o);return r}s($L,"collectMatchedTriggersByKind");function jL(e,t){let{file_glob:r,command_pattern:n,keyword:o}=$L(e,t);return new Set([...r,...n,...o])}s(jL,"collectMatchedTriggerIds");function kee(e,t,r){switch(e.kind){case "file_glob":return t.file===void 0?false:b7(e.pattern,{dot:true})(t.file);case "command_pattern":{if(t.command===void 0)return false;let n=LK(e.pattern);return n!==null&&n.test(t.command,r)}case "keyword":return zK(e.pattern,t)}}s(kee,"triggerMatches");function ty(e){let t=new Map;for(let r of Object.values(e.lessons))if(r.status==="active")for(let n of r.triggers)t.set(n,(t.get(n)??0)+1);return t}s(ty,"buildFanout");function VK(e){let t=new Map;for(let{lesson:n}of e)for(let o of n.topics)t.set(o,(t.get(o)??0)+1);let r=new Map;for(let{id:n,lesson:o}of e){let i=0;for(let a of o.topics)i=Math.max(i,t.get(a));r.set(n,i);}return r}s(VK,"buildTopicCoherence");var pd=10,ry=400,UL=60,Lee=3,Cee=2,Eee=1;function BL(e){let t=[...e].sort((i,a)=>a.value!==i.value?a.value-i.value:i.id<a.id?-1:1),r=new Map,n=null,o=0;return t.forEach((i,a)=>{let l=n!==null&&i.value===n?o:a+1;r.set(i.id,l),n=i.value,o=l;}),r}s(BL,"rankMap");function Yl(e){return Math.ceil(e.length/4)}s(Yl,"estTokens");function zm(e,t,r,n={}){if(r.length===0)return [];let o=eK(t),i=tK(e),a=ty(e),l=VK(r),c=jL(e,t),m=r.map(({id:h,lesson:y})=>{let _=y.triggers.filter(k=>c.has(k)),R=0;for(let k of _)R=Math.max(R,1/a.get(k));return {id:h,lesson:y,bm25:rK(o,y.rule,i),specificity:R,topicCoherence:l.get(h),matchedTriggers:_}}),p=BL(m.map(h=>({id:h.id,value:h.bm25}))),u=BL(m.map(h=>({id:h.id,value:h.specificity}))),f=BL(m.map(h=>({id:h.id,value:h.topicCoherence}))),g=m.map(h=>({id:h.id,lesson:h.lesson,score:Lee/(UL+u.get(h.id))+Cee/(UL+f.get(h.id))+Eee/(UL+p.get(h.id)),reason:{matchedTriggers:h.matchedTriggers,bm25:h.bm25,specificity:h.specificity,topicCoherence:h.topicCoherence}})).sort((h,y)=>{if(y.score!==h.score)return y.score-h.score;let _=h.lesson.createdAt,R=y.lesson.createdAt;return _!==R?_<R?1:-1:h.id<y.id?-1:1});return Oee(g,n)}s(zm,"rankLessons");function Oee(e,t){let r=e;if(t.limit!==void 0&&t.limit>=0&&(r=r.slice(0,t.limit)),t.maxTokens!==void 0&&r.length>0){let n=[r[0]],o=Yl(r[0].lesson.rule);for(let i of r.slice(1)){let a=Yl(i.lesson.rule);if(o+a>t.maxTokens)break;o+=a,n.push(i);}r=n;}return r}s(Oee,"applyCaps");function XK(){return {recallLimit:pd,recallMaxTokens:ry,autoPrune:false}}s(XK,"defaultLessonsConfig");function ny(e){return typeof e=="number"&&Number.isInteger(e)&&e>0?e:null}s(ny,"positiveInt");function QK(e){let t=je(e).config;if(!existsSync(t))return null;let r;try{r=JSON.parse(readFileSync(t,"utf8"));}catch{return "lessons config.json is not valid JSON \u2014 using built-in recall defaults. Fix or delete .agentsmesh/lessons/config.json."}if(typeof r!="object"||r===null)return "lessons config.json is not a JSON object \u2014 using built-in recall defaults.";let n=r,o=[];return "recallLimit"in n&&ny(n.recallLimit)===null&&o.push("recallLimit"),"recallMaxTokens"in n&&ny(n.recallMaxTokens)===null&&o.push("recallMaxTokens"),o.length>0?`lessons config.json has invalid ${o.join(" and ")} (expected a positive integer) \u2014 using the default for ${o.length===1?"it":"them"}.`:null}s(QK,"lessonsConfigWarning");function oy(e){let t={limit:pd,maxTokens:ry},r=je(e).config;if(!existsSync(r))return t;try{let n=JSON.parse(readFileSync(r,"utf8"));if(typeof n!="object"||n===null)return t;let o=n;return {limit:ny(o.recallLimit)??t.limit,maxTokens:ny(o.recallMaxTokens)??t.maxTokens}}catch{return t}}s(oy,"loadRecallConfig");var ZK="agentsmesh lessons hook",Dee="Edit|Write|Bash",Nee=["PreToolUse","PostToolUse"];function vee(e,t){let r=e.get(t),n=r instanceof YAMLSeq?r:new YAMLSeq;return n.items.some(i=>i instanceof YAMLMap&&i.get("command")===ZK)?false:(n.add(e.createNode({matcher:Dee,type:"command",command:ZK})),e.set(t,n),true)}s(vee,"injectEvent");function eW(e){let t=join(e,".agentsmesh","hooks.yaml");if(!existsSync(t))return false;let r=parseDocument(readFileSync(t,"utf8")),n=false;for(let o of Nee)vee(r,o)&&(n=true);return n&&writeFileSync(t,String(r),"utf8"),n}s(eW,"injectRecallHook");b();async function sy(e,t){let r=join(e,".gitignore"),n=await I(r)??"",o=new Set(n.split(`
223
+ `).map(l=>l.trim()).filter(l=>l.length>0&&!l.startsWith("#"))),i=t.filter(l=>!Mee(l,o));if(i.length===0)return false;let a=n.endsWith(`
224
224
  `)||n===""?"":`
225
225
  `;return await L(r,n+a+i.join(`
226
226
  `)+`
227
- `),true}s(sy,"ensureGitignoreEntries");function vee(e,t){if(t.has(e))return true;let r=e.replace(/\/$/,"");for(;r.includes("/")&&(r=r.slice(0,r.lastIndexOf("/")),r!=="");)if(t.has(r)||t.has(`${r}/`)||t.has(`${r}/**`))return true;return false}s(vee,"isCoveredByExisting");Be();var Fee=['## Lessons (BLOCKING REQUIREMENT \u2014 MUST run both, no exceptions; the user will check)\n\nGraph `.agentsmesh/lessons/lessons.json` is canonical \u2014 never hand-edit. Manual: the `lessons` skill.\n\n**Recall \u2014 MUST run before every file edit and every state-changing command** (build/test/install/migrate/git-write): `agentsmesh lessons query --file <path> --cmd <command>`, then apply every rule. Pure-read commands (cat/ls/grep/git-log) and the recall query itself are exempt.\n\n**Capture \u2014 MUST run immediately after any failure** (a failing test/CI/lint/typecheck, a code review, a user correction, a regression, or a wrong assumption \u2014 yours or anyone\'s): `agentsmesh lessons add "<rule>" --topic <id> --trigger-file <glob> --evidence <sha|lesson-id>`.\n\nNo shell? Use the `lessons_query` / `lessons_add` MCP tools. Skip either and the system does not exist.'],KL=`${Pp}
227
+ `),true}s(sy,"ensureGitignoreEntries");function Mee(e,t){if(t.has(e))return true;let r=e.replace(/\/$/,"");for(;r.includes("/")&&(r=r.slice(0,r.lastIndexOf("/")),r!=="");)if(t.has(r)||t.has(`${r}/`)||t.has(`${r}/**`))return true;return false}s(Mee,"isCoveredByExisting");Be();var Gee=['## Lessons (BLOCKING REQUIREMENT \u2014 MUST run both, no exceptions; the user will check)\n\nGraph `.agentsmesh/lessons/lessons.json` is canonical \u2014 never hand-edit. Manual: the `lessons` skill.\n\n**Recall \u2014 MUST run before every file edit and every state-changing command** (build/test/install/migrate/git-write): `agentsmesh lessons query --file <path> --cmd <command>`, then apply every rule. Pure-read commands (cat/ls/grep/git-log) and the recall query itself are exempt.\n\n**Capture \u2014 MUST run immediately after any failure** (a failing test/CI/lint/typecheck, a code review, a user correction, a regression, or a wrong assumption \u2014 yours or anyone\'s): `agentsmesh lessons add "<rule>" --topic <id> --trigger-file <glob> --evidence <sha|lesson-id>`.\n\nNo shell? Use the `lessons_query` / `lessons_add` MCP tools. Skip either and the system does not exist.'],KL=`${Pp}
228
228
  ${ld}
229
- ${G_}`;function tW(e){let t=Mee(e);return Rf(t,KL)}s(tW,"appendLessonsParagraph");function Mee(e){let t=Dp(e,Pp,G_);return Gee(t).trim()}s(Mee,"stripLessonsParagraph");function Gee(e){return [ld,...Fee].reduce((t,r)=>t.replace(`
229
+ ${G_}`;function tW(e){let t=$ee(e);return Rf(t,KL)}s(tW,"appendLessonsParagraph");function $ee(e){let t=Dp(e,Pp,G_);return jee(t).trim()}s($ee,"stripLessonsParagraph");function jee(e){return [ld,...Gee].reduce((t,r)=>t.replace(`
230
230
 
231
- ${r}`,"").replace(r,""),e)}s(Gee,"stripRawProceduralRule");U();var WL="lessons",$ee="Use when about to edit a file or run a state-changing command, or after any failure, correction, or surprising result.",jee=`# Lessons \u2014 operating manual (Iron Law)
231
+ ${r}`,"").replace(r,""),e)}s(jee,"stripRawProceduralRule");U();var WL="lessons",Uee="Use when about to edit a file or run a state-changing command, or after any failure, correction, or surprising result.",Bee=`# Lessons \u2014 operating manual (Iron Law)
232
232
 
233
233
  ## The Iron Law
234
234
 
@@ -275,9 +275,9 @@ deprecate, merge, untrigger, strip-markers, prune, journal, validate, stats, imp
275
275
 
276
276
  The final response MUST carry the receipt: \`Lesson: captured <id>\` or \`Lesson: none\`.
277
277
  No receipt = task incomplete. Do not capture one-off facts, task summaries, or project
278
- context \u2014 only reusable imperative rules with an effective trigger.`,rW=x({name:WL,description:$ee},jee);async function Ia(e){let t=je(e),r=[],n=[],o=[];mkdirSync(t.base,{recursive:true}),await gt(e),existsSync(t.graph)?o.push(t.graph):(await Vl(e,()=>{}),r.push(t.graph)),Bee(e,r,o),Uee(e,r,n,o);let i=Kee(e),a=eW(e),l=await sy(e,[Jl(e,cd(e)),Jl(e,md(e))]);return {created:r,updated:n,skipped:o,rootRuleUpdated:i,gitignoreUpdated:l,recallHookInjected:a}}s(Ia,"scaffoldLessons");function Uee(e,t,r,n){let o=join(e,".agentsmesh/skills",WL,"SKILL.md"),i=`${rW}
279
- `;if(!existsSync(o)){mkdirSync(dirname(o),{recursive:true}),writeFileSync(o,i,"utf8"),t.push(o);return}if(readFileSync(o,"utf8")===i){n.push(o);return}writeFileSync(o,i,"utf8"),r.push(o);}s(Uee,"seedLessonsSkill");function Bee(e,t,r){let n=je(e).config;if(existsSync(n)){r.push(n);return}mkdirSync(dirname(n),{recursive:true}),writeFileSync(n,`${JSON.stringify(XK(),null,2)}
280
- `,"utf8"),t.push(n);}s(Bee,"seedLessonsConfig");function Kee(e){let t=join(e,".agentsmesh/rules/_root.md");if(!existsSync(t)){mkdirSync(dirname(t),{recursive:true});let o=`---
278
+ context \u2014 only reusable imperative rules with an effective trigger.`,rW=x({name:WL,description:Uee},Bee);async function Ia(e){let t=je(e),r=[],n=[],o=[];mkdirSync(t.base,{recursive:true}),await gt(e),existsSync(t.graph)?o.push(t.graph):(await Vl(e,()=>{}),r.push(t.graph)),Wee(e,r,o),Kee(e,r,n,o);let i=Hee(e),a=eW(e),l=await sy(e,[Jl(e,cd(e)),Jl(e,md(e))]);return {created:r,updated:n,skipped:o,rootRuleUpdated:i,gitignoreUpdated:l,recallHookInjected:a}}s(Ia,"scaffoldLessons");function Kee(e,t,r,n){let o=join(e,".agentsmesh/skills",WL,"SKILL.md"),i=`${rW}
279
+ `;if(!existsSync(o)){mkdirSync(dirname(o),{recursive:true}),writeFileSync(o,i,"utf8"),t.push(o);return}if(readFileSync(o,"utf8")===i){n.push(o);return}writeFileSync(o,i,"utf8"),r.push(o);}s(Kee,"seedLessonsSkill");function Wee(e,t,r){let n=je(e).config;if(existsSync(n)){r.push(n);return}mkdirSync(dirname(n),{recursive:true}),writeFileSync(n,`${JSON.stringify(XK(),null,2)}
280
+ `,"utf8"),t.push(n);}s(Wee,"seedLessonsConfig");function Hee(e){let t=join(e,".agentsmesh/rules/_root.md");if(!existsSync(t)){mkdirSync(dirname(t),{recursive:true});let o=`---
281
281
  root: true
282
282
  description: ""
283
283
  ---
@@ -286,9 +286,9 @@ ${KL}
286
286
 
287
287
  # Operational Guidelines
288
288
  `;return writeFileSync(t,o,"utf8"),true}let r=readFileSync(t,"utf8"),n=`${tW(r)}
289
- `;return n===r?false:(writeFileSync(t,n,"utf8"),true)}s(Kee,"injectProceduralBlock");b();Te();function sW(e){let t=[];for(let r of De)for(let n of Tk(r.id,e))t.push({target:r.id,path:n});return t}s(sW,"collectDetectionPaths");function iW(e){let t=new Map;for(let{target:r,path:n}of sW(e)){let o=t.get(r)??[];o.push(n),t.set(r,o);}return [...t.entries()].map(([r,n])=>({id:r,paths:n}))}s(iW,"toolIndicators");iW("project");async function aW(e,t="project"){let r=[];for(let{id:n,paths:o}of iW(t))for(let i of o){let a=join(e,i);if(await j(a)){r.push(n);break}}return [...new Set(r)]}s(aW,"detectExistingConfigs");b();Te();var lW=/^# yaml-language-server: \$schema=[^\n]*\n?/;function Hee(){let e=Pa();return `https://unpkg.com/agentsmesh${e&&e!=="unknown"?`@${e}`:""}/schemas`}s(Hee,"schemaBaseUrl");function cW(e){return `${Hee()}/${e}.json`}s(cW,"schemaUrl");function Vm(e){return `# yaml-language-server: $schema=${cW(e)}
290
- `}s(Vm,"yamlSchemaDirective");function Xl(e,t){let r=Vm(t);return lW.test(e)?e.replace(lW,r):`${r}${e}`}s(Xl,"prependYamlSchemaDirective");function mW(e,t){let{$schema:r,...n}=e;return {$schema:cW(t),...n}}s(mW,"stampJsonSchemaField");var zee=["rules","commands","agents","skills","mcp","hooks","ignore","permissions"],Vee=jh();function zL(e,t=Vee){let r=(e.length>0?e:t).map(o=>` - ${o}`).join(`
291
- `),n=zee.map(o=>` - ${o}`).join(`
289
+ `;return n===r?false:(writeFileSync(t,n,"utf8"),true)}s(Hee,"injectProceduralBlock");b();Te();function sW(e){let t=[];for(let r of De)for(let n of Tk(r.id,e))t.push({target:r.id,path:n});return t}s(sW,"collectDetectionPaths");function iW(e){let t=new Map;for(let{target:r,path:n}of sW(e)){let o=t.get(r)??[];o.push(n),t.set(r,o);}return [...t.entries()].map(([r,n])=>({id:r,paths:n}))}s(iW,"toolIndicators");iW("project");async function aW(e,t="project"){let r=[];for(let{id:n,paths:o}of iW(t))for(let i of o){let a=join(e,i);if(await j(a)){r.push(n);break}}return [...new Set(r)]}s(aW,"detectExistingConfigs");b();Te();var lW=/^# yaml-language-server: \$schema=[^\n]*\n?/;function Vee(){let e=Pa();return `https://unpkg.com/agentsmesh${e&&e!=="unknown"?`@${e}`:""}/schemas`}s(Vee,"schemaBaseUrl");function cW(e){return `${Vee()}/${e}.json`}s(cW,"schemaUrl");function Vm(e){return `# yaml-language-server: $schema=${cW(e)}
290
+ `}s(Vm,"yamlSchemaDirective");function Xl(e,t){let r=Vm(t);return lW.test(e)?e.replace(lW,r):`${r}${e}`}s(Xl,"prependYamlSchemaDirective");function mW(e,t){let{$schema:r,...n}=e;return {$schema:cW(t),...n}}s(mW,"stampJsonSchemaField");var Jee=["rules","commands","agents","skills","mcp","hooks","ignore","permissions"],Yee=jh();function zL(e,t=Yee){let r=(e.length>0?e:t).map(o=>` - ${o}`).join(`
291
+ `),n=Jee.map(o=>` - ${o}`).join(`
292
292
  `);return `${Vm("agentsmesh")}version: 1
293
293
  targets:
294
294
  ${r}
@@ -420,43 +420,43 @@ ask: []
420
420
  # overrides:
421
421
  # claude-code:
422
422
  # model: opus
423
- `;b();fe();function ht(e,t){return join(e,t)}s(ht,"ab");async function tC(e){return await j(e)?(await readdir(e,{withFileTypes:true})).filter(r=>r.isFile()&&r.name.endsWith(".md")).length:0}s(tC,"countMdFiles");async function Jee(e){let t=ht(e,"skills");if(!await j(t))return false;let r=await readdir(t,{withFileTypes:true});for(let n of r)if(n.isDirectory()&&!n.name.startsWith("_")&&await j(join(t,n.name,"SKILL.md")))return true;return false}s(Jee,"hasAnyImportedSkill");async function dW(e){let t=ht(e,"rules");await O(t),await L(join(t,"_root.md"),ly),S.success("Created .agentsmesh/rules/_root.md"),await L(join(t,"_example.md"),VL),S.success("Created .agentsmesh/rules/_example.md");let r=ht(e,"commands");await O(r),await L(join(r,"_example.md"),JL),S.success("Created .agentsmesh/commands/_example.md");let n=ht(e,"agents");await O(n),await L(join(n,"_example.md"),YL),S.success("Created .agentsmesh/agents/_example.md");let o=ht(e,join("skills","_example"));await O(o),await L(join(o,"SKILL.md"),XL),S.success("Created .agentsmesh/skills/_example/SKILL.md"),await L(ht(e,"mcp.json"),QL),S.success("Created .agentsmesh/mcp.json"),await L(ht(e,"hooks.yaml"),qL),S.success("Created .agentsmesh/hooks.yaml"),await L(ht(e,"permissions.yaml"),ZL),S.success("Created .agentsmesh/permissions.yaml"),await L(ht(e,"ignore"),eC),S.success("Created .agentsmesh/ignore");}s(dW,"writeScaffoldFull");async function fW(e){let t=ht(e,"rules"),r=await tC(t),n=join(t,"_root.md"),o=await j(n);await O(t),r===0?(await L(n,ly),S.success("Created .agentsmesh/rules/_root.md"),await L(join(t,"_example.md"),VL),S.success("Created .agentsmesh/rules/_example.md")):o||(await L(n,ly),S.success("Created .agentsmesh/rules/_root.md"));let i=ht(e,"commands");await tC(i)===0&&(await O(i),await L(join(i,"_example.md"),JL),S.success("Created .agentsmesh/commands/_example.md"));let a=ht(e,"agents");if(await tC(a)===0&&(await O(a),await L(join(a,"_example.md"),YL),S.success("Created .agentsmesh/agents/_example.md")),!await Jee(e)){let u=ht(e,join("skills","_example"));await O(u),await L(join(u,"SKILL.md"),XL),S.success("Created .agentsmesh/skills/_example/SKILL.md");}let l=ht(e,"mcp.json");await j(l)||(await L(l,QL),S.success("Created .agentsmesh/mcp.json"));let c=ht(e,"hooks.yaml");await j(c)||(await L(c,qL),S.success("Created .agentsmesh/hooks.yaml"));let m=ht(e,"permissions.yaml");await j(m)||(await L(m,ZL),S.success("Created .agentsmesh/permissions.yaml"));let p=ht(e,"ignore");await j(p)||(await L(p,eC),S.success("Created .agentsmesh/ignore"));}s(fW,"writeScaffoldGapFill");var ka="agentsmesh.yaml",Jm="agentsmesh.local.yaml",Xee=["agentsmesh.local.yaml",".agentsmeshcache",".agentsmesh/.lock.tmp",".agentsmesh/packs/"],Qee=Object.fromEntries(De.map(e=>[e.id,(t,r)=>e.generators.importFrom(t,{scope:r})]));async function qee(e,t,r){let n=[];for(let o of r){let i=Qee[o];if(!i)continue;let a=await i(e,t);for(let l of a)n.push({from:relative(e,l.fromPath).replaceAll("\\","/"),to:l.toPath.replaceAll("\\","/")});}return {imported:n,importedToolCount:r.length}}s(qee,"importDetectedTools");async function cy(e,t,r){let n=join(t.configDir,ka),o=[],i=0,a;if(r.doImport){let m=await qee(t.rootBase,r.scope,r.detected);o=m.imported,i=m.importedToolCount,await fW(t.canonicalDir),a="gap-fill";}else await dW(t.canonicalDir),a="full";await L(n,r.defaultTargets===void 0?zL(r.targets):zL(r.targets,r.defaultTargets)),await L(join(t.configDir,Jm),pW);let l=false;r.scope==="project"&&(l=await sy(e,Xee));let c=r.lessons&&r.scope==="project"?await Ia(e):void 0;return {scope:r.scope,configFile:ka,localConfigFile:Jm,detectedConfigs:[...r.detected],imported:o,importedToolCount:i,scaffoldType:a,gitignoreUpdated:l,lessons:c}}s(cy,"applyInitPlan");cn();var hW="__back__";function Zee(e){if(e==="global")return [...Uh()].sort().map(o=>({value:o,label:o,hint:"global"}));let t=[...jh()],r=new Set(t),n=[...hp].filter(o=>!r.has(o)).sort();return [...t,...n].map(o=>({value:o,label:o,hint:r.has(o)?"recommended":void 0}))}s(Zee,"buildTargetOptions");async function rC(e,t,r,n,o,i){let a=[{value:"yes",label:"Yes"},{value:"no",label:"No"}];o&&a.push({value:hW,label:"\u21A9 Back"});let l=await e.select({message:t,options:a,initialValue:n??r?"yes":"no"});return e.isCancel(l)?"cancel":l===hW?"back":(i(l==="yes"),"next")}s(rC,"yesNoStep");function ete(e){return {exitCode:0,data:{scope:e,configFile:ka,localConfigFile:Jm,detectedConfigs:[],imported:[],importedToolCount:0,scaffoldType:"none",gitignoreUpdated:false,cancelled:true}}}s(ete,"cancelledResult");async function yW(e,t){let r=t.context.scope;e.intro(r==="global"?"agentsmesh init --global":"agentsmesh init");let n={targets:[]},o=[];o.push(async()=>{let u=await e.multiselect({message:"Which tools should agentsmesh generate config for? (select at least one)",options:Zee(r),initialValues:n.targets,required:true});return e.isCancel(u)?"cancel":(n.targets=u,"next")}),t.detected.length>0&&o.push(u=>rC(e,`Found existing config for: ${t.detected.join(", ")}. Import into .agentsmesh?`,true,n.doImport,u,f=>{n.doImport=f;})),r==="project"&&o.push(u=>rC(e,"Enable Lessons (shared memory: recall before edits, capture after failures)?",true,n.lessons,u,f=>{n.lessons=f;})),o.push(u=>rC(e,"Run generate now to write tool config files?",true,n.doGenerate,u,f=>{n.doGenerate=f;}));for(let u=0;u<o.length;){let f=await o[u](u>0);if(f==="cancel")return e.cancel("Cancelled \u2014 no changes written."),ete(r);u=f==="back"?Math.max(0,u-1):u+1;}let i={scope:r,targets:n.targets,defaultTargets:t.defaultTargets,detected:t.detected,doImport:n.doImport??false,lessons:n.lessons??false},a=await cy(t.projectRoot,t.context,i),l=n.doGenerate??false,c=0;if(l){let u=await Xo(r==="global"?{global:true}:{},t.projectRoot,{printMatrix:false});c=u.data.summary.created+u.data.summary.updated;}let m=r==="global"?"agentsmesh generate --global":"agentsmesh generate",p=[`Targets: ${n.targets.length} (${n.targets.join(", ")})`];return r==="project"&&p.push(n.lessons?"Lessons: enabled":"Lessons: off \u2014 add it later with 'agentsmesh init --lessons'"),p.push(l?`Generated: ${c} file(s)`:`Next: run '${m}'`),e.note(p.join(`
424
- `),"Setup complete"),e.outro(`agentsmesh is ready. Edit .agentsmesh/ then run '${m}' to sync.`),{exitCode:0,data:a}}s(yW,"runInitWizard");var _W=Uh();async function SW(e,t={},r={}){let n=t.global===true?"global":"project",o=t.lessons===true;if(o&&n==="global")throw new Error("--lessons is project-mode only. Lessons live in the project tree.");let i=Na(e,n),a=join(i.configDir,ka),l=await j(a);if(l&&o){let h=await Ia(e);return {exitCode:0,data:{scope:n,configFile:ka,localConfigFile:Jm,detectedConfigs:[],imported:[],importedToolCount:0,scaffoldType:"none",gitignoreUpdated:false,lessons:h,lessonsOnly:true}}}if(l)throw new Error(`Already initialized. ${ka} exists. Remove it first to re-init.`);let c=await aW(i.rootBase,n),m=n==="global"?c.filter(h=>_W.includes(h)):c,p=n==="global"?_W:void 0;if(r.prompter!==void 0&&t.yes!==true)return yW(r.prompter,{projectRoot:e,context:i,detected:m,defaultTargets:p});let u=m.length>0&&t.yes===true;return {exitCode:0,data:await cy(e,i,{scope:n,targets:u?m:[],defaultTargets:p,detected:m,doImport:u,lessons:o})}}s(SW,"runInit");fe();function IW(e){let{data:t}=e;if(t.lessonsOnly===true&&t.lessons!==void 0){RW(t.lessons),S.info("Run 'agentsmesh generate' to project the new lessons rule to every target.");return}if(t.detectedConfigs.length>0&&S.info(`Found existing configurations: ${t.detectedConfigs.join(", ")}`),t.detectedConfigs.length>0&&t.imported.length===0&&S.info("Run 'agentsmesh init --yes' to auto-import, or 'agentsmesh import --from <tool>' manually."),t.imported.length>0){S.info("Auto-importing existing configurations (--yes)...");for(let n of t.imported)S.success(` ${n.from} \u2192 ${n.to}`);S.info(`Imported ${t.imported.length} file(s) from ${t.importedToolCount} tool(s).`);}let r=t.imported.length>0&&t.detectedConfigs.length>0?` (targets: ${t.detectedConfigs.join(", ")})`:"";S.success(`Created ${t.configFile}${r}`),S.success(`Created ${t.localConfigFile}`),t.gitignoreUpdated&&S.success("Updated .gitignore"),t.lessons!==void 0&&RW(t.lessons);}s(IW,"renderInit");function RW(e){let t=process.cwd(),r=s(o=>relative(t,o).replaceAll("\\","/"),"rel");for(let o of e.created)S.success(` Created ${r(o)}`);for(let o of e.updated)S.success(` Refreshed ${r(o)} (managed \u2014 synced to the current manual)`);for(let o of e.skipped)S.info(` Kept ${r(o)} (already current)`);e.rootRuleUpdated?S.success(" Injected the Lessons ritual block into .agentsmesh/rules/_root.md"):S.info(" .agentsmesh/rules/_root.md already carries the current Lessons block"),e.gitignoreUpdated&&S.success(" Added .agentsmesh/lessons/recall-log.jsonl to .gitignore (opt-in telemetry stays out of git)"),e.recallHookInjected&&S.success(" Wired the PostToolUse recall hook into .agentsmesh/hooks.yaml (deterministic recall on hook-capable targets)"),S.success("Lessons subsystem ready (.agentsmesh/lessons/)."),S.info(" Run 'agentsmesh generate' to sync the ritual into every target."),S.info("");let n=e.created.some(o=>o.replaceAll("\\","/").endsWith("lessons.json"));S.info(n?" The graph starts empty and grows as agents capture failures. Try the loop:":" Recall + capture loop:"),S.info(' capture: agentsmesh lessons add "<rule>" --topic <id> --new-topic --topic-summary "<line>" --trigger-file "<glob>"'),S.info(" recall: agentsmesh lessons query --file <path> --cmd <command>"),S.info(" inspect: agentsmesh lessons journal | lessons show <id> | lessons validate"),S.info(" Optional: export AGENTSMESH_LESSONS_TELEMETRY=1 to measure recall cost via `lessons stats`.");}s(RW,"renderLessons");function kW(){return {intro:s(e=>Yt.intro(e),"intro"),outro:s(e=>Yt.outro(e),"outro"),note:s((e,t)=>Yt.note(e,t),"note"),select:s(e=>Yt.select({message:e.message,options:e.options.map(t=>({value:t.value,label:t.label,hint:t.hint})),initialValue:e.initialValue}),"select"),multiselect:s(e=>Yt.multiselect({message:e.message,options:e.options.map(t=>({value:t.value,label:t.label,hint:t.hint})),initialValues:e.initialValues?[...e.initialValues]:void 0,required:e.required??false}),"multiselect"),isCancel:s(e=>Yt.isCancel(e),"isCancel"),cancel:s(e=>Yt.cancel(e),"cancel")}}s(kW,"createClackPrompter");tt();Te();var nte=Object.fromEntries(De.map(e=>[e.id,{importFrom:e.generators.importFrom,emptyImportMessage:e.emptyImportMessage,lintRules:e.lintRules,lint:e.lint,capabilities:e.capabilities}]));function my(e){return nte[e]}s(my,"getTargetCatalogEntry");rt();sn();wp();var cte={type:"stdio",command:"npx",args:["-y","agentsmesh","mcp"]};function mte(e){return e.mcpServers.agentsmesh!==void 0?false:(e.mcpServers.agentsmesh=cte,true)}s(mte,"injectAgentsmeshEntry");async function nC(e){let t=resolve(e,".agentsmesh/mcp.json");try{let r;try{r=await pn(t)??{mcpServers:{}};}catch{r={mcpServers:{}};}if(!mte(r))return !1;let n=JSON.stringify(r,null,2)+`
423
+ `;b();fe();function ht(e,t){return join(e,t)}s(ht,"ab");async function tC(e){return await j(e)?(await readdir(e,{withFileTypes:true})).filter(r=>r.isFile()&&r.name.endsWith(".md")).length:0}s(tC,"countMdFiles");async function Xee(e){let t=ht(e,"skills");if(!await j(t))return false;let r=await readdir(t,{withFileTypes:true});for(let n of r)if(n.isDirectory()&&!n.name.startsWith("_")&&await j(join(t,n.name,"SKILL.md")))return true;return false}s(Xee,"hasAnyImportedSkill");async function dW(e){let t=ht(e,"rules");await O(t),await L(join(t,"_root.md"),ly),S.success("Created .agentsmesh/rules/_root.md"),await L(join(t,"_example.md"),VL),S.success("Created .agentsmesh/rules/_example.md");let r=ht(e,"commands");await O(r),await L(join(r,"_example.md"),JL),S.success("Created .agentsmesh/commands/_example.md");let n=ht(e,"agents");await O(n),await L(join(n,"_example.md"),YL),S.success("Created .agentsmesh/agents/_example.md");let o=ht(e,join("skills","_example"));await O(o),await L(join(o,"SKILL.md"),XL),S.success("Created .agentsmesh/skills/_example/SKILL.md"),await L(ht(e,"mcp.json"),QL),S.success("Created .agentsmesh/mcp.json"),await L(ht(e,"hooks.yaml"),qL),S.success("Created .agentsmesh/hooks.yaml"),await L(ht(e,"permissions.yaml"),ZL),S.success("Created .agentsmesh/permissions.yaml"),await L(ht(e,"ignore"),eC),S.success("Created .agentsmesh/ignore");}s(dW,"writeScaffoldFull");async function fW(e){let t=ht(e,"rules"),r=await tC(t),n=join(t,"_root.md"),o=await j(n);await O(t),r===0?(await L(n,ly),S.success("Created .agentsmesh/rules/_root.md"),await L(join(t,"_example.md"),VL),S.success("Created .agentsmesh/rules/_example.md")):o||(await L(n,ly),S.success("Created .agentsmesh/rules/_root.md"));let i=ht(e,"commands");await tC(i)===0&&(await O(i),await L(join(i,"_example.md"),JL),S.success("Created .agentsmesh/commands/_example.md"));let a=ht(e,"agents");if(await tC(a)===0&&(await O(a),await L(join(a,"_example.md"),YL),S.success("Created .agentsmesh/agents/_example.md")),!await Xee(e)){let u=ht(e,join("skills","_example"));await O(u),await L(join(u,"SKILL.md"),XL),S.success("Created .agentsmesh/skills/_example/SKILL.md");}let l=ht(e,"mcp.json");await j(l)||(await L(l,QL),S.success("Created .agentsmesh/mcp.json"));let c=ht(e,"hooks.yaml");await j(c)||(await L(c,qL),S.success("Created .agentsmesh/hooks.yaml"));let m=ht(e,"permissions.yaml");await j(m)||(await L(m,ZL),S.success("Created .agentsmesh/permissions.yaml"));let p=ht(e,"ignore");await j(p)||(await L(p,eC),S.success("Created .agentsmesh/ignore"));}s(fW,"writeScaffoldGapFill");var ka="agentsmesh.yaml",Jm="agentsmesh.local.yaml",qee=["agentsmesh.local.yaml",".agentsmeshcache",".agentsmesh/.lock.tmp",".agentsmesh/packs/"],Zee=Object.fromEntries(De.map(e=>[e.id,(t,r)=>e.generators.importFrom(t,{scope:r})]));async function ete(e,t,r){let n=[];for(let o of r){let i=Zee[o];if(!i)continue;let a=await i(e,t);for(let l of a)n.push({from:relative(e,l.fromPath).replaceAll("\\","/"),to:l.toPath.replaceAll("\\","/")});}return {imported:n,importedToolCount:r.length}}s(ete,"importDetectedTools");async function cy(e,t,r){let n=join(t.configDir,ka),o=[],i=0,a;if(r.doImport){let m=await ete(t.rootBase,r.scope,r.detected);o=m.imported,i=m.importedToolCount,await fW(t.canonicalDir),a="gap-fill";}else await dW(t.canonicalDir),a="full";await L(n,r.defaultTargets===void 0?zL(r.targets):zL(r.targets,r.defaultTargets)),await L(join(t.configDir,Jm),pW);let l=false;r.scope==="project"&&(l=await sy(e,qee));let c=r.lessons&&r.scope==="project"?await Ia(e):void 0;return {scope:r.scope,configFile:ka,localConfigFile:Jm,detectedConfigs:[...r.detected],imported:o,importedToolCount:i,scaffoldType:a,gitignoreUpdated:l,lessons:c}}s(cy,"applyInitPlan");cn();var hW="__back__";function tte(e){if(e==="global")return [...Uh()].sort().map(o=>({value:o,label:o,hint:"global"}));let t=[...jh()],r=new Set(t),n=[...hp].filter(o=>!r.has(o)).sort();return [...t,...n].map(o=>({value:o,label:o,hint:r.has(o)?"recommended":void 0}))}s(tte,"buildTargetOptions");async function rC(e,t,r,n,o,i){let a=[{value:"yes",label:"Yes"},{value:"no",label:"No"}];o&&a.push({value:hW,label:"\u21A9 Back"});let l=await e.select({message:t,options:a,initialValue:n??r?"yes":"no"});return e.isCancel(l)?"cancel":l===hW?"back":(i(l==="yes"),"next")}s(rC,"yesNoStep");function rte(e){return {exitCode:0,data:{scope:e,configFile:ka,localConfigFile:Jm,detectedConfigs:[],imported:[],importedToolCount:0,scaffoldType:"none",gitignoreUpdated:false,cancelled:true}}}s(rte,"cancelledResult");async function yW(e,t){let r=t.context.scope;e.intro(r==="global"?"agentsmesh init --global":"agentsmesh init");let n={targets:[]},o=[];o.push(async()=>{let u=await e.multiselect({message:"Which tools should agentsmesh generate config for? (select at least one)",options:tte(r),initialValues:n.targets,required:true});return e.isCancel(u)?"cancel":(n.targets=u,"next")}),t.detected.length>0&&o.push(u=>rC(e,`Found existing config for: ${t.detected.join(", ")}. Import into .agentsmesh?`,true,n.doImport,u,f=>{n.doImport=f;})),r==="project"&&o.push(u=>rC(e,"Enable Lessons (shared memory: recall before edits, capture after failures)?",true,n.lessons,u,f=>{n.lessons=f;})),o.push(u=>rC(e,"Run generate now to write tool config files?",true,n.doGenerate,u,f=>{n.doGenerate=f;}));for(let u=0;u<o.length;){let f=await o[u](u>0);if(f==="cancel")return e.cancel("Cancelled \u2014 no changes written."),rte(r);u=f==="back"?Math.max(0,u-1):u+1;}let i={scope:r,targets:n.targets,defaultTargets:t.defaultTargets,detected:t.detected,doImport:n.doImport??false,lessons:n.lessons??false},a=await cy(t.projectRoot,t.context,i),l=n.doGenerate??false,c=0;if(l){let u=await Xo(r==="global"?{global:true}:{},t.projectRoot,{printMatrix:false});c=u.data.summary.created+u.data.summary.updated;}let m=r==="global"?"agentsmesh generate --global":"agentsmesh generate",p=[`Targets: ${n.targets.length} (${n.targets.join(", ")})`];return r==="project"&&p.push(n.lessons?"Lessons: enabled":"Lessons: off \u2014 add it later with 'agentsmesh init --lessons'"),p.push(l?`Generated: ${c} file(s)`:`Next: run '${m}'`),e.note(p.join(`
424
+ `),"Setup complete"),e.outro(`agentsmesh is ready. Edit .agentsmesh/ then run '${m}' to sync.`),{exitCode:0,data:a}}s(yW,"runInitWizard");var _W=Uh();async function SW(e,t={},r={}){let n=t.global===true?"global":"project",o=t.lessons===true;if(o&&n==="global")throw new Error("--lessons is project-mode only. Lessons live in the project tree.");let i=Na(e,n),a=join(i.configDir,ka),l=await j(a);if(l&&o){let h=await Ia(e);return {exitCode:0,data:{scope:n,configFile:ka,localConfigFile:Jm,detectedConfigs:[],imported:[],importedToolCount:0,scaffoldType:"none",gitignoreUpdated:false,lessons:h,lessonsOnly:true}}}if(l)throw new Error(`Already initialized. ${ka} exists. Remove it first to re-init.`);let c=await aW(i.rootBase,n),m=n==="global"?c.filter(h=>_W.includes(h)):c,p=n==="global"?_W:void 0;if(r.prompter!==void 0&&t.yes!==true)return yW(r.prompter,{projectRoot:e,context:i,detected:m,defaultTargets:p});let u=m.length>0&&t.yes===true;return {exitCode:0,data:await cy(e,i,{scope:n,targets:u?m:[],defaultTargets:p,detected:m,doImport:u,lessons:o})}}s(SW,"runInit");fe();function IW(e){let{data:t}=e;if(t.lessonsOnly===true&&t.lessons!==void 0){RW(t.lessons),S.info("Run 'agentsmesh generate' to project the new lessons rule to every target.");return}if(t.detectedConfigs.length>0&&S.info(`Found existing configurations: ${t.detectedConfigs.join(", ")}`),t.detectedConfigs.length>0&&t.imported.length===0&&S.info("Run 'agentsmesh init --yes' to auto-import, or 'agentsmesh import --from <tool>' manually."),t.imported.length>0){S.info("Auto-importing existing configurations (--yes)...");for(let n of t.imported)S.success(` ${n.from} \u2192 ${n.to}`);S.info(`Imported ${t.imported.length} file(s) from ${t.importedToolCount} tool(s).`);}let r=t.imported.length>0&&t.detectedConfigs.length>0?` (targets: ${t.detectedConfigs.join(", ")})`:"";S.success(`Created ${t.configFile}${r}`),S.success(`Created ${t.localConfigFile}`),t.gitignoreUpdated&&S.success("Updated .gitignore"),t.lessons!==void 0&&RW(t.lessons);}s(IW,"renderInit");function RW(e){let t=process.cwd(),r=s(o=>relative(t,o).replaceAll("\\","/"),"rel");for(let o of e.created)S.success(` Created ${r(o)}`);for(let o of e.updated)S.success(` Refreshed ${r(o)} (managed \u2014 synced to the current manual)`);for(let o of e.skipped)S.info(` Kept ${r(o)} (already current)`);e.rootRuleUpdated?S.success(" Injected the Lessons ritual block into .agentsmesh/rules/_root.md"):S.info(" .agentsmesh/rules/_root.md already carries the current Lessons block"),e.gitignoreUpdated&&S.success(" Added .agentsmesh/lessons/recall-log.jsonl to .gitignore (opt-in telemetry stays out of git)"),e.recallHookInjected&&S.success(" Wired the PostToolUse recall hook into .agentsmesh/hooks.yaml (deterministic recall on hook-capable targets)"),S.success("Lessons subsystem ready (.agentsmesh/lessons/)."),S.info(" Run 'agentsmesh generate' to sync the ritual into every target."),S.info("");let n=e.created.some(o=>o.replaceAll("\\","/").endsWith("lessons.json"));S.info(n?" The graph starts empty and grows as agents capture failures. Try the loop:":" Recall + capture loop:"),S.info(' capture: agentsmesh lessons add "<rule>" --topic <id> --new-topic --topic-summary "<line>" --trigger-file "<glob>"'),S.info(" recall: agentsmesh lessons query --file <path> --cmd <command>"),S.info(" inspect: agentsmesh lessons journal | lessons show <id> | lessons validate"),S.info(" Optional: export AGENTSMESH_LESSONS_TELEMETRY=1 to measure recall cost via `lessons stats`.");}s(RW,"renderLessons");function kW(){return {intro:s(e=>Yt.intro(e),"intro"),outro:s(e=>Yt.outro(e),"outro"),note:s((e,t)=>Yt.note(e,t),"note"),select:s(e=>Yt.select({message:e.message,options:e.options.map(t=>({value:t.value,label:t.label,hint:t.hint})),initialValue:e.initialValue}),"select"),multiselect:s(e=>Yt.multiselect({message:e.message,options:e.options.map(t=>({value:t.value,label:t.label,hint:t.hint})),initialValues:e.initialValues?[...e.initialValues]:void 0,required:e.required??false}),"multiselect"),isCancel:s(e=>Yt.isCancel(e),"isCancel"),cancel:s(e=>Yt.cancel(e),"cancel")}}s(kW,"createClackPrompter");tt();Te();var ste=Object.fromEntries(De.map(e=>[e.id,{importFrom:e.generators.importFrom,emptyImportMessage:e.emptyImportMessage,lintRules:e.lintRules,lint:e.lint,capabilities:e.capabilities}]));function my(e){return ste[e]}s(my,"getTargetCatalogEntry");rt();sn();wp();var pte={type:"stdio",command:"npx",args:["-y","agentsmesh","mcp"]};function ute(e){return e.mcpServers.agentsmesh!==void 0?false:(e.mcpServers.agentsmesh=pte,true)}s(ute,"injectAgentsmeshEntry");async function nC(e){let t=resolve(e,".agentsmesh/mcp.json");try{let r;try{r=await pn(t)??{mcpServers:{}};}catch{r={mcpServers:{}};}if(!ute(r))return !1;let n=JSON.stringify(r,null,2)+`
425
425
  `;await mkdir(dirname(t),{recursive:!0});let o=`${t}.tmp.${process.pid}.${Date.now()}`;return await writeFile(o,n,"utf8"),await rename(o,t),!0}catch(r){return process.stderr.write(`[agentsmesh] warning: could not seed agentsmesh MCP server entry into mcp.json: ${r instanceof Error?r.message:String(r)}
426
- `),false}}s(nC,"seedAgentsmeshMcpEntry");Be();function LW(e,t){return e.map(r=>({from:relative(t,r.fromPath).replaceAll("\\","/"),to:r.toPath}))}s(LW,"mapResults");async function CW(e,t){if(t!=="project")return;let r=join(e,".agentsmesh/rules/_root.md");if(!existsSync(r))return;let n=readFileSync(r,"utf8");(n.includes(Pp)||/^## Lessons \(/m.test(n))&&await Ia(e);}s(CW,"ensureImportedLessonsSubsystem");async function EW(e,t){let r=t??process.cwd(),n=e.from;if(typeof n!="string"||!n)throw new Error("--from is required. Example: agentsmesh import --from claude-code");let o=n.toLowerCase().trim(),i=e.global===true?"global":"project";if(Bt(o)){let p=Na(r,i),f=await my(o).importFrom(p.rootBase,{scope:i});return f.length>0&&(await nC(p.rootBase),await CW(p.rootBase,i)),{exitCode:0,data:{scope:i,target:o,files:LW(f,p.rootBase)}}}let a,l;try{({config:a,context:l}=await _e(r,i));}catch{throw new Error(`Unknown --from "${n}" and no agentsmesh.yaml found. Run 'agentsmesh init' to enable plugin targets, or use a builtin: ${Ue.join(", ")}.`)}await ze(a,r);let c=ne(o);if(!c)throw new Error(`Unknown --from "${n}". Supported: ${[...Ue,...a.pluginTargets??[]].join(", ")}.`);let m=await c.generators.importFrom(l.rootBase,{scope:i});return m.length>0&&(await nC(l.rootBase),await CW(l.rootBase,i)),{exitCode:0,data:{scope:i,target:o,files:LW(m,l.rootBase)}}}s(EW,"runImport");tt();Jo();function py(e){let t=[],r={new:0,updated:0,unchanged:0,deleted:0};for(let n of e){if(n.status==="unchanged"){r.unchanged++;continue}if(n.status==="created"){r.new++;let o=createTwoFilesPatch(`${n.path} (current)`,`${n.path} (generated)`,"",n.content,void 0,void 0,{context:3});t.push({path:n.path,patch:o});continue}if(n.status==="updated"&&n.currentContent!==void 0){r.updated++;let o=createTwoFilesPatch(`${n.path} (current)`,`${n.path} (generated)`,n.currentContent,n.content,void 0,void 0,{context:3});t.push({path:n.path,patch:o});continue}}return {diffs:t,summary:r}}s(py,"computeDiff");function uy(e){return `${e.new} files would be created, ${e.updated} updated, ${e.unchanged} unchanged, ${e.deleted} deleted`}s(uy,"formatDiffSummary");sn();async function wW(e,t){let r=t??process.cwd(),n=e.global===true?"global":"project",o=e.targets,i=typeof o=="string"&&o?o.split(",").map(g=>g.trim()).filter(Boolean):void 0,{config:a,context:l}=await _e(r,n);await ze(a,r);let{canonical:c}=await $t(a,l.configDir,{},l.canonicalDir),m=await Yo({config:a,canonical:c,projectRoot:l.rootBase,scope:n,targetFilter:i});if(m.length===0)return {exitCode:0,data:{files:[],patches:[],summary:{created:0,updated:0,unchanged:0,deleted:0}}};let{diffs:p,summary:u}=py(m);return {exitCode:0,data:{files:m.filter(g=>g.status!=="unchanged"&&g.status!=="skipped").map(g=>({path:g.path,target:g.target,status:g.status})),patches:p.map(g=>({path:g.path,patch:g.patch})),summary:{created:u.new,updated:u.updated,unchanged:u.unchanged,deleted:u.deleted}}}}s(wW,"runDiff");tt();Jo();b();rt();$a();Ie();var gte=[{canonicalKey:"permissions",capabilityKey:"permissions",featureFlag:"permissions",file:".agentsmesh/permissions.yaml",label:"permissions",hasContent:s(e=>{let t=e.permissions;if(!t)return false;let r=t.ask?.length??0;return t.allow.length+t.deny.length+r>0},"hasContent")},{canonicalKey:"hooks",capabilityKey:"hooks",featureFlag:"hooks",file:".agentsmesh/hooks.yaml",label:"hooks",hasContent:s(e=>{let t=e.hooks;return t?Object.values(t).some(r=>Array.isArray(r)&&r.length>0):false},"hasContent")},{canonicalKey:"mcp",capabilityKey:"mcp",featureFlag:"mcp",file:".agentsmesh/mcp.json",label:"MCP servers",hasContent:s(e=>{let t=e.mcp;return t?Object.keys(t.mcpServers).length>0:false},"hasContent")},{canonicalKey:"commands",capabilityKey:"commands",featureFlag:"commands",file:".agentsmesh/commands",label:"commands",hasContent:s(e=>e.commands.length>0,"hasContent")},{canonicalKey:"agents",capabilityKey:"agents",featureFlag:"agents",file:".agentsmesh/agents",label:"agents",hasContent:s(e=>e.agents.length>0,"hasContent")},{canonicalKey:"skills",capabilityKey:"skills",featureFlag:"skills",file:".agentsmesh/skills",label:"skills",hasContent:s(e=>e.skills.length>0,"hasContent")},{canonicalKey:"ignore",capabilityKey:"ignore",featureFlag:"ignore",file:".agentsmesh/ignore",label:"ignore patterns",hasContent:s(e=>e.ignore.length>0,"hasContent")}];function bW(e){let t=new Set(e.enabledFeatures),r=[];for(let n of gte)!t.has(n.featureFlag)||!n.hasContent(e.canonical)||fn(e.capabilities[n.capabilityKey]).level!=="none"||r.push(F(n.file,e.target,`${e.target} does not support ${n.label}; canonical entries are silently dropped during generation. Disable the feature for this target or remove the canonical content.`));return r}s(bW,"lintSilentFeatureDrops");Ie();var hte=/^(?:\s*(?:bash|sh|zsh|pwsh|powershell)\s+)?["']?(?<path>(?:\.{1,2}\/|[^/\s"'`]+\/)[^\s"'`]+)["']?(?:\s|$)/;function yte(e){let r=e.match(hte)?.groups?.path;return typeof r=="string"?r:null}s(yte,"extractScriptToken");function AW(e){if(e.hasScriptProjection)return [];let t=e.canonical.hooks;if(!t)return [];let r=[];for(let n of Object.values(t))if(Array.isArray(n))for(let o of n){if(typeof o?.command!="string")continue;let i=yte(o.command);i&&r.push(F(".agentsmesh/hooks.yaml",e.target,`${e.target} hook command references script "${i}"; agentsmesh does not copy hook scripts into ${e.target} output, so the script must already exist relative to the hook execution directory or the generated config will fail.`));}return r}s(AW,"lintHookScriptReferences");Ie();function TW(e){if(e.preservesManualActivation)return [];let t=[];for(let r of e.canonical.rules)r.root||r.trigger==="manual"&&(r.targets.length>0&&!r.targets.includes(e.target)||t.push(F(r.source,e.target,`Rule has trigger: 'manual' (Cursor-style "@-mention only" activation), but ${e.target} loads every rule unconditionally. The rule will become always-on for ${e.target} \u2014 restrict it with \`targets: [cursor]\`, convert it to a skill with manual invocation, or remove it.`)));return t}s(TW,"lintRuleScopeInversion");var Ste=new Set([".git","node_modules"]),Rte=2e5;function La(e){let t=new Set;try{let r=[e];for(;r.length>0;){let n=r.pop();for(let o of readdirSync(n,{withFileTypes:!0}))if(o.isDirectory())Ste.has(o.name)||r.push(join(n,o.name));else if(o.isFile()&&(t.add(Jl(e,join(n,o.name))),t.size>Rte))return t}}catch{return null}return t}s(La,"listProjectFiles");var Lte="lessons",DW=".agentsmesh/lessons/lessons.json",NW=".agentsmesh/rules/_root.md",Cte=/^## Lessons \(/m;function vW(e,t){if(t==="global")return [];let r=je(e);if(!existsSync(r.graph))return [];let n=[],o;try{o=ed(e);}catch(m){return [oC("error",DW,`lessons.json failed to load: ${m instanceof Error?m.message:String(m)}`)]}let i=La(e)??void 0,a=Jn(o,{knownPaths:i});for(let m of a.findings)n.push(oC(m.level,DW,`[${m.code}] ${m.message}`));let l=join(e,NW),c=existsSync(l)?readFileSync(l,"utf8"):"";return Cte.test(c)||n.push(oC("warning",NW,'lessons procedural rule ("## Lessons (...)") is missing from _root.md \u2014 recall/capture enforcement will not fire.')),n}s(vW,"lintLessonsSubsystem");function oC(e,t,r){return {level:e,file:t,target:Lte,message:r}}s(oC,"diag");var Ete=["node_modules",".git","dist","coverage",".agentsmesh"];async function Ote(e){return (await Ci(e)).filter(n=>{let o=relative(e,n);return !Ete.some(i=>o.includes(`/${i}/`)||o.startsWith(`${i}/`))}).map(n=>relative(e,n))}s(Ote,"getProjectFiles");async function dy(e,t,r,n,o={}){let i=o.scope??"project",a=[...e.targets,...e.pluginTargets??[]],l=n?a.filter(_=>n.includes(_)):a,c=e.features.includes("rules"),m=e.features.includes("commands"),p=e.features.includes("mcp"),u=e.features.includes("permissions"),f=e.features.includes("hooks"),g=[...vW(r,i)],h=i==="global"?[]:await Ote(r);for(let _ of l){let R=ne(_),k=Bt(_)?my(_):R;k?.capabilities&&g.push(...bW({target:_,capabilities:k.capabilities,canonical:t,enabledFeatures:e.features})),f&&g.push(...AW({target:_,canonical:t,hasScriptProjection:R?.postProcessHookOutputs!==void 0})),c&&g.push(...TW({target:_,canonical:t,preservesManualActivation:R?.preservesManualActivation===true})),c&&k?.lintRules&&g.push(...k.lintRules(t,r,h,{scope:i})),R?.generators.lint&&g.push(...R.generators.lint(t));let w={scope:i};m&&k?.lint?.commands&&g.push(...k.lint.commands(t,w)),p&&k?.lint?.mcp&&g.push(...k.lint.mcp(t,w)),u&&k?.lint?.permissions&&g.push(...k.lint.permissions(t,w)),f&&k?.lint?.hooks&&g.push(...k.lint.hooks(t,w));}let y=g.some(_=>_.level==="error");return {diagnostics:g,hasErrors:y}}s(dy,"runLint");sn();async function MW(e,t){let r=t??process.cwd(),n=e.global===true?"global":"project",o=e.targets,i=typeof o=="string"&&o?o.split(",").map(u=>u.trim()).filter(Boolean):void 0,{config:a,context:l}=await _e(r,n);await ze(a,r);let{canonical:c}=await $t(a,l.configDir,{},l.canonicalDir),{diagnostics:m,hasErrors:p}=await dy(a,c,l.configDir,i,{scope:n});return {exitCode:p?1:0,data:{diagnostics:m.map(u=>({level:u.level,file:u.file,target:u.target,message:u.message})),summary:{errors:m.filter(u=>u.level==="error").length,warnings:m.filter(u=>u.level==="warning").length}}}}s(MW,"runLintCmd");function GW(e){let{data:t}=e;if(t.diagnostics.length===0){M.success("All checks passed.");return}let r=t.diagnostics.filter(a=>a.level==="error"),n=t.diagnostics.filter(a=>a.level==="warning");for(let a of r)M.error(`${a.file} (${a.target}): ${a.message}`);for(let a of n)M.warn(`${a.file} (${a.target}): ${a.message}`);let o=t.summary.errors,i=t.summary.warnings;M.info(`${o} error${o!==1?"s":""}, ${i} warning${i!==1?"s":""}`);}s(GW,"renderLint");function $W(e){let{data:t}=e;if(!t.hasLock){M.error("Not initialized for collaboration. Run 'agentsmesh generate' first.");return}if(t.inSync){M.note("Lock file is in sync.","Check"),M.success("Lock file is in sync.");return}let r=new Set(t.lockedViolations);M.error("Conflict detected:");for(let n of t.extendsModified)M.error(` extend "${n}" was modified`);for(let n of t.modified){let o=r.has(n)?" [LOCKED]":"";M.error(` ${n} was modified${o}`);}for(let n of t.added){let o=r.has(n)?" [LOCKED]":"";M.error(` ${n} was added${o}`);}for(let n of t.removed){let o=r.has(n)?" [LOCKED]":"";M.error(` ${n} was removed${o}`);}M.note("Generated files are out of sync.","Check"),M.info("Run 'agentsmesh merge' to resolve, or 'agentsmesh generate --force' to accept current state.");}s($W,"renderCheck");function jW(e){let{data:t}=e;if(t.files.length===0){M.info(`Nothing to import from ${t.target}.`);return}for(let n of t.files)M.success(`${n.from} \u2192 ${n.to}`);let r=t.scope==="global"?" --global":"";M.info(`Imported ${t.files.length} file(s). Run 'agentsmesh generate${r}' to sync to other tools.`);}s(jW,"renderImport");fe();function UW(e){let{summary:t}=e.data;if(t.created+t.updated+t.unchanged+t.deleted===0){S.info("No files to generate (no root rule or rules feature disabled).");return}for(let n of e.data.patches)process.stdout.write(n.patch);S.info(uy({new:t.created,updated:t.updated,unchanged:t.unchanged,deleted:t.deleted}));}s(UW,"renderDiff");function BW(e){if(!e.data.hadConflict){M.info("No conflicts to resolve.");return}M.success("Lock file conflict resolved.");}s(BW,"renderMerge");Xu();Qu();tt();Jo();Xu();Qu();fe();var Ate=300;function Tte(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}s(Tte,"normalizeWatchPath");function xte(e,t){let r=Tte(relative(e,t));return r===""?true:r===".lock"||r===".lock.tmp"||r===".generate.lock"||r.endsWith("/.lock")||r.endsWith("/.lock.tmp")||r.endsWith("/.generate.lock")||r.includes("/.generate.lock/")||r.startsWith(".generate.lock/")}s(xte,"shouldIgnoreWatchPath");function Pte(e,t,r,n,o,i,a,l,c){return JSON.stringify({features:e,rulesCount:t,commandsCount:r,agentsCount:n,skillsCount:o,mcpServerCount:i,permissionsCount:a,hooksCount:l,ignoreCount:c})}s(Pte,"featureFingerprint");async function WW(e,t,r={}){let n=t??process.cwd(),o=e.global===true?"global":"project",{context:i}=await _e(n,o),a=[i.canonicalDir,join(i.configDir,"agentsmesh.yaml"),join(i.configDir,"agentsmesh.local.yaml")],l=null,c=null,m=false,p=null,u=s(async()=>{if(m)return;l=null;let{config:_,context:R}=await _e(n,o),{canonical:k}=await $t(_,R.configDir,{},R.canonicalDir),w=k.mcp?Object.keys(k.mcp.mcpServers).length:0,D=k.permissions?k.permissions.allow.length+k.permissions.deny.length:0,N=k.hooks?Object.values(k.hooks).reduce(($,re)=>$+(Array.isArray(re)?re.length:0),0):0,K=k.ignore.length,J=Pte(_.features,k.rules.length,k.commands.length,k.agents.length,k.skills.length,w,D,N,K),ee=c!==null&&c!==J;if(c=J,m)return;let se=await Xo(e,n,{printMatrix:false});if(Mm(se),!m){if(ee){let $=await vm(e,n);Fm($,{verbose:e.verbose===true});}else S.info("Regenerated.");r.onCycle?.({featuresChanged:ee});}},"run"),f=s(()=>{let _=u().catch(R=>{if(!m){let k=R instanceof Error?R.message:String(R);S.error(k);}}).finally(()=>{p===_&&(p=null);});p=_;},"scheduleRun"),g=s(()=>{m||(l&&clearTimeout(l),l=setTimeout(f,Ate));},"schedule"),h=r.usePolling??process.platform==="win32",y=bte.watch(a,{ignoreInitial:true,usePolling:h,...h&&r.pollIntervalMs!==void 0?{interval:r.pollIntervalMs}:{}});return y.on("all",(_,R)=>{xte(i.canonicalDir,R)||g();}),await new Promise((_,R)=>{y.once("ready",_),y.once("error",R);}),S.info(o==="global"?"Watching ~/.agentsmesh/ and agentsmesh.yaml...":"Watching .agentsmesh/ and agentsmesh.yaml..."),p=u(),await p,p=null,{stop:s(async()=>{m=true,l&&(clearTimeout(l),l=null),await y.close(),p&&await p;},"stop")}}s(WW,"runWatch");tt();Zd();async function fy(e){let{config:t,configDir:r,canonicalDir:n}=e,o=await Ah(n);if(o===null)return {inSync:false,hasLock:false,modified:[],added:[],removed:[],extendsModified:[],lockedViolations:[]};let i=await fi(n),a=await gc(t,r),l=a.length>0?await Pm(a):{},c=new Set(Object.keys(o.checksums)),m=new Set(Object.keys(i)),p=[],u=[],f=[];for(let R of c){let k=i[R];k===void 0?f.push(R):k!==o.checksums[R]&&p.push(R);}for(let R of m)c.has(R)||u.push(R);let g=new Set([...Object.keys(o.extends),...Object.keys(l)]),h=[];for(let R of g)l[R]!==o.extends[R]&&h.push(R);let y=xh(o.checksums,i,t.collaboration?.lock_features??[]);return {inSync:p.length===0&&u.length===0&&f.length===0&&h.length===0,hasLock:true,modified:p,added:u,removed:f,extendsModified:h,lockedViolations:y}}s(fy,"checkLockSync");sn();async function HW(e,t){let r=t??process.cwd(),n=e.global===true?"global":"project",{config:o,context:i}=await _e(r,n);await ze(o,r);let a=await fy({config:o,configDir:i.configDir,canonicalDir:i.canonicalDir});return a.hasLock?{exitCode:a.inSync?0:1,data:{hasLock:true,inSync:a.inSync,modified:[...a.modified],added:[...a.added],removed:[...a.removed],extendsModified:[...a.extendsModified],lockedViolations:[...a.lockedViolations]}}:{exitCode:1,data:{hasLock:false,inSync:false,modified:[],added:[],removed:[],extendsModified:[],lockedViolations:[]}}}s(HW,"runCheck");tt();b();Zd();var Nte=".lock",vte="<<<<<<<";async function sC(e){let t=join(e,Nte),r=await I(t);return r===null?false:r.includes(vte)}s(sC,"hasLockConflict");async function VW(e,t,r){if(!await sC(e))throw new Error("No conflict to resolve.");let o=await fi(e),i=dirname(e),a=r?await gc(r,i):[],l=a.length>0?await Pm(a):{},c=await Ph(join(e,"packs")),m=process.env.USER??process.env.USERNAME??"unknown";await Th(e,{generatedAt:new Date().toISOString(),generatedBy:m,libVersion:t,checksums:o,extends:l,packs:c});}s(VW,"resolveLockConflict");async function JW(e,t){let r=t??process.cwd(),n=e.global===true?"global":"project",{config:o,context:i}=await _e(r,n),a=i.canonicalDir;return await sC(a)?(await VW(a,Pa(),o),{exitCode:0,data:{hadConflict:true,resolved:true}}):{exitCode:0,data:{hadConflict:false,resolved:false}}}s(JW,"runMerge");tt();Lh();function YW(e){let t=typeof e.path=="string"?e.path.trim():void 0,r=typeof e.target=="string"?e.target.trim():void 0,n=typeof e.as=="string"?e.as.trim():void 0,o=e["accept-elevated"]===true;return {sync:e.sync===true,dryRun:e["dry-run"]===true,force:e.force===true,useExtends:e.extends===true,all:e.all===true,forceFreshMaterialize:e.forceFreshMaterialize===true,explicitPath:t||void 0,explicitTarget:r||void 0,explicitAs:n?Tm.parse(n):void 0,nameOverride:typeof e.name=="string"?e.name.trim():"",acceptHooks:o||e["accept-hooks"]===true,acceptPermissions:o||e["accept-permissions"]===true,acceptMcp:o||e["accept-mcp"]===true}}s(YW,"readInstallFlags");var Gte=".install.lock";async function Ym(e,t={}){return await mkdir(e,{recursive:true}),Nm(join(e,Gte),{...t,label:"install lock"})}s(Ym,"acquireInstallLock");tt();b();kp();Fa();var Ute=promisify(execFile);function gy(e,t){if(e.startsWith("-"))throw new Error(`agentsmesh refuses ${t} starting with "-" (option-injection guard): ${e}`)}s(gy,"ensureNotFlag");async function iC(e){let{stdout:t}=await Ute("git",e,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ALLOW_PROTOCOL:Qd()}});return t.trim()}s(iC,"runGit");async function XW(){try{return await iC(["--version"]),!0}catch{return false}}s(XW,"isGitAvailable");async function Bte(e,t){gy(e,"remote-url"),gy(t,"ref"),Sp(e);let r=[t,`refs/heads/${t}`,`refs/tags/${t}`],n;for(let o of r)try{let a=(await iC(["ls-remote",e,o])).split(`
427
- `).map(c=>c.trim()).find(c=>c.length>0);if(!a)continue;let l=a.split(/\s+/)[0];if(l&&/^[0-9a-f]{40}$/i.test(l))return l}catch(i){n=i;}throw new Error(`Could not resolve ref "${t}" for ${e}: ${n instanceof Error?n.message:String(n)}`)}s(Bte,"gitLsRemoteResolve");async function hy(e,t){gy(t,"remote-url");let r=e===""?"HEAD":e;if(gy(r,"ref"),/^[0-9a-f]{40}$/i.test(r))return r.toLowerCase();if(Sp(t),r==="HEAD"){let o=(await iC(["ls-remote",t,"HEAD"])).split(`
428
- `).find(a=>a.trim().length>0);if(!o)throw new Error(`Could not resolve HEAD for ${t}`);let i=o.split(/\s+/)[0];if(!i||!/^[0-9a-f]{40}$/i.test(i))throw new Error(`Invalid ls-remote HEAD line for ${t}`);return i.toLowerCase()}return Bte(t,r)}s(hy,"resolveRemoteRefForInstall");async function QW(e){if(e.kind==="local")return {resolvedPath:e.localRoot,sourceForYaml:e.localSourceForYaml};let t=e.gitRemoteUrl;if(!t)throw new Error("Internal error: missing git remote URL");let r=await hy(e.rawRef||"HEAD",t);if(e.kind==="github"){let l=`github:${e.org}/${e.repo}@${r}`;return {resolvedPath:(await fc(l,"install",{cacheDir:tr(),refresh:false,allowOfflineFallback:false})).resolvedPath,sourceForYaml:l,version:r}}if(e.kind==="gitlab"){let l=`gitlab:${e.org}/${e.repo}@${r}`;return {resolvedPath:(await fc(l,"install",{cacheDir:tr(),refresh:false,allowOfflineFallback:false})).resolvedPath,sourceForYaml:l,version:r}}let n=r,i=`git+${(e.gitPlusBase??t).split("#")[0]}#${n}`;return {resolvedPath:(await fc(i,"install",{cacheDir:tr(),refresh:false,allowOfflineFallback:false})).resolvedPath,sourceForYaml:i,version:r}}s(QW,"fetchInstallSource");async function qW(e,t){if(e.kind==="local")return {resolvedPath:e.localRoot,sourceForYaml:e.localSourceForYaml};try{let r=await QW(e);return {resolvedPath:r.resolvedPath,sourceForYaml:r.sourceForYaml,version:r.version}}catch(r){let n=r instanceof Error?r.message:String(r),o=new Error(`Failed to fetch from ${t}: ${n}. Check your network connection and try again.`);throw r instanceof Error&&(o.cause=r),o}}s(qW,"resolveInstallResolvedPath");function dd(e){try{let t=new URL(e);if(t.hostname!=="github.com")return null;let r=t.pathname.split("/").filter(Boolean),n=r.indexOf("tree");if(n<2||n+1>=r.length)return null;let o=r[0],i=r[1],a=r[n+1],l=r.slice(n+2).join("/");return !o||!i||!a?null:{org:o,repo:i,ref:a,path:l||""}}catch{return null}}s(dd,"parseGithubTreeUrl");function fd(e){try{let t=new URL(e);if(t.hostname!=="github.com")return null;let r=t.pathname.split("/").filter(Boolean),n=r.indexOf("blob");if(n<2||n+1>=r.length)return null;let o=r[0],i=r[1],a=r[n+1],l=r.slice(n+2).join("/");return !o||!i||!a||!l?null:{org:o,repo:i,ref:a,path:l}}catch{return null}}s(fd,"parseGithubBlobUrl");function gd(e){try{let t=new URL(e);if(t.hostname!=="gitlab.com")return null;let r=t.pathname.split("/").filter(Boolean),n=r.indexOf("-");if(n<0||r[n+1]!=="tree")return null;let o=n+1;if(o+1>=r.length)return null;let i=r[o+1],a=r.slice(o+2).join("/"),l=r.slice(0,n);if(l.length<2)return null;let c=l[l.length-1],m=l.slice(0,-1).join("/");return !m||!c||!i?null:{namespace:m,project:c,ref:i,path:a||""}}catch{return null}}s(gd,"parseGitlabTreeUrl");function hd(e){try{let t=new URL(e);if(t.hostname!=="gitlab.com")return null;let r=t.pathname.split("/").filter(Boolean),n=r.indexOf("-");if(n<0||r[n+1]!=="blob")return null;let o=n+1;if(o+1>=r.length)return null;let i=r[o+1],a=r.slice(o+2).join("/"),l=r.slice(0,n);if(l.length<2)return null;let c=l[l.length-1],m=l.slice(0,-1).join("/");return !m||!c||!i||!a?null:{namespace:m,project:c,ref:i,path:a}}catch{return null}}s(hd,"parseGitlabBlobUrl");var Kte=new Set(["tree","blob","commit","releases","actions","issues","pulls","settings","wiki","discussions","security","projects","packages"]);function yd(e){try{let t=new URL(e);if(t.hostname!=="github.com")return null;let r=t.pathname.split("/").filter(Boolean).map(i=>i.replace(/\.git$/i,""));if(r.length<2||r.length>2||Kte.has(r[1]))return null;let n=r[0],o=r[1];return {org:n,repo:o}}catch{return null}}s(yd,"parseGithubRepoUrl");function _d(e){try{let t=new URL(e);if(t.hostname!=="gitlab.com")return null;let r=t.pathname.split("/").filter(Boolean).map(i=>i.replace(/\.git$/i,""));if(r.length<2||r.includes("-"))return null;let n=r[r.length-1],o=r.slice(0,-1).join("/");return !o||!n?null:{namespace:o,project:n}}catch{return null}}s(_d,"parseGitlabRepoUrl");function Sd(e){let t=e.match(/^git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/i);return t?{org:t[1],repo:t[2].replace(/\.git$/i,"")}:null}s(Sd,"parseGitSshGithub");function Rd(e){let t=e.match(/^git@gitlab\.com:(.+?)(?:\.git)?$/i);if(!t)return null;let n=t[1].replace(/\.git$/i,"").split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-1];return {namespace:n.slice(0,-1).join("/"),project:o}}s(Rd,"parseGitSshGitlab");b();var zte=/^[A-Za-z]:[\\/]/,Vte=/^[A-Za-z]:\//;function ZW(...e){return e.some(t=>t.includes("\\")||zte.test(t))?win32:posix}s(ZW,"pathApiFor");function kd(e){return e.replace(/\\/g,"/")}s(kd,"toPosixPath");function Id(e){return kd(e).replace(/^\/+|\/+$/g,"")}s(Id,"normalizeInstallPathField");function yy(e){let t=kd(e);return t===""||t==="."||t==="./."?".":t.startsWith("./")||t.startsWith("../")||t.startsWith("/")||Vte.test(t)?t:`./${t}`}s(yy,"normalizeLocalSourceForYaml");function Ca(e){return {...e,source:e.source_kind==="local"?yy(e.source):e.source,...e.path!==void 0?{path:Id(e.path)}:{},...e.paths!==void 0?{paths:e.paths.map(t=>Id(t))}:{}}}s(Ca,"normalizePersistedInstallPaths");function eH(e,t,r){let n=ZW(e,t),o=n.normalize(e),i=n.normalize(t),a=Id(r),l=`${n.sep}.agentsmesh${n.sep}`,c=o.indexOf(l);if(c>=0){let p=o.slice(0,c),u=o.slice(c+l.length),f=Id(u),g=kd(n.relative(i,p))||".";return {kind:"local",rawRef:"",pathInRepo:a||f.replace(/\.md$/i,"").replace(/\/$/,""),localRoot:p,localSourceForYaml:yy(g)}}let m=kd(n.relative(i,o))||".";return {kind:"local",rawRef:"",pathInRepo:a,localRoot:o,localSourceForYaml:yy(m)}}s(eH,"localParsedFromAbsPath");async function aC(e,t,r){let n=e.trim(),o=r?.trim().replace(/\\/g,"/")??"";if(n.startsWith("git+")){let p=n.lastIndexOf("#"),u=p<0?n:n.slice(0,p),f=p<0?"HEAD":n.slice(p+1),g=u.slice(4);return {kind:"git",rawRef:f,gitPlusBase:g,gitRemoteUrl:g,pathInRepo:o}}if(n.startsWith("https://")||n.startsWith("http://")){let p=dd(n)??fd(n);if(p)return {kind:"github",rawRef:p.ref,org:p.org,repo:p.repo,gitRemoteUrl:`https://github.com/${p.org}/${p.repo}.git`,pathInRepo:o||p.path};let u=yd(n);if(u)return {kind:"github",rawRef:"HEAD",org:u.org,repo:u.repo,gitRemoteUrl:`https://github.com/${u.org}/${u.repo}.git`,pathInRepo:o};let f=gd(n)??hd(n);if(f)return {kind:"gitlab",rawRef:f.ref,org:f.namespace,repo:f.project,gitRemoteUrl:`https://gitlab.com/${f.namespace}/${f.project}.git`,pathInRepo:o||f.path};let g=_d(n);if(g)return {kind:"gitlab",rawRef:"HEAD",org:g.namespace,repo:g.project,gitRemoteUrl:`https://gitlab.com/${g.namespace}/${g.project}.git`,pathInRepo:o}}if(n.startsWith("git@github.com:")){let p=Sd(n);if(!p)throw new Error(`Invalid GitHub SSH URL: ${n}`);return {kind:"github",rawRef:"HEAD",org:p.org,repo:p.repo,gitRemoteUrl:`https://github.com/${p.org}/${p.repo}.git`,pathInRepo:o}}if(n.startsWith("git@gitlab.com:")){let p=Rd(n);if(!p)throw new Error(`Invalid GitLab SSH URL: ${n}`);return {kind:"gitlab",rawRef:"HEAD",gitRemoteUrl:`https://gitlab.com/${p.namespace}/${p.project}.git`,pathInRepo:o}}if(n.startsWith("git@")){let p=n.match(/^git@([^:]+):(.+?)(?:\.git)?$/);if(!p)throw new Error(`Invalid SSH git URL: ${n}`);let u=p[1],f=p[2].replace(/\.git$/i,"");return {kind:"git",rawRef:"HEAD",gitRemoteUrl:`ssh://git@${u}/${f}.git`,pathInRepo:o}}let i=n.match(/^github:([^/]+)\/(.+?)@([^/@]+)$/);if(i){let p=i[1],u=i[2];return {kind:"github",rawRef:i[3],org:p,repo:u,gitRemoteUrl:`https://github.com/${p}/${u}.git`,pathInRepo:o}}let a=n.match(/^github:([^/]+)\/([^/@]+)$/);if(a){let p=a[1],u=a[2];return {kind:"github",rawRef:"HEAD",org:p,repo:u,gitRemoteUrl:`https://github.com/${p}/${u}.git`,pathInRepo:o}}let l=n.match(/^gitlab:(.+)\/([^/@]+)@([^/@]+)$/);if(l){let p=l[1],u=l[2];return {kind:"gitlab",rawRef:l[3],org:p,repo:u,gitRemoteUrl:`https://gitlab.com/${p}/${u}.git`,pathInRepo:o}}let c=n.match(/^gitlab:(.+)\/([^/@]+)$/);if(c){let p=c[1],u=c[2];return {kind:"gitlab",rawRef:"HEAD",org:p,repo:u,gitRemoteUrl:`https://gitlab.com/${p}/${u}.git`,pathInRepo:o}}let m=resolve(t,n);if(!await j(m))throw new Error(`Path does not exist: ${m}`);return eH(m,t,o)}s(aC,"parseInstallSource");function Ld(e){let t=e.trim();if(t.startsWith("local:"))return {kind:"local"};if(t.startsWith("git+")){let a=t.lastIndexOf("#"),l=a<0?t:t.slice(0,a),c=a<0?"HEAD":t.slice(a+1);return {kind:"git",remoteUrl:l.slice(4),ref:c}}let r=t.match(/^github:([^/]+)\/(.+?)@([^/@]+)$/);if(r!==null){let a=r[1],l=r[2],c=r[3];return {kind:"github",remoteUrl:`https://github.com/${a}/${l}.git`,ref:c}}let n=t.match(/^github:([^/]+)\/([^/@]+)$/);if(n!==null){let a=n[1],l=n[2];return {kind:"github",remoteUrl:`https://github.com/${a}/${l}.git`,ref:"HEAD"}}let o=t.match(/^gitlab:(.+)\/([^/@]+)@([^/@]+)$/);if(o!==null){let a=o[1],l=o[2],c=o[3];return {kind:"gitlab",remoteUrl:`https://gitlab.com/${a}/${l}.git`,ref:c}}let i=t.match(/^gitlab:(.+)\/([^/@]+)$/);if(i!==null){let a=i[1],l=i[2];return {kind:"gitlab",remoteUrl:`https://gitlab.com/${a}/${l}.git`,ref:"HEAD"}}if(t.startsWith("https://")||t.startsWith("http://")){let a=dd(t)??fd(t);if(a!==null)return {kind:"github",remoteUrl:`https://github.com/${a.org}/${a.repo}.git`,ref:a.ref};let l=yd(t);if(l!==null)return {kind:"github",remoteUrl:`https://github.com/${l.org}/${l.repo}.git`,ref:"HEAD"};let c=gd(t)??hd(t);if(c!==null)return {kind:"gitlab",remoteUrl:`https://gitlab.com/${c.namespace}/${c.project}.git`,ref:c.ref};let m=_d(t);return m!==null?{kind:"gitlab",remoteUrl:`https://gitlab.com/${m.namespace}/${m.project}.git`,ref:"HEAD"}:{kind:"git",remoteUrl:t,ref:"HEAD"}}if(t.startsWith("git@github.com:")){let a=Sd(t);return a===null?null:{kind:"github",remoteUrl:`https://github.com/${a.org}/${a.repo}.git`,ref:"HEAD"}}if(t.startsWith("git@gitlab.com:")){let a=Rd(t);return a===null?null:{kind:"gitlab",remoteUrl:`https://gitlab.com/${a.namespace}/${a.project}.git`,ref:"HEAD"}}if(t.startsWith("git@")){let a=t.match(/^git@([^:]+):(.+?)(?:\.git)?$/);if(a===null)return null;let l=a[1],c=a[2].replace(/\.git$/i,"");return {kind:"git",remoteUrl:`ssh://git@${l}/${c}.git`,ref:"HEAD"}}return null}s(Ld,"parseSourceUrl");Wk();function Yn(e){let t=[];return e.skills.length&&t.push("skills"),e.rules.length&&t.push("rules"),e.commands.length&&t.push("commands"),e.agents.length&&t.push("agents"),e.mcp!==null&&t.push("mcp"),e.permissions!==null&&t.push("permissions"),e.hooks!==null&&t.push("hooks"),e.ignore.length&&t.push("ignore"),t}s(Yn,"featuresFromCanonical");async function _y(e,t={}){let{sliceRoot:r,implicitPick:n}=await yh(e),{canonical:o,cleanup:i}=await _h(r,{...t,enableTargetEntityMappers:true});return {canonical:o,features:Yn(o),implicitPick:n,cleanup:i}}s(_y,"discoverFromContentRoot");function tH(e){return e.description.trim()?{skill:e,ok:true}:{skill:e,ok:false,reason:"missing description in frontmatter"}}s(tH,"validateSkill");function rH(e){return e.description.trim()?{rule:e,ok:true}:{rule:e,ok:false,reason:"missing description in frontmatter"}}s(rH,"validateRule");function nH(e){return e.description.trim()?{command:e,ok:true}:{command:e,ok:false,reason:"missing description in frontmatter"}}s(nH,"validateCommand");function oH(e){return e.description.trim()?{agent:e,ok:true}:{agent:e,ok:false,reason:"missing description in frontmatter"}}s(oH,"validateAgent");function yt(e){return basename(e.source).replace(/\.md$/i,"")}s(yt,"ruleSlug");function Xte(e){if(!e)return;let t=[];return e.skills!==void 0&&t.push("skills"),e.rules!==void 0&&t.push("rules"),e.commands!==void 0&&t.push("commands"),e.agents!==void 0&&t.push("agents"),t.length>0?t:void 0}s(Xte,"featuresFromImplicitPick");function Qm(e,t){let{implicitPick:r}=t,n=t.scopedFeatures??Xte(r);if(!r&&!n)return e;let o=new Set(n??[]),i={...e,mcp:!n||o.has("mcp")?e.mcp:null,permissions:!n||o.has("permissions")?e.permissions:null,hooks:!n||o.has("hooks")?e.hooks:null,ignore:!n||o.has("ignore")?e.ignore:[]};if(r?.skills!==void 0){let a=new Set(r.skills);i={...i,skills:r.skills.length===0?[]:i.skills.filter(l=>a.has(l.name))};}else n&&!o.has("skills")&&(i={...i,skills:[]});if(r?.rules!==void 0){let a=new Set(r.rules);i={...i,rules:r.rules.length===0?[]:i.rules.filter(l=>a.has(yt(l)))};}else n&&!o.has("rules")&&(i={...i,rules:[]});if(r?.commands!==void 0){let a=new Set(r.commands);i={...i,commands:r.commands.length===0?[]:i.commands.filter(l=>a.has(l.name))};}else n&&!o.has("commands")&&(i={...i,commands:[]});if(r?.agents!==void 0){let a=new Set(r.agents);i={...i,agents:r.agents.length===0?[]:i.agents.filter(l=>a.has(l.name))};}else n&&!o.has("agents")&&(i={...i,agents:[]});return i}s(Qm,"narrowDiscoveredForInstallScope");Qk();async function sH(e,t,r,n,o={}){let i=await Ih(e,t,{preferredSkillNames:t==="skills"?n?.skills:void 0}),{canonical:a,cleanup:l}=await _y(i.discoveryRoot,o),c=Qm(a,{scopedFeatures:[t]});return {prep:{yamlTarget:r,scopedFeatures:[t],cleanup:s(async()=>{await Promise.allSettled([l(),i.cleanup()]);},"combinedCleanup")},narrowed:c,discoveredFeatures:Yn(c)}}s(sH,"resolveManualDiscoveredForInstall");rs();Dk();b();Te();var Qte=(()=>{let e=new Map;for(let r of De){let n=r.project.managedOutputs,o=[...n?.dirs??[],...n?.files??[],...r.detectionPaths];for(let i of o){let a=i.replace(/\/$/,""),l=e.get(a)??new Set;l.add(r.id),e.set(a,l);}}let t=[];for(let[r,n]of e){if(n.size!==1)continue;let[o]=[...n];t.push({prefix:r,target:o});}return t.sort((r,n)=>n.prefix.length-r.prefix.length)})();function qte(e){return e.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"")}s(qte,"norm");function Sy(e){let t=qte(e);if(t){for(let{prefix:r,target:n}of Qte)if(t===r||t.startsWith(`${r}/`))return n}}s(Sy,"targetHintFromNativePath");function lC(e,t){return Sy(e)===t}s(lC,"pathSupportsNativePick");function iH(e,t){if(!e||!t)return;let r=Sy(t);if(r&&r!==e)throw new Error(`--target "${e}" does not match the install path (native path suggests "${r}"). Omit --target to auto-detect, or point at a subtree for that target.`)}s(iH,"validateTargetMatchesPath");function aH(e){return (e.commands?.length??0)+(e.rules?.length??0)+(e.skills?.length??0)+(e.agents?.length??0)>0}s(aH,"extendPickHasArrays");rt();b();oI();async function tre(e,t,r,n){if(n.kind==="skillDir")return gg(e);if(n.kind==="firstSegment"){let c=t.slice(r.prefix.length).split("/").filter(Boolean)[0];return c?[c]:[]}let o=await B(e),i=n.suffix,a=i.toLowerCase();return [...new Set(o.filter(l=>l.toLowerCase().endsWith(a)).map(l=>basename(l,i)))].sort()}s(tre,"namesForStrategy");async function lH(e,t,r){let n=ne(r)?.nativeInstall;if(!n)return {};let o=t.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"");if(n.inferPick)return n.inferPick(e,o);for(let i of n.pickPaths??[]){if(o!==i.prefix&&!o.startsWith(i.prefix))continue;let a=join(e,...o.split("/")),l=await tre(a,o,i,i.strategy);return l.length?{[i.feature]:l}:{}}return {}}s(lH,"inferImplicitPickFromNativePath");function cH(e){return (e.commands?.length??0)+(e.rules?.length??0)+(e.skills?.length??0)+(e.agents?.length??0)===0}s(cH,"isImplicitPickEmpty");Nk();function Cd(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}s(Cd,"normalizePath");function ire(e,t){let r=Cd(e),n=Cd(t);return r===n||r.startsWith(`${n}/`)||n.startsWith(`${r}/`)}s(ire,"overlapsPath");function Ry(e,t){let r=e??[];return r.includes(t)||r.push(t),r}s(Ry,"addUnique");async function are(e){let t=await mkdtemp(join(tmpdir(),"am-install-native-")),r=join(t,"repo"),n=s(async()=>{await rm$1(t,{recursive:true,force:true});},"cleanup");try{return await cp$1(e,r,{recursive:!0}),{stageRoot:r,cleanup:n}}catch(o){throw await n(),o}}s(are,"makeStageRoot");function lre(e,t){let r;for(let o of e){if(o.feature==="rules"&&o.toPath.startsWith(".agentsmesh/rules/")){r={...r,rules:Ry(r?.rules,basename(o.toPath,".md"))};continue}if(o.feature==="commands"&&o.toPath.startsWith(".agentsmesh/commands/")){let i=Cd(relative(join(t,".agentsmesh","commands"),join(t,o.toPath)));r={...r,commands:Ry(r?.commands,i.replace(/\.md$/i,"").split("/").filter(Boolean).join(":"))};continue}if(o.feature==="agents"&&o.toPath.startsWith(".agentsmesh/agents/")){r={...r,agents:Ry(r?.agents,basename(o.toPath,".md"))};continue}if(o.feature==="skills"&&o.toPath.startsWith(".agentsmesh/skills/")){let a=Cd(relative(join(t,".agentsmesh","skills"),join(t,o.toPath))).split("/")[0];a&&(r={...r,skills:Ry(r?.skills,a)});}}return r&&(r.rules?.length??0)+(r.commands?.length??0)+(r.agents?.length??0)+(r.skills?.length??0)>0?r:void 0}s(lre,"buildPickFromResults");function cre(e,t,r,n){let o=join(t,...Cd(e).split("/")),i=r.filter(a=>ire(o,a.fromPath));if(i.length===0)throw new Error(`No installable native resources found under "${e}" for target "${n}". Try --path "${e}" without --target so agentsmesh can auto-detect the layout, or use --as <rules|commands|agents|skills> to install the directory as a flat collection.`);return {features:[...new Set(i.map(a=>a.feature))],pick:lre(i,t)}}s(cre,"scopeImportedResults");async function cC(e,t){let{stageRoot:r,cleanup:n}=await are(e);try{let o=await Wu(r,t);return {stageRoot:r,results:o,cleanup:n}}catch(o){throw await n(),o}}s(cC,"stageImportedNativeRepo");async function mC(e,t,r){let n=await cC(e,r);try{return {stageRoot:n.stageRoot,cleanup:n.cleanup,...cre(t,n.stageRoot,n.results,r)}}catch(o){throw await n.cleanup(),o}}s(mC,"stageNativeInstallScope");async function dH(e,t,r,n){let o=n.explicitTarget?.trim();o&&Or.parse(o);let i=r.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"");iH(o,i);let a=join(e,".agentsmesh"),l=await j(a),c=i?Sy(i):void 0,p=!l&&!o&&(!i||c!==void 0)?await ah(e)??void 0:void 0;if(!o&&c&&p&&c!==p)throw new Error(`Install path suggests native layout "${c}" but auto-detect imported "${p}". Use --target ${c} for this path, or install from the repo root without a conflicting subtree path.`);let u=o??c??p,f=!!i&&!!u&&!i.startsWith(".agentsmesh");if(!l&&u){if(f){let w=await mC(e,i,u);return {discoveryRoot:w.stageRoot,implicitPick:w.pick,scopedFeatures:w.features,yamlTarget:u,importHappened:true,cleanup:w.cleanup}}let k=await cC(e,u);return {discoveryRoot:i?join(k.stageRoot,i):k.stageRoot,yamlTarget:u,importHappened:true,cleanup:k.cleanup}}let g;l?i?u&&lC(i,u)?g=e:g=t:g=e:g=t;let h,y,_;if(f&&u){let k=await mC(e,i,u);g=k.stageRoot,h=k.pick,y=k.features,_=k.cleanup;}else if(g===e&&i&&u&&lC(i,u)&&(h=await lH(e,i,u),cH(h)))throw new Error(`No installable native resources found under "${i}" for target "${u}". Try --path "${i}" without --target so agentsmesh can auto-detect the layout, or use --as <rules|commands|agents|skills> to install the directory as a flat collection.`);let R;return o?R=o:u&&(h&&aH(h)||(y?.length??0)>0)&&(R=u),{discoveryRoot:g,implicitPick:h,scopedFeatures:y,yamlTarget:R,importHappened:_!==void 0,cleanup:_}}s(dH,"prepareInstallDiscovery");async function pC(e,t,r,n,o={}){let i=await dH(e,t,r,{explicitTarget:n}),{canonical:a,implicitPick:l,cleanup:c}=await _y(i.discoveryRoot,o),m=i.cleanup,u={...i,cleanup:s(async()=>{await Promise.allSettled([c(),...m?[m()]:[]]);},"mergedCleanup")},f=l??i.implicitPick,g=Qm(a,{implicitPick:f,scopedFeatures:i.scopedFeatures}),h=Yn(g);return {prep:u,discovered:a,implicitPick:f,narrowed:g,discoveredFeatures:h}}s(pC,"resolveDiscoveredForInstall");var ure=[".claude-plugin","marketplace.json"];async function dre(e){try{return (await stat(e)).isDirectory()}catch{return false}}s(dre,"dirExists");function fre(e){if(typeof e!="string"||e.length===0||e.startsWith("/"))return null;let t=e.replace(/^\.\/+/,"").replace(/\/+$/,"");return t.split("/").some(r=>r==="..")?null:t}s(fre,"normalizeSource");async function gH(e,t,r){let n=join(e,...ure),o;try{o=await readFile(n,"utf-8");}catch{return null}let i;try{i=JSON.parse(o);}catch{return null}if(typeof i!="object"||i===null||!Array.isArray(i.plugins))return null;let a=i.plugins,l=[];for(let c of a){if(typeof c!="object"||c===null)continue;let m=fre(c.source);if(!m)continue;let p=join(e,m);if(!await dre(p))continue;let u=await t(p,m);r(u)&&l.push({path:m,layout:u});}return l}s(gH,"detectMarketplaceSubPacks");async function Ed(e){try{return (await stat(e)).isDirectory()}catch{return false}}s(Ed,"dirExists");async function Ea(e){try{return (await readdir(e,{withFileTypes:!0})).map(r=>({name:r.name,isDir:r.isDirectory(),isFile:r.isFile()}))}catch{return []}}s(Ea,"listDirEntries");function hH(e){return e.endsWith(".instructions.md")?"copilot-instructions":e.endsWith(".md")?"md":e.endsWith(".mdc")?"mdc":e.endsWith(".toml")?"toml":null}s(hH,"classifyFileShape");var yre=["rules","commands","agents","skills","mcp.json","hooks.yaml","permissions.yaml","ignore"],_re=[".cursorrules",".windsurfrules"];async function _H(e){let t=join(e,".agentsmesh");if(!await Ed(t))return null;let r=await Ea(t),n=new Set(r.map(o=>o.name));for(let o of yre)if(n.has(o))return {path:".agentsmesh"};return null}s(_H,"detectCanonical");async function SH(e){for(let t of _re)try{if((await stat(join(e,t))).isFile())return {path:t}}catch{}return null}s(SH,"detectRootRule");async function RH(e){try{if((await stat(join(e,"SKILL.md"))).isFile())return {path:"SKILL.md"}}catch{}return null}s(RH,"detectRootSkill");ss();var Rre={rules:"rules",commands:"commands",agents:"agents",skills:"skills"},Ire=[".claude-plugin",".codex-plugin",".cursor-plugin"],kre=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;async function IH(e){let t=join(e,"skills"),r=await Ea(t);for(let n of r)if(!(!n.isDir||n.name.startsWith("_")||!kre.test(n.name))&&await Ed(join(t,n.name)))try{if((await stat(join(t,n.name,"SKILL.md"))).isFile())return {path:"skills"}}catch{continue}return null}s(IH,"detectSkillPack");async function kH(e){let t=[];for(let[r,n]of Object.entries(Rre)){let o=join(e,r),i=await Ea(o),a=new Set;for(let l of i){if(!l.isFile||qn(l.name))continue;let c=hH(l.name);c&&a.add(c);}for(let l of a)t.push({path:r,suggestedAs:n,fileShape:l});}return t}s(kH,"detectFlatCollections");async function LH(e){let t=[];for(let r of Ire)await Ed(join(e,r))&&t.push({path:r});return t}s(LH,"detectToolNativeManifests");async function fC(e,t){let r=await _H(e);if(r)return {canonical:r,skillPack:null,rootSkill:null,rootRule:null,flatCollections:[],toolNativeManifests:[]};let n=await IH(e),o=n?null:await RH(e),i=await kH(e),a=n||o||i.length>0?null:await SH(e),l=await LH(e);return {canonical:r,skillPack:n?{path:t?`${t}/skills`:"skills"}:null,rootSkill:o?{path:t?`${t}/SKILL.md`:"SKILL.md"}:null,rootRule:a?{path:t?`${t}/${a.path}`:a.path}:null,flatCollections:i.map(c=>({...c,path:t?`${t}/${c.path}`:c.path})),toolNativeManifests:l.map(c=>({path:t?`${t}/${c.path}`:c.path}))}}s(fC,"detectFlatLayout");function dC(e){return e.canonical!==null||e.skillPack!==null||e.rootSkill!==null||e.rootRule!==null||e.flatCollections.length>0}s(dC,"hasContent");async function CH(e,t){let r=await Ea(e),n=[];for(let o of r){if(!o.isDir||o.name.startsWith("."))continue;let i=join(e,o.name),a=t?`${t}/${o.name}`:o.name,l=await fC(i,a);dC(l)&&n.push({path:a,layout:l});}return n}s(CH,"collectSubPackCandidates");async function Lre(e,t){if(dC(t))return [];let r=await gH(e,fC,dC);if(r&&r.length>0)return r;let n=await CH(e,"");if(n.length>=2)return n;let o=await Ea(e);for(let i of o){if(!i.isDir||i.name.startsWith("."))continue;let a=await CH(join(e,i.name),i.name);if(a.length>=2)return a}return []}s(Lre,"detectSubPacks");async function OH(e){let t=await fC(e,"");if(t.canonical)return {...t,subPacks:[]};let r=await Lre(e,t);return {...t,subPacks:r}}s(OH,"detectLayout");rt();b();U();function Ere(e){let t=[];for(let r of ff()){let n=ne(r)?.nativeInstall?.dialectHints;n?.length&&n.some(o=>o.frontmatterKey in e)&&t.push(r);}return t}s(Ere,"targetsMatchingFrontmatter");async function bH(e){let t;try{t=await readdir(e);}catch{return null}let r=t.sort().find(a=>a.toLowerCase().endsWith(".mdc"));if(!r)return null;let n=await I(join(e,r));if(!n)return null;let o=mn(n,join(e,r));if(!o.ok)return null;let i=Ere(o.value.frontmatter);return i.length===1?i[0]??null:null}s(bH,"inferMdcTarget");uh();hh();function Tre(e){let t=e.indexOf("#");return t<0?{path:e,anchor:""}:{path:e.slice(0,t),anchor:e.slice(t)}}s(Tre,"splitAnchor");function xre(e){return e.split(sep).join("/")}s(xre,"toForwardSlash");async function Pre(e){try{return await stat(e),!0}catch{return false}}s(Pre,"pathExists");async function PH(e){let{link:t,fromFile:r,contentRoot:n,includedPaths:o}=e,{path:i,anchor:a}=Tre(t.path);if(i===""||isAbsolute(i))return {link:t,classification:"unresolvable",resolvedRelative:null,anchor:a};let l=join(n,r,".."),c=normalize(resolve(l,i)),m=normalize(resolve(n)),p=relative(m,c);if(p.startsWith("..")||isAbsolute(p))return {link:t,classification:"unresolvable",resolvedRelative:null,anchor:a};let u=xre(p);return await Pre(c)?o.has(u)?{link:t,classification:"in-tree-included",resolvedRelative:u,anchor:a}:{link:t,classification:"resolvable-outside",resolvedRelative:u,anchor:a}:{link:t,classification:"unresolvable",resolvedRelative:u,anchor:a}}s(PH,"resolveLink");var Dre=/^(?:```|~~~)[^\n]*\n[\s\S]*?^(?:```|~~~)/gm,Nre=/(!?)\[[^\]\n]*\]\(([^)\n]+)\)/dg,vre=/^\s*\[([^\]\n]+)\]:\s*(.+?)\s*$/dgm;function Fre(e){let t=[];for(let r of e.matchAll(Dre)){let n=r.index??0;t.push([n,n+r[0].length]);}return t}s(Fre,"getFencedCodeRanges");function DH(e,t){for(let[r,n]of t)if(e>=r&&e<n)return true;return false}s(DH,"isInRanges");function gC(e){let t=e.length-e.trimStart().length,r=e.trim(),n=r.length,o=/^(.*?)\s+(["'])([\s\S]*?)\2\s*$/.exec(r);o?.[1]!==void 0&&(n=o[1].trimEnd().length);let i=t,a=r.slice(0,n);return a.length>=2&&a.startsWith("<")&&a.endsWith(">")&&(i+=1,n-=2),{start:i,length:n}}s(gC,"destPathSpan");function NH(e){let{start:t,length:r}=gC(e);return e.slice(t,t+r)}s(NH,"normalizeDestination");function Iy(e){let t=Fre(e),r=[];for(let n of e.matchAll(Nre)){let o=n.index??0;if(DH(o,t))continue;let i=n[1]==="!",a=n[2],l=n.indices?.[2];if(a===void 0||l===void 0)continue;let c=gC(a);r.push({kind:i?"image":"inline",destination:NH(a),destinationOffset:l[0]+c.start,destinationLength:c.length});}for(let n of e.matchAll(vre)){let o=n.index??0;if(DH(o,t))continue;let i=(n[1]??"").trim(),a=n[2]??"",l=n.indices?.[2];if(i===""||a.trim()===""||l===void 0)continue;let c=gC(a);r.push({kind:"reference-def",destination:NH(a),label:i,destinationOffset:l[0]+c.start,destinationLength:c.length});}return r}s(Iy,"scanMarkdownLinks");function vH(e,t){if(t.length===0)return e;let r=[...t].sort((o,i)=>i.offset-o.offset),n=e;for(let o of r)n=`${n.slice(0,o.offset)}${o.replacement}${n.slice(o.offset+o.length)}`;return n}s(vH,"applyRangeRewrites");function Mre(e){return !(e.length===0||e.startsWith("#")||e.startsWith("/")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))}s(Mre,"isCandidateRelativePath");function Gre(e){let t=e.replaceAll("\\","/");return t==="{baseDir}"?".":t.startsWith("{baseDir}/")?t.slice(10):t}s(Gre,"stripPath");function $re(e){let t=e.destination;return Mre(t)?{raw:t,path:Gre(t),kind:e.kind,...e.label!==void 0?{label:e.label}:{}}:null}s($re,"toScannedLink");function FH(e){let t=[];for(let r of Iy(e)){let n=$re(r);n!==null&&t.push(n);}return t}s(FH,"scanRelativeLinks");function qm(e,t){let r=e.replaceAll("\\","/"),n=t.replaceAll("\\","/"),o=r.endsWith("/")?r:`${r}/`;return n.startsWith(o)?n.slice(o.length):n}s(qm,"toForwardSlashRelative");function MH(e,t,r,n,o){let i=new Set;for(let a of t){i.add(qm(e,a.source));for(let l of a.supportingFiles)i.add(qm(e,l.absolutePath));}for(let a of r)i.add(qm(e,a.source));for(let a of n)i.add(qm(e,a.source));for(let a of o)i.add(qm(e,a.source));return i}s(MH,"buildIncludedPaths");function Ure(e,t,r,n){let o=[];for(let i of e)o.push({kind:"skill",name:i.name,body:i.body,sourcePath:i.source});for(let i of t)o.push({kind:"agent",name:i.name,body:i.body,sourcePath:i.source});for(let i of r)o.push({kind:"command",name:i.name,body:i.body,sourcePath:i.source});for(let i of n)o.push({kind:"rule",name:basename(i.source,".md"),body:i.body,sourcePath:i.source});return o}s(Ure,"listScannables");async function GH(e,t,r,n,o,i){let a=Ure(t,r,n,o),l=[];for(let c of a){let m=FH(c.body);if(m.length===0)continue;let p=qm(e,c.sourcePath),u=[];for(let f of m){let g=await PH({link:f,fromFile:p,contentRoot:e,includedPaths:i});g.classification!=="in-tree-included"&&u.push(g);}u.length>0&&l.push({entityKind:c.kind,entityName:c.name,resolved:u});}return l}s(GH,"detectBrokenLinks");hh();async function $H(e,t,r={}){let n=new Map,o=new Map,i=[],a=[...t].sort((p,u)=>p.precedence-u.precedence);for(let p of a){let{commands:u,cleanup:f}=await dh(join(e,p.dir),{restrictToTarget:p.target,parseOpts:r});i.push(f);for(let g of u){if(n.get(g.name)===void 0){n.set(g.name,{command:g,precedence:p.precedence});continue}let y=o.get(g.name)??[];y.push({path:g.source,precedence:p.precedence}),o.set(g.name,y);}}let l=[];for(let[p,u]of o){let f=n.get(p);if(f===void 0)throw new Error(`mergeCommands invariant: loser without winner for "${p}"`);l.push({basename:p,winnerPath:f.command.source,loserPaths:u.map(g=>g.path)});}return l.sort((p,u)=>p.basename.localeCompare(u.basename)),{commands:[...n.values()].map(p=>p.command).sort((p,u)=>p.name.localeCompare(u.name)),dedups:l,cleanup:s(async()=>{await Promise.allSettled(i.map(p=>p()));},"cleanup")}}s($H,"mergeCommands");async function jH(e,t,r={}){let[n,o,i,a]=await Promise.all([RU(`${e}/skills`,r),gh(`${e}/agents`,{parseOpts:r}),fh(`${e}/rules`,{parseOpts:r}),$H(e,t.mergeFromToolDirs,r)]),l=[...o.agents],c=[...i.rules],m=MH(e,n,l,a.commands,c),p=await GH(e,n,l,a.commands,c,m),u=s(async()=>{await Promise.allSettled([i.cleanup(),o.cleanup(),a.cleanup()]);},"cleanup");return {skills:n,agents:l,commands:a.commands,rules:c,dedups:a.dedups,brokenLinks:p,cleanup:u}}s(jH,"aggregateAnthropicSkillPack");var UH={mergeFromToolDirs:[{dir:"commands",precedence:0},{dir:".claude/commands",target:"claude-code",precedence:1},{dir:".gemini/commands",target:"gemini-cli",precedence:2}]};_c();function Wre(e){return {rules:[...e.rules],commands:[...e.commands],agents:[...e.agents],skills:[...e.skills],mcp:null,permissions:null,hooks:null,ignore:[]}}s(Wre,"aggregateToCanonical");function ky(){return {}}s(ky,"emptyPrep");async function Hre(e,t){let r=[];for(let n of t)if(n.fileShape==="mdc"&&!n.inferredTarget){let o=await bH(join(e,n.path));r.push(o?{...n,inferredTarget:o}:n);}else r.push(n);return r}s(Hre,"enrichMdcTargets");function KH(e){return e.canonical?"canonical-agentsmesh":e.skillPack||e.rootSkill?"anthropic-skill-pack":e.rootRule||e.toolNativeManifests.length>0?"tool-native":"unknown"}s(KH,"deriveSourceType");async function zre(e,t){let r=await sf(e,t);return {rules:[],commands:[],agents:[],skills:r?[r]:[],mcp:null,permissions:null,hooks:null,ignore:[]}}s(zre,"rootSkillToCanonical");async function Vre(e,t){let r=join(e,t),n=await readFile(r,"utf-8").catch(()=>""),o=`Imported from ${t}`;return {rules:n?[{source:r,root:true,targets:[],description:o,globs:[],body:n}]:[],commands:[],agents:[],skills:[],mcp:null,permissions:null,hooks:null,ignore:[]}}s(Vre,"rootRuleToCanonical");async function WH(e){let t=e.parseOpts??{};if(e.explicitAs)return {implicitPick:void 0,...await sH(e.contentRoot,e.explicitAs,e.explicitTarget,e.replayPick,t)};if(e.explicitTarget)return pC(e.resolvedPath,e.contentRoot,e.pathInRepo,e.explicitTarget,t);let r=await OH(e.contentRoot),n=await Hre(e.contentRoot,r.flatCollections),o={...r,flatCollections:n};if(o.skillPack&&!o.canonical){let a=await jH(e.contentRoot,UH,t),l=Wre(a);return {prep:{cleanup:a.cleanup},implicitPick:void 0,narrowed:l,discoveredFeatures:Yn(l),layout:o,aggregate:a}}if(o.rootSkill&&!o.canonical&&!o.skillPack){let a=await zre(e.contentRoot,t);return {prep:ky(),implicitPick:void 0,narrowed:a,discoveredFeatures:Yn(a),layout:o}}if(o.rootRule&&!o.canonical&&!o.skillPack&&!o.rootSkill&&o.flatCollections.length===0){let a=await Vre(e.contentRoot,o.rootRule.path);return {prep:ky(),implicitPick:void 0,narrowed:a,discoveredFeatures:Yn(a),layout:o}}return o.subPacks.length>0?{prep:ky(),implicitPick:void 0,narrowed:{rules:[],commands:[],agents:[],skills:[],mcp:null,permissions:null,hooks:null,ignore:[]},discoveredFeatures:[],layout:o}:o.flatCollections.length>0?{prep:ky(),implicitPick:void 0,narrowed:{rules:[],commands:[],agents:[],skills:[],mcp:null,permissions:null,hooks:null,ignore:[]},discoveredFeatures:[],layout:o}:{...await pC(e.resolvedPath,e.contentRoot,e.pathInRepo,e.explicitTarget,t),layout:o}}s(WH,"resolveInstallDiscovery");function zH(e){let t=new Set;e.skillPack&&t.add("skills"),e.rootSkill&&t.add("skills");for(let r of e.flatCollections)t.add(r.suggestedAs);return [...t]}s(zH,"featuresFromLayout");function Jre(e){return e.replace(/[/\\]+/g,"-").replace(/[^a-z0-9-]/gi,"").toLowerCase()}s(Jre,"subPackSlug");function HH(e,t,r){let n=zH(e.layout),o=!e.layout.skillPack&&!e.layout.rootSkill&&n.length>0;return {name:`${t}-${Jre(e.path)}`,source:r,path:e.path,...o?{as:n[0]}:{},features:n}}s(HH,"targetFromSubPack");function VH(e,t,r){return {name:t,source:r,path:e.path,as:e.suggestedAs,target:e.inferredTarget,features:[e.suggestedAs]}}s(VH,"targetFromCollection");function JH(e){let{layout:t,sourceName:r,sourceForYaml:n,explicitPath:o,explicitAs:i,explicitTarget:a}=e;if(o||i||a)return {targets:[],isMarketplace:false};if(t.canonical||t.skillPack)return {targets:[],isMarketplace:false};if(t.subPacks.length>=1)return Yre(e);if(t.flatCollections.length===1){let l=t.flatCollections[0];return {targets:[VH(l,r,n)],isMarketplace:false}}return t.flatCollections.length>1?Xre(e):{targets:[],isMarketplace:false}}s(JH,"selectInstallCandidates");function Yre(e){let{layout:t,sourceName:r,sourceForYaml:n}=e;if(e.all)return {targets:t.subPacks.map(a=>HH(a,r,n)),isMarketplace:true};if(e.force||!e.tty){let a=t.subPacks.map(l=>({path:l.path,features:zH(l.layout)})).map(l=>` - ${l.path} (${l.features.join(", ")})`).join(`
426
+ `),false}}s(nC,"seedAgentsmeshMcpEntry");Be();function LW(e,t){return e.map(r=>({from:relative(t,r.fromPath).replaceAll("\\","/"),to:r.toPath}))}s(LW,"mapResults");async function CW(e,t){if(t!=="project")return;let r=join(e,".agentsmesh/rules/_root.md");if(!existsSync(r))return;let n=readFileSync(r,"utf8");(n.includes(Pp)||/^## Lessons \(/m.test(n))&&await Ia(e);}s(CW,"ensureImportedLessonsSubsystem");async function EW(e,t){let r=t??process.cwd(),n=e.from;if(typeof n!="string"||!n)throw new Error("--from is required. Example: agentsmesh import --from claude-code");let o=n.toLowerCase().trim(),i=e.global===true?"global":"project";if(Bt(o)){let p=Na(r,i),f=await my(o).importFrom(p.rootBase,{scope:i});return f.length>0&&(await nC(p.rootBase),await CW(p.rootBase,i)),{exitCode:0,data:{scope:i,target:o,files:LW(f,p.rootBase)}}}let a,l;try{({config:a,context:l}=await _e(r,i));}catch{throw new Error(`Unknown --from "${n}" and no agentsmesh.yaml found. Run 'agentsmesh init' to enable plugin targets, or use a builtin: ${Ue.join(", ")}.`)}await ze(a,r);let c=ne(o);if(!c)throw new Error(`Unknown --from "${n}". Supported: ${[...Ue,...a.pluginTargets??[]].join(", ")}.`);let m=await c.generators.importFrom(l.rootBase,{scope:i});return m.length>0&&(await nC(l.rootBase),await CW(l.rootBase,i)),{exitCode:0,data:{scope:i,target:o,files:LW(m,l.rootBase)}}}s(EW,"runImport");tt();Jo();function py(e){let t=[],r={new:0,updated:0,unchanged:0,deleted:0};for(let n of e){if(n.status==="unchanged"){r.unchanged++;continue}if(n.status==="created"){r.new++;let o=createTwoFilesPatch(`${n.path} (current)`,`${n.path} (generated)`,"",n.content,void 0,void 0,{context:3});t.push({path:n.path,patch:o});continue}if(n.status==="updated"&&n.currentContent!==void 0){r.updated++;let o=createTwoFilesPatch(`${n.path} (current)`,`${n.path} (generated)`,n.currentContent,n.content,void 0,void 0,{context:3});t.push({path:n.path,patch:o});continue}}return {diffs:t,summary:r}}s(py,"computeDiff");function uy(e){return `${e.new} files would be created, ${e.updated} updated, ${e.unchanged} unchanged, ${e.deleted} deleted`}s(uy,"formatDiffSummary");sn();async function wW(e,t){let r=t??process.cwd(),n=e.global===true?"global":"project",o=e.targets,i=typeof o=="string"&&o?o.split(",").map(g=>g.trim()).filter(Boolean):void 0,{config:a,context:l}=await _e(r,n);await ze(a,r);let{canonical:c}=await $t(a,l.configDir,{},l.canonicalDir),m=await Yo({config:a,canonical:c,projectRoot:l.rootBase,scope:n,targetFilter:i});if(m.length===0)return {exitCode:0,data:{files:[],patches:[],summary:{created:0,updated:0,unchanged:0,deleted:0}}};let{diffs:p,summary:u}=py(m);return {exitCode:0,data:{files:m.filter(g=>g.status!=="unchanged"&&g.status!=="skipped").map(g=>({path:g.path,target:g.target,status:g.status})),patches:p.map(g=>({path:g.path,patch:g.patch})),summary:{created:u.new,updated:u.updated,unchanged:u.unchanged,deleted:u.deleted}}}}s(wW,"runDiff");tt();Jo();b();rt();$a();Ie();var yte=[{canonicalKey:"permissions",capabilityKey:"permissions",featureFlag:"permissions",file:".agentsmesh/permissions.yaml",label:"permissions",hasContent:s(e=>{let t=e.permissions;if(!t)return false;let r=t.ask?.length??0;return t.allow.length+t.deny.length+r>0},"hasContent")},{canonicalKey:"hooks",capabilityKey:"hooks",featureFlag:"hooks",file:".agentsmesh/hooks.yaml",label:"hooks",hasContent:s(e=>{let t=e.hooks;return t?Object.values(t).some(r=>Array.isArray(r)&&r.length>0):false},"hasContent")},{canonicalKey:"mcp",capabilityKey:"mcp",featureFlag:"mcp",file:".agentsmesh/mcp.json",label:"MCP servers",hasContent:s(e=>{let t=e.mcp;return t?Object.keys(t.mcpServers).length>0:false},"hasContent")},{canonicalKey:"commands",capabilityKey:"commands",featureFlag:"commands",file:".agentsmesh/commands",label:"commands",hasContent:s(e=>e.commands.length>0,"hasContent")},{canonicalKey:"agents",capabilityKey:"agents",featureFlag:"agents",file:".agentsmesh/agents",label:"agents",hasContent:s(e=>e.agents.length>0,"hasContent")},{canonicalKey:"skills",capabilityKey:"skills",featureFlag:"skills",file:".agentsmesh/skills",label:"skills",hasContent:s(e=>e.skills.length>0,"hasContent")},{canonicalKey:"ignore",capabilityKey:"ignore",featureFlag:"ignore",file:".agentsmesh/ignore",label:"ignore patterns",hasContent:s(e=>e.ignore.length>0,"hasContent")}];function bW(e){let t=new Set(e.enabledFeatures),r=[];for(let n of yte)!t.has(n.featureFlag)||!n.hasContent(e.canonical)||fn(e.capabilities[n.capabilityKey]).level!=="none"||r.push(F(n.file,e.target,`${e.target} does not support ${n.label}; canonical entries are silently dropped during generation. Disable the feature for this target or remove the canonical content.`));return r}s(bW,"lintSilentFeatureDrops");Ie();var _te=/^(?:\s*(?:bash|sh|zsh|pwsh|powershell)\s+)?["']?(?<path>(?:\.{1,2}\/|[^/\s"'`]+\/)[^\s"'`]+)["']?(?:\s|$)/;function Ste(e){let r=e.match(_te)?.groups?.path;return typeof r=="string"?r:null}s(Ste,"extractScriptToken");function AW(e){if(e.hasScriptProjection)return [];let t=e.canonical.hooks;if(!t)return [];let r=[];for(let n of Object.values(t))if(Array.isArray(n))for(let o of n){if(typeof o?.command!="string")continue;let i=Ste(o.command);i&&r.push(F(".agentsmesh/hooks.yaml",e.target,`${e.target} hook command references script "${i}"; agentsmesh does not copy hook scripts into ${e.target} output, so the script must already exist relative to the hook execution directory or the generated config will fail.`));}return r}s(AW,"lintHookScriptReferences");Ie();function TW(e){if(e.preservesManualActivation)return [];let t=[];for(let r of e.canonical.rules)r.root||r.trigger==="manual"&&(r.targets.length>0&&!r.targets.includes(e.target)||t.push(F(r.source,e.target,`Rule has trigger: 'manual' (Cursor-style "@-mention only" activation), but ${e.target} loads every rule unconditionally. The rule will become always-on for ${e.target} \u2014 restrict it with \`targets: [cursor]\`, convert it to a skill with manual invocation, or remove it.`)));return t}s(TW,"lintRuleScopeInversion");var Ite=new Set([".git","node_modules"]),kte=2e5;function La(e){let t=new Set;try{let r=[e];for(;r.length>0;){let n=r.pop();for(let o of readdirSync(n,{withFileTypes:!0}))if(o.isDirectory())Ite.has(o.name)||r.push(join(n,o.name));else if(o.isFile()&&(t.add(Jl(e,join(n,o.name))),t.size>kte))return t}}catch{return null}return t}s(La,"listProjectFiles");var Ete="lessons",DW=".agentsmesh/lessons/lessons.json",NW=".agentsmesh/rules/_root.md",Ote=/^## Lessons \(/m;function vW(e,t){if(t==="global")return [];let r=je(e);if(!existsSync(r.graph))return [];let n=[],o;try{o=ed(e);}catch(m){return [oC("error",DW,`lessons.json failed to load: ${m instanceof Error?m.message:String(m)}`)]}let i=La(e)??void 0,a=Jn(o,{knownPaths:i});for(let m of a.findings)n.push(oC(m.level,DW,`[${m.code}] ${m.message}`));let l=join(e,NW),c=existsSync(l)?readFileSync(l,"utf8"):"";return Ote.test(c)||n.push(oC("warning",NW,'lessons procedural rule ("## Lessons (...)") is missing from _root.md \u2014 recall/capture enforcement will not fire.')),n}s(vW,"lintLessonsSubsystem");function oC(e,t,r){return {level:e,file:t,target:Ete,message:r}}s(oC,"diag");var wte=["node_modules",".git","dist","coverage",".agentsmesh"];async function bte(e){return (await Ci(e)).filter(n=>{let o=relative(e,n);return !wte.some(i=>o.includes(`/${i}/`)||o.startsWith(`${i}/`))}).map(n=>relative(e,n))}s(bte,"getProjectFiles");async function dy(e,t,r,n,o={}){let i=o.scope??"project",a=[...e.targets,...e.pluginTargets??[]],l=n?a.filter(_=>n.includes(_)):a,c=e.features.includes("rules"),m=e.features.includes("commands"),p=e.features.includes("mcp"),u=e.features.includes("permissions"),f=e.features.includes("hooks"),g=[...vW(r,i)],h=i==="global"?[]:await bte(r);for(let _ of l){let R=ne(_),k=Bt(_)?my(_):R;k?.capabilities&&g.push(...bW({target:_,capabilities:k.capabilities,canonical:t,enabledFeatures:e.features})),f&&g.push(...AW({target:_,canonical:t,hasScriptProjection:R?.postProcessHookOutputs!==void 0})),c&&g.push(...TW({target:_,canonical:t,preservesManualActivation:R?.preservesManualActivation===true})),c&&k?.lintRules&&g.push(...k.lintRules(t,r,h,{scope:i})),R?.generators.lint&&g.push(...R.generators.lint(t));let w={scope:i};m&&k?.lint?.commands&&g.push(...k.lint.commands(t,w)),p&&k?.lint?.mcp&&g.push(...k.lint.mcp(t,w)),u&&k?.lint?.permissions&&g.push(...k.lint.permissions(t,w)),f&&k?.lint?.hooks&&g.push(...k.lint.hooks(t,w));}let y=g.some(_=>_.level==="error");return {diagnostics:g,hasErrors:y}}s(dy,"runLint");sn();async function MW(e,t){let r=t??process.cwd(),n=e.global===true?"global":"project",o=e.targets,i=typeof o=="string"&&o?o.split(",").map(u=>u.trim()).filter(Boolean):void 0,{config:a,context:l}=await _e(r,n);await ze(a,r);let{canonical:c}=await $t(a,l.configDir,{},l.canonicalDir),{diagnostics:m,hasErrors:p}=await dy(a,c,l.configDir,i,{scope:n});return {exitCode:p?1:0,data:{diagnostics:m.map(u=>({level:u.level,file:u.file,target:u.target,message:u.message})),summary:{errors:m.filter(u=>u.level==="error").length,warnings:m.filter(u=>u.level==="warning").length}}}}s(MW,"runLintCmd");function GW(e){let{data:t}=e;if(t.diagnostics.length===0){M.success("All checks passed.");return}let r=t.diagnostics.filter(a=>a.level==="error"),n=t.diagnostics.filter(a=>a.level==="warning");for(let a of r)M.error(`${a.file} (${a.target}): ${a.message}`);for(let a of n)M.warn(`${a.file} (${a.target}): ${a.message}`);let o=t.summary.errors,i=t.summary.warnings;M.info(`${o} error${o!==1?"s":""}, ${i} warning${i!==1?"s":""}`);}s(GW,"renderLint");function $W(e){let{data:t}=e;if(!t.hasLock){M.error("Not initialized for collaboration. Run 'agentsmesh generate' first.");return}if(t.inSync){M.note("Lock file is in sync.","Check"),M.success("Lock file is in sync.");return}let r=new Set(t.lockedViolations);M.error("Conflict detected:");for(let n of t.extendsModified)M.error(` extend "${n}" was modified`);for(let n of t.modified){let o=r.has(n)?" [LOCKED]":"";M.error(` ${n} was modified${o}`);}for(let n of t.added){let o=r.has(n)?" [LOCKED]":"";M.error(` ${n} was added${o}`);}for(let n of t.removed){let o=r.has(n)?" [LOCKED]":"";M.error(` ${n} was removed${o}`);}M.note("Generated files are out of sync.","Check"),M.info("Run 'agentsmesh merge' to resolve, or 'agentsmesh generate --force' to accept current state.");}s($W,"renderCheck");function jW(e){let{data:t}=e;if(t.files.length===0){M.info(`Nothing to import from ${t.target}.`);return}for(let n of t.files)M.success(`${n.from} \u2192 ${n.to}`);let r=t.scope==="global"?" --global":"";M.info(`Imported ${t.files.length} file(s). Run 'agentsmesh generate${r}' to sync to other tools.`);}s(jW,"renderImport");fe();function UW(e){let{summary:t}=e.data;if(t.created+t.updated+t.unchanged+t.deleted===0){S.info("No files to generate (no root rule or rules feature disabled).");return}for(let n of e.data.patches)process.stdout.write(n.patch);S.info(uy({new:t.created,updated:t.updated,unchanged:t.unchanged,deleted:t.deleted}));}s(UW,"renderDiff");function BW(e){if(!e.data.hadConflict){M.info("No conflicts to resolve.");return}M.success("Lock file conflict resolved.");}s(BW,"renderMerge");Xu();Qu();tt();Jo();Xu();Qu();fe();var xte=300;function Pte(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}s(Pte,"normalizeWatchPath");function Dte(e,t){let r=Pte(relative(e,t));return r===""?true:r===".lock"||r===".lock.tmp"||r===".generate.lock"||r.endsWith("/.lock")||r.endsWith("/.lock.tmp")||r.endsWith("/.generate.lock")||r.includes("/.generate.lock/")||r.startsWith(".generate.lock/")}s(Dte,"shouldIgnoreWatchPath");function Nte(e,t,r,n,o,i,a,l,c){return JSON.stringify({features:e,rulesCount:t,commandsCount:r,agentsCount:n,skillsCount:o,mcpServerCount:i,permissionsCount:a,hooksCount:l,ignoreCount:c})}s(Nte,"featureFingerprint");async function WW(e,t,r={}){let n=t??process.cwd(),o=e.global===true?"global":"project",{context:i}=await _e(n,o),a=[i.canonicalDir,join(i.configDir,"agentsmesh.yaml"),join(i.configDir,"agentsmesh.local.yaml")],l=null,c=null,m=false,p=null,u=s(async()=>{if(m)return;l=null;let{config:_,context:R}=await _e(n,o),{canonical:k}=await $t(_,R.configDir,{},R.canonicalDir),w=k.mcp?Object.keys(k.mcp.mcpServers).length:0,D=k.permissions?k.permissions.allow.length+k.permissions.deny.length:0,N=k.hooks?Object.values(k.hooks).reduce(($,re)=>$+(Array.isArray(re)?re.length:0),0):0,K=k.ignore.length,J=Nte(_.features,k.rules.length,k.commands.length,k.agents.length,k.skills.length,w,D,N,K),ee=c!==null&&c!==J;if(c=J,m)return;let se=await Xo(e,n,{printMatrix:false});if(Mm(se),!m){if(ee){let $=await vm(e,n);Fm($,{verbose:e.verbose===true});}else S.info("Regenerated.");r.onCycle?.({featuresChanged:ee});}},"run"),f=s(()=>{let _=u().catch(R=>{if(!m){let k=R instanceof Error?R.message:String(R);S.error(k);}}).finally(()=>{p===_&&(p=null);});p=_;},"scheduleRun"),g=s(()=>{m||(l&&clearTimeout(l),l=setTimeout(f,xte));},"schedule"),h=r.usePolling??process.platform==="win32",y=Tte.watch(a,{ignoreInitial:true,usePolling:h,...h&&r.pollIntervalMs!==void 0?{interval:r.pollIntervalMs}:{}});return y.on("all",(_,R)=>{Dte(i.canonicalDir,R)||g();}),await new Promise((_,R)=>{y.once("ready",_),y.once("error",R);}),S.info(o==="global"?"Watching ~/.agentsmesh/ and agentsmesh.yaml...":"Watching .agentsmesh/ and agentsmesh.yaml..."),p=u(),await p,p=null,{stop:s(async()=>{m=true,l&&(clearTimeout(l),l=null),await y.close(),p&&await p;},"stop")}}s(WW,"runWatch");tt();Zd();async function fy(e){let{config:t,configDir:r,canonicalDir:n}=e,o=await Ah(n);if(o===null)return {inSync:false,hasLock:false,modified:[],added:[],removed:[],extendsModified:[],lockedViolations:[]};let i=await fi(n),a=await gc(t,r),l=a.length>0?await Pm(a):{},c=new Set(Object.keys(o.checksums)),m=new Set(Object.keys(i)),p=[],u=[],f=[];for(let R of c){let k=i[R];k===void 0?f.push(R):k!==o.checksums[R]&&p.push(R);}for(let R of m)c.has(R)||u.push(R);let g=new Set([...Object.keys(o.extends),...Object.keys(l)]),h=[];for(let R of g)l[R]!==o.extends[R]&&h.push(R);let y=xh(o.checksums,i,t.collaboration?.lock_features??[]);return {inSync:p.length===0&&u.length===0&&f.length===0&&h.length===0,hasLock:true,modified:p,added:u,removed:f,extendsModified:h,lockedViolations:y}}s(fy,"checkLockSync");sn();async function HW(e,t){let r=t??process.cwd(),n=e.global===true?"global":"project",{config:o,context:i}=await _e(r,n);await ze(o,r);let a=await fy({config:o,configDir:i.configDir,canonicalDir:i.canonicalDir});return a.hasLock?{exitCode:a.inSync?0:1,data:{hasLock:true,inSync:a.inSync,modified:[...a.modified],added:[...a.added],removed:[...a.removed],extendsModified:[...a.extendsModified],lockedViolations:[...a.lockedViolations]}}:{exitCode:1,data:{hasLock:false,inSync:false,modified:[],added:[],removed:[],extendsModified:[],lockedViolations:[]}}}s(HW,"runCheck");tt();b();Zd();var Fte=".lock",Mte="<<<<<<<";async function sC(e){let t=join(e,Fte),r=await I(t);return r===null?false:r.includes(Mte)}s(sC,"hasLockConflict");async function VW(e,t,r){if(!await sC(e))throw new Error("No conflict to resolve.");let o=await fi(e),i=dirname(e),a=r?await gc(r,i):[],l=a.length>0?await Pm(a):{},c=await Ph(join(e,"packs")),m=process.env.USER??process.env.USERNAME??"unknown";await Th(e,{generatedAt:new Date().toISOString(),generatedBy:m,libVersion:t,checksums:o,extends:l,packs:c});}s(VW,"resolveLockConflict");async function JW(e,t){let r=t??process.cwd(),n=e.global===true?"global":"project",{config:o,context:i}=await _e(r,n),a=i.canonicalDir;return await sC(a)?(await VW(a,Pa(),o),{exitCode:0,data:{hadConflict:true,resolved:true}}):{exitCode:0,data:{hadConflict:false,resolved:false}}}s(JW,"runMerge");tt();Lh();function YW(e){let t=typeof e.path=="string"?e.path.trim():void 0,r=typeof e.target=="string"?e.target.trim():void 0,n=typeof e.as=="string"?e.as.trim():void 0,o=e["accept-elevated"]===true;return {sync:e.sync===true,dryRun:e["dry-run"]===true,force:e.force===true,useExtends:e.extends===true,all:e.all===true,forceFreshMaterialize:e.forceFreshMaterialize===true,explicitPath:t||void 0,explicitTarget:r||void 0,explicitAs:n?Tm.parse(n):void 0,nameOverride:typeof e.name=="string"?e.name.trim():"",acceptHooks:o||e["accept-hooks"]===true,acceptPermissions:o||e["accept-permissions"]===true,acceptMcp:o||e["accept-mcp"]===true}}s(YW,"readInstallFlags");var jte=".install.lock";async function Ym(e,t={}){return await mkdir(e,{recursive:true}),Nm(join(e,jte),{...t,label:"install lock"})}s(Ym,"acquireInstallLock");tt();b();kp();Fa();var Kte=promisify(execFile);function gy(e,t){if(e.startsWith("-"))throw new Error(`agentsmesh refuses ${t} starting with "-" (option-injection guard): ${e}`)}s(gy,"ensureNotFlag");async function iC(e){let{stdout:t}=await Kte("git",e,{env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ALLOW_PROTOCOL:Qd()}});return t.trim()}s(iC,"runGit");async function XW(){try{return await iC(["--version"]),!0}catch{return false}}s(XW,"isGitAvailable");async function Wte(e,t){gy(e,"remote-url"),gy(t,"ref"),Sp(e);let r=[t,`refs/heads/${t}`,`refs/tags/${t}`],n;for(let o of r)try{let a=(await iC(["ls-remote",e,o])).split(`
427
+ `).map(c=>c.trim()).find(c=>c.length>0);if(!a)continue;let l=a.split(/\s+/)[0];if(l&&/^[0-9a-f]{40}$/i.test(l))return l}catch(i){n=i;}throw new Error(`Could not resolve ref "${t}" for ${e}: ${n instanceof Error?n.message:String(n)}`)}s(Wte,"gitLsRemoteResolve");async function hy(e,t){gy(t,"remote-url");let r=e===""?"HEAD":e;if(gy(r,"ref"),/^[0-9a-f]{40}$/i.test(r))return r.toLowerCase();if(Sp(t),r==="HEAD"){let o=(await iC(["ls-remote",t,"HEAD"])).split(`
428
+ `).find(a=>a.trim().length>0);if(!o)throw new Error(`Could not resolve HEAD for ${t}`);let i=o.split(/\s+/)[0];if(!i||!/^[0-9a-f]{40}$/i.test(i))throw new Error(`Invalid ls-remote HEAD line for ${t}`);return i.toLowerCase()}return Wte(t,r)}s(hy,"resolveRemoteRefForInstall");async function QW(e){if(e.kind==="local")return {resolvedPath:e.localRoot,sourceForYaml:e.localSourceForYaml};let t=e.gitRemoteUrl;if(!t)throw new Error("Internal error: missing git remote URL");let r=await hy(e.rawRef||"HEAD",t);if(e.kind==="github"){let l=`github:${e.org}/${e.repo}@${r}`;return {resolvedPath:(await fc(l,"install",{cacheDir:tr(),refresh:false,allowOfflineFallback:false})).resolvedPath,sourceForYaml:l,version:r}}if(e.kind==="gitlab"){let l=`gitlab:${e.org}/${e.repo}@${r}`;return {resolvedPath:(await fc(l,"install",{cacheDir:tr(),refresh:false,allowOfflineFallback:false})).resolvedPath,sourceForYaml:l,version:r}}let n=r,i=`git+${(e.gitPlusBase??t).split("#")[0]}#${n}`;return {resolvedPath:(await fc(i,"install",{cacheDir:tr(),refresh:false,allowOfflineFallback:false})).resolvedPath,sourceForYaml:i,version:r}}s(QW,"fetchInstallSource");async function qW(e,t){if(e.kind==="local")return {resolvedPath:e.localRoot,sourceForYaml:e.localSourceForYaml};try{let r=await QW(e);return {resolvedPath:r.resolvedPath,sourceForYaml:r.sourceForYaml,version:r.version}}catch(r){let n=r instanceof Error?r.message:String(r),o=new Error(`Failed to fetch from ${t}: ${n}. Check your network connection and try again.`);throw r instanceof Error&&(o.cause=r),o}}s(qW,"resolveInstallResolvedPath");function dd(e){try{let t=new URL(e);if(t.hostname!=="github.com")return null;let r=t.pathname.split("/").filter(Boolean),n=r.indexOf("tree");if(n<2||n+1>=r.length)return null;let o=r[0],i=r[1],a=r[n+1],l=r.slice(n+2).join("/");return !o||!i||!a?null:{org:o,repo:i,ref:a,path:l||""}}catch{return null}}s(dd,"parseGithubTreeUrl");function fd(e){try{let t=new URL(e);if(t.hostname!=="github.com")return null;let r=t.pathname.split("/").filter(Boolean),n=r.indexOf("blob");if(n<2||n+1>=r.length)return null;let o=r[0],i=r[1],a=r[n+1],l=r.slice(n+2).join("/");return !o||!i||!a||!l?null:{org:o,repo:i,ref:a,path:l}}catch{return null}}s(fd,"parseGithubBlobUrl");function gd(e){try{let t=new URL(e);if(t.hostname!=="gitlab.com")return null;let r=t.pathname.split("/").filter(Boolean),n=r.indexOf("-");if(n<0||r[n+1]!=="tree")return null;let o=n+1;if(o+1>=r.length)return null;let i=r[o+1],a=r.slice(o+2).join("/"),l=r.slice(0,n);if(l.length<2)return null;let c=l[l.length-1],m=l.slice(0,-1).join("/");return !m||!c||!i?null:{namespace:m,project:c,ref:i,path:a||""}}catch{return null}}s(gd,"parseGitlabTreeUrl");function hd(e){try{let t=new URL(e);if(t.hostname!=="gitlab.com")return null;let r=t.pathname.split("/").filter(Boolean),n=r.indexOf("-");if(n<0||r[n+1]!=="blob")return null;let o=n+1;if(o+1>=r.length)return null;let i=r[o+1],a=r.slice(o+2).join("/"),l=r.slice(0,n);if(l.length<2)return null;let c=l[l.length-1],m=l.slice(0,-1).join("/");return !m||!c||!i||!a?null:{namespace:m,project:c,ref:i,path:a}}catch{return null}}s(hd,"parseGitlabBlobUrl");var Hte=new Set(["tree","blob","commit","releases","actions","issues","pulls","settings","wiki","discussions","security","projects","packages"]);function yd(e){try{let t=new URL(e);if(t.hostname!=="github.com")return null;let r=t.pathname.split("/").filter(Boolean).map(i=>i.replace(/\.git$/i,""));if(r.length<2||r.length>2||Hte.has(r[1]))return null;let n=r[0],o=r[1];return {org:n,repo:o}}catch{return null}}s(yd,"parseGithubRepoUrl");function _d(e){try{let t=new URL(e);if(t.hostname!=="gitlab.com")return null;let r=t.pathname.split("/").filter(Boolean).map(i=>i.replace(/\.git$/i,""));if(r.length<2||r.includes("-"))return null;let n=r[r.length-1],o=r.slice(0,-1).join("/");return !o||!n?null:{namespace:o,project:n}}catch{return null}}s(_d,"parseGitlabRepoUrl");function Sd(e){let t=e.match(/^git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/i);return t?{org:t[1],repo:t[2].replace(/\.git$/i,"")}:null}s(Sd,"parseGitSshGithub");function Rd(e){let t=e.match(/^git@gitlab\.com:(.+?)(?:\.git)?$/i);if(!t)return null;let n=t[1].replace(/\.git$/i,"").split("/").filter(Boolean);if(n.length<2)return null;let o=n[n.length-1];return {namespace:n.slice(0,-1).join("/"),project:o}}s(Rd,"parseGitSshGitlab");b();var Jte=/^[A-Za-z]:[\\/]/,Yte=/^[A-Za-z]:\//;function ZW(...e){return e.some(t=>t.includes("\\")||Jte.test(t))?win32:posix}s(ZW,"pathApiFor");function kd(e){return e.replace(/\\/g,"/")}s(kd,"toPosixPath");function Id(e){return kd(e).replace(/^\/+|\/+$/g,"")}s(Id,"normalizeInstallPathField");function yy(e){let t=kd(e);return t===""||t==="."||t==="./."?".":t.startsWith("./")||t.startsWith("../")||t.startsWith("/")||Yte.test(t)?t:`./${t}`}s(yy,"normalizeLocalSourceForYaml");function Ca(e){return {...e,source:e.source_kind==="local"?yy(e.source):e.source,...e.path!==void 0?{path:Id(e.path)}:{},...e.paths!==void 0?{paths:e.paths.map(t=>Id(t))}:{}}}s(Ca,"normalizePersistedInstallPaths");function eH(e,t,r){let n=ZW(e,t),o=n.normalize(e),i=n.normalize(t),a=Id(r),l=`${n.sep}.agentsmesh${n.sep}`,c=o.indexOf(l);if(c>=0){let p=o.slice(0,c),u=o.slice(c+l.length),f=Id(u),g=kd(n.relative(i,p))||".";return {kind:"local",rawRef:"",pathInRepo:a||f.replace(/\.md$/i,"").replace(/\/$/,""),localRoot:p,localSourceForYaml:yy(g)}}let m=kd(n.relative(i,o))||".";return {kind:"local",rawRef:"",pathInRepo:a,localRoot:o,localSourceForYaml:yy(m)}}s(eH,"localParsedFromAbsPath");async function aC(e,t,r){let n=e.trim(),o=r?.trim().replace(/\\/g,"/")??"";if(n.startsWith("git+")){let p=n.lastIndexOf("#"),u=p<0?n:n.slice(0,p),f=p<0?"HEAD":n.slice(p+1),g=u.slice(4);return {kind:"git",rawRef:f,gitPlusBase:g,gitRemoteUrl:g,pathInRepo:o}}if(n.startsWith("https://")||n.startsWith("http://")){let p=dd(n)??fd(n);if(p)return {kind:"github",rawRef:p.ref,org:p.org,repo:p.repo,gitRemoteUrl:`https://github.com/${p.org}/${p.repo}.git`,pathInRepo:o||p.path};let u=yd(n);if(u)return {kind:"github",rawRef:"HEAD",org:u.org,repo:u.repo,gitRemoteUrl:`https://github.com/${u.org}/${u.repo}.git`,pathInRepo:o};let f=gd(n)??hd(n);if(f)return {kind:"gitlab",rawRef:f.ref,org:f.namespace,repo:f.project,gitRemoteUrl:`https://gitlab.com/${f.namespace}/${f.project}.git`,pathInRepo:o||f.path};let g=_d(n);if(g)return {kind:"gitlab",rawRef:"HEAD",org:g.namespace,repo:g.project,gitRemoteUrl:`https://gitlab.com/${g.namespace}/${g.project}.git`,pathInRepo:o}}if(n.startsWith("git@github.com:")){let p=Sd(n);if(!p)throw new Error(`Invalid GitHub SSH URL: ${n}`);return {kind:"github",rawRef:"HEAD",org:p.org,repo:p.repo,gitRemoteUrl:`https://github.com/${p.org}/${p.repo}.git`,pathInRepo:o}}if(n.startsWith("git@gitlab.com:")){let p=Rd(n);if(!p)throw new Error(`Invalid GitLab SSH URL: ${n}`);return {kind:"gitlab",rawRef:"HEAD",gitRemoteUrl:`https://gitlab.com/${p.namespace}/${p.project}.git`,pathInRepo:o}}if(n.startsWith("git@")){let p=n.match(/^git@([^:]+):(.+?)(?:\.git)?$/);if(!p)throw new Error(`Invalid SSH git URL: ${n}`);let u=p[1],f=p[2].replace(/\.git$/i,"");return {kind:"git",rawRef:"HEAD",gitRemoteUrl:`ssh://git@${u}/${f}.git`,pathInRepo:o}}let i=n.match(/^github:([^/]+)\/(.+?)@([^/@]+)$/);if(i){let p=i[1],u=i[2];return {kind:"github",rawRef:i[3],org:p,repo:u,gitRemoteUrl:`https://github.com/${p}/${u}.git`,pathInRepo:o}}let a=n.match(/^github:([^/]+)\/([^/@]+)$/);if(a){let p=a[1],u=a[2];return {kind:"github",rawRef:"HEAD",org:p,repo:u,gitRemoteUrl:`https://github.com/${p}/${u}.git`,pathInRepo:o}}let l=n.match(/^gitlab:(.+)\/([^/@]+)@([^/@]+)$/);if(l){let p=l[1],u=l[2];return {kind:"gitlab",rawRef:l[3],org:p,repo:u,gitRemoteUrl:`https://gitlab.com/${p}/${u}.git`,pathInRepo:o}}let c=n.match(/^gitlab:(.+)\/([^/@]+)$/);if(c){let p=c[1],u=c[2];return {kind:"gitlab",rawRef:"HEAD",org:p,repo:u,gitRemoteUrl:`https://gitlab.com/${p}/${u}.git`,pathInRepo:o}}let m=resolve(t,n);if(!await j(m))throw new Error(`Path does not exist: ${m}`);return eH(m,t,o)}s(aC,"parseInstallSource");function Ld(e){let t=e.trim();if(t.startsWith("local:"))return {kind:"local"};if(t.startsWith("git+")){let a=t.lastIndexOf("#"),l=a<0?t:t.slice(0,a),c=a<0?"HEAD":t.slice(a+1);return {kind:"git",remoteUrl:l.slice(4),ref:c}}let r=t.match(/^github:([^/]+)\/(.+?)@([^/@]+)$/);if(r!==null){let a=r[1],l=r[2],c=r[3];return {kind:"github",remoteUrl:`https://github.com/${a}/${l}.git`,ref:c}}let n=t.match(/^github:([^/]+)\/([^/@]+)$/);if(n!==null){let a=n[1],l=n[2];return {kind:"github",remoteUrl:`https://github.com/${a}/${l}.git`,ref:"HEAD"}}let o=t.match(/^gitlab:(.+)\/([^/@]+)@([^/@]+)$/);if(o!==null){let a=o[1],l=o[2],c=o[3];return {kind:"gitlab",remoteUrl:`https://gitlab.com/${a}/${l}.git`,ref:c}}let i=t.match(/^gitlab:(.+)\/([^/@]+)$/);if(i!==null){let a=i[1],l=i[2];return {kind:"gitlab",remoteUrl:`https://gitlab.com/${a}/${l}.git`,ref:"HEAD"}}if(t.startsWith("https://")||t.startsWith("http://")){let a=dd(t)??fd(t);if(a!==null)return {kind:"github",remoteUrl:`https://github.com/${a.org}/${a.repo}.git`,ref:a.ref};let l=yd(t);if(l!==null)return {kind:"github",remoteUrl:`https://github.com/${l.org}/${l.repo}.git`,ref:"HEAD"};let c=gd(t)??hd(t);if(c!==null)return {kind:"gitlab",remoteUrl:`https://gitlab.com/${c.namespace}/${c.project}.git`,ref:c.ref};let m=_d(t);return m!==null?{kind:"gitlab",remoteUrl:`https://gitlab.com/${m.namespace}/${m.project}.git`,ref:"HEAD"}:{kind:"git",remoteUrl:t,ref:"HEAD"}}if(t.startsWith("git@github.com:")){let a=Sd(t);return a===null?null:{kind:"github",remoteUrl:`https://github.com/${a.org}/${a.repo}.git`,ref:"HEAD"}}if(t.startsWith("git@gitlab.com:")){let a=Rd(t);return a===null?null:{kind:"gitlab",remoteUrl:`https://gitlab.com/${a.namespace}/${a.project}.git`,ref:"HEAD"}}if(t.startsWith("git@")){let a=t.match(/^git@([^:]+):(.+?)(?:\.git)?$/);if(a===null)return null;let l=a[1],c=a[2].replace(/\.git$/i,"");return {kind:"git",remoteUrl:`ssh://git@${l}/${c}.git`,ref:"HEAD"}}return null}s(Ld,"parseSourceUrl");Wk();function Yn(e){let t=[];return e.skills.length&&t.push("skills"),e.rules.length&&t.push("rules"),e.commands.length&&t.push("commands"),e.agents.length&&t.push("agents"),e.mcp!==null&&t.push("mcp"),e.permissions!==null&&t.push("permissions"),e.hooks!==null&&t.push("hooks"),e.ignore.length&&t.push("ignore"),t}s(Yn,"featuresFromCanonical");async function _y(e,t={}){let{sliceRoot:r,implicitPick:n}=await yh(e),{canonical:o,cleanup:i}=await _h(r,{...t,enableTargetEntityMappers:true});return {canonical:o,features:Yn(o),implicitPick:n,cleanup:i}}s(_y,"discoverFromContentRoot");function tH(e){return e.description.trim()?{skill:e,ok:true}:{skill:e,ok:false,reason:"missing description in frontmatter"}}s(tH,"validateSkill");function rH(e){return e.description.trim()?{rule:e,ok:true}:{rule:e,ok:false,reason:"missing description in frontmatter"}}s(rH,"validateRule");function nH(e){return e.description.trim()?{command:e,ok:true}:{command:e,ok:false,reason:"missing description in frontmatter"}}s(nH,"validateCommand");function oH(e){return e.description.trim()?{agent:e,ok:true}:{agent:e,ok:false,reason:"missing description in frontmatter"}}s(oH,"validateAgent");function yt(e){return basename(e.source).replace(/\.md$/i,"")}s(yt,"ruleSlug");function qte(e){if(!e)return;let t=[];return e.skills!==void 0&&t.push("skills"),e.rules!==void 0&&t.push("rules"),e.commands!==void 0&&t.push("commands"),e.agents!==void 0&&t.push("agents"),t.length>0?t:void 0}s(qte,"featuresFromImplicitPick");function Qm(e,t){let{implicitPick:r}=t,n=t.scopedFeatures??qte(r);if(!r&&!n)return e;let o=new Set(n??[]),i={...e,mcp:!n||o.has("mcp")?e.mcp:null,permissions:!n||o.has("permissions")?e.permissions:null,hooks:!n||o.has("hooks")?e.hooks:null,ignore:!n||o.has("ignore")?e.ignore:[]};if(r?.skills!==void 0){let a=new Set(r.skills);i={...i,skills:r.skills.length===0?[]:i.skills.filter(l=>a.has(l.name))};}else n&&!o.has("skills")&&(i={...i,skills:[]});if(r?.rules!==void 0){let a=new Set(r.rules);i={...i,rules:r.rules.length===0?[]:i.rules.filter(l=>a.has(yt(l)))};}else n&&!o.has("rules")&&(i={...i,rules:[]});if(r?.commands!==void 0){let a=new Set(r.commands);i={...i,commands:r.commands.length===0?[]:i.commands.filter(l=>a.has(l.name))};}else n&&!o.has("commands")&&(i={...i,commands:[]});if(r?.agents!==void 0){let a=new Set(r.agents);i={...i,agents:r.agents.length===0?[]:i.agents.filter(l=>a.has(l.name))};}else n&&!o.has("agents")&&(i={...i,agents:[]});return i}s(Qm,"narrowDiscoveredForInstallScope");Qk();async function sH(e,t,r,n,o={}){let i=await Ih(e,t,{preferredSkillNames:t==="skills"?n?.skills:void 0}),{canonical:a,cleanup:l}=await _y(i.discoveryRoot,o),c=Qm(a,{scopedFeatures:[t]});return {prep:{yamlTarget:r,scopedFeatures:[t],cleanup:s(async()=>{await Promise.allSettled([l(),i.cleanup()]);},"combinedCleanup")},narrowed:c,discoveredFeatures:Yn(c)}}s(sH,"resolveManualDiscoveredForInstall");rs();Dk();b();Te();var Zte=(()=>{let e=new Map;for(let r of De){let n=r.project.managedOutputs,o=[...n?.dirs??[],...n?.files??[],...r.detectionPaths];for(let i of o){let a=i.replace(/\/$/,""),l=e.get(a)??new Set;l.add(r.id),e.set(a,l);}}let t=[];for(let[r,n]of e){if(n.size!==1)continue;let[o]=[...n];t.push({prefix:r,target:o});}return t.sort((r,n)=>n.prefix.length-r.prefix.length)})();function ere(e){return e.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"")}s(ere,"norm");function Sy(e){let t=ere(e);if(t){for(let{prefix:r,target:n}of Zte)if(t===r||t.startsWith(`${r}/`))return n}}s(Sy,"targetHintFromNativePath");function lC(e,t){return Sy(e)===t}s(lC,"pathSupportsNativePick");function iH(e,t){if(!e||!t)return;let r=Sy(t);if(r&&r!==e)throw new Error(`--target "${e}" does not match the install path (native path suggests "${r}"). Omit --target to auto-detect, or point at a subtree for that target.`)}s(iH,"validateTargetMatchesPath");function aH(e){return (e.commands?.length??0)+(e.rules?.length??0)+(e.skills?.length??0)+(e.agents?.length??0)>0}s(aH,"extendPickHasArrays");rt();b();oI();async function nre(e,t,r,n){if(n.kind==="skillDir")return gg(e);if(n.kind==="firstSegment"){let c=t.slice(r.prefix.length).split("/").filter(Boolean)[0];return c?[c]:[]}let o=await B(e),i=n.suffix,a=i.toLowerCase();return [...new Set(o.filter(l=>l.toLowerCase().endsWith(a)).map(l=>basename(l,i)))].sort()}s(nre,"namesForStrategy");async function lH(e,t,r){let n=ne(r)?.nativeInstall;if(!n)return {};let o=t.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"");if(n.inferPick)return n.inferPick(e,o);for(let i of n.pickPaths??[]){if(o!==i.prefix&&!o.startsWith(i.prefix))continue;let a=join(e,...o.split("/")),l=await nre(a,o,i,i.strategy);return l.length?{[i.feature]:l}:{}}return {}}s(lH,"inferImplicitPickFromNativePath");function cH(e){return (e.commands?.length??0)+(e.rules?.length??0)+(e.skills?.length??0)+(e.agents?.length??0)===0}s(cH,"isImplicitPickEmpty");Nk();function Cd(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}s(Cd,"normalizePath");function lre(e,t){let r=Cd(e),n=Cd(t);return r===n||r.startsWith(`${n}/`)||n.startsWith(`${r}/`)}s(lre,"overlapsPath");function Ry(e,t){let r=e??[];return r.includes(t)||r.push(t),r}s(Ry,"addUnique");async function cre(e){let t=await mkdtemp(join(tmpdir(),"am-install-native-")),r=join(t,"repo"),n=s(async()=>{await rm$1(t,{recursive:true,force:true});},"cleanup");try{return await cp$1(e,r,{recursive:!0}),{stageRoot:r,cleanup:n}}catch(o){throw await n(),o}}s(cre,"makeStageRoot");function mre(e,t){let r;for(let o of e){if(o.feature==="rules"&&o.toPath.startsWith(".agentsmesh/rules/")){r={...r,rules:Ry(r?.rules,basename(o.toPath,".md"))};continue}if(o.feature==="commands"&&o.toPath.startsWith(".agentsmesh/commands/")){let i=Cd(relative(join(t,".agentsmesh","commands"),join(t,o.toPath)));r={...r,commands:Ry(r?.commands,i.replace(/\.md$/i,"").split("/").filter(Boolean).join(":"))};continue}if(o.feature==="agents"&&o.toPath.startsWith(".agentsmesh/agents/")){r={...r,agents:Ry(r?.agents,basename(o.toPath,".md"))};continue}if(o.feature==="skills"&&o.toPath.startsWith(".agentsmesh/skills/")){let a=Cd(relative(join(t,".agentsmesh","skills"),join(t,o.toPath))).split("/")[0];a&&(r={...r,skills:Ry(r?.skills,a)});}}return r&&(r.rules?.length??0)+(r.commands?.length??0)+(r.agents?.length??0)+(r.skills?.length??0)>0?r:void 0}s(mre,"buildPickFromResults");function pre(e,t,r,n){let o=join(t,...Cd(e).split("/")),i=r.filter(a=>lre(o,a.fromPath));if(i.length===0)throw new Error(`No installable native resources found under "${e}" for target "${n}". Try --path "${e}" without --target so agentsmesh can auto-detect the layout, or use --as <rules|commands|agents|skills> to install the directory as a flat collection.`);return {features:[...new Set(i.map(a=>a.feature))],pick:mre(i,t)}}s(pre,"scopeImportedResults");async function cC(e,t){let{stageRoot:r,cleanup:n}=await cre(e);try{let o=await Wu(r,t);return {stageRoot:r,results:o,cleanup:n}}catch(o){throw await n(),o}}s(cC,"stageImportedNativeRepo");async function mC(e,t,r){let n=await cC(e,r);try{return {stageRoot:n.stageRoot,cleanup:n.cleanup,...pre(t,n.stageRoot,n.results,r)}}catch(o){throw await n.cleanup(),o}}s(mC,"stageNativeInstallScope");async function dH(e,t,r,n){let o=n.explicitTarget?.trim();o&&Or.parse(o);let i=r.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"");iH(o,i);let a=join(e,".agentsmesh"),l=await j(a),c=i?Sy(i):void 0,p=!l&&!o&&(!i||c!==void 0)?await ah(e)??void 0:void 0;if(!o&&c&&p&&c!==p)throw new Error(`Install path suggests native layout "${c}" but auto-detect imported "${p}". Use --target ${c} for this path, or install from the repo root without a conflicting subtree path.`);let u=o??c??p,f=!!i&&!!u&&!i.startsWith(".agentsmesh");if(!l&&u){if(f){let w=await mC(e,i,u);return {discoveryRoot:w.stageRoot,implicitPick:w.pick,scopedFeatures:w.features,yamlTarget:u,importHappened:true,cleanup:w.cleanup}}let k=await cC(e,u);return {discoveryRoot:i?join(k.stageRoot,i):k.stageRoot,yamlTarget:u,importHappened:true,cleanup:k.cleanup}}let g;l?i?u&&lC(i,u)?g=e:g=t:g=e:g=t;let h,y,_;if(f&&u){let k=await mC(e,i,u);g=k.stageRoot,h=k.pick,y=k.features,_=k.cleanup;}else if(g===e&&i&&u&&lC(i,u)&&(h=await lH(e,i,u),cH(h)))throw new Error(`No installable native resources found under "${i}" for target "${u}". Try --path "${i}" without --target so agentsmesh can auto-detect the layout, or use --as <rules|commands|agents|skills> to install the directory as a flat collection.`);let R;return o?R=o:u&&(h&&aH(h)||(y?.length??0)>0)&&(R=u),{discoveryRoot:g,implicitPick:h,scopedFeatures:y,yamlTarget:R,importHappened:_!==void 0,cleanup:_}}s(dH,"prepareInstallDiscovery");async function pC(e,t,r,n,o={}){let i=await dH(e,t,r,{explicitTarget:n}),{canonical:a,implicitPick:l,cleanup:c}=await _y(i.discoveryRoot,o),m=i.cleanup,u={...i,cleanup:s(async()=>{await Promise.allSettled([c(),...m?[m()]:[]]);},"mergedCleanup")},f=l??i.implicitPick,g=Qm(a,{implicitPick:f,scopedFeatures:i.scopedFeatures}),h=Yn(g);return {prep:u,discovered:a,implicitPick:f,narrowed:g,discoveredFeatures:h}}s(pC,"resolveDiscoveredForInstall");var fre=[".claude-plugin","marketplace.json"];async function gre(e){try{return (await stat(e)).isDirectory()}catch{return false}}s(gre,"dirExists");function hre(e){if(typeof e!="string"||e.length===0||e.startsWith("/"))return null;let t=e.replace(/^\.\/+/,"").replace(/\/+$/,"");return t.split("/").some(r=>r==="..")?null:t}s(hre,"normalizeSource");async function gH(e,t,r){let n=join(e,...fre),o;try{o=await readFile(n,"utf-8");}catch{return null}let i;try{i=JSON.parse(o);}catch{return null}if(typeof i!="object"||i===null||!Array.isArray(i.plugins))return null;let a=i.plugins,l=[];for(let c of a){if(typeof c!="object"||c===null)continue;let m=hre(c.source);if(!m)continue;let p=join(e,m);if(!await gre(p))continue;let u=await t(p,m);r(u)&&l.push({path:m,layout:u});}return l}s(gH,"detectMarketplaceSubPacks");async function Ed(e){try{return (await stat(e)).isDirectory()}catch{return false}}s(Ed,"dirExists");async function Ea(e){try{return (await readdir(e,{withFileTypes:!0})).map(r=>({name:r.name,isDir:r.isDirectory(),isFile:r.isFile()}))}catch{return []}}s(Ea,"listDirEntries");function hH(e){return e.endsWith(".instructions.md")?"copilot-instructions":e.endsWith(".md")?"md":e.endsWith(".mdc")?"mdc":e.endsWith(".toml")?"toml":null}s(hH,"classifyFileShape");var Sre=["rules","commands","agents","skills","mcp.json","hooks.yaml","permissions.yaml","ignore"],Rre=[".cursorrules",".windsurfrules"];async function _H(e){let t=join(e,".agentsmesh");if(!await Ed(t))return null;let r=await Ea(t),n=new Set(r.map(o=>o.name));for(let o of Sre)if(n.has(o))return {path:".agentsmesh"};return null}s(_H,"detectCanonical");async function SH(e){for(let t of Rre)try{if((await stat(join(e,t))).isFile())return {path:t}}catch{}return null}s(SH,"detectRootRule");async function RH(e){try{if((await stat(join(e,"SKILL.md"))).isFile())return {path:"SKILL.md"}}catch{}return null}s(RH,"detectRootSkill");ss();var kre={rules:"rules",commands:"commands",agents:"agents",skills:"skills"},Lre=[".claude-plugin",".codex-plugin",".cursor-plugin"],Cre=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;async function IH(e){let t=join(e,"skills"),r=await Ea(t);for(let n of r)if(!(!n.isDir||n.name.startsWith("_")||!Cre.test(n.name))&&await Ed(join(t,n.name)))try{if((await stat(join(t,n.name,"SKILL.md"))).isFile())return {path:"skills"}}catch{continue}return null}s(IH,"detectSkillPack");async function kH(e){let t=[];for(let[r,n]of Object.entries(kre)){let o=join(e,r),i=await Ea(o),a=new Set;for(let l of i){if(!l.isFile||qn(l.name))continue;let c=hH(l.name);c&&a.add(c);}for(let l of a)t.push({path:r,suggestedAs:n,fileShape:l});}return t}s(kH,"detectFlatCollections");async function LH(e){let t=[];for(let r of Lre)await Ed(join(e,r))&&t.push({path:r});return t}s(LH,"detectToolNativeManifests");async function fC(e,t){let r=await _H(e);if(r)return {canonical:r,skillPack:null,rootSkill:null,rootRule:null,flatCollections:[],toolNativeManifests:[]};let n=await IH(e),o=n?null:await RH(e),i=await kH(e),a=n||o||i.length>0?null:await SH(e),l=await LH(e);return {canonical:r,skillPack:n?{path:t?`${t}/skills`:"skills"}:null,rootSkill:o?{path:t?`${t}/SKILL.md`:"SKILL.md"}:null,rootRule:a?{path:t?`${t}/${a.path}`:a.path}:null,flatCollections:i.map(c=>({...c,path:t?`${t}/${c.path}`:c.path})),toolNativeManifests:l.map(c=>({path:t?`${t}/${c.path}`:c.path}))}}s(fC,"detectFlatLayout");function dC(e){return e.canonical!==null||e.skillPack!==null||e.rootSkill!==null||e.rootRule!==null||e.flatCollections.length>0}s(dC,"hasContent");async function CH(e,t){let r=await Ea(e),n=[];for(let o of r){if(!o.isDir||o.name.startsWith("."))continue;let i=join(e,o.name),a=t?`${t}/${o.name}`:o.name,l=await fC(i,a);dC(l)&&n.push({path:a,layout:l});}return n}s(CH,"collectSubPackCandidates");async function Ere(e,t){if(dC(t))return [];let r=await gH(e,fC,dC);if(r&&r.length>0)return r;let n=await CH(e,"");if(n.length>=2)return n;let o=await Ea(e);for(let i of o){if(!i.isDir||i.name.startsWith("."))continue;let a=await CH(join(e,i.name),i.name);if(a.length>=2)return a}return []}s(Ere,"detectSubPacks");async function OH(e){let t=await fC(e,"");if(t.canonical)return {...t,subPacks:[]};let r=await Ere(e,t);return {...t,subPacks:r}}s(OH,"detectLayout");rt();b();U();function wre(e){let t=[];for(let r of ff()){let n=ne(r)?.nativeInstall?.dialectHints;n?.length&&n.some(o=>o.frontmatterKey in e)&&t.push(r);}return t}s(wre,"targetsMatchingFrontmatter");async function bH(e){let t;try{t=await readdir(e);}catch{return null}let r=t.sort().find(a=>a.toLowerCase().endsWith(".mdc"));if(!r)return null;let n=await I(join(e,r));if(!n)return null;let o=mn(n,join(e,r));if(!o.ok)return null;let i=wre(o.value.frontmatter);return i.length===1?i[0]??null:null}s(bH,"inferMdcTarget");uh();hh();function Pre(e){let t=e.indexOf("#");return t<0?{path:e,anchor:""}:{path:e.slice(0,t),anchor:e.slice(t)}}s(Pre,"splitAnchor");function Dre(e){return e.split(sep).join("/")}s(Dre,"toForwardSlash");async function Nre(e){try{return await stat(e),!0}catch{return false}}s(Nre,"pathExists");async function PH(e){let{link:t,fromFile:r,contentRoot:n,includedPaths:o}=e,{path:i,anchor:a}=Pre(t.path);if(i===""||isAbsolute(i))return {link:t,classification:"unresolvable",resolvedRelative:null,anchor:a};let l=join(n,r,".."),c=normalize(resolve(l,i)),m=normalize(resolve(n)),p=relative(m,c);if(p.startsWith("..")||isAbsolute(p))return {link:t,classification:"unresolvable",resolvedRelative:null,anchor:a};let u=Dre(p);return await Nre(c)?o.has(u)?{link:t,classification:"in-tree-included",resolvedRelative:u,anchor:a}:{link:t,classification:"resolvable-outside",resolvedRelative:u,anchor:a}:{link:t,classification:"unresolvable",resolvedRelative:u,anchor:a}}s(PH,"resolveLink");var vre=/^(?:```|~~~)[^\n]*\n[\s\S]*?^(?:```|~~~)/gm,Fre=/(!?)\[[^\]\n]*\]\(([^)\n]+)\)/dg,Mre=/^\s*\[([^\]\n]+)\]:\s*(.+?)\s*$/dgm;function Gre(e){let t=[];for(let r of e.matchAll(vre)){let n=r.index??0;t.push([n,n+r[0].length]);}return t}s(Gre,"getFencedCodeRanges");function DH(e,t){for(let[r,n]of t)if(e>=r&&e<n)return true;return false}s(DH,"isInRanges");function gC(e){let t=e.length-e.trimStart().length,r=e.trim(),n=r.length,o=/^(.*?)\s+(["'])([\s\S]*?)\2\s*$/.exec(r);o?.[1]!==void 0&&(n=o[1].trimEnd().length);let i=t,a=r.slice(0,n);return a.length>=2&&a.startsWith("<")&&a.endsWith(">")&&(i+=1,n-=2),{start:i,length:n}}s(gC,"destPathSpan");function NH(e){let{start:t,length:r}=gC(e);return e.slice(t,t+r)}s(NH,"normalizeDestination");function Iy(e){let t=Gre(e),r=[];for(let n of e.matchAll(Fre)){let o=n.index??0;if(DH(o,t))continue;let i=n[1]==="!",a=n[2],l=n.indices?.[2];if(a===void 0||l===void 0)continue;let c=gC(a);r.push({kind:i?"image":"inline",destination:NH(a),destinationOffset:l[0]+c.start,destinationLength:c.length});}for(let n of e.matchAll(Mre)){let o=n.index??0;if(DH(o,t))continue;let i=(n[1]??"").trim(),a=n[2]??"",l=n.indices?.[2];if(i===""||a.trim()===""||l===void 0)continue;let c=gC(a);r.push({kind:"reference-def",destination:NH(a),label:i,destinationOffset:l[0]+c.start,destinationLength:c.length});}return r}s(Iy,"scanMarkdownLinks");function vH(e,t){if(t.length===0)return e;let r=[...t].sort((o,i)=>i.offset-o.offset),n=e;for(let o of r)n=`${n.slice(0,o.offset)}${o.replacement}${n.slice(o.offset+o.length)}`;return n}s(vH,"applyRangeRewrites");function $re(e){return !(e.length===0||e.startsWith("#")||e.startsWith("/")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))}s($re,"isCandidateRelativePath");function jre(e){let t=e.replaceAll("\\","/");return t==="{baseDir}"?".":t.startsWith("{baseDir}/")?t.slice(10):t}s(jre,"stripPath");function Ure(e){let t=e.destination;return $re(t)?{raw:t,path:jre(t),kind:e.kind,...e.label!==void 0?{label:e.label}:{}}:null}s(Ure,"toScannedLink");function FH(e){let t=[];for(let r of Iy(e)){let n=Ure(r);n!==null&&t.push(n);}return t}s(FH,"scanRelativeLinks");function qm(e,t){let r=e.replaceAll("\\","/"),n=t.replaceAll("\\","/"),o=r.endsWith("/")?r:`${r}/`;return n.startsWith(o)?n.slice(o.length):n}s(qm,"toForwardSlashRelative");function MH(e,t,r,n,o){let i=new Set;for(let a of t){i.add(qm(e,a.source));for(let l of a.supportingFiles)i.add(qm(e,l.absolutePath));}for(let a of r)i.add(qm(e,a.source));for(let a of n)i.add(qm(e,a.source));for(let a of o)i.add(qm(e,a.source));return i}s(MH,"buildIncludedPaths");function Kre(e,t,r,n){let o=[];for(let i of e)o.push({kind:"skill",name:i.name,body:i.body,sourcePath:i.source});for(let i of t)o.push({kind:"agent",name:i.name,body:i.body,sourcePath:i.source});for(let i of r)o.push({kind:"command",name:i.name,body:i.body,sourcePath:i.source});for(let i of n)o.push({kind:"rule",name:basename(i.source,".md"),body:i.body,sourcePath:i.source});return o}s(Kre,"listScannables");async function GH(e,t,r,n,o,i){let a=Kre(t,r,n,o),l=[];for(let c of a){let m=FH(c.body);if(m.length===0)continue;let p=qm(e,c.sourcePath),u=[];for(let f of m){let g=await PH({link:f,fromFile:p,contentRoot:e,includedPaths:i});g.classification!=="in-tree-included"&&u.push(g);}u.length>0&&l.push({entityKind:c.kind,entityName:c.name,resolved:u});}return l}s(GH,"detectBrokenLinks");hh();async function $H(e,t,r={}){let n=new Map,o=new Map,i=[],a=[...t].sort((p,u)=>p.precedence-u.precedence);for(let p of a){let{commands:u,cleanup:f}=await dh(join(e,p.dir),{restrictToTarget:p.target,parseOpts:r});i.push(f);for(let g of u){if(n.get(g.name)===void 0){n.set(g.name,{command:g,precedence:p.precedence});continue}let y=o.get(g.name)??[];y.push({path:g.source,precedence:p.precedence}),o.set(g.name,y);}}let l=[];for(let[p,u]of o){let f=n.get(p);if(f===void 0)throw new Error(`mergeCommands invariant: loser without winner for "${p}"`);l.push({basename:p,winnerPath:f.command.source,loserPaths:u.map(g=>g.path)});}return l.sort((p,u)=>p.basename.localeCompare(u.basename)),{commands:[...n.values()].map(p=>p.command).sort((p,u)=>p.name.localeCompare(u.name)),dedups:l,cleanup:s(async()=>{await Promise.allSettled(i.map(p=>p()));},"cleanup")}}s($H,"mergeCommands");async function jH(e,t,r={}){let[n,o,i,a]=await Promise.all([RU(`${e}/skills`,r),gh(`${e}/agents`,{parseOpts:r}),fh(`${e}/rules`,{parseOpts:r}),$H(e,t.mergeFromToolDirs,r)]),l=[...o.agents],c=[...i.rules],m=MH(e,n,l,a.commands,c),p=await GH(e,n,l,a.commands,c,m),u=s(async()=>{await Promise.allSettled([i.cleanup(),o.cleanup(),a.cleanup()]);},"cleanup");return {skills:n,agents:l,commands:a.commands,rules:c,dedups:a.dedups,brokenLinks:p,cleanup:u}}s(jH,"aggregateAnthropicSkillPack");var UH={mergeFromToolDirs:[{dir:"commands",precedence:0},{dir:".claude/commands",target:"claude-code",precedence:1},{dir:".gemini/commands",target:"gemini-cli",precedence:2}]};_c();function zre(e){return {rules:[...e.rules],commands:[...e.commands],agents:[...e.agents],skills:[...e.skills],mcp:null,permissions:null,hooks:null,ignore:[]}}s(zre,"aggregateToCanonical");function ky(){return {}}s(ky,"emptyPrep");async function Vre(e,t){let r=[];for(let n of t)if(n.fileShape==="mdc"&&!n.inferredTarget){let o=await bH(join(e,n.path));r.push(o?{...n,inferredTarget:o}:n);}else r.push(n);return r}s(Vre,"enrichMdcTargets");function KH(e){return e.canonical?"canonical-agentsmesh":e.skillPack||e.rootSkill?"anthropic-skill-pack":e.rootRule||e.toolNativeManifests.length>0?"tool-native":"unknown"}s(KH,"deriveSourceType");async function Jre(e,t){let r=await sf(e,t);return {rules:[],commands:[],agents:[],skills:r?[r]:[],mcp:null,permissions:null,hooks:null,ignore:[]}}s(Jre,"rootSkillToCanonical");async function Yre(e,t){let r=join(e,t),n=await readFile(r,"utf-8").catch(()=>""),o=`Imported from ${t}`;return {rules:n?[{source:r,root:true,targets:[],description:o,globs:[],body:n}]:[],commands:[],agents:[],skills:[],mcp:null,permissions:null,hooks:null,ignore:[]}}s(Yre,"rootRuleToCanonical");async function WH(e){let t=e.parseOpts??{};if(e.explicitAs)return {implicitPick:void 0,...await sH(e.contentRoot,e.explicitAs,e.explicitTarget,e.replayPick,t)};if(e.explicitTarget)return pC(e.resolvedPath,e.contentRoot,e.pathInRepo,e.explicitTarget,t);let r=await OH(e.contentRoot),n=await Vre(e.contentRoot,r.flatCollections),o={...r,flatCollections:n};if(o.skillPack&&!o.canonical){let a=await jH(e.contentRoot,UH,t),l=zre(a);return {prep:{cleanup:a.cleanup},implicitPick:void 0,narrowed:l,discoveredFeatures:Yn(l),layout:o,aggregate:a}}if(o.rootSkill&&!o.canonical&&!o.skillPack){let a=await Jre(e.contentRoot,t);return {prep:ky(),implicitPick:void 0,narrowed:a,discoveredFeatures:Yn(a),layout:o}}if(o.rootRule&&!o.canonical&&!o.skillPack&&!o.rootSkill&&o.flatCollections.length===0){let a=await Yre(e.contentRoot,o.rootRule.path);return {prep:ky(),implicitPick:void 0,narrowed:a,discoveredFeatures:Yn(a),layout:o}}return o.subPacks.length>0?{prep:ky(),implicitPick:void 0,narrowed:{rules:[],commands:[],agents:[],skills:[],mcp:null,permissions:null,hooks:null,ignore:[]},discoveredFeatures:[],layout:o}:o.flatCollections.length>0?{prep:ky(),implicitPick:void 0,narrowed:{rules:[],commands:[],agents:[],skills:[],mcp:null,permissions:null,hooks:null,ignore:[]},discoveredFeatures:[],layout:o}:{...await pC(e.resolvedPath,e.contentRoot,e.pathInRepo,e.explicitTarget,t),layout:o}}s(WH,"resolveInstallDiscovery");function zH(e){let t=new Set;e.skillPack&&t.add("skills"),e.rootSkill&&t.add("skills");for(let r of e.flatCollections)t.add(r.suggestedAs);return [...t]}s(zH,"featuresFromLayout");function Xre(e){return e.replace(/[/\\]+/g,"-").replace(/[^a-z0-9-]/gi,"").toLowerCase()}s(Xre,"subPackSlug");function HH(e,t,r){let n=zH(e.layout),o=!e.layout.skillPack&&!e.layout.rootSkill&&n.length>0;return {name:`${t}-${Xre(e.path)}`,source:r,path:e.path,...o?{as:n[0]}:{},features:n}}s(HH,"targetFromSubPack");function VH(e,t,r){return {name:t,source:r,path:e.path,as:e.suggestedAs,target:e.inferredTarget,features:[e.suggestedAs]}}s(VH,"targetFromCollection");function JH(e){let{layout:t,sourceName:r,sourceForYaml:n,explicitPath:o,explicitAs:i,explicitTarget:a}=e;if(o||i||a)return {targets:[],isMarketplace:false};if(t.canonical||t.skillPack)return {targets:[],isMarketplace:false};if(t.subPacks.length>=1)return Qre(e);if(t.flatCollections.length===1){let l=t.flatCollections[0];return {targets:[VH(l,r,n)],isMarketplace:false}}return t.flatCollections.length>1?qre(e):{targets:[],isMarketplace:false}}s(JH,"selectInstallCandidates");function Qre(e){let{layout:t,sourceName:r,sourceForYaml:n}=e;if(e.all)return {targets:t.subPacks.map(a=>HH(a,r,n)),isMarketplace:true};if(e.force||!e.tty){let a=t.subPacks.map(l=>({path:l.path,features:zH(l.layout)})).map(l=>` - ${l.path} (${l.features.join(", ")})`).join(`
429
429
  `);throw new Error(`Marketplace source with ${t.subPacks.length} sub-packs. Pass --all to install all, or use --path <subpath>:
430
- ${a}`)}return {targets:t.subPacks.map(i=>HH(i,r,n)),isMarketplace:true}}s(Yre,"selectMarketplace");function Xre(e){let{layout:t,sourceName:r,sourceForYaml:n}=e;if(e.force||!e.tty){let i=t.flatCollections.map(a=>` - ${a.path} (${a.suggestedAs}, .${a.fileShape})`).join(`
430
+ ${a}`)}return {targets:t.subPacks.map(i=>HH(i,r,n)),isMarketplace:true}}s(Qre,"selectMarketplace");function qre(e){let{layout:t,sourceName:r,sourceForYaml:n}=e;if(e.force||!e.tty){let i=t.flatCollections.map(a=>` - ${a.path} (${a.suggestedAs}, .${a.fileShape})`).join(`
431
431
  `);throw new Error(`Ambiguous source with ${t.flatCollections.length} resource collections. Pass --as <kind> to select, or --path <subpath>:
432
- ${i}`)}return {targets:t.flatCollections.map(i=>VH(i,r,n)),isMarketplace:false}}s(Xre,"selectMultipleCollections");sn();Hk();function Zm(e){return e==="."||e===""?void 0:e}s(Zm,"trimDot");function qre(e,t){let r=basename(t).replace(/\.md$/i,"");return e==="agents"?{agents:[r]}:e==="commands"?{commands:[r]}:{rules:[r]}}s(qre,"markdownPick");async function XH(e){if(!e.as)return {pathInRepo:Zm(e.pathInRepo)};let t=e.pathInRepo.replace(/^\/+|\/+$/g,""),r=await stat(e.contentRoot);if(e.as!=="skills"&&r.isFile()&&e.contentRoot.toLowerCase().endsWith(".md"))return {pathInRepo:Zm(dirname(t)),pick:qre(e.as,t||e.contentRoot)};if(e.as==="skills"){if(r.isFile()&&basename(e.contentRoot)==="SKILL.md"){let n=t?dirname(t):dirname(e.contentRoot);return {pathInRepo:Zm(dirname(n)),pick:{skills:[basename(n)]}}}if(r.isDirectory()){let n=t||basename(e.contentRoot),o=join(e.contentRoot.replace(/\/+$/g,""),"SKILL.md");try{if((await stat(o)).isFile()){let a=await Sh(o);return {pathInRepo:Zm(dirname(n)),pick:{skills:[a||basename(n)]}}}}catch{return {pathInRepo:Zm(t)}}}}return {pathInRepo:Zm(t)}}s(XH,"resolveManualInstallPersistence");Jo();fe();fe();async function ep(e,t,r){let n=e==="install"?"Pack is installed":e==="refresh"?"Refresh is committed":"Uninstall is committed",o=t==="global"?" --global":"";try{let i=await Xo(t==="global"?{global:!0}:{},r,{printMatrix:!1});Mm(i),i.exitCode!==0&&S.warn(`Generate failed after ${e}. ${n}; run agentsmesh generate${o}.`);}catch(i){let a=i instanceof Error?i.message:String(i);S.warn(`Generate failed after ${e}: ${a}`),S.warn(`${n}; run agentsmesh generate${o} after resolving the issue.`);}}s(ep,"runPostOperationGenerate");async function qo(e){return process.stdin.isTTY?new Promise(t=>{let r=QH.createInterface({input:process.stdin,output:process.stdout});r.question(`${e} (y/n) `,n=>{r.close();let o=n.trim().toLowerCase();t(o==="y"||o==="yes");});}):false}s(qo,"confirm");function Zre(e){return !!(e.skills.length||e.rules.length||e.commands.length||e.agents.length)}s(Zre,"hasArrayResources");function qH(e){return Zre(e)||e.mcp!==null||e.permissions!==null||e.hooks!==null||e.ignore.length>0}s(qH,"hasInstallableResources");async function ZH(e,t,r,n){let o=e.skills.map(l=>tH(l)),i=o.filter(l=>l.ok).map(l=>l.skill),a=o.filter(l=>!l.ok);if(!t&&!r&&n)for(let l of a)await qo(`Include invalid skill "${l.skill.name}" anyway? (${l.reason}). You can fix it later.`)&&i.push(l.skill);else t&&(i=o.map(l=>l.skill));return r&&(i=o.filter(l=>l.ok).map(l=>l.skill)),i}s(ZH,"resolveSkillPool");async function ez(e,t,r,n){let o=e.rules.map(l=>rH(l)),i=o.filter(l=>l.ok).map(l=>l.rule),a=o.filter(l=>!l.ok);if(!t&&!r&&n)for(let l of a)await qo(`Include invalid rule "${yt(l.rule)}" anyway? (${l.reason}). You can fix it later.`)&&i.push(l.rule);else t&&(i=o.map(l=>l.rule));return r&&(i=o.filter(l=>l.ok).map(l=>l.rule)),i}s(ez,"resolveRulePool");async function tz(e,t,r,n){let o=e.commands.map(l=>nH(l)),i=o.filter(l=>l.ok).map(l=>l.command),a=o.filter(l=>!l.ok);if(!t&&!r&&n)for(let l of a)await qo(`Include invalid command "${l.command.name}" anyway? (${l.reason}). You can fix it later.`)&&i.push(l.command);else t&&(i=o.map(l=>l.command));return r&&(i=o.filter(l=>l.ok).map(l=>l.command)),i}s(tz,"resolveCommandPool");async function rz(e,t,r,n){let o=e.agents.map(l=>oH(l)),i=o.filter(l=>l.ok).map(l=>l.agent),a=o.filter(l=>!l.ok);if(!t&&!r&&n)for(let l of a)await qo(`Include invalid agent "${l.agent.name}" anyway? (${l.reason}). You can fix it later.`)&&i.push(l.agent);else t&&(i=o.map(l=>l.agent));return r&&(i=o.filter(l=>l.ok).map(l=>l.agent)),i}s(rz,"resolveAgentPool");async function nz(e,t){let r=t.skills.map(a=>a.name),n=t.rules.map(a=>yt(a)),o=t.commands.map(a=>a.name),i=t.agents.map(a=>a.name);for(let a of t.skills)e.skills.some(l=>l.name===a.name)&&(await qo(`Skill "${a.name}" already exists in merged config. Add extend anyway?`)||(r=r.filter(c=>c!==a.name)));for(let a of t.rules){let l=yt(a);e.rules.some(c=>yt(c)===l)&&(await qo(`Rule "${l}" already exists in merged config. Add extend anyway?`)||(n=n.filter(m=>m!==l)));}for(let a of t.commands)e.commands.some(l=>l.name===a.name)&&(await qo(`Command "${a.name}" already exists in merged config. Add extend anyway?`)||(o=o.filter(c=>c!==a.name)));for(let a of t.agents)e.agents.some(l=>l.name===a.name)&&(await qo(`Agent "${a.name}" already exists in merged config. Add extend anyway?`)||(i=i.filter(c=>c!==a.name)));return {skillNames:r,ruleSlugs:n,commandNames:o,agentNames:i}}s(nz,"resolveInstallConflicts");function oz(e,t){if(!e)return;let r={},n=e.skills?.filter(l=>t.skillNames.includes(l)),o=e.rules?.filter(l=>t.ruleSlugs.includes(l)),i=e.commands?.filter(l=>t.commandNames.includes(l)),a=e.agents?.filter(l=>t.agentNames.includes(l));return n&&n.length>0&&(r.skills=n),o&&o.length>0&&(r.rules=o),i&&i.length>0&&(r.commands=i),a&&a.length>0&&(r.agents=a),Object.keys(r).length>0?r:void 0}s(oz,"pickForSelectedResources");function ene(e,t){let r=e.split("/").filter(Boolean);return r.length>0&&r[r.length-1]===t}s(ene,"pathEndsWithName");function Ly(e,t,r){return r!==1||t.length!==1?false:ene(e,t[0])}s(Ly,"inferSingleNamePick");function sz(e){let{pathInRepo:t,implicitPick:r,preConflictCounts:n,selected:o}=e,i={},a=o.skillNames.length>0&&(!!r?.skills?.length||o.skillNames.length<n.skills||Ly(t,o.skillNames,n.skills)),l=o.ruleSlugs.length>0&&(!!r?.rules?.length||o.ruleSlugs.length<n.rules||Ly(t,o.ruleSlugs,n.rules)),c=o.commandNames.length>0&&(!!r?.commands?.length||o.commandNames.length<n.commands||Ly(t,o.commandNames,n.commands)),m=o.agentNames.length>0&&(!!r?.agents?.length||o.agentNames.length<n.agents||Ly(t,o.agentNames,n.agents));return a&&(i.skills=[...o.skillNames]),l&&(i.rules=[...o.ruleSlugs]),c&&(i.commands=[...o.commandNames]),m&&(i.agents=[...o.agentNames]),Object.keys(i).length?i:void 0}s(sz,"buildInstallPick");function iz(e,t){let r=new Set(e);return t.skillNames.length===0&&r.delete("skills"),t.ruleSlugs.length===0&&r.delete("rules"),t.commandNames.length===0&&r.delete("commands"),t.agentNames.length===0&&r.delete("agents"),[...r]}s(iz,"deriveInstallFeatures");function tne(e){return e.skillNames.length===0&&e.ruleSlugs.length===0&&e.commandNames.length===0&&e.agentNames.length===0}s(tne,"isEmptyInstallSelection");function az(e){let{selected:t,discoveredFeatures:r,preConflict:n}=e,o=s(l=>r.includes(l),"had"),i=o("skills")&&t.skillNames.length===0&&n.skills>0&&"skills"||o("rules")&&t.ruleSlugs.length===0&&n.rules>0&&"rules"||o("commands")&&t.commandNames.length===0&&n.commands>0&&"commands"||o("agents")&&t.agentNames.length===0&&n.agents>0&&"agents";if(i)throw new Error(`No ${i} selected to install.`);let a=r.some(l=>["mcp","permissions","hooks","ignore"].includes(l));if(tne(t)&&!a)throw new Error("No resources selected to install.")}s(az,"ensureInstallSelection");rs();function lz(e,t){if(e.find(n=>n.name===t.name&&n.source!==t.source))throw new Error(`Extends entry "${t.name}" already exists with a different source. Use --name to provide a different name.`)}s(lz,"assertExtendNameAvailable");function rne(e,t,r){if(r===void 0){if(!e)return;let o={...e};for(let i of ["skills","commands","rules","agents"])t.includes(i)&&delete o[i];return Object.keys(o).length?o:void 0}let n={...e};for(let o of ["skills","commands","rules","agents"]){if(!(o in r))continue;let i=r[o];if(i===void 0||i.length===0){delete n[o];continue}n[o]=[...new Set([...e?.[o]??[],...i])];}return Object.keys(n).length?n:void 0}s(rne,"mergePick");function cz(e,t){let r=e.findIndex(a=>a.source===t.source);if(r<0)return [...e,{name:t.name,source:t.source,version:t.version,features:t.features,path:t.path,pick:t.pick,target:t.target,as:t.as}];let n=e[r],o=[...new Set([...n.features,...t.features])],i=rne(n.pick,t.features,t.pick);return e.map((a,l)=>l===r?{name:t.name,source:t.source,version:t.version??n.version,features:o,path:t.path!==void 0?t.path:n.path,pick:i,target:t.target??n.target,as:t.as??n.as}:a)}s(cz,"mergeExtendList");b();async function mz(e,t,r){let n=await I(e);if(n===null)throw new Error(`Missing config: ${e}`);let o=parse(n),i=cz(t.extends,r);o.extends=i;let a=stringify(o,{indent:2,lineWidth:0});await L(e,a.endsWith(`
432
+ ${i}`)}return {targets:t.flatCollections.map(i=>VH(i,r,n)),isMarketplace:false}}s(qre,"selectMultipleCollections");sn();Hk();function Zm(e){return e==="."||e===""?void 0:e}s(Zm,"trimDot");function ene(e,t){let r=basename(t).replace(/\.md$/i,"");return e==="agents"?{agents:[r]}:e==="commands"?{commands:[r]}:{rules:[r]}}s(ene,"markdownPick");async function XH(e){if(!e.as)return {pathInRepo:Zm(e.pathInRepo)};let t=e.pathInRepo.replace(/^\/+|\/+$/g,""),r=await stat(e.contentRoot);if(e.as!=="skills"&&r.isFile()&&e.contentRoot.toLowerCase().endsWith(".md"))return {pathInRepo:Zm(dirname(t)),pick:ene(e.as,t||e.contentRoot)};if(e.as==="skills"){if(r.isFile()&&basename(e.contentRoot)==="SKILL.md"){let n=t?dirname(t):dirname(e.contentRoot);return {pathInRepo:Zm(dirname(n)),pick:{skills:[basename(n)]}}}if(r.isDirectory()){let n=t||basename(e.contentRoot),o=join(e.contentRoot.replace(/\/+$/g,""),"SKILL.md");try{if((await stat(o)).isFile()){let a=await Sh(o);return {pathInRepo:Zm(dirname(n)),pick:{skills:[a||basename(n)]}}}}catch{return {pathInRepo:Zm(t)}}}}return {pathInRepo:Zm(t)}}s(XH,"resolveManualInstallPersistence");Jo();fe();fe();async function ep(e,t,r){let n=e==="install"?"Pack is installed":e==="refresh"?"Refresh is committed":"Uninstall is committed",o=t==="global"?" --global":"";try{let i=await Xo(t==="global"?{global:!0}:{},r,{printMatrix:!1});Mm(i),i.exitCode!==0&&S.warn(`Generate failed after ${e}. ${n}; run agentsmesh generate${o}.`);}catch(i){let a=i instanceof Error?i.message:String(i);S.warn(`Generate failed after ${e}: ${a}`),S.warn(`${n}; run agentsmesh generate${o} after resolving the issue.`);}}s(ep,"runPostOperationGenerate");async function qo(e){return process.stdin.isTTY?new Promise(t=>{let r=QH.createInterface({input:process.stdin,output:process.stdout});r.question(`${e} (y/n) `,n=>{r.close();let o=n.trim().toLowerCase();t(o==="y"||o==="yes");});}):false}s(qo,"confirm");function tne(e){return !!(e.skills.length||e.rules.length||e.commands.length||e.agents.length)}s(tne,"hasArrayResources");function qH(e){return tne(e)||e.mcp!==null||e.permissions!==null||e.hooks!==null||e.ignore.length>0}s(qH,"hasInstallableResources");async function ZH(e,t,r,n){let o=e.skills.map(l=>tH(l)),i=o.filter(l=>l.ok).map(l=>l.skill),a=o.filter(l=>!l.ok);if(!t&&!r&&n)for(let l of a)await qo(`Include invalid skill "${l.skill.name}" anyway? (${l.reason}). You can fix it later.`)&&i.push(l.skill);else t&&(i=o.map(l=>l.skill));return r&&(i=o.filter(l=>l.ok).map(l=>l.skill)),i}s(ZH,"resolveSkillPool");async function ez(e,t,r,n){let o=e.rules.map(l=>rH(l)),i=o.filter(l=>l.ok).map(l=>l.rule),a=o.filter(l=>!l.ok);if(!t&&!r&&n)for(let l of a)await qo(`Include invalid rule "${yt(l.rule)}" anyway? (${l.reason}). You can fix it later.`)&&i.push(l.rule);else t&&(i=o.map(l=>l.rule));return r&&(i=o.filter(l=>l.ok).map(l=>l.rule)),i}s(ez,"resolveRulePool");async function tz(e,t,r,n){let o=e.commands.map(l=>nH(l)),i=o.filter(l=>l.ok).map(l=>l.command),a=o.filter(l=>!l.ok);if(!t&&!r&&n)for(let l of a)await qo(`Include invalid command "${l.command.name}" anyway? (${l.reason}). You can fix it later.`)&&i.push(l.command);else t&&(i=o.map(l=>l.command));return r&&(i=o.filter(l=>l.ok).map(l=>l.command)),i}s(tz,"resolveCommandPool");async function rz(e,t,r,n){let o=e.agents.map(l=>oH(l)),i=o.filter(l=>l.ok).map(l=>l.agent),a=o.filter(l=>!l.ok);if(!t&&!r&&n)for(let l of a)await qo(`Include invalid agent "${l.agent.name}" anyway? (${l.reason}). You can fix it later.`)&&i.push(l.agent);else t&&(i=o.map(l=>l.agent));return r&&(i=o.filter(l=>l.ok).map(l=>l.agent)),i}s(rz,"resolveAgentPool");async function nz(e,t){let r=t.skills.map(a=>a.name),n=t.rules.map(a=>yt(a)),o=t.commands.map(a=>a.name),i=t.agents.map(a=>a.name);for(let a of t.skills)e.skills.some(l=>l.name===a.name)&&(await qo(`Skill "${a.name}" already exists in merged config. Add extend anyway?`)||(r=r.filter(c=>c!==a.name)));for(let a of t.rules){let l=yt(a);e.rules.some(c=>yt(c)===l)&&(await qo(`Rule "${l}" already exists in merged config. Add extend anyway?`)||(n=n.filter(m=>m!==l)));}for(let a of t.commands)e.commands.some(l=>l.name===a.name)&&(await qo(`Command "${a.name}" already exists in merged config. Add extend anyway?`)||(o=o.filter(c=>c!==a.name)));for(let a of t.agents)e.agents.some(l=>l.name===a.name)&&(await qo(`Agent "${a.name}" already exists in merged config. Add extend anyway?`)||(i=i.filter(c=>c!==a.name)));return {skillNames:r,ruleSlugs:n,commandNames:o,agentNames:i}}s(nz,"resolveInstallConflicts");function oz(e,t){if(!e)return;let r={},n=e.skills?.filter(l=>t.skillNames.includes(l)),o=e.rules?.filter(l=>t.ruleSlugs.includes(l)),i=e.commands?.filter(l=>t.commandNames.includes(l)),a=e.agents?.filter(l=>t.agentNames.includes(l));return n&&n.length>0&&(r.skills=n),o&&o.length>0&&(r.rules=o),i&&i.length>0&&(r.commands=i),a&&a.length>0&&(r.agents=a),Object.keys(r).length>0?r:void 0}s(oz,"pickForSelectedResources");function rne(e,t){let r=e.split("/").filter(Boolean);return r.length>0&&r[r.length-1]===t}s(rne,"pathEndsWithName");function Ly(e,t,r){return r!==1||t.length!==1?false:rne(e,t[0])}s(Ly,"inferSingleNamePick");function sz(e){let{pathInRepo:t,implicitPick:r,preConflictCounts:n,selected:o}=e,i={},a=o.skillNames.length>0&&(!!r?.skills?.length||o.skillNames.length<n.skills||Ly(t,o.skillNames,n.skills)),l=o.ruleSlugs.length>0&&(!!r?.rules?.length||o.ruleSlugs.length<n.rules||Ly(t,o.ruleSlugs,n.rules)),c=o.commandNames.length>0&&(!!r?.commands?.length||o.commandNames.length<n.commands||Ly(t,o.commandNames,n.commands)),m=o.agentNames.length>0&&(!!r?.agents?.length||o.agentNames.length<n.agents||Ly(t,o.agentNames,n.agents));return a&&(i.skills=[...o.skillNames]),l&&(i.rules=[...o.ruleSlugs]),c&&(i.commands=[...o.commandNames]),m&&(i.agents=[...o.agentNames]),Object.keys(i).length?i:void 0}s(sz,"buildInstallPick");function iz(e,t){let r=new Set(e);return t.skillNames.length===0&&r.delete("skills"),t.ruleSlugs.length===0&&r.delete("rules"),t.commandNames.length===0&&r.delete("commands"),t.agentNames.length===0&&r.delete("agents"),[...r]}s(iz,"deriveInstallFeatures");function nne(e){return e.skillNames.length===0&&e.ruleSlugs.length===0&&e.commandNames.length===0&&e.agentNames.length===0}s(nne,"isEmptyInstallSelection");function az(e){let{selected:t,discoveredFeatures:r,preConflict:n}=e,o=s(l=>r.includes(l),"had"),i=o("skills")&&t.skillNames.length===0&&n.skills>0&&"skills"||o("rules")&&t.ruleSlugs.length===0&&n.rules>0&&"rules"||o("commands")&&t.commandNames.length===0&&n.commands>0&&"commands"||o("agents")&&t.agentNames.length===0&&n.agents>0&&"agents";if(i)throw new Error(`No ${i} selected to install.`);let a=r.some(l=>["mcp","permissions","hooks","ignore"].includes(l));if(nne(t)&&!a)throw new Error("No resources selected to install.")}s(az,"ensureInstallSelection");rs();function lz(e,t){if(e.find(n=>n.name===t.name&&n.source!==t.source))throw new Error(`Extends entry "${t.name}" already exists with a different source. Use --name to provide a different name.`)}s(lz,"assertExtendNameAvailable");function one(e,t,r){if(r===void 0){if(!e)return;let o={...e};for(let i of ["skills","commands","rules","agents"])t.includes(i)&&delete o[i];return Object.keys(o).length?o:void 0}let n={...e};for(let o of ["skills","commands","rules","agents"]){if(!(o in r))continue;let i=r[o];if(i===void 0||i.length===0){delete n[o];continue}n[o]=[...new Set([...e?.[o]??[],...i])];}return Object.keys(n).length?n:void 0}s(one,"mergePick");function cz(e,t){let r=e.findIndex(a=>a.source===t.source);if(r<0)return [...e,{name:t.name,source:t.source,version:t.version,features:t.features,path:t.path,pick:t.pick,target:t.target,as:t.as}];let n=e[r],o=[...new Set([...n.features,...t.features])],i=one(n.pick,t.features,t.pick);return e.map((a,l)=>l===r?{name:t.name,source:t.source,version:t.version??n.version,features:o,path:t.path!==void 0?t.path:n.path,pick:i,target:t.target??n.target,as:t.as??n.as}:a)}s(cz,"mergeExtendList");b();async function mz(e,t,r){let n=await I(e);if(n===null)throw new Error(`Missing config: ${e}`);let o=parse(n),i=cz(t.extends,r);o.extends=i;let a=stringify(o,{indent:2,lineWidth:0});await L(e,a.endsWith(`
433
433
  `)?a:`${a}
434
- `);}s(mz,"writeAgentsmeshWithNewExtend");fe();async function pz(e){let{configDir:t,config:r,entryArgs:n,dryRun:o}=e,i=ine(n);if(lz(r.extends,i),o){S.info(`[dry-run] Would add extend:
435
- ${JSON.stringify(i,null,2)}`);return}let a=join(t,"agentsmesh.yaml");await mz(a,r,i),S.success(`Wrote extends entry "${i.name}" to agentsmesh.yaml.`);}s(pz,"writeInstallAsExtend");function ine(e){return {name:e.name,source:e.source,version:e.version,features:e.features,path:e.path,pick:e.pick,target:e.yamlTarget!==void 0?Or.parse(e.yamlTarget):void 0,as:e.as}}s(ine,"toNewExtendEntry");b();fe();b();var lne="pack.yaml";async function Cy(e){let t=await B(e),r=[];for(let i of t.sort()){let a=relative(e,i).replace(/\\/g,"/");if(a===lne)continue;let l=await wh(i);l!==null&&r.push(`${a}:${l}`);}let n=r.join(`
436
- `);return `sha256:${Oh(n)}`}s(Cy,"hashPackContent");b();var Lr=".agentsmesh-install-manifest.json",mne=["pack.yaml",Lr];z$1.object({name:z$1.string().min(1),source:z$1.string().min(1),installed_at:z$1.string().min(1),extends_id:z$1.string().nullable(),source_type:z$1.enum(["anthropic-skill-pack","canonical-agentsmesh","tool-native","unknown"]).nullable(),files:z$1.record(z$1.string().min(1),z$1.string().regex(/^sha256:[0-9a-f]{64}$/))});function pne(e,t){return relative(e,t).replaceAll("\\","/")}s(pne,"toForwardSlashRelative");async function Ey(e){let t=await B(e),r=[];for(let n of t){let o=pne(e,n);if(mne.includes(o))continue;let i=await bh(n);i!==null&&r.push([o,`sha256:${i}`]);}return r.sort(([n],[o])=>n.localeCompare(o)),Object.fromEntries(r)}s(Ey,"hashPackFiles");b();var une=/spdx-license-identifier:\s*([A-Za-z0-9.+-]+)/i,dne=[{id:"BSD-3-Clause",pattern:/redistribution and use in source and binary forms[\s\S]+?neither the name of[\s\S]+?contributors/i},{id:"BSD-2-Clause",pattern:/redistribution and use in source and binary forms/i},{id:"AGPL-3.0",pattern:/gnu affero general public license[\s\S]+?version 3/i},{id:"LGPL-3.0",pattern:/gnu lesser general public license[\s\S]+?version 3/i},{id:"LGPL-2.1",pattern:/gnu lesser general public license[\s\S]+?version 2\.1/i},{id:"GPL-3.0",pattern:/gnu general public license[\s\S]+?version 3/i},{id:"GPL-2.0",pattern:/gnu general public license[\s\S]+?version 2/i},{id:"MPL-2.0",pattern:/mozilla public license[\s\S]+?version 2\.0/i},{id:"Apache-2.0",pattern:/apache license[\s\S]+?version 2\.0/i},{id:"MIT",pattern:/permission is hereby granted, free of charge, to any person obtaining a copy/i},{id:"ISC",pattern:/permission to use, copy, modify,? and\/or distribute this software/i},{id:"Unlicense",pattern:/this is free and unencumbered software released into the public domain/i},{id:"CC0-1.0",pattern:/cc0 1\.0 universal/i}];function uz(e){if(e.trim().length===0)return null;let t=une.exec(e);if(t)return t[1]??null;for(let{id:r,pattern:n}of dne)if(n.test(e))return r;return null}s(uz,"detectSpdxLicense");var gne=["LICENSE","COPYING","NOTICE","COPYRIGHT"],hne=["",".md",".txt",".rst"];async function dz(e){for(let t of gne)for(let r of hne){let n=await I(join(e,`${t}${r}`));if(n===null)continue;let o=uz(n);if(o!==null)return o}return null}s(dz,"detectLicenseInPackDir");async function Sne(e,t){if(e.rules.length===0)return;let r=join(t,"rules");await O(r);for(let n of e.rules){let o=join(r,basename(n.source));await copyFile(n.source,o);}}s(Sne,"writeRules");async function Rne(e,t){if(e.commands.length===0)return;let r=join(t,"commands");await O(r);for(let n of e.commands){let o=join(r,basename(n.source));await copyFile(n.source,o);}}s(Rne,"writeCommands");async function Ine(e,t){if(e.agents.length===0)return;let r=join(t,"agents");await O(r);for(let n of e.agents){let o=join(r,basename(n.source));await copyFile(n.source,o);}}s(Ine,"writeAgents");async function kne(e,t){if(e.skills.length===0)return;let r=join(t,"skills");await O(r);for(let n of e.skills){let o=join(r,n.name);await O(o),await copyFile(n.source,join(o,"SKILL.md"));for(let i of n.supportingFiles){let a=join(o,i.relativePath);await O(dirname(a)),await copyFile(i.absolutePath,a);}}}s(kne,"writeSkills");async function Lne(e,t){for(let r of e)await copyFile(r.absolutePath,join(t,r.relativePath));}s(Lne,"writePreservedRootFiles");async function Cne(e,t){e.mcp!==null&&await L(join(t,"mcp.json"),`${JSON.stringify(e.mcp,null,2)}
434
+ `);}s(mz,"writeAgentsmeshWithNewExtend");fe();async function pz(e){let{configDir:t,config:r,entryArgs:n,dryRun:o}=e,i=lne(n);if(lz(r.extends,i),o){S.info(`[dry-run] Would add extend:
435
+ ${JSON.stringify(i,null,2)}`);return}let a=join(t,"agentsmesh.yaml");await mz(a,r,i),S.success(`Wrote extends entry "${i.name}" to agentsmesh.yaml.`);}s(pz,"writeInstallAsExtend");function lne(e){return {name:e.name,source:e.source,version:e.version,features:e.features,path:e.path,pick:e.pick,target:e.yamlTarget!==void 0?Or.parse(e.yamlTarget):void 0,as:e.as}}s(lne,"toNewExtendEntry");b();fe();b();var mne="pack.yaml";async function Cy(e){let t=await B(e),r=[];for(let i of t.sort()){let a=relative(e,i).replace(/\\/g,"/");if(a===mne)continue;let l=await wh(i);l!==null&&r.push(`${a}:${l}`);}let n=r.join(`
436
+ `);return `sha256:${Oh(n)}`}s(Cy,"hashPackContent");b();var Lr=".agentsmesh-install-manifest.json",une=["pack.yaml",Lr];z$1.object({name:z$1.string().min(1),source:z$1.string().min(1),installed_at:z$1.string().min(1),extends_id:z$1.string().nullable(),source_type:z$1.enum(["anthropic-skill-pack","canonical-agentsmesh","tool-native","unknown"]).nullable(),files:z$1.record(z$1.string().min(1),z$1.string().regex(/^sha256:[0-9a-f]{64}$/))});function dne(e,t){return relative(e,t).replaceAll("\\","/")}s(dne,"toForwardSlashRelative");async function Ey(e){let t=await B(e),r=[];for(let n of t){let o=dne(e,n);if(une.includes(o))continue;let i=await bh(n);i!==null&&r.push([o,`sha256:${i}`]);}return r.sort(([n],[o])=>n.localeCompare(o)),Object.fromEntries(r)}s(Ey,"hashPackFiles");b();var fne=/spdx-license-identifier:\s*([A-Za-z0-9.+-]+)/i,gne=[{id:"BSD-3-Clause",pattern:/redistribution and use in source and binary forms[\s\S]+?neither the name of[\s\S]+?contributors/i},{id:"BSD-2-Clause",pattern:/redistribution and use in source and binary forms/i},{id:"AGPL-3.0",pattern:/gnu affero general public license[\s\S]+?version 3/i},{id:"LGPL-3.0",pattern:/gnu lesser general public license[\s\S]+?version 3/i},{id:"LGPL-2.1",pattern:/gnu lesser general public license[\s\S]+?version 2\.1/i},{id:"GPL-3.0",pattern:/gnu general public license[\s\S]+?version 3/i},{id:"GPL-2.0",pattern:/gnu general public license[\s\S]+?version 2/i},{id:"MPL-2.0",pattern:/mozilla public license[\s\S]+?version 2\.0/i},{id:"Apache-2.0",pattern:/apache license[\s\S]+?version 2\.0/i},{id:"MIT",pattern:/permission is hereby granted, free of charge, to any person obtaining a copy/i},{id:"ISC",pattern:/permission to use, copy, modify,? and\/or distribute this software/i},{id:"Unlicense",pattern:/this is free and unencumbered software released into the public domain/i},{id:"CC0-1.0",pattern:/cc0 1\.0 universal/i}];function uz(e){if(e.trim().length===0)return null;let t=fne.exec(e);if(t)return t[1]??null;for(let{id:r,pattern:n}of gne)if(n.test(e))return r;return null}s(uz,"detectSpdxLicense");var yne=["LICENSE","COPYING","NOTICE","COPYRIGHT"],_ne=["",".md",".txt",".rst"];async function dz(e){for(let t of yne)for(let r of _ne){let n=await I(join(e,`${t}${r}`));if(n===null)continue;let o=uz(n);if(o!==null)return o}return null}s(dz,"detectLicenseInPackDir");async function Ine(e,t){if(e.rules.length===0)return;let r=join(t,"rules");await O(r);for(let n of e.rules){let o=join(r,basename(n.source));await copyFile(n.source,o);}}s(Ine,"writeRules");async function kne(e,t){if(e.commands.length===0)return;let r=join(t,"commands");await O(r);for(let n of e.commands){let o=join(r,basename(n.source));await copyFile(n.source,o);}}s(kne,"writeCommands");async function Lne(e,t){if(e.agents.length===0)return;let r=join(t,"agents");await O(r);for(let n of e.agents){let o=join(r,basename(n.source));await copyFile(n.source,o);}}s(Lne,"writeAgents");async function Cne(e,t){if(e.skills.length===0)return;let r=join(t,"skills");await O(r);for(let n of e.skills){let o=join(r,n.name);await O(o),await copyFile(n.source,join(o,"SKILL.md"));for(let i of n.supportingFiles){let a=join(o,i.relativePath);await O(dirname(a)),await copyFile(i.absolutePath,a);}}}s(Cne,"writeSkills");async function Ene(e,t){for(let r of e)await copyFile(r.absolutePath,join(t,r.relativePath));}s(Ene,"writePreservedRootFiles");async function One(e,t){e.mcp!==null&&await L(join(t,"mcp.json"),`${JSON.stringify(e.mcp,null,2)}
437
437
  `),e.permissions!==null&&await L(join(t,"permissions.yaml"),stringify(e.permissions)),e.hooks!==null&&await L(join(t,"hooks.yaml"),stringify(e.hooks)),e.ignore.length>0&&await L(join(t,"ignore"),`${e.ignore.join(`
438
438
  `)}
439
- `);}s(Cne,"writeSettings");function Ene(e){if(e.includes("/")||e.includes("\\")||e===".."||e==="."||e.includes("\0"))throw new Error(`Invalid pack name "${e}". Pack names must be a single directory segment without path separators.`)}s(Ene,"validatePackName");async function One(e,t,r){let n=await Ey(e),o=mW({name:t.name,source:t.source,installed_at:t.installed_at,extends_id:r.extends_id??null,source_type:r.source_type??null,files:n},"install-manifest");await L(join(e,Lr),`${JSON.stringify(o,null,2)}
440
- `);}s(One,"writeInstallManifest");async function fz(e,t,r,n,o={},i=[]){Ene(t);let a=join(e,`${t}.tmp`),l=join(e,`${t}.old`),c=join(e,t);await j(a)&&await rm$1(a,{recursive:true,force:true}),await j(l)&&await rm$1(l,{recursive:true,force:true});let m,p=false;try{await O(a),await Sne(r,a),await Rne(r,a),await Ine(r,a),await kne(r,a),await Cne(r,a),await Lne(i,a);let u=await Cy(a),f=await dz(a);m=Ca({...n,content_hash:u,license:f}),await L(join(a,"pack.yaml"),Xl(stringify(m),"pack")),await One(a,m,o),await mkdir(e,{recursive:!0}),await j(c)&&(await rename(c,l),p=!0);try{await rename(a,c);}catch(g){throw p&&(await rename(l,c).catch(h=>{let y=h instanceof Error?h.message:String(h);S.warn(`Failed to restore the previous pack after a failed atomic swap; the prior contents remain at "${l}". Recover them manually. (${y})`);}),p=!1),g}}catch(u){throw await rm$1(a,{recursive:true,force:true}).catch(()=>{}),u}return p&&await rm$1(l,{recursive:true,force:true}).catch(()=>{}),m}s(fz,"materializePack");xm();b();function IC(e,t){return [...new Set([...e,...t])]}s(IC,"union");function bne(e,t){if(e.path===void 0&&e.paths===void 0||t===void 0)return {path:void 0,paths:void 0};let n=IC(e.paths??(e.path?[e.path]:[]),[t]);return n.length===1?{path:n[0],paths:void 0}:{path:void 0,paths:n}}s(bne,"mergePathScope");function Ane(e,t,r){let n={...e};for(let i of t)r&&r[i]!==void 0?n[i]=IC(n[i]??[],r[i]):delete n[i];return (n.skills?.length??0)>0||(n.rules?.length??0)>0||(n.commands?.length??0)>0||(n.agents?.length??0)>0?n:void 0}s(Ane,"mergePick");async function Tne(e,t){if(e.rules.length===0)return;let r=join(t,"rules");await O(r);for(let n of e.rules)await copyFile(n.source,join(r,basename(n.source)));}s(Tne,"mergeRules");async function xne(e,t){if(e.commands.length===0)return;let r=join(t,"commands");await O(r);for(let n of e.commands)await copyFile(n.source,join(r,basename(n.source)));}s(xne,"mergeCommands");async function Pne(e,t){if(e.agents.length===0)return;let r=join(t,"agents");await O(r);for(let n of e.agents)await copyFile(n.source,join(r,basename(n.source)));}s(Pne,"mergeAgents");async function Dne(e,t){if(e.skills.length===0)return;let r=join(t,"skills");await O(r);for(let n of e.skills){let o=join(r,n.name);await O(o),await copyFile(n.source,join(o,"SKILL.md"));for(let i of n.supportingFiles){let a=join(o,i.relativePath);await O(dirname(a)),await copyFile(i.absolutePath,a);}}}s(Dne,"mergeSkills");async function Nne(e,t){for(let r of e)await copyFile(r.absolutePath,join(t,r.relativePath));}s(Nne,"mergePreservedRootFiles");async function vne(e,t){e.mcp!==null&&await L(join(t,"mcp.json"),`${JSON.stringify(e.mcp,null,2)}
439
+ `);}s(One,"writeSettings");function wne(e){if(e.includes("/")||e.includes("\\")||e===".."||e==="."||e.includes("\0"))throw new Error(`Invalid pack name "${e}". Pack names must be a single directory segment without path separators.`)}s(wne,"validatePackName");async function bne(e,t,r){let n=await Ey(e),o=mW({name:t.name,source:t.source,installed_at:t.installed_at,extends_id:r.extends_id??null,source_type:r.source_type??null,files:n},"install-manifest");await L(join(e,Lr),`${JSON.stringify(o,null,2)}
440
+ `);}s(bne,"writeInstallManifest");async function fz(e,t,r,n,o={},i=[]){wne(t);let a=join(e,`${t}.tmp`),l=join(e,`${t}.old`),c=join(e,t);await j(a)&&await rm$1(a,{recursive:true,force:true}),await j(l)&&await rm$1(l,{recursive:true,force:true});let m,p=false;try{await O(a),await Ine(r,a),await kne(r,a),await Lne(r,a),await Cne(r,a),await One(r,a),await Ene(i,a);let u=await Cy(a),f=await dz(a);m=Ca({...n,content_hash:u,license:f}),await L(join(a,"pack.yaml"),Xl(stringify(m),"pack")),await bne(a,m,o),await mkdir(e,{recursive:!0}),await j(c)&&(await rename(c,l),p=!0);try{await rename(a,c);}catch(g){throw p&&(await rename(l,c).catch(h=>{let y=h instanceof Error?h.message:String(h);S.warn(`Failed to restore the previous pack after a failed atomic swap; the prior contents remain at "${l}". Recover them manually. (${y})`);}),p=!1),g}}catch(u){throw await rm$1(a,{recursive:true,force:true}).catch(()=>{}),u}return p&&await rm$1(l,{recursive:true,force:true}).catch(()=>{}),m}s(fz,"materializePack");xm();b();function IC(e,t){return [...new Set([...e,...t])]}s(IC,"union");function Tne(e,t){if(e.path===void 0&&e.paths===void 0||t===void 0)return {path:void 0,paths:void 0};let n=IC(e.paths??(e.path?[e.path]:[]),[t]);return n.length===1?{path:n[0],paths:void 0}:{path:void 0,paths:n}}s(Tne,"mergePathScope");function xne(e,t,r){let n={...e};for(let i of t)r&&r[i]!==void 0?n[i]=IC(n[i]??[],r[i]):delete n[i];return (n.skills?.length??0)>0||(n.rules?.length??0)>0||(n.commands?.length??0)>0||(n.agents?.length??0)>0?n:void 0}s(xne,"mergePick");async function Pne(e,t){if(e.rules.length===0)return;let r=join(t,"rules");await O(r);for(let n of e.rules)await copyFile(n.source,join(r,basename(n.source)));}s(Pne,"mergeRules");async function Dne(e,t){if(e.commands.length===0)return;let r=join(t,"commands");await O(r);for(let n of e.commands)await copyFile(n.source,join(r,basename(n.source)));}s(Dne,"mergeCommands");async function Nne(e,t){if(e.agents.length===0)return;let r=join(t,"agents");await O(r);for(let n of e.agents)await copyFile(n.source,join(r,basename(n.source)));}s(Nne,"mergeAgents");async function vne(e,t){if(e.skills.length===0)return;let r=join(t,"skills");await O(r);for(let n of e.skills){let o=join(r,n.name);await O(o),await copyFile(n.source,join(o,"SKILL.md"));for(let i of n.supportingFiles){let a=join(o,i.relativePath);await O(dirname(a)),await copyFile(i.absolutePath,a);}}}s(vne,"mergeSkills");async function Fne(e,t){for(let r of e)await copyFile(r.absolutePath,join(t,r.relativePath));}s(Fne,"mergePreservedRootFiles");async function Mne(e,t){e.mcp!==null&&await L(join(t,"mcp.json"),`${JSON.stringify(e.mcp,null,2)}
441
441
  `),e.permissions!==null&&await L(join(t,"permissions.yaml"),stringify(e.permissions)),e.hooks!==null&&await L(join(t,"hooks.yaml"),stringify(e.hooks)),e.ignore.length>0&&await L(join(t,"ignore"),`${e.ignore.join(`
442
442
  `)}
443
- `);}s(vne,"mergeSettings");async function gz(e,t,r,n,o,i,a=[]){await Tne(r,e),await xne(r,e),await Pne(r,e),await Dne(r,e),await vne(r,e),await Nne(a,e);let l=IC(t.features,n),c=Ane(t.pick,n,o),m=bne(t,i?.path),p=await Cy(e),u=new Date().toISOString(),f=Ca({...t,source:i?.source??t.source,...i?.version!==void 0?{version:i.version}:t.version!==void 0?{version:t.version}:{},features:l,pick:c,...i?.target!==void 0?{target:i.target}:t.target!==void 0?{target:t.target}:{},...m,...i?.as!==void 0?{as:i.as}:t.as!==void 0?{as:t.as}:{},updated_at:u,content_hash:p});return await L(join(e,"pack.yaml"),Xl(stringify(f),"pack")),f}s(gz,"mergeIntoPack");L_();ss();async function hz(e){let t=[];try{let r=await readdir(e,{withFileTypes:!0});for(let n of r)n.isFile()&&rf(n.name)&&t.push({relativePath:n.name,absolutePath:join(e,n.name)});}catch{return []}return t.sort((r,n)=>r.relativePath.localeCompare(n.relativePath)),t}s(hz,"collectPreservedRootFiles");rs();fe();rs();b();Lh();function $ne(e){return e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}s($ne,"sanitize");function jne(e){try{let r=new URL(e.replace(/^git\+/,"https://").replace(/^ssh:\/\/git@/,"https://")).pathname.split("/").filter(Boolean);if(r.length===0)return "repo";let n=r[r.length-1].replace(/\.git$/i,"");return r.length>=2?`${r[r.length-2].replace(/\.git$/i,"")}-${n}`:n}catch{return "repo"}}s(jne,"gitUrlLastSegments");function yz(e,t,r){let n;if(e.kind==="local"){let l=(e.localRoot??"local").split(/[/\\]/).filter(Boolean);n=l[l.length-1]??"local";}else e.kind==="github"&&e.org&&e.repo?n=`${e.org}-${e.repo}`:e.kind==="gitlab"&&e.org&&e.repo?n=`${e.org.replace(/\//g,"-")}-${e.repo}`:e.gitRemoteUrl?n=jne(e.gitRemoteUrl):n="extend";t.featureHint?n=`${n}-${t.featureHint}`:n=`${n}-pack`;let o=$ne(n)||"extend";if(!r.has(o))return o;let i=2;for(;r.has(`${o}-${i}`);)i++;return `${o}-${i}`}s(yz,"suggestExtendName");function _z(e){let{config:t,parsed:r,entryFeatures:n,nameOverride:o}=e,i=new Set(t.extends.map(a=>a.name));return o||yz(r,{featureHint:n.length===1?n[0]:void 0},i)}s(_z,"selectInstallEntryName");function Sz(e){let t=e.trim();for(;t.startsWith("git+");){let c=t.lastIndexOf("#");t=(c<0?t.slice(4):t.slice(4,c)).trim();}let r=t.match(/^github:([^/]+)\/([^/@]+?)(?:\.git)?(?:@[^/]+)?$/i);if(r)return `github:${r[1].toLowerCase()}/${r[2].toLowerCase()}`;let n=t.match(/^gitlab:(.+?)\/([^/@]+?)(?:\.git)?(?:@[^/]+)?$/i);if(n)return `gitlab:${n[1].toLowerCase()}/${n[2].toLowerCase()}`;let o=t.match(/^https?:\/\/github\.com\/([^/]+)\/([^/?#]+?)(?:\.git)?(?:[/?#].*)?$/i);if(o)return `github:${o[1].toLowerCase()}/${o[2].toLowerCase()}`;let i=t.match(/^https?:\/\/gitlab\.com\/(.+?)\/([^/?#]+?)(?:\.git)?(?:[/?#].*)?$/i);if(i)return `gitlab:${i[1].toLowerCase()}/${i[2].toLowerCase()}`;let a=t.match(/^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/i);if(a)return `github:${a[1].toLowerCase()}/${a[2].toLowerCase()}`;let l=t.match(/^git@gitlab\.com:(.+?)\/([^/]+?)(?:\.git)?$/i);return l?`gitlab:${l[1].toLowerCase()}/${l[2].toLowerCase()}`:null}s(Sz,"canonicalRemoteIdentity");function Une(e){return e.kind==="github"&&e.org&&e.repo?`github:${e.org.toLowerCase()}/${e.repo.toLowerCase()}`:e.kind==="gitlab"&&e.org&&e.repo?`gitlab:${e.org.toLowerCase()}/${e.repo.toLowerCase()}`:e.gitRemoteUrl?Sz(e.gitRemoteUrl):null}s(Une,"parsedSourceIdentity");function Rz(e,t){let r=Une(t);if(r===null)return null;for(let n of e){let o=Sz(n.source);if(o!==null&&o===r)return n.name}return null}s(Rz,"findExistingInstallName");function kC(e,t){if(e.length!==t.length)return false;let r=[...e].sort(),n=[...t].sort();for(let o=0;o<r.length;o++)if(r[o]!==n[o])return false;return true}s(kC,"sameFeatureSet");function Iz(e){let{manifest:t,parsed:r,entryFeatures:n,yamlTarget:o,explicitAs:i}=e,a=Rz(t,r);if(a===null)return null;let l=t.find(c=>c.name===a);return l.target!==o||l.as!==i||!kC(l.features,n)?null:l.name}s(Iz,"pickReuseEntryName");var Wne=s(e=>!e.includes("/")&&!e.includes("\\")&&!e.includes("\0")&&e!=="."&&e!=="..","isSafeInstallName"),Lz=z$1.object({name:z$1.string().min(1).refine(Wne,{message:'install name must not contain path separators, NUL, or "."/".." segments'}),source:z$1.string().min(1),version:z$1.string().optional(),source_kind:z$1.enum(["github","gitlab","git","local"]),features:z$1.array(uc).min(1),pick:_p.optional(),target:Or.optional(),path:z$1.string().optional(),paths:z$1.array(z$1.string().min(1)).min(1).optional(),as:Tm.optional(),refreshed_at:z$1.string().min(1).optional(),original_ref:z$1.string().optional(),accepted_elevated:z$1.array(z$1.enum(["hooks","permissions","mcp"])).min(1).optional()}),Hne=z$1.object({version:z$1.literal(1),installs:z$1.array(Lz).default([])});function zne(e,t){return e.source===t.source&&e.target===t.target&&e.as===t.as&&kC(e.features,t.features)}s(zne,"sameInstallIdentity");function LC(e){return join(e,"installs.yaml")}s(LC,"manifestPath");async function Zt(e){let t=await I(LC(e));if(t===null)return [];try{return Hne.parse(parse(t)).installs.map(r=>Ca(r))}catch{return []}}s(Zt,"readInstallManifest");async function wy(e,t){let r=Ca(t),o=(await Zt(e)).filter(i=>i.name!==r.name&&!zne(i,r));o.push(r),await L(LC(e),Xl(stringify({version:1,installs:o.sort((i,a)=>i.name.localeCompare(a.name))}),"installs"));}s(wy,"upsertInstallManifestEntry");async function Cz(e,t){let r=await Zt(e),n=r.filter(o=>o.name!==t);return n.length===r.length?false:(await L(LC(e),Xl(stringify({version:1,installs:n.sort((o,i)=>o.name.localeCompare(i.name))}),"installs")),true)}s(Cz,"removeInstallManifestEntry");function Ez(e){return Ca(Lz.parse({name:e.name,source:e.source,version:e.version,source_kind:e.sourceKind,features:e.features,pick:e.pick,target:e.target,path:e.path,paths:e.paths,as:e.as,refreshed_at:e.refreshed_at,original_ref:e.originalRef,accepted_elevated:e.acceptedElevated}))}s(Ez,"buildInstallManifestEntry");b();function Jne(e){return e?{path:e,paths:void 0}:{path:void 0,paths:void 0}}s(Jne,"pathScope");function Yne(e,t){let r=new Set(t.skillNames),n=new Set(t.ruleSlugs),o=new Set(t.commandNames),i=new Set(t.agentNames);return {...e,skills:e.skills.filter(a=>r.has(a.name)),rules:e.rules.filter(a=>n.has(yt(a))),commands:e.commands.filter(a=>o.has(a.name)),agents:e.agents.filter(a=>i.has(a.name))}}s(Yne,"applySelection");async function Oz(e){let{canonicalDir:t,packName:r,narrowed:n,selected:o,sourceForYaml:i,version:a,sourceKind:l,entryFeatures:c,pick:m,yamlTarget:p,pathInRepo:u,manualAs:f,renameExistingPack:g,sourceType:h,contentRoot:y,forceFreshMaterialize:_,originalRef:R,acceptedElevated:k}=e,w=join(t,"packs"),D=Yne(n,o),N=y?await hz(y):[],K=new Date().toISOString(),J=p!==void 0?Or.parse(p):void 0,ee=_?null:await GU(w,i,{target:J,as:f,features:c}),se=r,$=c,re=m,Pe=u,Tt;if(ee){let be=ee.packDir,et=ee.meta;if(g&&ee.name!==r){let _t=join(w,r);if(await j(_t))throw new Error(`Auto-generated pack name "${r}" collides with an existing incompatible pack. Use --name to choose a different pack name.`);await rename(ee.packDir,_t),be=_t,et={...ee.meta,name:r};}let lt=await gz(be,et,D,c,m,{source:i,...a!==void 0?{version:a}:{},...J!==void 0?{target:J}:{},...u?{path:u}:{},...f!==void 0?{as:f}:{}},N);se=lt.name,$=lt.features,re=lt.pick,Pe=lt.path,Tt=lt.paths,S.success(`Updated pack "${lt.name}" in .agentsmesh/packs/.`);}else {if(!_&&await Sa(join(w,r)))throw new Error(`Auto-generated pack name "${r}" collides with an existing incompatible pack. Use --name to choose a different pack name.`);await fz(w,r,D,{name:r,source:i,...a!==void 0&&{version:a},source_kind:l,installed_at:K,updated_at:K,features:c,...m!==void 0&&{pick:m},...J!==void 0&&{target:J},...Jne(u),...f!==void 0&&{as:f}},h!==void 0?{source_type:h}:{},N),S.success(`Installed pack "${r}" to .agentsmesh/packs/.`);}await wy(t,Ez({name:se,source:i,version:a,sourceKind:l,features:$,pick:re,target:J,path:Pe,paths:Tt,as:f,originalRef:R,acceptedElevated:k})),l!=="local"&&await dO(i);}s(Oz,"installAsPack");function wz(e,t,r){if(!r?.features&&!r?.pick)return {narrowed:e,discoveredFeatures:t};let n=Qm(e,{scopedFeatures:r.features,implicitPick:r.pick});return {narrowed:n,discoveredFeatures:Yn(n)}}s(wz,"applyReplayInstallScope");function bz(e,t){let r=[];for(let n of e.skillNames)r.push({kind:"skill",name:n,path:t});for(let n of e.ruleSlugs)r.push({kind:"rule",name:n,path:t});for(let n of e.commandNames)r.push({kind:"command",name:n,path:t});for(let n of e.agentNames)r.push({kind:"agent",name:n,path:t});return r}s(bz,"buildInstalledList");function Az(e,t,r,n,o){let i=[];for(let a of e)o.skillNames.includes(a.name)||i.push({kind:"skill",name:a.name,reason:"conflict"});for(let a of t){let l=yt(a);o.ruleSlugs.includes(l)||i.push({kind:"rule",name:l,reason:"conflict"});}for(let a of r)o.commandNames.includes(a.name)||i.push({kind:"command",name:a.name,reason:"conflict"});for(let a of n)o.agentNames.includes(a.name)||i.push({kind:"agent",name:a.name,reason:"conflict"});return i}s(Az,"buildSkippedList");function Tz(e,t){if(t.sourceKind==="local")return {canonical:e,stripped:[]};let r=[],n=e.hooks,o=e.permissions,i=e.mcp;return n!==null&&!t.acceptHooks&&(n=null,r.push("hooks")),o!==null&&!t.acceptPermissions&&(o=null,r.push("permissions")),i!==null&&!t.acceptMcp&&(i=null,r.push("mcp")),r.length===0?{canonical:e,stripped:[]}:{canonical:{...e,hooks:n,permissions:o,mcp:i},stripped:r}}s(Tz,"stripUntrustedElevatedArtifacts");var Xne=["hooks","permissions","mcp"];function xz(e,t){let r=new Set(t?.acceptedElevated??[]);return {acceptHooks:e.acceptHooks||r.has("hooks"),acceptPermissions:e.acceptPermissions||r.has("permissions"),acceptMcp:e.acceptMcp||r.has("mcp")}}s(xz,"resolveElevatedConsent");function Pz(e,t){let r={hooks:t.acceptHooks,permissions:t.acceptPermissions,mcp:t.acceptMcp},n=Xne.filter(o=>e[o]!==null&&r[o]);return n.length>0?n:void 0}s(Pz,"consentedArtifactsForManifest");function Dz(e,t){return t?.originalRef!==void 0&&t.originalRef!==""?t.originalRef:e.rawRef!==""?e.rawRef:void 0}s(Dz,"resolveOriginalRef");function Nz(e,t){if(t.length===0)return e;let r=new Set(t);return e.filter(n=>!r.has(n))}s(Nz,"featuresAfterStrip");async function vz(e){let{scope:t,force:r,dryRun:n,tty:o,useExtends:i,forceFreshMaterialize:a,nameOverride:l,explicitAs:c}=e,{config:m,context:p,parsed:u,sourceForYaml:f,version:g,pathInRepo:h,contentRoot:y,persisted:_}=e,{replay:R,prep:k,implicitPick:w,narrowed:D,discoveredFeatures:N,sourceType:K}=e,J=xz({acceptHooks:e.acceptHooks,acceptPermissions:e.acceptPermissions,acceptMcp:e.acceptMcp},R),ee=Tz(D,{sourceKind:u.kind,...J});ee.stripped.length>0&&S.warn(`[agentsmesh] Stripped ${ee.stripped.join(", ")} from untrusted ${u.kind} source.
443
+ `);}s(Mne,"mergeSettings");async function gz(e,t,r,n,o,i,a=[]){await Pne(r,e),await Dne(r,e),await Nne(r,e),await vne(r,e),await Mne(r,e),await Fne(a,e);let l=IC(t.features,n),c=xne(t.pick,n,o),m=Tne(t,i?.path),p=await Cy(e),u=new Date().toISOString(),f=Ca({...t,source:i?.source??t.source,...i?.version!==void 0?{version:i.version}:t.version!==void 0?{version:t.version}:{},features:l,pick:c,...i?.target!==void 0?{target:i.target}:t.target!==void 0?{target:t.target}:{},...m,...i?.as!==void 0?{as:i.as}:t.as!==void 0?{as:t.as}:{},updated_at:u,content_hash:p});return await L(join(e,"pack.yaml"),Xl(stringify(f),"pack")),f}s(gz,"mergeIntoPack");L_();ss();async function hz(e){let t=[];try{let r=await readdir(e,{withFileTypes:!0});for(let n of r)n.isFile()&&rf(n.name)&&t.push({relativePath:n.name,absolutePath:join(e,n.name)});}catch{return []}return t.sort((r,n)=>r.relativePath.localeCompare(n.relativePath)),t}s(hz,"collectPreservedRootFiles");rs();fe();rs();b();Lh();function Une(e){return e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}s(Une,"sanitize");function Bne(e){try{let r=new URL(e.replace(/^git\+/,"https://").replace(/^ssh:\/\/git@/,"https://")).pathname.split("/").filter(Boolean);if(r.length===0)return "repo";let n=r[r.length-1].replace(/\.git$/i,"");return r.length>=2?`${r[r.length-2].replace(/\.git$/i,"")}-${n}`:n}catch{return "repo"}}s(Bne,"gitUrlLastSegments");function yz(e,t,r){let n;if(e.kind==="local"){let l=(e.localRoot??"local").split(/[/\\]/).filter(Boolean);n=l[l.length-1]??"local";}else e.kind==="github"&&e.org&&e.repo?n=`${e.org}-${e.repo}`:e.kind==="gitlab"&&e.org&&e.repo?n=`${e.org.replace(/\//g,"-")}-${e.repo}`:e.gitRemoteUrl?n=Bne(e.gitRemoteUrl):n="extend";t.featureHint?n=`${n}-${t.featureHint}`:n=`${n}-pack`;let o=Une(n)||"extend";if(!r.has(o))return o;let i=2;for(;r.has(`${o}-${i}`);)i++;return `${o}-${i}`}s(yz,"suggestExtendName");function _z(e){let{config:t,parsed:r,entryFeatures:n,nameOverride:o}=e,i=new Set(t.extends.map(a=>a.name));return o||yz(r,{featureHint:n.length===1?n[0]:void 0},i)}s(_z,"selectInstallEntryName");function Sz(e){let t=e.trim();for(;t.startsWith("git+");){let c=t.lastIndexOf("#");t=(c<0?t.slice(4):t.slice(4,c)).trim();}let r=t.match(/^github:([^/]+)\/([^/@]+?)(?:\.git)?(?:@[^/]+)?$/i);if(r)return `github:${r[1].toLowerCase()}/${r[2].toLowerCase()}`;let n=t.match(/^gitlab:(.+?)\/([^/@]+?)(?:\.git)?(?:@[^/]+)?$/i);if(n)return `gitlab:${n[1].toLowerCase()}/${n[2].toLowerCase()}`;let o=t.match(/^https?:\/\/github\.com\/([^/]+)\/([^/?#]+?)(?:\.git)?(?:[/?#].*)?$/i);if(o)return `github:${o[1].toLowerCase()}/${o[2].toLowerCase()}`;let i=t.match(/^https?:\/\/gitlab\.com\/(.+?)\/([^/?#]+?)(?:\.git)?(?:[/?#].*)?$/i);if(i)return `gitlab:${i[1].toLowerCase()}/${i[2].toLowerCase()}`;let a=t.match(/^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/i);if(a)return `github:${a[1].toLowerCase()}/${a[2].toLowerCase()}`;let l=t.match(/^git@gitlab\.com:(.+?)\/([^/]+?)(?:\.git)?$/i);return l?`gitlab:${l[1].toLowerCase()}/${l[2].toLowerCase()}`:null}s(Sz,"canonicalRemoteIdentity");function Kne(e){return e.kind==="github"&&e.org&&e.repo?`github:${e.org.toLowerCase()}/${e.repo.toLowerCase()}`:e.kind==="gitlab"&&e.org&&e.repo?`gitlab:${e.org.toLowerCase()}/${e.repo.toLowerCase()}`:e.gitRemoteUrl?Sz(e.gitRemoteUrl):null}s(Kne,"parsedSourceIdentity");function Rz(e,t){let r=Kne(t);if(r===null)return null;for(let n of e){let o=Sz(n.source);if(o!==null&&o===r)return n.name}return null}s(Rz,"findExistingInstallName");function kC(e,t){if(e.length!==t.length)return false;let r=[...e].sort(),n=[...t].sort();for(let o=0;o<r.length;o++)if(r[o]!==n[o])return false;return true}s(kC,"sameFeatureSet");function Iz(e){let{manifest:t,parsed:r,entryFeatures:n,yamlTarget:o,explicitAs:i}=e,a=Rz(t,r);if(a===null)return null;let l=t.find(c=>c.name===a);return l.target!==o||l.as!==i||!kC(l.features,n)?null:l.name}s(Iz,"pickReuseEntryName");var zne=s(e=>!e.includes("/")&&!e.includes("\\")&&!e.includes("\0")&&e!=="."&&e!=="..","isSafeInstallName"),Lz=z$1.object({name:z$1.string().min(1).refine(zne,{message:'install name must not contain path separators, NUL, or "."/".." segments'}),source:z$1.string().min(1),version:z$1.string().optional(),source_kind:z$1.enum(["github","gitlab","git","local"]),features:z$1.array(uc).min(1),pick:_p.optional(),target:Or.optional(),path:z$1.string().optional(),paths:z$1.array(z$1.string().min(1)).min(1).optional(),as:Tm.optional(),refreshed_at:z$1.string().min(1).optional(),original_ref:z$1.string().optional(),accepted_elevated:z$1.array(z$1.enum(["hooks","permissions","mcp"])).min(1).optional()}),Vne=z$1.object({version:z$1.literal(1),installs:z$1.array(Lz).default([])});function Jne(e,t){return e.source===t.source&&e.target===t.target&&e.as===t.as&&kC(e.features,t.features)}s(Jne,"sameInstallIdentity");function LC(e){return join(e,"installs.yaml")}s(LC,"manifestPath");async function Zt(e){let t=await I(LC(e));if(t===null)return [];try{return Vne.parse(parse(t)).installs.map(r=>Ca(r))}catch{return []}}s(Zt,"readInstallManifest");async function wy(e,t){let r=Ca(t),o=(await Zt(e)).filter(i=>i.name!==r.name&&!Jne(i,r));o.push(r),await L(LC(e),Xl(stringify({version:1,installs:o.sort((i,a)=>i.name.localeCompare(a.name))}),"installs"));}s(wy,"upsertInstallManifestEntry");async function Cz(e,t){let r=await Zt(e),n=r.filter(o=>o.name!==t);return n.length===r.length?false:(await L(LC(e),Xl(stringify({version:1,installs:n.sort((o,i)=>o.name.localeCompare(i.name))}),"installs")),true)}s(Cz,"removeInstallManifestEntry");function Ez(e){return Ca(Lz.parse({name:e.name,source:e.source,version:e.version,source_kind:e.sourceKind,features:e.features,pick:e.pick,target:e.target,path:e.path,paths:e.paths,as:e.as,refreshed_at:e.refreshed_at,original_ref:e.originalRef,accepted_elevated:e.acceptedElevated}))}s(Ez,"buildInstallManifestEntry");b();function Xne(e){return e?{path:e,paths:void 0}:{path:void 0,paths:void 0}}s(Xne,"pathScope");function Qne(e,t){let r=new Set(t.skillNames),n=new Set(t.ruleSlugs),o=new Set(t.commandNames),i=new Set(t.agentNames);return {...e,skills:e.skills.filter(a=>r.has(a.name)),rules:e.rules.filter(a=>n.has(yt(a))),commands:e.commands.filter(a=>o.has(a.name)),agents:e.agents.filter(a=>i.has(a.name))}}s(Qne,"applySelection");async function Oz(e){let{canonicalDir:t,packName:r,narrowed:n,selected:o,sourceForYaml:i,version:a,sourceKind:l,entryFeatures:c,pick:m,yamlTarget:p,pathInRepo:u,manualAs:f,renameExistingPack:g,sourceType:h,contentRoot:y,forceFreshMaterialize:_,originalRef:R,acceptedElevated:k}=e,w=join(t,"packs"),D=Qne(n,o),N=y?await hz(y):[],K=new Date().toISOString(),J=p!==void 0?Or.parse(p):void 0,ee=_?null:await GU(w,i,{target:J,as:f,features:c}),se=r,$=c,re=m,Pe=u,Tt;if(ee){let be=ee.packDir,et=ee.meta;if(g&&ee.name!==r){let _t=join(w,r);if(await j(_t))throw new Error(`Auto-generated pack name "${r}" collides with an existing incompatible pack. Use --name to choose a different pack name.`);await rename(ee.packDir,_t),be=_t,et={...ee.meta,name:r};}let lt=await gz(be,et,D,c,m,{source:i,...a!==void 0?{version:a}:{},...J!==void 0?{target:J}:{},...u?{path:u}:{},...f!==void 0?{as:f}:{}},N);se=lt.name,$=lt.features,re=lt.pick,Pe=lt.path,Tt=lt.paths,S.success(`Updated pack "${lt.name}" in .agentsmesh/packs/.`);}else {if(!_&&await Sa(join(w,r)))throw new Error(`Auto-generated pack name "${r}" collides with an existing incompatible pack. Use --name to choose a different pack name.`);await fz(w,r,D,{name:r,source:i,...a!==void 0&&{version:a},source_kind:l,installed_at:K,updated_at:K,features:c,...m!==void 0&&{pick:m},...J!==void 0&&{target:J},...Xne(u),...f!==void 0&&{as:f}},h!==void 0?{source_type:h}:{},N),S.success(`Installed pack "${r}" to .agentsmesh/packs/.`);}await wy(t,Ez({name:se,source:i,version:a,sourceKind:l,features:$,pick:re,target:J,path:Pe,paths:Tt,as:f,originalRef:R,acceptedElevated:k})),l!=="local"&&await dO(i);}s(Oz,"installAsPack");function wz(e,t,r){if(!r?.features&&!r?.pick)return {narrowed:e,discoveredFeatures:t};let n=Qm(e,{scopedFeatures:r.features,implicitPick:r.pick});return {narrowed:n,discoveredFeatures:Yn(n)}}s(wz,"applyReplayInstallScope");function bz(e,t){let r=[];for(let n of e.skillNames)r.push({kind:"skill",name:n,path:t});for(let n of e.ruleSlugs)r.push({kind:"rule",name:n,path:t});for(let n of e.commandNames)r.push({kind:"command",name:n,path:t});for(let n of e.agentNames)r.push({kind:"agent",name:n,path:t});return r}s(bz,"buildInstalledList");function Az(e,t,r,n,o){let i=[];for(let a of e)o.skillNames.includes(a.name)||i.push({kind:"skill",name:a.name,reason:"conflict"});for(let a of t){let l=yt(a);o.ruleSlugs.includes(l)||i.push({kind:"rule",name:l,reason:"conflict"});}for(let a of r)o.commandNames.includes(a.name)||i.push({kind:"command",name:a.name,reason:"conflict"});for(let a of n)o.agentNames.includes(a.name)||i.push({kind:"agent",name:a.name,reason:"conflict"});return i}s(Az,"buildSkippedList");function Tz(e,t){if(t.sourceKind==="local")return {canonical:e,stripped:[]};let r=[],n=e.hooks,o=e.permissions,i=e.mcp;return n!==null&&!t.acceptHooks&&(n=null,r.push("hooks")),o!==null&&!t.acceptPermissions&&(o=null,r.push("permissions")),i!==null&&!t.acceptMcp&&(i=null,r.push("mcp")),r.length===0?{canonical:e,stripped:[]}:{canonical:{...e,hooks:n,permissions:o,mcp:i},stripped:r}}s(Tz,"stripUntrustedElevatedArtifacts");var qne=["hooks","permissions","mcp"];function xz(e,t){let r=new Set(t?.acceptedElevated??[]);return {acceptHooks:e.acceptHooks||r.has("hooks"),acceptPermissions:e.acceptPermissions||r.has("permissions"),acceptMcp:e.acceptMcp||r.has("mcp")}}s(xz,"resolveElevatedConsent");function Pz(e,t){let r={hooks:t.acceptHooks,permissions:t.acceptPermissions,mcp:t.acceptMcp},n=qne.filter(o=>e[o]!==null&&r[o]);return n.length>0?n:void 0}s(Pz,"consentedArtifactsForManifest");function Dz(e,t){return t?.originalRef!==void 0&&t.originalRef!==""?t.originalRef:e.rawRef!==""?e.rawRef:void 0}s(Dz,"resolveOriginalRef");function Nz(e,t){if(t.length===0)return e;let r=new Set(t);return e.filter(n=>!r.has(n))}s(Nz,"featuresAfterStrip");async function vz(e){let{scope:t,force:r,dryRun:n,tty:o,useExtends:i,forceFreshMaterialize:a,nameOverride:l,explicitAs:c}=e,{config:m,context:p,parsed:u,sourceForYaml:f,version:g,pathInRepo:h,contentRoot:y,persisted:_}=e,{replay:R,prep:k,implicitPick:w,narrowed:D,discoveredFeatures:N,sourceType:K}=e,J=xz({acceptHooks:e.acceptHooks,acceptPermissions:e.acceptPermissions,acceptMcp:e.acceptMcp},R),ee=Tz(D,{sourceKind:u.kind,...J});ee.stripped.length>0&&S.warn(`[agentsmesh] Stripped ${ee.stripped.join(", ")} from untrusted ${u.kind} source.
444
444
  These artifacts control your tool settings (shell hooks, granted permissions, MCP launch specs).
445
445
  To accept them explicitly, re-run with: ${ee.stripped.map(Zo=>`--accept-${Zo}`).join(" ")} (or --accept-elevated for all three).`);let{narrowed:se,discoveredFeatures:$}=wz(ee.canonical,Nz(N,ee.stripped),R);if(!qH(se))throw new Error(w||k.scopedFeatures?"No resources match the install path or implicit selection (check pick names exist at that path).":"No supported resources found to install (skills, rules, commands, agents).");let re=await ZH(se,r,n,o),Pe=await ez(se,r,n,o),Tt=await tz(se,r,n,o),be=await rz(se,r,n,o),et={skills:re.length,rules:Pe.length,commands:Tt.length,agents:be.length},{canonical:lt}=await $t(m,p.configDir,{},p.canonicalDir),_t=!r&&!n&&o?await nz(lt,{skills:re,rules:Pe,commands:Tt,agents:be}):{skillNames:re.map(Zo=>Zo.name),ruleSlugs:Pe.map(Zo=>yt(Zo)),commandNames:Tt.map(Zo=>Zo.name),agentNames:be.map(Zo=>Zo.name)};az({selected:_t,discoveredFeatures:$,preConflict:et});let Ii=R?.features??iz($,_t);if(Ii.length===0)throw new Error("No features left to install after selection.");let n_=oz(R?.pick,_t)??_.pick??sz({pathInRepo:_.pathInRepo??h,implicitPick:w,preConflictCounts:et,selected:_t}),CE=await Zt(p.canonicalDir),pp=Iz({manifest:CE,parsed:u,entryFeatures:Ii,yamlTarget:k.yamlTarget,explicitAs:c}),up=_z({config:m,parsed:u,entryFeatures:Ii,nameOverride:l||pp||""}),dp=bz(_t,up),o_=Az(re,Pe,Tt,be,_t),uJ=Dz(u,R),dJ=Pz(se,J);if(i){if(await pz({configDir:p.configDir,config:m,entryArgs:{name:up,source:f,version:g,features:Ii,path:_.pathInRepo,pick:n_,yamlTarget:k.yamlTarget,as:c},dryRun:n}),n)return {installed:dp,skipped:o_}}else {if(n)return S.info(`[dry-run] Would install pack "${up}" to ${t==="global"?"~/.agentsmesh/packs/.":".agentsmesh/packs/."}`),{installed:dp,skipped:o_};await Oz({canonicalDir:p.canonicalDir,packName:up,narrowed:se,selected:_t,sourceForYaml:f,version:g,sourceKind:u.kind,entryFeatures:Ii,pick:n_,yamlTarget:k.yamlTarget,pathInRepo:_.pathInRepo,manualAs:c,renameExistingPack:l===""&&pp===null,sourceType:K,contentRoot:y,forceFreshMaterialize:a,originalRef:uJ,acceptedElevated:dJ});}return await ep("install",t,p.rootBase),{installed:dp,skipped:o_}}s(vz,"executeRunInstallPoolsAndWrite");function np(e,t){let r=t?.input??process.stdin,n=t?.output??process.stdout;return new Promise(o=>{let i=QH.createInterface({input:r,output:n,terminal:false}),a=false;i.on("close",()=>{a||o("");}),i.question(e,l=>{a=true,i.close(),o(l);});})}s(np,"readLine");function Mz(e,t){let r=t.resolved.length,n=r===1?"link":"links",o=[`Entity "${t.entityName}" (${t.entityKind}) has ${r} broken ${n}:`];for(let i of t.resolved)o.push(` - ${i.link.path} (${i.classification})`);o.push(""),e.write(`${o.join(`
446
446
  `)}
447
447
  `);}s(Mz,"writeBanner");async function Gz(e,t,r){let n=[];for(let o of e){if(o.resolved.length===0)continue;if(t.bypass){Mz(r,o),n.push({entityKind:o.entityKind,entityName:o.entityName,action:"leave-with-warnings"});continue}Mz(r,o);let i=(await r.ask("Action: [i]nclude resolvable as supporting files / [l]eave with warnings / [a]bort install ")).trim().toLowerCase();if(i==="i"){n.push({entityKind:o.entityKind,entityName:o.entityName,action:"include-resolvable"});continue}if(i==="l"){n.push({entityKind:o.entityKind,entityName:o.entityName,action:"leave-with-warnings"});continue}return {decisions:[],aborted:true}}return {decisions:n,aborted:false}}s(Gz,"runBrokenLinkPrompt");var EC=["skills","agents","commands","rules"],OC={skills:"skill",agents:"agent",commands:"command",rules:"rule"},Uz={skills:"skills",agents:"agents",commands:"commands",rules:"rules"};function ql(e){return {skills:[],agents:[],commands:[],rules:[],aborted:e}}s(ql,"emptySelection");function $z(e){return {skills:[...e.skills],agents:[...e.agents],commands:[...e.commands],rules:[...e.rules],aborted:false}}s($z,"selectAll");function jz(e,t,r){let n=[`Found in ${t}:`];for(let o of EC){let i=r[o];if(i.length===0)continue;let a=i.length===1?OC[o]:Uz[o];n.push(` - ${i.length} ${a}`);}n.push(""),e.write(`${n.join(`
448
448
  `)}
449
- `);}s(jz,"writeBanner");async function Qne(e,t,r){if(r.length===0)return {selected:[],aborted:false};let n=Uz[t],o=(await e.ask(`Install all ${r.length} ${n}? [y/n/c] `)).trim().toLowerCase();if(o==="y")return {selected:[...r],aborted:false};if(o==="n")return {selected:[],aborted:false};if(o!=="c")return {selected:[],aborted:true};let i=OC[t],a=[];for(let l=0;l<r.length;l++){let c=r[l],m=(await e.ask(`Install ${i} "${c}"? [y/N/a/q] `)).trim().toLowerCase();if(m==="y"){a.push(c);continue}if(!(m===""||m==="n")){if(m==="a"){for(let p=l;p<r.length;p++)a.push(r[p]);return {selected:a,aborted:false}}return m==="q"?{selected:a,aborted:false}:{selected:[],aborted:true}}}return {selected:a,aborted:false}}s(Qne,"walkType");function qne(e){let t=null;for(let r of EC)for(let n of e[r]){if(t!==null)return null;t={kind:r,id:n};}return t}s(qne,"findSingleEntity");async function Zne(e,t){let r=OC[t.kind],n=(await e.ask(`Install ${r} "${t.id}"? [y/N] `)).trim().toLowerCase();return n==="y"?{...ql(false),[t.kind]:[t.id]}:ql(!(n===""||n==="n"))}s(Zne,"runSingleEntityPrompt");async function Bz(e,t,r){if(t.bypass)return $z(e);let n=e.skills.length+e.agents.length+e.commands.length+e.rules.length;if(n===0)return ql(false);if(n===1){let a=qne(e);if(a!==null)return jz(r,t.packName,e),Zne(r,a)}jz(r,t.packName,e);let o=(await r.ask("Install [a]ll, [n]one, or [s]elect per type? [a/n/s] ")).trim().toLowerCase();if(o==="a")return $z(e);if(o==="n")return ql(false);if(o!=="s")return ql(true);let i={skills:[],agents:[],commands:[],rules:[]};for(let a of EC){let{selected:l,aborted:c}=await Qne(r,a,e[a]);if(c)return ql(true);i[a]=l;}return {...i,aborted:false}}s(Bz,"runBulkPrompt");fe();function noe(e,t,r){let n=[];for(let o of Iy(e))o.destination===t&&n.push({offset:o.destinationOffset,length:o.destinationLength,replacement:r});return n}s(noe,"buildLinkRewrites");function Wz(e,t,r){e.warn(`Broken link in ${t.entityKind} "${t.entityName}": ${r.link.path} (${r.classification})`);}s(Wz,"warnLink");function ooe(e){let t=new Map;for(let n of e){let o=basename(n.resolvedRelative),i=t.get(o)??new Set;i.add(n.resolvedRelative),t.set(o,i);}let r=new Map;for(let[n,o]of t){if(o.size===1){let i=[...o][0];r.set(i,`references/${n}`);continue}for(let i of o){let a=i.replaceAll("/","-");r.set(i,`references/${a}`);}}return r}s(ooe,"allocateSupportingFileNames");function Kz(e,t,r){return e.find(n=>n.entityKind===t&&n.entityName===r)}s(Kz,"findEntity");async function soe(e,t,r,n){let o=[...t],i=new Set(o.map(l=>l.relativePath)),a=new Set;for(let l of r){if(a.has(l.resolvedRelative))continue;a.add(l.resolvedRelative);let c=n.get(l.resolvedRelative);if(c===void 0||i.has(c))continue;i.add(c);let m=posix.join(e.replaceAll("\\","/"),l.resolvedRelative);o.push({relativePath:c,absolutePath:m,content:await readFile(m,"utf-8")});}return o}s(soe,"buildSupportingFiles");async function ioe(e,t,r,n){let o=r.resolved.filter(p=>p.classification==="resolvable-outside"),i=ooe(o),a=await soe(e,t.supportingFiles,o,i),l=[],c=new Set;for(let p of r.resolved)if(p.classification==="resolvable-outside"){if(c.has(p.link.raw))continue;let u=i.get(p.resolvedRelative);if(u===void 0)continue;c.add(p.link.raw);let f=`./${u}${p.anchor}`;l.push(...noe(t.body,p.link.raw,f));}else Wz(n,r,p);let m=vH(t.body,l);return {...t,body:m,supportingFiles:a}}s(ioe,"applySkillDecision");async function Hz(e){let{contentRoot:t,aggregate:r,decisions:n,logger:o}=e;if(n.length===0)return r;let i=new Set;for(let l of n)l.entityKind==="skill"&&l.action==="include-resolvable"&&i.add(l.entityName);let a=[];for(let l of r.skills){let c=i.has(l.name)?Kz(r.brokenLinks,"skill",l.name):void 0;a.push(c?await ioe(t,l,c,o):l);}for(let l of n){if(l.entityKind==="skill"&&l.action==="include-resolvable")continue;let c=Kz(r.brokenLinks,l.entityKind,l.entityName);if(c)for(let m of c.resolved)Wz(o,c,m);}return {...r,skills:a}}s(Hz,"applyBrokenLinkDecisions");var op=class extends Error{static{s(this,"InstallAbortError");}aborted=true;constructor(t){super(t),this.name="InstallAbortError";}};function loe(){return {ask:s(e=>np(e),"ask"),write:s(e=>process.stdout.write(e),"write")}}s(loe,"defaultAdapter");function coe(e){return {skills:e.skills.map(t=>t.name),agents:e.agents.map(t=>t.name),commands:e.commands.map(t=>t.name),rules:e.rules.map(t=>yt(t))}}s(coe,"bulkCandidatesFrom");function zz(e,t){let r=new Set(t.skills),n=new Set(t.agents),o=new Set(t.commands),i=new Set(t.rules);return {skills:e.skills.filter(a=>r.has(a.name)),agents:e.agents.filter(a=>n.has(a.name)),commands:e.commands.filter(a=>o.has(a.name)),rules:e.rules.filter(a=>i.has(yt(a))),mcp:null,permissions:null,hooks:null,ignore:[]}}s(zz,"filterCanonical");function moe(e){let t=[];return e.skills.length>0&&t.push("skills"),e.rules.length>0&&t.push("rules"),e.commands.length>0&&t.push("commands"),e.agents.length>0&&t.push("agents"),t}s(moe,"discoveredFeaturesOf");async function poe(e){let t=e.adapter??loe(),r=await Gz(e.aggregate.brokenLinks,{bypass:e.bypass},t);if(r.aborted)throw new op("User aborted at broken-link prompt.");let n=[...r.decisions],o=await Hz({contentRoot:e.contentRoot,aggregate:e.aggregate,decisions:n,logger:S}),i=coe(o);if(i.skills.length+i.agents.length+i.commands.length+i.rules.length===0)return {aggregate:o,narrowed:zz(o,{skills:[],agents:[],commands:[],rules:[]}),discoveredFeatures:[]};let l=await Bz(i,{packName:e.displayName,bypass:e.bypass},t);if(l.aborted)throw new op("User aborted at bulk-select prompt.");let c=zz(o,l);return {aggregate:o,narrowed:c,discoveredFeatures:moe(c)}}s(poe,"runSkillPackPromptFlow");function uoe(e){return basename(e)||"install source"}s(uoe,"displayNameForContentRoot");async function Vz(e){if(!e.discovery.aggregate)return {aborted:false};try{let t=await poe({contentRoot:e.contentRoot,aggregate:e.discovery.aggregate,narrowed:e.discovery.narrowed,bypass:e.bypass,displayName:uoe(e.contentRoot)});return {aborted:!1,narrowed:t.narrowed,discoveredFeatures:t.discoveredFeatures}}catch(t){if(t instanceof op)return S.warn(t.message),{aborted:true};throw t}}s(Vz,"runPromptFlowWithAbort");async function Jz(e){let{discovery:t,installReport:r,persisted:n,parsed:o,sourceForYaml:i,version:a,pathInRepo:l,contentRoot:c,config:m,context:p,dryRun:u,force:f,useExtends:g,forceFreshMaterialize:h,explicitAs:y,nameOverride:_,acceptHooks:R,acceptPermissions:k,acceptMcp:w,scope:D,sourceArg:N,replay:K}=e,J=process.stdin.isTTY,{prep:ee,implicitPick:se}=t,{narrowed:$,discoveredFeatures:re}=t;try{let Pe=await Vz({discovery:t,contentRoot:c,bypass:f||u||!J});if(Pe.aborted)return {exitCode:130,data:{source:N,mode:"install",installed:[],skipped:[],dryRun:u}};if($=Pe.narrowed??$,re=Pe.discoveredFeatures??re,re.length===0&&r.brokenResources.length>0){let be=r.brokenResources.map(et=>` - ${et.path}: ${et.reason}`).join(`
449
+ `);}s(jz,"writeBanner");async function Zne(e,t,r){if(r.length===0)return {selected:[],aborted:false};let n=Uz[t],o=(await e.ask(`Install all ${r.length} ${n}? [y/n/c] `)).trim().toLowerCase();if(o==="y")return {selected:[...r],aborted:false};if(o==="n")return {selected:[],aborted:false};if(o!=="c")return {selected:[],aborted:true};let i=OC[t],a=[];for(let l=0;l<r.length;l++){let c=r[l],m=(await e.ask(`Install ${i} "${c}"? [y/N/a/q] `)).trim().toLowerCase();if(m==="y"){a.push(c);continue}if(!(m===""||m==="n")){if(m==="a"){for(let p=l;p<r.length;p++)a.push(r[p]);return {selected:a,aborted:false}}return m==="q"?{selected:a,aborted:false}:{selected:[],aborted:true}}}return {selected:a,aborted:false}}s(Zne,"walkType");function eoe(e){let t=null;for(let r of EC)for(let n of e[r]){if(t!==null)return null;t={kind:r,id:n};}return t}s(eoe,"findSingleEntity");async function toe(e,t){let r=OC[t.kind],n=(await e.ask(`Install ${r} "${t.id}"? [y/N] `)).trim().toLowerCase();return n==="y"?{...ql(false),[t.kind]:[t.id]}:ql(!(n===""||n==="n"))}s(toe,"runSingleEntityPrompt");async function Bz(e,t,r){if(t.bypass)return $z(e);let n=e.skills.length+e.agents.length+e.commands.length+e.rules.length;if(n===0)return ql(false);if(n===1){let a=eoe(e);if(a!==null)return jz(r,t.packName,e),toe(r,a)}jz(r,t.packName,e);let o=(await r.ask("Install [a]ll, [n]one, or [s]elect per type? [a/n/s] ")).trim().toLowerCase();if(o==="a")return $z(e);if(o==="n")return ql(false);if(o!=="s")return ql(true);let i={skills:[],agents:[],commands:[],rules:[]};for(let a of EC){let{selected:l,aborted:c}=await Zne(r,a,e[a]);if(c)return ql(true);i[a]=l;}return {...i,aborted:false}}s(Bz,"runBulkPrompt");fe();function soe(e,t,r){let n=[];for(let o of Iy(e))o.destination===t&&n.push({offset:o.destinationOffset,length:o.destinationLength,replacement:r});return n}s(soe,"buildLinkRewrites");function Wz(e,t,r){e.warn(`Broken link in ${t.entityKind} "${t.entityName}": ${r.link.path} (${r.classification})`);}s(Wz,"warnLink");function ioe(e){let t=new Map;for(let n of e){let o=basename(n.resolvedRelative),i=t.get(o)??new Set;i.add(n.resolvedRelative),t.set(o,i);}let r=new Map;for(let[n,o]of t){if(o.size===1){let i=[...o][0];r.set(i,`references/${n}`);continue}for(let i of o){let a=i.replaceAll("/","-");r.set(i,`references/${a}`);}}return r}s(ioe,"allocateSupportingFileNames");function Kz(e,t,r){return e.find(n=>n.entityKind===t&&n.entityName===r)}s(Kz,"findEntity");async function aoe(e,t,r,n){let o=[...t],i=new Set(o.map(l=>l.relativePath)),a=new Set;for(let l of r){if(a.has(l.resolvedRelative))continue;a.add(l.resolvedRelative);let c=n.get(l.resolvedRelative);if(c===void 0||i.has(c))continue;i.add(c);let m=posix.join(e.replaceAll("\\","/"),l.resolvedRelative);o.push({relativePath:c,absolutePath:m,content:await readFile(m,"utf-8")});}return o}s(aoe,"buildSupportingFiles");async function loe(e,t,r,n){let o=r.resolved.filter(p=>p.classification==="resolvable-outside"),i=ioe(o),a=await aoe(e,t.supportingFiles,o,i),l=[],c=new Set;for(let p of r.resolved)if(p.classification==="resolvable-outside"){if(c.has(p.link.raw))continue;let u=i.get(p.resolvedRelative);if(u===void 0)continue;c.add(p.link.raw);let f=`./${u}${p.anchor}`;l.push(...soe(t.body,p.link.raw,f));}else Wz(n,r,p);let m=vH(t.body,l);return {...t,body:m,supportingFiles:a}}s(loe,"applySkillDecision");async function Hz(e){let{contentRoot:t,aggregate:r,decisions:n,logger:o}=e;if(n.length===0)return r;let i=new Set;for(let l of n)l.entityKind==="skill"&&l.action==="include-resolvable"&&i.add(l.entityName);let a=[];for(let l of r.skills){let c=i.has(l.name)?Kz(r.brokenLinks,"skill",l.name):void 0;a.push(c?await loe(t,l,c,o):l);}for(let l of n){if(l.entityKind==="skill"&&l.action==="include-resolvable")continue;let c=Kz(r.brokenLinks,l.entityKind,l.entityName);if(c)for(let m of c.resolved)Wz(o,c,m);}return {...r,skills:a}}s(Hz,"applyBrokenLinkDecisions");var op=class extends Error{static{s(this,"InstallAbortError");}aborted=true;constructor(t){super(t),this.name="InstallAbortError";}};function moe(){return {ask:s(e=>np(e),"ask"),write:s(e=>process.stdout.write(e),"write")}}s(moe,"defaultAdapter");function poe(e){return {skills:e.skills.map(t=>t.name),agents:e.agents.map(t=>t.name),commands:e.commands.map(t=>t.name),rules:e.rules.map(t=>yt(t))}}s(poe,"bulkCandidatesFrom");function zz(e,t){let r=new Set(t.skills),n=new Set(t.agents),o=new Set(t.commands),i=new Set(t.rules);return {skills:e.skills.filter(a=>r.has(a.name)),agents:e.agents.filter(a=>n.has(a.name)),commands:e.commands.filter(a=>o.has(a.name)),rules:e.rules.filter(a=>i.has(yt(a))),mcp:null,permissions:null,hooks:null,ignore:[]}}s(zz,"filterCanonical");function uoe(e){let t=[];return e.skills.length>0&&t.push("skills"),e.rules.length>0&&t.push("rules"),e.commands.length>0&&t.push("commands"),e.agents.length>0&&t.push("agents"),t}s(uoe,"discoveredFeaturesOf");async function doe(e){let t=e.adapter??moe(),r=await Gz(e.aggregate.brokenLinks,{bypass:e.bypass},t);if(r.aborted)throw new op("User aborted at broken-link prompt.");let n=[...r.decisions],o=await Hz({contentRoot:e.contentRoot,aggregate:e.aggregate,decisions:n,logger:S}),i=poe(o);if(i.skills.length+i.agents.length+i.commands.length+i.rules.length===0)return {aggregate:o,narrowed:zz(o,{skills:[],agents:[],commands:[],rules:[]}),discoveredFeatures:[]};let l=await Bz(i,{packName:e.displayName,bypass:e.bypass},t);if(l.aborted)throw new op("User aborted at bulk-select prompt.");let c=zz(o,l);return {aggregate:o,narrowed:c,discoveredFeatures:uoe(c)}}s(doe,"runSkillPackPromptFlow");function foe(e){return basename(e)||"install source"}s(foe,"displayNameForContentRoot");async function Vz(e){if(!e.discovery.aggregate)return {aborted:false};try{let t=await doe({contentRoot:e.contentRoot,aggregate:e.discovery.aggregate,narrowed:e.discovery.narrowed,bypass:e.bypass,displayName:foe(e.contentRoot)});return {aborted:!1,narrowed:t.narrowed,discoveredFeatures:t.discoveredFeatures}}catch(t){if(t instanceof op)return S.warn(t.message),{aborted:true};throw t}}s(Vz,"runPromptFlowWithAbort");async function Jz(e){let{discovery:t,installReport:r,persisted:n,parsed:o,sourceForYaml:i,version:a,pathInRepo:l,contentRoot:c,config:m,context:p,dryRun:u,force:f,useExtends:g,forceFreshMaterialize:h,explicitAs:y,nameOverride:_,acceptHooks:R,acceptPermissions:k,acceptMcp:w,scope:D,sourceArg:N,replay:K}=e,J=process.stdin.isTTY,{prep:ee,implicitPick:se}=t,{narrowed:$,discoveredFeatures:re}=t;try{let Pe=await Vz({discovery:t,contentRoot:c,bypass:f||u||!J});if(Pe.aborted)return {exitCode:130,data:{source:N,mode:"install",installed:[],skipped:[],dryRun:u}};if($=Pe.narrowed??$,re=Pe.discoveredFeatures??re,re.length===0&&r.brokenResources.length>0){let be=r.brokenResources.map(et=>` - ${et.path}: ${et.reason}`).join(`
450
450
  `);throw new Error(`No installable resources after skipping invalid files (${r.brokenResources.length}):
451
451
  ${be}
452
- Fix the frontmatter in the source files (most often: unquoted scalars containing colons or square brackets), or narrow --path to a subdirectory that excludes them.`)}let Tt=await vz({scope:D,force:f,dryRun:u,tty:J,useExtends:g,forceFreshMaterialize:h,nameOverride:_,explicitAs:y,acceptHooks:R,acceptPermissions:k,acceptMcp:w,config:m,context:p,parsed:o,sourceForYaml:i,version:a,pathInRepo:l,contentRoot:c,persisted:n,replay:K,prep:ee,implicitPick:se,narrowed:$,discoveredFeatures:re,sourceType:t.layout?KH(t.layout):void 0});return {exitCode:0,data:{source:N,mode:"install",installed:Tt.installed,skipped:Tt.skipped,dryRun:u,...r.brokenResources.length>0?{brokenResources:r.brokenResources}:{}}}}finally{ee.cleanup&&await ee.cleanup();}}s(Jz,"runSinglePackInstall");async function Yz(e,t,r){let n=[],o=[],i=0;for(let a of e)try{let l=await t(a);n.push(...l.installed),o.push(...l.skipped),i+=1;}catch(l){let c=l instanceof Error?l.message:String(l);r.subPackFailures.push({name:a.name,path:a.path??".",error:c});}return {exitCode:i>0?0:1,installed:n,skipped:o}}s(Yz,"runInstallMarketplace");async function Xz(e){let{pickerResult:t,installReport:r,sourceArg:n,projectRoot:o,dryRun:i,force:a,useExtends:l,nameOverride:c,replay:m,recurseInstall:p}=e;if(t.isMarketplace&&t.targets.length>0){let u=await Yz(t.targets,async f=>(await p({force:!0,"dry-run":i,path:f.path??"",as:f.as??"",target:f.target??"",name:f.name,extends:l},[n],o,{})).data,r);return {exitCode:u.exitCode,data:{source:n,mode:"install",installed:u.installed,skipped:u.skipped,dryRun:i,...r.brokenResources.length>0?{brokenResources:r.brokenResources}:{},...r.subPackFailures.length>0?{subPackFailures:r.subPackFailures}:{}}}}if(!t.isMarketplace&&t.targets.length===1){let u=t.targets[0];return p({force:a,"dry-run":i,path:u.path??"",as:u.as??"",target:u.target??"",name:c,extends:l},[n],o,m??{})}return null}s(Xz,"routePickerResult");tt();b();fe();async function foe(e){let t=await Zt(e.canonicalDir);if(t.length===0){S.info("No recorded installs found in .agentsmesh/installs.yaml.");return}let r=[];for(let n of t){let o=join(e.canonicalDir,"packs",n.name);await j(o)||r.push(n);}if(r.length===0){S.info("All recorded packs are already installed.");return}for(let n of r)await e.reinstall(n);S.success(`Reinstalled ${r.length} pack(s) from .agentsmesh/installs.yaml.`);}s(foe,"syncInstalledPacks");async function Qz(e){return e.sync?(await foe({canonicalDir:e.canonicalDir,reinstall:e.reinstall}),true):false}s(Qz,"maybeRunInstallSync");async function qz(e){let{projectRoot:t,sync:r,dryRun:n,force:o,scope:i,recurseInstall:a}=e;if(!r)return;let{context:l}=await _e(t,i),c=[],m=[];if(await Qz({sync:r,canonicalDir:l.canonicalDir,reinstall:s(async u=>{let f=u.paths&&u.paths.length>0?u.paths:[u.path];for(let g of f){let h=await a({...o?{force:true}:{},...n?{"dry-run":true}:{},...i==="global"?{global:true}:{},name:u.name,...u.target?{target:u.target}:{},...g?{path:g}:{},...u.as?{as:u.as}:{}},[u.source],t,{features:u.features,pick:u.pick,...u.original_ref!==void 0?{originalRef:u.original_ref}:{},...u.accepted_elevated!==void 0?{acceptedElevated:u.accepted_elevated}:{}});c.push(...h.data.installed),m.push(...h.data.skipped);}},"reinstall")}))return {exitCode:0,data:{source:"",mode:"sync",installed:c,skipped:m,dryRun:n}}}s(qz,"handleSync");function Zz(){return {brokenResources:[],subPackFailures:[]}}s(Zz,"createInstallReport");function yoe(e,t){if(!e)return;let r=normalize(e).replace(/\\/g,"/");if(r===".."||r.startsWith("../"))throw new Error(`Install --path "${t}" escapes the source root. Path must stay within the source.`)}s(yoe,"assertPathStaysInRepo");async function e1(e){let t=await qz(e);if(t)return t;let{projectRoot:r,replay:n,dryRun:o,force:i,useExtends:a,all:l,forceFreshMaterialize:c,explicitPath:m,explicitTarget:p,explicitAs:u,nameOverride:f,acceptHooks:g,acceptPermissions:h,acceptMcp:y,scope:_,sourceArg:R}=e;if(!R)throw new Error("Missing source. Usage: agentsmesh install <source> [--path ...] [--target ...]");let k=process.stdin.isTTY;if(!k&&!i&&!o)throw new Error("Non-interactive terminal: use --force or --dry-run for agentsmesh install.");let{config:w,context:D}=await _e(r,_);await ze(w,r);let N=await aC(R,D.configDir,m);if(N.kind!=="local"&&!await XW())throw new Error("git is required for remote installs. Please install git and try again.");let{resolvedPath:K,sourceForYaml:J,version:ee}=await qW(N,R),se=N.pathInRepo.replaceAll("\\","/").replace(/^\/+|\/+$/g,"");yoe(se,N.pathInRepo);let $=se?join(K,se):K;if(!await j($))throw new Error(`Install path does not exist: ${$}`);let re=await XH({as:u,contentRoot:$,pathInRepo:se}),Pe=Zz(),Tt={onParseError:s((et,lt)=>{Pe.brokenResources.push({path:lt,kind:"frontmatter",reason:et.message});},"onParseError")},be=await WH({resolvedPath:K,contentRoot:$,pathInRepo:se,explicitTarget:p,explicitAs:u,replayPick:n?.pick,parseOpts:Tt});if(be.layout&&!u&&!p&&!m){let et=JH({layout:be.layout,sourceName:f||(N.org&&N.repo?`${N.org}-${N.repo}`:"source"),sourceForYaml:J,explicitPath:m,explicitAs:u,explicitTarget:p,all:l,force:i,tty:k}),lt=await Xz({pickerResult:et,installReport:Pe,sourceArg:R,projectRoot:r,dryRun:o,force:i,useExtends:a,nameOverride:f,replay:n,recurseInstall:e.recurseInstall});if(lt!==null)return lt}return Jz({discovery:be,installReport:Pe,persisted:re,parsed:N,sourceForYaml:J,version:ee,pathInRepo:se,contentRoot:$,config:w,context:D,dryRun:o,force:i,useExtends:a,forceFreshMaterialize:c,explicitAs:u,nameOverride:f,acceptHooks:g,acceptPermissions:h,acceptMcp:y,scope:_,sourceArg:R,replay:n})}s(e1,"runInstallLocked");async function Zl(e,t,r,n){let{sync:o,dryRun:i,force:a,useExtends:l,all:c,forceFreshMaterialize:m,explicitPath:p,explicitTarget:u,explicitAs:f,nameOverride:g,acceptHooks:h,acceptPermissions:y,acceptMcp:_}=YW(e),R=e.global===true?"global":"project",k=t[0]?.trim(),w;if(n===void 0){let{context:D}=await _e(r,R);w=await Ym(D.canonicalDir);}try{return await e1({args:t,projectRoot:r,replay:n,sync:o,dryRun:i,force:a,useExtends:l,all:c,forceFreshMaterialize:m,explicitPath:p,explicitTarget:u,explicitAs:f,nameOverride:g,acceptHooks:h,acceptPermissions:y,acceptMcp:_,scope:R,sourceArg:k,recurseInstall:Zl})}finally{await w?.();}}s(Zl,"runInstall");async function t1(e,t,r){return Zl(e,t,r)}s(t1,"runInstall");function r1(e){let{data:t}=e;if(!(t.mode==="sync"&&t.installed.length===0&&t.skipped.length===0)){if(t.installed.length>0&&!t.dryRun){let n=[...new Set(t.installed.map(o=>o.kind))].map(o=>{let i=t.installed.filter(a=>a.kind===o).length;return `${i} ${o}${i>1?"s":""}`}).join(", ");M.success(`Installed ${n}.`),M.note(`Installed ${n}.`,"Install");}if(t.skipped.length>0)for(let r of t.skipped)M.warn(`Skipped ${r.kind} "${r.name}": ${r.reason}`);if(t.brokenResources&&t.brokenResources.length>0){let r=t.brokenResources.length;M.warn(`Skipped ${r} file${r>1?"s":""} with invalid frontmatter; see --json for details.`);}if(t.subPackFailures&&t.subPackFailures.length>0)for(let r of t.subPackFailures)M.warn(`Sub-pack "${r.name}" (${r.path}) failed: ${r.error}`);}}s(r1,"renderInstall");tt();sn();fe();function n1(e){let t=new Set,r=new Set;for(let n of e)t.has(n)?r.add(n):t.add(n);return [...r]}s(n1,"detectDuplicates");function by(e,t,r,n){let o=[];r.keepGenerated&&o.push(`--keep-generated: target trees will not be re-rendered; generated files derived from "${e}" may remain stale until the next generate.`);let i=r.keepPack||t===null?null:join(r.packsDir,e);return {name:e,packDir:i,manifestEntry:t,extendsEntry:n.get(e)??null,removeGenerated:!r.keepGenerated,warnings:o}}s(by,"buildPlan");function o1(e){if(!e.all&&e.names.length===0)throw new Error("uninstall: must provide at least one name or pass --all.");let t=new Map;for(let a of e.extends)t.has(a.name)||t.set(a.name,a);let r=new Map;for(let a of e.installs)r.set(a.name,a);if(e.all){let a=e.installs.map(m=>m.name),l=n1(a);if(l.length>0)throw new Error(`uninstall --all: installs.yaml has duplicate names: ${l.join(", ")}. Manifest is corrupt; remove the duplicates before retrying.`);let c=e.installs.map(m=>by(m.name,m,e,t));for(let m of e.extends)r.has(m.name)||c.push(by(m.name,null,e,t));return {removals:c,skipped:[]}}let n=n1(e.names);if(n.length>0)throw new Error(`uninstall: duplicate names requested: ${n.join(", ")}.`);let o=[],i=[];for(let a of e.names){let l=r.get(a);if(l!==void 0){o.push(by(a,l,e,t));continue}if(t.has(a)){o.push(by(a,null,e,t));continue}i.push(a);}return {removals:o,skipped:i}}s(o1,"planUninstall");b();b();xm();async function s1(e,t){let r=join(e,Lr);if(await j(r))return null;let n=await Sa(e);if(n===null)throw new Error(`Cannot migrate legacy pack at ${e}: pack.yaml is missing or invalid; cannot recover install provenance.`);let o=await Ey(e),i={name:n.name,source:n.source,installed_at:n.installed_at,extends_id:null,source_type:null,files:o};return t.dryRun!==true&&await L(r,`${JSON.stringify(i,null,2)}
453
- `),t.warn(`Legacy pack "${n.name}" detected; generated baseline install manifest from current contents. Local modifications since install cannot be detected.`),{manifest:i,manifestPath:r}}s(s1,"migrateLegacyManifest");b();var Ioe=["pack.yaml",Lr];function koe(e,t){return relative(e,t).replaceAll("\\","/")}s(koe,"toForwardSlashRelative");async function Ay(e,t){let r=await B(e),n=new Map;for(let i of r){let a=koe(e,i);Ioe.includes(a)||n.set(a,i);}let o=[];for(let[i,a]of Object.entries(t)){let l=n.get(i);if(l===void 0){o.push({relativePath:i,status:"deleted"});continue}let c=await bh(l);if(c===null){o.push({relativePath:i,status:"deleted"});continue}`sha256:${c}`!==a&&o.push({relativePath:i,status:"modified"});}for(let i of n.keys())i in t||o.push({relativePath:i,status:"added"});return o.sort((i,a)=>i.relativePath<a.relativePath?-1:i.relativePath>a.relativePath?1:0),o}s(Ay,"detectModifiedFiles");function i1(e,t){let r=t.modifications.length,n=r===1?"file":"files",o=[`Pack "${t.packName}" has ${r} locally modified ${n}:`];for(let i of t.modifications)o.push(` - ${i.relativePath} (${i.status})`);o.push(""),e.write(`${o.join(`
452
+ Fix the frontmatter in the source files (most often: unquoted scalars containing colons or square brackets), or narrow --path to a subdirectory that excludes them.`)}let Tt=await vz({scope:D,force:f,dryRun:u,tty:J,useExtends:g,forceFreshMaterialize:h,nameOverride:_,explicitAs:y,acceptHooks:R,acceptPermissions:k,acceptMcp:w,config:m,context:p,parsed:o,sourceForYaml:i,version:a,pathInRepo:l,contentRoot:c,persisted:n,replay:K,prep:ee,implicitPick:se,narrowed:$,discoveredFeatures:re,sourceType:t.layout?KH(t.layout):void 0});return {exitCode:0,data:{source:N,mode:"install",installed:Tt.installed,skipped:Tt.skipped,dryRun:u,...r.brokenResources.length>0?{brokenResources:r.brokenResources}:{}}}}finally{ee.cleanup&&await ee.cleanup();}}s(Jz,"runSinglePackInstall");async function Yz(e,t,r){let n=[],o=[],i=0;for(let a of e)try{let l=await t(a);n.push(...l.installed),o.push(...l.skipped),i+=1;}catch(l){let c=l instanceof Error?l.message:String(l);r.subPackFailures.push({name:a.name,path:a.path??".",error:c});}return {exitCode:i>0?0:1,installed:n,skipped:o}}s(Yz,"runInstallMarketplace");async function Xz(e){let{pickerResult:t,installReport:r,sourceArg:n,projectRoot:o,dryRun:i,force:a,useExtends:l,nameOverride:c,replay:m,recurseInstall:p}=e;if(t.isMarketplace&&t.targets.length>0){let u=await Yz(t.targets,async f=>(await p({force:!0,"dry-run":i,path:f.path??"",as:f.as??"",target:f.target??"",name:f.name,extends:l},[n],o,{})).data,r);return {exitCode:u.exitCode,data:{source:n,mode:"install",installed:u.installed,skipped:u.skipped,dryRun:i,...r.brokenResources.length>0?{brokenResources:r.brokenResources}:{},...r.subPackFailures.length>0?{subPackFailures:r.subPackFailures}:{}}}}if(!t.isMarketplace&&t.targets.length===1){let u=t.targets[0];return p({force:a,"dry-run":i,path:u.path??"",as:u.as??"",target:u.target??"",name:c,extends:l},[n],o,m??{})}return null}s(Xz,"routePickerResult");tt();b();fe();async function hoe(e){let t=await Zt(e.canonicalDir);if(t.length===0){S.info("No recorded installs found in .agentsmesh/installs.yaml.");return}let r=[];for(let n of t){let o=join(e.canonicalDir,"packs",n.name);await j(o)||r.push(n);}if(r.length===0){S.info("All recorded packs are already installed.");return}for(let n of r)await e.reinstall(n);S.success(`Reinstalled ${r.length} pack(s) from .agentsmesh/installs.yaml.`);}s(hoe,"syncInstalledPacks");async function Qz(e){return e.sync?(await hoe({canonicalDir:e.canonicalDir,reinstall:e.reinstall}),true):false}s(Qz,"maybeRunInstallSync");async function qz(e){let{projectRoot:t,sync:r,dryRun:n,force:o,scope:i,recurseInstall:a}=e;if(!r)return;let{context:l}=await _e(t,i),c=[],m=[];if(await Qz({sync:r,canonicalDir:l.canonicalDir,reinstall:s(async u=>{let f=u.paths&&u.paths.length>0?u.paths:[u.path];for(let g of f){let h=await a({...o?{force:true}:{},...n?{"dry-run":true}:{},...i==="global"?{global:true}:{},name:u.name,...u.target?{target:u.target}:{},...g?{path:g}:{},...u.as?{as:u.as}:{}},[u.source],t,{features:u.features,pick:u.pick,...u.original_ref!==void 0?{originalRef:u.original_ref}:{},...u.accepted_elevated!==void 0?{acceptedElevated:u.accepted_elevated}:{}});c.push(...h.data.installed),m.push(...h.data.skipped);}},"reinstall")}))return {exitCode:0,data:{source:"",mode:"sync",installed:c,skipped:m,dryRun:n}}}s(qz,"handleSync");function Zz(){return {brokenResources:[],subPackFailures:[]}}s(Zz,"createInstallReport");function Soe(e,t){if(!e)return;let r=normalize(e).replace(/\\/g,"/");if(r===".."||r.startsWith("../"))throw new Error(`Install --path "${t}" escapes the source root. Path must stay within the source.`)}s(Soe,"assertPathStaysInRepo");async function e1(e){let t=await qz(e);if(t)return t;let{projectRoot:r,replay:n,dryRun:o,force:i,useExtends:a,all:l,forceFreshMaterialize:c,explicitPath:m,explicitTarget:p,explicitAs:u,nameOverride:f,acceptHooks:g,acceptPermissions:h,acceptMcp:y,scope:_,sourceArg:R}=e;if(!R)throw new Error("Missing source. Usage: agentsmesh install <source> [--path ...] [--target ...]");let k=process.stdin.isTTY;if(!k&&!i&&!o)throw new Error("Non-interactive terminal: use --force or --dry-run for agentsmesh install.");let{config:w,context:D}=await _e(r,_);await ze(w,r);let N=await aC(R,D.configDir,m);if(N.kind!=="local"&&!await XW())throw new Error("git is required for remote installs. Please install git and try again.");let{resolvedPath:K,sourceForYaml:J,version:ee}=await qW(N,R),se=N.pathInRepo.replaceAll("\\","/").replace(/^\/+|\/+$/g,"");Soe(se,N.pathInRepo);let $=se?join(K,se):K;if(!await j($))throw new Error(`Install path does not exist: ${$}`);let re=await XH({as:u,contentRoot:$,pathInRepo:se}),Pe=Zz(),Tt={onParseError:s((et,lt)=>{Pe.brokenResources.push({path:lt,kind:"frontmatter",reason:et.message});},"onParseError")},be=await WH({resolvedPath:K,contentRoot:$,pathInRepo:se,explicitTarget:p,explicitAs:u,replayPick:n?.pick,parseOpts:Tt});if(be.layout&&!u&&!p&&!m){let et=JH({layout:be.layout,sourceName:f||(N.org&&N.repo?`${N.org}-${N.repo}`:"source"),sourceForYaml:J,explicitPath:m,explicitAs:u,explicitTarget:p,all:l,force:i,tty:k}),lt=await Xz({pickerResult:et,installReport:Pe,sourceArg:R,projectRoot:r,dryRun:o,force:i,useExtends:a,nameOverride:f,replay:n,recurseInstall:e.recurseInstall});if(lt!==null)return lt}return Jz({discovery:be,installReport:Pe,persisted:re,parsed:N,sourceForYaml:J,version:ee,pathInRepo:se,contentRoot:$,config:w,context:D,dryRun:o,force:i,useExtends:a,forceFreshMaterialize:c,explicitAs:u,nameOverride:f,acceptHooks:g,acceptPermissions:h,acceptMcp:y,scope:_,sourceArg:R,replay:n})}s(e1,"runInstallLocked");async function Zl(e,t,r,n){let{sync:o,dryRun:i,force:a,useExtends:l,all:c,forceFreshMaterialize:m,explicitPath:p,explicitTarget:u,explicitAs:f,nameOverride:g,acceptHooks:h,acceptPermissions:y,acceptMcp:_}=YW(e),R=e.global===true?"global":"project",k=t[0]?.trim(),w;if(n===void 0){let{context:D}=await _e(r,R);w=await Ym(D.canonicalDir);}try{return await e1({args:t,projectRoot:r,replay:n,sync:o,dryRun:i,force:a,useExtends:l,all:c,forceFreshMaterialize:m,explicitPath:p,explicitTarget:u,explicitAs:f,nameOverride:g,acceptHooks:h,acceptPermissions:y,acceptMcp:_,scope:R,sourceArg:k,recurseInstall:Zl})}finally{await w?.();}}s(Zl,"runInstall");async function t1(e,t,r){return Zl(e,t,r)}s(t1,"runInstall");function r1(e){let{data:t}=e;if(!(t.mode==="sync"&&t.installed.length===0&&t.skipped.length===0)){if(t.installed.length>0&&!t.dryRun){let n=[...new Set(t.installed.map(o=>o.kind))].map(o=>{let i=t.installed.filter(a=>a.kind===o).length;return `${i} ${o}${i>1?"s":""}`}).join(", ");M.success(`Installed ${n}.`),M.note(`Installed ${n}.`,"Install");}if(t.skipped.length>0)for(let r of t.skipped)M.warn(`Skipped ${r.kind} "${r.name}": ${r.reason}`);if(t.brokenResources&&t.brokenResources.length>0){let r=t.brokenResources.length;M.warn(`Skipped ${r} file${r>1?"s":""} with invalid frontmatter; see --json for details.`);}if(t.subPackFailures&&t.subPackFailures.length>0)for(let r of t.subPackFailures)M.warn(`Sub-pack "${r.name}" (${r.path}) failed: ${r.error}`);}}s(r1,"renderInstall");tt();sn();fe();function n1(e){let t=new Set,r=new Set;for(let n of e)t.has(n)?r.add(n):t.add(n);return [...r]}s(n1,"detectDuplicates");function by(e,t,r,n){let o=[];r.keepGenerated&&o.push(`--keep-generated: target trees will not be re-rendered; generated files derived from "${e}" may remain stale until the next generate.`);let i=r.keepPack||t===null?null:join(r.packsDir,e);return {name:e,packDir:i,manifestEntry:t,extendsEntry:n.get(e)??null,removeGenerated:!r.keepGenerated,warnings:o}}s(by,"buildPlan");function o1(e){if(!e.all&&e.names.length===0)throw new Error("uninstall: must provide at least one name or pass --all.");let t=new Map;for(let a of e.extends)t.has(a.name)||t.set(a.name,a);let r=new Map;for(let a of e.installs)r.set(a.name,a);if(e.all){let a=e.installs.map(m=>m.name),l=n1(a);if(l.length>0)throw new Error(`uninstall --all: installs.yaml has duplicate names: ${l.join(", ")}. Manifest is corrupt; remove the duplicates before retrying.`);let c=e.installs.map(m=>by(m.name,m,e,t));for(let m of e.extends)r.has(m.name)||c.push(by(m.name,null,e,t));return {removals:c,skipped:[]}}let n=n1(e.names);if(n.length>0)throw new Error(`uninstall: duplicate names requested: ${n.join(", ")}.`);let o=[],i=[];for(let a of e.names){let l=r.get(a);if(l!==void 0){o.push(by(a,l,e,t));continue}if(t.has(a)){o.push(by(a,null,e,t));continue}i.push(a);}return {removals:o,skipped:i}}s(o1,"planUninstall");b();b();xm();async function s1(e,t){let r=join(e,Lr);if(await j(r))return null;let n=await Sa(e);if(n===null)throw new Error(`Cannot migrate legacy pack at ${e}: pack.yaml is missing or invalid; cannot recover install provenance.`);let o=await Ey(e),i={name:n.name,source:n.source,installed_at:n.installed_at,extends_id:null,source_type:null,files:o};return t.dryRun!==true&&await L(r,`${JSON.stringify(i,null,2)}
453
+ `),t.warn(`Legacy pack "${n.name}" detected; generated baseline install manifest from current contents. Local modifications since install cannot be detected.`),{manifest:i,manifestPath:r}}s(s1,"migrateLegacyManifest");b();var Loe=["pack.yaml",Lr];function Coe(e,t){return relative(e,t).replaceAll("\\","/")}s(Coe,"toForwardSlashRelative");async function Ay(e,t){let r=await B(e),n=new Map;for(let i of r){let a=Coe(e,i);Loe.includes(a)||n.set(a,i);}let o=[];for(let[i,a]of Object.entries(t)){let l=n.get(i);if(l===void 0){o.push({relativePath:i,status:"deleted"});continue}let c=await bh(l);if(c===null){o.push({relativePath:i,status:"deleted"});continue}`sha256:${c}`!==a&&o.push({relativePath:i,status:"modified"});}for(let i of n.keys())i in t||o.push({relativePath:i,status:"added"});return o.sort((i,a)=>i.relativePath<a.relativePath?-1:i.relativePath>a.relativePath?1:0),o}s(Ay,"detectModifiedFiles");function i1(e,t){let r=t.modifications.length,n=r===1?"file":"files",o=[`Pack "${t.packName}" has ${r} locally modified ${n}:`];for(let i of t.modifications)o.push(` - ${i.relativePath} (${i.status})`);o.push(""),e.write(`${o.join(`
454
454
  `)}
455
- `);}s(i1,"writeBanner");async function a1(e,t,r){if(e.modifications.length===0)return {action:"proceed"};if(t.bypass)return i1(r,e),{action:"delete-anyway"};i1(r,e);let n=(await r.ask("Action: [d]elete anyway / [k]eep modified files (uninstall the rest) / [a]bort ")).trim().toLowerCase();return n==="d"?{action:"delete-anyway"}:n==="k"?{action:"keep-modified"}:{action:"abort"}}s(a1,"runModifiedFilesPrompt");async function Loe(e){let t=await I(join(e,Lr));if(t===null)return null;try{return JSON.parse(t).files??{}}catch{return null}}s(Loe,"readManifestFiles");async function Coe(e,t,r){if(e.manifestEntry===null)return {plan:e,modifications:[],action:"proceed",legacyMigrated:false,packDirMissing:false};let n=join(t,e.name);if(!await j(n))return r.warn(`Pack "${e.name}" directory missing at ${n}; only manifest entries will be removed.`),{plan:e,modifications:[],action:"proceed",legacyMigrated:false,packDirMissing:true};let o=await s1(n,{warn:r.warn,dryRun:r.dryRun===true}),i=o!==null,a=o!==null&&r.dryRun===true?o.manifest.files:await Loe(n);if(a===null)return {plan:e,modifications:[],action:"proceed",legacyMigrated:i,packDirMissing:false};let l=await Ay(n,a);if(r.keepPack||l.length===0)return {plan:e,modifications:l,action:"proceed",legacyMigrated:i,packDirMissing:false};let c=await a1({packName:e.name,modifications:l},{bypass:r.bypassPrompts},r.adapter);return c.action==="abort"?"abort":{plan:e,modifications:l,action:c.action,legacyMigrated:i,packDirMissing:false}}s(Coe,"decideOne");async function c1(e,t,r){let n=[];for(let o of e){let i=await Coe(o,t,r);if(i==="abort")return {decisions:n,aborted:true};n.push(i);}return {decisions:n,aborted:false}}s(c1,"gatherUninstallDecisions");b();b();async function m1(e,t,r){if(!t.extends.some(c=>c.name===r))return false;let n=await I(e);if(n===null)throw new Error(`Missing config: ${e}`);let o=parse(n),i=Array.isArray(o.extends)?o.extends:[],a=i.filter(c=>typeof c!="object"||c===null?true:c.name!==r);if(a.length===i.length)return false;o.extends=a;let l=stringify(o,{indent:2,lineWidth:0});return await L(e,l.endsWith(`
455
+ `);}s(i1,"writeBanner");async function a1(e,t,r){if(e.modifications.length===0)return {action:"proceed"};if(t.bypass)return i1(r,e),{action:"delete-anyway"};i1(r,e);let n=(await r.ask("Action: [d]elete anyway / [k]eep modified files (uninstall the rest) / [a]bort ")).trim().toLowerCase();return n==="d"?{action:"delete-anyway"}:n==="k"?{action:"keep-modified"}:{action:"abort"}}s(a1,"runModifiedFilesPrompt");async function Eoe(e){let t=await I(join(e,Lr));if(t===null)return null;try{return JSON.parse(t).files??{}}catch{return null}}s(Eoe,"readManifestFiles");async function Ooe(e,t,r){if(e.manifestEntry===null)return {plan:e,modifications:[],action:"proceed",legacyMigrated:false,packDirMissing:false};let n=join(t,e.name);if(!await j(n))return r.warn(`Pack "${e.name}" directory missing at ${n}; only manifest entries will be removed.`),{plan:e,modifications:[],action:"proceed",legacyMigrated:false,packDirMissing:true};let o=await s1(n,{warn:r.warn,dryRun:r.dryRun===true}),i=o!==null,a=o!==null&&r.dryRun===true?o.manifest.files:await Eoe(n);if(a===null)return {plan:e,modifications:[],action:"proceed",legacyMigrated:i,packDirMissing:false};let l=await Ay(n,a);if(r.keepPack||l.length===0)return {plan:e,modifications:l,action:"proceed",legacyMigrated:i,packDirMissing:false};let c=await a1({packName:e.name,modifications:l},{bypass:r.bypassPrompts},r.adapter);return c.action==="abort"?"abort":{plan:e,modifications:l,action:c.action,legacyMigrated:i,packDirMissing:false}}s(Ooe,"decideOne");async function c1(e,t,r){let n=[];for(let o of e){let i=await Ooe(o,t,r);if(i==="abort")return {decisions:n,aborted:true};n.push(i);}return {decisions:n,aborted:false}}s(c1,"gatherUninstallDecisions");b();b();async function m1(e,t,r){if(!t.extends.some(c=>c.name===r))return false;let n=await I(e);if(n===null)throw new Error(`Missing config: ${e}`);let o=parse(n),i=Array.isArray(o.extends)?o.extends:[],a=i.filter(c=>typeof c!="object"||c===null?true:c.name!==r);if(a.length===i.length)return false;o.extends=a;let l=stringify(o,{indent:2,lineWidth:0});return await L(e,l.endsWith(`
456
456
  `)?l:`${l}
457
- `),true}s(m1,"removeAgentsmeshExtendByName");async function p1(e){let{plan:t,canonicalDir:r,configPath:n,config:o}=e,i=false;t.packDir!==null&&await j(t.packDir)&&(await rm$1(t.packDir,{recursive:true}),i=true);let a=await Cz(r,t.name),l=false;t.extendsEntry!==null&&(l=await m1(n,o,t.name));let c=t.packDir!==null,m=t.manifestEntry!==null,p=t.extendsEntry!==null,u=c&&!i||m&&!a||p&&!l;return {name:t.name,packDirRemoved:i,manifestEntryRemoved:a,extendsEntryRemoved:l,partial:u}}s(p1,"applyUninstall");function Toe(e,t){return relative(e,t).replaceAll("\\","/")}s(Toe,"toForwardSlashRel");function wC(e){return e.map(t=>({name:t,reason:"not found in installs.yaml"}))}s(wC,"buildSkipped");function u1(e,t,r){return e.plan.manifestEntry===null?null:Toe(t,join(r,e.plan.name))}s(u1,"packPathFor");function d1(e,t,r){return e.map(n=>({name:n.plan.name,pack_path:u1(n,t,r),manifest_entry_removed:false,extends_entry_removed:false,generated_files_removed:0,modified_files_kept:n.modifications.map(o=>({relativePath:o.relativePath,status:o.status})),legacy_migrated:n.legacyMigrated,partial:n.action==="keep-modified"||n.plan.packDir===null}))}s(d1,"previewEntries");function f1(e,t,r,n){let o=e.action==="keep-modified"||!t.packDirRemoved;return {name:t.name,pack_path:u1(e,r,n),manifest_entry_removed:t.manifestEntryRemoved,extends_entry_removed:t.extendsEntryRemoved,generated_files_removed:0,modified_files_kept:o?e.modifications.map(i=>({relativePath:i.relativePath,status:i.status})):[],legacy_migrated:e.legacyMigrated,partial:t.partial}}s(f1,"appliedEntry");function xoe(e){let t=[];for(let r of e)for(let n of r.split(",").map(o=>o.trim()).filter(Boolean))t.push(n);return t}s(xoe,"parseNames");function Poe(){return {ask:s(e=>np(e),"ask"),write:s(e=>process.stdout.write(e),"write")}}s(Poe,"defaultAdapter");async function Ty(e,t,r,n={}){let o=e.global===true?"global":"project",i=e.all===true,a=e.force===true,l=e["dry-run"]===true,c=e["keep-pack"]===true,m=e["keep-generated"]===true,p=n.assumeTty===true||process.stdin.isTTY,u=xoe(t),f=e.json===true;function g(R){return f||S.error(R),{exitCode:1,data:{scope:o,mode:"uninstall",removed:[],skipped:[],failed:[],dryRun:l}}}if(s(g,"validationFailure"),!i&&u.length===0)return g("Missing install name. Usage: agentsmesh uninstall <name>[,<name>...] [--all]");if(!p&&!a&&!l)return g("Non-interactive terminal: use --force or --dry-run for agentsmesh uninstall.");let{config:h,context:y}=await _e(r,o);await ze(h,r);let _=await Ym(y.canonicalDir);try{let R=await Zt(y.canonicalDir),k=join(y.canonicalDir,"packs"),w=o1({names:u,all:i,keepPack:c,keepGenerated:m,installs:R,extends:h.extends,packsDir:k}),{decisions:D,aborted:N}=await c1(w.removals,k,{adapter:n.promptAdapter??Poe(),warn:s(se=>S.warn(se),"warn"),bypassPrompts:a||l||!p,keepPack:c,dryRun:l});if(N)return S.warn("Uninstall aborted at modification prompt."),{exitCode:130,data:{scope:o,mode:"uninstall",removed:[],skipped:[],failed:[],dryRun:l}};for(let se of w.removals)for(let $ of se.warnings)S.warn($);if(l){for(let se of D)S.info(`[dry-run] Would uninstall pack "${se.plan.name}".`);return {exitCode:0,data:{scope:o,mode:"uninstall",removed:d1(D,y.rootBase,k),skipped:wC(w.skipped),failed:[],dryRun:!0}}}let K=join(y.configDir,"agentsmesh.yaml"),J=[],ee=[];for(let se of D){let $=se.action==="keep-modified"?{...se.plan,packDir:null}:se.plan;try{let re=await p1({plan:$,canonicalDir:y.canonicalDir,configPath:K,config:h});J.push(f1(se,re,y.rootBase,k));}catch(re){let Pe=re instanceof Error?re.message:String(re);ee.push({name:se.plan.name,reason:Pe}),f||S.error(`Failed to uninstall "${se.plan.name}": ${Pe}`);}}return !m&&J.length>0?await ep("uninstall",o,y.rootBase):m&&J.length>0&&S.warn("--keep-generated: target files derived from the removed pack(s) may be stale until the next generate."),{exitCode:ee.length>0?1:0,data:{scope:o,mode:"uninstall",removed:J,skipped:wC(w.skipped),failed:ee,dryRun:!1}}}finally{await _();}}s(Ty,"runUninstall");async function h1(e,t,r){return Ty(e,t,r)}s(h1,"runUninstall");function y1(e){let{data:t}=e;if(t.dryRun){if(t.removed.length===0){M.info("[dry-run] No installs matched.");return}M.info(`[dry-run] Would uninstall ${t.removed.length} pack(s):`);for(let r of t.removed){let n=r.pack_path===null?"extends-only":r.pack_path;M.info(` - ${r.name} (${n})`);}return}if(t.removed.length>0){let r=t.removed.map(n=>`"${n.name}"`).join(", ");M.success(`Uninstalled ${t.removed.length} pack(s): ${r}.`),M.note(`Uninstalled ${t.removed.length} pack(s): ${r}.`,"Uninstall");}for(let r of t.skipped)M.warn(`Skipped "${r.name}": ${r.reason}`);for(let r of t.failed)M.error(`Failed "${r.name}": ${r.reason}`);}s(y1,"renderUninstall");tt();sn();fe();function _1(e){let t=e.json===true;return {dryRun:e["dry-run"]===true,force:e.force===true||t,global:e.global===true,json:t,verbose:e.verbose===true}}s(_1,"readRefreshFlags");function S1(e){let t=[];for(let r of e)for(let n of r.split(",").map(o=>o.trim()).filter(Boolean))t.push(n);return t}s(S1,"parseRefreshNames");b();function Doe(e){return e.modifications.length>0?"needs-consent":e.oldSha===e.newSha?"unchanged":"clean-update"}s(Doe,"classifyRefreshPlan");async function I1(e,t,r){let n=join(t,e.name),o=e.version??null,i=join(n,Lr),a=await I(i);if(a===null)return {name:e.name,entry:e,oldSha:o,newSha:o??"",modifications:[],classification:"error",error:{phase:"plan",message:`Pack manifest missing at ${i}`}};let l;try{l=JSON.parse(a).files??{};}catch{return {name:e.name,entry:e,oldSha:o,newSha:o??"",modifications:[],classification:"error",error:{phase:"plan",message:`Pack manifest is corrupt at ${i}`}}}let c=[];await j(n)&&(c=await Ay(n,l));let m;try{m=await r.resolveRef(e);}catch(p){let u=p instanceof Error?p.message:String(p);return {name:e.name,entry:e,oldSha:o,newSha:o??"",modifications:c,classification:"error",error:{phase:"plan",message:u}}}return {name:e.name,entry:e,oldSha:o,newSha:m,modifications:c,classification:Doe({modifications:c,oldSha:o,newSha:m})}}s(I1,"planSinglePack");function k1(){return async e=>{if(e.source_kind==="local")return e.version??"local";let t=Ld(e.source);if(t===null||t.remoteUrl===void 0)throw new Error(`Cannot parse source for refresh: ${e.source}`);let r=e.original_ref!==void 0&&e.original_ref!==""?e.original_ref:t.ref??"HEAD";return hy(r,t.remoteUrl)}}s(k1,"createDefaultResolveRef");async function L1(e,t,r){try{await r.runInstallForRefresh(e.entry,e.newSha);}catch(n){return {success:false,phase:"apply",error:n instanceof Error?n.message:String(n)}}try{let n=(r.now??(()=>new Date().toISOString()))(),i=(await Zt(t)).find(a=>a.name===e.entry.name);if(i===void 0)return {success:!1,phase:"manifest-update",error:`Entry "${e.entry.name}" not found after install`};await wy(t,{...i,refreshed_at:n});}catch(n){return {success:false,phase:"manifest-update",error:n instanceof Error?n.message:String(n)}}return {success:true}}s(L1,"applySinglePack");async function Noe(e,t,r={}){let n=r.readLine??np,o,i=new Promise(a=>{o=setTimeout(()=>a("timeout"),t),o.unref?.();});try{let a=await Promise.race([n(e),i]);return a==="timeout"?"timeout":voe(a)}finally{o&&clearTimeout(o);}}s(Noe,"promptWithTimeout");function voe(e){let t=e.trim().toLowerCase();return t==="y"||t==="yes"?"y":t==="per-pack"?"per-pack":"n"}s(voe,"normalize");async function bC(e,t){let n=[`The following ${e.length} pack(s) have local edits that refresh will overwrite:`,...e.map(i=>` - ${i.name}: ${i.modifiedCount} modified file(s)`),"Continue? [y/N/per-pack] (5 min timeout, default N) "].join(`
458
- `);switch(await Noe(n,t.timeoutMs,t)){case "y":return {proceed:true,perPack:false,declined:[]};case "per-pack":return {proceed:true,perPack:true,declined:[]};case "n":case "timeout":return {proceed:false,perPack:false,declined:e.map(i=>i.name)}}}s(bC,"runConsentPrompt");function Foe(e,t){let r=Ld(e.source);if(r===null||r.remoteUrl===void 0)return e.source;if(e.source_kind==="github"&&e.source.startsWith("github:")){let n=e.source.indexOf(":"),o=e.source.lastIndexOf("@");return `${o>n?e.source.slice(0,o):e.source}@${t}`}if(e.source_kind==="gitlab"&&e.source.startsWith("gitlab:")){let n=e.source.indexOf(":"),o=e.source.lastIndexOf("@");return `${o>n?e.source.slice(0,o):e.source}@${t}`}if(e.source.startsWith("git+")){let n=e.source.lastIndexOf("#");return `${n<0?e.source:e.source.slice(0,n)}#${t}`}return e.source}s(Foe,"buildSourceForRefresh");function C1(e){return async(t,r)=>{let n={force:true,forceFreshMaterialize:true};e.scope==="global"&&(n.global=true),t.target!==void 0&&(n.target=t.target),t.as!==void 0&&(n.as=t.as),t.path!==void 0&&(n.path=t.path),t.paths!==void 0&&t.paths.length>0&&(n.all=true),n.name=t.name;let o={features:t.features,pick:t.pick,...t.original_ref!==void 0?{originalRef:t.original_ref}:{},...t.accepted_elevated!==void 0?{acceptedElevated:t.accepted_elevated}:{}},i=Foe(t,r),a=await Zl(n,[i],e.projectRoot,o);if(a.exitCode!==0)throw new Error(`Install for refresh "${t.name}" failed with exit code ${a.exitCode}`)}}s(C1,"createRunInstallForRefresh");var E1=300*1e3;async function xy(e,t,r){let{dryRun:n,force:o,global:i,json:a}=_1(e),l=i?"global":"project",c=S1(t),m=s(()=>({scope:l,mode:"refresh",refreshed:[],unchanged:[],skipped:[],failed:[],dryRun:n}),"emptyData"),{config:p,context:u}=await _e(r,l);await ze(p,r);let f=await Ym(u.canonicalDir);try{let g=await Zt(u.canonicalDir);if(c.length>0){let $=new Set(g.map(Pe=>Pe.name)),re=c.filter(Pe=>!$.has(Pe));if(re.length>0)return a||S.error(`Unknown pack(s): ${re.join(", ")}`),{exitCode:2,data:m()}}let h=c.length>0?g.filter($=>c.includes($.name)):g;if(h.length===0)return a||S.info("No packs to refresh."),{exitCode:0,data:m()};let y=join(u.canonicalDir,"packs"),_=k1(),R=[];for(let $ of h)R.push(await I1($,y,{resolveRef:_}));let k=R.filter($=>$.classification==="error"),w=R.filter($=>$.classification==="unchanged"),D=R.filter($=>$.classification==="clean-update"),N=R.filter($=>$.classification==="needs-consent"),K=m();if(K.unchanged=w.map($=>({name:$.name,ref:$.newSha})),K.failed=k.map($=>({name:$.name,phase:"plan",error:$.error?.message??"unknown plan error"})),n){for(let $ of D)K.refreshed.push({name:$.name,oldRef:$.oldSha,newRef:$.newSha,oldSha:$.oldSha,newSha:$.newSha,changedFiles:{added:[],removed:[],modified:[]}});for(let $ of N)K.refreshed.push({name:$.name,oldRef:$.oldSha,newRef:$.newSha,oldSha:$.oldSha,newSha:$.newSha,changedFiles:{added:[],removed:[],modified:[]}});return {exitCode:k.length>0?1:0,data:K}}let J=new Set(D.map($=>$.name));if(N.length>0)if(o)for(let $ of N)J.add($.name);else {let $=await bC(N.map(re=>({name:re.name,modifiedCount:re.modifications.length})),{timeoutMs:E1});if($.proceed&&!$.perPack)for(let re of N)J.add(re.name);else if($.proceed&&$.perPack)for(let re of N)(await bC([{name:re.name,modifiedCount:re.modifications.length}],{timeoutMs:E1})).proceed?J.add(re.name):K.skipped.push({name:re.name,reason:"user-declined"});else for(let re of $.declined)K.skipped.push({name:re,reason:"user-declined"});}let ee=C1({projectRoot:r,scope:l});for(let $ of [...D,...N]){if(!J.has($.name))continue;let re=await L1($,u.canonicalDir,{runInstallForRefresh:ee});re.success?K.refreshed.push({name:$.name,oldRef:$.oldSha,newRef:$.newSha,oldSha:$.oldSha,newSha:$.newSha,changedFiles:{added:[],removed:[],modified:[]}}):K.failed.push({name:$.name,phase:re.phase??"apply",error:re.error??"unknown"});}return K.refreshed.length>0&&await ep("refresh",l,u.rootBase),{exitCode:K.failed.length>0?1:0,data:K}}finally{await f();}}s(xy,"runRefresh");async function O1(e,t,r){return xy(e,t,r)}s(O1,"runRefresh");function w1(e){let{data:t}=e;if(t.dryRun){if(t.refreshed.length===0&&t.unchanged.length===0){M.info("[dry-run] No packs to refresh.");return}M.info(`[dry-run] Would refresh ${t.refreshed.length} pack(s); ${t.unchanged.length} unchanged.`);for(let r of t.refreshed)M.info(` - ${r.name}: ${r.oldSha??"\u2014"} \u2192 ${r.newSha}`);for(let r of t.unchanged)M.info(` - ${r.name}: unchanged at ${r.ref}`);return}if(t.refreshed.length>0){M.success(`Refreshed ${t.refreshed.length} pack(s):`),M.note(`Refreshed ${t.refreshed.length} pack(s).`,"Refresh");for(let r of t.refreshed)M.info(` - ${r.name}: ${r.oldSha??"\u2014"} \u2192 ${r.newSha}`);}for(let r of t.unchanged)M.info(`Pack "${r.name}" unchanged at ${r.ref}.`);for(let r of t.skipped)M.warn(`Skipped "${r.name}": ${r.reason}`);for(let r of t.failed)M.error(`Failed "${r.name}" (${r.phase}): ${r.error}`);}s(w1,"renderRefresh");tt();b();xm();async function $oe(e){let t=await I(join(e,Lr));if(t===null)return {installed_at:null,source_type:null};try{let r=JSON.parse(t);return {installed_at:typeof r.installed_at=="string"?r.installed_at:null,source_type:typeof r.source_type=="string"?r.source_type:null}}catch{return {installed_at:null,source_type:null}}}s($oe,"readPackManifestMeta");function joe(e,t){return relative(e,t).replaceAll("\\","/")}s(joe,"toForwardSlashRel");async function Py(e,t){let r=e.global===true?"global":"project",n=Na(t,r),o=await Zt(n.canonicalDir),i=join(n.canonicalDir,"packs"),a=[];for(let l of o){let c=join(i,l.name),m=await $oe(c),p=await Sa(c);a.push({name:l.name,source:l.source,source_kind:l.source_kind,source_type:m.source_type,version:l.version??null,features:[...l.features],target:l.target??null,installed_at:m.installed_at,refreshed_at:l.refreshed_at??null,pack_path:joe(n.rootBase,c),license:p?.license??null});}return {exitCode:0,data:{scope:r,subcommand:"list",installs:a}}}s(Py,"runInstallsList");var Uoe=["list"];function b1(e){return {scope:e,subcommand:"list",installs:[]}}s(b1,"emptyData");async function A1(e,t,r){let n=e.global===true?"global":"project",o=t[0];return o===void 0||o===""?{exitCode:0,data:b1(n),showHelp:true}:o==="list"?Py(e,r):{exitCode:2,data:b1(n),showHelp:true,error:`Unknown installs subcommand: "${o}". Available: ${Uoe.join(", ")}. Did you mean \`agentsmesh install ${o}\`?`}}s(A1,"runInstalls");fe();var Dy=[{key:"name",label:"NAME"},{key:"source",label:"SOURCE"},{key:"features",label:"FEATURES"},{key:"license",label:"LICENSE"},{key:"installed",label:"LAST TOUCHED"}];function Boe(e){let t=e.refreshed_at??e.installed_at??null;return {name:e.name,source:e.source,features:e.features.join(", "),license:e.license??"-",installed:t?t.slice(0,10):"-"}}s(Boe,"toRow");function Koe(e){let t={name:0,source:0,features:0,license:0,installed:0};for(let n of Dy)t[n.key]=n.label.length;for(let n of e)for(let o of Dy)t[o.key]=Math.max(t[o.key],n[o.key].length);let r=Dy.map(n=>n.label.padEnd(t[n.key])).join(" ");S.info(r);for(let n of e)S.info(Dy.map(o=>n[o.key].padEnd(t[o.key])).join(" "));}s(Koe,"renderTable");function T1(e){if(e.error&&S.error(e.error),e.showHelp){Ud("installs");return}let{data:t}=e;if(t.installs.length===0){S.info("No installed packs.");return}Koe(t.installs.map(Boe));}s(T1,"renderInstalls");uL();b();var PC="agentsmesh.yaml";async function DC(e){let t=join(e,PC),r=await I(t);return r===null?{}:parse(r)??{}}s(DC,"readScopedConfigRaw");async function P1(e,t){let r=join(e,PC),n=await I(r)??`version: 1
459
- `,o=parse(n)??{};if(o.plugins||(o.plugins=[]),o.plugins.some(a=>a.id===t.id))return;let i={id:t.id,source:t.source};t.version!==void 0&&(i.version=t.version),o.plugins.push(i),await L(r,stringify(o));}s(P1,"writePluginEntry");async function D1(e,t){let r=join(e,PC),n=await I(r);if(n===null)return false;let o=parse(n)??{},i=(o.plugins??[]).length;o.plugins=(o.plugins??[]).filter(l=>l.id!==t),o.pluginTargets&&(o.pluginTargets=o.pluginTargets.filter(l=>l!==t));let a=o.plugins.length<i;return a&&await L(r,stringify(o)),a}s(D1,"removePluginEntry");async function N1(e,t,r){let n=t[0];if(n===void 0||n==="")return {exitCode:0,data:{subcommand:"list",plugins:[]},showHelp:true};switch(n){case "add":return Woe(e,t.slice(1),r);case "list":return Hoe(r);case "remove":return zoe(t.slice(1),r);case "info":return Voe(t.slice(1),r);default:return {exitCode:2,data:{subcommand:"list",plugins:[]},showHelp:true,error:`Unknown plugin subcommand: ${n}`}}}s(N1,"runPlugin");async function Woe(e,t,r){let n=t[0];if(!n)throw new Xn("Usage: agentsmesh plugin add <source> [--version <v>] [--id <id>]");let o=typeof e.version=="string"?e.version:"latest",a=(typeof e.id=="string"?e.id:void 0)??Joe(n);return await P1(r,{id:a,source:n,version:o==="latest"?void 0:o}),{exitCode:0,data:{subcommand:"add",id:a,package:n,version:o}}}s(Woe,"runPluginAdd");async function Hoe(e){let r=(await DC(e)).plugins??[],n=[];for(let o of r){let i="\u2717",a="";try{let l=await Mh(o,e);i=l.descriptors.length>0?"\u2713":"\u2713 (0 descriptors)",a=l.descriptors.map(c=>c.id).join(", ");}catch{}n.push({id:o.id,package:o.source,version:o.version,status:i,targets:a});}return {exitCode:0,data:{subcommand:"list",plugins:n}}}s(Hoe,"runPluginList");async function zoe(e,t){let r=e[0];if(!r)throw new Xn("Usage: agentsmesh plugin remove <id>");let n=await D1(t,r);return {exitCode:0,data:{subcommand:"remove",id:r,found:n}}}s(zoe,"runPluginRemove");async function Voe(e,t){let r=e[0];if(!r)throw new Xn("Usage: agentsmesh plugin info <id>");let o=((await DC(t)).plugins??[]).find(l=>l.id===r);if(!o)return {exitCode:1,data:{subcommand:"info",id:r,package:"",descriptors:[]}};let i;try{i=await Mh(o,t);}catch{return {exitCode:1,data:{subcommand:"info",id:r,package:o.source,version:o.version,descriptors:[]}}}let a=i.descriptors.map(l=>({id:l.id,description:l.emptyImportMessage}));return {exitCode:0,data:{subcommand:"info",id:r,package:o.source,version:o.version,descriptors:a}}}s(Voe,"runPluginInfo");function Joe(e){let t=e;if(t.startsWith("@")){let n=t.indexOf("/");n!==-1&&(t=t.slice(n+1));}t.startsWith("agentsmesh-target-")&&(t=t.slice(18)),t.startsWith("file:")&&(t=t.slice(5));let r=t.replace(/\\/g,"/").split("/");return t=r[r.length-1]??t,t=t.replace(/\.(js|ts)$/,""),t=t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),t||"plugin"}s(Joe,"derivePluginId");fe();function v1(e){if(e.error&&S.error(e.error),e.showHelp){Zoe();return}let{data:t}=e;switch(t.subcommand){case "add":Yoe(t.id,t.package,t.version);break;case "list":Xoe(t.plugins);break;case "remove":Qoe(t.id,t.found);break;case "info":qoe(t,e.exitCode);break}}s(v1,"renderPlugin");function Yoe(e,t,r){S.success(`Plugin '${e}' added to agentsmesh.yaml`),S.warn("Plugins load as trusted Node.js modules and run with full process privileges. Only install plugins from sources you trust.");let n=r!=="latest"?`@${r}`:"@latest";S.info(`Next: npm install ${t}${n}`),S.info(`Then add '${e}' to pluginTargets in agentsmesh.yaml to enable it.`);}s(Yoe,"renderAdd");function Xoe(e){if(e.length===0){S.info("No plugins configured. Use: agentsmesh plugin add <source>");return}S.info("Configured plugins:");for(let t of e){let r=t.version!==void 0?`@${t.version}`:"",n=t.status??"",o=t.targets??"";S.info(` ${t.id} | ${t.package}${r} | ${n} | ${o}`);}}s(Xoe,"renderList");function Qoe(e,t){t?S.success(`Plugin '${e}' removed from agentsmesh.yaml`):S.warn(`Plugin '${e}' was not found in agentsmesh.yaml`);}s(Qoe,"renderRemove");function qoe(e,t){if(t!==0&&e.package===""){S.error(`Plugin '${e.id}' not found in agentsmesh.yaml. Use: agentsmesh plugin add`);return}if(t!==0){S.error(`Failed to load plugin '${e.id}'`);return}S.info(`Plugin: ${e.id}`),S.info(`Source: ${e.package}${e.version!==void 0?`@${e.version}`:""}`),S.info(`Descriptors: ${e.descriptors.length}`);for(let r of e.descriptors)S.info(` - ${r.id}: ${r.description}`);}s(qoe,"renderInfo");function Zoe(){S.info("Usage: agentsmesh plugin <subcommand> [args] [flags]"),S.info(""),S.info("Subcommands:"),S.info(" add <source> Register a plugin package in agentsmesh.yaml"),S.info(" list Show all configured plugins and load status"),S.info(" remove <id> Remove a plugin from agentsmesh.yaml"),S.info(" info <id> Show descriptor details for a configured plugin"),S.info(""),S.info("Flags (add):"),S.info(" --version <v> Pin plugin version"),S.info(" --id <id> Override derived plugin id"),S.info(""),S.info("Note: plugins load as trusted Node.js modules and run with full process privileges."),S.info(" Only install plugins from sources you trust.");}s(Zoe,"printPluginHelp");b();cn();function Oa(e){return e.toUpperCase().replace(/-/g,"_")}s(Oa,"toPrefix");function Si(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}s(Si,"toPascal");function NC(e){let t=Oa(e.id),r=Si(e.id);return `import type { TargetGenerators } from '../catalog/target.interface.js';
457
+ `),true}s(m1,"removeAgentsmeshExtendByName");async function p1(e){let{plan:t,canonicalDir:r,configPath:n,config:o}=e,i=false;t.packDir!==null&&await j(t.packDir)&&(await rm$1(t.packDir,{recursive:true}),i=true);let a=await Cz(r,t.name),l=false;t.extendsEntry!==null&&(l=await m1(n,o,t.name));let c=t.packDir!==null,m=t.manifestEntry!==null,p=t.extendsEntry!==null,u=c&&!i||m&&!a||p&&!l;return {name:t.name,packDirRemoved:i,manifestEntryRemoved:a,extendsEntryRemoved:l,partial:u}}s(p1,"applyUninstall");function Poe(e,t){return relative(e,t).replaceAll("\\","/")}s(Poe,"toForwardSlashRel");function wC(e){return e.map(t=>({name:t,reason:"not found in installs.yaml"}))}s(wC,"buildSkipped");function u1(e,t,r){return e.plan.manifestEntry===null?null:Poe(t,join(r,e.plan.name))}s(u1,"packPathFor");function d1(e,t,r){return e.map(n=>({name:n.plan.name,pack_path:u1(n,t,r),manifest_entry_removed:false,extends_entry_removed:false,generated_files_removed:0,modified_files_kept:n.modifications.map(o=>({relativePath:o.relativePath,status:o.status})),legacy_migrated:n.legacyMigrated,partial:n.action==="keep-modified"||n.plan.packDir===null}))}s(d1,"previewEntries");function f1(e,t,r,n){let o=e.action==="keep-modified"||!t.packDirRemoved;return {name:t.name,pack_path:u1(e,r,n),manifest_entry_removed:t.manifestEntryRemoved,extends_entry_removed:t.extendsEntryRemoved,generated_files_removed:0,modified_files_kept:o?e.modifications.map(i=>({relativePath:i.relativePath,status:i.status})):[],legacy_migrated:e.legacyMigrated,partial:t.partial}}s(f1,"appliedEntry");function Doe(e){let t=[];for(let r of e)for(let n of r.split(",").map(o=>o.trim()).filter(Boolean))t.push(n);return t}s(Doe,"parseNames");function Noe(){return {ask:s(e=>np(e),"ask"),write:s(e=>process.stdout.write(e),"write")}}s(Noe,"defaultAdapter");async function Ty(e,t,r,n={}){let o=e.global===true?"global":"project",i=e.all===true,a=e.force===true,l=e["dry-run"]===true,c=e["keep-pack"]===true,m=e["keep-generated"]===true,p=n.assumeTty===true||process.stdin.isTTY,u=Doe(t),f=e.json===true;function g(R){return f||S.error(R),{exitCode:1,data:{scope:o,mode:"uninstall",removed:[],skipped:[],failed:[],dryRun:l}}}if(s(g,"validationFailure"),!i&&u.length===0)return g("Missing install name. Usage: agentsmesh uninstall <name>[,<name>...] [--all]");if(!p&&!a&&!l)return g("Non-interactive terminal: use --force or --dry-run for agentsmesh uninstall.");let{config:h,context:y}=await _e(r,o);await ze(h,r);let _=await Ym(y.canonicalDir);try{let R=await Zt(y.canonicalDir),k=join(y.canonicalDir,"packs"),w=o1({names:u,all:i,keepPack:c,keepGenerated:m,installs:R,extends:h.extends,packsDir:k}),{decisions:D,aborted:N}=await c1(w.removals,k,{adapter:n.promptAdapter??Noe(),warn:s(se=>S.warn(se),"warn"),bypassPrompts:a||l||!p,keepPack:c,dryRun:l});if(N)return S.warn("Uninstall aborted at modification prompt."),{exitCode:130,data:{scope:o,mode:"uninstall",removed:[],skipped:[],failed:[],dryRun:l}};for(let se of w.removals)for(let $ of se.warnings)S.warn($);if(l){for(let se of D)S.info(`[dry-run] Would uninstall pack "${se.plan.name}".`);return {exitCode:0,data:{scope:o,mode:"uninstall",removed:d1(D,y.rootBase,k),skipped:wC(w.skipped),failed:[],dryRun:!0}}}let K=join(y.configDir,"agentsmesh.yaml"),J=[],ee=[];for(let se of D){let $=se.action==="keep-modified"?{...se.plan,packDir:null}:se.plan;try{let re=await p1({plan:$,canonicalDir:y.canonicalDir,configPath:K,config:h});J.push(f1(se,re,y.rootBase,k));}catch(re){let Pe=re instanceof Error?re.message:String(re);ee.push({name:se.plan.name,reason:Pe}),f||S.error(`Failed to uninstall "${se.plan.name}": ${Pe}`);}}return !m&&J.length>0?await ep("uninstall",o,y.rootBase):m&&J.length>0&&S.warn("--keep-generated: target files derived from the removed pack(s) may be stale until the next generate."),{exitCode:ee.length>0?1:0,data:{scope:o,mode:"uninstall",removed:J,skipped:wC(w.skipped),failed:ee,dryRun:!1}}}finally{await _();}}s(Ty,"runUninstall");async function h1(e,t,r){return Ty(e,t,r)}s(h1,"runUninstall");function y1(e){let{data:t}=e;if(t.dryRun){if(t.removed.length===0){M.info("[dry-run] No installs matched.");return}M.info(`[dry-run] Would uninstall ${t.removed.length} pack(s):`);for(let r of t.removed){let n=r.pack_path===null?"extends-only":r.pack_path;M.info(` - ${r.name} (${n})`);}return}if(t.removed.length>0){let r=t.removed.map(n=>`"${n.name}"`).join(", ");M.success(`Uninstalled ${t.removed.length} pack(s): ${r}.`),M.note(`Uninstalled ${t.removed.length} pack(s): ${r}.`,"Uninstall");}for(let r of t.skipped)M.warn(`Skipped "${r.name}": ${r.reason}`);for(let r of t.failed)M.error(`Failed "${r.name}": ${r.reason}`);}s(y1,"renderUninstall");tt();sn();fe();function _1(e){let t=e.json===true;return {dryRun:e["dry-run"]===true,force:e.force===true||t,global:e.global===true,json:t,verbose:e.verbose===true}}s(_1,"readRefreshFlags");function S1(e){let t=[];for(let r of e)for(let n of r.split(",").map(o=>o.trim()).filter(Boolean))t.push(n);return t}s(S1,"parseRefreshNames");b();function voe(e){return e.modifications.length>0?"needs-consent":e.oldSha===e.newSha?"unchanged":"clean-update"}s(voe,"classifyRefreshPlan");async function I1(e,t,r){let n=join(t,e.name),o=e.version??null,i=join(n,Lr),a=await I(i);if(a===null)return {name:e.name,entry:e,oldSha:o,newSha:o??"",modifications:[],classification:"error",error:{phase:"plan",message:`Pack manifest missing at ${i}`}};let l;try{l=JSON.parse(a).files??{};}catch{return {name:e.name,entry:e,oldSha:o,newSha:o??"",modifications:[],classification:"error",error:{phase:"plan",message:`Pack manifest is corrupt at ${i}`}}}let c=[];await j(n)&&(c=await Ay(n,l));let m;try{m=await r.resolveRef(e);}catch(p){let u=p instanceof Error?p.message:String(p);return {name:e.name,entry:e,oldSha:o,newSha:o??"",modifications:c,classification:"error",error:{phase:"plan",message:u}}}return {name:e.name,entry:e,oldSha:o,newSha:m,modifications:c,classification:voe({modifications:c,oldSha:o,newSha:m})}}s(I1,"planSinglePack");function k1(){return async e=>{if(e.source_kind==="local")return e.version??"local";let t=Ld(e.source);if(t===null||t.remoteUrl===void 0)throw new Error(`Cannot parse source for refresh: ${e.source}`);let r=e.original_ref!==void 0&&e.original_ref!==""?e.original_ref:t.ref??"HEAD";return hy(r,t.remoteUrl)}}s(k1,"createDefaultResolveRef");async function L1(e,t,r){try{await r.runInstallForRefresh(e.entry,e.newSha);}catch(n){return {success:false,phase:"apply",error:n instanceof Error?n.message:String(n)}}try{let n=(r.now??(()=>new Date().toISOString()))(),i=(await Zt(t)).find(a=>a.name===e.entry.name);if(i===void 0)return {success:!1,phase:"manifest-update",error:`Entry "${e.entry.name}" not found after install`};await wy(t,{...i,refreshed_at:n});}catch(n){return {success:false,phase:"manifest-update",error:n instanceof Error?n.message:String(n)}}return {success:true}}s(L1,"applySinglePack");async function Foe(e,t,r={}){let n=r.readLine??np,o,i=new Promise(a=>{o=setTimeout(()=>a("timeout"),t),o.unref?.();});try{let a=await Promise.race([n(e),i]);return a==="timeout"?"timeout":Moe(a)}finally{o&&clearTimeout(o);}}s(Foe,"promptWithTimeout");function Moe(e){let t=e.trim().toLowerCase();return t==="y"||t==="yes"?"y":t==="per-pack"?"per-pack":"n"}s(Moe,"normalize");async function bC(e,t){let n=[`The following ${e.length} pack(s) have local edits that refresh will overwrite:`,...e.map(i=>` - ${i.name}: ${i.modifiedCount} modified file(s)`),"Continue? [y/N/per-pack] (5 min timeout, default N) "].join(`
458
+ `);switch(await Foe(n,t.timeoutMs,t)){case "y":return {proceed:true,perPack:false,declined:[]};case "per-pack":return {proceed:true,perPack:true,declined:[]};case "n":case "timeout":return {proceed:false,perPack:false,declined:e.map(i=>i.name)}}}s(bC,"runConsentPrompt");function Goe(e,t){let r=Ld(e.source);if(r===null||r.remoteUrl===void 0)return e.source;if(e.source_kind==="github"&&e.source.startsWith("github:")){let n=e.source.indexOf(":"),o=e.source.lastIndexOf("@");return `${o>n?e.source.slice(0,o):e.source}@${t}`}if(e.source_kind==="gitlab"&&e.source.startsWith("gitlab:")){let n=e.source.indexOf(":"),o=e.source.lastIndexOf("@");return `${o>n?e.source.slice(0,o):e.source}@${t}`}if(e.source.startsWith("git+")){let n=e.source.lastIndexOf("#");return `${n<0?e.source:e.source.slice(0,n)}#${t}`}return e.source}s(Goe,"buildSourceForRefresh");function C1(e){return async(t,r)=>{let n={force:true,forceFreshMaterialize:true};e.scope==="global"&&(n.global=true),t.target!==void 0&&(n.target=t.target),t.as!==void 0&&(n.as=t.as),t.path!==void 0&&(n.path=t.path),t.paths!==void 0&&t.paths.length>0&&(n.all=true),n.name=t.name;let o={features:t.features,pick:t.pick,...t.original_ref!==void 0?{originalRef:t.original_ref}:{},...t.accepted_elevated!==void 0?{acceptedElevated:t.accepted_elevated}:{}},i=Goe(t,r),a=await Zl(n,[i],e.projectRoot,o);if(a.exitCode!==0)throw new Error(`Install for refresh "${t.name}" failed with exit code ${a.exitCode}`)}}s(C1,"createRunInstallForRefresh");var E1=300*1e3;async function xy(e,t,r){let{dryRun:n,force:o,global:i,json:a}=_1(e),l=i?"global":"project",c=S1(t),m=s(()=>({scope:l,mode:"refresh",refreshed:[],unchanged:[],skipped:[],failed:[],dryRun:n}),"emptyData"),{config:p,context:u}=await _e(r,l);await ze(p,r);let f=await Ym(u.canonicalDir);try{let g=await Zt(u.canonicalDir);if(c.length>0){let $=new Set(g.map(Pe=>Pe.name)),re=c.filter(Pe=>!$.has(Pe));if(re.length>0)return a||S.error(`Unknown pack(s): ${re.join(", ")}`),{exitCode:2,data:m()}}let h=c.length>0?g.filter($=>c.includes($.name)):g;if(h.length===0)return a||S.info("No packs to refresh."),{exitCode:0,data:m()};let y=join(u.canonicalDir,"packs"),_=k1(),R=[];for(let $ of h)R.push(await I1($,y,{resolveRef:_}));let k=R.filter($=>$.classification==="error"),w=R.filter($=>$.classification==="unchanged"),D=R.filter($=>$.classification==="clean-update"),N=R.filter($=>$.classification==="needs-consent"),K=m();if(K.unchanged=w.map($=>({name:$.name,ref:$.newSha})),K.failed=k.map($=>({name:$.name,phase:"plan",error:$.error?.message??"unknown plan error"})),n){for(let $ of D)K.refreshed.push({name:$.name,oldRef:$.oldSha,newRef:$.newSha,oldSha:$.oldSha,newSha:$.newSha,changedFiles:{added:[],removed:[],modified:[]}});for(let $ of N)K.refreshed.push({name:$.name,oldRef:$.oldSha,newRef:$.newSha,oldSha:$.oldSha,newSha:$.newSha,changedFiles:{added:[],removed:[],modified:[]}});return {exitCode:k.length>0?1:0,data:K}}let J=new Set(D.map($=>$.name));if(N.length>0)if(o)for(let $ of N)J.add($.name);else {let $=await bC(N.map(re=>({name:re.name,modifiedCount:re.modifications.length})),{timeoutMs:E1});if($.proceed&&!$.perPack)for(let re of N)J.add(re.name);else if($.proceed&&$.perPack)for(let re of N)(await bC([{name:re.name,modifiedCount:re.modifications.length}],{timeoutMs:E1})).proceed?J.add(re.name):K.skipped.push({name:re.name,reason:"user-declined"});else for(let re of $.declined)K.skipped.push({name:re,reason:"user-declined"});}let ee=C1({projectRoot:r,scope:l});for(let $ of [...D,...N]){if(!J.has($.name))continue;let re=await L1($,u.canonicalDir,{runInstallForRefresh:ee});re.success?K.refreshed.push({name:$.name,oldRef:$.oldSha,newRef:$.newSha,oldSha:$.oldSha,newSha:$.newSha,changedFiles:{added:[],removed:[],modified:[]}}):K.failed.push({name:$.name,phase:re.phase??"apply",error:re.error??"unknown"});}return K.refreshed.length>0&&await ep("refresh",l,u.rootBase),{exitCode:K.failed.length>0?1:0,data:K}}finally{await f();}}s(xy,"runRefresh");async function O1(e,t,r){return xy(e,t,r)}s(O1,"runRefresh");function w1(e){let{data:t}=e;if(t.dryRun){if(t.refreshed.length===0&&t.unchanged.length===0){M.info("[dry-run] No packs to refresh.");return}M.info(`[dry-run] Would refresh ${t.refreshed.length} pack(s); ${t.unchanged.length} unchanged.`);for(let r of t.refreshed)M.info(` - ${r.name}: ${r.oldSha??"\u2014"} \u2192 ${r.newSha}`);for(let r of t.unchanged)M.info(` - ${r.name}: unchanged at ${r.ref}`);return}if(t.refreshed.length>0){M.success(`Refreshed ${t.refreshed.length} pack(s):`),M.note(`Refreshed ${t.refreshed.length} pack(s).`,"Refresh");for(let r of t.refreshed)M.info(` - ${r.name}: ${r.oldSha??"\u2014"} \u2192 ${r.newSha}`);}for(let r of t.unchanged)M.info(`Pack "${r.name}" unchanged at ${r.ref}.`);for(let r of t.skipped)M.warn(`Skipped "${r.name}": ${r.reason}`);for(let r of t.failed)M.error(`Failed "${r.name}" (${r.phase}): ${r.error}`);}s(w1,"renderRefresh");tt();b();xm();async function Uoe(e){let t=await I(join(e,Lr));if(t===null)return {installed_at:null,source_type:null};try{let r=JSON.parse(t);return {installed_at:typeof r.installed_at=="string"?r.installed_at:null,source_type:typeof r.source_type=="string"?r.source_type:null}}catch{return {installed_at:null,source_type:null}}}s(Uoe,"readPackManifestMeta");function Boe(e,t){return relative(e,t).replaceAll("\\","/")}s(Boe,"toForwardSlashRel");async function Py(e,t){let r=e.global===true?"global":"project",n=Na(t,r),o=await Zt(n.canonicalDir),i=join(n.canonicalDir,"packs"),a=[];for(let l of o){let c=join(i,l.name),m=await Uoe(c),p=await Sa(c);a.push({name:l.name,source:l.source,source_kind:l.source_kind,source_type:m.source_type,version:l.version??null,features:[...l.features],target:l.target??null,installed_at:m.installed_at,refreshed_at:l.refreshed_at??null,pack_path:Boe(n.rootBase,c),license:p?.license??null});}return {exitCode:0,data:{scope:r,subcommand:"list",installs:a}}}s(Py,"runInstallsList");var Koe=["list"];function b1(e){return {scope:e,subcommand:"list",installs:[]}}s(b1,"emptyData");async function A1(e,t,r){let n=e.global===true?"global":"project",o=t[0];return o===void 0||o===""?{exitCode:0,data:b1(n),showHelp:true}:o==="list"?Py(e,r):{exitCode:2,data:b1(n),showHelp:true,error:`Unknown installs subcommand: "${o}". Available: ${Koe.join(", ")}. Did you mean \`agentsmesh install ${o}\`?`}}s(A1,"runInstalls");fe();var Dy=[{key:"name",label:"NAME"},{key:"source",label:"SOURCE"},{key:"features",label:"FEATURES"},{key:"license",label:"LICENSE"},{key:"installed",label:"LAST TOUCHED"}];function Woe(e){let t=e.refreshed_at??e.installed_at??null;return {name:e.name,source:e.source,features:e.features.join(", "),license:e.license??"-",installed:t?t.slice(0,10):"-"}}s(Woe,"toRow");function Hoe(e){let t={name:0,source:0,features:0,license:0,installed:0};for(let n of Dy)t[n.key]=n.label.length;for(let n of e)for(let o of Dy)t[o.key]=Math.max(t[o.key],n[o.key].length);let r=Dy.map(n=>n.label.padEnd(t[n.key])).join(" ");S.info(r);for(let n of e)S.info(Dy.map(o=>n[o.key].padEnd(t[o.key])).join(" "));}s(Hoe,"renderTable");function T1(e){if(e.error&&S.error(e.error),e.showHelp){Ud("installs");return}let{data:t}=e;if(t.installs.length===0){S.info("No installed packs.");return}Hoe(t.installs.map(Woe));}s(T1,"renderInstalls");uL();b();var PC="agentsmesh.yaml";async function DC(e){let t=join(e,PC),r=await I(t);return r===null?{}:parse(r)??{}}s(DC,"readScopedConfigRaw");async function P1(e,t){let r=join(e,PC),n=await I(r)??`version: 1
459
+ `,o=parse(n)??{};if(o.plugins||(o.plugins=[]),o.plugins.some(a=>a.id===t.id))return;let i={id:t.id,source:t.source};t.version!==void 0&&(i.version=t.version),o.plugins.push(i),await L(r,stringify(o));}s(P1,"writePluginEntry");async function D1(e,t){let r=join(e,PC),n=await I(r);if(n===null)return false;let o=parse(n)??{},i=(o.plugins??[]).length;o.plugins=(o.plugins??[]).filter(l=>l.id!==t),o.pluginTargets&&(o.pluginTargets=o.pluginTargets.filter(l=>l!==t));let a=o.plugins.length<i;return a&&await L(r,stringify(o)),a}s(D1,"removePluginEntry");async function N1(e,t,r){let n=t[0];if(n===void 0||n==="")return {exitCode:0,data:{subcommand:"list",plugins:[]},showHelp:true};switch(n){case "add":return zoe(e,t.slice(1),r);case "list":return Voe(r);case "remove":return Joe(t.slice(1),r);case "info":return Yoe(t.slice(1),r);default:return {exitCode:2,data:{subcommand:"list",plugins:[]},showHelp:true,error:`Unknown plugin subcommand: ${n}`}}}s(N1,"runPlugin");async function zoe(e,t,r){let n=t[0];if(!n)throw new Xn("Usage: agentsmesh plugin add <source> [--version <v>] [--id <id>]");let o=typeof e.version=="string"?e.version:"latest",a=(typeof e.id=="string"?e.id:void 0)??Xoe(n);return await P1(r,{id:a,source:n,version:o==="latest"?void 0:o}),{exitCode:0,data:{subcommand:"add",id:a,package:n,version:o}}}s(zoe,"runPluginAdd");async function Voe(e){let r=(await DC(e)).plugins??[],n=[];for(let o of r){let i="\u2717",a="";try{let l=await Mh(o,e);i=l.descriptors.length>0?"\u2713":"\u2713 (0 descriptors)",a=l.descriptors.map(c=>c.id).join(", ");}catch{}n.push({id:o.id,package:o.source,version:o.version,status:i,targets:a});}return {exitCode:0,data:{subcommand:"list",plugins:n}}}s(Voe,"runPluginList");async function Joe(e,t){let r=e[0];if(!r)throw new Xn("Usage: agentsmesh plugin remove <id>");let n=await D1(t,r);return {exitCode:0,data:{subcommand:"remove",id:r,found:n}}}s(Joe,"runPluginRemove");async function Yoe(e,t){let r=e[0];if(!r)throw new Xn("Usage: agentsmesh plugin info <id>");let o=((await DC(t)).plugins??[]).find(l=>l.id===r);if(!o)return {exitCode:1,data:{subcommand:"info",id:r,package:"",descriptors:[]}};let i;try{i=await Mh(o,t);}catch{return {exitCode:1,data:{subcommand:"info",id:r,package:o.source,version:o.version,descriptors:[]}}}let a=i.descriptors.map(l=>({id:l.id,description:l.emptyImportMessage}));return {exitCode:0,data:{subcommand:"info",id:r,package:o.source,version:o.version,descriptors:a}}}s(Yoe,"runPluginInfo");function Xoe(e){let t=e;if(t.startsWith("@")){let n=t.indexOf("/");n!==-1&&(t=t.slice(n+1));}t.startsWith("agentsmesh-target-")&&(t=t.slice(18)),t.startsWith("file:")&&(t=t.slice(5));let r=t.replace(/\\/g,"/").split("/");return t=r[r.length-1]??t,t=t.replace(/\.(js|ts)$/,""),t=t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),t||"plugin"}s(Xoe,"derivePluginId");fe();function v1(e){if(e.error&&S.error(e.error),e.showHelp){tse();return}let{data:t}=e;switch(t.subcommand){case "add":Qoe(t.id,t.package,t.version);break;case "list":qoe(t.plugins);break;case "remove":Zoe(t.id,t.found);break;case "info":ese(t,e.exitCode);break}}s(v1,"renderPlugin");function Qoe(e,t,r){S.success(`Plugin '${e}' added to agentsmesh.yaml`),S.warn("Plugins load as trusted Node.js modules and run with full process privileges. Only install plugins from sources you trust.");let n=r!=="latest"?`@${r}`:"@latest";S.info(`Next: npm install ${t}${n}`),S.info(`Then add '${e}' to pluginTargets in agentsmesh.yaml to enable it.`);}s(Qoe,"renderAdd");function qoe(e){if(e.length===0){S.info("No plugins configured. Use: agentsmesh plugin add <source>");return}S.info("Configured plugins:");for(let t of e){let r=t.version!==void 0?`@${t.version}`:"",n=t.status??"",o=t.targets??"";S.info(` ${t.id} | ${t.package}${r} | ${n} | ${o}`);}}s(qoe,"renderList");function Zoe(e,t){t?S.success(`Plugin '${e}' removed from agentsmesh.yaml`):S.warn(`Plugin '${e}' was not found in agentsmesh.yaml`);}s(Zoe,"renderRemove");function ese(e,t){if(t!==0&&e.package===""){S.error(`Plugin '${e.id}' not found in agentsmesh.yaml. Use: agentsmesh plugin add`);return}if(t!==0){S.error(`Failed to load plugin '${e.id}'`);return}S.info(`Plugin: ${e.id}`),S.info(`Source: ${e.package}${e.version!==void 0?`@${e.version}`:""}`),S.info(`Descriptors: ${e.descriptors.length}`);for(let r of e.descriptors)S.info(` - ${r.id}: ${r.description}`);}s(ese,"renderInfo");function tse(){S.info("Usage: agentsmesh plugin <subcommand> [args] [flags]"),S.info(""),S.info("Subcommands:"),S.info(" add <source> Register a plugin package in agentsmesh.yaml"),S.info(" list Show all configured plugins and load status"),S.info(" remove <id> Remove a plugin from agentsmesh.yaml"),S.info(" info <id> Show descriptor details for a configured plugin"),S.info(""),S.info("Flags (add):"),S.info(" --version <v> Pin plugin version"),S.info(" --id <id> Override derived plugin id"),S.info(""),S.info("Note: plugins load as trusted Node.js modules and run with full process privileges."),S.info(" Only install plugins from sources you trust.");}s(tse,"printPluginHelp");b();cn();function Oa(e){return e.toUpperCase().replace(/-/g,"_")}s(Oa,"toPrefix");function Si(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}s(Si,"toPascal");function NC(e){let t=Oa(e.id),r=Si(e.id);return `import type { TargetGenerators } from '../catalog/target.interface.js';
460
460
  import type { TargetDescriptor, TargetLayout } from '../catalog/target-descriptor.js';
461
461
  import { generateRules } from './generator.js';
462
462
  import { importFrom${r} } from './importer.js';
@@ -684,26 +684,26 @@ export async function build${t}ImportPaths(
684
684
  // Reference: src/core/reference/import-maps/kiro.ts for a full example
685
685
  void ${r}_DIR;
686
686
  }
687
- `}s(U1,"TEMPLATE_IMPORT_MAP");var tse=/^[a-z][a-z0-9-]*$/;async function B1(e){let{id:t,projectRoot:r,force:n=false}=e,o=e.displayName??t,i={id:t,displayName:o};if(!tse.test(t))throw new Error(`Invalid target id "${t}". Must match /^[a-z][a-z0-9-]*$/ (lowercase letters, digits, hyphens; start with a letter).`);if(Ue.includes(t))throw new Error(`Target "${t}" already exists as a built-in target. Choose a different id.`);let a=[{rel:`src/targets/${t}/constants.ts`,content:F1(i)},{rel:`src/targets/${t}/index.ts`,content:NC(i)},{rel:`src/targets/${t}/generator.ts`,content:M1(i)},{rel:`src/targets/${t}/importer.ts`,content:G1(i)},{rel:`src/targets/${t}/linter.ts`,content:$1(i)},{rel:`src/targets/${t}/lint.ts`,content:j1(i)},{rel:`src/core/reference/import-maps/${t}.ts`,content:U1(i)},{rel:`tests/unit/targets/${t}/generator.test.ts`,content:vC(i)},{rel:`tests/unit/targets/${t}/importer.test.ts`,content:FC(i)},{rel:`tests/e2e/fixtures/${t}-project/AGENTS.md`,content:MC(i)}],l=[],c=[];for(let p of a){let u=join(r,p.rel);if(!n&&await j(u)){c.push(u);continue}await L(u,p.content),l.push(u);}let m=["1. Run: pnpm catalog:generate (auto-discovers the new target \u2014 updates IDs, descriptors, and import-map barrel)",`2. Fill in TODO(agentsmesh-scaffold) markers in src/targets/${t}/`,`3. Run: pnpm typecheck && pnpm test -- tests/unit/targets/${t}`,"4. Run: pnpm schemas:generate && pnpm matrix:generate"];return {written:l,skipped:c,postSteps:m}}s(B1,"writeTargetScaffold");async function W1(e,t,r){let n=t[0];return n===void 0||n===""?{exitCode:0,data:{id:"",written:[],skipped:[],postSteps:[]},showHelp:true}:n==="scaffold"?rse(e,t.slice(1),r):{exitCode:2,data:{id:"",written:[],skipped:[],postSteps:[]},showHelp:true,error:`Unknown target subcommand: ${n}`}}s(W1,"runTarget");async function rse(e,t,r){let n=t[0];if(!n)throw new Xn("Usage: agentsmesh target scaffold <id> [--name <displayName>] [--force]");let o=typeof e.name=="string"?e.name:void 0,i=e.force===true,a;try{a=await B1({id:n,displayName:o,projectRoot:r,force:i});}catch(l){return {exitCode:1,data:{id:n,written:[],skipped:[],postSteps:[]},error:l instanceof Error?l.message:String(l)}}return {exitCode:0,data:{id:n,written:a.written.map(l=>K1(l,r)),skipped:a.skipped.map(l=>K1(l,r)),postSteps:a.postSteps}}}s(rse,"runScaffold");function K1(e,t){return (e.startsWith(t)?e.slice(t.length+1):e).replaceAll("\\","/")}s(K1,"relativize");fe();function H1(e){if(e.error&&S.error(e.error),e.showHelp){nse();return}let{data:t}=e;for(let r of t.written)S.success(`created ${r}`);for(let r of t.skipped)S.warn(`skipped ${r} (already exists \u2014 use --force to overwrite)`);if(t.written.length>0){S.info(""),S.info("Next steps:");for(let r of t.postSteps)S.info(` ${r}`);}}s(H1,"renderTarget");function nse(){S.info("Usage: agentsmesh target <subcommand> [args] [flags]"),S.info(""),S.info("Subcommands:"),S.info(" scaffold <id> Generate a new target skeleton (files, tests, fixture)"),S.info(""),S.info("Flags (scaffold):"),S.info(" --name <displayName> Human-readable name (defaults to id)"),S.info(" --force Overwrite existing files");}s(nse,"printTargetHelp");rt();Ga();b();tt();sn();rs();function pse(e,t){return e===".agentsmesh"?false:!!(e.startsWith(".")||!t)}s(pse,"shouldSymlink");function use(e){let t=mkdtempSync(join(tmpdir(),"am-convert-")),r=readdirSync(e,{withFileTypes:true});for(let n of r){if(!pse(n.name,n.isDirectory()))continue;let o=join(e,n.name),i=join(t,n.name);symlinkSync(o,i,n.isDirectory()?"dir":"file");}return mkdirSync(join(t,".agentsmesh"),{recursive:true}),t}s(use,"createTempProjectRoot");async function vy(e,t){let r=t??process.cwd(),n=e.global===true?"global":"project",o=n==="global"?homedir():r,i=e.from,a=e.to;if(typeof i!="string"||!i)throw new Error("--from is required. Example: agentsmesh convert --from cursor --to claude-code");if(typeof a!="string"||!a)throw new Error("--to is required. Example: agentsmesh convert --from cursor --to claude-code");let l=i.toLowerCase().trim(),c=a.toLowerCase().trim();if(l===c)throw new Error("--from and --to must be different targets.");let m=Bt(l),p=Bt(c);if(!m||!p)try{let{config:_}=await _e(r,"project");await ze(_,r);}catch{let _=[];throw m||_.push(`--from "${i}"`),p||_.push(`--to "${a}"`),new Error(`Unknown ${_.join(" and ")}. Supported: ${Ue.join(", ")}.`)}let u=ne(l);if(!u)throw new Error(`Unknown --from "${i}". Supported: ${Ue.join(", ")}.`);if(!ne(c))throw new Error(`Unknown --to "${a}". Supported: ${Ue.join(", ")}.`);let g=e["dry-run"]===true,h=g?"dry-run":"convert",y=use(o);try{await u.generators.importFrom(y,{scope:n});let _=await Kt(y),R=Da.parse({version:1,targets:p?[c]:[],pluginTargets:p?[]:[c]}),k=await Yo({config:R,canonical:_,projectRoot:o,scope:n,targetFilter:[c]});if(!g){for(let N of k)if(N.status==="created"||N.status==="updated"){let K=Gh(o,N.path,N.target);await L(K,N.content);}}let w=k.filter(N=>N.status!=="skipped"),D=w.map(N=>({path:N.path,target:N.target,status:N.status}));return {exitCode:0,data:{from:l,to:c,mode:h,files:D,summary:{created:w.filter(N=>N.status==="created").length,updated:w.filter(N=>N.status==="updated").length,unchanged:w.filter(N=>N.status==="unchanged").length}}}}finally{rmSync(y,{recursive:true,force:true});}}s(vy,"runConvert");function z1(e){let{data:t}=e;if(t.files.length===0){M.info(`No files found to convert from ${t.from}.`);return}if(t.mode==="dry-run"){for(let i of t.files)M.info(`[dry-run] ${i.status} ${i.path} (${i.target})`);return}for(let i of t.files)(i.status==="created"||i.status==="updated")&&M.success(`${i.status} ${i.path}`);let{created:r,updated:n,unchanged:o}=t.summary;r>0||n>0?M.info(`Converted from ${t.from} \u2192 ${t.to}: ${r} created, ${n} updated, ${o} unchanged`):M.info(`Nothing changed. (${o} unchanged)`);}s(z1,"renderConvert");var dse=/(^|\s)\/[A-Za-z]|^[A-Z]:[\\/]/,v=class extends Error{static{s(this,"McpError");}code;details;constructor(t,r,n){if(dse.test(r))throw new Error(`McpError refuses absolute fs path in message: ${r}`);super(r),this.code=t,this.details=n;}toEnvelope(){return this.details===void 0?{code:this.code,message:this.message}:{code:this.code,message:this.message,details:this.details}}};function sp(e){return e.replace(/(['"`])\/[^'"`\s]+\1/gu,"$1<redacted>$1").replace(/(['"`])[A-Z]:[\\/][^'"`\s]+\1/gu,"$1<redacted>$1").replace(/\/[A-Za-z][^\s'"`<>()]*/gu,"<redacted>").replace(/[A-Z]:[\\/][^\s'"`<>()]*/gu,"<redacted>")}s(sp,"redactAbsolutePaths");async function GC(e){let t=resolve(e.projectRoot,".agentsmesh",e.feature),r=resolve(t,e.relativePath);if(!r.startsWith(t+sep)&&r!==t)throw new v("PATH_TRAVERSAL",`path escapes ${e.feature} directory`);if(Buffer.byteLength(e.content,"utf8")>1048576)throw new v("LIMIT_EXCEEDED","file body exceeds 1 MiB cap",{limit:1048576,actual:Buffer.byteLength(e.content,"utf8")});await mkdir(dirname(r),{recursive:true});let n=`${r}.tmp.${process.pid}.${Date.now()}`;return await writeFile(n,e.content,"utf8"),await rename(n,r),r}s(GC,"safeWrite");var Ise=/^---\r?\n([\s\S]*?)\r?\n---\r?\n\r?\n?([\s\S]*)$/;function ba(e){let t=Ise.exec(e);if(!t)return {frontmatter:{},body:e};let[,r,n]=t;return {frontmatter:parse(r)??{},body:n}}s(ba,"parseMd");function ip(e,t){return Object.keys(e).length===0?t:`---
687
+ `}s(U1,"TEMPLATE_IMPORT_MAP");var nse=/^[a-z][a-z0-9-]*$/;async function B1(e){let{id:t,projectRoot:r,force:n=false}=e,o=e.displayName??t,i={id:t,displayName:o};if(!nse.test(t))throw new Error(`Invalid target id "${t}". Must match /^[a-z][a-z0-9-]*$/ (lowercase letters, digits, hyphens; start with a letter).`);if(Ue.includes(t))throw new Error(`Target "${t}" already exists as a built-in target. Choose a different id.`);let a=[{rel:`src/targets/${t}/constants.ts`,content:F1(i)},{rel:`src/targets/${t}/index.ts`,content:NC(i)},{rel:`src/targets/${t}/generator.ts`,content:M1(i)},{rel:`src/targets/${t}/importer.ts`,content:G1(i)},{rel:`src/targets/${t}/linter.ts`,content:$1(i)},{rel:`src/targets/${t}/lint.ts`,content:j1(i)},{rel:`src/core/reference/import-maps/${t}.ts`,content:U1(i)},{rel:`tests/unit/targets/${t}/generator.test.ts`,content:vC(i)},{rel:`tests/unit/targets/${t}/importer.test.ts`,content:FC(i)},{rel:`tests/e2e/fixtures/${t}-project/AGENTS.md`,content:MC(i)}],l=[],c=[];for(let p of a){let u=join(r,p.rel);if(!n&&await j(u)){c.push(u);continue}await L(u,p.content),l.push(u);}let m=["1. Run: pnpm catalog:generate (auto-discovers the new target \u2014 updates IDs, descriptors, and import-map barrel)",`2. Fill in TODO(agentsmesh-scaffold) markers in src/targets/${t}/`,`3. Run: pnpm typecheck && pnpm test -- tests/unit/targets/${t}`,"4. Run: pnpm schemas:generate && pnpm matrix:generate"];return {written:l,skipped:c,postSteps:m}}s(B1,"writeTargetScaffold");async function W1(e,t,r){let n=t[0];return n===void 0||n===""?{exitCode:0,data:{id:"",written:[],skipped:[],postSteps:[]},showHelp:true}:n==="scaffold"?ose(e,t.slice(1),r):{exitCode:2,data:{id:"",written:[],skipped:[],postSteps:[]},showHelp:true,error:`Unknown target subcommand: ${n}`}}s(W1,"runTarget");async function ose(e,t,r){let n=t[0];if(!n)throw new Xn("Usage: agentsmesh target scaffold <id> [--name <displayName>] [--force]");let o=typeof e.name=="string"?e.name:void 0,i=e.force===true,a;try{a=await B1({id:n,displayName:o,projectRoot:r,force:i});}catch(l){return {exitCode:1,data:{id:n,written:[],skipped:[],postSteps:[]},error:l instanceof Error?l.message:String(l)}}return {exitCode:0,data:{id:n,written:a.written.map(l=>K1(l,r)),skipped:a.skipped.map(l=>K1(l,r)),postSteps:a.postSteps}}}s(ose,"runScaffold");function K1(e,t){return (e.startsWith(t)?e.slice(t.length+1):e).replaceAll("\\","/")}s(K1,"relativize");fe();function H1(e){if(e.error&&S.error(e.error),e.showHelp){sse();return}let{data:t}=e;for(let r of t.written)S.success(`created ${r}`);for(let r of t.skipped)S.warn(`skipped ${r} (already exists \u2014 use --force to overwrite)`);if(t.written.length>0){S.info(""),S.info("Next steps:");for(let r of t.postSteps)S.info(` ${r}`);}}s(H1,"renderTarget");function sse(){S.info("Usage: agentsmesh target <subcommand> [args] [flags]"),S.info(""),S.info("Subcommands:"),S.info(" scaffold <id> Generate a new target skeleton (files, tests, fixture)"),S.info(""),S.info("Flags (scaffold):"),S.info(" --name <displayName> Human-readable name (defaults to id)"),S.info(" --force Overwrite existing files");}s(sse,"printTargetHelp");rt();Ga();b();tt();sn();rs();function dse(e,t){return e===".agentsmesh"?false:!!(e.startsWith(".")||!t)}s(dse,"shouldSymlink");function fse(e){let t=mkdtempSync(join(tmpdir(),"am-convert-")),r=readdirSync(e,{withFileTypes:true});for(let n of r){if(!dse(n.name,n.isDirectory()))continue;let o=join(e,n.name),i=join(t,n.name);symlinkSync(o,i,n.isDirectory()?"dir":"file");}return mkdirSync(join(t,".agentsmesh"),{recursive:true}),t}s(fse,"createTempProjectRoot");async function vy(e,t){let r=t??process.cwd(),n=e.global===true?"global":"project",o=n==="global"?homedir():r,i=e.from,a=e.to;if(typeof i!="string"||!i)throw new Error("--from is required. Example: agentsmesh convert --from cursor --to claude-code");if(typeof a!="string"||!a)throw new Error("--to is required. Example: agentsmesh convert --from cursor --to claude-code");let l=i.toLowerCase().trim(),c=a.toLowerCase().trim();if(l===c)throw new Error("--from and --to must be different targets.");let m=Bt(l),p=Bt(c);if(!m||!p)try{let{config:_}=await _e(r,"project");await ze(_,r);}catch{let _=[];throw m||_.push(`--from "${i}"`),p||_.push(`--to "${a}"`),new Error(`Unknown ${_.join(" and ")}. Supported: ${Ue.join(", ")}.`)}let u=ne(l);if(!u)throw new Error(`Unknown --from "${i}". Supported: ${Ue.join(", ")}.`);if(!ne(c))throw new Error(`Unknown --to "${a}". Supported: ${Ue.join(", ")}.`);let g=e["dry-run"]===true,h=g?"dry-run":"convert",y=fse(o);try{await u.generators.importFrom(y,{scope:n});let _=await Kt(y),R=Da.parse({version:1,targets:p?[c]:[],pluginTargets:p?[]:[c]}),k=await Yo({config:R,canonical:_,projectRoot:o,scope:n,targetFilter:[c]});if(!g){for(let N of k)if(N.status==="created"||N.status==="updated"){let K=Gh(o,N.path,N.target);await L(K,N.content);}}let w=k.filter(N=>N.status!=="skipped"),D=w.map(N=>({path:N.path,target:N.target,status:N.status}));return {exitCode:0,data:{from:l,to:c,mode:h,files:D,summary:{created:w.filter(N=>N.status==="created").length,updated:w.filter(N=>N.status==="updated").length,unchanged:w.filter(N=>N.status==="unchanged").length}}}}finally{rmSync(y,{recursive:true,force:true});}}s(vy,"runConvert");function z1(e){let{data:t}=e;if(t.files.length===0){M.info(`No files found to convert from ${t.from}.`);return}if(t.mode==="dry-run"){for(let i of t.files)M.info(`[dry-run] ${i.status} ${i.path} (${i.target})`);return}for(let i of t.files)(i.status==="created"||i.status==="updated")&&M.success(`${i.status} ${i.path}`);let{created:r,updated:n,unchanged:o}=t.summary;r>0||n>0?M.info(`Converted from ${t.from} \u2192 ${t.to}: ${r} created, ${n} updated, ${o} unchanged`):M.info(`Nothing changed. (${o} unchanged)`);}s(z1,"renderConvert");var gse=/(^|\s)\/[A-Za-z]|^[A-Z]:[\\/]/,v=class extends Error{static{s(this,"McpError");}code;details;constructor(t,r,n){if(gse.test(r))throw new Error(`McpError refuses absolute fs path in message: ${r}`);super(r),this.code=t,this.details=n;}toEnvelope(){return this.details===void 0?{code:this.code,message:this.message}:{code:this.code,message:this.message,details:this.details}}};function sp(e){return e.replace(/(['"`])\/[^'"`\s]+\1/gu,"$1<redacted>$1").replace(/(['"`])[A-Z]:[\\/][^'"`\s]+\1/gu,"$1<redacted>$1").replace(/\/[A-Za-z][^\s'"`<>()]*/gu,"<redacted>").replace(/[A-Z]:[\\/][^\s'"`<>()]*/gu,"<redacted>")}s(sp,"redactAbsolutePaths");async function GC(e){let t=resolve(e.projectRoot,".agentsmesh",e.feature),r=resolve(t,e.relativePath);if(!r.startsWith(t+sep)&&r!==t)throw new v("PATH_TRAVERSAL",`path escapes ${e.feature} directory`);if(Buffer.byteLength(e.content,"utf8")>1048576)throw new v("LIMIT_EXCEEDED","file body exceeds 1 MiB cap",{limit:1048576,actual:Buffer.byteLength(e.content,"utf8")});await mkdir(dirname(r),{recursive:true});let n=`${r}.tmp.${process.pid}.${Date.now()}`;return await writeFile(n,e.content,"utf8"),await rename(n,r),r}s(GC,"safeWrite");var Lse=/^---\r?\n([\s\S]*?)\r?\n---\r?\n\r?\n?([\s\S]*)$/;function ba(e){let t=Lse.exec(e);if(!t)return {frontmatter:{},body:e};let[,r,n]=t;return {frontmatter:parse(r)??{},body:n}}s(ba,"parseMd");function ip(e,t){return Object.keys(e).length===0?t:`---
688
688
  ${stringify(e).trimEnd()}
689
689
  ---
690
690
 
691
- ${t}`}s(ip,"serializeMd");var Ose=/^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/,wse={rules:"_root"};function Fy(e){if(!Ose.test(e)||e.includes(".."))throw new v("INVALID_NAME",`invalid name: ${e}`)}s(Fy,"checkName");function My(e,t,r){return resolve(e,".agentsmesh",t,`${r}.md`)}s(My,"pathFor");function ap(e){let{feature:t,frontmatterSchema:r,toSummary:n}=e,o=s(l=>resolve(l,".agentsmesh",t),"featureDir");async function i(l){try{return (await readdir(o(l),{withFileTypes:!0})).filter(m=>m.isFile()&&m.name.endsWith(".md")).map(m=>m.name)}catch{return []}}s(i,"listFiles");async function a(l){try{return await stat(l),!0}catch{return false}}return s(a,"exists"),{async list(l){let c=await i(l.projectRoot),m=[];for(let p of c){let u=p.replace(/\.md$/,""),f=await readFile(join(o(l.projectRoot),p),"utf8"),{frontmatter:g}=ba(f);m.push(n(u,g));}return m},async get(l,{name:c}){Fy(c);let m=My(l.projectRoot,t,c);try{let p=await readFile(m,"utf8"),{frontmatter:u,body:f}=ba(p);return {name:c,frontmatter:u,body:f}}catch(p){let u=p.code;throw u==="ENOENT"?new v("NOT_FOUND",`${t} "${c}" not found`):new v("IO_ERROR",`failed to read ${t}`,{errno:u})}},async create(l,{name:c,frontmatter:m,body:p,dry_run:u}){Fy(c);let f=r.safeParse(m);if(!f.success)throw new v("VALIDATION_FAILED","invalid frontmatter",f.error.issues);let g=My(l.projectRoot,t,c);if(await a(g))throw new v("ALREADY_EXISTS",`${t} "${c}" exists`);if((await i(l.projectRoot)).length>=1e3)throw new v("LIMIT_EXCEEDED",`${t} dir at ${1e3} entries`);let y=ip(m,p);return u===true?{path:g,written:false}:(await GC({projectRoot:l.projectRoot,feature:t,relativePath:`${c}.md`,content:y}),{path:g,written:true})},async update(l,{name:c,frontmatter:m,body:p,merge:u,dry_run:f}){Fy(c);let g=My(l.projectRoot,t,c),h;try{let w=await readFile(g,"utf8");h=ba(w);}catch(w){let D=w.code;throw D==="ENOENT"?new v("NOT_FOUND",`${t} "${c}" not found`):new v("IO_ERROR",`failed to read ${t}`,{errno:D})}let y=m===void 0?h.frontmatter:u===true?{...h.frontmatter,...m}:m,_=r.safeParse(y);if(!_.success)throw new v("VALIDATION_FAILED","invalid frontmatter",_.error.issues);let R=p!==void 0?p:h.body,k=ip(y,R);return f===true?{path:g,written:false}:(await GC({projectRoot:l.projectRoot,feature:t,relativePath:`${c}.md`,content:k}),{path:g,written:true})},async delete(l,{name:c,force:m,dry_run:p}){if(Fy(c),wse[t]===c&&m!==true)throw new v("PROTECTED_FILE",`${t} "${c}" requires force: true`);let u=My(l.projectRoot,t,c);if(!await a(u))throw new v("NOT_FOUND",`${t} "${c}" not found`);return p===true?{path:u,deleted:false}:(await rm$1(u),{path:u,deleted:true})}}}s(ap,"createCanonicalHandlers");var bse=z$1.object({description:z$1.string().optional(),root:z$1.boolean().optional(),globs:z$1.array(z$1.string()).nullable().optional(),targets:z$1.array(z$1.string()).nullable().optional()}).passthrough(),Y1=ap({feature:"rules",frontmatterSchema:bse,toSummary:s((e,t)=>({name:e,description:t.description??null,root:!!t.root,globs:t.globs??null,targets:t.targets??null}),"toSummary")});var Ase=z$1.object({description:z$1.string().optional(),"allowed-tools":z$1.array(z$1.string()).optional()}).passthrough(),X1=ap({feature:"commands",frontmatterSchema:Ase,toSummary:s((e,t)=>({name:e,description:t.description??null,allowedTools:t["allowed-tools"]??null}),"toSummary")});var Tse=z$1.object({name:z$1.string().optional(),description:z$1.string().optional(),tools:z$1.array(z$1.string()).optional(),model:z$1.string().optional()}).passthrough(),Q1=ap({feature:"agents",frontmatterSchema:Tse,toSummary:s((e,t)=>({name:e,description:t.description??null,tools:t.tools??null,model:t.model??null}),"toSummary")});var xse=z$1.object({name:z$1.string().describe('Item name (e.g. "auth", "code-review")')}),Pse=z$1.object({name:z$1.string().describe('Item name (e.g. "auth", "code-review")'),frontmatter:z$1.record(z$1.string(),z$1.unknown()).describe("YAML frontmatter fields (e.g. { description, globs, targets })"),body:z$1.string().describe("Markdown body content"),dry_run:z$1.boolean().optional().describe("Preview changes without writing to disk")}),Dse=z$1.object({}).strict();function jC(e,t){let r=e==="rule"?"rules":e==="command"?"commands":"agents";return [{name:`list_${r}`,description:`List ${r} with summary metadata`,inputSchema:Dse,handler:s(n=>t.list(n),"handler"),resourceUri:`agentsmesh://canonical/${r}`},{name:`get_${e}`,description:`Get a single ${e} by name`,inputSchema:xse,handler:s((n,o)=>t.get(n,o),"handler"),resourceUri:`agentsmesh://canonical/${r}/{name}`},{name:`create_${e}`,description:`Create a new ${e}`,inputSchema:Pse,handler:s((n,o)=>t.create(n,o),"handler")},{name:`update_${e}`,description:`Update a ${e}. Default: replace frontmatter entirely. Set merge=true to shallow-merge. Omitting body preserves the existing body.`,inputSchema:z$1.object({name:z$1.string().describe("Name of the item to update"),frontmatter:z$1.record(z$1.string(),z$1.unknown()).optional().describe("New frontmatter fields (replaces by default; set merge=true to shallow-merge)"),body:z$1.string().optional().describe("New markdown body (omit to preserve existing)"),merge:z$1.boolean().optional().describe("If true, shallow-merge frontmatter instead of replacing"),dry_run:z$1.boolean().optional().describe("Preview changes without writing to disk")}),handler:s((n,o)=>t.update(n,o),"handler")},{name:`delete_${e}`,description:`Delete a ${e}. For rules: deleting _root requires force=true.`,inputSchema:z$1.object({name:z$1.string().describe("Name of the item to delete"),force:z$1.boolean().optional().describe("Required to delete protected files like _root"),dry_run:z$1.boolean().optional().describe("Preview without deleting")}),handler:s((n,o)=>t.delete(n,o),"handler")}]}s(jC,"canonicalTools");var q1=[...jC("rule",Y1),...jC("command",X1),...jC("agent",Q1)];async function eV(e){let t=resolve(e.projectRoot,".agentsmesh/skills",e.skillName),r=resolve(t,e.filePath);if(!r.startsWith(t+sep)&&r!==t)throw new v("PATH_TRAVERSAL","file escapes skill directory");try{return await readFile(r,"utf8")}catch(n){throw n.code==="ENOENT"?new v("NOT_FOUND",`skill file not found: ${e.filePath}`):new v("IO_ERROR","failed to read skill file")}}s(eV,"safeRead");var jse=/^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/,Use=/^[a-zA-Z0-9_][a-zA-Z0-9_/-]*\.[a-zA-Z0-9]+$/,oV=z$1.object({name:z$1.string().optional(),description:z$1.string().optional()}).passthrough();function Ad(e){if(!jse.test(e))throw new v("INVALID_NAME",`invalid skill name: ${e}`)}s(Ad,"checkName");function KC(e){if(!Use.test(e)||e.includes("..")||e.includes("//"))throw new v("PATH_TRAVERSAL",`invalid supporting-file path: ${e}`)}s(KC,"checkSupportPath");async function jy(e,t){if(Buffer.byteLength(t,"utf8")>1048576)throw new v("LIMIT_EXCEEDED","file body exceeds 1 MiB cap");await mkdir(dirname(e),{recursive:true});let r=`${e}.tmp.${process.pid}.${Date.now()}`;await writeFile(r,t,"utf8"),await rename(r,e);}s(jy,"atomicWrite");var sV=s(e=>resolve(e,".agentsmesh/skills"),"skillsDir"),Td=s((e,t)=>resolve(sV(e),t),"skillDir"),tc={async list(e){let t;try{t=(await readdir(sV(e.projectRoot),{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name);}catch{return []}let r=[];for(let n of t)try{let o=await readFile(resolve(Td(e.projectRoot,n),"SKILL.md"),"utf8"),i=ba(o).frontmatter;r.push({name:n,description:i.description??null});}catch{}return r},async get(e,{name:t}){Ad(t);let r=Td(e.projectRoot,t);try{let n=await readFile(resolve(r,"SKILL.md"),"utf8"),{frontmatter:o,body:i}=ba(n),l=(await readdir(r)).filter(c=>c!=="SKILL.md").sort();return {name:t,frontmatter:o,body:i,supportingFiles:l}}catch(n){throw n.code==="ENOENT"?new v("NOT_FOUND",`skill "${t}" not found`):new v("IO_ERROR","failed to read skill")}},async getFile(e,{name:t,path:r}){return Ad(t),KC(r),{content:await eV({projectRoot:e.projectRoot,skillName:t,filePath:r}),encoding:"utf-8"}},async create(e,t){Ad(t.name);let r=oV.safeParse(t.frontmatter);if(!r.success)throw new v("VALIDATION_FAILED","invalid frontmatter",r.error.issues);let n=Td(e.projectRoot,t.name),o=false;try{await stat(n),o=!0;}catch{}if(o)throw new v("ALREADY_EXISTS",`skill "${t.name}" exists`);let i=t.supportingFiles??{},a=Object.keys(i);if(a.forEach(KC),a.length+1>1e3)throw new v("LIMIT_EXCEEDED","supporting files exceed cap");if(t.dry_run===true)return {path:n,written:false,supportingFilesWritten:[]};let l=resolve(n,"SKILL.md");await jy(l,ip(t.frontmatter,t.body));for(let[c,m]of Object.entries(i))await jy(resolve(n,c),m);return {path:n,written:true,supportingFilesWritten:a}},async update(e,t){Ad(t.name);let r=Td(e.projectRoot,t.name),n;try{let p=await readFile(resolve(r,"SKILL.md"),"utf8");n=ba(p);}catch(p){throw p.code==="ENOENT"?new v("NOT_FOUND",`skill "${t.name}" not found`):new v("IO_ERROR","failed to read skill")}let o=t.frontmatter===void 0?n.frontmatter:t.merge===true?{...n.frontmatter,...t.frontmatter}:t.frontmatter,i=oV.safeParse(o);if(!i.success)throw new v("VALIDATION_FAILED","invalid frontmatter",i.error.issues);let a=t.body!==void 0?t.body:n.body,l=t.supportingFiles??{};Object.keys(l).forEach(KC);let c=[],m=[];if(t.dry_run===true)return Object.entries(l).forEach(([p,u])=>(u===null?m:c).push(p)),{path:r,written:false,supportingFilesAffected:{written:c,deleted:m}};await jy(resolve(r,"SKILL.md"),ip(o,a));for(let[p,u]of Object.entries(l)){let f=resolve(r,p);if(u===null)try{await rm$1(f),m.push(p);}catch{}else await jy(f,u),c.push(p);}return {path:r,written:true,supportingFilesAffected:{written:c,deleted:m}}},async delete(e,{name:t,dry_run:r}){Ad(t);let n=Td(e.projectRoot,t);try{await stat(n);}catch{throw new v("NOT_FOUND",`skill "${t}" not found`)}return r===true?{path:n,deleted:false}:(await rm$1(n,{recursive:true}),{path:n,deleted:true})}};var Bse=z$1.object({}).strict(),Kse=z$1.object({name:z$1.string().describe("Item name")}),iV=[{name:"list_skills",description:"List skills",inputSchema:Bse,handler:s(e=>tc.list(e),"handler"),resourceUri:"agentsmesh://canonical/skills"},{name:"get_skill",description:"Get one skill (frontmatter + body + supporting filenames)",inputSchema:Kse,handler:s((e,t)=>tc.get(e,t),"handler"),resourceUri:"agentsmesh://canonical/skills/{name}"},{name:"get_skill_file",description:"Read a skill supporting file by name and relative path",inputSchema:z$1.object({name:z$1.string().describe("Skill name"),path:z$1.string().describe('Relative path within the skill directory (e.g. "helper.md")')}),handler:s((e,t)=>tc.getFile(e,t),"handler"),resourceUri:"agentsmesh://canonical/skills/{name}/files/{path}"},{name:"create_skill",description:"Create a skill directory with SKILL.md and optional supporting files",inputSchema:z$1.object({name:z$1.string().describe("Skill name (becomes directory name)"),frontmatter:z$1.record(z$1.string(),z$1.unknown()).describe("YAML frontmatter for SKILL.md"),body:z$1.string().describe("Markdown body for SKILL.md"),supportingFiles:z$1.record(z$1.string(),z$1.string()).optional().describe("Map of relative-path \u2192 content for supporting files"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>tc.create(e,t),"handler")},{name:"update_skill",description:"Update a skill. supportingFiles: string value writes/replaces, null deletes, unlisted files are untouched.",inputSchema:z$1.object({name:z$1.string().describe("Skill name"),frontmatter:z$1.record(z$1.string(),z$1.unknown()).optional().describe("New frontmatter (replaces by default; merge=true to shallow-merge)"),body:z$1.string().optional().describe("New body (omit to preserve existing)"),merge:z$1.boolean().optional().describe("Shallow-merge frontmatter instead of replacing"),supportingFiles:z$1.record(z$1.string(),z$1.union([z$1.string(),z$1.null()])).optional().describe("Map of path \u2192 content (string=write, null=delete, absent=keep)"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>tc.update(e,t),"handler")},{name:"delete_skill",description:"Delete a skill",inputSchema:z$1.object({name:z$1.string(),dry_run:z$1.boolean().optional()}),handler:s((e,t)=>tc.delete(e,t),"handler")}];async function aV(e){if(e.filename!==void 0&&e.filename!=="agentsmesh.yaml")throw new v("PATH_TRAVERSAL","only agentsmesh.yaml is writable");if(Buffer.byteLength(e.content,"utf8")>1048576)throw new v("LIMIT_EXCEEDED","config exceeds 1 MiB cap");let t=resolve(e.projectRoot,"agentsmesh.yaml"),r=`${t}.tmp.${process.pid}.${Date.now()}`;return await writeFile(r,e.content,"utf8"),await rename(r,t),t}s(aV,"safeConfigWrite");function Vse(e){if(!e||typeof e!="object")return [e];let t=e,r=t.hooks;return Array.isArray(r)?r.map(n=>{let o=n&&typeof n=="object"?n:{};return {matcher:t.matcher,...o.type!==void 0&&{type:o.type},...o.command!==void 0&&{command:o.command},...o.prompt!==void 0&&{prompt:o.prompt},...o.timeout!==void 0&&{timeout:o.timeout}}}):[t]}s(Vse,"flattenEntry");function lV(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Array.isArray(n)?n.flatMap(Vse):n;return t}s(lV,"normalizeHooksRecord");rs();wp();async function xd(e){try{return parse(await readFile(e,"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw new v("IO_ERROR","failed to read yaml")}}s(xd,"readYaml");async function cp(e,t){if(Buffer.byteLength(t,"utf8")>1048576)throw new v("LIMIT_EXCEEDED","file exceeds 1 MiB cap");let r=`${e}.tmp.${process.pid}.${Date.now()}`;await writeFile(r,t,"utf8"),await rename(r,e);}s(cp,"atomicWrite");var Er={async getConfig(e){let t=await xd(resolve(e.projectRoot,"agentsmesh.yaml"));if(t===null)throw new v("NO_PROJECT","agentsmesh.yaml missing");return t},async listMcpServers(e){let t=resolve(e.projectRoot,".agentsmesh/mcp.json");try{return {servers:(await pn(t))?.mcpServers??null}}catch{return {servers:null}}},async getPermissions(e){return await xd(resolve(e.projectRoot,".agentsmesh/permissions.yaml"))??null},async getHooks(e){return await xd(resolve(e.projectRoot,".agentsmesh/hooks.yaml"))??null},async getIgnore(e){try{return {patterns:(await readFile(resolve(e.projectRoot,".agentsmesh/ignore"),"utf8")).split(/\r?\n/).filter(r=>r!==""&&!r.startsWith("#"))}}catch{return {patterns:null}}},async updateConfig(e,t){let r=await xd(resolve(e.projectRoot,"agentsmesh.yaml"))??{},n={...r},o=s((c,m)=>{m!==void 0&&(n[c]=t.merge===true&&Array.isArray(r[c])?Array.from(new Set([...r[c],...m])):m);},"apply");o("targets",t.targets),o("features",t.features),t.conversions!==void 0&&(n.conversions=t.merge===true&&r.conversions!==void 0?{...r.conversions,...t.conversions}:t.conversions);let i=Da.safeParse(n);if(!i.success)throw new v("VALIDATION_FAILED","invalid config",i.error.issues);let a=stringify(n);return t.dry_run===true?{path:resolve(e.projectRoot,"agentsmesh.yaml"),written:false}:{path:await aV({projectRoot:e.projectRoot,content:a,filename:t.filename}),written:true}},async addMcpServer(e,t){let r=resolve(e.projectRoot,".agentsmesh/mcp.json"),n=await pn(r).catch(()=>null)??{mcpServers:{}};if(n.mcpServers[t.name]!==void 0)throw new v("ALREADY_EXISTS",`server "${t.name}" exists`);return n.mcpServers[t.name]=t.server,t.dry_run===true?{path:r,written:false}:(await cp(r,JSON.stringify(n,null,2)+`
691
+ ${t}`}s(ip,"serializeMd");var bse=/^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/,Ase={rules:"_root"};function Fy(e){if(!bse.test(e)||e.includes(".."))throw new v("INVALID_NAME",`invalid name: ${e}`)}s(Fy,"checkName");function My(e,t,r){return resolve(e,".agentsmesh",t,`${r}.md`)}s(My,"pathFor");function ap(e){let{feature:t,frontmatterSchema:r,toSummary:n}=e,o=s(l=>resolve(l,".agentsmesh",t),"featureDir");async function i(l){try{return (await readdir(o(l),{withFileTypes:!0})).filter(m=>m.isFile()&&m.name.endsWith(".md")).map(m=>m.name)}catch{return []}}s(i,"listFiles");async function a(l){try{return await stat(l),!0}catch{return false}}return s(a,"exists"),{async list(l){let c=await i(l.projectRoot),m=[];for(let p of c){let u=p.replace(/\.md$/,""),f=await readFile(join(o(l.projectRoot),p),"utf8"),{frontmatter:g}=ba(f);m.push(n(u,g));}return m},async get(l,{name:c}){Fy(c);let m=My(l.projectRoot,t,c);try{let p=await readFile(m,"utf8"),{frontmatter:u,body:f}=ba(p);return {name:c,frontmatter:u,body:f}}catch(p){let u=p.code;throw u==="ENOENT"?new v("NOT_FOUND",`${t} "${c}" not found`):new v("IO_ERROR",`failed to read ${t}`,{errno:u})}},async create(l,{name:c,frontmatter:m,body:p,dry_run:u}){Fy(c);let f=r.safeParse(m);if(!f.success)throw new v("VALIDATION_FAILED","invalid frontmatter",f.error.issues);let g=My(l.projectRoot,t,c);if(await a(g))throw new v("ALREADY_EXISTS",`${t} "${c}" exists`);if((await i(l.projectRoot)).length>=1e3)throw new v("LIMIT_EXCEEDED",`${t} dir at ${1e3} entries`);let y=ip(m,p);return u===true?{path:g,written:false}:(await GC({projectRoot:l.projectRoot,feature:t,relativePath:`${c}.md`,content:y}),{path:g,written:true})},async update(l,{name:c,frontmatter:m,body:p,merge:u,dry_run:f}){Fy(c);let g=My(l.projectRoot,t,c),h;try{let w=await readFile(g,"utf8");h=ba(w);}catch(w){let D=w.code;throw D==="ENOENT"?new v("NOT_FOUND",`${t} "${c}" not found`):new v("IO_ERROR",`failed to read ${t}`,{errno:D})}let y=m===void 0?h.frontmatter:u===true?{...h.frontmatter,...m}:m,_=r.safeParse(y);if(!_.success)throw new v("VALIDATION_FAILED","invalid frontmatter",_.error.issues);let R=p!==void 0?p:h.body,k=ip(y,R);return f===true?{path:g,written:false}:(await GC({projectRoot:l.projectRoot,feature:t,relativePath:`${c}.md`,content:k}),{path:g,written:true})},async delete(l,{name:c,force:m,dry_run:p}){if(Fy(c),Ase[t]===c&&m!==true)throw new v("PROTECTED_FILE",`${t} "${c}" requires force: true`);let u=My(l.projectRoot,t,c);if(!await a(u))throw new v("NOT_FOUND",`${t} "${c}" not found`);return p===true?{path:u,deleted:false}:(await rm$1(u),{path:u,deleted:true})}}}s(ap,"createCanonicalHandlers");var Tse=z$1.object({description:z$1.string().optional(),root:z$1.boolean().optional(),globs:z$1.array(z$1.string()).nullable().optional(),targets:z$1.array(z$1.string()).nullable().optional()}).passthrough(),Y1=ap({feature:"rules",frontmatterSchema:Tse,toSummary:s((e,t)=>({name:e,description:t.description??null,root:!!t.root,globs:t.globs??null,targets:t.targets??null}),"toSummary")});var xse=z$1.object({description:z$1.string().optional(),"allowed-tools":z$1.array(z$1.string()).optional()}).passthrough(),X1=ap({feature:"commands",frontmatterSchema:xse,toSummary:s((e,t)=>({name:e,description:t.description??null,allowedTools:t["allowed-tools"]??null}),"toSummary")});var Pse=z$1.object({name:z$1.string().optional(),description:z$1.string().optional(),tools:z$1.array(z$1.string()).optional(),model:z$1.string().optional()}).passthrough(),Q1=ap({feature:"agents",frontmatterSchema:Pse,toSummary:s((e,t)=>({name:e,description:t.description??null,tools:t.tools??null,model:t.model??null}),"toSummary")});var Dse=z$1.object({name:z$1.string().describe('Item name (e.g. "auth", "code-review")')}),Nse=z$1.object({name:z$1.string().describe('Item name (e.g. "auth", "code-review")'),frontmatter:z$1.record(z$1.string(),z$1.unknown()).describe("YAML frontmatter fields (e.g. { description, globs, targets })"),body:z$1.string().describe("Markdown body content"),dry_run:z$1.boolean().optional().describe("Preview changes without writing to disk")}),vse=z$1.object({}).strict();function jC(e,t){let r=e==="rule"?"rules":e==="command"?"commands":"agents";return [{name:`list_${r}`,description:`List ${r} with summary metadata`,inputSchema:vse,handler:s(n=>t.list(n),"handler"),resourceUri:`agentsmesh://canonical/${r}`},{name:`get_${e}`,description:`Get a single ${e} by name`,inputSchema:Dse,handler:s((n,o)=>t.get(n,o),"handler"),resourceUri:`agentsmesh://canonical/${r}/{name}`},{name:`create_${e}`,description:`Create a new ${e}`,inputSchema:Nse,handler:s((n,o)=>t.create(n,o),"handler")},{name:`update_${e}`,description:`Update a ${e}. Default: replace frontmatter entirely. Set merge=true to shallow-merge. Omitting body preserves the existing body.`,inputSchema:z$1.object({name:z$1.string().describe("Name of the item to update"),frontmatter:z$1.record(z$1.string(),z$1.unknown()).optional().describe("New frontmatter fields (replaces by default; set merge=true to shallow-merge)"),body:z$1.string().optional().describe("New markdown body (omit to preserve existing)"),merge:z$1.boolean().optional().describe("If true, shallow-merge frontmatter instead of replacing"),dry_run:z$1.boolean().optional().describe("Preview changes without writing to disk")}),handler:s((n,o)=>t.update(n,o),"handler")},{name:`delete_${e}`,description:`Delete a ${e}. For rules: deleting _root requires force=true.`,inputSchema:z$1.object({name:z$1.string().describe("Name of the item to delete"),force:z$1.boolean().optional().describe("Required to delete protected files like _root"),dry_run:z$1.boolean().optional().describe("Preview without deleting")}),handler:s((n,o)=>t.delete(n,o),"handler")}]}s(jC,"canonicalTools");var q1=[...jC("rule",Y1),...jC("command",X1),...jC("agent",Q1)];async function eV(e){let t=resolve(e.projectRoot,".agentsmesh/skills",e.skillName),r=resolve(t,e.filePath);if(!r.startsWith(t+sep)&&r!==t)throw new v("PATH_TRAVERSAL","file escapes skill directory");try{return await readFile(r,"utf8")}catch(n){throw n.code==="ENOENT"?new v("NOT_FOUND",`skill file not found: ${e.filePath}`):new v("IO_ERROR","failed to read skill file")}}s(eV,"safeRead");var Bse=/^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/,Kse=/^[a-zA-Z0-9_][a-zA-Z0-9_/-]*\.[a-zA-Z0-9]+$/,oV=z$1.object({name:z$1.string().optional(),description:z$1.string().optional()}).passthrough();function Ad(e){if(!Bse.test(e))throw new v("INVALID_NAME",`invalid skill name: ${e}`)}s(Ad,"checkName");function KC(e){if(!Kse.test(e)||e.includes("..")||e.includes("//"))throw new v("PATH_TRAVERSAL",`invalid supporting-file path: ${e}`)}s(KC,"checkSupportPath");async function jy(e,t){if(Buffer.byteLength(t,"utf8")>1048576)throw new v("LIMIT_EXCEEDED","file body exceeds 1 MiB cap");await mkdir(dirname(e),{recursive:true});let r=`${e}.tmp.${process.pid}.${Date.now()}`;await writeFile(r,t,"utf8"),await rename(r,e);}s(jy,"atomicWrite");var sV=s(e=>resolve(e,".agentsmesh/skills"),"skillsDir"),Td=s((e,t)=>resolve(sV(e),t),"skillDir"),tc={async list(e){let t;try{t=(await readdir(sV(e.projectRoot),{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name);}catch{return []}let r=[];for(let n of t)try{let o=await readFile(resolve(Td(e.projectRoot,n),"SKILL.md"),"utf8"),i=ba(o).frontmatter;r.push({name:n,description:i.description??null});}catch{}return r},async get(e,{name:t}){Ad(t);let r=Td(e.projectRoot,t);try{let n=await readFile(resolve(r,"SKILL.md"),"utf8"),{frontmatter:o,body:i}=ba(n),l=(await readdir(r)).filter(c=>c!=="SKILL.md").sort();return {name:t,frontmatter:o,body:i,supportingFiles:l}}catch(n){throw n.code==="ENOENT"?new v("NOT_FOUND",`skill "${t}" not found`):new v("IO_ERROR","failed to read skill")}},async getFile(e,{name:t,path:r}){return Ad(t),KC(r),{content:await eV({projectRoot:e.projectRoot,skillName:t,filePath:r}),encoding:"utf-8"}},async create(e,t){Ad(t.name);let r=oV.safeParse(t.frontmatter);if(!r.success)throw new v("VALIDATION_FAILED","invalid frontmatter",r.error.issues);let n=Td(e.projectRoot,t.name),o=false;try{await stat(n),o=!0;}catch{}if(o)throw new v("ALREADY_EXISTS",`skill "${t.name}" exists`);let i=t.supportingFiles??{},a=Object.keys(i);if(a.forEach(KC),a.length+1>1e3)throw new v("LIMIT_EXCEEDED","supporting files exceed cap");if(t.dry_run===true)return {path:n,written:false,supportingFilesWritten:[]};let l=resolve(n,"SKILL.md");await jy(l,ip(t.frontmatter,t.body));for(let[c,m]of Object.entries(i))await jy(resolve(n,c),m);return {path:n,written:true,supportingFilesWritten:a}},async update(e,t){Ad(t.name);let r=Td(e.projectRoot,t.name),n;try{let p=await readFile(resolve(r,"SKILL.md"),"utf8");n=ba(p);}catch(p){throw p.code==="ENOENT"?new v("NOT_FOUND",`skill "${t.name}" not found`):new v("IO_ERROR","failed to read skill")}let o=t.frontmatter===void 0?n.frontmatter:t.merge===true?{...n.frontmatter,...t.frontmatter}:t.frontmatter,i=oV.safeParse(o);if(!i.success)throw new v("VALIDATION_FAILED","invalid frontmatter",i.error.issues);let a=t.body!==void 0?t.body:n.body,l=t.supportingFiles??{};Object.keys(l).forEach(KC);let c=[],m=[];if(t.dry_run===true)return Object.entries(l).forEach(([p,u])=>(u===null?m:c).push(p)),{path:r,written:false,supportingFilesAffected:{written:c,deleted:m}};await jy(resolve(r,"SKILL.md"),ip(o,a));for(let[p,u]of Object.entries(l)){let f=resolve(r,p);if(u===null)try{await rm$1(f),m.push(p);}catch{}else await jy(f,u),c.push(p);}return {path:r,written:true,supportingFilesAffected:{written:c,deleted:m}}},async delete(e,{name:t,dry_run:r}){Ad(t);let n=Td(e.projectRoot,t);try{await stat(n);}catch{throw new v("NOT_FOUND",`skill "${t}" not found`)}return r===true?{path:n,deleted:false}:(await rm$1(n,{recursive:true}),{path:n,deleted:true})}};var Wse=z$1.object({}).strict(),Hse=z$1.object({name:z$1.string().describe("Item name")}),iV=[{name:"list_skills",description:"List skills",inputSchema:Wse,handler:s(e=>tc.list(e),"handler"),resourceUri:"agentsmesh://canonical/skills"},{name:"get_skill",description:"Get one skill (frontmatter + body + supporting filenames)",inputSchema:Hse,handler:s((e,t)=>tc.get(e,t),"handler"),resourceUri:"agentsmesh://canonical/skills/{name}"},{name:"get_skill_file",description:"Read a skill supporting file by name and relative path",inputSchema:z$1.object({name:z$1.string().describe("Skill name"),path:z$1.string().describe('Relative path within the skill directory (e.g. "helper.md")')}),handler:s((e,t)=>tc.getFile(e,t),"handler"),resourceUri:"agentsmesh://canonical/skills/{name}/files/{path}"},{name:"create_skill",description:"Create a skill directory with SKILL.md and optional supporting files",inputSchema:z$1.object({name:z$1.string().describe("Skill name (becomes directory name)"),frontmatter:z$1.record(z$1.string(),z$1.unknown()).describe("YAML frontmatter for SKILL.md"),body:z$1.string().describe("Markdown body for SKILL.md"),supportingFiles:z$1.record(z$1.string(),z$1.string()).optional().describe("Map of relative-path \u2192 content for supporting files"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>tc.create(e,t),"handler")},{name:"update_skill",description:"Update a skill. supportingFiles: string value writes/replaces, null deletes, unlisted files are untouched.",inputSchema:z$1.object({name:z$1.string().describe("Skill name"),frontmatter:z$1.record(z$1.string(),z$1.unknown()).optional().describe("New frontmatter (replaces by default; merge=true to shallow-merge)"),body:z$1.string().optional().describe("New body (omit to preserve existing)"),merge:z$1.boolean().optional().describe("Shallow-merge frontmatter instead of replacing"),supportingFiles:z$1.record(z$1.string(),z$1.union([z$1.string(),z$1.null()])).optional().describe("Map of path \u2192 content (string=write, null=delete, absent=keep)"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>tc.update(e,t),"handler")},{name:"delete_skill",description:"Delete a skill",inputSchema:z$1.object({name:z$1.string(),dry_run:z$1.boolean().optional()}),handler:s((e,t)=>tc.delete(e,t),"handler")}];async function aV(e){if(e.filename!==void 0&&e.filename!=="agentsmesh.yaml")throw new v("PATH_TRAVERSAL","only agentsmesh.yaml is writable");if(Buffer.byteLength(e.content,"utf8")>1048576)throw new v("LIMIT_EXCEEDED","config exceeds 1 MiB cap");let t=resolve(e.projectRoot,"agentsmesh.yaml"),r=`${t}.tmp.${process.pid}.${Date.now()}`;return await writeFile(r,e.content,"utf8"),await rename(r,t),t}s(aV,"safeConfigWrite");function Yse(e){if(!e||typeof e!="object")return [e];let t=e,r=t.hooks;return Array.isArray(r)?r.map(n=>{let o=n&&typeof n=="object"?n:{};return {matcher:t.matcher,...o.type!==void 0&&{type:o.type},...o.command!==void 0&&{command:o.command},...o.prompt!==void 0&&{prompt:o.prompt},...o.timeout!==void 0&&{timeout:o.timeout}}}):[t]}s(Yse,"flattenEntry");function lV(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Array.isArray(n)?n.flatMap(Yse):n;return t}s(lV,"normalizeHooksRecord");rs();wp();async function xd(e){try{return parse(await readFile(e,"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw new v("IO_ERROR","failed to read yaml")}}s(xd,"readYaml");async function cp(e,t){if(Buffer.byteLength(t,"utf8")>1048576)throw new v("LIMIT_EXCEEDED","file exceeds 1 MiB cap");let r=`${e}.tmp.${process.pid}.${Date.now()}`;await writeFile(r,t,"utf8"),await rename(r,e);}s(cp,"atomicWrite");var Er={async getConfig(e){let t=await xd(resolve(e.projectRoot,"agentsmesh.yaml"));if(t===null)throw new v("NO_PROJECT","agentsmesh.yaml missing");return t},async listMcpServers(e){let t=resolve(e.projectRoot,".agentsmesh/mcp.json");try{return {servers:(await pn(t))?.mcpServers??null}}catch{return {servers:null}}},async getPermissions(e){return await xd(resolve(e.projectRoot,".agentsmesh/permissions.yaml"))??null},async getHooks(e){return await xd(resolve(e.projectRoot,".agentsmesh/hooks.yaml"))??null},async getIgnore(e){try{return {patterns:(await readFile(resolve(e.projectRoot,".agentsmesh/ignore"),"utf8")).split(/\r?\n/).filter(r=>r!==""&&!r.startsWith("#"))}}catch{return {patterns:null}}},async updateConfig(e,t){let r=await xd(resolve(e.projectRoot,"agentsmesh.yaml"))??{},n={...r},o=s((c,m)=>{m!==void 0&&(n[c]=t.merge===true&&Array.isArray(r[c])?Array.from(new Set([...r[c],...m])):m);},"apply");o("targets",t.targets),o("features",t.features),t.conversions!==void 0&&(n.conversions=t.merge===true&&r.conversions!==void 0?{...r.conversions,...t.conversions}:t.conversions);let i=Da.safeParse(n);if(!i.success)throw new v("VALIDATION_FAILED","invalid config",i.error.issues);let a=stringify(n);return t.dry_run===true?{path:resolve(e.projectRoot,"agentsmesh.yaml"),written:false}:{path:await aV({projectRoot:e.projectRoot,content:a,filename:t.filename}),written:true}},async addMcpServer(e,t){let r=resolve(e.projectRoot,".agentsmesh/mcp.json"),n=await pn(r).catch(()=>null)??{mcpServers:{}};if(n.mcpServers[t.name]!==void 0)throw new v("ALREADY_EXISTS",`server "${t.name}" exists`);return n.mcpServers[t.name]=t.server,t.dry_run===true?{path:r,written:false}:(await cp(r,JSON.stringify(n,null,2)+`
692
692
  `),{path:r,written:true})},async updateMcpServer(e,t){let r=resolve(e.projectRoot,".agentsmesh/mcp.json"),n=await pn(r).catch(()=>null);if(n===null||n.mcpServers[t.name]===void 0)throw new v("NOT_FOUND",`server "${t.name}" not found`);return n.mcpServers[t.name]=t.merge===true?{...n.mcpServers[t.name],...t.server}:t.server,t.dry_run===true?{path:r,written:false}:(await cp(r,JSON.stringify(n,null,2)+`
693
693
  `),{path:r,written:true})},async removeMcpServer(e,t){let r=resolve(e.projectRoot,".agentsmesh/mcp.json"),n=await pn(r).catch(()=>null);if(n===null||n.mcpServers[t.name]===void 0)throw new v("NOT_FOUND",`server "${t.name}" not found`);return delete n.mcpServers[t.name],t.dry_run===true?{path:r,removed:false}:(await cp(r,JSON.stringify(n,null,2)+`
694
694
  `),{path:r,removed:true})},async updatePermissions(e,t){let r=resolve(e.projectRoot,".agentsmesh/permissions.yaml"),n=await xd(r)??{allow:[],deny:[],ask:[]},o={...n},i=s((a,l)=>{l!==void 0&&(o[a]=t.mode==="append"?Array.from(new Set([...n[a]??[],...l])):l);},"apply");return i("allow",t.allow),i("deny",t.deny),i("ask",t.ask),t.dry_run===true?{path:r,written:false}:(await cp(r,stringify(o)),{path:r,written:true})},async updateHooks(e,t){let r=resolve(e.projectRoot,".agentsmesh/hooks.yaml");return t.dry_run===true?{path:r,written:false}:(await cp(r,stringify(lV(t.hooks))),{path:r,written:true})},async updateIgnore(e,t){let r=resolve(e.projectRoot,".agentsmesh/ignore"),n;if(t.mode==="append"){let o=(await readFile(r,"utf8").catch(()=>"")).split(/\r?\n/).filter(Boolean);n=Array.from(new Set([...o,...t.patterns]));}else n=t.patterns;return t.dry_run===true?{path:r,written:false}:(await cp(r,n.join(`
695
695
  `)+`
696
- `),{path:r,written:true})}};var iie=/[;&|`$<>!\\\r\n]/u,aie=/^[A-Za-z_][A-Za-z0-9_]*$/u,lie=/^[A-Za-z][A-Za-z0-9_-]*$/u,cie=/^[A-Za-z][A-Za-z0-9_-]*(\([^)]*\))?$/u,pV=/[\r\n]/u,uV=/[\0\r\n]/u;function mie(e){return uV.test(e)?false:!e.split(/[/\\]/u).includes("..")}s(mie,"isSafeMcpCwd");function pie(e){return z$1.string().min(1).max(512).refine(t=>!iie.test(t),{message:`${e} must not contain shell metacharacters (;&|\`$<>!\\\\, newlines)`})}s(pie,"noShellMeta");var zC=z$1.object({type:z$1.enum(["stdio","sse","http","streamable-http","streamable_http"]).optional(),description:z$1.string().max(1024).refine(e=>!uV.test(e),{message:"description must not contain NUL or newline characters"}).optional(),command:pie("command").optional(),args:z$1.array(z$1.string().max(2048)).max(100).optional(),env:z$1.record(z$1.string().regex(aie,"env key must be a valid identifier"),z$1.string().max(8192)).optional(),url:z$1.string().url().max(2048).refine(e=>/^https?:\/\//u.test(e),{message:"url must use http(s) protocol"}).optional(),headers:z$1.record(z$1.string().regex(lie,"header name must be a valid identifier"),z$1.string().max(8192)).optional(),cwd:z$1.string().max(2048).refine(mie,{message:'cwd must not contain "..", NUL, or newline characters'}).optional(),disabled:z$1.boolean().optional(),timeout:z$1.number().int().nonnegative().max(36e5).optional()}).strict(),uie=z$1.object({type:z$1.enum(["command","prompt"]).optional(),command:z$1.string().min(1).max(8192).optional(),prompt:z$1.string().min(1).max(8192).optional(),timeout:z$1.number().int().nonnegative().max(36e5).optional()}).strict().refine(e=>(e.command??"").length>0||(e.prompt??"").length>0,{message:"hook entry must define command or prompt"}),dV=z$1.string().max(256).refine(e=>!pV.test(e),{message:"hook matcher must not contain newlines"}),die=z$1.object({matcher:dV,type:z$1.enum(["command","prompt"]).optional(),command:z$1.string().min(1).max(8192).optional(),prompt:z$1.string().min(1).max(8192).optional(),timeout:z$1.number().int().nonnegative().max(36e5).optional()}).strict().refine(e=>(e.command??"").length>0||(e.prompt??"").length>0,{message:"hook entry must define command or prompt"}),fie=z$1.object({matcher:dV,hooks:z$1.array(uie).min(1).max(50)}).strict(),gie=z$1.union([die,fie]),fV=z$1.record(z$1.string().min(1).max(64),z$1.array(gie).max(100)),hie=z$1.string().min(1).max(256).refine(e=>!pV.test(e),{message:"permission pattern must not contain newlines"}).refine(e=>cie.test(e),{message:"permission pattern must match Tool or Tool(matcher) form"}),By=z$1.array(hie).max(500);var Pd=z$1.object({}).strict(),yie=[{name:"get_config",description:"Read agentsmesh.yaml",inputSchema:Pd,handler:s(e=>Er.getConfig(e),"handler"),resourceUri:"agentsmesh://config"},{name:"list_mcp_servers",description:"List MCP servers in canonical mcp.json",inputSchema:Pd,handler:s(e=>Er.listMcpServers(e),"handler"),resourceUri:"agentsmesh://canonical/mcp"},{name:"get_permissions",description:"Read permissions.yaml",inputSchema:Pd,handler:s(e=>Er.getPermissions(e),"handler"),resourceUri:"agentsmesh://canonical/permissions"},{name:"get_hooks",description:"Read hooks.yaml",inputSchema:Pd,handler:s(e=>Er.getHooks(e),"handler"),resourceUri:"agentsmesh://canonical/hooks"},{name:"get_ignore",description:"Read ignore patterns",inputSchema:Pd,handler:s(e=>Er.getIgnore(e),"handler"),resourceUri:"agentsmesh://canonical/ignore"}],_ie=[{name:"update_config",description:"Update agentsmesh.yaml. Default: replace listed fields. Set merge=true to union arrays and shallow-merge objects. Only writes agentsmesh.yaml, never agentsmesh.local.yaml.",inputSchema:z$1.object({targets:z$1.array(z$1.string()).optional().describe('Target tool IDs (e.g. ["claude-code", "cursor"])'),features:z$1.array(z$1.string()).optional().describe('Feature names (e.g. ["rules", "commands", "mcp"])'),conversions:z$1.record(z$1.string(),z$1.unknown()).optional().describe("Conversion overrides"),merge:z$1.boolean().optional().describe("If true, union arrays and shallow-merge objects instead of replacing"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>Er.updateConfig(e,t),"handler")},{name:"add_mcp_server",description:"Add an MCP server entry to .agentsmesh/mcp.json. Fails if name already exists.",inputSchema:z$1.object({name:z$1.string().describe('Server name (e.g. "github", "filesystem")'),server:zC.describe('Server config (e.g. { type: "stdio", command: "npx", args: [...], env: {...} })'),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>Er.addMcpServer(e,t),"handler")},{name:"update_mcp_server",description:"Update an MCP server entry (replace or merge)",inputSchema:z$1.object({name:z$1.string(),server:zC,merge:z$1.boolean().optional(),dry_run:z$1.boolean().optional()}),handler:s((e,t)=>Er.updateMcpServer(e,t),"handler")},{name:"remove_mcp_server",description:"Remove an MCP server entry",inputSchema:z$1.object({name:z$1.string(),dry_run:z$1.boolean().optional()}),handler:s((e,t)=>Er.removeMcpServer(e,t),"handler")},{name:"update_permissions",description:"Update permissions.yaml. mode=replace (default) overwrites listed fields; mode=append unions and dedups.",inputSchema:z$1.object({allow:By.optional().describe('Allowed tool patterns (e.g. ["Bash(npm run:*)"])'),deny:By.optional().describe("Denied tool patterns"),ask:By.optional().describe("Tools requiring confirmation"),mode:z$1.enum(["replace","append"]).optional().describe("replace=overwrite, append=union+dedup (default: replace)"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>Er.updatePermissions(e,t),"handler")},{name:"update_hooks",description:"Replace hooks.yaml content entirely. Read current hooks with get_hooks, modify, then write back.",inputSchema:z$1.object({hooks:fV.describe("Full hooks structure (e.g. { PreToolUse: [...], PostToolUse: [...] })"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>Er.updateHooks(e,t),"handler")},{name:"update_ignore",description:"Update .agentsmesh/ignore patterns. mode=replace (default) overwrites; mode=append adds new patterns.",inputSchema:z$1.object({patterns:z$1.array(z$1.string()).describe('Gitignore-syntax patterns (e.g. ["node_modules/", "dist/", ".env*"])'),mode:z$1.enum(["replace","append"]).optional().describe("replace=overwrite, append=add (default: replace)"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>Er.updateIgnore(e,t),"handler")}],gV=[...yie,..._ie];yL();cn();function Sie(){return Object.fromEntries(Ue.map(e=>[e,Object.fromEntries(Object.entries(FB).map(([t,r])=>[t,r[e]]))]))}s(Sie,"buildTargetIndex");var hV=Sie(),VC={async list(){return hV},async get(e){let t=hV[e.targetId];if(t===void 0)throw new v("NOT_FOUND",`unknown target: ${e.targetId}`);return {targetId:e.targetId,capabilities:t}}};ts();ts();Yd();tt();Jo();sn();rt();cn();async function JC(e,t){let r=ne(e);if(!r)throw new Qn(e,{supported:[...Ue,...df().map(n=>n.id)]});return r.generators.importFrom(t.root,{scope:t.scope??"project"})}s(JC,"importFrom");async function Dd(e,t={}){let r=t.scope??"project",{config:n,context:o}=await _e(e,r);await ze(n,e);let{canonical:i}=await $t(n,o.configDir,{refreshRemoteCache:t.refreshRemoteCache===true},o.canonicalDir);return {config:n,canonical:i,projectRoot:o.rootBase,scope:r,configDir:o.configDir,canonicalDir:o.canonicalDir}}s(Dd,"loadProjectContext");async function YC(e){let t=e.targetFilter?[...e.targetFilter]:void 0;return dy(e.config,e.canonical,e.projectRoot,t,{scope:e.scope})}s(YC,"lint");async function XC(e){let t=await Yo(e);return {...py(t),results:t}}s(XC,"diff");async function QC(e){return fy(e)}s(QC,"check");ts();Jo();Ga();Yd();Te();rt();Ae();function rc(e,t={}){let r=Math.max(1,t.cap??Vh),n=ty(e),o=[],i=new Map;for(let[f,g]of Object.entries(e.lessons)){if(g.status!=="active")continue;if(t.trimOverCap===false||g.triggers.length<=r){i.set(f,g.triggers);continue}let h=[...g.triggers].sort((R,k)=>{let w=n.get(R),D=n.get(k);return w!==D?w-D:R<k?-1:1}),y=new Set(h.slice(r)),_=g.triggers.filter(R=>!y.has(R));i.set(f,_),o.push({id:f,removedTriggers:[...y],keptCount:_.length});}let a=[],l=[];if(t.knownPaths!==void 0){let f=od(e,t.knownPaths);if(f.size>0){for(let[g,h]of i){let y=h.filter(R=>f.has(R));if(y.length===0)continue;let _=h.filter(R=>!f.has(R));_.length>=1?(i.set(g,_),a.push({id:g,removedTriggers:y,keptCount:_.length})):l.push(g);}l.sort();}}let c=new Set;for(let f of i.values())for(let g of f)c.add(g);let m=Object.keys(e.triggers).filter(f=>!c.has(f)).sort(),p=new Set;for(let f of Object.values(e.lessons))for(let g of f.topics)p.add(g);let u=Object.keys(e.topics).filter(f=>!p.has(f)).sort();return {removedTriggerIds:m,removedTopicIds:u,trimmedLessons:o,removedDeadGlobs:a,unreachableLessons:l,cap:r}}s(rc,"planPrune");function Ky(e,t){for(let n of [...t.trimmedLessons,...t.removedDeadGlobs??[]]){let o=e.lessons[n.id];if(o===void 0)continue;let i=new Set(n.removedTriggers);e.lessons[n.id]={...o,triggers:o.triggers.filter(a=>!i.has(a))};}for(let n of t.removedTopicIds)delete e.topics[n];let r=new Set(t.removedTriggerIds);if(r.size!==0){for(let[n,o]of Object.entries(e.lessons))o.triggers.some(i=>r.has(i))&&(e.lessons[n]={...o,triggers:o.triggers.filter(i=>!r.has(i))});for(let n of r)delete e.triggers[n];}}s(Ky,"applyPruneToGraph");function Nd(e){return e.removedTriggerIds.length===0&&e.removedTopicIds.length===0&&e.trimmedLessons.length===0&&e.removedDeadGlobs.length===0}s(Nd,"isEmptyPrunePlan");function Eie(e){let t=je(e).config;if(!existsSync(t))return false;try{let r=JSON.parse(readFileSync(t,"utf8"));return typeof r!="object"||r===null?!1:r.autoPrune===!0}catch{return false}}s(Eie,"isAutoPruneEnabled");async function yV(e,t){if(!Eie(e))return null;let r=Je(e);if(r===null||Nd(rc(r,{trimOverCap:false,knownPaths:t})))return null;let n={removedTriggers:0,removedTopics:0,detachedDeadGlobs:0};return await wt(e,i=>{let a=rc(i,{trimOverCap:false,knownPaths:t});Nd(a)||(Ky(i,a),n={removedTriggers:a.removedTriggerIds.length,removedTopics:a.removedTopicIds.length,detachedDeadGlobs:a.removedDeadGlobs.reduce((l,c)=>l+c.removedTriggers.length,0)});}),n.removedTriggers+n.removedTopics+n.detachedDeadGlobs>0?n:null}s(yV,"maybeAutoPrune");function Wy(e,t){let r=e.replaceAll("\\","/"),n=_V(t,r);if(!n.startsWith("../"))return n;let o=_V(qC(t),qC(resolve(t,r)));return o.startsWith("../")?n:o}s(Wy,"normalizeRecallFile");function _V(e,t){let r=relative(e,resolve(e,t)).replaceAll("\\","/");return r===""?t.replaceAll("\\","/"):r}s(_V,"relativize");function qC(e){try{return realpathSync(e)}catch{let t=dirname(e);return t===e?e:resolve(qC(t),basename(e))}}s(qC,"safeRealpath");var Gie="agentsmesh-lessons-seen";function Hy(e={}){if(e.disabled===true)return null;let t=e.explicit!==void 0&&e.explicit.trim().length>0?e.explicit.trim():Wm(e.env);if(t===void 0)return null;let r=$ie(t);return {sessionId:t,seen:jie(r),path:r}}s(Hy,"openSessionDedup");function $ie(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,200);return join(tmpdir(),Gie,`${t}.json`)}s($ie,"seenPath");function jie(e){if(!existsSync(e))return new Set;try{let t=JSON.parse(readFileSync(e,"utf8"));return Array.isArray(t)?new Set(t.filter(r=>typeof r=="string")):new Set}catch{return new Set}}s(jie,"loadSeen");function zy(e,t){return t.filter(r=>!e.seen.has(r.id))}s(zy,"filterUnseen");function Vy(e,t){if(t.length===0)return;let r=new Set(e.seen);for(let n of t)r.add(n);if(r.size!==e.seen.size)try{mkdirSync(dirname(e.path),{recursive:!0});let n=`${e.path}.${process.pid}.tmp`;writeFileSync(n,JSON.stringify([...r]),"utf8"),renameSync(n,e.path);}catch{}}s(Vy,"commitSeen");async function vd(e,t,r={}){try{await gt(e);}catch{}let n=Kh(e);if(n.status==="corrupt")return {lessons:[],totalMatches:0,suppressed:0,corrupt:true};if(n.status==="newer-version")return {lessons:[],totalMatches:0,suppressed:0,newerVersion:n.version};if(n.status==="absent")return {lessons:[],totalMatches:0,suppressed:0};let o=n.graph,i=t.file===void 0?t:{...t,file:Wy(t.file,e)},a=Hm(o,i),l=Hy({explicit:r.sessionId,disabled:r.noDedup}),c=l===null?a:zy(l,a),m=oy(e),p=zm(o,i,c,{limit:r.limit??m.limit,maxTokens:r.maxTokens===null?void 0:r.maxTokens??m.maxTokens});return l!==null&&Vy(l,p.map(u=>u.id)),eE(e,o,i,a,p,{bypassed:false}),{lessons:p,totalMatches:a.length,suppressed:a.length-c.length}}s(vd,"recallLessons");function eE(e,t,r,n,o,i={}){if(!Ra())return;let a=$L(t,r),l=s(m=>n.filter(({lesson:p})=>p.triggers.some(u=>m.has(u))).length,"countVia"),c=Wm();UK(e,{ts:new Date().toISOString(),hasFile:r.file!==void 0,hasCommand:r.command!==void 0,hasKeyword:r.keyword!==void 0,totalMatches:n.length,returnedCount:o.length,returnedTokens:o.reduce((m,p)=>m+Yl(p.lesson.rule),0),truncated:n.length>o.length,matchedByKind:{file:l(a.file_glob),command:l(a.command_pattern),keyword:l(a.keyword)},lessonIds:o.map(m=>m.id),bypassed:i.bypassed===true,...c!==void 0?{session:c}:{}});}s(eE,"recordRecallTelemetry");async function Fd(e,t,r={}){await gt(e);let n={file:t.triggers.files?.length??0,command:t.triggers.commands?.length??0,keyword:t.triggers.keywords?.length??0},o=r.knownPaths??La(e)??void 0;try{let i=await Xh(e,t,{...r,knownPaths:o});GL(e,n,i);let a=await yV(e,o);return a===null?i:{...i,autoPruned:a}}catch(i){throw GL(e,n,null),i}}s(Fd,"captureLesson");async function Jy(e,t,r,n={}){return wt(e,o=>Uie(o,t,r),{retries:n.retries})}s(Jy,"mergeLessons");function Uie(e,t,r){if(t===r)throw new Error(`mergeLessons: cannot merge lesson "${t}" into itself.`);let n=e.lessons[t];if(n===void 0)throw new Error(`mergeLessons: unknown lesson "${t}".`);let o=e.lessons[r];if(o===void 0)throw new Error(`mergeLessons: unknown lesson "${r}".`);if(o.status!=="active")throw new Error(`mergeLessons: keeper "${r}" is not active (status: ${o.status}).`);if(n.status!=="active")throw new Error(`mergeLessons: loser "${t}" is already ${n.status}; nothing to merge.`);return e.lessons[r]={...o,triggers:tE(o.triggers,n.triggers),topics:tE(o.topics,n.topics),evidence:tE(o.evidence,n.evidence)},e.lessons[t]={...n,status:"superseded",supersededBy:r},{loserId:t,keeperId:r}}s(Uie,"mergeInto");function tE(e,t){let r=[...e];for(let n of t)r.includes(n)||r.push(n);return r}s(tE,"union");var rE=String.raw`L\d+(?:\s*,\s*L\d+)*`,Bie=[new RegExp(String.raw`\s*\bSee\s+${rE}\.?`,"g"),new RegExp(String.raw`\s*\((?:${rE})\)\.?`,"g"),new RegExp(String.raw`\s*\[(?:${rE})\]\.?`,"g")],Kie=/\s*\(also relevant[^)]*\)\s*/g;function nE(e){let t=e;for(let r of Bie)t=t.replace(r,"");return t=t.replace(Kie," "),t.trim()}s(nE,"stripLegacyMarkers");function SV(e){let t=[];for(let[r,n]of Object.entries(e.lessons)){let o=nE(n.rule);o===n.rule||o.length===0||(t.push(r),e.lessons[r]={...n,rule:o});}return t.sort()}s(SV,"applyStrip");async function Yy(e,t={}){await gt(e);let r=Je(e);if(r===null)return {changedIds:[],changedCount:0};if(t.dryRun===true){let o=SV(r);return {changedIds:o,changedCount:o.length}}let n=[];return await wt(e,o=>{n=SV(o);}),{changedIds:n,changedCount:n.length}}s(Yy,"stripMarkersInGraph");function Aa(e){if(e instanceof v)throw e;if(e instanceof Qn)throw new v("VALIDATION_FAILED",e.message);let t=e instanceof Error?e.message:String(e);throw /unknown.*--from|unknown.*--to|unknown target/i.test(t)?new v("VALIDATION_FAILED",t):/lock/i.test(t)?new v("LOCK_HELD","generate lock is held"):new v("IO_ERROR","engine failure",{reason:t})}s(Aa,"wrapEngineError");async function RV(e,t){if(t.dry_run===true)throw new v("VALIDATION_FAILED","dry_run is not supported for import \u2014 the engine writes files directly. Use diff to preview changes instead.");try{let r=await JC(t.from,{root:e.projectRoot,scope:"project"});return {imported:r.length,files:r.map(n=>({fromPath:n.fromPath,toPath:n.toPath,feature:n.feature})),warnings:[],errors:[]}}catch(r){if(r instanceof Qn)throw new v("VALIDATION_FAILED",`unknown target "${t.from}"`);let n=r instanceof Error?r.message:String(r);if(/unknown target|invalid target|not found/i.test(n))throw new v("VALIDATION_FAILED",n);Aa(r);}}s(RV,"importFromTarget");async function IV(e,t){try{let r={from:t.from,to:t.to,"dry-run":t.dry_run===!0},n=await vy(r,e.projectRoot);return {filesAffected:n.data.summary.created+n.data.summary.updated,dryRun:t.dry_run===!0,warnings:[],errors:[]}}catch(r){let n=r instanceof Error?r.message:String(r);if(/unknown.*--from|unknown.*--to|unknown target/i.test(n))throw new v("VALIDATION_FAILED",n);Aa(r);}}s(IV,"convert");async function Wie(e,t){try{let r={"dry-run":t.dry_run===!0};t.targets&&t.targets.length>0&&(r.targets=t.targets.join(","));let{data:n}=await Xo(r,e.projectRoot,{printMatrix:!1}),o=n.files.filter(l=>l.status==="created"||l.status==="updated"),i={};for(let l of o){let c=i[l.target]??{filesWritten:0};i[l.target]={filesWritten:c.filesWritten+1};}let a={filesWritten:o.length,byTarget:i,lockfileUpdated:t.dry_run!==!0,errors:[],warnings:[]};return t.verbose===!0&&(a.files=n.files.map(l=>l.path)),a}catch(r){Aa(r);}}s(Wie,"generate");async function Hie(e,t){try{let r=await Dd(e.projectRoot),n=await YC({config:r.config,canonical:r.canonical,projectRoot:r.projectRoot,scope:r.scope});return {issues:(t.severity?n.diagnostics.filter(i=>i.level===t.severity):n.diagnostics).map(i=>({level:i.level,file:i.file,target:i.target,message:i.message}))}}catch(r){Aa(r);}}s(Hie,"lint");async function zie(e){try{let t=await Dd(e.projectRoot),r=await QC({config:t.config,configDir:t.configDir,canonicalDir:t.canonicalDir});return {drift:!r.inSync,missing:[...r.removed],extra:[...r.added],modified:[...r.modified]}}catch(t){Aa(t);}}s(zie,"check");async function Vie(e,t){try{let r=await Dd(e.projectRoot),n=t.targets&&t.targets.length>0?t.targets:void 0,o=await XC({config:r.config,canonical:r.canonical,projectRoot:r.projectRoot,scope:r.scope,targetFilter:n});return {willCreate:o.summary.new,willModify:o.summary.updated,willDelete:o.summary.deleted}}catch(r){Aa(r);}}s(Vie,"diff");var nc={generate:Wie,lint:Hie,check:zie,diff:Vie,import:RV,convert:IV};var kV=z$1.object({}).strict(),LV=[{name:"list_target_capabilities",description:"List support matrix for all targets",inputSchema:kV,handler:s(()=>VC.list(),"handler"),resourceUri:"agentsmesh://capabilities"},{name:"get_target_capabilities",description:"Get feature support levels for a specific target (e.g. which features are native, mapped, or unsupported)",inputSchema:z$1.object({targetId:z$1.string().describe('Target tool ID (e.g. "claude-code", "cursor")')}),handler:s((e,t)=>VC.get(t),"handler"),resourceUri:"agentsmesh://capabilities/{targetId}"},{name:"generate",description:"Generate target-native config files from canonical .agentsmesh/ content. Propagates rules, commands, agents, skills, MCP, hooks, ignore, and permissions to all configured targets.",inputSchema:z$1.object({targets:z$1.array(z$1.string()).optional().describe("Filter to specific targets (default: all from agentsmesh.yaml)"),features:z$1.array(z$1.string()).optional().describe("Filter to specific features"),verbose:z$1.boolean().optional().describe("Include full file list in response"),dry_run:z$1.boolean().optional().describe("Preview without writing files")}),handler:s((e,t)=>nc.generate(e,t),"handler")},{name:"lint",description:"Lint canonical .agentsmesh/ files for schema errors, missing frontmatter, and other issues",inputSchema:z$1.object({severity:z$1.enum(["error","warning","info"]).optional().describe("Filter results by minimum severity")}),handler:s((e,t)=>nc.lint(e,t),"handler")},{name:"check",description:"Detect drift between canonical and lockfile",inputSchema:kV,handler:s(e=>nc.check(e),"handler")},{name:"diff",description:"Preview what generate would create, modify, or delete without writing",inputSchema:z$1.object({targets:z$1.array(z$1.string()).optional().describe("Filter to specific targets"),features:z$1.array(z$1.string()).optional().describe("Filter to specific features")}),handler:s((e,t)=>nc.diff(e,t),"handler")},{name:"import",description:"Import another tool's native config into canonical .agentsmesh/. Note: dry_run is not supported (the engine writes directly).",inputSchema:z$1.object({from:z$1.string().describe('Source target ID to import from (e.g. "cursor", "claude-code")'),features:z$1.array(z$1.string()).optional().describe("Restrict import to specific features"),dry_run:z$1.boolean().optional().describe("NOT SUPPORTED \u2014 will throw VALIDATION_FAILED. Use diff instead.")}),handler:s((e,t)=>nc.import(e,t),"handler")},{name:"convert",description:"Convert config directly from one tool to another (e.g. Cursor \u2192 Claude Code) without creating canonical .agentsmesh/ files",inputSchema:z$1.object({from:z$1.string().describe('Source target ID (e.g. "cursor")'),to:z$1.string().describe('Destination target ID (e.g. "claude-code")'),dry_run:z$1.boolean().optional().describe("Preview conversion without writing files")}),handler:s((e,t)=>nc.convert(e,t),"handler")}];function oE(e){if(e instanceof v)throw e;let t=e instanceof Error?e.message:String(e),r=sp(t);throw /lock|LockAcquisitionError/i.test(r)?new v("LOCK_HELD",".install.lock is held by another process"):/missing source|usage:|non-interactive|invalid|unknown|not found|escapes the source root/i.test(r)?new v("VALIDATION_FAILED",r):new v("IO_ERROR","install pipeline failure",{reason:r})}s(oE,"wrapInstallError");function Jie(e){let t={force:true};return e.path!==void 0&&(t.path=e.path),e.target!==void 0&&(t.target=e.target),e.as!==void 0&&(t.as=e.as),e.name!==void 0&&(t.name=e.name),e.extends===true&&(t.extends=true),e.all===true&&(t.all=true),e.sync===true&&(t.sync=true),e.dry_run===true&&(t["dry-run"]=true),e.global===true&&(t.global=true),t}s(Jie,"toInstallFlags");function Yie(e){let t={force:true};return e.all===true&&(t.all=true),e.keep_pack===true&&(t["keep-pack"]=true),e.keep_generated===true&&(t["keep-generated"]=true),e.dry_run===true&&(t["dry-run"]=true),e.global===true&&(t.global=true),t}s(Yie,"toUninstallFlags");async function Xie(e,t){if(typeof t.source!="string"||t.source.trim().length===0)throw new v("VALIDATION_FAILED","install: `source` is required");try{let r=await Zl(Jie(t),[t.source],e.projectRoot);if(r.exitCode!==0)throw new v("IO_ERROR",`install exited ${r.exitCode}`);return r.data}catch(r){oE(r);}}s(Xie,"install");async function Qie(e,t){if(t.all!==true&&(!Array.isArray(t.names)||t.names.length===0))throw new v("VALIDATION_FAILED","uninstall: pass `names: [...]` or set `all: true`");try{return (await Ty(Yie(t),t.names??[],e.projectRoot)).data}catch(r){oE(r);}}s(Qie,"uninstall");async function qie(e,t={}){try{let r={};return t.global===!0&&(r.global=!0),(await Py(r,e.projectRoot)).data}catch(r){oE(r);}}s(qie,"installsList");var Xy={install:Xie,uninstall:Qie,installsList:qie};function Zie(e){let t={force:true};return e.dry_run===true&&(t["dry-run"]=true),e.global===true&&(t.global=true),t}s(Zie,"toRefreshFlags");function eae(e){if(e instanceof v)throw e;let t=e instanceof Error?e.message:String(e),r=sp(t);throw /lock|LockAcquisitionError/i.test(r)?new v("LOCK_HELD",".install.lock is held by another process"):/unknown pack|not found|usage:/i.test(r)?new v("VALIDATION_FAILED",r):/resolve|network|fetch/i.test(r)?new v("REFRESH_RESOLVE_FAILED",r):/materialize|apply|manifest-update/i.test(r)?new v("REFRESH_APPLY_FAILED",r):new v("IO_ERROR","refresh pipeline failure",{reason:r})}s(eae,"wrapRefreshError");async function tae(e,t={}){try{let r=await xy(Zie(t),[...t.names??[]],e.projectRoot);if(r.exitCode===2){let n=r.data.failed[0],o=t.names??[],i=n?.error??(o.length>0?`unknown pack(s): ${o.join(", ")}`:"refresh validation failed");throw new v("VALIDATION_FAILED",i)}return r.data}catch(r){eae(r);}}s(tae,"refresh");var CV={refresh:tae};var rae=z$1.object({source:z$1.string().min(1).describe("Pack source \u2014 GitHub/GitLab shorthand (`github:org/repo[@ref]`), git URL, SSH URL, or local path (`local:./relative/dir`)."),path:z$1.string().optional().describe("Subdirectory within the source repo to install from. Combined with `as` for manual single-category installs."),target:z$1.string().optional().describe("Target tool ID hint for native-format auto-discovery (e.g. `claude-code`, `cursor`). Bypasses the multi-signal classifier."),as:z$1.enum(["rules","commands","agents","skills"]).optional().describe("Manual install kind. When set, the source is treated as a flat collection of that category (skips the auto-classifier)."),name:z$1.string().optional().describe("Override the generated install entry name (default: derived from `org-repo` shorthand or the source path)."),extends:z$1.boolean().optional().describe("Record as an `extends:` entry in `agentsmesh.yaml` instead of materializing a pack in `.agentsmesh/packs/`. Always-on-latest semantics; resolved every `generate`."),all:z$1.boolean().optional().describe("Install every sub-pack from a marketplace source (`.claude-plugin/marketplace.json`) or every flat collection in a multi-collection layout."),sync:z$1.boolean().optional().describe("Reinstall missing packs from `.agentsmesh/installs.yaml` instead of from `source`."),dry_run:z$1.boolean().optional().describe("Preview what would be installed without writing."),global:z$1.boolean().optional().describe("Install into the global scope (`~/.agentsmesh/`) instead of the project scope. Regenerates user-level outputs.")}),nae=z$1.object({names:z$1.array(z$1.string().min(1)).default([]).describe("Install names to remove (from `installs.yaml`). Required unless `all: true`. Each name removes the pack directory under `.agentsmesh/packs/`, the matching `installs.yaml` row, and the matching `agentsmesh.yaml` `extends:` row when present."),all:z$1.boolean().optional().describe("Remove every install in the current scope. `names` is ignored when `all: true`."),keep_pack:z$1.boolean().optional().describe("Leave `.agentsmesh/packs/<name>/` on disk; only drop yaml entries. Useful when the user has locally-modified files."),keep_generated:z$1.boolean().optional().describe("Skip the post-uninstall `generate` pass. Target trees keep now-stale files until the next manual `generate`; a warning lists what will be cleaned then."),dry_run:z$1.boolean().optional().describe("Preview the removal plan; no writes. Legacy-manifest migration runs in memory only."),global:z$1.boolean().optional().describe("Uninstall from the global scope (`~/.agentsmesh/`) instead of the project scope.")}),oae=z$1.object({global:z$1.boolean().optional().describe("Read from `~/.agentsmesh/installs.yaml` instead of the project scope.")}),sae=z$1.object({names:z$1.array(z$1.string().min(1)).optional().describe("Pack names to refresh. Omit or pass empty array to refresh every installed pack in the current scope."),dry_run:z$1.boolean().optional().describe("Preview the refresh plan (resolved refs, drift detection) without writing."),global:z$1.boolean().optional().describe("Refresh packs in the global scope (`~/.agentsmesh/`) instead of the project scope.")}),EV=[{name:"install",description:"Install a community pack from a URL or local path. Auto-classifies the source layout (anthropic-skill-pack, canonical-agentsmesh, tool-native, or unknown) and dispatches accordingly; `--target` / `--as` override the classifier. Always runs non-interactively (every prompt accepts its documented `--force` default).",inputSchema:rae,handler:s((e,t)=>Xy.install(e,t),"handler")},{name:"uninstall",description:"Remove one or more installed packs. Drops the pack directory, the `installs.yaml` row, and the matching `agentsmesh.yaml` `extends:` row (when present), then runs `generate` so stale target files are cleaned. Mid-batch failures are isolated; survivors still apply and the response surfaces failures in `data.failed[]`.",inputSchema:nae,handler:s((e,t)=>Xy.uninstall(e,t),"handler")},{name:"installs_list",description:"List installed packs in the current scope. Read-only. Hydrates `installed_at` and `source_type` from each pack manifest where available; both are `null` for legacy packs without `.agentsmesh-install-manifest.json`.",inputSchema:oae,handler:s((e,t)=>Xy.installsList(e,t),"handler"),resourceUri:"agentsmesh://installs"},{name:"refresh",description:"Re-fetch and re-apply installed packs against their originally-recorded source/ref. Branch pins re-resolve to the current tip; tag pins re-resolve in case the tag moved; SHA pins stay put. Per-pack atomic via `materializePack` \u2014 a failure leaves the affected pack at its prior state. Always runs non-interactively (force: true) over MCP.",inputSchema:sae,handler:s((e,t)=>CV.refresh(e,t),"handler")}];async function Qy(e,t,r){return wt(e,n=>{let o=n.lessons[t];if(o===void 0)throw new Error(`Unknown lesson: ${t}`);if(r!==null&&n.lessons[r]===void 0)throw new Error(`Unknown superseder: ${r}`);let i=r===null?"deprecated":"superseded";return n.lessons[t]={...o,status:i,...r===null?{}:{supersededBy:r}},{id:t,status:i,supersededBy:r}})}s(Qy,"deprecateLesson");async function OV(e,t){await gt(e.projectRoot);let r=Je(e.projectRoot),n=r?.topics[t.topic];if(r===null||n===void 0)throw new v("NOT_FOUND",`lessons_show: unknown topic "${t.topic}".`);let o=Object.entries(r.lessons).filter(([,i])=>i.topics.includes(t.topic)).sort(([i],[a])=>i<a?-1:1).map(([i,a])=>({id:i,rule:a.rule,status:a.status,topics:[...a.topics],triggers:[...a.triggers],evidence:[...a.evidence]}));return {topic:t.topic,summary:n.summary,lessons:o}}s(OV,"lessonsShow");async function wV(e,t){try{return await Qy(e.projectRoot,t.id,t.superseded_by??null)}catch(r){let n=r instanceof Error?r.message:String(r);throw /^Unknown lesson:|^Unknown superseder:/.test(n)?new v("NOT_FOUND",`lessons_deprecate: ${n}`):r}}s(wV,"lessonsDeprecate");function sE(e){return e===void 0?[]:typeof e=="string"?e.length>0?[e]:[]:e.filter(t=>t.length>0)}s(sE,"toTriggerList");function iae(e){return e===void 0?[]:typeof e=="string"?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):e.filter(t=>t.length>0)}s(iae,"toEvidenceList");var mp={async query(e,t){let r={file:t.file,command:t.command??t.cmd,keyword:t.keyword};if(r.file===void 0&&r.command===void 0&&r.keyword===void 0)throw new v("VALIDATION_FAILED","lessons_query: provide at least one of file, command, or keyword to recall against.");r.file===void 0&&r.command===void 0&&process.stderr.write(`agentsmesh: keyword-only recall misses file_glob/command_pattern lessons \u2014 pass file and/or command for complete recall.
696
+ `),{path:r,written:true})}};var lie=/[;&|`$<>!\\\r\n]/u,cie=/^[A-Za-z_][A-Za-z0-9_]*$/u,mie=/^[A-Za-z][A-Za-z0-9_-]*$/u,pie=/^[A-Za-z][A-Za-z0-9_-]*(\([^)]*\))?$/u,pV=/[\r\n]/u,uV=/[\0\r\n]/u;function uie(e){return uV.test(e)?false:!e.split(/[/\\]/u).includes("..")}s(uie,"isSafeMcpCwd");function die(e){return z$1.string().min(1).max(512).refine(t=>!lie.test(t),{message:`${e} must not contain shell metacharacters (;&|\`$<>!\\\\, newlines)`})}s(die,"noShellMeta");var zC=z$1.object({type:z$1.enum(["stdio","sse","http","streamable-http","streamable_http"]).optional(),description:z$1.string().max(1024).refine(e=>!uV.test(e),{message:"description must not contain NUL or newline characters"}).optional(),command:die("command").optional(),args:z$1.array(z$1.string().max(2048)).max(100).optional(),env:z$1.record(z$1.string().regex(cie,"env key must be a valid identifier"),z$1.string().max(8192)).optional(),url:z$1.string().url().max(2048).refine(e=>/^https?:\/\//u.test(e),{message:"url must use http(s) protocol"}).optional(),headers:z$1.record(z$1.string().regex(mie,"header name must be a valid identifier"),z$1.string().max(8192)).optional(),cwd:z$1.string().max(2048).refine(uie,{message:'cwd must not contain "..", NUL, or newline characters'}).optional(),disabled:z$1.boolean().optional(),timeout:z$1.number().int().nonnegative().max(36e5).optional()}).strict(),fie=z$1.object({type:z$1.enum(["command","prompt"]).optional(),command:z$1.string().min(1).max(8192).optional(),prompt:z$1.string().min(1).max(8192).optional(),timeout:z$1.number().int().nonnegative().max(36e5).optional()}).strict().refine(e=>(e.command??"").length>0||(e.prompt??"").length>0,{message:"hook entry must define command or prompt"}),dV=z$1.string().max(256).refine(e=>!pV.test(e),{message:"hook matcher must not contain newlines"}),gie=z$1.object({matcher:dV,type:z$1.enum(["command","prompt"]).optional(),command:z$1.string().min(1).max(8192).optional(),prompt:z$1.string().min(1).max(8192).optional(),timeout:z$1.number().int().nonnegative().max(36e5).optional()}).strict().refine(e=>(e.command??"").length>0||(e.prompt??"").length>0,{message:"hook entry must define command or prompt"}),hie=z$1.object({matcher:dV,hooks:z$1.array(fie).min(1).max(50)}).strict(),yie=z$1.union([gie,hie]),fV=z$1.record(z$1.string().min(1).max(64),z$1.array(yie).max(100)),_ie=z$1.string().min(1).max(256).refine(e=>!pV.test(e),{message:"permission pattern must not contain newlines"}).refine(e=>pie.test(e),{message:"permission pattern must match Tool or Tool(matcher) form"}),By=z$1.array(_ie).max(500);var Pd=z$1.object({}).strict(),Sie=[{name:"get_config",description:"Read agentsmesh.yaml",inputSchema:Pd,handler:s(e=>Er.getConfig(e),"handler"),resourceUri:"agentsmesh://config"},{name:"list_mcp_servers",description:"List MCP servers in canonical mcp.json",inputSchema:Pd,handler:s(e=>Er.listMcpServers(e),"handler"),resourceUri:"agentsmesh://canonical/mcp"},{name:"get_permissions",description:"Read permissions.yaml",inputSchema:Pd,handler:s(e=>Er.getPermissions(e),"handler"),resourceUri:"agentsmesh://canonical/permissions"},{name:"get_hooks",description:"Read hooks.yaml",inputSchema:Pd,handler:s(e=>Er.getHooks(e),"handler"),resourceUri:"agentsmesh://canonical/hooks"},{name:"get_ignore",description:"Read ignore patterns",inputSchema:Pd,handler:s(e=>Er.getIgnore(e),"handler"),resourceUri:"agentsmesh://canonical/ignore"}],Rie=[{name:"update_config",description:"Update agentsmesh.yaml. Default: replace listed fields. Set merge=true to union arrays and shallow-merge objects. Only writes agentsmesh.yaml, never agentsmesh.local.yaml.",inputSchema:z$1.object({targets:z$1.array(z$1.string()).optional().describe('Target tool IDs (e.g. ["claude-code", "cursor"])'),features:z$1.array(z$1.string()).optional().describe('Feature names (e.g. ["rules", "commands", "mcp"])'),conversions:z$1.record(z$1.string(),z$1.unknown()).optional().describe("Conversion overrides"),merge:z$1.boolean().optional().describe("If true, union arrays and shallow-merge objects instead of replacing"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>Er.updateConfig(e,t),"handler")},{name:"add_mcp_server",description:"Add an MCP server entry to .agentsmesh/mcp.json. Fails if name already exists.",inputSchema:z$1.object({name:z$1.string().describe('Server name (e.g. "github", "filesystem")'),server:zC.describe('Server config (e.g. { type: "stdio", command: "npx", args: [...], env: {...} })'),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>Er.addMcpServer(e,t),"handler")},{name:"update_mcp_server",description:"Update an MCP server entry (replace or merge)",inputSchema:z$1.object({name:z$1.string(),server:zC,merge:z$1.boolean().optional(),dry_run:z$1.boolean().optional()}),handler:s((e,t)=>Er.updateMcpServer(e,t),"handler")},{name:"remove_mcp_server",description:"Remove an MCP server entry",inputSchema:z$1.object({name:z$1.string(),dry_run:z$1.boolean().optional()}),handler:s((e,t)=>Er.removeMcpServer(e,t),"handler")},{name:"update_permissions",description:"Update permissions.yaml. mode=replace (default) overwrites listed fields; mode=append unions and dedups.",inputSchema:z$1.object({allow:By.optional().describe('Allowed tool patterns (e.g. ["Bash(npm run:*)"])'),deny:By.optional().describe("Denied tool patterns"),ask:By.optional().describe("Tools requiring confirmation"),mode:z$1.enum(["replace","append"]).optional().describe("replace=overwrite, append=union+dedup (default: replace)"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>Er.updatePermissions(e,t),"handler")},{name:"update_hooks",description:"Replace hooks.yaml content entirely. Read current hooks with get_hooks, modify, then write back.",inputSchema:z$1.object({hooks:fV.describe("Full hooks structure (e.g. { PreToolUse: [...], PostToolUse: [...] })"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>Er.updateHooks(e,t),"handler")},{name:"update_ignore",description:"Update .agentsmesh/ignore patterns. mode=replace (default) overwrites; mode=append adds new patterns.",inputSchema:z$1.object({patterns:z$1.array(z$1.string()).describe('Gitignore-syntax patterns (e.g. ["node_modules/", "dist/", ".env*"])'),mode:z$1.enum(["replace","append"]).optional().describe("replace=overwrite, append=add (default: replace)"),dry_run:z$1.boolean().optional().describe("Preview without writing")}),handler:s((e,t)=>Er.updateIgnore(e,t),"handler")}],gV=[...Sie,...Rie];yL();cn();function Iie(){return Object.fromEntries(Ue.map(e=>[e,Object.fromEntries(Object.entries(FB).map(([t,r])=>[t,r[e]]))]))}s(Iie,"buildTargetIndex");var hV=Iie(),VC={async list(){return hV},async get(e){let t=hV[e.targetId];if(t===void 0)throw new v("NOT_FOUND",`unknown target: ${e.targetId}`);return {targetId:e.targetId,capabilities:t}}};ts();ts();Yd();tt();Jo();sn();rt();cn();async function JC(e,t){let r=ne(e);if(!r)throw new Qn(e,{supported:[...Ue,...df().map(n=>n.id)]});return r.generators.importFrom(t.root,{scope:t.scope??"project"})}s(JC,"importFrom");async function Dd(e,t={}){let r=t.scope??"project",{config:n,context:o}=await _e(e,r);await ze(n,e);let{canonical:i}=await $t(n,o.configDir,{refreshRemoteCache:t.refreshRemoteCache===true},o.canonicalDir);return {config:n,canonical:i,projectRoot:o.rootBase,scope:r,configDir:o.configDir,canonicalDir:o.canonicalDir}}s(Dd,"loadProjectContext");async function YC(e){let t=e.targetFilter?[...e.targetFilter]:void 0;return dy(e.config,e.canonical,e.projectRoot,t,{scope:e.scope})}s(YC,"lint");async function XC(e){let t=await Yo(e);return {...py(t),results:t}}s(XC,"diff");async function QC(e){return fy(e)}s(QC,"check");ts();Jo();Ga();Yd();Te();rt();Ae();function rc(e,t={}){let r=Math.max(1,t.cap??Vh),n=ty(e),o=[],i=new Map;for(let[f,g]of Object.entries(e.lessons)){if(g.status!=="active")continue;if(t.trimOverCap===false||g.triggers.length<=r){i.set(f,g.triggers);continue}let h=[...g.triggers].sort((R,k)=>{let w=n.get(R),D=n.get(k);return w!==D?w-D:R<k?-1:1}),y=new Set(h.slice(r)),_=g.triggers.filter(R=>!y.has(R));i.set(f,_),o.push({id:f,removedTriggers:[...y],keptCount:_.length});}let a=[],l=[];if(t.knownPaths!==void 0){let f=od(e,t.knownPaths);if(f.size>0){for(let[g,h]of i){let y=h.filter(R=>f.has(R));if(y.length===0)continue;let _=h.filter(R=>!f.has(R));_.length>=1?(i.set(g,_),a.push({id:g,removedTriggers:y,keptCount:_.length})):l.push(g);}l.sort();}}let c=new Set;for(let f of i.values())for(let g of f)c.add(g);let m=Object.keys(e.triggers).filter(f=>!c.has(f)).sort(),p=new Set;for(let f of Object.values(e.lessons))for(let g of f.topics)p.add(g);let u=Object.keys(e.topics).filter(f=>!p.has(f)).sort();return {removedTriggerIds:m,removedTopicIds:u,trimmedLessons:o,removedDeadGlobs:a,unreachableLessons:l,cap:r}}s(rc,"planPrune");function Ky(e,t){for(let n of [...t.trimmedLessons,...t.removedDeadGlobs??[]]){let o=e.lessons[n.id];if(o===void 0)continue;let i=new Set(n.removedTriggers);e.lessons[n.id]={...o,triggers:o.triggers.filter(a=>!i.has(a))};}for(let n of t.removedTopicIds)delete e.topics[n];let r=new Set(t.removedTriggerIds);if(r.size!==0){for(let[n,o]of Object.entries(e.lessons))o.triggers.some(i=>r.has(i))&&(e.lessons[n]={...o,triggers:o.triggers.filter(i=>!r.has(i))});for(let n of r)delete e.triggers[n];}}s(Ky,"applyPruneToGraph");function Nd(e){return e.removedTriggerIds.length===0&&e.removedTopicIds.length===0&&e.trimmedLessons.length===0&&e.removedDeadGlobs.length===0}s(Nd,"isEmptyPrunePlan");function wie(e){let t=je(e).config;if(!existsSync(t))return false;try{let r=JSON.parse(readFileSync(t,"utf8"));return typeof r!="object"||r===null?!1:r.autoPrune===!0}catch{return false}}s(wie,"isAutoPruneEnabled");async function yV(e,t){if(!wie(e))return null;let r=Je(e);if(r===null||Nd(rc(r,{trimOverCap:false,knownPaths:t})))return null;let n={removedTriggers:0,removedTopics:0,detachedDeadGlobs:0};return await wt(e,i=>{let a=rc(i,{trimOverCap:false,knownPaths:t});Nd(a)||(Ky(i,a),n={removedTriggers:a.removedTriggerIds.length,removedTopics:a.removedTopicIds.length,detachedDeadGlobs:a.removedDeadGlobs.reduce((l,c)=>l+c.removedTriggers.length,0)});}),n.removedTriggers+n.removedTopics+n.detachedDeadGlobs>0?n:null}s(yV,"maybeAutoPrune");function Wy(e,t){let r=e.replaceAll("\\","/"),n=_V(t,r);if(!n.startsWith("../"))return n;let o=_V(qC(t),qC(resolve(t,r)));return o.startsWith("../")?n:o}s(Wy,"normalizeRecallFile");function _V(e,t){let r=relative(e,resolve(e,t)).replaceAll("\\","/");return r===""?t.replaceAll("\\","/"):r}s(_V,"relativize");function qC(e){try{return realpathSync(e)}catch{let t=dirname(e);return t===e?e:resolve(qC(t),basename(e))}}s(qC,"safeRealpath");var jie="agentsmesh-lessons-seen";function Hy(e={}){if(e.disabled===true)return null;let t=e.explicit!==void 0&&e.explicit.trim().length>0?e.explicit.trim():Wm(e.env);if(t===void 0)return null;let r=Uie(t);return {sessionId:t,seen:Bie(r),path:r}}s(Hy,"openSessionDedup");function Uie(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,200);return join(tmpdir(),jie,`${t}.json`)}s(Uie,"seenPath");function Bie(e){if(!existsSync(e))return new Set;try{let t=JSON.parse(readFileSync(e,"utf8"));return Array.isArray(t)?new Set(t.filter(r=>typeof r=="string")):new Set}catch{return new Set}}s(Bie,"loadSeen");function zy(e,t){return t.filter(r=>!e.seen.has(r.id))}s(zy,"filterUnseen");function Vy(e,t){if(t.length===0)return;let r=new Set(e.seen);for(let n of t)r.add(n);if(r.size!==e.seen.size)try{mkdirSync(dirname(e.path),{recursive:!0});let n=`${e.path}.${process.pid}.tmp`;writeFileSync(n,JSON.stringify([...r]),"utf8"),renameSync(n,e.path);}catch{}}s(Vy,"commitSeen");async function vd(e,t,r={}){try{await gt(e);}catch{}let n=Kh(e);if(n.status==="corrupt")return {lessons:[],totalMatches:0,suppressed:0,corrupt:true};if(n.status==="newer-version")return {lessons:[],totalMatches:0,suppressed:0,newerVersion:n.version};if(n.status==="absent")return {lessons:[],totalMatches:0,suppressed:0};let o=n.graph,i=t.file===void 0?t:{...t,file:Wy(t.file,e)},a=Hm(o,i),l=Hy({explicit:r.sessionId,disabled:r.noDedup}),c=l===null?a:zy(l,a),m=oy(e),p=zm(o,i,c,{limit:r.limit??m.limit,maxTokens:r.maxTokens===null?void 0:r.maxTokens??m.maxTokens});return l!==null&&Vy(l,p.map(u=>u.id)),eE(e,o,i,a,p,{bypassed:false}),{lessons:p,totalMatches:a.length,suppressed:a.length-c.length}}s(vd,"recallLessons");function eE(e,t,r,n,o,i={}){if(!Ra())return;let a=$L(t,r),l=s(m=>n.filter(({lesson:p})=>p.triggers.some(u=>m.has(u))).length,"countVia"),c=Wm();UK(e,{ts:new Date().toISOString(),hasFile:r.file!==void 0,hasCommand:r.command!==void 0,hasKeyword:r.keyword!==void 0,totalMatches:n.length,returnedCount:o.length,returnedTokens:o.reduce((m,p)=>m+Yl(p.lesson.rule),0),truncated:n.length>o.length,matchedByKind:{file:l(a.file_glob),command:l(a.command_pattern),keyword:l(a.keyword)},lessonIds:o.map(m=>m.id),bypassed:i.bypassed===true,...c!==void 0?{session:c}:{}});}s(eE,"recordRecallTelemetry");async function Fd(e,t,r={}){await gt(e);let n={file:t.triggers.files?.length??0,command:t.triggers.commands?.length??0,keyword:t.triggers.keywords?.length??0},o=r.knownPaths??La(e)??void 0;try{let i=await Xh(e,t,{...r,knownPaths:o});GL(e,n,i);let a=await yV(e,o);return a===null?i:{...i,autoPruned:a}}catch(i){throw GL(e,n,null),i}}s(Fd,"captureLesson");async function Jy(e,t,r,n={}){return wt(e,o=>Kie(o,t,r),{retries:n.retries})}s(Jy,"mergeLessons");function Kie(e,t,r){if(t===r)throw new Error(`mergeLessons: cannot merge lesson "${t}" into itself.`);let n=e.lessons[t];if(n===void 0)throw new Error(`mergeLessons: unknown lesson "${t}".`);let o=e.lessons[r];if(o===void 0)throw new Error(`mergeLessons: unknown lesson "${r}".`);if(o.status!=="active")throw new Error(`mergeLessons: keeper "${r}" is not active (status: ${o.status}).`);if(n.status!=="active")throw new Error(`mergeLessons: loser "${t}" is already ${n.status}; nothing to merge.`);return e.lessons[r]={...o,triggers:tE(o.triggers,n.triggers),topics:tE(o.topics,n.topics),evidence:tE(o.evidence,n.evidence)},e.lessons[t]={...n,status:"superseded",supersededBy:r},{loserId:t,keeperId:r}}s(Kie,"mergeInto");function tE(e,t){let r=[...e];for(let n of t)r.includes(n)||r.push(n);return r}s(tE,"union");var rE=String.raw`L\d+(?:\s*,\s*L\d+)*`,Wie=[new RegExp(String.raw`\s*\bSee\s+${rE}\.?`,"g"),new RegExp(String.raw`\s*\((?:${rE})\)\.?`,"g"),new RegExp(String.raw`\s*\[(?:${rE})\]\.?`,"g")],Hie=/\s*\(also relevant[^)]*\)\s*/g;function nE(e){let t=e;for(let r of Wie)t=t.replace(r,"");return t=t.replace(Hie," "),t.trim()}s(nE,"stripLegacyMarkers");function SV(e){let t=[];for(let[r,n]of Object.entries(e.lessons)){let o=nE(n.rule);o===n.rule||o.length===0||(t.push(r),e.lessons[r]={...n,rule:o});}return t.sort()}s(SV,"applyStrip");async function Yy(e,t={}){await gt(e);let r=Je(e);if(r===null)return {changedIds:[],changedCount:0};if(t.dryRun===true){let o=SV(r);return {changedIds:o,changedCount:o.length}}let n=[];return await wt(e,o=>{n=SV(o);}),{changedIds:n,changedCount:n.length}}s(Yy,"stripMarkersInGraph");function Aa(e){if(e instanceof v)throw e;if(e instanceof Qn)throw new v("VALIDATION_FAILED",e.message);let t=e instanceof Error?e.message:String(e);throw /unknown.*--from|unknown.*--to|unknown target/i.test(t)?new v("VALIDATION_FAILED",t):/lock/i.test(t)?new v("LOCK_HELD","generate lock is held"):new v("IO_ERROR","engine failure",{reason:t})}s(Aa,"wrapEngineError");async function RV(e,t){if(t.dry_run===true)throw new v("VALIDATION_FAILED","dry_run is not supported for import \u2014 the engine writes files directly. Use diff to preview changes instead.");try{let r=await JC(t.from,{root:e.projectRoot,scope:"project"});return {imported:r.length,files:r.map(n=>({fromPath:n.fromPath,toPath:n.toPath,feature:n.feature})),warnings:[],errors:[]}}catch(r){if(r instanceof Qn)throw new v("VALIDATION_FAILED",`unknown target "${t.from}"`);let n=r instanceof Error?r.message:String(r);if(/unknown target|invalid target|not found/i.test(n))throw new v("VALIDATION_FAILED",n);Aa(r);}}s(RV,"importFromTarget");async function IV(e,t){try{let r={from:t.from,to:t.to,"dry-run":t.dry_run===!0},n=await vy(r,e.projectRoot);return {filesAffected:n.data.summary.created+n.data.summary.updated,dryRun:t.dry_run===!0,warnings:[],errors:[]}}catch(r){let n=r instanceof Error?r.message:String(r);if(/unknown.*--from|unknown.*--to|unknown target/i.test(n))throw new v("VALIDATION_FAILED",n);Aa(r);}}s(IV,"convert");async function zie(e,t){try{let r={"dry-run":t.dry_run===!0};t.targets&&t.targets.length>0&&(r.targets=t.targets.join(","));let{data:n}=await Xo(r,e.projectRoot,{printMatrix:!1}),o=n.files.filter(l=>l.status==="created"||l.status==="updated"),i={};for(let l of o){let c=i[l.target]??{filesWritten:0};i[l.target]={filesWritten:c.filesWritten+1};}let a={filesWritten:o.length,byTarget:i,lockfileUpdated:t.dry_run!==!0,errors:[],warnings:[]};return t.verbose===!0&&(a.files=n.files.map(l=>l.path)),a}catch(r){Aa(r);}}s(zie,"generate");async function Vie(e,t){try{let r=await Dd(e.projectRoot),n=await YC({config:r.config,canonical:r.canonical,projectRoot:r.projectRoot,scope:r.scope});return {issues:(t.severity?n.diagnostics.filter(i=>i.level===t.severity):n.diagnostics).map(i=>({level:i.level,file:i.file,target:i.target,message:i.message}))}}catch(r){Aa(r);}}s(Vie,"lint");async function Jie(e){try{let t=await Dd(e.projectRoot),r=await QC({config:t.config,configDir:t.configDir,canonicalDir:t.canonicalDir});return {drift:!r.inSync,missing:[...r.removed],extra:[...r.added],modified:[...r.modified]}}catch(t){Aa(t);}}s(Jie,"check");async function Yie(e,t){try{let r=await Dd(e.projectRoot),n=t.targets&&t.targets.length>0?t.targets:void 0,o=await XC({config:r.config,canonical:r.canonical,projectRoot:r.projectRoot,scope:r.scope,targetFilter:n});return {willCreate:o.summary.new,willModify:o.summary.updated,willDelete:o.summary.deleted}}catch(r){Aa(r);}}s(Yie,"diff");var nc={generate:zie,lint:Vie,check:Jie,diff:Yie,import:RV,convert:IV};var kV=z$1.object({}).strict(),LV=[{name:"list_target_capabilities",description:"List support matrix for all targets",inputSchema:kV,handler:s(()=>VC.list(),"handler"),resourceUri:"agentsmesh://capabilities"},{name:"get_target_capabilities",description:"Get feature support levels for a specific target (e.g. which features are native, mapped, or unsupported)",inputSchema:z$1.object({targetId:z$1.string().describe('Target tool ID (e.g. "claude-code", "cursor")')}),handler:s((e,t)=>VC.get(t),"handler"),resourceUri:"agentsmesh://capabilities/{targetId}"},{name:"generate",description:"Generate target-native config files from canonical .agentsmesh/ content. Propagates rules, commands, agents, skills, MCP, hooks, ignore, and permissions to all configured targets.",inputSchema:z$1.object({targets:z$1.array(z$1.string()).optional().describe("Filter to specific targets (default: all from agentsmesh.yaml)"),features:z$1.array(z$1.string()).optional().describe("Filter to specific features"),verbose:z$1.boolean().optional().describe("Include full file list in response"),dry_run:z$1.boolean().optional().describe("Preview without writing files")}),handler:s((e,t)=>nc.generate(e,t),"handler")},{name:"lint",description:"Lint canonical .agentsmesh/ files for schema errors, missing frontmatter, and other issues",inputSchema:z$1.object({severity:z$1.enum(["error","warning","info"]).optional().describe("Filter results by minimum severity")}),handler:s((e,t)=>nc.lint(e,t),"handler")},{name:"check",description:"Detect drift between canonical and lockfile",inputSchema:kV,handler:s(e=>nc.check(e),"handler")},{name:"diff",description:"Preview what generate would create, modify, or delete without writing",inputSchema:z$1.object({targets:z$1.array(z$1.string()).optional().describe("Filter to specific targets"),features:z$1.array(z$1.string()).optional().describe("Filter to specific features")}),handler:s((e,t)=>nc.diff(e,t),"handler")},{name:"import",description:"Import another tool's native config into canonical .agentsmesh/. Note: dry_run is not supported (the engine writes directly).",inputSchema:z$1.object({from:z$1.string().describe('Source target ID to import from (e.g. "cursor", "claude-code")'),features:z$1.array(z$1.string()).optional().describe("Restrict import to specific features"),dry_run:z$1.boolean().optional().describe("NOT SUPPORTED \u2014 will throw VALIDATION_FAILED. Use diff instead.")}),handler:s((e,t)=>nc.import(e,t),"handler")},{name:"convert",description:"Convert config directly from one tool to another (e.g. Cursor \u2192 Claude Code) without creating canonical .agentsmesh/ files",inputSchema:z$1.object({from:z$1.string().describe('Source target ID (e.g. "cursor")'),to:z$1.string().describe('Destination target ID (e.g. "claude-code")'),dry_run:z$1.boolean().optional().describe("Preview conversion without writing files")}),handler:s((e,t)=>nc.convert(e,t),"handler")}];function oE(e){if(e instanceof v)throw e;let t=e instanceof Error?e.message:String(e),r=sp(t);throw /lock|LockAcquisitionError/i.test(r)?new v("LOCK_HELD",".install.lock is held by another process"):/missing source|usage:|non-interactive|invalid|unknown|not found|escapes the source root/i.test(r)?new v("VALIDATION_FAILED",r):new v("IO_ERROR","install pipeline failure",{reason:r})}s(oE,"wrapInstallError");function Xie(e){let t={force:true};return e.path!==void 0&&(t.path=e.path),e.target!==void 0&&(t.target=e.target),e.as!==void 0&&(t.as=e.as),e.name!==void 0&&(t.name=e.name),e.extends===true&&(t.extends=true),e.all===true&&(t.all=true),e.sync===true&&(t.sync=true),e.dry_run===true&&(t["dry-run"]=true),e.global===true&&(t.global=true),t}s(Xie,"toInstallFlags");function Qie(e){let t={force:true};return e.all===true&&(t.all=true),e.keep_pack===true&&(t["keep-pack"]=true),e.keep_generated===true&&(t["keep-generated"]=true),e.dry_run===true&&(t["dry-run"]=true),e.global===true&&(t.global=true),t}s(Qie,"toUninstallFlags");async function qie(e,t){if(typeof t.source!="string"||t.source.trim().length===0)throw new v("VALIDATION_FAILED","install: `source` is required");try{let r=await Zl(Xie(t),[t.source],e.projectRoot);if(r.exitCode!==0)throw new v("IO_ERROR",`install exited ${r.exitCode}`);return r.data}catch(r){oE(r);}}s(qie,"install");async function Zie(e,t){if(t.all!==true&&(!Array.isArray(t.names)||t.names.length===0))throw new v("VALIDATION_FAILED","uninstall: pass `names: [...]` or set `all: true`");try{return (await Ty(Qie(t),t.names??[],e.projectRoot)).data}catch(r){oE(r);}}s(Zie,"uninstall");async function eae(e,t={}){try{let r={};return t.global===!0&&(r.global=!0),(await Py(r,e.projectRoot)).data}catch(r){oE(r);}}s(eae,"installsList");var Xy={install:qie,uninstall:Zie,installsList:eae};function tae(e){let t={force:true};return e.dry_run===true&&(t["dry-run"]=true),e.global===true&&(t.global=true),t}s(tae,"toRefreshFlags");function rae(e){if(e instanceof v)throw e;let t=e instanceof Error?e.message:String(e),r=sp(t);throw /lock|LockAcquisitionError/i.test(r)?new v("LOCK_HELD",".install.lock is held by another process"):/unknown pack|not found|usage:/i.test(r)?new v("VALIDATION_FAILED",r):/resolve|network|fetch/i.test(r)?new v("REFRESH_RESOLVE_FAILED",r):/materialize|apply|manifest-update/i.test(r)?new v("REFRESH_APPLY_FAILED",r):new v("IO_ERROR","refresh pipeline failure",{reason:r})}s(rae,"wrapRefreshError");async function nae(e,t={}){try{let r=await xy(tae(t),[...t.names??[]],e.projectRoot);if(r.exitCode===2){let n=r.data.failed[0],o=t.names??[],i=n?.error??(o.length>0?`unknown pack(s): ${o.join(", ")}`:"refresh validation failed");throw new v("VALIDATION_FAILED",i)}return r.data}catch(r){rae(r);}}s(nae,"refresh");var CV={refresh:nae};var oae=z$1.object({source:z$1.string().min(1).describe("Pack source \u2014 GitHub/GitLab shorthand (`github:org/repo[@ref]`), git URL, SSH URL, or local path (`local:./relative/dir`)."),path:z$1.string().optional().describe("Subdirectory within the source repo to install from. Combined with `as` for manual single-category installs."),target:z$1.string().optional().describe("Target tool ID hint for native-format auto-discovery (e.g. `claude-code`, `cursor`). Bypasses the multi-signal classifier."),as:z$1.enum(["rules","commands","agents","skills"]).optional().describe("Manual install kind. When set, the source is treated as a flat collection of that category (skips the auto-classifier)."),name:z$1.string().optional().describe("Override the generated install entry name (default: derived from `org-repo` shorthand or the source path)."),extends:z$1.boolean().optional().describe("Record as an `extends:` entry in `agentsmesh.yaml` instead of materializing a pack in `.agentsmesh/packs/`. Always-on-latest semantics; resolved every `generate`."),all:z$1.boolean().optional().describe("Install every sub-pack from a marketplace source (`.claude-plugin/marketplace.json`) or every flat collection in a multi-collection layout."),sync:z$1.boolean().optional().describe("Reinstall missing packs from `.agentsmesh/installs.yaml` instead of from `source`."),dry_run:z$1.boolean().optional().describe("Preview what would be installed without writing."),global:z$1.boolean().optional().describe("Install into the global scope (`~/.agentsmesh/`) instead of the project scope. Regenerates user-level outputs.")}),sae=z$1.object({names:z$1.array(z$1.string().min(1)).default([]).describe("Install names to remove (from `installs.yaml`). Required unless `all: true`. Each name removes the pack directory under `.agentsmesh/packs/`, the matching `installs.yaml` row, and the matching `agentsmesh.yaml` `extends:` row when present."),all:z$1.boolean().optional().describe("Remove every install in the current scope. `names` is ignored when `all: true`."),keep_pack:z$1.boolean().optional().describe("Leave `.agentsmesh/packs/<name>/` on disk; only drop yaml entries. Useful when the user has locally-modified files."),keep_generated:z$1.boolean().optional().describe("Skip the post-uninstall `generate` pass. Target trees keep now-stale files until the next manual `generate`; a warning lists what will be cleaned then."),dry_run:z$1.boolean().optional().describe("Preview the removal plan; no writes. Legacy-manifest migration runs in memory only."),global:z$1.boolean().optional().describe("Uninstall from the global scope (`~/.agentsmesh/`) instead of the project scope.")}),iae=z$1.object({global:z$1.boolean().optional().describe("Read from `~/.agentsmesh/installs.yaml` instead of the project scope.")}),aae=z$1.object({names:z$1.array(z$1.string().min(1)).optional().describe("Pack names to refresh. Omit or pass empty array to refresh every installed pack in the current scope."),dry_run:z$1.boolean().optional().describe("Preview the refresh plan (resolved refs, drift detection) without writing."),global:z$1.boolean().optional().describe("Refresh packs in the global scope (`~/.agentsmesh/`) instead of the project scope.")}),EV=[{name:"install",description:"Install a community pack from a URL or local path. Auto-classifies the source layout (anthropic-skill-pack, canonical-agentsmesh, tool-native, or unknown) and dispatches accordingly; `--target` / `--as` override the classifier. Always runs non-interactively (every prompt accepts its documented `--force` default).",inputSchema:oae,handler:s((e,t)=>Xy.install(e,t),"handler")},{name:"uninstall",description:"Remove one or more installed packs. Drops the pack directory, the `installs.yaml` row, and the matching `agentsmesh.yaml` `extends:` row (when present), then runs `generate` so stale target files are cleaned. Mid-batch failures are isolated; survivors still apply and the response surfaces failures in `data.failed[]`.",inputSchema:sae,handler:s((e,t)=>Xy.uninstall(e,t),"handler")},{name:"installs_list",description:"List installed packs in the current scope. Read-only. Hydrates `installed_at` and `source_type` from each pack manifest where available; both are `null` for legacy packs without `.agentsmesh-install-manifest.json`.",inputSchema:iae,handler:s((e,t)=>Xy.installsList(e,t),"handler"),resourceUri:"agentsmesh://installs"},{name:"refresh",description:"Re-fetch and re-apply installed packs against their originally-recorded source/ref. Branch pins re-resolve to the current tip; tag pins re-resolve in case the tag moved; SHA pins stay put. Per-pack atomic via `materializePack` \u2014 a failure leaves the affected pack at its prior state. Always runs non-interactively (force: true) over MCP.",inputSchema:aae,handler:s((e,t)=>CV.refresh(e,t),"handler")}];async function Qy(e,t,r){return wt(e,n=>{let o=n.lessons[t];if(o===void 0)throw new Error(`Unknown lesson: ${t}`);if(r!==null&&n.lessons[r]===void 0)throw new Error(`Unknown superseder: ${r}`);let i=r===null?"deprecated":"superseded";return n.lessons[t]={...o,status:i,...r===null?{}:{supersededBy:r}},{id:t,status:i,supersededBy:r}})}s(Qy,"deprecateLesson");async function OV(e,t){await gt(e.projectRoot);let r=Je(e.projectRoot),n=r?.topics[t.topic];if(r===null||n===void 0)throw new v("NOT_FOUND",`lessons_show: unknown topic "${t.topic}".`);let o=Object.entries(r.lessons).filter(([,i])=>i.topics.includes(t.topic)).sort(([i],[a])=>i<a?-1:1).map(([i,a])=>({id:i,rule:a.rule,status:a.status,topics:[...a.topics],triggers:[...a.triggers],evidence:[...a.evidence]}));return {topic:t.topic,summary:n.summary,lessons:o}}s(OV,"lessonsShow");async function wV(e,t){try{return await Qy(e.projectRoot,t.id,t.superseded_by??null)}catch(r){let n=r instanceof Error?r.message:String(r);throw /^Unknown lesson:|^Unknown superseder:/.test(n)?new v("NOT_FOUND",`lessons_deprecate: ${n}`):r}}s(wV,"lessonsDeprecate");function sE(e){return e===void 0?[]:typeof e=="string"?e.length>0?[e]:[]:e.filter(t=>t.length>0)}s(sE,"toTriggerList");function lae(e){return e===void 0?[]:typeof e=="string"?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):e.filter(t=>t.length>0)}s(lae,"toEvidenceList");var mp={async query(e,t){let r={file:t.file,command:t.command??t.cmd,keyword:t.keyword};if(r.file===void 0&&r.command===void 0&&r.keyword===void 0)throw new v("VALIDATION_FAILED","lessons_query: provide at least one of file, command, or keyword to recall against.");r.file===void 0&&r.command===void 0&&process.stderr.write(`agentsmesh: keyword-only recall misses file_glob/command_pattern lessons \u2014 pass file and/or command for complete recall.
697
697
  `);let{lessons:n,totalMatches:o,suppressed:i,corrupt:a,newerVersion:l}=await vd(e.projectRoot,r,{limit:t.limit,maxTokens:t.max_tokens??t["max-tokens"]});a===true?process.stderr.write("agentsmesh: lessons.json is unreadable (corrupt) \u2014 recall returned no lessons. Run `agentsmesh lessons validate`.\n"):l!==void 0&&process.stderr.write(`agentsmesh: lessons.json is version ${l}, newer than this build supports \u2014 recall returned no lessons. Upgrade agentsmesh to read it.
698
- `);let c=t.verbose===true;return {lessons:n.map(({id:m,lesson:p,score:u})=>c?{id:m,rule:p.rule,topics:[...p.topics],triggers:[...p.triggers],evidence:[...p.evidence],score:u}:{id:m,rule:p.rule}),totalMatches:o,...i>0?{suppressed:i}:{}}},async topics(e){await gt(e.projectRoot);let t=Je(e.projectRoot);return t===null?{topics:[]}:{topics:Object.entries(t.topics).map(([r,n])=>({id:r,summary:n.summary})).sort((r,n)=>r.id<n.id?-1:1)}},show:OV,deprecate:wV,async add(e,t){try{return await Fd(e.projectRoot,{rule:t.rule,topic:t.topic,triggers:{files:sE(t.trigger_files??t.trigger_file),commands:sE(t.trigger_commands??t.trigger_cmd),keywords:sE(t.trigger_keywords??t.trigger_kw)},evidence:iae(t.evidence),rationale:t.rationale},{allowNewTopic:t.new_topic===!0,topicSummary:t.topic_summary})}catch(r){throw r instanceof Vn?new v("NOT_FOUND",`lessons_add: unknown topic "${r.topic}". Pass new_topic=true + topic_summary to create it.`,{code:r.code}):r instanceof hi||r instanceof yi||r instanceof gi?new v("VALIDATION_FAILED",`lessons_add: ${r.message}`,{code:r.code}):r}}};var aae=z$1.object({file:z$1.string().optional().describe("Project-relative path of the file about to be edited."),command:z$1.string().optional().describe("Shell command about to be executed (CLI flag: --cmd)."),cmd:z$1.string().optional().describe("Alias of `command` (matches the CLI `--cmd` flag). Use `command` if unsure."),keyword:z$1.string().optional().describe("Free-form description of the active task."),limit:z$1.number().int().positive().optional().describe("Max ranked lessons to return (default 10). Results are relevance-ranked."),max_tokens:z$1.number().int().positive().optional().describe("Cap results by cumulative estimated rule-token cost (CLI flag: --max-tokens)."),"max-tokens":z$1.number().int().positive().optional().describe("Alias of `max_tokens` (matches the CLI `--max-tokens` flag)."),verbose:z$1.boolean().optional().describe("Include topics/triggers/evidence/score. Default false (compact: id + rule only).")}).strict(),oc=z$1.union([z$1.string(),z$1.array(z$1.string())]),lae=z$1.object({rule:z$1.string().min(1).describe("Imperative rule that prevents recurrence."),topic:z$1.string().min(1).describe("Topic id. Use new_topic + topic_summary to create one."),trigger_files:oc.optional().describe('file_glob triggers (e.g. ["src/cli/**/*.ts"] or a single "src/**").'),trigger_file:oc.optional().describe("Alias of `trigger_files` (matches the CLI `--trigger-file` flag)."),trigger_commands:oc.optional().describe("command_pattern triggers \u2014 regexes matched against shell commands."),trigger_cmd:oc.optional().describe("Alias of `trigger_commands` (matches the CLI `--trigger-cmd` flag)."),trigger_keywords:oc.optional().describe("keyword triggers \u2014 case-insensitive substrings of task descriptions."),trigger_kw:oc.optional().describe("Alias of `trigger_keywords` (matches the CLI `--trigger-kw` flag)."),evidence:oc.optional().describe("Evidence references (commit:SHA, lesson:id, \u2026). A scalar may be comma-separated."),rationale:z$1.string().optional().describe('Optional one-line "why" behind the rule.'),new_topic:z$1.boolean().optional().describe("Allow creating a new topic if missing."),topic_summary:z$1.string().optional().describe("Required when new_topic creates a topic. One-line summary.")}).strict(),bV=[{name:"lessons_query",description:"Recall primitive \u2014 return active lessons whose triggers match the supplied (file, command, keyword) predicates, relevance-ranked (trigger specificity + per-query topic coherence + BM25 over rule text) and capped to `limit` (default 10). Pass at least one predicate (a predicate-less call is rejected); always include `file` for an edit and `command` for a shell command \u2014 keyword-only recall misses file/command-scoped lessons. Returns compact `{id, rule}` by default; pass `verbose:true` for topics/triggers/evidence/score. Excludes deprecated and superseded lessons.",inputSchema:aae,handler:s((e,t)=>mp.query(e,t),"handler")},{name:"lessons_add",description:"Capture primitive \u2014 atomically add a new lesson. At least one EFFECTIVE trigger is REQUIRED \u2014 the add is rejected (UNRECALLABLE_LESSON, exit 2) when every trigger is dead on the mandatory file/command recall path (a stopword-only keyword whose needle loses all tokens to stopword filtering, or an invalid/ReDoS command regex). A lesson with a mix of live and dead triggers is NOT rejected. Prefer a precise `trigger_files` glob, the most reliable trigger. Deduplicates triggers against the graph. Idempotent on repeat (same rule + topic \u2192 same id, no duplicate triggers). Returns non-blocking `warnings` (trigger-hygiene nudges: oversized trigger set, broad globs, keyword-only, dead glob matching no file in the working tree [DEAD_GLOB], or rule closely paraphrasing an existing active lesson [NEAR_DUPLICATE_LESSON]) \u2014 heed them by preferring a few specific triggers.",inputSchema:lae,handler:s((e,t)=>mp.add(e,t),"handler")},{name:"lessons_topics",description:"List every topic id and summary \u2014 call before lessons_add to choose a valid --topic instead of guessing (which would create an unintended new topic).",inputSchema:z$1.object({}).strict(),handler:s(e=>mp.topics(e),"handler")},{name:"lessons_show",description:"Inspect a topic \u2014 return its summary and every lesson under it (id, rule, status, triggers, evidence), including deprecated/superseded ones. Use to find the id of a stale lesson before lessons_deprecate.",inputSchema:z$1.object({topic:z$1.string().min(1).describe("Topic id to inspect (see lessons_topics).")}).strict(),handler:s((e,t)=>mp.show(e,t),"handler")},{name:"lessons_deprecate",description:"Curation primitive \u2014 retire a lesson so recall stops returning it. With `superseded_by` the lesson is marked superseded by that replacement; without it the lesson is plainly deprecated. Throws on an unknown lesson or superseder.",inputSchema:z$1.object({id:z$1.string().min(1).describe("Lesson id to retire (see lessons_show)."),superseded_by:z$1.string().min(1).optional().describe("Replacement lesson id; omit for a plain deprecation.")}).strict(),handler:s((e,t)=>mp.deprecate(e,t),"handler")}];function AV(e){let t=toJSONSchema(e,{target:"draft-07"});return delete t.$schema,t}s(AV,"zodToMcpSchema");var qy=[...q1,...iV,...gV,...LV,...EV,...bV],iE=qy.filter(e=>e.resourceUri!==void 0).map(e=>({uri:e.resourceUri,name:e.name,description:e.description,read:s((t,r)=>e.handler(t,r),"read")}));Ga();async function uae(e){let t=resolve(e);for(;;){try{return await stat(resolve(t,"agentsmesh.yaml")),t}catch{}let r=dirname(t);if(r===t)throw new v("NO_PROJECT","agentsmesh.yaml not found");t=r;}}s(uae,"findProjectRoot");async function aE(e){let t=await uae(e.cwd);return {projectRoot:t,loadCanonical:s(()=>Kt(t),"loadCanonical")}}s(aE,"resolveContext");function xV(e,t){let r=dae(e);return t.map(n=>{let o=n.path.map(i=>typeof i=="symbol"?i.toString():i);if(n.code==="unrecognized_keys"&&r.length>0&&n.path.length===0){let i=n.keys?.[0],a=i===void 0?void 0:fae(i,r),l=a===void 0?"":` Did you mean "${a}"?`;return {code:n.code,path:o,message:`${n.message}. Expected one of: ${r.join(", ")}.${l}`,expected:r,...a===void 0?{}:{suggestion:a}}}return {code:n.code,path:o,message:n.message}})}s(xV,"enrichValidationIssues");function dae(e){let t=e.shape;return t!==void 0&&typeof t=="object"?Object.keys(t):[]}s(dae,"objectShapeKeys");function fae(e,t){let r=e.toLowerCase(),n=t.find(c=>c.toLowerCase()===r);if(n!==void 0)return n;let o,i=1/0,a=Math.max(2,Math.ceil(e.length/3));for(let c of t){let m=gae(r,c.toLowerCase());m<i&&(i=m,o=c);}return o!==void 0&&i<=a?o:t.filter(c=>c.toLowerCase().includes(r)||r.includes(c.toLowerCase())).sort((c,m)=>c.length-m.length)[0]}s(fae,"nearestKey");function gae(e,t){let r=Array.from({length:t.length+1},(n,o)=>o);for(let n=1;n<=e.length;n+=1){let o=r[0];r[0]=n;for(let i=1;i<=t.length;i+=1){let a=r[i],l=e[n-1]===t[i-1]?0:1;r[i]=Math.min(r[i]+1,r[i-1]+1,o+l),o=a;}}return r[t.length]}s(gae,"editDistance");async function Eae(){let e=dirname(fileURLToPath(import.meta.url));for(let t of [resolve(e,"../../package.json"),resolve(e,"../package.json"),resolve(e,"../../../package.json")])try{let r=JSON.parse(await readFile(t,"utf8"));if(r.name==="agentsmesh")return r.version}catch{}return "0.0.0"}s(Eae,"pkgVersion");function Oae(e,t){return new RegExp("^"+e.replace(/\{[^}]+\}/g,"([^/]+)")+"$").test(t)}s(Oae,"matchTemplate");function wae(e,t){let r=[...e.matchAll(/\{([^}]+)\}/g)].map(i=>i[1]),o=new RegExp("^"+e.replace(/\{[^}]+\}/g,"([^/]+)")+"$").exec(t);return o?Object.fromEntries(r.map((i,a)=>[i,o[a+1]])):{}}s(wae,"extractTemplateParams");async function PV(){let e=new Server({name:"agentsmesh-mcp",version:await Eae()},{capabilities:{tools:{},resources:{}}});e.setRequestHandler(ListToolsRequestSchema,async()=>({tools:qy.map(t=>({name:t.name,description:t.description,inputSchema:AV(t.inputSchema)}))})),e.setRequestHandler(CallToolRequestSchema,async t=>{let r=qy.find(n=>n.name===t.params.name);if(!r)return {isError:true,content:[{type:"text",text:JSON.stringify({code:"NOT_FOUND",message:`unknown tool: ${t.params.name}`})}]};try{let n=r.inputSchema.safeParse(t.params.arguments??{});if(!n.success){let a=xV(r.inputSchema,n.error.issues);throw new v("VALIDATION_FAILED","invalid input",a)}let o=await aE({cwd:process.cwd()}),i=await r.handler(o,n.data);return {content:[{type:"text",text:JSON.stringify(i)}]}}catch(n){let o=n instanceof v?n.toEnvelope():{code:"IO_ERROR",message:sp(n instanceof Error?n.message:"unknown error")};return {isError:true,content:[{type:"text",text:JSON.stringify(o)}]}}}),e.setRequestHandler(ListResourcesRequestSchema,async()=>({resources:iE.map(t=>({uri:t.uri,name:t.name,description:t.description}))})),e.setRequestHandler(ReadResourceRequestSchema,async t=>{let r=iE.find(a=>a.uri===t.params.uri||Oae(a.uri,t.params.uri));if(!r)throw new v("NOT_FOUND",`resource not found: ${t.params.uri}`);let n=await aE({cwd:process.cwd()}),o=wae(r.uri,t.params.uri),i=await r.read(n,o);return {contents:[{uri:t.params.uri,mimeType:"application/json",text:JSON.stringify(i)}]}}),await e.connect(new StdioServerTransport);}s(PV,"startServer");fe();async function DV(e,t){AE(),await PV();}s(DV,"runMcp");var cE={output:""},mE=s(e=>typeof e=="string"&&e.length>0?e:void 0,"str"),NV=" \u2026[truncated]";function bae(e){return e.length<=$m?e:e.slice(0,$m-NV.length)+NV}s(bae,"clampRule");async function vV(e,t){let r;try{r=JSON.parse(e);}catch{return cE}let n=mE(r.tool_input?.file_path),o=mE(r.tool_input?.command);if(n===void 0&&o===void 0)return cE;let i={...n!==void 0?{file:n}:{},...o!==void 0?{command:o}:{}},{lessons:a}=await vd(t,i,{sessionId:mE(r.session_id)});if(a.length===0)return cE;let l=n??o??"",c=a.map(p=>`- ${bae(p.lesson.rule)}`).join(`
699
- `),m=`Recalled agentsmesh lessons for ${l} \u2014 apply before your next action:
700
- ${c}`;return {output:JSON.stringify({hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:m}})}}s(vV,"buildRecallHookOutput");function FV(e){let t=e.filter(r=>!r.blocked);return {total:e.length,blocked:e.filter(r=>r.blocked).length,newLessons:t.filter(r=>r.isNewLesson).length,upserts:t.filter(r=>!r.isNewLesson).length,newTopics:t.filter(r=>r.isNewTopic).length,withWarnings:t.filter(r=>r.warningCodes.length>0).length,byTriggerKind:{file:e.reduce((r,n)=>r+n.triggerKinds.file,0),command:e.reduce((r,n)=>r+n.triggerKinds.command,0),keyword:e.reduce((r,n)=>r+n.triggerKinds.keyword,0)}}}s(FV,"summarizeCapture");var Aae=[{label:"0",test:s(e=>e===0,"test")},{label:"1",test:s(e=>e===1,"test")},{label:"2-3",test:s(e=>e>=2&&e<=3,"test")},{label:"4-9",test:s(e=>e>=4&&e<=9,"test")},{label:"10+",test:s(e=>e>=10,"test")}],Tae=1800*1e3;function MV(e,t){if(e.length===0)return 0;let r=[...e].sort((o,i)=>o-i),n=Math.min(r.length-1,Math.floor(t/100*r.length));return r[n]}s(MV,"percentile");function xae(e,t){return t.length>0&&t.every(r=>e.triggers[r]?.kind==="keyword")}s(xae,"isKeywordOnly");function Pae(e){let t=[],r=0;for(let n=0;n<e.length;n++){if(n===0){t.push(0);continue}let o=e[n],i=e[n-1];(o.session!==void 0||i.session!==void 0?o.session!==i.session:Date.parse(o.ts)-Date.parse(i.ts)>Tae)&&r++,t.push(r);}return t}s(Pae,"sessionIndices");function Dae(e,t,r){let n=e.filter(l=>l.lessonIds!==void 0).length,o=new Map,i=0,a=0;for(let l=0;l<e.length;l++){let c=e[l].lessonIds;if(c===void 0)continue;let m=t[l],p=o.get(m);p===void 0&&(p=new Set,o.set(m,p));for(let u of c){let f=Yl(r.lessons[u]?.rule??"");a+=f,p.has(u)?i+=f:p.add(u);}}return {rate:a===0?0:i/a,coverage:e.length===0?0:n/e.length}}s(Dae,"intraSessionRedundancy");function GV(e,t){let r=e.length,n=e.filter(_=>_.totalMatches===0).length,o=e.map(_=>_.returnedTokens),i=o.reduce((_,R)=>_+R,0),a=Object.values(t.lessons).filter(_=>_.status==="active"),l=a.reduce((_,R)=>_+Yl(R.rule),0),c=Pae(e),m=r===0?0:c[c.length-1]+1,p=e.filter(_=>_.bypassed===true).length,u=e.filter(_=>_.bypassed!==true).reduce((_,R)=>_+R.returnedTokens,0),f=l*m,g=e.filter(_=>_.totalMatches>0),h=g.filter(_=>_.matchedByKind.keyword>0&&_.matchedByKind.file===0&&_.matchedByKind.command===0).length,y=a.filter(_=>xae(t,_.triggers)).length;return {totalRecalls:r,noMatchRate:r===0?0:n/r,matchCountHistogram:Aae.map(_=>({bucket:_.label,count:e.filter(R=>_.test(R.totalMatches)).length})),returnedTokens:{p50:MV(o,50),p90:MV(o,90),max:o.length===0?0:Math.max(...o)},cumulativeRecallTokens:i,wholeActiveSetTokens:l,bypassedRecalls:p,preloadBreakEven:{sessions:m,preloadTokens:f,mandatoryRecallTokens:u,recallCheaper:u<f,ratio:u===0?0:f/u},redundancy:Dae(e,c,t),reachability:{keywordOnlyRecallRate:g.length===0?0:h/g.length,keywordOnlyUnreachableLessons:y}}}s(GV,"summarizeRecall");function Ut(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:null}s(Ut,"stringFlag");function $V(e,t){let r=e[t];return r===void 0||r===false||r===true?[]:Array.isArray(r)?r.filter(n=>n.length>0):r.split(",").map(n=>n.trim()).filter(n=>n.length>0)}s($V,"listFlag");function Zy(e,t){let r=e[t];return r===void 0||r===false||r===true?[]:Array.isArray(r)?r.filter(n=>n.length>0):r.length>0?[r]:[]}s(Zy,"repeatedFlag");function Md(e,t){let r=e[t];if(typeof r=="string"&&r.trim().length>0){let n=Number(r);return Number.isFinite(n)?n:null}return null}s(Md,"numberFlag");function jV(e){let t=Ut(e,"format");return t==="md"||t==="json"||t==="plain"?t:"plain"}s(jV,"parseFormat");function UV(e){let t={},r=Ut(e,"file"),n=Ut(e,"cmd")??Ut(e,"command"),o=Ut(e,"keyword");return r!==null&&(t.file=r),n!==null&&(t.command=n),o!==null&&(t.keyword=o),t}s(UV,"queryFromFlags");function Ta(){return {version:1,lessons:{},topics:{},triggers:{}}}s(Ta,"emptyGraph");function BV(){let e=new Date,t=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),n=String(e.getUTCDate()).padStart(2,"0");return `${t}-${r}-${n}`}s(BV,"todayIso");function KV(e,t,r){let n=[`# ${e}`,"",t,"","## Lessons",""];for(let[o,i]of r)n.push(`- **${o}** \u2014 ${i.rule}`);return `${n.join(`
698
+ `);let c=t.verbose===true;return {lessons:n.map(({id:m,lesson:p,score:u})=>c?{id:m,rule:p.rule,topics:[...p.topics],triggers:[...p.triggers],evidence:[...p.evidence],score:u}:{id:m,rule:p.rule}),totalMatches:o,...i>0?{suppressed:i}:{}}},async topics(e){await gt(e.projectRoot);let t=Je(e.projectRoot);return t===null?{topics:[]}:{topics:Object.entries(t.topics).map(([r,n])=>({id:r,summary:n.summary})).sort((r,n)=>r.id<n.id?-1:1)}},show:OV,deprecate:wV,async add(e,t){try{return await Fd(e.projectRoot,{rule:t.rule,topic:t.topic,triggers:{files:sE(t.trigger_files??t.trigger_file),commands:sE(t.trigger_commands??t.trigger_cmd),keywords:sE(t.trigger_keywords??t.trigger_kw)},evidence:lae(t.evidence),rationale:t.rationale},{allowNewTopic:t.new_topic===!0,topicSummary:t.topic_summary})}catch(r){throw r instanceof Vn?new v("NOT_FOUND",`lessons_add: unknown topic "${r.topic}". Pass new_topic=true + topic_summary to create it.`,{code:r.code}):r instanceof hi||r instanceof yi||r instanceof gi?new v("VALIDATION_FAILED",`lessons_add: ${r.message}`,{code:r.code}):r}}};var cae=z$1.object({file:z$1.string().optional().describe("Project-relative path of the file about to be edited."),command:z$1.string().optional().describe("Shell command about to be executed (CLI flag: --cmd)."),cmd:z$1.string().optional().describe("Alias of `command` (matches the CLI `--cmd` flag). Use `command` if unsure."),keyword:z$1.string().optional().describe("Free-form description of the active task."),limit:z$1.number().int().positive().optional().describe("Max ranked lessons to return (default 10). Results are relevance-ranked."),max_tokens:z$1.number().int().positive().optional().describe("Cap results by cumulative estimated rule-token cost (CLI flag: --max-tokens)."),"max-tokens":z$1.number().int().positive().optional().describe("Alias of `max_tokens` (matches the CLI `--max-tokens` flag)."),verbose:z$1.boolean().optional().describe("Include topics/triggers/evidence/score. Default false (compact: id + rule only).")}).strict(),oc=z$1.union([z$1.string(),z$1.array(z$1.string())]),mae=z$1.object({rule:z$1.string().min(1).describe("Imperative rule that prevents recurrence."),topic:z$1.string().min(1).describe("Topic id. Use new_topic + topic_summary to create one."),trigger_files:oc.optional().describe('file_glob triggers (e.g. ["src/cli/**/*.ts"] or a single "src/**").'),trigger_file:oc.optional().describe("Alias of `trigger_files` (matches the CLI `--trigger-file` flag)."),trigger_commands:oc.optional().describe("command_pattern triggers \u2014 regexes matched against shell commands."),trigger_cmd:oc.optional().describe("Alias of `trigger_commands` (matches the CLI `--trigger-cmd` flag)."),trigger_keywords:oc.optional().describe("keyword triggers \u2014 case-insensitive substrings of task descriptions."),trigger_kw:oc.optional().describe("Alias of `trigger_keywords` (matches the CLI `--trigger-kw` flag)."),evidence:oc.optional().describe("Evidence references (commit:SHA, lesson:id, \u2026). A scalar may be comma-separated."),rationale:z$1.string().optional().describe('Optional one-line "why" behind the rule.'),new_topic:z$1.boolean().optional().describe("Allow creating a new topic if missing."),topic_summary:z$1.string().optional().describe("Required when new_topic creates a topic. One-line summary.")}).strict(),bV=[{name:"lessons_query",description:"Recall primitive \u2014 return active lessons whose triggers match the supplied (file, command, keyword) predicates, relevance-ranked (trigger specificity + per-query topic coherence + BM25 over rule text) and capped to `limit` (default 10). Pass at least one predicate (a predicate-less call is rejected); always include `file` for an edit and `command` for a shell command \u2014 keyword-only recall misses file/command-scoped lessons. Returns compact `{id, rule}` by default; pass `verbose:true` for topics/triggers/evidence/score. Excludes deprecated and superseded lessons.",inputSchema:cae,handler:s((e,t)=>mp.query(e,t),"handler")},{name:"lessons_add",description:"Capture primitive \u2014 atomically add a new lesson. At least one EFFECTIVE trigger is REQUIRED \u2014 the add is rejected (UNRECALLABLE_LESSON, exit 2) when every trigger is dead on the mandatory file/command recall path (a stopword-only keyword whose needle loses all tokens to stopword filtering, or an invalid/ReDoS command regex). A lesson with a mix of live and dead triggers is NOT rejected. Prefer a precise `trigger_files` glob, the most reliable trigger. Deduplicates triggers against the graph. Idempotent on repeat (same rule + topic \u2192 same id, no duplicate triggers). Returns non-blocking `warnings` (trigger-hygiene nudges: oversized trigger set, broad globs, keyword-only, dead glob matching no file in the working tree [DEAD_GLOB], or rule closely paraphrasing an existing active lesson [NEAR_DUPLICATE_LESSON]) \u2014 heed them by preferring a few specific triggers.",inputSchema:mae,handler:s((e,t)=>mp.add(e,t),"handler")},{name:"lessons_topics",description:"List every topic id and summary \u2014 call before lessons_add to choose a valid --topic instead of guessing (which would create an unintended new topic).",inputSchema:z$1.object({}).strict(),handler:s(e=>mp.topics(e),"handler")},{name:"lessons_show",description:"Inspect a topic \u2014 return its summary and every lesson under it (id, rule, status, triggers, evidence), including deprecated/superseded ones. Use to find the id of a stale lesson before lessons_deprecate.",inputSchema:z$1.object({topic:z$1.string().min(1).describe("Topic id to inspect (see lessons_topics).")}).strict(),handler:s((e,t)=>mp.show(e,t),"handler")},{name:"lessons_deprecate",description:"Curation primitive \u2014 retire a lesson so recall stops returning it. With `superseded_by` the lesson is marked superseded by that replacement; without it the lesson is plainly deprecated. Throws on an unknown lesson or superseder.",inputSchema:z$1.object({id:z$1.string().min(1).describe("Lesson id to retire (see lessons_show)."),superseded_by:z$1.string().min(1).optional().describe("Replacement lesson id; omit for a plain deprecation.")}).strict(),handler:s((e,t)=>mp.deprecate(e,t),"handler")}];function AV(e){let t=toJSONSchema(e,{target:"draft-07"});return delete t.$schema,t}s(AV,"zodToMcpSchema");var qy=[...q1,...iV,...gV,...LV,...EV,...bV],iE=qy.filter(e=>e.resourceUri!==void 0).map(e=>({uri:e.resourceUri,name:e.name,description:e.description,read:s((t,r)=>e.handler(t,r),"read")}));Ga();async function fae(e){let t=resolve(e);for(;;){try{return await stat(resolve(t,"agentsmesh.yaml")),t}catch{}let r=dirname(t);if(r===t)throw new v("NO_PROJECT","agentsmesh.yaml not found");t=r;}}s(fae,"findProjectRoot");async function aE(e){let t=await fae(e.cwd);return {projectRoot:t,loadCanonical:s(()=>Kt(t),"loadCanonical")}}s(aE,"resolveContext");function xV(e,t){let r=gae(e);return t.map(n=>{let o=n.path.map(i=>typeof i=="symbol"?i.toString():i);if(n.code==="unrecognized_keys"&&r.length>0&&n.path.length===0){let i=n.keys?.[0],a=i===void 0?void 0:hae(i,r),l=a===void 0?"":` Did you mean "${a}"?`;return {code:n.code,path:o,message:`${n.message}. Expected one of: ${r.join(", ")}.${l}`,expected:r,...a===void 0?{}:{suggestion:a}}}return {code:n.code,path:o,message:n.message}})}s(xV,"enrichValidationIssues");function gae(e){let t=e.shape;return t!==void 0&&typeof t=="object"?Object.keys(t):[]}s(gae,"objectShapeKeys");function hae(e,t){let r=e.toLowerCase(),n=t.find(c=>c.toLowerCase()===r);if(n!==void 0)return n;let o,i=1/0,a=Math.max(2,Math.ceil(e.length/3));for(let c of t){let m=yae(r,c.toLowerCase());m<i&&(i=m,o=c);}return o!==void 0&&i<=a?o:t.filter(c=>c.toLowerCase().includes(r)||r.includes(c.toLowerCase())).sort((c,m)=>c.length-m.length)[0]}s(hae,"nearestKey");function yae(e,t){let r=Array.from({length:t.length+1},(n,o)=>o);for(let n=1;n<=e.length;n+=1){let o=r[0];r[0]=n;for(let i=1;i<=t.length;i+=1){let a=r[i],l=e[n-1]===t[i-1]?0:1;r[i]=Math.min(r[i]+1,r[i-1]+1,o+l),o=a;}}return r[t.length]}s(yae,"editDistance");async function wae(){let e=dirname(fileURLToPath(import.meta.url));for(let t of [resolve(e,"../../package.json"),resolve(e,"../package.json"),resolve(e,"../../../package.json")])try{let r=JSON.parse(await readFile(t,"utf8"));if(r.name==="agentsmesh")return r.version}catch{}return "0.0.0"}s(wae,"pkgVersion");function bae(e,t){return new RegExp("^"+e.replace(/\{[^}]+\}/g,"([^/]+)")+"$").test(t)}s(bae,"matchTemplate");function Aae(e,t){let r=[...e.matchAll(/\{([^}]+)\}/g)].map(i=>i[1]),o=new RegExp("^"+e.replace(/\{[^}]+\}/g,"([^/]+)")+"$").exec(t);return o?Object.fromEntries(r.map((i,a)=>[i,o[a+1]])):{}}s(Aae,"extractTemplateParams");async function PV(){let e=new Server({name:"agentsmesh-mcp",version:await wae()},{capabilities:{tools:{},resources:{}}});e.setRequestHandler(ListToolsRequestSchema,async()=>({tools:qy.map(t=>({name:t.name,description:t.description,inputSchema:AV(t.inputSchema)}))})),e.setRequestHandler(CallToolRequestSchema,async t=>{let r=qy.find(n=>n.name===t.params.name);if(!r)return {isError:true,content:[{type:"text",text:JSON.stringify({code:"NOT_FOUND",message:`unknown tool: ${t.params.name}`})}]};try{let n=r.inputSchema.safeParse(t.params.arguments??{});if(!n.success){let a=xV(r.inputSchema,n.error.issues);throw new v("VALIDATION_FAILED","invalid input",a)}let o=await aE({cwd:process.cwd()}),i=await r.handler(o,n.data);return {content:[{type:"text",text:JSON.stringify(i)}]}}catch(n){let o=n instanceof v?n.toEnvelope():{code:"IO_ERROR",message:sp(n instanceof Error?n.message:"unknown error")};return {isError:true,content:[{type:"text",text:JSON.stringify(o)}]}}}),e.setRequestHandler(ListResourcesRequestSchema,async()=>({resources:iE.map(t=>({uri:t.uri,name:t.name,description:t.description}))})),e.setRequestHandler(ReadResourceRequestSchema,async t=>{let r=iE.find(a=>a.uri===t.params.uri||bae(a.uri,t.params.uri));if(!r)throw new v("NOT_FOUND",`resource not found: ${t.params.uri}`);let n=await aE({cwd:process.cwd()}),o=Aae(r.uri,t.params.uri),i=await r.read(n,o);return {contents:[{uri:t.params.uri,mimeType:"application/json",text:JSON.stringify(i)}]}}),await e.connect(new StdioServerTransport);}s(PV,"startServer");fe();async function DV(e,t){AE(),await PV();}s(DV,"runMcp");var cE={output:""},mE=s(e=>typeof e=="string"&&e.length>0?e:void 0,"str"),NV=" \u2026[truncated]";function Tae(e){return e.length<=$m?e:e.slice(0,$m-NV.length)+NV}s(Tae,"clampRule");async function vV(e,t){let r;try{r=JSON.parse(e);}catch{return cE}let n=mE(r.tool_input?.file_path),o=mE(r.tool_input?.command);if(n===void 0&&o===void 0)return cE;let i=r.hook_event_name==="PreToolUse"?"PreToolUse":"PostToolUse",a={...n!==void 0?{file:n}:{},...o!==void 0?{command:o}:{}},{lessons:l}=await vd(t,a,{sessionId:mE(r.session_id)});if(l.length===0)return cE;let c=n??o??"",m=l.map(u=>`- ${Tae(u.lesson.rule)}`).join(`
699
+ `),p=`Recalled agentsmesh lessons for ${c} \u2014 apply before your next action:
700
+ ${m}`;return {output:JSON.stringify({hookSpecificOutput:{hookEventName:i,additionalContext:p}})}}s(vV,"buildRecallHookOutput");function FV(e){let t=e.filter(r=>!r.blocked);return {total:e.length,blocked:e.filter(r=>r.blocked).length,newLessons:t.filter(r=>r.isNewLesson).length,upserts:t.filter(r=>!r.isNewLesson).length,newTopics:t.filter(r=>r.isNewTopic).length,withWarnings:t.filter(r=>r.warningCodes.length>0).length,byTriggerKind:{file:e.reduce((r,n)=>r+n.triggerKinds.file,0),command:e.reduce((r,n)=>r+n.triggerKinds.command,0),keyword:e.reduce((r,n)=>r+n.triggerKinds.keyword,0)}}}s(FV,"summarizeCapture");var xae=[{label:"0",test:s(e=>e===0,"test")},{label:"1",test:s(e=>e===1,"test")},{label:"2-3",test:s(e=>e>=2&&e<=3,"test")},{label:"4-9",test:s(e=>e>=4&&e<=9,"test")},{label:"10+",test:s(e=>e>=10,"test")}],Pae=1800*1e3;function MV(e,t){if(e.length===0)return 0;let r=[...e].sort((o,i)=>o-i),n=Math.min(r.length-1,Math.floor(t/100*r.length));return r[n]}s(MV,"percentile");function Dae(e,t){return t.length>0&&t.every(r=>e.triggers[r]?.kind==="keyword")}s(Dae,"isKeywordOnly");function Nae(e){let t=[],r=0;for(let n=0;n<e.length;n++){if(n===0){t.push(0);continue}let o=e[n],i=e[n-1];(o.session!==void 0||i.session!==void 0?o.session!==i.session:Date.parse(o.ts)-Date.parse(i.ts)>Pae)&&r++,t.push(r);}return t}s(Nae,"sessionIndices");function vae(e,t,r){let n=e.filter(l=>l.lessonIds!==void 0).length,o=new Map,i=0,a=0;for(let l=0;l<e.length;l++){let c=e[l].lessonIds;if(c===void 0)continue;let m=t[l],p=o.get(m);p===void 0&&(p=new Set,o.set(m,p));for(let u of c){let f=Yl(r.lessons[u]?.rule??"");a+=f,p.has(u)?i+=f:p.add(u);}}return {rate:a===0?0:i/a,coverage:e.length===0?0:n/e.length}}s(vae,"intraSessionRedundancy");function GV(e,t){let r=e.length,n=e.filter(_=>_.totalMatches===0).length,o=e.map(_=>_.returnedTokens),i=o.reduce((_,R)=>_+R,0),a=Object.values(t.lessons).filter(_=>_.status==="active"),l=a.reduce((_,R)=>_+Yl(R.rule),0),c=Nae(e),m=r===0?0:c[c.length-1]+1,p=e.filter(_=>_.bypassed===true).length,u=e.filter(_=>_.bypassed!==true).reduce((_,R)=>_+R.returnedTokens,0),f=l*m,g=e.filter(_=>_.totalMatches>0),h=g.filter(_=>_.matchedByKind.keyword>0&&_.matchedByKind.file===0&&_.matchedByKind.command===0).length,y=a.filter(_=>Dae(t,_.triggers)).length;return {totalRecalls:r,noMatchRate:r===0?0:n/r,matchCountHistogram:xae.map(_=>({bucket:_.label,count:e.filter(R=>_.test(R.totalMatches)).length})),returnedTokens:{p50:MV(o,50),p90:MV(o,90),max:o.length===0?0:Math.max(...o)},cumulativeRecallTokens:i,wholeActiveSetTokens:l,bypassedRecalls:p,preloadBreakEven:{sessions:m,preloadTokens:f,mandatoryRecallTokens:u,recallCheaper:u<f,ratio:u===0?0:f/u},redundancy:vae(e,c,t),reachability:{keywordOnlyRecallRate:g.length===0?0:h/g.length,keywordOnlyUnreachableLessons:y}}}s(GV,"summarizeRecall");function Ut(e,t){let r=e[t];return typeof r=="string"&&r.length>0?r:null}s(Ut,"stringFlag");function $V(e,t){let r=e[t];return r===void 0||r===false||r===true?[]:Array.isArray(r)?r.filter(n=>n.length>0):r.split(",").map(n=>n.trim()).filter(n=>n.length>0)}s($V,"listFlag");function Zy(e,t){let r=e[t];return r===void 0||r===false||r===true?[]:Array.isArray(r)?r.filter(n=>n.length>0):r.length>0?[r]:[]}s(Zy,"repeatedFlag");function Md(e,t){let r=e[t];if(typeof r=="string"&&r.trim().length>0){let n=Number(r);return Number.isFinite(n)?n:null}return null}s(Md,"numberFlag");function jV(e){let t=Ut(e,"format");return t==="md"||t==="json"||t==="plain"?t:"plain"}s(jV,"parseFormat");function UV(e){let t={},r=Ut(e,"file"),n=Ut(e,"cmd")??Ut(e,"command"),o=Ut(e,"keyword");return r!==null&&(t.file=r),n!==null&&(t.command=n),o!==null&&(t.keyword=o),t}s(UV,"queryFromFlags");function Ta(){return {version:1,lessons:{},topics:{},triggers:{}}}s(Ta,"emptyGraph");function BV(){let e=new Date,t=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),n=String(e.getUTCDate()).padStart(2,"0");return `${t}-${r}-${n}`}s(BV,"todayIso");function KV(e,t,r){let n=[`# ${e}`,"",t,"","## Lessons",""];for(let[o,i]of r)n.push(`- **${o}** \u2014 ${i.rule}`);return `${n.join(`
701
701
  `)}
702
702
  `}s(KV,"renderTopicMarkdown");function WV(e,t,r){let n=[`# ${e}`,"",`**status:** ${t.status} **created:** ${t.createdAt}`,"",t.rule,"",`**topics:** ${t.topics.length>0?t.topics.join(", "):"(none)"}`,"","**triggers:**"];t.triggers.length===0&&n.push("- (none)");for(let o of t.triggers){let i=r[o];n.push(i?`- ${o} [${i.kind}] ${i.pattern}`:`- ${o} [missing trigger node]`);}return n.push("",`**evidence:** ${t.evidence.length>0?t.evidence.join(", "):"(none)"}`),t.supersededBy!==void 0&&n.push("",`**superseded by:** ${t.supersededBy}`),`${n.join(`
703
703
  `)}
704
- `}s(WV,"renderLessonMarkdown");function Me(e,t,r){switch(e){case "query":return {subcommand:e,exitCode:r,error:t,format:"plain",data:{lessons:[],query:{},autoMigrated:false,totalMatches:0}};case "add":return {subcommand:e,exitCode:r,error:t,data:{id:"",isNewLesson:false,isNewTopic:false,newTriggerIds:[],warnings:[]}};case "show":return {subcommand:e,exitCode:r,error:t,data:{subject:"",markdown:""}};case "deprecate":return {subcommand:e,exitCode:r,error:t,data:{id:"",supersededBy:null}};case "merge":return {subcommand:e,exitCode:r,error:t,data:{loserId:"",keeperId:""}};case "untrigger":return {subcommand:e,exitCode:r,error:t,data:{lessonId:"",triggerId:"",removedTriggerNode:false,remainingTriggerCount:0}};case "import-md":return {subcommand:e,exitCode:r,error:t,data:{topicCount:0,lessonCount:0,triggerCount:0,wroteGraphPath:"",deletedPaths:[]}};case "prune":return {subcommand:e,exitCode:r,error:t,data:{applied:false,cap:0,removedTriggerIds:[],removedTopicIds:[],trimmedLessons:[],removedDeadGlobs:[],unreachableLessons:[]}}}}s(Me,"errorResult");function HV(e,t){let r=e[t];if(r===void 0||r===false)return null;let n=typeof r=="string"?Number(r):NaN;return !Number.isInteger(n)||n<1?`Invalid --${t}: expected a positive integer.`:null}s(HV,"validatePositiveIntFlag");function Fae(e){let t=e.format;return t===void 0||t==="plain"||t==="md"||t==="json"?null:"Invalid --format: expected plain|md|json."}s(Fae,"validateFormatFlag");function e_(...e){let t=e.filter(r=>r!==void 0&&r.length>0);return t.length>0?t.join(`
705
- `):void 0}s(e_,"mergeWarnings");function Mae(e){if(existsSync(join(e,".agentsmesh")))return;let t=Qh(e);if(t!==null)return `no lessons graph here \u2014 this directory has no .agentsmesh, but a lessons project exists at ${t.replaceAll("\\","/")}. Run lessons from there (cd into it) for recall to work.`}s(Mae,"strayDirWarning");function pE(e,t,r){let n=HV(e,"top");if(n!==null)return Me("query",n,2);let o=HV(e,"max-tokens");if(o!==null)return Me("query",o,2);let i=Fae(e);if(i!==null)return Me("query",i,2);let a=jV(e),l=UV(e);if(l.file===void 0&&l.command===void 0&&l.keyword===void 0)return Me("query","Recall needs a predicate: pass at least one of --file <path-about-to-edit>, --cmd <command-about-to-run>, or --keyword <text>.",2);let c=l.keyword!==void 0&&l.file===void 0&&l.command===void 0?"keyword-only recall misses file_glob and command_pattern lessons \u2014 pass --file <path-about-to-edit> and/or --cmd <command-about-to-run> for complete recall.":void 0,m=l.file===void 0?l:{...l,file:Wy(l.file,t)},p=QK(t)??void 0,u=Kh(t);if(u.status==="corrupt"){let J={lessons:[],query:m,autoMigrated:r,totalMatches:0,warning:e_(`lessons.json is unreadable (corrupt) \u2014 recall returned no lessons. Run \`agentsmesh lessons validate\`. (${u.error.message})`,p)};return {subcommand:"query",exitCode:0,format:a,data:J}}if(u.status==="newer-version"){let J={lessons:[],query:m,autoMigrated:r,totalMatches:0,warning:e_(`lessons.json is version ${u.version}, newer than this build supports (${qu}) \u2014 recall returned no lessons. Upgrade agentsmesh to read it.`,p)};return {subcommand:"query",exitCode:0,format:a,data:J}}if(u.status==="absent"){let J=Mae(t),ee=e_(J??ad(),c,p);return {subcommand:"query",exitCode:0,format:a,data:{lessons:[],query:m,autoMigrated:r,totalMatches:0,warning:ee}}}let f=u.graph,g=Hm(f,m),h=Hy({explicit:Ut(e,"session")??void 0,disabled:e["no-dedup"]===true}),y=h===null?g:zy(h,g),_=oy(t),R=e.all===true?void 0:Md(e,"top")??_.limit,k=e.all===true?void 0:Md(e,"max-tokens")??_.maxTokens,w=zm(f,m,y,{limit:R,maxTokens:k});h!==null&&Vy(h,w.map(({id:J})=>J)),eE(t,f,m,g,w,{bypassed:e.all===true});let D=w.map(({id:J,lesson:ee,score:se})=>({id:J,rule:ee.rule,topics:[...ee.topics],triggers:[...ee.triggers],evidence:[...ee.evidence],score:se})),N=g.length-y.length,K={lessons:D,query:m,autoMigrated:r,totalMatches:g.length,...N>0?{suppressed:N}:{},...e.ids===true?{showIds:true}:{},...(()=>{let J=e_(c,p);return J?{warning:J}:{}})()};return {subcommand:"query",exitCode:0,format:a,data:K}}s(pE,"doQuery");function zV(e){return typeof e=="object"&&e!==null&&e.status==="deprecated"}s(zV,"isDeprecated");function Gae(e,t,r){let n=Wh(t),o=Wh(r);if(n===o)return t;if(e!==void 0){let l=Wh(e);if(n===l)return r;if(o===l)return t}let i=zV(t),a=zV(r);return i!==a?i?t:r:n>o?t:r}s(Gae,"pick");function uE(e,t,r){let n={};for(let o of new Set([...Object.keys(t),...Object.keys(r)])){let i=t[o],a=r[o];n[o]=i!==void 0&&a!==void 0?Gae(e[o],i,a):i??a;}return n}s(uE,"mergeRecord");function VV(e,t,r){return {version:t.version,lessons:uE(e.lessons,t.lessons,r.lessons),topics:uE(e.topics,t.topics,r.topics),triggers:uE(e.triggers,t.triggers,r.triggers)}}s(VV,"mergeGraphs");function dE(e){try{let t=Hl.safeParse(JSON.parse(readFileSync(e,"utf8")));return t.success?t.data:null}catch{return null}}s(dE,"readGraphFile");function fE(e){let[t,r,n]=e,o={subcommand:"merge-driver",exitCode:1,data:{merged:false},error:"lessons merge-driver: could not merge \u2014 git will fall back to conflict markers."};if(t===void 0||r===void 0||n===void 0)return o;let i=dE(t),a=dE(r),l=dE(n);if(i===null||a===null||l===null)return o;let c=VV(i,a,l);return Jn(c).ok?(writeFileSync(r,td(c),"utf8"),{subcommand:"merge-driver",exitCode:0,data:{merged:true}}):o}s(fE,"doMergeDriver");function JV(e,t,r){let n=e.lessons[t];if(n===void 0)throw new Error(`Unknown lesson: ${t}`);if(!n.triggers.includes(r))throw new Error(`Lesson "${t}" does not reference trigger "${r}".`);if(n.status==="active"&&n.triggers.length<=1)throw new Error(`Refusing to remove the only trigger of active lesson "${t}" \u2014 it would become unreachable. Add a replacement trigger first (lessons add "<same rule>" --topic ...), then untrigger.`);let o=n.triggers.filter(l=>l!==r);e.lessons[t]={...n,triggers:o};let i=Object.values(e.lessons).some(l=>l.triggers.includes(r)),a=false;return i||(delete e.triggers[r],a=true),{lessonId:t,triggerId:r,removedTriggerNode:a,remainingTriggerCount:o.length}}s(JV,"untriggerLesson");function t_(e){return (e instanceof Error?e.message:String(e)).replace(/^(mutateLessonsGraph|mergeLessons):\s*/,"")}s(t_,"errMessage");async function gE(e,t,r){let n=t!==void 0&&t.length>0?t:null,o=Ut(e,"rule")??n,i=Ut(e,"topic");if(o===null)return Me("add",`Missing rule \u2014 pass it positionally (\`add "<rule>"\`) or via --rule.${$d()}`,2);if(i===null)return Me("add",`Missing --topic \u2014 every lesson needs a topic id (run \`agentsmesh lessons topics\` to list them, or pass --new-topic --topic-summary "..." for a new area).${$d()}`,2);let a=existsSync(join(r,".agentsmesh"))?null:Qh(r),l=a!==null?`Capturing into a new .agentsmesh here \u2014 a lessons project already exists at ${a.replaceAll("\\","/")}. If that was unintended, cd into it and re-run.`:void 0,c=id(r)?void 0:"Captured \u2014 but recall is not wired into your AI tools yet (no `init --lessons`). Run `agentsmesh init --lessons`, then `agentsmesh generate`, so agents recall this automatically.";try{return {subcommand:"add",exitCode:0,data:{...await Fd(r,{rule:o,topic:i,triggers:{files:Zy(e,"trigger-file"),commands:Zy(e,"trigger-cmd"),keywords:Zy(e,"trigger-kw")},evidence:$V(e,"evidence"),rationale:Ut(e,"rationale")??void 0},{allowNewTopic:e["new-topic"]===!0,topicSummary:Ut(e,"topic-summary")??void 0}),...l?{locationNote:l}:{},...c?{activationNote:c}:{}}}}catch(m){return m instanceof Vn?Me("add",`Unknown topic: ${m.topic}. Pass --new-topic --topic-summary "..." to create it.`,1):m instanceof hi||m instanceof yi||m instanceof gi?Me("add",`${m.message}${$d()}`,2):Me("add",t_(m),1)}}s(gE,"doAdd");async function hE(e,t,r){if(t===void 0||t==="")return Me("deprecate","Usage: agentsmesh lessons deprecate <id> [--superseded-by <id>]",2);let n=Ut(e,"superseded-by");try{let{id:o,supersededBy:i}=await Qy(r,t,n);return {subcommand:"deprecate",exitCode:0,data:{id:o,supersededBy:i}}}catch(o){let i=t_(o),a=i.startsWith("Unknown lesson")?" Run `agentsmesh lessons journal` to list lesson ids (or `lessons query --ids` to see what recalled).":"";return Me("deprecate",`${i}${a}`,1)}}s(hE,"doDeprecate");async function yE(e,t,r){if(e===void 0||e===""||t===void 0||t==="")return Me("untrigger","Usage: agentsmesh lessons untrigger <lesson-id> <trigger-id>",2);try{return {subcommand:"untrigger",exitCode:0,data:await wt(r,i=>JV(i,e,t))}}catch(n){return Me("untrigger",t_(n),1)}}s(yE,"doUntrigger");async function _E(e,t,r){if(e===void 0||e===""||t===void 0||t==="")return Me("merge","Usage: agentsmesh lessons merge <loser-id> <keeper-id>",2);try{return {subcommand:"merge",exitCode:0,data:await Jy(r,e,t)}}catch(n){return Me("merge",t_(n),1)}}s(_E,"doMerge");async function SE(e,t){let r=e["dry-run"]===true,n=await Yy(t,{dryRun:r});return {subcommand:"strip-markers",exitCode:0,data:{changedIds:n.changedIds,changedCount:n.changedCount,dryRun:r}}}s(SE,"doStripMarkers");async function RE(e,t){let r=e.force===true,n=e.merge===true;if(!r&&!n&&existsSync(Qo(t)))return Me("import-md","lessons.json already exists. Pass --merge to fold legacy lessons into it (recommended \u2014 recovers stranded lessons without data loss), or --force to overwrite.",1);if(!existsSync(je(t).index))return Me("import-md","No legacy lessons store found (.agentsmesh/lessons/index.yaml) \u2014 nothing to migrate.",1);let o=Ut(e,"migrated-at")??BV(),i=await Km(t,{migratedAt:o,force:r,merge:n});return {subcommand:"import-md",exitCode:0,data:{topicCount:i.topicCount,lessonCount:i.lessonCount,triggerCount:i.triggerCount,wroteGraphPath:i.wroteGraphPath,deletedPaths:i.deletedPaths}}}s(RE,"doImportMd");function IE(e,t){return {applied:t,cap:e.cap,removedTriggerIds:e.removedTriggerIds,removedTopicIds:e.removedTopicIds,trimmedLessons:e.trimmedLessons.map(r=>({id:r.id,removedCount:r.removedTriggers.length,keptCount:r.keptCount})),removedDeadGlobs:e.removedDeadGlobs.map(r=>({id:r.id,removedCount:r.removedTriggers.length,keptCount:r.keptCount})),unreachableLessons:e.unreachableLessons}}s(IE,"toPruneData");async function kE(e,t){let r=Md(e,"cap");if(r!==null&&(!Number.isInteger(r)||r<1))return Me("prune","Invalid --cap: expected a positive integer.",2);let n=La(t)??void 0,o={...r!==null?{cap:r}:{},...n?{knownPaths:n}:{}};if(e.apply!==true){let c=Je(t)??Ta();return {subcommand:"prune",exitCode:0,data:IE(rc(c,o),false)}}let i=Je(t)??Ta(),a=rc(i,o);return Nd(a)?{subcommand:"prune",exitCode:0,data:IE(a,true)}:{subcommand:"prune",exitCode:0,data:await wt(t,c=>{let m=rc(c,o);return Ky(c,m),IE(m,true)})}}s(kE,"doPrune");function XV(e){let t=Je(e)??Ta(),r=Object.entries(t.topics).map(([o,i])=>({id:o,summary:i.summary})).sort((o,i)=>o.id<i.id?-1:1),n=id(e)?void 0:ad();return {subcommand:"topics",exitCode:0,data:{topics:r,...n?{setupHint:n}:{}}}}s(XV,"doTopics");function QV(e,t){if(e===void 0||e==="")return Me("show","Usage: agentsmesh lessons show <topic|lesson-id>",2);let r=Je(t);if(r!==null&&r.topics[e]!==void 0){let n=Object.entries(r.lessons).filter(([,i])=>i.topics.includes(e)&&i.status==="active").sort(([i],[a])=>i<a?-1:1),o=KV(e,r.topics[e].summary,n);return {subcommand:"show",exitCode:0,data:{subject:e,markdown:o}}}if(r!==null&&r.lessons[e]!==void 0){let n=WV(e,r.lessons[e],r.triggers);return {subcommand:"show",exitCode:0,data:{subject:e,markdown:n}}}return Me("show",`Unknown topic or lesson id: ${e}. Run \`agentsmesh lessons topics\` to list topics, or \`agentsmesh lessons journal\` to list lesson ids.`,1)}s(QV,"doShow");function qV(e){let t=Je(e)??Ta(),r=Object.entries(t.lessons).map(([i,a])=>({id:i,rule:a.rule,createdAt:a.createdAt,topics:[...a.topics]})).sort((i,a)=>i.createdAt!==a.createdAt?i.createdAt<a.createdAt?-1:1:i.id<a.id?-1:1),n=id(e)?void 0:ad();return {subcommand:"journal",exitCode:0,data:{entries:r,...n?{setupHint:n}:{}}}}s(qV,"doJournal");function ZV(e,t){let r=Je(t)??Ta(),n=GV(KK(t),r),o=FV(HK(t));return {subcommand:"stats",exitCode:0,format:e.json===true?"json":"text",data:{report:n,captureReport:o,hasLog:BK(t),hasCaptureLog:WK(t),telemetryEnabled:Ra()}}}s(ZV,"doStats");function eJ(e){let t;try{t=Je(e)??Ta();}catch(i){return {subcommand:"validate",exitCode:1,data:{ok:false,findings:[{level:"error",code:"CORRUPT_GRAPH",message:`lessons.json could not be parsed (${i instanceof Error?i.message:String(i)}). The graph is git-tracked \u2014 restore it (e.g. \`git checkout -- .agentsmesh/lessons/lessons.json\`) or repair the JSON; recall degrades to empty until then.`}]}}}let r=La(e)??void 0,n=Jn(t,{knownPaths:r}),o={ok:n.ok,findings:n.findings};return {subcommand:"validate",exitCode:n.ok?0:1,data:o}}s(eJ,"doValidate");async function tJ(e){let t=await Hae(),{output:r}=await vV(t,e);return {subcommand:"hook",exitCode:0,data:{output:r}}}s(tJ,"doHook");var Kae=1e6;async function Wae(e,t=Kae){let r=[],n=0;for await(let o of e){let i=o;if(n+=i.length,n>t)return "";r.push(i);}return Buffer.concat(r).toString("utf8")}s(Wae,"readBoundedStream");async function Hae(){return process.stdin.isTTY===true?"":Wae(process.stdin)}s(Hae,"readStdin");var zae=["json","verbose","help"],Vae={query:["file","cmd","command","keyword","format","top","all","max-tokens","session","no-dedup","ids"],add:["rule","topic","trigger-file","trigger-cmd","trigger-kw","evidence","rationale","new-topic","topic-summary"],topics:[],show:[],deprecate:["superseded-by"],merge:[],untrigger:[],"strip-markers":["dry-run"],journal:[],validate:[],stats:["json"],prune:["apply","cap"],"import-md":["merge","force","migrated-at"]};function rJ(e,t){let r=Vae[e];if(r===void 0)return null;let n=new Set([...r,...zae]);for(let o of Object.keys(t))if(!n.has(o))return `Unknown flag --${o} for \`lessons ${e}\`.
706
- Usage: ${Li[e].usage}`;return null}s(rJ,"validateLessonsFlags");async function Jae(e,t){if(e==="import-md")return false;if(e==="query"||e==="hook")try{return await gt(t)}catch{return false}return gt(t)}s(Jae,"migrateForSubcommand");async function nJ(e,t,r){let n=t[0];if(n===void 0||n==="")return {subcommand:"help",exitCode:0,data:null};let o=rJ(n,e);if(o!==null)return {subcommand:"help",exitCode:2,error:o,data:null};let i=await Jae(n,r);switch(n){case "query":return pE(e,r,i);case "add":return gE(e,t[1],r);case "topics":return XV(r);case "show":return QV(t[1],r);case "deprecate":return hE(e,t[1],r);case "merge":return _E(t[1],t[2],r);case "untrigger":return yE(t[1],t[2],r);case "strip-markers":return SE(e,r);case "journal":return qV(r);case "validate":return eJ(r);case "stats":return ZV(e,r);case "prune":return kE(e,r);case "import-md":return RE(e,r);case "hook":return tJ(r);case "merge-driver":return fE(t.slice(1));default:return {subcommand:"help",exitCode:2,error:`Unknown lessons subcommand: ${n}`,data:null}}}s(nJ,"runLessons");fe();fe();function r_(e){return `${(e*100).toFixed(1)}%`}s(r_,"pct");function sJ(e,t){if(t==="json"){process.stdout.write(`${JSON.stringify({...e.report,capture:e.captureReport},null,2)}
707
- `);return}if(!e.hasLog&&!e.hasCaptureLog){Yae(e.telemetryEnabled);return}e.hasLog&&Xae(e.report),e.hasCaptureLog&&Qae(e);}s(sJ,"renderStats");function Yae(e){e?S.info("(telemetry is ON here, but nothing has been recorded yet \u2014 telemetry is written by `lessons query` recalls and `lessons add` captures, not by `stats`. Run some `agentsmesh lessons` calls, then re-run stats.)"):S.info("(no lessons telemetry yet \u2014 recording happens during `lessons query` recalls and `lessons add` captures, NOT during `stats`. Set AGENTSMESH_LESSONS_TELEMETRY=1 in the environment that runs them \u2014 your shell for CLI calls, and/or the MCP server process for agent calls \u2014 then re-run `stats`.)");}s(Yae,"renderEmptyStatsHint");function Xae(e){let t=e.preloadBreakEven;S.info(`recalls: ${e.totalRecalls} no-match: ${r_(e.noMatchRate)} sessions: ${t.sessions} bypassed(--all): ${e.bypassedRecalls}`),S.info(`match counts: ${e.matchCountHistogram.map(r=>`${r.bucket}=${r.count}`).join(" ")}`),S.info(`returned tokens: p50=${e.returnedTokens.p50} p90=${e.returnedTokens.p90} max=${e.returnedTokens.max}`),S.info(`break-even (per session): preload ${t.sessions}\xD7${e.wholeActiveSetTokens}=${t.preloadTokens} vs mandatory recall=${t.mandatoryRecallTokens} \u2192 ${t.recallCheaper?"recall cheaper":"preload cheaper"} (ratio ${t.ratio.toFixed(2)})`),S.info(`redundancy: ${r_(e.redundancy.rate)} of delivered rule-tokens are intra-session repeats (coverage ${r_(e.redundancy.coverage)})`),S.info(`reachability: keyword-only recalls ${r_(e.reachability.keywordOnlyRecallRate)}, keyword-only-unreachable lessons ${e.reachability.keywordOnlyUnreachableLessons}`);}s(Xae,"renderRecallStats");function Qae(e){let t=e.captureReport,r=t.byTriggerKind,n=t.total===0?"\u2014":(e.report.totalRecalls/t.total).toFixed(2);S.info(`captures: ${t.total} blocked: ${t.blocked} new: ${t.newLessons} upsert: ${t.upserts} new-topics: ${t.newTopics} warned: ${t.withWarnings}`),S.info(`capture triggers by kind: file=${r.file} cmd=${r.command} kw=${r.keyword}`),S.info(`recall:capture ratio: ${n} recalls per capture`);}s(Qae,"renderCaptureStats");function iJ(e){let t=e.removedTriggerIds.length,r=e.removedTopicIds.length,n=e.trimmedLessons.length,o=e.removedDeadGlobs.length;if(t===0&&r===0&&n===0&&o===0){S.success(`Lessons graph already lean (cap ${e.cap}) \u2014 nothing to prune.`),oJ(e.unreachableLessons);return}let i=e.applied?"Pruned":"Would prune";S.success(`${i}: ${o} dead glob${o===1?"":"s"} detached, ${t} dead trigger${t===1?"":"s"} removed, ${r} orphan topic${r===1?"":"s"} removed, ${n} over-cap lesson${n===1?"":"s"} trimmed (cap ${e.cap}).`);for(let a of e.trimmedLessons)S.info(` trim ${a.id}: -${a.removedCount} \u2192 ${a.keptCount} kept`);for(let a of e.removedDeadGlobs)S.info(` dead-glob ${a.id}: -${a.removedCount} \u2192 ${a.keptCount} kept`);oJ(e.unreachableLessons),e.applied||S.warn("Dry run \u2014 pass --apply to write. lessons.json is git-tracked, so prune is reversible.");}s(iJ,"renderPrune");function oJ(e){e.length!==0&&S.warn(`${e.length} lesson${e.length===1?"":"s"} unreachable (every trigger is a dead glob) \u2014 left intact to avoid stranding; re-point a trigger or deprecate: ${e.join(", ")}`);}s(oJ,"renderUnreachable");function aJ(e){for(let t of e.findings){let r=`${t.level.toUpperCase()} ${t.code}: ${t.message}`;t.level==="error"?S.error(r):S.warn(r);}e.ok&&S.success("Lessons graph: ok.");}s(aJ,"renderValidate");function cJ(e){if(e.error!==void 0&&e.error.length>0){S.error(e.error);return}switch(e.subcommand){case "help":return ole();case "hook":e.data.output.length>0&&process.stdout.write(`${e.data.output}
708
- `);return;case "merge-driver":return;case "query":return qae(e.data,e.format);case "add":return Zae(e.data);case "topics":return ele(e.data);case "show":return tle(e.data);case "deprecate":S.success(e.data.supersededBy===null?`Deprecated ${e.data.id}.`:`Superseded ${e.data.id} \u2192 ${e.data.supersededBy}.`);return;case "merge":e.exitCode===0&&S.success(`Merged ${e.data.loserId} \u2192 ${e.data.keeperId}.`);return;case "untrigger":S.success(`Removed trigger ${e.data.triggerId} from ${e.data.lessonId} (${e.data.remainingTriggerCount} trigger${e.data.remainingTriggerCount===1?"":"s"} left)${e.data.removedTriggerNode?"; trigger node garbage-collected (no other lesson used it)":""}.`);return;case "strip-markers":S.success(`${e.data.dryRun?"Would strip":"Stripped"} legacy markers from ${e.data.changedCount} lesson${e.data.changedCount===1?"":"s"}.`);return;case "journal":return rle(e.data);case "validate":return aJ(e.data);case "prune":return iJ(e.data);case "stats":return sJ(e.data,e.format);case "import-md":return nle(e.data)}}s(cJ,"renderLessons");function qae(e,t){if(e.autoMigrated&&S.warn("lessons.json was auto-migrated from index.yaml on first invocation."),e.warning!==void 0&&e.warning.length>0&&S.warn(e.warning),t==="json"){process.stdout.write(`${JSON.stringify(e,null,2)}
709
- `);return}if(e.lessons.length===0){S.info("(no matches)");return}let r=s((n,o)=>e.showIds===true?`[${n}] ${o}`:o,"withId");if(t==="md")e.lessons.forEach((n,o)=>S.info(`${o+1}. ${r(n.id,n.rule)}`));else for(let n of e.lessons)S.info(r(n.id,n.rule));e.totalMatches!==void 0&&e.totalMatches>e.lessons.length&&S.warn(`(showing ${e.lessons.length} of ${e.totalMatches} matches \u2014 raise --top <n> with --max-tokens <m>, or pass --all)`),e.suppressed!==void 0&&e.suppressed>0&&S.warn(`(${e.suppressed} already shown this session \u2014 deduped; pass --no-dedup to include)`);}s(qae,"renderQuery");function Zae(e){if(!e.isNewLesson){if(e.newTriggerIds.length>0){let t=e.newTriggerIds.length;S.success(`Updated lesson: ${e.id} (+${t} trigger${t===1?"":"s"})`);}else S.info(`Existing lesson: ${e.id} (no change)`);lJ(e);return}S.success(`Added lesson: ${e.id}`),e.isNewTopic&&S.info(" created new topic"),e.newTriggerIds.length>0&&S.info(` new triggers: ${e.newTriggerIds.join(", ")}`),lJ(e);}s(Zae,"renderAdd");function lJ(e){e.locationNote!==void 0&&S.warn(e.locationNote),e.activationNote!==void 0&&S.warn(e.activationNote);for(let r of e.warnings)S.warn(`${r.code}: ${r.message}`);let t=e.autoPruned;t!==void 0&&S.info(` auto-pruned: ${t.removedTriggers} orphan trigger${t.removedTriggers===1?"":"s"}, ${t.removedTopics} orphan topic${t.removedTopics===1?"":"s"}, ${t.detachedDeadGlobs} dead glob${t.detachedDeadGlobs===1?"":"s"} detached (git-reversible)`);}s(lJ,"renderGuardrails");function ele(e){if(e.topics.length===0)S.info("(no topics)");else for(let t of e.topics)S.info(`${t.id} ${t.summary}`);e.setupHint!==void 0&&S.warn(e.setupHint);}s(ele,"renderTopics");function tle(e){process.stdout.write(e.markdown);}s(tle,"renderShow");function rle(e){for(let t of e.entries)S.info(`${t.createdAt} ${t.id} ${t.rule}`);e.setupHint!==void 0&&S.warn(e.setupHint);}s(rle,"renderJournal");function nle(e){S.success(`Imported lessons: topics=${e.topicCount} lessons=${e.lessonCount} triggers=${e.triggerCount}`),S.info(` graph: ${e.wroteGraphPath.replaceAll("\\","/")}`),e.deletedPaths.length>0&&S.info(` removed legacy: ${e.deletedPaths.length} path${e.deletedPaths.length===1?"":"s"}`);}s(nle,"renderImportMd");function ole(){S.info("Usage: agentsmesh lessons <subcommand> [args] [flags]"),S.info(""),S.info("Subcommands:");for(let e of Object.values(Li)){let t=e.usage.replace(/^agentsmesh lessons /,""),r=e.summary!==void 0?` (${e.summary})`:"";S.info(` ${t}${r}`);}}s(ole,"printHelp");function at(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Array.isArray(n)?n[n.length-1]:n;return t}s(at,"narrowFlags");var mJ={generate:s(async(e,t)=>{let r=at(e);M.intro("agentsmesh generate");let n=M.spinner();n.start("Generating tool config\u2026");let o=await Xo(r,void 0,{printMatrix:false});if(n.stop("Generate complete"),ct("generate",o,r,()=>Mm(o)),M.outro("Done"),r.json!==true){let i=await vm(r,process.cwd());Fm(i,{verbose:r.verbose===true});}},"generate"),init:s(async(e,t)=>{let r=process.stdin.isTTY===true&&process.stdout.isTTY===true&&e.yes!==true&&e.json!==true,n=r?{prompter:kW()}:{},o=await SW(process.cwd(),{yes:e.yes===true,global:e.global===true,lessons:e.lessons===true},n),i=r&&o.data.lessonsOnly!==true;ct("init",o,at(e),i?()=>{}:()=>IW(o));},"init"),import:s(async(e,t)=>{let r=at(e);M.intro("agentsmesh import");let n=M.spinner();n.start("Importing\u2026");let o=await EW(r);n.stop("Import complete"),ct("import",o,r,()=>jW(o)),M.outro("Done");},"import"),diff:s(async(e,t)=>{let r=at(e),n=await wW(r);ct("diff",n,r,()=>UW(n));},"diff"),lint:s(async(e,t)=>{let r=at(e),n=await MW(r);ct("lint",n,r,()=>GW(n));},"lint"),check:s(async(e,t)=>{let r=at(e),n=await HW(r);ct("check",n,r,()=>$W(n));},"check"),merge:s(async(e,t)=>{let r=at(e),n=await JW(r);ct("merge",n,r,()=>BW(n));},"merge"),matrix:s(async(e,t)=>{let r=at(e),n=await vm(r);ct("matrix",n,r,()=>Fm(n,{verbose:r.verbose===true}));},"matrix"),watch:s(async(e,t)=>{let r=at(e);if(r.json===true){lc("watch",{success:false,error:"--json is not supported with watch"}),process.exit(1);return}let n=await WW(r),o=s(()=>{n.stop().then(()=>process.exit(0));},"stop");process.on("SIGINT",o),process.on("SIGTERM",o);},"watch"),install:s(async(e,t)=>{let r=at(e);r.json===true&&(r.force=true),M.intro("agentsmesh install");let n=M.spinner();n.start("Installing\u2026");let o=await t1(r,t,process.cwd());n.stop("Install complete"),ct("install",o,r,()=>r1(o)),M.outro("Done");},"install"),uninstall:s(async(e,t)=>{let r=at(e);r.json===true&&(r.force=true),M.intro("agentsmesh uninstall");let n=M.spinner();n.start("Removing\u2026");let o=await h1(r,t,process.cwd());n.stop("Uninstall complete"),ct("uninstall",o,r,()=>y1(o)),M.outro("Done");},"uninstall"),refresh:s(async(e,t)=>{let r=at(e);M.intro("agentsmesh refresh");let n=M.spinner();n.start("Refreshing\u2026");let o=await O1(r,t,process.cwd());n.stop("Refresh complete"),ct("refresh",o,r,()=>w1(o)),M.outro("Done");},"refresh"),installs:s(async(e,t)=>{let r=at(e),n=await A1(r,t,process.cwd());ct("installs",n,r,()=>T1(n));},"installs"),plugin:s(async(e,t)=>{let r=at(e),n=await N1(r,t,process.cwd());ct("plugin",n,r,()=>v1(n));},"plugin"),target:s(async(e,t)=>{let r=at(e),n=await W1(r,t,process.cwd());ct("target",n,r,()=>H1(n));},"target"),convert:s(async(e,t)=>{let r=at(e);M.intro("agentsmesh convert");let n=M.spinner();n.start("Converting\u2026");let o=await vy(r);n.stop("Convert complete"),ct("convert",o,r,()=>z1(o)),M.outro("Done");},"convert"),mcp:s(async(e,t)=>{await DV(at(e));},"mcp"),lessons:s(async(e,t)=>{let r=await nJ(e,t,process.cwd());ct("lessons",r,at(e),()=>cJ(r)),r.exitCode!==0&&process.exit(r.exitCode);},"lessons")};var ale=new Set(["json","verbose","help"]);function LE(e,t,r){let n=e[t];if(n===void 0||typeof r=="boolean"){e[t]=r;return}Array.isArray(n)?n.push(r):typeof n=="string"?e[t]=[n,r]:e[t]=r;}s(LE,"setFlag");function lle(e){let t={},r=[],n="help";for(let o=0;o<e.length;o++){let i=e[o];if(n==="help"&&i==="--version")return {command:"version",flags:{},args:[]};if(n==="help"&&i==="--help")return {command:"help",flags:{},args:[]};if(i.startsWith("--")){let a=i.slice(2);if(ale.has(a)){LE(t,a,true);continue}let l=e[o+1];l===void 0||l.startsWith("--")?LE(t,a,true):(LE(t,a,l),o++);continue}n==="help"?n=i:r.push(i);}return {command:n,flags:t,args:r}}s(lle,"parseArgs");var cle=OE(mJ);async function mle(e){let{command:t,flags:r,args:n}=e;if(t==="help"){a_();return}if(t==="version"){PE();return}if(r.help===true){Ud(t,n);return}r.json===true&&bE(),await cle.route(t,r,n);}s(mle,"main");function ple(){let e=process.argv[1];if(!e)return false;let t=fileURLToPath(import.meta.url);try{let r=resolve(process.cwd(),e);return r===t||realpathSync(r)===realpathSync(t)}catch{return e.endsWith("cli.js")||e.includes("agentsmesh")}}s(ple,"isMainModule");if(ple()){let e=lle(process.argv.slice(2));mle(e).catch(t=>DE(t instanceof Error?t:new Error(String(t)),{verbose:e.flags.verbose===true,json:e.flags.json===true,command:e.command}));}export{lle as parseArgs};
704
+ `}s(WV,"renderLessonMarkdown");function Me(e,t,r){switch(e){case "query":return {subcommand:e,exitCode:r,error:t,format:"plain",data:{lessons:[],query:{},autoMigrated:false,totalMatches:0}};case "add":return {subcommand:e,exitCode:r,error:t,data:{id:"",isNewLesson:false,isNewTopic:false,newTriggerIds:[],warnings:[]}};case "show":return {subcommand:e,exitCode:r,error:t,data:{subject:"",markdown:""}};case "deprecate":return {subcommand:e,exitCode:r,error:t,data:{id:"",supersededBy:null}};case "merge":return {subcommand:e,exitCode:r,error:t,data:{loserId:"",keeperId:""}};case "untrigger":return {subcommand:e,exitCode:r,error:t,data:{lessonId:"",triggerId:"",removedTriggerNode:false,remainingTriggerCount:0}};case "import-md":return {subcommand:e,exitCode:r,error:t,data:{topicCount:0,lessonCount:0,triggerCount:0,wroteGraphPath:"",deletedPaths:[]}};case "prune":return {subcommand:e,exitCode:r,error:t,data:{applied:false,cap:0,removedTriggerIds:[],removedTopicIds:[],trimmedLessons:[],removedDeadGlobs:[],unreachableLessons:[]}}}}s(Me,"errorResult");function HV(e,t){let r=e[t];if(r===void 0||r===false)return null;let n=typeof r=="string"?Number(r):NaN;return !Number.isInteger(n)||n<1?`Invalid --${t}: expected a positive integer.`:null}s(HV,"validatePositiveIntFlag");function Gae(e){let t=e.format;return t===void 0||t==="plain"||t==="md"||t==="json"?null:"Invalid --format: expected plain|md|json."}s(Gae,"validateFormatFlag");function e_(...e){let t=e.filter(r=>r!==void 0&&r.length>0);return t.length>0?t.join(`
705
+ `):void 0}s(e_,"mergeWarnings");function $ae(e){if(existsSync(join(e,".agentsmesh")))return;let t=Qh(e);if(t!==null)return `no lessons graph here \u2014 this directory has no .agentsmesh, but a lessons project exists at ${t.replaceAll("\\","/")}. Run lessons from there (cd into it) for recall to work.`}s($ae,"strayDirWarning");function pE(e,t,r){let n=HV(e,"top");if(n!==null)return Me("query",n,2);let o=HV(e,"max-tokens");if(o!==null)return Me("query",o,2);let i=Gae(e);if(i!==null)return Me("query",i,2);let a=jV(e),l=UV(e);if(l.file===void 0&&l.command===void 0&&l.keyword===void 0)return Me("query","Recall needs a predicate: pass at least one of --file <path-about-to-edit>, --cmd <command-about-to-run>, or --keyword <text>.",2);let c=l.keyword!==void 0&&l.file===void 0&&l.command===void 0?"keyword-only recall misses file_glob and command_pattern lessons \u2014 pass --file <path-about-to-edit> and/or --cmd <command-about-to-run> for complete recall.":void 0,m=l.file===void 0?l:{...l,file:Wy(l.file,t)},p=QK(t)??void 0,u=Kh(t);if(u.status==="corrupt"){let J={lessons:[],query:m,autoMigrated:r,totalMatches:0,warning:e_(`lessons.json is unreadable (corrupt) \u2014 recall returned no lessons. Run \`agentsmesh lessons validate\`. (${u.error.message})`,p)};return {subcommand:"query",exitCode:0,format:a,data:J}}if(u.status==="newer-version"){let J={lessons:[],query:m,autoMigrated:r,totalMatches:0,warning:e_(`lessons.json is version ${u.version}, newer than this build supports (${qu}) \u2014 recall returned no lessons. Upgrade agentsmesh to read it.`,p)};return {subcommand:"query",exitCode:0,format:a,data:J}}if(u.status==="absent"){let J=$ae(t),ee=e_(J??ad(),c,p);return {subcommand:"query",exitCode:0,format:a,data:{lessons:[],query:m,autoMigrated:r,totalMatches:0,warning:ee}}}let f=u.graph,g=Hm(f,m),h=Hy({explicit:Ut(e,"session")??void 0,disabled:e["no-dedup"]===true}),y=h===null?g:zy(h,g),_=oy(t),R=e.all===true?void 0:Md(e,"top")??_.limit,k=e.all===true?void 0:Md(e,"max-tokens")??_.maxTokens,w=zm(f,m,y,{limit:R,maxTokens:k});h!==null&&Vy(h,w.map(({id:J})=>J)),eE(t,f,m,g,w,{bypassed:e.all===true});let D=w.map(({id:J,lesson:ee,score:se})=>({id:J,rule:ee.rule,topics:[...ee.topics],triggers:[...ee.triggers],evidence:[...ee.evidence],score:se})),N=g.length-y.length,K={lessons:D,query:m,autoMigrated:r,totalMatches:g.length,...N>0?{suppressed:N}:{},...e.ids===true?{showIds:true}:{},...(()=>{let J=e_(c,p);return J?{warning:J}:{}})()};return {subcommand:"query",exitCode:0,format:a,data:K}}s(pE,"doQuery");function zV(e){return typeof e=="object"&&e!==null&&e.status==="deprecated"}s(zV,"isDeprecated");function jae(e,t,r){let n=Wh(t),o=Wh(r);if(n===o)return t;if(e!==void 0){let l=Wh(e);if(n===l)return r;if(o===l)return t}let i=zV(t),a=zV(r);return i!==a?i?t:r:n>o?t:r}s(jae,"pick");function uE(e,t,r){let n={};for(let o of new Set([...Object.keys(t),...Object.keys(r)])){let i=t[o],a=r[o];n[o]=i!==void 0&&a!==void 0?jae(e[o],i,a):i??a;}return n}s(uE,"mergeRecord");function VV(e,t,r){return {version:t.version,lessons:uE(e.lessons,t.lessons,r.lessons),topics:uE(e.topics,t.topics,r.topics),triggers:uE(e.triggers,t.triggers,r.triggers)}}s(VV,"mergeGraphs");function dE(e){try{let t=Hl.safeParse(JSON.parse(readFileSync(e,"utf8")));return t.success?t.data:null}catch{return null}}s(dE,"readGraphFile");function fE(e){let[t,r,n]=e,o={subcommand:"merge-driver",exitCode:1,data:{merged:false},error:"lessons merge-driver: could not merge \u2014 git will fall back to conflict markers."};if(t===void 0||r===void 0||n===void 0)return o;let i=dE(t),a=dE(r),l=dE(n);if(i===null||a===null||l===null)return o;let c=VV(i,a,l);return Jn(c).ok?(writeFileSync(r,td(c),"utf8"),{subcommand:"merge-driver",exitCode:0,data:{merged:true}}):o}s(fE,"doMergeDriver");function JV(e,t,r){let n=e.lessons[t];if(n===void 0)throw new Error(`Unknown lesson: ${t}`);if(!n.triggers.includes(r))throw new Error(`Lesson "${t}" does not reference trigger "${r}".`);if(n.status==="active"&&n.triggers.length<=1)throw new Error(`Refusing to remove the only trigger of active lesson "${t}" \u2014 it would become unreachable. Add a replacement trigger first (lessons add "<same rule>" --topic ...), then untrigger.`);let o=n.triggers.filter(l=>l!==r);e.lessons[t]={...n,triggers:o};let i=Object.values(e.lessons).some(l=>l.triggers.includes(r)),a=false;return i||(delete e.triggers[r],a=true),{lessonId:t,triggerId:r,removedTriggerNode:a,remainingTriggerCount:o.length}}s(JV,"untriggerLesson");function t_(e){return (e instanceof Error?e.message:String(e)).replace(/^(mutateLessonsGraph|mergeLessons):\s*/,"")}s(t_,"errMessage");async function gE(e,t,r){let n=t!==void 0&&t.length>0?t:null,o=Ut(e,"rule")??n,i=Ut(e,"topic");if(o===null)return Me("add",`Missing rule \u2014 pass it positionally (\`add "<rule>"\`) or via --rule.${$d()}`,2);if(i===null)return Me("add",`Missing --topic \u2014 every lesson needs a topic id (run \`agentsmesh lessons topics\` to list them, or pass --new-topic --topic-summary "..." for a new area).${$d()}`,2);let a=existsSync(join(r,".agentsmesh"))?null:Qh(r),l=a!==null?`Capturing into a new .agentsmesh here \u2014 a lessons project already exists at ${a.replaceAll("\\","/")}. If that was unintended, cd into it and re-run.`:void 0,c=id(r)?void 0:"Captured \u2014 but recall is not wired into your AI tools yet (no `init --lessons`). Run `agentsmesh init --lessons`, then `agentsmesh generate`, so agents recall this automatically.";try{return {subcommand:"add",exitCode:0,data:{...await Fd(r,{rule:o,topic:i,triggers:{files:Zy(e,"trigger-file"),commands:Zy(e,"trigger-cmd"),keywords:Zy(e,"trigger-kw")},evidence:$V(e,"evidence"),rationale:Ut(e,"rationale")??void 0},{allowNewTopic:e["new-topic"]===!0,topicSummary:Ut(e,"topic-summary")??void 0}),...l?{locationNote:l}:{},...c?{activationNote:c}:{}}}}catch(m){return m instanceof Vn?Me("add",`Unknown topic: ${m.topic}. Pass --new-topic --topic-summary "..." to create it.`,1):m instanceof hi||m instanceof yi||m instanceof gi?Me("add",`${m.message}${$d()}`,2):Me("add",t_(m),1)}}s(gE,"doAdd");async function hE(e,t,r){if(t===void 0||t==="")return Me("deprecate","Usage: agentsmesh lessons deprecate <id> [--superseded-by <id>]",2);let n=Ut(e,"superseded-by");try{let{id:o,supersededBy:i}=await Qy(r,t,n);return {subcommand:"deprecate",exitCode:0,data:{id:o,supersededBy:i}}}catch(o){let i=t_(o),a=i.startsWith("Unknown lesson")?" Run `agentsmesh lessons journal` to list lesson ids (or `lessons query --ids` to see what recalled).":"";return Me("deprecate",`${i}${a}`,1)}}s(hE,"doDeprecate");async function yE(e,t,r){if(e===void 0||e===""||t===void 0||t==="")return Me("untrigger","Usage: agentsmesh lessons untrigger <lesson-id> <trigger-id>",2);try{return {subcommand:"untrigger",exitCode:0,data:await wt(r,i=>JV(i,e,t))}}catch(n){return Me("untrigger",t_(n),1)}}s(yE,"doUntrigger");async function _E(e,t,r){if(e===void 0||e===""||t===void 0||t==="")return Me("merge","Usage: agentsmesh lessons merge <loser-id> <keeper-id>",2);try{return {subcommand:"merge",exitCode:0,data:await Jy(r,e,t)}}catch(n){return Me("merge",t_(n),1)}}s(_E,"doMerge");async function SE(e,t){let r=e["dry-run"]===true,n=await Yy(t,{dryRun:r});return {subcommand:"strip-markers",exitCode:0,data:{changedIds:n.changedIds,changedCount:n.changedCount,dryRun:r}}}s(SE,"doStripMarkers");async function RE(e,t){let r=e.force===true,n=e.merge===true;if(!r&&!n&&existsSync(Qo(t)))return Me("import-md","lessons.json already exists. Pass --merge to fold legacy lessons into it (recommended \u2014 recovers stranded lessons without data loss), or --force to overwrite.",1);if(!existsSync(je(t).index))return Me("import-md","No legacy lessons store found (.agentsmesh/lessons/index.yaml) \u2014 nothing to migrate.",1);let o=Ut(e,"migrated-at")??BV(),i=await Km(t,{migratedAt:o,force:r,merge:n});return {subcommand:"import-md",exitCode:0,data:{topicCount:i.topicCount,lessonCount:i.lessonCount,triggerCount:i.triggerCount,wroteGraphPath:i.wroteGraphPath,deletedPaths:i.deletedPaths}}}s(RE,"doImportMd");function IE(e,t){return {applied:t,cap:e.cap,removedTriggerIds:e.removedTriggerIds,removedTopicIds:e.removedTopicIds,trimmedLessons:e.trimmedLessons.map(r=>({id:r.id,removedCount:r.removedTriggers.length,keptCount:r.keptCount})),removedDeadGlobs:e.removedDeadGlobs.map(r=>({id:r.id,removedCount:r.removedTriggers.length,keptCount:r.keptCount})),unreachableLessons:e.unreachableLessons}}s(IE,"toPruneData");async function kE(e,t){let r=Md(e,"cap");if(r!==null&&(!Number.isInteger(r)||r<1))return Me("prune","Invalid --cap: expected a positive integer.",2);let n=La(t)??void 0,o={...r!==null?{cap:r}:{},...n?{knownPaths:n}:{}};if(e.apply!==true){let c=Je(t)??Ta();return {subcommand:"prune",exitCode:0,data:IE(rc(c,o),false)}}let i=Je(t)??Ta(),a=rc(i,o);return Nd(a)?{subcommand:"prune",exitCode:0,data:IE(a,true)}:{subcommand:"prune",exitCode:0,data:await wt(t,c=>{let m=rc(c,o);return Ky(c,m),IE(m,true)})}}s(kE,"doPrune");function XV(e){let t=Je(e)??Ta(),r=Object.entries(t.topics).map(([o,i])=>({id:o,summary:i.summary})).sort((o,i)=>o.id<i.id?-1:1),n=id(e)?void 0:ad();return {subcommand:"topics",exitCode:0,data:{topics:r,...n?{setupHint:n}:{}}}}s(XV,"doTopics");function QV(e,t){if(e===void 0||e==="")return Me("show","Usage: agentsmesh lessons show <topic|lesson-id>",2);let r=Je(t);if(r!==null&&r.topics[e]!==void 0){let n=Object.entries(r.lessons).filter(([,i])=>i.topics.includes(e)&&i.status==="active").sort(([i],[a])=>i<a?-1:1),o=KV(e,r.topics[e].summary,n);return {subcommand:"show",exitCode:0,data:{subject:e,markdown:o}}}if(r!==null&&r.lessons[e]!==void 0){let n=WV(e,r.lessons[e],r.triggers);return {subcommand:"show",exitCode:0,data:{subject:e,markdown:n}}}return Me("show",`Unknown topic or lesson id: ${e}. Run \`agentsmesh lessons topics\` to list topics, or \`agentsmesh lessons journal\` to list lesson ids.`,1)}s(QV,"doShow");function qV(e){let t=Je(e)??Ta(),r=Object.entries(t.lessons).map(([i,a])=>({id:i,rule:a.rule,createdAt:a.createdAt,topics:[...a.topics]})).sort((i,a)=>i.createdAt!==a.createdAt?i.createdAt<a.createdAt?-1:1:i.id<a.id?-1:1),n=id(e)?void 0:ad();return {subcommand:"journal",exitCode:0,data:{entries:r,...n?{setupHint:n}:{}}}}s(qV,"doJournal");function ZV(e,t){let r=Je(t)??Ta(),n=GV(KK(t),r),o=FV(HK(t));return {subcommand:"stats",exitCode:0,format:e.json===true?"json":"text",data:{report:n,captureReport:o,hasLog:BK(t),hasCaptureLog:WK(t),telemetryEnabled:Ra()}}}s(ZV,"doStats");function eJ(e){let t;try{t=Je(e)??Ta();}catch(i){return {subcommand:"validate",exitCode:1,data:{ok:false,findings:[{level:"error",code:"CORRUPT_GRAPH",message:`lessons.json could not be parsed (${i instanceof Error?i.message:String(i)}). The graph is git-tracked \u2014 restore it (e.g. \`git checkout -- .agentsmesh/lessons/lessons.json\`) or repair the JSON; recall degrades to empty until then.`}]}}}let r=La(e)??void 0,n=Jn(t,{knownPaths:r}),o={ok:n.ok,findings:n.findings};return {subcommand:"validate",exitCode:n.ok?0:1,data:o}}s(eJ,"doValidate");async function tJ(e){let t=await Vae(),{output:r}=await vV(t,e);return {subcommand:"hook",exitCode:0,data:{output:r}}}s(tJ,"doHook");var Hae=1e6;async function zae(e,t=Hae){let r=[],n=0;for await(let o of e){let i=o;if(n+=i.length,n>t)return "";r.push(i);}return Buffer.concat(r).toString("utf8")}s(zae,"readBoundedStream");async function Vae(){return process.stdin.isTTY===true?"":zae(process.stdin)}s(Vae,"readStdin");var Jae=["json","verbose","help"],Yae={query:["file","cmd","command","keyword","format","top","all","max-tokens","session","no-dedup","ids"],add:["rule","topic","trigger-file","trigger-cmd","trigger-kw","evidence","rationale","new-topic","topic-summary"],topics:[],show:[],deprecate:["superseded-by"],merge:[],untrigger:[],"strip-markers":["dry-run"],journal:[],validate:[],stats:["json"],prune:["apply","cap"],"import-md":["merge","force","migrated-at"]};function rJ(e,t){let r=Yae[e];if(r===void 0)return null;let n=new Set([...r,...Jae]);for(let o of Object.keys(t))if(!n.has(o))return `Unknown flag --${o} for \`lessons ${e}\`.
706
+ Usage: ${Li[e].usage}`;return null}s(rJ,"validateLessonsFlags");async function Xae(e,t){if(e==="import-md")return false;if(e==="query"||e==="hook")try{return await gt(t)}catch{return false}return gt(t)}s(Xae,"migrateForSubcommand");async function nJ(e,t,r){let n=t[0];if(n===void 0||n==="")return {subcommand:"help",exitCode:0,data:null};let o=rJ(n,e);if(o!==null)return {subcommand:"help",exitCode:2,error:o,data:null};let i=await Xae(n,r);switch(n){case "query":return pE(e,r,i);case "add":return gE(e,t[1],r);case "topics":return XV(r);case "show":return QV(t[1],r);case "deprecate":return hE(e,t[1],r);case "merge":return _E(t[1],t[2],r);case "untrigger":return yE(t[1],t[2],r);case "strip-markers":return SE(e,r);case "journal":return qV(r);case "validate":return eJ(r);case "stats":return ZV(e,r);case "prune":return kE(e,r);case "import-md":return RE(e,r);case "hook":return tJ(r);case "merge-driver":return fE(t.slice(1));default:return {subcommand:"help",exitCode:2,error:`Unknown lessons subcommand: ${n}`,data:null}}}s(nJ,"runLessons");fe();fe();function r_(e){return `${(e*100).toFixed(1)}%`}s(r_,"pct");function sJ(e,t){if(t==="json"){process.stdout.write(`${JSON.stringify({...e.report,capture:e.captureReport},null,2)}
707
+ `);return}if(!e.hasLog&&!e.hasCaptureLog){Qae(e.telemetryEnabled);return}e.hasLog&&qae(e.report),e.hasCaptureLog&&Zae(e);}s(sJ,"renderStats");function Qae(e){e?S.info("(telemetry is ON here, but nothing has been recorded yet \u2014 telemetry is written by `lessons query` recalls and `lessons add` captures, not by `stats`. Run some `agentsmesh lessons` calls, then re-run stats.)"):S.info("(no lessons telemetry yet \u2014 recording happens during `lessons query` recalls and `lessons add` captures, NOT during `stats`. Set AGENTSMESH_LESSONS_TELEMETRY=1 in the environment that runs them \u2014 your shell for CLI calls, and/or the MCP server process for agent calls \u2014 then re-run `stats`.)");}s(Qae,"renderEmptyStatsHint");function qae(e){let t=e.preloadBreakEven;S.info(`recalls: ${e.totalRecalls} no-match: ${r_(e.noMatchRate)} sessions: ${t.sessions} bypassed(--all): ${e.bypassedRecalls}`),S.info(`match counts: ${e.matchCountHistogram.map(r=>`${r.bucket}=${r.count}`).join(" ")}`),S.info(`returned tokens: p50=${e.returnedTokens.p50} p90=${e.returnedTokens.p90} max=${e.returnedTokens.max}`),S.info(`break-even (per session): preload ${t.sessions}\xD7${e.wholeActiveSetTokens}=${t.preloadTokens} vs mandatory recall=${t.mandatoryRecallTokens} \u2192 ${t.recallCheaper?"recall cheaper":"preload cheaper"} (ratio ${t.ratio.toFixed(2)})`),S.info(`redundancy: ${r_(e.redundancy.rate)} of delivered rule-tokens are intra-session repeats (coverage ${r_(e.redundancy.coverage)})`),S.info(`reachability: keyword-only recalls ${r_(e.reachability.keywordOnlyRecallRate)}, keyword-only-unreachable lessons ${e.reachability.keywordOnlyUnreachableLessons}`);}s(qae,"renderRecallStats");function Zae(e){let t=e.captureReport,r=t.byTriggerKind,n=t.total===0?"\u2014":(e.report.totalRecalls/t.total).toFixed(2);S.info(`captures: ${t.total} blocked: ${t.blocked} new: ${t.newLessons} upsert: ${t.upserts} new-topics: ${t.newTopics} warned: ${t.withWarnings}`),S.info(`capture triggers by kind: file=${r.file} cmd=${r.command} kw=${r.keyword}`),S.info(`recall:capture ratio: ${n} recalls per capture`);}s(Zae,"renderCaptureStats");function iJ(e){let t=e.removedTriggerIds.length,r=e.removedTopicIds.length,n=e.trimmedLessons.length,o=e.removedDeadGlobs.length;if(t===0&&r===0&&n===0&&o===0){S.success(`Lessons graph already lean (cap ${e.cap}) \u2014 nothing to prune.`),oJ(e.unreachableLessons);return}let i=e.applied?"Pruned":"Would prune";S.success(`${i}: ${o} dead glob${o===1?"":"s"} detached, ${t} dead trigger${t===1?"":"s"} removed, ${r} orphan topic${r===1?"":"s"} removed, ${n} over-cap lesson${n===1?"":"s"} trimmed (cap ${e.cap}).`);for(let a of e.trimmedLessons)S.info(` trim ${a.id}: -${a.removedCount} \u2192 ${a.keptCount} kept`);for(let a of e.removedDeadGlobs)S.info(` dead-glob ${a.id}: -${a.removedCount} \u2192 ${a.keptCount} kept`);oJ(e.unreachableLessons),e.applied||S.warn("Dry run \u2014 pass --apply to write. lessons.json is git-tracked, so prune is reversible.");}s(iJ,"renderPrune");function oJ(e){e.length!==0&&S.warn(`${e.length} lesson${e.length===1?"":"s"} unreachable (every trigger is a dead glob) \u2014 left intact to avoid stranding; re-point a trigger or deprecate: ${e.join(", ")}`);}s(oJ,"renderUnreachable");function aJ(e){for(let t of e.findings){let r=`${t.level.toUpperCase()} ${t.code}: ${t.message}`;t.level==="error"?S.error(r):S.warn(r);}e.ok&&S.success("Lessons graph: ok.");}s(aJ,"renderValidate");function cJ(e){if(e.error!==void 0&&e.error.length>0){S.error(e.error);return}switch(e.subcommand){case "help":return ile();case "hook":e.data.output.length>0&&process.stdout.write(`${e.data.output}
708
+ `);return;case "merge-driver":return;case "query":return ele(e.data,e.format);case "add":return tle(e.data);case "topics":return rle(e.data);case "show":return nle(e.data);case "deprecate":S.success(e.data.supersededBy===null?`Deprecated ${e.data.id}.`:`Superseded ${e.data.id} \u2192 ${e.data.supersededBy}.`);return;case "merge":e.exitCode===0&&S.success(`Merged ${e.data.loserId} \u2192 ${e.data.keeperId}.`);return;case "untrigger":S.success(`Removed trigger ${e.data.triggerId} from ${e.data.lessonId} (${e.data.remainingTriggerCount} trigger${e.data.remainingTriggerCount===1?"":"s"} left)${e.data.removedTriggerNode?"; trigger node garbage-collected (no other lesson used it)":""}.`);return;case "strip-markers":S.success(`${e.data.dryRun?"Would strip":"Stripped"} legacy markers from ${e.data.changedCount} lesson${e.data.changedCount===1?"":"s"}.`);return;case "journal":return ole(e.data);case "validate":return aJ(e.data);case "prune":return iJ(e.data);case "stats":return sJ(e.data,e.format);case "import-md":return sle(e.data)}}s(cJ,"renderLessons");function ele(e,t){if(e.autoMigrated&&S.warn("lessons.json was auto-migrated from index.yaml on first invocation."),e.warning!==void 0&&e.warning.length>0&&S.warn(e.warning),t==="json"){process.stdout.write(`${JSON.stringify(e,null,2)}
709
+ `);return}if(e.lessons.length===0){S.info("(no matches)");return}let r=s((n,o)=>e.showIds===true?`[${n}] ${o}`:o,"withId");if(t==="md")e.lessons.forEach((n,o)=>S.info(`${o+1}. ${r(n.id,n.rule)}`));else for(let n of e.lessons)S.info(r(n.id,n.rule));e.totalMatches!==void 0&&e.totalMatches>e.lessons.length&&S.warn(`(showing ${e.lessons.length} of ${e.totalMatches} matches \u2014 raise --top <n> with --max-tokens <m>, or pass --all)`),e.suppressed!==void 0&&e.suppressed>0&&S.warn(`(${e.suppressed} already shown this session \u2014 deduped; pass --no-dedup to include)`);}s(ele,"renderQuery");function tle(e){if(!e.isNewLesson){if(e.newTriggerIds.length>0){let t=e.newTriggerIds.length;S.success(`Updated lesson: ${e.id} (+${t} trigger${t===1?"":"s"})`);}else S.info(`Existing lesson: ${e.id} (no change)`);lJ(e);return}S.success(`Added lesson: ${e.id}`),e.isNewTopic&&S.info(" created new topic"),e.newTriggerIds.length>0&&S.info(` new triggers: ${e.newTriggerIds.join(", ")}`),lJ(e);}s(tle,"renderAdd");function lJ(e){e.locationNote!==void 0&&S.warn(e.locationNote),e.activationNote!==void 0&&S.warn(e.activationNote);for(let r of e.warnings)S.warn(`${r.code}: ${r.message}`);let t=e.autoPruned;t!==void 0&&S.info(` auto-pruned: ${t.removedTriggers} orphan trigger${t.removedTriggers===1?"":"s"}, ${t.removedTopics} orphan topic${t.removedTopics===1?"":"s"}, ${t.detachedDeadGlobs} dead glob${t.detachedDeadGlobs===1?"":"s"} detached (git-reversible)`);}s(lJ,"renderGuardrails");function rle(e){if(e.topics.length===0)S.info("(no topics)");else for(let t of e.topics)S.info(`${t.id} ${t.summary}`);e.setupHint!==void 0&&S.warn(e.setupHint);}s(rle,"renderTopics");function nle(e){process.stdout.write(e.markdown);}s(nle,"renderShow");function ole(e){for(let t of e.entries)S.info(`${t.createdAt} ${t.id} ${t.rule}`);e.setupHint!==void 0&&S.warn(e.setupHint);}s(ole,"renderJournal");function sle(e){S.success(`Imported lessons: topics=${e.topicCount} lessons=${e.lessonCount} triggers=${e.triggerCount}`),S.info(` graph: ${e.wroteGraphPath.replaceAll("\\","/")}`),e.deletedPaths.length>0&&S.info(` removed legacy: ${e.deletedPaths.length} path${e.deletedPaths.length===1?"":"s"}`);}s(sle,"renderImportMd");function ile(){S.info("Usage: agentsmesh lessons <subcommand> [args] [flags]"),S.info(""),S.info("Subcommands:");for(let e of Object.values(Li)){let t=e.usage.replace(/^agentsmesh lessons /,""),r=e.summary!==void 0?` (${e.summary})`:"";S.info(` ${t}${r}`);}}s(ile,"printHelp");function at(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Array.isArray(n)?n[n.length-1]:n;return t}s(at,"narrowFlags");var mJ={generate:s(async(e,t)=>{let r=at(e);M.intro("agentsmesh generate");let n=M.spinner();n.start("Generating tool config\u2026");let o=await Xo(r,void 0,{printMatrix:false});if(n.stop("Generate complete"),ct("generate",o,r,()=>Mm(o)),M.outro("Done"),r.json!==true){let i=await vm(r,process.cwd());Fm(i,{verbose:r.verbose===true});}},"generate"),init:s(async(e,t)=>{let r=process.stdin.isTTY===true&&process.stdout.isTTY===true&&e.yes!==true&&e.json!==true,n=r?{prompter:kW()}:{},o=await SW(process.cwd(),{yes:e.yes===true,global:e.global===true,lessons:e.lessons===true},n),i=r&&o.data.lessonsOnly!==true;ct("init",o,at(e),i?()=>{}:()=>IW(o));},"init"),import:s(async(e,t)=>{let r=at(e);M.intro("agentsmesh import");let n=M.spinner();n.start("Importing\u2026");let o=await EW(r);n.stop("Import complete"),ct("import",o,r,()=>jW(o)),M.outro("Done");},"import"),diff:s(async(e,t)=>{let r=at(e),n=await wW(r);ct("diff",n,r,()=>UW(n));},"diff"),lint:s(async(e,t)=>{let r=at(e),n=await MW(r);ct("lint",n,r,()=>GW(n));},"lint"),check:s(async(e,t)=>{let r=at(e),n=await HW(r);ct("check",n,r,()=>$W(n));},"check"),merge:s(async(e,t)=>{let r=at(e),n=await JW(r);ct("merge",n,r,()=>BW(n));},"merge"),matrix:s(async(e,t)=>{let r=at(e),n=await vm(r);ct("matrix",n,r,()=>Fm(n,{verbose:r.verbose===true}));},"matrix"),watch:s(async(e,t)=>{let r=at(e);if(r.json===true){lc("watch",{success:false,error:"--json is not supported with watch"}),process.exit(1);return}let n=await WW(r),o=s(()=>{n.stop().then(()=>process.exit(0));},"stop");process.on("SIGINT",o),process.on("SIGTERM",o);},"watch"),install:s(async(e,t)=>{let r=at(e);r.json===true&&(r.force=true),M.intro("agentsmesh install");let n=M.spinner();n.start("Installing\u2026");let o=await t1(r,t,process.cwd());n.stop("Install complete"),ct("install",o,r,()=>r1(o)),M.outro("Done");},"install"),uninstall:s(async(e,t)=>{let r=at(e);r.json===true&&(r.force=true),M.intro("agentsmesh uninstall");let n=M.spinner();n.start("Removing\u2026");let o=await h1(r,t,process.cwd());n.stop("Uninstall complete"),ct("uninstall",o,r,()=>y1(o)),M.outro("Done");},"uninstall"),refresh:s(async(e,t)=>{let r=at(e);M.intro("agentsmesh refresh");let n=M.spinner();n.start("Refreshing\u2026");let o=await O1(r,t,process.cwd());n.stop("Refresh complete"),ct("refresh",o,r,()=>w1(o)),M.outro("Done");},"refresh"),installs:s(async(e,t)=>{let r=at(e),n=await A1(r,t,process.cwd());ct("installs",n,r,()=>T1(n));},"installs"),plugin:s(async(e,t)=>{let r=at(e),n=await N1(r,t,process.cwd());ct("plugin",n,r,()=>v1(n));},"plugin"),target:s(async(e,t)=>{let r=at(e),n=await W1(r,t,process.cwd());ct("target",n,r,()=>H1(n));},"target"),convert:s(async(e,t)=>{let r=at(e);M.intro("agentsmesh convert");let n=M.spinner();n.start("Converting\u2026");let o=await vy(r);n.stop("Convert complete"),ct("convert",o,r,()=>z1(o)),M.outro("Done");},"convert"),mcp:s(async(e,t)=>{await DV(at(e));},"mcp"),lessons:s(async(e,t)=>{let r=await nJ(e,t,process.cwd());ct("lessons",r,at(e),()=>cJ(r)),r.exitCode!==0&&process.exit(r.exitCode);},"lessons")};var cle=new Set(["json","verbose","help"]);function LE(e,t,r){let n=e[t];if(n===void 0||typeof r=="boolean"){e[t]=r;return}Array.isArray(n)?n.push(r):typeof n=="string"?e[t]=[n,r]:e[t]=r;}s(LE,"setFlag");function mle(e){let t={},r=[],n="help";for(let o=0;o<e.length;o++){let i=e[o];if(n==="help"&&i==="--version")return {command:"version",flags:{},args:[]};if(n==="help"&&i==="--help")return {command:"help",flags:{},args:[]};if(i.startsWith("--")){let a=i.slice(2);if(cle.has(a)){LE(t,a,true);continue}let l=e[o+1];l===void 0||l.startsWith("--")?LE(t,a,true):(LE(t,a,l),o++);continue}n==="help"?n=i:r.push(i);}return {command:n,flags:t,args:r}}s(mle,"parseArgs");var ple=OE(mJ);async function ule(e){let{command:t,flags:r,args:n}=e;if(t==="help"){a_();return}if(t==="version"){PE();return}if(r.help===true){Ud(t,n);return}r.json===true&&bE(),await ple.route(t,r,n);}s(ule,"main");function dle(){let e=process.argv[1];if(!e)return false;let t=fileURLToPath(import.meta.url);try{let r=resolve(process.cwd(),e);return r===t||realpathSync(r)===realpathSync(t)}catch{return e.endsWith("cli.js")||e.includes("agentsmesh")}}s(dle,"isMainModule");if(dle()){let e=mle(process.argv.slice(2));ule(e).catch(t=>DE(t instanceof Error?t:new Error(String(t)),{verbose:e.flags.verbose===true,json:e.flags.json===true,command:e.command}));}export{mle as parseArgs};