@compass-ai/nova 1.0.64 → 1.0.65
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 +407 -406
- package/dist/index.js +4 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var O2r=Object.create;var vme=Object.defineProperty;var H2r=Object.getOwnPropertyDescriptor;var J2r=Object.getOwnPropertyNames;var L2r=Object.getPrototypeOf,X2r=Object.prototype.hasOwnProperty;var Us=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(r,n)=>(typeof require<"u"?require:r)[n]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var Lt=(i,r)=>()=>(i&&(r=i(i=0)),r);var dt=(i,r)=>()=>(r||i((r={exports:{}}).exports,r),r.exports),LS=(i,r)=>{for(var n in r)vme(i,n,{get:r[n],enumerable:!0})},_vt=(i,r,n,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let l of J2r(r))!X2r.call(i,l)&&l!==n&&vme(i,l,{get:()=>r[l],enumerable:!(o=H2r(r,l))||o.enumerable});return i};var Eo=(i,r,n)=>(n=i!=null?O2r(L2r(i)):{},_vt(r||!i||!i.__esModule?vme(n,"default",{value:i,enumerable:!0}):n,i)),U2r=i=>_vt(vme({},"__esModule",{value:!0}),i);function Q2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.anthropic=="object"&&r.anthropic!==null&&typeof r.ollama=="object"&&r.ollama!==null&&typeof r.project=="object"&&r.project!==null&&typeof r.safety=="object"&&r.safety!==null&&typeof r.ui=="object"&&r.ui!==null&&typeof r.session=="object"&&r.session!==null&&typeof r.update=="object"&&r.update!==null&&typeof r.agentic=="object"&&r.agentic!==null}function j2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.model=="string"&&typeof r.maxTokens=="number"&&typeof r.temperature=="number"}function B2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.rootDir=="string"&&Array.isArray(r.ignorePatterns)&&Array.isArray(r.includePatterns)&&typeof r.maxFileSize=="number"&&typeof r.indexOnStartup=="boolean"}function z2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.requireApproval=="boolean"&&Array.isArray(r.autoApprovePatterns)&&Array.isArray(r.blockedPatterns)&&typeof r.maxFilesPerOperation=="number"&&typeof r.backupBeforeModify=="boolean"&&typeof r.shellCommandTimeout=="number"&&Array.isArray(r.allowedShellCommands)&&Array.isArray(r.blockedShellCommands)}function q2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r=="object"&&r!==null}function $2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.autoSave=="boolean"&&typeof r.autoSaveInterval=="number"&&typeof r.maxHistoryLength=="number"&&typeof r.autoCompactThreshold=="number"&&typeof r.sessionExpiryDays=="number"}function K2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.checkOnStartup=="boolean"&&typeof r.checkInterval=="number"&&typeof r.showNotifications=="boolean"&&typeof r.notificationStyle=="string"&&["banner","minimal","detailed","silent"].includes(r.notificationStyle)&&typeof r.includePrerelease=="boolean"}function exr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.version=="string"&&typeof r.config=="object"&&r.config!==null}var hvt=Lt(()=>{"use strict"});function gvt(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.dataCollection=="boolean"&&typeof r.telemetry=="boolean"&&typeof r.analytics=="boolean"&&typeof r.errorReporting=="boolean"}function txr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.id=="string"&&typeof r.version=="string"&&typeof r.grantedAt=="string"&&typeof r.expiresAt=="string"&&gvt(r.consent)}function rxr(){return{dataCollection:xme.dataCollection.defaultValue,telemetry:xme.telemetry.defaultValue,analytics:xme.analytics.defaultValue,errorReporting:xme.errorReporting.defaultValue}}function nxr(){return{dataCollection:!0,telemetry:!0,analytics:!0,errorReporting:!0}}function ixr(){return{dataCollection:!0,telemetry:!1,analytics:!1,errorReporting:!1}}var gMe,xme,yMe=Lt(()=>{"use strict";gMe="1.0.0",xme={dataCollection:{title:"Data Collection",description:"Allow Compass to store conversation history and session data locally for improved functionality.",required:!0,defaultValue:!0},telemetry:{title:"Anonymous Telemetry",description:"Help improve Compass by sending anonymous usage statistics.",required:!1,defaultValue:!1},analytics:{title:"Analytics",description:"Allow collection of feature usage patterns to improve the product.",required:!1,defaultValue:!1},errorReporting:{title:"Error Reporting",description:"Automatically send error reports to help fix bugs.",required:!1,defaultValue:!0}}});var SH,EH=Lt(()=>{"use strict";SH=(l=>(l.MANUAL="manual",l.AUTO="auto",l.STRICT="strict",l.SMART="smart",l))(SH||{})});function axr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.updateAvailable=="boolean"&&typeof r.currentVersion=="string"&&typeof r.checkedAt=="string"}function oxr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.checkOnStartup=="boolean"&&typeof r.checkInterval=="number"&&typeof r.showNotifications=="boolean"&&typeof r.notificationStyle=="string"&&typeof r.includePrerelease=="boolean"}function cxr(i){return["major","minor","patch","prerelease","build"].includes(i)}function lxr(i){return["banner","minimal","detailed","silent"].includes(i)}var sxr,yvt=Lt(()=>{"use strict";sxr={checkOnStartup:!0,checkInterval:4,showNotifications:!0,notificationStyle:"banner",includePrerelease:!1}});var Aq,IMe,wme,Sq=Lt(()=>{"use strict";Aq=(b=>(b.DIRECT="direct",b.CLARIFICATION="clarification",b.TODO_LIST="todo_list",b.PLAN="plan",b.PLAN_ADOPT="plan_adopt",b.NO_ACTION="no_action",b.SPAWN_AGENT="spawn_agent",b))(Aq||{}),IMe=(b=>(b.PENDING="pending",b.IN_PROGRESS="in_progress",b.PAUSED="paused",b.COMPLETED="completed",b.FAILED="failed",b.SKIPPED="skipped",b.ROLLED_BACK="rolled_back",b))(IMe||{}),wme=(W=>(W.IDLE="idle",W.CONTEXT_GATHERING="context_gathering",W.COMPLEXITY_ASSESSMENT="complexity_assessment",W.CLARIFICATION="clarification",W.PLAN_GENERATION="plan_generation",W.PLAN_REVIEW="plan_review",W.EXECUTION="execution",W.VERIFICATION="verification",W.COMPLETED="completed",W.FAILED="failed",W))(wme||{})});var Avt={};LS(Avt,{AGENT_SOURCE_PRIORITY:()=>Eq,compareAgentPriority:()=>wvt,createDefaultAgentDefinition:()=>vvt,getAgentSourcePriority:()=>Ame,isValidAgentFrontmatter:()=>Eme,isValidAgentPermissionMode:()=>Sme,isValidAgentSource:()=>Ivt,isValidCLIAgentConfig:()=>bvt,parseToolsList:()=>SD,serializeToolsList:()=>xvt});function Sme(i){return typeof i=="string"&&["default","acceptEditsAsk","bypassPermissions","plan","ignore","acceptEdits","dontAsk"].includes(i)}function Ivt(i){return typeof i=="string"&&["project","cli","user","builtin"].includes(i)}function Eme(i){if(typeof i!="object"||i===null)return!1;let r=i;return!(typeof r.name!="string"||r.name.length===0||typeof r.description!="string"||r.description.length===0||r.tools!==void 0&&typeof r.tools!="string"||r.disallowedTools!==void 0&&typeof r.disallowedTools!="string"||r.model!==void 0&&typeof r.model!="string"||r.permissionMode!==void 0&&!Sme(r.permissionMode)||r.skills!==void 0&&typeof r.skills!="string"||r.standalone!==void 0&&typeof r.standalone!="boolean"||r.mcpServers!==void 0&&typeof r.mcpServers!="string")}function bvt(i){if(typeof i!="object"||i===null)return!1;let r=i;return!(typeof r.description!="string"||typeof r.prompt!="string"||r.tools!==void 0&&!Array.isArray(r.tools)||r.disallowedTools!==void 0&&!Array.isArray(r.disallowedTools)||r.model!==void 0&&typeof r.model!="string"||r.permissionMode!==void 0&&!Sme(r.permissionMode)||r.skills!==void 0&&!Array.isArray(r.skills)||r.standalone!==void 0&&typeof r.standalone!="boolean"||r.mcpServers!==void 0&&!Array.isArray(r.mcpServers))}function vvt(i,r,n,o="builtin"){return{id:`${o}-${i}`,name:i,description:r,systemPrompt:n,source:o,permissionMode:"default",isActive:!0,rawFrontmatter:{name:i,description:r}}}function SD(i){if(!(!i||i.trim()===""))return i.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function xvt(i){if(!(!i||i.length===0))return i.join(", ")}function Ame(i){return Eq.indexOf(i)}function wvt(i,r){return Ame(i.source)-Ame(r.source)}var Eq,kme=Lt(()=>{"use strict";Eq=["builtin","user","cli","project"]});function dxr(){return{totalUsageTimeMs:0,lastRatingShownAt:null,lastRatingSubmittedAt:null,totalRatingsSubmitted:0,totalSessions:0,firstUsedAt:new Date().toISOString(),lastActivityAt:null}}function pxr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.totalUsageTimeMs=="number"&&(r.lastRatingShownAt===null||typeof r.lastRatingShownAt=="string")&&(r.lastRatingSubmittedAt===null||typeof r.lastRatingSubmittedAt=="string")&&typeof r.totalRatingsSubmitted=="number"&&typeof r.totalSessions=="number"&&typeof r.firstUsedAt=="string"&&(r.lastActivityAt===null||typeof r.lastActivityAt=="string")}var uxr,Svt=Lt(()=>{"use strict";uxr={usageTimeThresholdMs:12e4,cooldownPeriodMs:864e5,activityWindowMs:12e4,cooldownMultiplier:1.5,maxCooldownPeriodMs:6048e5}});function Gme(i){return typeof i=="string"&&Evt.includes(i)}function fxr(i){return typeof i=="string"&&["personal","project"].includes(i)}function mxr(i){if(typeof i!="object"||i===null)return!1;let r=i;return!(r.description!==void 0&&typeof r.description!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"||r.tools!==void 0&&!Array.isArray(r.tools)||r.match!==void 0&&typeof r.match!="object"||r.timeout!==void 0&&typeof r.timeout!="number")}function bMe(i){return Cme.indexOf(i)}function _xr(i,r){return bMe(i.source)-bMe(r.source)}var Evt,Cme,vMe=Lt(()=>{"use strict";Evt=["PreToolUse","PostToolUse","UserPromptSubmit","Notification","Stop"],Cme=["personal","project"]});function nZ(i){if(!i||typeof i!="object")return!1;let r=i;return typeof r.version=="string"&&typeof r.id=="string"&&typeof r.sessionId=="string"&&typeof r.projectPath=="string"&&typeof r.startedAt=="string"&&typeof r.endedAt=="string"&&typeof r.messageCount=="number"&&typeof r.summary=="string"&&Array.isArray(r.messages)&&Array.isArray(r.topics)&&(Array.isArray(r.operations)||Array.isArray(r.toolsUsed)&&Array.isArray(r.filesModified)&&Array.isArray(r.filesRead))}var xMe,wMe=Lt(()=>{"use strict";xMe="1.0"});var AMe,kvt=Lt(()=>{"use strict";AMe=class i extends Error{scope;provider;model;limitValue;currentUsage;resetAt;constructor(r){let o=new Date(r.resetAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),l=r.scope==="model"?`model "${r.model}"`:`provider "${r.provider}"`;super(`Daily token limit exceeded for ${l}. Used ${r.currentUsage.toLocaleString()} / ${r.limitValue.toLocaleString()} tokens. Resets at ${o}.`),this.name="TokenLimitExceededError",this.scope=r.scope,this.provider=r.provider,this.model=r.model,this.limitValue=r.limitValue,this.currentUsage=r.currentUsage,this.resetAt=r.resetAt,Object.setPrototypeOf(this,i.prototype)}}});var kq,ED,kH,Tme,SMe,Cq,EMe,kMe,hxr,CH,CMe,gxr,GMe,TMe,NMe,FMe,RMe,WMe,Gq,ZMe,iZ,Nme,kD,sZ,Cvt,fC,VMe,PMe,yxr,Ixr,aZ,bxr,Fme,vxr,xxr,wxr,Axr,Sxr,Exr,Gvt,Tq,GH,Tvt,DMe,Rme,Nq,Wme,Nvt,Fvt,Fq,kxr,MMe,YMe,Rq,Cxr,Gxr,Txr,Nxr,Vw,pC,OMe,Bv,Fxr,Rxr,Wxr,Zxr,Vxr,Pxr,vN,xN,jv,Zme,Dxr,Mxr,Yxr,Oxr,Hxr,HMe,JMe,Jxr,Vd=Lt(()=>{"use strict";kq=".compass",ED=".compass",kH="config.json",Tme="session.json",SMe="consent.json",Cq="credentials.enc",EMe="logs",kMe="backups",hxr="cache",CH="saved-sessions",CMe="index",gxr="context",GMe="temp",TMe="commands",NMe="agents",FMe="skills",RMe="hooks",WMe="rules",Gq="projects",ZMe="memory",iZ="NOVA.md",Nme="NOVA.local.md",kD="MEMORY.md",sZ=200,Cvt="chats",fC=16384,VMe=2e5,PMe=8e4,yxr=80,Ixr=10,aZ={anthropic:"haiku",ollama:"glm-4.7:cloud",zai:"glm-4.7:cloud",minimax:"glm-4.7:cloud"},bxr="haiku",Fme=200,vxr=75,xxr=5,wxr=0,Axr=80,Sxr=!0,Exr=3,Gvt=30,Tq=1,GH=100,Tvt=7,DMe=365,Rme=6e4,Nq=12e4,Wme=6e5,Nvt=50,Fvt=1024*1024,Fq=100,kxr=15,MMe=8e3,YMe=4e4,Rq=4e3,Cxr=6e3,Gxr=90,Txr=1e5,Nxr=500*1024*1024,Vw="claude-sonnet-4-5-20250929",pC=.4,OMe="haiku",Bv="verbose_analyst",Fxr=4,Rxr="banner",Wxr=4,Zxr=1e3,Vxr=16e3,Pxr=.1,vN={anthropic:{model:Vw,maxTokens:16384,temperature:pC},ollama:{model:"glm-4.7:cloud",endpoint:"https://ollama.com",maxTokens:16384,temperature:pC},project:{rootDir:process.cwd(),ignorePatterns:["node_modules/**",".git/**","dist/**","build/**","out/**","coverage/**",".next/**",".nuxt/**",".output/**","*.log",".env*","*.lock","package-lock.json","yarn.lock","pnpm-lock.yaml",".DS_Store","Thumbs.db","*.min.js","*.min.css","*.map",".compass/**"],includePatterns:["**/*"],maxFileSize:Fvt,indexOnStartup:!0},safety:{requireApproval:!0,autoApprovePatterns:[],blockedPatterns:[".env*","*.key","*.pem","*.p12","*.pfx","secrets/**","**/secrets/**","**/*.secret","**/credentials*","**/password*"],maxFilesPerOperation:Nvt,backupBeforeModify:!0,shellCommandTimeout:Nq,allowedShellCommands:["npm","npx","yarn","pnpm","git","node","tsc","eslint","prettier","jest","vitest","mocha","cargo","rustc","go","python","python3","pip","pip3","poetry","make","cmake","gradle","mvn","docker","kubectl","terraform","aws","gcloud","az","cat","ls","pwd","echo","head","tail","grep","find","wc","sort","uniq","diff","tree"],blockedShellCommands:["rm -rf /","rm -rf /*","rm -rf ~","rm -rf ~/*","sudo rm -rf",":(){:|:&};:","mkfs","dd if=/dev/zero","dd if=/dev/random","> /dev/sda","chmod -R 777 /","chown -R","wget | sh","curl | sh","wget | bash","curl | bash"]},ui:{},session:{autoSave:!0,autoSaveInterval:Rme,maxHistoryLength:Fq,autoCompactThreshold:8e4,sessionExpiryDays:Gvt,unleash:!1},update:{checkOnStartup:!0,checkInterval:Fxr,showNotifications:!0,notificationStyle:Rxr,includePrerelease:!1},agentic:{maxIterations:Fme,costWarningThreshold:xxr,costHardCap:wxr,autoCompactAtPercent:Axr,stuckDetectionEnabled:Sxr,stuckDetectionThreshold:Exr,maxIterationsPerTask:vxr}},xN=["anthropic","ollama","zai","minimax"],jv={API_KEY:"ANTHROPIC_API_KEY",COMPASS_API_KEY:"COMPASS_API_KEY",OLLAMA_API_KEY:"OLLAMA_API_KEY",ZAI_API_KEY:"ZAI_API_KEY",MINIMAX_API_KEY:"MINIMAX_API_KEY",MODEL:"COMPASS_MODEL",CONFIG_PATH:"COMPASS_CONFIG",DEBUG:"COMPASS_DEBUG",NO_COLOR:"NO_COLOR",FORCE_COLOR:"FORCE_COLOR",HOME:"HOME",USERPROFILE:"USERPROFILE"},Zme={anthropic:jv.API_KEY,ollama:jv.OLLAMA_API_KEY,zai:jv.ZAI_API_KEY,minimax:jv.MINIMAX_API_KEY},Dxr="1.0.64",Mxr="Compass CLI",Yxr="",Oxr="1.0.0",Hxr={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".scala":"scala",".cs":"csharp",".fs":"fsharp",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".c":"c",".h":"c",".hpp":"cpp",".swift":"swift",".php":"php",".pl":"perl",".pm":"perl",".sh":"bash",".bash":"bash",".zsh":"zsh",".fish":"fish",".ps1":"powershell",".sql":"sql",".r":"r",".R":"r",".lua":"lua",".vim":"vim",".el":"elisp",".clj":"clojure",".cljs":"clojure",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hrl":"erlang",".hs":"haskell",".ml":"ocaml",".mli":"ocaml",".nim":"nim",".zig":"zig",".v":"v",".d":"d",".dart":"dart",".groovy":"groovy",".gradle":"groovy",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".xml":"xml",".html":"html",".htm":"html",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".md":"markdown",".mdx":"markdown",".rst":"restructuredtext",".tex":"latex",".dockerfile":"dockerfile",".tf":"terraform",".hcl":"hcl",".proto":"protobuf",".graphql":"graphql",".gql":"graphql",".vue":"vue",".svelte":"svelte",".astro":"astro"},HMe=["package-lock.json","yarn.lock","pnpm-lock.yaml","composer.lock","Gemfile.lock","poetry.lock","Cargo.lock","go.sum","*.map","*.js.map","*.css.map","*.min.js","*.min.css","*.bundle.js","*.chunk.js","*.sql","*.csv","**/__snapshots__/**","**/fixtures/**/*.json","*.d.ts.map"],JMe=["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".output",".cache",".parcel-cache","vendor","__pycache__",".pytest_cache","target","bin","obj"],Jxr=[".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".svg",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".bin",".dat",".db",".sqlite",".sqlite3",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".wav",".avi",".mov",".mkv",".webm",".flv",".class",".jar",".war",".ear",".pyc",".pyo",".o",".obj",".a",".lib"]});var CD,Rvt,Vme=Lt(()=>{"use strict";hvt();yMe();EH();yvt();Sq();kme();Svt();vMe();wMe();kvt();Vd();CD="BASIC",Rvt=["BASIC","PRO","MAX","ENTERPRISE","UNLIMITED"]});var LMe={};LS(LMe,{CLAUDE_MODELS:()=>Pw,MODEL_ALIASES:()=>Wq,NO_SUBSCRIPTION_DAILY_TOKEN_LIMIT:()=>Wvt,calculateModelCost:()=>Hvt,compareModels:()=>Jvt,getAvailableAliases:()=>Dvt,getAvailableModelIds:()=>Pvt,getAvailableModels:()=>oZ,getCheapestModel:()=>Xvt,getDefaultModel:()=>Yvt,getDefaultModelId:()=>Ovt,getModelConfig:()=>a_,getModelDescription:()=>Pme,getModelTier:()=>Qvt,getModelsByCapability:()=>Lvt,getMostCapableModel:()=>Uvt,hasFullAccess:()=>Zvt,isAnthropicModel:()=>Vvt,isValidModel:()=>Mvt,resolveModelId:()=>_y});function Zvt(i){return i==="trial"||i==="active"}function _y(i){let r=i.toLowerCase();if(Wq[r])return Wq[r];for(let n of Object.keys(Pw))if(n.toLowerCase()===r)return n;return i}function a_(i){let r=_y(i);return Pw[r]}function Vvt(i){return a_(i)?.provider==="anthropic"}function oZ(){return Object.values(Pw)}function Pvt(){return Object.keys(Pw)}function Dvt(){return Object.keys(Wq)}function Mvt(i){return _y(i)in Pw}function Yvt(){return Pw["claude-sonnet-4-5-20250929"]}function Ovt(){return"claude-sonnet-4-5-20250929"}function Hvt(i,r,n){let o=a_(i);if(!o)return null;let l=r/1e6*o.pricing.inputPricePerMillion,f=n/1e6*o.pricing.outputPricePerMillion;return l+f}function Jvt(i,r,n){let o=a_(i),l=a_(r);if(!o||!l)return 0;switch(n){case"price":return o.pricing.inputPricePerMillion-l.pricing.inputPricePerMillion;case"context":return l.contextWindow-o.contextWindow;case"speed":return l.pricing.inputPricePerMillion-o.pricing.inputPricePerMillion;default:return 0}}function Lvt(i){return oZ().filter(r=>r.capabilities[i])}function Xvt(){return oZ().reduce((r,n)=>n.pricing.inputPricePerMillion<r.pricing.inputPricePerMillion?n:r)}function Uvt(){return Pw["claude-opus-4-6"]}function Qvt(i){let r=_y(i);if(r.includes("haiku"))return"economy";if(r.includes("sonnet"))return"balanced";if(r.includes("opus"))return"premium"}function Pme(i){let r=_y(i);if(r.includes("opus"))return"Most capable model - best for complex reasoning, analysis, and extended thinking";if(r.includes("sonnet"))return"Balanced performance and cost - ideal for most coding tasks";if(r.includes("haiku"))return"Fastest and most economical - great for quick responses and simple tasks";if(r.includes("glm-4.7"))return"OpenSource"}var Wvt,Pw,Wq,XS=Lt(()=>{"use strict";Wvt=15e4;Pw={"glm-5:cloud":{id:"glm-5:cloud",name:"Z.AI GLM 5",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}},"glm-4.7:cloud":{id:"glm-4.7:cloud",name:"Z.AI GLM 4.7",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}},"minimax-m2.5:cloud":{id:"minimax-m2.5:cloud",name:"MiniMax M2.5",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!1}},"kimi-k2.5:cloud":{id:"kimi-k2.5:cloud",name:"Kimi K2.5",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!1}},"gemini-3-pro-preview":{id:"gemini-3-pro-preview",name:"Gemini 3 Pro",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}},"claude-sonnet-4-6":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15,cacheWrite5mPricePerMillion:3.75,cacheWrite1hPricePerMillion:6,cacheHitPricePerMillion:.3},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}},"claude-sonnet-4-5-20250929":{id:"claude-sonnet-4-5-20250929",name:"Claude Sonnet 4.5",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15,cacheWrite5mPricePerMillion:3.75,cacheWrite1hPricePerMillion:6,cacheHitPricePerMillion:.3},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}},"claude-opus-4-6":{id:"claude-opus-4-6",name:"Claude Opus 4.6",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:5,outputPricePerMillion:25,cacheWrite5mPricePerMillion:6.25,cacheWrite1hPricePerMillion:10,cacheHitPricePerMillion:.5},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!0,complexityClassification:!0}},"claude-opus-4-5-20251101":{id:"claude-opus-4-5-20251101",name:"Claude Opus 4.5",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:5,outputPricePerMillion:25,cacheWrite5mPricePerMillion:6.25,cacheWrite1hPricePerMillion:10,cacheHitPricePerMillion:.5},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!0,complexityClassification:!0}},"claude-haiku-4-5-20251001":{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:1,outputPricePerMillion:5,cacheWrite5mPricePerMillion:1.25,cacheWrite1hPricePerMillion:2,cacheHitPricePerMillion:.1},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}}},Wq={sonnet:"claude-sonnet-4-6",opus:"claude-opus-4-6","sonnet-4.6":"claude-sonnet-4-6",sonnet46:"claude-sonnet-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929",sonnet45:"claude-sonnet-4-5-20250929","opus-4.6":"claude-opus-4-6",opus46:"claude-opus-4-6","opus-4.5":"claude-opus-4-5-20251101",opus45:"claude-opus-4-5-20251101",haiku:"claude-haiku-4-5-20251001","glm-5":"glm-5:cloud","glm-4.7":"glm-4.7:cloud","minimax-m2.5":"minimax-m2.5:cloud","kimi-k2.5":"kimi-k2.5:cloud","gemini-3-pro":"gemini-3-pro-preview",fast:"claude-haiku-4-5-20251001",quick:"claude-haiku-4-5-20251001",smart:"claude-sonnet-4-5-20250929",balanced:"claude-sonnet-4-5-20250929",powerful:"claude-opus-4-6",best:"claude-opus-4-6",beyond:"glm-5:cloud",robust:"glm-4.7:cloud",deep:"kimi-k2.5:cloud",versatile:"minimax-m2.5:cloud",creative:"gemini-3-pro-preview",s:"claude-sonnet-4-5-20250929",o:"claude-opus-4-6",h:"claude-haiku-4-5-20251001",g:"glm-5:cloud",m:"minimax-m2.5:cloud",k:"kimi-k2.5:cloud",p:"gemini-3-pro-preview"}});function Lxr(){let i=new Map;for(let r of TH){let n=i.get(r.category)||[];n.push(r),i.set(r.category,n)}return i}var Zq,XMe,UMe,TH,QMe=Lt(()=>{"use strict";Zq={network:{label:"Network Tools",priority:1},media:{label:"Media Tools",priority:2},development:{label:"Development Tools",priority:3},compression:{label:"Compression Tools",priority:4},text:{label:"Text Processing Tools",priority:5},file:{label:"File Tools",priority:6},system:{label:"System Tools",priority:7}},XMe=36e5,UMe=3e3,TH=[{command:"curl",name:"cURL",category:"network",description:"Transfer data with URLs",decisionRule:"Use for downloading files, making HTTP requests, testing APIs",useCases:["curl -O https://example.com/file.zip",'curl -X POST -d "data" https://api.example.com',"curl -I https://example.com (headers only)"]},{command:"wget",name:"wget",category:"network",description:"Non-interactive network downloader",decisionRule:"Use for downloading files, especially recursive downloads",useCases:["wget https://example.com/file.zip","wget -r https://example.com/docs/","wget -c https://example.com/large.zip (resume)"]},{command:"ssh",name:"SSH",category:"network",description:"Secure shell remote login",decisionRule:"Use for remote server access and secure connections",useCases:["ssh user@host","ssh -L 8080:localhost:80 user@host (tunnel)"]},{command:"ping",name:"Ping",category:"network",description:"Test network connectivity",decisionRule:"Use to check if a host is reachable",useCases:["ping example.com","ping -c 4 example.com (4 packets)"]},{command:"nslookup",name:"nslookup",category:"network",description:"Query DNS records",decisionRule:"Use for DNS lookups and troubleshooting",useCases:["nslookup example.com","nslookup -type=MX example.com"]},{command:"dig",name:"dig",category:"network",description:"DNS lookup utility",decisionRule:"Use for detailed DNS queries",useCases:["dig example.com","dig +short example.com","dig example.com MX"]},{command:"netstat",name:"netstat",category:"network",description:"Network statistics",decisionRule:"Use to view network connections and listening ports",useCases:["netstat -an (all connections)","netstat -tlnp (listening TCP ports)"]},{command:"ffmpeg",name:"FFmpeg",category:"media",description:"Audio/video conversion and processing",decisionRule:"Use for any audio/video conversion, extraction, or manipulation",useCases:["ffmpeg -i input.mp4 output.mp3 (extract audio)","ffmpeg -i input.mp4 -vn -acodec copy output.aac","ffmpeg -i input.mp4 -ss 00:01:00 -t 30 clip.mp4 (trim)"]},{command:"convert",name:"ImageMagick",category:"media",description:"Image conversion and manipulation",decisionRule:"Use for image format conversion, resizing, effects",useCases:["convert input.png output.jpg","convert input.png -resize 50% output.png","convert *.png output.pdf (combine to PDF)"]},{command:"yt-dlp",name:"yt-dlp",category:"media",description:"Video/audio downloader",decisionRule:"Use for downloading videos from YouTube and other sites",useCases:["yt-dlp https://youtube.com/watch?v=...","yt-dlp -x --audio-format mp3 URL (audio only)"]},{command:"git",name:"Git",category:"development",description:"Version control system",decisionRule:"Use for all version control operations",useCases:["git status","git diff","git log --oneline -10"]},{command:"node",name:"Node.js",category:"development",description:"JavaScript runtime",decisionRule:"Use for running JavaScript files or REPL",useCases:["node script.js",'node -e "console.log(1+1)"']},{command:"npm",name:"npm",category:"development",description:"Node.js package manager",decisionRule:"Use for JavaScript package management",useCases:["npm install package","npm run script","npm init -y"]},{command:"python",name:"Python",category:"development",description:"Python interpreter",decisionRule:"Use for running Python scripts or quick computations",useCases:["python script.py",'python -c "print(2**10)"']},{command:"pip",name:"pip",category:"development",description:"Python package manager",decisionRule:"Use for Python package installation",useCases:["pip install package","pip list","pip freeze > requirements.txt"]},{command:"docker",name:"Docker",category:"development",description:"Container platform",decisionRule:"Use for container operations",useCases:["docker ps","docker run -it ubuntu bash","docker build -t myapp ."]},{command:"code",name:"VS Code",category:"development",description:"Visual Studio Code editor",decisionRule:"Use to open files/folders in VS Code",useCases:["code .","code file.js"]},{command:"jq",name:"jq",category:"development",description:"JSON processor",decisionRule:"Use for parsing, filtering, and transforming JSON",useCases:["cat data.json | jq '.field'","jq '.items[] | .name' data.json","curl api.example.com | jq '.'"]},{command:"7z",name:"7-Zip",category:"compression",description:"High compression archiver",decisionRule:"Use for creating/extracting archives, especially 7z format",useCases:["7z x archive.7z","7z a archive.7z folder/"]},{command:"tar",name:"tar",category:"compression",description:"Archive utility",decisionRule:"Use for tar archives, common on Unix systems",useCases:["tar -xzf archive.tar.gz","tar -czf archive.tar.gz folder/","tar -tvf archive.tar (list contents)"]},{command:"zip",name:"zip",category:"compression",description:"Compress files into ZIP format",decisionRule:"Use for creating ZIP archives",useCases:["zip archive.zip file1 file2","zip -r archive.zip folder/"]},{command:"unzip",name:"unzip",category:"compression",description:"Extract ZIP archives",decisionRule:"Use for extracting ZIP files",useCases:["unzip archive.zip","unzip -l archive.zip (list contents)","unzip archive.zip -d destination/"]},{command:"gzip",name:"gzip",category:"compression",description:"GNU compression utility",decisionRule:"Use for gzip compression/decompression",useCases:["gzip file","gzip -d file.gz","gzip -k file (keep original)"]},{command:"grep",name:"grep",category:"text",description:"Search text patterns",decisionRule:"Use for searching patterns in files",useCases:['grep "pattern" file','grep -r "pattern" folder/','grep -i "pattern" file (case insensitive)']},{command:"sed",name:"sed",category:"text",description:"Stream editor",decisionRule:"Use for text transformations and substitutions",useCases:["sed 's/old/new/g' file","sed -i 's/old/new/g' file (in-place)"]},{command:"awk",name:"awk",category:"text",description:"Pattern scanning and processing",decisionRule:"Use for column-based text processing",useCases:["awk '{print $1}' file","awk -F: '{print $1}' /etc/passwd"]},{command:"find",name:"find",category:"file",description:"Search for files",decisionRule:"Use for finding files by name, type, date, etc.",useCases:['find . -name "*.js"',"find . -type f -mtime -7 (modified last 7 days)"]},{command:"rsync",name:"rsync",category:"file",description:"Fast file synchronization",decisionRule:"Use for copying/syncing files with progress and resume",useCases:["rsync -av source/ dest/","rsync -avz source/ user@host:dest/"]},{command:"pandoc",name:"Pandoc",category:"system",description:"Universal document converter",decisionRule:"Use for converting between document formats",useCases:["pandoc input.md -o output.pdf","pandoc input.docx -o output.html"]},{command:"htop",name:"htop",category:"system",description:"Interactive process viewer",decisionRule:"Use for monitoring system resources",useCases:["htop"]},{command:"btop",name:"btop",category:"system",description:"Resource monitor",decisionRule:"Use for monitoring system resources with better UI",useCases:["btop"]},{command:"lsof",name:"lsof",category:"system",description:"List open files",decisionRule:"Use to find which process is using a file or port",useCases:["lsof -i :8080 (what is using port 8080)","lsof /path/to/file"]}]});var jMe,Dme,Vq,BMe,Pq,Mme,Yme,wN,Dq=Lt(()=>{"use strict";jMe="Schedule.md",Dme="sched-",Vq=8,BMe=["active","paused","completed"],Pq=`# Scheduled Tasks
|
|
1
|
+
var O2r=Object.create;var vme=Object.defineProperty;var H2r=Object.getOwnPropertyDescriptor;var J2r=Object.getOwnPropertyNames;var L2r=Object.getPrototypeOf,X2r=Object.prototype.hasOwnProperty;var Us=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(r,n)=>(typeof require<"u"?require:r)[n]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var Lt=(i,r)=>()=>(i&&(r=i(i=0)),r);var dt=(i,r)=>()=>(r||i((r={exports:{}}).exports,r),r.exports),LS=(i,r)=>{for(var n in r)vme(i,n,{get:r[n],enumerable:!0})},_vt=(i,r,n,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let l of J2r(r))!X2r.call(i,l)&&l!==n&&vme(i,l,{get:()=>r[l],enumerable:!(o=H2r(r,l))||o.enumerable});return i};var Eo=(i,r,n)=>(n=i!=null?O2r(L2r(i)):{},_vt(r||!i||!i.__esModule?vme(n,"default",{value:i,enumerable:!0}):n,i)),U2r=i=>_vt(vme({},"__esModule",{value:!0}),i);function Q2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.anthropic=="object"&&r.anthropic!==null&&typeof r.ollama=="object"&&r.ollama!==null&&typeof r.project=="object"&&r.project!==null&&typeof r.safety=="object"&&r.safety!==null&&typeof r.ui=="object"&&r.ui!==null&&typeof r.session=="object"&&r.session!==null&&typeof r.update=="object"&&r.update!==null&&typeof r.agentic=="object"&&r.agentic!==null}function j2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.model=="string"&&typeof r.maxTokens=="number"&&typeof r.temperature=="number"}function B2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.rootDir=="string"&&Array.isArray(r.ignorePatterns)&&Array.isArray(r.includePatterns)&&typeof r.maxFileSize=="number"&&typeof r.indexOnStartup=="boolean"}function z2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.requireApproval=="boolean"&&Array.isArray(r.autoApprovePatterns)&&Array.isArray(r.blockedPatterns)&&typeof r.maxFilesPerOperation=="number"&&typeof r.backupBeforeModify=="boolean"&&typeof r.shellCommandTimeout=="number"&&Array.isArray(r.allowedShellCommands)&&Array.isArray(r.blockedShellCommands)}function q2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r=="object"&&r!==null}function $2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.autoSave=="boolean"&&typeof r.autoSaveInterval=="number"&&typeof r.maxHistoryLength=="number"&&typeof r.autoCompactThreshold=="number"&&typeof r.sessionExpiryDays=="number"}function K2r(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.checkOnStartup=="boolean"&&typeof r.checkInterval=="number"&&typeof r.showNotifications=="boolean"&&typeof r.notificationStyle=="string"&&["banner","minimal","detailed","silent"].includes(r.notificationStyle)&&typeof r.includePrerelease=="boolean"}function exr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.version=="string"&&typeof r.config=="object"&&r.config!==null}var hvt=Lt(()=>{"use strict"});function gvt(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.dataCollection=="boolean"&&typeof r.telemetry=="boolean"&&typeof r.analytics=="boolean"&&typeof r.errorReporting=="boolean"}function txr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.id=="string"&&typeof r.version=="string"&&typeof r.grantedAt=="string"&&typeof r.expiresAt=="string"&&gvt(r.consent)}function rxr(){return{dataCollection:xme.dataCollection.defaultValue,telemetry:xme.telemetry.defaultValue,analytics:xme.analytics.defaultValue,errorReporting:xme.errorReporting.defaultValue}}function nxr(){return{dataCollection:!0,telemetry:!0,analytics:!0,errorReporting:!0}}function ixr(){return{dataCollection:!0,telemetry:!1,analytics:!1,errorReporting:!1}}var gMe,xme,yMe=Lt(()=>{"use strict";gMe="1.0.0",xme={dataCollection:{title:"Data Collection",description:"Allow Compass to store conversation history and session data locally for improved functionality.",required:!0,defaultValue:!0},telemetry:{title:"Anonymous Telemetry",description:"Help improve Compass by sending anonymous usage statistics.",required:!1,defaultValue:!1},analytics:{title:"Analytics",description:"Allow collection of feature usage patterns to improve the product.",required:!1,defaultValue:!1},errorReporting:{title:"Error Reporting",description:"Automatically send error reports to help fix bugs.",required:!1,defaultValue:!0}}});var SH,EH=Lt(()=>{"use strict";SH=(l=>(l.MANUAL="manual",l.AUTO="auto",l.STRICT="strict",l.SMART="smart",l))(SH||{})});function axr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.updateAvailable=="boolean"&&typeof r.currentVersion=="string"&&typeof r.checkedAt=="string"}function oxr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.checkOnStartup=="boolean"&&typeof r.checkInterval=="number"&&typeof r.showNotifications=="boolean"&&typeof r.notificationStyle=="string"&&typeof r.includePrerelease=="boolean"}function cxr(i){return["major","minor","patch","prerelease","build"].includes(i)}function lxr(i){return["banner","minimal","detailed","silent"].includes(i)}var sxr,yvt=Lt(()=>{"use strict";sxr={checkOnStartup:!0,checkInterval:4,showNotifications:!0,notificationStyle:"banner",includePrerelease:!1}});var Aq,IMe,wme,Sq=Lt(()=>{"use strict";Aq=(b=>(b.DIRECT="direct",b.CLARIFICATION="clarification",b.TODO_LIST="todo_list",b.PLAN="plan",b.PLAN_ADOPT="plan_adopt",b.NO_ACTION="no_action",b.SPAWN_AGENT="spawn_agent",b))(Aq||{}),IMe=(b=>(b.PENDING="pending",b.IN_PROGRESS="in_progress",b.PAUSED="paused",b.COMPLETED="completed",b.FAILED="failed",b.SKIPPED="skipped",b.ROLLED_BACK="rolled_back",b))(IMe||{}),wme=(W=>(W.IDLE="idle",W.CONTEXT_GATHERING="context_gathering",W.COMPLEXITY_ASSESSMENT="complexity_assessment",W.CLARIFICATION="clarification",W.PLAN_GENERATION="plan_generation",W.PLAN_REVIEW="plan_review",W.EXECUTION="execution",W.VERIFICATION="verification",W.COMPLETED="completed",W.FAILED="failed",W))(wme||{})});var Avt={};LS(Avt,{AGENT_SOURCE_PRIORITY:()=>Eq,compareAgentPriority:()=>wvt,createDefaultAgentDefinition:()=>vvt,getAgentSourcePriority:()=>Ame,isValidAgentFrontmatter:()=>Eme,isValidAgentPermissionMode:()=>Sme,isValidAgentSource:()=>Ivt,isValidCLIAgentConfig:()=>bvt,parseToolsList:()=>SD,serializeToolsList:()=>xvt});function Sme(i){return typeof i=="string"&&["default","acceptEditsAsk","bypassPermissions","plan","ignore","acceptEdits","dontAsk"].includes(i)}function Ivt(i){return typeof i=="string"&&["project","cli","user","builtin"].includes(i)}function Eme(i){if(typeof i!="object"||i===null)return!1;let r=i;return!(typeof r.name!="string"||r.name.length===0||typeof r.description!="string"||r.description.length===0||r.tools!==void 0&&typeof r.tools!="string"||r.disallowedTools!==void 0&&typeof r.disallowedTools!="string"||r.model!==void 0&&typeof r.model!="string"||r.permissionMode!==void 0&&!Sme(r.permissionMode)||r.skills!==void 0&&typeof r.skills!="string"||r.standalone!==void 0&&typeof r.standalone!="boolean"||r.mcpServers!==void 0&&typeof r.mcpServers!="string")}function bvt(i){if(typeof i!="object"||i===null)return!1;let r=i;return!(typeof r.description!="string"||typeof r.prompt!="string"||r.tools!==void 0&&!Array.isArray(r.tools)||r.disallowedTools!==void 0&&!Array.isArray(r.disallowedTools)||r.model!==void 0&&typeof r.model!="string"||r.permissionMode!==void 0&&!Sme(r.permissionMode)||r.skills!==void 0&&!Array.isArray(r.skills)||r.standalone!==void 0&&typeof r.standalone!="boolean"||r.mcpServers!==void 0&&!Array.isArray(r.mcpServers))}function vvt(i,r,n,o="builtin"){return{id:`${o}-${i}`,name:i,description:r,systemPrompt:n,source:o,permissionMode:"default",isActive:!0,rawFrontmatter:{name:i,description:r}}}function SD(i){if(!(!i||i.trim()===""))return i.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function xvt(i){if(!(!i||i.length===0))return i.join(", ")}function Ame(i){return Eq.indexOf(i)}function wvt(i,r){return Ame(i.source)-Ame(r.source)}var Eq,kme=Lt(()=>{"use strict";Eq=["builtin","user","cli","project"]});function dxr(){return{totalUsageTimeMs:0,lastRatingShownAt:null,lastRatingSubmittedAt:null,totalRatingsSubmitted:0,totalSessions:0,firstUsedAt:new Date().toISOString(),lastActivityAt:null}}function pxr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r.totalUsageTimeMs=="number"&&(r.lastRatingShownAt===null||typeof r.lastRatingShownAt=="string")&&(r.lastRatingSubmittedAt===null||typeof r.lastRatingSubmittedAt=="string")&&typeof r.totalRatingsSubmitted=="number"&&typeof r.totalSessions=="number"&&typeof r.firstUsedAt=="string"&&(r.lastActivityAt===null||typeof r.lastActivityAt=="string")}var uxr,Svt=Lt(()=>{"use strict";uxr={usageTimeThresholdMs:12e4,cooldownPeriodMs:864e5,activityWindowMs:12e4,cooldownMultiplier:1.5,maxCooldownPeriodMs:6048e5}});function Gme(i){return typeof i=="string"&&Evt.includes(i)}function fxr(i){return typeof i=="string"&&["personal","project"].includes(i)}function mxr(i){if(typeof i!="object"||i===null)return!1;let r=i;return!(r.description!==void 0&&typeof r.description!="string"||r.enabled!==void 0&&typeof r.enabled!="boolean"||r.tools!==void 0&&!Array.isArray(r.tools)||r.match!==void 0&&typeof r.match!="object"||r.timeout!==void 0&&typeof r.timeout!="number")}function bMe(i){return Cme.indexOf(i)}function _xr(i,r){return bMe(i.source)-bMe(r.source)}var Evt,Cme,vMe=Lt(()=>{"use strict";Evt=["PreToolUse","PostToolUse","UserPromptSubmit","Notification","Stop"],Cme=["personal","project"]});function nZ(i){if(!i||typeof i!="object")return!1;let r=i;return typeof r.version=="string"&&typeof r.id=="string"&&typeof r.sessionId=="string"&&typeof r.projectPath=="string"&&typeof r.startedAt=="string"&&typeof r.endedAt=="string"&&typeof r.messageCount=="number"&&typeof r.summary=="string"&&Array.isArray(r.messages)&&Array.isArray(r.topics)&&(Array.isArray(r.operations)||Array.isArray(r.toolsUsed)&&Array.isArray(r.filesModified)&&Array.isArray(r.filesRead))}var xMe,wMe=Lt(()=>{"use strict";xMe="1.0"});var AMe,kvt=Lt(()=>{"use strict";AMe=class i extends Error{scope;provider;model;limitValue;currentUsage;resetAt;constructor(r){let o=new Date(r.resetAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),l=r.scope==="model"?`model "${r.model}"`:`provider "${r.provider}"`;super(`Daily token limit exceeded for ${l}. Used ${r.currentUsage.toLocaleString()} / ${r.limitValue.toLocaleString()} tokens. Resets at ${o}.`),this.name="TokenLimitExceededError",this.scope=r.scope,this.provider=r.provider,this.model=r.model,this.limitValue=r.limitValue,this.currentUsage=r.currentUsage,this.resetAt=r.resetAt,Object.setPrototypeOf(this,i.prototype)}}});var kq,ED,kH,Tme,SMe,Cq,EMe,kMe,hxr,CH,CMe,gxr,GMe,TMe,NMe,FMe,RMe,WMe,Gq,ZMe,iZ,Nme,kD,sZ,Cvt,fC,VMe,PMe,yxr,Ixr,aZ,bxr,Fme,vxr,xxr,wxr,Axr,Sxr,Exr,Gvt,Tq,GH,Tvt,DMe,Rme,Nq,Wme,Nvt,Fvt,Fq,kxr,MMe,YMe,Rq,Cxr,Gxr,Txr,Nxr,Vw,pC,OMe,Bv,Fxr,Rxr,Wxr,Zxr,Vxr,Pxr,vN,xN,jv,Zme,Dxr,Mxr,Yxr,Oxr,Hxr,HMe,JMe,Jxr,Vd=Lt(()=>{"use strict";kq=".compass",ED=".compass",kH="config.json",Tme="session.json",SMe="consent.json",Cq="credentials.enc",EMe="logs",kMe="backups",hxr="cache",CH="saved-sessions",CMe="index",gxr="context",GMe="temp",TMe="commands",NMe="agents",FMe="skills",RMe="hooks",WMe="rules",Gq="projects",ZMe="memory",iZ="NOVA.md",Nme="NOVA.local.md",kD="MEMORY.md",sZ=200,Cvt="chats",fC=16384,VMe=2e5,PMe=8e4,yxr=80,Ixr=10,aZ={anthropic:"haiku",ollama:"glm-4.7:cloud",zai:"glm-4.7:cloud",minimax:"glm-4.7:cloud"},bxr="haiku",Fme=200,vxr=75,xxr=5,wxr=0,Axr=80,Sxr=!0,Exr=3,Gvt=30,Tq=1,GH=100,Tvt=7,DMe=365,Rme=6e4,Nq=12e4,Wme=6e5,Nvt=50,Fvt=1024*1024,Fq=100,kxr=15,MMe=8e3,YMe=4e4,Rq=4e3,Cxr=6e3,Gxr=90,Txr=1e5,Nxr=500*1024*1024,Vw="claude-sonnet-4-5-20250929",pC=.4,OMe="haiku",Bv="verbose_analyst",Fxr=4,Rxr="banner",Wxr=4,Zxr=1e3,Vxr=16e3,Pxr=.1,vN={anthropic:{model:Vw,maxTokens:16384,temperature:pC},ollama:{model:"glm-4.7:cloud",endpoint:"https://ollama.com",maxTokens:16384,temperature:pC},project:{rootDir:process.cwd(),ignorePatterns:["node_modules/**",".git/**","dist/**","build/**","out/**","coverage/**",".next/**",".nuxt/**",".output/**","*.log",".env*","*.lock","package-lock.json","yarn.lock","pnpm-lock.yaml",".DS_Store","Thumbs.db","*.min.js","*.min.css","*.map",".compass/**"],includePatterns:["**/*"],maxFileSize:Fvt,indexOnStartup:!0},safety:{requireApproval:!0,autoApprovePatterns:[],blockedPatterns:[".env*","*.key","*.pem","*.p12","*.pfx","secrets/**","**/secrets/**","**/*.secret","**/credentials*","**/password*"],maxFilesPerOperation:Nvt,backupBeforeModify:!0,shellCommandTimeout:Nq,allowedShellCommands:["npm","npx","yarn","pnpm","git","node","tsc","eslint","prettier","jest","vitest","mocha","cargo","rustc","go","python","python3","pip","pip3","poetry","make","cmake","gradle","mvn","docker","kubectl","terraform","aws","gcloud","az","cat","ls","pwd","echo","head","tail","grep","find","wc","sort","uniq","diff","tree"],blockedShellCommands:["rm -rf /","rm -rf /*","rm -rf ~","rm -rf ~/*","sudo rm -rf",":(){:|:&};:","mkfs","dd if=/dev/zero","dd if=/dev/random","> /dev/sda","chmod -R 777 /","chown -R","wget | sh","curl | sh","wget | bash","curl | bash"]},ui:{},session:{autoSave:!0,autoSaveInterval:Rme,maxHistoryLength:Fq,autoCompactThreshold:8e4,sessionExpiryDays:Gvt,unleash:!1},update:{checkOnStartup:!0,checkInterval:Fxr,showNotifications:!0,notificationStyle:Rxr,includePrerelease:!1},agentic:{maxIterations:Fme,costWarningThreshold:xxr,costHardCap:wxr,autoCompactAtPercent:Axr,stuckDetectionEnabled:Sxr,stuckDetectionThreshold:Exr,maxIterationsPerTask:vxr}},xN=["anthropic","ollama","zai","minimax"],jv={API_KEY:"ANTHROPIC_API_KEY",COMPASS_API_KEY:"COMPASS_API_KEY",OLLAMA_API_KEY:"OLLAMA_API_KEY",ZAI_API_KEY:"ZAI_API_KEY",MINIMAX_API_KEY:"MINIMAX_API_KEY",MODEL:"COMPASS_MODEL",CONFIG_PATH:"COMPASS_CONFIG",DEBUG:"COMPASS_DEBUG",NO_COLOR:"NO_COLOR",FORCE_COLOR:"FORCE_COLOR",HOME:"HOME",USERPROFILE:"USERPROFILE"},Zme={anthropic:jv.API_KEY,ollama:jv.OLLAMA_API_KEY,zai:jv.ZAI_API_KEY,minimax:jv.MINIMAX_API_KEY},Dxr="1.0.65",Mxr="Compass CLI",Yxr="",Oxr="1.0.0",Hxr={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".kt":"kotlin",".scala":"scala",".cs":"csharp",".fs":"fsharp",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".c":"c",".h":"c",".hpp":"cpp",".swift":"swift",".php":"php",".pl":"perl",".pm":"perl",".sh":"bash",".bash":"bash",".zsh":"zsh",".fish":"fish",".ps1":"powershell",".sql":"sql",".r":"r",".R":"r",".lua":"lua",".vim":"vim",".el":"elisp",".clj":"clojure",".cljs":"clojure",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hrl":"erlang",".hs":"haskell",".ml":"ocaml",".mli":"ocaml",".nim":"nim",".zig":"zig",".v":"v",".d":"d",".dart":"dart",".groovy":"groovy",".gradle":"groovy",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".xml":"xml",".html":"html",".htm":"html",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".md":"markdown",".mdx":"markdown",".rst":"restructuredtext",".tex":"latex",".dockerfile":"dockerfile",".tf":"terraform",".hcl":"hcl",".proto":"protobuf",".graphql":"graphql",".gql":"graphql",".vue":"vue",".svelte":"svelte",".astro":"astro"},HMe=["package-lock.json","yarn.lock","pnpm-lock.yaml","composer.lock","Gemfile.lock","poetry.lock","Cargo.lock","go.sum","*.map","*.js.map","*.css.map","*.min.js","*.min.css","*.bundle.js","*.chunk.js","*.sql","*.csv","**/__snapshots__/**","**/fixtures/**/*.json","*.d.ts.map"],JMe=["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".output",".cache",".parcel-cache","vendor","__pycache__",".pytest_cache","target","bin","obj"],Jxr=[".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".svg",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".bin",".dat",".db",".sqlite",".sqlite3",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".wav",".avi",".mov",".mkv",".webm",".flv",".class",".jar",".war",".ear",".pyc",".pyo",".o",".obj",".a",".lib"]});var CD,Rvt,Vme=Lt(()=>{"use strict";hvt();yMe();EH();yvt();Sq();kme();Svt();vMe();wMe();kvt();Vd();CD="BASIC",Rvt=["BASIC","PRO","MAX","ENTERPRISE","UNLIMITED"]});var LMe={};LS(LMe,{CLAUDE_MODELS:()=>Pw,MODEL_ALIASES:()=>Wq,NO_SUBSCRIPTION_DAILY_TOKEN_LIMIT:()=>Wvt,calculateModelCost:()=>Hvt,compareModels:()=>Jvt,getAvailableAliases:()=>Dvt,getAvailableModelIds:()=>Pvt,getAvailableModels:()=>oZ,getCheapestModel:()=>Xvt,getDefaultModel:()=>Yvt,getDefaultModelId:()=>Ovt,getModelConfig:()=>a_,getModelDescription:()=>Pme,getModelTier:()=>Qvt,getModelsByCapability:()=>Lvt,getMostCapableModel:()=>Uvt,hasFullAccess:()=>Zvt,isAnthropicModel:()=>Vvt,isValidModel:()=>Mvt,resolveModelId:()=>_y});function Zvt(i){return i==="trial"||i==="active"}function _y(i){let r=i.toLowerCase();if(Wq[r])return Wq[r];for(let n of Object.keys(Pw))if(n.toLowerCase()===r)return n;return i}function a_(i){let r=_y(i);return Pw[r]}function Vvt(i){return a_(i)?.provider==="anthropic"}function oZ(){return Object.values(Pw)}function Pvt(){return Object.keys(Pw)}function Dvt(){return Object.keys(Wq)}function Mvt(i){return _y(i)in Pw}function Yvt(){return Pw["claude-sonnet-4-5-20250929"]}function Ovt(){return"claude-sonnet-4-5-20250929"}function Hvt(i,r,n){let o=a_(i);if(!o)return null;let l=r/1e6*o.pricing.inputPricePerMillion,f=n/1e6*o.pricing.outputPricePerMillion;return l+f}function Jvt(i,r,n){let o=a_(i),l=a_(r);if(!o||!l)return 0;switch(n){case"price":return o.pricing.inputPricePerMillion-l.pricing.inputPricePerMillion;case"context":return l.contextWindow-o.contextWindow;case"speed":return l.pricing.inputPricePerMillion-o.pricing.inputPricePerMillion;default:return 0}}function Lvt(i){return oZ().filter(r=>r.capabilities[i])}function Xvt(){return oZ().reduce((r,n)=>n.pricing.inputPricePerMillion<r.pricing.inputPricePerMillion?n:r)}function Uvt(){return Pw["claude-opus-4-6"]}function Qvt(i){let r=_y(i);if(r.includes("haiku"))return"economy";if(r.includes("sonnet"))return"balanced";if(r.includes("opus"))return"premium"}function Pme(i){let r=_y(i);if(r.includes("opus"))return"Most capable model - best for complex reasoning, analysis, and extended thinking";if(r.includes("sonnet"))return"Balanced performance and cost - ideal for most coding tasks";if(r.includes("haiku"))return"Fastest and most economical - great for quick responses and simple tasks";if(r.includes("glm-4.7"))return"OpenSource"}var Wvt,Pw,Wq,XS=Lt(()=>{"use strict";Wvt=15e4;Pw={"glm-5:cloud":{id:"glm-5:cloud",name:"Z.AI GLM 5",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}},"glm-4.7:cloud":{id:"glm-4.7:cloud",name:"Z.AI GLM 4.7",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}},"minimax-m2.5:cloud":{id:"minimax-m2.5:cloud",name:"MiniMax M2.5",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!1}},"kimi-k2.5:cloud":{id:"kimi-k2.5:cloud",name:"Kimi K2.5",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!1}},"gemini-3-pro-preview":{id:"gemini-3-pro-preview",name:"Gemini 3 Pro",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}},"claude-sonnet-4-6":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15,cacheWrite5mPricePerMillion:3.75,cacheWrite1hPricePerMillion:6,cacheHitPricePerMillion:.3},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}},"claude-sonnet-4-5-20250929":{id:"claude-sonnet-4-5-20250929",name:"Claude Sonnet 4.5",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:3,outputPricePerMillion:15,cacheWrite5mPricePerMillion:3.75,cacheWrite1hPricePerMillion:6,cacheHitPricePerMillion:.3},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}},"claude-opus-4-6":{id:"claude-opus-4-6",name:"Claude Opus 4.6",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:5,outputPricePerMillion:25,cacheWrite5mPricePerMillion:6.25,cacheWrite1hPricePerMillion:10,cacheHitPricePerMillion:.5},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!0,complexityClassification:!0}},"claude-opus-4-5-20251101":{id:"claude-opus-4-5-20251101",name:"Claude Opus 4.5",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:5,outputPricePerMillion:25,cacheWrite5mPricePerMillion:6.25,cacheWrite1hPricePerMillion:10,cacheHitPricePerMillion:.5},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!0,complexityClassification:!0}},"claude-haiku-4-5-20251001":{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:8192,pricing:{inputPricePerMillion:1,outputPricePerMillion:5,cacheWrite5mPricePerMillion:1.25,cacheWrite1hPricePerMillion:2,cacheHitPricePerMillion:.1},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0}}},Wq={sonnet:"claude-sonnet-4-6",opus:"claude-opus-4-6","sonnet-4.6":"claude-sonnet-4-6",sonnet46:"claude-sonnet-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929",sonnet45:"claude-sonnet-4-5-20250929","opus-4.6":"claude-opus-4-6",opus46:"claude-opus-4-6","opus-4.5":"claude-opus-4-5-20251101",opus45:"claude-opus-4-5-20251101",haiku:"claude-haiku-4-5-20251001","glm-5":"glm-5:cloud","glm-4.7":"glm-4.7:cloud","minimax-m2.5":"minimax-m2.5:cloud","kimi-k2.5":"kimi-k2.5:cloud","gemini-3-pro":"gemini-3-pro-preview",fast:"claude-haiku-4-5-20251001",quick:"claude-haiku-4-5-20251001",smart:"claude-sonnet-4-5-20250929",balanced:"claude-sonnet-4-5-20250929",powerful:"claude-opus-4-6",best:"claude-opus-4-6",beyond:"glm-5:cloud",robust:"glm-4.7:cloud",deep:"kimi-k2.5:cloud",versatile:"minimax-m2.5:cloud",creative:"gemini-3-pro-preview",s:"claude-sonnet-4-5-20250929",o:"claude-opus-4-6",h:"claude-haiku-4-5-20251001",g:"glm-5:cloud",m:"minimax-m2.5:cloud",k:"kimi-k2.5:cloud",p:"gemini-3-pro-preview"}});function Lxr(){let i=new Map;for(let r of TH){let n=i.get(r.category)||[];n.push(r),i.set(r.category,n)}return i}var Zq,XMe,UMe,TH,QMe=Lt(()=>{"use strict";Zq={network:{label:"Network Tools",priority:1},media:{label:"Media Tools",priority:2},development:{label:"Development Tools",priority:3},compression:{label:"Compression Tools",priority:4},text:{label:"Text Processing Tools",priority:5},file:{label:"File Tools",priority:6},system:{label:"System Tools",priority:7}},XMe=36e5,UMe=3e3,TH=[{command:"curl",name:"cURL",category:"network",description:"Transfer data with URLs",decisionRule:"Use for downloading files, making HTTP requests, testing APIs",useCases:["curl -O https://example.com/file.zip",'curl -X POST -d "data" https://api.example.com',"curl -I https://example.com (headers only)"]},{command:"wget",name:"wget",category:"network",description:"Non-interactive network downloader",decisionRule:"Use for downloading files, especially recursive downloads",useCases:["wget https://example.com/file.zip","wget -r https://example.com/docs/","wget -c https://example.com/large.zip (resume)"]},{command:"ssh",name:"SSH",category:"network",description:"Secure shell remote login",decisionRule:"Use for remote server access and secure connections",useCases:["ssh user@host","ssh -L 8080:localhost:80 user@host (tunnel)"]},{command:"ping",name:"Ping",category:"network",description:"Test network connectivity",decisionRule:"Use to check if a host is reachable",useCases:["ping example.com","ping -c 4 example.com (4 packets)"]},{command:"nslookup",name:"nslookup",category:"network",description:"Query DNS records",decisionRule:"Use for DNS lookups and troubleshooting",useCases:["nslookup example.com","nslookup -type=MX example.com"]},{command:"dig",name:"dig",category:"network",description:"DNS lookup utility",decisionRule:"Use for detailed DNS queries",useCases:["dig example.com","dig +short example.com","dig example.com MX"]},{command:"netstat",name:"netstat",category:"network",description:"Network statistics",decisionRule:"Use to view network connections and listening ports",useCases:["netstat -an (all connections)","netstat -tlnp (listening TCP ports)"]},{command:"ffmpeg",name:"FFmpeg",category:"media",description:"Audio/video conversion and processing",decisionRule:"Use for any audio/video conversion, extraction, or manipulation",useCases:["ffmpeg -i input.mp4 output.mp3 (extract audio)","ffmpeg -i input.mp4 -vn -acodec copy output.aac","ffmpeg -i input.mp4 -ss 00:01:00 -t 30 clip.mp4 (trim)"]},{command:"convert",name:"ImageMagick",category:"media",description:"Image conversion and manipulation",decisionRule:"Use for image format conversion, resizing, effects",useCases:["convert input.png output.jpg","convert input.png -resize 50% output.png","convert *.png output.pdf (combine to PDF)"]},{command:"yt-dlp",name:"yt-dlp",category:"media",description:"Video/audio downloader",decisionRule:"Use for downloading videos from YouTube and other sites",useCases:["yt-dlp https://youtube.com/watch?v=...","yt-dlp -x --audio-format mp3 URL (audio only)"]},{command:"git",name:"Git",category:"development",description:"Version control system",decisionRule:"Use for all version control operations",useCases:["git status","git diff","git log --oneline -10"]},{command:"node",name:"Node.js",category:"development",description:"JavaScript runtime",decisionRule:"Use for running JavaScript files or REPL",useCases:["node script.js",'node -e "console.log(1+1)"']},{command:"npm",name:"npm",category:"development",description:"Node.js package manager",decisionRule:"Use for JavaScript package management",useCases:["npm install package","npm run script","npm init -y"]},{command:"python",name:"Python",category:"development",description:"Python interpreter",decisionRule:"Use for running Python scripts or quick computations",useCases:["python script.py",'python -c "print(2**10)"']},{command:"pip",name:"pip",category:"development",description:"Python package manager",decisionRule:"Use for Python package installation",useCases:["pip install package","pip list","pip freeze > requirements.txt"]},{command:"docker",name:"Docker",category:"development",description:"Container platform",decisionRule:"Use for container operations",useCases:["docker ps","docker run -it ubuntu bash","docker build -t myapp ."]},{command:"code",name:"VS Code",category:"development",description:"Visual Studio Code editor",decisionRule:"Use to open files/folders in VS Code",useCases:["code .","code file.js"]},{command:"jq",name:"jq",category:"development",description:"JSON processor",decisionRule:"Use for parsing, filtering, and transforming JSON",useCases:["cat data.json | jq '.field'","jq '.items[] | .name' data.json","curl api.example.com | jq '.'"]},{command:"7z",name:"7-Zip",category:"compression",description:"High compression archiver",decisionRule:"Use for creating/extracting archives, especially 7z format",useCases:["7z x archive.7z","7z a archive.7z folder/"]},{command:"tar",name:"tar",category:"compression",description:"Archive utility",decisionRule:"Use for tar archives, common on Unix systems",useCases:["tar -xzf archive.tar.gz","tar -czf archive.tar.gz folder/","tar -tvf archive.tar (list contents)"]},{command:"zip",name:"zip",category:"compression",description:"Compress files into ZIP format",decisionRule:"Use for creating ZIP archives",useCases:["zip archive.zip file1 file2","zip -r archive.zip folder/"]},{command:"unzip",name:"unzip",category:"compression",description:"Extract ZIP archives",decisionRule:"Use for extracting ZIP files",useCases:["unzip archive.zip","unzip -l archive.zip (list contents)","unzip archive.zip -d destination/"]},{command:"gzip",name:"gzip",category:"compression",description:"GNU compression utility",decisionRule:"Use for gzip compression/decompression",useCases:["gzip file","gzip -d file.gz","gzip -k file (keep original)"]},{command:"grep",name:"grep",category:"text",description:"Search text patterns",decisionRule:"Use for searching patterns in files",useCases:['grep "pattern" file','grep -r "pattern" folder/','grep -i "pattern" file (case insensitive)']},{command:"sed",name:"sed",category:"text",description:"Stream editor",decisionRule:"Use for text transformations and substitutions",useCases:["sed 's/old/new/g' file","sed -i 's/old/new/g' file (in-place)"]},{command:"awk",name:"awk",category:"text",description:"Pattern scanning and processing",decisionRule:"Use for column-based text processing",useCases:["awk '{print $1}' file","awk -F: '{print $1}' /etc/passwd"]},{command:"find",name:"find",category:"file",description:"Search for files",decisionRule:"Use for finding files by name, type, date, etc.",useCases:['find . -name "*.js"',"find . -type f -mtime -7 (modified last 7 days)"]},{command:"rsync",name:"rsync",category:"file",description:"Fast file synchronization",decisionRule:"Use for copying/syncing files with progress and resume",useCases:["rsync -av source/ dest/","rsync -avz source/ user@host:dest/"]},{command:"pandoc",name:"Pandoc",category:"system",description:"Universal document converter",decisionRule:"Use for converting between document formats",useCases:["pandoc input.md -o output.pdf","pandoc input.docx -o output.html"]},{command:"htop",name:"htop",category:"system",description:"Interactive process viewer",decisionRule:"Use for monitoring system resources",useCases:["htop"]},{command:"btop",name:"btop",category:"system",description:"Resource monitor",decisionRule:"Use for monitoring system resources with better UI",useCases:["btop"]},{command:"lsof",name:"lsof",category:"system",description:"List open files",decisionRule:"Use to find which process is using a file or port",useCases:["lsof -i :8080 (what is using port 8080)","lsof /path/to/file"]}]});var jMe,Dme,Vq,BMe,Pq,Mme,Yme,wN,Dq=Lt(()=>{"use strict";jMe="Schedule.md",Dme="sched-",Vq=8,BMe=["active","paused","completed"],Pq=`# Scheduled Tasks
|
|
2
2
|
|
|
3
3
|
> Managed by Nova. Each task below runs on a cron schedule.
|
|
4
4
|
> Edit manually or use the schedule tools to manage tasks.
|
|
@@ -2352,7 +2352,8 @@ Note: The search text may have trailing whitespace or CRLF line endings that don
|
|
|
2352
2352
|
</div>
|
|
2353
2353
|
</body>
|
|
2354
2354
|
</html>
|
|
2355
|
-
`),this.pendingAuths.set(`code:${b.serverName}`,{...b,state:l}),re.info(`OAuth callback received for ${b.serverName}`)}catch(o){re.error("Error handling OAuth callback:",o),n.writeHead(500),n.end("Internal server error")}}async completeAuthFlow(r,n){let o=`code:${r}`,l=this.pendingAuths.get(o);if(!l)return{success:!1,error:"No pending OAuth flow for this server"};let f=l.state,h=l.codeVerifier;if(this.pendingAuths.delete(o),!n.tokenUrl)return{success:!1,error:"OAuth configuration incomplete: missing tokenUrl"};try{let b=new RXe;b.set("grant_type","authorization_code"),b.set("client_id",n.clientId||""),b.set("code",f),b.set("redirect_uri",this.getRedirectUri()),b.set("code_verifier",h),n.clientSecret&&b.set("client_secret",n.clientSecret);let E=await fetch(n.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:b.toString()});if(!E.ok){let H=await E.text();return{success:!1,error:`Token exchange failed: ${E.status} ${H}`}}let N=await E.json(),W={accessToken:N.access_token,tokenType:N.token_type||"Bearer",refreshToken:N.refresh_token,expiresAt:N.expires_in?new Date(Date.now()+N.expires_in*1e3):void 0,scopes:N.scope?.split(" ")};return this.storage.tokens[r]=W,await this.save(),re.info(`OAuth flow completed for ${r}`),{success:!0}}catch(b){let E=b instanceof Error?b.message:String(b);return re.error(`Failed to complete OAuth flow for ${r}:`,b),{success:!1,error:E}}}async refreshTokens(r,n){let o=this.storage.tokens[r];if(!o?.refreshToken)return{success:!1,error:"No refresh token available"};if(!n.tokenUrl)return{success:!1,error:"OAuth configuration incomplete: missing tokenUrl"};try{let l=new RXe;l.set("grant_type","refresh_token"),l.set("client_id",n.clientId||""),l.set("refresh_token",o.refreshToken),n.clientSecret&&l.set("client_secret",n.clientSecret);let f=await fetch(n.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!f.ok){let b=await f.text();return{success:!1,error:`Token refresh failed: ${f.status} ${b}`}}let h=await f.json();return this.storage.tokens[r]={accessToken:h.access_token,tokenType:h.token_type||"Bearer",refreshToken:h.refresh_token||o.refreshToken,expiresAt:h.expires_in?new Date(Date.now()+h.expires_in*1e3):void 0,scopes:h.scope?.split(" ")||o.scopes},await this.save(),re.debug(`Tokens refreshed for ${r}`),{success:!0}}catch(l){let f=l instanceof Error?l.message:String(l);return re.error(`Failed to refresh tokens for ${r}:`,l),{success:!1,error:f}}}async clearAuth(r){delete this.storage.tokens[r],this.storage.apiTokens&&delete this.storage.apiTokens[r],await this.save(),re.info(`Cleared authentication for ${r}`)}async setApiToken(r,n){this.storage.apiTokens||(this.storage.apiTokens={}),this.storage.apiTokens[r]=n,await this.save(),re.info(`Stored API token for ${r}`)}getApiToken(r){return this.storage.apiTokens?.[r]}hasStoredAuth(r){let n=!!this.storage.tokens[r]&&this.isTokenValid(this.storage.tokens[r]),o=!!this.storage.apiTokens?.[r];return n||o}getRedirectUri(){return`http://127.0.0.1:${this.callbackPort}/oauth/callback`}generateCodeVerifier(){return WXe(32).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}generateCodeChallenge(r){return x8r("sha256").update(r).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}getAuthHeader(r){re.debug(`getAuthHeader called for server: ${r}`),re.debug(`Available token keys: ${Object.keys(this.storage.tokens||{}).join(", ")||"none"}`),re.debug(`Available API token keys: ${Object.keys(this.storage.apiTokens||{}).join(", ")||"none"}`);let n=this.storage.tokens[r];if(n&&(re.debug(`Found OAuth token for ${r}, valid: ${this.isTokenValid(n)}`),this.isTokenValid(n))){let l=n.tokenType?.toLowerCase()==="bearer"?"Bearer":n.tokenType;return re.debug(`Returning OAuth auth header for ${r} with tokenType: ${l}`),`${l} ${n.accessToken}`}let o=this.storage.apiTokens?.[r];if(o)return re.debug(`Returning API token auth header for ${r}`),`Bearer ${o}`;re.debug(`No auth header found for ${r}`)}async discoverOAuthConfig(r){let o=new Mee(r).origin,l=[`${o}/.well-known/oauth-authorization-server`,`${o}/.well-known/openid-configuration`];for(let f of l)try{re.debug(`Trying OAuth discovery at: ${f}`);let h=await fetch(f,{method:"GET",headers:{Accept:"application/json"}});if(h.ok){let b=await h.json();if(re.debug(`OAuth discovery response from ${f}: ${JSON.stringify(b)}`),b.authorization_endpoint&&b.token_endpoint)return re.info(`Discovered OAuth config from ${f}`),{authorizationUrl:b.authorization_endpoint,tokenUrl:b.token_endpoint,scopes:b.scopes_supported}}}catch(h){re.debug(`OAuth discovery failed at ${f}:`,h)}return null}async startAuthFlowWithDiscovery(r,n,o){let l=A8r(n);l&&re.info(`Using built-in Kore-CLI OAuth credentials for ${r}`);let f=o;if(f?.authorizationUrl)f={clientId:l?.clientId,clientSecret:l?.clientSecret,...o};else{re.info(`Discovering OAuth endpoints for ${r}...`);let b=await this.discoverOAuthConfig(n);if(b)f={clientId:l?.clientId,clientSecret:l?.clientSecret,authorizationUrl:b.authorizationUrl,tokenUrl:b.tokenUrl,scopes:b.scopes,...o},re.debug(`Merged OAuth config: authUrl=${f.authorizationUrl}, scopes=${f.scopes?.join(",")}`),re.info(`Using discovered OAuth config for ${r}`);else if(l?.clientId)f={...l,...o},re.debug(`Using hardcoded OAuth config for ${r}`);else return{authUrl:"",error:"Could not discover OAuth configuration. Server may require manual token authentication."}}if(!f.authorizationUrl)return{authUrl:"",error:"OAuth configuration incomplete: missing authorizationUrl"};let h=f.clientId||"compass-cli";try{await this.startCallbackServer();let b=this.generateCodeVerifier(),E=this.generateCodeChallenge(b),N=WXe(16).toString("hex");this.pendingAuths.set(N,{serverName:r,state:N,codeVerifier:b,createdAt:new Date});let W=new Mee(f.authorizationUrl);return W.searchParams.set("client_id",h),W.searchParams.set("response_type","code"),W.searchParams.set("redirect_uri",this.getRedirectUri()),W.searchParams.set("state",N),W.searchParams.set("code_challenge",E),W.searchParams.set("code_challenge_method","S256"),f.scopes?.length&&W.searchParams.set("scope",f.scopes.join(" ")),re.info(`Starting OAuth flow for ${r}`),{authUrl:W.toString(),discoveredConfig:f}}catch(b){let E=b instanceof Error?b.message:String(b);return re.error(`Failed to start OAuth flow for ${r}:`,b),{authUrl:"",error:E}}}async completeAuthFlowWithConfig(r,n){let o=`code:${r}`,l=this.pendingAuths.get(o);if(!l)return{success:!1,error:"No pending OAuth flow for this server"};let f=l.state,h=l.codeVerifier;if(this.pendingAuths.delete(o),!n.tokenUrl)return{success:!1,error:"OAuth configuration incomplete: missing tokenUrl"};let b=n.clientId||"compass-cli";try{let E=new RXe;E.set("grant_type","authorization_code"),E.set("code",f),E.set("redirect_uri",this.getRedirectUri()),E.set("code_verifier",h);let N={"Content-Type":"application/x-www-form-urlencoded"};if(n.clientId&&n.clientSecret){let q=Buffer.from(`${b}:${n.clientSecret}`).toString("base64");N.Authorization=`Basic ${q}`}else E.set("client_id",b),n.clientSecret&&E.set("client_secret",n.clientSecret);let W=await fetch(n.tokenUrl,{method:"POST",headers:N,body:E.toString()});if(!W.ok){let q=await W.text();return{success:!1,error:`Token exchange failed: ${W.status} ${q}`}}let H=await W.json(),M={accessToken:H.access_token,tokenType:H.token_type||"Bearer",refreshToken:H.refresh_token,expiresAt:H.expires_in?new Date(Date.now()+H.expires_in*1e3):void 0,scopes:H.scope?.split(" ")};return this.storage.tokens[r]=M,await this.save(),re.info(`OAuth flow completed for ${r}`),re.debug(`Stored token for ${r}, tokenType: ${M.tokenType}, hasAccessToken: ${!!M.accessToken}`),re.debug(`Current storage token keys: ${Object.keys(this.storage.tokens).join(", ")}`),{success:!0}}catch(E){let N=E instanceof Error?E.message:String(E);return re.error(`Failed to complete OAuth flow for ${r}:`,E),{success:!1,error:N}}}async stopCallbackServer(){if(this.callbackServer)return new Promise(r=>{this.callbackServer.close(()=>{this.callbackServer=null,re.debug("OAuth callback server stopped"),r()})})}cleanupPendingAuths(){let r=new Date,n=600*1e3;for(let[o,l]of this.pendingAuths)r.getTime()-l.createdAt.getTime()>n&&this.pendingAuths.delete(o)}getAuthenticatedServers(){return Object.keys(this.storage.tokens).filter(r=>this.isTokenValid(this.storage.tokens[r]))}},rIe=null});import{spawn as S8r}from"child_process";async function EPt(i,r){let n=i.timeout,o=r||n||parseInt(process.env.MCP_TIMEOUT||"")||xPt,l=aE(i);if(!i.type&&l.type&&re.debug(`Inferred transport type '${l.type}' for server '${l.name}' (missing 'type' field in config)`),W4(l))return E8r(l,o);if(Z4(l))return k8r(l,o);if(V4(l))return C8r(l,o);let f=l?.name||"unknown";throw new Error(`Unknown transport type for server: ${f}. Config must have 'type' field set to 'http', 'sse', or 'stdio', or have 'url' (for sse) or 'command' (for stdio) fields to infer the type.`)}async function E8r(i,r){re.debug(`Creating HTTP connection to ${i.name} at ${i.url}`);let o=(await nIe()).getAuthHeader(i.name),l={...i.headers,...o?{Authorization:o}:{}};re.debug(`HTTP connection headers for ${i.name}: Authorization=${o?"Bearer ***"+o.slice(-8):"none"}`);let f=new PXe(i.url,l,r,i.name),h="connecting",b;try{return await f.connect(),h="connected",re.info(`Connected to HTTP MCP server: ${i.name}`),{client:f,close:async()=>{await f.close()},status:h}}catch(E){if(E instanceof P4)throw E;return b=E instanceof Error?E.message:String(E),h="error",re.error(`Failed to connect to HTTP MCP server ${i.name}:`,E),{client:f,close:async()=>{try{await f.close()}catch{}},status:h,error:b}}}async function k8r(i,r){re.debug(`Creating SSE connection to ${i.name} at ${i.url}`);let n=new DXe(i.url,i.headers,r),o="connecting",l;try{return await n.connect(),o="connected",re.info(`Connected to SSE MCP server: ${i.name}`),{client:n,close:async()=>{await n.close()},status:o}}catch(f){return l=f instanceof Error?f.message:String(f),o="error",re.error(`Failed to connect to SSE MCP server ${i.name}:`,f),{client:n,close:async()=>{try{await n.close()}catch{}},status:o,error:l}}}async function C8r(i,r){re.debug(`Creating stdio connection to ${i.name} with command: ${i.command}`);let n=i.command==="npx"?Math.max(r,6e4):r;i.command==="npx"&&n>r&&re.debug("Using extended timeout (60s) for npx command - first run may download packages");let o=new MXe(i.command,i.args||[],i.cwd,i.env,n),l="connecting",f;try{return await Promise.race([o.connect(),new Promise((h,b)=>setTimeout(()=>b(new Error("Connection timeout")),n))]),l="connected",re.debug(`Connected to stdio MCP server: ${i.name}`),{client:o,close:async()=>{await o.close()},status:l}}catch(h){return f=h instanceof Error?h.message:String(h),l="error",re.error(`Failed to connect to stdio MCP server ${i.name}:`,h),{client:o,close:async()=>{try{await o.close()}catch{}},status:l,error:f}}}async function YXe(i){try{return(await i.listTools()).tools||[]}catch(r){return re.error("Failed to fetch MCP tools:",r),[]}}async function OXe(i){try{return(await i.listResources()).resources||[]}catch(r){return re.error("Failed to fetch MCP resources:",r),[]}}async function HXe(i){try{return(await i.listPrompts()).prompts||[]}catch(r){return re.error("Failed to fetch MCP prompts:",r),[]}}async function kPt(i){try{return i.getServerCapabilities()||{}}catch(r){return re.error("Failed to fetch MCP server capabilities:",r),{}}}async function CPt(i,r,n){try{return await i.callTool({name:r,arguments:n})}catch(o){let l=o instanceof Error?o.message:String(o);return re.error(`Failed to call MCP tool ${r}:`,o),{success:!1,error:l}}}async function GPt(i,r){try{return{content:(await i.readResource({uri:r})).contents||[]}}catch(n){let o=n instanceof Error?n.message:String(n);return re.error(`Failed to read MCP resource ${r}:`,n),{content:[],error:o}}}async function TPt(i,r,n){try{return{messages:(await i.getPrompt({name:r,arguments:n})).messages||[]}}catch(o){let l=o instanceof Error?o.message:String(o);return re.error(`Failed to get MCP prompt ${r}:`,o),{messages:[],error:l}}}var P4,PXe,DXe,MXe,NPt=Lt(()=>{"use strict";to();VXe();tIe();P4=class extends Error{serverName;serverUrl;constructor(r,n){super(`Authentication required for MCP server '${r}'`),this.name="AuthenticationRequiredError",this.serverName=r,this.serverUrl=n}},PXe=class{url;headers;connected=!1;capabilities={};requestTimeout;serverName;constructor(r,n={},o=3e4,l="unknown"){this.url=r,this.serverName=l,this.headers={"Content-Type":"application/json",...n},this.requestTimeout=o}async connect(){try{let r=new AbortController,n=setTimeout(()=>r.abort(),this.requestTimeout),o=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"compass-cli",version:"1.0.0"}}}),signal:r.signal});if(clearTimeout(n),o.ok){let l=await o.json();l.result?.capabilities&&(this.capabilities={tools:!!l.result.capabilities.tools,resources:!!l.result.capabilities.resources,prompts:!!l.result.capabilities.prompts,logging:!!l.result.capabilities.logging}),this.connected=!0}else if(o.status===401){let l=await o.text().catch(()=>""),f=o.headers.get("WWW-Authenticate")||"";throw re.debug(`401 response from ${this.serverName}: body=${l.slice(0,200)}, WWW-Authenticate=${f}`),new P4(this.serverName,this.url)}else throw new Error(`HTTP ${o.status}: ${o.statusText}`)}catch(r){if(r instanceof P4)throw r;if(r.name==="AbortError")throw new Error("Connection timeout");let n=r instanceof Error?r.message:String(r);throw new Error(`Failed to connect: ${n}`)}}async close(){this.connected=!1}async listTools(){if(!this.connected)return{tools:[]};try{let r=new AbortController,n=setTimeout(()=>r.abort(),this.requestTimeout),o=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:2,method:"tools/list",params:{}}),signal:r.signal});if(clearTimeout(n),o.ok)return{tools:(await o.json()).result?.tools||[]}}catch(r){re.warn("Failed to list tools:",r)}return{tools:[]}}async listResources(){if(!this.connected)return{resources:[]};try{let r=new AbortController,n=setTimeout(()=>r.abort(),this.requestTimeout),o=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:3,method:"resources/list",params:{}}),signal:r.signal});if(clearTimeout(n),o.ok)return{resources:(await o.json()).result?.resources||[]}}catch(r){re.warn("Failed to list resources:",r)}return{resources:[]}}async listPrompts(){if(!this.connected)return{prompts:[]};try{let r=new AbortController,n=setTimeout(()=>r.abort(),this.requestTimeout),o=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:4,method:"prompts/list",params:{}}),signal:r.signal});if(clearTimeout(n),o.ok)return{prompts:(await o.json()).result?.prompts||[]}}catch(r){re.warn("Failed to list prompts:",r)}return{prompts:[]}}async callTool(r){if(!this.connected)return{success:!1,error:"Not connected"};try{let n=new AbortController,o=setTimeout(()=>n.abort(),this.requestTimeout),l=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:5,method:"tools/call",params:{name:r.name,arguments:r.arguments}}),signal:n.signal});if(clearTimeout(o),l.ok){let f=await l.json();return f.error?{success:!1,error:f.error.message}:{success:!0,content:f.result?.content||[],isError:f.result?.isError}}return{success:!1,error:`HTTP ${l.status}`}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async readResource(r){if(!this.connected)return{contents:[]};try{let n=new AbortController,o=setTimeout(()=>n.abort(),this.requestTimeout),l=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:6,method:"resources/read",params:{uri:r.uri}}),signal:n.signal});if(clearTimeout(o),l.ok)return{contents:(await l.json()).result?.contents||[]}}catch(n){re.warn("Failed to read resource:",n)}return{contents:[]}}async getPrompt(r){if(!this.connected)return{messages:[]};try{let n=new AbortController,o=setTimeout(()=>n.abort(),this.requestTimeout),l=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:7,method:"prompts/get",params:r}),signal:n.signal});if(clearTimeout(o),l.ok)return{messages:((await l.json()).result?.messages||[]).map(b=>({role:b.role,content:typeof b.content=="string"?b.content:b.content.text||""}))}}catch(n){re.warn("Failed to get prompt:",n)}return{messages:[]}}getServerCapabilities(){return this.connected?this.capabilities:null}},DXe=class{sseUrl;headers;connected=!1;capabilities={};messageEndpoint=null;requestId=0;pendingRequests=new Map;abortController=null;connectionTimeout;constructor(r,n={},o=3e4){this.sseUrl=r,this.headers=n,this.connectionTimeout=o}async connect(){return new Promise((r,n)=>{let o=setTimeout(()=>{this.abortController?.abort(),n(new Error("SSE connection timeout"))},this.connectionTimeout);this.establishSseConnection().then(async()=>{clearTimeout(o);let l=setTimeout(()=>{n(new Error("Timeout waiting for endpoint event from SSE server"))},1e4),f=async()=>{if(this.messageEndpoint){clearTimeout(l);try{let h=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"compass-cli",version:"1.0.0"}});h.result?.capabilities&&(this.capabilities={tools:!!h.result.capabilities.tools,resources:!!h.result.capabilities.resources,prompts:!!h.result.capabilities.prompts,logging:!!h.result.capabilities.logging}),await this.sendNotification("notifications/initialized",{}),this.connected=!0,r()}catch(h){n(h)}}else setTimeout(f,100)};f()}).catch(l=>{clearTimeout(o),n(l)})})}async establishSseConnection(){this.abortController=new AbortController;try{let r=await fetch(this.sseUrl,{method:"GET",headers:{Accept:"text/event-stream","Cache-Control":"no-cache",...this.headers},signal:this.abortController.signal});if(!r.ok)throw new Error(`SSE connection failed: HTTP ${r.status} ${r.statusText}`);if(!r.body)throw new Error("SSE response has no body");this.readSseStream(r.body)}catch(r){throw r.name==="AbortError"?new Error("SSE connection aborted"):r}}async readSseStream(r){let n=r.getReader(),o=new TextDecoder,l="",f="",h="";try{for(;;){let{done:b,value:E}=await n.read();if(b){re.debug("SSE stream ended"),this.connected=!1;break}l+=o.decode(E,{stream:!0});let N=l.split(/\r?\n/);l=N.pop()||"";for(let W of N){let H=W.trim();H.startsWith("event:")?f=H.slice(6).trim():H.startsWith("data:")?h+=H.slice(5).trim():H===""&&(f||h)&&(this.handleSseEvent(f,h),f="",h="")}}}catch(b){b.name!=="AbortError"&&re.error("SSE stream error:",b),this.connected=!1;for(let[E,N]of this.pendingRequests)N.reject(new Error("SSE connection closed")),this.pendingRequests.delete(E)}}handleSseEvent(r,n){if(re.debug(`SSE event received: ${r||"message"}, data: ${n.substring(0,100)}...`),r==="endpoint")try{if(n.startsWith("http://")||n.startsWith("https://"))this.messageEndpoint=n;else{let o=new URL(this.sseUrl);this.messageEndpoint=new URL(n,o).toString()}re.debug(`SSE message endpoint set to: ${this.messageEndpoint}`)}catch(o){re.error("Failed to parse endpoint URL:",o)}else if((r==="message"||r==="")&&n)try{let o=JSON.parse(n);this.handleJsonRpcResponse(o)}catch{re.debug(`Failed to parse SSE message data: ${n}`)}}handleJsonRpcResponse(r){if(r.id!==void 0&&r.id!==null){let n=this.pendingRequests.get(r.id);n&&(this.pendingRequests.delete(r.id),n.resolve(r))}}async sendRequest(r,n){if(!this.messageEndpoint)throw new Error("Message endpoint not available - SSE connection may not be established");let o=++this.requestId,l={jsonrpc:"2.0",id:o,method:r,params:n};return new Promise((f,h)=>{this.pendingRequests.set(o,{resolve:f,reject:h});let b=setTimeout(()=>{this.pendingRequests.has(o)&&(this.pendingRequests.delete(o),h(new Error(`Request timeout: ${r}`)))},this.connectionTimeout);fetch(this.messageEndpoint,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(l)}).then(E=>{E.ok||(clearTimeout(b),this.pendingRequests.delete(o),h(new Error(`HTTP ${E.status}: ${E.statusText}`)))}).catch(E=>{clearTimeout(b),this.pendingRequests.delete(o),h(E)})})}async sendNotification(r,n){if(!this.messageEndpoint)return;let o={jsonrpc:"2.0",method:r,params:n};try{await fetch(this.messageEndpoint,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(o)})}catch(l){re.debug("Failed to send notification:",l)}}async close(){this.connected=!1,this.abortController?.abort(),this.abortController=null,this.messageEndpoint=null;for(let[r,n]of this.pendingRequests)n.reject(new Error("Client closed")),this.pendingRequests.delete(r)}async listTools(){if(!this.connected)return{tools:[]};try{return{tools:(await this.sendRequest("tools/list",{})).result?.tools||[]}}catch(r){return re.warn("Failed to list tools:",r),{tools:[]}}}async listResources(){if(!this.connected)return{resources:[]};try{return{resources:(await this.sendRequest("resources/list",{})).result?.resources||[]}}catch(r){return re.warn("Failed to list resources:",r),{resources:[]}}}async listPrompts(){if(!this.connected)return{prompts:[]};try{return{prompts:(await this.sendRequest("prompts/list",{})).result?.prompts||[]}}catch(r){return re.warn("Failed to list prompts:",r),{prompts:[]}}}async callTool(r){if(!this.connected)return{success:!1,error:"Not connected"};try{let n=await this.sendRequest("tools/call",{name:r.name,arguments:r.arguments});return n.error?{success:!1,error:n.error.message}:{success:!0,content:n.result?.content||[],isError:n.result?.isError}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async readResource(r){if(!this.connected)return{contents:[]};try{return{contents:(await this.sendRequest("resources/read",{uri:r.uri})).result?.contents||[]}}catch(n){return re.warn("Failed to read resource:",n),{contents:[]}}}async getPrompt(r){if(!this.connected)return{messages:[]};try{return{messages:((await this.sendRequest("prompts/get",r)).result?.messages||[]).map(l=>({role:l.role,content:typeof l.content=="string"?l.content:l.content.text||""}))}}catch(n){return re.warn("Failed to get prompt:",n),{messages:[]}}}getServerCapabilities(){return this.connected?this.capabilities:null}},MXe=class{constructor(r,n=[],o,l,f=3e4){this.command=r;this.args=n;this.cwd=o;this.env=l;this.requestTimeout=f}process=null;connected=!1;capabilities={};requestId=0;pendingRequests=new Map;buffer="";lastStderrError=null;async connect(){return new Promise((r,n)=>{let o=!1,l=h=>{o||(o=!0,n(h))},f=()=>{o||(o=!0,r())};try{let h={...process.env,...this.env};if(re.debug(`Spawning stdio MCP server: ${this.command} ${this.args.join(" ")}`),this.process=S8r(this.command,this.args,{cwd:this.cwd||process.cwd(),env:h,stdio:["pipe","pipe","pipe"],shell:!0}),!this.process.stdout||!this.process.stdin){l(new Error("Failed to create stdio streams"));return}this.process.stdout.on("data",b=>{this.handleStdoutData(b)}),this.process.stderr?.on("data",b=>{let E=b.toString().trim();if(E){if(re.debug(`[MCP Server stderr]: ${E}`),E.includes("EADDRINUSE")){let N=E.match(/port[:\s]*(\d+)|:(\d+)/i),W=N?.[1]||N?.[2]||"unknown";this.lastStderrError=`Port ${W} is already in use. A previous MCP server process may still be running. Try killing the process using this port or wait for it to terminate.`}else if(E.includes("ECONNREFUSED"))this.lastStderrError="Connection refused. The target server may not be running.";else if(E.includes("ETIMEDOUT")||E.includes("timeout"))this.lastStderrError="Connection timed out while trying to reach the server.";else if(E.includes("ENOTFOUND"))this.lastStderrError="Server hostname not found. Please check the URL.";else if(E.includes("Error:")&&!this.lastStderrError){let N=E.match(/Error:\s*(.+?)(?:\n|$)/);N&&(this.lastStderrError=N[1].trim())}}}),this.process.on("exit",(b,E)=>{re.debug(`MCP server process exited with code ${b}, signal ${E}`),this.connected=!1,this.process=null;let N;this.lastStderrError?(N=this.lastStderrError,re.error(`MCP server failed: ${N}`)):b!==0?N=`Process exited with code ${b}`:E?N=`Process terminated by signal ${E}`:N="Process exited unexpectedly";for(let[W,H]of this.pendingRequests)H.reject(new Error(N)),this.pendingRequests.delete(W);l(new Error(N))}),this.process.on("error",b=>{re.error("MCP server process error:",b),this.connected=!1,l(b)}),setTimeout(async()=>{if(!(!this.process||o))try{let b=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"compass-cli",version:"1.0.0"}});b.result?.capabilities&&(this.capabilities={tools:!!b.result.capabilities.tools,resources:!!b.result.capabilities.resources,prompts:!!b.result.capabilities.prompts,logging:!!b.result.capabilities.logging}),this.sendNotification("notifications/initialized",{}),this.connected=!0,re.debug(`Stdio MCP server connected: ${this.command}`),f()}catch(b){l(b instanceof Error?b:new Error(String(b)))}},100)}catch(h){l(h instanceof Error?h:new Error(String(h)))}})}handleStdoutData(r){this.buffer+=r.toString();let n;for(;(n=this.buffer.indexOf(`
|
|
2355
|
+
`),this.pendingAuths.set(`code:${b.serverName}`,{...b,state:l}),re.info(`OAuth callback received for ${b.serverName}`)}catch(o){re.error("Error handling OAuth callback:",o),n.writeHead(500),n.end("Internal server error")}}async completeAuthFlow(r,n){let o=`code:${r}`,l=this.pendingAuths.get(o);if(!l)return{success:!1,error:"No pending OAuth flow for this server"};let f=l.state,h=l.codeVerifier;if(this.pendingAuths.delete(o),!n.tokenUrl)return{success:!1,error:"OAuth configuration incomplete: missing tokenUrl"};try{let b=new RXe;b.set("grant_type","authorization_code"),b.set("client_id",n.clientId||""),b.set("code",f),b.set("redirect_uri",this.getRedirectUri()),b.set("code_verifier",h),n.clientSecret&&b.set("client_secret",n.clientSecret);let E=await fetch(n.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:b.toString()});if(!E.ok){let H=await E.text();return{success:!1,error:`Token exchange failed: ${E.status} ${H}`}}let N=await E.json(),W={accessToken:N.access_token,tokenType:N.token_type||"Bearer",refreshToken:N.refresh_token,expiresAt:N.expires_in?new Date(Date.now()+N.expires_in*1e3):void 0,scopes:N.scope?.split(" ")};return this.storage.tokens[r]=W,await this.save(),re.info(`OAuth flow completed for ${r}`),{success:!0}}catch(b){let E=b instanceof Error?b.message:String(b);return re.error(`Failed to complete OAuth flow for ${r}:`,b),{success:!1,error:E}}}async refreshTokens(r,n){let o=this.storage.tokens[r];if(!o?.refreshToken)return{success:!1,error:"No refresh token available"};if(!n.tokenUrl)return{success:!1,error:"OAuth configuration incomplete: missing tokenUrl"};try{let l=new RXe;l.set("grant_type","refresh_token"),l.set("client_id",n.clientId||""),l.set("refresh_token",o.refreshToken),n.clientSecret&&l.set("client_secret",n.clientSecret);let f=await fetch(n.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!f.ok){let b=await f.text();return{success:!1,error:`Token refresh failed: ${f.status} ${b}`}}let h=await f.json();return this.storage.tokens[r]={accessToken:h.access_token,tokenType:h.token_type||"Bearer",refreshToken:h.refresh_token||o.refreshToken,expiresAt:h.expires_in?new Date(Date.now()+h.expires_in*1e3):void 0,scopes:h.scope?.split(" ")||o.scopes},await this.save(),re.debug(`Tokens refreshed for ${r}`),{success:!0}}catch(l){let f=l instanceof Error?l.message:String(l);return re.error(`Failed to refresh tokens for ${r}:`,l),{success:!1,error:f}}}async clearAuth(r){delete this.storage.tokens[r],this.storage.apiTokens&&delete this.storage.apiTokens[r],await this.save(),re.info(`Cleared authentication for ${r}`)}async setApiToken(r,n){this.storage.apiTokens||(this.storage.apiTokens={}),this.storage.apiTokens[r]=n,await this.save(),re.info(`Stored API token for ${r}`)}getApiToken(r){return this.storage.apiTokens?.[r]}hasStoredAuth(r){let n=!!this.storage.tokens[r]&&this.isTokenValid(this.storage.tokens[r]),o=!!this.storage.apiTokens?.[r];return n||o}getRedirectUri(){return`http://127.0.0.1:${this.callbackPort}/oauth/callback`}generateCodeVerifier(){return WXe(32).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}generateCodeChallenge(r){return x8r("sha256").update(r).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}getAuthHeader(r){re.debug(`getAuthHeader called for server: ${r}`),re.debug(`Available token keys: ${Object.keys(this.storage.tokens||{}).join(", ")||"none"}`),re.debug(`Available API token keys: ${Object.keys(this.storage.apiTokens||{}).join(", ")||"none"}`);let n=this.storage.tokens[r];if(n&&(re.debug(`Found OAuth token for ${r}, valid: ${this.isTokenValid(n)}`),this.isTokenValid(n))){let l=n.tokenType?.toLowerCase()==="bearer"?"Bearer":n.tokenType;return re.debug(`Returning OAuth auth header for ${r} with tokenType: ${l}`),`${l} ${n.accessToken}`}let o=this.storage.apiTokens?.[r];if(o)return re.debug(`Returning API token auth header for ${r}`),`Bearer ${o}`;re.debug(`No auth header found for ${r}`)}async discoverOAuthConfig(r){let o=new Mee(r).origin,l=[`${o}/.well-known/oauth-authorization-server`,`${o}/.well-known/openid-configuration`];for(let f of l)try{re.debug(`Trying OAuth discovery at: ${f}`);let h=await fetch(f,{method:"GET",headers:{Accept:"application/json"}});if(h.ok){let b=await h.json();if(re.debug(`OAuth discovery response from ${f}: ${JSON.stringify(b)}`),b.authorization_endpoint&&b.token_endpoint)return re.info(`Discovered OAuth config from ${f}`),{authorizationUrl:b.authorization_endpoint,tokenUrl:b.token_endpoint,scopes:b.scopes_supported}}}catch(h){re.debug(`OAuth discovery failed at ${f}:`,h)}return null}async startAuthFlowWithDiscovery(r,n,o){let l=A8r(n);l&&re.info(`Using built-in Kore-CLI OAuth credentials for ${r}`);let f=o;if(f?.authorizationUrl)f={clientId:l?.clientId,clientSecret:l?.clientSecret,...o};else{re.info(`Discovering OAuth endpoints for ${r}...`);let b=await this.discoverOAuthConfig(n);if(b)f={clientId:l?.clientId,clientSecret:l?.clientSecret,authorizationUrl:b.authorizationUrl,tokenUrl:b.tokenUrl,scopes:b.scopes,...o},re.debug(`Merged OAuth config: authUrl=${f.authorizationUrl}, scopes=${f.scopes?.join(",")}`),re.info(`Using discovered OAuth config for ${r}`);else if(l?.clientId)f={...l,...o},re.debug(`Using hardcoded OAuth config for ${r}`);else return{authUrl:"",error:"Could not discover OAuth configuration. Server may require manual token authentication."}}if(!f.authorizationUrl)return{authUrl:"",error:"OAuth configuration incomplete: missing authorizationUrl"};let h=f.clientId||"compass-cli";try{await this.startCallbackServer();let b=this.generateCodeVerifier(),E=this.generateCodeChallenge(b),N=WXe(16).toString("hex");this.pendingAuths.set(N,{serverName:r,state:N,codeVerifier:b,createdAt:new Date});let W=new Mee(f.authorizationUrl);return W.searchParams.set("client_id",h),W.searchParams.set("response_type","code"),W.searchParams.set("redirect_uri",this.getRedirectUri()),W.searchParams.set("state",N),W.searchParams.set("code_challenge",E),W.searchParams.set("code_challenge_method","S256"),f.scopes?.length&&W.searchParams.set("scope",f.scopes.join(" ")),re.info(`Starting OAuth flow for ${r}`),{authUrl:W.toString(),discoveredConfig:f}}catch(b){let E=b instanceof Error?b.message:String(b);return re.error(`Failed to start OAuth flow for ${r}:`,b),{authUrl:"",error:E}}}async completeAuthFlowWithConfig(r,n){let o=`code:${r}`,l=this.pendingAuths.get(o);if(!l)return{success:!1,error:"No pending OAuth flow for this server"};let f=l.state,h=l.codeVerifier;if(this.pendingAuths.delete(o),!n.tokenUrl)return{success:!1,error:"OAuth configuration incomplete: missing tokenUrl"};let b=n.clientId||"compass-cli";try{let E=new RXe;E.set("grant_type","authorization_code"),E.set("code",f),E.set("redirect_uri",this.getRedirectUri()),E.set("code_verifier",h);let N={"Content-Type":"application/x-www-form-urlencoded"};if(n.clientId&&n.clientSecret){let q=Buffer.from(`${b}:${n.clientSecret}`).toString("base64");N.Authorization=`Basic ${q}`}else E.set("client_id",b),n.clientSecret&&E.set("client_secret",n.clientSecret);let W=await fetch(n.tokenUrl,{method:"POST",headers:N,body:E.toString()});if(!W.ok){let q=await W.text();return{success:!1,error:`Token exchange failed: ${W.status} ${q}`}}let H=await W.json(),M={accessToken:H.access_token,tokenType:H.token_type||"Bearer",refreshToken:H.refresh_token,expiresAt:H.expires_in?new Date(Date.now()+H.expires_in*1e3):void 0,scopes:H.scope?.split(" ")};return this.storage.tokens[r]=M,await this.save(),re.info(`OAuth flow completed for ${r}`),re.debug(`Stored token for ${r}, tokenType: ${M.tokenType}, hasAccessToken: ${!!M.accessToken}`),re.debug(`Current storage token keys: ${Object.keys(this.storage.tokens).join(", ")}`),{success:!0}}catch(E){let N=E instanceof Error?E.message:String(E);return re.error(`Failed to complete OAuth flow for ${r}:`,E),{success:!1,error:N}}}async stopCallbackServer(){if(this.callbackServer)return new Promise(r=>{this.callbackServer.close(()=>{this.callbackServer=null,re.debug("OAuth callback server stopped"),r()})})}cleanupPendingAuths(){let r=new Date,n=600*1e3;for(let[o,l]of this.pendingAuths)r.getTime()-l.createdAt.getTime()>n&&this.pendingAuths.delete(o)}getAuthenticatedServers(){return Object.keys(this.storage.tokens).filter(r=>this.isTokenValid(this.storage.tokens[r]))}},rIe=null});import{spawn as S8r}from"child_process";async function EPt(i,r){let n=i.timeout,o=r||n||parseInt(process.env.MCP_TIMEOUT||"")||xPt,l=aE(i);if(!i.type&&l.type&&re.debug(`Inferred transport type '${l.type}' for server '${l.name}' (missing 'type' field in config)`),W4(l))return E8r(l,o);if(Z4(l))return k8r(l,o);if(V4(l))return C8r(l,o);let f=l?.name||"unknown";throw new Error(`Unknown transport type for server: ${f}. Config must have 'type' field set to 'http', 'sse', or 'stdio', or have 'url' (for sse) or 'command' (for stdio) fields to infer the type.`)}async function E8r(i,r){re.debug(`Creating HTTP connection to ${i.name} at ${i.url}`);let o=(await nIe()).getAuthHeader(i.name),l={...i.headers,...o?{Authorization:o}:{}};re.debug(`HTTP connection headers for ${i.name}: Authorization=${o?"Bearer ***"+o.slice(-8):"none"}`);let f=new PXe(i.url,l,r,i.name),h="connecting",b;try{return await f.connect(),h="connected",re.info(`Connected to HTTP MCP server: ${i.name}`),{client:f,close:async()=>{await f.close()},status:h}}catch(E){if(E instanceof P4)throw E;return b=E instanceof Error?E.message:String(E),h="error",re.error(`Failed to connect to HTTP MCP server ${i.name}:`,E),{client:f,close:async()=>{try{await f.close()}catch{}},status:h,error:b}}}async function k8r(i,r){re.debug(`Creating SSE connection to ${i.name} at ${i.url}`);let n=new DXe(i.url,i.headers,r),o="connecting",l;try{return await n.connect(),o="connected",re.info(`Connected to SSE MCP server: ${i.name}`),{client:n,close:async()=>{await n.close()},status:o}}catch(f){return l=f instanceof Error?f.message:String(f),o="error",re.error(`Failed to connect to SSE MCP server ${i.name}:`,f),{client:n,close:async()=>{try{await n.close()}catch{}},status:o,error:l}}}async function C8r(i,r){re.debug(`Creating stdio connection to ${i.name} with command: ${i.command}`);let n=i.command==="npx"?Math.max(r,6e4):r;i.command==="npx"&&n>r&&re.debug("Using extended timeout (60s) for npx command - first run may download packages");let o=new MXe(i.command,i.args||[],i.cwd,i.env,n),l="connecting",f;try{return await Promise.race([o.connect(),new Promise((h,b)=>setTimeout(()=>b(new Error("Connection timeout")),n))]),l="connected",re.debug(`Connected to stdio MCP server: ${i.name}`),{client:o,close:async()=>{await o.close()},status:l}}catch(h){return f=h instanceof Error?h.message:String(h),l="error",re.error(`Failed to connect to stdio MCP server ${i.name}:`,h),{client:o,close:async()=>{try{await o.close()}catch{}},status:l,error:f}}}async function YXe(i){try{return(await i.listTools()).tools||[]}catch(r){return re.error("Failed to fetch MCP tools:",r),[]}}async function OXe(i){try{return(await i.listResources()).resources||[]}catch(r){return re.error("Failed to fetch MCP resources:",r),[]}}async function HXe(i){try{return(await i.listPrompts()).prompts||[]}catch(r){return re.error("Failed to fetch MCP prompts:",r),[]}}async function kPt(i){try{return i.getServerCapabilities()||{}}catch(r){return re.error("Failed to fetch MCP server capabilities:",r),{}}}async function CPt(i,r,n){try{return await i.callTool({name:r,arguments:n})}catch(o){let l=o instanceof Error?o.message:String(o);return re.error(`Failed to call MCP tool ${r}:`,o),{success:!1,error:l}}}async function GPt(i,r){try{return{content:(await i.readResource({uri:r})).contents||[]}}catch(n){let o=n instanceof Error?n.message:String(n);return re.error(`Failed to read MCP resource ${r}:`,n),{content:[],error:o}}}async function TPt(i,r,n){try{return{messages:(await i.getPrompt({name:r,arguments:n})).messages||[]}}catch(o){let l=o instanceof Error?o.message:String(o);return re.error(`Failed to get MCP prompt ${r}:`,o),{messages:[],error:l}}}var P4,PXe,DXe,MXe,NPt=Lt(()=>{"use strict";to();VXe();tIe();P4=class extends Error{serverName;serverUrl;constructor(r,n){super(`Authentication required for MCP server '${r}'`),this.name="AuthenticationRequiredError",this.serverName=r,this.serverUrl=n}},PXe=class{url;headers;connected=!1;capabilities={};requestTimeout;serverName;constructor(r,n={},o=3e4,l="unknown"){this.url=r,this.serverName=l,this.headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...n},this.requestTimeout=o}async parseResponse(r){if((r.headers.get("content-type")||"").includes("text/event-stream")){let l=(await r.text()).split(`
|
|
2356
|
+
`),f="";for(let h of l)if(h.startsWith("data:")){let b=h.slice(5).trim();b&&(f=b)}if(!f)throw new Error("No data found in SSE response");return JSON.parse(f)}return await r.json()}async connect(){try{let r=new AbortController,n=setTimeout(()=>r.abort(),this.requestTimeout),o=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"compass-cli",version:"1.0.0"}}}),signal:r.signal});if(clearTimeout(n),o.ok){let l=await this.parseResponse(o);l.result?.capabilities&&(this.capabilities={tools:!!l.result.capabilities.tools,resources:!!l.result.capabilities.resources,prompts:!!l.result.capabilities.prompts,logging:!!l.result.capabilities.logging}),this.connected=!0}else if(o.status===401){let l=await o.text().catch(()=>""),f=o.headers.get("WWW-Authenticate")||"";throw re.debug(`401 response from ${this.serverName}: body=${l.slice(0,200)}, WWW-Authenticate=${f}`),new P4(this.serverName,this.url)}else throw new Error(`HTTP ${o.status}: ${o.statusText}`)}catch(r){if(r instanceof P4)throw r;if(r.name==="AbortError")throw new Error("Connection timeout");let n=r instanceof Error?r.message:String(r);throw new Error(`Failed to connect: ${n}`)}}async close(){this.connected=!1}async listTools(){if(!this.connected)return{tools:[]};try{let r=new AbortController,n=setTimeout(()=>r.abort(),this.requestTimeout),o=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:2,method:"tools/list",params:{}}),signal:r.signal});if(clearTimeout(n),o.ok)return{tools:(await this.parseResponse(o)).result?.tools||[]}}catch(r){re.warn("Failed to list tools:",r)}return{tools:[]}}async listResources(){if(!this.connected)return{resources:[]};try{let r=new AbortController,n=setTimeout(()=>r.abort(),this.requestTimeout),o=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:3,method:"resources/list",params:{}}),signal:r.signal});if(clearTimeout(n),o.ok)return{resources:(await this.parseResponse(o)).result?.resources||[]}}catch(r){re.warn("Failed to list resources:",r)}return{resources:[]}}async listPrompts(){if(!this.connected)return{prompts:[]};try{let r=new AbortController,n=setTimeout(()=>r.abort(),this.requestTimeout),o=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:4,method:"prompts/list",params:{}}),signal:r.signal});if(clearTimeout(n),o.ok)return{prompts:(await this.parseResponse(o)).result?.prompts||[]}}catch(r){re.warn("Failed to list prompts:",r)}return{prompts:[]}}async callTool(r){if(!this.connected)return{success:!1,error:"Not connected"};try{let n=new AbortController,o=setTimeout(()=>n.abort(),this.requestTimeout),l=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:5,method:"tools/call",params:{name:r.name,arguments:r.arguments}}),signal:n.signal});if(clearTimeout(o),l.ok){let f=await this.parseResponse(l);return f.error?{success:!1,error:f.error.message}:{success:!0,content:f.result?.content||[],isError:f.result?.isError}}return{success:!1,error:`HTTP ${l.status}`}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async readResource(r){if(!this.connected)return{contents:[]};try{let n=new AbortController,o=setTimeout(()=>n.abort(),this.requestTimeout),l=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:6,method:"resources/read",params:{uri:r.uri}}),signal:n.signal});if(clearTimeout(o),l.ok)return{contents:(await this.parseResponse(l)).result?.contents||[]}}catch(n){re.warn("Failed to read resource:",n)}return{contents:[]}}async getPrompt(r){if(!this.connected)return{messages:[]};try{let n=new AbortController,o=setTimeout(()=>n.abort(),this.requestTimeout),l=await fetch(this.url,{method:"POST",headers:this.headers,body:JSON.stringify({jsonrpc:"2.0",id:7,method:"prompts/get",params:r}),signal:n.signal});if(clearTimeout(o),l.ok)return{messages:((await this.parseResponse(l)).result?.messages||[]).map(b=>({role:b.role,content:typeof b.content=="string"?b.content:b.content.text||""}))}}catch(n){re.warn("Failed to get prompt:",n)}return{messages:[]}}getServerCapabilities(){return this.connected?this.capabilities:null}},DXe=class{sseUrl;headers;connected=!1;capabilities={};messageEndpoint=null;requestId=0;pendingRequests=new Map;abortController=null;connectionTimeout;constructor(r,n={},o=3e4){this.sseUrl=r,this.headers=n,this.connectionTimeout=o}async connect(){return new Promise((r,n)=>{let o=setTimeout(()=>{this.abortController?.abort(),n(new Error("SSE connection timeout"))},this.connectionTimeout);this.establishSseConnection().then(async()=>{clearTimeout(o);let l=setTimeout(()=>{n(new Error("Timeout waiting for endpoint event from SSE server"))},1e4),f=async()=>{if(this.messageEndpoint){clearTimeout(l);try{let h=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"compass-cli",version:"1.0.0"}});h.result?.capabilities&&(this.capabilities={tools:!!h.result.capabilities.tools,resources:!!h.result.capabilities.resources,prompts:!!h.result.capabilities.prompts,logging:!!h.result.capabilities.logging}),await this.sendNotification("notifications/initialized",{}),this.connected=!0,r()}catch(h){n(h)}}else setTimeout(f,100)};f()}).catch(l=>{clearTimeout(o),n(l)})})}async establishSseConnection(){this.abortController=new AbortController;try{let r=await fetch(this.sseUrl,{method:"GET",headers:{Accept:"text/event-stream","Cache-Control":"no-cache",...this.headers},signal:this.abortController.signal});if(!r.ok)throw new Error(`SSE connection failed: HTTP ${r.status} ${r.statusText}`);if(!r.body)throw new Error("SSE response has no body");this.readSseStream(r.body)}catch(r){throw r.name==="AbortError"?new Error("SSE connection aborted"):r}}async readSseStream(r){let n=r.getReader(),o=new TextDecoder,l="",f="",h="";try{for(;;){let{done:b,value:E}=await n.read();if(b){re.debug("SSE stream ended"),this.connected=!1;break}l+=o.decode(E,{stream:!0});let N=l.split(/\r?\n/);l=N.pop()||"";for(let W of N){let H=W.trim();H.startsWith("event:")?f=H.slice(6).trim():H.startsWith("data:")?h+=H.slice(5).trim():H===""&&(f||h)&&(this.handleSseEvent(f,h),f="",h="")}}}catch(b){b.name!=="AbortError"&&re.error("SSE stream error:",b),this.connected=!1;for(let[E,N]of this.pendingRequests)N.reject(new Error("SSE connection closed")),this.pendingRequests.delete(E)}}handleSseEvent(r,n){if(re.debug(`SSE event received: ${r||"message"}, data: ${n.substring(0,100)}...`),r==="endpoint")try{if(n.startsWith("http://")||n.startsWith("https://"))this.messageEndpoint=n;else{let o=new URL(this.sseUrl);this.messageEndpoint=new URL(n,o).toString()}re.debug(`SSE message endpoint set to: ${this.messageEndpoint}`)}catch(o){re.error("Failed to parse endpoint URL:",o)}else if((r==="message"||r==="")&&n)try{let o=JSON.parse(n);this.handleJsonRpcResponse(o)}catch{re.debug(`Failed to parse SSE message data: ${n}`)}}handleJsonRpcResponse(r){if(r.id!==void 0&&r.id!==null){let n=this.pendingRequests.get(r.id);n&&(this.pendingRequests.delete(r.id),n.resolve(r))}}async sendRequest(r,n){if(!this.messageEndpoint)throw new Error("Message endpoint not available - SSE connection may not be established");let o=++this.requestId,l={jsonrpc:"2.0",id:o,method:r,params:n};return new Promise((f,h)=>{this.pendingRequests.set(o,{resolve:f,reject:h});let b=setTimeout(()=>{this.pendingRequests.has(o)&&(this.pendingRequests.delete(o),h(new Error(`Request timeout: ${r}`)))},this.connectionTimeout);fetch(this.messageEndpoint,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(l)}).then(E=>{E.ok||(clearTimeout(b),this.pendingRequests.delete(o),h(new Error(`HTTP ${E.status}: ${E.statusText}`)))}).catch(E=>{clearTimeout(b),this.pendingRequests.delete(o),h(E)})})}async sendNotification(r,n){if(!this.messageEndpoint)return;let o={jsonrpc:"2.0",method:r,params:n};try{await fetch(this.messageEndpoint,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(o)})}catch(l){re.debug("Failed to send notification:",l)}}async close(){this.connected=!1,this.abortController?.abort(),this.abortController=null,this.messageEndpoint=null;for(let[r,n]of this.pendingRequests)n.reject(new Error("Client closed")),this.pendingRequests.delete(r)}async listTools(){if(!this.connected)return{tools:[]};try{return{tools:(await this.sendRequest("tools/list",{})).result?.tools||[]}}catch(r){return re.warn("Failed to list tools:",r),{tools:[]}}}async listResources(){if(!this.connected)return{resources:[]};try{return{resources:(await this.sendRequest("resources/list",{})).result?.resources||[]}}catch(r){return re.warn("Failed to list resources:",r),{resources:[]}}}async listPrompts(){if(!this.connected)return{prompts:[]};try{return{prompts:(await this.sendRequest("prompts/list",{})).result?.prompts||[]}}catch(r){return re.warn("Failed to list prompts:",r),{prompts:[]}}}async callTool(r){if(!this.connected)return{success:!1,error:"Not connected"};try{let n=await this.sendRequest("tools/call",{name:r.name,arguments:r.arguments});return n.error?{success:!1,error:n.error.message}:{success:!0,content:n.result?.content||[],isError:n.result?.isError}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async readResource(r){if(!this.connected)return{contents:[]};try{return{contents:(await this.sendRequest("resources/read",{uri:r.uri})).result?.contents||[]}}catch(n){return re.warn("Failed to read resource:",n),{contents:[]}}}async getPrompt(r){if(!this.connected)return{messages:[]};try{return{messages:((await this.sendRequest("prompts/get",r)).result?.messages||[]).map(l=>({role:l.role,content:typeof l.content=="string"?l.content:l.content.text||""}))}}catch(n){return re.warn("Failed to get prompt:",n),{messages:[]}}}getServerCapabilities(){return this.connected?this.capabilities:null}},MXe=class{constructor(r,n=[],o,l,f=3e4){this.command=r;this.args=n;this.cwd=o;this.env=l;this.requestTimeout=f}process=null;connected=!1;capabilities={};requestId=0;pendingRequests=new Map;buffer="";lastStderrError=null;async connect(){return new Promise((r,n)=>{let o=!1,l=h=>{o||(o=!0,n(h))},f=()=>{o||(o=!0,r())};try{let h={...process.env,...this.env};if(re.debug(`Spawning stdio MCP server: ${this.command} ${this.args.join(" ")}`),this.process=S8r(this.command,this.args,{cwd:this.cwd||process.cwd(),env:h,stdio:["pipe","pipe","pipe"],shell:!0}),!this.process.stdout||!this.process.stdin){l(new Error("Failed to create stdio streams"));return}this.process.stdout.on("data",b=>{this.handleStdoutData(b)}),this.process.stderr?.on("data",b=>{let E=b.toString().trim();if(E){if(re.debug(`[MCP Server stderr]: ${E}`),E.includes("EADDRINUSE")){let N=E.match(/port[:\s]*(\d+)|:(\d+)/i),W=N?.[1]||N?.[2]||"unknown";this.lastStderrError=`Port ${W} is already in use. A previous MCP server process may still be running. Try killing the process using this port or wait for it to terminate.`}else if(E.includes("ECONNREFUSED"))this.lastStderrError="Connection refused. The target server may not be running.";else if(E.includes("ETIMEDOUT")||E.includes("timeout"))this.lastStderrError="Connection timed out while trying to reach the server.";else if(E.includes("ENOTFOUND"))this.lastStderrError="Server hostname not found. Please check the URL.";else if(E.includes("Error:")&&!this.lastStderrError){let N=E.match(/Error:\s*(.+?)(?:\n|$)/);N&&(this.lastStderrError=N[1].trim())}}}),this.process.on("exit",(b,E)=>{re.debug(`MCP server process exited with code ${b}, signal ${E}`),this.connected=!1,this.process=null;let N;this.lastStderrError?(N=this.lastStderrError,re.error(`MCP server failed: ${N}`)):b!==0?N=`Process exited with code ${b}`:E?N=`Process terminated by signal ${E}`:N="Process exited unexpectedly";for(let[W,H]of this.pendingRequests)H.reject(new Error(N)),this.pendingRequests.delete(W);l(new Error(N))}),this.process.on("error",b=>{re.error("MCP server process error:",b),this.connected=!1,l(b)}),setTimeout(async()=>{if(!(!this.process||o))try{let b=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"compass-cli",version:"1.0.0"}});b.result?.capabilities&&(this.capabilities={tools:!!b.result.capabilities.tools,resources:!!b.result.capabilities.resources,prompts:!!b.result.capabilities.prompts,logging:!!b.result.capabilities.logging}),this.sendNotification("notifications/initialized",{}),this.connected=!0,re.debug(`Stdio MCP server connected: ${this.command}`),f()}catch(b){l(b instanceof Error?b:new Error(String(b)))}},100)}catch(h){l(h instanceof Error?h:new Error(String(h)))}})}handleStdoutData(r){this.buffer+=r.toString();let n;for(;(n=this.buffer.indexOf(`
|
|
2356
2357
|
`))!==-1;){let o=this.buffer.substring(0,n).trim();if(this.buffer=this.buffer.substring(n+1),o)try{let l=JSON.parse(o);this.handleResponse(l)}catch{re.debug(`Failed to parse MCP response: ${o}`)}}}handleResponse(r){if(r.id!==void 0&&r.id!==null){let n=this.pendingRequests.get(r.id);n&&(this.pendingRequests.delete(r.id),n.resolve(r))}}sendRequest(r,n){return new Promise((o,l)=>{if(!this.process?.stdin){l(new Error("Process not running"));return}let f=++this.requestId,h={jsonrpc:"2.0",id:f,method:r,params:n};this.pendingRequests.set(f,{resolve:o,reject:l});let b=JSON.stringify(h)+`
|
|
2357
2358
|
`;this.process.stdin.write(b,E=>{E&&(this.pendingRequests.delete(f),l(E))}),setTimeout(()=>{this.pendingRequests.has(f)&&(this.pendingRequests.delete(f),l(new Error(`Request timeout: ${r}`)))},this.requestTimeout)})}sendNotification(r,n){if(!this.process?.stdin)return;let l=JSON.stringify({jsonrpc:"2.0",method:r,params:n})+`
|
|
2358
2359
|
`;this.process.stdin.write(l)}async close(){if(this.connected=!1,this.process){try{this.sendNotification("notifications/cancelled",{reason:"Client closing"})}catch{}this.process.kill("SIGTERM"),setTimeout(()=>{this.process&&!this.process.killed&&this.process.kill("SIGKILL")},2e3),this.process=null}for(let[r,n]of this.pendingRequests)n.reject(new Error("Client closed")),this.pendingRequests.delete(r)}async listTools(){if(!this.connected)return{tools:[]};try{return{tools:(await this.sendRequest("tools/list",{})).result?.tools||[]}}catch(r){return re.warn("Failed to list tools:",r),{tools:[]}}}async listResources(){if(!this.connected)return{resources:[]};try{return{resources:(await this.sendRequest("resources/list",{})).result?.resources||[]}}catch(r){return re.warn("Failed to list resources:",r),{resources:[]}}}async listPrompts(){if(!this.connected)return{prompts:[]};try{return{prompts:(await this.sendRequest("prompts/list",{})).result?.prompts||[]}}catch(r){return re.warn("Failed to list prompts:",r),{prompts:[]}}}async callTool(r){if(!this.connected)return{success:!1,error:"Not connected"};try{let n=await this.sendRequest("tools/call",{name:r.name,arguments:r.arguments});return n.error?{success:!1,error:n.error.message}:{success:!0,content:n.result?.content||[],isError:n.result?.isError}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async readResource(r){if(!this.connected)return{contents:[]};try{return{contents:(await this.sendRequest("resources/read",{uri:r.uri})).result?.contents||[]}}catch(n){return re.warn("Failed to read resource:",n),{contents:[]}}}async getPrompt(r){if(!this.connected)return{messages:[]};try{return{messages:((await this.sendRequest("prompts/get",r)).result?.messages||[]).map(l=>({role:l.role,content:typeof l.content=="string"?l.content:l.content.text||""}))}}catch(n){return re.warn("Failed to get prompt:",n),{messages:[]}}}getServerCapabilities(){return this.connected?this.capabilities:null}isConnected(){return this.connected&&this.process!==null}}});function FPt(){return JXe||(JXe=new LXe),JXe}var LXe,JXe,RPt=Lt(()=>{"use strict";to();l_();SPt();VXe();LD();NPt();tIe();LXe=class{servers=new Map;connections=new Map;configManager;projectRoot;initialized=!1;constructor(){this.configManager=APt()}async initialize(r){if(!(this.initialized&&this.projectRoot===r)){this.projectRoot=r;try{await this.configManager.load(r),this.initialized=!0,await this.connectAllServers(),re.debug("MCP Server Manager initialized")}catch(n){throw re.error("Failed to initialize MCP Server Manager",n),n}}}async connectAllServers(){let r=this.configManager.getAllServers(this.projectRoot);for(let n of r){if(n.enabled===!1){re.debug(`Skipping disabled server: ${n.name}`),this.servers.set(n.name,{config:n,status:"disconnected",tools:[],resources:[],prompts:[],error:"Server is disabled"});continue}if(n.requiresCompassApiKey){if(!await(await S0()).hasCompassApiKey()){re.debug(`Skipping server '${n.name}': requires Compass API key (not configured)`),this.servers.set(n.name,{config:n,status:"disconnected",tools:[],resources:[],prompts:[],error:"Requires Compass API key"});continue}re.debug(`Server '${n.name}' requires Compass API key: found`)}if(n.scope==="project"&&this.projectRoot){if(!this.configManager.isProjectServerApproved(this.projectRoot,n.name)){re.debug(`Skipping unapproved project server: ${n.name}`),this.servers.set(n.name,{config:n,status:"disconnected",tools:[],resources:[],prompts:[],error:"Awaiting approval"});continue}re.debug(`Project server '${n.name}' is approved, treating as enabled`)}else if(n.enabled!==!0){re.debug(`Skipping server without explicit enabled=true: ${n.name}`),this.servers.set(n.name,{config:n,status:"disconnected",tools:[],resources:[],prompts:[],error:"Server not explicitly enabled"});continue}await this.connectServer(n.name)}}async connectServer(r){let n=this.configManager.getServer(r,this.projectRoot);if(!n)throw new Error(`Server not found: ${r}`);if(n.requiresCompassApiKey&&(Z4(n)||W4(n))){let f=await(await S0()).getCompassApiKey();f?(n={...n,headers:{...n.headers,"x-api-key":f}},re.debug(`Injected Compass API key into headers for server: ${r}`)):re.warn(`Server '${r}' requires Compass API key but none found`)}let o={config:n,status:"connecting",tools:[],resources:[],prompts:[]};this.servers.set(r,o);try{let l=pa();l.emit("mcp-server-connecting",{serverName:r,config:n});let f=await EPt(n);if(this.connections.set(r,f),f.status==="error")return o.status="error",o.error=f.error,l.emit("mcp-server-error",{serverName:r,error:f.error||"Unknown error"}),o;o.status="connected",o.connectedAt=new Date;let h=await kPt(f.client);return o.capabilities=h,h.tools&&(o.tools=await YXe(f.client),o.tools.forEach(b=>{b.serverName=r})),h.resources&&(o.resources=await OXe(f.client),o.resources.forEach(b=>{b.serverName=r})),h.prompts&&(o.prompts=await HXe(f.client),o.prompts.forEach(b=>{b.serverName=r})),re.info(`Connected to MCP server: ${r} (${o.tools.length} tools, ${o.resources.length} resources, ${o.prompts.length} prompts)`),l.emit("mcp-server-connected",{serverName:r,tools:o.tools,resources:o.resources,prompts:o.prompts}),o}catch(l){if(l instanceof P4&&n.oauth){re.info(`Authentication required for MCP server: ${r}`),o.status="authenticating",o.error="Authentication required";let b=await this.handleOAuthFlow(r,n);return b.success?(re.info(`Authentication successful for ${r}, reconnecting...`),this.connectServer(r)):(o.status="error",o.error=b.error||"Authentication failed",pa().emit("mcp-server-error",{serverName:r,error:o.error}),o)}let f=l instanceof Error?l.message:String(l);return o.status="error",o.error=f,re.error(`Failed to connect to MCP server ${r}:`,l),pa().emit("mcp-server-error",{serverName:r,error:f}),o}}async handleOAuthFlow(r,n){if(!n.oauth)return{success:!1,error:"No OAuth configuration found"};let o=pa(),l=await nIe();try{let{authUrl:f,error:h}=await l.startAuthFlow(r,n.oauth);if(h||!f)return{success:!1,error:h||"Failed to generate auth URL"};o.emit("mcp-auth-required",{serverName:r,authUrl:f,message:`Authentication required for '${r}'`}),re.info(`OAuth flow started for ${r}, waiting for callback...`);let b=300*1e3,E=1e3,N=Date.now();for(;Date.now()-N<b;){await new Promise(M=>setTimeout(M,E));let H=await l.completeAuthFlow(r,n.oauth);if(H.success)return re.info(`OAuth flow completed successfully for ${r}`),o.emit("mcp-auth-success",{serverName:r}),{success:!0};if(H.error&&!H.error.includes("No pending OAuth flow"))return re.error(`OAuth flow failed for ${r}: ${H.error}`),o.emit("mcp-auth-failed",{serverName:r,error:H.error}),{success:!1,error:H.error}}let W="Authentication timed out after 5 minutes";return re.error(`OAuth flow timed out for ${r}`),o.emit("mcp-auth-failed",{serverName:r,error:W}),{success:!1,error:W}}catch(f){let h=f instanceof Error?f.message:String(f);return re.error(`OAuth flow error for ${r}:`,f),o.emit("mcp-auth-failed",{serverName:r,error:h}),{success:!1,error:h}}}async disconnectServer(r){let n=this.connections.get(r);if(n){try{await n.close()}catch(f){re.warn(`Error closing connection to ${r}:`,f)}this.connections.delete(r)}let o=this.servers.get(r);o&&(o.status="disconnected",o.tools=[],o.resources=[],o.prompts=[]),re.debug(`Disconnected from MCP server: ${r}`),pa().emit("mcp-server-disconnected",{serverName:r})}async disconnectAllServers(){let r=Array.from(this.connections.keys());for(let n of r)await this.disconnectServer(n)}getServerState(r){return this.servers.get(r)}getAllServerStates(){return Array.from(this.servers.values())}getAllTools(){let r=[];for(let n of this.servers.values())n.status==="connected"&&r.push(...n.tools);return r}getAllResources(){let r=[];for(let n of this.servers.values())n.status==="connected"&&r.push(...n.resources);return r}getAllPrompts(){let r=[];for(let n of this.servers.values())n.status==="connected"&&r.push(...n.prompts);return r}async callTool(r,n,o){let l=o;if(!l){for(let[E,N]of this.servers)if(N.tools.some(W=>W.name===r)){l=E;break}}if(!l)return{success:!1,error:`Tool not found: ${r}`};let f=this.connections.get(l);if(!f||f.status!=="connected")return{success:!1,error:`Server not connected: ${l}`};let h=this.servers.get(l);h&&(h.lastActivity=new Date);let b=await CPt(f.client,r,n);return b.content&&JSON.stringify(b.content).length>TXe*4&&re.warn(`MCP tool ${r} output exceeds ${TXe} tokens. Consider increasing MAX_MCP_OUTPUT_TOKENS environment variable.`),b}async readResource(r,n){let o=n;if(!o){for(let[h,b]of this.servers)if(b.resources.some(E=>E.uri===r)){o=h;break}}if(!o)return{content:[],error:`Resource not found: ${r}`};let l=this.connections.get(o);if(!l||l.status!=="connected")return{content:[],error:`Server not connected: ${o}`};let f=this.servers.get(o);return f&&(f.lastActivity=new Date),GPt(l.client,r)}async getPrompt(r,n,o){let l=o;if(!l){for(let[b,E]of this.servers)if(E.prompts.some(N=>N.name===r)){l=b;break}}if(!l)return{messages:[],error:`Prompt not found: ${r}`};let f=this.connections.get(l);if(!f||f.status!=="connected")return{messages:[],error:`Server not connected: ${l}`};let h=this.servers.get(l);return h&&(h.lastActivity=new Date),TPt(f.client,r,n)}getServerList(){let r=this.configManager.getAllServers(this.projectRoot),n=[];for(let o of r){let l=this.servers.get(o.name),f="";W4(o)||Z4(o)?f=o.url:V4(o)&&(f=o.command),n.push({name:o.name,type:o.type,status:l?.status||"disconnected",scope:o.scope||"local",source:o.source||"user",toolCount:l?.tools.length||0,resourceCount:l?.resources.length||0,needsAuth:!1,endpoint:f})}return n}async refreshServer(r){let n=this.connections.get(r),o=this.servers.get(r);if(!n||!o||o.status!=="connected")throw new Error(`Server not connected: ${r}`);let l=o.capabilities||{};l.tools&&(o.tools=await YXe(n.client),o.tools.forEach(f=>{f.serverName=r})),l.resources&&(o.resources=await OXe(n.client),o.resources.forEach(f=>{f.serverName=r})),l.prompts&&(o.prompts=await HXe(n.client),o.prompts.forEach(f=>{f.serverName=r})),re.debug(`Refreshed MCP server: ${r}`)}async reconnectServer(r){return await this.disconnectServer(r),this.connectServer(r)}async approveAndConnect(r){if(!this.projectRoot)throw new Error("No project root set");let n=this.configManager.getServer(r,this.projectRoot);if(!n)throw new Error(`Server not found: ${r}`);let o=this.configManager.generateConfigHash(n);return await this.configManager.setProjectServerApproval(this.projectRoot,r,!0,o),this.connectServer(r)}getPendingApprovalServers(){return this.projectRoot?this.configManager.getUnapprovedProjectServers(this.projectRoot):[]}async shutdown(){await this.disconnectAllServers(),this.servers.clear(),this.initialized=!1,re.debug("MCP Server Manager shut down")}getConnectedCount(){let r=0;for(let n of this.servers.values())n.status==="connected"&&r++;return r}getTotalCount(){return this.servers.size}hasServersNeedingAuth(){return!1}},JXe=null});function WPt(i,r){let n=i.replace(/[^a-zA-Z0-9]/g,"_").toLowerCase(),o=r.replace(/[^a-zA-Z0-9]/g,"_").toLowerCase();return`${ZPt}${n}_${o}`}function G8r(i){return{type:"object",properties:i.properties||{},required:i.required||[]}}function ZJ(){return XXe||(XXe=new UXe),XXe}var ZPt,UXe,XXe,QXe=Lt(()=>{"use strict";WJ();RPt();l_();to();Sy();ZPt="mcp_";UXe=class{serverManager;registeredTools=new Map;initialized=!1;constructor(){this.serverManager=FPt()}async initialize(r){if(this.initialized)return;await this.serverManager.initialize(r);let n=pa();n.on("mcp-server-connected",({serverName:o,tools:l})=>{this.registerServerTools(o,l)}),n.on("mcp-server-disconnected",({serverName:o})=>{this.unregisterServerTools(o)}),n.on("mcp-server-error",({serverName:o})=>{this.unregisterServerTools(o)});for(let o of this.serverManager.getAllServerStates())o.status==="connected"&&o.tools.length>0&&this.registerServerTools(o.config.name,o.tools);this.initialized=!0,re.debug("MCP Tool Integration initialized")}registerServerTools(r,n){let o=K2(),l=[],h=this.serverManager.getServerState(r)?.config?.silent??!1;for(let b of n){let E=WPt(r,b.name),N=async(W,H)=>{let M=await this.serverManager.callTool(b.name,W,r);if(!M.success)throw new Error(M.error||"Tool execution failed");if(M.content){let q=M.content.filter(le=>le.type==="text").map(le=>le.text).join(`
|
|
@@ -3663,7 +3664,7 @@ ${r}`),o.push({role:"user",content:b}),o}estimateTaskTokens(r,n,o){let l=nf(r);f
|
|
|
3663
3664
|
`)}BS();var qze=[{name:"Sessions",description:"Commands for managing your conversation session",commands:[{name:"/clear",description:"Reset session to clean state",usage:"/clear",aliases:["/reset","/restart"]},{name:"/compact",description:"Summarize conversation to reduce token usage",usage:"/compact"},{name:"/export",description:"Export conversation to file",usage:"/export [format]",examples:["/export md","/export json","/export html"],hidden:!0},{name:"/exit",description:"Exit Compass",usage:"/exit",aliases:["/quit","/q"]}]},{name:"Model & Tokens",description:"Commands for model selection and token tracking",commands:[{name:"/model",description:"Switch between models",usage:"/model [name]",examples:["/model","/model sonnet","/model opus","/model haiku"]},{name:"/tokens",description:"Display token usage statistics",usage:"/tokens"},{name:"/context",description:"Show context window usage",usage:"/context"}]},{name:"File Operations",description:"Commands for file management and indexing",commands:[{name:"/files",description:"List indexed project files",usage:"/files [pattern]",examples:["/files","/files *.ts","/files src/"]},{name:"/index",description:"Reindex project files",usage:"/index"}]},{name:"Approval & Safety",description:"Commands for approval mode management",commands:[{name:"/approve",description:"Toggle approval mode",usage:"/approve [mode]",examples:["/approve","/approve auto","/approve manual"]}]},{name:"Help & Config",description:"Commands for help and configuration",commands:[{name:"/help",description:"Show this help menu",usage:"/help [topic]",examples:["/help","/help model","/help files"]},{name:"/config",description:"Display current configuration",usage:"/config"}]},{name:"Updates",description:"Commands for checking and installing updates",commands:[{name:"/update",description:"Check for and install updates",usage:"/update [check|install|history|version]",examples:["/update","/update check","/update install","/update history"],aliases:["/upgrade","/up"]}]},{name:"Cleanup",description:"Commands for cleaning up stored data",commands:[{name:"/purge",description:"Delete logs, backups, chats, and plans from .compass",usage:"/purge [--force|--help]",examples:["/purge","/purge --force"],aliases:["/cleanup"]}]}],Gdn=[{name:"Setup & Configuration",description:"Commands for initial setup and configuration",commands:[{name:"setup",description:"Run first-time setup wizard",usage:"compass setup"},{name:"init",description:"Initialize Compass in current project",usage:"compass init"},{name:"config",description:"View or modify configuration",usage:"compass config [key] [value]",examples:["compass config","compass config model sonnet"]}]},{name:"Data Management",description:"Commands for managing stored data",commands:[{name:"tokens",description:"View token usage history",usage:"compass tokens [--export]"},{name:"consent",description:"Manage consent settings",usage:"compass consent [status|review|revoke]"},{name:"data",description:"Manage stored data",usage:"compass data [list|export|delete]"},{name:"cache",description:"Clear cached data",usage:"compass cache clear"},{name:"reset",description:"Reset to factory settings",usage:"compass reset [--force]"}]},{name:"Updates",description:"Commands for checking and installing updates",commands:[{name:"update",description:"Check for and install updates",usage:"compass update [check|install|history]",examples:["compass update","compass update check","compass update install","compass update history"]}]}];function PLt(i){let r=i.commands.filter(o=>!o.hidden);if(r.length===0)return"";let n=["",Dn.bold.cyan(`\u2501\u2501\u2501 ${i.name} \u2501\u2501\u2501`),Dn.gray(i.description),""];for(let o of r){if(n.push(` ${Dn.yellow(o.name)}`),n.push(` ${Dn.white(o.description)}`),o.usage&&n.push(` ${Dn.gray("Usage:")} ${Dn.dim(o.usage)}`),o.aliases&&o.aliases.length>0&&n.push(` ${Dn.gray("Aliases:")} ${Dn.dim(o.aliases.join(", "))}`),o.examples&&o.examples.length>0){n.push(` ${Dn.gray("Examples:")}`);for(let l of o.examples)n.push(` ${Dn.dim(l)}`)}n.push("")}return n.join(`
|
|
3664
3665
|
`)}function Tdn(){try{let{getCustomCommands:i}=(VLt(),U2r(ZLt)),r=i();return!r||r.length===0?null:{name:"Custom Commands",description:"User-defined commands from .compass/commands/ or ~/.compass/commands/",commands:r.map(o=>{let l=o.namespace?`${o.scope}:${o.namespace}`:o.scope;return{name:`/${o.name}`,description:`${o.description} (${l})`,usage:o.frontmatter["argument-hint"]?`/${o.name} ${o.frontmatter["argument-hint"]}`:`/${o.name}`}})}}catch{return null}}function Ndn(){let i=[...qze],r=Tdn();r&&i.push(r);let n=i.map(PLt);return["",Dn.bold.white("Compass CLI - Interactive Commands"),Dn.gray("Use these commands during an interactive session"),...n,Dn.dim("\u2500".repeat(50)),Dn.gray("Tip: Type any natural language request to interact with Compass"),""].join(`
|
|
3665
3666
|
`)}function Fdn(i){let r=i.startsWith("/")?i:`/${i}`,o=qze.flatMap(f=>f.commands).find(f=>f.name===r||f.name===i||f.aliases?.includes(i)||f.aliases?.includes(r));if(!o)return null;let l=["",Dn.bold.cyan(o.name),Dn.white(o.description),""];if(o.usage&&(l.push(Dn.gray("Usage:")),l.push(` ${o.usage}`),l.push("")),o.aliases&&o.aliases.length>0&&(l.push(Dn.gray("Aliases:")),l.push(` ${o.aliases.join(", ")}`),l.push("")),o.examples&&o.examples.length>0){l.push(Dn.gray("Examples:"));for(let f of o.examples)l.push(` ${Dn.dim("$")} ${f}`);l.push("")}return l.join(`
|
|
3666
|
-
`)}T4();var FLn="1.0.
|
|
3667
|
+
`)}T4();var FLn="1.0.65",RLn="compass-cli",WLn="AI-powered development assistance using Anthropic's Claude models";export{Ome as ACTIVE_PLAN_TYPE_LIMITS,Eq as AGENT_SOURCE_PRIORITY,WLn as APP_DESCRIPTION,Mxr as APP_DISPLAY_NAME,RLn as APP_NAME,Yxr as APP_TAGLINE,Dxr as APP_VERSION,FLt as ASCII_BANNER,PMe as AUTO_COMPACT_TRIGGER,Rme as AUTO_SAVE_INTERVAL_MS,Eee as ActionLogger,J3t as ActionStatus,Xb as ActionType,Xhe as AnthropicClient,Q_e as ApprovalManager,SH as ApprovalMode,kMe as BACKUPS_DIR,Tq as BACKUP_RETENTION_DAYS,Jxr as BINARY_EXTENSIONS,B_e as BackupManager,hxr as CACHE_DIR,Zq as CATEGORY_INFO,xMe as CHAT_ARCHIVE_VERSION,Pw as CLAUDE_MODELS,Gdn as CLI_COMMANDS,bdn as COMPASS_ICON,kH as CONFIG_FILE_NAME,DMe as CONSENT_EXPIRY_DAYS,SMe as CONSENT_FILE_NAME,Oxr as CONSENT_VERSION,gxr as CONTEXT_DIR,Gxr as CONTEXT_WINDOW_SAFETY_MARGIN,yxr as CONTEXT_WINDOW_WARNING_PERCENT,Cq as CREDENTIALS_FILE_NAME,wN as CRON_DAY_NAMES,Mme as CRON_PRESETS,Y_e as ChatArchivalService,Hee as ComplexityClassifier,G_e as ConfigManager,Z_e as ConsentManager,M_e as CredentialStore,Yme as DAY_NAME_TO_CRON,bxr as DEFAULT_CLASSIFIER_MODEL,aZ as DEFAULT_CLASSIFIER_MODELS_BY_PROVIDER,vN as DEFAULT_CONFIG,Ixr as DEFAULT_COST_WARNING_THRESHOLD,fC as DEFAULT_MAX_TOKENS,Vw as DEFAULT_MODEL,Bv as DEFAULT_PERSONALITY_MODE,CD as DEFAULT_PLAN_TYPE,uxr as DEFAULT_RATING_CONFIG,Pq as DEFAULT_SCHEDULE_HEADER,pC as DEFAULT_TEMPERATURE,sxr as DEFAULT_UPDATE_CONFIG,Hme as DISABLED_MODELS,jv as ENV_VARS,Pee as EnhancedContextGatherer,R_e as EventEmitter,Aq as ExecutionMode,f4t as ExecutionStrategy,kq as GLOBAL_COMPASS_DIR,MK as GitService,Evt as HOOK_EVENTS,Cme as HOOK_SOURCE_PRIORITY,pxe as HistoryManager,CMe as INDEX_DIR,rre as InteractiveClarifier,d4t as IssueCategory,u4t as IssueSeverity,Hxr as LANGUAGE_EXTENSIONS,EMe as LOGS_DIR,$ee as LogInterpreter,GH as MAX_BACKUP_FILES,Nxr as MAX_CACHE_SIZE_BYTES,Rq as MAX_COMMAND_OUTPUT_TOKENS,kxr as MAX_DYNAMIC_STREAM_BLOCKS,Nvt as MAX_FILES_PER_OPERATION,MMe as MAX_FILE_READ_TOKENS,Fvt as MAX_FILE_SIZE_BYTES,Fq as MAX_HISTORY_LENGTH,Txr as MAX_INDEXED_FILES,sZ as MAX_MEMORY_LINES,Wxr as MAX_RETRY_ATTEMPTS,Cxr as MAX_SEARCH_RESULT_TOKENS,ZMe as MEMORY_DIR,kD as MEMORY_FILE_NAME,Wq as MODEL_ALIASES,Nme as NOVA_LOCAL_MD_FILE_NAME,iZ as NOVA_MD_FILE_NAME,Wvt as NO_SUBSCRIPTION_DAILY_TOKEN_LIMIT,$Me as PLAN_LIMITS,Gq as PROJECTS_DIR,ED as PROJECT_COMPASS_DIR,xN as PROVIDERS,Zme as PROVIDER_ENV_VARS,nre as PlanGenerator,Zxr as RETRY_BASE_DELAY_MS,Pxr as RETRY_JITTER_FACTOR,Vxr as RETRY_MAX_DELAY_MS,Yq as ROLLING_WINDOW_HOURS,Mq as ROLLING_WINDOW_MS,WMe as RULES_DIR,CH as SAVED_SESSIONS_DIR,jMe as SCHEDULE_FILE_NAME,Gvt as SESSION_EXPIRY_DAYS,Tme as SESSION_FILE_NAME,Wme as SHELL_COMMAND_MAX_TIMEOUT_MS,Nq as SHELL_COMMAND_TIMEOUT_MS,qze as SLASH_COMMANDS,TH as SYSTEM_UTILITIES,O_e as SessionManager,bye as ShellExecutor,M3t as StepStatus,See as StepTracker,Y3t as StepType,Dme as TASK_ID_PREFIX,Vq as TASK_ID_RANDOM_LENGTH,BMe as TASK_STATUSES,GMe as TEMP_DIR,zMe as TOKEN_LIMITS_STORE_FILENAME,qMe as TOKEN_LIMITS_STORE_VERSION,ewr as TOKEN_LIMIT_MESSAGES,Xxr as TOKEN_LIMIT_WARNING_THRESHOLD_PERCENT,VMe as TOKEN_WARNING_THRESHOLD,JMe as TOOL_READ_BLOCKLIST_DIRS,HMe as TOOL_READ_BLOCKLIST_PATTERNS,IMe as TaskExecutionStatus,O3t as TaskStatus,xYe as TokenLimitEnforcer,AMe as TokenLimitExceededError,H_e as TokenLimitStore,U_e as TokenTracker,Tee as ToolRegistry,XMe as UTILITY_DETECTION_CACHE_TTL,UMe as UTILITY_DETECTION_TIMEOUT,Rvt as VALID_PLAN_TYPES,FLn as VERSION,ire as Verifier,X7e as WORKFLOW_PROMPTS,Kee as WorkflowManager,sre as WorkflowOrchestrator,wme as WorkflowPhase,p4t as WorkflowState,gdn as applyCompletion,$Yr as applyPatch,zYr as areIdentical,NHr as calculateContextUsagePercent,Hvt as calculateModelCost,CHr as calculateRemainingTokens,dTr as colorByStatus,QYr as colorizeDiff,wvt as compareAgentPriority,_xr as compareHookPriority,Jvt as compareModels,CN as copy,HHr as createActionLogger,w$ as createChatArchivalService,eJr as createComplexityClassifier,vvt as createDefaultAgentDefinition,rxr as createDefaultConsent,dxr as createDefaultRatingState,y8r as createEnhancedContextGatherer,nxr as createFullConsent,a3r as createGitService,jun as createInteractiveClarifier,KJr as createLogInterpreter,ixr as createMinimalConsent,zun as createPlanGenerator,OHr as createStepTracker,k$ as createTokenLimitStore,$Hr as createToolRegistry,$un as createVerifier,tLr as createWorkflowManager,edn as createWorkflowOrchestrator,fYe as decrypt,pYe as encrypt,Pl as ensureDir,EHr as estimateConversationTokens,kHr as estimateSystemPromptTokens,nf as estimateTokens,idn as executeSlashCommand,Xze as extractCodeBlocks,Lze as extractMentions,Fdn as formatCommandHelp,sTr as formatCost,tTr as formatDate,rTr as formatDuration,iTr as formatFileSize,Ndn as formatFullHelp,PLt as formatHelpCategory,uTr as formatList,kSt as formatPercent,lTr as formatProgressBar,nTr as formatRelativeTime,un as formatTimestamp,aTr as formatTokenCount,THr as formatTokenDisplay,S4 as generateDiff,jYr as generateDiffSummary,ITr as generateSecureRandom,BYr as generateWordDiff,r5 as getActionLogger,Ame as getAgentSourcePriority,xy as getAnthropicClient,Ih as getApprovalManager,Dvt as getAvailableAliases,Pvt as getAvailableModelIds,oZ as getAvailableModels,SZ as getBackupManager,vkr as getBasename,qYr as getChangedLineCount,Xvt as getCheapestModel,NJ as getCodebaseIndexer,ldn as getCompletions,Jee as getComplexityClassifier,r8 as getConfigManager,cYe as getConsentManager,iF as getContextBuilder,FHr as getContextUsageColor,YHr as getConversationCompactor,S0 as getCredentialStore,Yvt as getDefaultModel,Ovt as getDefaultModelId,Dee as getEnhancedContextGatherer,pa as getEventEmitter,bkr as getExtension,tF as getFileService,ac as getGlobalCompassDir,sdn as getHistoryManager,bMe as getHookSourcePriority,Oze as getInteractiveClarifier,BUe as getLogInterpreter,a_ as getModelConfig,Pme as getModelDescription,Qvt as getModelTier,J_e as getModelTokens,Lvt as getModelsByCapability,Uvt as getMostCapableModel,axe as getPlanGenerator,cu as getProjectCompassDir,ykr as getRelativePath,u_ as getSessionManager,Ay as getShellExecutor,Bze as getSlashCommandRegistry,t5 as getStepTracker,vye as getSystemUtilitiesPromptSection,RVt as getSystemUtilityDetector,Idn as getTaskProcessor,Db as getTokenTracker,K2 as getToolRegistry,Lxr as getUtilitiesByCategory,Jze as getVerifier,eLr as getWorkflowManager,Kun as getWorkflowOrchestrator,Zvt as hasFullAccess,mYe as hash,bTr as hmac,iA as interpolateTemplate,Vvt as isAnthropicModel,I$ as isDirectory,E_e as isFile,OD as isPathWithin,Eme as isValidAgentFrontmatter,Sme as isValidAgentPermissionMode,Ivt as isValidAgentSource,j2r as isValidAnthropicConfig,bvt as isValidCLIAgentConfig,nZ as isValidChatArchive,Q2r as isValidCompassConfig,exr as isValidConfigFile,gvt as isValidConsent,txr as isValidConsentRecord,Gme as isValidHookEvent,mxr as isValidHookFrontmatter,fxr as isValidHookSource,Mvt as isValidModel,lxr as isValidNotificationStyle,B2r as isValidProjectConfig,pxr as isValidRatingState,z2r as isValidSafetyConfig,$2r as isValidSessionConfig,ndn as isValidSlashCommand,q2r as isValidUIConfig,axr as isValidUpdateCheckResult,oxr as isValidUpdateConfig,K2r as isValidUpdateSettingsConfig,cxr as isValidUpdateType,re as logger,o$ as matchesPattern,Ikr as normalizeSeparators,cTr as padString,ELt as parseArgs,rdn as parseInput,SD as parseToolsList,na as pathExists,t8 as readDir,ZUe as registerBuiltInTools,jze as registerSlashCommand,A0 as remove,wdn as renderBanner,Adn as renderMiniBanner,Sdn as renderWelcome,A$ as resetIfExpired,hkr as resolveGlobalPath,_y as resolveModelId,KMe as resolvePlanLimits,gkr as resolveProjectPath,od as safeReadFile,cd as safeReadJson,yy as safeWriteFile,J_ as safeWriteJson,YD as sanitizePath,vTr as secureCompare,xvt as serializeToolsList,Iy as stat,E$ as sumAllUsage,gZ as toForwardSlashes,oTr as truncate,GHr as wouldExceedContext};
|
|
3667
3668
|
/*! Bundled license information:
|
|
3668
3669
|
|
|
3669
3670
|
typescript/lib/typescript.js:
|