@compass-ai/nova 1.0.95 → 1.0.96

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.
Files changed (3) hide show
  1. package/dist/cli.js +781 -778
  2. package/dist/index.js +3 -3
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var j2r=Object.create;var sme=Object.defineProperty;var B2r=Object.getOwnPropertyDescriptor;var z2r=Object.getOwnPropertyNames;var q2r=Object.getPrototypeOf,$2r=Object.prototype.hasOwnProperty;var js=(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 Ut=(i,r)=>()=>(i&&(r=i(i=0)),r);var pt=(i,r)=>()=>(r||i((r={exports:{}}).exports,r),r.exports),Vw=(i,r)=>{for(var n in r)sme(i,n,{get:r[n],enumerable:!0})},UIt=(i,r,n,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let l of z2r(r))!$2r.call(i,l)&&l!==n&&sme(i,l,{get:()=>r[l],enumerable:!(o=B2r(r,l))||o.enumerable});return i};var Go=(i,r,n)=>(n=i!=null?j2r(q2r(i)):{},UIt(r||!i||!i.__esModule?sme(n,"default",{value:i,enumerable:!0}):n,i)),K2r=i=>UIt(sme({},"__esModule",{value:!0}),i);function exr(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 txr(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 rxr(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 nxr(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 ixr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r=="object"&&r!==null}function sxr(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 axr(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 oxr(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 XIt=Ut(()=>{"use strict"});function QIt(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 cxr(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"&&QIt(r.consent)}function lxr(){return{dataCollection:ame.dataCollection.defaultValue,telemetry:ame.telemetry.defaultValue,analytics:ame.analytics.defaultValue,errorReporting:ame.errorReporting.defaultValue}}function uxr(){return{dataCollection:!0,telemetry:!0,analytics:!0,errorReporting:!0}}function dxr(){return{dataCollection:!0,telemetry:!1,analytics:!1,errorReporting:!1}}var $4e,ame,K4e=Ut(()=>{"use strict";$4e="1.0.0",ame={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 mH,_H=Ut(()=>{"use strict";mH=(l=>(l.MANUAL="manual",l.AUTO="auto",l.STRICT="strict",l.SMART="smart",l))(mH||{})});function fxr(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 mxr(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 _xr(i){return["major","minor","patch","prerelease","build"].includes(i)}function hxr(i){return["banner","minimal","detailed","silent"].includes(i)}var pxr,jIt=Ut(()=>{"use strict";pxr={checkOnStartup:!0,checkInterval:4,showNotifications:!0,notificationStyle:"banner",includePrerelease:!1}});var fq,eMe,ome,mq=Ut(()=>{"use strict";fq=(I=>(I.DIRECT="direct",I.CLARIFICATION="clarification",I.TODO_LIST="todo_list",I.PLAN="plan",I.PLAN_ADOPT="plan_adopt",I.NO_ACTION="no_action",I.SPAWN_AGENT="spawn_agent",I))(fq||{}),eMe=(I=>(I.PENDING="pending",I.IN_PROGRESS="in_progress",I.PAUSED="paused",I.COMPLETED="completed",I.FAILED="failed",I.SKIPPED="skipped",I.ROLLED_BACK="rolled_back",I))(eMe||{}),ome=(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))(ome||{})});var evt={};Vw(evt,{AGENT_SOURCE_PRIORITY:()=>_q,compareAgentPriority:()=>KIt,createDefaultAgentDefinition:()=>qIt,getAgentSourcePriority:()=>cme,isValidAgentFrontmatter:()=>ume,isValidAgentPermissionMode:()=>lme,isValidAgentSource:()=>BIt,isValidCLIAgentConfig:()=>zIt,parseToolsList:()=>bD,serializeToolsList:()=>$It});function lme(i){return typeof i=="string"&&["default","acceptEditsAsk","bypassPermissions","plan","ignore","acceptEdits","dontAsk"].includes(i)}function BIt(i){return typeof i=="string"&&["project","cli","user","builtin"].includes(i)}function ume(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&&!lme(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 zIt(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&&!lme(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 qIt(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 bD(i){if(!(!i||i.trim()===""))return i.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function $It(i){if(!(!i||i.length===0))return i.join(", ")}function cme(i){return _q.indexOf(i)}function KIt(i,r){return cme(i.source)-cme(r.source)}var _q,dme=Ut(()=>{"use strict";_q=["builtin","user","cli","project"]});function yxr(){return{totalUsageTimeMs:0,lastRatingShownAt:null,lastRatingSubmittedAt:null,totalRatingsSubmitted:0,totalSessions:0,firstUsedAt:new Date().toISOString(),lastActivityAt:null}}function bxr(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 gxr,tvt=Ut(()=>{"use strict";gxr={usageTimeThresholdMs:12e4,cooldownPeriodMs:864e5,activityWindowMs:12e4,cooldownMultiplier:1.5,maxCooldownPeriodMs:6048e5}});function fme(i){return typeof i=="string"&&rvt.includes(i)}function Ixr(i){return typeof i=="string"&&["personal","project"].includes(i)}function vxr(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 tMe(i){return pme.indexOf(i)}function xxr(i,r){return tMe(i.source)-tMe(r.source)}var rvt,pme,rMe=Ut(()=>{"use strict";rvt=["PreToolUse","PostToolUse","UserPromptSubmit","Notification","Stop"],pme=["personal","project"]});function t5(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 nMe,iMe=Ut(()=>{"use strict";nMe="1.0"});var sMe,nvt=Ut(()=>{"use strict";sMe=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 hq,ID,hH,mme,aMe,gq,oMe,cMe,wxr,gH,lMe,Axr,uMe,dMe,pMe,fMe,mMe,_Me,yq,hMe,bq,gMe,IN,r5,ivt,cT,yMe,bMe,Sxr,kxr,n5,Exr,_me,Txr,Cxr,Gxr,Nxr,Fxr,Rxr,svt,Iq,yH,avt,IMe,hme,vq,gme,ovt,cvt,lvt,uvt,xq,Wxr,vMe,xMe,wq,yme,dvt,Zxr,Vxr,Pxr,Pw,vN,pvt,wMe,$v,Dxr,Mxr,Yxr,Oxr,Hxr,Jxr,xN,wN,kb,bme,Lxr,Uxr,Xxr,Qxr,jxr,AMe,fvt,mvt,SMe,Bxr,ju=Ut(()=>{"use strict";hq=".compass",ID=".compass",hH="config.json",mme="session.json",aMe="consent.json",gq="credentials.enc",oMe="logs",cMe="backups",wxr="cache",gH="saved-sessions",lMe="index",Axr="context",uMe="temp",dMe="commands",pMe="agents",fMe="skills",mMe="hooks",_Me="rules",yq="projects",hMe="memory",bq="NOVA.md",gMe="NOVA.local.md",IN="MEMORY.md",r5=200,ivt="chats",cT=16384,yMe=2e5,bMe=8e4,Sxr=80,kxr=10,n5={anthropic:"haiku",ollama:"glm-4.7:cloud",zai:"glm-4.7:cloud",minimax:"glm-4.7:cloud"},Exr="haiku",_me=200,Txr=75,Cxr=5,Gxr=0,Nxr=65,Fxr=!0,Rxr=3,svt=30,Iq=1,yH=100,avt=7,IMe=365,hme=6e4,vq=3e5,gme=6e5,ovt=3e5,cvt=18e5,lvt=50,uvt=1024*1024,xq=100,Wxr=15,vMe=8e3,xMe=4e4,wq=4e3,yme=6e3,dvt=16e3,Zxr=90,Vxr=1e5,Pxr=500*1024*1024,Pw="claude-sonnet-4-6",vN=1,pvt=.5,wMe="haiku",$v="professional",Dxr=4,Mxr="banner",Yxr=4,Oxr=1e3,Hxr=16e3,Jxr=.1,xN={anthropic:{model:Pw,maxTokens:16384,temperature:vN},ollama:{model:"glm-4.7:cloud",endpoint:"https://ollama.com",maxTokens:16384,temperature:pvt},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:uvt,indexOnStartup:!0},safety:{requireApproval:!0,autoApprovePatterns:[],blockedPatterns:[".env*","*.key","*.pem","*.p12","*.pfx","secrets/**","**/secrets/**","**/*.secret","**/credentials*","**/password*"],maxFilesPerOperation:lvt,backupBeforeModify:!0,shellCommandTimeout:vq,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:hme,maxHistoryLength:xq,autoCompactThreshold:8e4,sessionExpiryDays:svt,unleash:!1},update:{checkOnStartup:!0,checkInterval:Dxr,showNotifications:!0,notificationStyle:Mxr,includePrerelease:!1},agentic:{maxIterations:_me,costWarningThreshold:Cxr,costHardCap:Gxr,autoCompactAtPercent:Nxr,stuckDetectionEnabled:Fxr,stuckDetectionThreshold:Rxr,maxIterationsPerTask:Txr}},wN=["anthropic","ollama","zai","minimax"],kb={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",EXPERIMENTAL_AGENT_TEAMS:"COMPASS_EXPERIMENTAL_AGENT_TEAMS"},bme={anthropic:kb.API_KEY,ollama:kb.OLLAMA_API_KEY,zai:kb.ZAI_API_KEY,minimax:kb.MINIMAX_API_KEY},Lxr="1.0.95",Uxr="Compass CLI",Xxr="",Qxr="1.0.0",jxr={".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"},AMe=["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","**/__snapshots__/**","**/fixtures/**/*.json","*.d.ts.map"],fvt=["*.sql","*.csv","*.tsv","*.parquet"],mvt=50,SMe=["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".output",".cache",".parcel-cache","vendor","__pycache__",".pytest_cache","target","bin","obj"],Bxr=[".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 vD,_vt,Ime=Ut(()=>{"use strict";XIt();K4e();_H();jIt();mq();dme();tvt();rMe();iMe();nvt();ju();vD="BASIC",_vt=["BASIC","PRO","MAX","ENTERPRISE","UNLIMITED"]});var kMe={};Vw(kMe,{CLAUDE_MODELS:()=>Dw,MODEL_ALIASES:()=>xD,NO_SUBSCRIPTION_DAILY_TOKEN_LIMIT:()=>hvt,calculateModelCost:()=>Avt,compareModels:()=>Svt,getAvailableAliases:()=>Ivt,getAvailableModelIds:()=>bvt,getAvailableModels:()=>i5,getCheapestModel:()=>Evt,getDefaultModel:()=>xvt,getDefaultModelId:()=>wvt,getModelConfig:()=>Gm,getModelDescription:()=>vme,getModelKnowledgeCutoff:()=>Aq,getModelTier:()=>Cvt,getModelsByCapability:()=>kvt,getMostCapableModel:()=>Tvt,hasFullAccess:()=>gvt,isAnthropicModel:()=>yvt,isValidModel:()=>vvt,resolveModelId:()=>wy});function gvt(i){return i==="trial"||i==="active"}function wy(i){let r=i.toLowerCase();if(xD[r])return xD[r];for(let n of Object.keys(Dw))if(n.toLowerCase()===r)return n;return i}function Gm(i){let r=wy(i);return Dw[r]}function Aq(i){return Gm(i)?.knowledgeCutoff||"Unknown"}function yvt(i){return Gm(i)?.provider==="anthropic"}function i5(){return Object.values(Dw)}function bvt(){return Object.keys(Dw)}function Ivt(){return Object.keys(xD)}function vvt(i){return wy(i)in Dw}function xvt(){return Dw["claude-sonnet-4-6"]}function wvt(){return"claude-sonnet-4-6"}function Avt(i,r,n){let o=Gm(i);if(!o)return null;let l=r/1e6*o.pricing.inputPricePerMillion,p=n/1e6*o.pricing.outputPricePerMillion;return l+p}function Svt(i,r,n){let o=Gm(i),l=Gm(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 kvt(i){return i5().filter(r=>r.capabilities[i])}function Evt(){return i5().reduce((r,n)=>n.pricing.inputPricePerMillion<r.pricing.inputPricePerMillion?n:r)}function Tvt(){return Dw["claude-opus-4-6"]}function Cvt(i){let r=wy(i);if(r.includes("haiku"))return"economy";if(r.includes("sonnet"))return"balanced";if(r.includes("opus"))return"premium"}function vme(i){let r=wy(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 hvt,Dw,xD,O2=Ut(()=>{"use strict";hvt=15e4;Dw={"glm-5:cloud":{id:"glm-5:cloud",name:"Z.AI GLM 5",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"January 2025"},"glm-4.7:cloud":{id:"glm-4.7:cloud",name:"Z.AI GLM 4.7",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"January 2025"},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!1},knowledgeCutoff:"January 2025"},"kimi-k2.5:cloud":{id:"kimi-k2.5:cloud",name:"Kimi K2.5",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!1},knowledgeCutoff:"January 2025"},"gemini-3-pro-preview":{id:"gemini-3-pro-preview",name:"Gemini 3 Pro",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"January 2025"},"claude-sonnet-4-6":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15,cacheWrite5mPricePerMillion:3.75,cacheWrite1hPricePerMillion:6,cacheHitPricePerMillion:.3},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"January 2025"},"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:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15,cacheWrite5mPricePerMillion:3.75,cacheWrite1hPricePerMillion:6,cacheHitPricePerMillion:.3},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"April 2024"},"claude-opus-4-6":{id:"claude-opus-4-6",name:"Claude Opus 4.6",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:5,outputPricePerMillion:25,cacheWrite5mPricePerMillion:6.25,cacheWrite1hPricePerMillion:10,cacheHitPricePerMillion:.5},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!0,complexityClassification:!0},knowledgeCutoff:"January 2025"},"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:16384,pricing:{inputPricePerMillion:5,outputPricePerMillion:25,cacheWrite5mPricePerMillion:6.25,cacheWrite1hPricePerMillion:10,cacheHitPricePerMillion:.5},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!0,complexityClassification:!0},knowledgeCutoff:"April 2024"},"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:16384,pricing:{inputPricePerMillion:1,outputPricePerMillion:5,cacheWrite5mPricePerMillion:1.25,cacheWrite1hPricePerMillion:2,cacheHitPricePerMillion:.1},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"April 2024"}},xD={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.7":"minimax-m2.7: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-6",balanced:"claude-sonnet-4-6",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.7:cloud",creative:"gemini-3-pro-preview",s:"claude-sonnet-4-6",o:"claude-opus-4-6",h:"claude-haiku-4-5-20251001",g:"glm-5:cloud",m:"minimax-m2.7:cloud",k:"kimi-k2.5:cloud",p:"gemini-3-pro-preview"}});function zxr(){let i=new Map;for(let r of bH){let n=i.get(r.category)||[];n.push(r),i.set(r.category,n)}return i}var Sq,EMe,TMe,bH,CMe=Ut(()=>{"use strict";Sq={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}},EMe=36e5,TMe=3e3,bH=[{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 GMe,xme,kq,NMe,Eq,wme,Ame,AN,Tq=Ut(()=>{"use strict";GMe="Schedule.md",xme="sched-",kq=8,NMe=["active","paused","completed"],Eq=`# Scheduled Tasks
1
+ var j2r=Object.create;var sme=Object.defineProperty;var B2r=Object.getOwnPropertyDescriptor;var z2r=Object.getOwnPropertyNames;var q2r=Object.getPrototypeOf,$2r=Object.prototype.hasOwnProperty;var js=(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 Ut=(i,r)=>()=>(i&&(r=i(i=0)),r);var pt=(i,r)=>()=>(r||i((r={exports:{}}).exports,r),r.exports),Vw=(i,r)=>{for(var n in r)sme(i,n,{get:r[n],enumerable:!0})},UIt=(i,r,n,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let l of z2r(r))!$2r.call(i,l)&&l!==n&&sme(i,l,{get:()=>r[l],enumerable:!(o=B2r(r,l))||o.enumerable});return i};var Go=(i,r,n)=>(n=i!=null?j2r(q2r(i)):{},UIt(r||!i||!i.__esModule?sme(n,"default",{value:i,enumerable:!0}):n,i)),K2r=i=>UIt(sme({},"__esModule",{value:!0}),i);function exr(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 txr(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 rxr(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 nxr(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 ixr(i){if(typeof i!="object"||i===null)return!1;let r=i;return typeof r=="object"&&r!==null}function sxr(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 axr(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 oxr(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 XIt=Ut(()=>{"use strict"});function QIt(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 cxr(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"&&QIt(r.consent)}function lxr(){return{dataCollection:ame.dataCollection.defaultValue,telemetry:ame.telemetry.defaultValue,analytics:ame.analytics.defaultValue,errorReporting:ame.errorReporting.defaultValue}}function uxr(){return{dataCollection:!0,telemetry:!0,analytics:!0,errorReporting:!0}}function dxr(){return{dataCollection:!0,telemetry:!1,analytics:!1,errorReporting:!1}}var $4e,ame,K4e=Ut(()=>{"use strict";$4e="1.0.0",ame={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 mH,_H=Ut(()=>{"use strict";mH=(l=>(l.MANUAL="manual",l.AUTO="auto",l.STRICT="strict",l.SMART="smart",l))(mH||{})});function fxr(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 mxr(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 _xr(i){return["major","minor","patch","prerelease","build"].includes(i)}function hxr(i){return["banner","minimal","detailed","silent"].includes(i)}var pxr,jIt=Ut(()=>{"use strict";pxr={checkOnStartup:!0,checkInterval:4,showNotifications:!0,notificationStyle:"banner",includePrerelease:!1}});var fq,eMe,ome,mq=Ut(()=>{"use strict";fq=(I=>(I.DIRECT="direct",I.CLARIFICATION="clarification",I.TODO_LIST="todo_list",I.PLAN="plan",I.PLAN_ADOPT="plan_adopt",I.NO_ACTION="no_action",I.SPAWN_AGENT="spawn_agent",I))(fq||{}),eMe=(I=>(I.PENDING="pending",I.IN_PROGRESS="in_progress",I.PAUSED="paused",I.COMPLETED="completed",I.FAILED="failed",I.SKIPPED="skipped",I.ROLLED_BACK="rolled_back",I))(eMe||{}),ome=(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))(ome||{})});var evt={};Vw(evt,{AGENT_SOURCE_PRIORITY:()=>_q,compareAgentPriority:()=>KIt,createDefaultAgentDefinition:()=>qIt,getAgentSourcePriority:()=>cme,isValidAgentFrontmatter:()=>ume,isValidAgentPermissionMode:()=>lme,isValidAgentSource:()=>BIt,isValidCLIAgentConfig:()=>zIt,parseToolsList:()=>bD,serializeToolsList:()=>$It});function lme(i){return typeof i=="string"&&["default","acceptEditsAsk","bypassPermissions","plan","ignore","acceptEdits","dontAsk"].includes(i)}function BIt(i){return typeof i=="string"&&["project","cli","user","builtin"].includes(i)}function ume(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&&!lme(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 zIt(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&&!lme(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 qIt(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 bD(i){if(!(!i||i.trim()===""))return i.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function $It(i){if(!(!i||i.length===0))return i.join(", ")}function cme(i){return _q.indexOf(i)}function KIt(i,r){return cme(i.source)-cme(r.source)}var _q,dme=Ut(()=>{"use strict";_q=["builtin","user","cli","project"]});function yxr(){return{totalUsageTimeMs:0,lastRatingShownAt:null,lastRatingSubmittedAt:null,totalRatingsSubmitted:0,totalSessions:0,firstUsedAt:new Date().toISOString(),lastActivityAt:null}}function bxr(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 gxr,tvt=Ut(()=>{"use strict";gxr={usageTimeThresholdMs:12e4,cooldownPeriodMs:864e5,activityWindowMs:12e4,cooldownMultiplier:1.5,maxCooldownPeriodMs:6048e5}});function fme(i){return typeof i=="string"&&rvt.includes(i)}function Ixr(i){return typeof i=="string"&&["personal","project"].includes(i)}function vxr(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 tMe(i){return pme.indexOf(i)}function xxr(i,r){return tMe(i.source)-tMe(r.source)}var rvt,pme,rMe=Ut(()=>{"use strict";rvt=["PreToolUse","PostToolUse","UserPromptSubmit","Notification","Stop"],pme=["personal","project"]});function t5(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 nMe,iMe=Ut(()=>{"use strict";nMe="1.0"});var sMe,nvt=Ut(()=>{"use strict";sMe=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 hq,ID,hH,mme,aMe,gq,oMe,cMe,wxr,gH,lMe,Axr,uMe,dMe,pMe,fMe,mMe,_Me,yq,hMe,bq,gMe,IN,r5,ivt,cT,yMe,bMe,Sxr,kxr,n5,Exr,_me,Txr,Cxr,Gxr,Nxr,Fxr,Rxr,svt,Iq,yH,avt,IMe,hme,vq,gme,ovt,cvt,lvt,uvt,xq,Wxr,vMe,xMe,wq,yme,dvt,Zxr,Vxr,Pxr,Pw,vN,pvt,wMe,$v,Dxr,Mxr,Yxr,Oxr,Hxr,Jxr,xN,wN,kb,bme,Lxr,Uxr,Xxr,Qxr,jxr,AMe,fvt,mvt,SMe,Bxr,ju=Ut(()=>{"use strict";hq=".compass",ID=".compass",hH="config.json",mme="session.json",aMe="consent.json",gq="credentials.enc",oMe="logs",cMe="backups",wxr="cache",gH="saved-sessions",lMe="index",Axr="context",uMe="temp",dMe="commands",pMe="agents",fMe="skills",mMe="hooks",_Me="rules",yq="projects",hMe="memory",bq="NOVA.md",gMe="NOVA.local.md",IN="MEMORY.md",r5=200,ivt="chats",cT=16384,yMe=2e5,bMe=8e4,Sxr=80,kxr=10,n5={anthropic:"haiku",ollama:"glm-4.7:cloud",zai:"glm-4.7:cloud",minimax:"glm-4.7:cloud"},Exr="haiku",_me=200,Txr=75,Cxr=5,Gxr=0,Nxr=65,Fxr=!0,Rxr=3,svt=30,Iq=1,yH=100,avt=7,IMe=365,hme=6e4,vq=3e5,gme=6e5,ovt=3e5,cvt=18e5,lvt=50,uvt=1024*1024,xq=100,Wxr=15,vMe=8e3,xMe=4e4,wq=4e3,yme=6e3,dvt=16e3,Zxr=90,Vxr=1e5,Pxr=500*1024*1024,Pw="claude-sonnet-4-6",vN=1,pvt=.5,wMe="haiku",$v="professional",Dxr=4,Mxr="banner",Yxr=4,Oxr=1e3,Hxr=16e3,Jxr=.1,xN={anthropic:{model:Pw,maxTokens:16384,temperature:vN},ollama:{model:"glm-4.7:cloud",endpoint:"https://ollama.com",maxTokens:16384,temperature:pvt},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:uvt,indexOnStartup:!0},safety:{requireApproval:!0,autoApprovePatterns:[],blockedPatterns:[".env*","*.key","*.pem","*.p12","*.pfx","secrets/**","**/secrets/**","**/*.secret","**/credentials*","**/password*"],maxFilesPerOperation:lvt,backupBeforeModify:!0,shellCommandTimeout:vq,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:hme,maxHistoryLength:xq,autoCompactThreshold:8e4,sessionExpiryDays:svt,unleash:!1},update:{checkOnStartup:!0,checkInterval:Dxr,showNotifications:!0,notificationStyle:Mxr,includePrerelease:!1},agentic:{maxIterations:_me,costWarningThreshold:Cxr,costHardCap:Gxr,autoCompactAtPercent:Nxr,stuckDetectionEnabled:Fxr,stuckDetectionThreshold:Rxr,maxIterationsPerTask:Txr}},wN=["anthropic","ollama","zai","minimax"],kb={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",EXPERIMENTAL_AGENT_TEAMS:"COMPASS_EXPERIMENTAL_AGENT_TEAMS"},bme={anthropic:kb.API_KEY,ollama:kb.OLLAMA_API_KEY,zai:kb.ZAI_API_KEY,minimax:kb.MINIMAX_API_KEY},Lxr="1.0.96",Uxr="Compass CLI",Xxr="",Qxr="1.0.0",jxr={".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"},AMe=["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","**/__snapshots__/**","**/fixtures/**/*.json","*.d.ts.map"],fvt=["*.sql","*.csv","*.tsv","*.parquet"],mvt=50,SMe=["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".output",".cache",".parcel-cache","vendor","__pycache__",".pytest_cache","target","bin","obj"],Bxr=[".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 vD,_vt,Ime=Ut(()=>{"use strict";XIt();K4e();_H();jIt();mq();dme();tvt();rMe();iMe();nvt();ju();vD="BASIC",_vt=["BASIC","PRO","MAX","ENTERPRISE","UNLIMITED"]});var kMe={};Vw(kMe,{CLAUDE_MODELS:()=>Dw,MODEL_ALIASES:()=>xD,NO_SUBSCRIPTION_DAILY_TOKEN_LIMIT:()=>hvt,calculateModelCost:()=>Avt,compareModels:()=>Svt,getAvailableAliases:()=>Ivt,getAvailableModelIds:()=>bvt,getAvailableModels:()=>i5,getCheapestModel:()=>Evt,getDefaultModel:()=>xvt,getDefaultModelId:()=>wvt,getModelConfig:()=>Gm,getModelDescription:()=>vme,getModelKnowledgeCutoff:()=>Aq,getModelTier:()=>Cvt,getModelsByCapability:()=>kvt,getMostCapableModel:()=>Tvt,hasFullAccess:()=>gvt,isAnthropicModel:()=>yvt,isValidModel:()=>vvt,resolveModelId:()=>wy});function gvt(i){return i==="trial"||i==="active"}function wy(i){let r=i.toLowerCase();if(xD[r])return xD[r];for(let n of Object.keys(Dw))if(n.toLowerCase()===r)return n;return i}function Gm(i){let r=wy(i);return Dw[r]}function Aq(i){return Gm(i)?.knowledgeCutoff||"Unknown"}function yvt(i){return Gm(i)?.provider==="anthropic"}function i5(){return Object.values(Dw)}function bvt(){return Object.keys(Dw)}function Ivt(){return Object.keys(xD)}function vvt(i){return wy(i)in Dw}function xvt(){return Dw["claude-sonnet-4-6"]}function wvt(){return"claude-sonnet-4-6"}function Avt(i,r,n){let o=Gm(i);if(!o)return null;let l=r/1e6*o.pricing.inputPricePerMillion,p=n/1e6*o.pricing.outputPricePerMillion;return l+p}function Svt(i,r,n){let o=Gm(i),l=Gm(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 kvt(i){return i5().filter(r=>r.capabilities[i])}function Evt(){return i5().reduce((r,n)=>n.pricing.inputPricePerMillion<r.pricing.inputPricePerMillion?n:r)}function Tvt(){return Dw["claude-opus-4-6"]}function Cvt(i){let r=wy(i);if(r.includes("haiku"))return"economy";if(r.includes("sonnet"))return"balanced";if(r.includes("opus"))return"premium"}function vme(i){let r=wy(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 hvt,Dw,xD,O2=Ut(()=>{"use strict";hvt=15e4;Dw={"glm-5:cloud":{id:"glm-5:cloud",name:"Z.AI GLM 5",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"January 2025"},"glm-4.7:cloud":{id:"glm-4.7:cloud",name:"Z.AI GLM 4.7",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"January 2025"},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!1},knowledgeCutoff:"January 2025"},"kimi-k2.5:cloud":{id:"kimi-k2.5:cloud",name:"Kimi K2.5",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!1},knowledgeCutoff:"January 2025"},"gemini-3-pro-preview":{id:"gemini-3-pro-preview",name:"Gemini 3 Pro",provider:"ollama",baseUrl:"https://ollama.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"January 2025"},"claude-sonnet-4-6":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15,cacheWrite5mPricePerMillion:3.75,cacheWrite1hPricePerMillion:6,cacheHitPricePerMillion:.3},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"January 2025"},"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:16384,pricing:{inputPricePerMillion:3,outputPricePerMillion:15,cacheWrite5mPricePerMillion:3.75,cacheWrite1hPricePerMillion:6,cacheHitPricePerMillion:.3},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"April 2024"},"claude-opus-4-6":{id:"claude-opus-4-6",name:"Claude Opus 4.6",provider:"anthropic",baseUrl:"https://api.anthropic.com",contextWindow:2e5,maxOutputTokens:16384,pricing:{inputPricePerMillion:5,outputPricePerMillion:25,cacheWrite5mPricePerMillion:6.25,cacheWrite1hPricePerMillion:10,cacheHitPricePerMillion:.5},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!0,complexityClassification:!0},knowledgeCutoff:"January 2025"},"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:16384,pricing:{inputPricePerMillion:5,outputPricePerMillion:25,cacheWrite5mPricePerMillion:6.25,cacheWrite1hPricePerMillion:10,cacheHitPricePerMillion:.5},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!0,complexityClassification:!0},knowledgeCutoff:"April 2024"},"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:16384,pricing:{inputPricePerMillion:1,outputPricePerMillion:5,cacheWrite5mPricePerMillion:1.25,cacheWrite1hPricePerMillion:2,cacheHitPricePerMillion:.1},capabilities:{vision:!0,toolUse:!0,streaming:!0,extendedThinking:!1,complexityClassification:!0},knowledgeCutoff:"April 2024"}},xD={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.7":"minimax-m2.7: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-6",balanced:"claude-sonnet-4-6",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.7:cloud",creative:"gemini-3-pro-preview",s:"claude-sonnet-4-6",o:"claude-opus-4-6",h:"claude-haiku-4-5-20251001",g:"glm-5:cloud",m:"minimax-m2.7:cloud",k:"kimi-k2.5:cloud",p:"gemini-3-pro-preview"}});function zxr(){let i=new Map;for(let r of bH){let n=i.get(r.category)||[];n.push(r),i.set(r.category,n)}return i}var Sq,EMe,TMe,bH,CMe=Ut(()=>{"use strict";Sq={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}},EMe=36e5,TMe=3e3,bH=[{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 GMe,xme,kq,NMe,Eq,wme,Ame,AN,Tq=Ut(()=>{"use strict";GMe="Schedule.md",xme="sched-",kq=8,NMe=["active","paused","completed"],Eq=`# 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.
@@ -502,7 +502,7 @@ GFS4: `),console.error(i)});d_[Ay]||(Nxt=global[Ay]||[],Rxt(d_,Nxt),d_.close=(fu
502
502
  ${o.stack||o.message}`);else if(typeof o=="object")try{l.push(JSON.stringify(o,null,2))}catch{l.push(String(o))}else l.push(String(o));return l.join(" ")}colorize(r,n){if(!this.config.colorOutput)return n;switch(r){case"debug":return Dn.gray(n);case"info":return Dn.blue(n);case"warn":return Dn.yellow(n);case"error":return Dn.red(n);default:return n}}async writeToFile(r){if(this.config.fileOutput)try{let n=await this.ensureLogFile();n&&await p6e.default.appendFile(n,r+`
503
503
  `)}catch{}}log(r,n,o){if(!this.shouldLog(r))return;let l=this.formatMessage(r,n,o),p=this.colorize(r,l);process.stderr.write(p+`
504
504
  `),this.writeToFile(l).catch(()=>{})}debug(r,n){this.log("debug",r,n)}info(r,n){this.log("info",r,n)}warn(r,n){this.log("warn",r,n)}error(r,n){this.log("error",r,n)}output(r){console.log(r)}child(r){return new m6e(this,r)}setLevel(r){this.config.level=r}getLevel(){return this.config.level}setFileOutput(r){this.config.fileOutput=r}setColorOutput(r){this.config.colorOutput=r}setTimestamps(r){this.config.timestamps=r}getLogFilePath(){return this.logFilePath}isLevelEnabled(r){return this.shouldLog(r)}},m6e=class i{constructor(r,n){this.parent=r;this.prefix=n}parent;prefix;debug(r,n){this.parent.debug(`[${this.prefix}] ${r}`,n)}info(r,n){this.parent.info(`[${this.prefix}] ${r}`,n)}warn(r,n){this.parent.warn(`[${this.prefix}] ${r}`,n)}error(r,n){this.parent.error(`[${this.prefix}] ${r}`,n)}child(r){return new i(this.parent,`${this.prefix}:${r}`)}},$=new f6e});var g6e={};Vw(g6e,{appendFile:()=>xCr,copy:()=>TN,createSymlink:()=>SCr,emptyDir:()=>ICr,ensureArchiveDir:()=>h6e,ensureDir:()=>Zl,getArchiveDir:()=>a$,getFileSize:()=>gCr,getFilesRecursive:()=>ECr,getModificationTime:()=>yCr,isDirectory:()=>s$,isFile:()=>i_e,isReadable:()=>wCr,isSymlink:()=>hCr,isWritable:()=>ACr,listArchiveFiles:()=>b5,move:()=>_Cr,pathExists:()=>ea,readDir:()=>MH,readDirWithTypes:()=>WAt,readFileBuffer:()=>vCr,readSymlink:()=>kCr,remove:()=>G0,safeReadFile:()=>ed,safeReadJson:()=>_d,safeWriteFile:()=>C0,safeWriteJson:()=>X_,stat:()=>Sy,touch:()=>bCr,writeFileBuffer:()=>_6e});import Ow from"path";async function ed(i,r={}){let{encoding:n="utf8",fallback:o}=r;try{return await ol.default.readFile(i,{encoding:n})}catch(l){if(l.code==="ENOENT")return o??null;throw $.error(`Failed to read file: ${i}`,l),l}}async function _d(i,r){try{let n=await ed(i);return n===null?r??null:JSON.parse(n)}catch(n){if(n instanceof SyntaxError&&($.warn(`Invalid JSON in file: ${i}`,n),r!==void 0)||r!==void 0)return r;throw $.error(`Failed to parse JSON file: ${i}`,n),n}}async function C0(i,r,n={}){let{encoding:o="utf8",createDir:l=!0,atomic:p=!0,backup:h=!1,backupDir:I,mode:k}=n;try{if(l&&await ol.default.ensureDir(Ow.dirname(i)),h&&await ol.default.pathExists(i)){let N=I?Ow.join(I,Ow.basename(i)+".bak"):i+".bak";I&&await ol.default.ensureDir(I),await ol.default.copy(i,N,{overwrite:!0}),$.debug(`Backup created: ${N}`)}if(p){let N=`${i}.tmp.${Date.now()}.${process.pid}`;try{await ol.default.writeFile(N,r,{encoding:o,mode:k}),await ol.default.rename(N,i)}catch(W){try{await ol.default.remove(N)}catch{}throw W}}else await ol.default.writeFile(i,r,{encoding:o,mode:k})}catch(N){throw $.error(`Failed to write file: ${i}`,N),N}}async function X_(i,r,n={}){let o=JSON.stringify(r,null,2);await C0(i,o,n)}async function Zl(i){await ol.default.ensureDir(i)}async function ea(i){return ol.default.pathExists(i)}async function G0(i){await ol.default.remove(i)}async function TN(i,r,n){await ol.default.copy(i,r,n)}async function _Cr(i,r,n){await ol.default.move(i,r,n)}async function Sy(i){try{return await ol.default.stat(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function MH(i){try{return await ol.default.readdir(i)}catch(r){if(r.code==="ENOENT")return[];throw r}}async function WAt(i){try{return await ol.default.readdir(i,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}}async function s$(i){try{return(await ol.default.stat(i)).isDirectory()}catch{return!1}}async function i_e(i){try{return(await ol.default.stat(i)).isFile()}catch{return!1}}async function hCr(i){try{return(await ol.default.lstat(i)).isSymbolicLink()}catch{return!1}}async function gCr(i){return(await Sy(i))?.size??0}async function yCr(i){return(await Sy(i))?.mtime??null}async function bCr(i){await ol.default.ensureFile(i);let r=new Date;await ol.default.utimes(i,r,r)}async function ICr(i){await ol.default.emptyDir(i)}async function vCr(i){try{return await ol.default.readFile(i)}catch(r){if(r.code==="ENOENT")return null;throw $.error(`Failed to read file as buffer: ${i}`,r),r}}async function _6e(i,r,n={}){let{createDir:o=!0,atomic:l=!0,backup:p=!1,backupDir:h,mode:I}=n;try{if(o&&await ol.default.ensureDir(Ow.dirname(i)),p&&await ol.default.pathExists(i)){let k=h?Ow.join(h,Ow.basename(i)+".bak"):i+".bak";h&&await ol.default.ensureDir(h),await ol.default.copy(i,k,{overwrite:!0})}if(l){let k=`${i}.tmp.${Date.now()}.${process.pid}`;try{await ol.default.writeFile(k,r,{mode:I}),await ol.default.rename(k,i)}catch(N){try{await ol.default.remove(k)}catch{}throw N}}else await ol.default.writeFile(i,r,{mode:I})}catch(k){throw $.error(`Failed to write buffer to file: ${i}`,k),k}}async function xCr(i,r,n={}){let{encoding:o="utf8",createDir:l=!0}=n;try{l&&await ol.default.ensureDir(Ow.dirname(i)),await ol.default.appendFile(i,r,{encoding:o})}catch(p){throw $.error(`Failed to append to file: ${i}`,p),p}}async function wCr(i){try{return await ol.default.access(i,ol.default.constants.R_OK),!0}catch{return!1}}async function ACr(i){try{return await ol.default.access(i,ol.default.constants.W_OK),!0}catch{try{let r=Ow.dirname(i);return await ol.default.access(r,ol.default.constants.W_OK),!0}catch{return!1}}}async function SCr(i,r){await ol.default.ensureDir(Ow.dirname(r)),await ol.default.symlink(i,r)}async function kCr(i){try{return await ol.default.readlink(i)}catch{return null}}async function ECr(i,r={}){let{maxDepth:n,filter:o}=r,l=[];async function p(h,I){if(n!==void 0&&I>n)return;let k=await WAt(h);for(let N of k){let W=Ow.join(h,N.name),H=Ow.relative(i,W);N.isDirectory()?await p(W,I+1):N.isFile()&&(!o||o(H))&&l.push(H)}}return await s$(i)&&await p(i,0),l}function a$(i){return Ow.join(i,ID,ivt)}async function h6e(i){let r=a$(i);await ol.default.ensureDir(r)}async function b5(i){let r=a$(i);try{return(await ol.default.readdir(r)).filter(o=>o.endsWith(".json")).sort()}catch(n){if(n.code==="ENOENT")return[];throw $.error(`Failed to list archive files: ${r}`,n),n}}var ol,Dp=Ut(()=>{"use strict";ol=Go(MI(),1);Xa();ju()});function rn(i=new Date){return i.toISOString()}function TCr(i){return(typeof i=="string"?new Date(i):i).toLocaleDateString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function CCr(i){if(i<1e3)return`${i}ms`;let r=Math.floor(i/1e3),n=Math.floor(r/60),o=Math.floor(n/60),l=Math.floor(o/24);return l>0?`${l}d ${o%24}h`:o>0?`${o}h ${n%60}m`:n>0?`${n}m ${r%60}s`:`${r}s`}function GCr(i){let r=typeof i=="string"?new Date(i):i,o=new Date().getTime()-r.getTime(),l=Math.floor(o/1e3),p=Math.floor(l/60),h=Math.floor(p/60),I=Math.floor(h/24);return I>0?`${I} day${I===1?"":"s"} ago`:h>0?`${h} hour${h===1?"":"s"} ago`:p>0?`${p} minute${p===1?"":"s"} ago`:"just now"}function NCr(i){let r=["B","KB","MB","GB","TB"],n=i,o=0;for(;n>=1024&&o<r.length-1;)n/=1024,o++;return`${n.toFixed(o===0?0:1)} ${r[o]}`}function FCr(i,r="USD"){let o={USD:"$",EUR:"\u20AC",GBP:"\xA3",JPY:"\xA5"}[r]||r+" ";return i<.01?`${o}${i.toFixed(4)}`:i<1?`${o}${i.toFixed(3)}`:`${o}${i.toFixed(2)}`}function RCr(i){return i.toLocaleString()}function ZAt(i,r=0){return`${i.toFixed(r)}%`}function WCr(i,r){return i.length<=r?i:i.slice(0,r-3)+"..."}function ZCr(i,r,n="left"){if(i.length>=r)return i.slice(0,r);let o=r-i.length;switch(n){case"right":return" ".repeat(o)+i;case"center":{let l=Math.floor(o/2),p=o-l;return" ".repeat(l)+i+" ".repeat(p)}default:return i+" ".repeat(o)}}function VCr(i,r,n=20){let o=Math.min(100,Math.max(0,i/r*100)),l=Math.round(o/100*n),p=n-l,h="\u2588".repeat(l)+"\u2591".repeat(p),I=ZAt(o);return`[${h}] ${I}`}function PCr(i,r="and"){if(i.length===0)return"";if(i.length===1)return i[0];if(i.length===2)return`${i[0]} ${r} ${i[1]}`;let n=i.slice(0,-1).join(", "),o=i[i.length-1];return`${n}, ${r} ${o}`}function DCr(i,r){switch(r){case"success":return Dn.green(i);case"warning":return Dn.yellow(i);case"error":return Dn.red(i);case"info":return Dn.blue(i);case"muted":return Dn.gray(i);default:return i}}var Q_=Ut(()=>{"use strict";LS()});import VAt from"path";function y6e(i,r=MCr){if(i)return i.length<=r?i:i.substring(0,r)+"..."}function zo(i){return s_e?i&&s_e.setProjectRoot(i):s_e=new I6e(i),s_e}var b6e,MCr,I6e,s_e,t1=Ut(()=>{"use strict";b6e=Go(MI(),1);Q_();Xa();i$();MCr=100;I6e=class{projectRoot;currentLogFile=null;logFileInitialized=!1;enabled=!0;sessionId=null;constructor(r){this.projectRoot=r||process.cwd()}setProjectRoot(r){this.projectRoot=r,this.currentLogFile=null,this.logFileInitialized=!1}setSessionId(r){this.sessionId=r}getSessionId(){return this.sessionId}getLogFilePath(){return this.currentLogFile}setEnabled(r){this.enabled=r}formatDateForFilename(r){let n=String(r.getDate()).padStart(2,"0"),o=String(r.getMonth()+1).padStart(2,"0"),l=String(r.getFullYear()).slice(-2);return`${n}-${o}-${l}`}async ensureLogFile(){if(this.currentLogFile&&this.logFileInitialized)return this.currentLogFile;let r=VAt.join(this.projectRoot,".compass",".logs");try{await b6e.default.ensureDir(r)}catch(o){return $.debug("Failed to create .logs directory for system events",o),this.enabled=!1,""}await y5(r);let n=this.formatDateForFilename(new Date);return this.currentLogFile=VAt.join(r,`system-${n}.jsonl`),this.logFileInitialized=!0,this.currentLogFile}async writeEvent(r){if(this.enabled)try{let n=await this.ensureLogFile();if(!n)return;let o=JSON.stringify(r)+`
505
- `;await b6e.default.appendFile(n,o)}catch(n){$.debug("Failed to write system event",n)}}async logSessionStart(r,n){this.sessionId=r,await this.writeEvent({ts:rn(),level:"info",event:"session_start",component:"Session",session_id:r,data:{projectPath:n}})}async logSessionEnd(){await this.writeEvent({ts:rn(),level:"info",event:"session_end",component:"Session",session_id:this.sessionId||void 0})}async logBashExecuted(r){await this.writeEvent({ts:rn(),level:r.exitCode===0?"info":"warn",event:"bash_executed",component:"ShellExecutor",session_id:this.sessionId||void 0,data:{command:r.command,cwd:r.cwd,exitCode:r.exitCode,duration_ms:r.duration_ms,stdout:y6e(r.stdout),stderr:y6e(r.stderr),timedOut:r.timedOut,killed:r.killed}})}async logFileRead(r,n,o=!0,l){await this.writeEvent({ts:rn(),level:o?"info":"error",event:"file_read",component:"FileService",session_id:this.sessionId||void 0,data:{path:r,size:n,operation:"read",success:o,error:l}})}async logFileWrite(r,n,o=!0,l){await this.writeEvent({ts:rn(),level:o?"info":"error",event:"file_write",component:"FileService",session_id:this.sessionId||void 0,data:{path:r,size:n,operation:"write",success:o,error:l}})}async logFileDelete(r,n=!0,o){await this.writeEvent({ts:rn(),level:n?"info":"error",event:"file_delete",component:"FileService",session_id:this.sessionId||void 0,data:{path:r,operation:"delete",success:n,error:o}})}async logFileRename(r,n,o=!0,l){await this.writeEvent({ts:rn(),level:o?"info":"error",event:"file_rename",component:"FileService",session_id:this.sessionId||void 0,data:{path:r,newPath:n,operation:"rename",success:o,error:l}})}async logToolExecuted(r){await this.writeEvent({ts:rn(),level:r.success?"info":"error",event:"tool_executed",component:"ToolRegistry",session_id:this.sessionId||void 0,data:{name:r.name,executionId:r.executionId,success:r.success,duration_ms:r.duration_ms,input:r.input,output:y6e(r.output),error:r.error}})}async logError(r,n,o){await this.writeEvent({ts:rn(),level:"error",event:"error",component:r,session_id:this.sessionId||void 0,data:{error:n,details:o}})}async logEvent(r,n,o,l){await this.writeEvent({ts:rn(),level:r,event:n,component:o,session_id:this.sessionId||void 0,data:l})}async logConfigChanged(r){await this.writeEvent({ts:rn(),level:"info",event:"config_changed",component:"ConfigManager",session_id:this.sessionId||void 0,data:r})}async logProviderChanged(r){await this.writeEvent({ts:rn(),level:"info",event:"provider_changed",component:"ProviderManager",session_id:this.sessionId||void 0,data:r})}async logModelChanged(r){await this.writeEvent({ts:rn(),level:"info",event:"model_changed",component:"ProviderManager",session_id:this.sessionId||void 0,data:r})}async logMcpConnected(r){await this.writeEvent({ts:rn(),level:"info",event:"mcp_connected",component:"McpManager",session_id:this.sessionId||void 0,data:r})}async logMcpDisconnected(r){await this.writeEvent({ts:rn(),level:"warn",event:"mcp_disconnected",component:"McpManager",session_id:this.sessionId||void 0,data:r})}async logMcpError(r){await this.writeEvent({ts:rn(),level:"error",event:"mcp_error",component:"McpManager",session_id:this.sessionId||void 0,data:r})}async logToolRegistered(r,n){await this.writeEvent({ts:rn(),level:"debug",event:"tool_registered",component:"ToolRegistry",session_id:this.sessionId||void 0,data:{name:r,source:n}})}async logToolFailed(r,n,o){await this.writeEvent({ts:rn(),level:"error",event:"tool_failed",component:"ToolRegistry",session_id:this.sessionId||void 0,data:{name:r,error:n,executionId:o}})}async logWorkflowStarted(r){await this.writeEvent({ts:rn(),level:"info",event:"workflow_started",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logWorkflowCompleted(r){await this.writeEvent({ts:rn(),level:"info",event:"workflow_completed",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logWorkflowFailed(r){await this.writeEvent({ts:rn(),level:"error",event:"workflow_failed",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logStepStarted(r){await this.writeEvent({ts:rn(),level:"info",event:"step_started",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logStepCompleted(r){await this.writeEvent({ts:rn(),level:"info",event:"step_completed",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logStepFailed(r){await this.writeEvent({ts:rn(),level:"error",event:"step_failed",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logApprovalRequested(r){await this.writeEvent({ts:rn(),level:"info",event:"approval_requested",component:"ApprovalManager",session_id:this.sessionId||void 0,data:r})}async logApprovalGranted(r){await this.writeEvent({ts:rn(),level:"info",event:"approval_granted",component:"ApprovalManager",session_id:this.sessionId||void 0,data:r})}async logApprovalDenied(r){await this.writeEvent({ts:rn(),level:"warn",event:"approval_denied",component:"ApprovalManager",session_id:this.sessionId||void 0,data:r})}async logApprovalTimeout(r){await this.writeEvent({ts:rn(),level:"warn",event:"approval_timeout",component:"ApprovalManager",session_id:this.sessionId||void 0,data:r})}async logContextLoaded(r){await this.writeEvent({ts:rn(),level:"info",event:"context_loaded",component:"ContextManager",session_id:this.sessionId||void 0,data:r})}async logContextSaved(r){await this.writeEvent({ts:rn(),level:"info",event:"context_saved",component:"ContextManager",session_id:this.sessionId||void 0,data:r})}async logContextCompacted(r){await this.writeEvent({ts:rn(),level:"info",event:"context_compacted",component:"ContextManager",session_id:this.sessionId||void 0,data:r})}async logRateLimited(r){await this.writeEvent({ts:rn(),level:"warn",event:"rate_limited",component:"ApiClient",session_id:this.sessionId||void 0,data:r})}async logRetryAttempted(r){await this.writeEvent({ts:rn(),level:"warn",event:"retry_attempted",component:"ApiClient",session_id:this.sessionId||void 0,data:r})}async logApiError(r){await this.writeEvent({ts:rn(),level:"error",event:"api_error",component:"ApiClient",session_id:this.sessionId||void 0,data:r})}async logCacheHit(r){await this.writeEvent({ts:rn(),level:"debug",event:"cache_hit",component:"CacheManager",session_id:this.sessionId||void 0,data:r})}async logCacheMiss(r){await this.writeEvent({ts:rn(),level:"debug",event:"cache_miss",component:"CacheManager",session_id:this.sessionId||void 0,data:r})}async logIndexStarted(r){await this.writeEvent({ts:rn(),level:"info",event:"index_started",component:"CodebaseIndexer",session_id:this.sessionId||void 0,data:r})}async logIndexCompleted(r){await this.writeEvent({ts:rn(),level:"info",event:"index_completed",component:"CodebaseIndexer",session_id:this.sessionId||void 0,data:r})}async logComplexityAnalyzed(r){await this.writeEvent({ts:rn(),level:"info",event:"complexity_analyzed",component:"ComplexityClassifier",session_id:this.sessionId||void 0,data:r})}async logGitOperation(r){await this.writeEvent({ts:rn(),level:r.success?"info":"warn",event:"git_operation",component:"GitService",session_id:this.sessionId||void 0,data:r})}async logClarificationRequested(r){await this.writeEvent({ts:rn(),level:"info",event:"clarification_requested",component:"InteractiveClarifier",session_id:this.sessionId||void 0,data:r})}async logClarificationCompleted(r){await this.writeEvent({ts:rn(),level:"info",event:"clarification_completed",component:"InteractiveClarifier",session_id:this.sessionId||void 0,data:r})}async logPlanGenerated(r){await this.writeEvent({ts:rn(),level:"info",event:"plan_generated",component:"PlanGenerator",session_id:this.sessionId||void 0,data:r})}logPlanApprovalRequested(r){this.writeEvent({ts:rn(),level:"info",event:"plan_approval_requested",component:"ApprovalManager",session_id:this.sessionId||void 0,data:{planId:r}})}logPlanApprovalResolved(r,n){this.writeEvent({ts:rn(),level:"info",event:"plan_approval_resolved",component:"ApprovalManager",session_id:this.sessionId||void 0,data:{planId:r,choice:n}})}},s_e=null});import a_e from"path";function WD(){return v6e||(v6e=new o_e),v6e}var PAt,H2,o_e,v6e,c_e=Ut(()=>{"use strict";PAt=Go(wxt(),1);ju();sf();Dp();Xa();O2();t1();H2="compass",o_e=class i{config=structuredClone(xN);sources={anthropic:"default",ollama:"default",project:"default",safety:"default",ui:"default",session:"default",update:"default",agentic:"default"};loaded=!1;explorer=(0,PAt.cosmiconfig)(H2,{searchPlaces:["package.json",`.${H2}rc`,`.${H2}rc.json`,`.${H2}rc.yaml`,`.${H2}rc.yml`,`.${H2}rc.js`,`.${H2}rc.cjs`,`.${H2}rc.mjs`,`${H2}.config.js`,`${H2}.config.cjs`,`${H2}.config.mjs`,`${H2}.config.ts`],packageProp:H2});async load(r){return this.config=this.deepClone(xN),this.resetSources(),await this.loadGlobalConfig(),r?await this.loadProjectConfig(r):await this.loadProjectConfig(process.cwd()),await this.loadCosmicConfig(r),this.applyEnvironmentVariables(),this.loaded=!0,$.debug("Configuration loaded",{sources:this.sources}),{config:this.config,sources:this.sources}}getConfig(){return this.config}get(r){return this.config[r]}set(r,n){let o=this.deepClone(this.config[r]);this.config[r]={...this.config[r],...n},$.debug(`Configuration updated: ${r}`,n);let l=zo();if(l.logConfigChanged({key:r,oldValue:o,newValue:this.config[r],source:"user"}),r==="anthropic"){let p=n,h=o;p.model&&p.model!==h.model&&l.logModelChanged({model:p.model,previousModel:h.model,reason:"User configuration change"})}if(r==="ollama"){let p=n,h=o;p.model&&p.model!==h.model&&l.logModelChanged({model:p.model,previousModel:h.model,reason:"User configuration change"})}}setValue(r,n){let o=r.split("."),l=this.getValue(r),p=this.config;for(let I=0;I<o.length-1;I++){let k=o[I];(!(k in p)||typeof p[k]!="object")&&(p[k]={}),p=p[k]}p[o[o.length-1]]=n,$.debug(`Configuration value set: ${r}`,{value:n});let h=zo();h.logConfigChanged({key:r,oldValue:l,newValue:n,source:"user"}),r==="anthropic.model"&&n!==l&&h.logModelChanged({model:n,previousModel:l,reason:"User configuration change"})}getValue(r){let n=r.split("."),o=this.config;for(let l of n){if(o===null||typeof o!="object")return;o=o[l]}return o}async saveGlobal(r){let n=oc();await Zl(n);let o=a_e.join(n,hH),l=await _d(o,{version:"1.0",config:{}}),p={version:"1.0",config:this.deepMerge(l?.config||{},r)};await X_(o,p),$.debug("Global configuration saved"),this.mergeConfig(r,"global")}async saveProject(r,n){let o=ou(r);await Zl(o);let l=a_e.join(o,hH),p=await _d(l,{version:"1.0",config:{}}),h={version:"1.0",config:this.deepMerge(p?.config||{},n)};await X_(l,h),$.debug("Project configuration saved"),this.mergeConfig(n,"project")}getSource(r){return this.sources[r]}getSources(){return{...this.sources}}async saveOllamaConfig(r){let n={model:r.model,endpoint:r.endpoint,apiKey:r.apiKey,maxTokens:r.maxTokens??16384,temperature:r.temperature??.4,autoFetched:r.autoFetched??!0};await this.saveGlobal({ollama:n}),$.info("Ollama configuration saved from Compass",{model:r.model})}getOllamaConfig(){return this.config.ollama}hasOllamaConfig(){return!!(this.config.ollama?.model&&this.config.ollama?.endpoint)}isLoaded(){return this.loaded}reset(){this.config=this.deepClone(xN),this.resetSources(),this.loaded=!1,$.debug("Configuration reset to defaults")}validate(){let r=[];return this.config.anthropic.maxTokens<=0&&r.push("anthropic.maxTokens must be positive"),(this.config.anthropic.temperature<0||this.config.anthropic.temperature>1)&&r.push("anthropic.temperature must be between 0 and 1"),this.config.safety.maxFilesPerOperation<=0&&r.push("safety.maxFilesPerOperation must be positive"),this.config.safety.shellCommandTimeout<=0&&r.push("safety.shellCommandTimeout must be positive"),this.config.session.maxHistoryLength<=0&&r.push("session.maxHistoryLength must be positive"),this.config.session.autoCompactThreshold<=0&&r.push("session.autoCompactThreshold must be positive"),this.config.session.sessionExpiryDays<=0&&r.push("session.sessionExpiryDays must be positive"),this.config.project.maxFileSize<=0&&r.push("project.maxFileSize must be positive"),r}export(r=!0){return JSON.stringify(this.config,null,r?2:void 0)}import(r){let n=JSON.parse(r);this.config=this.deepMerge(this.config,n),$.debug("Configuration imported")}async loadGlobalConfig(){let r=a_e.join(oc(),hH);if(await ea(r))try{let n=await _d(r);n?.config&&(this.mergeConfig(n.config,"global"),$.debug("Global configuration loaded"))}catch(n){$.warn("Failed to load global configuration",n)}}async loadProjectConfig(r){let n=a_e.join(ou(r),hH);if(await ea(n))try{let o=await _d(n);o?.config&&(this.mergeConfig(o.config,"project"),$.debug("Project configuration loaded"))}catch(o){$.warn("Failed to load project configuration",o)}}async loadCosmicConfig(r){try{let n=r||process.cwd(),o=await this.explorer.search(n);if(o&&!o.isEmpty){let l=o.config;this.mergeConfig(l,"project"),$.debug(`Cosmiconfig loaded from: ${o.filepath}`)}}catch(n){$.debug("No cosmiconfig found",n)}}applyEnvironmentVariables(){let r=process.env[kb.API_KEY];r&&(this.config.anthropic.apiKey=r,this.sources.anthropic="env",$.debug("API key loaded from environment"));let n=process.env[kb.MODEL];n&&(this.config.anthropic.model=wy(n),this.sources.anthropic="env",$.debug(`Model set from environment: ${this.config.anthropic.model}`));let o=process.env[kb.DEBUG];o&&o.toLowerCase()!=="false"&&o!=="0"&&($.configure({level:"debug"}),$.debug("Debug mode enabled from environment"));let l=process.env[kb.NO_COLOR];l&&l.toLowerCase()!=="false"&&l!=="0"&&($.setColorOutput(!1),$.debug("Color output disabled from environment"));let p=process.env[kb.CONFIG_PATH];p&&$.debug(`Custom config path specified: ${p}`)}static DEPRECATED_KEYS=new Set(["tokenLimits"]);mergeConfig(r,n){for(let o of Object.keys(r)){if(i.DEPRECATED_KEYS.has(o)){$.warn(`[ConfigManager] "${o}" in config is deprecated and ignored. Token limits are now enforced as system defaults and cannot be overridden.`);continue}if(r[o]!==void 0){let l=this.config[o],p=r[o];if(typeof l=="object"&&l!==null&&typeof p=="object"&&p!==null&&!Array.isArray(l)&&!Array.isArray(p)){let h=this.deepMerge(l,p);this.config[o]=h}else this.config[o]=p;this.sources[o]=n}}}resetSources(){for(let r of Object.keys(this.sources))this.sources[r]="default"}deepClone(r){return JSON.parse(JSON.stringify(r))}deepMerge(r,n){let o={...r};for(let l of Object.keys(n)){let p=n[l],h=r[l];p!==void 0&&(p!==null&&typeof p=="object"&&!Array.isArray(p)&&h!==null&&typeof h=="object"&&!Array.isArray(h)?o[l]=this.deepMerge(h,p):o[l]=p)}return o}},v6e=null});function DAt(i,r=0){return(ky[i[r+0]]+ky[i[r+1]]+ky[i[r+2]]+ky[i[r+3]]+"-"+ky[i[r+4]]+ky[i[r+5]]+"-"+ky[i[r+6]]+ky[i[r+7]]+"-"+ky[i[r+8]]+ky[i[r+9]]+"-"+ky[i[r+10]]+ky[i[r+11]]+ky[i[r+12]]+ky[i[r+13]]+ky[i[r+14]]+ky[i[r+15]]).toLowerCase()}var ky,MAt=Ut(()=>{ky=[];for(let i=0;i<256;++i)ky.push((i+256).toString(16).slice(1))});import{randomFillSync as YCr}from"node:crypto";function x6e(){return l_e>u_e.length-16&&(YCr(u_e),l_e=0),u_e.slice(l_e,l_e+=16)}var u_e,l_e,YAt=Ut(()=>{u_e=new Uint8Array(256),l_e=u_e.length});import{randomUUID as OCr}from"node:crypto";var w6e,OAt=Ut(()=>{w6e={randomUUID:OCr}});function HCr(i,r,n){i=i||{};let o=i.random??i.rng?.()??x6e();if(o.length<16)throw new Error("Random bytes length must be >= 16");if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,r){if(n=n||0,n<0||n+16>r.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let l=0;l<16;++l)r[n+l]=o[l];return r}return DAt(o)}function JCr(i,r,n){return w6e.randomUUID&&!r&&!i?w6e.randomUUID():HCr(i,r,n)}var xa,HAt=Ut(()=>{OAt();YAt();MAt();xa=JCr});var j_=Ut(()=>{HAt()});function aa(){return A6e||(A6e=new d_e),A6e}var d_e,A6e,Im=Ut(()=>{"use strict";d_e=class{handlers=new Map;on(r,n){return this.handlers.has(r)||this.handlers.set(r,new Set),this.handlers.get(r).add(n),()=>{this.off(r,n)}}once(r,n){let o=l=>{this.off(r,o),n(l)};return this.on(r,o)}off(r,n){let o=this.handlers.get(r);o&&o.delete(n)}emit(r,n){let o=this.handlers.get(r);if(o)for(let l of o)try{let p=l(n);p instanceof Promise&&p.catch(h=>{console.error(`Async error in event handler for ${String(r)}:`,h)})}catch(p){console.error(`Error in event handler for ${String(r)}:`,p)}}removeAllListeners(r){r?this.handlers.delete(r):this.handlers.clear()}listenerCount(r){return this.handlers.get(r)?.size||0}eventNames(){return Array.from(this.handlers.keys()).filter(r=>this.handlers.get(r).size>0)}hasListeners(r){return this.listenerCount(r)>0}},A6e=null});import YH from"path";async function S6e(){return p_e||(p_e=new f_e,await p_e.load()),p_e}var f_e,p_e,k6e=Ut(()=>{"use strict";j_();K4e();sf();Dp();Q_();Xa();ju();Im();f_e=class{history={records:[],currentRecordId:null};loaded=!1;async load(){if(this.loaded)return;let r=this.getConsentFilePath();try{if(await ea(r)){let n=await _d(r);n&&(this.history=n,$.debug("Consent history loaded",{recordCount:this.history.records.length,currentRecordId:this.history.currentRecordId}))}}catch(n){$.warn("Failed to load consent history, starting fresh",n),this.history={records:[],currentRecordId:null}}this.loaded=!0}async getStatus(){this.loaded||await this.load();let r=this.getCurrentRecord();if(!r)return{isValid:!1,consent:null,grantedAt:null,expiresAt:null,daysUntilExpiry:null,needsRenewal:!0,version:null};let n=new Date,o=new Date(r.expiresAt),l=n>o,p=1e3*60*60*24,h=l?0:Math.ceil((o.getTime()-n.getTime())/p),I=r.version!==$4e,k=l||I;return{isValid:!l&&!I,consent:r.consent,grantedAt:r.grantedAt,expiresAt:r.expiresAt,daysUntilExpiry:h,needsRenewal:k,version:r.version}}async grantConsent(r){if(this.loaded||await this.load(),!r.dataCollection)throw new Error("Data collection consent is required for Compass to function");let n=new Date,o=new Date(n);o.setDate(o.getDate()+IMe);let l={id:xa(),version:$4e,consent:{dataCollection:r.dataCollection,telemetry:r.telemetry,analytics:r.analytics,errorReporting:r.errorReporting},grantedAt:rn(n),expiresAt:rn(o)};return this.history.records.push(l),this.history.currentRecordId=l.id,await this.save(),aa().emit("consent-changed",{granted:!0}),$.info("Consent granted",{recordId:l.id,version:l.version,expiresAt:l.expiresAt}),l}async revokeConsent(){this.loaded||await this.load(),this.history.currentRecordId=null,await this.save(),await this.cleanupUserData(),aa().emit("consent-changed",{granted:!1}),$.info("Consent revoked and user data cleaned up")}async updateConsent(r){this.loaded||await this.load();let n=this.getCurrentRecord();if(!n)return $.warn("Cannot update consent: no current consent record"),null;let o={...n.consent,...r};return await this.grantConsent(o)}getHistory(){return[...this.history.records]}async exportUserData(){this.loaded||await this.load();let r=oc(),n={exportedAt:rn(),exportVersion:"1.0",consentHistory:{records:this.history.records,currentRecordId:this.history.currentRecordId}},o=[{name:"config",file:"config.json"},{name:"tokenUsage",file:"token-usage.json"},{name:"commandHistory",file:"command-history.json"}];for(let{name:p,file:h}of o){let I=YH.join(r,h);if(await ea(I))try{let k=await _d(I);k&&(n[p]=k)}catch(k){$.debug(`Failed to export ${h}`,k)}}let l=YH.join(r,"saved-sessions");if(await ea(l))try{let p=await MH(l),h={};for(let I of p)if(I.endsWith(".json")){let k=YH.join(l,I),N=await _d(k);N&&(h[I.replace(".json","")]=N)}Object.keys(h).length>0&&(n.savedSessions=h)}catch(p){$.debug("Failed to export saved sessions",p)}return $.info("User data exported",{sections:Object.keys(n).length}),n}async isDataCollectionAllowed(){let r=await this.getStatus();return r.isValid&&r.consent?.dataCollection===!0}async isTelemetryAllowed(){let r=await this.getStatus();return r.isValid&&r.consent?.telemetry===!0}async isAnalyticsAllowed(){let r=await this.getStatus();return r.isValid&&r.consent?.analytics===!0}async isErrorReportingAllowed(){let r=await this.getStatus();return r.isValid&&r.consent?.errorReporting===!0}async hasValidConsent(){return(await this.getStatus()).isValid}getCurrentRecord(){return this.history.currentRecordId&&this.history.records.find(r=>r.id===this.history.currentRecordId)||null}getConsentFilePath(){return YH.join(oc(),aMe)}async save(){let r=this.getConsentFilePath();await Zl(YH.dirname(r)),await X_(r,this.history),$.debug("Consent history saved")}async cleanupUserData(){let r=oc(),n=["session.json","token-usage.json","command-history.json","cache","saved-sessions","logs","context","index"];for(let o of n){let l=YH.join(r,o);if(await ea(l))try{await G0(l),$.debug(`Removed: ${o}`)}catch(p){$.warn(`Failed to remove ${o}`,p)}}$.info("User data cleanup completed")}async reload(){this.loaded=!1,await this.load()}reset(){this.history={records:[],currentRecordId:null},this.loaded=!1}},p_e=null});import r1 from"crypto";function LAt(i,r){return r1.pbkdf2Sync(i,r,UCr,LCr,T6e)}function C6e(i,r){let n=r1.randomBytes(I5),o=r1.randomBytes(OH),l=LAt(r,n),p=r1.createCipheriv(JAt,l,o),h=p.update(i,"utf8","hex");h+=p.final("hex");let I=p.getAuthTag();return Buffer.concat([n,o,I,Buffer.from(h,"hex")]).toString("base64")}function G6e(i,r){let n=Buffer.from(i,"base64"),o=I5+OH+E6e+1;if(n.length<o)throw new Error("Invalid encrypted data: too short");let l=n.subarray(0,I5),p=n.subarray(I5,I5+OH),h=n.subarray(I5+OH,I5+OH+E6e),I=n.subarray(I5+OH+E6e),k=LAt(r,l),N=r1.createDecipheriv(JAt,k,p);N.setAuthTag(h);let W=N.update(I.toString("hex"),"hex","utf8");return W+=N.final("utf8"),W}function XCr(i=32){return r1.randomBytes(i).toString("hex")}function N6e(i){return r1.createHash(T6e).update(i).digest("hex")}function QCr(i,r){return r1.createHmac(T6e,r).update(i).digest("hex")}function jCr(i,r){return i.length!==r.length?(r1.timingSafeEqual(Buffer.from(i),Buffer.from(i)),!1):r1.timingSafeEqual(Buffer.from(i),Buffer.from(r))}function zCr(i){let r=r1.pbkdf2Sync(i,BCr,1e5,32,"sha256");return Buffer.from(r.toString("base64url"),"utf-8")}function UAt(i,r){try{let n=zCr(r),o=Buffer.from(n.toString("utf-8"),"base64url"),p=Buffer.from(i,"base64url").toString("utf-8"),h=Buffer.from(p,"base64url");if(h.length<57)throw new Error(`Invalid Fernet token: too short (${h.length} bytes, need at least 57)`);let I=h[0];if(I!==128)throw new Error(`Invalid Fernet version: 0x${I.toString(16)} (expected 0x80)`);let k=h.subarray(9,25),N=h.subarray(25,h.length-32),W=h.subarray(h.length-32),H=o.subarray(0,16),M=o.subarray(16,32),q=h.subarray(0,h.length-32),ne=r1.createHmac("sha256",H).update(q).digest();if(!r1.timingSafeEqual(W,ne))throw new Error("Invalid Fernet token: HMAC verification failed");let de=r1.createDecipheriv("aes-128-cbc",M,k);de.setAutoPadding(!0);let Qe=de.update(N);return Qe=Buffer.concat([Qe,de.final()]),Qe.toString("utf-8")}catch(n){throw n instanceof Error?new Error(`Failed to decrypt Fernet token: ${n.message}`):new Error("Failed to decrypt Fernet token: Unknown error")}}var JAt,OH,I5,E6e,LCr,UCr,T6e,BCr,o$=Ut(()=>{"use strict";JAt="aes-256-gcm",OH=16,I5=32,E6e=16,LCr=32,UCr=1e5,T6e="sha256";BCr=Buffer.from("b-f2T&>)XPx2vI/I9N7CfYH@Dvdb<F","utf-8")});import c$ from"path";import ZD from"os";import qCr from"crypto";async function J2(){if(XAt)return F6e;XAt=!0;try{let i=await import("keytar");return F6e=i.default||i,F6e}catch(i){return $.debug("Failed to load keytar native module:",i),null}}async function Rg(){return h_e||(h_e=new g_e,await h_e.initialize()),h_e}var F6e,XAt,QAt,YI,HH,m_e,__e,jAt,R6e,g_e,h_e,VD=Ut(()=>{"use strict";o$();Dp();sf();Xa();ju();F6e=null,XAt=!1,QAt="keytar-available.json";YI="compass-cli",HH="anthropic-api-key",m_e="compass-api-key",__e={anthropic:"anthropic-api-key",ollama:"ollama-api-key",zai:"zai-api-key",minimax:"minimax-api-key"},jAt="1.0",R6e={anthropic:"anthropicApiKey",ollama:"ollamaApiKey",zai:"zaiApiKey",minimax:"minimaxApiKey"},g_e=class{useKeytar=!0;machineKey=null;initialized=!1;async initialize(){if(this.initialized)return;let r=`${ZD.platform()}-${ZD.arch()}`;try{let n=c$.join(oc(),QAt);if(await ea(n)){let o=await ed(n);if(o){let l=JSON.parse(o);if(l.platform===r)if(l.available){if(await J2()){this.useKeytar=!0,this.initialized=!0,$.debug("Using system keychain (cached probe)");return}}else{this.useKeytar=!1,this.machineKey=await this.getMachineKey(),this.initialized=!0,$.debug("Using encrypted file storage (cached probe)");return}}}}catch{}try{let n=await J2();if(!n)throw new Error("Keytar module not available");let o=`${YI}-test`,l="availability-test";await n.setPassword(o,l,"test"),await n.deletePassword(o,l),this.useKeytar=!0,$.debug("Using system keychain for credential storage")}catch(n){this.useKeytar=!1,$.debug("System keychain unavailable, using encrypted file storage",n),this.machineKey=await this.getMachineKey()}this.initialized=!0,this.saveKeytarCache(r).catch(n=>{$.debug("Failed to cache keytar probe result",n)})}async saveKeytarCache(r){let n=oc();await Zl(n);let o=c$.join(n,QAt),l={available:this.useKeytar,platform:r,checkedAt:new Date().toISOString()};await C0(o,JSON.stringify(l))}async setApiKey(r){if(await this.ensureInitialized(),!r||typeof r!="string")throw new Error("API key must be a non-empty string");let n=r.trim();if(this.useKeytar)try{let o=await J2();if(o){await o.setPassword(YI,HH,n),$.debug("API key stored in system keychain");return}}catch(o){$.warn("Failed to store in keychain, falling back to file storage",o)}await this.saveToFile({anthropicApiKey:n}),$.debug("API key stored in encrypted file")}async getApiKey(){await this.ensureInitialized();let r=process.env[kb.API_KEY];if(r&&r.trim())return $.debug("API key loaded from environment variable"),r.trim();if(this.useKeytar)try{let o=await J2();if(o){let l=await o.getPassword(YI,HH);if(l)return $.debug("API key loaded from system keychain"),l}}catch(o){$.debug("Failed to read from keychain",o)}let n=await this.loadFromFile();return n?.anthropicApiKey?($.debug("API key loaded from encrypted file"),n.anthropicApiKey):null}async deleteApiKey(){await this.ensureInitialized();let r=!0;if(this.useKeytar)try{let o=await J2();o&&await o.deletePassword(YI,HH)&&$.debug("API key deleted from system keychain")}catch(o){$.debug("Failed to delete from keychain",o),r=!1}return await this.deleteFile()||(r=!1),r&&$.debug("API key deleted successfully"),r}async hasApiKey(){let r=await this.getApiKey();return r!==null&&r.length>0}async setCompassApiKey(r){if(await this.ensureInitialized(),!r||typeof r!="string")throw new Error("API key must be a non-empty string");let n=r.trim();if(this.useKeytar)try{let l=await J2();if(l){await l.setPassword(YI,m_e,n),$.debug("Compass API key stored in system keychain");return}}catch(l){$.warn("Failed to store in keychain, falling back to file storage",l)}let o=await this.loadFromFile()||{};await this.saveToFile({...o,compassApiKey:n}),$.debug("Compass API key stored in encrypted file")}async getCompassApiKey(){await this.ensureInitialized();let r=process.env[kb.COMPASS_API_KEY];if(r&&r.trim())return $.debug("Compass API key loaded from environment variable"),r.trim();if(this.useKeytar)try{let o=await J2();if(o){let l=await o.getPassword(YI,m_e);if(l)return $.debug("Compass API key loaded from system keychain"),l}}catch(o){$.debug("Failed to read from keychain",o)}let n=await this.loadFromFile();return n?.compassApiKey?($.debug("Compass API key loaded from encrypted file"),n.compassApiKey):null}async deleteCompassApiKey(){await this.ensureInitialized();let r=!0;if(this.useKeytar)try{let n=await J2();n&&await n.deletePassword(YI,m_e)&&$.debug("Compass API key deleted from system keychain")}catch(n){$.debug("Failed to delete from keychain",n),r=!1}try{let n=await this.loadFromFile();n?.compassApiKey&&(delete n.compassApiKey,await this.saveToFile(n),$.debug("Compass API key deleted from encrypted file"))}catch(n){$.error("Failed to delete Compass API key from file",n),r=!1}return r&&$.debug("Compass API key deleted successfully"),r}async hasCompassApiKey(){let r=await this.getCompassApiKey();return r!==null&&r.length>0}async setProviderApiKey(r,n){if(await this.ensureInitialized(),!n||typeof n!="string")throw new Error("API key must be a non-empty string");if(!wN.includes(r))throw new Error(`Invalid provider: ${r}. Must be one of: ${wN.join(", ")}`);let o=n.trim(),l=__e[r];if(this.useKeytar)try{let I=await J2();if(I){await I.setPassword(YI,l,o),$.debug(`${r} API key stored in system keychain`);return}}catch(I){$.warn("Failed to store in keychain, falling back to file storage",I)}let p=await this.loadFromFile()||{},h=R6e[r];await this.saveToFile({...p,[h]:o}),$.debug(`${r} API key stored in encrypted file`)}async getProviderApiKey(r){if(await this.ensureInitialized(),!wN.includes(r))return $.warn(`Invalid provider: ${r}`),null;let n=bme[r],o=process.env[n];if(o&&o.trim())return $.debug(`${r} API key loaded from environment variable ${n}`),o.trim();let l=__e[r];if(this.useKeytar)try{let I=await J2();if(I){let k=await I.getPassword(YI,l);if(k)return $.debug(`${r} API key loaded from system keychain`),k}}catch(I){$.debug(`Failed to read ${r} key from keychain`,I)}let p=await this.loadFromFile(),h=R6e[r];return p?.[h]?($.debug(`${r} API key loaded from encrypted file`),p[h]):null}async hasProviderApiKey(r){let n=await this.getProviderApiKey(r);return n!==null&&n.length>0}async deleteProviderApiKey(r){if(await this.ensureInitialized(),!wN.includes(r))return $.warn(`Invalid provider: ${r}`),!1;let n=!0,o=__e[r];if(this.useKeytar)try{let l=await J2();l&&await l.deletePassword(YI,o)&&$.debug(`${r} API key deleted from system keychain`)}catch(l){$.debug(`Failed to delete ${r} key from keychain`,l),n=!1}try{let l=await this.loadFromFile(),p=R6e[r];l?.[p]&&(delete l[p],await this.saveToFile(l),$.debug(`${r} API key deleted from encrypted file`))}catch(l){$.error(`Failed to delete ${r} API key from file`,l),n=!1}return n}async getConfiguredProviders(){let r=[];for(let n of wN)await this.hasProviderApiKey(n)&&r.push(n);return r}validateApiKeyFormat(r){if(!r||typeof r!="string")return!1;let n=r.trim();return!(n.length<20)}getStorageMethod(){return this.useKeytar?"keychain":"file"}isInitialized(){return this.initialized}async ensureInitialized(){this.initialized||await this.initialize()}async getMachineKey(){if(this.machineKey)return this.machineKey;let n=[ZD.hostname(),ZD.platform(),ZD.arch(),ZD.userInfo().username,ZD.homedir()].join(":"),o=qCr.createHash("sha256").update(n).digest("hex");return this.machineKey=o,o}async saveToFile(r){let n=await this.getMachineKey(),o=JSON.stringify(r),l=C6e(o,n),p={version:jAt,data:l,updatedAt:new Date().toISOString()},h=oc();await Zl(h);let I=c$.join(h,gq);await C0(I,JSON.stringify(p,null,2)),$.debug("Credentials saved to encrypted file")}async loadFromFile(){let r=c$.join(oc(),gq);if(!await ea(r))return null;try{let n=await ed(r);if(!n)return null;let o=JSON.parse(n);o.version!==jAt&&$.warn(`Credentials file version mismatch: ${o.version}`);let l=await this.getMachineKey(),p=G6e(o.data,l);return JSON.parse(p)}catch(n){return $.error("Failed to load credentials from file",n),null}}async deleteFile(){let r=c$.join(oc(),gq);try{return await ea(r)&&(await G0(r),$.debug("Credentials file deleted")),!0}catch(n){return $.error("Failed to delete credentials file",n),!1}}async migrateToKeychain(){if(!this.useKeytar)return $.debug("Keychain not available, migration skipped"),!1;try{let r=await J2();if(!r)return $.debug("Keytar not available, migration skipped"),!1;let n=await this.loadFromFile();return n?.anthropicApiKey?await r.getPassword(YI,HH)?($.debug("Keychain already has credentials, skipping migration"),!0):(await r.setPassword(YI,HH,n.anthropicApiKey),await this.deleteFile(),$.debug("Credentials migrated from file to system keychain"),!0):($.debug("No file-based credentials to migrate"),!0)}catch(r){return $.error("Failed to migrate credentials to keychain",r),!1}}async clearAll(){if(await this.ensureInitialized(),this.useKeytar)try{let r=await J2();if(r){await r.deletePassword(YI,HH),await r.deletePassword(YI,m_e);for(let n of wN)await r.deletePassword(YI,__e[n])}}catch(r){$.debug("Failed to clear keychain",r)}await this.deleteFile(),$.debug("All credentials cleared")}},h_e=null});import CN from"path";function l$(i){return new y_e(i)}var y_e,W6e=Ut(()=>{"use strict";j_();iMe();Dp();Xa();ju();y_e=class{projectPath;archiveDir;constructor(r){this.projectPath=r,this.archiveDir=a$(r)}async archiveSession(r){let n=r.state.conversationHistory;if(!n||n.length===0)return $.debug("No messages to archive, skipping"),{success:!1,error:"No messages to archive"};try{await h6e(this.projectPath);let o=this.buildArchive(r),l=this.generateFilename(o.summary),p=CN.join(this.archiveDir,l);return await X_(p,o),$.info(`Archived conversation to ${l}`),{success:!0,archiveId:o.id,filename:l,path:p}}catch(o){return $.error("Failed to archive session",o),{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async listArchives(){try{let r=await b5(this.projectPath),n=[];for(let o of r){let l=CN.join(this.archiveDir,o),p=await _d(l);p&&t5(p)&&n.push({id:p.id,filename:o,startedAt:p.startedAt,endedAt:p.endedAt,durationSeconds:p.durationSeconds,messageCount:p.messageCount,summary:p.summary,topics:p.topics,model:p.model,tokenUsage:p.tokenUsage})}return n.sort((o,l)=>new Date(l.endedAt).getTime()-new Date(o.endedAt).getTime())}catch(r){return $.error("Failed to list archives",r),[]}}async getArchive(r){try{let n=await b5(this.projectPath);for(let o of n)if(o===r||o.includes(r)){let l=CN.join(this.archiveDir,o),p=await _d(l);if(p&&t5(p))return p}if(r.endsWith(".json")){let o=CN.join(this.archiveDir,r);if(await ea(o)){let l=await _d(o);if(l&&t5(l))return l}}return null}catch(n){return $.error(`Failed to get archive: ${r}`,n),null}}async getLatestArchive(){try{let r=await b5(this.projectPath);if(r.length===0)return null;let n=r[r.length-1],o=CN.join(this.archiveDir,n),l=await _d(o);return l&&t5(l)?l:null}catch(r){return $.error("Failed to get latest archive",r),null}}async searchArchives(r){let n=r.toLowerCase(),o=[];try{let l=await b5(this.projectPath);for(let p of l){let h=CN.join(this.archiveDir,p),I=await _d(h);if(I&&t5(I)){let k=this.extractFilesModified(I.operations);(I.summary.toLowerCase().includes(n)||I.topics.some(W=>W.toLowerCase().includes(n))||k.some(W=>W.toLowerCase().includes(n))||I.messages.some(W=>W.content.toLowerCase().includes(n)))&&o.push({id:I.id,filename:p,startedAt:I.startedAt,endedAt:I.endedAt,durationSeconds:I.durationSeconds,messageCount:I.messageCount,summary:I.summary,topics:I.topics,model:I.model,tokenUsage:I.tokenUsage})}}return o.sort((p,h)=>new Date(h.endedAt).getTime()-new Date(p.endedAt).getTime())}catch(l){return $.error(`Failed to search archives for: ${r}`,l),[]}}async cleanupOldArchives(r=30,n=100){let o=0;try{let l=await b5(this.projectPath);if(l.length===0)return 0;let p=new Date;p.setDate(p.getDate()-r);for(let I of l){let k=CN.join(this.archiveDir,I),N=await _d(k);N&&t5(N)&&new Date(N.endedAt)<p&&(await G0(k),o++,$.debug(`Deleted old archive: ${I}`))}let h=await b5(this.projectPath);if(h.length>n){let I=h.slice(0,h.length-n);for(let k of I){let N=CN.join(this.archiveDir,k);await G0(N),o++,$.debug(`Deleted archive (over limit): ${k}`)}}return o>0&&$.info(`Cleaned up ${o} old archives`),o}catch(l){return $.error("Failed to cleanup old archives",l),o}}buildArchive(r){let n=r.state.conversationHistory,o=r.state.operations,l=n[0],p=n[n.length-1],h=l?.timestamp||r.createdAt,I=p?.timestamp||r.updatedAt,k=Math.round((new Date(I).getTime()-new Date(h).getTime())/1e3),N=this.countMessages(n),W=this.generateSummary(n),H=this.extractTopics(n,o),M=this.convertMessages(n);return{version:"1.0",id:xa(),sessionId:r.id,projectPath:r.projectPath,startedAt:h,endedAt:I,durationSeconds:k,messageCount:n.length,messageCounts:N,tokenUsage:{total:r.metadata.totalTokensUsed,estimatedCost:r.metadata.totalCost},model:r.state.currentModel,summary:W,topics:H,wasCompacted:r.metadata.isCompacted||!1,compactedSummary:r.state.compactedSummary,messages:M,operations:o}}countMessages(r){return r.reduce((n,o)=>(n[o.role]++,n),{user:0,assistant:0,system:0})}extractFilesModified(r){if(!r||r.length===0)return[];let n=new Set;for(let o of r)o.details.filePath&&(o.type==="file_create"||o.type==="file_modify"||o.type==="file_delete"||o.type==="file_rename")&&n.add(o.details.filePath),o.details.newFilePath&&n.add(o.details.newFilePath);return Array.from(n)}generateSummary(r){let n=r.find(l=>l.role==="user");if(!n)return"Empty conversation";let o=n.content.replace(/\n+/g," ").replace(/\s+/g," ").trim();if(o.length>100){o=o.substring(0,100);let l=o.lastIndexOf(" ");l>50&&(o=o.substring(0,l)),o+="..."}return o}extractTopics(r,n){let o=new Set;for(let h of n)if(h.details.filePath){let I=CN.extname(h.details.filePath).slice(1);I&&o.add(I);let k=h.details.filePath.split(/[/\\]/);for(let N of k.slice(0,-1))N&&N!=="."&&N!==".."&&!N.startsWith(".")&&o.add(N)}for(let h of n)h.type.includes("file")&&o.add("file-operations"),h.type.includes("git")&&o.add("git"),h.type.includes("shell")&&o.add("shell");let l=r.find(h=>h.role==="user")?.content.toLowerCase()||"",p=["bug","fix","feature","refactor","test","docs","style","perf","build","ci","deploy","debug","error","issue","implement","add","remove","update","change","create"];for(let h of p)l.includes(h)&&o.add(h);return Array.from(o).slice(0,10)}convertMessages(r){return r.map(n=>({role:n.role,content:n.content,timestamp:n.timestamp,tokenCount:n.tokenCount,model:n.model}))}generateFilename(r){let n=new Date,o=n.toISOString().slice(0,10),l=n.toTimeString().slice(0,8).replace(/:/g,"-"),p=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50);return`${o}_${l}_${p||"conversation"}.json`}}});import Hw from"path";function vm(){return Z6e||(Z6e=new b_e),Z6e}var b_e,Z6e,pT=Ut(()=>{"use strict";j_();_H();sf();Dp();Q_();wD();Xa();ju();Im();W6e();b_e=class{session=null;projectRoot=process.cwd();autoSaveTimer=null;dirty=!1;unguardedMode=!1;pendingAttachments=[];archivalService=null;createSession(r){return this.projectRoot=r||process.cwd(),this.session={id:xa(),createdAt:rn(),updatedAt:rn(),projectPath:this.projectRoot,state:{conversationHistory:[],operations:[],currentModel:Pw,approvalMode:"manual",contextFiles:[],executionMode:"hybrid"},metadata:{totalTokensUsed:0,totalCost:0,messageCount:0,operationCount:0,lastActivity:rn(),tags:[]}},this.dirty=!0,$.debug(`Session created: ${this.session.id}`),this.session}getSession(){return this.session}getState(){return this.session?.state||null}getMetadata(){return this.session?.metadata||null}addMessage(r){this.session||this.createSession();let n={id:xa(),timestamp:rn(),...r};return this.session.state.conversationHistory.push(n),this.session.metadata.messageCount++,this.session.metadata.lastActivity=rn(),this.session.updatedAt=rn(),this.session.state.conversationHistory.length>xq&&(this.session.state.conversationHistory=this.session.state.conversationHistory.slice(-xq)),this.dirty=!0,$.debug(`Message added: ${n.role} (${n.id})`),n}getConversationHistory(){return this.session?.state.conversationHistory||[]}clearHistory(){if(this.session){let r=this.session.state.conversationHistory.length,n=this.session.state.operations.length;this.session.state.conversationHistory=[],this.session.state.operations=[],this.session.state.compactedSummary=void 0,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Conversation history cleared: ${r} messages, ${n} operations removed`)}}async archiveCurrentSession(){if(!this.session)return{success:!1,error:"No active session to archive"};if(!this.session.state.conversationHistory||this.session.state.conversationHistory.length===0)return $.debug("No messages to archive, skipping"),{success:!1,error:"No messages to archive"};this.archivalService||(this.archivalService=l$(this.projectRoot));try{let r=await this.archivalService.archiveSession(this.session);return r.success&&$.info(`Session archived to: ${r.filename}`),r}catch(r){return $.error("Failed to archive session",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async archiveAndClearSession(){let r=null;this.archivalService||(this.archivalService=l$(this.projectRoot));let n=await this.archiveCurrentSession();return n.success&&n.path&&(r=await this.archivalService.getLatestArchive()),this.clearHistory(),this.archivalService.cleanupOldArchives().catch(o=>{$.warn("Failed to cleanup old archives",o)}),{archive:r,result:n}}getArchivalService(){return this.archivalService||(this.archivalService=l$(this.projectRoot)),this.archivalService}setCompactedSummary(r){this.session&&(this.session.state.compactedSummary=r,this.session.state.conversationHistory=[],this.session.updatedAt=rn(),this.dirty=!0,$.info("Compacted summary set, conversation history cleared"))}getCompactedSummary(){return this.session?.state.compactedSummary}syncAfterCompaction(r,n){this.session&&(this.session.state.compactedSummary=r,this.session.metadata.isCompacted=!0,this.session.metadata.compactionTimestamp=rn(),this.session.metadata.messagesPreserved=n,this.session.updatedAt=rn(),this.dirty=!0,$.info(`Session synced after compaction: summary stored, ${n} recent messages preserved`))}replaceConversationHistory(r){this.session&&(this.session.state.conversationHistory=r,this.session.metadata.messageCount=r.length,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Conversation history replaced: ${r.length} messages`))}updateEstimatedContextTokens(r){this.session&&(this.session.metadata.estimatedContextTokens=r,$.debug(`Session context tokens updated: ${r.toLocaleString()}`))}getEstimatedContextTokens(){return this.session?.metadata.estimatedContextTokens??0}recordOperation(r){this.session||this.createSession();let n={id:xa(),timestamp:rn(),...r};return this.session.state.operations.push(n),this.session.metadata.operationCount++,this.session.metadata.lastActivity=rn(),this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Operation recorded: ${n.type} (${n.id})`),n}getOperations(){return this.session?.state.operations||[]}getLastOperation(){let r=this.session?.state.operations||[];return r[r.length-1]}updateOperation(r,n){if(!this.session)return!1;let o=this.session.state.operations.find(l=>l.id===r);return o?(Object.assign(o,n),this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Operation updated: ${r}`),!0):!1}updateTokenUsage(r,n){this.session&&(this.session.metadata.totalTokensUsed+=r,this.session.metadata.totalCost+=n,this.session.metadata.lastActivity=rn(),this.session.updatedAt=rn(),this.dirty=!0)}setModel(r){this.session&&(this.session.state.currentModel=r,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Model set: ${r}`))}getCurrentModel(){return this.session?.state.currentModel||Pw}setApprovalMode(r){this.session&&(this.session.state.approvalMode=r,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Approval mode set: ${r}`))}getApprovalMode(){return this.session?.state.approvalMode||"manual"}setExecutionMode(r){this.session&&(this.session.state.executionMode=r,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Execution mode set: ${r}`))}getExecutionMode(){return this.session?.state.executionMode||"hybrid"}setShowToolBlocks(r){this.session&&(this.session.state.showToolBlocks=r,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Show tool blocks set: ${r}`))}getShowToolBlocks(){return this.session?.state.showToolBlocks??!0}addContextFile(r){this.session&&(this.session.state.contextFiles.includes(r)||(this.session.state.contextFiles.push(r),this.session.updatedAt=rn(),this.dirty=!0))}removeContextFile(r){if(this.session){let n=this.session.state.contextFiles.indexOf(r);n!==-1&&(this.session.state.contextFiles.splice(n,1),this.session.updatedAt=rn(),this.dirty=!0)}}getContextFiles(){return this.session?.state.contextFiles||[]}addExcludedFolder(r){this.session&&(this.session.state.excludedFolders||(this.session.state.excludedFolders=[]),this.session.state.excludedFolders.includes(r)||(this.session.state.excludedFolders.push(r),this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Excluded folder added: ${r}`)))}removeExcludedFolder(r){if(this.session&&this.session.state.excludedFolders){let n=this.session.state.excludedFolders.indexOf(r);n!==-1&&(this.session.state.excludedFolders.splice(n,1),this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Excluded folder removed: ${r}`))}}setExcludedFolders(r){this.session&&(this.session.state.excludedFolders=[...r],this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Excluded folders set: ${r.length} patterns`))}getExcludedFolders(){return this.session?.state.excludedFolders||[]}clearExcludedFolders(){this.session&&(this.session.state.excludedFolders=[],this.session.updatedAt=rn(),this.dirty=!0,$.debug("Excluded folders cleared"))}setPersonalityMode(r){this.session&&(this.session.state.personalityMode=r,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Personality mode set: ${r}`))}getPersonalityMode(){return this.session?.state.personalityMode||$v}setTemporaryPersonalityMode(r){this.session&&(this.session.state.temporaryPersonalityMode=r,this.session.updatedAt=rn(),$.debug(`Temporary personality mode set: ${r}`))}clearTemporaryPersonalityMode(){this.session&&this.session.state.temporaryPersonalityMode&&(this.session.state.temporaryPersonalityMode=void 0,this.session.updatedAt=rn(),$.debug("Temporary personality mode cleared"))}getEffectivePersonalityMode(){return this.session?.state.temporaryPersonalityMode?this.session.state.temporaryPersonalityMode:this.getPersonalityMode()}hasTemporaryPersonalityMode(){return this.session?.state.temporaryPersonalityMode!==void 0}setUnguardedMode(r){this.unguardedMode=r,$.debug(`Unguarded mode set: ${r} (transient - not persisted)`)}getUnguardedMode(){return this.unguardedMode}addTag(r){this.session&&(this.session.metadata.tags.includes(r)||(this.session.metadata.tags.push(r),this.session.updatedAt=rn(),this.dirty=!0))}removeTag(r){if(this.session){let n=this.session.metadata.tags.indexOf(r);n!==-1&&(this.session.metadata.tags.splice(n,1),this.session.updatedAt=rn(),this.dirty=!0)}}async save(){if(!this.session){$.debug("No session to save");return}if(!this.dirty){$.debug("Session not dirty, skipping save");return}try{let r=ou(this.projectRoot);await Zl(r);let n=Hw.join(r,mme);await X_(n,this.session),this.dirty=!1,$.debug("Session saved"),aa().emit("session-saved",{sessionId:this.session.id})}catch(r){throw $.error("Failed to save session",r),r}}async load(r){this.projectRoot=r||process.cwd();let n=Hw.join(ou(this.projectRoot),mme);if(!await ea(n))return $.debug("No existing session found"),null;try{let o=await _d(n);if(o){this.session=this.migrateSession(o),this.dirty=!1,$.info(`Session loaded: ${this.session.id}`);let l=Hw.resolve(this.projectRoot);Hw.resolve(this.session.projectPath)!==l&&($.debug(`Updating session projectPath from ${this.session.projectPath} to ${l}`),this.session.projectPath=l,this.session.updatedAt=rn(),this.dirty=!0)}return this.session}catch(o){return $.error("Failed to load session",o),null}}migrateSession(r){let n=!1;if(!r.metadata)r.metadata={totalTokensUsed:0,totalCost:0,messageCount:0,operationCount:0,lastActivity:rn(),tags:[]},n=!0,$.debug("Session migrated: added missing metadata field");else{let o=r.metadata;typeof o.totalTokensUsed!="number"&&(o.totalTokensUsed=0,n=!0),typeof o.totalCost!="number"&&(o.totalCost=0,n=!0),typeof o.messageCount!="number"&&(o.messageCount=0,n=!0),typeof o.operationCount!="number"&&(o.operationCount=0,n=!0),o.lastActivity||(o.lastActivity=rn(),n=!0),Array.isArray(o.tags)||(o.tags=[],n=!0)}if(!r.state)r.state={conversationHistory:[],operations:[],currentModel:Pw,approvalMode:"manual",contextFiles:[],executionMode:"hybrid"},n=!0,$.debug("Session migrated: added missing state field");else{let o=r.state;Array.isArray(o.conversationHistory)||(o.conversationHistory=[],n=!0),Array.isArray(o.operations)||(o.operations=[],n=!0),o.currentModel||(o.currentModel=Pw,n=!0),o.approvalMode||(o.approvalMode="manual",n=!0),Array.isArray(o.contextFiles)||(o.contextFiles=[],n=!0)}return r.id||(r.id=xa(),n=!0),r.createdAt||(r.createdAt=rn(),n=!0),r.updatedAt||(r.updatedAt=rn(),n=!0),r.projectPath||(r.projectPath=this.projectRoot,n=!0),n&&(this.dirty=!0,$.info("Session structure migrated to current schema")),r}async saveAs(r,n){if(!this.session)throw new Error("No active session to save");let o=Hw.join(oc(),gH);await Zl(o);let l={session:this.session,savedAt:rn(),name:r,description:n},h=`${r.replace(/[^a-zA-Z0-9-_]/g,"_")}.json`,I=Hw.join(o,h);return await X_(I,l),$.info(`Session saved as: ${r}`),I}async listSavedSessions(){let r=Hw.join(oc(),gH);if(!await ea(r))return[];let n=await MH(r),o=[];for(let l of n)if(l.endsWith(".json")){let p=Hw.join(r,l);try{let h=await _d(p);h&&o.push(h)}catch(h){$.debug(`Failed to load saved session: ${l}`,h)}}return o.sort((l,p)=>new Date(p.savedAt).getTime()-new Date(l.savedAt).getTime())}async loadSaved(r){let n=Hw.join(oc(),gH),l=`${r.replace(/[^a-zA-Z0-9-_]/g,"_")}.json`,p=Hw.join(n,l);if(!await ea(p))return $.debug(`Saved session not found: ${r}`),null;try{let h=await _d(p);return h?(this.session=h.session,this.projectRoot=h.session.projectPath,this.dirty=!1,$.info(`Loaded saved session: ${r}`),this.session):null}catch(h){return $.error(`Failed to load saved session: ${r}`,h),null}}async deleteSavedSession(r){let n=Hw.join(oc(),gH),l=`${r.replace(/[^a-zA-Z0-9-_]/g,"_")}.json`,p=Hw.join(n,l);if(!await ea(p))return!1;try{let{remove:h}=await Promise.resolve().then(()=>(Dp(),g6e));return await h(p),$.info(`Deleted saved session: ${r}`),!0}catch(h){return $.error(`Failed to delete saved session: ${r}`,h),!1}}startAutoSave(r=hme){this.stopAutoSave(),this.autoSaveTimer=setInterval(()=>{this.dirty&&this.save().catch(n=>{$.error("Auto-save failed",n)})},r),$.debug(`Auto-save started with interval: ${r}ms`)}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null,$.debug("Auto-save stopped"))}isDirty(){return this.dirty}async forceSave(){this.dirty=!0,await this.save()}getProjectRoot(){return this.projectRoot}setProjectRoot(r){this.projectRoot=r,this.session&&(this.session.projectPath=r,this.dirty=!0)}exportSession(){return this.session?{...this.session}:null}importSession(r){this.session={...r},this.projectRoot=r.projectPath,this.dirty=!0,$.info(`Session imported: ${r.id}`)}getPendingAttachments(){return[...this.pendingAttachments]}addPendingAttachment(r){this.pendingAttachments.push(r),$.debug(`Pending attachment added: ${r.filename} (${r.type})`)}addPendingAttachments(r){this.pendingAttachments.push(...r),$.debug(`Added ${r.length} pending attachments`)}clearPendingAttachments(){let r=this.pendingAttachments.length;this.pendingAttachments=[],r>0&&$.debug(`Cleared ${r} pending attachments`)}consumePendingAttachments(){let r=[...this.pendingAttachments];return this.pendingAttachments=[],r.length>0&&$.debug(`Consumed ${r.length} pending attachments`),r}hasPendingAttachments(){return this.pendingAttachments.length>0}getPendingAttachmentsCount(){return this.pendingAttachments.length}},Z6e=null});import V6e from"path";import eGr from"os";function d$(){return{version:RMe,windowStart:Date.now(),providers:{}}}function P6e(i){return i.startsWith("claude-")?"anthropic":"ollama"}function u$(i){let r=Date.now()-i.windowStart;return r>=Cq||r<0?d$():i}function p$(i){let r=0;for(let n of Object.values(i.providers))for(let o of Object.values(n))r+=o;return r}function v_e(i,r){let n=P6e(r);return i.providers[n]?.[r]??0}function tGr(i){if(!Array.isArray(i.generalBucket)||typeof i.modelBuckets!="object"||i.modelBuckets===null)return null;let r=i,n=Date.now(),o=n-Cq,l=d$(),p=n;for(let[I,k]of Object.entries(r.modelBuckets)){if(!Array.isArray(k))continue;let N=P6e(I),W=0;for(let H of k)typeof H.tokens!="number"||typeof H.timestamp!="number"||H.timestamp<o||(W+=H.tokens,H.timestamp<p&&(p=H.timestamp));W>0&&(l.providers[N]||(l.providers[N]={}),l.providers[N][I]=W)}l.windowStart=p;let h=p$(l);return $.info(`[TokenLimitStore] Migrated v2 usage data (${h.toLocaleString()} tokens) to v1 flat format.`),l}function f$(){let i=V6e.join(eGr.homedir(),".compass");return new I_e(i)}var JH,I_e,x_e=Ut(()=>{"use strict";JH=Go(MI(),1);IH();Xa();I_e=class{filePath;queue=Promise.resolve();constructor(r){this.filePath=V6e.join(r,FMe)}async recordUsage(r,n){if(!(!Number.isFinite(n)||n<=0))return this.enqueue(async()=>{let o=await this.load();o=u$(o);let l=P6e(r);o.providers[l]||(o.providers[l]={}),o.providers[l][r]=(o.providers[l][r]??0)+n,await this.save(o)})}async loadState(){return this.enqueue(async()=>{let r=await this.load();return r=u$(r),await this.save(r),r})}async getModelUsage(r){return this.enqueue(async()=>{let n=await this.load();return n=u$(n),v_e(n,r)})}async getGeneralUsage(){return this.enqueue(async()=>{let r=await this.load();return r=u$(r),p$(r)})}enqueue(r){let n=this.queue.then(r);return this.queue=n.then(()=>{},()=>{}),n}async load(){try{if(!await JH.default.pathExists(this.filePath))return d$();let n=await JH.default.readFile(this.filePath,"utf8"),o=JSON.parse(n);if(Array.isArray(o.generalBucket)){let l=tGr(o);if(l)return await this.save(l),l}return typeof o.windowStart=="number"&&typeof o.providers=="object"&&o.providers!==null?{version:1,windowStart:o.windowStart,providers:o.providers}:($.warn(`[TokenLimitStore] Usage file at ${this.filePath} has unexpected shape \u2014 resetting.`),d$())}catch(r){return $.warn(`[TokenLimitStore] Failed to read usage file (${String(r)}) \u2014 starting fresh.`),d$()}}async save(r){try{await JH.default.ensureDir(V6e.dirname(this.filePath));let n=`${this.filePath}.${process.pid}.tmp`;await JH.default.writeFile(n,JSON.stringify(r,null,2),"utf8"),await JH.default.move(n,this.filePath,{overwrite:!0})}catch(n){$.warn(`[TokenLimitStore] Failed to save usage file: ${String(n)}`)}}}});import rGr from"path";async function Fb(){return m$||(m$=new A_e,m$.setLimitStore(f$()),await m$.initialize()),m$}var nGr,w_e,A_e,m$,_$=Ut(()=>{"use strict";j_();sf();Dp();Q_();Xa();O2();ju();IH();x_e();nGr="token-usage.json",w_e={version:"1.0",sessions:[],currentSessionId:null,lastUpdated:""},A_e=class{data;currentSession=null;warningThreshold;costWarningThreshold;initialized=!1;dirty=!1;tokenWarningEmitted=!1;costWarningEmitted=!1;constructor(){this.data={...w_e},this.warningThreshold=2e5,this.costWarningThreshold=10}async initialize(){this.initialized||(await this.load(),this.initialized=!0,$.debug("Token tracker initialized"))}startSession(r){let n=r||xa(),o=this.data.sessions.find(l=>l.sessionId===n);return o?(this.currentSession=o,this.data.currentSessionId=n,$.debug(`Resumed existing token tracking session: ${n}`),n):(this.tokenWarningEmitted=!1,this.costWarningEmitted=!1,this.currentSession={sessionId:n,startTime:rn(),calls:[],totals:this.createEmptyTokenUsage(),estimatedCost:this.createEmptyCostEstimate()},this.data.sessions.push(this.currentSession),this.data.currentSessionId=n,this.dirty=!0,$.debug(`Token tracking session started: ${n}`),n)}async recordUsage(r,n,o){this.currentSession||this.startSession();let l=this.calculateCost(n,r),p={id:xa(),timestamp:rn(),model:r,usage:{...n},cost:l,purpose:o};this.currentSession.calls.push(p),this.updateSessionTotals();let h=this.checkWarnings();for(let I of h)$.debug(I.message);this.dirty=!0,await this.save(),$.debug(`Recorded usage: ${n.inputTokens} in, ${n.outputTokens} out, ${l.totalCost.toFixed(4)} USD`)}getCurrentSessionUsage(){return this.currentSession}getSessionMetrics(){if(!this.currentSession||this.currentSession.calls.length===0)return null;let r=this.currentSession.calls,n=r.map(l=>l.usage.inputTokens),o=r.map(l=>l.usage.outputTokens);return{averageInputTokens:this.calculateAverage(n),averageOutputTokens:this.calculateAverage(o),peakInputTokens:Math.max(...n),peakOutputTokens:Math.max(...o),totalCalls:r.length,totalTokens:this.currentSession.totals.totalTokens,totalCost:this.currentSession.estimatedCost.totalCost}}getAllTimeStats(){let r=this.data.sessions.flatMap(h=>h.calls);if(r.length===0)return{averageInputTokens:0,averageOutputTokens:0,peakInputTokens:0,peakOutputTokens:0,totalCalls:0,totalTokens:0,totalCost:0};let n=r.map(h=>h.usage.inputTokens),o=r.map(h=>h.usage.outputTokens),l=this.data.sessions.reduce((h,I)=>h+I.totals.totalTokens,0),p=this.data.sessions.reduce((h,I)=>h+I.estimatedCost.totalCost,0);return{averageInputTokens:this.calculateAverage(n),averageOutputTokens:this.calculateAverage(o),peakInputTokens:Math.max(...n),peakOutputTokens:Math.max(...o),totalCalls:r.length,totalTokens:l,totalCost:p}}getStatsByPeriod(r,n=new Date){let o=r.getTime(),l=n.getTime(),p=this.data.sessions.flatMap(W=>W.calls.filter(H=>{let M=new Date(H.timestamp).getTime();return M>=o&&M<=l}));if(p.length===0)return{averageInputTokens:0,averageOutputTokens:0,peakInputTokens:0,peakOutputTokens:0,totalCalls:0,totalTokens:0,totalCost:0};let h=p.map(W=>W.usage.inputTokens),I=p.map(W=>W.usage.outputTokens),k=p.reduce((W,H)=>W+H.usage.totalTokens,0),N=p.reduce((W,H)=>W+H.cost.totalCost,0);return{averageInputTokens:this.calculateAverage(h),averageOutputTokens:this.calculateAverage(I),peakInputTokens:Math.max(...h),peakOutputTokens:Math.max(...I),totalCalls:p.length,totalTokens:k,totalCost:N}}getStatsByModel(){let r=new Map;for(let o of this.data.sessions)for(let l of o.calls){let p=r.get(l.model)||[];p.push(l),r.set(l.model,p)}let n=new Map;for(let[o,l]of r){if(l.length===0)continue;let p=l.map(N=>N.usage.inputTokens),h=l.map(N=>N.usage.outputTokens),I=l.reduce((N,W)=>N+W.usage.totalTokens,0),k=l.reduce((N,W)=>N+W.cost.totalCost,0);n.set(o,{averageInputTokens:this.calculateAverage(p),averageOutputTokens:this.calculateAverage(h),peakInputTokens:Math.max(...p),peakOutputTokens:Math.max(...h),totalCalls:l.length,totalTokens:I,totalCost:k})}return n}async endSession(){this.currentSession&&(this.currentSession.endTime=rn(),this.dirty=!0,await this.save(),$.debug(`Token tracking session ended: ${this.currentSession.sessionId}`),this.currentSession=null,this.data.currentSessionId=null)}async exportUsage(){return{...this.data,lastUpdated:rn()}}getSessionById(r){return this.data.sessions.find(n=>n.sessionId===r)||null}getSessions(r,n){let o=[...this.data.sessions];if(r){let l=r.getTime();o=o.filter(p=>new Date(p.startTime).getTime()>=l)}if(n){let l=n.getTime();o=o.filter(p=>new Date(p.startTime).getTime()<=l)}return o}setWarningThreshold(r){this.warningThreshold=r,this.tokenWarningEmitted=!1,$.debug(`Token warning threshold set to ${r}`)}getWarningThreshold(){return this.warningThreshold}setCostWarningThreshold(r){this.costWarningThreshold=r,this.costWarningEmitted=!1,$.debug(`Cost warning threshold set to $${r}`)}getCostWarningThreshold(){return this.costWarningThreshold}checkWarnings(){let r=[];if(!this.currentSession)return r;let n=this.currentSession.totals.totalTokens,o=this.currentSession.estimatedCost.totalCost;return n>=this.warningThreshold&&!this.tokenWarningEmitted?(this.tokenWarningEmitted=!0,r.push({type:"exceeded_threshold",message:`Token usage (${n.toLocaleString()}) has exceeded the warning threshold (${this.warningThreshold.toLocaleString()})`,currentValue:n,threshold:this.warningThreshold,severity:"warning"})):n>=this.warningThreshold*.8&&!this.tokenWarningEmitted&&r.push({type:"approaching_limit",message:`Token usage (${n.toLocaleString()}) is approaching the warning threshold (${this.warningThreshold.toLocaleString()})`,currentValue:n,threshold:this.warningThreshold,severity:"info"}),o>=this.costWarningThreshold&&!this.costWarningEmitted?(this.costWarningEmitted=!0,r.push({type:"high_cost",message:`Session cost ($${o.toFixed(2)}) has exceeded the warning threshold ($${this.costWarningThreshold.toFixed(2)})`,currentValue:o,threshold:this.costWarningThreshold,severity:"warning"})):o>=this.costWarningThreshold*.8&&!this.costWarningEmitted&&r.push({type:"high_cost",message:`Session cost ($${o.toFixed(2)}) is approaching the warning threshold ($${this.costWarningThreshold.toFixed(2)})`,currentValue:o,threshold:this.costWarningThreshold,severity:"info"}),r}_limitStore=null;setLimitStore(r){this._limitStore=r}getLimitStore(){if(!this._limitStore)throw new Error("[TokenTracker] TokenLimitStore not set \u2014 call setLimitStore() first.");return this._limitStore}resolveLimit(r,n,o){let l=ZMe(n,o),p=l.perModelLimits[r]??l.defaultPerModelLimit;return{generalLimit:l.generalLimit,modelLimit:p}}async checkLimit(r,n,o){let p=await this.getLimitStore().loadState(),{generalLimit:h,modelLimit:I}=this.resolveLimit(r,n,o),k=p$(p),N=v_e(p,r),W=Math.max(0,h-k),H=Math.max(0,I-N);return N>=I?{allowed:!1,generalRemaining:W,modelRemaining:0,reason:`Token limit exceeded for model "${r}". Used ${N.toLocaleString()} / ${I.toLocaleString()} tokens in the last ${Gq}h.`}:k>=h?{allowed:!1,generalRemaining:0,modelRemaining:H,reason:`Aggregate token limit exceeded. Used ${k.toLocaleString()} / ${h.toLocaleString()} tokens in the last ${Gq}h.`}:{allowed:!0,generalRemaining:W,modelRemaining:H}}async recordLimitUsage(r,n){try{await this.getLimitStore().recordUsage(r,n)}catch(o){$.warn(`[TokenTracker] Failed to record limit usage for ${r}: ${String(o)}`)}}async getUsageForModel(r){return this.getLimitStore().getModelUsage(r)}async getRemainingTokens(r,n,o){let{modelLimit:l}=this.resolveLimit(r,n,o),p=await this.getUsageForModel(r);return Math.max(0,l-p)}async clearAllData(){this.data={...w_e},this.currentSession=null,this.dirty=!0,await this.save(),$.info("All token usage data cleared")}async clearOldData(r){let n=new Date;n.setDate(n.getDate()-r);let o=n.getTime(),l=this.data.sessions.length;this.data.sessions=this.data.sessions.filter(h=>new Date(h.startTime).getTime()>=o);let p=l-this.data.sessions.length;return p>0&&(this.dirty=!0,await this.save(),$.info(`Cleared ${p} sessions older than ${r} days`)),p}calculateCost(r,n){let o=Gm(n);if(!o)return $.debug(`Unknown model for cost calculation: ${n}`),this.createEmptyCostEstimate();let l=r.inputTokens/1e6*o.pricing.inputPricePerMillion,p=r.outputTokens/1e6*o.pricing.outputPricePerMillion;return{inputCost:l,outputCost:p,totalCost:l+p,currency:"USD"}}updateSessionTotals(){if(!this.currentSession)return;let r=this.createEmptyTokenUsage(),n=this.createEmptyCostEstimate();for(let o of this.currentSession.calls)r.inputTokens+=o.usage.inputTokens,r.outputTokens+=o.usage.outputTokens,r.totalTokens+=o.usage.totalTokens,o.usage.cacheCreationInputTokens&&(r.cacheCreationInputTokens=(r.cacheCreationInputTokens||0)+o.usage.cacheCreationInputTokens),o.usage.cacheReadInputTokens&&(r.cacheReadInputTokens=(r.cacheReadInputTokens||0)+o.usage.cacheReadInputTokens),n.inputCost+=o.cost.inputCost,n.outputCost+=o.cost.outputCost,n.totalCost+=o.cost.totalCost;this.currentSession.totals=r,this.currentSession.estimatedCost=n}calculateAverage(r){if(r.length===0)return 0;let n=r.reduce((o,l)=>o+l,0);return Math.round(n/r.length)}createEmptyTokenUsage(){return{inputTokens:0,outputTokens:0,totalTokens:0}}createEmptyCostEstimate(){return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"}}getFilePath(){return rGr.join(oc(),nGr)}async load(){try{await Zl(oc());let r=this.getFilePath(),n=await _d(r);n&&(this.data={...w_e,...n},n.currentSessionId&&(this.currentSession=n.sessions.find(o=>o.sessionId===n.currentSessionId)||null),$.debug(`Loaded token usage data: ${this.data.sessions.length} sessions`))}catch(r){$.debug("Failed to load token usage data, starting fresh",r),this.data={...w_e}}}async save(){if(this.dirty)try{await Zl(oc());let r=this.getFilePath();this.data.lastUpdated=rn(),await X_(r,this.data),this.dirty=!1,$.debug("Token usage data saved")}catch(r){$.error("Failed to save token usage data",r)}}async forceSave(){this.dirty=!0,await this.save()}},m$=null});function xh(){return M6e||(M6e=new S_e),M6e}var sGr,aGr,S_e,M6e,GN=Ut(()=>{"use strict";j_();_H();Xa();Q_();sf();Im();t1();sGr=5,aGr=100,S_e=class{mode="manual";history={requests:[],responses:[]};autoApprovePatterns=[];requireApprovalPatterns=[];maxAutoApproveFiles=sGr;maxAutoApproveLines=aGr;eventEmitter;pendingRequest=null;resolveApproval=null;currentComplexityMode=null;currentComplexityConfidence=0;smartModeConfidenceThreshold=70;sessionAutoApprovalEnabled=!1;fileEditsAutoApprovalEnabled=!1;pendingPlanApproval=null;resolvePlanApprovalPromise=null;approvedCommandPrefixes=new Set;pendingClarificationWizard=null;resolveClarificationWizardPromise=null;constructor(){this.eventEmitter=aa()}getMode(){return this.mode}enableSessionAutoApproval(){this.sessionAutoApprovalEnabled=!0,$.info("Session auto-approval enabled - all subsequent operations will be auto-approved")}disableSessionAutoApproval(){this.sessionAutoApprovalEnabled=!1,$.info("Session auto-approval disabled")}isSessionAutoApprovalEnabled(){return this.sessionAutoApprovalEnabled}enableFileEditsAutoApproval(){this.fileEditsAutoApprovalEnabled=!0,$.info("File edits auto-approval enabled - file writes, edits, and commands will be auto-approved")}disableFileEditsAutoApproval(){this.fileEditsAutoApprovalEnabled=!1,$.info("File edits auto-approval disabled")}getCommandPrefix(r){let o=r.trim().split(/\s+/),l=["sudo","env","npx","pnpm","yarn","bunx"];for(let p of o)if(!l.includes(p.toLowerCase()))return p.toLowerCase();return o[0]?.toLowerCase()||""}isCommandPrefixApproved(r){let n=this.getCommandPrefix(r);return this.approvedCommandPrefixes.has(n)}approveCommandPrefix(r){let n=this.getCommandPrefix(r);this.approvedCommandPrefixes.add(n),$.info(`Command prefix approved for session: ${n}`)}getApprovedCommandPrefixes(){return Array.from(this.approvedCommandPrefixes)}clearApprovedCommandPrefixes(){this.approvedCommandPrefixes.clear(),$.debug("Approved command prefixes cleared")}setComplexityContext(r,n=0){this.currentComplexityMode=r,this.currentComplexityConfidence=n,$.debug(`Complexity context set: mode=${r}, confidence=${n}`)}getComplexityContext(){return{mode:this.currentComplexityMode,confidence:this.currentComplexityConfidence}}clearComplexityContext(){this.currentComplexityMode=null,this.currentComplexityConfidence=0,$.debug("Complexity context cleared")}setSmartModeConfidenceThreshold(r){this.smartModeConfidenceThreshold=Math.max(0,Math.min(100,r)),$.debug(`SMART mode confidence threshold set to: ${this.smartModeConfidenceThreshold}`)}quickClassifyRequest(r){let n=r.toLowerCase(),o=["refactor","redesign","migrate","architecture","rewrite","restructure","overhaul","major","breaking change","system","framework","infrastructure","database schema","api redesign","authentication system","authorization","security overhaul"],l=["implement","feature","add functionality","integrate","connect","setup","configure","multi-file","across files","multiple components","service","module","api endpoint"],p=["create","simple","basic","hello world","example","add file","new file","write","make","generate","readme","config","single","quick","small","fix typo","update text","change string","rename"];if(o.some(q=>n.includes(q)))return $.debug("Quick classify: PLAN (complex keyword found)"),{mode:"plan",confidence:80};let I=l.some(q=>n.includes(q)),k=/multiple|several|all|many|across/i.test(n);if(I||k)return $.debug("Quick classify: CLARIFICATION (medium keyword found)"),{mode:"clarification",confidence:70};let N=p.some(q=>n.includes(q)),W=n.length<100,H=/\b(a|one|single|the)\s+(file|page|document)\b/i.test(n),M=/^(create|make|write|add|generate)\b/i.test(n.trim());if(N||W&&(H||M)){let q=N?85:75;return $.debug(`Quick classify: DIRECT (simple indicators, confidence: ${q})`),{mode:"direct",confidence:q}}return $.debug("Quick classify: CLARIFICATION (default for ambiguous request)"),{mode:"clarification",confidence:60}}classifyAndSetContext(r){let{mode:n,confidence:o}=this.quickClassifyRequest(r);this.setComplexityContext(n,o),$.info(`Request classified: mode=${n}, confidence=${o}%`)}setMode(r){let n=this.mode;this.mode=r,$.info(`Approval mode changed from ${n} to ${r}`)}toggleMode(){return this.mode==="manual"?this.mode="auto":this.mode="manual",$.info(`Approval mode toggled to: ${this.mode}`),this.mode}configure(r){r.autoApprovePatterns!==void 0&&(this.autoApprovePatterns=r.autoApprovePatterns),r.requireApprovalPatterns!==void 0&&(this.requireApprovalPatterns=r.requireApprovalPatterns),r.maxAutoApproveFiles!==void 0&&(this.maxAutoApproveFiles=r.maxAutoApproveFiles),r.maxAutoApproveLines!==void 0&&(this.maxAutoApproveLines=r.maxAutoApproveLines),$.debug("Approval manager configured",r)}getConfig(){return{mode:this.mode,autoApprovePatterns:[...this.autoApprovePatterns],requireApprovalPatterns:[...this.requireApprovalPatterns],maxAutoApproveFiles:this.maxAutoApproveFiles,maxAutoApproveLines:this.maxAutoApproveLines}}async requestApproval(r,n,o){let l={id:xa(),type:r,timestamp:rn(),description:n,details:o,riskLevel:this.assessRiskLevel(r,o),estimatedImpact:this.estimateImpact(r,o)};this.history.requests.push(l),this.pendingRequest=l,$.debug(`Approval requested: ${l.id}`,{type:r,riskLevel:l.riskLevel});let p=zo();if(p.logApprovalRequested({approvalId:l.id,actionType:r,actionDescription:n,reason:`Risk level: ${l.riskLevel}`}),this.canAutoApprove(l)){let I=this.createResponse(l,!0,"Auto-approved based on configuration");return this.history.responses.push(I),this.pendingRequest=null,$.info(`Request ${l.id} auto-approved`),p.logApprovalGranted({approvalId:l.id,actionType:r,actionDescription:n,decidedBy:"system",reason:"Auto-approved based on configuration"}),I}if(this.mode==="strict")return this.waitForUserApproval(l);if(this.mode==="manual")return this.waitForUserApproval(l);if(this.shouldRequireApproval(l))return this.waitForUserApproval(l);let h=this.createResponse(l,!0,"Auto-approved (auto mode)");return this.history.responses.push(h),this.pendingRequest=null,$.info(`Request ${l.id} auto-approved in auto mode`),p.logApprovalGranted({approvalId:l.id,actionType:r,actionDescription:n,decidedBy:"system",reason:"Auto-approved (auto mode)"}),h}resolveRequest(r,n){if(!this.pendingRequest||!this.resolveApproval){$.warn("No pending approval request to resolve");return}let o=r==="approve",l=this.createResponse(this.pendingRequest,o,n);this.history.responses.push(l),$.info(`Request ${this.pendingRequest.id} ${o?"approved":"rejected"}`,{choice:r,reason:n});let p=zo(),h={approvalId:this.pendingRequest.id,actionType:this.pendingRequest.type,actionDescription:this.pendingRequest.description,decidedBy:"user",reason:n};o?p.logApprovalGranted(h):p.logApprovalDenied(h),this.resolveApproval(l),this.pendingRequest=null,this.resolveApproval=null}getPendingRequest(){return this.pendingRequest}hasPendingRequest(){return this.pendingRequest!==null}cancelPendingRequest(){if(this.pendingRequest&&this.resolveApproval){let r=this.createResponse(this.pendingRequest,!1,"Cancelled by user");this.history.responses.push(r),zo().logApprovalDenied({approvalId:this.pendingRequest.id,actionType:this.pendingRequest.type,actionDescription:this.pendingRequest.description,decidedBy:"user",reason:"Cancelled by user"}),this.resolveApproval(r)}this.pendingRequest=null,this.resolveApproval=null}getHistory(){return{requests:[...this.history.requests],responses:[...this.history.responses]}}getStatistics(){let r=this.history.responses.filter(o=>o.approved).length,n=this.history.responses.filter(o=>o.approved&&o.reason?.includes("Auto-approved")).length;return{totalRequests:this.history.requests.length,approved:r,rejected:this.history.responses.filter(o=>!o.approved).length,autoApproved:n}}clearHistory(){this.history={requests:[],responses:[]},$.debug("Approval history cleared")}async requestPlanApproval(r,n,o,l){let p={id:xa(),timestamp:rn(),plan:r,context:n,complexity:o,completedTaskIds:l};return this.pendingPlanApproval=p,$.info("Plan approval requested",{planId:r.id,taskCount:r.tasks.length,totalComplexity:r.totalComplexity}),zo().logPlanApprovalRequested(r.id),this.eventEmitter.emit("plan-approval-required",{request:p}),new Promise(I=>{this.resolvePlanApprovalPromise=I})}resolvePlanApproval(r,n,o){if(!this.pendingPlanApproval||!this.resolvePlanApprovalPromise){$.warn("No pending plan approval request to resolve");return}let l={requestId:this.pendingPlanApproval.id,approved:r==="approve"||r==="approve-compact"||r==="approve-auto-edits",timestamp:rn(),choice:r,modifications:n,clarifications:o};$.info("Plan approval resolved",{planId:this.pendingPlanApproval.plan.id,choice:r,approved:l.approved}),zo().logPlanApprovalResolved(this.pendingPlanApproval.plan.id,r),this.eventEmitter.emit("plan-approval-resolved",{requestId:this.pendingPlanApproval.id,choice:r,modifications:n,clarifications:o}),this.resolvePlanApprovalPromise(l),this.pendingPlanApproval=null,this.resolvePlanApprovalPromise=null}getPendingPlanApproval(){return this.pendingPlanApproval}hasPendingPlanApproval(){return this.pendingPlanApproval!==null}cancelPendingPlanApproval(){if(this.pendingPlanApproval&&this.resolvePlanApprovalPromise){let r={requestId:this.pendingPlanApproval.id,approved:!1,timestamp:rn(),choice:"reject"};$.info("Plan approval cancelled",{planId:this.pendingPlanApproval.plan.id}),zo().logPlanApprovalResolved(this.pendingPlanApproval.plan.id,"reject"),this.resolvePlanApprovalPromise(r)}this.pendingPlanApproval=null,this.resolvePlanApprovalPromise=null}async requestClarification(r,n,o){let l={id:xa(),timestamp:rn(),taskSummary:r,questions:n,reasoning:o};return this.pendingClarificationWizard=l,$.info("Clarification wizard requested",{requestId:l.id,questionCount:n.length}),this.eventEmitter.emit("clarification-required",{request:l}),new Promise(p=>{this.resolveClarificationWizardPromise=p})}resolveClarificationWizard(r){if(!this.pendingClarificationWizard||!this.resolveClarificationWizardPromise){$.warn("No pending clarification wizard request to resolve");return}let n=r!==null,o=this.pendingClarificationWizard,l;if(n&&r){let h=o.questions.map((k,N)=>({question:k,answer:r[N]||{questionId:k.id,answer:"",answeredAt:rn()}})),I=r.map((k,N)=>{let W=o.questions[N],H=Array.isArray(k.answer)?k.answer.join(", "):k.answer;return`${W.category}: ${H}`});l={qaRecords:h,completedAt:rn(),duration:0,decisionSummary:I.join("; ")}}let p={requestId:o.id,completed:n,timestamp:rn(),answers:r||void 0,result:l};$.info("Clarification wizard resolved",{requestId:o.id,completed:n,answerCount:r?.length||0}),this.resolveClarificationWizardPromise(p),this.pendingClarificationWizard=null,this.resolveClarificationWizardPromise=null}getPendingClarificationWizard(){return this.pendingClarificationWizard}hasPendingClarificationWizard(){return this.pendingClarificationWizard!==null}cancelPendingClarificationWizard(){if(this.pendingClarificationWizard&&this.resolveClarificationWizardPromise){let r={requestId:this.pendingClarificationWizard.id,completed:!1,timestamp:rn()};$.info("Clarification wizard cancelled",{requestId:this.pendingClarificationWizard.id}),this.resolveClarificationWizardPromise(r)}this.pendingClarificationWizard=null,this.resolveClarificationWizardPromise=null}getRequest(r){return this.history.requests.find(n=>n.id===r)}getResponse(r){return this.history.responses.find(n=>n.requestId===r)}async waitForUserApproval(r){return this.eventEmitter.emit("approval-required",{request:r}),new Promise(n=>{this.resolveApproval=n})}canAutoApprove(r){if(this.sessionAutoApprovalEnabled)return r.riskLevel==="critical"?($.debug("Session auto-approval: Skipping critical operation, requiring manual approval"),!1):($.debug("Session auto-approval: Auto-approving operation"),!0);if(this.fileEditsAutoApprovalEnabled&&["file_create","file_modify","shell_command"].includes(r.type))if(r.type==="shell_command"&&(r.riskLevel==="high"||r.riskLevel==="critical"))$.debug("File edits auto-approval: Skipping high-risk shell command, requiring manual approval");else return $.debug("File edits auto-approval: Auto-approving operation"),!0;if(r.type==="shell_command"&&r.details.command&&this.isCommandPrefixApproved(r.details.command)){let o=this.getCommandPrefix(r.details.command);return $.debug(`Command prefix '${o}' is approved, auto-approving`),!0}if(r.riskLevel==="high"||r.riskLevel==="critical"||this.mode==="strict"||r.details.affectedFiles!==void 0&&r.details.affectedFiles>this.maxAutoApproveFiles||(r.details.linesAdded||0)+(r.details.linesRemoved||0)>this.maxAutoApproveLines)return!1;if(r.details.filePaths){for(let o of r.details.filePaths)if(Qq(o,this.requireApprovalPatterns))return!1}return this.mode==="smart"?this.canSmartAutoApprove(r):this.mode!=="manual"}canSmartAutoApprove(r){let n=r.details.complexityMode||this.currentComplexityMode,o=r.details.complexityConfidence??this.currentComplexityConfidence;return n?n!=="direct"?($.debug(`SMART mode: Complexity mode is ${n}, requiring approval`),!1):o<this.smartModeConfidenceThreshold?($.debug(`SMART mode: Confidence ${o} below threshold ${this.smartModeConfidenceThreshold}, requiring approval`),!1):r.riskLevel!=="low"?($.debug(`SMART mode: Risk level is ${r.riskLevel}, requiring approval`),!1):["file_create","file_modify","file_rename"].includes(r.type)?($.info(`SMART mode: Auto-approving ${r.type} (complexity: ${n}, confidence: ${o}%, risk: ${r.riskLevel})`),!0):($.debug(`SMART mode: Operation type ${r.type} not safe for auto-approval`),!1):($.debug("SMART mode: No complexity context available, requiring approval"),!1)}shouldRequireApproval(r){if(r.details.filePaths){for(let n of r.details.filePaths)if(Qq(n,this.requireApprovalPatterns)||this.autoApprovePatterns.length>0&&!Qq(n,this.autoApprovePatterns))return!0}return r.riskLevel==="medium"||r.type==="shell_command"||r.type==="git_push"}assessRiskLevel(r,n){if(r==="git_push")return"critical";if(r==="file_delete")return"high";if(r==="multi_file_operation"){let o=n.affectedFiles||0;if(o>10)return"high";if(o>5)return"medium"}if(r==="shell_command"){let o=n.command?.toLowerCase()||"";return o.includes("rm ")||o.includes("delete")||o.includes("drop")||o.includes("truncate")?"high":"medium"}if(r==="git_commit")return"medium";if(r==="file_modify"){let o=(n.linesAdded||0)+(n.linesRemoved||0);if(o>200)return"medium";if(o>100)return"low"}return"low"}estimateImpact(r,n){let o=[];if(n.affectedFiles!==void 0&&o.push(`${n.affectedFiles} file${n.affectedFiles===1?"":"s"}`),n.linesAdded!==void 0&&n.linesAdded>0&&o.push(`+${n.linesAdded} line${n.linesAdded===1?"":"s"}`),n.linesRemoved!==void 0&&n.linesRemoved>0&&o.push(`-${n.linesRemoved} line${n.linesRemoved===1?"":"s"}`),n.command){let l=n.command.length>50?n.command.substring(0,47)+"...":n.command;o.push(`Command: ${l}`)}return o.length===0?"Minimal impact":o.join(", ")}createResponse(r,n,o){return{requestId:r.id,approved:n,timestamp:rn(),mode:this.mode,reason:o}}},M6e=null});import oGr from"path";async function zAt(i,r=Iq,n=yH){if(!BAt.has(i)){BAt.add(i);try{if(!await LH.default.pathExists(i))return;let l=await LH.default.readdir(i),p=[];for(let k of l)try{let N=oGr.join(i,k),W=await LH.default.stat(N);W.isFile()&&k!=="manifest.json"&&p.push({name:k,path:N,mtimeMs:W.mtimeMs})}catch{}let h=Date.now()-r*24*60*60*1e3,I=[];for(let k of p)if(k.mtimeMs<h)try{await LH.default.unlink(k.path)}catch{}else I.push(k);if(I.length>n){I.sort((N,W)=>W.mtimeMs-N.mtimeMs);let k=I.slice(n);for(let N of k)try{await LH.default.unlink(N.path)}catch{}}}catch{}}}var LH,BAt,qAt=Ut(()=>{"use strict";LH=Go(MI(),1);ju();BAt=new Set});import PD from"path";async function v5(){return k_e||(k_e=new E_e,await k_e.load()),k_e}var E_e,k_e,Y6e=Ut(()=>{"use strict";j_();Dp();sf();Q_();Xa();ju();qAt();E_e=class{projectRoot=process.cwd();manifest={version:"1.0",backups:[]};setProjectRoot(r){this.projectRoot=r}async createBackup(r){let n=PD.resolve(this.projectRoot,r);if(!await ea(n))return $.debug(`File does not exist, no backup needed: ${r}`),null;let o=await this.getBackupsDir(),l=xa(),p=new Date().toISOString().replace(/[:.]/g,"-"),h=PD.basename(r),I=`${p}_${l}_${h}`,k=PD.join(o,I);await TN(n,k);let N=await Sy(n),W={id:l,originalPath:r,backupPath:k,timestamp:rn(),size:N?.size||0};return this.manifest.backups.push(W),await this.saveManifest(),$.debug(`Backup created: ${k}`),W}async restore(r){let n=this.manifest.backups.find(l=>l.id===r);if(!n)return $.warn(`Backup not found: ${r}`),!1;if(!await ea(n.backupPath))return $.error(`Backup file missing: ${n.backupPath}`),!1;let o=PD.resolve(this.projectRoot,n.originalPath);return await Zl(PD.dirname(o)),await TN(n.backupPath,o),$.info(`Restored from backup: ${n.originalPath}`),!0}async restoreLatest(r){let n=this.manifest.backups.filter(o=>o.originalPath===r).sort((o,l)=>new Date(l.timestamp).getTime()-new Date(o.timestamp).getTime());return n.length===0?($.warn(`No backups found for: ${r}`),!1):this.restore(n[0].id)}getBackupsForFile(r){return this.manifest.backups.filter(n=>n.originalPath===r).sort((n,o)=>new Date(o.timestamp).getTime()-new Date(n.timestamp).getTime())}getAllBackups(){return[...this.manifest.backups].sort((r,n)=>new Date(n.timestamp).getTime()-new Date(r.timestamp).getTime())}async deleteBackup(r){let n=this.manifest.backups.findIndex(l=>l.id===r);if(n===-1)return!1;let o=this.manifest.backups[n];return await ea(o.backupPath)&&await G0(o.backupPath),this.manifest.backups.splice(n,1),await this.saveManifest(),$.debug(`Backup deleted: ${r}`),!0}async cleanup(){let r=0,n=new Date;n.setDate(n.getDate()-Iq);let o=this.manifest.backups.filter(l=>new Date(l.timestamp)<n);for(let l of o)await this.deleteBackup(l.id)&&r++;if(this.manifest.backups.length>yH){let p=[...this.manifest.backups].sort((h,I)=>new Date(I.timestamp).getTime()-new Date(h.timestamp).getTime()).slice(yH);for(let h of p)await this.deleteBackup(h.id)&&r++}return r>0&&$.info(`Cleaned up ${r} old backups`),r}async getBackupContent(r){let n=this.manifest.backups.find(o=>o.id===r);return!n||!await ea(n.backupPath)?null:ed(n.backupPath)}async load(){let r=await this.getManifestPath();if(await ea(r)){let n=await ed(r);if(n)try{this.manifest=JSON.parse(n)}catch{$.warn("Failed to parse backup manifest, starting fresh"),this.manifest={version:"1.0",backups:[]}}}}getTotalBackupSize(){return this.manifest.backups.reduce((r,n)=>r+n.size,0)}getBackupCount(){return this.manifest.backups.length}hasBackup(r){return this.manifest.backups.some(n=>n.id===r)}async getBackupsDir(){let r=PD.join(ou(this.projectRoot),cMe);return await Zl(r),await zAt(r),r}async getManifestPath(){let r=await this.getBackupsDir();return PD.join(r,"manifest.json")}async saveManifest(){let r=await this.getManifestPath();await C0(r,JSON.stringify(this.manifest,null,2))}},k_e=null});function wa(i,r,n,o,l){if(o==="m")throw new TypeError("Private method is not writable");if(o==="a"&&!l)throw new TypeError("Private accessor was defined without a setter");if(typeof r=="function"?i!==r||!l:!r.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?l.call(i,n):l?l.value=n:r.set(i,n),n}function Bn(i,r,n,o){if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a getter");if(typeof r=="function"?i!==r||!o:!r.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?o:n==="a"?o.call(i):o?o.value:r.get(i)}var NN=Ut(()=>{});var O6e,$At=Ut(()=>{O6e=function(){let{crypto:i}=globalThis;if(i?.randomUUID)return O6e=i.randomUUID.bind(i),i.randomUUID();let r=new Uint8Array(1),n=i?()=>i.getRandomValues(r)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,o=>(+o^n()&15>>+o/4).toString(16))}});function FN(i){return typeof i=="object"&&i!==null&&("name"in i&&i.name==="AbortError"||"message"in i&&String(i.message).includes("FetchRequestCanceledException"))}var h$,UH=Ut(()=>{h$=i=>{if(i instanceof Error)return i;if(typeof i=="object"&&i!==null){try{if(Object.prototype.toString.call(i)==="[object Error]"){let r=new Error(i.message,i.cause?{cause:i.cause}:{});return i.stack&&(r.stack=i.stack),i.cause&&!r.cause&&(r.cause=i.cause),i.name&&(r.name=i.name),r}}catch{}try{return new Error(JSON.stringify(i))}catch{}}return new Error(i)}});var So,N0,Ey,x5,XH,QH,jH,BH,zH,qH,$H,KH,e8,n1=Ut(()=>{UH();So=class extends Error{},N0=class i extends So{constructor(r,n,o,l,p){super(`${i.makeMessage(r,n,o)}`),this.status=r,this.headers=l,this.requestID=l?.get("request-id"),this.error=n,this.type=p??null}static makeMessage(r,n,o){let l=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):o;return r&&l?`${r} ${l}`:r?`${r} status code (no body)`:l||"(no status code or body)"}static generate(r,n,o,l){if(!r||!l)return new x5({message:o,cause:h$(n)});let p=n,h=p?.error?.type;return r===400?new QH(r,p,o,l,h):r===401?new jH(r,p,o,l,h):r===403?new BH(r,p,o,l,h):r===404?new zH(r,p,o,l,h):r===409?new qH(r,p,o,l,h):r===422?new $H(r,p,o,l,h):r===429?new KH(r,p,o,l,h):r>=500?new e8(r,p,o,l,h):new i(r,p,o,l,h)}},Ey=class extends N0{constructor({message:r}={}){super(void 0,void 0,r||"Request was aborted.",void 0)}},x5=class extends N0{constructor({message:r,cause:n}){super(void 0,void 0,r||"Connection error.",void 0),n&&(this.cause=n)}},XH=class extends x5{constructor({message:r}={}){super({message:r??"Request timed out."})}},QH=class extends N0{},jH=class extends N0{},BH=class extends N0{},zH=class extends N0{},qH=class extends N0{},$H=class extends N0{},KH=class extends N0{},e8=class extends N0{}});function T_e(i){return typeof i!="object"?{}:i??{}}function L6e(i){if(!i)return!0;for(let r in i)return!1;return!0}function eSt(i,r){return Object.prototype.hasOwnProperty.call(i,r)}var lGr,KAt,H6e,J6e,tSt,C_e,DD=Ut(()=>{n1();lGr=/^[a-z][a-z0-9+.-]*:/i,KAt=i=>lGr.test(i),H6e=i=>(H6e=Array.isArray,H6e(i)),J6e=H6e;tSt=(i,r)=>{if(typeof r!="number"||!Number.isInteger(r))throw new So(`${i} must be an integer`);if(r<0)throw new So(`${i} must be a positive integer`);return r},C_e=i=>{try{return JSON.parse(i)}catch{return}}});var rSt,nSt=Ut(()=>{rSt=i=>new Promise(r=>setTimeout(r,i))});var w5,U6e=Ut(()=>{w5="0.82.0"});function uGr(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function pGr(){if(typeof navigator>"u"||!navigator)return null;let i=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:r,pattern:n}of i){let o=n.exec(navigator.userAgent);if(o){let l=o[1]||0,p=o[2]||0,h=o[3]||0;return{browser:r,version:`${l}.${p}.${h}`}}}return null}var oSt,dGr,iSt,sSt,aSt,cSt,X6e=Ut(()=>{U6e();oSt=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";dGr=()=>{let i=uGr();if(i==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":w5,"X-Stainless-OS":sSt(Deno.build.os),"X-Stainless-Arch":iSt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":w5,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(i==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":w5,"X-Stainless-OS":sSt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":iSt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let r=pGr();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":w5,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":w5,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};iSt=i=>i==="x32"?"x32":i==="x86_64"||i==="x64"?"x64":i==="arm"?"arm":i==="aarch64"||i==="arm64"?"arm64":i?`other:${i}`:"unknown",sSt=i=>(i=i.toLowerCase(),i.includes("ios")?"iOS":i==="android"?"Android":i==="darwin"?"MacOS":i==="win32"?"Windows":i==="freebsd"?"FreeBSD":i==="openbsd"?"OpenBSD":i==="linux"?"Linux":i?`Other:${i}`:"Unknown"),cSt=()=>aSt??(aSt=dGr())});function lSt(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Q6e(...i){let r=globalThis.ReadableStream;if(typeof r>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new r(...i)}function G_e(i){let r=Symbol.asyncIterator in i?i[Symbol.asyncIterator]():i[Symbol.iterator]();return Q6e({start(){},async pull(n){let{done:o,value:l}=await r.next();o?n.close():n.enqueue(l)},async cancel(){await r.return?.()}})}function g$(i){if(i[Symbol.asyncIterator])return i;let r=i.getReader();return{async next(){try{let n=await r.read();return n?.done&&r.releaseLock(),n}catch(n){throw r.releaseLock(),n}},async return(){let n=r.cancel();return r.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function uSt(i){if(i===null||typeof i!="object")return;if(i[Symbol.asyncIterator]){await i[Symbol.asyncIterator]().return?.();return}let r=i.getReader(),n=r.cancel();r.releaseLock(),await n}var t8=Ut(()=>{});var dSt,pSt=Ut(()=>{dSt=({headers:i,body:r})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(r)})});function fSt(i){return Object.entries(i).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new So(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}var mSt=Ut(()=>{n1()});function gSt(i){let r=0;for(let l of i)r+=l.length;let n=new Uint8Array(r),o=0;for(let l of i)n.set(l,o),o+=l.length;return n}function y$(i){let r;return(_St??(r=new globalThis.TextEncoder,_St=r.encode.bind(r)))(i)}function j6e(i){let r;return(hSt??(r=new globalThis.TextDecoder,hSt=r.decode.bind(r)))(i)}var _St,hSt,B6e=Ut(()=>{});function _Gr(i,r){for(let l=r??0;l<i.length;l++){if(i[l]===10)return{preceding:l,index:l+1,carriage:!1};if(i[l]===13)return{preceding:l,index:l+1,carriage:!0}}return null}function ySt(i){for(let o=0;o<i.length-1;o++){if(i[o]===10&&i[o+1]===10||i[o]===13&&i[o+1]===13)return o+2;if(i[o]===13&&i[o+1]===10&&o+3<i.length&&i[o+2]===13&&i[o+3]===10)return o+4}return-1}var L2,U2,RN,z6e=Ut(()=>{NN();B6e();RN=class{constructor(){L2.set(this,void 0),U2.set(this,void 0),wa(this,L2,new Uint8Array,"f"),wa(this,U2,null,"f")}decode(r){if(r==null)return[];let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?y$(r):r;wa(this,L2,gSt([Bn(this,L2,"f"),n]),"f");let o=[],l;for(;(l=_Gr(Bn(this,L2,"f"),Bn(this,U2,"f")))!=null;){if(l.carriage&&Bn(this,U2,"f")==null){wa(this,U2,l.index,"f");continue}if(Bn(this,U2,"f")!=null&&(l.index!==Bn(this,U2,"f")+1||l.carriage)){o.push(j6e(Bn(this,L2,"f").subarray(0,Bn(this,U2,"f")-1))),wa(this,L2,Bn(this,L2,"f").subarray(Bn(this,U2,"f")),"f"),wa(this,U2,null,"f");continue}let p=Bn(this,U2,"f")!==null?l.preceding-1:l.preceding,h=j6e(Bn(this,L2,"f").subarray(0,p));o.push(h),wa(this,L2,Bn(this,L2,"f").subarray(l.index),"f"),wa(this,U2,null,"f")}return o}flush(){return Bn(this,L2,"f").length?this.decode(`
505
+ `;await b6e.default.appendFile(n,o)}catch(n){$.debug("Failed to write system event",n)}}async logSessionStart(r,n){this.sessionId=r,await this.writeEvent({ts:rn(),level:"info",event:"session_start",component:"Session",session_id:r,data:{projectPath:n}})}async logSessionEnd(){await this.writeEvent({ts:rn(),level:"info",event:"session_end",component:"Session",session_id:this.sessionId||void 0})}async logBashExecuted(r){await this.writeEvent({ts:rn(),level:r.exitCode===0?"info":"warn",event:"bash_executed",component:"ShellExecutor",session_id:this.sessionId||void 0,data:{command:r.command,cwd:r.cwd,exitCode:r.exitCode,duration_ms:r.duration_ms,stdout:y6e(r.stdout),stderr:y6e(r.stderr),timedOut:r.timedOut,killed:r.killed}})}async logFileRead(r,n,o=!0,l){await this.writeEvent({ts:rn(),level:o?"info":"error",event:"file_read",component:"FileService",session_id:this.sessionId||void 0,data:{path:r,size:n,operation:"read",success:o,error:l}})}async logFileWrite(r,n,o=!0,l){await this.writeEvent({ts:rn(),level:o?"info":"error",event:"file_write",component:"FileService",session_id:this.sessionId||void 0,data:{path:r,size:n,operation:"write",success:o,error:l}})}async logFileDelete(r,n=!0,o){await this.writeEvent({ts:rn(),level:n?"info":"error",event:"file_delete",component:"FileService",session_id:this.sessionId||void 0,data:{path:r,operation:"delete",success:n,error:o}})}async logFileRename(r,n,o=!0,l){await this.writeEvent({ts:rn(),level:o?"info":"error",event:"file_rename",component:"FileService",session_id:this.sessionId||void 0,data:{path:r,newPath:n,operation:"rename",success:o,error:l}})}async logToolExecuted(r){await this.writeEvent({ts:rn(),level:r.success?"info":"error",event:"tool_executed",component:"ToolRegistry",session_id:this.sessionId||void 0,data:{name:r.name,executionId:r.executionId,success:r.success,duration_ms:r.duration_ms,input:r.input,output:y6e(r.output),error:r.error}})}async logError(r,n,o){await this.writeEvent({ts:rn(),level:"error",event:"error",component:r,session_id:this.sessionId||void 0,data:{error:n,details:o}})}async logEvent(r,n,o,l){await this.writeEvent({ts:rn(),level:r,event:n,component:o,session_id:this.sessionId||void 0,data:l})}async logConfigChanged(r){await this.writeEvent({ts:rn(),level:"info",event:"config_changed",component:"ConfigManager",session_id:this.sessionId||void 0,data:r})}async logProviderChanged(r){await this.writeEvent({ts:rn(),level:"info",event:"provider_changed",component:"ProviderManager",session_id:this.sessionId||void 0,data:r})}async logModelChanged(r){await this.writeEvent({ts:rn(),level:"info",event:"model_changed",component:"ProviderManager",session_id:this.sessionId||void 0,data:r})}async logMcpConnected(r){await this.writeEvent({ts:rn(),level:"info",event:"mcp_connected",component:"McpManager",session_id:this.sessionId||void 0,data:r})}async logMcpDisconnected(r){await this.writeEvent({ts:rn(),level:"warn",event:"mcp_disconnected",component:"McpManager",session_id:this.sessionId||void 0,data:r})}async logMcpError(r){await this.writeEvent({ts:rn(),level:"error",event:"mcp_error",component:"McpManager",session_id:this.sessionId||void 0,data:r})}async logToolRegistered(r,n){await this.writeEvent({ts:rn(),level:"debug",event:"tool_registered",component:"ToolRegistry",session_id:this.sessionId||void 0,data:{name:r,source:n}})}async logToolFailed(r,n,o){await this.writeEvent({ts:rn(),level:"error",event:"tool_failed",component:"ToolRegistry",session_id:this.sessionId||void 0,data:{name:r,error:n,executionId:o}})}async logWorkflowStarted(r){await this.writeEvent({ts:rn(),level:"info",event:"workflow_started",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logWorkflowCompleted(r){await this.writeEvent({ts:rn(),level:"info",event:"workflow_completed",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logWorkflowFailed(r){await this.writeEvent({ts:rn(),level:"error",event:"workflow_failed",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logStepStarted(r){await this.writeEvent({ts:rn(),level:"info",event:"step_started",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logStepCompleted(r){await this.writeEvent({ts:rn(),level:"info",event:"step_completed",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logStepFailed(r){await this.writeEvent({ts:rn(),level:"error",event:"step_failed",component:"WorkflowManager",session_id:this.sessionId||void 0,data:r})}async logApprovalRequested(r){await this.writeEvent({ts:rn(),level:"info",event:"approval_requested",component:"ApprovalManager",session_id:this.sessionId||void 0,data:r})}async logApprovalGranted(r){await this.writeEvent({ts:rn(),level:"info",event:"approval_granted",component:"ApprovalManager",session_id:this.sessionId||void 0,data:r})}async logApprovalDenied(r){await this.writeEvent({ts:rn(),level:"warn",event:"approval_denied",component:"ApprovalManager",session_id:this.sessionId||void 0,data:r})}async logApprovalTimeout(r){await this.writeEvent({ts:rn(),level:"warn",event:"approval_timeout",component:"ApprovalManager",session_id:this.sessionId||void 0,data:r})}async logContextLoaded(r){await this.writeEvent({ts:rn(),level:"info",event:"context_loaded",component:"ContextManager",session_id:this.sessionId||void 0,data:r})}async logContextSaved(r){await this.writeEvent({ts:rn(),level:"info",event:"context_saved",component:"ContextManager",session_id:this.sessionId||void 0,data:r})}async logContextCompacted(r){await this.writeEvent({ts:rn(),level:"info",event:"context_compacted",component:"ContextManager",session_id:this.sessionId||void 0,data:r})}async logRateLimited(r){await this.writeEvent({ts:rn(),level:"warn",event:"rate_limited",component:"ApiClient",session_id:this.sessionId||void 0,data:r})}async logRetryAttempted(r){await this.writeEvent({ts:rn(),level:"warn",event:"retry_attempted",component:"ApiClient",session_id:this.sessionId||void 0,data:r})}async logApiError(r){await this.writeEvent({ts:rn(),level:"error",event:"api_error",component:"ApiClient",session_id:this.sessionId||void 0,data:r})}async logCacheHit(r){await this.writeEvent({ts:rn(),level:"debug",event:"cache_hit",component:"CacheManager",session_id:this.sessionId||void 0,data:r})}async logCacheMiss(r){await this.writeEvent({ts:rn(),level:"debug",event:"cache_miss",component:"CacheManager",session_id:this.sessionId||void 0,data:r})}async logIndexStarted(r){await this.writeEvent({ts:rn(),level:"info",event:"index_started",component:"CodebaseIndexer",session_id:this.sessionId||void 0,data:r})}async logIndexCompleted(r){await this.writeEvent({ts:rn(),level:"info",event:"index_completed",component:"CodebaseIndexer",session_id:this.sessionId||void 0,data:r})}async logComplexityAnalyzed(r){await this.writeEvent({ts:rn(),level:"info",event:"complexity_analyzed",component:"ComplexityClassifier",session_id:this.sessionId||void 0,data:r})}async logGitOperation(r){await this.writeEvent({ts:rn(),level:r.success?"info":"warn",event:"git_operation",component:"GitService",session_id:this.sessionId||void 0,data:r})}async logClarificationRequested(r){await this.writeEvent({ts:rn(),level:"info",event:"clarification_requested",component:"InteractiveClarifier",session_id:this.sessionId||void 0,data:r})}async logClarificationCompleted(r){await this.writeEvent({ts:rn(),level:"info",event:"clarification_completed",component:"InteractiveClarifier",session_id:this.sessionId||void 0,data:r})}async logPlanGenerated(r){await this.writeEvent({ts:rn(),level:"info",event:"plan_generated",component:"PlanGenerator",session_id:this.sessionId||void 0,data:r})}logPlanApprovalRequested(r){this.writeEvent({ts:rn(),level:"info",event:"plan_approval_requested",component:"ApprovalManager",session_id:this.sessionId||void 0,data:{planId:r}})}logPlanApprovalResolved(r,n){this.writeEvent({ts:rn(),level:"info",event:"plan_approval_resolved",component:"ApprovalManager",session_id:this.sessionId||void 0,data:{planId:r,choice:n}})}},s_e=null});import a_e from"path";function WD(){return v6e||(v6e=new o_e),v6e}var PAt,H2,o_e,v6e,c_e=Ut(()=>{"use strict";PAt=Go(wxt(),1);ju();sf();Dp();Xa();O2();t1();H2="compass",o_e=class i{config=structuredClone(xN);sources={anthropic:"default",ollama:"default",project:"default",safety:"default",ui:"default",session:"default",update:"default",agentic:"default"};loaded=!1;explorer=(0,PAt.cosmiconfig)(H2,{searchPlaces:["package.json",`.${H2}rc`,`.${H2}rc.json`,`.${H2}rc.yaml`,`.${H2}rc.yml`,`.${H2}rc.js`,`.${H2}rc.cjs`,`.${H2}rc.mjs`,`${H2}.config.js`,`${H2}.config.cjs`,`${H2}.config.mjs`,`${H2}.config.ts`],packageProp:H2});async load(r){return this.config=this.deepClone(xN),this.resetSources(),await this.loadGlobalConfig(),r?await this.loadProjectConfig(r):await this.loadProjectConfig(process.cwd()),await this.loadCosmicConfig(r),this.applyEnvironmentVariables(),this.loaded=!0,$.debug("Configuration loaded",{sources:this.sources}),{config:this.config,sources:this.sources}}getConfig(){return this.config}get(r){return this.config[r]}set(r,n){let o=this.deepClone(this.config[r]);this.config[r]={...this.config[r],...n},$.debug(`Configuration updated: ${r}`,n);let l=zo();if(l.logConfigChanged({key:r,oldValue:o,newValue:this.config[r],source:"user"}),r==="anthropic"){let p=n,h=o;p.model&&p.model!==h.model&&l.logModelChanged({model:p.model,previousModel:h.model,reason:"User configuration change"})}if(r==="ollama"){let p=n,h=o;p.model&&p.model!==h.model&&l.logModelChanged({model:p.model,previousModel:h.model,reason:"User configuration change"})}}setValue(r,n){let o=r.split("."),l=this.getValue(r),p=this.config;for(let I=0;I<o.length-1;I++){let k=o[I];(!(k in p)||typeof p[k]!="object")&&(p[k]={}),p=p[k]}p[o[o.length-1]]=n,$.debug(`Configuration value set: ${r}`,{value:n});let h=zo();h.logConfigChanged({key:r,oldValue:l,newValue:n,source:"user"}),r==="anthropic.model"&&n!==l&&h.logModelChanged({model:n,previousModel:l,reason:"User configuration change"})}getValue(r){let n=r.split("."),o=this.config;for(let l of n){if(o===null||typeof o!="object")return;o=o[l]}return o}async saveGlobal(r){let n=oc();await Zl(n);let o=a_e.join(n,hH),l=await _d(o,{version:"1.0",config:{}}),p={version:"1.0",config:this.deepMerge(l?.config||{},r)};await X_(o,p),$.debug("Global configuration saved"),this.mergeConfig(r,"global")}async saveProject(r,n){let o=ou(r);await Zl(o);let l=a_e.join(o,hH),p=await _d(l,{version:"1.0",config:{}}),h={version:"1.0",config:this.deepMerge(p?.config||{},n)};await X_(l,h),$.debug("Project configuration saved"),this.mergeConfig(n,"project")}getSource(r){return this.sources[r]}getSources(){return{...this.sources}}async saveOllamaConfig(r){let n={model:r.model,endpoint:r.endpoint,apiKey:r.apiKey,maxTokens:r.maxTokens??16384,temperature:r.temperature??.4,autoFetched:r.autoFetched??!0};await this.saveGlobal({ollama:n}),$.info("Ollama configuration saved from Compass",{model:r.model})}getOllamaConfig(){return this.config.ollama}hasOllamaConfig(){return!!(this.config.ollama?.model&&this.config.ollama?.endpoint)}isLoaded(){return this.loaded}reset(){this.config=this.deepClone(xN),this.resetSources(),this.loaded=!1,$.debug("Configuration reset to defaults")}validate(){let r=[];return this.config.anthropic.maxTokens<=0&&r.push("anthropic.maxTokens must be positive"),(this.config.anthropic.temperature<0||this.config.anthropic.temperature>1)&&r.push("anthropic.temperature must be between 0 and 1"),this.config.safety.maxFilesPerOperation<=0&&r.push("safety.maxFilesPerOperation must be positive"),this.config.safety.shellCommandTimeout<=0&&r.push("safety.shellCommandTimeout must be positive"),this.config.session.maxHistoryLength<=0&&r.push("session.maxHistoryLength must be positive"),this.config.session.autoCompactThreshold<=0&&r.push("session.autoCompactThreshold must be positive"),this.config.session.sessionExpiryDays<=0&&r.push("session.sessionExpiryDays must be positive"),this.config.project.maxFileSize<=0&&r.push("project.maxFileSize must be positive"),r}export(r=!0){return JSON.stringify(this.config,null,r?2:void 0)}import(r){let n=JSON.parse(r);this.config=this.deepMerge(this.config,n),$.debug("Configuration imported")}async loadGlobalConfig(){let r=a_e.join(oc(),hH);if(await ea(r))try{let n=await _d(r);n?.config&&(this.mergeConfig(n.config,"global"),$.debug("Global configuration loaded"))}catch(n){$.warn("Failed to load global configuration",n)}}async loadProjectConfig(r){let n=a_e.join(ou(r),hH);if(await ea(n))try{let o=await _d(n);o?.config&&(this.mergeConfig(o.config,"project"),$.debug("Project configuration loaded"))}catch(o){$.warn("Failed to load project configuration",o)}}async loadCosmicConfig(r){try{let n=r||process.cwd(),o=await this.explorer.search(n);if(o&&!o.isEmpty){let l=o.config;this.mergeConfig(l,"project"),$.debug(`Cosmiconfig loaded from: ${o.filepath}`)}}catch(n){$.debug("No cosmiconfig found",n)}}applyEnvironmentVariables(){let r=process.env[kb.API_KEY];r&&(this.config.anthropic.apiKey=r,this.sources.anthropic="env",$.debug("API key loaded from environment"));let n=process.env[kb.MODEL];n&&(this.config.anthropic.model=wy(n),this.sources.anthropic="env",$.debug(`Model set from environment: ${this.config.anthropic.model}`));let o=process.env[kb.DEBUG];o&&o.toLowerCase()!=="false"&&o!=="0"&&($.configure({level:"debug"}),$.debug("Debug mode enabled from environment"));let l=process.env[kb.NO_COLOR];l&&l.toLowerCase()!=="false"&&l!=="0"&&($.setColorOutput(!1),$.debug("Color output disabled from environment"));let p=process.env[kb.CONFIG_PATH];p&&$.debug(`Custom config path specified: ${p}`)}static DEPRECATED_KEYS=new Set(["tokenLimits"]);mergeConfig(r,n){for(let o of Object.keys(r)){if(i.DEPRECATED_KEYS.has(o)){$.warn(`[ConfigManager] "${o}" in config is deprecated and ignored. Token limits are now enforced as system defaults and cannot be overridden.`);continue}if(r[o]!==void 0){let l=this.config[o],p=r[o];if(typeof l=="object"&&l!==null&&typeof p=="object"&&p!==null&&!Array.isArray(l)&&!Array.isArray(p)){let h=this.deepMerge(l,p);this.config[o]=h}else this.config[o]=p;this.sources[o]=n}}}resetSources(){for(let r of Object.keys(this.sources))this.sources[r]="default"}deepClone(r){return JSON.parse(JSON.stringify(r))}deepMerge(r,n){let o={...r};for(let l of Object.keys(n)){let p=n[l],h=r[l];p!==void 0&&(p!==null&&typeof p=="object"&&!Array.isArray(p)&&h!==null&&typeof h=="object"&&!Array.isArray(h)?o[l]=this.deepMerge(h,p):o[l]=p)}return o}},v6e=null});function DAt(i,r=0){return(ky[i[r+0]]+ky[i[r+1]]+ky[i[r+2]]+ky[i[r+3]]+"-"+ky[i[r+4]]+ky[i[r+5]]+"-"+ky[i[r+6]]+ky[i[r+7]]+"-"+ky[i[r+8]]+ky[i[r+9]]+"-"+ky[i[r+10]]+ky[i[r+11]]+ky[i[r+12]]+ky[i[r+13]]+ky[i[r+14]]+ky[i[r+15]]).toLowerCase()}var ky,MAt=Ut(()=>{ky=[];for(let i=0;i<256;++i)ky.push((i+256).toString(16).slice(1))});import{randomFillSync as YCr}from"node:crypto";function x6e(){return l_e>u_e.length-16&&(YCr(u_e),l_e=0),u_e.slice(l_e,l_e+=16)}var u_e,l_e,YAt=Ut(()=>{u_e=new Uint8Array(256),l_e=u_e.length});import{randomUUID as OCr}from"node:crypto";var w6e,OAt=Ut(()=>{w6e={randomUUID:OCr}});function HCr(i,r,n){i=i||{};let o=i.random??i.rng?.()??x6e();if(o.length<16)throw new Error("Random bytes length must be >= 16");if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,r){if(n=n||0,n<0||n+16>r.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let l=0;l<16;++l)r[n+l]=o[l];return r}return DAt(o)}function JCr(i,r,n){return w6e.randomUUID&&!r&&!i?w6e.randomUUID():HCr(i,r,n)}var xa,HAt=Ut(()=>{OAt();YAt();MAt();xa=JCr});var j_=Ut(()=>{HAt()});function aa(){return A6e||(A6e=new d_e),A6e}var d_e,A6e,Im=Ut(()=>{"use strict";d_e=class{handlers=new Map;on(r,n){return this.handlers.has(r)||this.handlers.set(r,new Set),this.handlers.get(r).add(n),()=>{this.off(r,n)}}once(r,n){let o=l=>{this.off(r,o),n(l)};return this.on(r,o)}off(r,n){let o=this.handlers.get(r);o&&o.delete(n)}emit(r,n){let o=this.handlers.get(r);if(o)for(let l of o)try{let p=l(n);p instanceof Promise&&p.catch(h=>{console.error(`Async error in event handler for ${String(r)}:`,h)})}catch(p){console.error(`Error in event handler for ${String(r)}:`,p)}}removeAllListeners(r){r?this.handlers.delete(r):this.handlers.clear()}listenerCount(r){return this.handlers.get(r)?.size||0}eventNames(){return Array.from(this.handlers.keys()).filter(r=>this.handlers.get(r).size>0)}hasListeners(r){return this.listenerCount(r)>0}},A6e=null});import YH from"path";async function S6e(){return p_e||(p_e=new f_e,await p_e.load()),p_e}var f_e,p_e,k6e=Ut(()=>{"use strict";j_();K4e();sf();Dp();Q_();Xa();ju();Im();f_e=class{history={records:[],currentRecordId:null};loaded=!1;async load(){if(this.loaded)return;let r=this.getConsentFilePath();try{if(await ea(r)){let n=await _d(r);n&&(this.history=n,$.debug("Consent history loaded",{recordCount:this.history.records.length,currentRecordId:this.history.currentRecordId}))}}catch(n){$.warn("Failed to load consent history, starting fresh",n),this.history={records:[],currentRecordId:null}}this.loaded=!0}async getStatus(){this.loaded||await this.load();let r=this.getCurrentRecord();if(!r)return{isValid:!1,consent:null,grantedAt:null,expiresAt:null,daysUntilExpiry:null,needsRenewal:!0,version:null};let n=new Date,o=new Date(r.expiresAt),l=n>o,p=1e3*60*60*24,h=l?0:Math.ceil((o.getTime()-n.getTime())/p),I=r.version!==$4e,k=l||I;return{isValid:!l&&!I,consent:r.consent,grantedAt:r.grantedAt,expiresAt:r.expiresAt,daysUntilExpiry:h,needsRenewal:k,version:r.version}}async grantConsent(r){if(this.loaded||await this.load(),!r.dataCollection)throw new Error("Data collection consent is required for Compass to function");let n=new Date,o=new Date(n);o.setDate(o.getDate()+IMe);let l={id:xa(),version:$4e,consent:{dataCollection:r.dataCollection,telemetry:r.telemetry,analytics:r.analytics,errorReporting:r.errorReporting},grantedAt:rn(n),expiresAt:rn(o)};return this.history.records.push(l),this.history.currentRecordId=l.id,await this.save(),aa().emit("consent-changed",{granted:!0}),$.info("Consent granted",{recordId:l.id,version:l.version,expiresAt:l.expiresAt}),l}async revokeConsent(){this.loaded||await this.load(),this.history.currentRecordId=null,await this.save(),await this.cleanupUserData(),aa().emit("consent-changed",{granted:!1}),$.info("Consent revoked and user data cleaned up")}async updateConsent(r){this.loaded||await this.load();let n=this.getCurrentRecord();if(!n)return $.warn("Cannot update consent: no current consent record"),null;let o={...n.consent,...r};return await this.grantConsent(o)}getHistory(){return[...this.history.records]}async exportUserData(){this.loaded||await this.load();let r=oc(),n={exportedAt:rn(),exportVersion:"1.0",consentHistory:{records:this.history.records,currentRecordId:this.history.currentRecordId}},o=[{name:"config",file:"config.json"},{name:"tokenUsage",file:"token-usage.json"},{name:"commandHistory",file:"command-history.json"}];for(let{name:p,file:h}of o){let I=YH.join(r,h);if(await ea(I))try{let k=await _d(I);k&&(n[p]=k)}catch(k){$.debug(`Failed to export ${h}`,k)}}let l=YH.join(r,"saved-sessions");if(await ea(l))try{let p=await MH(l),h={};for(let I of p)if(I.endsWith(".json")){let k=YH.join(l,I),N=await _d(k);N&&(h[I.replace(".json","")]=N)}Object.keys(h).length>0&&(n.savedSessions=h)}catch(p){$.debug("Failed to export saved sessions",p)}return $.info("User data exported",{sections:Object.keys(n).length}),n}async isDataCollectionAllowed(){let r=await this.getStatus();return r.isValid&&r.consent?.dataCollection===!0}async isTelemetryAllowed(){let r=await this.getStatus();return r.isValid&&r.consent?.telemetry===!0}async isAnalyticsAllowed(){let r=await this.getStatus();return r.isValid&&r.consent?.analytics===!0}async isErrorReportingAllowed(){let r=await this.getStatus();return r.isValid&&r.consent?.errorReporting===!0}async hasValidConsent(){return(await this.getStatus()).isValid}getCurrentRecord(){return this.history.currentRecordId&&this.history.records.find(r=>r.id===this.history.currentRecordId)||null}getConsentFilePath(){return YH.join(oc(),aMe)}async save(){let r=this.getConsentFilePath();await Zl(YH.dirname(r)),await X_(r,this.history),$.debug("Consent history saved")}async cleanupUserData(){let r=oc(),n=["session.json","token-usage.json","command-history.json","cache","saved-sessions","logs","context","index"];for(let o of n){let l=YH.join(r,o);if(await ea(l))try{await G0(l),$.debug(`Removed: ${o}`)}catch(p){$.warn(`Failed to remove ${o}`,p)}}$.info("User data cleanup completed")}async reload(){this.loaded=!1,await this.load()}reset(){this.history={records:[],currentRecordId:null},this.loaded=!1}},p_e=null});import r1 from"crypto";function LAt(i,r){return r1.pbkdf2Sync(i,r,UCr,LCr,T6e)}function C6e(i,r){let n=r1.randomBytes(I5),o=r1.randomBytes(OH),l=LAt(r,n),p=r1.createCipheriv(JAt,l,o),h=p.update(i,"utf8","hex");h+=p.final("hex");let I=p.getAuthTag();return Buffer.concat([n,o,I,Buffer.from(h,"hex")]).toString("base64")}function G6e(i,r){let n=Buffer.from(i,"base64"),o=I5+OH+E6e+1;if(n.length<o)throw new Error("Invalid encrypted data: too short");let l=n.subarray(0,I5),p=n.subarray(I5,I5+OH),h=n.subarray(I5+OH,I5+OH+E6e),I=n.subarray(I5+OH+E6e),k=LAt(r,l),N=r1.createDecipheriv(JAt,k,p);N.setAuthTag(h);let W=N.update(I.toString("hex"),"hex","utf8");return W+=N.final("utf8"),W}function XCr(i=32){return r1.randomBytes(i).toString("hex")}function N6e(i){return r1.createHash(T6e).update(i).digest("hex")}function QCr(i,r){return r1.createHmac(T6e,r).update(i).digest("hex")}function jCr(i,r){return i.length!==r.length?(r1.timingSafeEqual(Buffer.from(i),Buffer.from(i)),!1):r1.timingSafeEqual(Buffer.from(i),Buffer.from(r))}function zCr(i){let r=r1.pbkdf2Sync(i,BCr,1e5,32,"sha256");return Buffer.from(r.toString("base64url"),"utf-8")}function UAt(i,r){try{let n=zCr(r),o=Buffer.from(n.toString("utf-8"),"base64url"),p=Buffer.from(i,"base64url").toString("utf-8"),h=Buffer.from(p,"base64url");if(h.length<57)throw new Error(`Invalid Fernet token: too short (${h.length} bytes, need at least 57)`);let I=h[0];if(I!==128)throw new Error(`Invalid Fernet version: 0x${I.toString(16)} (expected 0x80)`);let k=h.subarray(9,25),N=h.subarray(25,h.length-32),W=h.subarray(h.length-32),H=o.subarray(0,16),M=o.subarray(16,32),q=h.subarray(0,h.length-32),ne=r1.createHmac("sha256",H).update(q).digest();if(!r1.timingSafeEqual(W,ne))throw new Error("Invalid Fernet token: HMAC verification failed");let de=r1.createDecipheriv("aes-128-cbc",M,k);de.setAutoPadding(!0);let Qe=de.update(N);return Qe=Buffer.concat([Qe,de.final()]),Qe.toString("utf-8")}catch(n){throw n instanceof Error?new Error(`Failed to decrypt Fernet token: ${n.message}`):new Error("Failed to decrypt Fernet token: Unknown error")}}var JAt,OH,I5,E6e,LCr,UCr,T6e,BCr,o$=Ut(()=>{"use strict";JAt="aes-256-gcm",OH=16,I5=32,E6e=16,LCr=32,UCr=1e5,T6e="sha256";BCr=Buffer.from("b-f2T&>)XPx2vI/I9N7CfYH@Dvdb<F","utf-8")});import c$ from"path";import ZD from"os";import qCr from"crypto";async function J2(){if(XAt)return F6e;XAt=!0;try{let i=await import("keytar");return F6e=i.default||i,F6e}catch(i){return $.debug("Failed to load keytar native module:",i),null}}async function Rg(){return h_e||(h_e=new g_e,await h_e.initialize()),h_e}var F6e,XAt,QAt,YI,HH,m_e,__e,jAt,R6e,g_e,h_e,VD=Ut(()=>{"use strict";o$();Dp();sf();Xa();ju();F6e=null,XAt=!1,QAt="keytar-available.json";YI="compass-cli",HH="anthropic-api-key",m_e="compass-api-key",__e={anthropic:"anthropic-api-key",ollama:"ollama-api-key",zai:"zai-api-key",minimax:"minimax-api-key"},jAt="1.0",R6e={anthropic:"anthropicApiKey",ollama:"ollamaApiKey",zai:"zaiApiKey",minimax:"minimaxApiKey"},g_e=class{useKeytar=!0;machineKey=null;initialized=!1;async initialize(){if(this.initialized)return;let r=`${ZD.platform()}-${ZD.arch()}`;try{let n=c$.join(oc(),QAt);if(await ea(n)){let o=await ed(n);if(o){let l=JSON.parse(o);if(l.platform===r)if(l.available){if(await J2()){this.useKeytar=!0,this.initialized=!0,$.debug("Using system keychain (cached probe)");return}}else{this.useKeytar=!1,this.machineKey=await this.getMachineKey(),this.initialized=!0,$.debug("Using encrypted file storage (cached probe)");return}}}}catch{}try{let n=await J2();if(!n)throw new Error("Keytar module not available");let o=`${YI}-test`,l="availability-test";await n.setPassword(o,l,"test"),await n.deletePassword(o,l),this.useKeytar=!0,$.debug("Using system keychain for credential storage")}catch(n){this.useKeytar=!1,$.debug("System keychain unavailable, using encrypted file storage",n),this.machineKey=await this.getMachineKey()}this.initialized=!0,this.saveKeytarCache(r).catch(n=>{$.debug("Failed to cache keytar probe result",n)})}async saveKeytarCache(r){let n=oc();await Zl(n);let o=c$.join(n,QAt),l={available:this.useKeytar,platform:r,checkedAt:new Date().toISOString()};await C0(o,JSON.stringify(l))}async setApiKey(r){if(await this.ensureInitialized(),!r||typeof r!="string")throw new Error("API key must be a non-empty string");let n=r.trim();if(this.useKeytar)try{let o=await J2();if(o){await o.setPassword(YI,HH,n),$.debug("API key stored in system keychain");return}}catch(o){$.warn("Failed to store in keychain, falling back to file storage",o)}await this.saveToFile({anthropicApiKey:n}),$.debug("API key stored in encrypted file")}async getApiKey(){await this.ensureInitialized();let r=process.env[kb.API_KEY];if(r&&r.trim())return $.debug("API key loaded from environment variable"),r.trim();if(this.useKeytar)try{let o=await J2();if(o){let l=await o.getPassword(YI,HH);if(l)return $.debug("API key loaded from system keychain"),l}}catch(o){$.debug("Failed to read from keychain",o)}let n=await this.loadFromFile();return n?.anthropicApiKey?($.debug("API key loaded from encrypted file"),n.anthropicApiKey):null}async deleteApiKey(){await this.ensureInitialized();let r=!0;if(this.useKeytar)try{let o=await J2();o&&await o.deletePassword(YI,HH)&&$.debug("API key deleted from system keychain")}catch(o){$.debug("Failed to delete from keychain",o),r=!1}return await this.deleteFile()||(r=!1),r&&$.debug("API key deleted successfully"),r}async hasApiKey(){let r=await this.getApiKey();return r!==null&&r.length>0}async setCompassApiKey(r){if(await this.ensureInitialized(),!r||typeof r!="string")throw new Error("API key must be a non-empty string");let n=r.trim();if(this.useKeytar)try{let l=await J2();if(l){await l.setPassword(YI,m_e,n),$.debug("Compass API key stored in system keychain");return}}catch(l){$.warn("Failed to store in keychain, falling back to file storage",l)}let o=await this.loadFromFile()||{};await this.saveToFile({...o,compassApiKey:n}),$.debug("Compass API key stored in encrypted file")}async getCompassApiKey(){await this.ensureInitialized();let r=process.env[kb.COMPASS_API_KEY];if(r&&r.trim())return $.debug("Compass API key loaded from environment variable"),r.trim();if(this.useKeytar)try{let o=await J2();if(o){let l=await o.getPassword(YI,m_e);if(l)return $.debug("Compass API key loaded from system keychain"),l}}catch(o){$.debug("Failed to read from keychain",o)}let n=await this.loadFromFile();return n?.compassApiKey?($.debug("Compass API key loaded from encrypted file"),n.compassApiKey):null}async deleteCompassApiKey(){await this.ensureInitialized();let r=!0;if(this.useKeytar)try{let n=await J2();n&&await n.deletePassword(YI,m_e)&&$.debug("Compass API key deleted from system keychain")}catch(n){$.debug("Failed to delete from keychain",n),r=!1}try{let n=await this.loadFromFile();n?.compassApiKey&&(delete n.compassApiKey,await this.saveToFile(n),$.debug("Compass API key deleted from encrypted file"))}catch(n){$.error("Failed to delete Compass API key from file",n),r=!1}return r&&$.debug("Compass API key deleted successfully"),r}async hasCompassApiKey(){let r=await this.getCompassApiKey();return r!==null&&r.length>0}async setProviderApiKey(r,n){if(await this.ensureInitialized(),!n||typeof n!="string")throw new Error("API key must be a non-empty string");if(!wN.includes(r))throw new Error(`Invalid provider: ${r}. Must be one of: ${wN.join(", ")}`);let o=n.trim(),l=__e[r];if(this.useKeytar)try{let I=await J2();if(I){await I.setPassword(YI,l,o),$.debug(`${r} API key stored in system keychain`);return}}catch(I){$.warn("Failed to store in keychain, falling back to file storage",I)}let p=await this.loadFromFile()||{},h=R6e[r];await this.saveToFile({...p,[h]:o}),$.debug(`${r} API key stored in encrypted file`)}async getProviderApiKey(r){if(await this.ensureInitialized(),!wN.includes(r))return $.warn(`Invalid provider: ${r}`),null;let n=bme[r],o=process.env[n];if(o&&o.trim())return $.debug(`${r} API key loaded from environment variable ${n}`),o.trim();let l=__e[r];if(this.useKeytar)try{let I=await J2();if(I){let k=await I.getPassword(YI,l);if(k)return $.debug(`${r} API key loaded from system keychain`),k}}catch(I){$.debug(`Failed to read ${r} key from keychain`,I)}let p=await this.loadFromFile(),h=R6e[r];return p?.[h]?($.debug(`${r} API key loaded from encrypted file`),p[h]):null}async hasProviderApiKey(r){let n=await this.getProviderApiKey(r);return n!==null&&n.length>0}async deleteProviderApiKey(r){if(await this.ensureInitialized(),!wN.includes(r))return $.warn(`Invalid provider: ${r}`),!1;let n=!0,o=__e[r];if(this.useKeytar)try{let l=await J2();l&&await l.deletePassword(YI,o)&&$.debug(`${r} API key deleted from system keychain`)}catch(l){$.debug(`Failed to delete ${r} key from keychain`,l),n=!1}try{let l=await this.loadFromFile(),p=R6e[r];l?.[p]&&(delete l[p],await this.saveToFile(l),$.debug(`${r} API key deleted from encrypted file`))}catch(l){$.error(`Failed to delete ${r} API key from file`,l),n=!1}return n}async getConfiguredProviders(){let r=[];for(let n of wN)await this.hasProviderApiKey(n)&&r.push(n);return r}validateApiKeyFormat(r){if(!r||typeof r!="string")return!1;let n=r.trim();return!(n.length<20)}getStorageMethod(){return this.useKeytar?"keychain":"file"}isInitialized(){return this.initialized}async ensureInitialized(){this.initialized||await this.initialize()}async getMachineKey(){if(this.machineKey)return this.machineKey;let n=[ZD.hostname(),ZD.platform(),ZD.arch(),ZD.userInfo().username,ZD.homedir()].join(":"),o=qCr.createHash("sha256").update(n).digest("hex");return this.machineKey=o,o}async saveToFile(r){let n=await this.getMachineKey(),o=JSON.stringify(r),l=C6e(o,n),p={version:jAt,data:l,updatedAt:new Date().toISOString()},h=oc();await Zl(h);let I=c$.join(h,gq);await C0(I,JSON.stringify(p,null,2)),$.debug("Credentials saved to encrypted file")}async loadFromFile(){let r=c$.join(oc(),gq);if(!await ea(r))return null;try{let n=await ed(r);if(!n)return null;let o=JSON.parse(n);o.version!==jAt&&$.warn(`Credentials file version mismatch: ${o.version}`);let l=await this.getMachineKey(),p=G6e(o.data,l);return JSON.parse(p)}catch(n){return $.error("Failed to load credentials from file",n),null}}async deleteFile(){let r=c$.join(oc(),gq);try{return await ea(r)&&(await G0(r),$.debug("Credentials file deleted")),!0}catch(n){return $.error("Failed to delete credentials file",n),!1}}async migrateToKeychain(){if(!this.useKeytar)return $.debug("Keychain not available, migration skipped"),!1;try{let r=await J2();if(!r)return $.debug("Keytar not available, migration skipped"),!1;let n=await this.loadFromFile();return n?.anthropicApiKey?await r.getPassword(YI,HH)?($.debug("Keychain already has credentials, skipping migration"),!0):(await r.setPassword(YI,HH,n.anthropicApiKey),await this.deleteFile(),$.debug("Credentials migrated from file to system keychain"),!0):($.debug("No file-based credentials to migrate"),!0)}catch(r){return $.error("Failed to migrate credentials to keychain",r),!1}}async clearAll(){if(await this.ensureInitialized(),this.useKeytar)try{let r=await J2();if(r){await r.deletePassword(YI,HH),await r.deletePassword(YI,m_e);for(let n of wN)await r.deletePassword(YI,__e[n])}}catch(r){$.debug("Failed to clear keychain",r)}await this.deleteFile(),$.debug("All credentials cleared")}},h_e=null});import CN from"path";function l$(i){return new y_e(i)}var y_e,W6e=Ut(()=>{"use strict";j_();iMe();Dp();Xa();ju();y_e=class{projectPath;archiveDir;constructor(r){this.projectPath=r,this.archiveDir=a$(r)}async archiveSession(r){let n=r.state.conversationHistory;if(!n||n.length===0)return $.debug("No messages to archive, skipping"),{success:!1,error:"No messages to archive"};try{await h6e(this.projectPath);let o=this.buildArchive(r),l=this.generateFilename(o.summary),p=CN.join(this.archiveDir,l);return await X_(p,o),$.info(`Archived conversation to ${l}`),{success:!0,archiveId:o.id,filename:l,path:p}}catch(o){return $.error("Failed to archive session",o),{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async listArchives(){try{let r=await b5(this.projectPath),n=[];for(let o of r){let l=CN.join(this.archiveDir,o),p=await _d(l);p&&t5(p)&&n.push({id:p.id,filename:o,startedAt:p.startedAt,endedAt:p.endedAt,durationSeconds:p.durationSeconds,messageCount:p.messageCount,summary:p.summary,topics:p.topics,model:p.model,tokenUsage:p.tokenUsage})}return n.sort((o,l)=>new Date(l.endedAt).getTime()-new Date(o.endedAt).getTime())}catch(r){return $.error("Failed to list archives",r),[]}}async getArchive(r){try{let n=await b5(this.projectPath);for(let o of n)if(o===r||o.includes(r)){let l=CN.join(this.archiveDir,o),p=await _d(l);if(p&&t5(p))return p}if(r.endsWith(".json")){let o=CN.join(this.archiveDir,r);if(await ea(o)){let l=await _d(o);if(l&&t5(l))return l}}return null}catch(n){return $.error(`Failed to get archive: ${r}`,n),null}}async getLatestArchive(){try{let r=await b5(this.projectPath);if(r.length===0)return null;let n=r[r.length-1],o=CN.join(this.archiveDir,n),l=await _d(o);return l&&t5(l)?l:null}catch(r){return $.error("Failed to get latest archive",r),null}}async searchArchives(r){let n=r.toLowerCase(),o=[];try{let l=await b5(this.projectPath);for(let p of l){let h=CN.join(this.archiveDir,p),I=await _d(h);if(I&&t5(I)){let k=this.extractFilesModified(I.operations);(I.summary.toLowerCase().includes(n)||I.topics.some(W=>W.toLowerCase().includes(n))||k.some(W=>W.toLowerCase().includes(n))||I.messages.some(W=>W.content.toLowerCase().includes(n)))&&o.push({id:I.id,filename:p,startedAt:I.startedAt,endedAt:I.endedAt,durationSeconds:I.durationSeconds,messageCount:I.messageCount,summary:I.summary,topics:I.topics,model:I.model,tokenUsage:I.tokenUsage})}}return o.sort((p,h)=>new Date(h.endedAt).getTime()-new Date(p.endedAt).getTime())}catch(l){return $.error(`Failed to search archives for: ${r}`,l),[]}}async cleanupOldArchives(r=30,n=100){let o=0;try{let l=await b5(this.projectPath);if(l.length===0)return 0;let p=new Date;p.setDate(p.getDate()-r);for(let I of l){let k=CN.join(this.archiveDir,I),N=await _d(k);N&&t5(N)&&new Date(N.endedAt)<p&&(await G0(k),o++,$.debug(`Deleted old archive: ${I}`))}let h=await b5(this.projectPath);if(h.length>n){let I=h.slice(0,h.length-n);for(let k of I){let N=CN.join(this.archiveDir,k);await G0(N),o++,$.debug(`Deleted archive (over limit): ${k}`)}}return o>0&&$.info(`Cleaned up ${o} old archives`),o}catch(l){return $.error("Failed to cleanup old archives",l),o}}buildArchive(r){let n=r.state.conversationHistory,o=r.state.operations,l=n[0],p=n[n.length-1],h=l?.timestamp||r.createdAt,I=p?.timestamp||r.updatedAt,k=Math.round((new Date(I).getTime()-new Date(h).getTime())/1e3),N=this.countMessages(n),W=this.generateSummary(n),H=this.extractTopics(n,o),M=this.convertMessages(n);return{version:"1.0",id:xa(),sessionId:r.id,projectPath:r.projectPath,startedAt:h,endedAt:I,durationSeconds:k,messageCount:n.length,messageCounts:N,tokenUsage:{total:r.metadata.totalTokensUsed,estimatedCost:r.metadata.totalCost},model:r.state.currentModel,summary:W,topics:H,wasCompacted:r.metadata.isCompacted||!1,compactedSummary:r.state.compactedSummary,messages:M,operations:o}}countMessages(r){return r.reduce((n,o)=>(n[o.role]++,n),{user:0,assistant:0,system:0})}extractFilesModified(r){if(!r||r.length===0)return[];let n=new Set;for(let o of r)o.details.filePath&&(o.type==="file_create"||o.type==="file_modify"||o.type==="file_delete"||o.type==="file_rename")&&n.add(o.details.filePath),o.details.newFilePath&&n.add(o.details.newFilePath);return Array.from(n)}generateSummary(r){let n=r.find(l=>l.role==="user");if(!n)return"Empty conversation";let o=n.content.replace(/\n+/g," ").replace(/\s+/g," ").trim();if(o.length>100){o=o.substring(0,100);let l=o.lastIndexOf(" ");l>50&&(o=o.substring(0,l)),o+="..."}return o}extractTopics(r,n){let o=new Set;for(let h of n)if(h.details.filePath){let I=CN.extname(h.details.filePath).slice(1);I&&o.add(I);let k=h.details.filePath.split(/[/\\]/);for(let N of k.slice(0,-1))N&&N!=="."&&N!==".."&&!N.startsWith(".")&&o.add(N)}for(let h of n)h.type.includes("file")&&o.add("file-operations"),h.type.includes("git")&&o.add("git"),h.type.includes("shell")&&o.add("shell");let l=r.find(h=>h.role==="user")?.content.toLowerCase()||"",p=["bug","fix","feature","refactor","test","docs","style","perf","build","ci","deploy","debug","error","issue","implement","add","remove","update","change","create"];for(let h of p)l.includes(h)&&o.add(h);return Array.from(o).slice(0,10)}convertMessages(r){return r.map(n=>({role:n.role,content:n.content,timestamp:n.timestamp,tokenCount:n.tokenCount,model:n.model}))}generateFilename(r){let n=new Date,o=n.toISOString().slice(0,10),l=n.toTimeString().slice(0,8).replace(/:/g,"-"),p=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50);return`${o}_${l}_${p||"conversation"}.json`}}});import Hw from"path";function vm(){return Z6e||(Z6e=new b_e),Z6e}var b_e,Z6e,pT=Ut(()=>{"use strict";j_();_H();sf();Dp();Q_();wD();Xa();ju();Im();W6e();b_e=class{session=null;projectRoot=process.cwd();autoSaveTimer=null;dirty=!1;unguardedMode=!1;narrationEnabled=!1;pendingAttachments=[];archivalService=null;createSession(r){return this.projectRoot=r||process.cwd(),this.session={id:xa(),createdAt:rn(),updatedAt:rn(),projectPath:this.projectRoot,state:{conversationHistory:[],operations:[],currentModel:Pw,approvalMode:"manual",contextFiles:[],executionMode:"hybrid"},metadata:{totalTokensUsed:0,totalCost:0,messageCount:0,operationCount:0,lastActivity:rn(),tags:[]}},this.dirty=!0,$.debug(`Session created: ${this.session.id}`),this.session}getSession(){return this.session}getState(){return this.session?.state||null}getMetadata(){return this.session?.metadata||null}addMessage(r){this.session||this.createSession();let n={id:xa(),timestamp:rn(),...r};return this.session.state.conversationHistory.push(n),this.session.metadata.messageCount++,this.session.metadata.lastActivity=rn(),this.session.updatedAt=rn(),this.session.state.conversationHistory.length>xq&&(this.session.state.conversationHistory=this.session.state.conversationHistory.slice(-xq)),this.dirty=!0,$.debug(`Message added: ${n.role} (${n.id})`),n}getConversationHistory(){return this.session?.state.conversationHistory||[]}clearHistory(){if(this.session){let r=this.session.state.conversationHistory.length,n=this.session.state.operations.length;this.session.state.conversationHistory=[],this.session.state.operations=[],this.session.state.compactedSummary=void 0,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Conversation history cleared: ${r} messages, ${n} operations removed`)}}async archiveCurrentSession(){if(!this.session)return{success:!1,error:"No active session to archive"};if(!this.session.state.conversationHistory||this.session.state.conversationHistory.length===0)return $.debug("No messages to archive, skipping"),{success:!1,error:"No messages to archive"};this.archivalService||(this.archivalService=l$(this.projectRoot));try{let r=await this.archivalService.archiveSession(this.session);return r.success&&$.info(`Session archived to: ${r.filename}`),r}catch(r){return $.error("Failed to archive session",r),{success:!1,error:r instanceof Error?r.message:"Unknown error"}}}async archiveAndClearSession(){let r=null;this.archivalService||(this.archivalService=l$(this.projectRoot));let n=await this.archiveCurrentSession();return n.success&&n.path&&(r=await this.archivalService.getLatestArchive()),this.clearHistory(),this.archivalService.cleanupOldArchives().catch(o=>{$.warn("Failed to cleanup old archives",o)}),{archive:r,result:n}}getArchivalService(){return this.archivalService||(this.archivalService=l$(this.projectRoot)),this.archivalService}setCompactedSummary(r){this.session&&(this.session.state.compactedSummary=r,this.session.state.conversationHistory=[],this.session.updatedAt=rn(),this.dirty=!0,$.info("Compacted summary set, conversation history cleared"))}getCompactedSummary(){return this.session?.state.compactedSummary}syncAfterCompaction(r,n){this.session&&(this.session.state.compactedSummary=r,this.session.metadata.isCompacted=!0,this.session.metadata.compactionTimestamp=rn(),this.session.metadata.messagesPreserved=n,this.session.updatedAt=rn(),this.dirty=!0,$.info(`Session synced after compaction: summary stored, ${n} recent messages preserved`))}replaceConversationHistory(r){this.session&&(this.session.state.conversationHistory=r,this.session.metadata.messageCount=r.length,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Conversation history replaced: ${r.length} messages`))}updateEstimatedContextTokens(r){this.session&&(this.session.metadata.estimatedContextTokens=r,$.debug(`Session context tokens updated: ${r.toLocaleString()}`))}getEstimatedContextTokens(){return this.session?.metadata.estimatedContextTokens??0}recordOperation(r){this.session||this.createSession();let n={id:xa(),timestamp:rn(),...r};return this.session.state.operations.push(n),this.session.metadata.operationCount++,this.session.metadata.lastActivity=rn(),this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Operation recorded: ${n.type} (${n.id})`),n}getOperations(){return this.session?.state.operations||[]}getLastOperation(){let r=this.session?.state.operations||[];return r[r.length-1]}updateOperation(r,n){if(!this.session)return!1;let o=this.session.state.operations.find(l=>l.id===r);return o?(Object.assign(o,n),this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Operation updated: ${r}`),!0):!1}updateTokenUsage(r,n){this.session&&(this.session.metadata.totalTokensUsed+=r,this.session.metadata.totalCost+=n,this.session.metadata.lastActivity=rn(),this.session.updatedAt=rn(),this.dirty=!0)}setModel(r){this.session&&(this.session.state.currentModel=r,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Model set: ${r}`))}getCurrentModel(){return this.session?.state.currentModel||Pw}setApprovalMode(r){this.session&&(this.session.state.approvalMode=r,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Approval mode set: ${r}`))}getApprovalMode(){return this.session?.state.approvalMode||"manual"}setExecutionMode(r){this.session&&(this.session.state.executionMode=r,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Execution mode set: ${r}`))}getExecutionMode(){return this.session?.state.executionMode||"hybrid"}setShowToolBlocks(r){this.session&&(this.session.state.showToolBlocks=r,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Show tool blocks set: ${r}`))}getShowToolBlocks(){return this.session?.state.showToolBlocks??!0}addContextFile(r){this.session&&(this.session.state.contextFiles.includes(r)||(this.session.state.contextFiles.push(r),this.session.updatedAt=rn(),this.dirty=!0))}removeContextFile(r){if(this.session){let n=this.session.state.contextFiles.indexOf(r);n!==-1&&(this.session.state.contextFiles.splice(n,1),this.session.updatedAt=rn(),this.dirty=!0)}}getContextFiles(){return this.session?.state.contextFiles||[]}addExcludedFolder(r){this.session&&(this.session.state.excludedFolders||(this.session.state.excludedFolders=[]),this.session.state.excludedFolders.includes(r)||(this.session.state.excludedFolders.push(r),this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Excluded folder added: ${r}`)))}removeExcludedFolder(r){if(this.session&&this.session.state.excludedFolders){let n=this.session.state.excludedFolders.indexOf(r);n!==-1&&(this.session.state.excludedFolders.splice(n,1),this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Excluded folder removed: ${r}`))}}setExcludedFolders(r){this.session&&(this.session.state.excludedFolders=[...r],this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Excluded folders set: ${r.length} patterns`))}getExcludedFolders(){return this.session?.state.excludedFolders||[]}clearExcludedFolders(){this.session&&(this.session.state.excludedFolders=[],this.session.updatedAt=rn(),this.dirty=!0,$.debug("Excluded folders cleared"))}setPersonalityMode(r){this.session&&(this.session.state.personalityMode=r,this.session.updatedAt=rn(),this.dirty=!0,$.debug(`Personality mode set: ${r}`))}getPersonalityMode(){return this.session?.state.personalityMode||$v}setTemporaryPersonalityMode(r){this.session&&(this.session.state.temporaryPersonalityMode=r,this.session.updatedAt=rn(),$.debug(`Temporary personality mode set: ${r}`))}clearTemporaryPersonalityMode(){this.session&&this.session.state.temporaryPersonalityMode&&(this.session.state.temporaryPersonalityMode=void 0,this.session.updatedAt=rn(),$.debug("Temporary personality mode cleared"))}getEffectivePersonalityMode(){return this.session?.state.temporaryPersonalityMode?this.session.state.temporaryPersonalityMode:this.getPersonalityMode()}hasTemporaryPersonalityMode(){return this.session?.state.temporaryPersonalityMode!==void 0}setUnguardedMode(r){this.unguardedMode=r,$.debug(`Unguarded mode set: ${r} (transient - not persisted)`)}getUnguardedMode(){return this.unguardedMode}setNarrationEnabled(r){this.narrationEnabled=r,$.debug(`Narration mode set: ${r} (transient - not persisted)`)}getNarrationEnabled(){return this.narrationEnabled}addTag(r){this.session&&(this.session.metadata.tags.includes(r)||(this.session.metadata.tags.push(r),this.session.updatedAt=rn(),this.dirty=!0))}removeTag(r){if(this.session){let n=this.session.metadata.tags.indexOf(r);n!==-1&&(this.session.metadata.tags.splice(n,1),this.session.updatedAt=rn(),this.dirty=!0)}}async save(){if(!this.session){$.debug("No session to save");return}if(!this.dirty){$.debug("Session not dirty, skipping save");return}try{let r=ou(this.projectRoot);await Zl(r);let n=Hw.join(r,mme);await X_(n,this.session),this.dirty=!1,$.debug("Session saved"),aa().emit("session-saved",{sessionId:this.session.id})}catch(r){throw $.error("Failed to save session",r),r}}async load(r){this.projectRoot=r||process.cwd();let n=Hw.join(ou(this.projectRoot),mme);if(!await ea(n))return $.debug("No existing session found"),null;try{let o=await _d(n);if(o){this.session=this.migrateSession(o),this.dirty=!1,$.info(`Session loaded: ${this.session.id}`);let l=Hw.resolve(this.projectRoot);Hw.resolve(this.session.projectPath)!==l&&($.debug(`Updating session projectPath from ${this.session.projectPath} to ${l}`),this.session.projectPath=l,this.session.updatedAt=rn(),this.dirty=!0)}return this.session}catch(o){return $.error("Failed to load session",o),null}}migrateSession(r){let n=!1;if(!r.metadata)r.metadata={totalTokensUsed:0,totalCost:0,messageCount:0,operationCount:0,lastActivity:rn(),tags:[]},n=!0,$.debug("Session migrated: added missing metadata field");else{let o=r.metadata;typeof o.totalTokensUsed!="number"&&(o.totalTokensUsed=0,n=!0),typeof o.totalCost!="number"&&(o.totalCost=0,n=!0),typeof o.messageCount!="number"&&(o.messageCount=0,n=!0),typeof o.operationCount!="number"&&(o.operationCount=0,n=!0),o.lastActivity||(o.lastActivity=rn(),n=!0),Array.isArray(o.tags)||(o.tags=[],n=!0)}if(!r.state)r.state={conversationHistory:[],operations:[],currentModel:Pw,approvalMode:"manual",contextFiles:[],executionMode:"hybrid"},n=!0,$.debug("Session migrated: added missing state field");else{let o=r.state;Array.isArray(o.conversationHistory)||(o.conversationHistory=[],n=!0),Array.isArray(o.operations)||(o.operations=[],n=!0),o.currentModel||(o.currentModel=Pw,n=!0),o.approvalMode||(o.approvalMode="manual",n=!0),Array.isArray(o.contextFiles)||(o.contextFiles=[],n=!0)}return r.id||(r.id=xa(),n=!0),r.createdAt||(r.createdAt=rn(),n=!0),r.updatedAt||(r.updatedAt=rn(),n=!0),r.projectPath||(r.projectPath=this.projectRoot,n=!0),n&&(this.dirty=!0,$.info("Session structure migrated to current schema")),r}async saveAs(r,n){if(!this.session)throw new Error("No active session to save");let o=Hw.join(oc(),gH);await Zl(o);let l={session:this.session,savedAt:rn(),name:r,description:n},h=`${r.replace(/[^a-zA-Z0-9-_]/g,"_")}.json`,I=Hw.join(o,h);return await X_(I,l),$.info(`Session saved as: ${r}`),I}async listSavedSessions(){let r=Hw.join(oc(),gH);if(!await ea(r))return[];let n=await MH(r),o=[];for(let l of n)if(l.endsWith(".json")){let p=Hw.join(r,l);try{let h=await _d(p);h&&o.push(h)}catch(h){$.debug(`Failed to load saved session: ${l}`,h)}}return o.sort((l,p)=>new Date(p.savedAt).getTime()-new Date(l.savedAt).getTime())}async loadSaved(r){let n=Hw.join(oc(),gH),l=`${r.replace(/[^a-zA-Z0-9-_]/g,"_")}.json`,p=Hw.join(n,l);if(!await ea(p))return $.debug(`Saved session not found: ${r}`),null;try{let h=await _d(p);return h?(this.session=h.session,this.projectRoot=h.session.projectPath,this.dirty=!1,$.info(`Loaded saved session: ${r}`),this.session):null}catch(h){return $.error(`Failed to load saved session: ${r}`,h),null}}async deleteSavedSession(r){let n=Hw.join(oc(),gH),l=`${r.replace(/[^a-zA-Z0-9-_]/g,"_")}.json`,p=Hw.join(n,l);if(!await ea(p))return!1;try{let{remove:h}=await Promise.resolve().then(()=>(Dp(),g6e));return await h(p),$.info(`Deleted saved session: ${r}`),!0}catch(h){return $.error(`Failed to delete saved session: ${r}`,h),!1}}startAutoSave(r=hme){this.stopAutoSave(),this.autoSaveTimer=setInterval(()=>{this.dirty&&this.save().catch(n=>{$.error("Auto-save failed",n)})},r),$.debug(`Auto-save started with interval: ${r}ms`)}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null,$.debug("Auto-save stopped"))}isDirty(){return this.dirty}async forceSave(){this.dirty=!0,await this.save()}getProjectRoot(){return this.projectRoot}setProjectRoot(r){this.projectRoot=r,this.session&&(this.session.projectPath=r,this.dirty=!0)}exportSession(){return this.session?{...this.session}:null}importSession(r){this.session={...r},this.projectRoot=r.projectPath,this.dirty=!0,$.info(`Session imported: ${r.id}`)}getPendingAttachments(){return[...this.pendingAttachments]}addPendingAttachment(r){this.pendingAttachments.push(r),$.debug(`Pending attachment added: ${r.filename} (${r.type})`)}addPendingAttachments(r){this.pendingAttachments.push(...r),$.debug(`Added ${r.length} pending attachments`)}clearPendingAttachments(){let r=this.pendingAttachments.length;this.pendingAttachments=[],r>0&&$.debug(`Cleared ${r} pending attachments`)}consumePendingAttachments(){let r=[...this.pendingAttachments];return this.pendingAttachments=[],r.length>0&&$.debug(`Consumed ${r.length} pending attachments`),r}hasPendingAttachments(){return this.pendingAttachments.length>0}getPendingAttachmentsCount(){return this.pendingAttachments.length}},Z6e=null});import V6e from"path";import eGr from"os";function d$(){return{version:RMe,windowStart:Date.now(),providers:{}}}function P6e(i){return i.startsWith("claude-")?"anthropic":"ollama"}function u$(i){let r=Date.now()-i.windowStart;return r>=Cq||r<0?d$():i}function p$(i){let r=0;for(let n of Object.values(i.providers))for(let o of Object.values(n))r+=o;return r}function v_e(i,r){let n=P6e(r);return i.providers[n]?.[r]??0}function tGr(i){if(!Array.isArray(i.generalBucket)||typeof i.modelBuckets!="object"||i.modelBuckets===null)return null;let r=i,n=Date.now(),o=n-Cq,l=d$(),p=n;for(let[I,k]of Object.entries(r.modelBuckets)){if(!Array.isArray(k))continue;let N=P6e(I),W=0;for(let H of k)typeof H.tokens!="number"||typeof H.timestamp!="number"||H.timestamp<o||(W+=H.tokens,H.timestamp<p&&(p=H.timestamp));W>0&&(l.providers[N]||(l.providers[N]={}),l.providers[N][I]=W)}l.windowStart=p;let h=p$(l);return $.info(`[TokenLimitStore] Migrated v2 usage data (${h.toLocaleString()} tokens) to v1 flat format.`),l}function f$(){let i=V6e.join(eGr.homedir(),".compass");return new I_e(i)}var JH,I_e,x_e=Ut(()=>{"use strict";JH=Go(MI(),1);IH();Xa();I_e=class{filePath;queue=Promise.resolve();constructor(r){this.filePath=V6e.join(r,FMe)}async recordUsage(r,n){if(!(!Number.isFinite(n)||n<=0))return this.enqueue(async()=>{let o=await this.load();o=u$(o);let l=P6e(r);o.providers[l]||(o.providers[l]={}),o.providers[l][r]=(o.providers[l][r]??0)+n,await this.save(o)})}async loadState(){return this.enqueue(async()=>{let r=await this.load();return r=u$(r),await this.save(r),r})}async getModelUsage(r){return this.enqueue(async()=>{let n=await this.load();return n=u$(n),v_e(n,r)})}async getGeneralUsage(){return this.enqueue(async()=>{let r=await this.load();return r=u$(r),p$(r)})}enqueue(r){let n=this.queue.then(r);return this.queue=n.then(()=>{},()=>{}),n}async load(){try{if(!await JH.default.pathExists(this.filePath))return d$();let n=await JH.default.readFile(this.filePath,"utf8"),o=JSON.parse(n);if(Array.isArray(o.generalBucket)){let l=tGr(o);if(l)return await this.save(l),l}return typeof o.windowStart=="number"&&typeof o.providers=="object"&&o.providers!==null?{version:1,windowStart:o.windowStart,providers:o.providers}:($.warn(`[TokenLimitStore] Usage file at ${this.filePath} has unexpected shape \u2014 resetting.`),d$())}catch(r){return $.warn(`[TokenLimitStore] Failed to read usage file (${String(r)}) \u2014 starting fresh.`),d$()}}async save(r){try{await JH.default.ensureDir(V6e.dirname(this.filePath));let n=`${this.filePath}.${process.pid}.tmp`;await JH.default.writeFile(n,JSON.stringify(r,null,2),"utf8"),await JH.default.move(n,this.filePath,{overwrite:!0})}catch(n){$.warn(`[TokenLimitStore] Failed to save usage file: ${String(n)}`)}}}});import rGr from"path";async function Fb(){return m$||(m$=new A_e,m$.setLimitStore(f$()),await m$.initialize()),m$}var nGr,w_e,A_e,m$,_$=Ut(()=>{"use strict";j_();sf();Dp();Q_();Xa();O2();ju();IH();x_e();nGr="token-usage.json",w_e={version:"1.0",sessions:[],currentSessionId:null,lastUpdated:""},A_e=class{data;currentSession=null;warningThreshold;costWarningThreshold;initialized=!1;dirty=!1;tokenWarningEmitted=!1;costWarningEmitted=!1;constructor(){this.data={...w_e},this.warningThreshold=2e5,this.costWarningThreshold=10}async initialize(){this.initialized||(await this.load(),this.initialized=!0,$.debug("Token tracker initialized"))}startSession(r){let n=r||xa(),o=this.data.sessions.find(l=>l.sessionId===n);return o?(this.currentSession=o,this.data.currentSessionId=n,$.debug(`Resumed existing token tracking session: ${n}`),n):(this.tokenWarningEmitted=!1,this.costWarningEmitted=!1,this.currentSession={sessionId:n,startTime:rn(),calls:[],totals:this.createEmptyTokenUsage(),estimatedCost:this.createEmptyCostEstimate()},this.data.sessions.push(this.currentSession),this.data.currentSessionId=n,this.dirty=!0,$.debug(`Token tracking session started: ${n}`),n)}async recordUsage(r,n,o){this.currentSession||this.startSession();let l=this.calculateCost(n,r),p={id:xa(),timestamp:rn(),model:r,usage:{...n},cost:l,purpose:o};this.currentSession.calls.push(p),this.updateSessionTotals();let h=this.checkWarnings();for(let I of h)$.debug(I.message);this.dirty=!0,await this.save(),$.debug(`Recorded usage: ${n.inputTokens} in, ${n.outputTokens} out, ${l.totalCost.toFixed(4)} USD`)}getCurrentSessionUsage(){return this.currentSession}getSessionMetrics(){if(!this.currentSession||this.currentSession.calls.length===0)return null;let r=this.currentSession.calls,n=r.map(l=>l.usage.inputTokens),o=r.map(l=>l.usage.outputTokens);return{averageInputTokens:this.calculateAverage(n),averageOutputTokens:this.calculateAverage(o),peakInputTokens:Math.max(...n),peakOutputTokens:Math.max(...o),totalCalls:r.length,totalTokens:this.currentSession.totals.totalTokens,totalCost:this.currentSession.estimatedCost.totalCost}}getAllTimeStats(){let r=this.data.sessions.flatMap(h=>h.calls);if(r.length===0)return{averageInputTokens:0,averageOutputTokens:0,peakInputTokens:0,peakOutputTokens:0,totalCalls:0,totalTokens:0,totalCost:0};let n=r.map(h=>h.usage.inputTokens),o=r.map(h=>h.usage.outputTokens),l=this.data.sessions.reduce((h,I)=>h+I.totals.totalTokens,0),p=this.data.sessions.reduce((h,I)=>h+I.estimatedCost.totalCost,0);return{averageInputTokens:this.calculateAverage(n),averageOutputTokens:this.calculateAverage(o),peakInputTokens:Math.max(...n),peakOutputTokens:Math.max(...o),totalCalls:r.length,totalTokens:l,totalCost:p}}getStatsByPeriod(r,n=new Date){let o=r.getTime(),l=n.getTime(),p=this.data.sessions.flatMap(W=>W.calls.filter(H=>{let M=new Date(H.timestamp).getTime();return M>=o&&M<=l}));if(p.length===0)return{averageInputTokens:0,averageOutputTokens:0,peakInputTokens:0,peakOutputTokens:0,totalCalls:0,totalTokens:0,totalCost:0};let h=p.map(W=>W.usage.inputTokens),I=p.map(W=>W.usage.outputTokens),k=p.reduce((W,H)=>W+H.usage.totalTokens,0),N=p.reduce((W,H)=>W+H.cost.totalCost,0);return{averageInputTokens:this.calculateAverage(h),averageOutputTokens:this.calculateAverage(I),peakInputTokens:Math.max(...h),peakOutputTokens:Math.max(...I),totalCalls:p.length,totalTokens:k,totalCost:N}}getStatsByModel(){let r=new Map;for(let o of this.data.sessions)for(let l of o.calls){let p=r.get(l.model)||[];p.push(l),r.set(l.model,p)}let n=new Map;for(let[o,l]of r){if(l.length===0)continue;let p=l.map(N=>N.usage.inputTokens),h=l.map(N=>N.usage.outputTokens),I=l.reduce((N,W)=>N+W.usage.totalTokens,0),k=l.reduce((N,W)=>N+W.cost.totalCost,0);n.set(o,{averageInputTokens:this.calculateAverage(p),averageOutputTokens:this.calculateAverage(h),peakInputTokens:Math.max(...p),peakOutputTokens:Math.max(...h),totalCalls:l.length,totalTokens:I,totalCost:k})}return n}async endSession(){this.currentSession&&(this.currentSession.endTime=rn(),this.dirty=!0,await this.save(),$.debug(`Token tracking session ended: ${this.currentSession.sessionId}`),this.currentSession=null,this.data.currentSessionId=null)}async exportUsage(){return{...this.data,lastUpdated:rn()}}getSessionById(r){return this.data.sessions.find(n=>n.sessionId===r)||null}getSessions(r,n){let o=[...this.data.sessions];if(r){let l=r.getTime();o=o.filter(p=>new Date(p.startTime).getTime()>=l)}if(n){let l=n.getTime();o=o.filter(p=>new Date(p.startTime).getTime()<=l)}return o}setWarningThreshold(r){this.warningThreshold=r,this.tokenWarningEmitted=!1,$.debug(`Token warning threshold set to ${r}`)}getWarningThreshold(){return this.warningThreshold}setCostWarningThreshold(r){this.costWarningThreshold=r,this.costWarningEmitted=!1,$.debug(`Cost warning threshold set to $${r}`)}getCostWarningThreshold(){return this.costWarningThreshold}checkWarnings(){let r=[];if(!this.currentSession)return r;let n=this.currentSession.totals.totalTokens,o=this.currentSession.estimatedCost.totalCost;return n>=this.warningThreshold&&!this.tokenWarningEmitted?(this.tokenWarningEmitted=!0,r.push({type:"exceeded_threshold",message:`Token usage (${n.toLocaleString()}) has exceeded the warning threshold (${this.warningThreshold.toLocaleString()})`,currentValue:n,threshold:this.warningThreshold,severity:"warning"})):n>=this.warningThreshold*.8&&!this.tokenWarningEmitted&&r.push({type:"approaching_limit",message:`Token usage (${n.toLocaleString()}) is approaching the warning threshold (${this.warningThreshold.toLocaleString()})`,currentValue:n,threshold:this.warningThreshold,severity:"info"}),o>=this.costWarningThreshold&&!this.costWarningEmitted?(this.costWarningEmitted=!0,r.push({type:"high_cost",message:`Session cost ($${o.toFixed(2)}) has exceeded the warning threshold ($${this.costWarningThreshold.toFixed(2)})`,currentValue:o,threshold:this.costWarningThreshold,severity:"warning"})):o>=this.costWarningThreshold*.8&&!this.costWarningEmitted&&r.push({type:"high_cost",message:`Session cost ($${o.toFixed(2)}) is approaching the warning threshold ($${this.costWarningThreshold.toFixed(2)})`,currentValue:o,threshold:this.costWarningThreshold,severity:"info"}),r}_limitStore=null;setLimitStore(r){this._limitStore=r}getLimitStore(){if(!this._limitStore)throw new Error("[TokenTracker] TokenLimitStore not set \u2014 call setLimitStore() first.");return this._limitStore}resolveLimit(r,n,o){let l=ZMe(n,o),p=l.perModelLimits[r]??l.defaultPerModelLimit;return{generalLimit:l.generalLimit,modelLimit:p}}async checkLimit(r,n,o){let p=await this.getLimitStore().loadState(),{generalLimit:h,modelLimit:I}=this.resolveLimit(r,n,o),k=p$(p),N=v_e(p,r),W=Math.max(0,h-k),H=Math.max(0,I-N);return N>=I?{allowed:!1,generalRemaining:W,modelRemaining:0,reason:`Token limit exceeded for model "${r}". Used ${N.toLocaleString()} / ${I.toLocaleString()} tokens in the last ${Gq}h.`}:k>=h?{allowed:!1,generalRemaining:0,modelRemaining:H,reason:`Aggregate token limit exceeded. Used ${k.toLocaleString()} / ${h.toLocaleString()} tokens in the last ${Gq}h.`}:{allowed:!0,generalRemaining:W,modelRemaining:H}}async recordLimitUsage(r,n){try{await this.getLimitStore().recordUsage(r,n)}catch(o){$.warn(`[TokenTracker] Failed to record limit usage for ${r}: ${String(o)}`)}}async getUsageForModel(r){return this.getLimitStore().getModelUsage(r)}async getRemainingTokens(r,n,o){let{modelLimit:l}=this.resolveLimit(r,n,o),p=await this.getUsageForModel(r);return Math.max(0,l-p)}async clearAllData(){this.data={...w_e},this.currentSession=null,this.dirty=!0,await this.save(),$.info("All token usage data cleared")}async clearOldData(r){let n=new Date;n.setDate(n.getDate()-r);let o=n.getTime(),l=this.data.sessions.length;this.data.sessions=this.data.sessions.filter(h=>new Date(h.startTime).getTime()>=o);let p=l-this.data.sessions.length;return p>0&&(this.dirty=!0,await this.save(),$.info(`Cleared ${p} sessions older than ${r} days`)),p}calculateCost(r,n){let o=Gm(n);if(!o)return $.debug(`Unknown model for cost calculation: ${n}`),this.createEmptyCostEstimate();let l=r.inputTokens/1e6*o.pricing.inputPricePerMillion,p=r.outputTokens/1e6*o.pricing.outputPricePerMillion;return{inputCost:l,outputCost:p,totalCost:l+p,currency:"USD"}}updateSessionTotals(){if(!this.currentSession)return;let r=this.createEmptyTokenUsage(),n=this.createEmptyCostEstimate();for(let o of this.currentSession.calls)r.inputTokens+=o.usage.inputTokens,r.outputTokens+=o.usage.outputTokens,r.totalTokens+=o.usage.totalTokens,o.usage.cacheCreationInputTokens&&(r.cacheCreationInputTokens=(r.cacheCreationInputTokens||0)+o.usage.cacheCreationInputTokens),o.usage.cacheReadInputTokens&&(r.cacheReadInputTokens=(r.cacheReadInputTokens||0)+o.usage.cacheReadInputTokens),n.inputCost+=o.cost.inputCost,n.outputCost+=o.cost.outputCost,n.totalCost+=o.cost.totalCost;this.currentSession.totals=r,this.currentSession.estimatedCost=n}calculateAverage(r){if(r.length===0)return 0;let n=r.reduce((o,l)=>o+l,0);return Math.round(n/r.length)}createEmptyTokenUsage(){return{inputTokens:0,outputTokens:0,totalTokens:0}}createEmptyCostEstimate(){return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"}}getFilePath(){return rGr.join(oc(),nGr)}async load(){try{await Zl(oc());let r=this.getFilePath(),n=await _d(r);n&&(this.data={...w_e,...n},n.currentSessionId&&(this.currentSession=n.sessions.find(o=>o.sessionId===n.currentSessionId)||null),$.debug(`Loaded token usage data: ${this.data.sessions.length} sessions`))}catch(r){$.debug("Failed to load token usage data, starting fresh",r),this.data={...w_e}}}async save(){if(this.dirty)try{await Zl(oc());let r=this.getFilePath();this.data.lastUpdated=rn(),await X_(r,this.data),this.dirty=!1,$.debug("Token usage data saved")}catch(r){$.error("Failed to save token usage data",r)}}async forceSave(){this.dirty=!0,await this.save()}},m$=null});function xh(){return M6e||(M6e=new S_e),M6e}var sGr,aGr,S_e,M6e,GN=Ut(()=>{"use strict";j_();_H();Xa();Q_();sf();Im();t1();sGr=5,aGr=100,S_e=class{mode="manual";history={requests:[],responses:[]};autoApprovePatterns=[];requireApprovalPatterns=[];maxAutoApproveFiles=sGr;maxAutoApproveLines=aGr;eventEmitter;pendingRequest=null;resolveApproval=null;currentComplexityMode=null;currentComplexityConfidence=0;smartModeConfidenceThreshold=70;sessionAutoApprovalEnabled=!1;fileEditsAutoApprovalEnabled=!1;pendingPlanApproval=null;resolvePlanApprovalPromise=null;approvedCommandPrefixes=new Set;pendingClarificationWizard=null;resolveClarificationWizardPromise=null;constructor(){this.eventEmitter=aa()}getMode(){return this.mode}enableSessionAutoApproval(){this.sessionAutoApprovalEnabled=!0,$.info("Session auto-approval enabled - all subsequent operations will be auto-approved")}disableSessionAutoApproval(){this.sessionAutoApprovalEnabled=!1,$.info("Session auto-approval disabled")}isSessionAutoApprovalEnabled(){return this.sessionAutoApprovalEnabled}enableFileEditsAutoApproval(){this.fileEditsAutoApprovalEnabled=!0,$.info("File edits auto-approval enabled - file writes, edits, and commands will be auto-approved")}disableFileEditsAutoApproval(){this.fileEditsAutoApprovalEnabled=!1,$.info("File edits auto-approval disabled")}getCommandPrefix(r){let o=r.trim().split(/\s+/),l=["sudo","env","npx","pnpm","yarn","bunx"];for(let p of o)if(!l.includes(p.toLowerCase()))return p.toLowerCase();return o[0]?.toLowerCase()||""}isCommandPrefixApproved(r){let n=this.getCommandPrefix(r);return this.approvedCommandPrefixes.has(n)}approveCommandPrefix(r){let n=this.getCommandPrefix(r);this.approvedCommandPrefixes.add(n),$.info(`Command prefix approved for session: ${n}`)}getApprovedCommandPrefixes(){return Array.from(this.approvedCommandPrefixes)}clearApprovedCommandPrefixes(){this.approvedCommandPrefixes.clear(),$.debug("Approved command prefixes cleared")}setComplexityContext(r,n=0){this.currentComplexityMode=r,this.currentComplexityConfidence=n,$.debug(`Complexity context set: mode=${r}, confidence=${n}`)}getComplexityContext(){return{mode:this.currentComplexityMode,confidence:this.currentComplexityConfidence}}clearComplexityContext(){this.currentComplexityMode=null,this.currentComplexityConfidence=0,$.debug("Complexity context cleared")}setSmartModeConfidenceThreshold(r){this.smartModeConfidenceThreshold=Math.max(0,Math.min(100,r)),$.debug(`SMART mode confidence threshold set to: ${this.smartModeConfidenceThreshold}`)}quickClassifyRequest(r){let n=r.toLowerCase(),o=["refactor","redesign","migrate","architecture","rewrite","restructure","overhaul","major","breaking change","system","framework","infrastructure","database schema","api redesign","authentication system","authorization","security overhaul"],l=["implement","feature","add functionality","integrate","connect","setup","configure","multi-file","across files","multiple components","service","module","api endpoint"],p=["create","simple","basic","hello world","example","add file","new file","write","make","generate","readme","config","single","quick","small","fix typo","update text","change string","rename"];if(o.some(q=>n.includes(q)))return $.debug("Quick classify: PLAN (complex keyword found)"),{mode:"plan",confidence:80};let I=l.some(q=>n.includes(q)),k=/multiple|several|all|many|across/i.test(n);if(I||k)return $.debug("Quick classify: CLARIFICATION (medium keyword found)"),{mode:"clarification",confidence:70};let N=p.some(q=>n.includes(q)),W=n.length<100,H=/\b(a|one|single|the)\s+(file|page|document)\b/i.test(n),M=/^(create|make|write|add|generate)\b/i.test(n.trim());if(N||W&&(H||M)){let q=N?85:75;return $.debug(`Quick classify: DIRECT (simple indicators, confidence: ${q})`),{mode:"direct",confidence:q}}return $.debug("Quick classify: CLARIFICATION (default for ambiguous request)"),{mode:"clarification",confidence:60}}classifyAndSetContext(r){let{mode:n,confidence:o}=this.quickClassifyRequest(r);this.setComplexityContext(n,o),$.info(`Request classified: mode=${n}, confidence=${o}%`)}setMode(r){let n=this.mode;this.mode=r,$.info(`Approval mode changed from ${n} to ${r}`)}toggleMode(){return this.mode==="manual"?this.mode="auto":this.mode="manual",$.info(`Approval mode toggled to: ${this.mode}`),this.mode}configure(r){r.autoApprovePatterns!==void 0&&(this.autoApprovePatterns=r.autoApprovePatterns),r.requireApprovalPatterns!==void 0&&(this.requireApprovalPatterns=r.requireApprovalPatterns),r.maxAutoApproveFiles!==void 0&&(this.maxAutoApproveFiles=r.maxAutoApproveFiles),r.maxAutoApproveLines!==void 0&&(this.maxAutoApproveLines=r.maxAutoApproveLines),$.debug("Approval manager configured",r)}getConfig(){return{mode:this.mode,autoApprovePatterns:[...this.autoApprovePatterns],requireApprovalPatterns:[...this.requireApprovalPatterns],maxAutoApproveFiles:this.maxAutoApproveFiles,maxAutoApproveLines:this.maxAutoApproveLines}}async requestApproval(r,n,o){let l={id:xa(),type:r,timestamp:rn(),description:n,details:o,riskLevel:this.assessRiskLevel(r,o),estimatedImpact:this.estimateImpact(r,o)};this.history.requests.push(l),this.pendingRequest=l,$.debug(`Approval requested: ${l.id}`,{type:r,riskLevel:l.riskLevel});let p=zo();if(p.logApprovalRequested({approvalId:l.id,actionType:r,actionDescription:n,reason:`Risk level: ${l.riskLevel}`}),this.canAutoApprove(l)){let I=this.createResponse(l,!0,"Auto-approved based on configuration");return this.history.responses.push(I),this.pendingRequest=null,$.info(`Request ${l.id} auto-approved`),p.logApprovalGranted({approvalId:l.id,actionType:r,actionDescription:n,decidedBy:"system",reason:"Auto-approved based on configuration"}),I}if(this.mode==="strict")return this.waitForUserApproval(l);if(this.mode==="manual")return this.waitForUserApproval(l);if(this.shouldRequireApproval(l))return this.waitForUserApproval(l);let h=this.createResponse(l,!0,"Auto-approved (auto mode)");return this.history.responses.push(h),this.pendingRequest=null,$.info(`Request ${l.id} auto-approved in auto mode`),p.logApprovalGranted({approvalId:l.id,actionType:r,actionDescription:n,decidedBy:"system",reason:"Auto-approved (auto mode)"}),h}resolveRequest(r,n){if(!this.pendingRequest||!this.resolveApproval){$.warn("No pending approval request to resolve");return}let o=r==="approve",l=this.createResponse(this.pendingRequest,o,n);this.history.responses.push(l),$.info(`Request ${this.pendingRequest.id} ${o?"approved":"rejected"}`,{choice:r,reason:n});let p=zo(),h={approvalId:this.pendingRequest.id,actionType:this.pendingRequest.type,actionDescription:this.pendingRequest.description,decidedBy:"user",reason:n};o?p.logApprovalGranted(h):p.logApprovalDenied(h),this.resolveApproval(l),this.pendingRequest=null,this.resolveApproval=null}getPendingRequest(){return this.pendingRequest}hasPendingRequest(){return this.pendingRequest!==null}cancelPendingRequest(){if(this.pendingRequest&&this.resolveApproval){let r=this.createResponse(this.pendingRequest,!1,"Cancelled by user");this.history.responses.push(r),zo().logApprovalDenied({approvalId:this.pendingRequest.id,actionType:this.pendingRequest.type,actionDescription:this.pendingRequest.description,decidedBy:"user",reason:"Cancelled by user"}),this.resolveApproval(r)}this.pendingRequest=null,this.resolveApproval=null}getHistory(){return{requests:[...this.history.requests],responses:[...this.history.responses]}}getStatistics(){let r=this.history.responses.filter(o=>o.approved).length,n=this.history.responses.filter(o=>o.approved&&o.reason?.includes("Auto-approved")).length;return{totalRequests:this.history.requests.length,approved:r,rejected:this.history.responses.filter(o=>!o.approved).length,autoApproved:n}}clearHistory(){this.history={requests:[],responses:[]},$.debug("Approval history cleared")}async requestPlanApproval(r,n,o,l){let p={id:xa(),timestamp:rn(),plan:r,context:n,complexity:o,completedTaskIds:l};return this.pendingPlanApproval=p,$.info("Plan approval requested",{planId:r.id,taskCount:r.tasks.length,totalComplexity:r.totalComplexity}),zo().logPlanApprovalRequested(r.id),this.eventEmitter.emit("plan-approval-required",{request:p}),new Promise(I=>{this.resolvePlanApprovalPromise=I})}resolvePlanApproval(r,n,o){if(!this.pendingPlanApproval||!this.resolvePlanApprovalPromise){$.warn("No pending plan approval request to resolve");return}let l={requestId:this.pendingPlanApproval.id,approved:r==="approve"||r==="approve-compact"||r==="approve-auto-edits",timestamp:rn(),choice:r,modifications:n,clarifications:o};$.info("Plan approval resolved",{planId:this.pendingPlanApproval.plan.id,choice:r,approved:l.approved}),zo().logPlanApprovalResolved(this.pendingPlanApproval.plan.id,r),this.eventEmitter.emit("plan-approval-resolved",{requestId:this.pendingPlanApproval.id,choice:r,modifications:n,clarifications:o}),this.resolvePlanApprovalPromise(l),this.pendingPlanApproval=null,this.resolvePlanApprovalPromise=null}getPendingPlanApproval(){return this.pendingPlanApproval}hasPendingPlanApproval(){return this.pendingPlanApproval!==null}cancelPendingPlanApproval(){if(this.pendingPlanApproval&&this.resolvePlanApprovalPromise){let r={requestId:this.pendingPlanApproval.id,approved:!1,timestamp:rn(),choice:"reject"};$.info("Plan approval cancelled",{planId:this.pendingPlanApproval.plan.id}),zo().logPlanApprovalResolved(this.pendingPlanApproval.plan.id,"reject"),this.resolvePlanApprovalPromise(r)}this.pendingPlanApproval=null,this.resolvePlanApprovalPromise=null}async requestClarification(r,n,o){let l={id:xa(),timestamp:rn(),taskSummary:r,questions:n,reasoning:o};return this.pendingClarificationWizard=l,$.info("Clarification wizard requested",{requestId:l.id,questionCount:n.length}),this.eventEmitter.emit("clarification-required",{request:l}),new Promise(p=>{this.resolveClarificationWizardPromise=p})}resolveClarificationWizard(r){if(!this.pendingClarificationWizard||!this.resolveClarificationWizardPromise){$.warn("No pending clarification wizard request to resolve");return}let n=r!==null,o=this.pendingClarificationWizard,l;if(n&&r){let h=o.questions.map((k,N)=>({question:k,answer:r[N]||{questionId:k.id,answer:"",answeredAt:rn()}})),I=r.map((k,N)=>{let W=o.questions[N],H=Array.isArray(k.answer)?k.answer.join(", "):k.answer;return`${W.category}: ${H}`});l={qaRecords:h,completedAt:rn(),duration:0,decisionSummary:I.join("; ")}}let p={requestId:o.id,completed:n,timestamp:rn(),answers:r||void 0,result:l};$.info("Clarification wizard resolved",{requestId:o.id,completed:n,answerCount:r?.length||0}),this.resolveClarificationWizardPromise(p),this.pendingClarificationWizard=null,this.resolveClarificationWizardPromise=null}getPendingClarificationWizard(){return this.pendingClarificationWizard}hasPendingClarificationWizard(){return this.pendingClarificationWizard!==null}cancelPendingClarificationWizard(){if(this.pendingClarificationWizard&&this.resolveClarificationWizardPromise){let r={requestId:this.pendingClarificationWizard.id,completed:!1,timestamp:rn()};$.info("Clarification wizard cancelled",{requestId:this.pendingClarificationWizard.id}),this.resolveClarificationWizardPromise(r)}this.pendingClarificationWizard=null,this.resolveClarificationWizardPromise=null}getRequest(r){return this.history.requests.find(n=>n.id===r)}getResponse(r){return this.history.responses.find(n=>n.requestId===r)}async waitForUserApproval(r){return this.eventEmitter.emit("approval-required",{request:r}),new Promise(n=>{this.resolveApproval=n})}canAutoApprove(r){if(this.sessionAutoApprovalEnabled)return r.riskLevel==="critical"?($.debug("Session auto-approval: Skipping critical operation, requiring manual approval"),!1):($.debug("Session auto-approval: Auto-approving operation"),!0);if(this.fileEditsAutoApprovalEnabled&&["file_create","file_modify","shell_command"].includes(r.type))if(r.type==="shell_command"&&(r.riskLevel==="high"||r.riskLevel==="critical"))$.debug("File edits auto-approval: Skipping high-risk shell command, requiring manual approval");else return $.debug("File edits auto-approval: Auto-approving operation"),!0;if(r.type==="shell_command"&&r.details.command&&this.isCommandPrefixApproved(r.details.command)){let o=this.getCommandPrefix(r.details.command);return $.debug(`Command prefix '${o}' is approved, auto-approving`),!0}if(r.riskLevel==="high"||r.riskLevel==="critical"||this.mode==="strict"||r.details.affectedFiles!==void 0&&r.details.affectedFiles>this.maxAutoApproveFiles||(r.details.linesAdded||0)+(r.details.linesRemoved||0)>this.maxAutoApproveLines)return!1;if(r.details.filePaths){for(let o of r.details.filePaths)if(Qq(o,this.requireApprovalPatterns))return!1}return this.mode==="smart"?this.canSmartAutoApprove(r):this.mode!=="manual"}canSmartAutoApprove(r){let n=r.details.complexityMode||this.currentComplexityMode,o=r.details.complexityConfidence??this.currentComplexityConfidence;return n?n!=="direct"?($.debug(`SMART mode: Complexity mode is ${n}, requiring approval`),!1):o<this.smartModeConfidenceThreshold?($.debug(`SMART mode: Confidence ${o} below threshold ${this.smartModeConfidenceThreshold}, requiring approval`),!1):r.riskLevel!=="low"?($.debug(`SMART mode: Risk level is ${r.riskLevel}, requiring approval`),!1):["file_create","file_modify","file_rename"].includes(r.type)?($.info(`SMART mode: Auto-approving ${r.type} (complexity: ${n}, confidence: ${o}%, risk: ${r.riskLevel})`),!0):($.debug(`SMART mode: Operation type ${r.type} not safe for auto-approval`),!1):($.debug("SMART mode: No complexity context available, requiring approval"),!1)}shouldRequireApproval(r){if(r.details.filePaths){for(let n of r.details.filePaths)if(Qq(n,this.requireApprovalPatterns)||this.autoApprovePatterns.length>0&&!Qq(n,this.autoApprovePatterns))return!0}return r.riskLevel==="medium"||r.type==="shell_command"||r.type==="git_push"}assessRiskLevel(r,n){if(r==="git_push")return"critical";if(r==="file_delete")return"high";if(r==="multi_file_operation"){let o=n.affectedFiles||0;if(o>10)return"high";if(o>5)return"medium"}if(r==="shell_command"){let o=n.command?.toLowerCase()||"";return o.includes("rm ")||o.includes("delete")||o.includes("drop")||o.includes("truncate")?"high":"medium"}if(r==="git_commit")return"medium";if(r==="file_modify"){let o=(n.linesAdded||0)+(n.linesRemoved||0);if(o>200)return"medium";if(o>100)return"low"}return"low"}estimateImpact(r,n){let o=[];if(n.affectedFiles!==void 0&&o.push(`${n.affectedFiles} file${n.affectedFiles===1?"":"s"}`),n.linesAdded!==void 0&&n.linesAdded>0&&o.push(`+${n.linesAdded} line${n.linesAdded===1?"":"s"}`),n.linesRemoved!==void 0&&n.linesRemoved>0&&o.push(`-${n.linesRemoved} line${n.linesRemoved===1?"":"s"}`),n.command){let l=n.command.length>50?n.command.substring(0,47)+"...":n.command;o.push(`Command: ${l}`)}return o.length===0?"Minimal impact":o.join(", ")}createResponse(r,n,o){return{requestId:r.id,approved:n,timestamp:rn(),mode:this.mode,reason:o}}},M6e=null});import oGr from"path";async function zAt(i,r=Iq,n=yH){if(!BAt.has(i)){BAt.add(i);try{if(!await LH.default.pathExists(i))return;let l=await LH.default.readdir(i),p=[];for(let k of l)try{let N=oGr.join(i,k),W=await LH.default.stat(N);W.isFile()&&k!=="manifest.json"&&p.push({name:k,path:N,mtimeMs:W.mtimeMs})}catch{}let h=Date.now()-r*24*60*60*1e3,I=[];for(let k of p)if(k.mtimeMs<h)try{await LH.default.unlink(k.path)}catch{}else I.push(k);if(I.length>n){I.sort((N,W)=>W.mtimeMs-N.mtimeMs);let k=I.slice(n);for(let N of k)try{await LH.default.unlink(N.path)}catch{}}}catch{}}}var LH,BAt,qAt=Ut(()=>{"use strict";LH=Go(MI(),1);ju();BAt=new Set});import PD from"path";async function v5(){return k_e||(k_e=new E_e,await k_e.load()),k_e}var E_e,k_e,Y6e=Ut(()=>{"use strict";j_();Dp();sf();Q_();Xa();ju();qAt();E_e=class{projectRoot=process.cwd();manifest={version:"1.0",backups:[]};setProjectRoot(r){this.projectRoot=r}async createBackup(r){let n=PD.resolve(this.projectRoot,r);if(!await ea(n))return $.debug(`File does not exist, no backup needed: ${r}`),null;let o=await this.getBackupsDir(),l=xa(),p=new Date().toISOString().replace(/[:.]/g,"-"),h=PD.basename(r),I=`${p}_${l}_${h}`,k=PD.join(o,I);await TN(n,k);let N=await Sy(n),W={id:l,originalPath:r,backupPath:k,timestamp:rn(),size:N?.size||0};return this.manifest.backups.push(W),await this.saveManifest(),$.debug(`Backup created: ${k}`),W}async restore(r){let n=this.manifest.backups.find(l=>l.id===r);if(!n)return $.warn(`Backup not found: ${r}`),!1;if(!await ea(n.backupPath))return $.error(`Backup file missing: ${n.backupPath}`),!1;let o=PD.resolve(this.projectRoot,n.originalPath);return await Zl(PD.dirname(o)),await TN(n.backupPath,o),$.info(`Restored from backup: ${n.originalPath}`),!0}async restoreLatest(r){let n=this.manifest.backups.filter(o=>o.originalPath===r).sort((o,l)=>new Date(l.timestamp).getTime()-new Date(o.timestamp).getTime());return n.length===0?($.warn(`No backups found for: ${r}`),!1):this.restore(n[0].id)}getBackupsForFile(r){return this.manifest.backups.filter(n=>n.originalPath===r).sort((n,o)=>new Date(o.timestamp).getTime()-new Date(n.timestamp).getTime())}getAllBackups(){return[...this.manifest.backups].sort((r,n)=>new Date(n.timestamp).getTime()-new Date(r.timestamp).getTime())}async deleteBackup(r){let n=this.manifest.backups.findIndex(l=>l.id===r);if(n===-1)return!1;let o=this.manifest.backups[n];return await ea(o.backupPath)&&await G0(o.backupPath),this.manifest.backups.splice(n,1),await this.saveManifest(),$.debug(`Backup deleted: ${r}`),!0}async cleanup(){let r=0,n=new Date;n.setDate(n.getDate()-Iq);let o=this.manifest.backups.filter(l=>new Date(l.timestamp)<n);for(let l of o)await this.deleteBackup(l.id)&&r++;if(this.manifest.backups.length>yH){let p=[...this.manifest.backups].sort((h,I)=>new Date(I.timestamp).getTime()-new Date(h.timestamp).getTime()).slice(yH);for(let h of p)await this.deleteBackup(h.id)&&r++}return r>0&&$.info(`Cleaned up ${r} old backups`),r}async getBackupContent(r){let n=this.manifest.backups.find(o=>o.id===r);return!n||!await ea(n.backupPath)?null:ed(n.backupPath)}async load(){let r=await this.getManifestPath();if(await ea(r)){let n=await ed(r);if(n)try{this.manifest=JSON.parse(n)}catch{$.warn("Failed to parse backup manifest, starting fresh"),this.manifest={version:"1.0",backups:[]}}}}getTotalBackupSize(){return this.manifest.backups.reduce((r,n)=>r+n.size,0)}getBackupCount(){return this.manifest.backups.length}hasBackup(r){return this.manifest.backups.some(n=>n.id===r)}async getBackupsDir(){let r=PD.join(ou(this.projectRoot),cMe);return await Zl(r),await zAt(r),r}async getManifestPath(){let r=await this.getBackupsDir();return PD.join(r,"manifest.json")}async saveManifest(){let r=await this.getManifestPath();await C0(r,JSON.stringify(this.manifest,null,2))}},k_e=null});function wa(i,r,n,o,l){if(o==="m")throw new TypeError("Private method is not writable");if(o==="a"&&!l)throw new TypeError("Private accessor was defined without a setter");if(typeof r=="function"?i!==r||!l:!r.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?l.call(i,n):l?l.value=n:r.set(i,n),n}function Bn(i,r,n,o){if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a getter");if(typeof r=="function"?i!==r||!o:!r.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?o:n==="a"?o.call(i):o?o.value:r.get(i)}var NN=Ut(()=>{});var O6e,$At=Ut(()=>{O6e=function(){let{crypto:i}=globalThis;if(i?.randomUUID)return O6e=i.randomUUID.bind(i),i.randomUUID();let r=new Uint8Array(1),n=i?()=>i.getRandomValues(r)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,o=>(+o^n()&15>>+o/4).toString(16))}});function FN(i){return typeof i=="object"&&i!==null&&("name"in i&&i.name==="AbortError"||"message"in i&&String(i.message).includes("FetchRequestCanceledException"))}var h$,UH=Ut(()=>{h$=i=>{if(i instanceof Error)return i;if(typeof i=="object"&&i!==null){try{if(Object.prototype.toString.call(i)==="[object Error]"){let r=new Error(i.message,i.cause?{cause:i.cause}:{});return i.stack&&(r.stack=i.stack),i.cause&&!r.cause&&(r.cause=i.cause),i.name&&(r.name=i.name),r}}catch{}try{return new Error(JSON.stringify(i))}catch{}}return new Error(i)}});var So,N0,Ey,x5,XH,QH,jH,BH,zH,qH,$H,KH,e8,n1=Ut(()=>{UH();So=class extends Error{},N0=class i extends So{constructor(r,n,o,l,p){super(`${i.makeMessage(r,n,o)}`),this.status=r,this.headers=l,this.requestID=l?.get("request-id"),this.error=n,this.type=p??null}static makeMessage(r,n,o){let l=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):o;return r&&l?`${r} ${l}`:r?`${r} status code (no body)`:l||"(no status code or body)"}static generate(r,n,o,l){if(!r||!l)return new x5({message:o,cause:h$(n)});let p=n,h=p?.error?.type;return r===400?new QH(r,p,o,l,h):r===401?new jH(r,p,o,l,h):r===403?new BH(r,p,o,l,h):r===404?new zH(r,p,o,l,h):r===409?new qH(r,p,o,l,h):r===422?new $H(r,p,o,l,h):r===429?new KH(r,p,o,l,h):r>=500?new e8(r,p,o,l,h):new i(r,p,o,l,h)}},Ey=class extends N0{constructor({message:r}={}){super(void 0,void 0,r||"Request was aborted.",void 0)}},x5=class extends N0{constructor({message:r,cause:n}){super(void 0,void 0,r||"Connection error.",void 0),n&&(this.cause=n)}},XH=class extends x5{constructor({message:r}={}){super({message:r??"Request timed out."})}},QH=class extends N0{},jH=class extends N0{},BH=class extends N0{},zH=class extends N0{},qH=class extends N0{},$H=class extends N0{},KH=class extends N0{},e8=class extends N0{}});function T_e(i){return typeof i!="object"?{}:i??{}}function L6e(i){if(!i)return!0;for(let r in i)return!1;return!0}function eSt(i,r){return Object.prototype.hasOwnProperty.call(i,r)}var lGr,KAt,H6e,J6e,tSt,C_e,DD=Ut(()=>{n1();lGr=/^[a-z][a-z0-9+.-]*:/i,KAt=i=>lGr.test(i),H6e=i=>(H6e=Array.isArray,H6e(i)),J6e=H6e;tSt=(i,r)=>{if(typeof r!="number"||!Number.isInteger(r))throw new So(`${i} must be an integer`);if(r<0)throw new So(`${i} must be a positive integer`);return r},C_e=i=>{try{return JSON.parse(i)}catch{return}}});var rSt,nSt=Ut(()=>{rSt=i=>new Promise(r=>setTimeout(r,i))});var w5,U6e=Ut(()=>{w5="0.82.0"});function uGr(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function pGr(){if(typeof navigator>"u"||!navigator)return null;let i=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:r,pattern:n}of i){let o=n.exec(navigator.userAgent);if(o){let l=o[1]||0,p=o[2]||0,h=o[3]||0;return{browser:r,version:`${l}.${p}.${h}`}}}return null}var oSt,dGr,iSt,sSt,aSt,cSt,X6e=Ut(()=>{U6e();oSt=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";dGr=()=>{let i=uGr();if(i==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":w5,"X-Stainless-OS":sSt(Deno.build.os),"X-Stainless-Arch":iSt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":w5,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(i==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":w5,"X-Stainless-OS":sSt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":iSt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let r=pGr();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":w5,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":w5,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};iSt=i=>i==="x32"?"x32":i==="x86_64"||i==="x64"?"x64":i==="arm"?"arm":i==="aarch64"||i==="arm64"?"arm64":i?`other:${i}`:"unknown",sSt=i=>(i=i.toLowerCase(),i.includes("ios")?"iOS":i==="android"?"Android":i==="darwin"?"MacOS":i==="win32"?"Windows":i==="freebsd"?"FreeBSD":i==="openbsd"?"OpenBSD":i==="linux"?"Linux":i?`Other:${i}`:"Unknown"),cSt=()=>aSt??(aSt=dGr())});function lSt(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Q6e(...i){let r=globalThis.ReadableStream;if(typeof r>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new r(...i)}function G_e(i){let r=Symbol.asyncIterator in i?i[Symbol.asyncIterator]():i[Symbol.iterator]();return Q6e({start(){},async pull(n){let{done:o,value:l}=await r.next();o?n.close():n.enqueue(l)},async cancel(){await r.return?.()}})}function g$(i){if(i[Symbol.asyncIterator])return i;let r=i.getReader();return{async next(){try{let n=await r.read();return n?.done&&r.releaseLock(),n}catch(n){throw r.releaseLock(),n}},async return(){let n=r.cancel();return r.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function uSt(i){if(i===null||typeof i!="object")return;if(i[Symbol.asyncIterator]){await i[Symbol.asyncIterator]().return?.();return}let r=i.getReader(),n=r.cancel();r.releaseLock(),await n}var t8=Ut(()=>{});var dSt,pSt=Ut(()=>{dSt=({headers:i,body:r})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(r)})});function fSt(i){return Object.entries(i).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new So(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}var mSt=Ut(()=>{n1()});function gSt(i){let r=0;for(let l of i)r+=l.length;let n=new Uint8Array(r),o=0;for(let l of i)n.set(l,o),o+=l.length;return n}function y$(i){let r;return(_St??(r=new globalThis.TextEncoder,_St=r.encode.bind(r)))(i)}function j6e(i){let r;return(hSt??(r=new globalThis.TextDecoder,hSt=r.decode.bind(r)))(i)}var _St,hSt,B6e=Ut(()=>{});function _Gr(i,r){for(let l=r??0;l<i.length;l++){if(i[l]===10)return{preceding:l,index:l+1,carriage:!1};if(i[l]===13)return{preceding:l,index:l+1,carriage:!0}}return null}function ySt(i){for(let o=0;o<i.length-1;o++){if(i[o]===10&&i[o+1]===10||i[o]===13&&i[o+1]===13)return o+2;if(i[o]===13&&i[o+1]===10&&o+3<i.length&&i[o+2]===13&&i[o+3]===10)return o+4}return-1}var L2,U2,RN,z6e=Ut(()=>{NN();B6e();RN=class{constructor(){L2.set(this,void 0),U2.set(this,void 0),wa(this,L2,new Uint8Array,"f"),wa(this,U2,null,"f")}decode(r){if(r==null)return[];let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?y$(r):r;wa(this,L2,gSt([Bn(this,L2,"f"),n]),"f");let o=[],l;for(;(l=_Gr(Bn(this,L2,"f"),Bn(this,U2,"f")))!=null;){if(l.carriage&&Bn(this,U2,"f")==null){wa(this,U2,l.index,"f");continue}if(Bn(this,U2,"f")!=null&&(l.index!==Bn(this,U2,"f")+1||l.carriage)){o.push(j6e(Bn(this,L2,"f").subarray(0,Bn(this,U2,"f")-1))),wa(this,L2,Bn(this,L2,"f").subarray(Bn(this,U2,"f")),"f"),wa(this,U2,null,"f");continue}let p=Bn(this,U2,"f")!==null?l.preceding-1:l.preceding,h=j6e(Bn(this,L2,"f").subarray(0,p));o.push(h),wa(this,L2,Bn(this,L2,"f").subarray(l.index),"f"),wa(this,U2,null,"f")}return o}flush(){return Bn(this,L2,"f").length?this.decode(`
506
506
  `):[]}};L2=new WeakMap,U2=new WeakMap;RN.NEWLINE_CHARS=new Set([`
507
507
  `,"\r"]);RN.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function b$(){}function N_e(i,r,n){return!r||F_e[i]>F_e[n]?b$:r[i].bind(r)}function F0(i){let r=i.logger,n=i.logLevel??"off";if(!r)return hGr;let o=bSt.get(r);if(o&&o[0]===n)return o[1];let l={error:N_e("error",r,n),warn:N_e("warn",r,n),info:N_e("info",r,n),debug:N_e("debug",r,n)};return bSt.set(r,[n,l]),l}var F_e,q6e,hGr,bSt,WN,R_e=Ut(()=>{DD();F_e={off:0,error:200,warn:300,info:400,debug:500},q6e=(i,r,n)=>{if(i){if(eSt(F_e,i))return i;F0(n).warn(`${r} was set to ${JSON.stringify(i)}, expected one of ${JSON.stringify(Object.keys(F_e))}`)}};hGr={error:b$,warn:b$,info:b$,debug:b$},bSt=new WeakMap;WN=i=>(i.options&&(i.options={...i.options},delete i.options.headers),i.headers&&(i.headers=Object.fromEntries((i.headers instanceof Headers?[...i.headers]:Object.entries(i.headers)).map(([r,n])=>[r,r.toLowerCase()==="x-api-key"||r.toLowerCase()==="authorization"||r.toLowerCase()==="cookie"||r.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in i&&(i.retryOfRequestLogID&&(i.retryOf=i.retryOfRequestLogID),delete i.retryOfRequestLogID),i)});async function*gGr(i,r){if(!i.body)throw r.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new So("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new So("Attempted to iterate over a response with no body");let n=new $6e,o=new RN,l=g$(i.body);for await(let p of yGr(l))for(let h of o.decode(p)){let I=n.decode(h);I&&(yield I)}for(let p of o.flush()){let h=n.decode(p);h&&(yield h)}}async function*yGr(i){let r=new Uint8Array;for await(let n of i){if(n==null)continue;let o=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?y$(n):n,l=new Uint8Array(r.length+o.length);l.set(r),l.set(o,r.length),r=l;let p;for(;(p=ySt(r))!==-1;)yield r.slice(0,p),r=r.slice(p)}r.length>0&&(yield r)}function bGr(i,r){let n=i.indexOf(r);return n!==-1?[i.substring(0,n),r,i.substring(n+r.length)]:[i,"",""]}var I$,fT,$6e,K6e=Ut(()=>{NN();n1();t8();z6e();t8();UH();DD();B6e();R_e();n1();fT=class i{constructor(r,n,o){this.iterator=r,I$.set(this,void 0),this.controller=n,wa(this,I$,o,"f")}static fromSSEResponse(r,n,o){let l=!1,p=o?F0(o):console;async function*h(){if(l)throw new So("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");l=!0;let I=!1;try{for await(let k of gGr(r,n)){if(k.event==="completion")try{yield JSON.parse(k.data)}catch(N){throw p.error("Could not parse message into JSON:",k.data),p.error("From chunk:",k.raw),N}if(k.event==="message_start"||k.event==="message_delta"||k.event==="message_stop"||k.event==="content_block_start"||k.event==="content_block_delta"||k.event==="content_block_stop")try{yield JSON.parse(k.data)}catch(N){throw p.error("Could not parse message into JSON:",k.data),p.error("From chunk:",k.raw),N}if(k.event!=="ping"&&k.event==="error"){let N=C_e(k.data)??k.data,W=N?.error?.type;throw new N0(void 0,N,void 0,r.headers,W)}}I=!0}catch(k){if(FN(k))return;throw k}finally{I||n.abort()}}return new i(h,n,o)}static fromReadableStream(r,n,o){let l=!1;async function*p(){let I=new RN,k=g$(r);for await(let N of k)for(let W of I.decode(N))yield W;for(let N of I.flush())yield N}async function*h(){if(l)throw new So("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");l=!0;let I=!1;try{for await(let k of p())I||k&&(yield JSON.parse(k));I=!0}catch(k){if(FN(k))return;throw k}finally{I||n.abort()}}return new i(h,n,o)}[(I$=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let r=[],n=[],o=this.iterator(),l=p=>({next:()=>{if(p.length===0){let h=o.next();r.push(h),n.push(h)}return p.shift()}});return[new i(()=>l(r),this.controller,Bn(this,I$,"f")),new i(()=>l(n),this.controller,Bn(this,I$,"f"))]}toReadableStream(){let r=this,n;return Q6e({async start(){n=r[Symbol.asyncIterator]()},async pull(o){try{let{value:l,done:p}=await n.next();if(p)return o.close();let h=y$(JSON.stringify(l)+`
508
508
  `);o.enqueue(h)}catch(l){o.error(l)}},async cancel(){await n.return?.()}})}};$6e=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(r){if(r.endsWith("\r")&&(r=r.substring(0,r.length-1)),!r){if(!this.event&&!this.data.length)return null;let p={event:this.event,data:this.data.join(`
@@ -3760,7 +3760,7 @@ ${r}`),o.push({role:"user",content:I}),o}estimateTaskTokens(r,n,o){let l=Ld(r);f
3760
3760
  `)}LS();var kze=[{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"]}]}],Npn=[{name:"Setup & Configuration",description:"Commands for initial setup and configuration",commands:[{name:"setup",description:"Run first-time setup wizard",usage:"nova setup"},{name:"init",description:"Initialize Nova in current project",usage:"nova init"},{name:"config",description:"View or modify configuration",usage:"nova config [key] [value]",examples:["nova config","nova config model sonnet"]}]},{name:"Data Management",description:"Commands for managing stored data",commands:[{name:"tokens",description:"View token usage history",usage:"nova tokens [--export]"},{name:"consent",description:"Manage consent settings",usage:"nova consent [status|review|revoke]"},{name:"data",description:"Manage stored data",usage:"nova data [list|export|delete]"},{name:"cache",description:"Clear cached data",usage:"nova cache clear"},{name:"reset",description:"Reset to factory settings",usage:"nova reset [--force]"}]},{name:"Updates",description:"Commands for checking and installing updates",commands:[{name:"update",description:"Check for and install updates",usage:"nova update [check|install|history]",examples:["nova update","nova update check","nova update install","nova update history"]}]}];function LLt(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(`
3761
3761
  `)}function Fpn(){try{let{getCustomCommands:i}=(JLt(),K2r(HLt)),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 Rpn(){let i=[...kze],r=Fpn();r&&i.push(r);let n=i.map(LLt);return["",Dn.bold.white("Nova 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 Nova"),""].join(`
3762
3762
  `)}function Wpn(i){let r=i.startsWith("/")?i:`/${i}`,o=kze.flatMap(p=>p.commands).find(p=>p.name===r||p.name===i||p.aliases?.includes(i)||p.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 p of o.examples)l.push(` ${Dn.dim("$")} ${p}`);l.push("")}return l.join(`
3763
- `)}I4();var Q7n="1.0.95",j7n="compass-cli",B7n="AI-powered development assistance using Anthropic's Claude models";export{Sme as ACTIVE_PLAN_TYPE_LIMITS,_q as AGENT_SOURCE_PRIORITY,B7n as APP_DESCRIPTION,Uxr as APP_DISPLAY_NAME,j7n as APP_NAME,Xxr as APP_TAGLINE,Lxr as APP_VERSION,DLt as ASCII_BANNER,bMe as AUTO_COMPACT_TRIGGER,hme as AUTO_SAVE_INTERVAL_MS,cee as ActionLogger,E7e as ActionStatus,Zb as ActionType,Ahe as AnthropicClient,S_e as ApprovalManager,mH as ApprovalMode,cMe as BACKUPS_DIR,Iq as BACKUP_RETENTION_DAYS,Bxr as BINARY_EXTENSIONS,E_e as BackupManager,wxr as CACHE_DIR,Sq as CATEGORY_INFO,nMe as CHAT_ARCHIVE_VERSION,Dw as CLAUDE_MODELS,Npn as CLI_COMMANDS,Rvt as COMMAND_EXAMPLES,owr as COMMAND_GROUPS,ypn as COMPASS_ICON,hH as CONFIG_FILE_NAME,IMe as CONSENT_EXPIRY_DAYS,aMe as CONSENT_FILE_NAME,Qxr as CONSENT_VERSION,Axr as CONTEXT_DIR,Zxr as CONTEXT_WINDOW_SAFETY_MARGIN,Sxr as CONTEXT_WINDOW_WARNING_PERCENT,gq as CREDENTIALS_FILE_NAME,AN as CRON_DAY_NAMES,wme as CRON_PRESETS,y_e as ChatArchivalService,Eee as ComplexityClassifier,o_e as ConfigManager,f_e as ConsentManager,g_e as CredentialStore,Ame as DAY_NAME_TO_CRON,vN as DEFAULT_ANTHROPIC_TEMPERATURE,Exr as DEFAULT_CLASSIFIER_MODEL,n5 as DEFAULT_CLASSIFIER_MODELS_BY_PROVIDER,xN as DEFAULT_CONFIG,kxr as DEFAULT_COST_WARNING_THRESHOLD,cT as DEFAULT_MAX_TOKENS,Pw as DEFAULT_MODEL,pvt as DEFAULT_OLLAMA_TEMPERATURE,$v as DEFAULT_PERSONALITY_MODE,vD as DEFAULT_PLAN_TYPE,gxr as DEFAULT_RATING_CONFIG,Eq as DEFAULT_SCHEDULE_HEADER,pxr as DEFAULT_UPDATE_CONFIG,kme as DISABLED_MODELS,Wvt as DOC_LINKS,VMe as ENVIRONMENT_VARIABLES,kb as ENV_VARS,Nvt as EXIT_CODES,gee as EnhancedContextGatherer,d_e as EventEmitter,fq as ExecutionMode,i4t as ExecutionStrategy,hq as GLOBAL_COMPASS_DIR,vK as GitService,rvt as HOOK_EVENTS,pme as HOOK_SOURCE_PRIORITY,X2e as HistoryManager,lMe as INDEX_DIR,Ote as InteractiveClarifier,r4t as IssueCategory,t4t as IssueSeverity,jxr as LANGUAGE_EXTENSIONS,oMe as LOGS_DIR,Zee as LogInterpreter,Fvt as MAIN_EXAMPLES,yH as MAX_BACKUP_FILES,Pxr as MAX_CACHE_SIZE_BYTES,wq as MAX_COMMAND_OUTPUT_TOKENS,Wxr as MAX_DYNAMIC_STREAM_BLOCKS,lvt as MAX_FILES_PER_OPERATION,vMe as MAX_FILE_READ_TOKENS,uvt as MAX_FILE_SIZE_BYTES,xq as MAX_HISTORY_LENGTH,Vxr as MAX_INDEXED_FILES,r5 as MAX_MEMORY_LINES,Yxr as MAX_RETRY_ATTEMPTS,yme as MAX_SEARCH_RESULT_TOKENS,hMe as MEMORY_DIR,IN as MEMORY_FILE_NAME,xD as MODEL_ALIASES,gMe as NOVA_LOCAL_MD_FILE_NAME,bq as NOVA_MD_FILE_NAME,hvt as NO_SUBSCRIPTION_DAILY_TOKEN_LIMIT,WMe as PLAN_LIMITS,yq as PROJECTS_DIR,ID as PROJECT_COMPASS_DIR,wN as PROVIDERS,bme as PROVIDER_ENV_VARS,Hte as PlanGenerator,Oxr as RETRY_BASE_DELAY_MS,Jxr as RETRY_JITTER_FACTOR,Hxr as RETRY_MAX_DELAY_MS,Gq as ROLLING_WINDOW_HOURS,Cq as ROLLING_WINDOW_MS,_Me as RULES_DIR,gH as SAVED_SESSIONS_DIR,GMe as SCHEDULE_FILE_NAME,svt as SESSION_EXPIRY_DAYS,mme as SESSION_FILE_NAME,gme as SHELL_COMMAND_MAX_TIMEOUT_MS,vq as SHELL_COMMAND_TIMEOUT_MS,kze as SLASH_COMMANDS,bH as SYSTEM_UTILITIES,b_e as SessionManager,U0e as ShellExecutor,_Vt as StepStatus,oee as StepTracker,hVt as StepType,xme as TASK_ID_PREFIX,kq as TASK_ID_RANDOM_LENGTH,NMe as TASK_STATUSES,uMe as TEMP_DIR,FMe as TOKEN_LIMITS_STORE_FILENAME,RMe as TOKEN_LIMITS_STORE_VERSION,awr as TOKEN_LIMIT_MESSAGES,qxr as TOKEN_LIMIT_WARNING_THRESHOLD_PERCENT,yMe as TOKEN_WARNING_THRESHOLD,SMe as TOOL_READ_BLOCKLIST_DIRS,AMe as TOOL_READ_BLOCKLIST_PATTERNS,eMe as TaskExecutionStatus,gVt as TaskStatus,D6e as TokenLimitEnforcer,sMe as TokenLimitExceededError,I_e as TokenLimitStore,A_e as TokenTracker,pee as ToolRegistry,EMe as UTILITY_DETECTION_CACHE_TTL,TMe as UTILITY_DETECTION_TIMEOUT,_vt as VALID_PLAN_TYPES,Q7n as VERSION,Jte as Verifier,n7e as WORKFLOW_PROMPTS,Vee as WorkflowManager,Lte as WorkflowOrchestrator,ome as WorkflowPhase,n4t as WorkflowState,mpn as applyCompletion,sOr as applyPatch,nOr as areIdentical,DHr as calculateContextUsagePercent,Avt as calculateModelCost,ZHr as calculateRemainingTokens,DCr as colorByStatus,eOr as colorizeDiff,KIt as compareAgentPriority,xxr as compareHookPriority,Svt as compareModels,TN as copy,KHr as createActionLogger,l$ as createChatArchivalService,TJr as createComplexityClassifier,qIt as createDefaultAgentDefinition,lxr as createDefaultConsent,yxr as createDefaultRatingState,V8r as createEnhancedContextGatherer,uxr as createFullConsent,fVr as createGitService,Ydn as createInteractiveClarifier,ELr as createLogInterpreter,dxr as createMinimalConsent,Hdn as createPlanGenerator,$Hr as createStepTracker,f$ as createTokenLimitStore,l8r as createToolRegistry,Ldn as createVerifier,CLr as createWorkflowManager,Xdn as createWorkflowOrchestrator,G6e as decrypt,C6e as encrypt,Zl as ensureDir,RHr as estimateConversationTokens,WHr as estimateSystemPromptTokens,Ld as estimateTokens,zdn as executeSlashCommand,Ize as extractCodeBlocks,bze as extractMentions,cwr as formatAfterHelpText,lwr as formatCommandAfterHelp,Wpn as formatCommandHelp,FCr as formatCost,TCr as formatDate,CCr as formatDuration,NCr as formatFileSize,Rpn as formatFullHelp,LLt as formatHelpCategory,PCr as formatList,ZAt as formatPercent,VCr as formatProgressBar,GCr as formatRelativeTime,rn as formatTimestamp,RCr as formatTokenCount,PHr as formatTokenDisplay,h4 as generateDiff,tOr as generateDiffSummary,MLt as generateGreeting,XCr as generateSecureRandom,rOr as generateWordDiff,q5 as getActionLogger,cme as getAgentSourcePriority,R0 as getAnthropicClient,xh as getApprovalManager,Ivt as getAvailableAliases,bvt as getAvailableModelIds,i5 as getAvailableModels,v5 as getBackupManager,jkr as getBasename,iOr as getChangedLineCount,Evt as getCheapestModel,_J as getCodebaseIndexer,spn as getCompletions,Tee as getComplexityClassifier,WD as getConfigManager,S6e as getConsentManager,iF as getContextBuilder,MHr as getContextUsageColor,qHr as getConversationCompactor,Rg as getCredentialStore,xvt as getDefaultModel,wvt as getDefaultModelId,yee as getEnhancedContextGatherer,aa as getEventEmitter,Qkr as getExtension,kT as getFileService,oc as getGlobalCompassDir,Kdn as getHistoryManager,tMe as getHookSourcePriority,hze as getInteractiveClarifier,IXe as getLogInterpreter,Gm as getModelConfig,vme as getModelDescription,Aq as getModelKnowledgeCutoff,Cvt as getModelTier,v_e as getModelTokens,kvt as getModelsByCapability,Tvt as getMostCapableModel,Y2e as getPlanGenerator,ou as getProjectCompassDir,Ukr as getRelativePath,vm as getSessionManager,Ty as getShellExecutor,Aze as getSlashCommandRegistry,z5 as getStepTracker,X0e as getSystemUtilitiesPromptSection,aZt as getSystemUtilityDetector,hpn as getTaskProcessor,Fb as getTokenTracker,tx as getToolRegistry,zxr as getUtilitiesByCategory,yze as getVerifier,TLr as getWorkflowManager,Udn as getWorkflowOrchestrator,gvt as hasFullAccess,N6e as hash,QCr as hmac,nA as interpolateTemplate,yvt as isAnthropicModel,s$ as isDirectory,i_e as isFile,ND as isPathWithin,ume as isValidAgentFrontmatter,lme as isValidAgentPermissionMode,BIt as isValidAgentSource,txr as isValidAnthropicConfig,zIt as isValidCLIAgentConfig,t5 as isValidChatArchive,exr as isValidCompassConfig,oxr as isValidConfigFile,QIt as isValidConsent,cxr as isValidConsentRecord,fme as isValidHookEvent,vxr as isValidHookFrontmatter,Ixr as isValidHookSource,vvt as isValidModel,hxr as isValidNotificationStyle,rxr as isValidProjectConfig,bxr as isValidRatingState,nxr as isValidSafetyConfig,sxr as isValidSessionConfig,Bdn as isValidSlashCommand,ixr as isValidUIConfig,fxr as isValidUpdateCheckResult,mxr as isValidUpdateConfig,axr as isValidUpdateSettingsConfig,_xr as isValidUpdateType,$ as logger,Qq as matchesPattern,Xkr as normalizeSeparators,ZCr as padString,RLt as parseArgs,jdn as parseInput,bD as parseToolsList,ea as pathExists,MH as readDir,sXe as registerBuiltInTools,wze as registerSlashCommand,G0 as remove,Spn as renderBanner,kpn as renderMiniBanner,Epn as renderWelcome,u$ as resetIfExpired,Jkr as resolveGlobalPath,wy as resolveModelId,ZMe as resolvePlanLimits,Lkr as resolveProjectPath,ed as safeReadFile,_d as safeReadJson,C0 as safeWriteFile,X_ as safeWriteJson,GD as sanitizePath,jCr as secureCompare,$It as serializeToolsList,Sy as stat,p$ as sumAllUsage,p5 as toForwardSlashes,WCr as truncate,VHr as wouldExceedContext};
3763
+ `)}I4();var Q7n="1.0.96",j7n="compass-cli",B7n="AI-powered development assistance using Anthropic's Claude models";export{Sme as ACTIVE_PLAN_TYPE_LIMITS,_q as AGENT_SOURCE_PRIORITY,B7n as APP_DESCRIPTION,Uxr as APP_DISPLAY_NAME,j7n as APP_NAME,Xxr as APP_TAGLINE,Lxr as APP_VERSION,DLt as ASCII_BANNER,bMe as AUTO_COMPACT_TRIGGER,hme as AUTO_SAVE_INTERVAL_MS,cee as ActionLogger,E7e as ActionStatus,Zb as ActionType,Ahe as AnthropicClient,S_e as ApprovalManager,mH as ApprovalMode,cMe as BACKUPS_DIR,Iq as BACKUP_RETENTION_DAYS,Bxr as BINARY_EXTENSIONS,E_e as BackupManager,wxr as CACHE_DIR,Sq as CATEGORY_INFO,nMe as CHAT_ARCHIVE_VERSION,Dw as CLAUDE_MODELS,Npn as CLI_COMMANDS,Rvt as COMMAND_EXAMPLES,owr as COMMAND_GROUPS,ypn as COMPASS_ICON,hH as CONFIG_FILE_NAME,IMe as CONSENT_EXPIRY_DAYS,aMe as CONSENT_FILE_NAME,Qxr as CONSENT_VERSION,Axr as CONTEXT_DIR,Zxr as CONTEXT_WINDOW_SAFETY_MARGIN,Sxr as CONTEXT_WINDOW_WARNING_PERCENT,gq as CREDENTIALS_FILE_NAME,AN as CRON_DAY_NAMES,wme as CRON_PRESETS,y_e as ChatArchivalService,Eee as ComplexityClassifier,o_e as ConfigManager,f_e as ConsentManager,g_e as CredentialStore,Ame as DAY_NAME_TO_CRON,vN as DEFAULT_ANTHROPIC_TEMPERATURE,Exr as DEFAULT_CLASSIFIER_MODEL,n5 as DEFAULT_CLASSIFIER_MODELS_BY_PROVIDER,xN as DEFAULT_CONFIG,kxr as DEFAULT_COST_WARNING_THRESHOLD,cT as DEFAULT_MAX_TOKENS,Pw as DEFAULT_MODEL,pvt as DEFAULT_OLLAMA_TEMPERATURE,$v as DEFAULT_PERSONALITY_MODE,vD as DEFAULT_PLAN_TYPE,gxr as DEFAULT_RATING_CONFIG,Eq as DEFAULT_SCHEDULE_HEADER,pxr as DEFAULT_UPDATE_CONFIG,kme as DISABLED_MODELS,Wvt as DOC_LINKS,VMe as ENVIRONMENT_VARIABLES,kb as ENV_VARS,Nvt as EXIT_CODES,gee as EnhancedContextGatherer,d_e as EventEmitter,fq as ExecutionMode,i4t as ExecutionStrategy,hq as GLOBAL_COMPASS_DIR,vK as GitService,rvt as HOOK_EVENTS,pme as HOOK_SOURCE_PRIORITY,X2e as HistoryManager,lMe as INDEX_DIR,Ote as InteractiveClarifier,r4t as IssueCategory,t4t as IssueSeverity,jxr as LANGUAGE_EXTENSIONS,oMe as LOGS_DIR,Zee as LogInterpreter,Fvt as MAIN_EXAMPLES,yH as MAX_BACKUP_FILES,Pxr as MAX_CACHE_SIZE_BYTES,wq as MAX_COMMAND_OUTPUT_TOKENS,Wxr as MAX_DYNAMIC_STREAM_BLOCKS,lvt as MAX_FILES_PER_OPERATION,vMe as MAX_FILE_READ_TOKENS,uvt as MAX_FILE_SIZE_BYTES,xq as MAX_HISTORY_LENGTH,Vxr as MAX_INDEXED_FILES,r5 as MAX_MEMORY_LINES,Yxr as MAX_RETRY_ATTEMPTS,yme as MAX_SEARCH_RESULT_TOKENS,hMe as MEMORY_DIR,IN as MEMORY_FILE_NAME,xD as MODEL_ALIASES,gMe as NOVA_LOCAL_MD_FILE_NAME,bq as NOVA_MD_FILE_NAME,hvt as NO_SUBSCRIPTION_DAILY_TOKEN_LIMIT,WMe as PLAN_LIMITS,yq as PROJECTS_DIR,ID as PROJECT_COMPASS_DIR,wN as PROVIDERS,bme as PROVIDER_ENV_VARS,Hte as PlanGenerator,Oxr as RETRY_BASE_DELAY_MS,Jxr as RETRY_JITTER_FACTOR,Hxr as RETRY_MAX_DELAY_MS,Gq as ROLLING_WINDOW_HOURS,Cq as ROLLING_WINDOW_MS,_Me as RULES_DIR,gH as SAVED_SESSIONS_DIR,GMe as SCHEDULE_FILE_NAME,svt as SESSION_EXPIRY_DAYS,mme as SESSION_FILE_NAME,gme as SHELL_COMMAND_MAX_TIMEOUT_MS,vq as SHELL_COMMAND_TIMEOUT_MS,kze as SLASH_COMMANDS,bH as SYSTEM_UTILITIES,b_e as SessionManager,U0e as ShellExecutor,_Vt as StepStatus,oee as StepTracker,hVt as StepType,xme as TASK_ID_PREFIX,kq as TASK_ID_RANDOM_LENGTH,NMe as TASK_STATUSES,uMe as TEMP_DIR,FMe as TOKEN_LIMITS_STORE_FILENAME,RMe as TOKEN_LIMITS_STORE_VERSION,awr as TOKEN_LIMIT_MESSAGES,qxr as TOKEN_LIMIT_WARNING_THRESHOLD_PERCENT,yMe as TOKEN_WARNING_THRESHOLD,SMe as TOOL_READ_BLOCKLIST_DIRS,AMe as TOOL_READ_BLOCKLIST_PATTERNS,eMe as TaskExecutionStatus,gVt as TaskStatus,D6e as TokenLimitEnforcer,sMe as TokenLimitExceededError,I_e as TokenLimitStore,A_e as TokenTracker,pee as ToolRegistry,EMe as UTILITY_DETECTION_CACHE_TTL,TMe as UTILITY_DETECTION_TIMEOUT,_vt as VALID_PLAN_TYPES,Q7n as VERSION,Jte as Verifier,n7e as WORKFLOW_PROMPTS,Vee as WorkflowManager,Lte as WorkflowOrchestrator,ome as WorkflowPhase,n4t as WorkflowState,mpn as applyCompletion,sOr as applyPatch,nOr as areIdentical,DHr as calculateContextUsagePercent,Avt as calculateModelCost,ZHr as calculateRemainingTokens,DCr as colorByStatus,eOr as colorizeDiff,KIt as compareAgentPriority,xxr as compareHookPriority,Svt as compareModels,TN as copy,KHr as createActionLogger,l$ as createChatArchivalService,TJr as createComplexityClassifier,qIt as createDefaultAgentDefinition,lxr as createDefaultConsent,yxr as createDefaultRatingState,V8r as createEnhancedContextGatherer,uxr as createFullConsent,fVr as createGitService,Ydn as createInteractiveClarifier,ELr as createLogInterpreter,dxr as createMinimalConsent,Hdn as createPlanGenerator,$Hr as createStepTracker,f$ as createTokenLimitStore,l8r as createToolRegistry,Ldn as createVerifier,CLr as createWorkflowManager,Xdn as createWorkflowOrchestrator,G6e as decrypt,C6e as encrypt,Zl as ensureDir,RHr as estimateConversationTokens,WHr as estimateSystemPromptTokens,Ld as estimateTokens,zdn as executeSlashCommand,Ize as extractCodeBlocks,bze as extractMentions,cwr as formatAfterHelpText,lwr as formatCommandAfterHelp,Wpn as formatCommandHelp,FCr as formatCost,TCr as formatDate,CCr as formatDuration,NCr as formatFileSize,Rpn as formatFullHelp,LLt as formatHelpCategory,PCr as formatList,ZAt as formatPercent,VCr as formatProgressBar,GCr as formatRelativeTime,rn as formatTimestamp,RCr as formatTokenCount,PHr as formatTokenDisplay,h4 as generateDiff,tOr as generateDiffSummary,MLt as generateGreeting,XCr as generateSecureRandom,rOr as generateWordDiff,q5 as getActionLogger,cme as getAgentSourcePriority,R0 as getAnthropicClient,xh as getApprovalManager,Ivt as getAvailableAliases,bvt as getAvailableModelIds,i5 as getAvailableModels,v5 as getBackupManager,jkr as getBasename,iOr as getChangedLineCount,Evt as getCheapestModel,_J as getCodebaseIndexer,spn as getCompletions,Tee as getComplexityClassifier,WD as getConfigManager,S6e as getConsentManager,iF as getContextBuilder,MHr as getContextUsageColor,qHr as getConversationCompactor,Rg as getCredentialStore,xvt as getDefaultModel,wvt as getDefaultModelId,yee as getEnhancedContextGatherer,aa as getEventEmitter,Qkr as getExtension,kT as getFileService,oc as getGlobalCompassDir,Kdn as getHistoryManager,tMe as getHookSourcePriority,hze as getInteractiveClarifier,IXe as getLogInterpreter,Gm as getModelConfig,vme as getModelDescription,Aq as getModelKnowledgeCutoff,Cvt as getModelTier,v_e as getModelTokens,kvt as getModelsByCapability,Tvt as getMostCapableModel,Y2e as getPlanGenerator,ou as getProjectCompassDir,Ukr as getRelativePath,vm as getSessionManager,Ty as getShellExecutor,Aze as getSlashCommandRegistry,z5 as getStepTracker,X0e as getSystemUtilitiesPromptSection,aZt as getSystemUtilityDetector,hpn as getTaskProcessor,Fb as getTokenTracker,tx as getToolRegistry,zxr as getUtilitiesByCategory,yze as getVerifier,TLr as getWorkflowManager,Udn as getWorkflowOrchestrator,gvt as hasFullAccess,N6e as hash,QCr as hmac,nA as interpolateTemplate,yvt as isAnthropicModel,s$ as isDirectory,i_e as isFile,ND as isPathWithin,ume as isValidAgentFrontmatter,lme as isValidAgentPermissionMode,BIt as isValidAgentSource,txr as isValidAnthropicConfig,zIt as isValidCLIAgentConfig,t5 as isValidChatArchive,exr as isValidCompassConfig,oxr as isValidConfigFile,QIt as isValidConsent,cxr as isValidConsentRecord,fme as isValidHookEvent,vxr as isValidHookFrontmatter,Ixr as isValidHookSource,vvt as isValidModel,hxr as isValidNotificationStyle,rxr as isValidProjectConfig,bxr as isValidRatingState,nxr as isValidSafetyConfig,sxr as isValidSessionConfig,Bdn as isValidSlashCommand,ixr as isValidUIConfig,fxr as isValidUpdateCheckResult,mxr as isValidUpdateConfig,axr as isValidUpdateSettingsConfig,_xr as isValidUpdateType,$ as logger,Qq as matchesPattern,Xkr as normalizeSeparators,ZCr as padString,RLt as parseArgs,jdn as parseInput,bD as parseToolsList,ea as pathExists,MH as readDir,sXe as registerBuiltInTools,wze as registerSlashCommand,G0 as remove,Spn as renderBanner,kpn as renderMiniBanner,Epn as renderWelcome,u$ as resetIfExpired,Jkr as resolveGlobalPath,wy as resolveModelId,ZMe as resolvePlanLimits,Lkr as resolveProjectPath,ed as safeReadFile,_d as safeReadJson,C0 as safeWriteFile,X_ as safeWriteJson,GD as sanitizePath,jCr as secureCompare,$It as serializeToolsList,Sy as stat,p$ as sumAllUsage,p5 as toForwardSlashes,WCr as truncate,VHr as wouldExceedContext};
3764
3764
  /*! Bundled license information:
3765
3765
 
3766
3766
  typescript/lib/typescript.js: