command-code 0.19.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -278,4 +278,4 @@ import*as e from"path";import t,{join as n,dirname as r,parse as s,relative as o
278
278
  )
279
279
  `})])),b(ky)}}),jy=__esm({"../shared/src/database/schema/index.ts"(){Ht(),sh(),Ay(),Iy(),rh(),Ny(),Ry(),$y(),My(),Ly(),Dy(),Oy(),Fy(),qy(),oh()}}),By=__esm({"../shared/src/database/config/database.ts"(){Ht(),Py(),jy()}}),Uy=__esm({"../shared/src/database/index.ts"(){Ht(),By(),jy()}}),zy=__esm({"../shared/src/index.ts"(){Ht(),Os(),Fs(),kh(),Th(),_h(),Kt(),Qt(),xh(),Uy()}}),Wy=__esm({"src/api/request.ts"(){Ht(),Ls(),Ur(),Ds(),Cs(),Kr(),Mr(),zy(),Ty=getPackageJson(),_y="string"==typeof Ty.version&&Ty.version.trim()?Ty.version:"unknown",xy=class{static{__name(this,"Request")}config;constructor(e){this.config=e}async send(e){const{endpoint:t}=e,n=this.buildUrl({endpoint:t}),r=trackAPICallStart({method:e.method,endpoint:t,cliVersion:_y}),s=await this.buildHeaders({headers:e.headers,span:r.span});let o;try{o=await this.makeRequest({url:n,options:e,headers:s})}catch(e){const t=new Ts({cause:e instanceof Error?e:void 0});throw r.end({statusCode:0,error:t}),t}if(!o.ok){const{error:e}=await this.handleErrorResponse({response:o});throw r.end({statusCode:o.status,error:e}),e}return r.end({statusCode:o.status}),e.stream?o.body:o.json()}buildUrl({endpoint:e}){return`${this.config.baseUrl}${e}`}async buildHeaders({headers:e,span:t}){const n=await getAuthKey(),r=getTraceId(),s=t?.spanContext(),o=r&&s?.spanId?`00-${r}-${s.spanId}-01`:void 0,i=getTelemetryEnv(),a="prod"===i?"production":i;return{"Content-Type":"application/json",[Ct.CLI_ENVIRONMENT]:a,...n?{Authorization:`Bearer ${n}`}:{},...o?{traceparent:o}:{},...e,[Ct.CLI_VERSION]:_y}}async makeRequest({url:e,options:t,headers:n}){const r=new AbortController,s=this.config.timeout?setTimeout(()=>r.abort(),this.config.timeout):null;try{const o=await fetch(e,{headers:n,method:t.method,body:t.body?JSON.stringify(t.body):void 0,signal:t.signal??r.signal});return s&&clearTimeout(s),o}catch(e){throw s&&clearTimeout(s),e}}async handleErrorResponse({response:e}){let t;try{t=await e.json()}catch{t=await e.text()}const n={};return e.headers.forEach((e,t)=>{n[t]=e}),{error:ks.generate(e.status,t,e.statusText,n),errorBody:t}}async post(e){return this.send({...e,method:"POST"})}async get(e){return this.send({...e,method:"GET"})}async put(e){return this.send({...e,method:"PUT"})}async delete(e){return this.send({...e,method:"DELETE"})}}}});function getApiBaseUrl(){const e="true"===process.env.COMMANDCODE_SANDBOX,t=process.env.COMMANDCODE_API_URL;if(e&&t)return t;const n=process.argv.includes("--local"),r=process.argv.includes("--staging");return n?"http://localhost:9090":r?"https://staging-api.commandcode.ai":"https://api.commandcode.ai"}var Gy,Hy,Qy,Vy,Ky,Yy,Jy,Xy=__esm({"src/api/utils.ts"(){Ht(),__name(getApiBaseUrl,"getApiBaseUrl")}}),Zy=__esm({"../shared/src/constants/tools.ts"(){Ht(),Gy={READ_FILE:"read_file",EDIT_FILE:"edit_file",WRITE_FILE:"write_file",READ_DIRECTORY:"read_directory",READ_MULTIPLE_FILES:"read_multiple_files",GREP:"grep",SHELL_COMMAND:"shell_command",THINKING:"think",TODO_WRITE:"todo_write",QUESTION:"ask_user_question",EXPLORE:"explore",KILL_SHELL:"kill_shell",ENTER_PLAN_MODE:"enter_plan_mode",EXIT_PLAN_MODE:"exit_plan_mode",DIAGNOSTICS:"diagnostics",GET_SELF_KNOWLEDGE:"get_self_knowledge"},Hy={WEB_SEARCH:"web_search",WEB_FETCH:"web_fetch"},Qy=__name(e=>e===Hy.WEB_SEARCH,"isWebSearchTool"),Vy=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],Ky=__name(({serverToolBlock:e,contentBlocks:t})=>{const n=e.toolCallId??e.id,r=e.toolName??e.name??"",s=t.find(e=>"tool-result"===e.type&&e.providerExecuted&&e.toolCallId===n);if(s)return"error-text"===s.output?.type||"error-json"===s.output?.type?{message:s.output?.value??"Error",isError:!0}:"string"==typeof s.output?.value&&s.output.value.trim()?{message:Qy(r)?"Found results":"Content fetched",isError:!1}:{message:Qy(r)?"Found 10 results":"Content fetched",isError:!1};const o=t.find(e=>("web_search_tool_result"===e.type||"web_fetch_tool_result"===e.type)&&e.tool_use_id===n);return Vy.includes(o?.content?.type)?{message:`Error: ${o?.content?.error_code||"unknown_error"}`,isError:!0}:Qy(r)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage"),Yy=["create_file","delete_file",Gy.EDIT_FILE,Gy.WRITE_FILE,Gy.SHELL_COMMAND],Jy=[Gy.SHELL_COMMAND]}});function getEnterpriseMemoryPath(){switch(y.platform()){case"darwin":return"/Library/Application Support/CommandCode/AGENTS.md";case"win32":return e.join("C:","ProgramData","CommandCode","AGENTS.md");default:return"/etc/.commandcode/AGENTS.md"}}function getUserMemoryPath(){const t=y.homedir();return e.join(t,".commandcode","AGENTS.md")}function getProjectMemoryPaths(t){return[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")]}async function discoverMemoryFiles(e){const t=[],n=getEnterpriseMemoryPath();t.push({type:"enterprise",path:n,exists:C(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(C(n)){t.push({type:"project",path:n,exists:!0,description:"Team-shared project instructions"});break}t.find(e=>"project"===e.type)||t.push({type:"project",path:e[0],exists:!1,description:"Team-shared project instructions"})}const s=getUserMemoryPath();return t.push({type:"user",path:s,exists:C(s),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return C(e)&&P(e).isFile()?await D.readFile(e,"utf-8"):null}catch(t){return console.error(`Error reading memory file ${e}:`,t),null}}function getCodeBlockRegex(){return/```[\s\S]*?```|`[^`]+`/g}function getImportRegex(){return/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm}async function processImports(t,n,r=0,s=5){if(r>=s)return t;const o=[],i=t.replace(/```[\s\S]*?```|`[^`]+`/g,e=>(o.push(e),`__CODE_BLOCK_${o.length-1}__`)),a=Array.from(i.matchAll(/(?:^|[\s\n])@((?:~\/)?[^\s\n]+(?:\.[^\s\n]+)?)/gm));let l=i;for(const t of a){const o=t[1];let i=o;o.startsWith("~/")?i=e.join(y.homedir(),o.slice(2)):e.isAbsolute(o)||(i=e.resolve(e.dirname(n),o));const a=await loadMemoryFile(i);if(a){const e=await processImports(a,i,r+1,s);l=l.replace(t[0],`\n# Imported from ${o}\n${e}\n`)}}return l=l.replace(/__CODE_BLOCK_(\d+)__/g,(e,t)=>o[parseInt(t)]),l}async function loadAllMemories(t,n){const r=new Map,s=getEnterpriseMemoryPath();if(C(s)){const e=await loadMemoryFile(s);if(e){const t=await processImports(e,s);r.set(s,t)}}const o=getUserMemoryPath();if(C(o)){const e=await loadMemoryFile(o);if(e){const t=await processImports(e,o);r.set(o,t)}}const i=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of i)if(C(e)){const t=await loadMemoryFile(e);if(t){const n=await processImports(t,e);r.set(e,n)}break}if(n&&n.length>0)for(const s of n){const n=e.isAbsolute(s)?e.dirname(s):e.dirname(e.resolve(t,s));if(n.startsWith(t)&&n!==t){const s=[];let o=n;for(;o.startsWith(t)&&o!==t;)s.push(o),o=e.dirname(o);for(const t of s.reverse()){const n=[e.join(t,"AGENTS.md"),e.join(t,".commandcode","AGENTS.md")];for(const e of n)if(C(e)&&!r.has(e)){const t=await loadMemoryFile(e);if(t){const n=await processImports(t,e);r.set(e,n)}break}}}}return r}async function openInEditor(t){const n=process.env.EDITOR||process.env.VISUAL||"code",r=e.dirname(t);return C(r)||await D.mkdir(r,{recursive:!0}),C(t)||await D.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const s=M(n,[t],{stdio:"inherit",shell:!0});s.on("exit",t=>{0===t?e():r(new Error(`Editor exited with code ${t}`))}),s.on("error",e=>{console.error("Error opening memory file. Please ensure you have an editor set up."),r(e)})})}async function initProjectMemory(t){const n=e.join(t,"AGENTS.md");return C(n)||await D.writeFile(n,"# Memory\n\n## Project Overview\nSee @README.md for project overview and @package.json for available npm/pnpm commands for this project.\n\n## Code Style Guidelines\n- Use descriptive variable names\n- Follow existing patterns in the codebase\n- Extract complex conditions into meaningful boolean variables\n\n## Architecture Notes\nAdd important architectural decisions and patterns here.\n\n## Common Workflows\nDocument frequently used workflows and commands here.\n","utf-8"),n}async function getMemoryContent(t){try{const n=process.cwd(),r=await loadAllMemories(n,t);if(0===r.size)return null;const s=[],o=getEnterpriseMemoryPath(),i=getUserMemoryPath(),a=[e.join(n,"AGENTS.md"),e.join(n,".commandcode","AGENTS.md")];r.has(o)&&s.push(`# Memory from: ${o}\n\n${r.get(o)}`),r.has(i)&&s.push(`# Memory from: ${i}\n\n${r.get(i)}`);for(const e of a)if(r.has(e)){s.push(`# Memory from: ${e}\n\n${r.get(e)}`);break}for(const[e,t]of r)e===o||e===i||a.includes(e)||s.push(`# Memory from: ${e}\n\n${t}`);return s.join("\n\n---\n\n")}catch(e){return null}}var ew,tw,nw,rw,sw,ow,iw,aw=__esm({"src/utils/memory.ts"(){Ht(),Kt(),__name(getEnterpriseMemoryPath,"getEnterpriseMemoryPath"),__name(getUserMemoryPath,"getUserMemoryPath"),__name(getProjectMemoryPaths,"getProjectMemoryPaths"),__name(discoverMemoryFiles,"discoverMemoryFiles"),__name(loadMemoryFile,"loadMemoryFile"),__name(getCodeBlockRegex,"getCodeBlockRegex"),__name(getImportRegex,"getImportRegex"),__name(processImports,"processImports"),__name(loadAllMemories,"loadAllMemories"),__name(openInEditor,"openInEditor"),__name(initProjectMemory,"initProjectMemory"),__name(getMemoryContent,"getMemoryContent")}});function migrateHeader(e){const{content:t}=e;if(t.includes(ew))return t.includes(nw)?t:t.includes(tw)?t.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"").replace(ew,nw):t.replace(ew,nw);let n=t;return n.includes(tw)&&(n=n.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"")),ow.test(n)?n=n.replace(ow,`$1${nw}`):iw.test(n)&&(n=n.replace(iw,`$1${nw}`)),n}var lw=__esm({"src/commands/taste/utils/header-migration.ts"(){Ht(),nw=`${ew="# Taste (Continuously Learned by [CommandCode][cmd])"}\n\n${tw="[cmd]: https://commandcode.ai/"}`,rw="# Taste (Continuously Learned by CommandCode)",sw="# Taste (Continuously Learned by CommandCode.ai)",ow=/^(\s*)# Taste \(Continuously Learned by CommandCode\)(?!\.ai)/,iw=/^(\s*)# Taste \(Continuously Learned by CommandCode\.ai\)/,__name(migrateHeader,"migrateHeader")}});async function getTasteContent(){try{const t=process.cwd(),n=e.join(t,".commandcode","taste","taste.md");if(!C(n))return null;const r=await D.readFile(n,"utf-8"),s=r.trim();return s&&s!==nw&&s!==ew&&s!==sw&&s!==rw?r:null}catch(e){return null}}var cw,uw=__esm({"src/utils/taste/get-taste-content.ts"(){Ht(),Kt(),lw(),__name(getTasteContent,"getTasteContent")}}),dw=__esm({"src/tools/skills/types.ts"(){Ht()}});function getGlobalSkillsDir(){return t.join(w.homedir(),".commandcode","skills")}function getGlobalAgentsCompatSkillsDir(){return t.join(w.homedir(),".agents","skills")}function findGitRoot(){return walkUpToFindDir({dirName:".git"})}function walkUpToFindDir(e){const{dirName:n}=e,r=w.homedir();let s=process.cwd();for(let e=0;e<cw&&s!==r;e++){if(C(t.join(s,n)))return s;const e=t.dirname(s);if(e===s)break;s=e}}function getProjectSkillsDir(e){const n=e?.gitRoot??findGitRoot();if(n)return t.join(n,".commandcode","skills");const r=walkUpToFindDir({dirName:".commandcode"});return r?t.join(r,".commandcode","skills"):t.join(process.cwd(),".commandcode","skills")}function getProjectAgentsCompatSkillsDir(e){const n=e?.gitRoot??findGitRoot();if(n)return t.join(n,".agents","skills");const r=walkUpToFindDir({dirName:".agents"});return r?t.join(r,".agents","skills"):t.join(process.cwd(),".agents","skills")}async function resolveSkillFilePath(e){const{skillDir:n}=e,r=t.join(n,"SKILL.md");try{return await O.access(r),r}catch{}const s=t.join(n,"skill.md");try{return await O.access(s),s}catch{return null}}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await O.access(n);const e=await O.readdir(n,{withFileTypes:!0}),r=(await Promise.all(e.map(async e=>{if(e.isDirectory())return e;if(e.isSymbolicLink())try{return(await O.stat(t.join(n,e.name))).isDirectory()?e:null}catch{return null}return null}))).filter(e=>null!==e);return(await Promise.all(r.map(async e=>{try{const r=await resolveSkillFilePath({skillDir:t.join(n,e.name)});if(!r)return null;const s=await O.readFile(r,"utf-8"),{data:o}=Ne(s),i=th.parse(o);return i.name!==e.name?null:{name:i.name,description:i.description,filePath:r}}catch(e){return null}}))).filter(e=>null!==e)}catch(e){return[]}}function mergeSkillSummaries(e){const{primary:t,secondary:n}=e,r=new Set(t.map(e=>e.name)),s=n.filter(e=>!r.has(e.name));return[...t,...s]}async function loadAllSkillSummaries(){const e=findGitRoot(),[t,n,r,s]=await Promise.all([loadSkillSummariesFromDirectory({dir:getGlobalSkillsDir()}),loadSkillSummariesFromDirectory({dir:getProjectSkillsDir({gitRoot:e})}),loadSkillSummariesFromDirectory({dir:getGlobalAgentsCompatSkillsDir()}),loadSkillSummariesFromDirectory({dir:getProjectAgentsCompatSkillsDir({gitRoot:e})})]);return{global:mergeSkillSummaries({primary:t,secondary:r}),project:mergeSkillSummaries({primary:n,secondary:s})}}var mw=__esm({"src/tools/skills/loader.ts"(){Ht(),Eh(),Kt(),__name(getGlobalSkillsDir,"getGlobalSkillsDir"),__name(getGlobalAgentsCompatSkillsDir,"getGlobalAgentsCompatSkillsDir"),cw=10,__name(findGitRoot,"findGitRoot"),__name(walkUpToFindDir,"walkUpToFindDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(getProjectAgentsCompatSkillsDir,"getProjectAgentsCompatSkillsDir"),__name(resolveSkillFilePath,"resolveSkillFilePath"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(mergeSkillSummaries,"mergeSkillSummaries"),__name(loadAllSkillSummaries,"loadAllSkillSummaries")}});function escapeXML(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function generateSkillsXML(e){const{global:n,project:r}=e,s=[...n,...r];return 0===s.length?"":`<available_skills>\n${s.map(e=>{const n=t.normalize(e.filePath);return`<skill>\n<name>\n${escapeXML(e.name)}\n</name>\n<description>\n${escapeXML(e.description)}\n</description>\n<location>\n${escapeXML(n)}\n</location>\n</skill>`}).join("\n")}\n</available_skills>`}var pw,gw,hw=__esm({"src/tools/skills/xml-generator.ts"(){Ht(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML")}}),fw=__esm({"src/tools/skills/index.ts"(){Ht(),dw(),mw(),hw()}}),yw=__esm({"src/tools/read-file/types.ts"(){Ht(),pw=f.object({absolutePath:f.string().describe("The absolute path to the file to read"),offset:f.preprocess(e=>"string"==typeof e?parseInt(e,10):e,f.number().optional()).describe("Optional line number to start reading from (0-based index)"),limit:f.preprocess(e=>"string"==typeof e?parseInt(e,10):e,f.number().optional()).describe("Optional number of lines to read")}),f.object({content:f.union([f.string(),f.instanceof(Buffer)]),contentType:f.enum(["text","binary"]),fileType:f.string(),size:f.number(),linesRead:f.number().optional()}),gw=class extends Error{static{__name(this,"FileReadError")}code;constructor(e,t){super(e),this.name="FileReadError",this.code=t}}}});function isWindowsAbsolutePath(e){return/^[a-zA-Z]:[\\\/]/.test(e)}var ww,Sw=__esm({"src/utils/index.ts"(){Ht(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath")}});async function readFileContent(t){const{absolutePath:n,offset:r,limit:s}=t;if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new gw("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=e.normalize(n);try{await D.access(o,E.constants.F_OK|E.constants.R_OK)}catch{throw new gw(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await D.stat(o)).isFile())throw new gw("Path does not point to a file","NOT_A_FILE");const i=getFileType(o),a=isBinaryFile(i);if(void 0!==r&&void 0===s||void 0===r&&void 0!==s)throw new gw("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new gw("Offset must be >= 0","INVALID_OFFSET");if(void 0!==s&&s<=0)throw new gw("Limit must be > 0","INVALID_LIMIT");try{if(a){const e=await D.readFile(o);return{fileType:i,content:e,size:e.length,contentType:"binary"}}if(void 0!==r&&void 0!==s){const e=await readTextFileLines(o,r,s);return{fileType:i,contentType:"text",content:e.content,size:Buffer.byteLength(e.content,"utf8"),linesRead:e.linesRead}}{const e=await D.readFile(o,"utf8");return{content:e,fileType:i,contentType:"text",size:Buffer.byteLength(e,"utf8")}}}catch(e){if(e instanceof gw)throw e;throw new gw(`Failed to read file: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}function getFileType(t){const n=e.extname(t).toLowerCase();return{".txt":"text",".md":"markdown",".csv":"csv",".log":"log",".xml":"xml",".html":"html",".htm":"html",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".env":"env",".js":"javascript",".ts":"typescript",".jsx":"jsx",".tsx":"tsx",".py":"python",".java":"java",".c":"c",".cpp":"cpp",".cc":"cpp",".h":"c-header",".hpp":"cpp-header",".cs":"csharp",".go":"go",".rb":"ruby",".php":"php",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".clj":"clojure",".elm":"elm",".erl":"erlang",".ex":"elixir",".exs":"elixir",".hs":"haskell",".lua":"lua",".pl":"perl",".r":"r",".dart":"dart",".f":"fortran",".f90":"fortran",".groovy":"groovy",".jl":"julia",".m":"matlab",".sh":"shell",".bash":"bash",".zsh":"zsh",".ps1":"powershell",".sql":"sql",".vue":"vue",".svelte":"svelte",".astro":"astro",".component.ts":"angular",".module.ts":"angular",".service.ts":"angular",".razor":"razor",".cshtml":"razor",".erb":"ruby-template",".mustache":"mustache",".handlebars":"handlebars",".hbs":"handlebars",".ejs":"ejs",".pug":"pug",".liquid":"liquid",".twig":"twig",...ww}[n]||"unknown"}function isBinaryFile(e){return Object.values(ww).includes(e)}async function readTextFileLines(e,t,n){const r=(await D.readFile(e,"utf8")).split(/\r?\n/),s=t,o=Math.min(s+n,r.length),i=r.slice(s,o);return{content:i.join("\n"),linesRead:i.length}}var bw,Ew=__esm({"src/tools/read-file/read-file.ts"(){Ht(),Sw(),yw(),__name(readFileContent,"readFileContent"),ww={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".pdf":"application/pdf",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf"},__name(getFileType,"getFileType"),__name(isBinaryFile,"isBinaryFile"),__name(readTextFileLines,"readTextFileLines")}});function formatReadSummary({successfulReads:e,totalFiles:t}){return`Read ${e}/${t} ${1===t?"file":"files"}`}var vw=__esm({"src/tools/utils/read-summary.ts"(){Ht(),__name(formatReadSummary,"formatReadSummary"),bw=/^Read\s+(\d+)\/(\d+)\s+files?(?:,\s+(\d+)\s+lines?)?$/i}});function formatOutput(e){const t=[];if("binary"===e.contentType)return t.push(formatReadSummary({successfulReads:1,totalFiles:1})),t.push(`Binary file: ${e.fileType}`),t.join("\n");const n=e.linesRead??(e.content?String(e.content).split("\n").length:0);return t.push(`${formatReadSummary({successfulReads:1,totalFiles:1})}, ${n} ${1===n?"line":"lines"}`),"text"===e.contentType&&e.content&&t.push(String(e.content)),t.join("\n")}var Cw,kw,Tw,_w,xw,Pw=__esm({"src/tools/read-file/formatter.ts"(){Ht(),vw(),__name(formatOutput,"formatOutput")}}),Aw=__esm({"src/tools/read-file/index.ts"(){Ht(),yw(),Ew(),Pw(),Cw={name:"read_file",description:"Reads the contents of a file from the local filesystem, handling both text and binary files appropriately. \nThis tool automatically detects the file type based on extension and processes it accordingly - text files are returned as readable strings while binary files return metadata about the file type and size. \nFor large text files, you can optionally read specific line ranges using the offset and limit parameters to avoid loading the entire file into memory. \nThe tool validates that the provided path is absolute and that the file exists and is readable before attempting to read it. \nIt should be used when you need to examine file contents, verify file existence, or extract specific portions of text files for analysis or processing.",input_schema:{type:"object",properties:{absolutePath:{type:"string",description:'The absolute path to the file to read. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). Relative paths like "./file.txt" or "../file.txt" are not accepted. The file must exist and be readable by the current process.'},offset:{type:"number",description:"The line number to start reading from (0-based index, where 0 is the first line). This parameter must be used together with the limit parameter for reading specific line ranges. Cannot be negative. Use this when you need to read a specific section of a large file without loading the entire content."},limit:{type:"number",description:"The maximum number of lines to read starting from the offset. Must be a positive integer and used together with the offset parameter. This helps manage memory usage when dealing with large files by reading only the necessary portion."}},required:["absolutePath"]},execute:__name(async e=>{try{const t=pw.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading file"}},"execute")}}}),Iw=__esm({"src/tools/edit-file/types.ts"(){Ht(),kw=f.object({filePath:f.string().describe("The absolute path to the file to edit"),oldValue:f.string().describe("The text to replace"),newValue:f.string().describe("The new text to insert"),replacementCount:f.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:f.boolean().optional().describe("Whether to replace all occurrences (default: false)")}),f.object({path:f.string(),replacementsCount:f.number(),oldContent:f.string(),newContent:f.string()}),f.object({name:f.string(),message:f.string(),code:f.string().optional()})}}),Nw=__esm({"src/lib/checkpoints/types.ts"(){Ht(),Tw=f.object({backupFileName:f.string().nullable(),version:f.number().int().positive(),backupTime:f.string().datetime()}),_w=f.object({messageId:f.string().uuid(),trackedFileBackups:f.record(f.string(),Tw),timestamp:f.string().datetime()}),f.object({type:f.literal("file-history-snapshot"),messageId:f.string().uuid(),snapshot:_w,isSnapshotUpdate:f.boolean()}),f.object({maxFileSize:f.number().int().positive().default(10485760),retentionDays:f.number().int().positive().default(30)}),xw=class extends Error{static{__name(this,"CheckpointError")}code;constructor(e,t){super(e),this.name="CheckpointError",this.code=t}}}});function getPathHash(e){const{filePath:t}=e;return`${G.createHash("sha256").update(t).digest("hex").slice(0,16)}-${t.length}`}function getBackupFileName(e){const{filePath:t,version:n}=e;return`${getPathHash({filePath:t})}@v${n}`}function getCommandCodeBasePath(){return t.join(w.homedir(),".commandcode")}function getFileHistoryPath(e){const{sessionId:n}=e;return t.join(getCommandCodeBasePath(),"file-history",n)}function getBackupFilePath(e){const{sessionId:n,backupFileName:r}=e;return t.join(getFileHistoryPath({sessionId:n}),r)}async function getAvailableDiskSpace(e){const{targetPath:t}=e;try{const e=await O.statfs(t);return e.bavail*e.bsize}catch{return-1}}async function hasEnoughDiskSpace(e){const{fileSizeBytes:t,targetPath:n}=e,r=2*t,s=await getAvailableDiskSpace({targetPath:n});return-1===s||s>=r}async function ensureDirectoryExists(e){const{dirPath:t}=e;await O.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await O.writeFile(r,n);const e=await O.stat(r),s="string"==typeof n?Buffer.byteLength(n,"utf-8"):n.length;if(e.size!==s)throw new Error(`Write verification failed: expected ${s} bytes, got ${e.size}`);await O.rename(r,t)}catch(e){try{await O.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await O.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await O.access(t),!0}catch{return!1}}function getCurrentTimestamp(){return(new Date).toISOString()}function getRelativeTimeString(e){const{timestamp:t}=e,n=Date.now()-new Date(t).getTime(),r=Math.floor(n/1e3),s=Math.floor(r/60),o=Math.floor(s/60),i=Math.floor(o/24);return i>0?`${i}d ago`:o>0?`${o}h ago`:s>0?`${s}m ago`:"just now"}function getFileName(e){const{filePath:n}=e;return t.basename(n)}function isWithinRetentionPeriod(e){const{timestamp:t,retentionDays:n}=e,r=new Date(t).getTime();return Date.now()-r<=24*n*60*60*1e3}var Rw,$w,Mw,Lw,Dw=__esm({"src/lib/checkpoints/utils.ts"(){Ht(),Kt(),__name(getPathHash,"getPathHash"),__name(getBackupFileName,"getBackupFileName"),__name(getCommandCodeBasePath,"getCommandCodeBasePath"),__name(getFileHistoryPath,"getFileHistoryPath"),__name(getBackupFilePath,"getBackupFilePath"),__name(getAvailableDiskSpace,"getAvailableDiskSpace"),__name(hasEnoughDiskSpace,"hasEnoughDiskSpace"),__name(ensureDirectoryExists,"ensureDirectoryExists"),__name(atomicWriteFile,"atomicWriteFile"),__name(getFileSizeBytes,"getFileSizeBytes"),__name(fileExists,"fileExists"),__name(getCurrentTimestamp,"getCurrentTimestamp"),__name(getRelativeTimeString,"getRelativeTimeString"),__name(getFileName,"getFileName"),__name(isWithinRetentionPeriod,"isWithinRetentionPeriod")}}),Ow=__esm({"src/lib/checkpoints/file-history.ts"(){Ht(),Nw(),Dw(),Cs(),Rw={maxFileSize:10485760,retentionDays:30},$w=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...Rw,...n},this.status={enabled:!0,pausedReason:null,pausedAt:null},this.trackedState={files:new Map,versions:new Map},this.noticeDismissed=!1}getStatus(){return{...this.status}}getTrackedState(){return{files:new Map(this.trackedState.files),versions:new Map(this.trackedState.versions)}}shouldShowPausedNotice(){return null!==this.status.pausedReason&&!this.noticeDismissed}dismissPausedNotice(){this.noticeDismissed=!0}async checkAndResumeIfPossible(){if("disk_full"===this.status.pausedReason){const e=getFileHistoryPath({sessionId:this.sessionId});await hasEnoughDiskSpace({fileSizeBytes:104857600,targetPath:e})&&(this.status.pausedReason=null,this.status.pausedAt=null,this.noticeDismissed=!1)}}async backupFile(e){const{filePath:t}=e;if(await this.checkAndResumeIfPossible(),this.status.pausedReason)return{success:!1,backup:null,skipped:!0,skipReason:"disk_full"};if(!await fileExists({filePath:t})){const e=1,n={backupFileName:null,version:e,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,n),this.trackedState.versions.set(t,e),{success:!0,backup:n,skipped:!0,skipReason:"new_file"}}const n=await getFileSizeBytes({filePath:t});if(n>this.config.maxFileSize)return{success:!1,backup:null,skipped:!0,skipReason:"file_too_large"};const r=getFileHistoryPath({sessionId:this.sessionId});if(!await hasEnoughDiskSpace({fileSizeBytes:n,targetPath:r}))return this.status.pausedReason="disk_full",this.status.pausedAt=getCurrentTimestamp(),this.noticeDismissed=!1,{success:!1,backup:null,skipped:!0,skipReason:"disk_full"};try{const e=await O.readFile(t),n=(this.trackedState.versions.get(t)||0)+1,s=getBackupFileName({filePath:t,version:n});await ensureDirectoryExists({dirPath:r});const o=getBackupFilePath({sessionId:this.sessionId,backupFileName:s});await atomicWriteFile({filePath:o,content:e});const i={backupFileName:s,version:n,backupTime:getCurrentTimestamp()};return this.trackedState.files.set(t,i),this.trackedState.versions.set(t,n),{success:!0,backup:i,skipped:!1}}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"file_backup_failed"}),context:{component:ys.FILE_HISTORY,heading:"File backup failed"}}),{success:!1,backup:null,skipped:!0,skipReason:"read_error"}}}async restoreFile(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName)return void(await fileExists({filePath:t})&&await O.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new xw(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:ys.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const s=await O.readFile(r);await atomicWriteFile({filePath:t,content:s})}async verifyRestoreOperation(e){const{filePath:t,backup:n}=e;if(null===n.backupFileName){if(!await fileExists({filePath:t}))return{canRestore:!0};try{return await O.access(t,O.constants.W_OK),{canRestore:!0}}catch{return{canRestore:!1,error:"Cannot delete file: permission denied"}}}const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});return await fileExists({filePath:r})?{canRestore:!0}:{canRestore:!1,error:`Backup file missing: ${n.backupFileName}`}}getTrackedFileBackups(){const e={};for(const[t,n]of this.trackedState.files)e[t]=n;return e}loadTrackedState(e){const{trackedFileBackups:t}=e;this.trackedState.files.clear(),this.trackedState.versions.clear();for(const[e,n]of Object.entries(t))this.trackedState.files.set(e,n),this.trackedState.versions.set(e,n.version)}async cleanupOrphanedBackups(e){const{referencedBackups:t}=e,n=getFileHistoryPath({sessionId:this.sessionId});let r=0;try{const e=await O.readdir(n);for(const s of e)if(!s.endsWith(".tmp")&&!t.has(s))try{await O.unlink(`${n}/${s}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await O.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}}}}),Fw=__esm({"src/lib/checkpoints/checkpoint-manager.ts"(){Ht(),Ow(),Dw(),hs(),Cs(),Mw=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new $w({sessionId:t,config:r}),this.sessionStore=n||null,this.snapshots=[],this.config={maxFileSize:r?.maxFileSize||10485760,retentionDays:r?.retentionDays||30}}getFileHistoryManager(){return this.fileHistoryManager}setSessionStore(e){const{sessionStore:t}=e;this.sessionStore=t}async backupFile(e){const{filePath:t}=e,n=await this.fileHistoryManager.backupFile({filePath:t,sessionId:this.fileHistoryManager.getSessionId()});if(n.success&&this.snapshots.length>0){const e=this.snapshots[this.snapshots.length-1];e.trackedFileBackups=this.fileHistoryManager.getTrackedFileBackups(),this.sessionStore&&this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0}).catch(()=>{})}return{success:n.success,backup:n.backup}}async createSnapshot(e){const{messageId:t}=e,n={messageId:t,trackedFileBackups:{},timestamp:getCurrentTimestamp()};return this.snapshots.push(n),this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:n,isUpdate:!1}),n}async updateCurrentSnapshot(){if(0===this.snapshots.length)return;const e=this.snapshots[this.snapshots.length-1],t=this.fileHistoryManager.getTrackedFileBackups(),n=this.snapshots.length>1?this.snapshots[this.snapshots.length-2]:null,r=n?.trackedFileBackups||{},s={};for(const[e,n]of Object.entries(t)){const t=r[e];(!t||t.version!==n.version||t.backupFileName!==n.backupFileName)&&(s[e]=n)}e.trackedFileBackups=s,this.sessionStore&&await this.sessionStore.saveSnapshot({snapshot:e,isUpdate:!0})}listCheckpoints(){const e=[];for(let t=0;t<this.snapshots.length;t++){const n=this.snapshots[t];t>0&&this.snapshots[t-1];let r="";if(this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:n.messageId}),t=this.sessionStore.getMessageAtIndex({index:e});t&&(r=truncateString({text:t.content,maxChars:100}))}const s=Object.keys(n.trackedFileBackups);let o=null;if(s.length>0){const e=s[0];n.trackedFileBackups[e]&&(o={additions:0,deletions:0,fileName:getFileName({filePath:e})})}e.push({messageId:n.messageId,timestamp:n.timestamp,userPrompt:r,fileCount:Object.keys(n.trackedFileBackups).length,filesModified:s,codeChanges:o})}return e.sort((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime())}getSnapshot(e){const{messageId:t}=e;return this.snapshots.find(e=>e.messageId===t)||null}async restore(e){const{messageId:t,mode:n}=e;if(!this.getSnapshot({messageId:t}))return{success:!1,error:"Snapshot not found",filesRestored:0,filesDeleted:0,messagesRemoved:0};const r=this.snapshots.findIndex(e=>e.messageId===t);let s=0,o=0,i=0;if("files"===n||"both"===n){const e=[];for(let t=this.snapshots.length-1;t>=r;t--){const n=this.snapshots[t];for(const[t,r]of Object.entries(n.trackedFileBackups))e.push({filePath:t,backup:r})}const t=[];for(const n of e){const e=await this.fileHistoryManager.verifyRestoreOperation({filePath:n.filePath,backup:n.backup});e.canRestore||t.push(`${n.filePath}: ${e.error}`)}if(t.length>0)return trackError({error:sanitizeErrorForTelemetry({error:new Error(`Restore verification failed:\n${t.join("\n")}`),label:"restore_verification_failed"}),context:{component:ys.CHECKPOINT_MANAGER,heading:"Checkpoint restore verification failed","checkpoint.failures":t.length}}),{success:!1,error:`Restore verification failed:\n${t.join("\n")}`,filesRestored:0,filesDeleted:0,messagesRemoved:0};for(const t of e)await this.fileHistoryManager.restoreFile({filePath:t.filePath,backup:t.backup}),null===t.backup.backupFileName?o++:s++;const n=r>0?this.snapshots[r-1].trackedFileBackups:{};this.fileHistoryManager.loadTrackedState({trackedFileBackups:n})}if("conversation"===n||"both"===n){if(i=this.snapshots.length-r,this.sessionStore){const e=this.sessionStore.getMessageIndexById({messageId:t});await this.sessionStore.truncateMessagesAtIndex({index:e}),await this.sessionStore.deleteSnapshotsAfter({messageId:t,inclusive:!0})}this.snapshots=this.snapshots.slice(0,r)}const a=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&a.add(t.backupFileName);for(const e of Object.values(this.fileHistoryManager.getTrackedFileBackups()))e.backupFileName&&a.add(e.backupFileName);return await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:a}),{success:!0,filesRestored:s,filesDeleted:o,messagesRemoved:i}}async loadSnapshots(){if(this.sessionStore&&(this.snapshots=await this.sessionStore.loadSnapshots(),this.snapshots.length>0)){const e=this.snapshots[this.snapshots.length-1];this.fileHistoryManager.loadTrackedState({trackedFileBackups:e.trackedFileBackups})}}isCheckpointingPaused(){return null!==this.fileHistoryManager.getStatus().pausedReason}getPausedReason(){return this.fileHistoryManager.getStatus().pausedReason}shouldShowPausedNotice(){return this.fileHistoryManager.shouldShowPausedNotice()}dismissPausedNotice(){this.fileHistoryManager.dismissPausedNotice()}getSessionId(){return this.fileHistoryManager.getSessionId()}async runCleanup(){let e=0,t=0;const n=this.snapshots.filter(e=>isWithinRetentionPeriod({timestamp:e.timestamp,retentionDays:this.config.retentionDays}));e=this.snapshots.length-n.length,this.snapshots=n;const r=new Set;for(const e of this.snapshots)for(const t of Object.values(e.trackedFileBackups))t.backupFileName&&r.add(t.backupFileName);return t=await this.fileHistoryManager.cleanupOrphanedBackups({referencedBackups:r}),{snapshotsRemoved:e,filesRemoved:t}}getSnapshotCount(){return this.snapshots.length}hasCheckpoints(){return this.snapshots.length>0}}}});function initializeCheckpointService(e){const{sessionId:t}=e;return Lw=new Mw({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return Lw?Lw.backupFile({filePath:t}):{success:!0,backup:null}}var qw=__esm({"src/lib/checkpoints/checkpoint-service.ts"(){Ht(),Fw(),Lw=null,__name(initializeCheckpointService,"initializeCheckpointService"),__name(backupFileBeforeEdit,"backupFileBeforeEdit")}}),jw=__esm({"src/lib/checkpoints/index.ts"(){Ht(),Nw(),Ow(),Fw(),Dw(),qw()}});function createFileEditError(e,t){const n=new Error(e);return n.name="FileEditError",n.code=t,n}async function editFile(t){const{filePath:n,oldValue:r,newValue:s,replaceAll:o=!1,replacementCount:i=1}=t;if(!n)throw createFileEditError("filePath is required","INVALID_PATH");if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw createFileEditError("filePath must be an absolute path (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");if(!r)throw createFileEditError("oldValue is required","INVALID_INPUT");if(null==s)throw createFileEditError("newValue is required","INVALID_INPUT");if(!o&&i<1)throw createFileEditError("replacementCount must be at least 1","INVALID_COUNT");try{await I.access(n,N.F_OK|N.R_OK|N.W_OK)}catch(e){throw createFileEditError(`File not found or not accessible: ${n}`,"FILE_ACCESS_ERROR")}let a;try{const e=await readFileContent({absolutePath:n});if("binary"===e.contentType)throw createFileEditError("Cannot edit binary files. Only text files are supported.","BINARY_FILE_ERROR");a=e.content}catch(e){if(e&&"object"==typeof e&&"name"in e&&"FileEditError"===e.name)throw e;throw createFileEditError(`Failed to read file: ${e instanceof Error?e.message:"Unknown error"}`,"READ_ERROR")}const l=(a.match(new RegExp(escapeRegExp(r),"g"))||[]).length;if(0===l)throw createFileEditError("No occurrences of the specified text were found in the file","NO_MATCHES");let u,d;if(o)u=l;else if(u=i,u>l)throw createFileEditError(`Expected ${u} replacements, but only found ${l} occurrences`,"INSUFFICIENT_MATCHES");let m=0;if(o||u===l)d=a.split(r).join(s),m=l;else{d=a;for(let e=0;e<u;e++){const e=d.indexOf(r);-1!==e&&(d=d.substring(0,e)+s+d.substring(e+r.length),m++)}}if(0===m)throw createFileEditError("No replacements were made","NO_REPLACEMENTS");try{return await backupFileBeforeEdit({filePath:n}),await I.writeFile(n,d,"utf-8"),{path:n,replacementsCount:m,oldContent:a,newContent:d}}catch(e){throw createFileEditError(`Failed to write file: ${e instanceof Error?e.message:"Unknown error"}`,"WRITE_ERROR")}}function escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Bw=__esm({"src/tools/edit-file/edit-file.ts"(){Ht(),Ew(),Sw(),Iw(),jw(),__name(createFileEditError,"createFileEditError"),__name(editFile,"editFile"),__name(escapeRegExp,"escapeRegExp")}});function formatOutput2(e){const t=1!==e.replacementsCount?"s":"",n=`Edited ${e.path} (${e.replacementsCount} replacement${t})`;return e.newContent.length<500?`${n}\n\n${e.newContent}`:n}var Uw,zw,Ww,Gw=__esm({"src/tools/edit-file/formatter.ts"(){Ht(),__name(formatOutput2,"formatOutput")}}),Hw=__esm({"src/tools/edit-file/index.ts"(){Ht(),Iw(),Bw(),Gw(),Uw={name:"edit_file",description:"Performs precise text replacements in files by finding and replacing exact string matches, similar to a str_replace operation.\nThis tool is designed for making targeted edits to text files, allowing you to replace specific occurrences of text with new content while preserving the rest of the file unchanged.\nIt validates that the file exists, is accessible, and is a text file (not binary) before attempting any modifications, ensuring data integrity.\nThe tool can replace a single occurrence, a specific number of occurrences, or all occurrences of the target text based on your requirements.\nIt should be used when you need to fix typos, update variable names, modify configuration values, or make any other precise text changes in code or text files.\nThe tool will report the exact number of replacements made and will fail safely if the target text is not found or if multiple matches exist when expecting a unique match.",input_schema:{type:"object",properties:{filePath:{type:"string",description:"The absolute path to the file to edit. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). The file must exist and have write permissions. Binary files cannot be edited with this tool."},oldValue:{type:"string",description:"The exact text string to search for in the file. This must match exactly including whitespace, indentation, and line breaks. The match is case-sensitive. If multiple matches exist and replaceAll is false, only the first occurrence from the beginning of the file will be replaced."},newValue:{type:"string",description:"The replacement text that will be inserted in place of each matched occurrence of oldValue. Can be an empty string to effectively delete the matched text. Preserves any surrounding whitespace and formatting."},replaceAll:{type:"boolean",description:"When true, replaces all occurrences of oldValue in the file. When false (default), replaces only the number of occurrences specified by replacementCount. Use true when you need to update all instances, such as renaming a variable throughout a file."},replacementCount:{type:"number",description:"The number of occurrences to replace when replaceAll is false. Default is 1. Must be a positive integer. If set higher than the actual number of occurrences, the tool will report an error. Use this for controlled, partial replacements."}},required:["filePath","oldValue","newValue"]},execute:__name(async e=>{try{const t=kw.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while editing file"}},"execute")}}}),Qw=__esm({"src/tools/read-directory/types.ts"(){Ht(),zw=f.object({path:f.string().describe("The absolute path to the directory to read"),exclude:f.array(f.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:f.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")}),f.object({files:f.array(f.string()),directories:f.array(f.string())}),Ww=class extends Error{static{__name(this,"DirectoryReadError")}code;constructor(e,t){super(e),this.name="DirectoryReadError",this.code=t}}}});async function readDirectory(t){const{path:n,exclude:r=[],respectGitIgnore:s=!1}=t;if(!e.isAbsolute(n))throw new Ww("Path must be absolute, not relative","INVALID_PATH");try{if(!(await D.stat(n)).isDirectory())throw new Ww("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof Ww)throw e;throw new Ww(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await D.readdir(n);let o=[];s&&(o=await loadGitIgnorePatterns(n));const i=[...r,...o],a=[],l=[];for(const r of t){if(shouldIgnoreEntry(r,i))continue;const t=e.join(n,r);try{const e=await D.stat(t);e.isDirectory()?l.push(r):e.isFile()&&a.push(r)}catch(e){console.warn(`Warning: Could not access ${t}`)}}return{files:a.sort(),directories:l.sort()}}catch(e){if(e instanceof Ww)throw e;throw new Ww(`Error reading directory: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}async function loadGitIgnorePatterns(t){const n=[];try{if(!await isInGitRepository(t))return n;let r=e.resolve(t);const s=await findGitRoot2(t);for(;r&&isWithinGitRoot(r,s);){const t=e.join(r,".gitignore");try{const e=(await D.readFile(t,"utf-8")).split(/\r?\n/).map(e=>e.trim()).filter(e=>e&&!e.startsWith("#"));n.push(...e)}catch(e){}const s=e.dirname(r);if(s===r)break;r=s}}catch(e){}return n}async function isInGitRepository(e){try{return null!==await findGitRoot2(e)}catch{return!1}}async function findGitRoot2(t){let n=e.resolve(t);for(;;){try{const t=e.join(n,".git");if((await D.stat(t)).isDirectory())return n}catch{}const t=e.dirname(n);if(t===n)throw new Error("Not in a git repository");n=t}}function isWithinGitRoot(t,n){const r=e.resolve(t),s=e.resolve(n);return"win32"===process.platform?r.toLowerCase().startsWith(s.toLowerCase()):r.startsWith(s)}function shouldIgnoreEntry(e,t){for(const n of t)if(Re(e,n))return!0;return!1}var Vw=__esm({"src/tools/read-directory/read-directory.ts"(){Ht(),Qw(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot2,"findGitRoot"),__name(isWithinGitRoot,"isWithinGitRoot"),__name(shouldIgnoreEntry,"shouldIgnoreEntry")}});function formatOutput3(e){const t=e.directories.length+e.files.length,n=[];return n.push(`Found ${t} items (${e.directories.length} dirs, ${e.files.length} files)`),e.directories.length>0&&(n.push("Directories:"),e.directories.forEach(e=>n.push(` ${e}/`))),e.files.length>0&&(n.push("Files:"),e.files.forEach(e=>n.push(` ${e}`))),0===t&&n.push("(empty directory)"),n.join("\n")}var Kw,Yw,Jw=__esm({"src/tools/read-directory/formatter.ts"(){Ht(),__name(formatOutput3,"formatOutput")}}),Xw=__esm({"src/tools/read-directory/index.ts"(){Ht(),Qw(),Vw(),Jw(),Kw={name:"read_directory",description:"Lists the contents of a directory, providing separate arrays of files and subdirectories found at the specified path.\nThis tool is essential for exploring project structure, discovering available files, and understanding directory organization before performing operations on specific files.\nIt automatically respects .gitignore patterns by default when operating within git repositories, ensuring you don't see files that are intentionally excluded from version control.\nThe tool supports custom exclusion patterns using glob syntax, allowing you to filter out specific files or directories based on your needs, such as build artifacts or temporary files.\nResults are always sorted alphabetically for consistent output, making it easier to locate specific items in large directories.\nIt should be used when you need to explore a directory's contents, verify file existence, or understand project structure before performing file operations.",input_schema:{type:"object",properties:{path:{type:"string",description:"The absolute path to the directory to read. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). The directory must exist and be accessible. Returns an error if the path points to a file instead of a directory."},exclude:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to exclude from results. Uses minimatch syntax for pattern matching. Examples: ["*.log", "temp*", "**/*.tmp"] would exclude all log files, anything starting with "temp", and all .tmp files in any subdirectory. Patterns are applied in addition to any .gitignore rules.'}},required:["path"]},execute:__name(async e=>{try{const t=zw.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading directory"}},"execute")}}}),Zw=__esm({"src/tools/write-file/types.ts"(){Ht(),Yw=f.object({filePath:f.string().describe("The absolute path where the file should be written"),content:f.string().describe("The content to write to the file")}),f.object({success:f.boolean(),message:f.string(),path:f.string().optional()})}});async function writeFile2({filePath:e,content:n}){const s=e.startsWith("~/")?t.join(w.homedir(),e.slice(2)):e;if(!u(s))throw new Error(`Invalid file path: '${s}'. Only absolute paths are supported.`);try{const e=r(s);return C(e)||await z(e,{recursive:!0}),await backupFileBeforeEdit({filePath:s}),await q(s,n,"utf-8"),{path:s,bytesWritten:Buffer.byteLength(n,"utf-8")}}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";throw new Error(`Failed to write file '${s}': ${t}`)}}var eS=__esm({"src/tools/write-file/write-file.ts"(){Ht(),jw(),__name(writeFile2,"writeFile")}});function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}var tS,nS,rS,sS,oS,iS=__esm({"src/tools/write-file/formatter.ts"(){Ht(),__name(formatOutput4,"formatOutput")}}),aS=__esm({"src/tools/write-file/index.ts"(){Ht(),Zw(),eS(),iS(),tS={name:"write_file",description:"Creates or overwrites a file with the specified content at the given absolute path, automatically creating any necessary parent directories.\nThis tool handles the complete file writing process, including directory creation, making it ideal for generating new files, saving processed output, or creating configuration files.\nIf the file already exists, it will be completely overwritten with the new content - the previous contents will be lost, so use with caution on existing files.\nThe tool automatically creates any missing parent directories in the path, eliminating the need to manually ensure directory structure exists before writing.\nIt should be used when you need to create new files, save generated content, write configuration files, or output processed data to the filesystem.\nAll content is written as UTF-8 encoded text, making it suitable for source code, configuration files, documentation, and other text-based formats.",input_schema:{type:"object",properties:{filePath:{type:"string",description:"The absolute path where the file should be written. Must be a complete path starting from the root directory (/ on Unix/Linux/macOS or C:\\ on Windows). If parent directories do not exist, they will be created automatically. Existing files at this path will be overwritten without warning."},content:{type:"string",description:"The text content to write to the file. Can be any UTF-8 string including multi-line text, JSON, XML, source code, or any other text format. Empty strings are valid and will create an empty file. Line endings are preserved as provided."}},required:["filePath","content"]},execute:__name(async e=>{try{const t=Yw.parse(e),n=await writeFile2(t);return formatOutput4({success:!0,message:`Successfully wrote ${n.bytesWritten} bytes to file\n`,path:n.path})}catch(e){return formatOutput4({success:!1,message:e instanceof Error?e.message:"Unknown error occurred"})}},"execute")}}}),lS=__esm({"src/tools/read-multiple-files/types.ts"(){Ht(),nS=f.object({include:f.array(f.string()).describe("Array of glob patterns to include files"),exclude:f.array(f.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:f.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:f.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:f.string().optional().describe("Base directory for relative paths. Default: current working directory")}),rS=f.object({filePath:f.string(),content:f.string(),fileType:f.string(),size:f.number()}),f.object({content:f.string(),filesRead:f.array(f.string()),errors:f.array(f.object({file:f.string(),error:f.string()})),fileDetails:f.array(rS)}),sS=class extends Error{static{__name(this,"MultipleFilesReadError")}code;constructor(e,t){super(e),this.name="MultipleFilesReadError",this.code=t}}}});async function findMatchingFiles({include:e,exclude:t,gitIgnore:n,targetDirectory:r}){const s=new Set;for(const o of e)try{(await $e(o,{cwd:r,ignore:t,dot:!1,nodir:!0,absolute:!1,...n?{gitignore:!0}:{}})).forEach(e=>s.add(e))}catch(e){console.warn(`Warning: Failed to process pattern "${o}": ${e}`)}return Array.from(s).sort()}function processFileResult({filePath:e,content:t}){const n={filePath:e,fileType:t.fileType,size:t.size,content:""};return void 0!==t.content&&("text"===t.contentType?n.content=String(t.content):n.content=`[Binary file: ${t.fileType}, ${t.size} bytes]`),n}async function readMultipleFiles(e){const{include:n,exclude:r=[],gitIgnore:s=!0,defaultExclude:o=!0,targetDirectory:i=process.cwd()}=e;if(!n||0===n.length)throw new sS("At least one include pattern must be provided","NO_PATTERNS");const a=t.resolve(i),l={content:"",filesRead:[],fileDetails:[],errors:[]};try{const e=[...r];o&&e.push(...oS);const i=await findMatchingFiles({include:n,exclude:e,gitIgnore:s,targetDirectory:a});for(const e of i)try{const n=t.resolve(a,e),r=await readFileContent({absolutePath:n}),s=processFileResult({content:r,filePath:e});l.fileDetails.push(s),l.content+=`\n// File: ${e} (${r.fileType})\n`,l.content+=s.content,l.content+="\n",l.filesRead.push(e)}catch(t){const n=t instanceof Error?t.message:String(t);l.errors.push({file:e,error:n}),l.fileDetails.push({filePath:e,content:"",fileType:"unknown",size:0})}return l}catch(e){if(e instanceof sS)throw e;throw new sS(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}var cS=__esm({"src/tools/read-multiple-files/read-multiple-files.ts"(){Ht(),Ew(),lS(),oS=["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/.svn/**","**/.hg/**","**/coverage/**","**/*.log","**/tmp/**","**/temp/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.cache"],__name(findMatchingFiles,"findMatchingFiles"),__name(processFileResult,"processFileResult"),__name(readMultipleFiles,"readMultipleFiles")}});function getReadSummary(e){const t=e.fileDetails.length,n=e.filesRead.length,r=e.errors.length,{fileTypesCounts:s}=e.fileDetails.reduce((e,t)=>(e.fileTypesCounts[t.fileType]=(e.fileTypesCounts[t.fileType]||0)+1,e),{fileTypesCounts:{}});return{totalFiles:t,successfulReads:n,failedReads:r,fileTypesCounts:s,contentLength:e.content.length}}function formatOutput5(e){const t=getReadSummary(e),n=[];if(n.push(formatReadSummary(t)),e.errors.length>0){n.push("Errors:");for(const t of e.errors)n.push(` - ${t.file}: ${t.error}`)}return n.push("--- File Contents ---"),n.push(e.content),n.join("\n")}var uS,dS,mS,pS,gS,hS,fS,yS=__esm({"src/tools/read-multiple-files/formatter.ts"(){Ht(),vw(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput")}}),wS=__esm({"src/tools/read-multiple-files/index.ts"(){Ht(),lS(),cS(),yS(),uS={name:"read_multiple_files",description:"Reads multiple files simultaneously based on glob patterns, returning their contents concatenated with clear file headers for easy identification.\nThis tool is designed for bulk file operations, such as analyzing all source files in a project, reviewing multiple configuration files, or processing sets of related documents.\nIt automatically excludes common non-source directories like node_modules and build folders by default, and respects .gitignore patterns to avoid processing files that shouldn't be analyzed.\nThe tool handles both text and binary files appropriately - text files have their content included while binary files are noted with their type and size information.\nEach file's content is clearly separated with a header showing the file path and type, making it easy to distinguish between different files in the concatenated output.\nIt should be used when you need to analyze multiple files at once, search across multiple files for patterns, or gather content from various sources for processing or review.\nThe tool provides detailed feedback including which files were successfully read, any errors encountered, and statistics about the operation.",input_schema:{type:"object",properties:{include:{type:"array",items:{type:"string"},description:'Array of glob patterns to match files for reading. Uses standard glob syntax with support for wildcards (* for single level, ** for recursive). Examples: ["**/*.ts"] matches all TypeScript files, ["src/**/*.js", "lib/**/*.js"] matches JavaScript files in src and lib directories. At least one pattern must be provided.'},exclude:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to exclude files from reading. Applied after include patterns. Examples: ["**/*.test.ts", "**/*.spec.js"] excludes test files, ["**/generated/**"] excludes generated directories. These patterns are additive with default exclusions and .gitignore rules.'},defaultExclude:{type:"boolean",description:"Whether to apply default exclusions for common non-source directories and files. Default is true. When enabled, automatically excludes: node_modules, dist, build, .git, coverage, tmp, temp, .DS_Store, *.log, *.tmp, *.cache, and other common build artifacts. Set to false to read all matching files regardless of common conventions."},gitIgnore:{type:"boolean",description:"Whether to respect .gitignore files when matching patterns. Default is true. When enabled, any files or directories listed in .gitignore files will be excluded from results. Useful for avoiding generated files, secrets, or other intentionally untracked files. Set to false to include all files matching your patterns."},targetDirectory:{type:"string",description:"The base directory from which to resolve glob patterns. Default is the current working directory. Must be an absolute path. All include and exclude patterns will be resolved relative to this directory. Use this to scope your file search to a specific part of the filesystem."}},required:["include"]},execute:__name(async e=>{try{const t=nS.parse(e);return formatOutput5(await readMultipleFiles(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading multiple files"}},"execute")}}}),SS=__esm({"src/tools/grep/types.ts"(){Ht(),dS=f.object({pattern:f.string().min(1,"Pattern is required"),include:f.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},f.array(f.string()).optional()),directory:f.string().optional()})}});function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(t*hS));else if(Array.isArray(e))t=e.reduce((e,t)=>e+estimateTokens(t),0);else if(t=3,"string"==typeof e.content)t+=estimateTextTokens(e.content);else if(Array.isArray(e.content))for(const n of e.content)if("text"===n.type&&"text"in n)t+=estimateTextTokens(n.text);else if("image"===n.type){const e=n,r=e.image??e.source?.data??"";t+=estimateImageTokens("string"==typeof r?r.replace(/^data:[^;]+;base64,/,""):"")}else if("tool-call"===n.type){const e=n;t+=5,e.toolName&&(t+=estimateTextTokens(e.toolName)),e.input&&(t+=estimateTextTokens(JSON.stringify(e.input))*hS)}else if("tool-result"===n.type){const e=n;t+=3,e.output&&"object"==typeof e.output&&"string"==typeof e.output.value&&(t+=estimateTextTokens(e.output.value))}return Math.ceil(t)}function estimateTextTokens(e){if(!e)return 0;let t=e.length/gS;const n=.1*e.split(/\s+/).length;return Math.max(0,Math.ceil(t-n))}function estimateImageTokens(e){const t=getImageDimensions(e);return t?Math.ceil(t.width*t.height/750):Math.ceil(1228.8)}function getImageDimensions(e){try{const t=Buffer.from(e,"base64");if("89504e470d0a1a0a"===t.subarray(0,8).toString("hex")){return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}if(255===t[0]&&216===t[1])for(let e=2;e<t.length-10;e++)if(255===t[e]&&(192===t[e+1]||194===t[e+1])){const n=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:n}}}catch(e){}return null}function exceedsOutputTokenLimit(e){return estimateTokens(e)>mS}function checkToolOutputTokensLimit(e){return exceedsOutputTokenLimit(e)?fS:e}function calculateUsageFromResponse(e){return(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0)+(e.output_tokens||0)}var bS=__esm({"src/utils/tokens.ts"(){Ht(),hs(),mS=ms,pS=2e5,gS=3.5,hS=1.1,__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),fS="Results are too large. Let's try a more specific pattern to narrow it down. There's a 25K token limit on tool outputs per request.",__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse")}});function execCommand({args:e,command:t}){return new Promise((n,r)=>{const s=M(t,e,{stdio:["pipe","pipe","pipe"],cwd:process.cwd()});let o="",i="";s.stdout?.on("data",e=>{try{const t=e.toString();if(o.length+t.length>us)return i=fS,void s.kill("SIGTERM");o+=t}catch(e){i+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,s.kill("SIGTERM")}}),s.stderr?.on("data",e=>{try{const t=e.toString();if(i.length+t.length>ds)return void(i+="\n[Error output truncated: too large]");i+=t}catch(e){i+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),s.on("close",e=>{0===e?n(o):1!==e||i?r(new Error(i||`Command failed with exit code ${e}`)):n("")}),s.on("error",e=>{r(e)})})}function parseGrepLine(e){const t=e.match(/^([^:]+):(\d+):(.*)$/);if(!t)return null;const[,n,r,s]=t;return{file:n,line:parseInt(r,10),column:1,content:s.trim(),match:s.trim()}}async function grepSearchInDirectory(e){const{pattern:t,include:n}=e;if(!t)throw new Error("Pattern parameter is required");try{let e,r="rg",s=["--line-number","--color=never","--no-heading",t,"."];if(n&&n.length>0)for(const e of n)s.splice(-1,0,"--glob",e);s.splice(-1,0,"--glob","!node_modules/**"),s.splice(-1,0,"--glob","!.git/**"),s.splice(-1,0,"--glob","!.svn/**");try{e=await execCommand({args:s,command:"rg"})}catch(o){if(!(o instanceof Error&&o.message.includes("ENOENT")))throw o;if(r="grep",s=["-r","-n","--color=never","-E",t,"."],n&&n.length>0)for(const e of n)s.splice(-1,0,"--include",e);s.splice(-1,0,"--exclude-dir=node_modules"),s.splice(-1,0,"--exclude-dir=.git"),s.splice(-1,0,"--exclude-dir=.svn"),e=await execCommand({args:s,command:"grep"})}if(!e.trim())return[];const o=e.trim().split("\n"),i=[];for(const e of o){const t=parseGrepLine(e);t&&i.push(t)}return i}catch(e){if(e instanceof Error){if(e.message.includes("ENOENT"))throw new Error("Search command not found. Please ensure ripgrep (rg) or grep is installed and available in PATH.");throw e}throw new Error("Unknown error occurred during search")}}var ES=__esm({"src/tools/grep/grep.ts"(){Ht(),hs(),bS(),__name(execCommand,"execCommand"),__name(parseGrepLine,"parseGrepLine"),__name(grepSearchInDirectory,"grepSearchInDirectory")}});function formatGrepResults(e){if(0===e.length)return"No matches found";const t=e.reduce((e,t)=>(e[t.file]||(e[t.file]=[]),e[t.file].push(t),e),{}),n=[],r=e.length,s=Object.keys(t).length;n.push(`Found ${r} matches in ${s} files`);for(const[e,r]of Object.entries(t)){n.push(`\n${e} (${r.length} matches):`);for(const e of r)n.push(` Line ${e.line}: ${e.content}`)}return n.join("\n")}var vS,CS,kS,TS=__esm({"src/tools/grep/formatter.ts"(){Ht(),__name(formatGrepResults,"formatGrepResults")}}),_S=__esm({"src/tools/grep/index.ts"(){Ht(),SS(),ES(),TS(),bS(),vS={name:"grep",description:"Searches for text patterns across files in a directory using regular expressions, providing powerful pattern matching capabilities for code analysis, debugging, and content discovery.\nThis tool performs recursive searches through directory structures, examining file contents to find all occurrences of the specified pattern, making it ideal for locating specific code implementations, finding TODO comments, searching for function usage, or identifying configuration values.\nThe search uses Perl-compatible regular expressions (PCRE), supporting advanced patterns including lookaheads, lookbehinds, character classes, and quantifiers, with results showing file paths and line numbers for each match.\nFile filtering can be applied using glob patterns to search only specific file types, improving performance and relevance by focusing on the files that matter for your search.\nIt should be used when you need to find where something is defined or used in a codebase, locate specific text patterns across multiple files, verify the presence of certain code patterns, or analyze code structure and dependencies.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'The regular expression pattern to search for in file contents. Supports full PCRE syntax including special characters (\\d, \\w, \\s), quantifiers (*, +, ?, {n,m}), anchors (^, $), and groups. Special regex characters like ., *, [, ], (, ), {, }, |, \\, ^, $ must be escaped with backslash when matching literally. Examples: "TODO.*urgent" finds TODO comments marked urgent, "function\\s+\\w+\\(" finds function definitions, "import.*from.*react" finds React imports.'},include:{type:"array",items:{type:"string"},description:'Optional array of glob patterns to filter which files to search. Only files matching at least one pattern will be searched. Supports standard glob syntax: * matches any characters except /, ** matches any characters including /, ? matches single character, [abc] matches character set. Examples: ["*.ts", "*.tsx"] searches TypeScript files, ["src/**/*.js"] searches JavaScript files in src directory, ["*.{js,jsx,ts,tsx}"] searches all JavaScript/TypeScript files. If omitted, searches all files except those in .gitignore.'},directory:{type:"string",description:'Optional directory to search in, specified as a relative path from the current working directory. Cannot be an absolute path. Examples: "src" searches in src folder, "packages/core" searches in packages/core, "." or omitted searches current directory. The directory must exist and be readable. Defaults to the current working directory if not specified.'}},required:["pattern"]},execute:__name(async e=>{try{const t=dS.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?e.message===fS?e.message:`ERROR: ${e.message}`:"ERROR: Unknown error occurred while searching files"}},"execute")}}}),xS=__esm({"src/tools/glob/types.ts"(){Ht(),CS=f.object({pattern:f.string().min(1,"Pattern is required"),path:f.string().optional()}),kS=class extends Error{static{__name(this,"GlobError")}code;constructor(e,t){super(e),this.name="GlobError",this.code=t}}}});async function globSearch(e){const{pattern:n,path:r="."}=e;if(!n)throw new kS("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new kS("Search path must be within the current working directory or an added directory","INVALID_PATH");const s=await $e(n,{cwd:e,ignore:Bt,dot:!1,nodir:!0,absolute:!1,gitignore:!0}),o=await Promise.all(s.map(async n=>{const r=t.join(e,n);try{return{file:n,mtime:(await O.stat(r)).mtimeMs}}catch{return{file:n,mtime:0}}}));return o.sort((e,t)=>t.mtime-e.mtime),{files:o.map(e=>e.file),searchPath:e}}catch(e){if(e instanceof kS)throw e;if(e instanceof Error)throw new kS(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new kS("Unknown error occurred during file search","UNKNOWN_ERROR")}}var PS=__esm({"src/tools/glob/glob.ts"(){Ht(),xS(),Kt(),en(),__name(globSearch,"globSearch")}});function formatGlobResults(e){if(0===e.files.length)return"No files found matching pattern";const t=[],n=e.files.length;t.push(`Found ${n} file${1!==n?"s":""}`);for(const n of e.files)t.push(` ${n}`);return t.join("\n")}var AS,IS,NS,RS=__esm({"src/tools/glob/formatter.ts"(){Ht(),__name(formatGlobResults,"formatGlobResults")}}),$S=__esm({"src/tools/glob/index.ts"(){Ht(),xS(),PS(),RS(),AS={name:"glob",description:"Searches for files in a directory tree using glob-style path patterns, enabling fast and flexible discovery of files across codebases of any size.\nThis tool matches file paths against glob patterns such as **/*.js or src/**/*.ts, making it ideal for locating files by name, extension, or directory structure without inspecting file contents. It performs recursive traversal where applicable and efficiently handles large repositories.\nResults are returned as a list of matching file paths, sorted by modification time, allowing you to quickly identify the most recently changed or relevant files.\nFile pattern matching can be refined using inclusive or exclusive glob expressions to narrow down results, improving performance and focus when working with large or complex projects.\nIt should be used when you need to find files based on naming or path patterns, explore the structure of an unfamiliar codebase, locate configuration or entry-point files, or prepare a targeted set of files for further inspection with tools like grep.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files. Supports wildcards: * matches any characters except /, ** matches any characters including / (for recursive search), ? matches single character, [abc] matches character set, {js,ts} matches alternatives. Examples: "**/*.ts" finds all TypeScript files recursively, "src/**/*.{js,jsx}" finds JavaScript files in src directory, "*.json" finds JSON files in current directory, "**/test/**/*.spec.ts" finds test spec files.'},path:{type:"string",description:'Optional directory to search in, specified as a relative path from the current working directory. Cannot be an absolute path. Examples: "src" searches in src folder, "packages/core" searches in packages/core, "." or omitted searches current directory. The directory must exist and be readable. Defaults to the current working directory if not specified.'}},required:["pattern"]},execute:__name(async e=>{try{const t=CS.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while finding files"}},"execute")}}}),MS=__esm({"src/tools/shell-command/types.ts"(){Ht(),IS=f.object({command:f.string().min(1,"Command cannot be empty"),args:f.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},f.array(f.string()).optional()),directory:f.string().optional(),timeout:f.preprocess(e=>"string"==typeof e?parseInt(e,10):e,f.number().optional())}),NS=class extends Error{static{__name(this,"ShellCommandError")}code;exitCode;signal;stdout;stderr;duration;constructor(e,t,n,r,s,o,i){super(e),this.name="ShellCommandError",this.code=t,this.exitCode=n,this.signal=r,this.stdout=s,this.stderr=o,this.duration=i}}}});async function executeShellCommand(t){const{command:n,args:r=[],directory:s,timeout:o=3e4}=t,i=Date.now();if(!n.trim())throw new NS("Command cannot be empty","EMPTY_COMMAND");let a;if(s){if(e.isAbsolute(s))throw new NS("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");a=e.resolve(process.cwd(),s)}else a=process.cwd();try{if(!(await O.stat(a)).isDirectory())throw new NS(`Path is not a directory: ${s}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof NS)throw e;throw new NS(`Directory does not exist or is not accessible: ${s||"current directory"}`,"DIRECTORY_ACCESS_ERROR")}try{const e={cwd:a,stdio:["pipe","pipe","pipe"],shell:!0};return new Promise((t,s)=>{let a="",l="",u=!1,d=!1;const m=r.length>0?Me([n,...r]):n,g=setTimeout(()=>{if(!u){h.kill("SIGTERM");const e=Date.now()-i;s(new NS(`Command timed out after ${o}ms`,"TIMEOUT",null,"SIGTERM",a,l,e))}},o),h=M(m,[],e);h.stdout?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>us)return l=fS,d=!0,void h.kill("SIGTERM");a+=t}catch(e){l+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,h.kill("SIGTERM")}}),h.stderr?.on("data",e=>{try{const t=e.toString();if(l.length+t.length>ds)return void(l+="\n[Error output truncated: too large]");l+=t}catch(e){l+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),h.on("close",(e,n)=>{u=!0,clearTimeout(g);const r=Date.now()-i;0===e?t({stdout:a.trim(),stderr:l.trim(),exitCode:e,signal:n,duration:r}):s(new NS(d?fS:`Command failed with exit code ${e}`,d?"OUTPUT_TRUNCATED":"COMMAND_FAILED",e,n,a.trim(),l.trim(),r))}),h.on("error",e=>{u=!0,clearTimeout(g);const t=Date.now()-i;s(new NS(`Failed to start command: ${e.message}`,"START_FAILED",null,null,a.trim(),l.trim(),t))})})}catch(e){if(e instanceof NS)throw e;throw new NS(`Unexpected error: ${e instanceof Error?e.message:String(e)}`,"UNEXPECTED_ERROR")}}var LS=__esm({"src/tools/shell-command/shell-command.ts"(){Ht(),MS(),hs(),bS(),__name(executeShellCommand,"executeShellCommand")}});function formatShellCommandResult(e){const t=[];return 0===e.exitCode||null===e.exitCode||t.push(`Exit code: ${e.exitCode}`),e.signal&&t.push(`Signal: ${e.signal}`),e.stdout&&t.push(e.stdout),e.stderr&&t.push(e.stderr),t.join("\n")}var DS,OS=__esm({"src/tools/shell-command/formatter.ts"(){Ht(),__name(formatShellCommandResult,"formatShellCommandResult")}}),FS=__esm({"src/tools/shell-command/index.ts"(){Ht(),MS(),LS(),OS(),bS(),DS={name:"shell_command",description:"Executes shell commands in a controlled environment with comprehensive output capture, timeout protection, and working directory management, enabling system operations, build processes, and tool integrations.\nThis tool spawns commands as child processes with full control over execution environment, capturing both standard output and error streams while monitoring exit codes and signals, making it ideal for running build scripts, executing CLI tools, performing system operations, or integrating with external programs.\nCommands run with shell interpretation enabled for cross-platform compatibility, supporting pipes, redirections, and shell built-ins, with automatic timeout termination to prevent hanging processes from blocking execution.\nThe tool provides detailed execution results including stdout, stderr, exit codes, and execution duration, helping diagnose issues and verify successful completion of operations.\nIt should be used when you need to run build or test commands, execute system utilities, interact with CLI tools, perform file operations that require shell commands, or integrate with external programs and scripts.\nImportant: Commands execute with the permissions of the current process. Be cautious with commands that modify the filesystem or system state. Always validate and sanitize any user-provided input before including it in commands.",input_schema:{type:"object",properties:{command:{type:"string",description:'The shell command to execute. Can be any valid shell command available in the system PATH or built-in shell commands. Common commands include: "npm" for Node.js packages, "git" for version control, "ls"/"dir" for listing files, "echo" for output, "cat"/"type" for file contents. The command string is passed to the system shell (sh on Unix, cmd.exe on Windows). Special characters should be properly escaped. Cannot be empty.'},args:{type:"array",items:{type:"string"},description:'Optional array of arguments to pass to the command. Each argument is passed as a separate string and is automatically escaped for shell safety. Use this instead of including arguments in the command string for better security and cross-platform compatibility. Examples: ["install", "--save-dev", "typescript"] for npm, ["status", "--short"] for git, ["-la", "/usr"] for ls. Arguments containing spaces or special characters are automatically quoted.'},directory:{type:"string",description:'Optional working directory where the command should be executed, specified as a relative path from the current working directory. Must be a relative path (absolute paths are not allowed for security). The directory must exist and be accessible. Examples: "src" runs in src folder, "packages/core" runs in packages/core, "../sibling" runs in sibling directory. If omitted, uses the current working directory. Useful for running commands that depend on specific file locations or configurations.'},timeout:{type:"number",description:"Optional maximum time in milliseconds to wait for the command to complete before forcibly terminating it. Must be between 100 and 300000 (5 minutes). Defaults to 30000ms (30 seconds). The command process is killed with SIGTERM if it exceeds this duration. Useful for preventing long-running or hanging processes. Set higher for operations known to take time (builds, installs), lower for quick operations. Examples: 5000 for quick commands, 60000 for npm install, 120000 for large builds."}},required:["command"]},execute:__name(async e=>{try{const t=IS.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof NS){if("OUTPUT_TRUNCATED"===e.code)return[e.stdout,fS].filter(Boolean).join("\n");if(e.stdout||e.stderr){let t=`ERROR: ${e.message}`;return e.stdout&&(t+=`\nOutput:\n${e.stdout}`),e.stderr&&(t+=`\nError output:\n${e.stderr}`),t}return`ERROR: ${e.message}`}return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while executing command"}},"execute")}}});async function think(e){const{thought:t}=e;return`${t}`}var qS,jS=__esm({"src/tools/thinking/thinking.ts"(){Ht(),__name(think,"think")}}),BS=__esm({"src/tools/thinking/index.ts"(){Ht(),jS(),qS={name:"think",description:'Use this tool to think step by step about complex problems. Use first-person language: "I need to understand..." or "Let me figure out..." rather than "The user wants...". Show your reasoning process.',input_schema:{type:"object",properties:{thought:{type:"string",description:"Your step-by-step reasoning and thought process"}},required:["thought"]},execute:think}}});async function todoWrite(e){return"string"==typeof e.todos?e.todos:JSON.stringify(e.todos)}var US,zS=__esm({"src/tools/todo-write/todo-write.ts"(){Ht(),__name(todoWrite,"todoWrite")}}),WS=__esm({"src/tools/todo-write/index.ts"(){Ht(),zS(),US={name:"todo_write",description:"Create and manage a structured task list. Use this to track progress, organize complex tasks, and show thoroughness to the user. Create todos when tasks require multiple steps, are non-trivial, or when explicitly requested.",input_schema:{type:"object",properties:{todos:{type:"array",description:"The updated todo list",items:{type:"object",properties:{content:{type:"string",minLength:1,description:"The todo item content"},status:{type:"string",enum:["pending","in_progress","completed"],description:"The status of the todo item"},id:{type:"string",description:"Unique identifier for the todo item"}},required:["content","status","id"]}}},required:["todos"]},execute:todoWrite}}});async function askUserQuestion(e,t){const n=e.questions;if("string"==typeof n)try{const t=n.replace(/,\s*([}\]])/g,"$1"),r=JSON.parse(t);if(!Array.isArray(r))return JSON.stringify({error:"The questions parameter must be an array of question objects, not a single object."});e.questions=r}catch{return JSON.stringify({error:"The questions parameter could not be parsed. Please provide questions as a valid JSON array."})}if(!e.questions||0===e.questions.length)return JSON.stringify({error:"No questions provided"});for(let t=0;t<e.questions.length;t++){const n=e.questions[t];if(!n.question?.trim()||!n.header?.trim()||!n.options)return JSON.stringify({error:`Question ${t+1} is missing required fields (question, header, options)`});if(n.options.length<2||n.options.length>4)return JSON.stringify({error:`Question ${t+1} must have 2-4 options`});for(const e of n.options)if(!e.label?.trim()||!e.description?.trim())return JSON.stringify({error:`Question ${t+1} has an option with missing label or description`});n.header.length>20&&(n.header=n.header.slice(0,20).trimEnd())}if(!t?.onQuestionRequest)return JSON.stringify({error:"Question request callback not available"});if(t.abortSignal?.aborted)return JSON.stringify({error:"Interrupted by user"});try{const n=await t.onQuestionRequest(e);return t.abortSignal?.aborted?JSON.stringify({error:"Interrupted by user"}):JSON.stringify(n)}catch(e){return e instanceof Error?JSON.stringify({error:e.message}):JSON.stringify({error:"Failed to get user response"})}}var GS=__esm({"src/tools/ask-user-question/ask-user-question.ts"(){Ht(),__name(askUserQuestion,"askUserQuestion")}});function isErrorResponse(e){return"error"in e&&"string"==typeof e.error}function formatOutput6(e){const{result:t,params:n}=e;if(isErrorResponse(t))return`Error: ${t.error}`;if(!t.answers||0===t.answers.length)return"User declined to answer questions";const r=t.answers.filter(e=>e.selectedOptions&&Array.isArray(e.selectedOptions)&&e.selectedOptions.length>0);if(0===r.length)return"User declined to answer questions";const s=[];return r.forEach(e=>{let t=`Question ${e.questionIndex+1}`;n?.questions?.[e.questionIndex]&&(t=n.questions[e.questionIndex].question||t);const r=e.selectedOptions.join(", ");s.push(`${t} → ${r}`)}),s.join("\n")}var HS,QS,VS,KS=__esm({"src/tools/ask-user-question/formatter.ts"(){Ht(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput")}}),YS=__esm({"src/tools/ask-user-question/index.ts"(){Ht(),GS(),KS(),KS(),HS={name:"ask_user_question",description:'Use this tool when you need to ask the user questions during execution. This allows you to:\n1. Gather user preferences or requirements\n2. Clarify ambiguous instructions\n3. Get decisions on implementation choices as you work\n4. Offer choices to the user about what direction to take.\n\nUsage notes:\n- Users will always be able to select "Type something" to provide custom text input\n- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label\n- Use multiSelect: true to allow multiple answers to be selected for a question',acceptsCallbacks:!0,input_schema:{type:"object",properties:{questions:{type:"array",description:"Questions to ask the user",items:{type:"object",properties:{question:{type:"string",description:"The complete question to ask the user. Should be clear, specific, and end with a question mark."},header:{type:"string",description:'Very short label displayed as a chip/tag (max 20 chars). Examples: "Auth method", "Library", "Approach".'},options:{type:"array",description:'The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no "Type something" option, that will be provided automatically.',items:{type:"object",properties:{label:{type:"string",description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."},description:{type:"string",description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}},required:["label","description"]}},multiSelect:{type:"boolean",description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."}},required:["question","header","options"]}}},required:["questions"]},execute:__name(async(e,t)=>{const n=await askUserQuestion(e,{onQuestionRequest:t?.onQuestionRequest,abortSignal:t?.abortSignal});try{return formatOutput6({result:JSON.parse(n),params:e})}catch{return n}},"execute")}}}),JS=__esm({"src/tools/killshell/types.ts"(){Ht(),QS=f.object({port:f.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:f.number().int().positive().optional()}).refine(e=>void 0!==e.port&&void 0===e.pid||void 0===e.port&&void 0!==e.pid,{message:"Exactly one of port or pid must be provided"}),VS=class extends Error{static{__name(this,"KillshellError")}code;pid;port;constructor(e,t,n,r){super(e),this.name="KillshellError",this.code=t,this.pid=n,this.port=r}}}});function isUnixLike(){const e=process.platform;return"darwin"===e||"linux"===e}function isWindows(){return"win32"===process.platform}async function executeCommand(e,t){return new Promise((n,r)=>{const s=M(e,t,{shell:!1,stdio:["pipe","pipe","pipe"]});let o="",i="";s.stdout?.on("data",e=>{o+=e.toString()}),s.stderr?.on("data",e=>{i+=e.toString()}),s.on("close",e=>{0===e?n(o.trim()):r(new Error(i.trim()||o.trim()))}),s.on("error",e=>{r(e)})})}async function findPidByPort(e){try{if(isUnixLike()){const t=(await executeCommand("lsof",["-ti",`:${e}`,"-sTCP:LISTEN"])).trim().split("\n")[0];if(!t||!/^\d+$/.test(t))return null;const n=parseInt(t,10);return isNaN(n)?null:n}if(isWindows()){const t=(await executeCommand("netstat",["-ano"])).split("\n");for(const n of t){const t=n.trim();if(!t)continue;const r=t.split(/\s+/);if(r.length<5)continue;if("LISTENING"!==r[3])continue;const s=r[1].match(/:(\d+)$/);if(!s)continue;const o=parseInt(s[1],10);if(isNaN(o)||o!==e)continue;const i=parseInt(r[r.length-1],10);if(!isNaN(i))return i}return null}}catch(t){const n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found")||n.includes("command not found")){const e=isWindows()?"netstat":"lsof";throw new Error(`Required command '${e}' not found. Please ensure it is installed and in PATH.`)}if(n.includes("permission denied")||n.includes("EACCES"))throw new Error(`Permission denied when trying to find process on port ${e}. Try running with elevated privileges.`);if(n&&n.length>0&&!/no process|not found|exit code 1/i.test(n))throw new Error(`Failed to determine PID for port ${e}: ${n}`);return null}return null}async function getProcessName(e){try{if(isUnixLike())return(await executeCommand("ps",["-p",e.toString(),"-o","comm="])).trim();if(isWindows()){const t=(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).match(/"([^"]+)"/);return t?t[1]:void 0}}catch(e){return}}async function isProcessAlive(e){try{if(isUnixLike())return await executeCommand("kill",["-0",e.toString()]),!0;if(isWindows())return(await executeCommand("tasklist",["/FI",`PID eq ${e}`,"/FO","CSV","/NH"])).trim().length>0}catch{return!1}return!1}async function waitForProcessTermination(e,t=5e3,n=100){const r=Date.now();for(;Date.now()-r<t;){if(!await isProcessAlive(e))return!0;await new Promise(e=>setTimeout(e,n))}return!1}async function killProcess(e){if(isUnixLike())await executeCommand("kill",["-15",e.toString()]),await waitForProcessTermination(e,5e3,100)||(await executeCommand("kill",["-9",e.toString()]),await waitForProcessTermination(e,2e3,100));else{if(!isWindows())throw new Error(`Unsupported platform: ${process.platform}`);await executeCommand("taskkill",["/PID",e.toString(),"/F"])}}async function executeKillshell(e){let t,n;if(void 0!==e.port){n=e.port;const r=await findPidByPort(e.port);if(null===r)throw new VS(`No process found listening on port ${e.port}`,"NO_PROCESS_FOUND",void 0,e.port);t=r}else void 0!==e.pid&&(t=e.pid);if(!t)throw new VS("Unable to determine target process","INVALID_TARGET");const r=await getProcessName(t);try{await killProcess(t)}catch(e){const r=e instanceof Error?e.message:String(e);throw new VS(`Failed to kill process ${t}: ${r}`,"KILL_FAILED",t,n)}return{success:!0,message:n?`Successfully killed process on port ${n}`:`Successfully killed process ${t}`,pid:t,port:n,processName:r}}var XS=__esm({"src/tools/killshell/killshell.ts"(){Ht(),JS(),__name(isUnixLike,"isUnixLike"),__name(isWindows,"isWindows"),__name(executeCommand,"executeCommand"),__name(findPidByPort,"findPidByPort"),__name(getProcessName,"getProcessName"),__name(isProcessAlive,"isProcessAlive"),__name(waitForProcessTermination,"waitForProcessTermination"),__name(killProcess,"killProcess"),__name(executeKillshell,"executeKillshell")}});function formatKillshellResult(e){const t=[];return t.push(`${ke.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}var ZS,eb,tb,nb,rb,sb,ob,ib,ab,lb,cb,ub,db,mb,pb,gb,hb,fb,yb,wb,Sb=__esm({"src/tools/killshell/formatter.ts"(){Ht(),__name(formatKillshellResult,"formatKillshellResult")}}),bb=__esm({"src/tools/killshell/index.ts"(){Ht(),JS(),XS(),Sb(),ZS={name:"kill_shell",description:"Terminates processes by port number or PID, useful for freeing occupied ports or stopping stuck development servers. Attempts graceful termination first (SIGTERM/taskkill), then forces if needed. Use with caution - terminating system processes may cause instability.",acceptsCallbacks:!0,input_schema:{type:"object",properties:{port:{type:"number",description:"Port number (1-65535) to free by terminating the listening process. Automatically finds and kills the process using this port."},pid:{type:"number",description:"Process ID to terminate directly. Use when you know the exact PID to kill."}},required:[]},execute:__name(async(e,t)=>{try{const n=QS.parse(e);return t?.onPermissionRequest&&!await t.onPermissionRequest("kill_shell",e)?"ERROR: Permission denied — Process termination was not approved":formatKillshellResult(await executeKillshell(n))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while killing process"}},"execute")}}}),Eb=__esm({"src/tools/exit-plan-mode/index.ts"(){Ht(),eb={name:"exit_plan_mode",description:'Call this tool when your plan is complete and ready for user approval.\n\nThis will:\n1. Ask the user if they want to exit plan mode and begin implementation\n2. If user says "Yes": Exit plan mode and begin implementation\n3. If user says "No": Stay in plan mode for further refinement\n\nUsage:\n- Call this AFTER writing the plan file\n- Call this AFTER asking any clarifying questions\n- This is the FINAL step in plan mode\n\nIMPORTANT: Call this tool ALONE — do not combine it with other tool calls in the same message. It switches your mode and system prompt.\n\nDO NOT:\n- Call this before the plan is written\n- Call this multiple times\n- Ask "Ready to implement?" yourself - this tool does that',acceptsCallbacks:!0,input_schema:{type:"object",properties:{},required:[]},execute:__name(async(e,t)=>{if(!t?.onQuestionRequest)return JSON.stringify({error:"Question callback not available"});const n=await t.onQuestionRequest({questions:[{question:"Exit plan mode and begin implementation?",header:"Exit Plan",options:[{label:"Yes, auto-accept",description:"Exit plan mode and implement with auto-accept (no permission prompts)"},{label:"Yes, exit",description:"Exit plan mode and implement with manual approval for each change"},{label:"Cancel",description:"Stay in plan mode to refine the plan further"}],multiSelect:!1}],hideCustomInput:!0,exitPlanMode:!0}),r=n?.answers?.[0]?.selectedOptions?.[0]||"";return r.startsWith("Yes, auto-accept")?"Exited plan mode. Now in auto-accept mode.":r.startsWith("Yes, exit")?"Exited plan mode. Now in standard mode.":"Staying in plan mode. Continue refining the plan."},"execute")}}}),vb=__esm({"src/tools/enter-plan-mode/index.ts"(){Ht(),tb={name:"enter_plan_mode",description:'Call this tool to enter plan mode for read-only exploration and structured planning.\n\nThis will:\n1. Ask the user if they want to enter plan mode\n2. If user says "Yes": Switch to plan mode (read-only exploration and planning)\n3. If user says "No": Stay in current mode\n\nWHEN TO CALL:\n- User explicitly asks to "plan", "design", or "explore"\n- Task requires understanding multiple files/systems you haven\'t read yet\n- Task involves architectural decisions or spans 3+ files\n- You need to research the codebase before you can implement effectively\n- You\'re unsure about the right approach\n\nIMPORTANT: Call this tool ALONE — do not combine it with other tool calls in the same message. It switches your mode and system prompt, so other tools in the same message would run under the wrong mode.\n\nDO NOT:\n- Call this if already in plan mode\n- Call this for simple, well-defined tasks where you know exactly what to do',acceptsCallbacks:!0,input_schema:{type:"object",properties:{},required:[]},execute:__name(async(e,t)=>{if(!t?.onQuestionRequest)return JSON.stringify({error:"Question callback not available"});const n=await t.onQuestionRequest({questions:[{question:"Enter plan mode for read-only exploration and planning?",header:"Plan Mode",options:[{label:"Yes (Recommended)",description:"Switch to plan mode — explore codebase and create an implementation plan"},{label:"No, stay in current mode",description:"Continue without entering plan mode"}],multiSelect:!1}],hideCustomInput:!0,enterPlanMode:!0});return(n?.answers?.[0]?.selectedOptions?.[0]||"").startsWith("Yes")?"User approved. Entered plan mode. Begin exploring the codebase to understand the task.":"User chose to stay in current mode. Proceed normally."},"execute")}}}),Cb=__esm({"src/tools/web-search/index.ts"(){Ht(),nb={type:"web_search_20250305",name:"web_search",max_uses:5}}}),kb=__esm({"src/tools/web-fetch/index.ts"(){Ht(),rb={type:"web_fetch_20250910",name:"web_fetch"}}}),Tb=__esm({"src/tools/get-diagnostics/types.ts"(){Ht(),sb=f.preprocess(e=>{if("string"==typeof e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{return[e]}return e},f.array(f.string()).optional()),ob=f.object({filePaths:sb.describe('Array of absolute file paths to get diagnostics for. MUST always be an array, even for a single file e.g. ["/path/to/file.ts"]. Pass specific file paths when you know which files are relevant. Only omit to scan the entire workspace when the user explicitly asks for all workspace diagnostics.')})}}),_b=__esm({"src/tui/vscode-context/ipc-client.ts"(){Ht(),In(),ib=t.join(w.homedir(),".commandcode","ide"),ab=__name(e=>{const n=t.resolve(e);let r=n;try{r=v.realpathSync(n)}catch{}return"win32"===process.platform?r.toLowerCase():r},"normalizePathForComparison"),lb=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),cb=__name(e=>{if("win32"===process.platform)return null;try{const t=$(`ps -o ppid= -p ${e}`,{encoding:"utf-8",timeout:1e3}),n=parseInt(t.trim(),10);return Number.isNaN(n)||n<=1?null:n}catch{return null}},"getParentPid"),ub=__name((e,t,n=cb)=>{const r=new Map;for(const t of e)r.set(t.session.pid,t);let s=t;for(let e=0;e<10&&null!==s;e++){const e=r.get(s);if(e)return e;s=n(s)}return null},"findAncestorSession"),db=__name(()=>"vscode"!==process.env.TERM_PROGRAM?null:process.env.CURSOR_TRACE_ID?"cursor":process.env.WINDSURF_SESSION_ID?"windsurf":"code","detectIDE"),mb=__name((e,n)=>{try{v.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{v.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),pb=__name((e,n={})=>{const{sessionDir:r=ib,parentPidFn:s=cb,startPid:o=process.ppid}=n;try{if(!v.existsSync(r))return null;const n=`${e}-`,i=v.readdirSync(r).filter(e=>e.endsWith(".json")&&e.startsWith(n)),a=[];for(const e of i)try{const n=t.join(r,e),s=JSON.parse(v.readFileSync(n,"utf-8"));if(!lb(s.pid)){mb(n,r);continue}a.push({session:s,file:e})}catch{continue}if(0===a.length)return null;const l=ub(a,o,s);if(l)return dlog("[VSCode:IPC] Discovered session via PID ancestry",{socketPath:l.session.socketPath,ideName:l.session.ideName}),l.session.socketPath;const u=ab(process.cwd());let d=null,m=0;for(const{session:e}of a)for(const n of e.workspaceFolders){const r=ab(n);(u===r||u.startsWith(r+t.sep))&&r.length>m&&(d=e,m=r.length)}return d&&dlog("[VSCode:IPC] Discovered session via workspace match",{socketPath:d.socketPath,ideName:d.ideName}),d?.socketPath??null}catch{return null}},"discoverSocketPath"),gb=__name(()=>{const e=db();return e?pb(e):null},"resolveSocketPath"),hb=__name(()=>({type:"request",id:H(),payload:{action:"getContext"}}),"createContextRequest"),fb=__name(e=>{if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.id&&!!["request","response","error"].includes(t.type)&&"object"==typeof t.payload&&null!==t.payload},"isValidIPCMessage"),yb=__name((e,t)=>{try{const n=JSON.parse(e.toString());if(!fb(n))return dlog("[VSCode:IPC] Invalid message structure"),null;if("response"!==n.type)return null;if(n.id!==t)return null;const r=n.payload;return"object"!=typeof r||null===r?null:r}catch{return null}},"parseResponse"),wb=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??gb()}get isConnected(){return this.connected}async connect(e=2e3){if(!this.socketPath)return dlog("[VSCode:IPC] No socket path resolved"),!1;const t=this.socketPath;dlog("[VSCode:IPC] Connecting to socket",{path:t,timeout:e});try{return await new Promise(n=>{try{const r=xe.connect(t);this.socket=r;const s=__name(()=>{r.off("error",o)},"cleanup"),o=__name(e=>{clearTimeout(i),s(),this.connected=!1,dlog("[VSCode:IPC] Connection error",{error:e.message}),n(!1)},"handleError"),i=setTimeout(()=>{dlog("[VSCode:IPC] Connection timeout"),s(),r.destroy(),n(!1)},e);r.on("connect",()=>{try{if(clearTimeout(i),s(),this.socket!==r)return r.destroy(),void n(!1);this.connected=!0,dlog("[VSCode:IPC] Connected successfully"),r.on("close",()=>{this.connected=!1}),r.on("error",()=>{this.connected=!1}),n(!0)}catch(e){dlog("[VSCode:IPC] Error in connect handler",{error:e}),r.destroy(),n(!1)}}),r.on("error",o)}catch(e){dlog("[VSCode:IPC] Connection exception",{error:e}),n(!1)}})}catch{return!1}}async getContext(e=5e3){try{const t=this.socket;if(!t||!this.connected)return dlog("[VSCode:IPC] Cannot get context - not connected"),null;const n=hb();return await new Promise(r=>{const s=__name(()=>{t.off("data",a),t.off("error",l)},"cleanup"),o=setTimeout(()=>{dlog("[VSCode:IPC] Context request timeout"),s(),r(null)},e);let i="";const a=__name(e=>{try{i+=e.toString();const t=i.indexOf("\n");if(-1===t)return;clearTimeout(o),s();const a=i.slice(0,t),l=yb(Buffer.from(a),n.id);l||dlog("[VSCode:IPC] Invalid response received"),r(l)}catch(e){clearTimeout(o),s(),dlog("[VSCode:IPC] Error processing response",{error:e}),r(null)}},"handleData"),l=__name(e=>{clearTimeout(o),s(),dlog("[VSCode:IPC] Socket error during request",{error:e.message}),r(null)},"handleError");t.on("data",a),t.on("error",l);try{t.write(JSON.stringify(n)+"\n")}catch(e){clearTimeout(o),s(),dlog("[VSCode:IPC] Failed to send request",{error:e}),r(null)}})}catch{return null}}async getDiagnostics(e={}){const{filePaths:t,timeout:n=5e3}=e,r=this.socket;if(!r||!this.connected)return dlog("[VSCode:IPC] Cannot get diagnostics - not connected"),null;const s={type:"request",id:H(),payload:{action:"getDiagnostics",filePaths:t}};return new Promise(e=>{const t=__name(()=>{r.off("data",a),r.off("error",l)},"cleanup"),o=setTimeout(()=>{dlog("[VSCode:IPC] Diagnostics request timeout"),t(),e(null)},n);let i="";const a=__name(n=>{for(i+=n.toString();;){const n=i.indexOf("\n");if(-1===n)return;const r=i.slice(0,n);if(i=i.slice(n+1),r.trim())try{const n=JSON.parse(r);if(n.id!==s.id){dlog("[VSCode:IPC] Ignoring diagnostics response for different request id");continue}return clearTimeout(o),t(),void("response"===n.type&&n.payload?.diagnostics?e(n.payload.diagnostics):"error"===n.type?(dlog("[VSCode:IPC] Diagnostics error response",{message:n.payload?.message,code:n.payload?.code}),e(null)):(dlog("[VSCode:IPC] Invalid diagnostics response"),e(null)))}catch(e){dlog("[VSCode:IPC] Failed to parse diagnostics response line",{error:e})}}},"handleData"),l=__name(n=>{clearTimeout(o),t(),dlog("[VSCode:IPC] Socket error during diagnostics request",{error:n.message}),e(null)},"handleError");r.on("data",a),r.on("error",l);try{r.write(JSON.stringify(s)+"\n")}catch(n){clearTimeout(o),t(),dlog("[VSCode:IPC] Failed to send diagnostics request",{error:n}),e(null)}})}disconnect(){if(this.socket){dlog("[VSCode:IPC] Disconnecting");try{this.socket.end()}catch{}this.socket=null,this.connected=!1}}static async isAvailable(e=1e3){try{const t=new _VSCodeIPCClient;if(!t.socketPath)return dlog("[VSCode:IPC] Availability check",{available:!1,reason:"no socket path"}),!1;const n=await t.connect(e);return t.disconnect(),dlog("[VSCode:IPC] Availability check",{available:n}),n}catch{return!1}}}}});async function fetchDiagnostics(e){if(!db())throw new Error("Not running inside an IDE terminal. The diagnostics tool requires the Command Code VS Code extension.");const n=e?.map(e=>t.resolve(e)),r=new wb;try{if(!await r.connect())throw new Error("Could not connect to IDE extension. Make sure the Command Code extension is installed and active.");const e=await r.getDiagnostics({filePaths:n,timeout:5e3});if(null===e)throw new Error("Failed to get diagnostics from IDE.");return dlog("[diagnostics] Fetched diagnostics",{fileCount:e.length,total:e.reduce((e,t)=>e+t.diagnostics.length,0)}),e}finally{r.disconnect()}}var xb=__esm({"src/tools/get-diagnostics/get-diagnostics.ts"(){Ht(),_b(),In(),__name(fetchDiagnostics,"fetchDiagnostics")}});function formatDiagnostics(e){if(0===e.length)return"No diagnostics found. All files are clean.";const t=[];let n=0,r=0,s=0,o=0;for(const i of e){t.push(`${i.relativePath}:`);for(const e of i.diagnostics){const i=`L${e.range.startLine}:${e.range.startCol}`,a=e.code?` ${e.code}`:"",l=e.source?` [${e.source}]`:"";switch(t.push(` ${i} ${e.severity}${a}: ${e.message}${l}`),e.severity){case"error":n++;break;case"warning":r++;break;case"information":s++;break;case"hint":o++}}t.push("")}const i=[];n>0&&i.push(`${n} error${1!==n?"s":""}`),r>0&&i.push(`${r} warning${1!==r?"s":""}`),s>0&&i.push(`${s} info`),o>0&&i.push(`${o} hint${1!==o?"s":""}`);const a=`${e.length} file${1!==e.length?"s":""}`;return t.push(`Summary: ${i.join(", ")} across ${a}`),t.join("\n")}var Pb,Ab,Ib,Nb,Rb,$b,Mb,Lb,Db,Ob,Fb=__esm({"src/tools/get-diagnostics/formatter.ts"(){Ht(),__name(formatDiagnostics,"formatDiagnostics")}}),qb=__esm({"src/tools/get-diagnostics/index.ts"(){Ht(),Tb(),xb(),Fb(),Pb={name:"diagnostics",description:"Get LSP diagnostics (errors, warnings, hints) from the IDE. Returns type errors, lint warnings, and other language server diagnostics reported by all active language servers (TypeScript, ESLint, Python, etc.). Only available when connected to an IDE with the Command Code extension. Pass specific file paths when you know which files are relevant. Only omit filePaths to scan the entire workspace when the user explicitly asks for all workspace diagnostics.",input_schema:{type:"object",properties:{filePaths:{type:"array",items:{type:"string"},description:'Array of absolute file paths to get diagnostics for. MUST always be an array, even for a single file e.g. ["/path/to/file.ts"]. Pass specific file paths when you know which files are relevant. Only omit to scan the entire workspace when the user explicitly asks for all workspace diagnostics.'}},required:[]},execute:__name(async e=>{const t=ob.parse(e);return formatDiagnostics(await fetchDiagnostics(t.filePaths))},"execute")}}}),jb=__esm({"src/utils/help-data.ts"(){Ht(),Kt(),Ab="Coding agent that continuously learns your taste of writing code.",Ib=34,Nb=[{key:"Shift+Tab",description:"Toggle mode (default → auto-accept → plan)"},{key:"Ctrl+T",description:"Toggle learning feed"},{key:"Ctrl+O",description:"Toggle expanded tool output (Shift+O in iTerm2)"},{key:"Alt+P",description:"Quick model switch (Option+P on macOS)"},{key:"Ctrl+G",description:"Open input in external editor ($EDITOR)"},{key:"Press Esc twice",description:"Rewind to previous checkpoint"},{key:"/",description:"Open command menu"}],Rb=[{key:"cmd",description:"Start interactive session"},{key:'cmd "message"',description:"Start with initial message"},{key:"-r, --resume [name]",description:"Resume a conversation by name (use quotes for multi-word names), or pick from history"},{key:"-c, --continue",description:"Continue the last conversation"},{key:"-t, --trust",description:"Auto-trust project (skip initial permission prompt)"},{key:"-p, --print [query]",description:"Run in non-interactive mode, output response and exit"},{key:"--plan",description:"Start in plan mode"},{key:"--permission-mode <mode>",description:"Set permission mode (standard, plan, auto-accept)"},{key:"--auto-accept",description:"Start in auto-accept mode"},{key:"--yolo",description:"Bypass all permission prompts (alias for --dangerously-skip-permissions)"},{key:"--add-dir <directory>",description:"Add directory to workspace context"},{key:"--skip-onboarding",description:"Skip taste onboarding (for automated runs)"},{key:"--ide-setup",description:"Setup extension for editor context"},{key:"-v, --version",description:"Output the version number"},{key:"-h, --help",description:"Display this help message"}],$b=[{key:"/init",description:"Initialize AGENTS.md for this project"},{key:"/memory",description:"Manage Command Code memory"},{key:"/resume",description:"Resume a past conversation"},{key:"/rename [name]",description:"Rename the current session"},{key:"/rewind",description:"Restore to a previous checkpoint (Press Esc twice)"},{key:"/clear",description:"Clear the conversation history"},{key:"/share",description:"Share conversation (copy link to clipboard)"},{key:"/unshare",description:"Stop sharing conversation"},{key:"/taste",description:"Manage Taste learning and usage"},{key:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{key:"/skills",description:"Browse and open agent skills"},{key:"/agents",description:"Manage agent configurations"},{key:"/mcp",description:"Manage MCP server connections"},{key:"/model",description:"Switch between Command Code models"},{key:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{key:"/compact",description:"Compact the conversation history"},{key:"/compact-mode",description:"Select a compact mode to compact sessions"},{key:"/context",description:"Show context window usage and breakdown"},{key:"/ide",description:"Setup extension to fetch editor context"},{key:"/login",description:"Authenticate with CommandCode via browser"},{key:"/logout",description:"Remove stored authentication"},{key:"/feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"/review [pr]",description:"Review a pull request (optional PR number)"},{key:"/pr-comments",description:"Fetch all PR comments for current branch"},{key:"/add-dir",description:"Manage additional directory scope"},{key:"/status",description:"Show comprehensive environment status"},{key:"/usage",description:"Display credits, plan, and usage metrics"},{key:"/help",description:"Display help information"},{key:"/exit",description:"Exit Command Code"}],Mb=[{key:"cmd info",description:"Display system information"},{key:"cmd status",description:"Show authentication status"},{key:"cmd help",description:"Display help information"},{key:"cmd whoami",description:"Show current user"},{key:"cmd update",description:"Update Command Code to the latest version"},{key:"cmd feedback [title]",description:"Share feedback or report bugs (optional title)"},{key:"cmd taste",description:"Manage taste learning packages"},{key:"cmd taste learn <source>",description:"Learn taste from a local repository or GitHub repo"},{key:"cmd learn-taste",description:"Learn command structure from repositories"},{key:"cmd mcp",description:"Manage MCP (Model Context Protocol) servers"},{key:"cmd skills",description:"Manage skills from GitHub repositories"},{key:"cmd login",description:"Login with Command Code account"},{key:"cmd logout",description:"Remove stored authentication"}],Lb=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],Db=[{key:"cmd",description:"Start interactive session"},{key:'cmd "fix the login bug"',description:"Start with a task"},{key:"cmd -c",description:"Continue last conversation"},{key:"cmd -r",description:"Resume a past session"},{key:'cmd --resume "auth refactor"',description:"Resume a named session"},{key:'cmd -p "your query"',description:"Run non-interactive query"},{key:"cmd taste learn .",description:"Learn taste from the current repository"},{key:"cmd taste learn owner/repo",description:"Learn taste from a GitHub repository"},{key:"cmd --add-dir ../shared",description:"Start with additional directory scope"},{key:"cmd info",description:"Show system information"},{key:'cmd feedback "title"',description:"Open feedback form with title"}],Ob='Start with a prompt: cmd "fix the login bug"'}});function formatHelpItems(e){return e.map(e=>`- ${e.key}: ${e.description}`).join("\n")}function getSelfKnowledge(){return`# Command Code — Product Knowledge\n\n## KEYBOARD SHORTCUTS\n${formatHelpItems(Nb)}\n\n## SLASH COMMANDS (type these in the chat input)\n${formatHelpItems($b)}\n\n## CLI SUBCOMMANDS\n${formatHelpItems(Mb)}\n\n## CLI EXAMPLES\n${formatHelpItems(Db)}\n\n## CLI OPTIONS (flags when launching cmd)\n${formatHelpItems(Rb)}\n\n## TASTE SYSTEM\nTaste is powered by the meta neuro-symbolic AI model taste-1 with continuous reinforcement learning (RL). It combines reasoning with neural intuition to learn your coding preferences.\n\nHow taste works:\n- Learns from you — every accept, reject, and edit becomes a signal\n- Thinks like you — learns patterns and micro-decisions you'd never document\n- Grows with you — continuous learning loop that never goes stale\n\nEnable taste: Use /taste in a session or run npx taste from the command line.\n\nTaste packages (three types):\n- Project: Stored in .commandcode/taste/ — learnings unique to this codebase\n- Global: Stored in ~/.commandcode/taste/ — personal taste across all projects (use -g flag)\n- Remote: Stored at commandcode.ai/username/taste — team sharing, backup, sync across machines\n\nFile structure:\n .commandcode/taste/\n ├── taste.md (main taste file)\n ├── cli/taste.md\n ├── typescript/taste.md\n └── architecture/taste.md\n\nKey commands:\n- npx taste push --all — push entire project taste to remote\n- npx taste pull username/project-name — pull taste from remote\n- npx taste push cli -g — push package to global\n- npx taste pull cli -g — pull package from global\n- npx taste list — list available packages\n- npx taste lint — validate package format\n- npx taste open — open packages in editor\n\nPrivacy: Taste processing runs on your codebase and stores learning data locally only.\n\n## KEY FEATURES\n- Taste System: Automatically learns coding preferences from interactions and applies them consistently\n- Skills: User-defined knowledge modules for specialized tasks (stored in .commandcode/skills/ or .agents/skills/)\n- Agents: Custom agent configurations for different workflows (stored in .commandcode/agents/)\n- Memory: Project-specific instructions via COMMANDCODE.md files\n- MCP: Model Context Protocol server connections for extended tool capabilities\n- Plan Mode: Structured exploration and planning before implementation [Shift+Tab to toggle]\n- Conversation Management: Resume, continue, share, and rewind conversations\n- PR Review: Built-in pull request review capabilities (/review command)\n- Learning Feed: View what taste is learning in real-time [Ctrl+T to toggle]\n- Model Switching: Switch between models with Alt+P (Option+P on macOS)\n\n## FREQUENTLY ASKED QUESTIONS\nQ: What is Command Code?\nA: Command Code is the first coding agent that automatically learns your taste of writing great code.\n\nQ: What is taste-1?\nA: taste-1 is our meta neuro-symbolic AI model with continuous reinforcement learning (RL).\n\nQ: Is Command Code free?\nA: Command Code offers both free and premium plans. Check https://commandcode.ai/pricing for details.\n\nQ: How do I install Command Code?\nA: Run npm i -g command-code, then cmd login, then cmd to start.\n\nQ: What are Agent Skills?\nA: Reusable instructions that teach Command Code how to handle specific tasks like code reviews, testing, or commit messages. Use /skills to browse them.\n\nQ: What are MCP servers?\nA: MCP (Model Context Protocol) servers let Command Code connect to external tools and data sources like GitHub, Notion, databases, and more. Use /mcp to manage them.\n\nQ: What is plan mode?\nA: Plan mode lets you review and approve Command Code's approach before it writes any code. Press Shift+Tab to toggle it.\n\nQ: What is headless mode?\nA: Headless mode lets you run Command Code non-interactively in scripts, CI/CD pipelines, and automation workflows. Use cmd -p "query" to run.\n\nQ: How do I fix "command not found" after installing?\nA: Ensure your global npm bin directory is in your PATH. Run npm config get prefix to find it, then add <prefix>/bin to your PATH.\n\nQ: Why am I getting unauthorized errors?\nA: Run cmd logout followed by cmd login to refresh your session. If the issue persists, check your account at https://commandcode.ai/studio.\n\nQ: How do I check my usage limits?\nA: Visit the billing page in Command Code Studio at https://commandcode.ai/studio.\n\nQ: My MCP server won't connect. What should I do?\nA: Check the server config with cmd mcp get <name> and use /mcp inside a session to see the error. For stdio servers, ensure the command is installed and in your PATH.\n\nQ: Where can I get help?\nA: Join our Discord at https://commandcode.ai/discord, report issues on GitHub, or email support@commandcode.ai.\n\n## TROUBLESHOOTING\n\n### Installation\n- "command not found" after install: Ensure global npm bin directory is in PATH. Run npm config get prefix, add <prefix>/bin to PATH, restart terminal.\n\n### Authentication\n- Login fails or session expired: Run cmd logout then cmd login. If still failing, delete ~/.commandcode/auth.json and retry.\n- API key or provider issues: Verify provider config, check API key validity, check usage limits.\n- Chrome Local Network Access prompt during login: Click "Allow" — this is expected and safe. Command Code runs a temporary local server for OAuth callback.\n\n### MCP Servers\n- Server won't connect: Check config with cmd mcp get <name>, verify command is in PATH, use /mcp in session for error details.\n- Authentication issues: Re-authenticate with cmd mcp auth <server>, or clear and retry with cmd mcp auth --clear <server>.\n\n### Skills\n- Not appearing in /skills menu: Check directory structure (.commandcode/skills/ or .agents/skills/), verify SKILL.md exists with valid frontmatter.\n- Editor not opening: Check $EDITOR is set and the editor is in PATH.\n- Skill not being used: Make description more specific with keywords, ask Command Code explicitly to use the skill.\n\n### Performance\n- Slow responses: Check internet connection, disconnect unneeded MCP servers, keep prompts focused and specific.\n- High token usage: Review usage in Studio, use headless mode for scripted tasks, use plan mode to agree on approach first.\n\n### Support\n- Discord: https://commandcode.ai/discord\n- GitHub: https://github.com/commandcode/command-code\n- Email: support@commandcode.ai\n\n## PRICING & LIMITS\nHow it works:\n- Monthly reset: Request limits reset at the start of each billing cycle.\n- Auto top-up: Buy extra credits at model cost. Credits roll over and never expire.\n- No AI training: Command Code does not train on your code or store your code snippets.\n\nManage your plan:\n- Purchase credits or subscribe: Settings > Billing at https://commandcode.ai/settings/billing\n- Track usage: https://commandcode.ai/usage\n- Manage payment methods: Access billing portal from Settings > Billing\n\nPremium requests: Any request that uses a premium model (like taste-1) during your coding session.\nWhen you hit your limit: Continue with auto top-up enabled. Extra credits are purchased at model cost and roll over.\nSwitch plans: Upgrade or downgrade anytime from Settings > Billing. Changes take effect next billing cycle.\nTeam billing: Billed per seat. Credits are pooled at the team level.\n\nEnterprise: Enhanced security, compliance, and control. Contact support@commandcode.ai for Enterprise edition.\n\n## PRIVACY & LEGAL\n- Command Code does not train on your code or store your code snippets.\n- Taste processing runs on your codebase and stores learning data in your project and on your local machine only.\n- Privacy Policy: https://commandcode.ai/privacy\n- Terms of Service: https://commandcode.ai/terms\n\n## HELPFUL LINKS\n${formatHelpItems(Lb)}`}var Bb,Ub,zb,Wb,Gb=__esm({"src/tools/get-self-knowledge/get-self-knowledge.ts"(){Ht(),jb(),__name(formatHelpItems,"formatHelpItems"),__name(getSelfKnowledge,"getSelfKnowledge")}}),Hb=__esm({"src/tools/get-self-knowledge/index.ts"(){Ht(),Gb(),Bb={name:"get_self_knowledge",description:"Retrieve Command Code product documentation — features, shortcuts, commands, options, taste, FAQs, troubleshooting, pricing, or privacy. Call this whenever the user asks about Command Code capabilities or needs help. Authoritative source — do NOT search the codebase. Call once per conversation. After the first call, the information is already in your context — do not call again.",input_schema:{type:"object",properties:{},required:[]},execute:__name(async()=>getSelfKnowledge(),"execute")}}}),Qb=__esm({"src/mcp/constants.ts"(){Ht(),Ub="2025-03-26",zb={name:"command-code",version:"1.0.0"},Promise.resolve().then(()=>(Ur(),Lr)).then(({getPackageJson:e})=>{zb.version=e().version??"1.0.0"}).catch(()=>{})}});function getTokenFilePath(){return e.join(w.homedir(),".commandcode",Wb)}async function loadTokenStorage(){try{const e=getTokenFilePath(),t=await D.readFile(e,"utf-8"),n=JSON.parse(t);return 1!==n.version||"object"!=typeof n.tokens?{version:1,tokens:{}}:n}catch(e){return dlog("[MCP] Failed to load token storage",e),{version:1,tokens:{}}}}async function saveTokenStorage(t){const n=getTokenFilePath(),r=e.dirname(n);await D.mkdir(r,{recursive:!0}),await D.writeFile(n,JSON.stringify(t,null,2),{mode:384}),await D.chmod(n,384)}async function storeTokens(e,t){const n=await loadTokenStorage();n.tokens[e]=t,await saveTokenStorage(n)}async function getTokens(e){return(await loadTokenStorage()).tokens[e]||null}async function deleteTokens(e){const t=await loadTokenStorage();return e in t.tokens&&(delete t.tokens[e],await saveTokenStorage(t),!0)}async function hasTokens(e){return e in(await loadTokenStorage()).tokens}function isTokenExpired(e){return!!e.expiresAt&&Date.now()>=e.expiresAt-6e4}async function getValidAccessToken({serverName:e,refreshCallback:t}){const n=await getTokens(e);if(!n)return null;if(!isTokenExpired(n))return n.accessToken;if(n.refreshToken&&t)try{const r=await t(n.refreshToken);return await storeTokens(e,r),r.accessToken}catch(t){return dlog("[MCP] Token refresh failed",t),await deleteTokens(e),null}return await deleteTokens(e),null}async function listServersWithTokens(){const e=await loadTokenStorage();return Object.keys(e.tokens)}async function storeClientSecret(e,t){const n=await loadTokenStorage();n.clientSecrets||(n.clientSecrets={}),n.clientSecrets[e]=t,await saveTokenStorage(n)}async function getClientSecret(e){const t=await loadTokenStorage();return t.clientSecrets?.[e]??null}var Vb,Kb,Yb,Jb,Xb,Zb=__esm({"src/mcp/auth/token-storage.ts"(){Ht(),Kt(),In(),Wb="mcp-tokens.json",__name(getTokenFilePath,"getTokenFilePath"),__name(loadTokenStorage,"loadTokenStorage"),__name(saveTokenStorage,"saveTokenStorage"),__name(storeTokens,"storeTokens"),__name(getTokens,"getTokens"),__name(deleteTokens,"deleteTokens"),__name(hasTokens,"hasTokens"),__name(isTokenExpired,"isTokenExpired"),__name(getValidAccessToken,"getValidAccessToken"),__name(listServersWithTokens,"listServersWithTokens"),__name(storeClientSecret,"storeClientSecret"),__name(getClientSecret,"getClientSecret")}}),eE=__esm({"src/mcp/types.ts"(){Ht(),Vb=f.object({authorizationUrl:f.string(),tokenUrl:f.string(),clientId:f.string(),clientSecret:f.string().optional(),scopes:f.array(f.string()).optional()}),Kb=f.object({transport:f.enum(["stdio","http"]),enabled:f.boolean().default(!0),command:f.string().optional(),args:f.array(f.string()).optional(),url:f.string().optional(),headers:f.record(f.string(),f.string()).optional(),oauth:Vb.optional(),env:f.record(f.string(),f.string()).optional()}),Yb=f.object({mcpServers:f.record(f.string(),Kb)})}});function getUserMcpConfigPath(){return e.join(w.homedir(),".commandcode",Jb)}function getLocalMcpConfigPath(t=process.cwd()){const n=Le(t);return e.join(w.homedir(),".commandcode","projects",n,Jb)}function getProjectMcpConfigPath(t=process.cwd()){return e.join(t,Xb)}function getMcpConfigPath({scope:e,projectPath:t=process.cwd()}){switch(e){case"user":return getUserMcpConfigPath();case"local":return getLocalMcpConfigPath(t);case"project":return getProjectMcpConfigPath(t)}}function getAllMcpConfigPaths(e=process.cwd()){return[{scope:"user",path:getUserMcpConfigPath()},{scope:"project",path:getProjectMcpConfigPath(e)},{scope:"local",path:getLocalMcpConfigPath(e)}]}var tE=__esm({"src/mcp/config/scopes.ts"(){Ht(),Kt(),Jb="mcp.json",Xb=".mcp.json",__name(getUserMcpConfigPath,"getUserMcpConfigPath"),__name(getLocalMcpConfigPath,"getLocalMcpConfigPath"),__name(getProjectMcpConfigPath,"getProjectMcpConfigPath"),__name(getMcpConfigPath,"getMcpConfigPath"),__name(getAllMcpConfigPaths,"getAllMcpConfigPaths")}});async function loadMcpConfig({scope:e,projectPath:t=process.cwd()}){try{const n=getMcpConfigPath({scope:e,projectPath:t}),r=await D.readFile(n,"utf-8"),s=JSON.parse(r),o=Yb.safeParse(s);return o.success?o.data:null}catch(e){return dlog("[MCP] Failed to load config",e),null}}async function saveMcpConfig({config:t,scope:n,projectPath:r=process.cwd()}){const s=getMcpConfigPath({scope:n,projectPath:r}),o=e.dirname(s);await D.mkdir(o,{recursive:!0}),await D.writeFile(s,JSON.stringify(t,null,2)+"\n",{mode:384})}async function loadMergedMcpConfig(e=process.cwd()){const t=getAllMcpConfigPaths(e),n={},r=new Map;for(const{scope:s}of t){const t=await loadMcpConfig({scope:s,projectPath:e});if(t?.mcpServers)for(const[e,o]of Object.entries(t.mcpServers))n[e]=o,r.set(e,s)}return{config:{mcpServers:n},serverScopes:r}}async function addMcpServer({name:e,serverConfig:t,scope:n,projectPath:r=process.cwd()}){let s=await loadMcpConfig({scope:n,projectPath:r});s||(s={mcpServers:{}});let o=t;if("project"===n&&t.oauth?.clientSecret){await storeClientSecret(e,t.oauth.clientSecret);const{clientSecret:n,...r}=t.oauth;o={...o,oauth:r}}o={...o,enabled:o.enabled??!0},s.mcpServers[e]=o,await saveMcpConfig({config:s,scope:n,projectPath:r})}async function removeMcpServer({name:e,scope:t,projectPath:n=process.cwd()}){const r=await loadMcpConfig({scope:t,projectPath:n});return!!r?.mcpServers[e]&&(delete r.mcpServers[e],await saveMcpConfig({config:r,scope:t,projectPath:n}),!0)}async function updateMcpServerStatus({name:e,enabled:t,scope:n,projectPath:r=process.cwd()}){const s=await loadMcpConfig({scope:n,projectPath:r});return!!s?.mcpServers[e]&&(s.mcpServers[e]={...s.mcpServers[e],enabled:t},await saveMcpConfig({config:s,scope:n,projectPath:r}),!0)}async function getMcpServer({name:e,projectPath:t=process.cwd()}){const{config:n,serverScopes:r}=await loadMergedMcpConfig(t),s=n.mcpServers[e],o=r.get(e);return s&&o?{config:s,scope:o}:null}async function listMcpServers(e=process.cwd()){const{config:t,serverScopes:n}=await loadMergedMcpConfig(e);return Object.entries(t.mcpServers).map(([e,t])=>({name:e,config:t,scope:n.get(e)}))}var nE,rE,sE=__esm({"src/mcp/config/mcp-config.ts"(){Ht(),In(),Zb(),eE(),tE(),__name(loadMcpConfig,"loadMcpConfig"),__name(saveMcpConfig,"saveMcpConfig"),__name(loadMergedMcpConfig,"loadMergedMcpConfig"),__name(addMcpServer,"addMcpServer"),__name(removeMcpServer,"removeMcpServer"),__name(updateMcpServerStatus,"updateMcpServerStatus"),__name(getMcpServer,"getMcpServer"),__name(listMcpServers,"listMcpServers")}}),oE=__esm({"src/mcp/client/stdio-transport.ts"(){Ht(),nE=class _StdioTransport extends De{constructor(e){super(),this.options=e}static{__name(this,"StdioTransport")}process=null;buffer="";pendingRequests=new Map;static REQUEST_TIMEOUT_MS=8e4;nextRequestId=0;isConnected=!1;static fromConfig(e){if("stdio"!==e.transport)throw new Error("Config is not for stdio transport");if(!e.command)throw new Error("Command is required for stdio transport");return new _StdioTransport({command:e.command,args:e.args,env:e.env})}async connect(){if(!this.isConnected)return new Promise((e,t)=>{try{this.process=M(this.options.command,this.options.args||[],{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.options.env}}),this.process.on("error",e=>{this.handleError(e),this.isConnected||t(e)}),this.process.on("exit",(e,t)=>{this.isConnected=!1,this.emit("close",e,t);for(const[,n]of this.pendingRequests){const r=t?`signal ${t}`:`code ${e}`;n.reject(new Error(`Process exited with ${r}`))}this.pendingRequests.clear()}),this.process.stdout?.on("data",e=>{this.handleData(e.toString())}),this.process.stderr?.on("data",e=>{this.emit("stderr",e.toString())}),this.isConnected=!0,e()}catch(e){t(e)}})}async request(e,t){if(!this.isConnected||!this.process?.stdin)throw new Error("Transport is not connected");const n=this.nextRequestId++,r={jsonrpc:"2.0",method:e,id:n,...t&&{params:t}};return new Promise((e,t)=>{const s=setTimeout(()=>{this.pendingRequests.delete(n),t(new Error("Request timed out"))},_StdioTransport.REQUEST_TIMEOUT_MS);this.pendingRequests.set(n,{resolve:__name(t=>{clearTimeout(s),e(t)},"resolve"),reject:__name(e=>{clearTimeout(s),t(e)},"reject")});const o=JSON.stringify(r)+"\n";this.process.stdin.write(o,e=>{e&&(clearTimeout(s),this.pendingRequests.delete(n),t(e))})})}notify(e,t){if(!this.isConnected||!this.process?.stdin)throw new Error("Transport is not connected");const n={jsonrpc:"2.0",method:e,...t&&{params:t}},r=JSON.stringify(n)+"\n";this.process.stdin.write(r,e=>{e&&this.handleError(e)})}async close(){this.process&&(this.process.stdin?.end(),this.process.kill(),this.process=null),this.isConnected=!1,this.pendingRequests.clear()}get connected(){return this.isConnected}handleData(e){let t;for(this.buffer+=e;-1!==(t=this.buffer.indexOf("\n"));){const e=this.buffer.substring(0,t);this.buffer=this.buffer.substring(t+1),e.trim()&&this.handleMessage(e)}}handleMessage(e){try{const t=JSON.parse(e);if("id"in t&&void 0!==t.id){const e=t,n=this.pendingRequests.get(e.id);n&&(this.pendingRequests.delete(e.id),n.resolve(e))}else{const e=t;this.emit("notification",e)}}catch(t){this.emit("error",new Error(`Failed to parse message: ${e}`))}}handleError(e){this.isConnected=!1,this.emit("error",e)}}}});function fetchWithTimeout(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),rE);return fetch(e,{...t,signal:n.signal}).finally(()=>clearTimeout(r))}var iE,aE,lE=__esm({"src/mcp/fetch.ts"(){Ht(),rE=8e4,__name(fetchWithTimeout,"fetchWithTimeout")}}),cE={};function generateRandomString(e){return W.randomBytes(e).toString("base64url").slice(0,e)}function generatePKCE(){const e=generateRandomString(64);return{verifier:e,challenge:W.createHash("sha256").update(e).digest("base64url")}}function escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function startCallbackServer(e,t){return new Promise((n,r)=>{let s=null,o=null;const i=new Promise((e,t)=>{s=e,o=t}),a=Oe.createServer((n,r)=>{const i=new m(n.url||"/",`http://${aE}:${e}`);if("/callback"===i.pathname){const e=i.searchParams.get("code"),n=i.searchParams.get("error"),a=i.searchParams.get("error_description");if(i.searchParams.get("state")!==t)r.writeHead(400,{"Content-Type":"text/html"}),r.end('\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Authentication Failed</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Authentication Failed</h1>\n\t\t\t\t\t\t\t<p>Invalid state parameter. Please try again.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t'),o?.(new Error("OAuth state parameter mismatch"));else if(n){const e=escapeHtml(a||n);r.writeHead(400,{"Content-Type":"text/html"}),r.end(`\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Authentication Failed</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Authentication Failed</h1>\n\t\t\t\t\t\t\t<p>${e}</p>\n\t\t\t\t\t\t\t<p>You can close this window.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t`),o?.(new Error(a||n))}else e?(r.writeHead(200,{"Content-Type":"text/html"}),r.end('\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Authentication Successful</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Authentication Successful</h1>\n\t\t\t\t\t\t\t<p>You can close this window and return to Command Code.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t'),s?.(e)):(r.writeHead(400,{"Content-Type":"text/html"}),r.end('\n\t\t\t\t\t\t<!DOCTYPE html>\n\t\t\t\t\t\t<html>\n\t\t\t\t\t\t<head><title>Invalid Request</title></head>\n\t\t\t\t\t\t<body style="font-family: system-ui; padding: 40px; text-align: center;">\n\t\t\t\t\t\t\t<h1>Invalid Request</h1>\n\t\t\t\t\t\t\t<p>No authorization code received.</p>\n\t\t\t\t\t\t</body>\n\t\t\t\t\t\t</html>\n\t\t\t\t\t'),o?.(new Error("No authorization code received")))}else r.writeHead(404),r.end("Not Found")});a.on("error",r),a.listen(e,aE,()=>{n({server:a,getCode:__name(()=>i,"getCode")})})})}async function exchangeCodeForTokens(e,t,n,r){const s=new URLSearchParams({grant_type:"authorization_code",code:t,redirect_uri:r,client_id:e.clientId,code_verifier:n});e.clientSecret&&s.set("client_secret",e.clientSecret);const o=await fetchWithTimeout(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()});if(!o.ok){const e=await o.text();throw new Error(`Token exchange failed: ${o.status} ${e}`)}const i=await o.json();return{accessToken:i.access_token,refreshToken:i.refresh_token,expiresAt:i.expires_in?Date.now()+1e3*i.expires_in:void 0,tokenType:i.token_type,scope:i.scope}}async function refreshAccessToken({config:e,refreshToken:t}){const n=new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:e.clientId});e.clientSecret&&n.set("client_secret",e.clientSecret);const r=await fetchWithTimeout(e.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()});if(!r.ok){const e=await r.text();throw new Error(`Token refresh failed: ${r.status} ${e}`)}const s=await r.json();return{accessToken:s.access_token,refreshToken:s.refresh_token||t,expiresAt:s.expires_in?Date.now()+1e3*s.expires_in:void 0,tokenType:s.token_type,scope:s.scope}}async function performOAuthFlow(e,t,n){const r=n?.port||iE,s=n?.timeout||12e4,o=n?.onStatus||(()=>{});let i=null;try{const n=generatePKCE(),a=generateRandomString(32),l=`http://${aE}:${r}/callback`;o("Starting authentication server...");const{server:u,getCode:d}=await startCallbackServer(r,a);i=u;const g=new m(t.authorizationUrl);if(g.searchParams.set("response_type","code"),g.searchParams.set("client_id",t.clientId),g.searchParams.set("redirect_uri",l),g.searchParams.set("state",a),g.searchParams.set("code_challenge",n.challenge),g.searchParams.set("code_challenge_method","S256"),t.scopes&&t.scopes.length>0&&g.searchParams.set("scope",t.scopes.join(" ")),t.extraParams)for(const[e,n]of Object.entries(t.extraParams))g.searchParams.set(e,n);o("Opening browser for authentication..."),await me(g.toString()),o("Waiting for authorization...");const h=d();let f;const y=new Promise((e,t)=>{f=setTimeout(()=>t(new Error("Authentication timed out")),s)}),w=await Promise.race([h,y]);clearTimeout(f),o("Exchanging authorization code for tokens...");const S=await exchangeCodeForTokens(t,w,n.verifier,l);return await storeTokens(e,S),o("Authentication successful!"),{success:!0,tokens:S}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}finally{i&&i.close()}}function createRefreshCallback(e){return t=>refreshAccessToken({config:e,refreshToken:t})}__export(cE,{DEFAULT_OAUTH_CALLBACK_PORT:()=>iE,LOCALHOST_IP:()=>aE,createRefreshCallback:()=>createRefreshCallback,performOAuthFlow:()=>performOAuthFlow,refreshAccessToken:()=>refreshAccessToken});var uE,dE,mE,pE=__esm({"src/mcp/auth/oauth-flow.ts"(){Ht(),Zb(),lE(),iE=8085,aE="127.0.0.1",__name(generateRandomString,"generateRandomString"),__name(generatePKCE,"generatePKCE"),__name(escapeHtml,"escapeHtml"),__name(startCallbackServer,"startCallbackServer"),__name(exchangeCodeForTokens,"exchangeCodeForTokens"),__name(refreshAccessToken,"refreshAccessToken"),__name(performOAuthFlow,"performOAuthFlow"),__name(createRefreshCallback,"createRefreshCallback")}}),gE=__esm({"src/mcp/client/http-transport.ts"(){Ht(),Qb(),Zb(),lE(),uE=class _HttpTransport extends De{constructor(e){super(),this.options=e}static{__name(this,"HttpTransport")}nextRequestId=0;isConnected=!1;abortController=null;static fromConfig({config:e,serverName:t}){if("http"!==e.transport)throw new Error("Config is not for http transport");if(!e.url)throw new Error("URL is required for http transport");return new _HttpTransport({url:e.url,headers:e.headers,serverName:t,oauth:e.oauth?{authorizationUrl:e.oauth.authorizationUrl,tokenUrl:e.oauth.tokenUrl,clientId:e.oauth.clientId,clientSecret:e.oauth.clientSecret,scopes:e.oauth.scopes}:void 0})}async connect(){this.isConnected||(this.abortController=new AbortController,this.isConnected=!0)}sessionId=null;async getHeaders(){const e={"Content-Type":"application/json",Accept:"application/json, text/event-stream","User-Agent":`${zb.name}/${zb.version}`,...this.options.headers};if(this.sessionId&&(e["Mcp-Session-Id"]=this.sessionId),this.options.serverName&&this.options.oauth){if(!this.options.oauth.clientSecret){const e=await getClientSecret(this.options.serverName);e&&(this.options.oauth.clientSecret=e)}const t=__name(async e=>{const{refreshAccessToken:t}=await Promise.resolve().then(()=>(pE(),cE));return t({config:this.options.oauth,refreshToken:e})},"refreshCallback"),n=await getValidAccessToken({serverName:this.options.serverName,refreshCallback:t});n&&(e.Authorization=`Bearer ${n}`)}return e}parseSSEResponse(e){const t=e.split("\n");for(const e of t)if(e.startsWith("data: ")){const t=e.slice(6).trim();if(t&&"[DONE]"!==t)try{return JSON.parse(t)}catch{}}return null}async request(e,t){if(!this.isConnected)throw new Error("Transport is not connected");const n={jsonrpc:"2.0",method:e,id:this.nextRequestId++,...t&&{params:t}},r=new AbortController,s=setTimeout(()=>r.abort(),rE);this.abortController&&this.abortController.signal.addEventListener("abort",()=>r.abort(),{once:!0});try{const e=await this.getHeaders(),t=await fetch(this.options.url,{method:"POST",headers:e,body:JSON.stringify(n),signal:r.signal});if(!t.ok){let e=t.statusText;try{const n=await t.text(),r=JSON.parse(n);r.error?.message?e=r.error.message:r.message&&(e=r.message)}catch{}throw new Error(`MCP connection failed (${t.status}): ${e}`)}const s=t.headers.get("mcp-session-id");s&&(this.sessionId=s);const o=t.headers.get("content-type")||"",i=await t.text();if(o.includes("text/event-stream")||i.startsWith("event:")||i.startsWith("data:")){const e=this.parseSSEResponse(i);if(e)return e;throw new Error("Failed to parse SSE response")}return JSON.parse(i)}catch(e){if(e instanceof Error&&"AbortError"===e.name)throw new Error("Request timed out");throw e}finally{clearTimeout(s)}}async notify(e,t){if(!this.isConnected)throw new Error("Transport is not connected");const n={jsonrpc:"2.0",method:e,...t&&{params:t}},r=new AbortController,s=setTimeout(()=>r.abort(),rE);this.abortController&&this.abortController.signal.addEventListener("abort",()=>r.abort(),{once:!0});try{const e=await this.getHeaders();await fetch(this.options.url,{method:"POST",headers:e,body:JSON.stringify(n),signal:r.signal})}catch(e){e instanceof Error&&"AbortError"!==e.name&&this.emit("error",e)}finally{clearTimeout(s)}}async close(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.isConnected=!1,this.emit("close")}get connected(){return this.isConnected}}}});function getMcpConnectionManager(){return mE||(mE=new dE),mE}var hE=__esm({"src/mcp/client/connection-manager.ts"(){Ht(),Qb(),sE(),oE(),gE(),wE(),dE=class extends De{static{__name(this,"McpConnectionManager")}connections=new Map;initialized=!1;initializePromise=null;async initialize(e=process.cwd()){if(!this.initialized){if(this.initializePromise)return this.initializePromise;this.initializePromise=this.doInitialize(e);try{await this.initializePromise}finally{this.initializePromise=null}}}async doInitialize(e){const{config:t,serverScopes:n}=await loadMergedMcpConfig(e),r=[];for(const[e,s]of Object.entries(t.mcpServers)){if(!s.enabled)continue;const t=n.get(e);r.push(this.connectServer(e,s,t))}await Promise.allSettled(r),this.initialized=!0}async connectServer(e,t,n){const r={name:e,config:t,scope:n,transport:this.createTransport(t,e),status:"connecting",tools:[]};this.connections.set(e,r),this.emit("connecting",e);try{await r.transport.connect();const t=await this.initializeProtocol(r);if(r.serverInfo=t.serverInfo,r.capabilities=t.capabilities,r.transport instanceof nE?r.transport.notify("notifications/initialized"):await r.transport.notify("notifications/initialized"),t.capabilities.tools){const e=await this.fetchTools(r);r.tools=e.tools}r.status="connected",this.emit("connected",e,r.tools.length)}catch(t){r.status="error",r.error=t instanceof Error?t.message:String(t),this.emit("error",e,r.error)}}createTransport(e,t){return"stdio"===e.transport?nE.fromConfig(e):uE.fromConfig({config:e,serverName:t})}async initializeProtocol(e){const t=await e.transport.request("initialize",{protocolVersion:Ub,capabilities:{roots:{}},clientInfo:zb});if(t.error)throw new Error(`Initialize failed: ${t.error.message}`);return t.result}async fetchTools(e){const t=await e.transport.request("tools/list");if(t.error)throw new Error(`Tools list failed: ${t.error.message}`);return t.result}getConnectedServers(){return Array.from(this.connections.values()).map(e=>({name:e.name,config:e.config,scope:e.scope,status:e.status,error:e.error,capabilities:e.capabilities,serverInfo:e.serverInfo,tools:e.tools}))}getAllTools(){const e=[];for(const t of this.connections.values())if("connected"===t.status)for(const n of t.tools)e.push({serverName:t.name,tool:n,prefixedName:`mcp__${t.name}__${n.name}`});return e}async callTool(e,t,n){const r=this.connections.get(e);if(!r)throw new Error(`Server '${e}' not found`);if("connected"!==r.status)throw new Error(`Server '${e}' is not connected (status: ${r.status})`);const s=await r.transport.request("tools/call",{name:t,arguments:n});if(s.error)throw new Error(`Tool call failed: ${s.error.message}`);return s.result}async callToolByPrefixedName(e,t){const n=parseMcpToolName(e);if(!n)throw new Error(`Invalid MCP tool name: ${e}`);return this.callTool(n.serverName,n.toolName,t)}async disconnectServer(e){const t=this.connections.get(e);t&&(await t.transport.close(),t.status="disconnected",this.emit("disconnected",e))}async disconnectAll(){const e=[];for(const t of this.connections.values())e.push(t.transport.close());await Promise.allSettled(e),this.connections.clear(),this.initialized=!1}async reconnectServer(e){const t=this.connections.get(e);if(!t)throw new Error(`Server '${e}' not found`);await t.transport.close(),await this.connectServer(e,t.config,t.scope)}async ensureServerConnection(e,t=process.cwd()){const{config:n,serverScopes:r}=await loadMergedMcpConfig(t),s=n.mcpServers[e];if(!s)throw new Error(`Server '${e}' not found`);if(!1===s.enabled)throw new Error(`Server '${e}' is disabled`);if(this.connections.get(e))return void await this.reconnectServer(e);const o=r.get(e);if(!o)throw new Error(`Server '${e}' scope not found`);await this.connectServer(e,s,o)}get isInitialized(){return this.initialized}},mE=null,__name(getMcpConnectionManager,"getMcpConnectionManager")}});function mcpToolToSchema({serverName:e,tool:t}){const n=`mcp__${e}__${t.name}`,r=t.inputSchema||{},s=r.properties??{},o=r.required;return{name:n,description:t.description||`MCP tool: ${t.name} (from ${e})`,input_schema:{type:"object",properties:s,...o&&o.length>0?{required:o}:{}}}}function getAllMcpToolSchemas(){return getMcpConnectionManager().getAllTools().map(({serverName:e,tool:t})=>mcpToolToSchema({serverName:e,tool:t}))}function isMcpTool(e){return e.startsWith("mcp__")}function parseMcpToolName(e){if(!isMcpTool(e))return null;const t=e.split("__");return t.length<3?null:{serverName:t[1],toolName:t.slice(2).join("__")}}async function executeMcpTool({prefixedName:e,args:t}){const n=getMcpConnectionManager();try{const r=await n.callToolByPrefixedName(e,t),s=r.content.map(e=>"text"===e.type?e.text||"":"image"===e.type?`[Image: ${e.mimeType||"unknown type"}]`:"resource"===e.type?`[Resource: ${e.mimeType||"unknown type"}]`:"").join("\n");return{success:!r.isError,result:s,...r.isError&&{error:s}}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}var fE,yE,wE=__esm({"src/mcp/client/tool-adapter.ts"(){Ht(),hE(),__name(mcpToolToSchema,"mcpToolToSchema"),__name(getAllMcpToolSchemas,"getAllMcpToolSchemas"),__name(isMcpTool,"isMcpTool"),__name(parseMcpToolName,"parseMcpToolName"),__name(executeMcpTool,"executeMcpTool")}}),SE=__esm({"src/tools/agents/defaults.ts"(){Ht(),fE=["explore","plan","review","general"],yE=[{name:"explore",description:"Use this for codebase exploration, search, or understanding tasks that require multiple file operations",tools:"glob, grep, read_file, read_directory, read_multiple_files, think",systemPrompt:'You are a codebase explorer. Your prompt will specify depth level and what information is needed.\n\nTOOLS AVAILABLE:\n- glob: Find files by patterns\n- grep: Search code for keywords/patterns\n- read_file: Read specific files\n- read_directory: List directory contents\n- read_multiple_files: Read many files efficiently\n- think: Reason through findings\n\nDEPTH LEVELS:\n- quick: 1-2 files, answer the specific question only\n- medium: 3-5 files, understand the main component and context\n- thorough: 10+ files, comprehensive understanding\n\nINSTRUCTIONS:\n1. Look for "Depth: [level]" in the prompt (usually on line 2)\n2. Identify exactly what information is needed (specified in the prompt)\n3. Use only the file operations needed to get that information\n4. Stop when you have the requested information\n\nIf no depth level specified, default to "quick".\n\nRESPONSE FORMAT:\n- Provide exactly what was requested\n- Include relevant file paths and code sections\n- Match your depth to the specified level\n- Stop when done - don\'t over-explore',location:"personal",filePath:"__builtin__"},{name:"plan",description:"Use this to design implementation approaches by synthesizing exploration findings and considering architectural trade-offs",tools:"read_file, read_multiple_files, think",systemPrompt:"You are an implementation planner and software architect. You receive findings from exploration and design the implementation approach.\n\nTOOLS AVAILABLE:\n- read_file: Read specific files for detailed analysis\n- read_multiple_files: Read many files efficiently\n- think: Reason through design decisions\n\nYOUR ROLE:\n1. Synthesize findings from exploration agents\n2. Identify possible implementation approaches\n3. Consider architectural trade-offs and implications\n4. Determine what clarifications are needed from the user\n5. Design the optimal approach based on existing patterns\n\nDESIGN PROCESS:\n1. Review exploration findings to understand current architecture\n2. Identify 2-4 possible approaches for the task\n3. For each approach, consider:\n - How well it fits existing patterns\n - Complexity vs benefits\n - Risks and potential issues\n - What needs to be modified\n4. Determine if user clarification is needed (approach choice, scope, preferences)\n5. Recommend an approach with clear rationale\n\nOUTPUT FORMAT:\nProvide a structured analysis:\n- **Current Architecture**: Summary of relevant findings\n- **Possible Approaches**: 2-4 options with pros/cons\n- **Recommended Approach**: Your suggestion with rationale\n- **Clarifications Needed**: Questions for the user (if any)\n- **Implementation Outline**: High-level steps for the recommended approach\n\nBe concise but thorough. Focus on actionable design decisions.",location:"personal",filePath:"__builtin__"}]}});function isReservedAgentName(e){return!!e&&fE.includes(e.toLowerCase())}var bE=__esm({"src/tools/agents/utils.ts"(){Ht(),SE(),__name(isReservedAgentName,"isReservedAgentName")}});function getRootAgentDir(){return t.join(w.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await O.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const s=t.join(e,r),o=await O.readFile(s,"utf-8"),{data:i,content:a}=Ne(o),l=i.name||r.replace(".md","");if(isReservedAgentName(l))return null;let u=i.tools||"";return"*"!==u&&'"*"'!==u||(u="*"),{name:l,description:i.description||"",tools:u,systemPrompt:a.trim(),location:n,filePath:s}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}}async function loadAllAgents(){const[e,t]=await Promise.all([loadAgentsFromDirectory(getRootAgentDir(),"personal"),loadAgentsFromDirectory(getLocalAgentDir(),"project")]);return{personal:e,project:t}}var EE,vE,CE=__esm({"src/tools/agents/loader.ts"(){Ht(),Kt(),bE(),__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents")}});function isPlainObject(e){return"object"==typeof e&&null!==e}function escapeControlCharsInJsonStrings(e){const t=[];let n=!1,r=0;for(;r<e.length;){const s=e[r];if(!n){'"'===s&&(n=!0),t.push(s),r++;continue}if("\\"===s){t.push(s,e[r+1]??""),r+=2;continue}if('"'===s){n=!1,t.push(s),r++;continue}const o=s.charCodeAt(0);o>=32?(t.push(s),r++):(t.push(EE[s]??`\\u${o.toString(16).padStart(4,"0")}`),r++)}return t.join("")}function repairTruncatedJson(e){if(!e.startsWith("{"))return null;for(const t of vE)try{const n=JSON.parse(e+t);if(isPlainObject(n))return n}catch{}return null}function tryParseDirectly(e){try{const t=JSON.parse(e);if(isPlainObject(t))return t;if("string"==typeof t)return parseToolArgs(t)}catch{}return null}function tryParseAfterEscaping(e){try{const t=JSON.parse(escapeControlCharsInJsonStrings(e));if(isPlainObject(t))return t}catch{}return null}function parseToolArgs(e){return tryParseDirectly(e)??tryParseAfterEscaping(e)??repairTruncatedJson(e)??repairTruncatedJson(escapeControlCharsInJsonStrings(e))}function normalizeToolInput(e){return"string"!=typeof e?e:parseToolArgs(e)??e}var kE,TE,_E=__esm({"../shared/src/utils/parse-tool-args.ts"(){Ht(),EE={"\n":"\\n","\r":"\\r","\t":"\\t"},vE=['"}','"}}',"}",'": ""}'],__name(isPlainObject,"isPlainObject"),__name(escapeControlCharsInJsonStrings,"escapeControlCharsInJsonStrings"),__name(repairTruncatedJson,"repairTruncatedJson"),__name(tryParseDirectly,"tryParseDirectly"),__name(tryParseAfterEscaping,"tryParseAfterEscaping"),__name(parseToolArgs,"parseToolArgs"),__name(normalizeToolInput,"normalizeToolInput")}}),xE=__esm({"src/utils/logger.ts"(){Ht(),In(),kE=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${ke.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${ke.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${ke.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${ke.warning} ${e}`)}debug(e,t){dlog(`[${this.prefix}] ${e}`,t)}}}});function formatToolResultOutput(e){if(e.output&&"object"==typeof e.output)return e.output;const t=e.result??e.output??"",n="string"==typeof t?t:JSON.stringify(t);return!0===e.isError?{type:"error-text",value:n}:{type:"text",value:n}}async function consumeSSEStream(e,t){const n=e.getReader(),r=new TextDecoder,s=[];let o=null,i="",a=0,l=0,u=0,d=0,m=null,g="";try{for(;;){const{done:e,value:h}=await n.read();if(e)break;g+=r.decode(h,{stream:!0});const f=g.split("\n");g=f.pop()||"";for(const e of f){const n=e.trim();if(!n)continue;let r;try{r=JSON.parse(n)}catch{continue}if("text-delta"!==r.type)if("reasoning-delta"!==r.type)if("reasoning-end"!==r.type)if("tool-call"!==r.type)if("tool-result"!==r.type){if("finish"===r.type){const e=r.totalUsage;e&&(a=e.inputTokens||0,l=e.outputTokens||0,u=e.inputTokenDetails?.cacheReadTokens||0,d=e.inputTokenDetails?.cacheWriteTokens||0),m="tool-calls"===r.finishReason?"tool_calls":"end_turn";continue}if("error"===r.type){const e=r.error,t=e?.message||r.error||"Stream error",n=new Error("string"==typeof t?t:String(t));throw null!=e?.statusCode&&(n.statusCode=e.statusCode),null!=e?.isRetryable&&(n.isRetryable=e.isRetryable),n}}else o=null,s.push({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:formatToolResultOutput(r),providerExecuted:!0===r.providerExecuted||void 0});else o=null,TE.debug(`[SSE] tool-call: name=${r.toolName}, id=${r.toolCallId}`),s.push({type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:normalizeToolInput(r.input??r.args??{}),providerExecuted:!0===r.providerExecuted||void 0});else i&&(s.push({type:"reasoning",text:i}),i="");else i+=r.text??"";else o||(o={type:"text",text:""},s.push(o)),o.text+=r.text,t?.onText?.(r.text)}}}finally{n.releaseLock()}i&&s.push({type:"reasoning",text:i});const h=s.filter(e=>"tool-call"===e.type).length;return h>0&&TE.debug(`[SSE] Stream complete: ${s.length} blocks, ${h} tool calls, stop_reason=${m}`),{content:s,usage:{input_tokens:a,output_tokens:l,cache_read_input_tokens:u||void 0,cache_creation_input_tokens:d||void 0},stop_reason:m}}var PE=__esm({"src/utils/sse-stream-consumer.ts"(){Ht(),_E(),xE(),TE=new kE("SSEStreamConsumer"),__name(formatToolResultOutput,"formatToolResultOutput"),__name(consumeSSEStream,"consumeSSEStream")}});function toRelativePath(t){const n=global.COMMAND_CODE_CWD||process.cwd(),r=process.env.HOME||process.env.USERPROFILE||"",s=e.relative(n,t);return s.startsWith("..")?r&&t.startsWith(r)?t.replace(r,"~"):t:""===s?e.basename(t):s}function replacePathsInText(t){if(!t||"string"!=typeof t)return t;let n=t;return n=n.replace(/\/(?:Users|home|opt|var|tmp|usr|etc)\/[^\s'"`,;)}\]]+/g,t=>e.isAbsolute(t)?toRelativePath(t):t),n=n.replace(/[A-Za-z]:\\[^\s'"`,;)}\]]+/g,e=>toRelativePath(e)),n}var AE,IE,NE,RE,$E,ME,LE,DE,OE,FE,qE,jE,BE,UE,zE,WE,GE,HE,QE,VE,KE,YE,JE,XE,ZE,ev,tv,nv,rv,sv,ov,iv,av,lv,cv=__esm({"src/tools/utils/path-display.ts"(){Ht(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText")}}),uv={};__export(uv,{FeedEntrySchema:()=>BE,LLM_STATUS_MESSAGES:()=>rv,createAgentToolEntry:()=>XE,createAssistantEntry:()=>WE,createBashEntry:()=>HE,createCommandResultEntry:()=>YE,createErrorEntry:()=>VE,createIDEStatusEntry:()=>JE,createInfoEntry:()=>zE,createSystemEntry:()=>QE,createTasteOnboardingEntry:()=>KE,createToolEntry:()=>GE,createUserEntry:()=>UE,formatError:()=>ev,getRandomLLMStatus:()=>sv,getToolDisplayName:()=>ov,getToolInputContent:()=>av,isErrorEntry:()=>tv,isPendingEntry:()=>nv,parseTodosFromOutput:()=>lv,updateEntryWithOutput:()=>ZE});var dv=__esm({"src/types/feed.ts"(){Ht(),Zy(),wE(),cv(),hs(),AE=f.object({id:f.string(),timestamp:f.number(),type:f.literal("image"),source:f.object({type:f.enum(["base64","url"]),media_type:f.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:f.string()})}),IE=f.object({id:f.string(),timestamp:f.number(),input:f.string(),output:f.string().optional(),metadata:f.record(f.string(),f.any()).optional(),images:f.array(AE).optional().default([])}),NE=IE.extend({role:f.literal("user")}),RE=IE.extend({role:f.literal("assistant")}),$E=IE.extend({role:f.literal("tool"),name:f.string(),description:f.string().optional()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),ME=IE.extend({role:f.literal("bash"),command:f.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),LE=IE.extend({role:f.literal("system")}),DE=IE.extend({role:f.literal("error")}),OE=IE.extend({role:f.literal("info")}),FE=IE.extend({role:f.literal("taste-onboarding")}),qE=IE.extend({role:f.literal("command-result"),hasError:f.boolean().optional(),details:f.string().optional()}),jE=IE.extend({role:f.literal("ide-status"),status:f.enum(["connected","installed","needs_reload","not_in_ide","failed"]),ide:f.string().nullable(),details:f.array(f.string()).optional()}),BE=f.discriminatedUnion("role",[NE,RE,$E,ME,LE,DE,OE,FE,qE,jE]),UE=__name((e,t)=>BE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),zE=__name((e,t)=>BE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e,metadata:t}),"createInfoEntry"),WE=__name(e=>BE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),GE=__name((e,t,n)=>BE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),HE=__name(e=>BE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),QE=__name((e,t)=>BE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e,metadata:t}),"createSystemEntry"),VE=__name(e=>BE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),KE=__name(()=>BE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),YE=__name((e,t=!1,n)=>BE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),JE=__name((e,t,n)=>BE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"ide-status",input:"",status:e,ide:t,details:n}),"createIDEStatusEntry"),XE=__name(({name:e,input:t})=>{const n=Date.now();return BE.parse({id:crypto.randomUUID(),timestamp:n,role:"tool",name:e,input:t,output:void 0,metadata:{isAgent:!0,status:"running",startTime:n,tokensUsed:0}})},"createAgentToolEntry"),ZE=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return BE.parse(n)},"updateEntryWithOutput"),ev=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),tv=__name(e=>/^error:/i.test(e.output??""),"isErrorEntry"),nv=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),rv=["Yapping…","Brewing…","Contemplating…","Conjuring…","Pondering…","Mixing…","Stirring…","Channeling…","Sculpting…","Crystallizing…","Spinning…","Tuning…","Sparking…","Revving…","Cruising…","Exploring…","Blazing…","Climbing…","Diving…","Surfing…","Riding…","Dancing…","Juggling…","Performing…","Casting…","Cooking…","Baking…","Seasoning…","Garnishing…","Vibing…","Chilling…","Grooving…","Jamming…","Swaying…","Bouncing…","Flowing…","Gliding…","Floating…","Drifting…","Wandering…","Meandering…","Strolling…","Skipping…","Hopping…","Leaping…","Soaring…","Glowing…","Shimmering…","Twinkling…","Flickering…","Pulsing…","Humming…","Buzzing…","Whirring…","Purring…","Chirping…","Whistling…","Giggling…","Snickering…","Chuckling…","Grinning…","Supercalifragilisting…","Somethingsomethinging…","Smirking…","Winking…","Nodding…","Stretching…","Flexing…","Wiggling…","Swirling…","Twirling…","Spiraling…","Weaving…","Bobbing…","Rocking…","Swinging…","Swooshing…","Zipping…","Zooming…","Whizzing…","Zapping…","Popping…","Snapping…","Crackling…","Sizzling…","Bubbling…","Fizzing…"],sv=__name(()=>rv[Math.floor(Math.random()*rv.length)],"getRandomLLMStatus"),ov=__name(e=>{switch(e){case Gy.READ_FILE:return"READ";case Gy.EDIT_FILE:return"EDIT";case Gy.WRITE_FILE:return"WRITE";case Gy.READ_DIRECTORY:return"LIST";case Gy.READ_MULTIPLE_FILES:return"READ[n]";case Gy.GREP:return"SEARCH";case Gy.SHELL_COMMAND:return"SHELL";case Gy.TODO_WRITE:return"TODOS";case Gy.THINKING:return"thinking…";case Hy.WEB_SEARCH:return"WEB SEARCH";case Hy.WEB_FETCH:return"WEB FETCH";case Gy.QUESTION:return"QUESTION";case Gy.EXPLORE:return"EXPLORE";case Gy.KILL_SHELL:return"KILL SHELL";default:if(isMcpTool(e)){const t=parseMcpToolName(e);if(t){const e=t.toolName.replace(/[-_]/g," ").toUpperCase();return`${t.serverName}: ${e} (MCP)`}}return e.replace(/_/g," ").toUpperCase()}},"getToolDisplayName"),iv=__name(e=>{const t=Object.entries(e);if(0===t.length)return"";const[n,r]=t[0];return`${n}: ${truncateString({text:"string"==typeof r?r:JSON.stringify(r)??"",maxChars:as})}${t.length>1?` (+${t.length-1} more)`:""}`},"formatMcpToolParams"),av=__name((e,t)=>{try{switch(e){case Gy.READ_FILE:case Gy.WRITE_FILE:const n=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(n);case Gy.EDIT_FILE:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Gy.READ_DIRECTORY:return toRelativePath(t.path||"directory");case Gy.GREP:const r=t.path||"files";return`"${t.pattern}" in ${toRelativePath(r)}`;case Gy.SHELL_COMMAND:if(t.command){const e=Array.isArray(t.args)&&t.args.length>0?` ${t.args.join(" ")}`:"string"==typeof t.args&&t.args?` ${t.args}`:"";return`${t.command}${e}`}return t.command||"";case Gy.TODO_WRITE:let s;try{s="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=lv(s);return`${e?e.length:0} items`}catch{return"items"}case Gy.THINKING:return t.content||"planning";case Gy.READ_MULTIPLE_FILES:const o=t.include||[];if(!Array.isArray(o)||0===o.length)return"multiple files";const i=o.slice(0,cs).map(toRelativePath).join(", "),a=o.length-cs;return a>0?`${i} (+${a} more)`:i;case Hy.WEB_SEARCH:return t.query||"search";case Hy.WEB_FETCH:return t.url||"fetch";case Gy.QUESTION:return"User answered questions";case Gy.KILL_SHELL:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";case Gy.ENTER_PLAN_MODE:case Gy.EXIT_PLAN_MODE:return"";default:{if(isMcpTool(e)&&t&&"object"==typeof t)return iv(t);let n=t?.messages||[];if("string"==typeof n)try{n=JSON.parse(n)}catch(e){return JSON.stringify(t||{})}if(Array.isArray(n)&&n.length>0&&n[0]&&"object"==typeof n[0]&&"content"in n[0]){const e=n[0].content;if("string"==typeof e){const t=e.trim(),n=t.indexOf(".");return truncateString({text:n>0?t.slice(0,n):t,maxChars:ls})}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),lv=__name(e=>{try{const t=JSON.parse(e);return Array.isArray(t)&&t.every(e=>e.id&&e.content&&e.status)?t:null}catch{return null}},"parseTodosFromOutput")}});async function processFileReferences(t){const n=[];let r=t;const s=[...t.matchAll(/@([^\s@]+)/g)];for(const t of s){const s=t[0],o=t[1];try{const t=e.isAbsolute(o)?o:e.resolve(process.cwd(),o),i=await readFileContent({absolutePath:t});if("binary"===i.contentType)continue;const a=String(i.content),l=e.relative(process.cwd(),t),u=1e5;if(a.length>u){n.push({token:s,resolvedPath:t,content:"",tooLarge:!0});const e=`${l}`;r=r.replace(s,e);continue}n.push({token:s,resolvedPath:t,content:a});const d=`{${l}: ${a}}`;r=r.replace(s,d)}catch(e){continue}}return{displayContent:t,processedContent:r,fileReferences:n}}function reconstructContent(t,n){let r=t;for(const t of n){const n=`{${e.relative(process.cwd(),t.resolvedPath)}: ${t.content}}`;r=r.replace(t.token,n)}return r}var mv,pv=__esm({"src/utils/file-references.ts"(){Ht(),Ew(),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent")}}),gv=__esm({"src/utils/strip-ide-context.ts"(){Ht(),mv=__name(e=>e.replace(/<ide-context>[\s\S]*?<\/ide-context>\s*/g,""),"stripIdeContext")}});function buildToolNameMap(e){const t=new Map;for(const n of e)if("assistant"===n.role&&Array.isArray(n.content))for(const e of n.content){const n=e;"tool_use"!==n.type&&"server_tool_use"!==n.type||t.set(n.id,n.name)}return t}function extractResultValue(e){return"string"==typeof e.content?e.content:JSON.stringify(e.content??"")}function isServerToolError(e){return"object"==typeof e.content&&null!==e.content&&("type"in e.content&&["web_search_tool_result_error","web_fetch_tool_result_error","web_search_tool_error","web_fetch_tool_error"].includes(e.content.type))}function convertUserMessage(e,t){const n=[],r=[];for(const s of e){const e=s;if("tool_result"===e.type){const r=extractResultValue(e);n.push({type:"tool-result",toolCallId:e.tool_use_id,toolName:t.get(e.tool_use_id)??"unknown",output:e.is_error?{type:"error-text",value:r}:{type:"text",value:r}});continue}if("text"!==e.type){if("image"===e.type){const t="base64"===e.source?.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source?.data??"";r.push({type:"image",image:t});continue}}else r.push({type:"text",text:e.text})}const s=[];if(n.length>0&&s.push({role:"tool",content:n}),r.length>0){const e=r[0],t=1===r.length&&"text"===e.type?e.text:r;s.push({role:"user",content:t})}return s}function convertAssistantBlock(e,t){const n=e;if("text"===n.type&&n.text)return{assistantPart:{type:"text",text:n.text}};if("thinking"===n.type&&n.thinking)return{assistantPart:{type:"reasoning",text:n.thinking}};if("tool_use"===n.type)return t.set(n.id,n.name),{assistantPart:{type:"tool-call",toolCallId:n.id,toolName:n.name,input:n.input??{}}};if("server_tool_use"===n.type)return{assistantPart:{type:"tool-call",toolCallId:n.id,toolName:n.name,input:n.input??{},providerExecuted:!0}};if("web_search_tool_result"===n.type||"web_fetch_tool_result"===n.type||"server_tool_result"===n.type){const e=extractResultValue(n);return{toolResult:{type:"tool-result",toolCallId:n.tool_use_id,toolName:t.get(n.tool_use_id)??"unknown",output:isServerToolError(n)?{type:"error-text",value:e}:{type:"text",value:e},providerExecuted:!0}}}return{}}function convertAssistantMessage(e,t){const n=[],r=[];for(const s of e){const{assistantPart:e,toolResult:o}=convertAssistantBlock(s,t);e&&n.push(e),o&&r.push(o)}const s=[];if(n.length>0){const e=n[0],t=1===n.length&&"text"===e.type?e.text:n;s.push({role:"assistant",content:t})}return r.length>0&&s.push({role:"tool",content:r}),s}function legacyAnthropicToSession(e){const t=buildToolNameMap(e),n=[];for(const r of e)"string"!=typeof r.content?Array.isArray(r.content)&&("user"!==r.role?"assistant"!==r.role||n.push(...convertAssistantMessage(r.content,t)):n.push(...convertUserMessage(r.content,t))):n.push({role:r.role,content:r.content});return n}function isLegacyFormat(e){const t=e.metadata;return!t||2!==t.version}var hv,fv,yv,wv,Sv,bv,Ev=__esm({"src/migrations/legacy-message-compat.ts"(){Ht(),__name(buildToolNameMap,"buildToolNameMap"),__name(extractResultValue,"extractResultValue"),__name(isServerToolError,"isServerToolError"),__name(convertUserMessage,"convertUserMessage"),__name(convertAssistantBlock,"convertAssistantBlock"),__name(convertAssistantMessage,"convertAssistantMessage"),__name(legacyAnthropicToSession,"legacyAnthropicToSession"),__name(isLegacyFormat,"isLegacyFormat")}}),vv=__esm({"src/sessions/index.ts"(){Ht(),dv(),pv(),Kt(),Cs(),In(),gv(),Ev(),hv=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(w.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Le(process.cwd())}constructor(e){this.sessionId=e||crypto.randomUUID();const n=_SessionManager.getCurrentProjectDirName();this.projectPath=t.join(_SessionManager.getProjectsBasePath(),n),this.sessionFilePath=t.join(this.projectPath,`${this.sessionId}.jsonl`);try{this.gitBranch=$("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await O.mkdir(this.projectPath,{recursive:!0}),!0}catch(e){return console.error("Error initializing project:",e),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"project_init_failed"}),context:{component:ys.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await O.stat(this.projectPath)).isDirectory()}catch{return!1}}async saveMessages(e,t){try{if(0===e.length)return;const n=JSON.stringify(e);if(n===this.lastSavedMessagesHash)return;await this.initializeProject();const r=[];for(const n of e){const e=crypto.randomUUID(),s={id:e,timestamp:n.meta.timestamp,sessionId:this.sessionId,parentId:this.lastMessageId,role:n.message.role,content:n.message.content,gitBranch:this.gitBranch,metadata:{...n.meta,version:2,...t?.metadata||{}}};r.push(JSON.stringify(s)),this.lastMessageId=e}await O.writeFile(this.sessionFilePath,r.join("\n")+"\n"),this.lastSavedMessagesHash=n}catch(e){console.error("Failed to save messages to session:",e)}}async loadMessages(e){const n=e||this.sessionId,r=t.join(this.projectPath,`${n}.jsonl`);try{const e=(await O.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()),t=[];let s=0;const o=[];for(const t of e)try{o.push(JSON.parse(t))}catch(e){s++,console.error("Error parsing session line:",e)}if(o.some(e=>isLegacyFormat(e))){const e=legacyAnthropicToSession(o.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content}))),s=o.filter(e=>"user"===e.role||"assistant"===e.role);let i=0;for(const n of e){const e=s[Math.min(i,s.length-1)];"tool"!==n.role&&"user"!==n.role||i++,t.push({message:n,meta:{timestamp:e?.timestamp??(new Date).toISOString(),source:"cli",...e?.metadata||{}}})}dlog(`[Session] Migrating v1 session to v2: ${r} (${t.length} messages)`);const a=t.map(e=>JSON.stringify({id:crypto.randomUUID(),timestamp:e.meta.timestamp,sessionId:n,parentId:null,role:e.message.role,content:e.message.content,gitBranch:this.gitBranch,metadata:{...e.meta,version:2}}));await O.writeFile(r,a.join("\n")+"\n").catch(()=>{})}else for(const e of o)"user"!==e.role&&"assistant"!==e.role&&"tool"!==e.role||t.push({message:{role:e.role,content:e.content},meta:{timestamp:e.timestamp,source:"cli",...e.metadata||{}}});return{messages:t,corruptedLines:s,totalLines:e.length}}catch(e){return console.error("Error loading messages:",e),{messages:[],corruptedLines:0,totalLines:0}}}reconstructFeedFromMessages(e){const t=[];for(const n of e){const e=n.message,r=Date.now(),s=crypto.randomUUID();if("tool"!==e.role)if("user"===e.role){let n="";if("string"==typeof e.content)n=e.content;else if(Array.isArray(e.content))for(const t of e.content)"text"===t.type&&(n+=t.text);n=mv(n),n&&t.push({id:s,timestamp:r,role:"user",input:n,images:[]})}else if("assistant"===e.role){let n="";if("string"==typeof e.content)t.push({id:s,timestamp:r,role:"assistant",input:e.content,images:[]});else if(Array.isArray(e.content)){for(const r of e.content)if("text"===r.type)n+=r.text;else if("tool-call"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=av(r.toolName,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.toolName,input:e,output:"Completed",images:[]})}n.trim()&&t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]})}}}return t}async loadSession(e){const n=e||this.sessionId,r=t.join(this.projectPath,`${n}.jsonl`);try{const e=(await O.readFile(r,"utf-8")).trim().split("\n"),t=[];for(const n of e)if(n.trim())try{const e=JSON.parse(n);t.push(e)}catch(e){console.error("Error parsing session line:",e)}return t}catch(e){return console.error("Error loading session:",e),[]}}convertToFeedEntries(e){return e.map(e=>{const t={id:e.id,timestamp:new Date(e.timestamp).getTime(),role:e.role,metadata:e.metadata};return"object"==typeof e.content&&null!==e.content&&"input"in e.content?{...t,input:e.content.input,output:e.content.output,...e.content.name?{name:e.content.name}:{},...e.content.command?{command:e.content.command}:{}}:{...t,input:"string"==typeof e.content?e.content:JSON.stringify(e.content)}})}convertToAnthropicMessages(e){return e.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>{let t;if(t="string"==typeof e.content?e.content:e.content&&"object"==typeof e.content?e.content.input||JSON.stringify(e.content):"","user"===e.role&&e.metadata?.fileReferences)try{t=reconstructContent(t,e.metadata.fileReferences)}catch(e){console.error("Failed to reconstruct file content from session:",e)}return{role:e.role,content:t}})}static async isProjectInitialized(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return(await O.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await O.mkdir(r,{recursive:!0}),!0}catch(e){return console.error("Error initializing project directory:",e),!1}}static async listSessions(){const e=_SessionManager.getCurrentProjectDirName(),n=t.join(_SessionManager.getProjectsBasePath(),e);try{try{await O.access(n)}catch{return[]}const e=(await O.readdir(n)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".prompts.")&&!e.includes(".checkpoints.")),r=[];for(const s of e){const e=s.replace(".jsonl",""),o=t.join(n,s);try{const t=await O.stat(o),s=(await O.readFile(o,"utf-8")).trim().split("\n").filter(e=>e.trim());if(s.length>0){let o="",i="";const a=JSON.parse(s[0]);a.gitBranch&&(i=a.gitBranch);for(const e of s){const t=JSON.parse(e);if("user"===t.role){if("string"==typeof t.content)o=t.content;else if(Array.isArray(t.content)){for(const e of t.content)if("text"===e.type){o=e.text;break}}else t.content?.input&&(o=t.content.input);if(o)break}}o=mv(o);const l=await _SessionManager.loadSessionMetaForId(e,n),u=l?.title;r.push({id:e,createdAt:t.birthtime.toISOString(),lastModified:t.mtime.toISOString(),firstMessage:o||"No messages",title:u||void 0,messageCount:s.length,projectPath:n,gitBranch:i||"-"})}}catch(t){console.error(`Error processing session ${e}:`,t)}}return r.sort((e,t)=>new Date(t.lastModified).getTime()-new Date(e.lastModified).getTime())}catch(e){return console.error("Error listing sessions:",e),[]}}getSessionId(){return this.sessionId}async saveShareInfo(e){const n=t.join(this.projectPath,`${this.sessionId}.share.json`);try{await O.writeFile(n,JSON.stringify(e,null,2))}catch(e){console.error("Failed to save share info:",e)}}async loadShareInfo(){const e=t.join(this.projectPath,`${this.sessionId}.share.json`);try{const t=await O.readFile(e,"utf-8");return JSON.parse(t)}catch(e){return null}}async deleteShareInfo(){const e=t.join(this.projectPath,`${this.sessionId}.share.json`);try{await O.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await O.readFile(this.getMetaFilePath(),"utf-8");return JSON.parse(e)}catch(e){return e instanceof SyntaxError&&dlog("Session",`Corrupt session meta file: ${this.getMetaFilePath()}`),null}}async saveSessionMeta(e){try{const t={...await this.loadSessionMeta(),...e};return await O.writeFile(this.getMetaFilePath(),JSON.stringify(t,null,2)),!0}catch(e){return dlog("Session",`Failed to save session meta: ${e}`),!1}}async saveSessionTitle(e){return await this.saveSessionMeta({title:e})}async loadSessionTitle(){const e=await this.loadSessionMeta();return e?.title||null}static async loadProjectMetaFiles(){const e=_SessionManager.getCurrentProjectDirName(),n=t.join(_SessionManager.getProjectsBasePath(),e);try{await O.access(n)}catch{return[]}const r=(await O.readdir(n)).filter(e=>e.endsWith(".meta.json"));return Promise.all(r.map(async e=>{const t=e.slice(0,-10);return{sessionId:t,meta:await _SessionManager.loadSessionMetaForId(t,n)}}))}static async isSessionNameTaken({name:e,excludeSessionId:t}){const n=e.trim().toLowerCase();return!!n&&(await _SessionManager.loadProjectMetaFiles()).some(({sessionId:e,meta:r})=>(!t||e!==t)&&r?.title?.trim().toLowerCase()===n)}static async findSessionByName(e){const t=e.trim().toLowerCase();if(!t)return null;const n=(await _SessionManager.loadProjectMetaFiles()).find(({meta:e})=>e?.title?.trim().toLowerCase()===t);return n?{id:n.sessionId}:null}static async loadSessionMetaForId(e,n){const r=t.join(n,`${e}.meta.json`);try{const e=await O.readFile(r,"utf-8");return JSON.parse(e)}catch(e){return null}}getCheckpointsFilePath(){return t.join(this.projectPath,`${this.sessionId}.checkpoints.jsonl`)}async saveSnapshot(e){const{snapshot:t,isUpdate:n}=e,r=this.getCheckpointsFilePath();try{await this.initializeProject();const e={type:"file-history-snapshot",messageId:t.messageId,snapshot:t,isSnapshotUpdate:n};if(n){let n=[];try{n=(await O.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{}const s=n.findIndex(e=>e.messageId===t.messageId);-1!==s?n[s]=e:n.push(e);const o=n.map(e=>JSON.stringify(e)).join("\n")+"\n";await O.writeFile(r,o)}else await O.appendFile(r,JSON.stringify(e)+"\n")}catch(e){console.error("Failed to save checkpoint snapshot:",e)}}async loadSnapshots(){const e=this.getCheckpointsFilePath();try{const t=(await O.readFile(e,"utf-8")).trim().split("\n").filter(e=>e.trim()),n=[];for(const e of t)try{const t=JSON.parse(e);"file-history-snapshot"===t.type&&n.push(t.snapshot)}catch{}return n}catch{return[]}}async deleteSnapshotsAfter(e){const{messageId:t,inclusive:n=!1}=e,r=this.getCheckpointsFilePath();try{const e=(await O.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e)),s=e.findIndex(e=>e.messageId===t);if(-1===s)return;const o=(n?e.slice(0,s):e.slice(0,s+1)).map(e=>JSON.stringify(e)).join("\n")+"\n";await O.writeFile(r,o)}catch{}}getMessageAtIndex(e){const{index:t,messages:n}=e;if(t<0||t>=n.length)return null;const r=n[t];let s="";if("string"==typeof r.message.content)s=r.message.content;else if(Array.isArray(r.message.content))for(const e of r.message.content)"text"===e.type&&(s+=e.text);return s=mv(s),{messageId:r.meta.messageId||crypto.randomUUID(),content:s}}getMessageIndexById(e){const{messageId:t,messages:n}=e;return n.findIndex(e=>e.meta.messageId===t)}getMessageCount(e){const{messages:t}=e;return t.length}async truncateMessagesAtIndex(e){const{index:t,messages:n}=e,r=n.slice(0,t);return r.length>0&&await this.saveMessages(r),r}}}});function stableStringify(e){return null==e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?"["+e.map(stableStringify).join(",")+"]":"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+stableStringify(e[t])).join(",")+"}"}function generateCacheKey(e,t){return`${e}:${stableStringify(t)}`}async function generateToolDescription(e,t){const n=generateCacheKey(e,t),r=yv.get(n);if(r)return yv.delete(n),yv.set(n,r),dlog(`[ToolDescription] cache hit for ${e}: "${r}"`),r;dlog(`[ToolDescription] generating for ${e}`);try{const e=createPrompt(t);dlog(`[ToolDescription] calling /alpha/generate with model: ${It}`);const r=await getConfiguredProvider(),s=await isOAuthEnforced(),o={[Ct.PROJECT_SLUG]:hv.getCurrentProjectDirName(),[Ct.INTERNAL_TEAM_FLAG_HEADER]:s.toString()},{token:i,oauthProvider:a}=await getOAuthCredentials({provider:r});i&&(o[Ct.OAUTH_TOKEN]=`Bearer ${i}`,a&&(o[Ct.OAUTH_PROVIDER]=a));const l={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:It,max_tokens:Sv,temperature:bv,stream:!0},threadId:crypto.randomUUID()},u=getApiBaseUrl(),d=new xy({baseUrl:u}).post({endpoint:kt.ALPHA.GENERATE,body:l,headers:o,stream:!0}).then(e=>consumeSSEStream(e)),m=await Promise.race([d,new Promise((e,t)=>setTimeout(()=>t(new Error("Timeout")),5e3))]);if(!m)return dlog("[ToolDescription] no result"),null;const g=m.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("").trim();dlog(`[ToolDescription] raw response: "${g}"`);const h=cleanDescription(g);if(h){if(yv.size>=fv){const e=yv.keys().next().value;void 0!==e&&yv.delete(e)}yv.set(n,h),dlog(`[ToolDescription] cached: "${h}"`)}else dlog("[ToolDescription] description rejected after cleaning");return h}catch(t){return dlog(`[ToolDescription] failed for ${e}: ${t instanceof Error?t.message:String(t)}`),null}}function sanitize(e){return String(e).replace(/[\r\n\t\f\v]+/g," ").replace(/\s+/g," ").trim().slice(0,wv)}function createPrompt(e){return`Precisely describe what this command does in active voice. Never use a word like "complex" or "risk" in description. Start with a verb, capital letter, no period. Never say you need to see more or that the command is incomplete — always describe what the command does based on what you see.\n\nFor simple commands (git, npm, standard CLI tools), keep it brief (5-10 words):\n- ls → "List files in current directory"\n- git status → "Show working tree status"\n- npm install → "Install package dependencies"\n\nFor piped commands or obscure flags, add enough context to clarify what it does:\n- find . -name "*.tmp" -exec rm {} \\; → "Find and delete all .tmp files recursively"\n- git reset --hard origin/main → "Discard all local changes and match remote main"\n- curl -s url | jq '.data[]' → "Fetch JSON from URL and extract data array elements"\n\nCommand: ${`${sanitize(e.command||"")} ${sanitize(Array.isArray(e.args)?e.args.join(" "):e.args||"")}`.trim()}\n\nDescription:`}function cleanDescription(e){let t=e.trim().replace(/^["']|["']$/g,"").replace(/\.$/,"").trim();return t.length>0&&(t=t.charAt(0).toUpperCase()+t.slice(1)),t.split(/\s+/).length<3?null:t}var Cv=__esm({"src/utils/tool-description-generator.ts"(){Ht(),Kt(),In(),Wy(),Xy(),vv(),gn(),xr(),Rr(),PE(),fv=100,yv=new Map,wv=4e3,Sv=80,bv=.3,__name(stableStringify,"stableStringify"),__name(generateCacheKey,"generateCacheKey"),__name(generateToolDescription,"generateToolDescription"),__name(sanitize,"sanitize"),__name(createPrompt,"createPrompt"),__name(cleanDescription,"cleanDescription")}});function resolveNearestAncestor(e){let n=t.dirname(e),r=t.basename(e);for(;n!==t.dirname(n);)try{return t.join(v.realpathSync(n),r)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code){r=t.join(t.basename(n),r),n=t.dirname(n);continue}return null}return null}function resolveSymlinks(e){try{return v.realpathSync(e)}catch(e){if(!(e instanceof Error&&"code"in e&&"ENOENT"===e.code))return null}try{if(v.lstatSync(e).isSymbolicLink())return null}catch{}return resolveNearestAncestor(e)}function resolvePlansDir(e){try{return v.realpathSync(e)}catch{return e}}function isPlanPath(e){const{filePath:n}=e;if(!n||"string"!=typeof n)return!1;const r=w.homedir(),s=n.startsWith("~/")?t.join(r,n.slice(2)):n,o=resolveSymlinks(t.resolve(s));if(!o)return!1;const i=resolvePlansDir(t.join(r,".commandcode","plans"));return o.startsWith(i+t.sep)||o===i}var kv,Tv,_v,xv=__esm({"src/utils/plan-path-validator.ts"(){Ht(),Kt(),__name(resolveNearestAncestor,"resolveNearestAncestor"),__name(resolveSymlinks,"resolveSymlinks"),__name(resolvePlansDir,"resolvePlansDir"),__name(isPlanPath,"isPlanPath")}});function getToolsForMode(e){const{allTools:t,mode:n}=e;return"standard"===n||"auto-accept"===n?t.filter(e=>!Tv.includes(e.name)):"plan"===n?t.filter(e=>!kv.includes(e.name)&&!_v.includes(e.name)):t.filter(e=>!Tv.includes(e.name))}function isToolAllowedInMode(e){const{toolName:t,mode:n,toolParams:r}=e;if(!t||"string"!=typeof t)return{allowed:!1,reason:"Invalid tool name provided."};if("standard"===n||"auto-accept"===n)return{allowed:!0};if("plan"===n){if(isMcpTool(t))return{allowed:!1,reason:"MCP tools are not available in plan mode. Press Shift+Tab to exit plan mode first."};if("write_file"===t&&r?.filePath){const e=r.filePath;return isPlanPath({filePath:e})?{allowed:!0}:{allowed:!1,reason:`Cannot write to "${e}" in plan mode. Use the full absolute path ~/.commandcode/plans/<filename>.md to write plan files.`}}return kv.includes(t)?{allowed:!1,reason:`Tool "${t}" is not available in plan mode. Plan mode is read-only. Press Shift+Tab to exit plan mode.`}:{allowed:!0}}return{allowed:!1,reason:`Invalid permission mode "${n}". Please restart the application.`}}var Pv=__esm({"src/tools/get-tools-for-mode.ts"(){Ht(),xv(),wE(),kv=["edit_file","delete_file","shell_command","todo_write","kill_shell"],Tv=["exit_plan_mode"],_v=["enter_plan_mode"],__name(getToolsForMode,"getToolsForMode"),__name(isToolAllowedInMode,"isToolAllowedInMode")}});function sleep(e){const{delay:t,signal:n}=e;return new Promise((e,r)=>{if(n?.aborted)return r(new Error("Interrupted by user"));const s=setTimeout(()=>{n?.removeEventListener("abort",onAbort),e()},t);function onAbort(){clearTimeout(s),n?.removeEventListener("abort",onAbort),r(new Error("Interrupted by user"))}__name(onAbort,"onAbort"),n?.addEventListener("abort",onAbort,{once:!0})})}var Av,Iv,Nv,Rv=__esm({"src/utils/sleep.ts"(){Ht(),__name(sleep,"sleep")}});function setBenchmarkOutput(e){Av=e}function createBenchmarkCollector(){return Av?{startTime:Date.now(),turnDetails:[],agents:[],maxTurnsReached:!1}:null}function buildAgentMetricsMarker(e){return`\n${Iv}${JSON.stringify(e)}${Nv}`}function extractAgentMetrics(e){const t=e.indexOf(Iv);if(-1===t)return{cleanContent:e,metrics:null};const n=t+Iv.length,r=e.indexOf(Nv,n);if(-1===r)return{cleanContent:e,metrics:null};try{const s=e.substring(n,r),o=JSON.parse(s);return{cleanContent:e.substring(0,t).trimEnd()+e.substring(r+Nv.length),metrics:o}}catch{return{cleanContent:e,metrics:null}}}function createAgentBenchmarkTracker(){return Av?{turns:0,toolCalls:{},toolErrors:0}:null}function trackAgentTurn(e){e&&e.turns++}function trackAgentToolCall(e){const{tracker:t,toolName:n,isError:r}=e;t&&(t.toolCalls[n]=(t.toolCalls[n]??0)+1,r&&t.toolErrors++)}function buildAgentResult(e){const{result:t,tracker:n,agentName:r,startTime:s,tokens:o}=e;return n?t+buildAgentMetricsMarker({name:r,turns:n.turns,toolCalls:n.toolCalls,toolErrors:n.toolErrors,tokens:o,durationMs:Date.now()-s}):t}function writeBenchmarkMetrics(e){if(!Av)return;const t=Date.now()-e.startTime,n=e.turnDetails.length,r={};let s=0,o=0,i=0,a=0;for(const t of e.turnDetails){for(const e of t.toolCalls)s++,r[e.name]=(r[e.name]??0)+1,e.isError&&o++;i+=t.inputTokens,a+=t.outputTokens}const l={wallTimeMs:t,turns:n,turnDetails:e.turnDetails,toolCalls:{total:s,byType:r,errors:o},tokens:{input:i,output:a},maxTurnsReached:e.maxTurnsReached,agents:e.agents};try{E.writeFileSync(Av,JSON.stringify(l,null,2))}catch{}}var $v,Mv=__esm({"src/utils/benchmark-collector.ts"(){Ht(),__name(setBenchmarkOutput,"setBenchmarkOutput"),__name(createBenchmarkCollector,"createBenchmarkCollector"),Iv="\x3c!-- BENCHMARK_AGENT_METRICS:",Nv=" --\x3e",__name(buildAgentMetricsMarker,"buildAgentMetricsMarker"),__name(extractAgentMetrics,"extractAgentMetrics"),__name(createAgentBenchmarkTracker,"createAgentBenchmarkTracker"),__name(trackAgentTurn,"trackAgentTurn"),__name(trackAgentToolCall,"trackAgentToolCall"),__name(buildAgentResult,"buildAgentResult"),__name(writeBenchmarkMetrics,"writeBenchmarkMetrics")}});function agentToTool(t,n){const{clientTools:r,serverTools:s,toolsMap:o,displayNameToToolName:i}=n;return{name:t.name,description:t.description,input_schema:{type:"object",properties:{messages:{type:"array",description:"Messages to pass to the agent",items:{type:"object",properties:{content:{type:"string",description:"The text content of the message"}},required:["content"]}}},required:["messages"]},execute:__name(async(n,a)=>{let l=null;const u=Date.now();let d=null;try{const m=a?.permissionMode||"standard",g=filterToolsForMode({tools:getAvailableTools(t,{clientTools:r,serverTools:s,toolsMap:o,displayNameToToolName:i}),clientTools:r,serverTools:s,mode:m});let h=Date.now();const f=10,y=[];if(a?.onFeedUpdate){const e=av(t.name,n);l=XE({name:t.name,input:e}),a.onFeedUpdate(l)}d=setInterval(()=>{if(a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},a.onFeedUpdate(l)}},1e3);const w=createAgentBenchmarkTracker(),S=await getConfiguredProvider(),E=await isOAuthEnforced(),{token:v,oauthProvider:C}=await getOAuthCredentials({provider:S});validateOAuthToken({token:v,provider:S});const k=getApiBaseUrl(),T=new xy({baseUrl:k});let _=0;const x=[];let P=n?.messages;if("string"==typeof P)try{P=JSON.parse(P)}catch(e){P=[]}if(Array.isArray(P)&&P.length>0)for(const e of P)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&x.push({role:"user",content:t})}const A={stream:!0,messages:x,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:g,model:getConfiguredModel()},I=await isTasteLearningEnabled(),N={[Ct.PROJECT_SLUG]:hv.getCurrentProjectDirName(),[Ct.TASTE_LEARNING]:I.toString(),[Ct.INTERNAL_TEAM_FLAG_HEADER]:E.toString()};v&&(N[Ct.OAUTH_TOKEN]=`Bearer ${v}`,C&&(N[Ct.OAUTH_PROVIDER]=C));const R=getEnvironmentContext(),$=await getMemoryContent([]),M=crypto.randomUUID();let L="",D=!0;const O=__name(()=>{$v.debug("[Agent] Abort signal triggered, stopping immediately"),D=!1,d&&(clearInterval(d),d=null)},"abortHandler");a?.abortSignal&&a.abortSignal.addEventListener("abort",O);try{for(;D;){if(a?.abortSignal?.aborted)throw $v.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:T,body:{mode:"custom-agent",config:R,memory:$,threadId:M,params:{...A,messages:x}},headers:N,abortSignal:a?.abortSignal,onTextDelta:__name(e=>{_+=estimateTokens(e);const t=Date.now();if(a?.onFeedUpdate&&l&&t-h>=f){const e=Math.floor((t-u)/1e3);l={...l,metadata:{...l.metadata,tokensUsed:_,elapsedSeconds:e}},a.onFeedUpdate(l),h=t}},"onTextDelta")});if(trackAgentTurn(w),a?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(_=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool-call"===e.type&&!e.providerExecuted);if(L=t.content.filter(e=>"tool-call"===e.type&&!!e.providerExecuted).length>0?processServerToolBlocks(t,a):t.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===n.length){const e=t.content.filter(e=>"text"===e.type?e.text.trim().length>0:"tool-call"!==e.type&&"tool-result"!==e.type||!e.providerExecuted);e.length>0&&x.push({role:"assistant",content:e}),D=!1;break}const r=t.content.filter(e=>"text"!==e.type||e.text.trim().length>0);r.length>0&&x.push({role:"assistant",content:r});const s=[],o=new Set;let i=!1;for(const t of n){if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");let n=t.input;try{const r=Yy.includes(t.toolName),g=Jy.includes(t.toolName)?generateToolDescription(t.toolName,n).catch(()=>null):Promise.resolve(null);if(r&&a?.onPermissionRequest){d&&(clearInterval(d),d=null);const e=await g;if(!await a.onPermissionRequest(t.toolName,n,e)){$v.debug(`Permission denied for tool: ${t.toolName}`),i=!0;break}d=setInterval(()=>{if(a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{...l.metadata,elapsedSeconds:t}},a.onFeedUpdate(l)}},1e3)}if("object"==typeof n&&null!==n){const r={...n};let s=!1;const o=["path","file_path","absolutePath","filePath","directory","folder"];for(const t of o)if(t in r&&"string"==typeof r[t]){const n=r[t];if(!e.isAbsolute(n)){const o=e.resolve(process.cwd(),n);r[t]=o,s=!0,$v.debug(`Converted '${t}': '${n}' -> '${o}'`)}}"paths"in r&&Array.isArray(r.paths)&&(r.paths=r.paths.map(t=>"string"!=typeof t||e.isAbsolute(t)?t:(s=!0,e.resolve(process.cwd(),t)))),s?(n=r,$v.debug(`Resolved input for ${t.toolName}: ${av(t.toolName,n)}`)):$v.debug(`No path resolution needed for ${t.toolName}: ${av(t.toolName,n)}`)}if(a?.onFeedUpdate&&l){const e=av(t.toolName,n);y.push({name:t.toolName,input:e}),y.length>3&&y.shift();const r=Date.now(),s=Math.floor((r-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:_,elapsedSeconds:s,recentTools:[...y]}},$v.debug(`Updating agent with recentTools (${y.length} tools): ${JSON.stringify(y)}`),a.onFeedUpdate(l)}const h=await executeTool(t.toolName,n,{abortSignal:a?.abortSignal,permissionMode:m});if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");const f=checkToolOutputTokensLimit(h);if(s.push({type:"tool-result",toolCallId:t.toolCallId,toolName:t.toolName,output:{type:"text",value:f}}),o.add(t.toolCallId),trackAgentToolCall({tracker:w,toolName:t.toolName,isError:!1}),a?.onFeedUpdate&&l){const e=Date.now(),t=Math.floor((e-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:_,elapsedSeconds:t,recentTools:[...y]}},a.onFeedUpdate(l)}$v.debug(`Tool executed successfully: ${t.toolName}`)}catch(e){const n=e instanceof Error?e.message:"Unknown error";s.push({type:"tool-result",toolCallId:t.toolCallId,toolName:t.toolName,output:{type:"error-text",value:`Error: ${n}`}}),o.add(t.toolCallId),trackAgentToolCall({tracker:w,toolName:t.toolName,isError:!0}),$v.error(`Tool execution failed: ${t.toolName} - ${n}`)}}if(i){const e=x[x.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool-call"===e.type?o.has(e.toolCallId):"text"===e.type);t.length>0?e.content=t:x.pop()}D=!1;break}x.push({role:"tool",content:s})}}finally{a?.abortSignal&&a.abortSignal.removeEventListener("abort",O)}if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const e=Date.now(),t=(e-u)/1e3;l={...l,output:L||"DONE",metadata:{isAgent:!0,status:"done",startTime:u,endTime:e,tokensUsed:_,elapsedSeconds:t}},a.onFeedUpdate(l)}return buildAgentResult({result:L||"DONE",tracker:w,agentName:t.name,startTime:u,tokens:_})}catch(e){if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const t=Date.now(),n=(t-u)/1e3,r=e instanceof Error?e.message:"Unknown error",s="Interrupted by user"===r||a?.abortSignal?.aborted;l={...l,output:r,metadata:{isAgent:!0,status:s?"interrupted":"error",startTime:u,endTime:t,tokensUsed:l?.metadata?.tokensUsed||0,elapsedSeconds:n}},a.onFeedUpdate(l)}throw e}},"execute")}}function filterToolsForMode(e){const{tools:t,clientTools:n,serverTools:r,mode:s}=e;if("standard"===s||"auto-accept"===s)return t;const o=t.filter(e=>n.includes(e)),i=t.filter(e=>r.includes(e));return[...getToolsForMode({allTools:o,mode:s}),...i]}function getAvailableTools(e,t){const{clientTools:n,serverTools:r,toolsMap:s,displayNameToToolName:o}=t;let i=[];if("*"===e.tools)i=[...n,...r];else if("string"==typeof e.tools&&e.tools){const t=e.tools.split(",").map(e=>e.trim());for(const e of t){let t=o[e];if(!t&&s.has(e)&&(t=e),t){const e=s.get(t);if(e)i.push(e);else{const e=r.find(e=>e.name===t);e&&i.push(e)}}}}else if(Array.isArray(e.tools))for(const t of e.tools){let e=o[t];if(!e&&s.has(t)&&(e=t),e){const t=s.get(e);if(t)i.push(t);else{const t=r.find(t=>t.name===e);t&&i.push(t)}}}return i}async function callAPIWithRetry(e){const{request:t,body:n,headers:r,abortSignal:s,onTextDelta:o}=e;let i=null;for(let e=0;e<5;e++){if(s?.aborted)throw new Error("Interrupted by user");try{const e=await t.post({body:n,stream:!0,endpoint:kt.ALPHA.GENERATE,signal:s,headers:r});return await consumeSSEStream(e,{onText:o})}catch(t){if(i=t,$v.debug(`[callAPIWithRetry] Error on attempt ${e+1}/5: ${t.message||t}, status=${t.status}, code=${t.code}, retryable=${isRetryableError(t)}`),s?.aborted)throw new Error("Interrupted by user");if(isNonRetryableError(t,s))throw formatAPIError(t,s);if(!isRetryableError(t)||4===e)throw formatAPIError(t,s);const n=200*Math.pow(2,e);$v.debug(`API Error (attempt ${e+1}/5): ${t.message}. Retrying in ${n}ms...`),await sleep({delay:n,signal:s})}}throw i||new Error("Failed to get response after retries")}function isNonRetryableError(e,t){return"Interrupted by user"===e?.message||"Insufficient credits"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||t?.aborted||e instanceof _s&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof Ps||403===e?.status}function isRetryableError(e){return!!e?.message&&(!!['Unexpected event order, got error before "message_start"',"API Error: Unexpected event order","Body is unusable: Body has already been read","fetch failed","ECONNRESET","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","network error","socket hang up","UND_ERR_CONNECT_TIMEOUT"].some(t=>e.message.includes(t))||e?.status>=500&&e?.status<600)}function formatAPIError(e,t){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||t?.aborted)return new Error("Interrupted by user");if(e instanceof _s&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof Ps||403===e?.status)return e;if(e?.message?.startsWith("Error:"))return e;let n="Error: ";return e.message?n+="Something went wrong. Please try again or contact support if the issue persists.":e.toString?n+=e.toString():n+="Unknown error occurred",new Error(n)}function processServerToolBlocks(e,t){if(0===e.content.filter(e=>"tool-call"===e.type&&e.providerExecuted).length)return"";let n="";const r=e.content;for(const e of r)if("text"===e.type)n+=e.text;else if("tool-call"===e.type&&e.providerExecuted&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const{message:n,isError:s}=Ky({serverToolBlock:e,contentBlocks:r}),o=av(e.toolName,e.input),i={id:`${e.toolName}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.toolName,input:o,output:s?ev(n):n};t.onFeedUpdate(i)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}var Lv,Dv,Ov=__esm({"src/tools/agents/execute.ts"(){Ht(),Kt(),Rr(),Wy(),Xy(),gn(),Ds(),PE(),Qv(),Cv(),Zy(),Pv(),bS(),Rv(),xE(),dv(),aw(),vv(),xr(),Zy(),Mv(),$v=new kE("AgentExecutor"),__name(agentToTool,"agentToTool"),__name(filterToolsForMode,"filterToolsForMode"),__name(getAvailableTools,"getAvailableTools"),__name(callAPIWithRetry,"callAPIWithRetry"),__name(isNonRetryableError,"isNonRetryableError"),__name(isRetryableError,"isRetryableError"),__name(formatAPIError,"formatAPIError"),__name(processServerToolBlocks,"processServerToolBlocks")}});function initializeAgentManager(e){Dv=e}async function loadAgentTools(){if(!Dv)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");Lv.clear();for(const e of yE){const t=agentToTool(e,Dv);Lv.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,Dv);Lv.set(t.name,t)}}async function getAgentTools(){return 0===Lv.size&&await loadAgentTools(),Array.from(Lv.values())}async function getAgentTool(e){return 0===Lv.size&&await loadAgentTools(),Lv.get(e)}var Fv=__esm({"src/tools/agents/manager.ts"(){Ht(),CE(),Ov(),SE(),Lv=new Map,Dv=null,__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool")}}),qv=__esm({"src/tools/agents/index.ts"(){Ht(),Fv()}});function isPathInTasteDirectory(t){const{filePath:n,projectRoot:r}=t,s=e.join(r,".commandcode","taste"),o=e.normalize(e.resolve(r,n)),i=e.normalize(s);return o.startsWith(i)}function getTasteFileInfo(t){const n=e.normalize(e.resolve(t)),r=e.normalize(e.join(process.cwd(),".commandcode","taste")),s=e.normalize(e.join(y.homedir(),".commandcode","taste"));let o=null;if(n.startsWith(r)?o=r:n.startsWith(s)&&(o=s),!o)return{isTaste:!1};if(!n.endsWith("taste.md"))return{isTaste:!1};const i=e.relative(o,n).split(e.sep);return 1===i.length?{isTaste:!0}:2===i.length?{isTaste:!0,category:i[0]}:{isTaste:!1}}function getTasteAccessError(){return"Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system."}var jv,Bv,Uv,zv,Wv,Gv,Hv=__esm({"src/utils/taste-path-validator.ts"(){Ht(),Kt(),__name(isPathInTasteDirectory,"isPathInTasteDirectory"),__name(getTasteFileInfo,"getTasteFileInfo"),__name(getTasteAccessError,"getTasteAccessError")}});function isAgentTool(e){return!zv.has(e)&&!isMcpTool(e)}async function executeTool(e,t,n){if(isMcpTool(e)){const n=trackToolStart({toolName:e});try{const r=await executeMcpTool({prefixedName:e,args:t});return r.success?(n.end({status:"success"}),r.result??"Tool executed successfully"):(n.end({status:"error",error:new Error(r.error)}),`Error: ${r.error}`)}catch(e){const t=sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"mcp_tool_error"});return n.end({status:"error",error:t}),`Error: ${e instanceof Error?e.message:String(e)}`}}const r=n?.permissionMode||"standard",s=isToolAllowedInMode({toolName:e,mode:r,toolParams:t});if(!s.allowed)throw new Error(s.reason||`Tool "${e}" not allowed in ${r} mode`);let o=Uv.get(e);if(o||(o=await getAgentTool(e)),!o){const t=await getAgentTools(),n=[...Array.from(Uv.keys()),...t.map(e=>e.name)];throw new Error(`Tool "${e}" not found. Available tools: ${n.join(", ")}`)}if(("write_file"===e||"edit_file"===e)&&!0!==n?.allowTasteWrite){const e=t.filePath,n=isPathInTasteDirectory({filePath:e,projectRoot:process.cwd()});if(e&&n)throw new Error("Error: Cannot modify taste files (.commandcode/taste/). These files are managed automatically by the learning system.".replace("Error: ",""))}const i=trackToolStart({toolName:e});try{let r;return r=(!Uv.has(e)||!0===o.acceptsCallbacks)&&n?await o.execute(t,n):await o.execute(t),i.end({status:"success"}),r}catch(e){if(e instanceof Error&&"Interrupted by user"===e.message){const t=sanitizeErrorForTelemetry({error:e,label:"tool_interrupted"});throw i.end({status:"error",error:t}),e}if(e instanceof Error){const t=sanitizeErrorForTelemetry({error:e,label:"tool_error"});return i.end({status:"error",error:t}),`Error: ${e.message}`}return i.end({status:"error",error:new Error("Unknown error occurred")}),"Error: Unknown error occurred"}}async function getToolSchemas(e){const t=e?.mode||"standard",n=null!==db()?[...jv]:jv.filter(e=>e.name!==Gy.DIAGNOSTICS),r=await getAgentTools(),s=getToolsForMode({allTools:n,mode:t}).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema})),o=r.map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}));let i=[];return"plan"!==t&&getMcpConnectionManager().isInitialized&&(i=getAllMcpToolSchemas()),[...s,...o,...i,...Bv]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}var Qv=__esm({"src/tools/index.ts"(){Ht(),Aw(),Hw(),Xw(),aS(),wS(),_S(),$S(),FS(),BS(),WS(),YS(),bb(),Eb(),vb(),Cb(),kb(),qb(),Hb(),_b(),Zy(),wE(),hE(),qv(),Hv(),Cs(),Pv(),jv=[Cw,Uw,Kw,tS,uS,vS,AS,DS,qS,US,HS,ZS,eb,tb,Pb,Bb],Bv=[nb,rb],Uv=new Map(jv.map(e=>[e.name,e])),zv=new Set([...jv.map(e=>e.name),...Bv.map(e=>e.name)]),__name(isAgentTool,"isAgentTool"),__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase"),Wv={},jv.forEach(e=>{Wv[e.name]=toPascalCase(e.name)}),Bv.forEach(e=>{Wv[e.name]=toPascalCase(e.name)}),Gv={},Object.entries(Wv).forEach(([e,t])=>{Gv[t]=e}),initializeAgentManager({clientTools:jv,serverTools:Bv,toolsMap:Uv,displayNameToToolName:Gv})}});async function resolveEditStartLine({filePath:e,oldContent:t}){const n=await I.readFile(e,"utf-8"),r=n.indexOf(t);if(-1!==r)return n.substring(0,r).split("\n").length}function isDirectoryEmpty(){try{return 0===x(process.cwd()).length}catch{return!1}}var Vv=__esm({"src/utils/fs.ts"(){Ht(),__name(resolveEditStartLine,"resolveEditStartLine"),__name(isDirectoryEmpty,"isDirectoryEmpty")}});function parseEmbeddedErrorJSON(e){const t=e.indexOf("{");if(-1===t)return null;try{const n=JSON.parse(e.slice(t));if(n?.error?.message){const r=e.slice(0,t).trim();return{status:/^\d+$/.test(r)?Number(r):null,type:n.error.type||null,message:n.error.message}}}catch{}return null}var Kv=__esm({"src/utils/stream-error-interceptor.ts"(){Ht(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON")}});async function trackLifecycleEvent({eventType:e,metadata:t}){if(isTelemetryEnabled())try{const n=getApiBaseUrl(),r=new xy({baseUrl:n});await r.post({endpoint:kt.ALPHA.LIFECYCLE_EVENTS.TRACK,body:{eventType:e,metadata:t}}),dlog("[lifecycle-event tracked]",{eventType:e})}catch(t){dlog("[lifecycle-event failed]",{eventType:e,error:t})}}var Yv,Jv=__esm({"src/api/track-lifecycle-event.ts"(){Ht(),Wy(),Xy(),Kt(),In(),Mr(),__name(trackLifecycleEvent,"trackLifecycleEvent")}});async function hasFirstMessageBeenTracked(){try{return!0===(await loadUserConfig()).firstMessageSent}catch{return!1}}async function markFirstMessageTracked(){try{await updateUserConfig({firstMessageSent:!0})}catch(e){dlog("[detect-first-message] failed to mark as tracked",{error:e})}}async function detectAndTrackFirstMessage(){if(!await hasFirstMessageBeenTracked())return Yv||(Yv=(async()=>{try{await trackLifecycleEvent({eventType:"cli_first_message"}),await markFirstMessageTracked(),dlog("[detect-first-message] tracked first message")}catch(e){dlog("[detect-first-message] failed to track",{error:e})}finally{Yv=null}})())}var Xv,Zv,eC=__esm({"src/utils/detect-first-message.ts"(){Ht(),Jv(),In(),xr(),Yv=null,__name(hasFirstMessageBeenTracked,"hasFirstMessageBeenTracked"),__name(markFirstMessageTracked,"markFirstMessageTracked"),__name(detectAndTrackFirstMessage,"detectAndTrackFirstMessage")}}),tC=__esm({"src/utils/learning-events.ts"(){Ht(),Xv=class extends De{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;_observerHasRun=!1;_importHasStarted=!1;_learningComplete=!1;_authResolve=null;_authReject=null;get observerHasRun(){return this._observerHasRun}markObserverRun(){this._observerHasRun=!0}get importHasStarted(){return this._importHasStarted}markImportStarted(){this._importHasStarted=!0}get learningComplete(){return this._learningComplete}markLearningComplete(){this._learningComplete=!0,this.emit("learning-complete")}addEvent(e){const{type:t,message:n,details:r,step:s,label:o,sessionCount:i,promptCount:a,learningCount:l,categories:u,storage:d}=e,m={id:crypto.randomUUID(),timestamp:new Date,type:t,message:n,details:r,step:s,label:o,sessionCount:i,promptCount:a,learningCount:l,categories:u,storage:d};this.events.unshift(m),this.events.length>this.maxEvents&&(this.events=this.events.slice(0,this.maxEvents)),this.emit("new-event",m)}emitStepStart(e){this.addEvent({type:"step_start",...e})}emitProgress(e){this.addEvent({type:"progress",...e})}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}waitForAuth(){return new Promise((e,t)=>{this._authResolve=e,this._authReject=t})}resolveAuth(){this._authResolve?.(),this._authResolve=null,this._authReject=null}rejectAuth(e){this._authReject?.(new Error(e??"Login cancelled")),this._authResolve=null,this._authReject=null}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this._authReject?.(new Error("Reset during auth")),this._authResolve=null,this._authReject=null,this.emit("reset")}},Zv=new Xv}});function extractLearningWithConfidence(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)\.\s+Confidence:\s*(\d+\.?\d*)/);return n?{text:n[1].trim(),confidence:parseFloat(n[2])}:null}function extractLearnings(e){const{text:t}=e;return t.split("\n").filter(e=>e.trim().startsWith("-")).map(e=>extractLearningWithConfidence({line:e})).filter(Boolean)}function compareLearnings(e){const{oldText:t,newText:n}=e,r=extractLearnings({text:t}),s=extractLearnings({text:n}),o=new Map(r.map(e=>[e.text,e.confidence])),i=[],a=[],l=[];return s.forEach(e=>{const t=o.get(e.text);void 0===t?i.push(e):e.confidence>t?a.push({text:e.text,oldConfidence:t,newConfidence:e.confidence}):e.confidence<t&&l.push({text:e.text,oldConfidence:t,newConfidence:e.confidence})}),{added:i,upgraded:a,downgraded:l}}var nC,rC,sC,oC,iC,aC,lC=__esm({"src/utils/learning-parser.ts"(){Ht(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings")}}),cC=__esm({"src/agent/learning-agent.ts"(){Ht(),Kt(),vv(),Qv(),Rv(),In(),tC(),lC(),xE(),xr(),Rr(),Cs(),nC=new kE("LearningAgent"),rC=class{static{__name(this,"LearningAgent")}lastProcessedMessageIndex=-1;isProcessing=!1;pendingMessages=null;maxTurns=20;maxApiRetries=3;request;projectRoot;tasteDir;sessionId;abortSignal;constructor(t){this.request=t.request,this.sessionId=t.sessionId,this.projectRoot=t.projectRoot,this.tasteDir=e.join(t.projectRoot,".commandcode","taste")}updateRequest(e){this.request=e}setAbortSignal(e){this.abortSignal=e}async checkAndProcess(e){const{messages:t}=e;if(this.isProcessing)return this.pendingMessages=t,{success:!0};if(0===t.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length)return{success:!0};this.isProcessing=!0;try{for(await this.runLearningLoop({messages:t}),this.lastProcessedMessageIndex=t.length-1;null!==this.pendingMessages;){const e=this.pendingMessages;this.pendingMessages=null,e.filter((e,t)=>t>this.lastProcessedMessageIndex&&"user"===e.role).length>0&&(await this.runLearningLoop({messages:e}),this.lastProcessedMessageIndex=e.length-1)}return{success:!0}}catch(e){const n=e instanceof Error?e.message:String(e);return dlog(`[LearningAgent] ERROR: ${n}`),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learning_pass_failed"}),context:{component:ys.LEARNING_AGENT,heading:"Learning pass failed"}}),Zv.addEvent({type:"error",message:n||"learning pass failed",details:n}),this.lastProcessedMessageIndex=t.length-1,{success:!1}}finally{this.isProcessing=!1}}async runLearningLoop(e){const{messages:t}=e,n=["analyzing deltas","computing embeddings","updating weights","refining patterns","processing signals","extracting features","tuning parameters","optimizing priors"],r=n[Math.floor(Math.random()*n.length)];Zv.addEvent({type:"analyzing",message:r}),await this.initializeTasteDirectory();const s=await this.getTasteStructure(),o=t.length-this.lastProcessedMessageIndex-1,i=Math.max(20,o),a=Math.max(0,t.length-i),l=t.slice(a);let u=0,d=!1;dlog(`[LearningAgent] analyzing ${o} new messages for patterns`);const m=[{role:"user",content:`Current taste structure:\n${s}\n\nRecent conversation:\n${JSON.stringify(l,null,2)}`}];for(;u<this.maxTurns;){const e=await this.callLearningAPI({conversation:m}),t=this.extractToolCalls({content:e.content});if(0===t.length){const t=e.content.filter(e=>"text"===e.type);t.length>0&&dlog(`[LearningAgent] result: ${(t[0].text||"").substring(0,150)}`);break}dlog(`[LearningAgent] using tools: ${t.map(e=>e.toolName).join(", ")}`);const{results:n,learningsFound:r}=await this.executeTools({toolCalls:t});r&&(d=!0,dlog("[LearningAgent] patterns found and saved")),m.push({role:"assistant",content:e.content}),m.push({role:"tool",content:n}),u++}u>=this.maxTurns&&nC.debug("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||Zv.addEvent({type:"no_learnings",message:"no changes to taste"}),Zv.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool-call"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{this.validateTastePath({toolName:e.toolName,input:e.input});const t=this.adjustPathsForTaste({toolName:e.toolName,input:e.input});let s="",o="";if("write_file"===e.toolName||"edit_file"===e.toolName){const e=t;if(o=String(e.filePath||e.file_path||""),o)try{s=await E.promises.readFile(o,"utf-8")}catch{}}if("write_file"===e.toolName||"edit_file"===e.toolName){const e=t.filePath;e&&this.validateFinalTastePath(e)}const i=await executeTool(e.toolName,t,{allowTasteWrite:!0});let a="";if(("write_file"===e.toolName||"edit_file"===e.toolName)&&o)try{a=await E.promises.readFile(o,"utf-8")}catch{}if("write_file"===e.toolName||"edit_file"===e.toolName){r=!0;const e=o.replace(`${this.projectRoot}/`,""),t=compareLearnings({oldText:s,newText:a});(t.added.length||t.upgraded.length||t.downgraded.length)&&dlog(`[LearningAgent] taste: +${t.added.length} ↑${t.upgraded.length} ↓${t.downgraded.length} → ${e}`),t.added.forEach(t=>{Zv.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{Zv.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{Zv.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:i}})}catch(t){n.push({type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:t instanceof Error?t.message:String(t)}})}return{results:n,learningsFound:r}}validateTastePath(t){const{toolName:n,input:r}=t,s={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(!s||!r[s])return;const o=String(r[s]);if(e.isAbsolute(o))throw new Error(`Security: ${n} received absolute path. Only taste-relative paths are allowed (e.g., ".commandcode/taste/cli/taste.md" or ".commandcode/taste/taste.md"). Attempted: ${o}`);const i=e.normalize(o);if(i.startsWith(".."))throw new Error(`Security: ${n} path traversal attempt detected. Attempted: ${o}`);const a=e.join(this.tasteDir,i);if(!e.normalize(a).startsWith(this.tasteDir))throw new Error(`Security: ${n} can only access files within .commandcode/taste/. Attempted: ${o}`)}adjustPathsForTaste(t){const{toolName:n,input:r}=t,s={...r},o={read_file:"absolutePath",write_file:"filePath",edit_file:"filePath",read_directory:"path"}[n];if(o&&s[o]){const t=String(s[o]);let r;const i="write_file"===n||"edit_file"===n;if(e.isAbsolute(t)&&t.startsWith(this.tasteDir))if(i){if(!this.isValidTasteFilePath(t))throw new Error(`Invalid path: Absolute path in taste dir but wrong pattern: ${t}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`);r=t}else r=t;else{if(e.isAbsolute(t))throw new Error(`Invalid path: Absolute path outside taste directory: ${t}`);const n=e.normalize(t);if(n.startsWith(".."))throw new Error(`Security: Path traversal attempt detected: ${t}`);if(r=n.startsWith(".commandcode/taste")||n.startsWith(".commandcode"+e.sep+"taste")?n.replace(/^\.commandcode[/\\]taste/,this.tasteDir):e.join(this.tasteDir,n),r=e.normalize(r),!r.startsWith(this.tasteDir))throw new Error(`Security: Resolved path escapes taste directory: ${t} -> ${r}`);if(i&&!this.isValidTasteFilePath(r))throw new Error(`Invalid adjusted path: ${r}\n Must be: {project}/.commandcode/taste/taste.md or {project}/.commandcode/taste/{category}/taste.md`)}s[o]=r}return s}isValidTasteFilePath(e){return[/\.commandcode\/taste\/taste\.md$/,/\.commandcode\/taste\/[^/]+\/taste\.md$/].some(t=>t.test(e))}validateFinalTastePath(e){if(!this.isValidTasteFilePath(e))throw new Error(`Security: Invalid taste file path. Only allowed:\n - {project}/.commandcode/taste/taste.md\n - {project}/.commandcode/taste/{category}/taste.md\nAttempted: ${e}`)}async initializeTasteDirectory(){if(!E.existsSync(this.tasteDir)){E.mkdirSync(this.tasteDir,{recursive:!0});const t=e.join(this.tasteDir,"taste.md");E.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!E.existsSync(t))return!1;const n=E.readFileSync(t,"utf-8"),r=this.parseCategories({content:n}).filter(e=>e.learningCount>5);if(0===r.length)return!1;let s=n;for(const t of r){const n=t.name.toLowerCase().replace(/\s+/g,"-"),r=e.join(this.tasteDir,n),o=e.join(r,"taste.md");E.mkdirSync(r,{recursive:!0}),Zv.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const i=`# ${t.name}\n${t.learnings.join("\n")}\n`;E.writeFileSync(o,i,"utf-8");const a=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;s=s.replace(t.fullSection,a)}return E.writeFileSync(t,s,"utf-8"),!0}parseCategories(e){const{content:t}=e,n=[],r=t.split(/^# /gm).filter(e=>e.trim());for(const e of r){const t=e.split("\n"),r=t[0].trim();if(e.includes("See ["))continue;const s=t.filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:"));s.length>0&&n.push({name:r,learningCount:s.length,learnings:s,fullSection:`# ${e}`})}return n}async getTasteStructure(){return E.existsSync(this.tasteDir)?await this.buildTree({dir:this.tasteDir,prefix:""}):"(empty - no taste files yet)"}async buildTree(t){const{dir:n,prefix:r}=t,s=E.readdirSync(n,{withFileTypes:!0});let o="";for(let t=0;t<s.length;t++){const i=s[t],a=t===s.length-1,l=a?"└── ":"├── ";if(i.isDirectory()){o+=`${r}${l}${i.name}/\n`;const t=r+(a?" ":"│ ");o+=await this.buildTree({dir:e.join(n,i.name),prefix:t})}else if("taste.md"===i.name){const t=(E.readFileSync(e.join(n,i.name),"utf-8").match(/^- .*Confidence:.*$/gm)||[]).length;o+=`${r}${l}${i.name} (${t} learnings)\n`}else o+=`${r}${l}${i.name}\n`}return o}async getTasteTools(){const e=await getToolSchemas(),t=["read_file","write_file","edit_file","read_directory"];return e.filter(e=>t.includes(e.name)).map(e=>({name:e.name,description:e.description,input_schema:e.input_schema}))}async callLearningAPI(e){const{conversation:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced(),{token:s,oauthProvider:o}=await getOAuthCredentials({provider:n});validateOAuthToken({token:s,provider:n}),dlog(`[LearningAgent] callLearningAPI provider=${n} oauthProvider=${o} hasToken=${!!s}`);const i={[Ct.PROJECT_SLUG]:hv.getCurrentProjectDirName(),[Ct.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};s&&(i[Ct.OAUTH_TOKEN]=`Bearer ${s}`,o&&(i[Ct.OAUTH_PROVIDER]=o));const a=await this.getTasteTools(),l=getConfiguredModel();dlog(`[LearningAgent] calling ${kt.ALPHA.TASTE.LEARN} (model: ${l})`);const u={conversation:t,tools:a,model:l,threadId:this.sessionId};let d=0,m=null;for(;d<=this.maxApiRetries;)try{const e=await this.request.post({endpoint:kt.ALPHA.TASTE.LEARN,body:u,headers:i,signal:this.abortSignal});if(!e)throw new Error("No response received");const t=e;return dlog(`[LearningAgent] API response received: ${t.content.length} blocks`),{role:"assistant",content:t.content}}catch(e){if(m=e instanceof Error?e:new Error(String(e)),d++,this.abortSignal?.aborted)throw dlog("[LearningAgent] abort detected - stopping retries immediately"),new Error("Interrupted by user");const t=e?.status||e?.statusCode;if(t&&t>=400&&t<500)throw dlog(`[LearningAgent] API error: ${m.message}`),trackError({error:sanitizeErrorForTelemetry({error:m,label:"learning_api_client_error"}),context:{component:ys.LEARNING_AGENT,heading:"Learning API client error (no retry)","http.status":t}}),m;if(d>this.maxApiRetries)throw dlog(`[LearningAgent] API failed after ${this.maxApiRetries} retries`),trackError({error:sanitizeErrorForTelemetry({error:m,label:"learning_api_max_retries"}),context:{component:ys.LEARNING_AGENT,heading:"Learning API failed after retries","retry.count":this.maxApiRetries,"retry.attempts_made":d}}),m;const n=1e3*Math.pow(2,d);dlog(`[LearningAgent] retrying API call (${d}/${this.maxApiRetries})`),await sleep({delay:n,signal:this.abortSignal})}throw m||new Error("API call failed")}static async isInitialized(t){const{projectRoot:n}=t,r=e.join(n,".commandcode","taste");return E.existsSync(r)}}}}),uC=__esm({"src/agent/compact-agent.ts"(){Ht(),Kt(),vv(),gn(),xr(),Rr(),In(),PE(),sC="claude-haiku-4-5-20251001",oC=class{static{__name(this,"CompactAgent")}request;sessionId;maxApiRetries=3;constructor(e){this.request=e.request,this.sessionId=e.sessionId}updateRequest(e){this.request=e}async compactMessages(e){const{messages:t}=e;dlog(`[CompactAgent] compacting ${t.length} messages`);try{const e=await this.callCompactAPI({messages:t});return dlog(`[CompactAgent] compaction complete: ${e.summary.length} chars`),e}catch(e){throw dlog(`[CompactAgent] ERROR: ${e instanceof Error?e.message:String(e)}`),e}}async callCompactAPI(e){const{messages:t}=e,n=await getConfiguredProvider(),r=await isOAuthEnforced(),{token:s,oauthProvider:o}=await getOAuthCredentials({provider:n});validateOAuthToken({token:s,provider:n});const i={[Ct.PROJECT_SLUG]:hv.getCurrentProjectDirName(),[Ct.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};s&&(i[Ct.OAUTH_TOKEN]=`Bearer ${s}`,o&&(i[Ct.OAUTH_PROVIDER]=o));const a=t.map(e=>{const t=e.role;let n="";return"string"==typeof e.content?n=e.content:Array.isArray(e.content)&&(n=e.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("\n")),`[${t}]: ${n}`}).join("\n\n"),l={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],system:"Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.\nThis summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.\n\nBefore providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:\n\n1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:\n - The user's explicit requests and intents\n - Your approach to addressing the user's requests\n - Key decisions, technical concepts and code patterns\n - Specific details like:\n - file names\n - full code snippets\n - function signatures\n - file edits\n - Errors that you ran into and how you fixed them\n - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.\n\nYour summary should include the following sections:\n\n1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail\n2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.\n3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.\n4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.\n5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.\n6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.\n7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.\n8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.\n9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.\n If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.\n\nHere's an example of how your output should be structured:\n\n<example>\n<analysis>\n[Your thought process, ensuring all points are covered thoroughly and accurately]\n</analysis>\n\n<summary>\n1. Primary Request and Intent:\n [Detailed description]\n\n2. Key Technical Concepts:\n - [Concept 1]\n - [Concept 2]\n - [...]\n\n3. Files and Code Sections:\n - [File Name 1]\n - [Summary of why this file is important]\n - [Summary of the changes made to this file, if any]\n - [Important Code Snippet]\n - [File Name 2]\n - [Important Code Snippet]\n - [...]\n\n4. Errors and fixes:\n - [Detailed description of error 1]:\n - [How you fixed the error]\n - [User feedback on the error if any]\n - [...]\n\n5. Problem Solving:\n [Description of solved problems and ongoing troubleshooting]\n\n6. All user messages:\n - [Detailed non tool use user message]\n - [...]\n\n7. Pending Tasks:\n - [Task 1]\n - [Task 2]\n - [...]\n\n8. Current Work:\n [Precise description of current work]\n\n9. Optional Next Step:\n [Optional Next step to take]\n\n</summary>\n</example>\n\nPlease provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.\n\nThere may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:\n<example>\n## Compact Instructions\nWhen summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.\n</example>\n\n<example>\n# Summary instructions\nWhen you are using compact - please focus on test output and code changes. Include file reads verbatim.\n</example>",messages:[{role:"user",content:`Please summarize the following conversation.\n\n${a}`}],model:sC,max_tokens:16e3,stream:!0},threadId:this.sessionId};let u=0,d=null;for(;u<=this.maxApiRetries;)try{dlog(`[CompactAgent] calling ${kt.ALPHA.GENERATE} with model: ${sC}`);const e=await this.request.post({endpoint:kt.ALPHA.GENERATE,body:l,headers:i,stream:!0});if(!e)throw new Error("No response stream received");const t=await consumeSSEStream(e),n=t.content.filter(e=>"text"===e.type).map(e=>e.text||"").join("");return dlog("[CompactAgent] API response received"),{summary:n,tokensUsed:{input:t.usage.input_tokens,output:t.usage.output_tokens}}}catch(e){d=e instanceof Error?e:new Error(String(e)),u++;const t=e?.status;if(t&&t>=400&&t<500)throw dlog(`[CompactAgent] API error: ${d.message}`),d;if(u>this.maxApiRetries)throw dlog(`[CompactAgent] API failed after ${this.maxApiRetries} retries`),d;dlog(`[CompactAgent] retrying API call (${u}/${this.maxApiRetries})`)}throw d||new Error("Compact API call failed")}}}});function extractMessageText(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t="";for(const n of e)"text"===n.type&&(t+=n.text);return t}async function buildAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced(),n={[Ct.PROJECT_SLUG]:hv.getCurrentProjectDirName(),[Ct.INTERNAL_TEAM_FLAG_HEADER]:t.toString()},{token:r,oauthProvider:s}=await getOAuthCredentials({provider:e});return r&&(n[Ct.OAUTH_TOKEN]=`Bearer ${r}`,s&&(n[Ct.OAUTH_PROVIDER]=s)),dlog("[TitleGen] buildAuthHeaders",{provider:e,oauthEnforced:t,hasOAuthToken:!!n[Ct.OAUTH_TOKEN]}),n}function hasUserAndAssistantMessage(e){let t=!1,n=!1;for(const r of e)if("user"===r.message.role&&(t=!0),"assistant"===r.message.role&&(n=!0),t&&n)return!0;return!1}async function generateSessionTitle(e){const{messages:t,sessionManager:n}=e;if(!hasUserAndAssistantMessage(t))return;if(await n.loadSessionTitle())return;let r="",s="";for(const e of t)if(r||"user"!==e.message.role||(r=extractMessageText(e.message.content).slice(0,aC)),s||"assistant"!==e.message.role||(s=extractMessageText(e.message.content).slice(0,aC)),r&&s)break;if(!r||!s)return;const o=`${iC}\n\nSession description:\n<description>User: ${r}\n\n---\n\nAssistant: ${s}</description>\n\nGenerate the session title now.`,i=await buildAuthHeaders(),a={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:o}],model:It,max_tokens:50,temperature:.3,stream:!0},threadId:n.getSessionId()},l=getApiBaseUrl(),u=new xy({baseUrl:l}),d=await u.post({endpoint:kt.ALPHA.GENERATE,body:a,headers:i,stream:!0}),m=(await consumeSSEStream(d)).content.filter(e=>"text"===e.type).map(e=>e.text||"").join("").trim();m&&(await n.saveSessionTitle(m),dlog("Session",`Title generated: ${m}`))}var dC=__esm({"src/chat/title-generator.ts"(){Ht(),vv(),Wy(),gn(),xr(),Rr(),In(),Kt(),PE(),Xy(),iC="You are generating a succinct session title for a coding session based on the provided description.\n\nThe title should be:\n- Clear, concise, and accurately reflect the task\n- No more than 6 words\n- Easy to understand by a general audience\n- Free of unnecessary jargon (use technical terms only if essential)\n- Written in sentence case (capitalize only the first word and proper nouns)\n\nReturn only the title as a plain string, not JSON.\n\nExample titles:\nAdd retry logic to API\nSimplify error handling flow\nClean up unused components",aC=1e3,__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle")}});async function callServerAPI(e){const t=await getConfiguredProvider(),n=await isOAuthEnforced(),{token:r,oauthProvider:s}=await getOAuthCredentials({provider:t});validateOAuthToken({token:r,provider:t});const o=await isTasteLearningEnabled(),i={[Ct.PROJECT_SLUG]:hv.getCurrentProjectDirName(),[Ct.TASTE_LEARNING]:o.toString(),[Ct.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};r&&(i[Ct.OAUTH_TOKEN]=`Bearer ${r}`,s&&(i[Ct.OAUTH_PROVIDER]=s));const a={config:e.config,memory:e.memory,taste:e.taste??null,skills:e.skills??null,permissionMode:e.permissionMode??"standard",params:{model:e.model,messages:e.messages,tools:e.tools,system:e.system,max_tokens:e.maxOutputTokens??64e3,stream:!0}};dlog(`[AISDKBridge] POST ${kt.ALPHA.GENERATE} model=${e.model} msgs=${e.messages.length} tools=${e.tools.length}`);const l=getApiBaseUrl(),u=new xy({baseUrl:l}),d=await u.post({body:a,stream:!0,endpoint:kt.ALPHA.GENERATE,signal:e.signal,headers:i});return await consumeSSEStream(d,{onText:e.onTextDelta})}var mC,pC,gC,hC=__esm({"src/chat/ai-sdk-bridge.ts"(){Ht(),PE(),Wy(),Xy(),Kt(),xr(),Rr(),vv(),In(),__name(callServerAPI,"callServerAPI")}}),fC={};__export(fC,{ContextEngine:()=>gC});var yC,wC,SC=__esm({"src/chat/context-engine.ts"(){Ht(),Vv(),fw(),Ds(),pv(),dv(),Zy(),Qv(),Rv(),Kv(),xE(),Hv(),bS(),vv(),eC(),Cs(),jw(),Xy(),Wy(),Th(),Kt(),gn(),xr(),Rr(),aw(),cC(),uC(),uw(),In(),dC(),hs(),Cv(),hC(),mC=new kE("ContextEngine"),pC=200,gC=class{static{__name(this,"ContextEngine")}request;messages=[];callbacks;sessionManager;abortController=null;requestInterrupted=!1;contextTokensUsed=0;currentInteractionTokens=0;compactionCount=0;syncQueue=Promise.resolve();lastFileContexts=[];titleGenerationInFlight=!1;learningAgent;compactAgent;checkpointManager;constructor(e,t){const n=getApiBaseUrl();this.request=new xy({baseUrl:n}),this.callbacks=e,this.sessionManager=new hv(t),this.learningAgent=new rC({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new oC({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new xy({baseUrl:e}),this.learningAgent.updateRequest(this.request),this.compactAgent.updateRequest(this.request)}createSessionStoreAdapter(){return{saveSnapshot:__name(async e=>{await this.sessionManager.saveSnapshot(e)},"saveSnapshot"),loadSnapshots:__name(async()=>this.sessionManager.loadSnapshots(),"loadSnapshots"),deleteSnapshotsAfter:__name(async e=>{await this.sessionManager.deleteSnapshotsAfter(e)},"deleteSnapshotsAfter"),getMessageAtIndex:__name(e=>this.sessionManager.getMessageAtIndex({index:e.index,messages:this.messages}),"getMessageAtIndex"),getMessageIndexById:__name(e=>this.sessionManager.getMessageIndexById({messageId:e.messageId,messages:this.messages}),"getMessageIndexById"),truncateMessagesAtIndex:__name(async e=>{const t=await this.sessionManager.truncateMessagesAtIndex({index:e.index,messages:this.messages});this.messages=t},"truncateMessagesAtIndex"),getMessageCount:__name(()=>this.sessionManager.getMessageCount({messages:this.messages}),"getMessageCount")}}setupCheckpointSessionStore(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()})}async interrupt(e=!1){if(this.requestInterrupted=!0,this.abortController){this.abortController.abort(),this.abortController=null,mC.debug("LLM request interrupted by user");const t=this.messages[this.messages.length-1];if("assistant"===t?.message.role&&Array.isArray(t.message.content)){const n=t.message.content.filter(e=>"tool-call"===e.type);if(n.length>0){const e=n.map(e=>({type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:"Interrupted by user"}}));this.addMessageAndSync(this.createMessageWithMeta({role:"tool",content:e})),mC.debug(`Added tool-result parts for ${e.length} interrupted tool calls`)}e&&this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:[{type:"text",text:"Interrupted by user"}]},{isAutomated:!0}))}if(e){const e=UE("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>mC.error(`Failed to save interruption to session: ${e}`))}}}async sendMessage(e,t,n,r,s){let o=e,i=[];try{const t=await processFileReferences(e);if(o=t.processedContent,i=t.fileReferences,i.length>0){const e=i.map(e=>e.resolvedPath);this.lastFileContexts=[...new Set([...this.lastFileContexts,...e])]}}catch(e){console.error("File reference processing failed:",e)}n&&(o=`${n}\n\n${o}`);const a=UE(r??e);t&&t.length>0&&(a.metadata={...a.metadata,images:t}),i&&i.length>0&&(a.metadata={...a.metadata,fileReferences:i}),this.callbacks.onFeedUpdate(a);const l=[];t&&t.length>0&&t.forEach(e=>{l.push({type:"image",image:`data:${e.mediaType};base64,${e.data}`})}),o.trim()&&l.push({type:"text",text:o});const u={role:"user",content:l},d=crypto.randomUUID(),m={messageId:d};this.getAutomatedMessageMeta({input:e,displayMessage:r,isAutomated:s?.isAutomated}).isAutomated&&(m.isAutomated=!0);const g=this.createMessageWithMeta(u,m);detectAndTrackFirstMessage().catch(()=>{}),this.addMessageAndSync(g),this.checkpointManager.createSnapshot({messageId:d}).catch(e=>mC.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,a).catch(e=>mC.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const h=await this.processMessages();return this.triggerTitleGeneration(),h}triggerLearningAgent(){(async()=>{try{if(!await isTasteLearningEnabled())return;const e=this.messages.filter(e=>!e.meta.isAutomated&&!this.messageContainsToolResult(e.message)).map(e=>e.message),t=this.sanitizeMessagesForAPI(e);await this.learningAgent.checkAndProcess({messages:t})}catch(e){mC.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}triggerTitleGeneration(){this.titleGenerationInFlight||(this.titleGenerationInFlight=!0,generateSessionTitle({messages:this.messages,sessionManager:this.sessionManager}).catch(e=>{dlog("Session",`Title generation failed: ${e instanceof Error?e.message:String(e)}`)}).finally(()=>{this.titleGenerationInFlight=!1}))}async processMessages(){let e="";this.requestInterrupted=!1;const t=new AbortController;this.abortController=t,this.learningAgent.setAbortSignal(t.signal);let n=!1;try{for(;;)try{this.checkIfInterrupted(),n||(this.initializeInteractionTokens(),n=!0);const t=await this.callAPIWithRetry();this.checkIfInterrupted(),this.updateContextUsage(t),await this.checkAndCompactIfNeeded();const r=t.content.filter(e=>"tool-call"===e.type&&!e.providerExecuted),s=t.content.filter(e=>"tool-call"===e.type&&e.providerExecuted);if(e=s.length>0?this.processServerToolBlocks(t):t.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===r.length){const n=t.content.filter(e=>"text"===e.type?e.text.trim().length>0:"tool-call"!==e.type&&"tool-result"!==e.type||!e.providerExecuted);if(n.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:n})),e.trim()&&0===s.length){const t=WE(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>mC.error(`Failed to save messages: ${e}`))}if(0!==s.length&&this.sessionManager.saveMessages(this.messages).catch(e=>mC.error(`Failed to save messages: ${e}`)),this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0){let t=!1;for(const n of e){const e=UE(n.displayMessage??n.input);this.callbacks.onFeedUpdate(e);const r=this.getAutomatedMessageMeta(n);this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:n.input},r)),t=!0}this.sessionManager.saveMessages(this.messages).catch(e=>mC.error(`Failed to save messages: ${e}`)),t&&this.triggerLearningAgent();continue}}break}const o=t.content.filter(e=>"text"===e.type?e.text.trim().length>0:"tool-call"!==e.type&&"tool-result"!==e.type||!e.providerExecuted);if(o.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:o})),e.trim()){const t=WE(e);this.callbacks.onFeedUpdate(t)}const i=await this.executeToolBlocks({toolBlocks:r}),{toolResults:a,executedToolIds:l,permissionDenied:u}=i;if(u){const e=this.messages[this.messages.length-1];if("assistant"===e?.message.role&&Array.isArray(e.message.content)){const t=e.message.content.filter(e=>"tool-call"===e.type?l.has(e.toolCallId):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}let d=!1,m=!1;if(a.length>0&&(this.addMessageAndSync(this.createMessageWithMeta({role:"tool",content:a})),d=!0),this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){const e=UE(t.displayMessage??t.input);this.callbacks.onFeedUpdate(e);const n=this.getAutomatedMessageMeta(t);this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t.input},n)),d=!0,m=!0}}d&&this.sessionManager.saveMessages(this.messages).catch(e=>mC.error(`Failed to save messages: ${e}`)),m&&this.triggerLearningAgent()}catch(e){throw this.isNonRetryableError(e)&&mC.debug("Request interrupted or insufficient credits"),e}}finally{this.abortController===t&&(this.abortController=null)}return e}getHistory(){return[...this.messages]}async loadSession(e){const{messages:t,corruptedLines:n,totalLines:r}=await this.sessionManager.loadMessages(e);this.messages=t,this.triggerTitleGeneration();try{await this.loadCheckpoints()}catch(t){mC.error(`Failed to load checkpoints for session ${e}: ${t}`)}const s=this.sessionManager.reconstructFeedFromMessages(t);return mC.debug(`Loaded session ${e} with ${t.length} messages (${n} corrupted lines)`),{feedEntries:s,corruptedLines:n,totalLines:r}}getMessages(){return[...this.messages]}getRawMessages(){return this.sanitizeMessagesForAPI(this.messages.map(e=>e.message))}sanitizeMessagesForAPI(e){const t=[];for(const n of e){if("tool"===n.role){const e=t.length>0?t[t.length-1]:null,r=new Set;if("assistant"===e?.role&&Array.isArray(e.content))for(const t of e.content)"tool-call"===t.type&&r.add(t.toolCallId);const s=n.content.filter(e=>"tool-result"!==e.type||r.has(e.toolCallId));s.length>0&&t.push({...n,content:s});continue}const e=t.length>0?t[t.length-1]:null;if(e&&e.role===n.role){const t=Array.isArray(e.content)?e.content:[{type:"text",text:e.content}],r=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];e.content=[...t,...r];continue}t.push({...n})}return t}getSessionId(){return this.sessionManager.getSessionId()}getSessionManager(){return this.sessionManager}getContextTokensUsed(){return this.contextTokensUsed}getCompactionCount(){return this.compactionCount}isRequestInProgress(){return null!==this.abortController}async manualCompact(){if(this.messages.length<=2)return{tokensSaved:0,didCompact:!1};mC.debug(`Manual compact: ${this.messages.length} messages`);const e=this.contextTokensUsed;await this.summarizeAndCompact();const t=Math.max(0,e-this.contextTokensUsed);return this.compactionCount++,{tokensSaved:t,didCompact:!0}}async compactConversation({preserveCurrentInteraction:e=!1}={preserveCurrentInteraction:!1}){const t=this.messages.length,n=this.contextTokensUsed;let r=-1;if(e)for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if("user"===t.message.role){const n=t.message.content;if(!Array.isArray(n)){r=e;break}if(!n.some(e=>"tool-result"===e.type)){r=e;break}}}let s=0;const o=[];for(let t=0;t<this.messages.length;t++){const n=this.messages[t],i=n.message.role;if(e&&t>=r&&-1!==r)o.push(n);else{if("user"===i){const e=n.message.content;if(Array.isArray(e)){if(e.some(e=>"tool-result"===e.type)){s+=estimateTokens(n.message);continue}o.push(n)}else o.push(n)}else if("assistant"===i){const e=n.message.content;if(Array.isArray(e)){const t=e.filter(e=>"tool-call"===e.type);for(const e of t)s+=estimateTokens({role:"assistant",content:[e]});const r=e.filter(e=>"text"===e.type&&e.text?.trim());r.length>0?o.push({...n,message:{...n.message,content:r}}):s+=estimateTokens(n.message)}else"string"==typeof e&&e.trim()&&o.push(n)}"user"!==i&&"assistant"!==i&&(s+=estimateTokens(n.message))}}this.messages=o,await this.sessionManager.saveMessages(this.messages);const i=Math.max(0,n-s);return this.contextTokensUsed=i,this.callbacks.onContextUsageUpdate?.({current:i,limit:pS}),{messagesRemoved:t-o.length,tokensSaved:s}}createMessageWithMeta(e,t={}){return{message:e,meta:{timestamp:(new Date).toISOString(),source:"cli",...t}}}isAutomatedSlashCommandPrompt(e){const{input:t,displayMessage:n}=e;return!!n&&!!n.trim().startsWith("/")&&n.trim()!==t.trim()}getAutomatedMessageMeta(e){return e.isAutomated||this.isAutomatedSlashCommandPrompt(e)?{isAutomated:!0}:{}}messageContainsToolResult(e){if("user"!==e.role)return!1;const t=e.content;return!!Array.isArray(t)&&t.some(e=>{if("object"!=typeof e||null===e||!("type"in e))return!1;const t=e.type;return"tool_result"===t||"tool-result"===t})}extractFilePathFromTool(e,t){try{switch(e){case"read_file":case"write_file":case"edit_file":return t.absolutePath||t.file_path||t.filePath||t.path;case"read_directory":case"grep":return t.path;case"read_multiple_files":const e=t.include||[];return Array.isArray(e)&&e.length>0?e[0]:void 0;default:return}}catch{return}}addMessageAndSync(e){this.messages.push(e);const t=this.callbacks.getShareInfo?.();t&&(this.syncQueue=this.syncQueue.then(async()=>{try{await this.syncMessageToShare(t,e)}catch(e){}}))}async syncMessageToShare(e,t){try{const n=hh.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:kt.ALPHA.SHARE.APPEND})}catch(e){throw e}}checkIfInterrupted(){if(this.requestInterrupted||this.abortController?.signal.aborted)throw new Error("Interrupted by user")}initializeInteractionTokens(){const e=this.messages[this.messages.length-1];this.currentInteractionTokens=estimateTokens(e.message)}async prepareServerCall(){const e=this.callbacks.getPermissionMode?.()||"standard",t=await getToolSchemas({mode:e}),n=await getConfiguredProvider();n&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(n);const r=getConfiguredModel(),s=this.getRawMessages(),o=getEnvironmentContext(),i=await getMemoryContent(this.lastFileContexts),a=await getTasteContent(),l=generateSkillsXML(await loadAllSkillSummaries());return mC.debug(`prepareServerCall (${r}, ${s.length} msgs, ${t.length} tools)`),{model:r,messages:s,tools:t,config:o,memory:i||null,taste:a||null,skills:l||null,permissionMode:e}}async callAPIWithRetry(){let e=null;const{model:t,messages:n,tools:r,config:s,memory:o,taste:i,skills:a,permissionMode:l}=await this.prepareServerCall();for(let u=0;u<10;u++)try{const e=await callServerAPI({model:t,messages:n,tools:r,config:s,memory:o,taste:i,skills:a,permissionMode:l,maxOutputTokens:64e3,signal:this.abortController?.signal,onTextDelta:__name(e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)},"onTextDelta"),onError:__name(e=>{mC.debug(`API stream error: ${e.message}`)},"onError")});return this.callbacks.onRetryUpdate?.(null),e}catch(t){if(e=t instanceof Error?t:new Error(String(t)),dlog(`[ContextEngine] API error (attempt ${u+1}/10): statusCode=${t?.statusCode} status=${t?.status} message=${t?.message} responseBody=${t?.responseBody?.substring?.(0,300)}`),this.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(t))throw trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"non_retryable_api_error"}),context:{component:ys.CONTEXT_ENGINE,heading:"Non-retryable AI SDK error",code:t?.status||t?.statusCode}}),this.formatAPIError(t);if(9===u)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:e,label:"api_max_retries_exceeded"}),context:{heading:"AI SDK max retries exceeded",component:ys.CONTEXT_ENGINE,"retry.attempts":10}}),this.formatAPIError(t);const n=Math.min(u,10),r=100*Math.pow(2,n),s=Math.max(r,1e3),o=Math.min(s,1e4);u>=2&&this.callbacks.onRetryUpdate?.(u+1),await sleep({delay:o,signal:this.abortController?.signal})}throw e||new Error("Failed to get response after retries")}isNonRetryableError(e){const{message:t}=this.extractErrorMessage(e),n=t?.toLowerCase()||"",r="Interrupted by user"===t||"AbortError"===e?.name||n.includes("aborted")||this.requestInterrupted||this.abortController?.signal.aborted,s="Insufficient credits"===t||n.includes("insufficient credits"),o=!1===e?.isRetryable;o&&dlog(`[ContextEngine] AI SDK isRetryable=false: status=${e?.statusCode??e?.status} message=${e?.message}`);const i=e?.status||e?.statusCode,a=e instanceof xs||401===i||e instanceof Ps||403===i,l=e?.type||e?.error?.type,u="rate_limit_error"===l||429===i||n.includes("rate limit"),d="overloaded_error"===l||529===i||n.includes("overloaded");return r||s||o||a||u||d}extractErrorMessage(e){dlog("Extracting error message from:",e);const t=e?.status||e?.statusCode||null;if(e?.responseBody){const n=parseEmbeddedErrorJSON(e.responseBody);if(n)return{...n,status:n.status||t};try{const n=JSON.parse(e.responseBody);if(n?.error?.message)return{status:t,type:n.error.type||null,message:n.error.message}}catch{}}if(e?.error?.message){const n=parseEmbeddedErrorJSON(e.error.message);return n?{...n,status:n.status||t}:{status:t,type:e.error.type||null,message:e.error.message}}const n=e?.message;if("string"==typeof n){const e=parseEmbeddedErrorJSON(n);if(e)return{...e,status:e.status||t}}return{status:t,type:e?.type||null,message:e?.message||null}}formatAPIError(e){if("Interrupted by user"===e?.message||"AbortError"===e?.name||e?.message?.includes("aborted")||e?.message?.includes("interrupted")||"ECONNABORTED"===e?.code||this.requestInterrupted||this.abortController?.signal.aborted)return new Error("Interrupted by user");const t=this.extractErrorMessage(e),n=t.status,r=t.type,s=t.message,o=getSupportId(),i="unknown"!==o?`\nRequest ID: ${o}`:"",a='\n\nType "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord';dlog("API error occurred:",e),dlog("Extracted error details:",t),dlog("Error type:",r),dlog("Error message:",s);const l=s?.toLowerCase().includes("insufficient credits");if(l)return new Error(`Insufficient credits\n\nUpgrade your plan or add credits: https://commandcode.ai/settings/billing${i}`);const u=s?.toLowerCase().includes("oauth authentication required");if(u)return e;if(e instanceof xs||401===(e?.status||e?.statusCode))return new Error(`Error: Authentication failed. Your API key may be invalid or expired. Run "cmd login" to sign in again.${a}${i}`);let d="";if(s)if(s.includes("Invalid 'Authorization' header"))d=`Error: Authentication failed. Run "cmd login" to sign in again.${a}${i}`;else{let e=s;for(;e.startsWith("Error: ");)e=e.substring(7);(e.includes("Unexpected event order")||e.includes("part")&&e.includes("not found")||e.includes("AI_")||e.includes("Invalid prompt"))&&(e="Something went wrong. Please try again or contact support if the issue persists.");let t=e.replace(/(?<!\.)Anthropic(?!\.)/gi,"Command Code");t.length>pC&&(t=t.substring(0,pC)+"..."),d=`Error: ${[n,r?r.charAt(0).toUpperCase()+r.slice(1):null,t].filter(Boolean).join(" ")}`;const o=s.toLowerCase(),l="overloaded_error"===r||o.includes("overloaded"),u="rate_limit_error"===r||o.includes("rate limit");d+=l?"\n\nThe API is currently experiencing high traffic. Please try again in a moment.":u?'\n\nYou can wait a moment and try again, or type "continue" to retry.':a,d+=i}else{const t=e?.toString?.()||"Unknown error occurred";d=t.length>pC?t.substring(0,pC)+"...":t,d+=a+i}return new Error(d)}async executeToolBlocks(e){const t=new Set;let n=!1;const r=[],s=[];for(const o of e.toolBlocks){this.checkIfInterrupted();const e=crypto.randomUUID(),i=Yy.includes(o.toolName),a=Jy.includes(o.toolName)?this.getToolDescription(o):Promise.resolve(null);let l=null;try{i&&this.callbacks.onPermissionRequest&&(l=await a);const t=await this.checkToolPermission(o,l);if(t.needsPermission&&!t.allowed){this.handlePermissionDenied(o,e),n=!0;break}}catch(n){const r=n instanceof Error?n.message:"Permission check failed";this.showToolError(o,r,e,l),s.push({toolBlock:o,toolResult:{type:"tool-result",toolCallId:o.toolCallId,toolName:o.toolName,output:{type:"error-text",value:`Error: ${r}`}}}),t.add(o.toolCallId);continue}null===l&&(l=await a),r.push({toolBlock:o,entryId:e,description:l})}const o=[];for(const{toolBlock:e,toolResult:n}of s)o.push(n),t.add(e.toolCallId);if(r.length>0){const e=await Promise.allSettled(r.map(async({toolBlock:e,entryId:t,description:n})=>{this.checkIfInterrupted(),isAgentTool(e.toolName)||e.toolName===Gy.GET_SELF_KNOWLEDGE||this.showToolRunning(e,t,n);const r="edit_file"===e.toolName?await resolveEditStartLine({filePath:e.input.filePath,oldContent:e.input.oldValue}).catch(()=>{}):void 0,s=await this.executeSingleTool(e);return isAgentTool(e.toolName)||e.toolName===Gy.GET_SELF_KNOWLEDGE||this.showToolSuccess(e,s,t,n,r),{toolBlock:e,toolResult:{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:s}}}}));for(let n=0;n<e.length;n++){const s=e[n],{toolBlock:i,entryId:a,description:l}=r[n];if("fulfilled"===s.status)o.push(s.value.toolResult),t.add(i.toolCallId);else{const e=s.reason instanceof Error?s.reason.message:"Unknown error";"Interrupted by user"===e&&isAgentTool(i.toolName)?t.add(i.toolCallId):(o.push({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:{type:"error-text",value:`Error: ${e}`}}),t.add(i.toolCallId),i.toolName!==Gy.GET_SELF_KNOWLEDGE&&this.showToolError(i,e,a,l))}}}return{toolResults:o,executedToolIds:t,permissionDenied:n}}async getToolDescription(e){try{return await Promise.race([generateToolDescription(e.toolName,e.input),new Promise(e=>setTimeout(()=>e(null),6e3))])}catch(t){return mC.debug(`Failed to generate description for ${e.toolName}: ${t instanceof Error?t.message:"Unknown error"}`),this.callbacks.onToolDescriptionError&&this.callbacks.onToolDescriptionError(e.toolName,t),null}}async checkToolPermission(e,t){return Yy.includes(e.toolName)&&this.callbacks.onPermissionRequest?{needsPermission:!0,allowed:await this.callbacks.onPermissionRequest(e.toolName,e.input,t)}:{needsPermission:!1,allowed:!0}}async executeSingleTool(e){const t=this.callbacks.getPermissionMode?.()||"standard",n=await executeTool(e.toolName,e.input,{onPermissionRequest:this.callbacks.onPermissionRequest,onQuestionRequest:this.callbacks.onQuestionRequest,abortSignal:this.abortController?.signal,onFeedUpdate:this.callbacks.onFeedUpdate,permissionMode:t});this.checkIfInterrupted();const r=checkToolOutputTokensLimit(n),s=estimateTokens(r);return this.currentInteractionTokens+=s,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),r}handlePermissionDenied(e,t){const n=av(e.toolName,e.input),r={..."edit_file"===e.toolName?e.input:{},permissionDenied:!0},s={...GE(e.toolName,n,r),id:t},o=ZE(s,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o)}buildToolMetadata({toolBlock:e,editStartLine:t}){if("edit_file"===e.toolName)return{...e.input,...void 0!==t?{startLine:t}:{}};if("write_file"===e.toolName){const t=e.input,n="string"==typeof t.content?t.content:"",r=n.split("\n"),s=r.length>es?r.slice(0,es).join("\n"):n;return{...t,content:s,totalLines:r.length}}}showToolRunning(e,t,n){const r=av(e.toolName,e.input),s={...GE(e.toolName,r,{status:"running"}),id:t,...n?{description:n}:{}};this.callbacks.onFeedUpdate(s)}showToolSuccess(e,t,n,r,s){let o=this.buildToolMetadata({toolBlock:e,editStartLine:s});if("read_file"===e.toolName){const t=e.input.absolutePath||e.input.filePath||e.input.file_path||e.input.path;if(t){const e=getTasteFileInfo(t);e.isTaste&&(o={...o||{},isTasteFile:!0,tasteCategory:e.category})}}const i={...e.input,...o?.isTasteFile?{isTasteFile:o.isTasteFile}:{},...o?.tasteCategory?{tasteCategory:o.tasteCategory}:{}},a=av(e.toolName,i),l={...GE(e.toolName,a,o),id:n,...r?{description:r}:{}},u=ZE(l,t);this.callbacks.onFeedUpdate(u)}showToolError(e,t,n,r){const s=av(e.toolName,e.input),o="edit_file"===e.toolName?{...e.input,permissionDenied:!0}:void 0,i={...GE(e.toolName,s,o),id:n,...r?{description:r}:{}},a=ZE(i,ev(t));this.callbacks.onFeedUpdate(a)}processServerToolBlocks(e){if(0===e.content.filter(e=>"tool-call"===e.type&&e.providerExecuted).length)return"";let t="";const n=e.content;for(const e of n)if("text"===e.type)t+=e.text;else if("tool-call"===e.type&&e.providerExecuted){if(t.trim()){const e=WE(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:s}=Ky({serverToolBlock:e,contentBlocks:n}),o=av(e.toolName,e.input),i=GE(e.toolName,o),a=ZE(i,s?ev(r):r);this.callbacks.onFeedUpdate(a)}if(t.trim()){const e=WE(t.trim());this.callbacks.onFeedUpdate(e)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}updateContextUsage(e){if(!("usage"in e))return;const t=e.usage;if(!t?.input_tokens)return;const n=calculateUsageFromResponse(t);this.contextTokensUsed=n,this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:pS})}async checkAndCompactIfNeeded(){const e=Math.floor(pS*Ut.TIER_1_THRESHOLD),t=Math.floor(pS*Ut.TIER_2_THRESHOLD),n=Math.floor(pS*Ut.TIER_3_THRESHOLD),r=getCompactMode();try{if(this.contextTokensUsed>n){mC.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 3 threshold (${n}), triggering summarization`),this.callbacks.onStatusUpdate?.("Context limit reached. Auto-compacting the conversation...");const e=this.contextTokensUsed;await this.summarizeAndCompact();const t=Math.max(0,e-this.contextTokensUsed);return void this.emitAutoCompactInfo(t)}if("fast"!==r)return;if(this.contextTokensUsed>t){mC.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${t}), removing all except last ${Ut.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(Ut.TIER_2_KEEP_COUNT);return mC.debug(`Tier 2 compaction completed: removed ${e.toolsRemoved} tool calls, saved ${e.tokensSaved} tokens`),void this.emitAutoCompactInfo(e.tokensSaved)}if(this.contextTokensUsed>e){const t=this.countToolCalls(),n=Ut.TIER_1_KEEP_COUNT;if(t>n){mC.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${e}), keeping last ${n} tool calls`);const t=await this.removeToolCallsExceptLast(n);mC.debug(`Tier 1 compaction completed: removed ${t.toolsRemoved} tool calls, saved ${t.tokensSaved} tokens`),this.emitAutoCompactInfo(t.tokensSaved)}}}catch(e){mC.debug(`Failed to automatically compact conversation: ${e}`)}}emitAutoCompactInfo(e){this.compactionCount++,e>0&&this.callbacks.onFeedUpdate(zE(`Auto-compacted conversation, saved ~${e.toLocaleString()} tokens.`,{isAutoCompact:!0}))}countToolCalls(){let e=0;for(const t of this.messages){const n=t.message.content;if(Array.isArray(n))for(const t of n)"tool-call"===t.type&&e++}return e}async removeToolCallsExceptLast(e){const t=this.contextTokensUsed;let n=0;const r=[];for(let e=0;e<this.messages.length;e++){const t=this.messages[e].message.content;if(Array.isArray(t))for(let n=0;n<t.length;n++)"tool-call"===t[n].type&&r.push({id:t[n].toolCallId,msgIndex:e,blockIndex:n})}const s=new Set(r.slice(-e).map(e=>e.id)),o=new Set(r.filter(e=>!s.has(e.id)).map(e=>e.id)),i=[];for(const e of this.messages){const t=e.message.role,r=e.message.content;if("tool"===t&&Array.isArray(r)){const t=r.filter(e=>"tool-result"!==e.type||!o.has(e.toolCallId)||(n+=estimateTokens({role:"user",content:[e]}),!1));if(0===t.length)continue;i.push({...e,message:{...e.message,content:t}});continue}if("assistant"===t&&Array.isArray(r)){const t=r.filter(e=>"tool-call"!==e.type||!o.has(e.toolCallId)||(n+=estimateTokens({role:"assistant",content:[e]}),!1));if(0===t.length)continue;i.push({...e,message:{...e.message,content:t}});continue}i.push(e)}this.messages=i,await this.sessionManager.saveMessages(this.messages);const a=Math.max(0,t-n);return this.contextTokensUsed=a,this.callbacks.onContextUsageUpdate?.({current:a,limit:pS}),{toolsRemoved:o.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return mC.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(Ut.TIER_2_KEEP_COUNT);mC.debug(`Summarizing ${e.length} older messages, keeping ${t.length} recent messages`);const n=e.map(e=>e.message),r=await this.compactAgent.compactMessages({messages:n});mC.debug(`Summarization complete: ${r.summary.length} chars, used ${r.tokensUsed.input}/${r.tokensUsed.output} tokens`);const s=this.createMessageWithMeta({role:"user",content:[{type:"text",text:`This is an auto-compacted summary of the earlier conversation that ran out of context.\n\n${r.summary}`}]},{isSummary:!0}),o=this.contextTokensUsed,i=e.reduce((e,t)=>e+estimateTokens(t.message),0);this.messages=[s,...t],await this.sessionManager.saveMessages(this.messages);const a=estimateTokens(s.message),l=Math.max(0,o-i+a);this.contextTokensUsed=l,this.callbacks.onContextUsageUpdate?.({current:l,limit:pS}),mC.debug(`Tier 3 summarization complete: reduced from ${o} to ~${l} tokens`)}catch(e){mC.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(Ut.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=Ut.KEEP_RECENT_TOKENS;let t=0,n=this.messages.length;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r],o=estimateTokens(s.message);if(t+o>e){n=r+1;break}t+=o;const i=s.message.content;Array.isArray(i)&&i.some(e=>"tool-result"===e.type)}n=Math.min(n,this.messages.length-3),n=Math.max(0,n);let r=0;this.messages[0]?.meta?.isSummary&&(r=1);for(let e=r;e<n;e++){const t=this.messages[e].message.content;if(Array.isArray(t)&&t.some(e=>"image"===e.type)){n=e;break}}for(;n>r&&"user"===this.messages[n].message.role;)n--;return{messagesToSummarize:this.messages.slice(r,n),messagesToKeep:this.messages.slice(n),keepStartIndex:n}}getCheckpointManager(){return this.checkpointManager}listCheckpoints(){return this.checkpointManager.listCheckpoints()}hasCheckpoints(){return this.checkpointManager.hasCheckpoints()}async restoreToCheckpoint(e){const{messageId:t,mode:n}=e;this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()});const r=this.sessionManager.getMessageIndexById({messageId:t,messages:this.messages});let s=0;if(-1!==r&&("conversation"===n||"both"===n))for(let e=r;e<this.messages.length;e++)s+=estimateTokens(this.messages[e].message);const o=await this.checkpointManager.restore({messageId:t,mode:n});return!o.success||"conversation"!==n&&"both"!==n||(this.contextTokensUsed=Math.max(0,this.contextTokensUsed-s),this.callbacks.onContextUsageUpdate&&this.callbacks.onContextUsageUpdate({current:this.contextTokensUsed,limit:pS})),o}async loadCheckpoints(){this.checkpointManager.setSessionStore({sessionStore:this.createSessionStoreAdapter()}),await this.checkpointManager.loadSnapshots(),this.checkpointManager.runCleanup().catch(()=>{})}isCheckpointingPaused(){return this.checkpointManager.isCheckpointingPaused()}getCheckpointPausedReason(){return this.checkpointManager.getPausedReason()}}}}),bC=__esm({"src/utils/clear-console.ts"(){Ht(),yC=__name(()=>process.stdout.write("win32"===process.platform?"":""),"clearConsole")}});async function findAvailablePort(e=5959,t=10){for(let n=0;n<t;n++){const t=e+n;if(await checkPortAvailable(t))return t}throw new Error(`No available port found after ${t} attempts starting from port ${e}`)}async function checkPortAvailable(e){return new Promise(t=>{const n=_e.createServer();n.once("error",()=>{t(!1)}),n.once("listening",()=>{n.close(()=>{t(!0)})}),n.listen(e,"127.0.0.1")})}function createAuthServer(e,t){let n,r;const s=new Promise((e,t)=>{n=e,r=t}),o=Oe.createServer((e,s)=>{const i=["http://localhost:3000","https://staging.commandcode.ai","https://commandcode.ai"],a=e.headers.origin||"",l=i.includes(a)?a:i[0];if(s.setHeader("Access-Control-Allow-Origin",l),s.setHeader("Access-Control-Allow-Methods","POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type"),s.setHeader("Content-Type","application/json"),"OPTIONS"===e.method)return s.writeHead(204),void s.end();if("/callback"!==e.url){const e={success:!1,error:"Not found"};return s.writeHead(404),void s.end(JSON.stringify(e))}if("POST"!==e.method){const e={success:!1,error:"Method not allowed. Use POST."};return s.writeHead(405),void s.end(JSON.stringify(e))}let u="";e.on("data",t=>{u+=t.toString(),u.length>1e4&&e.destroy()}),e.on("end",()=>{try{const e=JSON.parse(u);if(e.error){const t=e,n={success:!0};return s.writeHead(200),s.end(JSON.stringify(n)),"access_denied"===t.error?r(new wC(t.error_description||"Authorization was denied by the user")):r(new Error(t.error_description||t.error)),void o.close()}const i=e;if(!(i.apiKey&&i.state&&i.userId&&i.userName&&i.keyName)){const e={success:!1,error:"Missing required fields"};return s.writeHead(400),void s.end(JSON.stringify(e))}if(i.state!==t){const e={success:!1,error:"Invalid state token"};return s.writeHead(403),void s.end(JSON.stringify(e))}const a={success:!0};s.writeHead(200),s.end(JSON.stringify(a)),n(i),o.close()}catch{const e={success:!1,error:"Invalid JSON"};s.writeHead(400),s.end(JSON.stringify(e))}}),e.on("error",()=>{s.writeHead(500),s.end(JSON.stringify({success:!1,error:"Request error"}))})});return o.on("error",e=>{r(e)}),o.listen(e,"127.0.0.1"),{server:o,waitForCallback:s}}function stopServer(e){return new Promise((t,n)=>{e.close(e=>{e?"ERR_SERVER_NOT_RUNNING"===e.code?t():n(e):t()})})}var EC,vC=__esm({"src/utils/auth/local-server.ts"(){Ht(),__name(findAvailablePort,"findAvailablePort"),__name(checkPortAvailable,"checkPortAvailable"),wC=class extends Error{static{__name(this,"AuthAccessDeniedError")}constructor(e="Authorization was denied by the user"){super(e),this.name="AuthAccessDeniedError"}},__name(createAuthServer,"createAuthServer"),__name(stopServer,"stopServer")}});function generateStateToken(){return W.randomBytes(32).toString("base64url")}async function openBrowser(e){try{return await me(e),!0}catch(e){return console.error("[CLI Auth] Failed to open browser:",e instanceof Error?e.message:"Unknown error"),trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"browser_open_failed"}),context:{component:ys.AUTH_FLOW,heading:"Failed to open browser"}}),!1}}function getStudioBaseUrl(){switch(zt()){case"local":return"http://localhost:3000";case"staging":return"https://staging.commandcode.ai";default:return"https://commandcode.ai"}}function buildAuthUrl(e,t){return`${getStudioBaseUrl()}/studio/auth/cli?callback=${encodeURIComponent(`http://localhost:${e}/callback`)}&state=${encodeURIComponent(t)}`}async function storeCredentials(e){const t=getAuthDir(),n=getAuthFile();await D.mkdir(t,{recursive:!0,mode:448});const r=JSON.stringify({apiKey:e.apiKey,userId:e.userId,userName:e.userName,keyName:e.keyName,authenticatedAt:e.authenticatedAt},null,2);await D.writeFile(n,r,{mode:384}),await D.chmod(n,384)}async function loadCredentials(){try{const e=getAuthFile(),t=await D.readFile(e,"utf-8"),n=JSON.parse(t);return n.apiKey?{apiKey:n.apiKey,userId:n.userId??"",userName:n.userName??"",keyName:n.keyName??"",authenticatedAt:n.authenticatedAt??""}:null}catch(e){return"ENOENT"===e.code||process.env.DEBUG&&console.error("Failed to load credentials:",e),null}}var CC,kC,TC,_C=__esm({"src/utils/auth/auth-flow.ts"(){Ht(),vC(),Yt(),Zt(),Cs(),__name(generateStateToken,"generateStateToken"),__name(openBrowser,"openBrowser"),__name(getStudioBaseUrl,"getStudioBaseUrl"),__name(buildAuthUrl,"buildAuthUrl"),EC=class extends Error{constructor(e,t){super(t),this.code=e,this.name="AuthFlowError"}static{__name(this,"AuthFlowError")}},__name(storeCredentials,"storeCredentials"),__name(loadCredentials,"loadCredentials")}});async function validateApiKey(e){try{const t=getApiBaseUrl(),n=await fetch(`${t}${kt.ALPHA.WHOAMI}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});return 401===n.status?{valid:!1,error:"invalid_key"}:n.ok?{valid:!0,user:await n.json()}:(process.env.DEBUG&&console.error(`API key validation failed with status ${n.status}`),{valid:!1,error:"server_error"})}catch(e){return trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"apikey_validation_network_error"}),context:{component:ys.AUTH_FLOW,heading:"API key validation network error"}}),process.env.DEBUG&&console.error("API key validation network error:",e),{valid:!1,error:"network_error"}}}function sanitizeApiKey(e){const t=String.fromCharCode(27),n=e.replaceAll(t+"[200~","").replaceAll(t+"[201~","").replaceAll("[200~","").replaceAll("[201~","");return Array.from(n).filter(e=>{const t=e.charCodeAt(0);return t>31&&127!==t}).join("").trim()}function useAuthFlow(e){const{onSuccess:t,onFailure:n,onCancel:r,timeout:s=CC}=e,[o,i]=K("initializing"),[a,l]=K("Starting authentication..."),[u,d]=K(""),[m,g]=K(null),h=Y(null),f=Y(!1),y=Y(!1),w=Y(null),S=Y(t),E=Y(n),v=Y(r);J(()=>{S.current=t,E.current=n,v.current=r});const C=Z(()=>{w.current&&(clearTimeout(w.current),w.current=null),h.current&&(stopServer(h.current).catch(e=>{process.env.DEBUG&&console.error("Failed to stop auth server:",e)}),h.current=null)},[]),k=Z(()=>{y.current||(y.current=!0,f.current=!0,C(),v.current())},[C]),T=Z((e,t)=>{y.current||(y.current=!0,C(),S.current(e,t))},[C]),_=Z((e,t)=>{y.current||(y.current=!0,C(),E.current(e,t))},[C]),x=Z(async e=>{const t=sanitizeApiKey(e);if(!t)return;i("validating"),l("Validating API key...");const n=await validateApiKey(t);if(f.current)return;if(y.current)return;if(!n.valid){let e;switch(n.error){case"invalid_key":e="Invalid API key. Please check and try again.";break;case"network_error":e="Could not reach server. Check your connection and try again.";break;case"server_error":e="Server error. Please try again later.";break;default:e="Validation failed. Please try again."}return i("invalid_key"),l(e),void(w.current=setTimeout(()=>{f.current||y.current||(i("manual_entry"),l("Paste a valid API key below.")),w.current=null},2e3))}const r=n.user.user;try{const e={apiKey:t,userId:r?.id||"manual-entry",userName:r?.userName||r?.name||"API Key",keyName:"cli-manual-entry",authenticatedAt:(new Date).toISOString()};if(y.current)return;await storeCredentials(e),i("success"),T(e,"manual")}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"store_credentials_failed"}),context:{component:ys.AUTH_FLOW,heading:"Failed to store credentials"}}),process.env.DEBUG&&console.error("Failed to store credentials:",e),l("Failed to save API key. Please try again."),i("manual_entry")}},[T]);return J(()=>{let e=!0;return __name(async()=>{if(!f.current)try{const t=await findAvailablePort(kC,TC);if(!e||f.current)return;const n=generateStateToken(),r=buildAuthUrl(t,n);g(r);const{server:o,waitForCallback:a}=createAuthServer(t,n);if(h.current=o,!e||f.current)return void await stopServer(o);i("waiting_browser"),l("Complete login in your browser...");const u=await openBrowser(r);if(!e||f.current)return;if(!u)return C(),l("Could not open browser. Paste your API key below."),void i("manual_entry");const d=new Promise((e,t)=>{setTimeout(()=>{t(new EC("TIMEOUT","Browser authentication timed out"))},s)});try{const t=await Promise.race([a,d]);if(!e||f.current)return;if(y.current)return;const n={apiKey:t.apiKey,userId:t.userId,userName:t.userName,keyName:t.keyName,authenticatedAt:(new Date).toISOString()};if(y.current)return;if(await storeCredentials(n),!e||f.current||y.current)return;i("browser_success"),T(n,"browser")}catch(t){if(y.current)return;if(!e||f.current)return;if(t instanceof wC)return trackError({error:sanitizeErrorForTelemetry({error:t,label:"auth_denied_by_user"}),context:{component:ys.AUTH_FLOW,heading:"Authorization denied by user"}}),i("denied"),void _("denied","Authorization denied by user.");C(),t instanceof EC&&"TIMEOUT"===t.code?(trackError({error:sanitizeErrorForTelemetry({error:t,label:"browser_auth_timeout"}),context:{component:ys.AUTH_FLOW,heading:"Browser auth timed out"}}),l("Browser auth timed out. Paste your API key below.")):(trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_failed"}),context:{component:ys.AUTH_FLOW,heading:"Browser auth failed"}}),l("Browser auth failed. Paste your API key below.")),i("manual_entry")}}catch(t){if(y.current)return;if(!e||f.current)return;trackError({error:sanitizeErrorForTelemetry({error:t instanceof Error?t:new Error(String(t)),label:"browser_auth_startup_failed"}),context:{component:ys.AUTH_FLOW,heading:"Browser auth startup failed"}}),process.env.DEBUG&&console.error("Browser auth startup failed:",t),C(),i("manual_entry"),l("Could not start browser auth. Paste your API key below.")}},"startBrowserAuth")(),()=>{e=!1,C()}},[s,T,_,C]),{authState:o,statusMessage:a,browserUrl:m,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:x,cancel:k,hasCompleted:y.current}}var xC=__esm({"src/tui/hooks/use-auth-flow.ts"(){Ht(),_C(),vC(),Xy(),Kt(),Cs(),CC=12e4,kC=5959,TC=10,__name(validateApiKey,"validateApiKey"),__name(sanitizeApiKey,"sanitizeApiKey"),__name(useAuthFlow,"useAuthFlow")}});function getAuthStatusColor(e){switch(e){case"browser_success":case"success":return"green";case"denied":case"error":case"invalid_key":return"red";case"manual_entry":return"yellow";default:return"cyan"}}function getAuthHelpText(e){return"waiting_browser"===e?"Authorize in browser, or paste API key here":"invalid_key"===e?"That key was invalid. Try again.":"Paste your API key and press Enter"}function getAuthUrlLabel(e){return"waiting_browser"===e?"Login: ":"Get API key: "}var PC,AC,IC,NC=__esm({"src/utils/auth/auth-status.ts"(){Ht(),__name(getAuthStatusColor,"getAuthStatusColor"),__name(getAuthHelpText,"getAuthHelpText"),__name(getAuthUrlLabel,"getAuthUrlLabel")}}),RC=__esm({"src/tui/auth-flow-ui.tsx"(){Ht(),gr(),NC(),dr(),Pr(),(PC=Q.memo(({authState:e,browserUrl:t,apiKeyInput:n,setApiKeyInput:r,handleApiKeySubmit:s})=>{const o="waiting_browser"===e||"manual_entry"===e||"invalid_key"===e,i=t&&("waiting_browser"===e||"manual_entry"===e);return Q.createElement(Q.Fragment,null,o&&Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,{borderStyle:"single",borderColor:"manual_entry"===e||"invalid_key"===e?jn.YELLOW:jn.GRAY,paddingX:1},Q.createElement(te,{color:jn.DIM},"API Key: "),Q.createElement(ee,{flexGrow:1},Q.createElement(TextInput,{value:n,onChange:r,onSubmit:s,placeholder:"Paste your API key...",mask:"*",showCursor:!0}))),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},getAuthHelpText(e))),i&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},getAuthUrlLabel(e)),Q.createElement(Cr,{url:t,text:"Open login page ↗",color:jn.CYAN,dimColor:!0}))),"validating"===e&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Checking API key with server...")),("waiting_browser"===e||"manual_entry"===e||"invalid_key"===e)&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Ctrl+C to cancel")))})).displayName="AuthInputSection",AC=__name(({authState:e,statusMessage:t,browserUrl:n,apiKeyInput:r,setApiKeyInput:s,handleApiKeySubmit:o})=>{const i=__name(()=>{switch(e){case"initializing":case"validating":default:return Q.createElement(Fe,{type:"dots"});case"waiting_browser":return Q.createElement(te,{color:jn.CYAN},ke.ellipsis);case"browser_success":case"success":return Q.createElement(te,{color:jn.GREEN},ke.tick);case"denied":case"invalid_key":return Q.createElement(te,{color:jn.RED},ke.cross);case"manual_entry":return Q.createElement(te,{color:jn.YELLOW},ke.arrowDown);case"error":return Q.createElement(te,{color:jn.RED},ke.warning)}},"getStatusIcon"),a=__name(()=>getAuthStatusColor(e),"getStatusColor");return"browser_success"===e||"success"===e||"denied"===e?null:Q.createElement(ee,{flexDirection:"column",paddingY:1},Q.createElement(ee,{marginBottom:1},Q.createElement(ee,{marginRight:1},i()),Q.createElement(te,{color:a()},t)),Q.createElement(PC,{authState:e,browserUrl:n,apiKeyInput:r,setApiKeyInput:s,handleApiKeySubmit:o}))},"AuthFlowUI")}}),$C=__esm({"src/tui/login-with-api-key.tsx"(){Ht(),xC(),RC(),IC=__name(({onComplete:e})=>{const{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:s,setApiKeyInput:o,handleApiKeySubmit:i,cancel:a}=useAuthFlow({onSuccess:__name((t,n)=>{e({success:!0,config:t,source:n})},"onSuccess"),onFailure:__name((t,n)=>{e({success:!1,reason:t,message:n})},"onFailure"),onCancel:__name(()=>{e({success:!1,reason:"cancelled",message:"Authentication cancelled by user."})},"onCancel")});return se((e,t)=>{t.ctrl&&"c"===e&&a()}),Q.createElement(AC,{authState:t,statusMessage:n,browserUrl:r,apiKeyInput:s,setApiKeyInput:o,handleApiKeySubmit:i})},"LoginWithApiKey")}});function heading({text:e,sub:t,dim:n,green:r}){const s=t?` ${t}`:"";return r?`${ce.bgGreen(ce.black(` ${e} `))}${s}`:n?`${ce.bgBlack(ce.white(` ${e} `))}${s}`:`${ce.bold(ce.bgCyan(ce.black(` ${e} `)))}${s}`}var MC=__esm({"src/utils/heading.ts"(){Ht(),__name(heading,"heading")}});function createOSC8Link(e,t,n=!0){return`${n?"":""}]8;;${e}${t||e}]8;;${n?"":""}`}var LC=__esm({"src/utils/osc8-link.ts"(){Ht(),__name(createOSC8Link,"createOSC8Link")}});async function performAnthropicAuth(){try{const{url:e,verifier:t,state:n}=Sn.createAuthorizationUrl(),r=await Be({message:"Open the Anthropic auth page?",initialValue:!0});if(Ge(r))return{success:!1,error:"Anthropic authentication cancelled"};console.log(),console.log(ce.dim(" Login: ")+createOSC8Link(e,"Open auth page ↗")),console.log(),!0===r?(await me(e),console.log(ce.yellow(" Copy your authorization code and paste it below.")),console.log()):(console.log(ce.yellow(" Open the URL above and copy your authorization code below.")),console.log());const s=await He({message:"Paste your authorization code:",mask:"*"});if(Ge(s))return{success:!1,error:"No API key provided"};if(!s.trim())return{success:!1,error:"No authorization code provided"};const o=s.split("#")[0].trim();return await Sn.exchangeCodeForTokens(o,t,n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}var DC=__esm({"src/commands/auth/anthropic-auth.ts"(){Ht(),xn(),LC(),__name(performAnthropicAuth,"performAnthropicAuth")}});async function performCopilotAuth(){try{const e=await Be({message:"Open GitHub to authorize Copilot access?",initialValue:!0});return Ge(e)?{success:!1,error:"Copilot authentication cancelled"}:(await Pn.login({onAuth:__name(({userCode:t,verificationUri:n})=>{console.log(),console.log(ce.yellow(` Enter this code on GitHub: ${ce.bold(t)}`)),console.log(),!0===e?me(n).catch(()=>{console.log(ce.dim(` Open: ${n}`))}):(console.log(ce.dim(" Open this URL in your browser:")),console.log(` ${n}`),console.log())},"onAuth"),onProgress:__name(e=>{console.log(` ${ce.dim(ke.circleFilled)} ${ce.dim(e)}`)},"onProgress")}),{success:!0})}catch(e){const t=e instanceof Error?e.message:"Unknown error";return dlog("[CopilotAuth] performCopilotAuth failed",{error:t}),{success:!1,error:t}}}var OC,FC=__esm({"src/commands/auth/copilot-auth.ts"(){Ht(),Nn(),In(),__name(performCopilotAuth,"performCopilotAuth")}});async function hasBeenInstalled(){try{return!0===(await loadUserConfig()).installed}catch{return!1}}async function markAsInstalled(){try{await updateUserConfig({installed:!0})}catch(e){dlog("[detect-first-install] failed to mark as installed",{error:e})}}async function detectAndTrackFirstInstall(){if(!await hasBeenInstalled())return OC||(OC=(async()=>{try{const e=getPackageJson().version||"unknown";await trackLifecycleEvent({eventType:"cli_installed",metadata:{cliVersion:e}}),await markAsInstalled(),dlog("[detect-first-install] tracked first install")}catch(e){dlog("[detect-first-install] failed to track",{error:e})}finally{OC=null}})())}var qC,jC,BC,UC,zC,WC,GC,HC=__esm({"src/utils/detect-first-install.ts"(){Ht(),Jv(),Ur(),In(),xr(),OC=null,__name(hasBeenInstalled,"hasBeenInstalled"),__name(markAsInstalled,"markAsInstalled"),__name(detectAndTrackFirstInstall,"detectAndTrackFirstInstall")}}),QC=__esm({"src/commands/auth/errors.ts"(){Ht(),qC=class extends Error{static{__name(this,"LoginCancelledError")}constructor(e){super(e),this.name="LoginCancelledError"}},jC=class extends Error{static{__name(this,"AuthorizationDeniedError")}constructor(e){super(e),this.name="AuthorizationDeniedError"}}}});function TaskSpinner({loadingMessage:e,successMessage:t,task:n,onComplete:r,showSuccessState:s=!0}){const[o,i]=K("loading"),[a,l]=K(null);return J(()=>{n().then(e=>{l(e),i(s?"success":"done")})},[n,s]),J(()=>{if("done"===o&&null!==a&&r(a),"success"===o&&null!==a){const e=setTimeout(()=>r(a),100);return()=>clearTimeout(e)}},[o,a,r]),"done"===o?null:Q.createElement(zC,null,"loading"===o?Q.createElement(BC,{message:e}):Q.createElement(UC,{message:t}))}async function checkExistingAuth(e){const t=await checkAuthStatus(e);return t.authenticated?{isAuthenticated:!0,userName:t.userName}:{isAuthenticated:!1}}function getAuthFileName(e){return"local"===e?"auth.local.json":"staging"===e?"auth.staging.json":"auth.json"}function isGenericUserName(e){return!e||"API Key"===e}function isGenericUserNameForOutro(e){return isGenericUserName(e)||"Manual API Key"===e}function formatUserDisplay(e,t=!1){return(t?isGenericUserNameForOutro(e):isGenericUserName(e))?t?" successfully":"":` as ${ce.cyan(e)}`}function buildAlreadyLoggedInMessage(e){const t=formatUserDisplay(e);return[`${ce.green(ke.tick)} ${ce.bold("Already logged in")}${t}`,"",`${ce.dim("Run")} ${ce.cyan("cmd")} ${ce.dim("to get started.")}`].join("\n")}function buildSuccessMessage(e,t){const n=formatUserDisplay(e,!0);return[`${ce.green(ke.tick)} ${ce.bold("Logged in")}${n}`,"",`${ce.dim("API key stored in")} ${ce.cyan(`~/.commandcode/${t}`)}`,`${ce.dim("Run")} ${ce.cyan("cmd")} ${ce.dim("to get started.")}`].join("\n")}function isLoginSuccess(e){return e.success}function isLoginDenied(e){return"denied"===e.reason}function isLoginCancelled(e){return"cancelled"===e.reason}function createLoginError(e){return isLoginDenied(e)?new jC(e.message):isLoginCancelled(e)?new qC(e.message):new Error(e.message)}function processLoginResult(e){return isLoginSuccess(e)?{success:!0,userName:e.config?.userName}:{success:!1,error:createLoginError(e)}}function needsProviderSelection(e){return e.length>1}function getDefaultProvider(e){return e[0]?.value??""}function isAnthropicProvider(e){return"anthropic"===e}function isCopilotProvider(e){return"github-copilot"===e}function isUserCancellation(e){return e instanceof qC||e instanceof jC}function getErrorMessage(e){return e instanceof Error?e.message:"Unknown error"}function showAuthIntro(){console.log("\n"),qe.intro(heading({text:"Command Code Authentication"}))}async function promptProviderSelection(e){const t=await We({message:"Select provider",options:e});if(Ge(t))throw ze(`${ke.cross} No provider selected.`),new qC("No provider selected");return t}async function selectProvider(){const e=getProviderOptions();return needsProviderSelection(e)?promptProviderSelection(e):getDefaultProvider(e)}function showLoginCancelMessage(e){ze(`${ke.cross} ${e}`)}function showAnthropicAuthNote(){Ue("Command Code authentication complete. Now authenticating with Anthropic...")}function printMessage(e){console.log(""),console.log(e),console.log("")}function renderTaskWithSpinner(e,t,n,r=!0){return new Promise(s=>{const o=__name(e=>{i(),s(e)},"handleComplete"),{unmount:i}=oe(Q.createElement(TaskSpinner,{loadingMessage:e,successMessage:t,task:n,onComplete:o,showSuccessState:r}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}function runLoginWithApiKeyFlow(){return new Promise(e=>{const{unmount:t}=oe(Q.createElement(IC,{onComplete:__name(n=>{setTimeout(()=>{t(),e(n)},100)},"onComplete")}),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1})})}async function checkAuthWithSpinner(e){return new Promise(t=>{const{unmount:n}=oe(Q.createElement(WC,{env:e,onComplete:e=>{n(),t(e)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function saveConfigWithSpinner(e){await renderTaskWithSpinner("Saving configuration...","Configuration saved",()=>updateUserConfig({provider:e}),!0)}async function executeLoginFlow(){const e=processLoginResult(await runLoginWithApiKeyFlow());if(!e.success)throw showLoginCancelMessage(e.error.message),e.error;return e.userName}async function handleProviderAuth(e){dlog("[Auth] handleProviderAuth",e),isAnthropicProvider(e)?(showAnthropicAuthNote(),await performAnthropicAuth()):isCopilotProvider(e)&&(dlog("[Auth] starting copilot auth flow"),Ue("Command Code authentication complete. Now authenticating with GitHub Copilot..."),await performCopilotAuth())}async function finalizeLogin(e,t,n){await saveConfigWithSpinner(e),printMessage(buildSuccessMessage(t,getAuthFileName(n)))}async function runLogin(){const e=zt(),t=await checkAuthWithSpinner(e);if(t.isAuthenticated)return printMessage(buildAlreadyLoggedInMessage(t.userName)),!0;showAuthIntro();const n=await executeLoginFlow();detectAndTrackFirstInstall().catch(()=>{});let r="command-code";return isInternalTeamFlagEnforced()&&(r=await selectProvider(),await handleProviderAuth(r)),await finalizeLogin(r,n,e),!0}async function loginAction(){try{await runLogin(),process.exit(0)}catch(e){isUserCancellation(e)&&process.exit(0),console.error(`${ke.cross} Login failed:`,getErrorMessage(e)),process.exit(1)}}var VC=__esm({"src/tui/auth/login.tsx"(){Ht(),Kt(),$C(),_n(),Yt(),MC(),Nr(),xr(),DC(),FC(),In(),HC(),QC(),Ls(),dr(),BC=__name(({message:e})=>Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.CYAN},Q.createElement(Fe,{type:"dots"})),Q.createElement(te,null," ",e)),"LoadingIndicator"),UC=__name(({message:e})=>Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.GREEN},ke.tick),Q.createElement(te,null," ",e)),"SuccessIndicator"),zC=__name(({children:e})=>Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,null," "),Q.createElement(ee,null,e)),"StatusContainer"),__name(TaskSpinner,"TaskSpinner"),__name(checkExistingAuth,"checkExistingAuth"),__name(getAuthFileName,"getAuthFileName"),__name(isGenericUserName,"isGenericUserName"),__name(isGenericUserNameForOutro,"isGenericUserNameForOutro"),__name(formatUserDisplay,"formatUserDisplay"),__name(buildAlreadyLoggedInMessage,"buildAlreadyLoggedInMessage"),__name(buildSuccessMessage,"buildSuccessMessage"),__name(isLoginSuccess,"isLoginSuccess"),__name(isLoginDenied,"isLoginDenied"),__name(isLoginCancelled,"isLoginCancelled"),__name(createLoginError,"createLoginError"),__name(processLoginResult,"processLoginResult"),__name(needsProviderSelection,"needsProviderSelection"),__name(getDefaultProvider,"getDefaultProvider"),__name(isAnthropicProvider,"isAnthropicProvider"),__name(isCopilotProvider,"isCopilotProvider"),__name(isUserCancellation,"isUserCancellation"),__name(getErrorMessage,"getErrorMessage"),__name(showAuthIntro,"showAuthIntro"),__name(promptProviderSelection,"promptProviderSelection"),__name(selectProvider,"selectProvider"),__name(showLoginCancelMessage,"showLoginCancelMessage"),__name(showAnthropicAuthNote,"showAnthropicAuthNote"),__name(printMessage,"printMessage"),__name(renderTaskWithSpinner,"renderTaskWithSpinner"),__name(runLoginWithApiKeyFlow,"runLoginWithApiKeyFlow"),WC=__name(({env:e,onComplete:t})=>{const[n,r]=K("checking"),[s,o]=K(null);return J(()=>{checkExistingAuth(e).then(e=>{o(e),r(e.isAuthenticated?"logged_in":"not_logged_in")})},[e]),J(()=>{if("checking"!==n&&null!==s){const e=setTimeout(()=>t(s),100);return()=>clearTimeout(e)}},[n,s,t]),Q.createElement(zC,null,"checking"===n&&Q.createElement(BC,{message:"Checking authentication status..."}),"logged_in"===n&&Q.createElement(UC,{message:"Authenticated"}),"not_logged_in"===n&&Q.createElement(UC,{message:"Ready to log in"}))},"AuthCheckSpinner"),__name(checkAuthWithSpinner,"checkAuthWithSpinner"),__name(saveConfigWithSpinner,"saveConfigWithSpinner"),__name(executeLoginFlow,"executeLoginFlow"),__name(handleProviderAuth,"handleProviderAuth"),__name(finalizeLogin,"finalizeLogin"),__name(runLogin,"runLogin"),__name(loginAction,"loginAction"),GC=new ve("login").description("Login with Command Code account").allowUnknownOption().allowExcessArguments().action(loginAction)}});async function safeRemoveFile(e,t){try{return await O.unlink(e),{existed:!0}}catch(e){return"ENOENT"===e.code?{existed:!1}:{existed:!0,warning:`Could not remove ${t}: ${e.message}`}}}function collectWarnings(...e){return e.map(e=>e.warning).filter(e=>void 0!==e)}async function performLogout(){try{const e=await safeRemoveFile(getAuthFile(),"auth file"),t=collectWarnings(e);return{success:!0,wasAuthenticated:e.existed,warnings:t}}catch(e){return{success:!1,wasAuthenticated:!1,warnings:[],error:e instanceof Error?e.message:"Unknown error"}}}var KC,YC,JC,XC,ZC,ek,tk=__esm({"src/utils/auth/logout.ts"(){Ht(),Zt(),__name(safeRemoveFile,"safeRemoveFile"),__name(collectWarnings,"collectWarnings"),__name(performLogout,"performLogout")}});function printWarnings(e){e.length>0&&(console.warn(ce.yellow("\nLogout completed with warnings:")),e.forEach(e=>console.warn(ce.yellow(` - ${e}`))))}function renderLogoutUI(){return new Promise(e=>{const{unmount:t}=oe(Q.createElement(ZC,{onComplete:n=>{t(),e(n)}}),{stdout:process.stdout,stderr:process.stderr,stdin:process.stdin})})}async function logoutAction(){const e=await renderLogoutUI();e.success||process.exit(1),printWarnings(e.warnings),console.log(""),process.exit(0)}var nk=__esm({"src/tui/auth/logout.tsx"(){Ht(),tk(),dr(),KC=__name(()=>Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.CYAN},Q.createElement(Fe,{type:"dots"})),Q.createElement(te,null," Logging out...")),"LoadingIndicator"),YC=__name(()=>Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.GREEN},ke.tick),Q.createElement(te,null," Logged out")),"SuccessIndicator"),JC=__name(({errorMessage:e})=>Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.RED},ke.cross),Q.createElement(te,{color:jn.RED}," Logout failed: ",e)),"ErrorIndicator"),XC=__name(({status:e,errorMessage:t})=>{switch(e){case"loading":return Q.createElement(KC,null);case"success":return Q.createElement(YC,null);case"error":return Q.createElement(JC,{errorMessage:t})}},"StatusDisplay"),ZC=__name(({onComplete:e})=>{const[t,n]=K("loading"),[r,s]=K(""),[o,i]=K(null);return J(()=>{performLogout().then(e=>{i(e),e.success?n("success"):(s(e.error||"Unknown error"),n("error"))})},[]),J(()=>{if(("success"===t||"error"===t)&&o){const t=setTimeout(()=>e(o),100);return()=>clearTimeout(t)}},[t,o,e]),Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,null," "),Q.createElement(ee,null,Q.createElement(XC,{status:t,errorMessage:r})))},"LogoutSpinner"),__name(printWarnings,"printWarnings"),__name(renderLogoutUI,"renderLogoutUI"),__name(logoutAction,"logoutAction"),ek=new ve("logout").description("Remove stored authentication").allowUnknownOption().allowExcessArguments().action(logoutAction)}}),rk=__esm({"src/commands/auth/index.ts"(){Ht(),VC(),nk(),Ls(),QC(),Ls(),nk(),VC(),DC(),FC(),Yt(),Zt(),new ve("auth").description("Manage authentication with Command Code").addCommand(GC).addCommand(ek).addCommand(vs)}});async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new xy({baseUrl:e});return await t.get({endpoint:kt.ALPHA.WHOAMI})}var sk=__esm({"src/utils/get-entity.ts"(){Ht(),Xy(),Wy(),Kt(),__name(getAuthenticatedEntity,"getAuthenticatedEntity")}}),ok={};async function getBillingLink({billingLink:e,setBillingLink:t}){if(e)return e;try{const e=await getAuthKey();if(!e)return;const n=await getAuthenticatedEntity();if(e.startsWith("user_")){const e="https://commandcode.ai/settings/billing";return t(e),e}if(n.org){const e=`https://commandcode.ai/${n.org.login}/settings/billing`;return t(e),e}}catch{return"https://commandcode.ai/settings/billing"}}async function handleSubmit({role:e,input:t,images:n,ideContext:r,displayMessage:s,isAutomated:o,feed:i,setFeed:a,isCmdCodeBusy:l,setIsCmdCodeBusy:u,setQueuedMessages:d,setStatus:m,setInteractionTokens:g,updateStatus:h,setUpdateStatus:f,billingLink:y,setBillingLink:w,contextEngineRef:S,isSubmittingRef:E,setInput:v,setStaticKey:C,executeBash:k}){if(!t.length)return;if(h&&f(null),g(0),"bash"===e){if(E.current)return;E.current=!0;const e=HE(t);return a([...i,e]),v(""),await k(t,e=>{a(e)},()=>{yC(),C(e=>e+1)}),void(E.current=!1)}if(l)return d(e=>[...e,{input:t,displayMessage:s,isAutomated:o}]),void v("");if(E.current)return;E.current=!0,u(!0),m(sv()),v("");let T=!1;try{S.current&&await S.current.sendMessage(t,n,r,s,o?{isAutomated:!0}:void 0)}catch(e){if("Interrupted by user"===e?.message||e?.message?.toLowerCase().includes("interrupt")||e?.message?.toLowerCase().includes("abort")||"InterruptedError"===e?.name||"AbortError"===e?.name||"ECONNABORTED"===e?.code)return void(T=!0);if(T=!0,"Insufficient credits"===e.message){m("Insufficient credits");const e=`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code here: ${await getBillingLink({billingLink:y,setBillingLink:w})}`;return void a(t=>[...t,VE(e)])}if(e.message.startsWith("Error:"))return m("Error"),void a(t=>[...t,VE(e.message)]);m("Error");const t=e.message||"An unexpected error occurred";a(e=>[...e,VE(t)])}finally{u(!1),T||m("Ready..."),E.current=!1}}__export(ok,{getBillingLink:()=>getBillingLink,handleSubmit:()=>handleSubmit});var ik,ak=__esm({"src/tui/actions/submit.ts"(){Ht(),dv(),rk(),sk(),Kt(),bC(),__name(getBillingLink,"getBillingLink"),__name(handleSubmit,"handleSubmit")}});function isCorruptedArchiveError(e){const t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("zlib")||t.includes("unexpected end")||t.includes("tar_bad_archive")||t.includes("unrecognized archive")||t.includes("invalid tar header")}async function clearGigetCache(e,n){const r=t.join(w.homedir(),".cache","giget","gh",`${e}-${n}`);await O.rm(r,{recursive:!0,force:!0}).catch(()=>{})}async function cleanupStaleTempDirectories(){try{const e=w.tmpdir(),n=await O.readdir(e,{withFileTypes:!0}),r=Date.now();for(const s of n)if(s.isDirectory()&&(s.name.startsWith("commandcode-skill-")||s.name.startsWith("commandcode-skill-discovery-")))try{const n=t.join(e,s.name);r-(await O.stat(n)).mtimeMs>ik&&await O.rm(n,{recursive:!0,force:!0})}catch(e){}}catch(e){}}function wrapFetchError(e,t,n){const r=e instanceof Error?e.message:String(e),s=r.toLowerCase();return s.includes("could not find commit hash")||s.includes("not found")||s.includes("404")?new Error(`Repository "${t}/${n}" not found on GitHub.\nIf the repo doesn't use "main" branch, specify the branch: ${t}/${n}@<branch>`):s.includes("403")||s.includes("401")||s.includes("forbidden")||s.includes("unauthorized")||s.includes("could not download")?new Error(`Repository "${t}/${n}" is private or inaccessible.\nSkills can only be installed from public repositories.`):s.includes("enotfound")||s.includes("econnrefused")||s.includes("etimedout")?new Error("Network error: unable to reach GitHub. Check your internet connection."):s.includes("zlib")||s.includes("unexpected end")||s.includes("tar_bad_archive")||s.includes("unrecognized archive")||s.includes("invalid tar header")?new Error(`Download of "${t}/${n}" failed (corrupted archive).\nThis is usually a transient GitHub issue. Please try again.`):new Error(`Failed to fetch "${t}/${n}": ${r}`)}var lk,ck,uk=__esm({"src/services/skill-utils.ts"(){Ht(),ik=864e5,__name(isCorruptedArchiveError,"isCorruptedArchiveError"),__name(clearGigetCache,"clearGigetCache"),__name(cleanupStaleTempDirectories,"cleanupStaleTempDirectories"),__name(wrapFetchError,"wrapFetchError")}}),dk={};async function findSkillMdFiles(e){const{dir:n,maxDepth:r=5,currentDepth:s=0,relativePath:o="",foundCount:i={value:0}}=e;if(s>r)return[];if(i.value>=lk)return[];const a=[];try{const e=await O.readdir(n,{withFileTypes:!0}),l=e.find(e=>("SKILL.md"===e.name||"skill.md"===e.name)&&e.isFile());if(l){const e=t.join(n,l.name);try{if((await O.stat(e)).size>ck);else{const r=await O.readFile(e,"utf-8"),{data:s}=Ne(r),l=o.split("/").filter(Boolean),u=l[l.length-1]||t.basename(n);a.push({name:s.name||u,path:o||".",description:s.description}),i.value++}}catch(e){process.env.DEBUG&&console.error(`Failed to parse SKILL.md at ${o||"."}: ${e instanceof Error?e.message:String(e)}`)}}const u=e.filter(e=>e.isDirectory());for(const e of u){if("node_modules"===e.name||".git"===e.name||"dist"===e.name||"build"===e.name||".next"===e.name)continue;const l=t.join(n,e.name),u=o?`${o}/${e.name}`:e.name,d=await findSkillMdFiles({dir:l,maxDepth:r,currentDepth:s+1,relativePath:u,foundCount:i});a.push(...d)}}catch(e){process.env.DEBUG&&console.error(`Failed to read directory ${o||"."}: ${e instanceof Error?e.message:String(e)}`)}return a}async function discoverSkillsLocally(e){const{owner:n,repo:r,path:s,branch:o,keepTempDir:i=!1}=e;await cleanupStaleTempDirectories();const a=t.join(w.tmpdir(),`commandcode-skill-discovery-${H()}`);try{await O.mkdir(a,{recursive:!0});let e=`gh:${n}/${r}`;s&&(e+=`/${s}`),o&&(e+=`#${o}`);const{downloadTemplate:t}=await import("giget");try{await t(e,{dir:a,force:!0,silent:!0})}catch(s){if(!isCorruptedArchiveError(s))throw s;await clearGigetCache(n,r),await t(e,{dir:a,force:!0,silent:!0})}const l=await findSkillMdFiles({dir:a,maxDepth:5});return i?{skills:l,tempDir:a}:(await O.rm(a,{recursive:!0,force:!0}).catch(()=>{}),{skills:l})}catch(e){throw await O.rm(a,{recursive:!0,force:!0}).catch(()=>{}),wrapFetchError(e,n,r)}}__export(dk,{discoverSkillsLocally:()=>discoverSkillsLocally});var mk=__esm({"src/services/local-skill-discovery.ts"(){Ht(),uk(),lk=100,ck=1048576,__name(findSkillMdFiles,"findSkillMdFiles"),__name(discoverSkillsLocally,"discoverSkillsLocally")}});Ht(),Ht();var pk=process.argv.includes("-d")||process.argv.includes("--debug");pk&&(process.env.DEBUG="true"),pk||(process.removeAllListeners("warning"),process.on("warning",()=>{})),globalThis.AI_SDK_LOG_WARNINGS=!1,Ht(),Ht(),Cs();var{red:gk,yellow:hk,dim:fk}=le,yk=__name(e=>{const{heading:t="ERROR: ",error:n,displayError:r=!0,exit:s=!0,skipTelemetry:o=!1}=e;if(n){if(o||trackError({error:sanitizeErrorForTelemetry({error:n,label:"cli_error"}),context:{component:ys.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${Ve.error} ${gk(t)}`),console.log(`${Ve.error} ${gk("ERROR →")} ${n.name}`),console.log(`${Ve.info} ${gk("REASON →")} ${n.message}`),console.log(`${Ve.info} ${gk("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${Ve.info} ${fk(`Request ID: ${e}`)}`),console.log(`${fk(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${Ve.warning} ${hk(t)}\n`);if(!s)return!1;process.exit(0)}},"handleError");function handleUnhandledErrors(){process.on("unhandledRejection",e=>{const t=e instanceof Error?e:new Error(String(e));trackError({error:sanitizeErrorForTelemetry({error:t,label:"unhandled_rejection"}),context:{component:ys.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),yk({heading:Qe`CRITICAL: Unhandled Promise Rejection!
280
280
  This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:t,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})}),process.on("uncaughtException",e=>{trackError({error:sanitizeErrorForTelemetry({error:e,label:"uncaught_exception"}),context:{component:ys.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),yk({heading:Qe`CRITICAL: Uncaught Exception!
281
- This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:e,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})})}Cs(),__name(handleUnhandledErrors,"handleUnhandledErrors"),Ht(),Ht(),Ls(),Wy(),Xy(),Kt(),Zy(),xr(),Rr(),gn(),aw(),uw(),fw(),Qv(),vv(),PE(),Ds(),Mv();var wk=null,Sk=!1,bk=new Set([Gy.EDIT_FILE,Gy.WRITE_FILE,Gy.SHELL_COMMAND]);async function readStdin(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("Timeout reading from stdin"))},3e4);process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n.trim())}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}async function isAuthenticated(){return null!==await getAuthKey()}function setupSignalHandlers(){if(Sk)return;Sk=!0;const e=__name(e=>{wk?.abort(),process.stderr.write(`\n${e}\n`),process.exit(130)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated.")),process.stdout.on("error",e=>{"EPIPE"===e.code&&process.exit(0),process.stderr.write(`Error writing to stdout: ${e.message}\n`),process.exit(1)})}async function printMode(e={}){setupSignalHandlers(),wk=new AbortController;let t=e.query||"";if(!t){process.stdin.isTTY&&(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1));try{t=await readStdin()}catch(e){const t=e instanceof Error?e.message:"Unknown error";process.stderr.write(`Error reading from stdin: ${t}\n`),process.exit(1)}}t.trim()||(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1)),await isAuthenticated()||(process.stderr.write('Error: Not authenticated. Please run "cmd login" first.\n'),process.exit(3));try{e.model&&setModelOverride(e.model),e.benchmarkOutput&&setBenchmarkOutput(e.benchmarkOutput);const n=await processQuery({query:t,signal:wk.signal,dangerouslySkipPermissions:e.dangerouslySkipPermissions,maxTurns:e.maxTurns??Ek,verbose:e.verbose??!1});process.stdout.write(n),n.endsWith("\n")||process.stdout.write("\n"),process.exit(0)}catch(e){e instanceof Error&&"AbortError"===e.name&&(process.stderr.write("\nCancelled.\n"),process.exit(130)),e instanceof xs&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof Ps&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof Rs&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof Ts&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof $s&&(process.stderr.write("Error: The API server encountered an error. Please try again later.\n"),process.exit(7));const t=e instanceof Error?e.message:"Unknown error";/permission denied|access denied|not permitted|unauthorized/i.test(t)&&(process.stderr.write(`Error: ${t}\n`),process.exit(4)),process.stderr.write(`Error: ${t}\n`),process.exit(1)}}__name(readStdin,"readStdin"),__name(isAuthenticated,"isAuthenticated"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode");var Ek=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced(),{token:r,oauthProvider:s}=await getOAuthCredentials({provider:t});validateOAuthToken({token:r,provider:t});const o=getEnvironmentContext(),i=await getMemoryContent([]),a=await getTasteContent(),l=generateSkillsXML(await loadAllSkillSummaries())||null,u=crypto.randomUUID(),d=await isTasteLearningEnabled(),m={[Ct.PROJECT_SLUG]:hv.getCurrentProjectDirName(),[Ct.TASTE_LEARNING]:d.toString(),[Ct.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(m[Ct.OAUTH_TOKEN]=`Bearer ${r}`,s&&(m[Ct.OAUTH_PROVIDER]=s)),{tools:e,config:o,memory:i,taste:a,skills:l,headers:m,sessionId:u}}async function callApi(e,t,n,r){const s={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:getConfiguredModel()},o={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:s,threadId:t.sessionId};return consumeSSEStream(await e.post({body:o,stream:!0,endpoint:kt.ALPHA.GENERATE,headers:t.headers,signal:r}))}async function executeToolCall(e,t,n){if(bk.has(e.toolName)&&!n)return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:`Error: Tool "${e.toolName}" requires permissions. Use --yolo (or --dangerously-skip-permissions) to enable file writes and shell commands in print mode.`}};try{const n=await executeTool(e.toolName,e.input,{abortSignal:t});return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:n}}}catch(t){if(t instanceof xs||t instanceof Ps||t instanceof Rs||t instanceof Ts||t instanceof $s)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:`Error: ${n}`}}}}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall");var vk=80;function truncate(e){return e.length<=vk?e:e.slice(0,vk)+"..."}function formatToolLabel(e){const t=e.input,n=__name(e=>truncate(String(t[e]??"")),"param");switch(e.toolName){case"shell_command":return`Shell: ${n("command")}`;case"read_file":return`Read: ${n("absolutePath")}`;case"edit_file":return`Edit: ${n("filePath")}`;case"write_file":return`Write: ${n("filePath")}`;case"grep":return`Search: ${n("pattern")}`;case"glob":return`Glob: ${n("pattern")}`;case"read_directory":return`List: ${n("path")}`;case"read_multiple_files":return`Read: ${truncate(String(t.include??""))}`;case"think":return"Thinking";case"explore":return"Exploring";case"todo_write":return"Updating todos";case"ask_user_question":return`Question: ${n("question")}`;case"kill_shell":return`Kill: ${n("processId")}`;case"web_search":return`Search: ${n("query")}`;case"web_fetch":return`Fetch: ${n("url")}`;case"get_diagnostics":return"Diagnostics";default:return e.toolName}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1,maxTurns:s,verbose:o}=e,i=getApiBaseUrl(),a=new xy({baseUrl:i}),l=[{role:"user",content:t}],u=await setupConversationContext(),d=createBenchmarkCollector();let m=0,g="";const h={stream:process.stderr,color:"cyan"},f=o?Te(h):null;try{for(;m<s;){if(m++,n.aborted)throw new Error("Cancelled");f?.start();const e=d?Date.now():0,t=await callApi(a,u,l,n),s=d?Date.now()-e:0;f?.stop();const i=t.usage,y=d?{turnNumber:m,apiDurationMs:s,toolCalls:[],toolDurationMs:0,inputTokens:i?.input_tokens??0,outputTokens:i?.output_tokens??0,cacheReadTokens:i?.cache_read_input_tokens??0,cacheCreationTokens:i?.cache_creation_input_tokens??0}:null,w=t.content.filter(e=>"text"===e.type),S=t.content.filter(e=>"tool-call"===e.type),E=w.map(e=>e.text).join("");if(E&&(g+=E),0===S.length){d&&y&&d.turnDetails.push(y);break}const v=[],C=d?Date.now():0;for(const e of S){if(n.aborted)throw new Error("Cancelled");let t=null;if(o){const n=formatToolLabel(e);t=Te({...h,text:n}).start()}const s=await executeToolCall(e,n,r);if(t){const e="error-text"===s.output.type?ke.cross:ke.tick;t.stopAndPersist({symbol:e})}const i="string"==typeof s.output?s.output:"value"in s.output?s.output.value:"";if(d&&"string"==typeof i){const{cleanContent:e,metrics:t}=extractAgentMetrics(i);t&&(d.agents.push(t),s.output={type:"text",value:e})}y&&y.toolCalls.push({name:e.toolName,isError:"error-text"===s.output.type}),v.push(s)}d&&y&&(y.toolDurationMs=Date.now()-C,d.turnDetails.push(y));const k=t.content.filter(e=>"tool-result"!==e.type);l.push({role:"assistant",content:k}),l.push({role:"tool",content:v})}m>=s&&(d&&(d.maxTurnsReached=!0),process.stderr.write(`Warning: Reached maximum conversation turns (${s}). The response may be incomplete. Use --max-turns to increase the limit.\n`))}finally{d&&writeBenchmarkMetrics(d)}return g}function getShellPathAndName(){const e=process.env.SHELL||"/bin/bash",t=e.split("/").pop()?.toLowerCase()||"bash";return{path:e,name:t}}function getShellType(e){return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":"unknown"}function detectUserShell(){const{path:e,name:t}=getShellPathAndName();return"win32"===process.platform?{type:"unknown",path:e}:{type:getShellType(t),path:e}}__name(truncate,"truncate"),__name(formatToolLabel,"formatToolLabel"),__name(processQuery,"processQuery"),Ht(),Ht(),Ht(),Ht(),hs(),bS(),Ht(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var Ck=["no job control","cannot set terminal process group"],kk=null;function getShellInfo(){return kk||(kk=detectUserShell()),kk}__name(getShellInfo,"getShellInfo");var Tk=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:s=process.env}=t;return new Promise(t=>{let o=!1;const i=__name(e=>{o||(o=!0,t(e))},"doResolve"),a=getShellInfo(),l="bash"===a.type||"zsh"===a.type,u=l?a.path:"/bin/bash",d=M(u,l?["-i","-c",e]:["-c",e],{cwd:r,env:{...s},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let m="",g="",h=null;n>0&&(h=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),i({stdout:m,stderr:g+(g?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(m.length+n.length>us){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void i({stdout:m,stderr:fS,exitCode:1,command:e})}m+=n}catch(e){g+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,d.kill("SIGTERM")}}),d.stderr?.on("data",e=>{try{const t=e.toString();if(g.length+t.length>ds)return void(g+="\n[Error output truncated: too large]");g+=t}catch(e){g+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{h&&clearTimeout(h);const n=l?g.split("\n").filter(e=>!Ck.some(t=>e.includes(t))).join("\n"):g;i({stdout:m.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{h&&clearTimeout(h),i({stdout:m,stderr:g+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),_k=__name(e=>{let t="";return e.stdout&&(t+=e.stdout),e.stderr&&(t&&(t+="\n"),t+=e.stderr),0===e.exitCode||e.stderr||(t&&(t+="\n"),t+=`[Process exited with code ${e.exitCode}]`),t||"(No output)"},"formatBashOutput");dv();var xk=__name(()=>{const[e,t]=K({isExecuting:!1,currentCommand:null});return{executeBash:Z(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Tk(e,{timeout:3e4,cwd:process.cwd()}),s=_k(t);n(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--){const r=n[t];if("bash"===r.role&&"command"in r&&r.command===e&&!r.output){n[t]=ZE(r,s);break}}return n}),r()}catch(t){const s=t instanceof Error?t.message:"Unknown error occurred";n(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--){const r=n[t];if("bash"===r.role&&"command"in r&&r.command===e&&!r.output){n[t]=ZE(r,`Error: ${s}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");function useUiOverlays(){const[e,t]=K(!1),[n,r]=K(!1),[s,o]=K(!1),[i,a]=K(!1),[l,u]=K(!1),[d,m]=K(!1),[g,h]=K(!1),[f,y]=K(!1),[w,S]=K(!1),[E,v]=K(!1),[C,k]=K(!1),[T,_]=K(!1),[x,P]=K(!1),[A,I]=K(!1),[N,R]=K(!1),[$,M]=K(!1),[L,D]=K(!1),[O,F]=K(0),[q,j]=K("off");return{showFileList:e,setShowFileList:t,showAgentsConfig:n,setShowAgentsConfig:r,showTasteConfig:s,setShowTasteConfig:o,showSkillsConfig:i,setShowSkillsConfig:a,showProviderSelector:l,setShowProviderSelector:u,showModelSelector:d,setShowModelSelector:m,showMemorySelector:g,setShowMemorySelector:h,showMcpManager:f,setShowMcpManager:y,showLearningFeed:w,setShowLearningFeed:S,showSessionSelector:E,setShowSessionSelector:v,showAddDirModal:C,setShowAddDirModal:k,showRewindSelector:T,setShowRewindSelector:_,showLoginOverlay:x,setShowLoginOverlay:P,showCompactModeSelector:A,setShowCompactModeSelector:I,showContextView:N,setShowContextView:R,showStatusView:$,setShowStatusView:M,showUsageOverlay:L,setShowUsageOverlay:D,staticKey:O,setStaticKey:F,transcriptMode:q,setTranscriptMode:j,expandedToolOutput:"off"!==q}}function useFeed(){const[e,t]=K([]),[n,r]=K([]),[s,o]=K([]),[i,a]=K(!1),l=Y([]);return J(()=>{l.current=s},[s]),{feed:e,setFeed:t,liveEntries:n,setLiveEntries:r,queuedMessages:s,setQueuedMessages:o,isCmdCodeBusy:i,setIsCmdCodeBusy:a,queuedMessagesRef:l}}function useSession(){const[e,t]=K(crypto.randomUUID()),[n,r]=K(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:Y(null)}}function useStatus(e){const[t,n]=K("Ready..."),r=Y(!1),[s,o]=K(""),i=Y(null),[a,l]=K(null),u=Y(a),[d,m]=K(null),[g,h]=K(!1),[f,y]=K(""),[w,S]=K(null),[E,v]=K(0),[C,k]=K(null),[T,_]=K(!1),[x,P]=K(e??null);J(()=>{u.current=a},[a]),J(()=>{if(x){const e=setTimeout(()=>{P(null)},3e4);return()=>clearTimeout(e)}},[x]);const A=__name(e=>{i.current&&clearTimeout(i.current),o(e),i.current=setTimeout(()=>{o(""),i.current=null},5e3)},"showHintMessage");return{status:t,setStatus:n,pinnedStatusRef:r,hintMessage:s,setHintMessage:o,hintTimerRef:i,shareInfo:a,setShareInfo:l,shareInfoRef:u,billingLink:d,setBillingLink:m,showShareNotification:g,setShowShareNotification:h,unshareNotificationMessage:f,setUnshareNotificationMessage:y,retryAttempt:w,setRetryAttempt:S,interactionTokens:E,setInteractionTokens:v,contextUsage:C,setContextUsage:k,tasteLearningEnabled:T,setTasteLearningEnabled:_,updateStatus:x,setUpdateStatus:P,showHintMessage:A}}function useAuth(){const[e,t]=K(null),[n,r]=K(getConfiguredModel()),[s,o]=K(!1),[i,a]=K(null),[l,u]=K(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,isOAuthMode:s,setIsOAuthMode:o,authComponentInfo:i,setAuthComponentInfo:a,showProviderNotification:l,setShowProviderNotification:u,providerNotificationTimer:Y(null),modelNotificationTimer:Y(null)}}Ht(),__name(useUiOverlays,"useUiOverlays"),Ht(),__name(useFeed,"useFeed"),Ht(),__name(useSession,"useSession"),Ht(),__name(useStatus,"useStatus"),Ht(),xr(),__name(useAuth,"useAuth"),Ht(),Ht(),Ht(),Kt();var Pk=class extends De{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,n){super(),this.projectRoot=e,this.configPath=n||t.join(e,".commandcode","settings.local.json"),this.config=this.getDefaultConfig(),this.loadConfig()}getDefaultConfig(){return{enabled:!0,defaultScope:"session",autoApprove:{create:!1,edit:!1,delete:!1,execute:!1,shellCommands:!1},trustedPaths:[],trustedCommands:[],sessionPermissions:new Map,projectPermissions:new Map,sessionShellPermissions:new Map,projectShellPermissions:new Map}}async loadConfig(){try{const e=await O.readFile(this.configPath,"utf-8"),t=JSON.parse(e);t.permissions&&("acceptEdits"===t.permissions.defaultMode&&(this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0),t.permissions.autoApprove&&(void 0!==t.permissions.autoApprove.create&&(this.config.autoApprove.create=t.permissions.autoApprove.create),void 0!==t.permissions.autoApprove.update&&(this.config.autoApprove.edit=t.permissions.autoApprove.update),void 0!==t.permissions.autoApprove.delete&&(this.config.autoApprove.delete=t.permissions.autoApprove.delete)),t.permissions.allow&&t.permissions.allow.forEach(e=>{if(e.startsWith("Bash(")&&e.endsWith(")")){const t=e.slice(5,-1);this.config.trustedCommands.push(t)}}))}catch(e){}}async requestPermission(e){if(!this.config.enabled)return{allowed:!0};const t=e.action;return this.config.autoApprove[e.action]||this.isTrustedPath(e.filePath)?{allowed:!0}:this.config.sessionPermissions.has(t)?{allowed:this.config.sessionPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("permission-request",e,n=>{this.handleUserChoice(e,n).then(t)})})}async handleUserChoice(e,t){const n=e.action,r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionPermissions.set(n,!0);break;case"project":await this.createCommandCodeSettings(),this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getFileKey(e){const n=t.relative(this.projectRoot,e.filePath);return`${e.action}:${n}`}isTrustedPath(e){const n=t.relative(this.projectRoot,e);return this.config.trustedPaths.some(t=>n.startsWith(t)||e.startsWith(t))}async requestShellPermission(e){if(!this.config.enabled)return{allowed:!0};const t=this.getCommandKey(e);return this.config.autoApprove.shellCommands||this.isTrustedCommand(e.command)?{allowed:!0}:this.config.projectShellPermissions.has(t)?{allowed:this.config.projectShellPermissions.get(t)||!1,scope:"project"}:this.config.sessionShellPermissions.has(t)?{allowed:this.config.sessionShellPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("shell-permission-request",e,n=>{this.handleShellUserChoice(e,n).then(t)})})}async handleShellUserChoice(e,t){const n=this.getCommandKey(e),r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionShellPermissions.set(n,!0);break;case"project":await this.addCommandToSettings(e.command),this.config.projectShellPermissions.set(n,!0)}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getCommandKey(e){return`${e.command.split(" ")[0]}:${e.args?Array.isArray(e.args)?e.args.join(" "):e.args:""}`.trim()}isTrustedCommand(e){return!!["ls","ls -la","ls -l","ls -R","pwd","grep","tree","find","stat","file","dirname","basename","grep","git status","git log","git diff","git branch"].some(t=>e===t||!!e.startsWith(t+" "))||this.config.trustedCommands.some(t=>{if(t===e)return!0;if(t.endsWith(":*")){const n=t.slice(0,-2);return e===n||e.startsWith(n+" ")}return e.startsWith(t)})}clearSessionPermissions(){this.config.sessionPermissions.clear(),this.config.sessionShellPermissions.clear()}clearProjectPermissions(){this.config.projectPermissions.clear(),this.config.projectShellPermissions.clear()}setAutoApprove(e,t){this.config.autoApprove[e]=t}addTrustedPath(e){this.config.trustedPaths.includes(e)||this.config.trustedPaths.push(e)}removeTrustedPath(e){const t=this.config.trustedPaths.indexOf(e);t>-1&&this.config.trustedPaths.splice(t,1)}addTrustedCommand(e){this.config.trustedCommands.includes(e)||this.config.trustedCommands.push(e)}removeTrustedCommand(e){const t=this.config.trustedCommands.indexOf(e);t>-1&&this.config.trustedCommands.splice(t,1)}setEnabled(e){this.config.enabled=e}getConfig(){return{...this.config}}async createCommandCodeSettings(){const e=t.join(this.projectRoot,".commandcode"),n=t.join(e,"settings.local.json");try{await O.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await O.readFile(n,"utf-8"),r=JSON.parse(e);r.permissions&&r.permissions.allow&&(t.permissions.allow=[...new Set([...r.permissions.allow,...t.permissions.allow])]),r.permissions&&r.permissions.deny&&(t.permissions.deny=r.permissions.deny)}catch(e){}await O.writeFile(n,JSON.stringify(t,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const n=t.join(this.projectRoot,".commandcode"),r=t.join(n,"settings.local.json"),s=`Bash(${e.split(" ")[0]}:*)`;try{let e;await O.mkdir(n,{recursive:!0});try{const t=await O.readFile(r,"utf-8");e=JSON.parse(t)}catch(t){e={permissions:{allow:[],deny:[],defaultMode:"ask"}}}e.permissions||(e.permissions={allow:[],deny:[],defaultMode:"ask"}),e.permissions.allow||(e.permissions.allow=[]),e.permissions.allow.includes(s)||e.permissions.allow.push(s),await O.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},Ak=__name((e={})=>{const[t,n]=K(null),[r,s]=K(null),[o,i]=K(!1);return J(()=>{const t=e.projectRoot||process.cwd(),r=new Pk(t);return r.on("permission-request",(t,n)=>{s(t),i(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{s(t),i(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:Z(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:Z(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:Z(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),s(null),i(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),s(null),i(!1)}},[t]),clearSessionPermissions:Z(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:Z(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:Z((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:Z(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:o,service:t}},"usePermissions");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r="auto-accept"===("boolean"==typeof t?t?"auto-accept":"standard":t),s=["create","edit","delete","execute","shellCommands"];for(const e of s)n.setAutoApprove(e,r)}function usePermissionMode({initialPermissionMode:e,dangerouslySkipPermissions:t=!1,setPendingPermission:n,setStatus:r,contextEngineRef:s}){const[o,i]=K(()=>e||(t?"auto-accept":"standard")),a=Y(o);J(()=>{a.current=o},[o]);const{requestShellPermission:l,service:u,respondToPrompt:d,clearSessionPermissions:m,setEnabled:g}=Ak({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{n({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),s.current&&r("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{n({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),s.current&&r("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?r("Permission granted"):r("Permission denied")},"onPermissionResponse")});return J(()=>{u&&applyAutoAcceptMode({enabled:o,service:u})},[o,u]),{permissionMode:o,setPermissionMode:i,permissionModeRef:a,permissionsService:u,respondToPrompt:d,clearSessionPermissions:m}}function usePendingOps(){const[e,t]=K(null),[n,r]=K(null);return{pendingPermission:e,setPendingPermission:t,pendingQuestion:n,setPendingQuestion:r}}function useOnboarding(){const[e,t]=K(!1),[n,r]=K(!1),[s,o]=K(!0),[i,a]=K(!1),[l,u]=K(!1),[d,m]=K(null),[g,h]=K(!1);return{showTrustPrompt:e,setShowTrustPrompt:t,projectTrusted:n,setProjectTrusted:r,checkingProject:s,setCheckingProject:o,showTasteOnboarding:i,setShowTasteOnboarding:a,onboardingComplete:l,setOnboardingComplete:u,tasteOnboardingEntryId:d,setTasteOnboardingEntryId:m,autoLearnTaste:g,setAutoLearnTaste:h,tasteOnboardingCheckedRef:Y(!1)}}function useExit(){const[e,t]=K(!1),[n,r]=K(null),s=Y(null),o=Y(0),i=Y(null),a=Z(()=>{s.current=null,r(null),i.current&&(clearTimeout(i.current),i.current=null)},[]);return{shouldExit:e,setShouldExit:t,pendingExitKey:n,setPendingExitKey:r,pendingExitKeyRef:s,lastExitKeyTimeRef:o,exitConfirmationTimeoutRef:i,resetPendingExitKey:a}}function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:t,description:`Terminate process on ${t}`}}function buildShellPermissionRequest(e,t){const n=e.args,r=Array.isArray(n)?n.join(" "):"string"==typeof n?n:"";return{command:"string"==typeof e.command?e.command:"",args:"string"==typeof n?n:Array.isArray(n)?n.join(" "):void 0,workingDirectory:"string"==typeof e.directory?e.directory:void 0,description:t??`Execute shell command: ${String(e.command??"")} ${r}`}}function getFileAction(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function buildFilePermissionRequest(e,t){const n="edit_file"===e?t.oldValue:void 0,r="edit_file"===e?t.newValue:void 0;return{action:getFileAction(e),filePath:String(t.filePath??t.file_path??t.path??t.absolutePath??"unknown"),description:"string"==typeof t.description?t.description:`${e} operation`,oldContent:"string"==typeof n?n:void 0,newContent:"string"==typeof r?r:void 0}}function useContextEngine({sessionId:e,sessionLoaded:t,showSessionSelector:n,projectTrusted:r,setFeed:s,setLiveEntries:o,setQueuedMessages:i,queuedMessagesRef:a,setStatus:l,pinnedStatusRef:u,setRetryAttempt:d,setInteractionTokens:m,setContextUsage:g,setCurrentProvider:h,shareInfoRef:f,permissionsService:y,permissionModeRef:w,setPendingQuestion:S,contextEngineRef:E}){const v=Z(t=>({onFeedUpdate:__name(e=>{const t=e.metadata?.status;"running"!==t?(o(t=>0===t.length?t:t.filter(t=>t.id!==e.id)),s(t=>[...t,e])):o(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]})},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...a.current];return a.current=[],i([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{m(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{g(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{d(e)},"onRetryUpdate"),onProviderChange:__name(e=>{h(e)},"onProviderChange"),onStatusUpdate:__name(e=>{u.current=!0,l(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{const r=t??{};if(!y)return!0;if("shell_command"===e){const e=buildShellPermissionRequest(r,n);return(await y.requestShellPermission(e)).allowed}if("kill_shell"===e){const e=createKillShellPermissionRequest(r);return(await y.requestShellPermission(e)).allowed}const s=buildFilePermissionRequest(e,r);return(await y.requestPermission(s)).allowed},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{S({params:e,resolve:t,reject:n}),l("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const n=f.current;return n?{sessionId:t??e,secret:n.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>w.current,"getPermissionMode")}),[y,e]);return J(()=>{E.current||!r||n||t||(E.current=new gC(v(),e))},[e,n,t,r,v,E]),{createContextEngineCallbacks:v}}Ht(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),__name(usePermissionMode,"usePermissionMode"),Ht(),__name(usePendingOps,"usePendingOps"),Ht(),__name(useOnboarding,"useOnboarding"),Ht(),__name(useExit,"useExit"),Ht(),SC(),__name(createKillShellPermissionRequest,"createKillShellPermissionRequest"),__name(buildShellPermissionRequest,"buildShellPermissionRequest"),__name(getFileAction,"getFileAction"),__name(buildFilePermissionRequest,"buildFilePermissionRequest"),__name(useContextEngine,"useContextEngine"),Ht(),Ht(),Ht(),In();var Ik=5242880,Nk=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(y.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await D.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean).slice(-100);let t=0;this.buffer=e.map(e=>{try{return JSON.parse(e).p}catch{return t++,""}}).filter(Boolean),t>0&&dlog(`[PromptHistory] Skipped ${t} corrupted entries`)}catch(e){e instanceof Error&&"code"in e&&"ENOENT"===e.code||dlog(`[PromptHistory] Failed to load history: ${e instanceof Error?e.message:String(e)}`),this.buffer=[]}this.initialized=!0}}add(e){if(!e||0===e.trim().length)return;const t=e.length>5e4?e.slice(0,5e4)+"...":e;this.buffer[this.buffer.length-1]!==t&&(this.buffer.push(t),this.buffer.length>500&&(this.buffer=this.buffer.slice(-500)),this.writeQueue.push({p:t,t:Date.now()}),this.scheduleFlush())}getAt(e){if(e<0||e>=this.buffer.length)return;const t=this.buffer.length-1-e;return this.buffer[t]}count(){return this.buffer.length}getAll(){return[...this.buffer]}isInitialized(){return this.initialized}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,await this.flush()},100))}async flush(){if(0===this.writeQueue.length)return;if(this.isFlushing)return void this.scheduleFlush();if(this.writeFailures>=3)return void(this.writeQueue=[]);this.isFlushing=!0;const t=this.writeQueue;this.writeQueue=[];try{const n=e.dirname(this.filePath);await D.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await D.appendFile(this.filePath,r),this.writeFailures=0,await this.rotateIfNeeded()}catch(e){this.writeFailures++;const n=e instanceof Error?e.message:String(e);this.writeFailures<3?(this.writeQueue.unshift(...t),dlog(`[PromptHistory] Write failed, retrying (${this.writeFailures}/3): ${n}`)):dlog(`[PromptHistory] Write disabled after 3 failures: ${n}`)}finally{this.isFlushing=!1}}async rotateIfNeeded(){try{const e=await D.stat(this.filePath);if(e.size<=Ik)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await D.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=Math.floor(2621440),r=[];let s=0;for(let e=t.length-1;e>=0;e--){const o=Buffer.byteLength(t[e],"utf-8")+1;if(s+o>n)break;s+=o,r.unshift(t[e])}await D.writeFile(this.filePath,r.join("\n")+"\n"),dlog(`[PromptHistory] Rotated: kept ${r.length} of ${t.length} entries (${s} bytes)`)}catch(e){dlog(`[PromptHistory] Rotation failed (non-critical): ${e instanceof Error?e.message:String(e)}`)}}async cleanup(){return this.cleanupPromise||(this.cleanupPromise=this.performCleanup().finally(()=>{this.cleanupPromise=null})),this.cleanupPromise}async performCleanup(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);const e=Date.now();for(;this.isFlushing;){if(Date.now()-e>=5e3){dlog("[PromptHistory] Cleanup timed out waiting for flush after 5000ms");break}await new Promise(e=>setTimeout(e,10))}await this.flush()}};function createHistoryManager(){return new Nk}__name(createHistoryManager,"createHistoryManager"),hE(),vv(),bC(),Vv(),Ht(),Kt(),lw();var Rk=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await D.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await D.access(r);const e=await D.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await D.writeFile(r,t,"utf-8")}catch{await D.writeFile(r,nw+"\n\n","utf-8")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await D.access(n),!0}catch{return!1}}};xr(),Rr(),Ht(),SC(),dv(),bC(),Ht(),Kt(),Th(),Wy(),Xy();var{setText:$k}=Ke;async function loadShareInfo({contextEngineRef:e,setShareInfo:t}){const n=e.current?.getSessionManager();if(n){const e=await n.loadShareInfo();e&&t({url:e.url,secret:e.secret})}}async function handleShareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setShowShareNotification:s,contextEngineRef:o}){if(e){if(t)return await $k(t.url),r(""),s(!0),void setTimeout(()=>{s(!1)},3e3);try{r("Creating share link...");const t=o.current?.getMessages()||[],i=hh.sanitizeMessages(t,global.COMMAND_CODE_CWD||process.cwd()),a=new xy({baseUrl:getApiBaseUrl()}),l=await a.post({endpoint:kt.ALPHA.SHARE.CREATE,body:{sessionId:e,messages:i}});n({url:l.url,secret:l.secret});const u=o.current?.getSessionManager();u&&await u.saveShareInfo({url:l.url,secret:l.secret}),await $k(l.url),r(""),s(!0),setTimeout(()=>{s(!1)},5e3)}catch(e){r(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else r("No active session to share")}async function handleUnshareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setUnshareNotificationMessage:s,contextEngineRef:o}){if(e){if(!t)return s("NOT SHARED: Session is not currently shared"),void setTimeout(()=>s(""),5e3);try{r("Removing share link...");const i=new xy({baseUrl:getApiBaseUrl()});await i.delete({endpoint:kt.ALPHA.SHARE.DELETE,body:{sessionId:e,secret:t.secret}});const a=o.current?.getSessionManager();a&&await a.deleteShareInfo(),s("UNSHARED: Sharing has stopped"),r(""),n(null),setTimeout(()=>{s("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;r(t),setTimeout(()=>r(""),5e3)}}else r("No active session to unshare")}async function handleSelectSession({selectedSessionId:e,sessionLoadIdRef:t,contextEngineRef:n,setFeed:r,setLiveEntries:s,setSessionId:o,setShowSessionSelector:i,setSessionLoaded:a,setPermissionMode:l,setStaticKey:u,setShareInfo:d,createContextEngineCallbacks:m}){const g=crypto.randomUUID();t.current=g;try{r([]),s([]),n.current=null,l("standard"),o(e),i(!1),a(!0),n.current=new gC(m(e),e);const{feedEntries:h,corruptedLines:f,totalLines:y}=await n.current.loadSession(e);if(t.current!==g)return;await loadShareInfo({contextEngineRef:n,setShareInfo:d});const w=[];if(0===h.length&&y>0&&w.push(VE(`Session could not be loaded. ${y} lines could not be parsed.`)),0===h.length&&0===y&&w.push(zE("Session loaded but contains no messages.")),h.length>0&&(f>0&&w.push(zE(`Warning: ${f} message(s) could not be loaded.`)),w.push(...h)),t.current!==g)return;r(w),yC(),u(e=>e+1)}catch(e){if(t.current!==g)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";r([VE(`Failed to load session: ${n}. Starting fresh session.`)]),i(!1),a(!1),o(crypto.randomUUID())}}async function handleNewSession({contextEngineRef:e,setFeed:t,setLiveEntries:n,setSessionId:r,setShowSessionSelector:s,setSessionLoaded:o,setPermissionMode:i}){t([]),n([]),e.current=null,i("standard"),r(crypto.randomUUID()),s(!1),o(!1)}async function submitInitialPrompt({initialPrompt:e,onCommand:t,submitAsUserMessage:n}){const r=e.trim();r.startsWith("/")&&t&&"handled"===(await t(r)).status||await n()}function useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:s,stdout:o,feedState:i,sessionState:a,statusState:l,authState:u,onboarding:d,uiOverlays:m,permissionState:g,contextEngineRef:h,isSubmittingRef:f,initialPromptSubmittedRef:y,historyManagerRef:w,executeBash:S,createContextEngineCallbacks:E,setInput:v,onCommand:C}){const k=Z(async()=>{try{const e=await isTasteLearningEnabled();l.setTasteLearningEnabled(e),e&&await Rk.initializeProject()}catch{}},[l.setTasteLearningEnabled]),T=Z(async()=>{const e=await getConfiguredProvider();u.setCurrentProvider(e);const t=await isOAuthEnforced();u.setIsOAuthMode(t)},[u.setCurrentProvider,u.setIsOAuthMode]),_=Z(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(()=>{})},[]),x=Z(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:a.sessionLoadIdRef,contextEngineRef:h,setFeed:i.setFeed,setLiveEntries:i.setLiveEntries,setSessionId:a.setSessionId,setShowSessionSelector:m.setShowSessionSelector,setSessionLoaded:a.setSessionLoaded,setPermissionMode:g.setPermissionMode,setStaticKey:m.setStaticKey,setShareInfo:l.setShareInfo,createContextEngineCallbacks:E})},[a,i,m,g,l,h,E]),P=Z(async()=>{if(n){const e=await hv.listSessions();return void(e.length>0&&x(e[0].id))}t?x(t):e&&m.setShowSessionSelector(!0)},[n,t,e,x,m]);J(()=>{(async()=>{await hv.isProjectInitialized()?(d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_(),await P()):r?(await hv.initializeProject(),d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_(),await P()):isDirectoryEmpty()?(await hv.initializeProject(),d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_()):(d.setShowTrustPrompt(!0),d.setCheckingProject(!1))})()},[e,n,r]),J(()=>{if(!d.projectTrusted)return;const e=createHistoryManager();return w.current=e,e.init(),()=>{e.cleanup()}},[d.projectTrusted]),J(()=>{if(!o)return;const e=__name(()=>{m.showLearningFeed||(yC(),m.setStaticKey(e=>e+1))},"handleResize");return o.on("resize",e),()=>{o.off("resize",e)}},[o]),J(()=>{s&&d.projectTrusted&&!d.checkingProject&&h.current&&!m.showSessionSelector&&!y.current&&(y.current=!0,submitInitialPrompt({initialPrompt:s,onCommand:C,submitAsUserMessage:__name(()=>handleSubmit({role:"user",input:s,feed:i.feed,setFeed:i.setFeed,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,contextEngineRef:h,isSubmittingRef:f,setInput:v,setStaticKey:m.setStaticKey,executeBash:S}),"submitAsUserMessage")}))},[s,d.projectTrusted,d.checkingProject,m.showSessionSelector,C]);const A=Y(null);A.current={feed:i.feed,setFeed:i.setFeed,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,contextEngineRef:h,isSubmittingRef:f,setInput:v,setStaticKey:m.setStaticKey,executeBash:S,role:"",input:""};const I=Z(async({role:e,input:t,images:n,ideContext:r,displayMessage:s,isAutomated:o})=>handleSubmit({...A.current,role:e,input:t,images:n,ideContext:r,displayMessage:s,isAutomated:o}),[]);return{loadTasteStatus:k,loadCurrentProvider:T,initializeMcpInBackground:_,onSubmit:I}}__name(loadShareInfo,"loadShareInfo"),__name(handleShareCommand,"handleShareCommand"),__name(handleUnshareCommand,"handleUnshareCommand"),__name(handleSelectSession,"handleSelectSession"),__name(handleNewSession,"handleNewSession"),ak(),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Ht(),xn(),dv(),_n(),Ht(),Kt(),In(),Ht();var Mk={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return Mk[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Le(t);return e.join(w.homedir(),".commandcode","projects",n)}function getGlobalProjectSettingsPath(t=process.cwd()){return e.join(getGlobalProjectSettingsDir(t),"settings.json")}async function loadGlobalProjectSettings(e=process.cwd()){try{const t=getGlobalProjectSettingsPath(e),n=await D.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function saveGlobalProjectSettings(t,n=process.cwd()){try{const r=getGlobalProjectSettingsPath(n),s=e.dirname(r);await D.mkdir(s,{recursive:!0}),await D.writeFile(r,JSON.stringify(t,null,2))}catch(e){const t=e instanceof Error?e.message:String(e);dlog("Error saving global project settings:",e),Zv.addEvent({type:"error",message:`Failed to save global project settings: ${t}`})}}async function loadLocalProjectSettings(t=process.cwd()){try{const n=e.join(t,".commandcode","settings.local.json"),r=await D.readFile(n,"utf-8");return JSON.parse(r)}catch{return{}}}async function loadMergedProjectSettings(e=process.cwd()){try{const t=mergeSettings(await loadGlobalProjectSettings(e),await loadLocalProjectSettings(e)),n=t.tasteOnboarding,r=n?.learnedSessions?.["claude-code"]?.length||0;return dlog(`[Config] project settings loaded (taste: ${n?.completed?"complete":n?.skipped?"skipped":"pending"}, learned: ${r} sessions)`),t}catch(e){return dlog("[Settings] error loading",e),{}}}function mergeSettings(e,t){const n={...e};return t.tasteOnboarding&&(n.tasteOnboarding={...e.tasteOnboarding,...t.tasteOnboarding},(e.tasteOnboarding?.learnedSessions||t.tasteOnboarding?.learnedSessions)&&(n.tasteOnboarding.learnedSessions={...e.tasteOnboarding?.learnedSessions,...t.tasteOnboarding?.learnedSessions})),n}__name(getAgentDisplayName,"getAgentDisplayName"),__name(getProjectDirName,"getProjectDirName"),Ht(),In(),tC(),Kt(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),Ht(),In();var Lk=e.join(y.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=A(e,{encoding:"utf8"}),n=Ye.createInterface({input:t,crlfDelay:1/0});for await(const e of n)if(e.trim()){try{const r=JSON.parse(e);if("session_meta"===r.type&&r.payload?.cwd)return n.close(),t.destroy(),{cwd:r.payload.cwd,id:r.payload.id,timestamp:r.payload.timestamp}}catch{}break}return n.close(),t.destroy(),null}catch{return null}}async function findAllSessionFiles(t,n){const r=[];try{await D.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const s=await D.readdir(t);for(const o of s){if(!/^\d{4}$/.test(o))continue;const s=e.join(t,o);if(!(await D.stat(s)).isDirectory())continue;const i=await D.readdir(s);for(const t of i){if(!/^\d{2}$/.test(t))continue;const i=e.join(s,t);if(!(await D.stat(i)).isDirectory())continue;const a=await D.readdir(i);for(const s of a){if(!/^\d{2}$/.test(s))continue;const a=e.join(i,s);if(!(await D.stat(a)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${o}/${t}/${s}`});const l=(await D.readdir(a)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(a,t));r.push(...l)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return r}async function processFilesInBatches(e,t,n=10,r){const s=[];for(let o=0;o<e.length;o+=n){const i=e.slice(o,o+n),a=await Promise.all(i.map(t));for(const e of a)null!==e&&s.push(e);r?.(Math.min(o+n,e.length),e.length)}return s}async function findCodexSessions(t,n,r=0){const s=t||process.cwd(),o=[];dlog(`[Codex] scanning for project: ${s}`);const i=await findAllSessionFiles(Lk,n);if(0===i.length)return dlog("[Codex] no session files found"),n?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${i.length} session files to scan`),n?.({phase:"reading",totalFiles:i.length,processedFiles:0,matchedSessions:0});let a=0;const l=await processFilesInBatches(i,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===s)try{const r=await D.stat(t),s=e.basename(t,".jsonl");return{id:n.id||s,filePath:t,createdAt:new Date(n.timestamp||r.birthtime),lastModified:r.mtime,messageCount:0,agent:"codex",projectDir:n.cwd}}catch{return null}return null},10,(e,t)=>{a=o.length,n?.({phase:"reading",totalFiles:t,processedFiles:e,matchedSessions:a})});o.push(...l);const u=r>0?o.slice(0,r):o;return dlog(`[Codex] matched ${u.length} sessions for project`),n?.({phase:"complete",totalFiles:i.length,processedFiles:i.length,matchedSessions:u.length}),u.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await D.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("event_msg"===n.type&&"user_message"===n.payload?.type&&n.payload?.message){const e=n.payload.message;"string"==typeof e&&e.trim()&&t.push(e.trim())}}catch{continue}t.length>0&&dlog(`[Codex] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Codex] failed to extract prompts: ${e}`,t)}return t}__name(readSessionMeta,"readSessionMeta"),__name(findAllSessionFiles,"findAllSessionFiles"),__name(processFilesInBatches,"processFilesInBatches"),__name(findCodexSessions,"findCodexSessions"),__name(findCodexSessionIds,"findCodexSessionIds"),__name(extractCodexPrompts,"extractCodexPrompts"),Ht(),In();var Dk=e.join(y.homedir(),".cursor","projects");function getCursorProjectDirNames(e){const t=e.replace(/[/\\:]/g,"-"),n=t.replace(/^-+/,"");return[...new Set([n,t])].filter(Boolean)}async function findAgentTranscriptsDir(t){try{await D.access(Dk)}catch{return dlog("[Cursor] projects directory not found"),null}const n=getCursorProjectDirNames(t);dlog(`[Cursor] looking for project dirs: ${n.join(", ")}`);try{const t=await D.readdir(Dk);for(const r of n){if(!t.includes(r))continue;const n=e.join(Dk,r,"agent-transcripts");try{if((await D.stat(n)).isDirectory())return dlog(`[Cursor] found agent-transcripts at: ${n}`),n}catch{}}}catch(e){dlog("[Cursor] error scanning projects",e)}return null}async function findCursorSessions(t,n=0){const r=t||process.cwd(),s=[];dlog(`[Cursor] scanning for project: ${r}`);const o=await findAgentTranscriptsDir(r);if(!o)return dlog("[Cursor] no agent-transcripts found"),[];try{const t=await D.readdir(o);for(const n of t){const t=e.join(o,n);try{if(!(await D.stat(t)).isDirectory())continue;const r=e.join(t,`${n}.jsonl`);try{const e=await D.stat(r);s.push({id:n,filePath:r,createdAt:e.birthtime,lastModified:e.mtime,messageCount:0,agent:"cursor"})}catch{}}catch{}}}catch(e){dlog("[Cursor] error reading agent-transcripts",e)}const i=s.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime()),a=n>0?i.slice(0,n):i;return dlog(`[Cursor] matched ${a.length} sessions for project`),a}async function findCursorSessionIds(e){return(await findCursorSessions(e)).map(e=>e.id)}async function extractCursorPrompts(e){const t=[];try{const n=(await D.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"!==n.role)continue;const r=n.message?.content;if(!Array.isArray(r))continue;for(const e of r)if("text"===e.type&&"string"==typeof e.text){const n=e.text.trim().replace(/^<user_query>\n?/,"").replace(/\n?<\/user_query>$/,"").trim();n&&t.push(n)}}catch{continue}t.length>0&&dlog(`[Cursor] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Cursor] failed to extract prompts: ${e}`,t)}return t}async function loadProjectSettings(){return loadMergedProjectSettings()}async function saveProjectSettings(e){await saveGlobalProjectSettings(e)}function isOnboardingDone(e){return!0===e?.skipped||!0===e?.completed}function buildAgentSessionsList(e){return Object.entries(e).filter(([e,t])=>t&&t.length>0).map(([e,t])=>({agent:e,sessionIds:t,displayName:getAgentDisplayName(e)}))}async function checkOnboardingConditions(){try{const e=(await loadProjectSettings()).tasteOnboarding,t=e?.learnedSessions||{},n=e?.skippedSessions||{},r={};for(const e of new Set([...Object.keys(t),...Object.keys(n)]))r[e]=[...t[e]||[],...n[e]||[]];const s=await findNewSessions(r),o=s["claude-code"]?.length||0,i=o+(s.codex?.length||0)+(s.cursor?.length||0);return i>0?(dlog(`[Onboarding] found ${i} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:i,hasTasteContent:!0,agentSessions:buildAgentSessionsList(s)}):(isOnboardingDone(e)?dlog(`[Onboarding] ${e?.skipped?"user skipped":"already completed"}, no new sessions`):dlog("[Onboarding] no sessions to learn from, skipping"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:isOnboardingDone(e),agentSessions:[]})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[]}}}async function getSessionFilesFromDir(e){try{return(await D.readdir(e)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints")).map(e=>e.replace(".jsonl",""))}catch{return[]}}async function findNewSessions(t){const n={},r=t["claude-code"]||[],s=t.codex||[],o=t.cursor||[];try{const t=e.join(y.homedir(),".claude","projects");await D.access(t);const s=getProjectDirName(process.cwd()),o=(await D.readdir(t)).filter(e=>e===s);for(const s of o){const o=e.join(t,s);if((await D.stat(o)).isDirectory()){const e=await getSessionFilesFromDir(o);e.length>0&&(n["claude-code"]=e.filter(e=>!r.includes(e)))}}dlog(`[Sessions] claude-code: ${n["claude-code"]?.length||0} new, ${r.length} learned`)}catch{dlog("[Sessions] claude projects dir not found")}try{const e=await findCodexSessionIds();e.length>0&&(n.codex=e.filter(e=>!s.includes(e)));dlog(`[Sessions] codex: ${n.codex?.length||0} new, ${s.length} learned`)}catch{dlog("[Sessions] codex sessions not found")}try{const e=await findCursorSessionIds();e.length>0&&(n.cursor=e.filter(e=>!o.includes(e)));dlog(`[Sessions] cursor: ${n.cursor?.length||0} new, ${o.length} learned`)}catch{dlog("[Sessions] cursor sessions not found")}return n}async function markSessionsAsLearned(e,t){const n=await loadProjectSettings();n.tasteOnboarding||(n.tasteOnboarding={}),n.tasteOnboarding.learnedSessions||(n.tasteOnboarding.learnedSessions={});const r=n.tasteOnboarding.learnedSessions[e]||[];if(n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.skippedSessions?.[e]){const r=new Set(t);n.tasteOnboarding.skippedSessions[e]=n.tasteOnboarding.skippedSessions[e].filter(e=>!r.has(e)),0===n.tasteOnboarding.skippedSessions[e].length&&delete n.tasteOnboarding.skippedSessions[e]}n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0;try{const t=e.tasteOnboarding.learnedSessions||{},n=await findNewSessions(t);e.tasteOnboarding.skippedSessions||(e.tasteOnboarding.skippedSessions={});for(const[t,r]of Object.entries(n))if(r.length>0){const n=e.tasteOnboarding.skippedSessions[t]||[];e.tasteOnboarding.skippedSessions[t]=Array.from(new Set([...n,...r]))}}catch{dlog("[Onboarding] failed to record skipped sessions, skip flag still set")}await saveProjectSettings(e)}async function markOnboardingCompleted(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.completed=!0,await saveProjectSettings(e)}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:s}){if(e)if(t)dlog("[Onboarding] skipped - already completed");else if(n)dlog("[Onboarding] skipped - already showing");else if(r.current)dlog("[Onboarding] skipped - already checked this session");else{r.current=!0,dlog("[Onboarding] checking if taste learning should start...");try{const e=await checkOnboardingConditions();e.shouldTrigger?(dlog(`[Onboarding] starting taste learning (${e.reason})`),s(!0)):dlog("[Onboarding] not needed")}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}function useLifecycle({exit:e,feedState:t,exitState:n,statusState:r,authState:s,onboarding:o,uiOverlays:i,skipOnboarding:a}){J(()=>{if(n.shouldExit){r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),s.providerNotificationTimer.current&&clearTimeout(s.providerNotificationTimer.current),s.modelNotificationTimer.current&&clearTimeout(s.modelNotificationTimer.current);try{e()}catch{process.exit(0)}}},[n.shouldExit,e]),J(()=>()=>{r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),s.providerNotificationTimer.current&&clearTimeout(s.providerNotificationTimer.current),s.modelNotificationTimer.current&&clearTimeout(s.modelNotificationTimer.current)},[]),J(()=>{(async()=>{if("anthropic"===s.currentProvider&&s.isOAuthMode)try{await Sn.getValidAccessToken()||r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}catch{r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[s.currentProvider,s.isOAuthMode]),J(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(sv())},7e3);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),J(()=>{a||triggerTasteOnboarding({projectTrusted:o.projectTrusted,onboardingComplete:o.onboardingComplete,isOnboardingMode:o.showTasteOnboarding,tasteOnboardingCheckedRef:o.tasteOnboardingCheckedRef,setIsOnboardingMode:o.setShowTasteOnboarding})},[o.projectTrusted,o.onboardingComplete,o.showTasteOnboarding,a]),J(()=>{if(o.showTasteOnboarding&&!o.tasteOnboardingEntryId){const e=KE();o.setTasteOnboardingEntryId(e.id),t.setFeed(t=>[...t,e])}!o.showTasteOnboarding&&o.tasteOnboardingEntryId&&(t.setFeed(e=>e.filter(e=>e.id!==o.tasteOnboardingEntryId)),o.setTasteOnboardingEntryId(null))},[o.showTasteOnboarding,o.tasteOnboardingEntryId])}__name(getCursorProjectDirNames,"getCursorProjectDirNames"),__name(findAgentTranscriptsDir,"findAgentTranscriptsDir"),__name(findCursorSessions,"findCursorSessions"),__name(findCursorSessionIds,"findCursorSessionIds"),__name(extractCursorPrompts,"extractCursorPrompts"),__name(loadProjectSettings,"loadProjectSettings"),__name(saveProjectSettings,"saveProjectSettings"),__name(isOnboardingDone,"isOnboardingDone"),__name(buildAgentSessionsList,"buildAgentSessionsList"),__name(checkOnboardingConditions,"checkOnboardingConditions"),__name(getSessionFilesFromDir,"getSessionFilesFromDir"),__name(findNewSessions,"findNewSessions"),__name(markSessionsAsLearned,"markSessionsAsLearned"),__name(markOnboardingSkipped,"markOnboardingSkipped"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(triggerTasteOnboarding,"triggerTasteOnboarding"),__name(useLifecycle,"useLifecycle"),Ht(),bC(),vv(),dv(),Ht(),kn(),Rr(),bC(),Kt(),Ht();var Ok="└",Fk=" ",qk=`${Fk}TASTE${Fk}`;function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showProviderSelector:n,showModelSelector:r,showMemorySelector:s,showMcpManager:o,showLearningFeed:i,showRewindSelector:a,showLoginOverlay:l,showUsageOverlay:u,showAddDirModal:d,authComponentInfo:m,setShowLearningFeed:g,setShowModelSelector:h,setStaticKey:f,transcriptMode:y,setTranscriptMode:w,isCmdCodeBusy:S,liveEntries:E,queuedMessagesRef:v,setInput:C,setQueuedMessages:k,setFeed:T,setLiveEntries:_,setIsCmdCodeBusy:x,setRetryAttempt:P,setStatus:A,pendingExitKey:I,setPendingExitKey:N,pendingExitKeyRef:R,lastExitKeyTimeRef:$,exitConfirmationTimeoutRef:M,resetPendingExitKey:L,pendingPermission:D,setPendingPermission:O,pendingQuestion:F,setPendingQuestion:q,setShouldExit:j,contextEngineRef:B,handleToggleAutoAccept:U,handleDoubleEscapeEmpty:z,respondToPrompt:W,createErrorEntry:G}){const H=__name(()=>{if(!B.current)return;B.current.interrupt(!0);const e=E.length>0;if(x(!1),P(null),_([]),A("Interrupted by user"),!e){const e=G("Interrupted by user");T(t=>[...t,e])}if(v.current.length>0){const e=v.current.map(e=>e.displayMessage??e.input).join("\n");C(t=>t?e+"\n"+t:e),k([]),v.current=[]}},"handleInterrupt");se((E,v)=>{if(v.shift&&v.tab||""===E)U();else if(e||t||n||r||s||o||m||i||a||l||u||d)I&&L();else{if(""===E||v.ctrl&&"c"===E){if(S&&B.current)return void H();const e=Date.now(),t=e-$.current;return $.current=e,"ctrl-c"===R.current&&t<2e3?(M.current&&(clearTimeout(M.current),M.current=null),void j(!0)):(C(()=>""),R.current="ctrl-c",N("ctrl-c"),M.current&&clearTimeout(M.current),void(M.current=setTimeout(()=>{R.current=null,N(null),M.current=null},2e3)))}if(v.ctrl&&"t"===E)return yC(),g(!i),void f(e=>e+1);if(getIsExpandToolShortcut(v,E))return yC(),w("off"===y?"limited":"off"),void f(e=>e+1);if(v.ctrl&&"e"===E&&"off"!==y)return yC(),w("limited"===y?"full":"limited"),void f(e=>e+1);if(v.meta&&"p"===E||isAltP(E))h(!0);else if(v.escape){if(F)return F.reject(new Error("Question cancelled by user")),q(null),void A("Question cancelled");if(D)return W({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),D.resolve(!1),O(null),void A("Permission denied");S&&B.current&&H()}}})}function useHandlers({resume:e,feedState:t,onboarding:n,uiOverlays:r,exitState:s,pendingOps:o,permissionState:i,statusState:a,authState:l,contextEngineRef:u,loadTasteStatus:d,loadCurrentProvider:m,setInput:g}){const h=Z(()=>{i.setPermissionMode(e=>{let t="standard";if("standard"===e&&(t="auto-accept"),"auto-accept"===e&&(t="plan"),"auto-accept"===t&&o.pendingPermission){const e={label:"Yes",value:"yes",description:"Allow this action",scope:void 0};i.respondToPrompt(e),o.pendingPermission.resolve(!0),o.setPendingPermission(null)}return"plan"===t&&o.pendingPermission&&(o.pendingPermission.resolve(!1),o.setPendingPermission(null)),t})},[i.setPermissionMode,i.respondToPrompt,o.pendingPermission,o.setPendingPermission]),f=Z(()=>{const e=!t.isCmdCodeBusy&&!o.pendingPermission&&!o.pendingQuestion,n=u.current?.hasCheckpoints()??!1;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,o.pendingPermission,o.pendingQuestion,r.setShowRewindSelector]),y=Z(s=>{if(n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),yC(),s?.skipped){const e=zE("",{isTasteSkip:!0});t.setFeed(t=>[...t,e])}r.setStaticKey(e=>e+1),e&&r.setShowSessionSelector(!0)},[e,n,r,t]),w=Z(async()=>{try{if(await hv.initializeProject(),n.setShowTrustPrompt(!1),e)return console.log("No conversations found to resume."),void s.setShouldExit(!0);n.setProjectTrusted(!0),d(),m()}catch(e){console.error("Failed to initialize project:",e),n.setShowTrustPrompt(!1),s.setShouldExit(!0)}},[e,n,s,d,m]),S=Z(()=>{s.setShouldExit(!0)},[s.setShouldExit]);return useKeyboard({showTasteConfig:r.showTasteConfig,showSkillsConfig:r.showSkillsConfig,showProviderSelector:r.showProviderSelector,showModelSelector:r.showModelSelector,showMemorySelector:r.showMemorySelector,showMcpManager:r.showMcpManager,showLearningFeed:r.showLearningFeed,showRewindSelector:r.showRewindSelector,showLoginOverlay:r.showLoginOverlay,showUsageOverlay:r.showUsageOverlay,showAddDirModal:r.showAddDirModal,authComponentInfo:l.authComponentInfo,setShowLearningFeed:r.setShowLearningFeed,setShowModelSelector:r.setShowModelSelector,setStaticKey:r.setStaticKey,transcriptMode:r.transcriptMode,setTranscriptMode:r.setTranscriptMode,isCmdCodeBusy:t.isCmdCodeBusy,liveEntries:t.liveEntries,queuedMessagesRef:t.queuedMessagesRef,setInput:g,setQueuedMessages:t.setQueuedMessages,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setRetryAttempt:a.setRetryAttempt,setStatus:a.setStatus,pendingExitKey:s.pendingExitKey,setPendingExitKey:s.setPendingExitKey,pendingExitKeyRef:s.pendingExitKeyRef,lastExitKeyTimeRef:s.lastExitKeyTimeRef,exitConfirmationTimeoutRef:s.exitConfirmationTimeoutRef,resetPendingExitKey:s.resetPendingExitKey,pendingPermission:o.pendingPermission,setPendingPermission:o.setPendingPermission,pendingQuestion:o.pendingQuestion,setPendingQuestion:o.setPendingQuestion,setShouldExit:s.setShouldExit,contextEngineRef:u,handleToggleAutoAccept:h,handleDoubleEscapeEmpty:f,respondToPrompt:i.respondToPrompt,createErrorEntry:VE}),{handleToggleAutoAccept:h,handleDoubleEscapeEmpty:f,handleTasteOnboardingComplete:y,handleTrust:w,handleNoTrust:S}}__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Ht(),Ht(),Kt(),dv(),Nr(),Ht(),Ht(),Ht(),Kt(),In(),$r(),Ur(),Ht(),Kt();var jk=t.join(w.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(jk);v.existsSync(e)||v.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!v.existsSync(jk))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=v.readFileSync(jk,"utf-8");return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null,...JSON.parse(e)}}catch{return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}}}function writeUpdatesConfig(e){ensureDir(),v.writeFileSync(jk,JSON.stringify(e,null,2))}function updateUpdatesConfig(e){writeUpdatesConfig({...readUpdatesConfig(),...e})}function shouldCheckForUpdate(){const e=readUpdatesConfig();return!!e.autoUpdate&&Date.now()-e.lastCheckedAt>=e.checkIntervalMs}function recordUpdateCheck(){updateUpdatesConfig({lastCheckedAt:Date.now()})}function setPendingUpdate(e){updateUpdatesConfig({lastCheckedAt:Date.now(),pending:e})}function clearPendingUpdate(){updateUpdatesConfig({pending:null})}function getPendingUpdate(e){const t=readUpdatesConfig();return t.pending?t.pending.currentVersion!==e?(clearPendingUpdate(),null):t.pending:null}__name(function getDefaultConfig(){return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}},"getDefaultConfig"),__name(ensureDir,"ensureDir"),__name(readUpdatesConfig,"readUpdatesConfig"),__name(writeUpdatesConfig,"writeUpdatesConfig"),__name(updateUpdatesConfig,"updateUpdatesConfig"),__name(shouldCheckForUpdate,"shouldCheckForUpdate"),__name(recordUpdateCheck,"recordUpdateCheck"),__name(setPendingUpdate,"setPendingUpdate"),__name(clearPendingUpdate,"clearPendingUpdate"),__name(getPendingUpdate,"getPendingUpdate"),Jv(),$r();var Bk=Xe(R),Uk=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!process.env.COMMANDCODE_SKIP_UPDATES||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=$("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","pipe"],env:{...process.env,NODE_NO_WARNINGS:"1"}});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return Uk.version}function isAlphaVersion(e){return e.includes("alpha")}function filterVersions(e){return{stable:e.filter(e=>!e.includes("alpha")),alpha:e.filter(e=>e.includes("alpha"))}}function getLatestVersion(e){return 0===e.length?null:e.sort(Ze.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&Ze.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&Ze.gt(t,e))return{latestVersion:t,updateAvailable:!0}}return{latestVersion:e,updateAvailable:!1}}async function checkForUpdateAvailable(){const e=fetchVersions();if(!e)return null;const t=getCurrentVersion(),{stable:n,alpha:r}=filterVersions(e),{latestVersion:s,updateAvailable:o}=determineUpdateTarget(t,n,r);return{currentVersion:t,latestVersion:s,updateAvailable:o}}async function executeUpdate(e){try{return await Bk(`npm i -g command-code@${e}`,{env:{...process.env,NODE_NO_WARNINGS:"1"},timeout:6e5}),!0}catch{return!1}}function checkForUpdateAsync(){shouldSkipUpdateSystem()||shouldCheckForUpdate()&&doUpdateCheck().catch(()=>{})}async function doUpdateCheck(){dlog("[Updater] Starting async update check");const e=await checkForUpdateAvailable();return e?e.updateAvailable?(dlog(`[Updater] Update available: ${e.currentVersion} -> ${e.latestVersion}`),void setPendingUpdate({targetVersion:e.latestVersion,currentVersion:e.currentVersion,detectedAt:Date.now()})):(dlog("[Updater] No update available"),void recordUpdateCheck()):(dlog("[Updater] Failed to fetch version info"),void recordUpdateCheck())}async function maybeRunPendingUpdate(){if(shouldSkipUpdateSystem())return;const e=getCurrentVersion(),t=getPendingUpdate(e);if(!t)return;if(!Ze.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=Te(`Updating ${e} → ${t.targetVersion}`).start(),r=await executeUpdate(t.targetVersion);if(clearPendingUpdate(),!r)return n.fail("Update failed"),void console.log("Run `cmd update` to try again.");n.succeed(`Updated to v${t.targetVersion}`),trackLifecycleEvent({eventType:"cli_updated",metadata:{fromVersion:e,toVersion:t.targetVersion}}).catch(()=>{})}async function performAutoUpdate(e){const{silent:t,updateInfo:n,onStart:r}=e||{};if(isLocalDevelopmentBuild())return{success:!1};const s=n||await checkForUpdateAvailable();return s?.updateAvailable?(r?.(s.latestVersion),await executeUpdate(s.latestVersion)?{success:!0,updateInfo:s}:(t||(console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code")),{success:!1,updateInfo:s})):{success:!1}}function getCurrentGitBranch(){try{return $("git rev-parse --abbrev-ref HEAD",{encoding:"utf-8",stdio:["pipe","pipe","ignore"],cwd:process.cwd()}).trim()||null}catch(e){return null}}function getGitHeaderInfo(){return{branch:getCurrentGitBranch(),isLocal:isLocalDevelopmentBuild()}}__name(shouldSkipUpdateSystem,"shouldSkipUpdateSystem"),__name(fetchVersions,"fetchVersions"),__name(getCurrentVersion,"getCurrentVersion"),__name(isAlphaVersion,"isAlphaVersion"),__name(filterVersions,"filterVersions"),__name(getLatestVersion,"getLatestVersion"),__name(determineUpdateTarget,"determineUpdateTarget"),__name(checkForUpdateAvailable,"checkForUpdateAvailable"),__name(executeUpdate,"executeUpdate"),__name(checkForUpdateAsync,"checkForUpdateAsync"),__name(doUpdateCheck,"doUpdateCheck"),__name(maybeRunPendingUpdate,"maybeRunPendingUpdate"),__name(performAutoUpdate,"performAutoUpdate"),__name(getCurrentGitBranch,"getCurrentGitBranch"),__name(getGitHeaderInfo,"getGitHeaderInfo");var zk=new Set(["OPEN","MERGED","CLOSED"]),Wk=null;function getCachedPRInfo(e){if(Wk&&Wk.branch===e){if(!(Date.now()-Wk.timestamp>3e5))return Wk.result;Wk=null}}function setPRCache(e,t){Wk={branch:e,result:t,timestamp:Date.now()}}function execFileAsync({cmd:e,args:t,encoding:n,timeout:r}){return new Promise((s,o)=>{L(e,[...t],{encoding:n,timeout:r},(e,t)=>{e?o(e):s(t.trim())})})}function parsePRResponse(e){try{const t=JSON.parse(e);return t.number&&t.url&&t.state&&zk.has(t.state)?{number:t.number,title:t.title||"",url:t.url,state:t.state}:null}catch{return null}}function getCachedPR(e){return e?getCachedPRInfo(e)??null:null}__name(getCachedPRInfo,"getCachedPRInfo"),__name(setPRCache,"setPRCache"),__name(execFileAsync,"execFileAsync"),__name(parsePRResponse,"parsePRResponse"),__name(getCachedPR,"getCachedPR");var Gk=__name(async()=>{const e=getCurrentGitBranch();if(!e)return null;if("main"===e||"master"===e)return null;const t=getCachedPRInfo(e);if(void 0!==t)return t;try{const t=parsePRResponse(await execFileAsync({cmd:"gh",args:["pr","view","--json","number,title,url,state"],encoding:"utf-8",timeout:3e3}));return setPRCache(e,t),t}catch{return null}},"detectPR");Ht();var Hk='You are an expert code reviewer. Do follow these steps:\n\nGather PR context using the GitHub CLI:\n1. When no PR number is given, list open PRs with `gh pr list` and ask which one to review\n2. Fetch PR metadata via `gh pr view <number>`\n3. Retrieve the changeset with `gh pr diff <number>`\n4. One go gather context: Run gh pr view <number> && echo "---DIFF---" && gh pr diff <number>\n5. Analyze the changes and provide a thorough code review that includes:\n\t- Overview of the PR is doing\n\t- Analysis of the code quality and style\n\t- Give specific suggestions for improvement\n\t- Highlight any potential bugs/issues or risks\n\t- Score PR on a scale of 1-5 based on overall table with quality and readiness for merging\nKeep your review concise, less wordy, but thorough.\nFocus on:\n- Correctness of code\n- Following project conventions\n- Performance issues and implications\n- Test coverage\n- Security considerations\n\nBe less wordy. If you make a table, don\'t go over 60pts.\nFormat your review in sections and bullets.';function buildReviewPrompt({prNumber:e,autoDetected:t=!1}){const n=e.trim();return n?`${Hk}\n\nReview PR number: ${n}${t?"\n(Note: PR number auto-detected from current branch.)":""}`:`${Hk}\n\nReview PR number: `}function lastResponseHasComments(e){const t=e[e.length-1];if(!t||"assistant"!==t.message.role)return!1;const{content:n}=t.message;if("string"==typeof n)return n.includes("## Review Comments")||n.includes("## PR Comments");const r=n.filter(e=>"text"===e.type).map(e=>e.text).join("");return r.includes("## Review Comments")||r.includes("## PR Comments")}function loadCustomCommands(){const e=[],n=t.join(process.cwd(),".commandcode","commands"),r=t.join(w.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,s=""){if(v.existsSync(n))try{const o=v.readdirSync(n,{withFileTypes:!0});for(const i of o){const o=t.join(n,i.name);if(i.isDirectory())loadCommandsFromDirectory(o,r,s?`${s}/${i.name}`:i.name);else if(i.isFile()&&i.name.endsWith(".md")){const n=t.basename(i.name,".md"),a=v.readFileSync(o,"utf-8").trim();e.push({name:n,source:r,content:a,subdirectory:s})}}}catch(e){}}return __name(loadCommandsFromDirectory,"loadCommandsFromDirectory"),loadCommandsFromDirectory(r,"user"),loadCommandsFromDirectory(n,"project"),e}function customCommandsToMenuItems(e){return e.map(e=>{const t=`/${e.name}`;let n;return n=e.subdirectory?"project"===e.source?`(project: ${e.subdirectory})`:`(user: ${e.subdirectory})`:"project"===e.source?"(project)":"(user)",{command:t,description:`${e.content.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim()} ${n}`}})}function getCustomCommandContent(e){const t=loadCustomCommands(),n=e.startsWith("/")?e.substring(1):e,r=t.find(e=>e.name===n);return r?r.content:null}__name(buildReviewPrompt,"buildReviewPrompt"),Ht(),__name(lastResponseHasComments,"lastResponseHasComments"),Ht(),Kt(),Ht(),Kt(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),Nr(),Ht();var Qk=["Code","Code - Insiders","VSCodium","Cursor"],Vk="Code",Kk={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},Yk=__name(e=>g(e).href,"formatPathForTerminal"),Jk=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),Xk=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),Zk=__name(({home:t,configSegments:n,variants:r})=>{for(const s of r){const r=Xk({home:t,configSegments:n,variant:s});if(E.existsSync(e.dirname(r)))return s}return null},"findExistingVariant"),eT=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&tT(t.when)},"isTerminalShiftEnterBinding"),tT=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),nT=__name(e=>{const t=et(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),rT=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),sT=__name(({error:e,content:t})=>{const n=e.message;return rT(t)&&(n.includes("Expected double-quoted property name")||n.includes("Unexpected token")||n.includes("is not valid JSON"))?"Invalid JSON: trailing comma detected. Remove the comma before the closing bracket.":n.includes("Expected")&&n.includes(",")&&n.includes("or")?"Invalid JSON: missing comma between elements.":n.includes("Unterminated string")||n.includes("Bad string")?"Invalid JSON: unterminated string. Check for missing closing quotes.":"Invalid JSON syntax. Please check the file format."},"formatJsonParseError"),oT=__name(e=>{let t="",n=!1,r=!1;for(let s=0;s<e.length;s++){const o=e[s];if(n)t+=o,r?r=!1:"\\"===o?r=!0:'"'===o&&(n=!1);else if('"'!==o){if(","===o){let t=s+1;for(;t<e.length&&/\s/.test(e[t]);)t++;if("}"===e[t]||"]"===e[t])continue}t+=o}else n=!0,t+=o}return t},"removeTrailingCommas"),iT=__name(e=>{try{const t=et(e),n=oT(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:sT({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),aT=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:Yk(t)}),"createSuccessResult"),lT=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:Yk(t)}),"createErrorResult"),cT=__name(()=>{const t=y.homedir(),n=y.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=Jk(n);if(!r)return Xk({home:t,configSegments:[".config"],variant:Vk});const s=Zk({home:t,configSegments:r,variants:Qk});return Xk({home:t,configSegments:r,variant:s??Vk})},"getVSCodeKeybindingsPath"),uT=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)eT(n)&&(n.command===Kk.command&&n.args?.text===Kk.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),dT=__name(t=>{try{if(!E.existsSync(t)){const n=e.dirname(t);return E.existsSync(n)||E.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=E.readFileSync(t,"utf-8");if(nT(n))return{rawContent:n,keybindings:[]};const r=iT(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:lT({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):lT({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return lT({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),mT=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(Kk,null,2);if(nT(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return lT({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const s=e.lastIndexOf("}",r);return-1===s?lT({message:"VSCode keybindings.json is malformed (missing closing brace).",keybindingsPath:t}):e.substring(0,s+1)+",\n"+n+e.substring(s+1)},"generateNewContent");function setupVSCodeTerminal(){const e=cT();try{const t=dT(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,s=uT(r);if(s.hasConflicting)return lT({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(s.hasCompatible)return aT({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const o=mT({rawContent:n,keybindingsPath:e});return"string"!=typeof o?o:(E.writeFileSync(e,o,"utf-8"),aT({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return lT({message:`Failed to configure VSCode key binding: ${t instanceof Error?t.message:"Unknown error"}`,keybindingsPath:e})}}function isVSCodeTerminal(){return"vscode"===process.env.TERM_PROGRAM}__name(setupVSCodeTerminal,"setupVSCodeTerminal"),__name(isVSCodeTerminal,"isVSCodeTerminal"),hs(),dr();var pT=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear",e.SHARE="/share",e.TASTE="/taste",e.LEARN_TASTE="/learn-taste",e.SKILLS="/skills",e.RESUME="/resume",e.RENAME="/rename",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.MCP="/mcp",e.COMPACT="/compact",e.COMPACT_MODE="/compact-mode",e.REWIND="/rewind",e.LOGIN="/login",e.LOGOUT="/logout",e.FEEDBACK="/feedback",e.TERMINAL_SETUP="/terminal-setup",e.IDE_SETUP="/ide",e.ADD_DIR="/add-dir",e.REVIEW="/review",e.PR_COMMENTS="/pr-comments",e.CONTEXT="/context",e.STATUS="/status",e.USAGE="/usage",e))(pT||{}),gT=new Set(["/exit","/clear","/help","/share","/unshare","/taste","/learn-taste","/skills","/resume","/rename","/provider","/model","/memory","/init","/agents","/mcp","/compact","/compact-mode","/rewind","/login","/logout","/feedback","/terminal-setup","/ide","/add-dir","/pr-comments","/context","/status","/usage"]),hT=[{command:"/add-dir",description:"Add directory to workspace context"},{command:"/agents",description:"Manage agent configurations"},{command:"/clear",description:"Clear the conversation history (reset, new)"},{command:"/compact",description:"Compact the conversation history"},{command:"/compact-mode",description:"Select a compact mode to compact sessions"},{command:"/context",description:"Show context window usage and breakdown"},{command:"/exit",description:"Exit Command Code"},{command:"/feedback",description:"Share feedback or report bugs"},{command:"/help",description:"Show available shortcuts"},{command:"/ide",description:"Install extension to fetch IDE context"},{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{command:"/login",description:"Authenticate with CommandCode via browser"},{command:"/logout",description:"Remove stored authentication"},{command:"/mcp",description:"Manage MCP server connections"},{command:"/memory",description:"Manage Command Code memory"},{command:"/model",description:"Switch between Command Code models"},{command:"/pr-comments",description:"Fetch all PR comments for current branch"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/rename",description:"Rename the current session"},{command:"/resume",description:"Resume a past conversation"},{command:"/review",description:"Review a pull request (optional PR number)"},{command:"/rewind",description:"Restore to a previous checkpoint (Press Esc twice)"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/status",description:"Show comprehensive environment status"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/terminal-setup",description:"Setup VSCode keybindings"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/usage",description:"Display credits, plan, and usage metrics"}],fT=__name(({onSelectCommand:e,onInsertCommand:t,onClose:n,searchQuery:r=""})=>{const[s,o]=K(0),[i,a]=K(0),{stdout:l}=re(),u=l?.columns??80,d=Math.max(20,u-22-2-1-2),m=X(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...hT.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];if(!r)return e;const t=r.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let s=0;return n.startsWith("/"+t)?s+=100:n.includes(t)&&(s+=50),r.includes(t)&&(s+=25),{...e,score:s}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[r]),g=X(()=>{const e=i,t=Math.min(e+8,m.length);return m.slice(e,t)},[m,i]);return J(()=>{o(0),a(0)},[r]),se((r,l)=>{if(l.escape)n();else if(l.upArrow)o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t});else if(l.downArrow)o(e=>{const t=Math.min(m.length-1,e+1);return t>=i+8&&a(Math.max(0,t-8+1)),t});else{if(l.return){const t=m[s];return void(t&&e(t.command))}if(l.tab||l.rightArrow){const e=m[s];return void(e&&t(e.command))}}}),0===m.length?Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Q.createElement(te,{color:jn.DIM},"No commands found")):(m.length,Q.createElement(ee,{flexDirection:"column",paddingLeft:1},Q.createElement(ee,{columnGap:2},Q.createElement(ee,{flexDirection:"column",width:22},g.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:n,color:s===n?jn.WHITE:jn.DIM,wrap:"truncate"},e.command)})),Q.createElement(ee,{flexDirection:"column"},g.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:n,color:s===n?jn.WHITE:jn.DIM,wrap:"truncate"},truncateString({text:e.description,maxChars:d}))})))))},"CommandMenu");aw(),Ht(),Ht(),Rr(),dr();var yT=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),wT=__name(e=>{const t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`},"formatUptime"),ST=__name(({icon:e,label:t,children:n})=>Q.createElement(te,null,Q.createElement(te,{color:jn.CYAN},e," "),Q.createElement(te,{color:jn.DIM},t.padEnd(12)),n),"Row"),bT=__name(({title:e})=>Q.createElement(te,null,Q.createElement(te,{color:jn.GRAY},"───"),Q.createElement(te,{color:jn.WHITE}," ",e," "),Q.createElement(te,{color:jn.GRAY},"─".repeat(35))),"Header"),ET=__name(({title:e,marginTop:t=0,children:n})=>Q.createElement(ee,{flexDirection:"column",marginTop:t},Q.createElement(bT,{title:e}),Q.createElement(ee,{flexDirection:"column",paddingY:1},n)),"Section"),vT=__name(({cpuCount:e,totalMem:t})=>Q.createElement(ET,{title:"System Information"},Q.createElement(ST,{icon:ke.bullet,label:"Date"},Q.createElement(te,null,formatDate())),Q.createElement(ST,{icon:ke.pointer,label:"Platform"},Q.createElement(te,{color:jn.GREEN},yT(y.platform())),Q.createElement(te,{color:jn.DIM}," ","(",y.platform(),", ",y.arch(),")")),Q.createElement(ST,{icon:ke.triangleUp,label:"Hostname"},Q.createElement(te,null,y.hostname())),Q.createElement(ST,{icon:ke.bullet,label:"User"},Q.createElement(te,{color:jn.YELLOW},y.userInfo().username)),Q.createElement(ST,{icon:ke.bullet,label:"CPUs"},Q.createElement(te,{color:jn.MAGENTA},e," cores")),Q.createElement(ST,{icon:ke.bullet,label:"Memory"},Q.createElement(te,{color:jn.CYAN},t," GB")),Q.createElement(ST,{icon:ke.play,label:"Uptime"},Q.createElement(te,null,wT(y.uptime()))),Q.createElement(ST,{icon:ke.arrowRight,label:"Home"},Q.createElement(te,{color:jn.DIM},y.homedir())),Q.createElement(ST,{icon:ke.pointer,label:"Shell"},Q.createElement(te,null,process.env.SHELL||"N/A")),Q.createElement(ST,{icon:ke.bullet,label:"Node"},Q.createElement(te,{color:jn.GREEN},process.version))),"SystemInfoSection"),CT=__name(({cpus:e})=>Q.createElement(ET,{title:"CPU Details",marginTop:1},e.map((e,t)=>Q.createElement(ST,{key:t,icon:ke.bullet,label:`Core ${t}`},Q.createElement(te,null,e.model.trim()),Q.createElement(te,{color:jn.YELLOW}," @ ",e.speed," MHz")))),"CPUDetailsSection"),kT=__name(({networkInterfaces:e})=>Q.createElement(ET,{title:"Network",marginTop:1},Object.entries(e).map(([e,t])=>{const n=t?.filter(e=>"IPv4"===e.family&&!e.internal);return n&&0!==n.length?n.map((t,n)=>Q.createElement(ST,{key:`${e}-${n}`,icon:ke.bullet,label:e},Q.createElement(te,{color:jn.GREEN},t.address))):null})),"NetworkSection"),TT=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,null,"System Information"),Q.createElement(te,null,"─".repeat(40)),Q.createElement(te,null,"Date ",formatDate()),Q.createElement(te,null,"Platform ",yT(y.platform())," (",y.platform(),","," ",y.arch(),")"),Q.createElement(te,null,"Hostname ",y.hostname()),Q.createElement(te,null,"User ",y.userInfo().username),Q.createElement(te,null,"CPUs ",e.length," cores"),Q.createElement(te,null,"Memory ",t," GB"),Q.createElement(te,null,"Uptime ",wT(y.uptime())),Q.createElement(te,null,"Home ",y.homedir()),Q.createElement(te,null,"Shell ",process.env.SHELL||"N/A"),Q.createElement(te,null,"Node ",process.version),r&&Q.createElement(Q.Fragment,null,Q.createElement(te,null,"\n","CPU Details"),Q.createElement(te,null,"─".repeat(40)),e.map((e,t)=>Q.createElement(te,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),Q.createElement(te,null,"\n","Network"),Q.createElement(te,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>Q.createElement(te,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),_T=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>Q.createElement(ee,{flexDirection:"column"},Q.createElement(vT,{cpuCount:e.length,totalMem:t}),r&&Q.createElement(CT,{cpus:e}),r&&Q.createElement(kT,{networkInterfaces:n})),"StyledInfo"),xT=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=ie();J(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=y.cpus(),s=y.networkInterfaces(),o=Math.round(y.totalmem()/1024/1024/1024);return t?Q.createElement(TT,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e}):Q.createElement(_T,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e})},"InfoUI"),PT={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},AT=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),IT=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(AT("__CFBundleIdentifier","com.todesktop"))return"Cursor";const e=[process.env.VSCODE_GIT_ASKPASS_MAIN,process.env.VSCODE_GIT_ASKPASS_NODE,process.env.GIT_ASKPASS].filter(Boolean);for(const t of e){const e=t.toLowerCase();if(e.includes("cursor"))return"Cursor";if(e.includes("windsurf"))return"Windsurf"}return"vscode"===process.env.TERM_PROGRAM&&"1"===process.env.VSCODE_INJECTION?"VSCode":null},"detectIDE"),NT=__name(()=>{const e=IT();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&PT[t]?PT[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),RT=__name(()=>{if("win32"===w.platform()){const e=process.env.COMSPEC;return e?l(e):process.env.SHELL?l(process.env.SHELL):"cmd.exe"}if(process.env.FISH_VERSION)return"fish";if(process.env.ZSH_VERSION)return"zsh";if(process.env.BASH_VERSION)return"bash";try{const e=process.ppid;if(e){const t=$(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=l(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?l(e):"N/A"},"getShellName"),$T=__name(()=>{const e=IT();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),MT=__name(()=>{try{const e=$("cmd --version",{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:yT(w.platform()),terminal:NT(),shell:RT(),version:MT(),ide:$T()}}function buildGitHubIssueUrl(e){const t=getSystemInfo(),n=new URLSearchParams;if(n.append("template","1.bug_report.yml"),e){const t=e.slice(0,256).trim();t&&n.append("title",t)}return n.append("version",t.version),n.append("os",t.os),n.append("terminal",t.terminal),n.append("shell",t.shell),`https://github.com/CommandCodeAI/command-code/issues/new?${n.toString()}`}function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",s=!1,o="";for(let e=0;e<t.length;e++){const i=t[e];'"'!==i&&"'"!==i||s?i===o&&s?(s=!1,o=""):" "!==i||s?r+=i:(r.trim()&&n.push(r.trim()),r=""):(s=!0,o=i)}return r.trim()&&n.push(r.trim()),n}function parseCommandInput(e){const{input:t}=e,n=t.trim();if(!n.startsWith("/"))return null;const r=n.indexOf(" ");if(-1===r)return{commandName:n,rawArguments:"",positionalArgs:[]};const s=n.substring(0,r),o=n.substring(r+1).trim();return{commandName:s,rawArguments:o,positionalArgs:parsePositionalArguments({input:o})}}function processCommandTemplate(e){const{template:t,rawArguments:n,positionalArgs:r}=e;let s=t;return s=s.replace(/\$ARGUMENTS/g,n),s=s.replace(/\$(\d+)/g,(e,t)=>{const n=parseInt(t,10)-1;return n>=0&&n<r.length?r[n]:""}),{content:s}}async function handleRenameCommand({name:e,contextEngineRef:t,setFeed:n}){const r=e?.trim();if(!r)return void n(e=>[...e,zE("Usage: /rename [name]")]);const s=t.current?.getSessionManager();if(!s)return void n(e=>[...e,zE("No active session to rename")]);const o=s.getSessionId();await hv.isSessionNameTaken({name:r,excludeSessionId:o})?n(e=>[...e,VE(`A session named "${r}" already exists. Choose a different name.`)]):await s.saveSessionTitle(r)?n(e=>[...e,zE(`Session renamed to "${r}"`)]):n(e=>[...e,VE("Failed to rename session. Please try again.")])}async function handleCompactCommand({contextEngineRef:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:s,setStaticKey:o}){if(e.current)if(e.current.isRequestInProgress())t(e=>[...e,zE("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{r(!0),n("Compacting conversation...");const i=await e.current.manualCompact();yC(),o(e=>e+1);let a="Compacted conversation.";i.didCompact||(a="Conversation is already compact."),i.didCompact&&i.tokensSaved>0&&(a=`Compacted conversation, saved ~${i.tokensSaved.toLocaleString()} tokens.`),t(e=>[...e,zE(a)]),r(!1),n("Ready..."),s({current:e.current.getContextTokensUsed()||0,limit:pS})}catch(e){const s=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;t(e=>[...e,VE(s)]),r(!1),n("Ready...")}else t(e=>[...e,zE("No active conversation to compact.")])}function handleRewindCommand({contextEngineRef:e,setFeed:t,setShowRewindSelector:n}){e.current?e.current.hasCheckpoints()?n(!0):t(e=>[...e,zE("No checkpoints available. Start sending messages to create checkpoints.")]):t(e=>[...e,zE("No active conversation to rewind.")])}async function handleRewindSelect({messageId:e,mode:t,contextEngineRef:n,setFeed:r,setStatus:s,setShowRewindSelector:o,setStaticKey:i,setInput:a}){if(o(!1),n.current)try{const o=n.current.listCheckpoints().find(t=>t.messageId===e);s("Restoring checkpoint...");const l=await n.current.restoreToCheckpoint({messageId:e,mode:t});if(l.success){const e=n.current.getSessionManager(),t=n.current.getMessages();r(e.reconstructFeedFromMessages(t)),yC(),i(e=>e+1),o?.userPrompt&&a(o.userPrompt);const u=[];l.filesRestored>0&&u.push(`${l.filesRestored} file${l.filesRestored>1?"s":""} restored`),l.filesDeleted>0&&u.push(`${l.filesDeleted} file${l.filesDeleted>1?"s":""} deleted`),l.messagesRemoved>0&&u.push(`${l.messagesRemoved} message${l.messagesRemoved>1?"s":""} removed`);const d=u.length>0?`Restored to checkpoint: ${u.join(", ")}.`:"Restored to checkpoint.";return r(e=>[...e,zE(d)]),void s("Ready...")}r(e=>[...e,VE(`Failed to restore: ${l.error}`)]),s("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;r(e=>[...e,VE(t)]),s("Ready...")}}function handleRewindCancel({setShowRewindSelector:e}){e(!1)}async function handleLoginCommand({setFeed:e,setShowLoginOverlay:t}){const n=zt();if(await getAuthKey(n)){let t="";try{const e=await loadCredentials();t=e?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}const n=t&&"API Key"!==t&&"Manual API Key"!==t?` as ${t}`:"";return void e(e=>[...e,zE(`Already logged in${n}`)])}t(!0)}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:s,contextEngineRef:o}){if(n(!1),!e)return r(e=>[...e,VE(t)]),void s("Ready...");r(e=>[...e,zE(t)]),o.current&&o.current.refreshRequest(),s("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,zE("Authentication cancelled.")]),n("Ready...")}async function handleLogoutCommand({setFeed:e,contextEngineRef:t,setRetryAttempt:n,setIsCmdCodeBusy:r}){const s=await performLogout();if(!s.success)return void e(e=>[...e,VE(`Logout failed: ${s.error}`)]);if(n(null),r(!1),t.current&&(t.current.interrupt(),t.current.refreshRequest()),!s.wasAuthenticated)return void e(e=>[...e,zE("Not currently authenticated.")]);const o=s.warnings.length>0?`Successfully logged out from Command Code. Warnings: ${s.warnings.join(", ")}`:"Successfully logged out from Command Code.";e(e=>[...e,zE(o)])}__name(getSystemInfo,"getSystemInfo"),__name(buildGitHubIssueUrl,"buildGitHubIssueUrl"),LC(),Ht(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),bC(),Ht(),dv(),vv(),__name(handleRenameCommand,"handleRenameCommand"),Ht(),dv(),bC(),bS(),__name(handleCompactCommand,"handleCompactCommand"),Ht(),dv(),bC(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Ht(),dv(),rk(),_C(),tk(),Kt(),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Ht(),_b(),In(),xr();var LT=Xe(R);function getVsixPath(){try{const e=t.dirname(d(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return v.existsSync(n)?n:null}catch{return null}}async function getExtensionStatus(e){if(!e)return{installed:!1,version:null,connected:!1};const[t,n]=await Promise.all([checkInstalled(e),wb.isAvailable(500)]);return{...t,connected:n}}async function checkInstalled(e){try{const{stdout:t}=await LT(`${e} --list-extensions --show-versions`,{timeout:5e3}),n=t.match(new RegExp("commandcode.commandcode-vscode@([\\d.]+)","i"));return n?{installed:!0,version:n[1]}:{installed:!1,version:null}}catch{return{installed:!1,version:null}}}async function installExtension(e){if(!e)return{success:!1,error:"No IDE detected"};const t=getVsixPath();if(!t)return{success:!1,error:"VSIX not bundled"};try{return await LT(`${e} --install-extension "${t}" --force`,{timeout:3e4}),dlog(`[IDE] Extension installed for ${e}`),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}function installExtensionAsync(e){e&&installExtension(e).catch(()=>{})}async function isAutoInstallEnabled(){try{return!1!==(await loadUserConfig()).autoInstallExtension}catch{return!0}}__name(getVsixPath,"getVsixPath"),__name(getExtensionStatus,"getExtensionStatus"),__name(checkInstalled,"checkInstalled"),__name(installExtension,"installExtension"),__name(installExtensionAsync,"installExtensionAsync"),__name(isAutoInstallEnabled,"isAutoInstallEnabled");var DT={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"};async function ensureExtensionInstalled(){if(process.env.CI)return;const e=db();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:le.green("✔"),installed:le.green("✔"),needs_reload:le.yellow("◌"),failed:le.red("✖"),not_in_ide:le.yellow("◌")},n={connected:`Connected to ${e.ide}`,installed:`Installed for ${e.ide}`,needs_reload:`${e.ide} extension needs reload`,failed:e.ide?`${e.ide} install failed`:"Install failed",not_in_ide:"Not in IDE"};return["",`${t[e.status]} ${n[e.status]}`,...(e.details??[]).map(e=>le.dim(` ${e}`)),""]}async function runIDESetup(){const e=db(),t=e?DT[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new wb,r=await n.connect(500);if(n.disconnect(),r)return{status:"connected",ide:t};const{installed:s}=await checkInstalled(e);return s?{status:"needs_reload",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:(await installExtension(e)).success?{status:"installed",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:{status:"failed",ide:t,details:[`Make sure "${e}" is available in your PATH.`,"Then run /ide to retry installation."]}}async function handleHelpCommand({setFeed:e}){const{createSystemEntry:t}=await Promise.resolve().then(()=>(dv(),uv));e(e=>[...e,t("KEYBOARD SHORTCUTS\nCOMMANDS")])}async function handleTerminalSetupCommand({setFeed:e}){const t=UE(`/${$t.TERMINAL_SETUP}`),n=setupVSCodeTerminal(),r=YE(n.message,!n.success,n.details);e(e=>[...e,t,r])}async function handleIDESetupCommand({setFeed:e}){const t=await runIDESetup(),n=JE(t.status,t.ide,t.details);e(e=>[...e,n])}async function handleClearCommand({setFeed:e,setLiveEntries:t,setShareInfo:n,setShowShareNotification:r,setUnshareNotificationMessage:s,setStaticKey:o,setContextUsage:i,setInteractionTokens:a,contextEngineRef:l,setSessionId:u,createContextEngineCallbacks:d,clearSessionPermissions:m}){if(e([]),t([]),yC(),n(null),r(!1),s(""),l.current){const e=l.current.getSessionManager();e&&await e.deleteShareInfo(),l.current=null;const t=crypto.randomUUID();u(t),m();const{ContextEngine:n}=await Promise.resolve().then(()=>(SC(),fC));l.current=new n(d(t),t)}o(e=>e+1),i(null),a(0)}async function handleInitCommand({setFeed:e}){try{const t=process.cwd(),n=`Created AGENTS.md at ${await initProjectMemory(t)}. You can now edit it with /memory or open it in your editor.`;e(e=>[...e,zE(n)])}catch(t){const n=`Error: Failed to initialize AGENTS.md: ${t instanceof Error?t.message:"Unknown error"}`;e(e=>[...e,zE(n)])}}async function handleFeedbackCommand({setFeed:e},t){const n=buildGitHubIssueUrl(t);try{await me(n,{wait:!1,background:!0}),e(e=>[...e,zE(`Opened ${createOSC8Link(n,"GitHub issue")} in your browser`)])}catch{const{createSystemEntry:t,createErrorEntry:r}=await Promise.resolve().then(()=>(dv(),uv));e(e=>[...e,r("Failed to open browser"),t(createOSC8Link(n,"Open GitHub issue manually"))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const s=KE();n(s.id),r(e=>[...e,s])}async function handleCommand(e,t){if(e.startsWith("/resume:")){const n=e.substring(8);return await handleSelectSession({selectedSessionId:n,sessionLoadIdRef:t.sessionLoadIdRef,contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:t.setSessionId,setShowSessionSelector:t.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setPermissionMode:t.setPermissionMode,setStaticKey:t.setStaticKey,setShareInfo:t.setShareInfo,createContextEngineCallbacks:t.createContextEngineCallbacks}),{status:"handled"}}const n=parseCommandInput({input:e});if(!n)return{status:"unknown"};const{commandName:r,rawArguments:s,positionalArgs:o}=n;if(gT.has(r)&&s.trim().length>0)return{status:"unknown"};if("/exit"===r)return t.setShouldExit(!0),{status:"handled"};if("/clear"===r)return await handleClearCommand(t),{status:"handled"};if("/help"===r)return await handleHelpCommand(t),{status:"handled"};if("/share"===r)return await handleShareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setShowShareNotification:t.setShowShareNotification,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/unshare"===r)return await handleUnshareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setUnshareNotificationMessage:t.setUnshareNotificationMessage,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/taste"===r)return t.setShowTasteConfig(!0),{status:"handled"};if("/learn-taste"===r)return handleLearnCommand(t),{status:"handled"};if("/skills"===r)return t.setShowSkillsConfig(!0),{status:"handled"};if("/provider"===r)return isInternalTeamFlagEnforced()?(t.setShowProviderSelector(!0),{status:"handled"}):(t.setStatus("Provider selection not available"),{status:"handled"});if("/model"===r)return t.setShowModelSelector(!0),{status:"handled"};if("/memory"===r)return t.setShowMemorySelector(!0),{status:"handled"};if("/resume"===r)return t.setShowSessionSelector(!0),{status:"handled"};if("/init"===r)return await handleInitCommand(t),{status:"handled"};if("/agents"===r)return t.setShowAgentsConfig(!0),{status:"handled"};if("/mcp"===r)return t.setShowMcpManager(!0),{status:"handled"};if("/compact"===r)return await handleCompactCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setContextUsage:t.setContextUsage,setStaticKey:t.setStaticKey}),{status:"handled"};if("/compact-mode"===r)return t.setShowCompactModeSelector(!0),{status:"handled"};if("/context"===r)return t.setShowContextView(!0),{status:"handled"};if("/rewind"===r)return handleRewindCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setShowRewindSelector:t.setShowRewindSelector}),{status:"handled"};if("/login"===r)return await handleLoginCommand({setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay}),{status:"handled"};if("/logout"===r)return await handleLogoutCommand({setFeed:t.setFeed,contextEngineRef:t.contextEngineRef,setRetryAttempt:t.setRetryAttempt,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),{status:"handled"};if("/feedback"===r)return await handleFeedbackCommand(t),{status:"handled"};if("/terminal-setup"===r)return await handleTerminalSetupCommand(t),{status:"handled"};if("/ide"===r)return await handleIDESetupCommand(t),{status:"handled"};if("/add-dir"===r)return t.setShowAddDirModal(!0),{status:"handled"};if("/rename"===r)return await handleRenameCommand({name:s.trim(),contextEngineRef:t.contextEngineRef,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/usage"===r)return t.setShowUsageOverlay(!0),{status:"handled"};if("/review"===r){const e=s.trim(),{handleSubmit:n}=await Promise.resolve().then(()=>(ak(),ok));let r=e,o=!1;if(!e){const e=await Gk();r=e?String(e.number):"",o=!!e}return await n({input:buildReviewPrompt({prNumber:r,autoDetected:o}),role:"user",displayMessage:r?`/review ${r}`:"/review",isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}if("/pr-comments"===r)return await handleSubmit({input:"Fetch and display all comments from the current GitHub pull request.\n\n Run these commands in order:\n\n 1. `gh pr view --json number,headRepository` — if this fails, reply \"No comments found.\" and stop.\n 2. `gh api --paginate '/repos/{owner}/{repo}/issues/NUMBER/comments' --jq '.[] | {body,\n user: .user.login, id, created_at}' > /tmp/pr-NUMBER-issue-comments.json`\n 3. `gh api --paginate '/repos/{owner}/{repo}/pulls/NUMBER/comments' --jq '.[] | {body,\n diff_hunk: (.diff_hunk | split(\"\n\") | .[-5:] | join(\"\n\")), path, line, user: .user.login,\n in_reply_to_id, id, created_at}' > /tmp/pr-NUMBER-review-comments.json`\n\n If both return empty, reply \"No comments found.\"\n\n `{owner}` and `{repo}` are gh template variables — write them literally, never substitute. Always\n use `--jq` (not piped `| jq`).\n\n Read the temp JSON files to build output comments directly in markdown using the format:\n\n ## PR Comments\n\n - @author (date):\n > body\n\n ## Review Comments\n\n - @author path#line:\n ```diff (replace ```suggestion code blocks with ```diff to avoid rendering errors)\n [diff_hunk]\n ```\n > body [replies indented by in_reply_to_id]\n\n Number the comments in the order they were created (created_at).\n No explanatory text, no horizontal rules. No extra space in the end.",role:"user",displayMessage:"/pr-comments",isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),lastResponseHasComments(t.contextEngineRef.current?.getMessages()??[])&&t.setInput("Fix all review comments"),{status:"handled"};if("/status"===r)return t.setShowStatusView(!0),{status:"handled"};const i=getCustomCommandContent(r);if(i){const n=processCommandTemplate({template:i,rawArguments:s,positionalArgs:o}),{handleSubmit:r}=await Promise.resolve().then(()=>(ak(),ok));return await r({input:n.content,role:"user",displayMessage:e,isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}return{status:"unknown"}}function useCommandCtx({feedState:e,sessionState:t,statusState:n,uiOverlays:r,onboarding:s,exitState:o,permissionState:i,contextEngineRef:a,isSubmittingRef:l,executeBash:u,createContextEngineCallbacks:d,setInput:m}){const g=X(()=>({feed:e.feed,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setQueuedMessages:e.setQueuedMessages,setStatus:n.setStatus,setInteractionTokens:n.setInteractionTokens,setContextUsage:n.setContextUsage,setStaticKey:r.setStaticKey,updateStatus:n.updateStatus,setUpdateStatus:n.setUpdateStatus,billingLink:n.billingLink,setBillingLink:n.setBillingLink,shareInfo:n.shareInfo,setShareInfo:n.setShareInfo,setShowShareNotification:n.setShowShareNotification,setUnshareNotificationMessage:n.setUnshareNotificationMessage,setRetryAttempt:n.setRetryAttempt,setShowTasteConfig:r.setShowTasteConfig,setShowSkillsConfig:r.setShowSkillsConfig,setShowProviderSelector:r.setShowProviderSelector,setShowModelSelector:r.setShowModelSelector,setShowMemorySelector:r.setShowMemorySelector,setShowAgentsConfig:r.setShowAgentsConfig,setShowMcpManager:r.setShowMcpManager,setShowRewindSelector:r.setShowRewindSelector,setShowCompactModeSelector:r.setShowCompactModeSelector,setShowContextView:r.setShowContextView,setShowAddDirModal:r.setShowAddDirModal,setShowLoginOverlay:r.setShowLoginOverlay,setShowStatusView:r.setShowStatusView,setShowUsageOverlay:r.setShowUsageOverlay,setShowTasteOnboarding:s.setShowTasteOnboarding,setAutoLearnTaste:s.setAutoLearnTaste,setTasteOnboardingEntryId:s.setTasteOnboardingEntryId,sessionId:t.sessionId,setSessionId:t.setSessionId,sessionLoadIdRef:t.sessionLoadIdRef,sessionLoaded:t.sessionLoaded,setSessionLoaded:t.setSessionLoaded,setShowSessionSelector:r.setShowSessionSelector,setPermissionMode:i.setPermissionMode,contextEngineRef:a,clearSessionPermissions:i.clearSessionPermissions,createContextEngineCallbacks:d,setShouldExit:o.setShouldExit,setInput:m,isSubmittingRef:l,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,executeBash:u}),[e,t,n,r,s,o,i,a,l,u,d,m]),h=Y(g);return h.current=g,{commandCtx:g,onCommand:Z(e=>handleCommand(e,h.current),[])}}async function handleProviderSelect({provider:e,setCurrentProvider:t,setShowProviderSelector:n,setAuthComponentInfo:r,setStatus:s,setShowProviderNotification:o,providerNotificationTimer:i}){try{const a=getProviderConfig(e);if(a?.requiresAuth&&a.checkAuth&&!await a.checkAuth()&&a.authComponent)return void r({provider:e,Component:a.authComponent});await updateUserConfig({provider:e}),t(e),n(!1),s(`Provider set to ${getProviderDisplayName(e)}`),i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),s("Failed to set provider"),n(!1)}}function handleProviderCancel({setShowProviderSelector:e}){e(!1)}function handleAuthSuccess({authComponentInfo:e,setAuthComponentInfo:t,setShowProviderSelector:n,setCurrentProvider:r,setStatus:s,setShowProviderNotification:o,providerNotificationTimer:i}){e&&(t(null),n(!1),r(e.provider),s(`${getProviderDisplayName(e.provider)} authentication successful`),i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},5e3))}function handleAuthCancel({setAuthComponentInfo:e}){e(null)}function getModelDisplayName(e){const t=Object.values(Dt).find(t=>t.id===e);return t?t.name:e}async function handleModelSelect({modelId:e,setCurrentModel:t,setShowModelSelector:n,setStatus:r,setStaticKey:s,modelNotificationTimer:o,setShowModelNotification:i}){try{await setSelectedModel({model:e}),t(e),n(!1),yC(),s(e=>e+1),r(`Model set to ${getModelDisplayName(e)}`),o.current&&clearTimeout(o.current),i(!0),o.current=setTimeout(()=>{i(!1),o.current=null},5e3)}catch(e){console.error("Failed to set model:",e),r("Failed to set model"),n(!1)}}function handleModelCancel({setShowModelSelector:e}){e(!1)}__name(ensureExtensionInstalled,"ensureExtensionInstalled"),__name(formatSetupResult,"formatSetupResult"),__name(runIDESetup,"runIDESetup"),ak(),__name(handleHelpCommand,"handleHelpCommand"),__name(handleTerminalSetupCommand,"handleTerminalSetupCommand"),__name(handleIDESetupCommand,"handleIDESetupCommand"),__name(handleClearCommand,"handleClearCommand"),__name(handleInitCommand,"handleInitCommand"),__name(handleFeedbackCommand,"handleFeedbackCommand"),__name(handleLearnCommand,"handleLearnCommand"),__name(handleCommand,"handleCommand"),__name(useCommandCtx,"useCommandCtx"),Ht(),Ht(),Nr(),xr(),__name(handleProviderSelect,"handleProviderSelect"),__name(handleProviderCancel,"handleProviderCancel"),__name(handleAuthSuccess,"handleAuthSuccess"),__name(handleAuthCancel,"handleAuthCancel"),Ht(),Kt(),xr(),bC(),__name(getModelDisplayName,"getModelDisplayName"),__name(handleModelSelect,"handleModelSelect"),__name(handleModelCancel,"handleModelCancel"),Ht(),xr();var OT={default:"Compact Normal",fast:"Compact Fast"};async function handleCompactModeSelect({mode:e,setShowCompactModeSelector:t,setStatus:n}){try{await setCompactMode({mode:e}),t(!1),n(`Compact mode set to: ${OT[e]}`)}catch{n("Failed to set compact mode"),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var FT=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l}){const u=Y({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l});return u.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l},{onSelectSession:Z(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a}=u.current;handleSelectSession({selectedSessionId:e,sessionLoadIdRef:n.sessionLoadIdRef,contextEngineRef:i,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:n.setSessionId,setShowSessionSelector:s.setShowSessionSelector,setSessionLoaded:n.setSessionLoaded,setPermissionMode:o.setPermissionMode,setStaticKey:s.setStaticKey,setShareInfo:r.setShareInfo,createContextEngineCallbacks:a})},[]),onNewSession:Z(()=>{const{feedState:e,sessionState:t,uiOverlays:n,permissionState:r,contextEngineRef:s}=u.current;handleNewSession({contextEngineRef:s,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setSessionId:t.setSessionId,setShowSessionSelector:n.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setPermissionMode:r.setPermissionMode})},[]),onRewindSelect:Z(({messageId:e,mode:t})=>{const{feedState:n,statusState:r,uiOverlays:s,contextEngineRef:o,setInput:i}=u.current;handleRewindSelect({messageId:e,mode:t,contextEngineRef:o,setFeed:n.setFeed,setStatus:r.setStatus,setShowRewindSelector:s.setShowRewindSelector,setStaticKey:s.setStaticKey,setInput:i})},[]),onRewindCancel:Z(()=>{handleRewindCancel({setShowRewindSelector:u.current.uiOverlays.setShowRewindSelector})},[]),onLoginComplete:Z((e,t)=>{const{feedState:n,statusState:r,uiOverlays:s,contextEngineRef:o}=u.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:s.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus,contextEngineRef:o})},[]),onLoginCancel:Z(()=>{const{feedState:e,statusState:t,uiOverlays:n}=u.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),handleProviderSelect:Z(e=>{const{authState:t,statusState:n,uiOverlays:r}=u.current;handleProviderSelect({provider:e,setCurrentProvider:t.setCurrentProvider,setShowProviderSelector:r.setShowProviderSelector,setAuthComponentInfo:t.setAuthComponentInfo,setStatus:n.setStatus,setShowProviderNotification:t.setShowProviderNotification,providerNotificationTimer:t.providerNotificationTimer})},[]),handleProviderCancel:Z(()=>{handleProviderCancel({setShowProviderSelector:u.current.uiOverlays.setShowProviderSelector})},[]),handleModelSelect:Z(e=>{const{authState:t,statusState:n,uiOverlays:r}=u.current;handleModelSelect({modelId:e,setCurrentModel:t.setCurrentModel,setShowModelSelector:r.setShowModelSelector,setStatus:n.setStatus,setStaticKey:r.setStaticKey,modelNotificationTimer:t.modelNotificationTimer,setShowModelNotification:FT})},[]),handleModelCancel:Z(()=>{handleModelCancel({setShowModelSelector:u.current.uiOverlays.setShowModelSelector})},[]),handleCompactModeSelect:Z(e=>{const{statusState:t,uiOverlays:n}=u.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),handleCompactModeCancel:Z(()=>{handleCompactModeCancel({setShowCompactModeSelector:u.current.uiOverlays.setShowCompactModeSelector})},[]),handleAuthSuccess:Z(()=>{const{authState:e,statusState:t,uiOverlays:n}=u.current;handleAuthSuccess({authComponentInfo:e.authComponentInfo,setAuthComponentInfo:e.setAuthComponentInfo,setShowProviderSelector:n.setShowProviderSelector,setCurrentProvider:e.setCurrentProvider,setStatus:t.setStatus,setShowProviderNotification:e.setShowProviderNotification,providerNotificationTimer:e.providerNotificationTimer})},[]),handleAuthCancel:Z(()=>{handleAuthCancel({setAuthComponentInfo:u.current.authState.setAuthComponentInfo})},[])}}__name(useMainActionCallbacks,"useMainActionCallbacks"),Ht(),Xy(),Wy(),Ht(),Kt(),rk(),Ds(),Wy(),Xy();var qT=[{name:"Individual Pro",type:"individual",price:15,monthlyCredits:30},{name:"Individual Max",type:"individual",price:200,monthlyCredits:400},{name:"Teams Pro",type:"team",price:40,monthlyCredits:40},{name:"Teams Max",type:"team",price:400,monthlyCredits:400}];function formatCredits(e){return`$${e.toFixed(2)}`}function formatPercent(e){return`${e.toFixed(1)}%`}__name(formatCredits,"formatCredits"),__name(formatPercent,"formatPercent");var jT=[{keywords:["team","max"],tierIndex:3},{keywords:["team"],tierIndex:2},{keywords:["max"],tierIndex:1}];function getPlanInfo({planId:e}){if(!e)return null;if(void 0!==Nt[e]){const t=e.startsWith("team"),n=qT.find(n=>{if(n.type!==(t?"team":"individual"))return!1;const r=n.name.toLowerCase().replace(/\s+/g,"-");return e.startsWith(r)});if(n)return n}const t=qT.find(t=>e.toLowerCase().includes(t.name.toLowerCase().replace(/\s+/g,"-")));if(t)return t;const n=e.toLowerCase();for(const{keywords:e,tierIndex:t}of jT)if(e.every(e=>n.includes(e)))return qT[t]??null;return null}function getUsagePercent({used:e,total:t}){return t<=0?0:Math.min(e/t*100,100)}function getDaysRemaining(e){const t=new Date(e);return Number.isNaN(t.getTime())?null:Math.max(0,Math.ceil((t.getTime()-Date.now())/864e5))}function formatDateCompact(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return"N/A";const n=new Date,r={month:"short",day:"numeric",timeZone:"UTC"};return t.getUTCFullYear()!==n.getFullYear()&&(r.year="numeric"),t.toLocaleDateString("en-US",r)}async function safeFetch({request:e,endpoint:t}){try{return{data:await e.get({endpoint:t}),error:null}}catch(e){return e instanceof Ts?{data:null,error:"Network error: unable to reach API"}:e instanceof xs?{data:null,error:"Session expired"}:{data:null,error:`${t}: ${e instanceof Error?e.message:"Unknown error"}`}}}function buildEndpoint({endpoint:e,orgId:t}){return t?`${e}?orgId=${t}`:e}async function fetchCredits({request:e,orgId:t}){return safeFetch({request:e,endpoint:buildEndpoint({endpoint:"/alpha/billing/credits",orgId:t})})}async function fetchSubscription({request:e,orgId:t}){return safeFetch({request:e,endpoint:buildEndpoint({endpoint:"/alpha/billing/subscriptions",orgId:t})})}async function fetchWhoami({request:e}){return safeFetch({request:e,endpoint:"/alpha/whoami"})}async function fetchUsageSummary({request:e,orgId:t,since:n}){let r=buildEndpoint({endpoint:"/alpha/usage/summary",orgId:t});if(n){const e=r.includes("?")?"&":"?";r=`${r}${e}since=${encodeURIComponent(n)}`}return safeFetch({request:e,endpoint:r})}async function fetchUsageData(){if(!await getAuthKey())return{whoami:null,credits:null,subscription:null,summary:null,errors:["Not authenticated"]};const e=getApiBaseUrl(),t=new xy({baseUrl:e}),n=await fetchWhoami({request:t}),r=n.data?.org?.id??null,[s,o]=await Promise.all([fetchCredits({request:t,orgId:r}),fetchSubscription({request:t,orgId:r})]),i=o.data?.data?.currentPeriodStart??null,a=await fetchUsageSummary({request:t,orgId:r,since:i}),l=[n.error,s.error,o.error,a.error].filter(e=>null!==e);return{whoami:n.data,credits:s.data,subscription:o.data,summary:a.data,errors:l}}__name(getPlanInfo,"getPlanInfo"),__name(getUsagePercent,"getUsagePercent"),__name(getDaysRemaining,"getDaysRemaining"),__name(formatDateCompact,"formatDateCompact"),__name(safeFetch,"safeFetch"),__name(buildEndpoint,"buildEndpoint"),__name(fetchCredits,"fetchCredits"),__name(fetchSubscription,"fetchSubscription"),__name(fetchWhoami,"fetchWhoami"),__name(fetchUsageSummary,"fetchUsageSummary"),__name(fetchUsageData,"fetchUsageData");var BT=["○","◔","◐","◕","●"];function getCircleGauge(e){return e<=0?BT[0]:e<25?BT[1]:e<50?BT[2]:e<75?BT[3]:BT[4]}function findNewThreshold({depletionPct:e,warnedThresholds:t}){const n=[...Rt].sort((e,t)=>t-e);for(const r of n)if(e>=r&&!t.has(r))return r;return null}function getDepletionPct({planId:e,monthlyCredits:t}){const n=Nt[e];if(!n||n<=0)return null;const r=n-t;return Math.min(100,Math.max(0,r/n*100))}function buildWarningMessage({depletionPct:e,remainingCredits:t,billingUrl:n}){return`${Math.round(e)}% of plan credits used (${Number.isInteger(t)?String(t):t.toFixed(1)} remaining). Upgrade: ${n}`}function useCreditWarning({interactionTokens:e}){const[t,n]=K(null),r=Y(new Set),s=Y(null),o=Y(!1),i=Y(null),a=Y("https://commandcode.ai/settings/billing"),l=Y(null),u=Y(null),d=Z(async()=>{try{const e=getApiBaseUrl(),t=new xy({baseUrl:e});if(!o.current){o.current=!0;try{const e=await getAuthenticatedEntity();i.current=e.org?.id??null,a.current=e.org?`https://commandcode.ai/${e.org.login}/settings/billing`:"https://commandcode.ai/settings/billing";const n=await t.get({endpoint:buildEndpoint({endpoint:kt.ALPHA.BILLING.SUBSCRIPTIONS,orgId:i.current})});s.current=n}catch{return}}const l=s.current;if(!l?.success||!l.data)return;const{planId:d,status:m}=l.data;if("active"!==m&&"past_due"!==m)return;if(!Nt[d])return;let g;try{g=await t.get({endpoint:buildEndpoint({endpoint:kt.ALPHA.BILLING.CREDITS,orgId:i.current})})}catch{return}const{monthlyCredits:h}=g.credits,f=getDepletionPct({planId:d,monthlyCredits:h});if(null===f)return;const y=findNewThreshold({depletionPct:f,warnedThresholds:r.current});if(null===y)return;for(const e of Rt)e<=y&&r.current.add(e);const w=buildWarningMessage({depletionPct:f,remainingCredits:d.startsWith("individual-")?h/2:h,billingUrl:a.current});n(w),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{n(null),u.current=null},3e4)}catch{}},[]);return J(()=>{if(0!==e)return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{d(),l.current=null},2e3),()=>{l.current&&clearTimeout(l.current)}},[e,d]),J(()=>()=>{u.current&&clearTimeout(u.current),l.current&&clearTimeout(l.current)},[]),{creditWarning:t}}__name(getCircleGauge,"getCircleGauge"),sk(),Kt(),__name(findNewThreshold,"findNewThreshold"),__name(getDepletionPct,"getDepletionPct"),__name(buildWarningMessage,"buildWarningMessage"),__name(useCreditWarning,"useCreditWarning"),Ht(),Ht(),Ht();var UT=__name(({staticKey:e})=>Q.createElement(ne,{items:[{staticKey:e}],key:e},()=>Q.createElement(te,{key:e},"\0")),"Responsive");Ht(),Kt(),dr();var zT=__name(({onTrust:e,onExit:t})=>{const{exit:n}=ie(),[r,s]=K(1),o=process.cwd().replace(process.env.HOME||"","~");return se((o,i)=>{i.upArrow||i.downArrow?s(1===r?2:1):i.return?1===r?e():(t(),n()):"1"===o?e():("2"===o||i.escape||i.ctrl&&"c"===o)&&(t(),n())}),Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.YELLOW,padding:1},Q.createElement(te,{color:jn.YELLOW,bold:!0},"Do you trust the files in this folder?"),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY},o)),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(te,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),Q.createElement(ee,{marginTop:1},Q.createElement(te,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{color:1===r?jn.CYAN:jn.GRAY},1===r?ke.pointer:" "," 1. Yes, proceed")),Q.createElement(ee,null,Q.createElement(te,{color:2===r?jn.CYAN:jn.GRAY},2===r?ke.pointer:" "," 2. No, exit"))))},"TrustPrompt"),WT=V(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(zT,{onTrust:t,onExit:n}))},"TrustView"));Ht(),Ht(),vv(),hs(),dr();var GT=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=ie(),[r,s]=K([]),[o,i]=K(0),[a,l]=K(!0),[u,d]=K(0),m=30;J(()=>{g()},[]);const g=__name(async()=>{l(!0);const e=await hv.listSessions();s(e),l(!1)},"loadSessions");if(se((t,s)=>{s.upArrow?i(e=>{const t=Math.max(0,e-1);return t<u&&d(t),t}):s.downArrow?i(e=>{const t=Math.min(r.length-1,e+1);return t>=u+m&&d(t-m+1),t}):s.return?r.length>0&&e(r[o].id):(s.escape||s.ctrl&&"c"===t)&&n()}),a)return Q.createElement(ee,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(te,{color:jn.GRAY},"Loading sessions..."));const h=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),s=Math.floor(n/36e5),o=Math.floor(n/864e5),i=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:s<24?`${s} hour${s>1?"s":""} ago`:o<7?`${o} day${o>1?"s":""} ago`:1===i?"1 week ago":`${i} weeks ago`},"formatRelativeTime"),f=__name(e=>truncateString({text:e,maxChars:ss}),"truncateMessage");if(0===r.length)return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.GRAY},"No sessions available"));const y=r.slice(u,u+m),w=u;return Q.createElement(ee,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM},"Showing ",u+1,"-",Math.min(u+m,r.length)," ","of ",r.length," sessions",u>0&&" (↑ for more)",u+m<r.length&&" (↓ for more)")),Q.createElement(ee,{columnGap:2,marginBottom:1},Q.createElement(ee,{width:7},Q.createElement(te,{color:jn.GRAY}," ")),Q.createElement(ee,{width:13},Q.createElement(te,{color:jn.GRAY},"Modified")),Q.createElement(ee,{width:11},Q.createElement(te,{color:jn.GRAY},"# Messages")),Q.createElement(ee,{width:20},Q.createElement(te,{color:jn.GRAY},"Git Branch")),Q.createElement(ee,null,Q.createElement(te,{color:jn.GRAY},"Summary"))),Q.createElement(ee,{columnGap:2},Q.createElement(ee,{flexDirection:"column",width:7},y.map((e,t)=>{const n=w+t;return Q.createElement(te,{key:`sel-${n}`,color:o===n?jn.CYAN:jn.GRAY},o===n?`${ke.pointer} ${n+1}.`:` ${n+1}.`)})),Q.createElement(ee,{flexDirection:"column",width:13},y.map((e,t)=>{const n=w+t;return Q.createElement(te,{key:`mod-${e.id}`,color:o===n?jn.WHITE:jn.GRAY},h(e.lastModified))})),Q.createElement(ee,{flexDirection:"column",width:11},y.map((e,t)=>{const n=w+t;return Q.createElement(te,{key:`msg-${e.id}`,color:o===n?jn.WHITE:jn.GRAY},e.messageCount)})),Q.createElement(ee,{flexDirection:"column",width:20},y.map((e,t)=>{const n=w+t;return Q.createElement(te,{key:`branch-${e.id}`,color:o===n?jn.WHITE:jn.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),Q.createElement(ee,{flexDirection:"column"},y.map((e,t)=>{const n=w+t;return Q.createElement(te,{key:`summary-${e.id}`,color:o===n?jn.WHITE:jn.GRAY},f(e.firstMessage))}))))},"SessionTable"),HT=V(__name(function SessionView2({onSelectSession:e,onNewSession:t}){return Q.createElement(GT,{onSelectSession:e,onNewSession:t})},"SessionView"));Ht(),Ht(),gr(),dr();var QT=__name((e,t)=>{if(!e.startsWith("option_"))return null;const n=e.slice(7),r=parseInt(n,10);return Number.isNaN(r)||r<0||r>t?null:r},"parseOptionIndex"),VT=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r,hideReview:s=!1})=>{if(s&&1===e.length)return null;const o=[];if(e.forEach((s,i)=>{const a=i===t&&!r,l=n.has(i);let u,d;a?(u=ke.bullet,d=jn.CYAN):l?(u=ke.tick,d=jn.GREEN):(u=ke.circle,d=jn.GRAY),o.push(Q.createElement(te,{key:i},Q.createElement(te,{color:d},u),Q.createElement(te,{color:a?jn.CYAN:void 0}," ",s.header),i<e.length-1?Q.createElement(te,{color:jn.DIM}," | "):null))}),!s){const e=r;o.push(Q.createElement(te,{key:"review"},Q.createElement(te,{color:jn.DIM}," | "),Q.createElement(te,{color:e?jn.CYAN:jn.GRAY},e?ke.bullet:ke.circle),Q.createElement(te,{color:e?jn.CYAN:void 0,bold:e}," ","Review")))}return Q.createElement(ee,null,o)},"TabIndicator"),KT=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,s]=K(0),[o,i]=K(new Map),a=Y(new Map),[l,u]=K(""),[d,m]=K(new Set),[g,h]=K(null),[f,y]=K(!1),[w,S]=K(!1),[E,v]=K(!1),[C,k]=K(null),[T,_]=K(!1),x=e[r],P=x?.multiSelect??!1,A=o.get(r),I=x?[...x.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],N=I.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),R=new Map(N.map((e,t)=>[e.label,I[t]])),$=__name(e=>{"submit"===e.value?q():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),M=__name(()=>{if(!A||0===A.length)return 0;const e=A[0],t=x.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),L=__name(e=>{if(!f)if(P){const t=QT(e.value,x.options.length-1);if(null===t)return;const n=x.options[t]?.label||"";m(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=QT(e.value,x.options.length-1);if(null===t)return;y(!0);const n=x.options[t]?.label||"";F([n])}},"handleSelect"),D=__name(()=>{if(f)return;y(!0);const e=Array.from(d);F(e)},"handleMultiSelectDone"),O=__name(()=>{if(!f&&l.trim())if(P){const e=new Set(x.options.map(e=>e.label));m(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(l.trim()),n})}else y(!0),F([l.trim()])},"handleOtherSubmit"),F=__name(t=>{a.current.set(r,t);const o=new Map(a.current);i(o);const l=__name(t=>{const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);u(t&&e?e:"")}},"restoreStateForQuestion");if(r<e.length-1){const e=r+1;l(e),s(e),y(!1),v(!1),k(null),_(!1)}else if(e.every((e,t)=>o.has(t))){if(n&&1===e.length)return void q();m(new Set),u(""),S(!0),y(!1)}else{const t=e.findIndex((e,t)=>!o.has(t));-1!==t&&(l(t),s(t)),y(!1),v(!1),k(null),_(!1)}},"finishQuestion"),q=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:a.current.get(t)||[]}));t({answers:n})},"submitAnswers"),j=__name(t=>{S(!1),s(t),_(!1),v(!1),k(null);const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}},"editQuestion"),B=__name(t=>{if(t<0||t>=e.length)return;P&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),y(!1),v(!1),k(null),_(!1);const n=e[t],o=a.current.get(t);if(n?.multiSelect&&o){m(new Set(o));const e=o.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==o?.length)u("");else{const e=o[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}s(t)},"navigateToQuestion"),U=__name(()=>{if(!g||!P)return;if("done"===g.value)return;const e=QT(g.value,x.options.length-1);if(null===e)return;const t=x.options[e]?.label||"";m(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return se((t,s)=>{if(" "===t&&P&&!E&&U(),"d"!==t||!P||E||w||D(),!w&&!f){if(s.downArrow&&!E&&!T&&!n&&g&&N.length>0&&g.value===N[N.length-1]?.value&&v(!0),s.upArrow&&!E&&!T&&g&&N.length>0&&g.value===N[0]?.value&&(P?_(!0):n||(v(!0),k(N.length-1))),s.upArrow&&E){v(!1),k(N.length-1);const e=N[N.length-1];e&&h(e)}if(s.downArrow&&E)if(v(!1),P)_(!0);else{k(0);const e=N[0];e&&h(e)}if(s.upArrow&&T&&(_(!1),v(!0)),s.downArrow&&T){_(!1),k(0);const e=N[0];e&&h(e)}s.return&&T&&P&&D()}if(f||E||T||(w?s.leftArrow&&j(e.length-1):s.leftArrow&&r>0?B(r-1):s.rightArrow&&(r<e.length-1?B(r+1):(P&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),S(!0)))),s.escape&&!f)if(w)S(!1);else if(E){v(!1);const e=C??N.length-1;k(e);const t=N[e];t&&h(t)}else if(T){_(!1);const e=N[N.length-1];e&&h(e)}}),x||w?w?Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(VT,{questions:e,currentIndex:e.length,answeredQuestions:new Set(o.keys()),isReviewPage:!0})),e.map((e,t)=>Q.createElement(ee,{key:t,marginBottom:1,flexDirection:"column"},Q.createElement(te,{color:jn.DIM},t+1,". ",e.question),Q.createElement(te,{color:jn.GREEN}," ",o.get(t)?.join(", ")||"No answer"))),Q.createElement(tt,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:$,initialIndex:0,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.CYAN},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(te,{color:t?jn.CYAN:jn.WHITE},e)}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},ke.arrowLeft," to go back and edit"))):Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(VT,{questions:e,currentIndex:r,answeredQuestions:new Set(o.keys()),isReviewPage:!1,hideReview:n})),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{bold:!0},x.question)),E||T?Q.createElement(ee,{flexDirection:"column"},N.map((e,t)=>{const n=R.get(e.label),r=P&&n&&d.has(n.label),s=!P&&n&&A?.includes(n.label),o=r||s;return Q.createElement(ee,{key:t,flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,null," "),Q.createElement(te,{color:o?jn.GREEN:jn.WHITE}," ",t+1,"."," "),P&&(o?Q.createElement(te,{color:jn.GREEN},"[",ke.tick,"]"," "):Q.createElement(te,{color:jn.DIM},"[ ] ")),Q.createElement(te,{color:o?jn.GREEN:jn.WHITE},n?.label||""),!P&&o&&Q.createElement(te,{color:jn.GREEN}," ",ke.tick)),n?.description&&Q.createElement(ee,null,Q.createElement(te,null," "),Q.createElement(te,{color:jn.DIM},P?" ":" ",n.description)))})):Q.createElement(tt,{key:`${r}-${C??"default"}`,items:N,initialIndex:C??M(),onSelect:L,onHighlight:h,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.CYAN},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=R.get(e),r=P&&n&&d.has(n.label),s=!P&&n&&A?.includes(n.label),o=r||s,i=e.match(/^\s*(\d+)\.\s*(.*)$/),a=i?.[1]||"",l=i?.[2]||e;return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{color:t?jn.CYAN:o?jn.GREEN:jn.WHITE}," ",a,"."," "),P&&(o?Q.createElement(te,{color:jn.GREEN},"[",ke.tick,"]"," "):Q.createElement(te,{color:jn.DIM},"[ ] ")),Q.createElement(te,{color:t?jn.CYAN:o?jn.GREEN:jn.WHITE},l),!P&&o&&Q.createElement(te,{color:jn.GREEN}," ",ke.tick)),n?.description&&Q.createElement(te,{color:jn.DIM},P?" ":" ",n.description))}}),!n&&Q.createElement(ee,null,Q.createElement(te,{color:jn.CYAN},E?ke.pointer:" "),Q.createElement(te,{color:E?jn.CYAN:void 0}," ",N.length+1,"."," "),P&&(d.has(l.trim())?Q.createElement(te,{color:jn.GREEN},"[",ke.tick,"] "):Q.createElement(te,{color:jn.DIM},"[ ] ")),Q.createElement(TextInput,{value:l,onChange:e=>{const t=e.replace(/\r\n/g," ").replace(/[\r\n]/g," "),n=l.trim();u(t),P&&m(e=>{const r=new Set(e);return n&&r.has(n)&&r.delete(n),t.trim()&&r.add(t.trim()),r})},onSubmit:O,placeholder:"Type something...",focus:E,stripBracketedPaste:!0})),P&&Q.createElement(ee,null,Q.createElement(te,{color:jn.CYAN},T?ke.pointer:" "),Q.createElement(te,{color:T?jn.CYAN:void 0,bold:T}," ",r===e.length-1?"Submit":"Next")),e.length>1&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function QuestionView({pendingQuestion:e,setPermissionMode:t,setPendingQuestion:n,setStatus:r,setStaticKey:s}){return Q.createElement(ee,{marginY:1},Q.createElement(KT,{questions:e.params.questions,hideCustomInput:e.params.hideCustomInput,onResponse:o=>{if(e.params.exitPlanMode){const e=o.answers[0]?.selectedOptions[0]||"";e.startsWith("Yes, auto-accept")?(t("auto-accept"),yC(),s(e=>e+1)):e.startsWith("Yes, exit")&&(t("standard"),yC(),s(e=>e+1))}if(e.params.enterPlanMode){const e=o.answers[0]?.selectedOptions[0];e?.startsWith("Yes")&&(t("plan"),yC(),s(e=>e+1))}e.resolve(o),n(null),r("Answers submitted")}}))}bC(),__name(QuestionView,"QuestionView"),Ht(),Ht(),Kt(),Vv(),Ht(),dr();var YT=/\[([^\]]+)\]/g;function BracketWrap({children:e,color:t,bold:n=!1}){return Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.DIMMEST,bold:n},"["),"string"==typeof e?Q.createElement(te,{color:t,bold:n},e):e,Q.createElement(te,{color:jn.DIMMEST,bold:n},"]"))}function BracketedText({text:e,color:t,bold:n=!1,wrap:r}){const s=X(()=>{const t=[];let n=0;for(const r of e.matchAll(YT)){const s=r.index??0;s>n&&t.push({type:"text",value:e.slice(n,s)}),t.push({type:"bracket",value:r[1]??""}),n=s+r[0].length}return n<e.length&&t.push({type:"text",value:e.slice(n)}),0===t.length&&t.push({type:"text",value:e}),t},[e]),o=X(()=>s.map((e,r)=>"bracket"===e.type?Q.createElement(BracketWrap,{key:`bracket-${r}`,color:t,bold:n},e.value):e.value),[s,t,n]);return Q.createElement(te,{color:t,bold:n,wrap:r},o)}__name(BracketWrap,"BracketWrap"),__name(BracketedText,"BracketedText"),dr(),Ht(),vw(),dv(),gn(),hs(),Rr(),dr(),Ht(),dr();var JT=class extends st{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}hr(){return"\n"+le.dim("───")+"\n"}blockquote(e){return"object"==typeof e&&(e=this.parser.parse(e.tokens)),this.o.blockquote(e.trim()).split("\n").map(e=>`│ ${e}`).join("\n")+"\n\n"}listDepth=0;list(e,t=!1,n=""){let r;this.listDepth++;try{r=super.list(e,t,n),r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),1===this.listDepth&&(r=r.replace(/^ /gm,""))}finally{this.listDepth--}return r}},XT=new rt;XT.setOptions({renderer:new JT({strong:le.bold,em:le.italic,del:le.dim.strikethrough,codespan:le.hex(sr.CODE),code:le.hex(sr.CODE),heading:le.bold,firstHeading:le.bold.hex(sr.HEADING).underline,link:le.hex(jn.CYAN),href:le.hex(jn.CYAN).underline,blockquote:le.hex(jn.GRAY).italic,table:le.reset,tableOptions:{style:{head:[jn.CYAN],border:[jn.GRAY]}},hr:le.reset,paragraph:le.reset,html:le.hex(jn.GRAY),showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var ZT=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const s=X(()=>{if(!e)return"";const t=[],n=e.replace(ZT,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=XT.parse(n);if("string"!=typeof r)return e;return r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").replace(/^(\s*)\* /gm,"$1- ").replace(/\n{3,}/g,"\n\n").trim()}catch{return e}},[e]);return Q.createElement(te,{color:t,dimColor:n,wrap:r},s)}function buildTreeConnectors(e,t=!1){return e.split("\n").map((e,n,r)=>t||n!==r.length-1?"│":Ok).join("\n")}__name(Markdown,"Markdown"),Ht(),__name(buildTreeConnectors,"buildTreeConnectors");var e_=" │ ";function computeSimilarity({strA:e,strB:t}){const n=e.trim(),r=t.trim();if(n===r)return 1;if(!n||!r)return 0;const s=Object.create(null);for(let e=0;e<n.length;e++){const t=n[e];s[t]=(s[t]??0)+1}let o=0;for(let e=0;e<r.length;e++){const t=r[e],n=s[t];n&&(o++,s[t]=n-1)}return 2*o/(n.length+r.length)}function buildSimilarityMatrix(e,t,n){const r=new Float64Array(e.length*n);for(let s=0;s<e.length;s++)for(let o=0;o<n;o++)r[s*n+o]=computeSimilarity({strA:e[s],strB:t[o]});return r}function collectSimilarityCandidates(e,t,n){const r=[];for(let s=0;s<t;s++)for(let t=0;t<n;t++){const o=e[s*n+t];o>=.3&&r.push({score:o,removedIdx:s,addedIdx:t})}return r}function buildLinePairs(e,t){const n=e.length,r=t.length,s=new Map;if(n*r>200){const e=Math.min(n,r);for(let t=0;t<e;t++)s.set(t,t);return s}const o=collectSimilarityCandidates(buildSimilarityMatrix(e,t,r),n,r);o.sort((e,t)=>t.score-e.score);const i=new Set,a=new Set;for(const{removedIdx:e,addedIdx:t}of o)i.has(e)||a.has(t)||(s.set(e,t),i.add(e),a.add(t));return s}function groupAdjacentChanges(e){const t=[];let n=0;for(;n<e.length;){const r=e[n];if(!r.added&&!r.removed){const e=r.value.split("\n");""===e.at(-1)&&e.pop(),t.push({type:"context",contextLines:e,removedLines:[],addedLines:[]}),n++;continue}const s=[],o=[];for(;n<e.length&&(e[n].added||e[n].removed);){const t=e[n].value.split("\n");""===t.at(-1)&&t.pop(),e[n].removed?(s.push(...t),n++):(o.push(...t),n++)}t.push({type:"change",contextLines:[],removedLines:s,addedLines:o})}return t}function renderWordSegments({wordChanges:e,type:t,dimDiff:n}){const r="removed"===t?Gn.REMOVED_HIGHLIGHT_BG:Gn.ADDED_HIGHLIGHT_BG,s=[];let o=0;for(const i of e){if("removed"===t&&i.added)continue;if("added"===t&&i.removed)continue;const e="removed"===t?i.removed:i.added,a=i.value.replace(/\s/g," "),l=`${t}-${o++}-${e?"highlighted":"unchanged"}`;e?s.push(Q.createElement(te,{key:l,backgroundColor:r,dimColor:n},a)):s.push(Q.createElement(te,{key:l,color:jn.WHITE,dimColor:n},a))}return s}function renderContextLine({line:e,lineNum:t,lineNumWidth:n,dimDiff:r,nodeKey:s}){return Q.createElement(ee,{key:s,width:"100%"},Q.createElement(te,{color:Gn.LINE_NUM,dimColor:r}," "+t.toString().padStart(n)),Q.createElement(te,{color:Gn.LINE_NUM,dimColor:r},e_),Q.createElement(te,{color:jn.WHITE,dimColor:r}," ",e.replace(/\s/g," ")))}function renderContextGroup({lines:e,leadCount:t,trailCount:n,lineNumWidth:r,dimDiff:s,counters:o}){const i=[];if(t+n>=e.length){for(const t of e)i.push(renderContextLine({line:t,lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;return i}for(let n=0;n<t;n++)i.push(renderContextLine({line:e[n],lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;const a=e.length-t-n;a>0&&(o.oldLineNum+=a,o.newLineNum+=a,i.push(Q.createElement(ee,{key:"sep-"+o.nodeKey++},Q.createElement(te,{color:Gn.LINE_NUM,dimColor:s}," ".repeat(r+1)),Q.createElement(te,{color:Gn.LINE_NUM,dimColor:s},e_),Q.createElement(te,{color:Gn.LINE_NUM,dimColor:s},`⋮ ${a} line${1===a?"":"s"}`))));for(let t=e.length-n;t<e.length;t++)i.push(renderContextLine({line:e[t],lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;return i}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:s=!1,marginLeft:o=2,startLine:i=1,dimDiff:a=!1,maxLines:l}){const u=nt.diffLines(e,t);let d=0,m=0;for(const e of u)e.added&&(d+=e.count||1),e.removed&&(m+=e.count||1);const g=u.reduce((e,t)=>e+(t.added?0:t.count||1),0),h=u.reduce((e,t)=>e+(t.removed?0:t.count||1),0),f=Math.max(3,(i+g-1).toString().length,(i+h-1).toString().length),y=groupAdjacentChanges(u),w=[],S={oldLineNum:i,newLineNum:i,nodeKey:0};for(let e=0;e<y.length;e++){const t=y[e];if("context"===t.type){const n=t.contextLines,r=e>0&&"change"===y[e-1].type,s=e<y.length-1&&"change"===y[e+1].type;if(!r&&!s){S.oldLineNum+=n.length,S.newLineNum+=n.length;continue}const o=r?Math.min(3,n.length):0,i=s?Math.min(3,Math.max(0,n.length-o)):0;w.push(...renderContextGroup({lines:n,leadCount:o,trailCount:i,lineNumWidth:f,dimDiff:a,counters:S}));continue}const{removedLines:n,addedLines:r}=t,s=buildLinePairs(n,r),o=new Map,i=new Map;for(const[e,t]of s){const s=nt.diffWordsWithSpace(n[e],r[t]);o.set(e,s),i.set(t,s)}for(let e=0;e<n.length;e++){const t=o.get(e);w.push(Q.createElement(ee,{key:"rm-"+S.nodeKey++,width:"100%",backgroundColor:Gn.REMOVED_BG},Q.createElement(te,{color:Gn.REMOVED_TEXT,dimColor:a}," "+S.oldLineNum.toString().padStart(f)),Q.createElement(te,{color:Gn.LINE_NUM,dimColor:a},e_),Q.createElement(te,{color:Gn.REMOVED_TEXT,dimColor:a},"- "),t?renderWordSegments({wordChanges:t,type:"removed",dimDiff:a}):Q.createElement(te,{color:Gn.REMOVED_TEXT,dimColor:a},n[e].replace(/\s/g," ")))),S.oldLineNum++}for(let e=0;e<r.length;e++){const t=i.get(e);w.push(Q.createElement(ee,{key:"add-"+S.nodeKey++,width:"100%",backgroundColor:Gn.ADDED_BG},Q.createElement(te,{color:Gn.ADDED_TEXT,dimColor:a}," "+S.newLineNum.toString().padStart(f)),Q.createElement(te,{color:Gn.LINE_NUM,dimColor:a},e_),Q.createElement(te,{color:Gn.ADDED_TEXT,dimColor:a},"+ "),t?renderWordSegments({wordChanges:t,type:"added",dimDiff:a}):Q.createElement(te,{color:Gn.ADDED_TEXT,dimColor:a},r[e].replace(/\s/g," ")))),S.newLineNum++}}const E=void 0!==l&&w.length>l,v=E?w.slice(0,l):w;return{diffContent:Q.createElement(ee,{flexDirection:"column"},s&&!r&&(d>0||m>0)&&Q.createElement(te,{color:jn.GRAY},"Updated"," ",Q.createElement(te,{color:jn.WHITE,bold:!0},n)," ","with"," ",d>0&&Q.createElement(Q.Fragment,null,Q.createElement(te,{color:Kn.SUCCESS},d)," ","addition",1!==d?"s":"",m>0?" and ":""),m>0&&Q.createElement(Q.Fragment,null,Q.createElement(te,{color:Kn.ERROR},m)," ","removal",1!==m?"s":"")),r&&Q.createElement(te,{color:jn.RED},"Rejected update to",Q.createElement(te,{color:jn.RED},` ${n}`)),Q.createElement(ee,{flexDirection:"column",marginLeft:o,marginRight:o+4,width:(process.stdout.columns||80)-2*o-8},v)),isTruncated:E,totalLines:w.length}}function formatTodosForDisplay(e){const t=lv(e);return t?Q.createElement(ee,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?ke.checkboxOn:ke.checkboxOff;let r,s=!1;switch(e.status){case"completed":r=Kn.SUCCESS,s=!0;break;case"in_progress":r=Kn.IN_PROGRESS;break;default:r=jn.WHITE}return Q.createElement(ee,{key:e.id||t,flexDirection:"row"},Q.createElement(ee,{width:2},Q.createElement(te,{color:r},n)),Q.createElement(te,{color:r,bold:"in_progress"===e.status,strikethrough:s},e.content))})):Q.createElement(te,null,e)}function computeDisplayInput({input:e,isAgent:t,isShell:n,expandedOutput:r}){if(!e)return e;if(t){const t=e.split(/[.\n]/)[0];return t?t+(e.includes(".")||e.includes("\n")?".":""):e}return n&&!r?truncateCommand({command:e}):e}function formatToolInput({input:e,isShell:t}){return Q.createElement(BracketWrap,null,t?e:Q.createElement(Markdown,null,e))}function parseReadSummaryLine(e){if(!e)return null;const t=e.split("\n")[0]?.trim();return t?t.match(bw):null}function getReadToolInlineSummary({name:e,summaryMatch:t}){if(!t||"READ"!==e)return null;const n=t[3]?Number(t[3]):void 0;return{dimText:void 0===n?void 0:`${n} ${1===n?"line":"lines"}`}}function renderReadToolInlineSummary(e){return e?.dimText?Q.createElement(te,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:s}){if(e)return{symbolColor:jn.YELLOW,symbol:ke.arrowRight};if(t)return{symbolColor:jn.RED,symbol:ke.square};if(n)return{symbolColor:zn,symbol:"✻"};if(r&&s){const e=lv(s),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?Kn.SUCCESS:Kn.WARNING,symbol:ke.square}}return{symbolColor:Hn.BG,symbol:ke.square}}function renderToolHeader({isThinking:e,isTasteFile:t,tasteCategory:n,name:r,summaryMatch:s,expandedOutput:o,expandKey:i,output:a}){if(e){const e=a?Math.max(1,Math.round(a.length/500)):1;return Q.createElement(Q.Fragment,null,Q.createElement(te,{color:zn},`Thought for ${e} second${1!==e?"s":""}`," "),!o&&Q.createElement(BracketWrap,{color:jn.DIM},`${i}+o to expand`))}if(t)return Q.createElement(Q.Fragment,null,Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:Un.BADGE_BG,color:Un.BADGE_FG,bold:!0},qk)),Q.createElement(te,null," ","Using your taste"," ",n?"package of ":"packages",n&&Q.createElement(te,{bold:!0},n)));let l=r;return"READ[n]"===r&&s&&(l=`READ[${Number(s[1])}]`),Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:Hn.BG,color:Hn.FG,bold:!0},`${Fk}${l}${Fk}`))}function renderAgentStatus({agentStatus:e,hasError:t,output:n,elapsedSeconds:r,tokensUsed:s}){const o=`${formatTime2(r)} | ${formatTokens(s)}`;return"running"===e?Q.createElement(te,{color:jn.GRAY},"Running (",o,")"):"interrupted"===e||"Interrupted by user"===n?Q.createElement(te,{color:jn.RED,wrap:"wrap"},"Interrupted by user"):"error"===e||t?Q.createElement(te,{color:jn.RED,wrap:"wrap"},n," (",o,")"):Q.createElement(Q.Fragment,null,Q.createElement(te,{wrap:"wrap"},"Done"),Q.createElement(te,{color:jn.GRAY}," (",o,")"))}function getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}){if(n)return{text:e,isTruncated:!1,remainingLines:0,truncationMsg:null};const s=dedentText(e),{text:o,isTruncated:i,remainingLines:a}=truncateToVisualLines({output:s,maxVisualLines:"Question"===t?Jr:Yr,maxChars:"Question"===t?1/0:rs}),l=i&&"Question"!==t;return{text:o,isTruncated:l,remainingLines:a,truncationMsg:l?a>0?Q.createElement(BracketedText,{text:`... +${a} lines [${r}+o to expand]`,color:jn.DIM}):Q.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:jn.DIM}):null}}function renderTruncatedOutput({output:e,name:t,expandedOutput:n,expandKey:r}){const{text:s,isTruncated:o,truncationMsg:i}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r});return o?Q.createElement(Q.Fragment,null,s,"\n",i):s}function renderEditFileDiff({input:e,metadata:t,expandedOutput:n,isPermissionDenied:r,output:s,expandKey:o}){const i=n?void 0:Xr,{diffContent:a,isTruncated:l,totalLines:u}=generateDiff({filePath:e,showMetadata:!0,oldValue:t.oldValue,newValue:t.newValue,startLine:"number"==typeof t.startLine?t.startLine:1,dimDiff:r,permissionDenied:r,maxLines:i});return Q.createElement(ee,{flexDirection:"column"},a,l&&Q.createElement(ee,{marginTop:1},Q.createElement(BracketedText,{text:`… (${u-Xr} more lines) [${o}+o to expand]`,color:jn.DIM})),r&&s&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.RED,wrap:"wrap"},s)))}function renderWriteFileContent({input:e,metadata:t,expandedOutput:n,expandKey:r}){const s=t.content;if(!s)return Q.createElement(te,{color:jn.GRAY},"Created"," ",Q.createElement(te,{color:jn.WHITE,bold:!0},e)," ","(empty file)");const o=s.endsWith("\n")?s.slice(0,-1).split("\n"):s.split("\n"),i="number"==typeof t.totalLines?t.totalLines:o.length,a=n?void 0:Zr,l=void 0!==a&&i>a,u=l?o.slice(0,a):o,d=String(i).length;return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.GRAY},"Created"," ",Q.createElement(te,{color:jn.WHITE,bold:!0},e)," ","(",i," line",1!==i?"s":"",")"),Q.createElement(ee,{marginTop:1,flexDirection:"column"},u.map((e,t)=>Q.createElement(ee,{key:t,width:"100%",backgroundColor:Gn.ADDED_BG},Q.createElement(te,{color:Gn.ADDED_TEXT}," "+String(t+1).padStart(d)),Q.createElement(te,{color:Gn.LINE_NUM},e_),Q.createElement(te,{color:Gn.ADDED_TEXT,wrap:"truncate-end"},e.replace(/\s/g," "))))),l&&void 0!==a&&Q.createElement(ee,{marginTop:1},Q.createElement(BracketedText,{text:`… (${i-a} more lines) [${r}+o to expand]`,color:jn.DIM})))}function renderOutputContent({isTodos:e,isThinking:t,isEditFile:n,isWriteFile:r,metadata:s,output:o,expandedOutput:i,isPermissionDenied:a,input:l,hasError:u,name:d,expandKey:m,showTreeConnector:g}){if(e)return formatTodosForDisplay(o);if(t)return i?Q.createElement(ee,{width:"100%",flexDirection:"column"},Q.createElement(te,null," "),Q.createElement(te,{color:zn,wrap:"wrap",italic:!0},o)):null;if(n&&s?.oldValue&&s?.newValue){const e=renderEditFileDiff({input:l,metadata:s,expandedOutput:i,isPermissionDenied:a,output:o,expandKey:m});return g?Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:lr},Ok," "),e):e}if(r&&s&&"content"in s){const e=renderWriteFileContent({input:l,metadata:s,expandedOutput:i,expandKey:m});return g?Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:lr},Ok," "),e):e}return g?renderTextWithLongConnector({output:o,name:d,expandedOutput:i,expandKey:m,hasError:u}):Q.createElement(ee,{width:"100%"},Q.createElement(te,{color:u?jn.RED:"",wrap:"wrap"},renderTruncatedOutput({output:o,name:d,expandedOutput:i,expandKey:m})))}function renderTextWithLongConnector({output:e,name:t,expandedOutput:n,expandKey:r,hasError:s}){const{text:o,isTruncated:i,truncationMsg:a}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}),l=s?jn.RED:void 0,u=buildTreeConnectors(o,i);return Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(ee,{columnGap:1,width:"100%"},Q.createElement(te,{color:lr},u),Q.createElement(ee,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(te,{color:l,wrap:"wrap"},o))),i&&Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:lr},Ok," "),a))}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:s=!1,metadata:o,expandedOutput:i=!1}){const a="thinking…"===e,l="TODOS"===e,u="EDIT"===e,d="WRITE"===e,m="READ"===e||e.startsWith("READ[")&&e.endsWith("]"),g=!0===o?.isTasteFile,h=o?.tasteCategory,f=!0===o?.permissionDenied,y=!a&&!l&&!g,{name:w}=detectTerminal(),S="iTerm2"===w?"shift":"ctrl",E=!0===o?.isAgent,v=computeDisplayInput({input:t,isAgent:E,isShell:"SHELL"===e,expandedOutput:i}),C=!a&&v&&!g,k=o?.status,T=o?.tokensUsed||0,_="number"==typeof o?.elapsedSeconds?Math.floor(o.elapsedSeconds):0,x=m?parseReadSummaryLine(n):null,P=m?getReadToolInlineSummary({name:e,summaryMatch:x}):null,A=Boolean(n&&!g&&!E&&(!m||s)),{symbolColor:I,symbol:N}=resolveSymbol({isPending:r,hasError:s,isThinking:a,isTodos:l,output:n});return Q.createElement(ee,null,a&&Q.createElement(te,{color:I},N),Q.createElement(ee,{flexDirection:"column",marginLeft:a?1:0},Q.createElement(ee,null,renderToolHeader({isThinking:a,isTasteFile:g,tasteCategory:h,name:e,summaryMatch:x,expandedOutput:i,expandKey:S}),C&&Q.createElement(te,null," ",formatToolInput({input:v,isShell:"SHELL"===e})),renderReadToolInlineSummary(P)),E&&("running"===k||n)&&Q.createElement(ee,{columnGap:1,marginLeft:y?1:0},y&&Q.createElement(te,{color:lr},Ok," "),renderAgentStatus({agentStatus:k,hasError:s,output:n,elapsedSeconds:_,tokensUsed:T})),A&&Q.createElement(ee,{marginLeft:y?1:0},renderOutputContent({isTodos:l,isThinking:a,isEditFile:u,isWriteFile:d,metadata:o,output:n,expandedOutput:i,isPermissionDenied:f,input:t,hasError:s,name:e,expandKey:S,showTreeConnector:y})),r&&!E&&Q.createElement(ee,{columnGap:1,marginLeft:1},Q.createElement(te,{color:lr},Ok," "),Q.createElement(te,{color:jn.GRAY},"Processing…"))))}__name(computeSimilarity,"computeSimilarity"),__name(buildSimilarityMatrix,"buildSimilarityMatrix"),__name(collectSimilarityCandidates,"collectSimilarityCandidates"),__name(buildLinePairs,"buildLinePairs"),__name(groupAdjacentChanges,"groupAdjacentChanges"),__name(renderWordSegments,"renderWordSegments"),__name(renderContextLine,"renderContextLine"),__name(renderContextGroup,"renderContextGroup"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(computeDisplayInput,"computeDisplayInput"),__name(formatToolInput,"formatToolInput"),__name(parseReadSummaryLine,"parseReadSummaryLine"),__name(getReadToolInlineSummary,"getReadToolInlineSummary"),__name(renderReadToolInlineSummary,"renderReadToolInlineSummary"),__name(resolveSymbol,"resolveSymbol"),__name(renderToolHeader,"renderToolHeader"),__name(renderAgentStatus,"renderAgentStatus"),__name(getTruncatedOutputParts,"getTruncatedOutputParts"),__name(renderTruncatedOutput,"renderTruncatedOutput"),__name(renderEditFileDiff,"renderEditFileDiff"),__name(renderWriteFileContent,"renderWriteFileContent"),__name(renderOutputContent,"renderOutputContent"),__name(renderTextWithLongConnector,"renderTextWithLongConnector"),__name(ToolMessage,"ToolMessage");var t_=__name(({request:e,onResponse:n,onToggleAutoAccept:r})=>{const[s]=K(0),[o,i]=K(1);J(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&i(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const a=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, allow all edits during this session [shift+tab]",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],l=__name(e=>{const t=a.find(t=>t.value===e.value);t&&("yes-session"===t.value&&r&&r(),n(t))},"handleSelect"),u=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),d=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const n=t.basename(e.filePath),r=t.relative(process.cwd(),e.filePath);return r&&!r.startsWith("../")&&r.length<50?r:n||e.filePath}catch{return e.filePath}},"getDisplayPath"),m=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.GRAY,paddingX:1,width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(te,{bold:!0,color:jn.YELLOW},`${m()} ${"edit"===e.action?d():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&Q.createElement(ee,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:d(),marginLeft:0,startLine:o}).diffContent),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{bold:!0},"Do you want to ",u()," ",Q.createElement(te,{color:jn.CYAN},d()),"?")),Q.createElement(tt,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:s,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.CYAN},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(te,{color:t?jn.CYAN:jn.WHITE},e.includes("[shift+tab]")?Q.createElement(Q.Fragment,null,e.split("[shift+tab]")[0],Q.createElement(BracketWrap,{color:t?jn.CYAN:jn.WHITE,bold:!0},"shift+tab")):e.includes("(")?Q.createElement(Q.Fragment,null,e.split("(")[0],Q.createElement(te,{color:jn.GRAY},"(",e.split("(")[1])):e)}))},"PermissionPrompt");Ht(),Kt(),dr();var n_=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=K(0),s=[{label:"Yes",value:"yes",description:"Allow this command",scope:void 0},{label:"Yes, allow all edits during this session [shift+tab]",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],o=__name(e=>{const r=s.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),i=__name(()=>{const t=e.args?Array.isArray(e.args)?e.args.join(" "):e.args:"";return t?`${e.command} ${t}`:e.command},"getCommandDisplay");return Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.GRAY,paddingX:1,width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(te,{bold:!0,color:jn.YELLOW},"Execute Shell Command")),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{bold:!0,wrap:"wrap"},"Command Code needs to execute ",Q.createElement(te,{color:jn.CYAN},i()),".")),e.workingDirectory&&Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.GRAY},"Working directory: ",e.workingDirectory)),e.description&&Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM,italic:!0},e.description)),Q.createElement(tt,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:r,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.CYAN},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(te,{color:t?jn.CYAN:jn.WHITE},e.includes("[shift+tab]")?Q.createElement(Q.Fragment,null,e.split("[shift+tab]")[0],Q.createElement(BracketWrap,{color:t?jn.CYAN:jn.WHITE,bold:!0},"shift+tab")):e)}))},"ShellPermissionPrompt");function getKillShellRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}function getFileAction2(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function handlePermissionResponse({choice:e,resolve:t,setPendingPermission:n,respondToPrompt:r,setStatus:s,permissionMode:o,showHintMessage:i,allowedStatus:a,deniedStatus:l}){r(e);const u="no"!==e.value;t(u),n(null),u?(s(a),"standard"===o&&i("Use shift+tab to enable auto-accept")):s(l)}__name(getKillShellRequest,"getKillShellRequest"),__name(getFileAction2,"getFileAction"),__name(handlePermissionResponse,"handlePermissionResponse");var r_=V(__name(function PermissionView2({pendingPermission:e,permissionMode:t,setPendingPermission:n,setStatus:r,respondToPrompt:s,showHintMessage:o,handleToggleAutoAccept:i}){const a={resolve:e.resolve,setPendingPermission:n,respondToPrompt:s,setStatus:r,permissionMode:t,showHintMessage:o};if("shell_command"===e.toolName){const t=e.params;return Q.createElement(ee,{marginY:1},Q.createElement(n_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Shell command allowed",deniedStatus:"Shell command denied"}),onToggleAutoAccept:i}))}if("kill_shell"===e.toolName){const t=getKillShellRequest(e.params);return Q.createElement(ee,{marginY:1},Q.createElement(n_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Process termination allowed",deniedStatus:"Process termination denied"}),onToggleAutoAccept:i}))}const l=e.params,u={action:getFileAction2(e.toolName),filePath:String(l.filePath??l.file_path??l.path??l.absolutePath??l.notebook_path??"unknown"),description:`Allow ${e.toolName} operation`,oldContent:"edit_file"===e.toolName&&"string"==typeof l.oldContent?l.oldContent:void 0,newContent:"edit_file"===e.toolName&&"string"==typeof l.newContent?l.newContent:void 0};return Q.createElement(ee,{marginY:1},Q.createElement(t_,{request:u,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onToggleAutoAccept:i}))},"PermissionView"));Ht(),bC(),Ht(),Ht(),Kt();var s_="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",o_="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░███████░███████████░░░░████░░░\n░░░███░███░███░███░███░███████░░░\n░░░███░░░░░███░███░███░███░███░░░\n░░░███░███░███░███░███░███░███░░░\n░░░███████░███░███░███░███████░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n";function getMaxLineWidth(e){return Math.max(...e.split("\n").map(e=>e.length))}__name(getMaxLineWidth,"getMaxLineWidth");var i_=getMaxLineWidth(s_),a_=getMaxLineWidth(o_),l_=i_+1,c_=a_+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var u_=__name(e=>{const t=e??getTerminalWidth();return t>=l_?s_:t>=c_?o_:d_},"getResponsiveCommandLogo"),d_="⌘ CMD\n",m_="░█▀▀░█▀▄▀█░█▀▄░\n░█░░░█░▀░█░█░█░\n░▀▀▀░▀░░░▀░▀▀░░",p_=getMaxLineWidth(m_),g_=c_,h_=__name(e=>{const t=e??getTerminalWidth();return t>=l_?"full":t>=g_?"compact":"minimal"},"getHeaderLayout");tC(),Ht(),dr();var f_=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:s=0,titleColor:o=jn.GRAY,dividerChar:i="─",dividerColor:a=jn.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*s),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",g=r?` ${r}`:"",h=d.length+m.length+g.length,f=i.repeat(Math.max(0,u-h));return Q.createElement(ee,{paddingLeft:s,paddingRight:s,marginBottom:1,...l},(t||n)&&Q.createElement(te,{color:a},d),e&&Q.createElement(te,{color:o},m),Q.createElement(te,{color:a},f),r&&Q.createElement(te,{color:jn.DIM},g))},"Divider");bC(),dr(),Ht(),dr();var y_=[{type:"user",text:"I always prefer pnpm",duration:2e3},{type:"learned",text:"Learned: pnpm (95% preference)",details:".commandcode/taste/taste.md",duration:2e3},{type:"user",text:"I prefer commander over meow",duration:2e3},{type:"updated",text:"Updated: commander boosted (60% → 95%), meow adjusted (90% → 35%)",details:".commandcode/taste/cli/taste.md",duration:2e3},{type:"user",text:"I prefer TypeScript for Node CLIs",duration:2e3},{type:"learned",text:"Learned: TypeScript for CLIs (90% preference)",details:".commandcode/taste/cli/taste.md",duration:2e3}],w_=__name(({onComplete:e,onExit:t})=>{const[n,r]=K(0),[s,o]=K(!1),i=n>=y_.length;return J(()=>{if(n>=y_.length)return;if(s)return;const e=y_[n],t=setTimeout(()=>{r(e=>Math.min(e+1,y_.length))},e.duration);return()=>clearTimeout(t)},[n,s]),se((n,s)=>{""===n||s.ctrl&&"c"===n?t?t():e():s.escape?e():i?(s.return||" "===n)&&e():" "===n?o(e=>!e):s.return&&r(e=>Math.min(e+1,y_.length))}),Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{bold:!0},"Meet Your Coding Taste")),Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"Command Code learns your coding style as you work.")),Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"Here's how your preferences evolve in real-time:")),Q.createElement(ee,{flexDirection:"column",marginY:1},y_.slice(0,n).map((e,t)=>"user"===e.type?Q.createElement(ee,{key:t},Q.createElement(te,null,ke.pointer," ",e.text)):Q.createElement(ee,{key:t,flexDirection:"column",marginBottom:1,marginLeft:1},Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"⎿ "),Q.createElement(te,{color:Un.TEXT},e.text)),e.details&&Q.createElement(ee,{marginLeft:3},Q.createElement(te,{color:jn.DIM},"Saved(",e.details,")"))))),i?Q.createElement(ee,{flexDirection:"column",marginY:1},Q.createElement(ee,null,Q.createElement(te,{bold:!0,color:Un.TEXT},"Demo Complete!")),Q.createElement(ee,null,Q.createElement(te,null,"Command Code will now use these preferences to generate")),Q.createElement(ee,null,Q.createElement(te,null,"better suggestions tailored to your coding style. The")),Q.createElement(ee,null,Q.createElement(te,null,"more you code, the smarter it gets.")),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press Enter to get started →"))):Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(s?" (paused)":""))))},"TasteDemoComponent"),S_=__name(({onClose:e,onExit:t})=>{const[n,r]=K(Zv.getEvents()),[s,o]=K(0);se((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),J(()=>{const e=__name(()=>{r(Zv.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return Zv.on("new-event",e),Zv.on("cleared",t),()=>{Zv.off("new-event",e),Zv.off("cleared",t)}},[]),J(()=>{const e=__name(()=>{yC(),o(e=>e+1)},"handleResize");return process.stdout.on("resize",e),()=>{process.stdout.off("resize",e)}},[]);const i=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),a=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let s=n,o=null;if(r){s=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);o=`confidence: ${parseFloat(e).toString()}%`}const i={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:i,content:s,confidence:o}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),l=__name(e=>{const t=e.match(/^(.+?)\s*\((\d+)%\s*(?:→|->)\s*(\d+)%\)$/);if(!t)return null;const n=t[1].trim(),r=parseInt(t[2],10),s=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:s,diff:s-r}},"parsePercentageChange"),u=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),s=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:s,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails"),d=X(()=>(process.stdout.rows??24)-1,[s]);return Q.createElement(ee,{flexDirection:"column",width:"100%",height:d,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ot,{name:"vice"},Q.createElement(te,null,u_()))),Q.createElement(f_,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),Q.createElement(ee,{flexDirection:"column"},0===n.length?Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ee,null,Q.createElement(te,null,"Start using Command Code and it will begin recording your coding taste.")),Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"Your preferences, patterns, and style will appear here in real-time."))),Q.createElement(ae,{count:2}),Q.createElement(f_,{title:"DEMO",titleColor:"white",subPrefix:!0}),Q.createElement(w_,{onComplete:()=>{e()},onExit:t})):Q.createElement(ee,{flexDirection:"column"},n.map(e=>{if(i(e.type)){const{type:t,label:n,content:r,confidence:s}=a(e.message),o="moved"===t?u(e.details):null,i="upgraded"===t||"downgraded"===t?l(r):null;return Q.createElement(ee,{key:e.id,marginBottom:1},Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:Un.BADGE_BG,color:Un.BADGE_FG,bold:!0},`${Fk}${n}${Fk}`)),o?Q.createElement(te,{color:jn.DIM}," ","(",o.fullPath,")"):e.details?Q.createElement(te,{color:jn.DIM}," ","(",e.details,")"):null),Q.createElement(ee,{marginLeft:1},Q.createElement(te,{color:jn.DIM},"⎿"," "),o?Q.createElement(Q.Fragment,null,Q.createElement(te,null," ",o.category," ","package ("),Q.createElement(te,{color:jn.DIM},o.oldPath),Q.createElement(te,null," ",ke.arrowRight," ",o.newPath),Q.createElement(te,null,")")):i?Q.createElement(Q.Fragment,null,Q.createElement(te,null," ",i.text," ","("),Q.createElement(te,{color:jn.DIM},"confidence:"," "),Q.createElement(te,{color:jn.DIM},i.oldPercent,"%"),Q.createElement(te,null," ",ke.arrowRight," "),Q.createElement(te,{color:i.diff>0?jn.GREEN:jn.RED},i.newPercent,"%"),Q.createElement(te,null,")")):Q.createElement(Q.Fragment,null,Q.createElement(te,null," ",r),s&&Q.createElement(te,{color:jn.DIM}," ","(",s,")")))))}return Q.createElement(ee,{key:e.id,marginBottom:1},Q.createElement(te,{color:jn.DIM},ke.pointerSmall," ",e.message))}))))},"LearningFeedFull");function LearningView({setShowLearningFeed:e,setStaticKey:t,onExit:n}){return Q.createElement(S_,{onClose:()=>{yC(),e(!1),t(e=>e+1)},onExit:n})}__name(LearningView,"LearningView"),Ht(),dr(),Ht(),dr(),bC(),xr();var b_=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,s]=K(!1),[o,i]=K(!0);J(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();s(e)}catch(e){}finally{i(!1)}},"loadSettings")()},[]),se((t,n)=>{if(!n.return&&" "!==t)return n.escape?(yC(),void e()):void 0;a()});const a=__name(async()=>{const e=!r;s(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){s(!e)}},"toggleTasteLearning");return o?Q.createElement(ee,{key:n,borderStyle:"single",borderColor:jn.BLUE,padding:1,flexDirection:"column"},Q.createElement(te,{color:jn.BLUE,bold:!0},"Taste Settings"),Q.createElement(te,{color:jn.DIM},"Loading configuration...")):Q.createElement(ee,{key:n,borderStyle:"single",borderColor:jn.GRAY,padding:1,flexDirection:"column"},Q.createElement(te,{bold:!0},"Taste Learning"),Q.createElement(te,{color:jn.DIM},"Configure taste learning preferences for this project"),Q.createElement(ee,{marginTop:1}),Q.createElement(ee,{justifyContent:"space-between"},Q.createElement(te,null,"Taste learning",Q.createElement(te,{color:jn.DIM}," - Learn from your interactions")),Q.createElement(te,{color:r?jn.GREEN:jn.GRAY},r?"enabled":"disabled")),Q.createElement(ee,{marginTop:1}),Q.createElement(te,{color:jn.DIM},"Taste data stored in .commandcode/taste/taste.md"),Q.createElement(te,{color:jn.DIM},"Enter/Space to toggle • Esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,setShowTasteConfig:t,loadTasteStatus:n}){return Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM},"Press Esc to return to conversation")),Q.createElement(b_,{onClose:()=>t(!1),onSettingsChange:n,staticKey:e})))}__name(TasteConfigView,"TasteConfigView"),Ht(),Ht(),Kt(),fw(),bC(),dr();var E_=__name(e=>Math.ceil(e.length/4),"estimateTokens"),v_=__name(e=>e.includes("/.agents/skills/")||e.includes("\\.agents\\skills\\"),"isAgentsSkill"),C_=__name(({onClose:e})=>{const[t,n]=K([]),[r,s]=K(!0),[o,i]=K(null),[a,l]=K(0);J(()=>{__name(async()=>{try{const{global:e,project:t}=await loadAllSkillSummaries(),r=[...e.map(e=>({label:e.name,value:e.filePath,location:"user",description:e.description,filePath:e.filePath})),...t.map(e=>({label:e.name,value:e.filePath,location:"project",description:e.description,filePath:e.filePath}))];n(r)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{s(!1)}},"loadSkills")()},[]);const u=t.filter(e=>"project"===e.location),d=t.filter(e=>"user"===e.location),m=[...u,...d],g=__name(async t=>{try{await it([{file:t.filePath,line:1}]),yC(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?i(h()):i(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelectSkill");se((t,n)=>{if(n.escape)return yC(),void e();if(n.upArrow)l(e=>Math.max(0,e-1));else if(n.downArrow)l(e=>Math.min(m.length-1,e+1));else if(n.return){const e=m[a];e&&g(e)}});const h=__name(()=>{const e=process.platform;return"win32"===e?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===e?"~/.zshrc":"~/.bashrc")},"getEditorSetupMessage");return r?Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,{color:Bn,bold:!0},"Agent Skills"),Q.createElement(te,{color:jn.DIM},"Loading skills...")):o?Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,{color:jn.RED,bold:!0},"Agent Skills"),Q.createElement(te,{color:jn.DIM},o),Q.createElement(ee,{marginTop:1}),Q.createElement(te,{color:jn.DIM},"Press ",Q.createElement(te,{bold:!0},"Esc")," to close")):0===t.length?Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,{color:Bn,bold:!0},"Agent Skills"),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM},"No skills found")),Q.createElement(te,{color:jn.DIM},"Create skills in:"),Q.createElement(te,{color:jn.DIM}," ","~/",".commandcode","/","skills","/ (user)"),Q.createElement(te,{color:jn.DIM}," ","~/.agents/","skills","/ (user, .agents)"),Q.createElement(te,{color:jn.DIM}," ",".commandcode","/","skills","/ (project)"),Q.createElement(te,{color:jn.DIM}," ",".agents/","skills","/ (project, .agents)"),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press ",Q.createElement(te,{bold:!0},"Esc")," to close"))):Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ee,null,Q.createElement(te,{color:Bn,bold:!0},"Skills"," "),Q.createElement(te,{color:jn.DIM},m.length," skills")),u.length>0&&Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(ee,null,Q.createElement(te,{color:Jn,bold:!0},"Project skills"," "),Q.createElement(te,{color:Jn},"(",".commandcode","/","skills"," or .agents/","skills",")")),u.map((e,t)=>{const n=a===t,r=v_(e.filePath);return Q.createElement(ee,{key:e.value},Q.createElement(te,{color:n?jn.GREEN:jn.WHITE},e.label),r&&Q.createElement(te,{color:jn.DIM}," [.agents]"),Q.createElement(te,{color:jn.DIM}," · ~",E_(e.description)," description tokens"))})),d.length>0&&Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(ee,null,Q.createElement(te,{color:Jn,bold:!0},"User skills"," "),Q.createElement(te,{color:Jn},"(~/",".commandcode","/","skills"," or ~/.agents/","skills",")")),d.map((e,t)=>{const n=a===u.length+t,r=v_(e.filePath);return Q.createElement(ee,{key:e.value},Q.createElement(te,{color:n?jn.GREEN:jn.WHITE},e.label),r&&Q.createElement(te,{color:jn.DIM}," [.agents]"),Q.createElement(te,{color:jn.DIM}," · ~",E_(e.description)," description tokens"))})),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(te,{dimColor:!0},"Add skills: ",Q.createElement(te,{color:jn.CYAN},"cmd skills add ","<owner/repo>")),Q.createElement(te,{color:jn.DIM},"Press ",Q.createElement(te,{bold:!0},"Esc")," to close")))},"SkillsConfig");function SkillsConfigView({staticKey:e,setShowSkillsConfig:t}){return Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(C_,{onClose:()=>t(!1),staticKey:e})))}function useTerminalWidth(){const{stdout:e}=re(),[t,n]=K(()=>e.columns??80);return J(()=>{const t=__name(()=>n(e.columns??80),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}function getUsageColor(e){return e>=80?jn.RED:e>=50?jn.YELLOW:jn.GREEN}function buildProgressBar({percentage:e,width:t}){const n=Math.max(0,Math.min(100,e)),r=Math.round(n/100*t),s=t-r;return{filled:"━".repeat(r),empty:"━".repeat(s)}}__name(SkillsConfigView,"SkillsConfigView"),Ht(),Ht(),dr(),Pr(),Ht(),__name(useTerminalWidth,"useTerminalWidth"),Ht(),dr(),__name(getUsageColor,"getUsageColor"),__name(buildProgressBar,"buildProgressBar"),bC();var k_="https://commandcode.ai/settings/usage";function getLayoutSizes({terminalWidth:e}){return e<50?{labelWidth:14,progressBarWidth:Math.max(10,e-10),showTwoColumn:!1}:e<70?{labelWidth:16,progressBarWidth:Math.max(15,e-15),showTwoColumn:!1}:{labelWidth:22,progressBarWidth:Math.min(30,e-15),showTwoColumn:!0}}function getSuccessColor(e){return e>=90?jn.GREEN:e>=70?jn.YELLOW:jn.RED}function getDaysColor(e){if(null!==e)return e<3?jn.RED:e<7?jn.YELLOW:void 0}__name(getLayoutSizes,"getLayoutSizes"),__name(getSuccessColor,"getSuccessColor"),__name(getDaysColor,"getDaysColor");var T_=__name(({plan:e,status:t})=>Q.createElement(ee,{marginBottom:0},Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:jn.BLUE,color:"#f4f4f4",bold:!0},`${Fk}USAGE${Fk}`)),e&&Q.createElement(Q.Fragment,null,Q.createElement(te,null," "),Q.createElement(te,{color:jn.GRAY},e.name)),t&&Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{color:"active"===t?jn.GREEN:jn.YELLOW},t))),"UsageBadge"),__=__name(({label:e,labelWidth:t,children:n})=>Q.createElement(te,null,Q.createElement(te,{dimColor:!0},e.padEnd(t)),n),"Row"),x_=__name(({showRetry:e})=>Q.createElement(ee,{marginTop:1},e&&Q.createElement(te,{color:jn.DIM},Q.createElement(te,{bold:!0},"r")," to retry · "),Q.createElement(te,{color:jn.DIM},"Press ",Q.createElement(te,{bold:!0},"Esc")," to close")),"UsageFooter");function getCallsLabel(e){if(!e)return"Calls";const t=new Date(e);return Number.isNaN(t.getTime())?"Calls":`Calls (since ${t.toLocaleDateString("en-US",{month:"short",day:"numeric"})})`}function buildDataRows({credits:e,summary:t,sub:n}){const r=e?.freeCredits??0,s=getCallsLabel(n?.currentPeriodStart);return{left:[{label:"Purchased",value:Q.createElement(te,null,formatCredits(e?.purchasedCredits??0))},...r>0?[{label:"Free",value:Q.createElement(te,null,formatCredits(r))}]:[],{label:"Renews",value:Q.createElement(te,null,n?formatDateCompact(n.currentPeriodEnd):"—")}],right:[{label:s,value:Q.createElement(te,null,t?t.totalCount.toLocaleString():"—")},{label:"Success",value:t?Q.createElement(te,{color:getSuccessColor(t.successRate)},formatPercent(t.successRate)):Q.createElement(te,null,"—")}]}}__name(getCallsLabel,"getCallsLabel"),__name(buildDataRows,"buildDataRows");var P_=__name(({onClose:e})=>{const[t,n]=K("loading"),[r,s]=K(null),[o,i]=K(!1),a=useTerminalWidth(),l=X(()=>getLayoutSizes({terminalWidth:a}),[a]),u=Z(async e=>{try{i(!1);const t=await fetchUsageData();if(e.aborted)return;if(!t.whoami)return i(t.errors.includes("Not authenticated")),void n("error");s(t),n("loaded")}catch{if(e.aborted)return;n("error")}},[]),d=Q.useRef(null);se((r,s)=>{if(s.escape&&(yC(),e()),"r"===r&&"error"===t){n("loading"),d.current?.abort();const e=new AbortController;d.current=e,u(e.signal)}}),J(()=>{const e=new AbortController;return d.current=e,u(e.signal),()=>e.abort()},[u]);const m=r?.subscription?.data??null,g=m?getPlanInfo({planId:m.planId??""}):null;if("loading"===t)return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(T_,{plan:g,status:m?.status??null}),Q.createElement(te,{color:jn.DIM},"Loading…"),Q.createElement(x_,null));if("error"===t)return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(T_,{plan:g,status:m?.status??null}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},o?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),Q.createElement(x_,{showRetry:!o}));if(!r)return null;if(!r.credits&&!r.subscription)return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(T_,{plan:g,status:m?.status??null}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"No billing data found. Visit "),Q.createElement(Cr,{url:k_,text:"Studio",color:jn.CYAN}),Q.createElement(te,{color:jn.DIM}," for usage details.")),Q.createElement(x_,null));const h=r.credits?.credits,f=r.summary,y=g?.monthlyCredits??0,w=Math.max(0,h?.monthlyCredits??0),S=getUsagePercent({used:Math.max(0,y-w),total:y}),E=(h?.purchasedCredits??0)>0||(h?.freeCredits??0)>0||w>0,v=m?.currentPeriodEnd?getDaysRemaining(m.currentPeriodEnd):null,C=getUsageColor(S),k=buildProgressBar({percentage:S,width:l.progressBarWidth}),T=getCircleGauge(S),_=getDaysColor(v),{labelWidth:x,showTwoColumn:P}=l,A=buildDataRows({credits:h,summary:f,sub:m});return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(T_,{plan:g,status:m?.status??null})),y>0?Q.createElement(Q.Fragment,null,Q.createElement(ee,null,Q.createElement(te,{color:C},k.filled),Q.createElement(te,{color:Jn},k.empty),Q.createElement(te,{bold:!0,color:C},` ${Math.round(S)}%`)),Q.createElement(ee,null,Q.createElement(te,{color:C},T),Q.createElement(te,{bold:!0}," ",formatPercent(S)),Q.createElement(te,{color:jn.GRAY}," used"),null!==v&&Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{color:_},0===v?"expires today":`${v} day${1===v?"":"s"} left`)))):E?null:Q.createElement(te,{color:jn.DIM},"Plan details unavailable"),P?Q.createElement(ee,{flexDirection:"column",marginTop:1},Array.from({length:Math.max(A.left.length,A.right.length)}).map((e,t)=>{const n=A.left[t],r=A.right[t];return Q.createElement(ee,{key:`row-${n?.label??""}-${r?.label??""}`},Q.createElement(te,{dimColor:!0},(n?.label??"").padEnd(x)),Q.createElement(ee,{width:23},n?.value??Q.createElement(te,null)),r&&Q.createElement(Q.Fragment,null,Q.createElement(te,{dimColor:!0},r.label.padEnd(14)),r.value))})):Q.createElement(ee,{flexDirection:"column",marginTop:1},[...A.left,...A.right].map(e=>Q.createElement(__,{key:e.label,label:e.label,labelWidth:x},e.value))),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Full breakdown at "),Q.createElement(Cr,{url:k_,text:"commandcode.ai/settings/usage",color:jn.CYAN})),Q.createElement(x_,null))},"UsageOverlay");function UsageView({staticKey:e,setShowUsageOverlay:t}){return Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(P_,{onClose:()=>t(!1)})))}function countMessagesByRole({messages:e}){let t=0,n=0;for(const r of e)"user"===r.message.role&&t++,"assistant"===r.message.role&&n++;return{user:t,assistant:n}}function countToolCalls({messages:e}){let t=0,n=0;for(const r of e){const e=r.message.content;if(Array.isArray(e))for(const r of e)"tool-call"===r.type&&t++,"tool-result"===r.type&&n++}return{calls:t,results:n}}function countImages({messages:e}){let t=0;for(const n of e){const e=n.message.content;if(Array.isArray(e))for(const n of e)"image"===n.type&&t++}return t}function findCompactions({messages:e}){const t=[];for(const n of e)n.meta.isSummary&&t.push({type:"auto",timestamp:n.meta.timestamp});return t}function estimateConversationTokens({messages:e}){let t=0;for(const n of e)t+=estimateTokens(n.message);return t}function buildAutoCompactStatus({tokensUsed:e,tokenLimit:t}){const n=e/t,r=[{tier:1,threshold:Ut.TIER_1_THRESHOLD,description:`Prune to last ${Ut.TIER_1_KEEP_COUNT} tool calls`},{tier:2,threshold:Ut.TIER_2_THRESHOLD,description:`Prune to last ${Ut.TIER_2_KEEP_COUNT} tool calls`},{tier:3,threshold:Ut.TIER_3_THRESHOLD,description:"Full summarization"}];let s=0;const o=r.map(r=>{const o=Math.round(r.threshold*t),i=Math.max(0,o-e);let a="upcoming";return n>=r.threshold&&(a="passed",s=r.tier),{tier:r.tier,threshold:r.threshold,tokensAt:o,description:r.description,status:a,tokensAway:i}}),i=o.findIndex(e=>"upcoming"===e.status);return{tiers:-1!==i?o.map((e,t)=>t===i?{...e,status:"current"}:e):o,currentTier:s,keepRecentTokens:Ut.KEEP_RECENT_TOKENS}}function generateTips({percentage:e,conversationTokens:t,totalTokens:n,mcpToolCount:r,messageCount:s,imageCount:o}){const i=[];if(0===n)return i;const a=n>0?Math.round(t/n*100):0;e>=90&&i.push("Tier 3 auto-compact imminent — /compact now to control what gets summarized"),e>=80&&e<90&&i.push("Auto-compact Tier 3 triggers at 90% — /compact to free space before it kicks in");const l=a>60&&e>40;return l&&i.push(`${a}% is conversation — /compact to reclaim tokens`),r>0&&e>30&&i.push(`${r} MCP tools loaded — disconnect unused servers to save tokens`),o>0&&i.push(`${o} image${o>1?"s":""} in context — images use ~1.5k tokens each`),e>=50&&e<80&&!l&&i.push("/compact to free space · /model to switch models"),s>50&&e>40&&i.push(`${s} messages — consider starting a new session for a fresh context`),i}async function collectMemoryItems(){const e=(await discoverMemoryFiles(process.cwd())).filter(e=>e.exists),t=[];for(const n of e){const e=await loadMemoryFile(n.path),r=e?estimateTokens(e):0,s=process.env.HOME??"",o=s&&n.path.startsWith(s)?`~${n.path.slice(s.length)}`:n.path;t.push({name:n.description,tokens:r,source:o})}return t}function collectBuiltInTools(){const e=[];for(const t of jv){const n=JSON.stringify(t.input_schema??{}),r=estimateTokens(`${t.name} ${t.description??""} ${n}`);e.push({name:t.name,tokens:r})}for(const t of Bv){const n=estimateTokens(`${t.name} ${t.type}`);e.push({name:t.name,tokens:n})}return e}function collectMcpTools(){const e=getMcpConnectionManager().getConnectedServers(),t=[];for(const n of e)if("connected"===n.status)for(const e of n.tools){const r=JSON.stringify(e.inputSchema??{}),s=estimateTokens(`${e.name} ${e.description??""} ${r}`);t.push({name:e.name,tokens:s,source:n.name})}return t}async function collectSkillItems(){const e=await loadAllSkillSummaries(),t=[];for(const n of e.project){const e=estimateTokens(`${n.name} ${n.description}`);t.push({name:n.name,tokens:e,source:"project"})}for(const n of e.global){const e=estimateTokens(`${n.name} ${n.description}`);t.push({name:n.name,tokens:e,source:"user"})}return t}async function collectAgentItems(){const e=await loadAllAgents(),t=[];for(const n of e.project){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"project"})}for(const n of e.personal){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"user"})}return t}function sumTokens(e){let t=0;for(const n of e)t+=n.tokens;return t}async function analyzeContext({contextEngine:e}){const t=e.getContextTokensUsed(),n=pS,r=getConfiguredModel(),s=e.getHistory(),o=countMessagesByRole({messages:s}),i=countToolCalls({messages:s}),a=countImages({messages:s}),l=findCompactions({messages:s}),u=e.getCompactionCount(),d=Math.max(u,l.length),m=estimateConversationTokens({messages:s}),g=collectBuiltInTools(),h=collectMcpTools(),[f,y,w]=await Promise.all([collectSkillItems(),collectAgentItems(),collectMemoryItems()]),S=sumTokens(g),E=sumTokens(h),v=S+E+sumTokens(f)+sumTokens(y)+sumTokens(w),C=t>0,k=C?t:m+v,T=!C&&s.length>0,_=Math.min(k/n*100,100),x=Math.max(0,n-k),P=Math.max(0,k-m-v),A=[];if(k>0){m>0&&A.push({name:"Conversation",tokens:m,percentage:Math.round(m/k*100),detail:`${o.user+o.assistant} messages`}),P>0&&A.push({name:"System prompt",tokens:P,percentage:Math.round(P/k*100),detail:"identity, taste, skills"});const e=S+E;if(e>0){const t=g.length,n=h.length,r=n>0?`${t} built-in + ${n} MCP`:`${t} built-in`;A.push({name:"Tool schemas",tokens:e,percentage:Math.round(e/k*100),detail:r})}}A.sort((e,t)=>t.tokens-e.tokens);const I=s.length>0?s[0]?.meta.timestamp??null:null;return{tokensUsed:k,tokenLimit:n,percentage:_,tokensRemaining:x,isEstimated:T,model:r,breakdown:A,autoCompact:buildAutoCompactStatus({tokensUsed:k,tokenLimit:n}),stats:{messageCount:s.length,userMessages:o.user,assistantMessages:o.assistant,toolCalls:i.calls,toolResults:i.results,imageCount:a,compactionCount:d,sessionStartTime:I},compactions:l,tips:generateTips({percentage:_,conversationTokens:m,totalTokens:k,mcpToolCount:h.length,messageCount:s.length,imageCount:a})}}function getLayoutSizes2({terminalWidth:e}){const t=e;return t<50?{labelWidth:14,progressBarWidth:Math.max(10,t-10),breakdownBarWidth:0,showBreakdownBars:!1,showBreakdownDetail:!1}:t<70?{labelWidth:16,progressBarWidth:Math.max(15,t-15),breakdownBarWidth:8,showBreakdownBars:!0,showBreakdownDetail:!1}:{labelWidth:22,progressBarWidth:Math.min(30,t-15),breakdownBarWidth:16,showBreakdownBars:!0,showBreakdownDetail:!0}}function formatDuration(e){if(!e)return"N/A";const t=new Date(e).getTime();if(isNaN(t))return"N/A";const n=Date.now(),r=Math.round((n-t)/6e4);return r<1?"<1m":r<60?`${r}m`:`${Math.floor(r/60)}h ${r%60}m`}function ContextProgress({analysis:e,progressBarWidth:t}){const n=getUsageColor(e.percentage),r=buildProgressBar({percentage:e.percentage,width:t});return Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ee,{marginBottom:0},Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:jn.BLUE,color:"#f4f4f4",bold:!0},`${Fk}CONTEXT${Fk}`)),Q.createElement(te,null," "),Q.createElement(te,{color:jn.GRAY},e.model)),Q.createElement(ee,null,Q.createElement(te,{color:n},r.filled),Q.createElement(te,{color:Jn},r.empty),Q.createElement(te,{bold:!0,color:n},` ${e.percentage.toFixed(1)}%`)),Q.createElement(ee,null,Q.createElement(te,null,formatTokens(e.tokensUsed)),Q.createElement(te,{color:jn.GRAY},` / ${formatTokens(e.tokenLimit)}`),Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{color:n},formatTokens(e.tokensRemaining)),Q.createElement(te,{color:jn.GRAY}," remaining"),e.isEstimated&&Q.createElement(te,{color:jn.DIM}," (estimated)")),Q.createElement(CompactionDistance,{analysis:e}))}function BreakdownRow({item:e,maxTokens:t,labelWidth:n,barWidth:r,showBar:s,showDetail:o}){const i=s&&t>0?Math.round(e.tokens/t*r):0,a="█".repeat(i),l="░".repeat(r-i);return Q.createElement(ee,null,Q.createElement(te,null,e.name.padEnd(n)),s&&Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.CYAN},a),Q.createElement(te,{color:Jn},l)),Q.createElement(te,{bold:!0},` ${formatTokens(e.tokens)}`),Q.createElement(te,{color:jn.GRAY},` ${e.percentage}%`),o&&e.detail&&Q.createElement(te,{color:jn.DIM},` ${e.detail}`))}function ContextBreakdown({analysis:e,labelWidth:t,breakdownBarWidth:n,showBreakdownBars:r,showBreakdownDetail:s}){return 0===e.breakdown.length?null:Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{color:Jn,bold:!0},"Breakdown"),e.breakdown.map(o=>Q.createElement(BreakdownRow,{key:o.name,item:o,maxTokens:e.tokensUsed,labelWidth:t,barWidth:n,showBar:r,showDetail:s})))}function CompactionDistance({analysis:e}){const t=e.autoCompact.tiers.find(e=>3===e.tier);if(!t||"passed"===t.status)return null;const n=Math.round(100*t.threshold)-Math.round(e.percentage),r=n<=10?jn.RED:n<=25?jn.YELLOW:jn.GRAY;return Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"Full summarization"),Q.createElement(te,{color:r},` ${n}% away`))}function ContextSession({analysis:e,labelWidth:t}){return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Jn,bold:!0},"Session"),Q.createElement(ee,null,Q.createElement(te,null,"Messages".padEnd(t)),Q.createElement(te,{color:jn.GRAY},`${e.stats.messageCount} (${e.stats.userMessages} user, ${e.stats.assistantMessages} assistant)`)),Q.createElement(ee,null,Q.createElement(te,null,"Tool calls".padEnd(t)),Q.createElement(te,{color:jn.GRAY},`${e.stats.toolCalls} calls · ${e.stats.toolResults} results`)),e.stats.imageCount>0&&Q.createElement(ee,null,Q.createElement(te,null,"Images".padEnd(t)),Q.createElement(te,{color:jn.GRAY},`${e.stats.imageCount}`)),Q.createElement(ee,null,Q.createElement(te,null,"Duration".padEnd(t)),Q.createElement(te,{color:jn.GRAY},formatDuration(e.stats.sessionStartTime))))}function ContextTips({tips:e}){return 0===e.length?null:Q.createElement(ee,{flexDirection:"column"},e.map(e=>Q.createElement(ee,{key:e},Q.createElement(te,{color:jn.CYAN},ke.pointer),Q.createElement(te,{color:jn.GRAY}," ",e))))}function ContextHints(){return Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(ee,null,Q.createElement(te,{color:jn.GRAY},">"," "),Q.createElement(te,{color:jn.GRAY},"Auto-compact kicks in when context reaches its limit")),Q.createElement(ee,null,Q.createElement(te,{color:jn.GRAY},">"," "),Q.createElement(te,{color:jn.GRAY},"Run /compact to manually summarize your conversation and free up context")))}function ContextMessage({analysis:e}){const t=getLayoutSizes2({terminalWidth:useTerminalWidth()});return Q.createElement(ee,{flexDirection:"column",paddingTop:1},Q.createElement(ContextProgress,{analysis:e,progressBarWidth:t.progressBarWidth}),Q.createElement(ContextBreakdown,{analysis:e,labelWidth:t.labelWidth,breakdownBarWidth:t.breakdownBarWidth,showBreakdownBars:t.showBreakdownBars,showBreakdownDetail:t.showBreakdownDetail}),Q.createElement(ContextSession,{analysis:e,labelWidth:t.labelWidth}),Q.createElement(ContextTips,{tips:e.tips}),Q.createElement(ContextHints,null))}function ContextConfigView({staticKey:e,contextEngineRef:t,setShowContextView:n,setInput:r}){const[s,o]=K(null),[i,a]=K(null);return J(()=>{let e=!0;return __name(async()=>{if(t.current)try{const n=await analyzeContext({contextEngine:t.current});e&&o(n)}catch{e&&a("Failed to analyze context.")}else e&&a("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),se((e,t)=>{t.escape&&(yC(),r(""),n(!1))}),Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(ee,{flexDirection:"column",width:"100%"},i?Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Bn,bold:!0},"Context"),Q.createElement(te,{color:jn.DIM},i)):s?Q.createElement(ContextMessage,{analysis:s}):Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Bn,bold:!0},"Context"),Q.createElement(te,{color:jn.DIM},"Loading context analysis...")),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press Esc to return to conversation"))))}__name(UsageView,"UsageView"),Ht(),Ht(),Kt(),hE(),CE(),mw(),Qv(),aw(),bS(),xr(),__name(countMessagesByRole,"countMessagesByRole"),__name(countToolCalls,"countToolCalls"),__name(countImages,"countImages"),__name(findCompactions,"findCompactions"),__name(estimateConversationTokens,"estimateConversationTokens"),__name(buildAutoCompactStatus,"buildAutoCompactStatus"),__name(generateTips,"generateTips"),__name(collectMemoryItems,"collectMemoryItems"),__name(collectBuiltInTools,"collectBuiltInTools"),__name(collectMcpTools,"collectMcpTools"),__name(collectSkillItems,"collectSkillItems"),__name(collectAgentItems,"collectAgentItems"),__name(sumTokens,"sumTokens"),__name(analyzeContext,"analyzeContext"),bC(),Ht(),dr(),Rr(),__name(getLayoutSizes2,"getLayoutSizes"),__name(formatDuration,"formatDuration"),__name(ContextProgress,"ContextProgress"),__name(BreakdownRow,"BreakdownRow"),__name(ContextBreakdown,"ContextBreakdown"),__name(CompactionDistance,"CompactionDistance"),__name(ContextSession,"ContextSession"),__name(ContextTips,"ContextTips"),__name(ContextHints,"ContextHints"),__name(ContextMessage,"ContextMessage"),dr(),__name(ContextConfigView,"ContextConfigView"),Ht(),Ht(),Kt(),Ls(),CE(),mw(),Ur(),Nr(),xr();var A_="https://commandcode.ai/studio";function getVersionStatus(){try{return{current:getPackageJson().version,updateAvailable:null}}catch{return{current:"Unknown",updateAvailable:null}}}async function getAuthStatus(){try{const e=await checkAuthStatus(),t=e.userName||null;return{authenticated:e.authenticated,username:t}}catch{return{authenticated:!1,username:null}}}async function getModelStatus(){try{const e=await getSelectedModel(),t=getProviderDisplayName((await loadUserConfig()).provider||null);return{id:e,displayName:getModelDisplayName(e),provider:t}}catch{return{id:"Unknown",displayName:"Unknown",provider:"Unknown"}}}async function getSkillsAgentsStatus(){let e=0,t=0,n=0,r=0;try{const n=await loadAllSkillSummaries();e=n.global.length,t=n.project.length}catch{}try{const e=await loadAllAgents();n=e.personal.length,r=e.project.length}catch{}return{personalSkills:e,projectSkills:t,personalAgents:n,projectAgents:r}}function execGitAsync(e){return new Promise(t=>{L("git",e,{encoding:"utf8",cwd:process.cwd(),timeout:3e3},(e,n)=>{t(e?null:n.trim()||null)})})}async function getGitStatus2(){const e=await execGitAsync(["rev-parse","--abbrev-ref","HEAD"]);if(!e)return{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null};const[t,n]=await Promise.all([execGitAsync(["rev-parse","--show-toplevel"]),execGitAsync(["remote","get-url","origin"])]);return{branch:e,worktreePath:t,remoteUrl:n?formatRemoteUrl(n):null,remoteHttpUrl:n?buildHttpUrl(n):null}}function parseSSHUrl(e){const t=e.match(/@([^:]+):(.+?)(?:\.git)?$/);return t?.[1]&&t[2]?{host:t[1],path:t[2]}:null}function formatRemoteUrl(e){const t=parseSSHUrl(e);if(t)return t.path;const n=e.match(/\/\/[^/]+\/(.+?)(?:\.git)?$/);return n?.[1]?n[1]:e}function buildHttpUrl(e){const t=parseSSHUrl(e);if(t)return`https://${t.host}/${t.path}`;const n=e.match(/^ssh:\/\/[^@]+@([^/]+)\/(.+?)(?:\.git)?$/);return n?.[1]&&n[2]?`https://${n[1]}/${n[2]}`:/^https?:\/\//.test(e)?e.replace(/\.git$/,""):e}function getPrStatus(e){try{const t=getCachedPR(e);return t?{number:t.number,url:t.url,state:t.state}:null}catch{return null}}async function hasTasteMdFiles(e){if(!C(e))return!1;try{return(await U(e,{recursive:!0,encoding:"utf-8"})).some(e=>e.endsWith(".md"))}catch{return!1}}async function getTasteStatus(){const e=t.join(process.cwd(),".commandcode","taste"),n=t.join(e,"taste.md"),r=C(n),s=r||await hasTasteMdFiles(e);let o=!0;try{o=await isTasteLearningEnabled()}catch{}return{fileExists:s,filePath:r?n:e,learningEnabled:o}}function detectProxy(){const e=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy;return e?sanitizeProxyUrl(e):null}function sanitizeProxyUrl(e){try{const t=new URL(e);return t.username="",t.password="",t.toString().replace(/\/$/,"")}catch{return"[malformed proxy URL]"}}function getSystemStatus(){let e,t,n,r;try{e=yT(w.platform()),t=NT(),n=RT(),r=$T()}catch{e="Unknown",t="Unknown",n="Unknown",r="N/A"}return{cwd:process.cwd(),os:e,arch:w.arch(),shell:n,terminal:t,nodeVersion:process.version,ide:"N/A"!==r?r:null,proxy:detectProxy()}}async function gatherStatusData(){const e=safeSync(getVersionStatus,{current:"Unknown",updateAvailable:null}),t=safeSync(getSystemStatus,{cwd:process.cwd(),os:"Unknown",arch:w.arch(),shell:"Unknown",terminal:"Unknown",nodeVersion:process.version,ide:null,proxy:null}),[n,r,s,o,i]=await Promise.all([safeAsync(getAuthStatus,{authenticated:!1,username:null}),safeAsync(getModelStatus,{id:"Unknown",displayName:"Unknown",provider:"Unknown"}),safeAsync(getTasteStatus,{fileExists:!1,filePath:"",learningEnabled:!1}),safeAsync(getSkillsAgentsStatus,{personalSkills:0,projectSkills:0,personalAgents:0,projectAgents:0}),safeAsync(getGitStatus2,{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null})]),a=safeSync(()=>getPrStatus(i.branch),null);return{version:e,auth:n,model:r,git:i,pr:a,taste:s,skillsAgents:o,system:t}}function safeSync(e,t){try{return e()}catch{return t}}async function safeAsync(e,t){try{return await e()}catch{return t}}function formatCountValue(e,t){const n=e+t;return 0===n?"None":`${n} (${e} user, ${t} project)`}function formatSystemValue({system:e}){const t=[`${e.os} ${e.arch}`];return e.ide&&t.push(e.ide),!e.terminal||e.ide&&e.ide.toLowerCase().startsWith(e.terminal.toLowerCase())||t.push(e.terminal),t.push(e.shell),t.push(`Node ${e.nodeVersion}`),t.join(" · ")}__name(getVersionStatus,"getVersionStatus"),__name(getAuthStatus,"getAuthStatus"),__name(getModelStatus,"getModelStatus"),__name(getSkillsAgentsStatus,"getSkillsAgentsStatus"),__name(execGitAsync,"execGitAsync"),__name(getGitStatus2,"getGitStatus"),__name(parseSSHUrl,"parseSSHUrl"),__name(formatRemoteUrl,"formatRemoteUrl"),__name(buildHttpUrl,"buildHttpUrl"),__name(getPrStatus,"getPrStatus"),__name(hasTasteMdFiles,"hasTasteMdFiles"),__name(getTasteStatus,"getTasteStatus"),__name(detectProxy,"detectProxy"),__name(sanitizeProxyUrl,"sanitizeProxyUrl"),__name(getSystemStatus,"getSystemStatus"),__name(gatherStatusData,"gatherStatusData"),__name(safeSync,"safeSync"),__name(safeAsync,"safeAsync"),Ht(),Kt(),cv(),dr(),Pr(),__name(formatCountValue,"formatCountValue"),__name(formatSystemValue,"formatSystemValue");var I_=__name(({label:e,value:t,valueColor:n,dimValue:r})=>Q.createElement(ee,null,Q.createElement(te,{dimColor:!0},`${e}:`.padEnd(14)),r?Q.createElement(te,{dimColor:!0},t):Q.createElement(te,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=e,n=t.version.updateAvailable?`v${t.version.current} → v${t.version.updateAvailable} available`:`v${t.version.current}`,r=`${t.model.provider} · ${t.model.displayName}`,s=t.git.branch||"N/A",o=t.git.worktreePath?toRelativePath(t.git.worktreePath):null,i=t.auth.authenticated?ke.tick:ke.cross,a=t.auth.authenticated?jn.WHITE:Kn.ERROR,l=t.skillsAgents.personalSkills+t.skillsAgents.projectSkills,u=t.skillsAgents.personalAgents+t.skillsAgents.projectAgents,d=t.taste.fileExists?"Active · "+(t.taste.learningEnabled?"Learning on":"Learning off"):"No taste.md";return Q.createElement(ee,{flexDirection:"column",paddingX:0},Q.createElement(ee,null,Q.createElement(te,{color:Bn,bold:!0},"Command Code"," "),Q.createElement(te,{dimColor:!0},n)),Q.createElement(ee,null,Q.createElement(te,{dimColor:!0},"Visit "),Q.createElement(Cr,{url:A_,text:A_,color:jn.CYAN}),Q.createElement(te,{dimColor:!0}," for usage and billing")),Q.createElement(ee,{marginTop:1},Q.createElement(te,{dimColor:!0},"Account:".padEnd(14)),t.auth.authenticated&&t.auth.username?Q.createElement(Q.Fragment,null,Q.createElement(Cr,{url:`https://commandcode.ai/${t.auth.username}/`,text:t.auth.username,color:jn.CYAN}),Q.createElement(te,{color:a}," ",i)):t.auth.authenticated?Q.createElement(Q.Fragment,null,Q.createElement(te,null,"Authenticated"),Q.createElement(te,{color:a}," ",i)):Q.createElement(Q.Fragment,null,Q.createElement(te,{color:Kn.WARNING},"Not signed in"),Q.createElement(te,{color:a}," ",i),Q.createElement(te,{dimColor:!0}," — run "),Q.createElement(te,{bold:!0},"/login"))),Q.createElement(I_,{label:"Model",value:r}),Q.createElement(I_,{label:"Branch",value:s,dimValue:!t.git.branch}),o?Q.createElement(I_,{label:"Worktree",value:o}):null,t.git.remoteUrl?Q.createElement(ee,null,Q.createElement(te,{dimColor:!0},"Repository:".padEnd(14)),Q.createElement(Cr,{url:t.git.remoteHttpUrl||`https://github.com/${t.git.remoteUrl}`,text:t.git.remoteUrl,color:jn.CYAN}),t.pr?Q.createElement(Q.Fragment,null,Q.createElement(te,{dimColor:!0}," · "),Q.createElement(Cr,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?jn.CYAN:jn.GRAY}),Q.createElement(te,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null):t.pr?Q.createElement(ee,null,Q.createElement(te,{dimColor:!0},"Pull Request:".padEnd(14)),Q.createElement(Cr,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?jn.CYAN:jn.GRAY}),Q.createElement(te,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null,Q.createElement(I_,{label:"Taste",value:d,dimValue:!t.taste.fileExists}),Q.createElement(I_,{label:"Directory",value:toRelativePath(t.system.cwd)}),Q.createElement(I_,{label:"Skills",value:formatCountValue(t.skillsAgents.personalSkills,t.skillsAgents.projectSkills),dimValue:0===l}),Q.createElement(I_,{label:"Agents",value:formatCountValue(t.skillsAgents.personalAgents,t.skillsAgents.projectAgents),dimValue:0===u}),Q.createElement(I_,{label:"System",value:formatSystemValue({system:t.system})}),t.system.proxy?Q.createElement(I_,{label:"Proxy",value:t.system.proxy}):null)}function StatusConfigView({staticKey:e,setShowStatusView:t,setInput:n}){const[r,s]=K({phase:"loading"});return J(()=>{let e=!1;return gatherStatusData().then(t=>{e||s({phase:"ready",data:t})}).catch(t=>{if(e)return;const n=t instanceof Error?t.message:"Failed to gather status";s({phase:"error",message:n})}),()=>{e=!0}},[]),se((e,r)=>{r.escape&&(n(""),t(!1))}),Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(ee,{flexDirection:"column",width:"100%"},"ready"===r.phase?Q.createElement(StatusMessage,{statusData:r.data}):"error"===r.phase?Q.createElement(te,{dimColor:!0},"Could not load status: ",r.message):Q.createElement(te,{dimColor:!0},"Gathering status…"),Q.createElement(ee,{marginTop:1},Q.createElement(te,{dimColor:!0},"Press Esc to return to conversation"))))}function moveFocusDown(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?n>0?{...e,zone:"suggestions",suggestionIndex:0}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:e:"suggestions"===e.zone?e.suggestionIndex<n-1?{...e,suggestionIndex:e.suggestionIndex+1}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:{...e,zone:"input"}:e.activeDirIndex<r-1?{...e,activeDirIndex:e.activeDirIndex+1}:{...e,zone:"input"}}function moveFocusUp(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?r>0?{...e,zone:"active-dir",activeDirIndex:r-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:e:"suggestions"===e.zone?e.suggestionIndex>0?{...e,suggestionIndex:e.suggestionIndex-1}:{...e,zone:"input"}:e.activeDirIndex>0?{...e,activeDirIndex:e.activeDirIndex-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:{...e,zone:"input"}}function getAdjustedSuggestionOffset(e){const{selectedIndex:t,currentOffset:n,maxVisible:r,totalSuggestions:s}=e;return s<=r?0:t<n?t:t>=n+r?t-r+1:n}function getSuggestionBase(e){const n=resolveDirectoryPath(e),r=/[\\/]$/.test(e),s=e.replace(/\\/g,"/");if(s.endsWith("/."))return{searchDirectory:n,prefix:".",outputPrefix:`${s.slice(0,-1)}`};if(r)return{searchDirectory:n,prefix:"",outputPrefix:s};const o=s.lastIndexOf("/");return-1===o?{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:""}:{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:s.slice(0,o+1)}}function getDirectorySuggestions(e){const t=e.trim();if(!t)return[];try{const{searchDirectory:e,prefix:n,outputPrefix:r}=getSuggestionBase(t),s=n.startsWith(".")||r.includes("/.");return v.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!!s||!e.name.startsWith(".")).filter(e=>!n||e.name.toLowerCase().startsWith(n.toLowerCase())).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>`${r}${e.name}/`)}catch(e){const t=e.code;return"ENOENT"!==t&&"ENOTDIR"!==t&&console.error(`Warning: Could not list directory suggestions: ${t}`),[]}}function getFooterText(e){return"active-dir"===e.focusZone?"[Del] Remove [↑↓] Navigate [Tab] Autocomplete [Esc] Close":"[Enter] Add [↑↓] Navigate [Tab] Autocomplete [Esc] Close"}__name(StatusMessage,"StatusMessage"),__name(StatusConfigView,"StatusConfigView"),Ht(),Ht(),en(),Ht(),en(),__name(function createInitialFocusState(){return{zone:"input",suggestionIndex:0,activeDirIndex:0}},"createInitialFocusState"),__name(moveFocusDown,"moveFocusDown"),__name(moveFocusUp,"moveFocusUp"),__name(getAdjustedSuggestionOffset,"getAdjustedSuggestionOffset"),__name(getSuggestionBase,"getSuggestionBase"),__name(getDirectorySuggestions,"getDirectorySuggestions"),__name(getFooterText,"getFooterText"),dr(),gr();var N_=__name(({onClose:e})=>{const[t,n]=K(""),[r,s]=K(null),[o,i]=K([]),[a,l]=K(getAdditionalDirectories()),[u,d]=K({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,g]=K(0);J(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),g(0)},[t]),J(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{s(null)},5e3);return()=>clearTimeout(e)},[r]);const h=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(s({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):s({tone:"warning",text:t.message}):s({tone:"error",text:t.message})},"submitPath"),f=__name(e=>{if(!removeAdditionalDirectory(e))return s({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void l(getAdditionalDirectories());s({tone:"success",text:`Removed ${formatDirectoryForDisplay(e)} from directory scope`}),l(getAdditionalDirectories()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");se((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&o[u.suggestionIndex]?void h(o[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])f(a[u.activeDirIndex]);else{if(r.tab&&o.length>0){const e=o[u.suggestionIndex]??o[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),s(null)))}r.downArrow?d(e=>moveFocusDown(e,{suggestionCount:o.length,activeDirCount:a.length})):r.upArrow&&d(e=>moveFocusUp(e,{suggestionCount:o.length,activeDirCount:a.length}))}}}),J(()=>{"suggestions"===u.zone&&g(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:o.length}))},[u,o.length]),J(()=>{d(e=>"suggestions"===e.zone&&e.suggestionIndex>=o.length?{...e,zone:"input",suggestionIndex:Math.max(0,o.length-1)}:"active-dir"===e.zone&&e.activeDirIndex>=a.length?{...e,zone:"input",activeDirIndex:Math.max(0,a.length-1)}:e)},[o.length,a.length]);const y=o.slice(m,m+8),w=getFooterText({focusZone:u.zone});return Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.CYAN,paddingX:1,paddingY:0},Q.createElement(te,{bold:!0,color:jn.CYAN},"Add directory to workspace"),Q.createElement(te,{color:jn.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(te,{color:jn.GRAY},"Added directories"),0===a.length?Q.createElement(te,{color:jn.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return Q.createElement(te,{key:e,color:n?jn.YELLOW:jn.GREEN,bold:n},n?` ${ke.pointer} `:" ",formatDirectoryForDisplay(e))})),Q.createElement(ee,{marginTop:1},Q.createElement(te,{bold:!0,color:jn.WHITE},"Path")),Q.createElement(ee,null,Q.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?ke.pointer:" "} `,prefixColor:"input"===u.zone?jn.CYAN:jn.GRAY,onChange:e=>{n(e),s(null)},onSubmit:h})),!t&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:{error:jn.RED,warning:jn.YELLOW,success:jn.GREEN}[r.tone]},r.text)),o.length>0&&Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(te,{color:jn.GRAY},"Suggestions"),y.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return Q.createElement(te,{key:e,color:r?jn.CYAN:jn.GRAY,bold:r},r?` ${ke.pointer} `:" ",e)})),Q.createElement(ee,{marginTop:1},Q.createElement(BracketedText,{text:w,color:jn.DIM})))},"AddDirModal");Ht(),Ht(),Kt(),Ht(),Ht(),Kt(),Qv(),dr();var R_=__name(()=>t.join(w.homedir(),".commandcode","agents"),"getRootAgentDir"),$_=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),M_=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[s,o]=K("idle"),[i,a]=K(""),l=[...jv.map(e=>e.name),...Bv.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return o("error"),void a("Agent configuration is incomplete");o("saving");try{const r="personal"===e.location?R_():$_();await O.mkdir(r,{recursive:!0});const s=`${e.agentType}.md`,o=t.join(r,s),i=Array.from(e.selectedTools).map(e=>Wv[e]||e).join(", "),a=0===e.selectedTools.size?"none":e.selectedTools.size===l.length?'"*"':JSON.stringify(i),u=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${a}\n---\n\n${e.sysPrompt}\n`;await O.writeFile(o,u,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");se((e,t)=>{r||!t.return||"idle"!==s&&"error"!==s||u()});const d=Array.from(e.selectedTools).map(e=>Wv[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return Q.createElement(ee,{flexDirection:"column",gap:1},Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"Name:"),Q.createElement(te,{color:jn.GRAY},e.agentType)),Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"Location:"),Q.createElement(te,{color:jn.GRAY},m)),Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"Tools:"),Q.createElement(te,{color:jn.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"Description"),Q.createElement(te,{color:jn.GRAY},"(Tells ","Command Code"," when to use this agent):")),Q.createElement(te,{color:jn.GRAY},e.ccToolDefinition),Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"System Prompt:")),Q.createElement(te,{color:jn.GRAY},e.sysPrompt),!r&&Q.createElement(ee,{marginTop:1},"idle"===s&&Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.GREEN,dimColor:!0},"Press"),Q.createElement(te,{color:jn.GREEN,bold:!0},"Enter"),Q.createElement(te,{color:jn.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===s&&Q.createElement(te,{color:jn.YELLOW},"Saving agent..."),"saved"===s&&Q.createElement(te,{color:jn.GREEN},ke.tick," ",i),"error"===s&&Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.RED},ke.cross," Error: ",i),Q.createElement(te,{color:jn.GRAY},"Press Enter to retry"))))},"AgentSummary");Qv(),dr();var L_=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[s,o]=K("menu"),i=[...jv.map(e=>e.name),...Bv.map(e=>e.name)];let a=new Set;if("*"===e.tools||'"*"'===e.tools)a=new Set(i);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>Gv[e]||e);a=new Set(t)}const l={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a},u=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?o("view"):"edit"===e.value?o("edit"):"delete"===e.value&&o("delete")},"handleMenuSelect");if(se((e,n)=>{n.escape&&("menu"===s?t():o("menu")),n.return&&"view"===s&&o("menu")}),"view"===s)return Q.createElement(ee,{flexDirection:"column"},Q.createElement(M_,{config:l,onSaveComplete:()=>o("menu"),viewOnly:!0}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY},"Press Enter to go back")));if("edit"===s)return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.YELLOW},"Edit functionality coming soon..."),Q.createElement(te,{color:jn.GRAY},"Press Esc to go back"));if("delete"===s){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],s=__name(async r=>{if("confirm-delete"===r.value)try{await O.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),o("menu")}else o("menu")},"handleDeleteSelect");return Q.createElement(ee,{flexDirection:"column",gap:1},Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.RED},"Delete agent"),Q.createElement(te,{color:jn.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),Q.createElement(ee,null,Q.createElement(tt,{items:r,onSelect:s,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},` ${t}`)})))}return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.WHITE,bold:!0},e.name),Q.createElement(ee,{marginTop:1},Q.createElement(tt,{items:u,onSelect:d,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},` ${t}`)})),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");SE(),dr();var D_=__name(({handleSelect:e,createdAgentName:n})=>{const[r,s]=K([]),[o,i]=K([]),[a,l]=K([]),[u,d]=K(!0),[m,g]=K(!1),[h,f]=K(null),[y,S]=K(!1),E=__name(()=>t.join(w.homedir(),".commandcode","agents"),"getRootAgentDir"),v=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),C=__name(async(e,n)=>{try{g(!1);const r=(await O.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const s=t.join(e,r),o=await O.readFile(s,"utf-8"),{data:i,content:a}=Ne(o);let l=i.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:i.name||r.replace(".md",""),description:i.description||"",tools:l,sysPrompt:a.trim(),location:n,filePath:s}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");J(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([C(E(),"personal"),C(v(),"project")]),n=yE.map(e=>({name:e.name,description:e.description,tools:Array.isArray(e.tools)?e.tools.join(", "):e.tools,sysPrompt:e.systemPrompt,location:"personal",filePath:`__builtin__:${e.name}`}));s(e),i(t),l(n),d(!1)},"loadAgents")()},[m]);const k=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{k.push({label:e.name,value:e.filePath})}),o.forEach(e=>{k.push({label:e.name,value:e.filePath})});const T=r.length+o.length,_=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...o].find(e=>e.filePath===t.value);e&&(f(e),S(!0))}},"handleAgentSelect");if(u)return Q.createElement(te,{color:jn.GRAY},"Loading agents...");if(y&&h){const e=h.filePath.startsWith("__builtin__:");return Q.createElement(L_,{agent:h,onBack:()=>{S(!1),f(null)},setRevalidateAgent:g,isReadOnly:e})}const x=__name(({isSelected:e,label:t})=>{const n=k.find(e=>e.label===t),s=n?.value||"",i=r[0]?.filePath===s,a=o[0]?.filePath===s;return Q.createElement(ee,{flexDirection:"column"},i&&r.length>0&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY,bold:!0},"User agents")),a&&o.length>0&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY,bold:!0},"Project agents")),Q.createElement(ee,null,Q.createElement(te,{color:jn.WHITE},e?">":" "),Q.createElement(te,{color:e?jn.WHITE:jn.GRAY}," ",t)))},"CustomItemComponent");return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"Agents"),T>0?Q.createElement(te,{color:jn.GRAY}," ","(",T," agent",T>1?"s":"",")"):Q.createElement(te,{color:jn.GRAY}," (No custom agents)")),n&&Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{color:jn.GREEN,dimColor:!0},"Created agent: ",n)),Q.createElement(tt,{items:k,onSelect:_,indicatorComponent:()=>null,itemComponent:x}),a.length>0&&Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(te,{color:jn.GRAY,bold:!0},"Default agents"),a.map(e=>Q.createElement(te,{key:e.filePath,color:jn.GRAY}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(te,{color:jn.GRAY},"Create specialized subagents that Command Code can delegate to."),Q.createElement(te,{color:jn.GRAY},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Ht(),Kt(),js(),dr(),Qv(),Ht(),Ht(),Kt(),dr();var O_=__name(({onSelect:e})=>Q.createElement(tt,{items:[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},` ${t}`)}),"LocationSelector");Ht(),gr(),Kt(),Qv(),yr(),vr(),bE(),dr();var F_=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:s,onSysPromptChange:o,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=K(!1),[g,h]=K(!1),f=Z(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?o(e):t.cleanedContent&&o(t.cleanedContent))}o(e)}}else if(m(!0),t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?o(e):t.cleanedContent&&o(t.cleanedContent))}},[d,o]),y=Z(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||g){if(!g||t.isPasteEnd){if(g&&t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(h(!0),t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[g,i]);return"agentType"===e?Q.createElement(Q.Fragment,null,Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(Wv).some(e=>Le(e)===Le(t))||Object.keys(Wv).some(e=>Le(e)===Le(t)))&&Q.createElement(te,{color:jn.RED},ke.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Le(t))&&Q.createElement(te,{color:jn.RED},ke.warning," This name is reserved. Reserved names:"," ",fE.join(", "))),Q.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Le(t);Object.values(Wv).some(t=>Le(t)===e)||Object.keys(Wv).some(t=>Le(t)===e)||isReservedAgentName(e)||a()},onChange:s,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?Q.createElement(Q.Fragment,null,Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.WHITE},"Enter the system prompt for your agent:"),Q.createElement(te,{color:jn.GRAY},"Be comprehensive for best results.")),Q.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:f,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.WHITE},"When should ","Command Code"," use this agent?"),Q.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:y,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Ht(),dr();var q_=__name(({onSelect:e})=>Q.createElement(tt,{items:[{label:"1. Generate with Command Code (recommended)",value:"recommended"},{label:"2. Manual configuration",value:"manual"}],onSelect:t=>{"recommended"!==t.value&&"manual"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},` ${t}`)}),"MethodSelector");Ht(),gr(),Ht(),dr();var j_=["·","○","◇","☆","✧","☆","◇","○","⌘"],B_=[12,5,4,4,4,4,4,5,16],U_=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<B_.length;e++)if(n+=B_[e],t<n)return j_[e];const r=t-58;n=0;for(let e=0;e<U_.length;e++)if(n+=U_[e],r<n)return j_[7-e];return j_[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=__name(e=>{const n=e-(t-5);return n>=0&&n<ir.length?ir[n]:ar},"getCharColor");return Q.createElement(te,null,e.split("").map((e,t)=>Q.createElement(te,{key:t,color:r(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return Q.createElement(te,{color:t??Bn,bold:!0},`${getWaveSymbol(e)} `)}function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon"),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");var z_=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,s]=K(0),[o,i]=K(0),a=Y(n);a.current=n;const l=getTerminalWidth();J(()=>{const e=setInterval(()=>{s(e=>(e+1)%88),i(e=>{const t=a.current;if(e===t)return e;const n=t-e,r=e+Math.sign(n)*Math.max(1,Math.ceil(Math.abs(n)/10));return n>0?Math.min(r,t):Math.max(r,t)})},80);return()=>clearInterval(e)},[]);const u=r%(e.length+10),d=l>70,m=l>40&&l<=70;return Q.createElement(ee,{width:l,height:1,paddingLeft:0,marginLeft:0},Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:Qn.BG,color:Qn.FG}," "),Q.createElement(te,{backgroundColor:Qn.BG},Q.createElement(CMDIcon,{frame:4*r})),Q.createElement(ShimmerText,{text:e,offset:u,bg:Qn.BG}),Q.createElement(te,{backgroundColor:Qn.BG,color:Qn.FG}," ")),Q.createElement(te,null," "),d?Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:jn.DIM},formatTime3(t)),Q.createElement(te,{color:jn.DIM},"•"),Q.createElement(te,{color:jn.GRAY},ke.arrowDown),Q.createElement(te,{color:jn.DIM},formatToken(Math.round(o))),Q.createElement(te,{color:jn.DIM},"•"),Q.createElement(ee,{columnGap:1},Q.createElement(te,{bold:!0,color:jn.GRAY},"esc"),Q.createElement(te,{color:jn.DIM},"to interrupt"))):m?Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:jn.DIM},formatToken(Math.round(o)))):Q.createElement(Q.Fragment,null))},"Status");vr(),yr(),dr();var W_=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:s})=>{const[o,i]=K(!1),[a,l]=K(0),[u,d]=K(0);J(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=Z(()=>{0!==e.trim().length&&n()},[e,n]),g=Z(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||o){if(!o||n.isPasteEnd){if(o&&n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(i(!0),n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[o,t]);return Q.createElement(ee,{flexDirection:"column"},r?Q.createElement(ee,null,Q.createElement(CMDIcon,{frame:u}),Q.createElement(te,{color:jn.WHITE},"Generating agent from description...")):Q.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:g,onSubmit:m}),s&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.RED},`${ke.warning} ${s}`)))},"RecommendedFlow");Ht(),Qv(),dr();var G_=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[s,o]=K(!1),[i,a]=K(0),l=X(()=>[...jv.map(e=>e.name),...Bv.map(e=>e.name)],[]),u=X(()=>[{name:"All tools",tools:l},{name:"Read-only tools",tools:l.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:l.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:l.filter(e=>"shell_command"===e)},{name:"Search tools",tools:l.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:l.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].filter(e=>e.tools.length>0),[l]),d=X(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),s?(u.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-3"}),e.push({type:"toggle",value:"hide-advanced"}),e.push({type:"spacer",value:"spacer-1"}),e.push({type:"label",value:"Individual Tools:"}),l.forEach(t=>{e.push({type:"tool",value:t})})):(u.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[s,u,e,l]),m=d.map((t,n)=>{if("divider"===t.type)return{label:"─".repeat(30),value:n,type:"divider"};if("spacer"===t.type)return{label:"",value:n,type:"spacer"};if("label"===t.type)return{label:t.value,value:n,type:"label"};if("continue"===t.type)return{label:"[ Continue ]",value:n,type:"continue"};if("toggle"===t.type)return{label:"show-advanced"===t.value?"[ Show advanced options ]":"[ Hide advanced options ]",value:n,type:"toggle"};if("category"===t.type){const r=u.find(e=>e.name===t.value),s=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${s?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${Wv[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),g=m.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return se((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?g.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=g.length?0:t});else if(l.return||" "===e){const e=g[i];if(e){const i=d[e.value];if(!i)return;"continue"===i.type?r():"toggle"===i.type?(o(!s),a(0)):"category"===i.type?n(i.value):"tool"===i.type&&t(i.value)}}}),Q.createElement(ee,{flexDirection:"column"},m.map((e,t)=>{const n=g.findIndex(t=>t.value===e.value),r=-1!==n&&n===i;if("divider"===e.type)return Q.createElement(ee,{key:`divider-${t}`},Q.createElement(te,{color:jn.GRAY}," ",e.label));if("spacer"===e.type)return Q.createElement(ee,{key:`spacer-${t}`,height:1});if("label"===e.type)return Q.createElement(ee,{key:`label-${t}`},Q.createElement(te,{color:jn.GRAY}," ",e.label));const s="continue"===e.type;return Q.createElement(ee,{key:`item-${t}`},Q.createElement(te,{color:r?jn.WHITE:jn.GRAY,bold:s&&r},r?">":" "," ",e.label))}),Q.createElement(ee,{marginTop:1},e.size===l.length&&Q.createElement(te,{color:jn.GRAY},"All tools selected"),e.size>0&&e.size<l.length&&Q.createElement(te,{color:jn.GRAY},e.size," tools selected"),0===e.size&&Q.createElement(te,{color:jn.GRAY},"No tools selected")))},"ToolsSelector");Rr(),Xy(),Wy(),Ds(),ak(),xr();var H_=__name(({onComplete:e})=>{const[t,n]=K("location"),[r,s]=K(!1),[o,i]=K(null),[a,l]=K("agentType"),u=X(()=>[...jv.map(e=>e.name),...Bv.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,g]=K(d()),h=__name(t=>{n("location"),l("agentType"),g(d()),e(t)},"resetToDefaults"),f=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===a)return"Agent type (identifier)";if("sysPrompt"===a)return"System prompt";if("ccToolDefinition"===a)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),y=__name(e=>{g({...m,location:e}),n("method")},"handleLocationSelect"),w=__name(e=>{g({...m,method:e}),n("configuration")},"handleMethodSelect"),S=__name(async()=>{try{i(null),s(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced(),{token:r,oauthProvider:o}=await getOAuthCredentials({provider:e});validateOAuthToken({token:r,provider:e});const a={[Ct.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(a[Ct.OAUTH_TOKEN]=`Bearer ${r}`,o&&(a[Ct.OAUTH_PROVIDER]=o));const l=getApiBaseUrl(),u=new xy({baseUrl:l}),d=parseModelString(getConfiguredModel()).modelId,h=await u.post({headers:a,endpoint:kt.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:d}});g({...m,agentType:Le(h.agentName),sysPrompt:h.systemPrompt,ccToolDefinition:h.toolDescription}),n("tools")}catch(e){if(e instanceof _s&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")){const e=await getBillingLink({billingLink:null,setBillingLink:__name(()=>{},"setBillingLink")})??"https://commandcode.ai/settings/billing";i(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: ${e}`)}else i("An error occurred while generating the agent. Please try again.")}finally{s(!1)}},"handleRecommendedSubmit"),E=__name(()=>{g({...m,agentType:Le(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),v=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),C=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),T=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),g({...m,selectedTools:t})},"handleToggleTool"),_=__name(e=>{const t=[{name:"All tools",tools:u},{name:"Read-only tools",tools:u.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:u.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:u.filter(e=>"shell_command"===e)},{name:"Search tools",tools:u.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:u.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(m.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),g({...m,selectedTools:n})},"handleToggleCategory");return Q.createElement(ee,{flexDirection:"column",gap:1},Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.WHITE,bold:!0},"Create new agent"),Q.createElement(te,{color:jn.GRAY},f())),Q.createElement(ee,null,"location"===t&&Q.createElement(O_,{onSelect:y}),"method"===t&&Q.createElement(q_,{onSelect:w}),"configuration"===t&&"recommended"===m.method&&Q.createElement(W_,{description:m.recommendedMethodDescription,onChange:e=>g({...m,recommendedMethodDescription:e}),loading:r,errorMessage:o,onSubmit:S}),"configuration"===t&&"manual"===m.method&&Q.createElement(ee,{flexDirection:"column",gap:1},Q.createElement(F_,{step:a,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>g({...m,agentType:e}),onSysPromptChange:e=>g({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>g({...m,ccToolDefinition:e}),onAgentTypeSubmit:E,onSysPromptSubmit:v,onCCToolDefinitionSubmit:C})),"tools"===t&&Q.createElement(G_,{selectedTools:m.selectedTools,onToggleTool:T,onToggleCategory:_,onComplete:k}),"summary"===t&&Q.createElement(M_,{config:m,onSaveComplete:h})))},"AgentNew");dr();var Q_=__name(({onCancel:e})=>{const[t,n]=K(null),[r,s]=K(null),o=__name(e=>{n(e.value),s(null)},"handleSelect");return se((t,n)=>{n.escape&&e()}),Q.createElement(ee,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:jn.GRAY,borderStyle:"single",flexDirection:"column"},null===t&&Q.createElement(D_,{handleSelect:o,createdAgentName:r}),"create_new_agent"===t&&Q.createElement(H_,{onComplete:e=>{s(e),n(null)}}))},"AgentsConfig");dr(),Ht(),xr(),dr();var V_=[{label:"Compact Normal (default)",value:"default",description:"Summarize session when context limit reached."},{label:"Compact Fast",value:"fast",description:"Fast tiered compaction. Higher quality, uses more tokens."}],K_=__name(({onSelect:e,onCancel:t})=>{const[n,r]=K(null);J(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const s=__name(t=>{e(t.value)},"handleSelect");if(se((e,n)=>{n.escape&&t()}),null===n)return null;const o=V_.findIndex(e=>e.value===n);return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ee,null,Q.createElement(te,{color:Bn,bold:!0},"Select a compact mode to compact sessions")),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM},"Choose how Command Code handles automatic context compaction.")),Q.createElement(tt,{items:V_,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.CYAN},e?ke.pointer:" "),itemComponent:({isSelected:e,label:t})=>{const r=V_.find(e=>e.label===t),s=r?.value===n,o=V_.findIndex(e=>e.label===t);return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{color:e?jn.CYAN:s?jn.GREEN:jn.WHITE},` ${o+1}. ${r?.label??t}`),s&&Q.createElement(te,{color:jn.GREEN}," ",ke.tick)),Q.createElement(te,{color:jn.DIM},` ${r?.description??""}`))}}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press "),Q.createElement(te,{color:jn.DIM,bold:!0},"Esc"),Q.createElement(te,{color:jn.DIM}," to cancel")))},"CompactModeSelector");Ht(),dr(),Ht(),gr(),Kt(),yr(),kn(),Ht();var Y_=n(S(),"commandcode-images"),J_={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{C(Y_)||T(Y_,{recursive:!0});const r=J_[e.mediaType]||".png",s=`image-${t}-${Date.now()}${r}`,o=n(Y_,s),i=Buffer.from(e.data,"base64");return _(o,i),o}catch{return null}}function accumulateDelta(e,t,n){const r=n+t;return e===t||e===r?t:r&&e.startsWith(r)?t+e.slice(r.length):t&&e.startsWith(t)?t+e.slice(t.length):t+e}function useBracketedPaste(e){const{input:t,detectedContent:n,setInput:r,setDetectedImages:s,setDetectedContent:o,incrementInputKey:i}=e,a=Z((e,t)=>{s(t=>[...t,e]),r(t),i()},[s,r,i]),l=Y(!1),u=Y(""),d=Y(null),m=Y(""),g=Z(async(e,t)=>{let s=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const l=await detectDroppedImageFile(s);if(l)return void a(l,t);const u=await detectClipboardImage();if(u)return void a(u,t);let d=s;if(!d.trim()){const e=await detectClipboardText();d=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(d){if(d.length>300){const e=`[Text#${n.length+1}]`;o(e=>[...e,d]),r(t+e)}else r(t+d);i()}},[a,n.length,o,r,i]),h=Z(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(l.current){const e=u.current,t=m.current;u.current="",m.current="",l.current=!1,d.current=null,e&&await g(e,t)}},500)},[g]);return{handlePaste:Z(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return l.current&&(l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)),await g(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!l.current)return l.current=!0,m.current=n.textBeforePaste??t,u.current=n.pastedContent??n.cleanedContent,h(),!0;if(l.current&&!n.isPasteEnd)return void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current)),h(),!0;if(l.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current));const e=u.current,t=m.current;return u.current="",m.current="",l.current=!1,await g(e,t),!0}if(n.isPasteEnd&&!n.isPasteStart&&!l.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return a(e,t),!0}return!1},[t,g,h,a]),resetPasteState:Z(()=>{l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:Z(()=>l.current,[])}}__name(saveTempImage,"saveTempImage"),Mn(),Rr(),Ht(),vr(),yr(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),vr(),Ht(),Ht();var X_=["code --wait","cursor --wait","nano"],Z_=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return Z_.some(e=>n===e||n.endsWith(`/${e}`))?t.some(e=>"--wait"===e||"-w"===e)?e:`${n} --wait ${t.slice(1).join(" ")}`.trim():e}function isCommandAvailable(e){try{const t=e.split(" ")[0],n="win32"===process.platform?"where":"command -v";return $(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of X_)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var ex=class extends Error{static{__name(this,"NoEditorError")}constructor(){super("No editor configured"),this.name="NoEditorError"}};async function openInEditor2(e){let t=process.env.EDITOR||process.env.VISUAL||null;if(!t&&("true"===process.env.COMMAND_CODE_DISABLE_EDITOR_FALLBACK||(t=findFallbackEditor()),!t))throw new ex;t=ensureWaitFlag(t);const r=n(S(),`commandcode-${Date.now()}.md`);return await q(r,e),new Promise((e,n)=>{const s=t.split(" ").filter(e=>e.length>0),o=s[0],i=s.slice(1),a=M(o,[...i,r],{stdio:"inherit"});a.on("close",async()=>{try{const t=await j(r,"utf-8");await B(r),e(t.trimEnd())}catch(e){n(e)}}),a.on("error",async e=>{try{await B(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[s,o]=K(!1),[i,a]=K(null),l=Z(async()=>{if(!s){o(!0),a(null);try{const s=e.replace(/\n+$/,""),o=await openInEditor2(s);t(o),n(e=>e+1),r?.()}catch(e){a(e instanceof ex?"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/core-concepts/interactive-mode#setting-up-your-editor":`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{o(!1)}}},[e,t,r,s]),u=Z(()=>{a(null)},[]);return{isEditorOpen:s,editorError:i,handleOpenInEditor:l,clearEditorError:u}}__name(function getNoEditorMessage(){return"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/core-concepts/interactive-mode#setting-up-your-editor"},"getNoEditorMessage"),__name(openInEditor2,"openInEditor"),__name(useExternalEditor,"useExternalEditor"),Ht();var tx=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=K(null),s=Y(!1);return J(()=>{if(!t||s.current)return;let e=!0;return s.current=!0,Gk().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function loadGitignore(e){const t=at(),r=n(e,".gitignore");if(C(r))try{const e=k(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}dr(),Ht(),dr(),__name(loadGitignore,"loadGitignore");var nx=__name(({onSelectFile:e,onClose:t,searchQuery:s=""})=>{const[a,l]=K(process.cwd()),[u,d]=K([]),[m,g]=K(0),[h,f]=K(0),y=s.trim()?15:10,w=Z((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const s=n(t,e);try{const e=x(s),i=[];return e.forEach(e=>{const a=n(s,e);try{const e=P(a),n=o(t,a);if(r.ignores(n))return;i.push({name:n,path:a,isDirectory:e.isDirectory()})}catch{}}),i.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),i.slice(0,50)}catch{}}if(e.includes("/")){const s=e.split("/"),i=s.pop()||"",a=n(t,s.join("/"));try{const e=x(a),s=[],l=i.toLowerCase();return e.forEach(e=>{const u=e.toLowerCase();if(!i||u.includes(l)){const i=n(a,e);try{const e=P(i),n=o(t,i);if(r.ignores(n))return;s.push({name:n,path:i,isDirectory:e.isDirectory()})}catch{}}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),s.slice(0,50)}catch{}}const s=[],i=e.toLowerCase(),a=__name((e,l=0)=>{if(!(l>8))try{x(e).forEach(u=>{const d=n(e,u);try{const e=P(d),n=o(t,d);if(r.ignores(n))return;const m=n.toLowerCase();(u.toLowerCase().includes(i)||m.includes(i))&&s.push({name:n,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==u&&a(d,l+1)}catch(e){}})}catch(e){}},"searchRecursively");return a(t),s.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),s=n===i,o=r===i;if(s&&!o)return-1;if(!s&&o)return 1;const a=n.split("/").pop()||"",l=r.split("/").pop()||"",u=a.includes(i),d=l.includes(i);if(u&&!d)return-1;if(!u&&d)return 1;const m=e.name.split("/").length,g=t.name.split("/").length;return m!==g?m-g:e.name.localeCompare(t.name)}),s.slice(0,50)},[]),S=Z(e=>{try{const t=x(e),s=[],i=process.cwd(),a=loadGitignore(i);"/"!==e&&s.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=n(e,t);try{const e=P(r),n=o(i,r);if(a.ignores(n))return;s.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(s),g(0),f(0)}catch{}},[]);J(()=>{if(s.trim()){const e=w(s);d(e),g(0),f(0)}else S(a)},[a,S,s,w]),se((n,r)=>{if(r.escape)t();else if(r.upArrow)g(e=>{const t=Math.max(0,e-1);return t<h&&f(t),t});else if(r.downArrow)g(e=>{const t=Math.min(u.length-1,e+1);return t>=h+y&&f(t-y+1),t});else{if(r.rightArrow){const e=u[m];if(!e)return;return void(e.isDirectory&&!s.trim()&&l(i(e.path)))}if(r.return){const t=u[m];if(!t)return;return void e(t.path)}}});const E=u.slice(h,h+y);return Q.createElement(ee,{flexDirection:"column",paddingLeft:1},Q.createElement(ee,{marginBottom:1,flexDirection:"column"},Q.createElement(te,{color:jn.DIM},s.trim()?`Searching for: "${s}"`:`Files: ${a}`),Q.createElement(te,{color:jn.DIM},s.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===E.length?Q.createElement(te,{color:jn.DIM},s.trim()?`No files found matching "${s}"`:"No files found in this directory"):E.map((e,t)=>{const n=h+t,r=e.name,s=n===m;return Q.createElement(te,{key:e.path,color:s?jn.GREEN:jn.DIM},e.isDirectory?`${r}/`:r)}))},"FileList");Ht(),Kt(),Nr(),dr(),Ht(),dr();var rx=__name(({usage:e})=>{if(!e)return null;const t=Math.min(e.current/e.limit*100,100),n=Math.max(0,Math.round(90-t));if(n>20)return null;const r=__name(e=>e>=90?jn.RED:e>=70?jn.YELLOW:jn.DIM,"getColor"),s=t>=90?6:Math.round(t/100*6),o=6-s,i=ke.square.repeat(s),a=ke.squareLightShade.repeat(o),l=r(t);return Q.createElement(ee,{paddingRight:3},Q.createElement(te,{color:l},`Context left before auto-compact ${n}% `),Q.createElement(te,{color:l},i),o>0&&Q.createElement(te,{color:jn.DIM},a))},"ContextUsage");Ht(),tC(),hs(),dr();var sx=__name(()=>{const[e,t]=K("continuous learning"),[n,r]=K(!1),[s,o]=K(!1),i=Y([]),a=Y(0),l=Y(null),u=Y(!1);J(()=>{const e=__name(e=>"analyzing"===e.type?(u.current=!0,r(!0),o(!1),i.current=[],a.current=0,l.current&&(clearTimeout(l.current),l.current=null),void t(e.message)):u.current&&"analyzed"!==e.type?void i.current.push(e):"analyzed"===e.type?(u.current=!1,void(i.current.length>0?(a.current=0,n()):(r(!1),o(!1),t("continuous learning")))):void 0,"handleNewEvent"),n=__name(()=>{if(a.current>=i.current.length)return r(!1),o(!1),t("continuous learning"),void(i.current=[]);const e=i.current[a.current];t(e.message);const s="learned"===e.type||"refactored"===e.type;o(s);const u="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;l.current=setTimeout(()=>{a.current++,n()},u)},"cycleThroughNextEvent");return Zv.on("new-event",e),()=>{Zv.off("new-event",e),l.current&&clearTimeout(l.current)}},[]);const d=` ${n?ke.squareSmallFilled:ke.squareSmall} TASTE`,m=9+e.length+d.length>os;let g=e;g=truncateString(m?{text:e,maxChars:os}:{text:e,maxChars:os-d.length-9-10});const h=s?void 0:jn.DIM;return Q.createElement(ee,{paddingRight:2},!m&&Q.createElement(Q.Fragment,null,Q.createElement(BracketWrap,{color:jn.DIM},"ctrl+t"),Q.createElement(te,{color:jn.DIM}," ")),Q.createElement(te,{color:h},g),!m&&Q.createElement(te,{color:Un.TEXT},d))},"LearningFeedMini");Ht(),dr();var ox=__name(({mode:e,pendingExitKey:t})=>t?Q.createElement(te,{color:jn.DIM},"Press Ctrl+C again to exit"):"auto-accept"===e?Q.createElement(ee,{flexDirection:"row"},Q.createElement(te,{color:tr},"» accept edits on "),Q.createElement(BracketWrap,{color:jn.DIM},"shift+tab")):"plan"===e?Q.createElement(ee,{flexDirection:"row"},Q.createElement(te,{color:er},"plan mode "),Q.createElement(BracketWrap,{color:jn.DIM},"shift+tab")):Q.createElement(te,{color:jn.DIM},"? for shortcuts"),"ModeIndicator");Ht(),dr(),Pr();var ix=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?jn.DIM:nr.MERGED;return Q.createElement(Q.Fragment,null,t&&Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{color:n},"PR "),Q.createElement(Cr,{url:e.url,text:`#${e.number}`,color:n}))},"PRLinkBadge"),ax=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?Q.createElement(Q.Fragment,null,t&&Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{color:"connected"===e.type?jn.GREEN:jn.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),lx=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:s,tasteLearning:o,contextUsage:i,connectionIndicator:a,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:g,isBashMode:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E})=>{const v=e>=60;return Q.createElement(Q.Fragment,null,Q.createElement(ee,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r||l?Q.createElement(ee,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(ee,{flexDirection:"row",columnGap:0},n&&!l?Q.createElement(te,{color:Yn},t):Q.createElement(ox,{mode:r,pendingExitKey:l}),!l&&Q.createElement(ix,{prInfo:s}),!l&&Q.createElement(ax,{indicator:a})),v&&Q.createElement(ee,{flexDirection:"column",alignItems:"flex-end"},o&&Q.createElement(sx,null),i&&Q.createElement(rx,{usage:i}))):Q.createElement(Q.Fragment,null,Q.createElement(ee,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(ox,{mode:r}),v&&o&&Q.createElement(sx,null)),Q.createElement(ee,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(ee,{flexDirection:"row",columnGap:0},Q.createElement(te,{color:n?Yn:jn.DIM},t),Q.createElement(ix,{prInfo:s}),Q.createElement(ax,{indicator:a})),v&&i&&Q.createElement(rx,{usage:i}))),(u||d||g&&m)&&Q.createElement(ee,{flexDirection:"row",columnGap:1},u&&Q.createElement(te,null,ke.tick," ","Command Code"," updated:"," ",Q.createElement(te,{color:jn.DIM},"v",u.updatedFrom),Q.createElement(te,{color:jn.DIM}," ",ke.arrowRight," "),Q.createElement(te,null,"v",u.updatedTo)),!u&&d&&Q.createElement(te,{color:jn.YELLOW,dimColor:!0},ke.info," Update available:"," ",d.currentVersion," ",ke.arrowRight," ",d.latestVersion),g&&m&&Q.createElement(te,{color:jn.GREEN,dimColor:!0},ke.bullet," Provider:"," ",getProviderDisplayName(m)))),h&&Q.createElement(ee,{paddingLeft:2},Q.createElement(te,{color:jn.GREEN},"! for bash mode")),y&&f&&Q.createElement(ee,{paddingLeft:2},Q.createElement(te,{color:Bn},"SHARED: ",f.url," (copied to clipboard)")),w&&Q.createElement(ee,{paddingLeft:2},Q.createElement(te,{color:w.includes("NOT SHARED")?jn.RED:Bn},w)),S&&Q.createElement(ee,{paddingLeft:2},Q.createElement(te,{color:Bn},S)),E&&Q.createElement(ee,{paddingLeft:2},Q.createElement(te,{color:jn.YELLOW},ke.warning," ",E)))},"BottomIndicator");Ht(),vv(),hs(),dr();var cx=12,ux=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),s=Math.floor(n/36e5),o=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:s<24?`${s}h ago`:`${o}d ago`},"formatRelativeTime"),dx=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),mx=__name(e=>truncateString({text:dx(e),maxChars:ss}),"truncateMessage"),px=__name(e=>e.title?dx(e.title):mx(e.firstMessage),"getSessionSummary"),gx=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=K([]),[s,o]=K(0),[i,a]=K(0),[l,u]=K(!0),[d,m]=K(!1),[g]=K(()=>getCurrentGitBranch());J(()=>{__name(async()=>{u(!0);const e=await hv.listSessions();r(e),u(!1)},"loadSessions")()},[]);const h=d&&g?n.filter(e=>e.gitBranch===g):n;if(se((n,r)=>{if(!r.escape)return r.ctrl&&"b"===n?(m(e=>!e),o(0),void a(0)):void(r.upArrow?o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):r.downArrow?o(e=>{const t=Math.min(h.length-1,e+1);return t>=i+cx&&a(t-cx+1),t}):r.return&&h.length>0&&s<h.length&&e(h[s].id));t()}),l)return Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Q.createElement(te,{color:jn.GRAY},"Loading sessions..."));if(0===h.length)return Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Q.createElement(te,{color:jn.GRAY},d&&g?`No sessions found for branch "${g}"`:"No previous sessions found"),Q.createElement(te,{color:jn.DIM},d?"Press ctrl+b to show all branches, ESC to cancel":"Press ESC to go back"));const f=h.slice(i,i+cx);return Q.createElement(ee,{flexDirection:"column",paddingLeft:1,width:"100%"},Q.createElement(te,{color:jn.CYAN,bold:!0},"Resume Session"),Q.createElement(ee,{marginTop:1}),Q.createElement(ee,{columnGap:2,marginBottom:1},Q.createElement(ee,{width:5},Q.createElement(te,{color:jn.GRAY}," ")),Q.createElement(ee,{width:13},Q.createElement(te,{color:jn.GRAY},"Modified")),Q.createElement(ee,{width:20},Q.createElement(te,{color:jn.GRAY},"Git Branch")),Q.createElement(ee,{width:11},Q.createElement(te,{color:jn.GRAY},"# Messages")),Q.createElement(ee,null,Q.createElement(te,{color:jn.GRAY},"Summary"))),Q.createElement(ee,{columnGap:2},Q.createElement(ee,{flexDirection:"column",width:5},f.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:`sel-${n}`,color:s===n?jn.WHITE:jn.GRAY},s===n?`${ke.pointer} ${n+1}.`:` ${n+1}.`)})),Q.createElement(ee,{flexDirection:"column",width:13},f.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:`mod-${e.id}`,color:s===n?jn.WHITE:jn.GRAY},ux(e.lastModified))})),Q.createElement(ee,{flexDirection:"column",width:20},f.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:`branch-${e.id}`,color:s===n?jn.WHITE:jn.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),Q.createElement(ee,{flexDirection:"column",width:11},f.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:`msg-${e.id}`,color:s===n?jn.WHITE:jn.GRAY},e.messageCount)})),Q.createElement(ee,{flexDirection:"column"},f.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:`summary-${e.id}`,color:s===n?jn.WHITE:jn.GRAY,wrap:"truncate-end"},px(e))}))),Q.createElement(ee,{marginTop:1}),h.length>cx&&Q.createElement(te,{color:jn.DIM},"Showing ",i+1,"–",Math.min(i+cx,h.length)," ","of ",h.length,i>0?" · ↑ more":"",i+cx<h.length?" · ↓ more":""),Q.createElement(te,{color:jn.DIM},"↑↓ navigate · Enter select · ctrl+b ",d?`[branch: ${g??"unknown"}]`:"branch filter"," · ESC cancel"))},"SessionsResumeTable");function getImageHintText({selectedIndex:e,imageCount:t,inHistory:n}){return-1!==e?t>1?"← → · Delete to remove · Esc to deselect":"Delete to remove · Esc to deselect":n?"↓ · ↑ imgs":"↑ to select"}function buildImageRows({imageCount:e,rowWidth:t}){const n=[];let r=[],s=0;for(let o=0;o<e;o++){const e=`[Image #${o+1}]`.length,i=e+(r.length>0?1:0);r.length>0&&s+i>t?(n.push(r),r=[o],s=e):(r.push(o),s+=i)}return r.length>0&&n.push(r),n}function shouldSelectImageOnUpArrow({isOnFirstLine:e,imageCount:t,selectedImageIndex:n,historyIndex:r}){return e&&t>0&&-1===n&&-1===r}function nextImageIndex({currentIndex:e,imageCount:t}){return e===t-1?0:e+1}function prevImageIndex({currentIndex:e,imageCount:t}){return 0===e?t-1:e-1}function removeImageAt({images:e,index:t}){const n=e.filter((e,n)=>n!==t);return{remainingImages:n,nextSelectedIndex:n.length>0?n.length-1:-1}}function ImageLabel({index:e,isSelected:t,filePath:n,showSpaceBefore:r}){const s=`[Image #${e+1}]`,o=n?createOSC8Link(`file://${n}`,s,!1):s;return Q.createElement(te,null,r?" ":"",t?Q.createElement(te,{inverse:!0},s):o)}function ImageRowsDisplay({detectedImages:e,selectedImageIndex:t,imageTempPaths:n,termWidth:r,inHistory:s}){if(0===e.length)return null;const o=getImageHintText({selectedIndex:t,imageCount:e.length,inHistory:s}),i=Math.max(1,r-(o.length+2)),a=buildImageRows({imageCount:e.length,rowWidth:i});return Q.createElement(ee,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>Q.createElement(ee,{key:r,flexDirection:"row"},Q.createElement(ee,{flexShrink:0,marginRight:1},0===r&&Q.createElement(te,{color:jn.DIM},o)),Q.createElement(ee,{flexDirection:"row"},e.map((e,r)=>Q.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Ht(),dr(),Ht(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),LC(),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Ht(),_b();var hx=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,s]=K(null),[o,i]=K(!1),a=Y(!1),l=Y(null),[u,d]=K(!1),[m,g]=K("connected"),h=Y(null),f=Y(null),y=Z((e,t)=>{f.current&&(clearTimeout(f.current),f.current=null),g(e),d(!0),void 0!==t&&(f.current=setTimeout(()=>{d(!1)},t))},[]),w=Z(()=>{f.current&&(clearTimeout(f.current),f.current=null)},[]),S=Z(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new wb,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=h.current;if(null===r?n&&y("connected",3e3):r!==n&&(n?y("connected",2e3):y("disconnected",5e3)),h.current=n,i(n),n&&t){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),l.current=null),s(r)}else s(null)}catch{!0===h.current&&y("disconnected",5e3),h.current=!1,i(!1),s(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[y]);J(()=>{if(!t||n)return;S(!0);const e=setInterval(()=>S(!1),500);return()=>{clearInterval(e),w(),l.current?.disconnect(),l.current=null}},[t,n,S,w]);const E={visible:u,message:"connected"===m?`IDE ${ke.tick}`:"IDE disconnected",type:m};return{context:r,connected:o,refresh:S,connectionIndicator:E}},"useVSCodeContext");Ht();var fx=__name(e=>{if(!e.activeFile&&!e.selection)return"";const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:s}=e.activeFile;t.push(`File: ${n} (${r}, line ${s.line})`)}if(e.selection){const{text:n,startLine:r,endLine:s}=e.selection,o=e.activeFile?.language??"";t.push(`Selected lines ${r}-${s}:`),t.push(`\`\`\`${o}`);const i=n.replace(/```/g,"` ` `").replace(/<\/ide-context>/gi,"&lt;/ide-context&gt;");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");Ht();var yx=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),wx=__name((e,t,n)=>{const r=e?t?.selection:null;if(r)return`${r.lineCount} lines selected`;const s=e?t?.activeFile:null;if(s?.relativePath){const e=s.relativePath.split("/").pop()||"",t=n<80?15:n<120?25:40;return`In ${e.length>t?e.slice(0,t-1)+"…":e}`}return"? for shortcuts"},"getIndicatorText"),Sx=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var bx=__name(()=>Q.createElement(ee,{flexDirection:"column",paddingLeft:1},Q.createElement(te,{color:jn.DIM,bold:!0},"Available Shortcuts:"),Q.createElement(ee,{columnGap:4},Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.DIM},"! for bash mode"),Q.createElement(te,{color:jn.DIM},"/ for commands"),Q.createElement(te,{color:jn.DIM},"@ for file paths"),Q.createElement(te,{color:jn.DIM},"shift + tab to toggle auto-accept")),Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.DIM},"double tap esc to clear input"),Q.createElement(te,{color:jn.DIM},"ctrl + j / shift + ⏎ for newline"),Q.createElement(te,{color:jn.DIM},"ctrl + g to open in editor"),Q.createElement(te,{color:jn.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),Ex=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:s="Enter your input…",showFileList:i,setShowFileList:a,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:m,tasteLearning:g=!1,tasteUsage:h=!1,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:T,permissionMode:_="standard",onToggleAutoAccept:x,hintMessage:P,historyManager:A,pendingExitKey:I=null,onOverlayVisibilityChange:N,onDoubleEscapeEmpty:R,onAltP:$,isProcessing:M=!1,ideContextEnabled:L=!0})=>{const[D,O]=K(0),[F,q]=K(!1),[j,B]=K(!1),[U,z]=K(!1),[W,G]=K(!1),[H,V]=K(""),[ne,oe]=K(!1),ie=Y(0),ae=Y(0),[le,ce]=K([]),[ue,de]=K([]),[me,pe]=K(-1),[ge,he]=K(""),fe=Y(!1),ye=Y(!1),we=Y(void 0),[Se,be]=K(-1),[Ee,ve]=K(""),Ce=Y(0),{isEditorOpen:Te,editorError:_e,handleOpenInEditor:xe,clearEditorError:Pe}=useExternalEditor({input:e,setInput:n,setInputKey:O,onEditorClose:__name(()=>{fe.current=!1},"onEditorClose")}),{handlePaste:Ae,resetPasteState:Ie,isPasting:Ne}=useBracketedPaste({input:e,detectedContent:le,setInput:n,setDetectedImages:de,setDetectedContent:ce,incrementInputKey:__name(()=>O(e=>e+1),"incrementInputKey")}),{context:Re,connected:$e,refresh:Me,connectionIndicator:Le}=hx({enabled:L,paused:M}),{stdout:De}=re(),Oe=De?.columns??80,{pr:Fe}=tx();J(()=>{const e=i||W||ne;N?.(e)},[i,W,ne,N]);const qe=Z(()=>{de([]),pe(-1)},[]),je=Z(()=>{n(""),B(!1),G(!1),V(""),oe(!1),ce([]),qe(),he(""),Ie(),be(-1),ve(""),O(e=>e+1)},[n,Ie,qe]),Be=Z(()=>{fe.current=!0;const{text:t,cursor:r}=insertTextAt(e,Ce.current,"\n");n(t),we.current=r,O(e=>e+1),setTimeout(()=>{fe.current=!1},0)},[e,n]);se(async(t,r)=>{if(-1!==me&&r.leftArrow)return void pe(prevImageIndex({currentIndex:me,imageCount:ue.length}));if(-1!==me&&r.rightArrow)return void pe(nextImageIndex({currentIndex:me,imageCount:ue.length}));if(r.upArrow){if(i||W||ne)return;const t=e.indexOf("\n"),r=-1===t||Ce.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:ue.length,selectedImageIndex:me,historyIndex:Se}))return void pe(ue.length-1);if(-1!==me&&pe(-1),0!==e.length&&-1===Se&&!r)return;const s=A?.count()??0;if(0===s)return;-1===Se&&ve(e);const o=Math.min(Se+1,s-1);return void(o!==Se&&(be(o),n(A?.getAt(o)||""),O(e=>e+1)))}if(r.downArrow){if(i||W||ne)return;if(-1===Se)return;const t=e.lastIndexOf("\n");if(!(-1===t||Ce.current>t))return;const r=Se-1;return be(r),n(-1===r?Ee:A?.getAt(r)||""),void O(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void qe();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return fe.current=!0,void xe();if(getIsExpandToolShortcut(r,t))return fe.current=!0,n(e),O(e=>e+1),void setTimeout(()=>{fe.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Ne()}))return ye.current=!0,Be(),void setTimeout(()=>{ye.current=!1},0);if(r.meta&&r.backspace)return void je();if(r.meta&&"w"===t)return fe.current=!0,void je();const s=r.ctrl&&"v"===t||Sx.includes(t),o=r.meta&&"v"===t;if(s||o){if(s&&"darwin"===process.platform){const t=e;fe.current=!0;const r=await detectClipboardImage();return r&&(de(e=>[...e,r]),n(t),O(e=>e+1)),void(fe.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return z(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==me&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:ue,index:me});return de([...e]),void pe(t)}if(r.escape){if(-1!==me)return void pe(-1);if(W)return;if(ne)return oe(!1),n(ge),void O(e=>e+1);const t=Date.now();return t-ie.current<500?(e.length>0?je():R?.(),ie.current=0,ae.current=0):(ie.current=t,F||j||(ae.current=t)),q(!1),void B(!1)}F&&(r.backspace||r.delete)&&0===e.length&&q(!1)}});const Ue=Z(async t=>{if(Te)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void $?.();const s=processBracketedPaste(t);if((s.isPasteStart||s.isPasteEnd||Ne())&&await Ae(t))return;if(fe.current)return void(fe.current=!1);-1!==Se&&be(-1);const o=1===t.length,l=t.slice(-1);if(o){if("?"===l&&!F)return q(!0),n(""),void O(e=>e+1);if("!"===l&&!j)return q(!1),B(!0),n(""),void O(e=>e+1)}if("/"!==l||W||"/"!==t||(G(!0),V("")),W&&!t.startsWith("/")&&(G(!1),V("")),W&&t.startsWith("/")){const e=t.substring(1);e.includes(" ")?(G(!1),V("")):V(e)}"@"!==l||i||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(a(!0),u(""));const d=t.lastIndexOf("@");if(t.length<e.length&&-1!==d&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(d+1),n=!e.includes(" "),r=d>0?t[d-1]:"";n&&isPrecededByWhitespace(r)&&(a(!0),u(e))}if(i)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)a(!1),u("");else{const n=t.substring(e+1);u(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);u(e),a(!1)}else u(n)}}F&&(t!==e||t.length<e.length)&&q(!1),_e&&Pe(),0===t.length&&(B(!1),G(!1),V(""),oe(!1),ce([]),u(""),he(""),Ie()),n(t)},[F,e,n,i,a,W,j,ue,Se,Ae,Ie,$,_e,Pe,Te]),ze=Z(async()=>{if(Me(),ae.current=0,F)return void q(!1);let n=e.trim();if(!j&&n.startsWith("/")&&d&&"handled"===(await d(n)).status)return A?.add(n),B(!1),G(!1),V(""),qe(),ce([]),be(-1),void ve("");be(-1),ve("");let r=[];const s=ue.length>0,o=le.length>0;if(!j&&s&&(r=[...ue]),!j&&o){let e=n;le.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}n.length>0&&A?.add(n),t({input:n,role:j?"bash":"user",images:r,ideContext:Re?fx(Re):void 0}),B(!1),G(!1),V(""),qe(),ce([])},[t,d,F,e,j,ue,le,A,Me,qe]),We=Z(t=>{const r=o(process.cwd(),t);let s;if(i&&""!==l){const t=e.lastIndexOf("@");s=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else s=`${e}${r} `;n(s),a(!1),u(""),O(e=>e+1)},[n,a,e,i,l,u]),Ge=Z(()=>{a(!1),u("")},[a,u]),He=Z(t=>{if("/resume"===t)A?.add(t),be(-1),ve(""),he(e),G(!1),V(""),oe(!0),n(""),O(e=>e+1);else{const e=Object.values(pT).includes(t);G(!1),V(""),e?(A?.add(t),be(-1),ve(""),n(""),O(e=>e+1),d&&d(t)):(n(t+" "),O(e=>e+1))}},[d,n,e,A]),Qe=Z(e=>{G(!1),V(""),n(e+" "),O(e=>e+1)},[n]),Ve=Z(()=>{G(!1),V(""),n(""),be(-1),ve(""),O(e=>e+1)},[n]),Ke=Z(e=>{oe(!1),n(""),he(""),be(-1),ve(""),O(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),Ye=Z(()=>{oe(!1),n(ge),be(-1),ve(""),O(e=>e+1)},[ge,n]),Je=Z(e=>{Ce.current=e,we.current=void 0},[]),Xe=X(()=>{const t=Fe&&("OPEN"===Fe.state||"MERGED"===Fe.state);return"auto-accept"===_||"plan"===_||$e||t?!F&&!ne:!F&&0===e.length&&!j&&!ne},[F,e,j,ne,_,$e,Fe]),Ze=Y(new Map),et=X(()=>ue.map((e,t)=>{if(Ze.current.has(e))return Ze.current.get(e)??null;const n=saveTempImage(e,t+1);return Ze.current.set(e,n),n}),[ue]),tt=__name(()=>F||i||W||ne||U?0:Xe||I||j?3:4,"getBottomMargin");return Q.createElement(ee,{width:"100%",flexDirection:"column",marginBottom:tt()},!ne&&Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(ImageRowsDisplay,{detectedImages:ue,selectedImageIndex:me,imageTempPaths:et,termWidth:Oe,inHistory:-1!==Se}),Q.createElement(te,{color:j?jn.GREEN:jn.GRAY},ke.line.repeat(Oe)),Q.createElement(TextInput,{key:D,value:e,placeholder:Te?"Save and close the editor to continue...":s,onChange:Ue,onSubmit:()=>{if(!ye.current)return Date.now()-ae.current<100?(ae.current=0,void Be()):void(i||W||ne||Te||ze());ye.current=!1},showCursor:!Te&&r&&-1===me,onCursorChange:Je,initialCursor:we.current,prefix:`${j?"!":ke.pointer} `,prefixColor:j?jn.GREEN:jn.WHITE}),Q.createElement(te,{color:j?jn.GREEN:jn.GRAY},ke.line.repeat(Oe))),F&&Q.createElement(bx,null),U&&Q.createElement(ee,{paddingTop:1},Q.createElement(te,{color:jn.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&Q.createElement(nx,{onSelectFile:We,onClose:Ge,searchQuery:l}),W&&Q.createElement(fT,{onSelectCommand:He,onInsertCommand:Qe,onClose:Ve,searchQuery:H}),ne&&Q.createElement(gx,{onSelectSession:Ke,onClose:Ye}),!W&&(Xe||I)&&Q.createElement(lx,{termWidth:Oe,indicatorText:wx($e,Re,Oe),isIDEIndicator:yx($e,Re),permissionMode:_,prInfo:Fe,tasteLearning:g,contextUsage:m,connectionIndicator:Le,pendingExitKey:I,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:T,isBashMode:j,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E}),_e&&Q.createElement(ee,{paddingLeft:1,flexDirection:"column"},Q.createElement(te,{color:jn.YELLOW},_e)))},"InputBox");Ht(),hs(),dr();var vx=__name(({messages:e})=>0===e.length?null:Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ee,{marginBottom:0},Q.createElement(te,{color:Wn,inverse:!0},` Queued (${e.length}) `)),e.map((e,t)=>Q.createElement(ee,{key:t},Q.createElement(te,{color:jn.DIM},ke.pointerSmall," "),Q.createElement(te,{color:jn.DIM},truncateString({text:e.displayMessage??e.input,maxChars:80}))))),"QueuedMessages"),Cx=Q.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:s,setInput:o,onSubmit:i,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:g=0,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,showProviderInfo:x,permissionMode:P,onToggleAutoAccept:A,hintMessage:I,historyManager:N,pendingExitKey:R,onResetPendingExitKey:$,onDoubleEscapeEmpty:M,retryAttempt:L,onAltP:D})=>{const[O,F]=K(0),q=Y(s);return J(()=>{R&&s!==q.current&&s.length>0&&$?.(),q.current=s},[s,R,$]),J(()=>{if(!t)return void F(0);const e=setInterval(()=>{F(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),Q.createElement(ee,{flexDirection:"column"},Q.createElement(vx,{messages:e}),Q.createElement(ee,{flexDirection:"row",justifyContent:"space-between"},Q.createElement(ee,{flexDirection:"column"},(t||n.isExecuting)&&null===L&&Q.createElement(z_,{tokens:g,timeElapsed:O,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),I&&Q.createElement(ee,{marginLeft:1},Q.createElement(te,{color:jn.DIM}," ","⎿"," ","Tip: ",I)))),Q.createElement(Ex,{input:s,setInput:o,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,showProviderInfo:x,permissionMode:P,onToggleAutoAccept:A,hintMessage:I,historyManager:N,pendingExitKey:!R||t||n.isExecuting?null:R,onDoubleEscapeEmpty:M,onAltP:D,isProcessing:t}))});Ht(),xC(),RC(),Ar(),Nr();var kx=__name(({onComplete:e,onCancel:t})=>{const[n,r]=K(!1),[s,o]=K(""),{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:g}=useAuthFlow({onSuccess:__name((t,n)=>{const s=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";o(s),isInternalTeamFlagEnforced()?r(!0):e(!0,s?`Logged in as ${s}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return se((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,s?`Logged in as ${s}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");g()}}),n?Q.createElement(kr,{onSuccess:()=>{e(!0,s?`Logged in as ${s} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,s?`Logged in as ${s}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,s?`Logged in as ${s}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):Q.createElement(AC,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");async function discoverOAuthMetadata(e){const t=new m(e),n=`${t.protocol}//${t.host}`;try{const e=`${n}/.well-known/oauth-authorization-server`,t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const e=await t.json();if(e.authorization_endpoint&&e.token_endpoint)return{authorizationEndpoint:e.authorization_endpoint,tokenEndpoint:e.token_endpoint,registrationEndpoint:e.registration_endpoint,scopes:e.scopes_supported}}}catch(e){dlog("[MCP] OAuth discovery endpoint not available",e)}try{const e=`${n}/.well-known/openid-configuration`,t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const e=await t.json();if(e.authorization_endpoint&&e.token_endpoint)return{authorizationEndpoint:e.authorization_endpoint,tokenEndpoint:e.token_endpoint,registrationEndpoint:e.registration_endpoint,scopes:e.scopes_supported}}}catch(e){dlog("[MCP] OIDC discovery not available",e)}return null}async function checkServerAuthRequirements(e){try{const t=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",method:"initialize",id:0,params:{protocolVersion:Ub,capabilities:{},clientInfo:zb}})});return 401===t.status||403===t.status?{requiresAuth:!0,metadata:await discoverOAuthMetadata(e)||void 0}:{requiresAuth:!1}}catch(e){return{requiresAuth:!1,error:`Server unreachable: ${e instanceof Error?e.message:String(e)}`}}}async function registerOAuthClient({registrationEndpoint:e,clientName:t,redirectUris:n}){try{const r=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:t,redirect_uris:n,token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"]})});if(r.ok){const e=await r.json();return{clientId:e.client_id,clientSecret:e.client_secret}}}catch(e){dlog("[MCP] OAuth client registration failed",e)}return null}Ht(),Ht(),eE(),Qb(),sE(),tE(),oE(),gE(),hE(),wE(),Ht(),hE(),wE(),Zb(),pE(),Ht(),lE(),Qb(),In(),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient"),dr();var Tx=__name(({onClose:e})=>{const[t,n]=K([]),[r,s]=K(!0),[o,i]=K(0),[a,l]=K("list"),[u,d]=K(null),m=Z(async()=>{s(!0);try{const e=await listMcpServers(),t=getMcpConnectionManager().getConnectedServers(),r=await Promise.all(e.map(async e=>{const n=t.find(t=>t.name===e.name);let r,s,o="disconnected";return!1===e.config.enabled?o="disabled":n&&"connected"===n.status?(o="connected",r=n.tools.length):n&&"error"===n.status?(o="error",s=n.error):e.config.oauth&&(o=await hasTokens(e.name)?"authenticated":"requires_auth"),{name:e.name,config:e.config,scope:e.scope,status:o,toolCount:r,error:s}}));n(r)}catch{}finally{s(!1)}},[]);J(()=>{m()},[m]);const g=X(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),h=g[o]??null;se((t,n)=>{if(n.ctrl&&"c"===t)e();else if(n.escape)"actions"===a||"confirm-remove"===a?(l("list"),d(null)):e();else if("list"===a){if(n.upArrow&&(i(e=>Math.max(0,e-1)),d(null)),n.downArrow){if(0===g.length)return;const e=Math.max(0,g.length-1);i(t=>Math.min(e,t+1)),d(null)}n.return&&h&&(l("actions"),d(null))}});const f=__name(e=>{switch(e){case"connected":return Q.createElement(te,{color:jn.GREEN},ke.tick);case"authenticated":return Q.createElement(te,{color:jn.CYAN},ke.tick);case"requires_auth":return Q.createElement(te,{color:jn.YELLOW},ke.warning);case"error":return Q.createElement(te,{color:jn.RED},ke.cross);default:return Q.createElement(te,{color:jn.GRAY},ke.circle)}},"getStatusIcon"),y=__name(e=>{switch(e.status){case"connected":return"connected"+(void 0!==e.toolCount?` · ${e.toolCount} tools`:"");case"authenticated":return"authenticated · not connected";case"requires_auth":return"requires authentication";case"error":return e.error||"error";case"disabled":return"disabled";default:return"not connected"}},"getStatusText"),w=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),S=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),E=__name(async e=>{if(h)if("back"!==e.value)if("connected"!==e.value)if("authenticated"!==e.value)if("connect"!==e.value)if("auth"!==e.value)if("remove"!==e.value)if("disable"!==e.value)if("enable"!==e.value);else{d({text:`Enabling ${h.name}...`,color:jn.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:h.name,enabled:!0,scope:h.scope}))return void d({text:`${ke.cross} Failed to enable ${h.name}, server may no longer exist in ${h.scope} scope`,color:jn.YELLOW});await m(),d({text:`${ke.tick} Enabled ${h.name}`,color:jn.GREEN})}catch(e){d({text:`${ke.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:jn.RED})}}else{d({text:`Disabling ${h.name}...`,color:jn.CYAN,loading:!0});try{const e=getMcpConnectionManager();if(!await updateMcpServerStatus({name:h.name,enabled:!1,scope:h.scope}))return void d({text:`${ke.cross} Failed to disable ${h.name}, server may no longer exist in ${h.scope} scope`,color:jn.YELLOW});await e.disconnectServer(h.name),await m(),d({text:`${ke.tick} Disabled ${h.name}`,color:jn.GREEN})}catch(e){d({text:`${ke.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:jn.RED})}}else l("confirm-remove");else{if(!h.config.oauth)return void d({text:"No OAuth configured for this server",color:jn.YELLOW});d({text:`Authenticating ${h.name}...`,color:jn.CYAN,loading:!0});try{const e={authorizationUrl:h.config.oauth.authorizationUrl,tokenUrl:h.config.oauth.tokenUrl,clientId:h.config.oauth.clientId,clientSecret:h.config.oauth.clientSecret,scopes:h.config.oauth.scopes},t=await performOAuthFlow(h.name,e,{onStatus:__name(()=>{},"onStatus")});if(t.success){d({text:`${ke.tick} Authenticated with ${h.name}`,color:jn.GREEN});try{const e=getMcpConnectionManager();await e.ensureServerConnection(h.name)}catch{}await m()}else d({text:`${ke.cross} Auth failed: ${t.error}`,color:jn.RED})}catch(e){d({text:`${ke.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:jn.RED})}}else{d({text:`Connecting ${h.name}...`,color:jn.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.ensureServerConnection(h.name),d({text:`${ke.tick} Connected to ${h.name}`,color:jn.GREEN}),await m()}catch(e){d({text:`${ke.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:jn.RED})}}else d({text:"Already authenticated",color:jn.GREEN});else d({text:"Already connected",color:jn.GREEN});else l("list")},"handleActionSelect"),v=__name(async e=>{if(h)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===h.status&&await e.disconnectServer(h.name),await removeMcpServer({name:h.name,scope:h.scope}),l("list"),await m(),i(e=>Math.min(e,Math.max(0,g.length-2)))}catch(e){d({text:`${ke.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:jn.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Bn,bold:!0},"Manage MCP servers"),Q.createElement(te,{color:jn.DIM},"Loading..."));if("confirm-remove"===a&&h)return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.RED,bold:!0},"Remove ",h.name,"?"),Q.createElement(te,{color:jn.DIM},"This will remove the server from ",h.scope," config."),Q.createElement(ee,{marginTop:1},Q.createElement(tt,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:v,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY}," ",t)})),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&h){const e=[],t="disabled"===h.status,n="connected"===h.status,r="authenticated"===h.status||n;return t&&e.push({label:"Enable",value:"enable"}),!t&&n&&e.push({label:"Connected",value:"connected"}),t||n||e.push({label:"Connect",value:"connect"}),!t&&h.config.oauth&&r&&e.push({label:"Authenticated",value:"authenticated"}),t||!h.config.oauth||r||e.push({label:"Authenticate",value:"auth"}),t||e.push({label:"Disable",value:"disable"}),e.push({label:"Remove",value:"remove"}),e.push({label:"Back",value:"back"}),Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Bn,bold:!0},h.name),Q.createElement(ee,null,f(h.status),Q.createElement(te,{color:jn.DIM}," ",y(h))),Q.createElement(ee,{marginTop:1},Q.createElement(tt,{items:e,onSelect:E,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY}," ",t)})),u&&Q.createElement(ee,{marginTop:1},u.loading&&Q.createElement(te,{color:u.color},Q.createElement(Fe,{type:"dots"})," "),Q.createElement(te,{color:u.color},u.text)),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"↑↓ navigate · Enter to select · Esc to go back")))}let C=null;return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Bn,bold:!0},"Manage MCP servers"),Q.createElement(te,{color:jn.DIM},t.length," ",1===t.length?"server":"servers"),0===t.length?Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(te,{color:jn.DIM},"No MCP servers configured."),Q.createElement(te,{color:jn.DIM},'Use "cmd mcp add" to add a server.'),Q.createElement(te,{color:jn.DIM},"Docs: https://commandcode.ai/docs/mcp")):Q.createElement(ee,{marginTop:1,flexDirection:"column"},g.map((e,t)=>{const n=e.scope!==C;C=e.scope;const r=t===o;return Q.createElement(Q.Fragment,{key:e.name},n&&Q.createElement(ee,{marginTop:0===t?0:1},Q.createElement(te,{bold:!0},w(e.scope)),Q.createElement(te,{color:jn.DIM}," (",S(e.scope),")")),Q.createElement(ee,{paddingLeft:1},Q.createElement(te,{color:r?jn.WHITE:jn.GRAY},r?"› ":" "),Q.createElement(te,{color:r?jn.WHITE:void 0,bold:r},e.name),Q.createElement(te,{color:jn.DIM}," · "),f(e.status),Q.createElement(te,{color:"connected"===e.status?jn.GREEN:"authenticated"===e.status?jn.CYAN:"requires_auth"===e.status?jn.YELLOW:jn.GRAY}," ",y(e))))})),u&&Q.createElement(ee,{marginTop:1},u.loading&&Q.createElement(te,{color:u.color},Q.createElement(Fe,{type:"dots"})," "),Q.createElement(te,{color:u.color},u.text)),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Ht(),aw(),Kt(),_n(),dr();var _x=__name(({onClose:e})=>{const[t,n]=K([]),[r,s]=K(0),[o,i]=K(!0),[a,l]=K(null);J(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),i(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),i(!1)}},"loadMemoryFiles")()},[]);const u=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(se((t,n)=>{n.escape?e():n.upArrow?s(e=>Math.max(0,e-1)):n.downArrow?s(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&u(d[r]),"1"===t&&d[0]&&u(d[0]),"2"===t&&d[1]&&u(d[1]))}),o)return Q.createElement(ee,{paddingLeft:1,paddingTop:1},Q.createElement(te,{color:jn.DIM},"Loading memory files..."));if(a)return Q.createElement(ee,{paddingLeft:1,paddingTop:1},Q.createElement(te,{color:jn.RED},ke.cross," ",a));const m=d.map((e,t)=>{const n=t+1;let r="",s="";return"project"===e.type?(r=`${n}. Project memory`,s=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,s=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:s}});return Q.createElement(ee,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:jn.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},Q.createElement(ee,null,Q.createElement(te,{color:jn.WHITE,bold:!0},"Select memory to edit:")),Q.createElement(ee,{columnGap:4,marginTop:1},Q.createElement(ee,{flexDirection:"column"},m.map((e,t)=>Q.createElement(te,{key:t,color:r===t?jn.WHITE:jn.DIM},r===t?`${wn} `:" ",e.label))),Q.createElement(ee,{flexDirection:"column"},m.map((e,t)=>Q.createElement(te,{key:t,color:r===t?jn.WHITE:jn.DIM},e.description)))))},"MemorySelector");Ht(),Kt(),dv(),Ur(),Nr(),dr(),Ht(),dr();var xx=lt()?"⠶":"#";function AssistantMessage({content:e}){return Q.createElement(ee,null,Q.createElement(te,{color:Zn},xx),Q.createElement(ee,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(Markdown,null,e)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let s=jn.GREEN,o=ke.tick,i="default",a=t||"(No output)";n&&(s=jn.YELLOW,o=ke.arrowRight,i=jn.YELLOW,a="Executing…"),r&&(s=jn.RED,o=ke.cross,i=jn.RED);const l=X(()=>buildTreeConnectors(a),[a]);return Q.createElement(ee,null,Q.createElement(te,{color:s},o),Q.createElement(ee,{flexDirection:"column",marginLeft:1},Q.createElement(ee,null,Q.createElement(te,{color:jn.GRAY},"$ "),Q.createElement(te,{color:s,bold:!0},e)),Q.createElement(ee,{columnGap:1,marginLeft:1},Q.createElement(te,{color:lr},l),Q.createElement(te,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?jn.YELLOW:void 0,s=X(()=>buildTreeConnectors(e),[e]);return Q.createElement(ee,{flexDirection:"column",marginBottom:0,marginTop:-1},Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:lr},s),Q.createElement(ee,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(te,{color:r},e))),t&&Q.createElement(ee,{marginLeft:3},Q.createElement(te,{color:jn.DIM},"See ",t)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return Q.createElement(ee,null,Q.createElement(te,{color:jn.RED},t?ke.pointer:ke.warning),Q.createElement(ee,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?Q.createElement(te,{color:jn.RED,wrap:"wrap"},e):Q.createElement(Markdown,{color:jn.RED},e)))}function IDEStatusMessage({status:e,ide:t,details:n}){return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,"connected"===e&&Q.createElement(te,null,Q.createElement(te,{color:jn.GREEN},ke.tick),Q.createElement(te,null," Connected to "),Q.createElement(te,{color:jn.CYAN},t)),"installed"===e&&Q.createElement(te,null,Q.createElement(te,{color:jn.GREEN},ke.tick),Q.createElement(te,null," Installed for "),Q.createElement(te,{color:jn.CYAN},t)),"needs_reload"===e&&Q.createElement(te,null,Q.createElement(te,{color:jn.YELLOW},ke.circle),Q.createElement(te,null," "),Q.createElement(te,{color:jn.CYAN},t),Q.createElement(te,null," extension needs reload")),"failed"===e&&Q.createElement(te,null,Q.createElement(te,{color:jn.RED},ke.cross),Q.createElement(te,null," Install failed")),"not_in_ide"===e&&Q.createElement(te,null,Q.createElement(te,{color:jn.YELLOW},ke.circle),Q.createElement(te,null," Not in IDE"))),n?.map((e,t)=>Q.createElement(te,{key:t,color:jn.DIM}," ",e)))}function AutoCompactMessage({content:e}){return Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},ke.info),Q.createElement(ee,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(te,{color:jn.DIM},e)))}function TasteSkipMessage(){return Q.createElement(ee,null,Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:Un.BADGE_BG,color:Un.BADGE_FG,bold:!0},qk)),Q.createElement(te,{color:jn.DIM}," Skipped. Run "),Q.createElement(te,{color:sr.CODE},"/learn-taste"),Q.createElement(te,{color:jn.DIM}," or "),Q.createElement(te,{color:sr.CODE},"cmd learn-taste"),Q.createElement(te,{color:jn.DIM}," anytime."))}function InfoMessage({content:e,metadata:t}){return t?.isTasteSkip?Q.createElement(TasteSkipMessage,null):t?.isAutoCompact?Q.createElement(AutoCompactMessage,{content:e}):Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},ke.info),Q.createElement(ee,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(te,{color:jn.DIM},e)))}__name(AssistantMessage,"AssistantMessage"),Ht(),dr(),__name(BashMessage,"BashMessage"),Ht(),dr(),__name(CommandResultMessage,"CommandResultMessage"),Ht(),dr(),__name(ErrorMessage,"ErrorMessage"),Ht(),dr(),__name(IDEStatusMessage,"IDEStatusMessage"),Ht(),dr(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(InfoMessage,"InfoMessage"),Ht(),Ht(),Kt();dr(),jb(),Ht(),Ur();var Px="cmd";function getBinNames(){const e=getPackageJson();return e.bin&&"object"==typeof e.bin?Object.keys(e.bin):e.bin&&"string"==typeof e.bin?[e.name]:[Px]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||Px;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||Px}catch{return Px}}function HelpMessage(){const e=getInvokedCommandName(),t=X(()=>$b.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return Q.createElement(ee,{flexDirection:"column",paddingY:1},Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ee,null,Q.createElement(te,{bold:!0},"Command Code"),Q.createElement(te,{color:jn.GRAY}," v","0.19.0")),Q.createElement(te,{color:jn.GRAY},Ab)),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Usage"),Q.createElement(ee,{paddingLeft:2},Q.createElement(te,null,e," <command> [options]"))),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Options"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Rb.map(t=>Q.createElement(ee,{key:t.key},Q.createElement(te,null,t.key.replace(/^cmd/,e).padEnd(Ib)),Q.createElement(te,{color:jn.GRAY},t.description))))),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Commands"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Mb.map(t=>Q.createElement(ee,{key:t.key},Q.createElement(te,null,t.key.replace(/^cmd/,e).padEnd(Ib)),Q.createElement(te,{color:jn.GRAY},t.description))))),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Slash Commands"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},t.map(e=>Q.createElement(ee,{key:e.key},Q.createElement(te,null,e.key.padEnd(Ib)),Q.createElement(te,{color:jn.GRAY},e.description))))),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Keyboard Shortcuts"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Nb.map(e=>Q.createElement(ee,{key:e.key},Q.createElement(te,null,e.key.padEnd(Ib)),Q.createElement(te,{color:jn.GRAY},e.description))))),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Examples"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Db.map(t=>Q.createElement(ee,{key:t.key},Q.createElement(te,null,t.key.replace(/^cmd/,e).padEnd(Ib)),Q.createElement(te,{color:jn.GRAY},t.description))))),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.CYAN},ke.pointer),Q.createElement(te,{color:jn.GRAY}," ",Ob.replace(/cmd/,e))),Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{bold:!0},"Links"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Lb.map(e=>Q.createElement(ee,{key:e.key},Q.createElement(te,null,e.key.padEnd(Ib)),Q.createElement(te,{color:jn.CYAN},e.description))))))}function SystemMessage({content:e,metadata:t}){if(e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS"))return Q.createElement(HelpMessage,null);if("CONTEXT"===e){const e=t?.analysis;if(e)return Q.createElement(ContextMessage,{analysis:e})}return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{wrap:"wrap"},Q.createElement(Markdown,null,e)))}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),Nr(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),Ht(),_n(),LC(),dr();var Ax={"Interrupted by user":"Interrupted by user","Insufficient credits":fn};function UserMessage({content:e,images:t,imageCount:n=0}){const r="Interrupted by user"===e,s="Insufficient credits"===e,o=e.startsWith("Error:"),i=r||s||o,a=i&&Ax[e]||e,l=null!=t?t.length:n,u=Y(null);null===u.current&&t&&t.length>0&&(u.current=t.map((e,t)=>saveTempImage(e,t+1)));const d=u.current??[];return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,{backgroundColor:i?void 0:Xn.BG,paddingRight:1},Q.createElement(te,{color:i?jn.RED:Xn.POINTER,bold:!i},ke.pointer),Q.createElement(ee,{marginLeft:1},Q.createElement(te,{color:i?jn.RED:jn.WHITE,wrap:"wrap"},a))),l>0&&Q.createElement(ee,{marginLeft:1},Q.createElement(te,{color:jn.DIM},"⎿"," ",Array.from({length:l},(e,t)=>{const n=d[t],r=`[Image #${t+1}]`;return null!=n?createOSC8Link(`file://${n}`,r,!1):r}).join(" "))))}function renderFeedEntry(e,t){if("user"===e.role){const t=Array.isArray(e.metadata?.images)?e.metadata.images:void 0;return Q.createElement(UserMessage,{content:e.input,images:t})}return"assistant"===e.role?Q.createElement(AssistantMessage,{content:e.input}):"tool"===e.role?Q.createElement(ToolMessage,{name:ov(e.name||""),input:e.input,output:e.output||"",isPending:nv(e),hasError:tv(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?Q.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:nv(e),hasError:tv(e)}):"system"===e.role?Q.createElement(SystemMessage,{content:e.input,metadata:e.metadata}):"info"===e.role?Q.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?Q.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?Q.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?Q.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName(e){const t=Object.values(Dt).find(t=>t.id===e);return t?t.name.toLowerCase().replace(" ","-"):e.includes("sonnet-4-6")?"sonnet-4.6":e.includes("sonnet")?"sonnet-4.5":e.includes("opus-4-6")?"opus-4.6":e.includes("opus")?"opus-4.5":"sonnet-4.6"}function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [ctrl+e to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),s="─".repeat(r);return Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:Jn},s),Q.createElement(BracketedText,{text:n,color:Jn}),Q.createElement(te,{color:Jn},s))}__name(UserMessage,"UserMessage"),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName,"getModelShortName"),__name(TranscriptDivider,"TranscriptDivider");var Ix=Q.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:s,hiddenCount:o=0})=>{const i=o>0?{role:"transcript-divider",count:o}:null,a=[...t?["header"]:[],...i?[i]:[],...e],l=useTerminalWidth(),u=X(()=>u_(l),[l]),d=X(()=>h_(l),[l]),m=X(()=>getPackageJson().version||"0.0.0",[]),g=X(()=>getGitHeaderInfo(),[]),h=X(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),f=s?getModelShortName(s):"sonnet-4.6",y="taste-1",w=isInternalTeamFlagEnforced()&&!process.env.CMD_DEMO?" · co":"";return Q.createElement(ne,{items:a,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return Q.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:l});if("header"===e)return"compact"===d?Q.createElement(ee,{key:"header",marginBottom:1,flexDirection:"row"},Q.createElement(ee,{width:p_,flexShrink:0},Q.createElement(ot,{name:"vice"},Q.createElement(te,null,m_))),Q.createElement(ee,{flexDirection:"column",marginLeft:2},Q.createElement(ee,null,Q.createElement(te,{bold:!0},"Command Code"),Q.createElement(te,{color:Jn}," ","v",m)),Q.createElement(te,{color:Jn},"models: ",f," · ",y,w),Q.createElement(te,{color:Jn},h,g&&g.isLocal&&g.branch&&` (${g.branch})`))):Q.createElement(ee,{key:"header",marginBottom:1,flexDirection:"column"},Q.createElement(ot,{name:"vice"},Q.createElement(te,null,u.trimEnd())),Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(ee,null,Q.createElement(te,{color:Jn},"# "),Q.createElement(te,{bold:!0},"Command Code"),Q.createElement(te,{color:Jn}," v",m)),Q.createElement(te,{color:Jn},"# models: ",f," · ",y,w),Q.createElement(ee,null,Q.createElement(te,{color:Jn},"# ",h,g&&g.isLocal&&g.branch&&Q.createElement(te,{color:Jn}," ","(branch:"," ",g.branch,")")))));const t=e,n=renderFeedEntry(t,r);return Q.createElement(ee,{key:t.id,paddingBottom:1,width:"90%"},n)})});Ht(),dv(),Rr(),dr();var Nx=V(__name(function LiveAgentStatusInner2({entry:e}){const t=ov(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],s=r?r+(n.includes(".")||n.includes("\n")?".":""):n,o=e.metadata?.tokensUsed||0,i=e.metadata?.elapsedSeconds||0,a=e.metadata?.recentTools||[],[l,u]=K(".");return J(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),Q.createElement(ee,{flexDirection:"column",marginBottom:1,width:"90%"},Q.createElement(ee,null,Q.createElement(te,{backgroundColor:Vn.BG,color:Vn.FG,bold:!0},` ${t} `),s&&Q.createElement(te,null," ","(",s,")")),Q.createElement(ee,{columnGap:1,marginLeft:1},Q.createElement(te,null,"⎿"," "),Q.createElement(te,{color:jn.GRAY},"Running (",formatTime2(i)," | ",formatTokens(o),")",l)),a.length>0&&Q.createElement(ee,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=ov(e.name);return Q.createElement(ee,{key:t,columnGap:1},Q.createElement(te,{color:jn.GRAY},"⎿"),Q.createElement(te,{color:jn.GRAY}," ",n),e.input&&Q.createElement(te,{color:jn.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),Rx=V(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:Q.createElement(Nx,{entry:e})},"LiveAgentStatus"));Ht(),Kt(),dr(),Rr(),xr();var $x=Object.values(Dt),Mx=Object.keys(qt),Lx=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=n?Math.max(0,$x.findIndex(e=>e.id===n)):0,[s,o]=K(r),[i,a]=K(null),[l,u]=K(null);return J(()=>{(async()=>{await isOAuthEnforced()&&u(await getConfiguredProvider())})()},[]),se((n,r)=>{if(r.escape)t();else{if(r.upArrow)return a(null),void o(e=>e>0?e-1:$x.length-1);if(r.downArrow)return a(null),void o(e=>e<$x.length-1?e+1:0);if(r.return){const t=$x[s];if(!t)return;if(l){const e=jt[l];if(e&&!e.includes(t.provider)){const e=qt[l]||l;return void a(`${e} OAuth does not support ${t.provider} models. Switch to GitHub Copilot via /provider.`)}}e(t.id)}}}),Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ee,null,Q.createElement(te,{color:Bn,bold:!0},"Select model")),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{dimColor:!0},"Switch between Command Code models. Applies to this session and future sessions.")),Mx.map((e,t)=>{const r=$x.filter(t=>t.provider===e);return 0===r.length?null:Q.createElement(ee,{key:e,flexDirection:"column",marginBottom:t<Mx.length-1?1:0},Q.createElement(te,{dimColor:!0,bold:!0},qt[e]),r.map(e=>{const t=$x.indexOf(e)===s,r=e.id===n;return Q.createElement(ee,{key:e.id},Q.createElement(te,{color:t?jn.CYAN:jn.GRAY},t?ke.pointer:" "),Q.createElement(te,{color:t?jn.CYAN:r?jn.GREEN:jn.WHITE},` ${e.label.padEnd(24)}`),e.description&&Q.createElement(te,{dimColor:!0},e.description),r&&Q.createElement(te,{color:jn.GREEN}," ",ke.tick))}))}),i&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.RED},i)),Q.createElement(ee,{marginTop:i?0:1},Q.createElement(te,{dimColor:!0},"up/down navigate . Enter to select . Esc to cancel")))},"ModelSelector");Ht(),Nr(),dr();var Dx=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),s=__name(t=>{e(t.value)},"handleSelect");se((e,n)=>{n.escape&&t()});const o=n?r.findIndex(e=>e.value===n):0,i=n&&-1===o;return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ee,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},Q.createElement(ee,null,Q.createElement(te,{bold:!0},"Select AI Provider")),n&&Q.createElement(ee,{flexDirection:"row"},Q.createElement(te,{color:jn.DIM},"Current: "),Q.createElement(te,{color:jn.GREEN},getProviderDisplayName(n)),i&&Q.createElement(te,{color:jn.YELLOW}," [OAuth enforced]"))),Q.createElement(ee,{marginBottom:0},Q.createElement(te,{color:jn.DIM},"Available Providers:")),Q.createElement(tt,{items:r,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:e?jn.CYAN:jn.GRAY,bold:e},e?ke.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.CYAN:jn.GRAY,bold:e},` ${t}`)}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=K(0);if(J(()=>{if(null===e)return;const t=setInterval(()=>{n(e=>(e+1)%4)},500);return()=>clearInterval(t)},[e]),null===e)return null;const r=".".repeat(t).padEnd(3," ");return Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:rr,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Ht(),dr(),__name(RetryMessage,"RetryMessage"),Ht(),Dw(),hs(),_n(),dr();var Ox=[{mode:"both",label:"Both",description:"Restore conversation and code (recommended)"},{mode:"conversation",label:"Conversation only",description:"Rewind conversation, keep current code"},{mode:"files",label:"Code only",description:"Restore code, keep conversation"}],Fx=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=X(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[s,o]=K(Math.max(0,r.length-1)),[i,a]=K(Math.max(0,r.length-8)),[l,u]=K("checkpoint"),[d,m]=K(null),[g,h]=K(0),f=X(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),y=X(()=>f?Ox:Ox.filter(e=>"conversation"===e.mode),[f]);if(J(()=>{if(r.length>0){const e=r.length-1;o(e),a(Math.max(0,r.length-8))}},[r.length,8]),se((e,f)=>{f.escape?"mode"===l?(u("checkpoint"),m(null),h(0)):n():"checkpoint"===l?f.upArrow?o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):f.downArrow?o(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):f.return&&r.length>0&&(m(r[s]),u("mode"),h(0)):"mode"===l&&(f.upArrow?h(e=>Math.max(0,e-1)):f.downArrow?h(e=>Math.min(y.length-1,e+1)):f.return&&d&&y[g]&&t({messageId:d.messageId,mode:y[g].mode}))}),0===r.length)return Q.createElement(ee,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(te,{color:Bn,bold:!0},"Rewind"),Q.createElement(te,{color:jn.DIM},"No checkpoints available. Start a conversation to create checkpoints."),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press "),Q.createElement(te,{color:jn.DIM,bold:!0},"Esc"),Q.createElement(te,{color:jn.DIM}," to close")));if("mode"===l&&d)return Q.createElement(ee,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(te,{color:Bn,bold:!0},"Rewind"),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM},"Restore to: "),Q.createElement(te,{color:jn.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),Q.createElement(ee,{flexDirection:"column"},y.map((e,t)=>{const n=g===t,r=t===y.length-1;return Q.createElement(ee,{key:e.mode,flexDirection:"column"},Q.createElement(ee,{flexDirection:"row"},Q.createElement(te,{color:n?Bn:void 0},n?`${wn} `:" "),Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:n?Bn:jn.WHITE},e.label),Q.createElement(te,{color:jn.DIM},e.description))),!r&&Q.createElement(te,null," "))})),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press "),Q.createElement(te,{color:jn.DIM,bold:!0},"Enter"),Q.createElement(te,{color:jn.DIM}," to confirm, "),Q.createElement(te,{color:jn.DIM,bold:!0},"Esc"),Q.createElement(te,{color:jn.DIM}," to go back")));const w=r.slice(i,i+8);return Q.createElement(ee,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(te,{color:Bn,bold:!0},"Rewind"),Q.createElement(te,{color:jn.DIM},"Select a checkpoint to restore your session"),r.length>8&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),Q.createElement(ee,{marginTop:1}),Q.createElement(ee,{flexDirection:"column"},w.map((e,t)=>{const n=i+t,o=s===n,a=e.filesModified.length,l=t===w.length-1,u=n===r.length-1;return Q.createElement(ee,{key:e.messageId,flexDirection:"column"},Q.createElement(ee,{flexDirection:"row"},Q.createElement(te,{color:o?Bn:void 0},o?`${wn} `:" "),Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{color:o?Bn:jn.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),Q.createElement(te,{color:jn.DIM}," • "),Q.createElement(te,{color:jn.DIM},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),Q.createElement(te,{color:jn.DIM},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&Q.createElement(te,null," "))})),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press "),Q.createElement(te,{color:jn.DIM,bold:!0},"Enter"),Q.createElement(te,{color:jn.DIM}," to select, "),Q.createElement(te,{color:jn.DIM,bold:!0},"Esc"),Q.createElement(te,{color:jn.DIM}," to cancel")))},"RewindSelector");Ht(),In(),Ht(),Ht(),tC();var qx=__name(e=>{const[t,n]=K(e),[r,s]=K(null);return J(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),s(null)},"handleReset"),r=__name(e=>{"error"!==e.type?n(t=>{if("step_start"===e.type){const n=t.findIndex(t=>t.id===e.step);return n<0?t:t.map((t,r)=>r<n?{...t,active:!1,complete:!0}:r===n?{...t,active:!0,message:e.message||"",...e.label&&{label:e.label},..."complete"===e.step&&{complete:!0},...void 0!==e.learningCount&&void 0!==e.categories&&void 0!==e.storage&&t.summary&&{summary:{learningCount:e.learningCount,categories:e.categories,storage:e.storage}}}:t)}if("progress"===e.type){const n=t.findIndex(e=>e.active);return n<0?t:t.map((t,r)=>r===n?{...t,items:[...t.items,e.message]}:t)}if("insight"===e.type){const n=t.findIndex(e=>"learning"===e.id);return n<0?t:t.map((t,r)=>r===n?{...t,insights:[...t.insights,e.message]}:t)}return t}):s(e.message)},"handleNewEvent");return Zv.on("reset",t),Zv.on("new-event",r),()=>{Zv.off("reset",t),Zv.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:s}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new xy({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let s,o;try{const e=await getOAuthCredentials({provider:n});s=e.token,o=e.oauthProvider,validateOAuthToken({token:s,provider:n})}catch(e){dlog("Failed to get or validate OAuth token:",e instanceof Error?e.message:String(e))}const i={[Ct.PROJECT_SLUG]:hv.getCurrentProjectDirName(),[Ct.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return s&&(i[Ct.OAUTH_TOKEN]=`Bearer ${s}`,o&&(i[Ct.OAUTH_PROVIDER]=o)),{request:t,headers:i}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const s of e){const e=estimateTokens(s);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([s])):r+e>2e3?(n.length>0&&t.push(n),n=[s],r=e):(n.push(s),r+=e)}return n.length>0&&t.push(n),t}Ht(),Ht(),cC(),Wy(),Xy(),bS(),In(),tC(),Ht(),In(),tC(),bS(),Ht(),Ht(),Kt(),Wy(),Xy(),vv(),In(),xr(),Rr(),__name(createRequestClient,"createRequestClient"),Ht(),bS(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Ht(),Ht(),In(),gn(),tC(),Ht();var jx="claude-haiku-4-5-20251001";function buildObserverPrompt(e,t){return`Scan prompts. ${t} casual observations like a dev friend glancing at your work.\n\nPLAIN TEXT ONLY. No markdown, no formatting.\n\nBe natural and VARIED. Don't repeat the same sentence starters.\n\nGood (notice the variety):\npnpm over npm, nice\ndebugging that auth flow\nreact + typescript stack\ncircular deps came up\ntui flicker stuff\nah the classic memory leak\nsession persistence wip\nfighting with imports again\nhaiku model issues huh\n\nBad (too repetitive - NEVER do this):\nI see you prefer pnpm\nI see debugging auth\nI see react stack\nI see circular deps\noh, TUI issues\noh, memory leak\n\nRules:\n- plain text, lowercase is fine\n- vary your sentence starts - mix it up\n- max 6 words\n- sound human, not robotic\n\nPrompts:\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}function createInsightEmitter(){let e="",t=0;const n=__name(()=>{if(e.includes("\n")){const t=e.split("\n");for(let e=0;e<t.length-1;e++){const n=t[e].trim();n&&(dlog(`[ObserverAPI] emitting insight: ${n}`),Zv.addEvent({type:"insight",message:n}))}e=t[t.length-1]}},"emitCompletedLines");return{addText:__name(r=>{t++,dlog(`[ObserverAPI] text chunk ${t}: "${r.substring(0,50)}..."`),e+=r,n()},"addText"),emitRemaining:__name(()=>{e.trim()&&(dlog(`[ObserverAPI] emitting final insight: ${e.trim()}`),Zv.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function callObserverAPI(e,t,n){dlog(`[ObserverAPI] calling ${kt.ALPHA.GENERATE} with model: ${jx}`);const r={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:n}],model:jx,max_tokens:200,temperature:.7,stream:!0},threadId:Ee()},s=await e.post({endpoint:kt.ALPHA.GENERATE,body:r,headers:t,stream:!0});dlog("[ObserverAPI] got response stream");const o=createInsightEmitter();await consumeSSEStream(s,{onText:__name(e=>{o.addText(e)},"onText")}),dlog(`[ObserverAPI] stream complete, ${o.getChunkCount()} chunks received`),o.emitRemaining(),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,s){let o=0;for(const e of n)o+=estimateTokens(e);dlog(`[Observer] batch ${r}/${s}: ${n.length} prompts`);const i=buildObserverPrompt(n,4);await callObserverAPI(e,t,i)}async function observeSessionPrompts(e){if(Zv.observerHasRun)return;Zv.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${r.length} batches`);const s=Math.min(r.length,6);for(let t=0;t<s;t++){if(Zv.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const s=r[t];try{await processBatch(e,n,s,t+1,r.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),Zv.addEvent({type:"progress",message:"Continuing without live observations..."})}}Kt(),PE(),__name(buildObserverPrompt,"buildObserverPrompt"),__name(createInsightEmitter,"createInsightEmitter"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var Bx=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(y.homedir(),".claude","projects");await D.access(r);const s=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${s}`);const o=(await D.readdir(r)).filter(e=>e===s);for(const s of o){const o=e.join(r,s);try{if(!(await D.stat(o)).isDirectory())continue;const r=(await D.readdir(o)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const s of r){const r=e.join(o,s),i=await D.stat(r),a=s.replace(".jsonl","");if(n.push({id:a,filePath:r,createdAt:i.birthtime,lastModified:i.mtime,messageCount:0,agent:"claude-code"}),t>0&&n.length>=t)break}if(t>0&&n.length>=t)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return n}static async findCodexSessions(e=0,t){try{Zv.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&Zv.addEvent({type:"progress",message:`Scanning Codex: ${e.processedFiles}/${e.totalFiles} files (${e.matchedSessions} matched)`})},e);return dlog(`[Import] found ${n.length} Codex sessions`),n}catch(e){return dlog("[Import] no codex sessions",e),[]}}static async findCursorSessions(e=0){try{Zv.addEvent({type:"progress",message:"Scanning Cursor sessions..."});const t=await findCursorSessions(process.cwd(),e);return dlog(`[Import] found ${t.length} Cursor sessions`),t}catch(e){return dlog("[Import] no cursor sessions",e),[]}}static async extractUserPrompts(e){const t=[];try{const n=(await D.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"===n.type&&n.message){const e=n.message;let r="";e.content&&"string"==typeof e.content&&(r=e.content),r.trim()&&t.push(r.trim())}}catch{continue}t.length>0&&dlog(`[Import] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Import] failed: ${e}`,t)}return t}static splitPromptsIntoBatches(e,t=15e4){const n=[];let r=[],s=0;for(const o of e){const e=estimateTokens(o);if(e>t){r.length>0&&(n.push(r),r=[],s=0);const e=this.splitLargePrompt(o,t);for(const t of e)n.push([t])}else s+e<=t?(r.push(o),s+=e):(r.length>0&&n.push(r),r=[o],s=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let s="",o=0;for(const e of r){const r=estimateTokens(e);o+r<=t?(s+=(s?"\n":"")+e,o+=r):(s&&n.push(s),s=e,o=r)}return s&&n.push(s),n}static async importAndLearn(){const e=[],t=[],n=[],r=[],s=[];try{Zv.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const o=await loadProjectSettings(),i=o.tasteOnboarding?.learnedSessions||{},a=i["claude-code"]?.length||0,l=i.codex?.length||0,u=i.cursor?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${l} learned, cursor=${u} learned`);const d=await findNewSessions(i),m=d["claude-code"]||[],g=d.codex||[],h=d.cursor||[],f=m.length+g.length+h.length;if(dlog(`[Import] findNewSessions returned: claude-code=${m.length} new, codex=${g.length} new, cursor=${h.length} new`),0===f){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=await findCursorSessions(process.cwd()),r=e.length+t.length+n.length,s=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length},{name:"Cursor",count:n.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);Zv.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:r>0?`From ${s.join(" + ")} sessions`:"No sessions found for this project"});const o=[];return e.length>0&&o.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&o.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),n.length>0&&o.push({agent:"cursor",sessionIds:n.map(e=>e.id),displayName:"Cursor"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:r,learnedSessions:a+l+u,agentSessions:o,status:"already-learned"}}if(m.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>m.includes(e.id));n.push(...e)}if(g.length>0){const e=(await this.findCodexSessions()).filter(e=>g.includes(e.id));r.push(...e)}if(h.length>0){const e=(await this.findCursorSessions()).filter(e=>h.includes(e.id));s.push(...e)}const y=n.length+r.length+s.length;dlog(`[Import] total sessions: ${y} (claude-code: ${n.length}, codex: ${r.length}, cursor: ${s.length})`),Zv.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const w=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts},{name:"Cursor",sessions:s,extractPrompts:extractCursorPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of w){Zv.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const S=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${S.length} batches`);const E=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});Zv.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${S.length} batch${1===S.length?"":"es"}`});try{const o=getApiBaseUrl(),i=new xy({baseUrl:o});let a=!0;for(let e=0;e<S.length;e++){const t=S[e],n=e+1,r=S.length;r>1&&Zv.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const s=this.formatBatchLearning(t),o=new rC({request:i,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:s}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await o.checkAndProcess({messages:l})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),Zv.markLearningComplete(),await E,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}if(s.length>0){const e=s.map(e=>e.id);await markSessionsAsLearned("cursor",e),dlog(`[Import] marked ${e.length} cursor sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const l=await this.extractLearningSummary(),u=[];if(n.length>0&&u.push(`Claude Code (${n.length})`),r.length>0&&u.push(`Codex (${r.length})`),s.length>0&&u.push(`Cursor (${s.length})`),!a){const o="Learning failed - sessions not marked as learned";return e.push(o),Zv.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...s.length>0?[{agent:"cursor",sessionIds:s.map(e=>e.id),displayName:"Cursor"}]:[]]}}return Zv.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${u.join(" + ")}`,learningCount:l.totalLearnings,categories:l.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...s.length>0?[{agent:"cursor",sessionIds:s.map(e=>e.id),displayName:"Cursor"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),Zv.addEvent({type:"error",message:r}),{success:!1,totalPrompts:t.length,preferencesLearned:0,errors:e}}}catch(t){const n=t instanceof Error?t.message:String(t);return e.push(n),{success:!1,totalPrompts:0,preferencesLearned:0,errors:e}}}static async extractLearningSummary(){try{const t=e.join(process.cwd(),".commandcode","taste","taste.md"),n=await D.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),s=r?r.length:0;return{totalLearnings:s,categories:n.split("\n").filter(e=>e.startsWith("# ")).map(e=>e.replace(/^# /,"").trim()).filter(e=>e&&!e.toLowerCase().startsWith("taste"))}}catch{return{totalLearnings:0,categories:[]}}}static formatBatchLearning(e){return e.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}};tC();var Ux=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),zx=__name(e=>{const[t,n]=K({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return J(()=>{Zv.reset(),Zv.markImportStarted(),(async()=>{try{const t=await Promise.race([Bx.importAndLearn(),Ux(12e4)]);if(t.success)return void n(e=>({...e,isImporting:!1,waitingForInput:!0}));if("already-learned"===t.status)return void n(e=>({...e,isImporting:!1,alreadyLearned:!0,learnedSessionCount:t.learnedSessions||0,totalSessionCount:t.totalSessions||0,agentSessions:t.agentSessions||[],waitingForInput:!0}));const r=t.errors.join("\n");n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}catch(t){const r=t instanceof Error?t.message:String(t);n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}})()},[e]),t},"useImportProcess");Ht();var Wx=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{se((r,s)=>{n&&(s.escape&&e(),(s.return||"\n"===r)&&t())})},"useKeyboardInput");Ht(),In();var Gx=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=K(null),[s,o]=K(null),i=Y(!1);return J(()=>{if(i.current)return;let n=null;return(async()=>{try{i.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),o(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:s,isLoading:!n&&!s}},"useOnboardingConditions");async function completeOnboarding(e){try{await markOnboardingCompleted(),dlog("[Helper] onboarding marked complete")}catch(e){dlog(`[Helper] complete error: ${e instanceof Error?e.message:String(e)}`)}finally{Zv.reset(),e()}}async function skipOnboarding(e){try{await markOnboardingSkipped(),dlog("[Helper] onboarding marked skipped")}catch(e){dlog(`[Helper] skip error: ${e instanceof Error?e.message:String(e)}`)}finally{Zv.reset(),e()}}Ht(),In(),Ht(),In(),tC(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var Hx=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=Y(n),s=Z(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),o=Z(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=Z(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=Z(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=Z(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]);return n!==r.current&&(r.current=n),{handleImportStart:s,handleImportComplete:o,handleImportError:i,handleErrorDismiss:a,handleSkip:l}},"useOnboardingHandlers");Ht(),In();var Qx=__name(({conditions:e,autoLearn:t})=>{const[n,r]=K("checking"),s=Y(!1);return J(()=>{if(e&&!s.current){if(s.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),J(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Ht(),Ht(),dr();var Vx=__name(({error:e})=>Q.createElement(ee,{padding:1},Q.createElement(ee,{flexDirection:"column",borderColor:jn.RED,padding:1},Q.createElement(ee,{marginBottom:1},Q.createElement(te,null,"Error initializing onboarding: ",e)),Q.createElement(ee,null,Q.createElement(te,null,"Continuing without onboarding...")))),"OnboardingError");Ht(),Ht(),Kt(),dr();var Kx=__name(()=>`(run /${$t.LEARN_TASTE} anytime)`,"getSkipHint"),Yx=__name(()=>Q.createElement(te,null,"Skip for now"," ",Q.createElement(te,{color:jn.DIM},Kx())),"SkipOptionText"),Jx=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[s,o]=K(1);return se((e,t)=>{t.escape?r():t.upArrow||t.downArrow?o(e=>1===e?2:1):"1"!==e?"2"!==e?t.return&&(1===s?n():r()):r():n()}),Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:Un.TEXT,paddingX:1,paddingY:0},Q.createElement(te,{color:Un.TEXT,bold:!0},"Build Your Coding Taste"),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(te,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),Q.createElement(ee,{marginTop:1},Q.createElement(te,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{color:1===s?Un.TEXT:jn.GRAY},1===s?ke.pointer:" "," 1. Yes, learn from my sessions (recommended)")),Q.createElement(ee,null,Q.createElement(te,{color:2===s?Un.TEXT:jn.GRAY},2===s?ke.pointer:" "," 2."," ",Q.createElement(Yx,null)))),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice");Ht(),Ht(),dr();var Xx=__name(({error:e})=>Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.RED,paddingX:2,paddingY:1,marginBottom:2},Q.createElement(te,{color:jn.RED,bold:!0},"Oops, something went wrong:"),Q.createElement(ee,{marginTop:1},Q.createElement(te,null,e))),"ErrorSection");Ht(),Ht(),dr(),Ht(),Ht(),Ht(),dr(),Ht(),dr();var Zx=__name(()=>Q.createElement(te,{backgroundColor:Un.BADGE_BG,color:Un.BADGE_FG},qk),"TasteBadge");Ht(),dr(),Ht();var eP=["percolating","excavating","deciphering","triangulating","osmosing","metabolizing","grokking","spelunking","interpolating","marinating","crystallizing","synthesizing","calibrating","fermenting","coalescing","transmuting","simmering","distilling","ruminating","perusing","assimilating","untangling","decoding","absorbing","harmonizing","digesting","contemplating","extrapolating","materializing","finalizing"],tP="⎿",nP=__name(()=>{const[e,t]=K(()=>Math.floor(Math.random()*eP.length));return J(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*eP.length))},2e3);return()=>clearInterval(e)},[]),Q.createElement(te,{color:jn.YELLOW},eP[e],"...")},"PulsingText");Ht(),dr();var rP=[ke.bullet,ke.squareSmallFilled,ke.lozenge,ke.star,ke.triangleRight,ke.triangleUp,ke.circleFilled,ke.pointer],sP=__name(e=>String(e).padStart(3," "),"padNum"),oP=__name(e=>rP[e%rP.length],"getSymbol"),iP=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${sP(t)} ↓${sP(n)} (↑↓ scroll)`,"buildStatusLine"),aP=__name(({insights:e})=>{const[t,n]=K(0),[r,s]=K(!0),o=e.length,i=o>10,a=Math.max(0,o-10);if(J(()=>{r&&i&&n(a)},[o,r,i,a]),se((e,t)=>{if(i)return t.upArrow?(s(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(a,e+1);return t===a&&s(!0),t}))}),0===o)return null;const l=e.slice(t,t+10),u=t,d=o-t-10;return Q.createElement(ee,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&Q.createElement(te,{color:jn.DIM},iP(o,u,d,r)),l.map((e,n)=>{const r=t+n;return Q.createElement(ee,{key:r,marginBottom:0},Q.createElement(te,{color:jn.DIM},oP(r)," ",e))}))},"ScrollableInsights");Ht(),dr();var lP=__name(()=>{const[e,t]=K(!0);return J(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),Q.createElement(te,{color:jn.YELLOW},e?ke.circleFilled:ke.circle)},"PulsingDot"),cP=__name(({label:e,message:t,active:n,complete:r,items:s,insights:o,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return Q.createElement(ee,{flexDirection:"column",marginBottom:0},Q.createElement(Zx,null),Q.createElement(ee,{marginTop:0},Q.createElement(te,{color:jn.DIM},tP),Q.createElement(ee,{marginLeft:2},a?Q.createElement(te,{color:Un.TEXT},"learned your coding taste"):Q.createElement(nP,null))));const u=__name(()=>r?Q.createElement(te,{color:Hn.BG},ke.square):n?Q.createElement(lP,null):Q.createElement(te,{color:jn.DIM},ke.circle),"getStatusIcon"),d=s.length>0||o.length>0||t||l&&l.learningCount>0;return!r||n||d?Q.createElement(ee,{flexDirection:"column",marginBottom:0},(n||r)&&Q.createElement(ee,{marginBottom:0},Q.createElement(ee,{marginRight:1},u()),Q.createElement(te,{color:r?jn.WHITE:n?jn.YELLOW:jn.DIM},e)),r&&t&&(!l||0===l.learningCount)&&Q.createElement(ee,{marginLeft:3,marginBottom:0},Q.createElement(te,{color:jn.DIM},t)),s.length>0&&Q.createElement(ee,{flexDirection:"column",marginLeft:1,marginBottom:0},s.map((e,t)=>Q.createElement(te,{key:t,color:jn.DIM},`${ke.bullet} ${e}`))),o.length>0&&Q.createElement(aP,{insights:o}),r&&l&&l.learningCount>0&&Q.createElement(ee,{flexDirection:"column",marginLeft:1,marginBottom:0},Q.createElement(ee,{marginBottom:1,flexDirection:"row"},Q.createElement(te,null,tP),Q.createElement(ee,{marginLeft:2},Q.createElement(te,{color:Un.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),Q.createElement(ee,{flexDirection:"column",marginLeft:1},Q.createElement(te,{color:jn.DIM},ke.pointerSmall," Stored in"," ",l.storage),Q.createElement(te,{color:jn.DIM},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),uP=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return Q.createElement(ee,{flexDirection:"column",marginBottom:1},e.map((e,n)=>Q.createElement(ee,{key:e.id,marginLeft:0===n?0:3},Q.createElement(cP,{label:e.label,message:e.message,active:e.active,complete:e.complete,items:e.items,insights:e.insights,summary:e.summary,isIntro:0===n,isAllComplete:t}))))},"StepsSection"),dP=__name(({steps:e})=>Q.createElement(uP,{steps:e}),"ProgressSection");Ht(),dr();var mP=__name(({isImporting:e=!1,waitingForInput:t=!1})=>Q.createElement(Q.Fragment,null,e&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"ESC to cancel")),t&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Ht();var pP=[{id:"importing",label:"Initializing Taste Profile",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"batching",label:"Organizing your sessions",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"learning",label:"Learning your coding taste",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"complete",label:"Learned your coding taste!",message:"",active:!1,complete:!1,items:[],insights:[],summary:{learningCount:0,categories:[],storage:".commandcode/taste/taste.md"}}],gP=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:s}=qx(pP),{isImporting:o,waitingForInput:i,error:a}=zx(t);return Wx({onEscape:e,onEnter:__name(()=>{i&&(a&&n?n():e())},"onEnter"),enabled:o||i}),Q.createElement(ee,{flexDirection:"column",padding:1},s&&Q.createElement(Xx,{error:s}),!s&&Q.createElement(dP,{steps:r}),Q.createElement(mP,{isImporting:o,waitingForInput:i}))},"ImportProgress"),hP=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:s,onErrorDismiss:o,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?Q.createElement(Jx,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?Q.createElement(gP,{onComplete:r,onError:s,onErrorDismiss:o}):null,"OnboardingStepRenderer"),fP=__name(({onComplete:e,autoLearn:t=!1})=>{J(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:s}=Gx({autoLearn:t,onShouldSkip:e}),{step:o,setStep:i}=Qx({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=Hx({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${o}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),s?null:r?Q.createElement(Vx,{error:r}):"done"===o?null:Q.createElement(hP,{step:o,conditions:n,onImportStart:a,onImportComplete:l,onImportError:u,onErrorDismiss:d,onSkip:m})},"TasteOnboarding");function getEntryCharCount(e){return("input"in e?e.input??"":"").length+("output"in e?e.output??"":"").length+("command"in e?e.command??"":"").length}function getBudgetedFeed(e,t){if(0===e.length)return[];const n=[...e].reverse();let r=t;const s=[];for(const e of n)if(s.unshift(e),r-=getEntryCharCount(e),r<=0)break;return s}__name(getEntryCharCount,"getEntryCharCount"),__name(getBudgetedFeed,"getBudgetedFeed");var yP=V(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:s,transcriptMode:o,tasteOnboardingEntryId:i,autoLearnTaste:a,retryAttempt:l,input:u,setInput:d,fileSearchQuery:m,setFileSearchQuery:g,showFileList:h,setShowFileList:f,showProviderSelector:y,showModelSelector:w,showMemorySelector:S,showMcpManager:E,showAgentsConfig:v,showRewindSelector:C,showLoginOverlay:k,showUsageOverlay:T,showAddDirModal:_,showCompactModeSelector:x,authComponentInfo:P,status:A,currentProvider:I,currentModel:N,showProviderNotification:R,shareInfo:$,showShareNotification:M,unshareNotificationMessage:L,updateStatus:D,updateFailedInfo:O,creditWarning:F,permissionMode:q,hintMessage:j,pendingExitKey:B,tasteLearningEnabled:U,interactionTokens:z,contextUsage:W,historyManagerRef:G,executionState:H,contextEngineRef:V,onSubmit:K,onCommand:Y,onToggleAutoAccept:J,onResetPendingExitKey:ne,onDoubleEscapeEmpty:re,onTasteOnboardingComplete:se,permissionPanel:oe,questionPanel:ie,onRewindSelect:ae,onRewindCancel:le,onLoginComplete:ce,onLoginCancel:ue,setShowProviderSelector:de,setShowModelSelector:me,setShowMemorySelector:pe,setShowMcpManager:ge,setShowAgentsConfig:he,setShowAddDirModal:fe,setShowUsageOverlay:ye,handleProviderSelect:we,handleProviderCancel:Se,handleModelSelect:be,handleModelCancel:Ee,handleCompactModeSelect:ve,handleCompactModeCancel:Ce,handleAuthSuccess:ke,handleAuthCancel:Te}){const _e=X(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),xe=useTerminalWidth(),Pe=X(()=>"off"===o?_e:getBudgetedFeed(_e,"limited"===o?15e3:5e4),[_e,o]),Ae=X(()=>"off"===o?0:Math.max(0,_e.length-Pe.length),[_e.length,Pe.length,o]),Ie=X(()=>0===Ae?Pe:Pe.filter(e=>"user"!==e.role),[Pe,Ae]),Ne=Z(()=>he(!1),[he]),Re=Z(()=>pe(!1),[pe]),$e=Z(()=>ge(!1),[ge]),Me=Z(()=>fe(!1),[fe]),Le=Z(()=>me(!0),[me]),De=!("off"!==o||oe||ie||y||w||P||S||E||v||C||k||T||_||x||i);return Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(Ix,{staticKey:s,feed:Ie,showHeader:!0,expandedToolOutput:"off"!==o,currentModel:N,hiddenCount:Ae}),i&&Q.createElement(fP,{onComplete:se,autoLearn:a}),t.map(e=>e.metadata?.isAgent?Q.createElement(Rx,{key:e.id,entry:e}):Q.createElement(ee,{key:e.id,marginBottom:1,width:"90%"},renderFeedEntry(e,"off"!==o))),Q.createElement(RetryMessage,{attempt:l}),ie,oe,"off"!==o&&Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"─".repeat(xe))),Q.createElement(ee,{paddingRight:1},Q.createElement(te,{backgroundColor:Hn.BG,color:Hn.FG,bold:!0},`${Fk}DETAILED TRANSCRIPT${Fk}`),Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{bold:!0},"ctrl+o"),Q.createElement(te,{color:jn.DIM}," to toggle"),Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{bold:!0},"ctrl+e"),Q.createElement(te,{color:jn.DIM}," ","to"," ","limited"===o?"show all":"collapse"))),De&&Q.createElement(Cx,{queuedMessages:n,isProcessing:r,executionState:H,status:A,input:u,setInput:d,onSubmit:K,showFileList:h,setShowFileList:f,fileSearchQuery:m,setFileSearchQuery:g,onCommand:Y,outputTokens:z,contextUsage:W,tasteLearning:U,shareInfo:$,showShareNotification:M,unshareNotificationMessage:L,updateStatus:D,updateFailedInfo:O,creditWarning:F,currentProvider:I,showProviderInfo:R,permissionMode:q,onToggleAutoAccept:J,hintMessage:j,historyManager:G.current,pendingExitKey:B,onResetPendingExitKey:ne,onDoubleEscapeEmpty:re,retryAttempt:l,onAltP:Le}),y&&Q.createElement(ee,{marginY:1},Q.createElement(Dx,{onSelect:we,onCancel:Se,currentProvider:I})),w&&Q.createElement(ee,{marginY:1},Q.createElement(Lx,{onSelect:be,onCancel:Ee,currentModel:N})),x&&Q.createElement(ee,{marginY:1},Q.createElement(K_,{onSelect:ve,onCancel:Ce})),v&&Q.createElement(ee,{marginY:1},Q.createElement(Q_,{onCancel:Ne})),S&&Q.createElement(ee,{marginY:1},Q.createElement(_x,{onClose:Re})),E&&Q.createElement(ee,{marginY:1},Q.createElement(Tx,{onClose:$e})),C&&V.current&&Q.createElement(ee,{marginY:1},Q.createElement(Fx,{checkpoints:V.current.listCheckpoints(),onSelect:ae,onCancel:le})),P&&Q.createElement(ee,{marginY:1},Q.createElement(P.Component,{onSuccess:ke,onCancel:Te})),k&&Q.createElement(ee,{marginY:1},Q.createElement(kx,{onComplete:ce,onCancel:ue})),_&&Q.createElement(ee,{marginY:1},Q.createElement(N_,{onClose:Me})))},"MainView"));function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,onboarding:o,exitState:i,pendingOps:a,permissionState:l,contextEngineRef:u,historyManagerRef:d,executionState:m,actionCallbacks:g,onSubmit:h,onCommand:f,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,updateFailedInfo:v,creditWarning:C,handleTrust:k,handleNoTrust:T,handleToggleAutoAccept:_,handleDoubleEscapeEmpty:x,handleTasteOnboardingComplete:P,loadTasteStatus:A}){if(i.shouldExit)return null;if(o.checkingProject)return null;if(o.showTrustPrompt)return Q.createElement(WT,{staticKey:s.staticKey,onTrust:k,onExit:T});if(s.showSessionSelector)return Q.createElement(HT,{onSelectSession:g.onSelectSession,onNewSession:g.onNewSession});if(!o.projectTrusted)return null;const I=a.pendingQuestion?Q.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:s.setStaticKey}):null,N=a.pendingPermission?Q.createElement(r_,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:_}):null;return s.showLearningFeed?Q.createElement(LearningView,{setShowLearningFeed:s.setShowLearningFeed,setStaticKey:s.setStaticKey,onExit:()=>i.setShouldExit(!0)}):s.showTasteConfig?Q.createElement(TasteConfigView,{staticKey:s.staticKey,setShowTasteConfig:s.setShowTasteConfig,loadTasteStatus:A}):s.showSkillsConfig?Q.createElement(SkillsConfigView,{staticKey:s.staticKey,setShowSkillsConfig:s.setShowSkillsConfig}):s.showUsageOverlay?Q.createElement(UsageView,{staticKey:s.staticKey,setShowUsageOverlay:s.setShowUsageOverlay}):s.showContextView?Q.createElement(ContextConfigView,{staticKey:s.staticKey,contextEngineRef:u,setShowContextView:s.setShowContextView,setInput:w}):s.showStatusView?Q.createElement(StatusConfigView,{staticKey:s.staticKey,setShowStatusView:s.setShowStatusView,setInput:w}):Q.createElement(yP,{feed:e.feed,liveEntries:e.liveEntries,queuedMessages:e.queuedMessages,isCmdCodeBusy:e.isCmdCodeBusy,staticKey:s.staticKey,transcriptMode:s.transcriptMode,tasteOnboardingEntryId:o.tasteOnboardingEntryId,autoLearnTaste:o.autoLearnTaste,retryAttempt:n.retryAttempt,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,showFileList:s.showFileList,setShowFileList:s.setShowFileList,showProviderSelector:s.showProviderSelector,showModelSelector:s.showModelSelector,showMemorySelector:s.showMemorySelector,showMcpManager:s.showMcpManager,showAgentsConfig:s.showAgentsConfig,showRewindSelector:s.showRewindSelector,showLoginOverlay:s.showLoginOverlay,showUsageOverlay:s.showUsageOverlay,setShowUsageOverlay:s.setShowUsageOverlay,showAddDirModal:s.showAddDirModal,showCompactModeSelector:s.showCompactModeSelector,authComponentInfo:r.authComponentInfo,status:n.status,currentProvider:r.currentProvider,currentModel:r.currentModel,showProviderNotification:r.showProviderNotification,shareInfo:n.shareInfo,showShareNotification:n.showShareNotification,unshareNotificationMessage:n.unshareNotificationMessage,updateStatus:n.updateStatus,updateFailedInfo:v,creditWarning:C,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,tasteLearningEnabled:n.tasteLearningEnabled,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,historyManagerRef:d,executionState:m,contextEngineRef:u,onSubmit:h,onCommand:f,onToggleAutoAccept:_,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:x,onTasteOnboardingComplete:P,permissionPanel:N,questionPanel:I,onRewindSelect:g.onRewindSelect,onRewindCancel:g.onRewindCancel,onLoginComplete:g.onLoginComplete,onLoginCancel:g.onLoginCancel,setShowProviderSelector:s.setShowProviderSelector,setShowModelSelector:s.setShowModelSelector,setShowMemorySelector:s.setShowMemorySelector,setShowMcpManager:s.setShowMcpManager,setShowAgentsConfig:s.setShowAgentsConfig,setShowRewindSelector:s.setShowRewindSelector,setShowLoginOverlay:s.setShowLoginOverlay,setShowAddDirModal:s.setShowAddDirModal,handleProviderSelect:g.handleProviderSelect,handleProviderCancel:g.handleProviderCancel,handleModelSelect:g.handleModelSelect,handleModelCancel:g.handleModelCancel,handleCompactModeSelect:g.handleCompactModeSelect,handleCompactModeCancel:g.handleCompactModeCancel,handleAuthSuccess:g.handleAuthSuccess,handleAuthCancel:g.handleAuthCancel})}__name(renderView,"renderView");var wP=__name(({resume:e=!1,resumeSessionId:t,continue:n=!1,trust:r=!1,dangerouslySkipPermissions:s=!1,updateStatus:o,updateFailedInfo:i,initialPrompt:a,skipOnboarding:l=!1,initialPermissionMode:u})=>{const{exit:d}=ie(),{stdout:m}=re(),[g,h]=K(""),[f,y]=K(""),w=Y(!1),S=Y(!1),E=Y(null),v=Y(null),C=useUiOverlays(),k=useFeed(),T=useSession(),_=useStatus(o),x=useAuth(),P=usePendingOps(),A=useOnboarding(),I=useExit(),{executeBash:N,executionState:R}=xk(),$=usePermissionMode({initialPermissionMode:u,dangerouslySkipPermissions:s,setPendingPermission:P.setPendingPermission,setStatus:_.setStatus,contextEngineRef:v}),{createContextEngineCallbacks:M}=useContextEngine({sessionId:T.sessionId,sessionLoaded:T.sessionLoaded,showSessionSelector:C.showSessionSelector,projectTrusted:A.projectTrusted,setFeed:k.setFeed,setLiveEntries:k.setLiveEntries,setQueuedMessages:k.setQueuedMessages,queuedMessagesRef:k.queuedMessagesRef,setStatus:_.setStatus,pinnedStatusRef:_.pinnedStatusRef,setRetryAttempt:_.setRetryAttempt,setInteractionTokens:_.setInteractionTokens,setContextUsage:_.setContextUsage,setCurrentProvider:x.setCurrentProvider,shareInfoRef:_.shareInfoRef,permissionsService:$.permissionsService,permissionModeRef:$.permissionModeRef,setPendingQuestion:P.setPendingQuestion,contextEngineRef:v}),{onCommand:L}=useCommandCtx({feedState:k,sessionState:T,statusState:_,uiOverlays:C,onboarding:A,exitState:I,permissionState:$,contextEngineRef:v,isSubmittingRef:w,executeBash:N,createContextEngineCallbacks:M,setInput:h}),{loadTasteStatus:D,loadCurrentProvider:O,onSubmit:F}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:a,stdout:m,feedState:k,sessionState:T,statusState:_,authState:x,onboarding:A,uiOverlays:C,permissionState:$,contextEngineRef:v,isSubmittingRef:w,initialPromptSubmittedRef:S,historyManagerRef:E,executeBash:N,createContextEngineCallbacks:M,setInput:h,onCommand:L});useLifecycle({exit:d,feedState:k,exitState:I,statusState:_,authState:x,onboarding:A,uiOverlays:C,skipOnboarding:l});const{handleToggleAutoAccept:q,handleDoubleEscapeEmpty:j,handleTasteOnboardingComplete:B,handleTrust:U,handleNoTrust:z}=useHandlers({resume:e,feedState:k,onboarding:A,uiOverlays:C,exitState:I,pendingOps:P,permissionState:$,statusState:_,authState:x,contextEngineRef:v,loadTasteStatus:D,loadCurrentProvider:O,setInput:__name(e=>h(e),"setInput")}),W=useMainActionCallbacks({feedState:k,sessionState:T,statusState:_,authState:x,uiOverlays:C,permissionState:$,contextEngineRef:v,createContextEngineCallbacks:M,setInput:h}),{creditWarning:G}=useCreditWarning({interactionTokens:_.interactionTokens});return renderView({feedState:k,sessionState:T,statusState:_,authState:x,uiOverlays:C,onboarding:A,exitState:I,pendingOps:P,permissionState:$,contextEngineRef:v,historyManagerRef:E,executionState:R,actionCallbacks:W,onSubmit:F,onCommand:L,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,updateFailedInfo:i,creditWarning:G,handleTrust:U,handleNoTrust:z,handleToggleAutoAccept:q,handleDoubleEscapeEmpty:j,handleTasteOnboardingComplete:B,loadTasteStatus:D})},"InteractiveCLI");vr(),qn(),vv();var SP=__name(e=>e?{isValid:!0}:{isValid:!1,errorMessage:["Error: Interactive mode requires a TTY terminal.","Please run this command directly in your terminal, not through a pipe or redirect."].join("\n")},"validateTtyEnvironment"),bP=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),EP=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),vP=__name(({options:e,resumeSessionId:t})=>{let n;return e.permissionMode?n=e.permissionMode:e.plan&&(n="plan"),{resume:"boolean"==typeof e.resume?e.resume:void 0,resumeSessionId:t,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding,initialPermissionMode:n}},"buildInteractiveCLIProps"),CP=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),kP=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),TP=__name(()=>{kP()},"initializeTerminal"),_P=__name(async(e={})=>{const t=SP(process.stdin.isTTY);let n;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),TP(),"string"==typeof e.resume){const t=e.resume;await hv.isProjectInitialized()||(console.error("Project not initialized. Run cmd to start a conversation first."),process.exit(1));const r=await hv.findSessionByName(t);r||(console.error(`No session named "${t}" found.`),process.exit(1)),n=r.id}if(bP(e)&&!n){const e=await hv.isProjectInitialized(),t=e?await hv.listSessions():[],n=EP({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const r=vP({options:e,resumeSessionId:n}),s=CP();oe(Q.createElement(wP,{...r}),s)},"interactiveMode");en(),Ht(),Kt(),rk(),VC();var xP=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.error(`${ke.cross} Authentication failed. Please try again with: cmd login`),!1)}catch(e){return isUserCancellation(e)||(console.error(`${ke.cross} Login failed: ${getErrorMessage(e)}`),console.error("Please try again with: cmd login")),!1}},"attemptLogin");async function ensureAuthenticated(){try{return!!await getAuthKey()||xP()}catch(e){return console.error("Error checking authentication:",e),!1}}__name(ensureAuthenticated,"ensureAuthenticated");var PP=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),AP=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth"),IP=__name(e=>{const t={};return e.trust&&(t.trust=!0),e.dangerouslySkipPermissions&&(t.dangerouslySkipPermissions=!0,t.trust=!0),e.skipOnboarding&&(t.skipOnboarding=!0),e.plan&&(t.plan=!0),e.permissionMode&&(t.permissionMode=e.permissionMode),t},"buildRuntimeOptions"),NP=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:e.resume,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),RP=__name((e,t)=>"string"==typeof e.print&&e.print.trim()?e.print:t&&!t.startsWith("-")?t:"","extractPrintQuery");async function interactiveModeAction(e,t){if(t.addDir&&t.addDir.length>0)for(const e of t.addDir)addDirectory(e);if(void 0!==t.print){const n=RP(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions,maxTurns:t.maxTurns,verbose:t.verbose,model:t.model,benchmarkOutput:t.benchmarkOutput})}const n=PP(e);await AP();const r=IP(t),s=NP({options:t,runtimeOptions:r,initialPrompt:n});_P(s)}__name(interactiveModeAction,"interactiveModeAction"),Ht(),In(),Cs(),xr(),HC(),rk(),globalThis.COMMAND_CODE_CWD=process.cwd();var $P=__name(()=>process.cwd(),"getCwd"),MP=__name(()=>process.argv.slice(2),"getArgs"),LP=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),DP=__name(()=>{const e=$P(),t=MP(),n=LP(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){DP(),process.argv.includes("--ide-setup")&&(formatSetupResult(await runIDESetup()).forEach(e=>console.log(e)),process.exit(0)),await maybeRunPendingUpdate(),await migrateDeprecatedModel(),await getAuthKey()&&detectAndTrackFirstInstall().catch(()=>{}),checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100)}__name(preRun,"preRun"),Ht(),Kt(),In(),Ur(),jb(),Nr();var OP=getPackageJson(),FP=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=OP.version,t=getInvokedCommandName(),n=$b.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(le.bold("Command Code")+le.gray(` v${e}`)),console.log(le.gray(Ab)),console.log(),console.log(le.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(le.bold("Options"));for(const e of Rb){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ib)+le.gray(e.description))}console.log(),console.log(le.bold("Commands"));for(const e of Mb){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ib)+le.gray(e.description))}console.log(),console.log(le.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Ib)+le.gray(e.description));console.log(),console.log(le.bold("Keyboard Shortcuts"));for(const e of Nb)console.log(" "+e.key.padEnd(Ib)+le.gray(e.description));console.log(),console.log(le.bold("Examples"));for(const e of Db){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ib)+le.gray(e.description))}console.log(),console.log(le.cyan("❯")+" "+le.gray(Ob.replace(/cmd/,t))),console.log(),console.log(le.bold("Links"));for(const e of Lb)console.log(" "+e.key.padEnd(Ib)+le.cyan(e.description));console.log()}function createProgram(){const e=new ve;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(OP.version,"-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume [name]","Resume a session by name, or pick from history").option("-c, --continue"," Continue the most recent session in the current directory").option("-t, --trust","Trust the project (skip initial trust permission prompt)").addOption(new Ce("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Ce("--yolo","Bypass all permission prompts (alias for --dangerously-skip-permissions)").implies({dangerouslySkipPermissions:!0})).option("--plan","Start in plan mode (read-only exploration and planning)").addOption(new Ce("--auto-accept","Start in auto-accept mode").implies({permissionMode:"auto-accept"})).addOption(new Ce("--permission-mode <mode>","Set permission mode").choices(["standard","plan","auto-accept"])).option("--skip-onboarding","Skip taste onboarding (for non-interactive/automated runs)").option("-p, --print [query]","Run in non-interactive mode, output response and exit").option("--max-turns <number>","Maximum conversation turns in print mode (default: 10)",e=>{const t=parseInt(e,10);if(isNaN(t)||t<1)throw new Error("--max-turns must be a positive integer");return t}).option("--verbose","Stream tool execution progress to stderr in print mode").option("--ide-setup","Setup extension to fetch IDE context").option("--add-dir <directory>","Add directory to workspace context",FP,[]).addOption(new Ce("--model <model>","Override model for this run").hideHelp()).addOption(new Ce("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Ce("--experimental","Enable experimental features").hideHelp()).addOption(new Ce(Et).hideHelp()).addOption(new Ce(vt).hideHelp()).addOption(new Ce("-d, --debug","Enable debug mode").hideHelp()).addOption(new Ce("--local","Use local server").hideHelp()).addOption(new Ce("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption(),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}function setupCommanderHooks(e){e.hook("preAction",(e,t)=>{dlogSection("cmd");const n=t.name(),r=t.parent?.name();dlog(`[cmd] ${r&&r!==n?"subcommand":"running"}: ${n}`);const s=t.opts(),o=Object.entries(s).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");o&&dlog(`[cmd] options: ${o}`);const i=t.args;i.length>0&&dlog(`[cmd] arguments: ${i.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}function isTTY(){return Boolean(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.CI)}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Ht(),Cs(),Kr(),_C(),sk(),Jv(),Ur(),rk(),Ht(),__name(isTTY,"isTTY");var qP=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),trackCliSessionExistsEvent(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=y.platform(),n=y.arch();let r,s,o,i;try{const e=await getAuthenticatedEntity();e.success&&(r=e.user?.userName,s=e.user?.id,o=e.org?.login,i=e.org?.id)}catch{}if(!s)try{const e=await loadCredentials();s=e?.userId}catch{}systemInfo({userName:r,userId:s,orgLogin:o,orgId:i,nodeVersion:e,platform:t,arch:n})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){qP||(qP=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function trackCliSessionExistsEvent(){try{if(!await getAuthKey())return;const e=getSessionId();if(!e)return;const t=getPackageJson().version||"unknown",n=y.platform(),r=y.arch(),s=isTTY()?"interactive":"non-interactive";await trackLifecycleEvent({eventType:"cli_session_exists",metadata:{sessionId:e,cliVersion:t,mode:s,os:`${n}-${r}`}})}catch{}}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Te("Opening GitHub issues...").start();try{await me(t,{wait:!1,background:!0}),n.succeed(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`),console.log("")}catch(e){n.fail("Failed to open browser"),console.log(""),console.log(createOSC8Link(t,"Open GitHub issue manually")),console.log("")}}__name(setupTelemetry,"setupTelemetry"),__name(trackSystemInfo,"trackSystemInfo"),__name(registerCleanupHandlers,"registerCleanupHandlers"),__name(handleShutdownSignal,"handleShutdownSignal"),__name(trackCliSessionExistsEvent,"trackCliSessionExistsEvent"),rk(),Ht(),LC(),__name(openGitHubIssue,"openGitHubIssue");var jP=new ve("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Ht();var BP=new ve("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const{waitUntilExit:t}=oe(Q.createElement(xT,{verbose:e.verbose,text:e.text}));await t()}Ht(),Ht(),__name(runInfo,"runInfo");var UP=new ve("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{await runInfo(e)});function runLearnTaste(){const{unmount:e}=oe(Q.createElement(gP,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}Ht(),Kt(),Ht(),__name(runLearnTaste,"runLearnTaste"),In(),Cs();var zP=new ve($t.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{runLearnTaste()}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:ys.LEARN_TASTE_COMMAND,heading:"Learn taste render failed"}}),dlog(`[/learn-taste] render failed: ${e instanceof Error?e.message:String(e)}`),await shutdownTelemetry(),process.exit(1)}});function addMcpCommand(){const e=new ve("add");return e.description("Add an MCP server").argument("<name>","Server name (unique identifier)").argument("[url]","Server URL (required for http transport)").option("-t, --transport <type>","Transport type (stdio or http)","stdio").addOption(new Ce("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("-e, --env <KEY=value>","Environment variable (repeatable)",collectKeyValue,{}).option("-H, --header <header>","HTTP header (repeatable, http only)",collectHeaders,{}).allowUnknownOption().allowExcessArguments().action(async(e,t,n,r)=>{const s=getInvokedCommandName();try{let o;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(le.red(`Error: Invalid server name '${e}'`)),console.error(le.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1)),"stdio"!==n.transport&&"http"!==n.transport&&(console.error(le.red(`Error: Invalid transport type '${n.transport}'`)),console.error(le.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(le.red("Error: URL is required for http transport")),console.error(le.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(le.red(`Error: Invalid URL '${t}'`)),process.exit(1)}o={transport:"http",enabled:!0,url:t,...Object.keys(n.header).length>0&&{headers:n.header},...Object.keys(n.env).length>0&&{env:n.env}},console.log(le.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(le.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(le.cyan("Server requires OAuth authentication."));let t,n="command-code";if(r.metadata.registrationEndpoint){console.log(le.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${iE}/callback`]});e&&(n=e.clientId,t=e.clientSecret)}o.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},console.log(le.gray("A browser window will open for authentication.\n"));const s=await performOAuthFlow(e,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(le.gray(` ${e}`))},"onStatus")});s.success?console.log(le.green("✓ Successfully authenticated")):(i=!0,console.log(le.yellow(`Warning: Authentication failed: ${s.error}`)),console.log(le.gray("You can retry with: cmd mcp auth "+e)),console.log(le.gray("Or authenticate via the /mcp menu in a session")))}}else{const s=r.args,i=process.argv.indexOf("--");let a,l=[];if(-1!==i){const e=process.argv.slice(i+1);0===e.length&&(console.error(le.red("Error: Command is required for stdio transport")),console.error(le.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),a=e[0],l=e.slice(1)}else if(t){a=t;const n=s.indexOf(e);-1!==n&&s.length>n+2&&(l=s.slice(n+2))}else console.error(le.red("Error: Command is required for stdio transport")),console.error(le.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(le.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);o={transport:"stdio",enabled:!0,command:a,...l.length>0&&{args:l},...Object.keys(n.env).length>0&&{env:n.env}}}await addMcpServer({name:e,serverConfig:o,scope:n.scope});const a="user"===n.scope?"global":"project"===n.scope?"project":"local";if(i?console.log(le.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(le.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===o.transport)console.log(le.gray(` URL: ${o.url}`));else{const e=[o.command,...o.args||[]].join(" ");console.log(le.gray(` Command: ${e}`))}console.log(""),console.log(le.cyan("Next steps:")),console.log(le.gray(`Start ${s} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function collectKeyValue(e,t){const[n,...r]=e.split("=");return n&&0!==r.length||(console.error(le.red(`Error: Invalid format '${e}', expected KEY=value`)),process.exit(1)),t[n]=r.join("="),t}function collectHeaders(e,t){const n=e.indexOf(":");-1===n&&(console.error(le.red(`Error: Invalid header format '${e}', expected 'Header: value'`)),process.exit(1));const r=e.substring(0,n).trim(),s=e.substring(n+1).trim();return r||(console.error(le.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=s,t}function listMcpCommand(){const e=new ve("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(le.yellow("\nNo MCP servers configured\n")),console.log(le.gray("Add a server with:")),console.log(le.gray(" cmd mcp add --transport http <name> <url>")),console.log(le.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(le.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(le.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(le.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const s of e){const e=s.config.enabled?le.green("enabled"):le.gray("disabled");let o;o=s.config.oauth?await hasTokens(s.name)?le.green(ke.tick):le.red(ke.cross):s.config.headers||s.config.env?le.green(ke.tick):le.gray("-"),console.log(` ${le.white(s.name.padEnd(t))} ${le.cyan(s.config.transport.padEnd(n))} ${le.gray(s.scope.padEnd(r))} ${o} ${e}`)}console.log(le.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new ve("get");return e.description("Show details for an MCP server").argument("<name>","Server name").action(async e=>{try{const t=await getMcpServer({name:e});t||(console.error(le.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(le.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${le.dim("Scope:")} ${r}`),console.log(` ${le.dim("Transport:")} ${n.transport}`),console.log(` ${le.dim("Status:")} ${n.enabled?le.green("enabled"):le.gray("disabled")}`),"http"===n.transport){if(console.log(` ${le.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${le.dim("Headers:")}`);for(const[e,t]of Object.entries(n.headers)){const n=e.toLowerCase().includes("auth")||e.toLowerCase().includes("token")||e.toLowerCase().includes("key")?"***":t;console.log(` ${e}: ${n}`)}}}else console.log(` ${le.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${le.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${le.dim("Environment:")}`);for(const[e,t]of Object.entries(n.env)){const n=e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token")||e.toLowerCase().includes("password")?"***":t;console.log(` ${e}=${n}`)}}console.log("")}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new ve("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Ce("-s, --scope <scope>","Scope to remove from (auto-detects if not specified)").choices(["local","project","user"])).action(async(e,t)=>{try{const n=await getMcpServer({name:e});n||(console.error(le.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(le.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(le.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const s="user"===r?"global":"project"===r?"project":"local";console.log(le.green(`✓ Removed MCP server '${e}' from ${s} config`))}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new ve("add-json");return e.description("Add an MCP server from JSON configuration").argument("<name>","Server name (unique identifier)").argument("<json>","Server configuration as JSON string").addOption(new Ce("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("--client-secret <secret>","OAuth client secret (injected into oauth config)").action(async(e,t,n)=>{const r=getInvokedCommandName();try{let s,o;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(le.red(`Error: Invalid server name '${e}'`)),console.error(le.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1));try{s=JSON.parse(t)}catch{console.error(le.red("Error: Invalid JSON")),console.error(le.gray("Make sure to quote the JSON string properly")),console.error(le.gray(`Example: ${r} mcp add-json github '{"type":"stdio","command":"npx"}'`)),process.exit(1)}s&&"object"==typeof s&&"type"in s&&!("transport"in s)&&(s.transport=s.type,delete s.type),s?.oauth?.callbackPort&&(o=s.oauth.callbackPort,delete s.oauth.callbackPort),n.clientSecret&&s?.oauth&&(s.oauth.clientSecret=n.clientSecret);const i=Kb.safeParse(s);if(!i.success){console.error(le.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(le.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(le.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(le.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(le.cyan("Starting OAuth authentication...")),console.log(le.gray("A browser window will open for authentication.\n"));const t={authorizationUrl:a.oauth.authorizationUrl,tokenUrl:a.oauth.tokenUrl,clientId:a.oauth.clientId,clientSecret:a.oauth.clientSecret,scopes:a.oauth.scopes},n=await performOAuthFlow(e,t,{...o&&{port:o},onStatus:__name(e=>{console.log(le.gray(` ${e}`))},"onStatus")});n.success?console.log(le.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(le.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(le.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(le.gray("Or authenticate via the /mcp menu in a session")))}const u="user"===n.scope?"global":"project"===n.scope?"project":"local";if(l?console.log(le.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(le.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(le.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(le.gray(` Command: ${e}`))}console.log(""),console.log(le.cyan("Next steps:")),console.log(le.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new ve("auth");return e.description("Manage OAuth authentication for MCP servers").argument("[server]","Server name to authenticate").option("--status","Check authentication status").option("--clear","Clear stored authentication").option("--list","List servers with stored authentication").action(async(e,t)=>{const n=getInvokedCommandName();try{if(t.list){const e=await listServersWithTokens();if(0===e.length)return void console.log(le.yellow("No servers with stored authentication."));console.log(le.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?le.yellow("expired"):le.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(le.red("Error: Server name is required")),console.error(le.gray(`Usage: ${n} mcp auth <server>`)),console.error(le.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(le.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(le.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(le.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(le.gray(" A refresh token is available for re-authentication"));else{if(console.log(le.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(le.gray(` Expires in ${e} minutes`))}t.scope&&console.log(le.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(le.green(`✓ Cleared authentication for '${e}'`)):console.log(le.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(le.red(`Error: MCP server '${e}' not found`)),console.error(le.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),r.config.oauth||(console.error(le.red(`Error: Server '${e}' does not have OAuth configured`)),console.error(le.gray(`Add OAuth config using "${n} mcp add-json" with oauth field`)),process.exit(1));const s={authorizationUrl:r.config.oauth.authorizationUrl,tokenUrl:r.config.oauth.tokenUrl,clientId:r.config.oauth.clientId,clientSecret:r.config.oauth.clientSecret,scopes:r.config.oauth.scopes};console.log(le.cyan(`Authenticating with '${e}'...`)),console.log(le.gray("A browser window will open for authentication.\n"));const o=await performOAuthFlow(e,s,{onStatus:__name(e=>{console.log(le.gray(` ${e}`))},"onStatus")});if(o.success)return console.log(le.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(le.gray("Restart the session to connect with the authenticated server."));console.error(le.red(`\nError: Authentication failed: ${o.error}`)),console.log(le.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new ve("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}async function runCommand(e){return new Promise((t,n)=>{const r=M(e.cmd,e.args,{stdio:["ignore","pipe","pipe"],env:process.env});let s="",o="";r.stdout.on("data",e=>{s+=String(e)}),r.stderr.on("data",e=>{o+=String(e)}),r.on("error",n),r.on("close",r=>{0!==r?n(new Error(`${e.cmd} ${e.args.join(" ")} failed${o?`: ${o.trim()}`:""}`)):t({stdout:s,stderr:o})})})}async function detectDefaultBranch(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"symbolic-ref","refs/remotes/origin/HEAD","--short"]}),n=t.trim().replace(/^origin\//,"");if(n)return n}catch{}for(const t of["main","master"])try{return await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--verify",t]}),t}catch{}try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--abbrev-ref","HEAD"]});return t.trim()}catch{return"main"}}async function findGitRoot4(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.dir,"rev-parse","--show-toplevel"]});return t.trim()}catch{return null}}async function countLearnings(e){try{return(await D.readFile(e,"utf-8")).split("\n").filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:")).length}catch{return 0}}async function resolveSource(t){const n=t.source.trim(),r=e.resolve(n);try{if(!(await D.stat(r)).isDirectory())throw new Error(`Source must be a repository directory: ${n}`);return{type:"local",displayName:r,repoDir:r,repoName:e.basename(r),github:await inferGitHubRepo({repoDir:r})}}catch(e){if(e instanceof Error&&e.message.startsWith("Source must be"))throw e}const s=parseGitHubSource({source:n});if(!s){const e=n.startsWith("git@")?" SSH URLs are not supported. Use HTTPS or owner/repo instead.":"";throw new Error(`Unsupported source '${n}'.${e} Use a local path, GitHub HTTPS URL, or owner/repo.`)}const o=String(t.maxCommits??200),i=`https://github.com/${s.owner}/${s.repo}.git`,a=await D.mkdtemp(e.join(y.tmpdir(),"taste-learn-"));try{await runCommand({cmd:"git",args:["clone","--depth",o,"--single-branch",...t.branch?["--branch",t.branch]:[],"--",i,a]})}catch{throw await D.rm(a,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Repository not found: ${s.owner}/${s.repo}. Check the owner and repo name, or verify it's a public repository.`)}return{type:"github",displayName:`${s.owner}/${s.repo}`,repoDir:a,repoName:s.repo,github:s,cleanup:__name(async()=>{await D.rm(a,{recursive:!0,force:!0})},"cleanup")}}function getTastePathForDir(t){return e.join(t.projectRoot,".commandcode","taste")}async function resolveDisplayName(t){if(t.startsWith("/")||t.startsWith(".")){const n=e.resolve(t),r=await findGitRoot4({dir:n});return r?e.basename(r):e.basename(n)}return t}function parseGitHubSource(e){const t=e.source.match(/^([\w.-]+)\/([\w.-]+)$/);if(t)return{owner:t[1],repo:t[2].replace(/\.git$/,"")};try{const t=new URL(e.source);if("github.com"!==t.hostname)return null;const n=t.pathname.split("/").filter(Boolean);return n.length<2?null:{owner:n[0],repo:n[1].replace(/\.git$/,"")}}catch{return null}}async function inferGitHubRepo(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"remote","get-url","origin"]});return parseGitHubSource({source:t.trim()})??void 0}catch{return}}async function feedToLearningAgent(e){const t=await getConfiguredProvider(),n=await getOAuthCredentials({provider:t});if(await isOAuthEnforced()&&!n?.token)throw new Error("Authentication required. Run: cmd login");n?.token&&validateOAuthToken({token:n.token,provider:t});const r=getApiBaseUrl(),s=new xy({baseUrl:r}),o=new rC({request:s,sessionId:crypto.randomUUID(),projectRoot:e.outputDir}),i=[{role:"user",content:e.compiledContext}];await o.checkAndProcess({messages:i})}function logLearnSummary(e){const{summary:t}=e;console.log(le.cyan("\n ─── Results ───\n")),console.log(` Source: ${t.sourceName}`),console.log(` Signals: ${t.signalCount} extracted`),console.log(` Context: ${t.contextLength} chars compiled`),console.log(` Taste dir: ${t.tasteDir}`),console.log("")}function shouldContinueExtraction(e){return!(e.offset>=e.commitsLength||e.signalCount>=e.signalCap||e.commitsWithDiffs>=50)}async function extractAllSignals(e){e.onProgress?.("Collecting commits");const t=await collectCommits(e);if(0===t.length)return e.onProgress?.("No commits found"),{signals:[],commitCount:0};e.onProgress?.(`Found ${t.length} commits to analyze`);const n=e.maxSignals??50,r=[];let s=0;for(let o=0;shouldContinueExtraction({offset:o,commitsLength:t.length,signalCount:r.length,signalCap:n,commitsWithDiffs:s});o+=10){const i=t.slice(o,o+10);if(0===i.length)break;const a=await runBounded(5,i,async t=>({commit:t,subs:await getSubstitutions(e.repoDir,t.hash)}));for(const{commit:e,subs:t}of a){if(0===t.length)continue;s++;const o=groupCrossFilePatterns(t);for(const t of o.slice(0,5)){if(t.removed.length>200||t.added.length>200)continue;const s=[`Commit: ${e.subject}`];s.push(`File: ${t.file}`),t.context&&s.push(`In: ${t.context}`);const o=buildSnippet(t.codeBefore,t.added,t.codeAfter);if(o&&s.push(o),r.push({text:`${truncate2(t.removed,60)} → ${truncate2(t.added,60)}`,evidence:s,category:inferCategory(t.removed,t.added)}),r.length>=n)break}if(r.length>=n)break}}return e.onProgress?.(`Extracted ${r.length} diff signals from ${s} commits`),{signals:r,commitCount:t.length}}async function collectCommits(e){const t=buildAuthorPattern(e.author,e.authorAliases),n=t?.includes("|")??!1,r=t?[...n?["--extended-regexp"]:[],"--author",t,"--regexp-ignore-case"]:[],s=e.branch?[e.branch]:[],o=e.author?e.maxCommits:3*e.maxCommits,{stdout:i}=await runCommand({cmd:"git",args:["-C",e.repoDir,"log",...s,"--no-merges",...r,"--pretty=format:%H%x1f%aI%x1f%aN%x1f%s%x1e","-n",String(o)]});return i.split("").map(e=>e.trim()).filter(Boolean).map(e=>{const[t="",n="",r="",s=""]=e.split("");return{hash:t.trim(),subject:s.trim(),authorDate:n.trim(),authorName:r.trim()}}).filter(e=>!isDependencyBot(e.authorName,e.subject)).slice(0,e.maxCommits)}async function getSubstitutions(e,t){try{const{stdout:n}=await runCommand({cmd:"git",args:["-C",e,"show","--format=","-U3","--diff-algorithm=histogram","-b","--ignore-blank-lines","-M",t]}),r=[];let s="",o="",i=[],a=[],l=[];const u=2;let d=null;const m=__name(()=>{d&&(r.push({removed:d.removed,added:d.added,file:d.file,context:d.context,codeBefore:d.codeBefore.length>0?d.codeBefore:void 0,codeAfter:d.codeAfter.length>0?d.codeAfter:void 0}),d=null)},"commitPending"),g=__name(()=>{if(i.length>0&&a.length>0){const e=i.join("\n").trim(),t=a.join("\n").trim();e===t||isVersionBump(e,t)||isTrivialChange(e,t)||(m(),d={removed:e,added:t,file:s,context:o||void 0,codeBefore:[...l],codeAfter:[]})}i=[],a=[]},"flush");for(const e of n.split("\n")){if(e.startsWith("diff --git")){g(),m(),s=e.match(/b\/(.+)$/)?.[1]??"",o="",l=[],isNoiseFile(s)&&(s="");continue}if(e.startsWith("@@")){g(),m(),o=e.match(/@@ .+ @@\s*(.+)/)?.[1]?.trim()??"",l=[];continue}if(!s)continue;if(e.startsWith("-")&&!e.startsWith("---")){a.length>0&&g(),i.push(e.slice(1));continue}if(e.startsWith("+")&&!e.startsWith("+++")){a.push(e.slice(1));continue}g();const t=e.startsWith(" ")?e.slice(1):e;if(!t.trim())continue;const n=d;null!==n&&n.codeAfter.length<u&&(n.codeAfter.push(t),n.codeAfter.length>=u&&m()),l.push(t),l.length>u&&l.shift()}return g(),m(),r}catch(e){return process.env.DEBUG&&console.error(`[taste-learn] getSubstitutions failed for ${t}:`,e instanceof Error?e.message:e),[]}}function groupCrossFilePatterns(e){const t=new Map;for(const n of e){const e=`${n.removed.trim()}\0${n.added.trim()}`,r=t.get(e)??[];r.push(n),t.set(e,r)}const n=[];for(const[,e]of t)if(e.length>=2){const t=e.map(e=>e.file).join(", ");n.push({...e[0],file:t,context:`Same change across ${e.length} files`})}else n.push(e[0]);return n}Ht(),Ht(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Ht(),__name(listMcpCommand,"listMcpCommand"),Ht(),__name(getMcpCommand,"getMcpCommand"),Ht(),__name(removeMcpCommand,"removeMcpCommand"),Ht(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Ht(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Ht(),Kt(),Ht(),bC(),Ht(),Kt(),Ht(),__name(runCommand,"runCommand"),Ht(),__name(detectDefaultBranch,"detectDefaultBranch"),__name(findGitRoot4,"findGitRoot"),__name(countLearnings,"countLearnings"),__name(resolveSource,"resolveSource"),__name(getTastePathForDir,"getTastePathForDir"),__name(resolveDisplayName,"resolveDisplayName"),__name(parseGitHubSource,"parseGitHubSource"),__name(inferGitHubRepo,"inferGitHubRepo"),Ht(),cC(),Wy(),Xy(),xr(),Rr(),__name(feedToLearningAgent,"feedToLearningAgent"),__name(logLearnSummary,"logLearnSummary"),Ht(),tC(),Ht(),__name(shouldContinueExtraction,"shouldContinueExtraction"),__name(extractAllSignals,"extractAllSignals"),__name(collectCommits,"collectCommits"),__name(getSubstitutions,"getSubstitutions"),__name(groupCrossFilePatterns,"groupCrossFilePatterns");var WP=5,GP=3;function buildSnippet(e,t,n){const r=e??[],s=n??[],o=t.split("\n").map(e=>e.trimEnd());if(0===o.length&&0===r.length&&0===s.length)return;let i,a=0;o.length>GP?(i=o.slice(0,GP-1),a=o.length-i.length):i=o;const l=i.length+(a>0?1:0),u=Math.max(0,WP-l),d=Math.min(r.length,Math.ceil(u/2)),m=Math.min(s.length,u-d),g=[];for(const e of r.slice(-d))g.push(` ${e.trimEnd()}`);for(const e of i)g.push(`→ ${e}`);a>0&&g.push(`→ ... (+${a} more changed ${1===a?"line":"lines"})`);for(const e of s.slice(0,m))g.push(` ${e.trimEnd()}`);return 0!==g.length?`Snippet:\n${g.join("\n")}`:void 0}__name(buildSnippet,"buildSnippet");var HP=[/package-lock\.json$/,/pnpm-lock\.yaml$/,/yarn\.lock$/,/CHANGELOG\.(md|yml|yaml)$/i,/\.versionbot\//,/\.min\.(js|css)$/,/dist\//,/\.map$/];function isNoiseFile(e){return HP.some(t=>t.test(e))}function isTrivialChange(e,t){return e.trim().length<3&&t.trim().length<3}function isVersionBump(e,t){const n=/^"?version"?\s*:\s*"?\d+\.\d+/;return n.test(e.trim())&&n.test(t.trim())}function inferCategory(e,t){const n=`${e} ${t}`.toLowerCase();return/import|require|from\s+['"]/.test(n)?"imports":/function|=>|async|return/.test(n)?"code-style":/class|interface|type\s+/.test(n)?"types":/test|describe|it\(|expect/.test(n)?"testing":/console|log|debug|error/.test(n)?"logging":/try|catch|throw|Error/.test(n)?"error-handling":"code-style"}function buildAuthorPattern(e,t){return t&&t.length>0?t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"):e??void 0}__name(isNoiseFile,"isNoiseFile"),__name(isTrivialChange,"isTrivialChange"),__name(isVersionBump,"isVersionBump"),__name(inferCategory,"inferCategory"),__name(buildAuthorPattern,"buildAuthorPattern");var QP=new Set(["renovate[bot]","renovate","dependabot[bot]","dependabot","greenkeeper[bot]","snyk-bot"]),VP=[/^update .+ digest to /i,/^update .+ action to /i,/^update .+ to v?\d/i,/^update lock file maintenance/i,/^update dependency .+ to /i,/^chore\(deps\)/i,/^bump .+ from .+ to /i,/^lock file maintenance/i];function isDependencyBot(e,t){const n=e.toLowerCase();return!!QP.has(n)||!(!n.includes("[bot]")||!VP.some(e=>e.test(t)))}function truncate2(e,t){const n=e.replace(/\n/g," ").trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}async function runBounded(e,t,n){const r=[];let s=0;const o=__name(async()=>{for(;s<t.length;){const e=s++;r[e]=await n(t[e])}},"next");return await Promise.all(Array.from({length:Math.min(e,t.length)},()=>o())),r}function compileTasteContext(e){const{signals:t,repoName:n,author:r,commitCount:s}=e,o=r?`Target author: ${r}\n`:"",i=[];if(i.push(`# Dynamic Taste Analysis — Code Change Patterns\n\nRepository: ${n}\n${o}Commits analyzed: ${s}\nSignals extracted: ${t.length}\n\nThis analysis was generated by examining actual code changes (diffs, substitutions, refactoring patterns) rather than static file contents. Every signal below comes from real commits.`),t.length>0){const e=["## Correction Diffs — What Wrong→Right Looks Like"];for(const n of t.slice(0,50)){e.push(`\n**${n.text}**`);for(const t of n.evidence)e.push(`- ${t}`)}i.push(e.join("\n"))}const a=r?` for ${r}`:"";return i.push(`## Instructions for Taste Learning\n\nYou are analyzing code change patterns from a real repository${a}. Based on the correction diffs above, generate deeply personal and opinionated coding taste.\n\n**Critical guidelines:**\n\n1. **Be specific, not generic.** Instead of "Use TypeScript", write "Use branded types for IDs and explicit return types on every function. Prefer \`readonly\` arrays and objects by default."\n\n2. **Extract the WHY from patterns.** If you see verbose names being replaced with concise ones, don't just say "use short names" — say "Prefer concise variable names that derive meaning from context rather than encoding type information."\n\n3. **Look for recurring themes.** If multiple substitutions show the same pattern (e.g., nested if→guard clauses), that's a strong taste signal worth capturing.\n\n4. **Make it actionable.** Every taste entry should be specific enough that another developer could follow it and produce code that looks like it belongs in this repository.\n\n5. **Prioritize quality corrections** — these are the purest taste signals (wrong→right pairs with explicit WHY context from commit messages).\n\n6. **Capture anti-patterns too.** If you see code being removed in refactors, note what the developer avoids: "Never nest deeper than 2 levels — flatten with early returns."\n\n7. **Don't repeat generic tool preferences** like "Use pnpm" or "Use TypeScript" unless the substitutions show something specific about HOW they use those tools.\n\n8. **Prioritize opinionated preferences.** The goal is taste that makes someone's code distinctly theirs — not industry best practices.\n\nWrite the taste entries to the taste.md file using the standard format with confidence scores.`),i.join("\n\n")}async function runLearnPipeline(t){const n=__name(()=>({outputDir:"",tasteDir:"",sourceName:t.source,signalCount:0,contextLength:0}),"abortedResult");if(t.needsAuth){Zv.addEvent({type:"auth_required",step:"auth",message:"Login to synthesize your taste profile",label:"Signing in"});try{await Zv.waitForAuth()}catch{return Zv.emitStepStart({step:"complete",label:"Login skipped",message:"Login skipped",learningCount:0,storage:""}),Zv.markLearningComplete(),{summary:n()}}}t.isLocalSource||Zv.emitStepStart({step:"cloning",label:"Cloning repository",message:`Cloning ${t.source}`});const r=await resolveSource({source:t.source,maxCommits:t.maxCommits});if(t.signal.aborted)return{summary:n(),resolved:r};const s="github"===r.type,o=r.repoName,i=await findGitRoot4({dir:r.repoDir});if(!i)throw new Error(`Not a git repository: ${r.repoDir}. Run inside a git repo or pass the path: npx taste learn /path/to/repo`);const a=s?e.resolve(process.cwd(),o):i;s&&Zv.emitStepStart({step:"collecting",label:"Collecting commits",message:`Cloned ${r.displayName} → ${a}`});const l=t.branch??await detectDefaultBranch({repoDir:i});await D.mkdir(a,{recursive:!0}),Zv.emitStepStart({step:"collecting",label:"Collecting commits",message:`Fetching up to ${t.maxCommits} commits from ${l}`});const{signals:u,commitCount:d}=await extractAllSignals({repoDir:i,maxCommits:t.maxCommits,maxSignals:t.maxSignals,branch:l,onProgress:__name(e=>{Zv.emitProgress({step:"extracting",message:e})},"onProgress")});if(t.signal.aborted)return{summary:n(),resolved:r};if(0===u.length)throw new Error("No signals extracted. Check the repository has commit history.");Zv.emitStepStart({step:"extracting",label:"Extracting taste signals",message:`${u.length} before/after code changes extracted`}),Zv.emitStepStart({step:"compiling",label:"Compiling taste context",message:`Formatting ${u.length} signals for the learning agent`});const m=compileTasteContext({signals:u,repoName:o,commitCount:d});if(t.signal.aborted)return{summary:n(),resolved:r};Zv.emitStepStart({step:"learning",label:"Learning taste",message:"Interpreting code change patterns with AI"}),await feedToLearningAgent({compiledContext:m,outputDir:a});const g=getTastePathForDir({projectRoot:a}),h=e.join(g,"taste.md"),f=await countLearnings(h);return Zv.emitStepStart({step:"complete",label:"Taste learned",message:"Taste learned",learningCount:f,storage:h}),Zv.markLearningComplete(),{summary:{outputDir:a,tasteDir:g,sourceName:r.displayName,signalCount:u.length,contextLength:m.length},resolved:r}}__name(isDependencyBot,"isDependencyBot"),__name(truncate2,"truncate"),__name(runBounded,"runBounded"),Ht(),__name(compileTasteContext,"compileTasteContext"),__name(runLearnPipeline,"runLearnPipeline"),Ht(),Ht(),tC(),Ht();var KP=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return KP.some(t=>t.test(e))}function chunkToString(e){return"string"==typeof e?e:Buffer.isBuffer(e)?e.toString("utf-8"):""}async function withFilteredStderrNoise(e){const t=process.stderr.write.bind(process.stderr);process.stderr.write=(e,...n)=>{const r=chunkToString(e);return!(!r||!shouldIgnoreChunk(r))||("function"==typeof n[0]?t(e,n[0]):t(e,n[0],n[1]))};try{return await e()}finally{process.stderr.write=t}}function toRepoLearnErrorMessage(e){return e instanceof Error?e.message:String(e)}function isRepoLearnMetricLikeText(e){const t=e.trim().toLowerCase();return/^\d+\s/.test(t)||/^saved\s/.test(t)||/^output\s/.test(t)||/^target\s/.test(t)||/\bcandidates\b/.test(t)||/\bevidence records\b/.test(t)||/\bhistory and review signals\b/.test(t)}function truncateRepoLearnPanelText(e,t=12){return truncateString({text:e,maxChars:Math.min(96,getEffectiveWidth({padding:t}))})}__name(shouldIgnoreChunk,"shouldIgnoreChunk"),__name(chunkToString,"chunkToString"),__name(withFilteredStderrNoise,"withFilteredStderrNoise"),Ht(),hs(),__name(toRepoLearnErrorMessage,"toRepoLearnErrorMessage"),__name(isRepoLearnMetricLikeText,"isRepoLearnMetricLikeText"),__name(truncateRepoLearnPanelText,"truncateRepoLearnPanelText"),Ht(),tC(),Ht();var YP=[{id:"collecting",label:"Collecting commits from repository"},{id:"extracting",label:"Extracting taste signals from diffs"},{id:"compiling",label:"Compiling taste context"},{id:"learning",label:"Learning taste from change patterns"},{id:"complete",label:"Taste learned"}],JP=[{id:"cloning",label:"Cloning repository"},...YP],XP=[ke.bullet,ke.squareSmallFilled,ke.lozenge,ke.star,ke.triangleRight,ke.triangleUp];function createInitialRepoLearnSteps(e){return(e??YP).map(e=>({...e,status:"pending"}))}__name(createInitialRepoLearnSteps,"createInitialRepoLearnSteps"),Ht(),tC();var ZP={learningCount:0,storage:"",topLearnings:[]};function getStepStatus(e,t){return e<t?"complete":e===t?"active":"pending"}function deriveStepStates(e,t){return e.map((e,n)=>({...e,status:getStepStatus(n,t)}))}function parseSummaryMetric(e){if(e.startsWith("Maintainer: "))return{maintainerLabel:e.replace(/^Maintainer:\s+/,"")};const t=e.match(/^(\d+)\s+maintainer-specific preferences$/);if(t)return{maintainerCount:Number(t[1])};const n=e.match(/^(\d+)\s+repository conventions$/);return n?{repoCount:Number(n[1])}:null}__name(getStepStatus,"getStepStatus"),__name(deriveStepStates,"deriveStepStates"),__name(parseSummaryMetric,"parseSummaryMetric");var eA=__name(e=>e.map(e=>({...e,status:"complete"})),"markAllStepsComplete"),tA=__name(e=>e??ZP,"withBase");function useRepoLearnState(e){const t=e??YP,[n,r]=K(()=>createInitialRepoLearnSteps(t)),[s,o]=K(""),[i,a]=K([]),[l,u]=K(null),[d,m]=K(!1),[g,h]=K(!1),[f,y]=K(null),[w,S]=K(0),E=Y(null),[v,C]=K(null),k=Z(()=>{E.current=Date.now()},[]);return J(()=>{const e=__name(()=>{r(createInitialRepoLearnSteps(t)),o(""),a([]),u(null),h(!1),y(null),S(0),E.current=null,C(null),m(!1)},"handleReset"),n=__name(e=>{if("error"===e.type)return y(e.message),h(!0),r(eA),void o("");if("auth_required"!==e.type){if("step_start"===e.type&&e.step){const n=t.findIndex(t=>t.id===e.step);return n>=0&&r(deriveStepStates(t,n)),o(e.message||e.label||""),void("complete"===e.step&&u(t=>{const n=tA(t);return{...n,learningCount:e.learningCount??n.learningCount,storage:e.storage??n.storage}}))}"progress"!==e.type||"complete"!==e.step?"progress"!==e.type?"insight"===e.type&&(isRepoLearnMetricLikeText(e.message)||("complete"!==e.step?(S(e=>e+1),a(t=>[...t,e.message].slice(-4))):u(t=>{const n=tA(t);return{...n,topLearnings:[...n.topLearnings,e.message].slice(0,3)}}))):o(e.message):u(t=>{const n=tA(t),r=parseSummaryMetric(e.message);return r?{...n,...r}:n})}else m(!0)},"handleEvent"),s=__name(()=>{h(e=>e||(r(eA),!0)),o(""),E.current&&C(Math.round((Date.now()-E.current)/1e3))},"handleComplete");return Zv.on("reset",e),Zv.on("new-event",n),Zv.on("learning-complete",s),()=>{Zv.off("reset",e),Zv.off("new-event",n),Zv.off("learning-complete",s)}},[t]),{steps:n,currentMessage:s,insights:i,insightCount:w,summary:l,done:g,error:f,showLogin:d,setShowLogin:m,elapsedSeconds:v,markStarted:k}}__name(useRepoLearnState,"useRepoLearnState"),Ht(),Ht(),dr();var nA=__name(({isComplete:e,hasError:t})=>Q.createElement(ee,{flexDirection:"column",marginTop:1,marginBottom:0},Q.createElement(Zx,null),Q.createElement(ee,{marginTop:0},Q.createElement(te,{color:jn.DIM},tP),Q.createElement(ee,{marginLeft:2},t?Q.createElement(te,{color:jn.DIM},"learning interrupted"):e?Q.createElement(te,{color:Un.TEXT},"learned your coding taste"):Q.createElement(nP,null)))),"RepoLearnTastePill");Ht(),dr();var rA=__name(({status:e})=>"active"===e?Q.createElement(ee,null,Q.createElement(te,{color:jn.YELLOW},Q.createElement(Fe,{type:"dots"})),Q.createElement(te,null," ")):"complete"===e?Q.createElement(te,{color:Hn.BG},ke.square," "):Q.createElement(te,{color:jn.DIM},ke.circle," "),"StepStatusIndicator"),sA=__name(({steps:e,currentMessage:t})=>Q.createElement(ee,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return Q.createElement(ee,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},Q.createElement(ee,null,Q.createElement(ee,{marginRight:1},Q.createElement(rA,{status:e.status})),Q.createElement(te,{bold:n,color:"complete"===e.status?jn.WHITE:n?jn.YELLOW:jn.DIM},e.label)),n&&t?Q.createElement(ee,{marginLeft:3},Q.createElement(te,{color:jn.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Ht(),dr();var oA=__name(({insights:e,insightCount:t})=>0===e.length?null:Q.createElement(ee,{flexDirection:"column",marginTop:1,marginLeft:4},Q.createElement(te,{color:jn.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>Q.createElement(te,{key:`${t}-${e}`,color:jn.DIM},XP[t%XP.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Ht(),dr();var iA=__name(({message:e})=>Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.RED,paddingX:2,paddingY:1,marginTop:1},Q.createElement(te,{color:jn.RED,bold:!0},"Oops, something went wrong:"),Q.createElement(ee,{marginTop:1},Q.createElement(te,null,e))),"RepoLearnErrorPanel");Ht(),dr(),Pr();var aA=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),s=e.learningCount>0;return Q.createElement(ee,{flexDirection:"column",marginLeft:3},Q.createElement(ee,{marginBottom:1,flexDirection:"row"},Q.createElement(te,{color:jn.DIM},tP),Q.createElement(ee,{marginLeft:2},Q.createElement(te,{color:Un.TEXT},s?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),Q.createElement(ee,{flexDirection:"column",marginLeft:1},Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},ke.pointerSmall," Taste stored in"," "),Q.createElement(Cr,{url:`file://${e.storage}`,text:r||".commandcode/taste/taste.md",color:jn.CYAN})),Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},ke.pointerSmall," Share your coding taste: ",Q.createElement(te,{color:jn.CYAN},"npx taste push --all")))),Q.createElement(ee,{marginTop:1,marginLeft:1},Q.createElement(te,{color:jn.DIM},s?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Ht(),dr();var lA=__name(({done:e,error:t})=>t?Q.createElement(ee,{marginTop:1},Q.createElement(te,{bold:!0},"Press ESC to exit")):e?Q.createElement(ee,{marginTop:1},Q.createElement(te,{bold:!0},"Press ENTER to continue")):Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"ESC to cancel")),"RepoLearnFooter");Ht(),dr();var cA=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=X(()=>u_(n),[n]);return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ot,{name:"vice"},Q.createElement(te,null,r.trimEnd()))),e?Q.createElement(te,{color:jn.WHITE},e):Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.WHITE},"Learning your coding taste from ",Q.createElement(te,{bold:!0,color:jn.CYAN},t??"repository")),Q.createElement(te,{color:jn.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:s,insightCount:o}){return e?Q.createElement(iA,{message:e}):t?Q.createElement(aA,{summary:n,elapsedSeconds:r}):Q.createElement(oA,{insights:s,insightCount:o})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:s}){const o=useRepoLearnState(n),i=Y(!1);return J(()=>{i.current||(i.current=!0,o.markStarted(),e().catch(()=>{}))},[e,o.markStarted]),se((e,n)=>{if(o.showLogin)return;const r=n.escape||""===e,s=n.return||"\n"===e||"\r"===e;r?t({published:!1,cancelled:!0}):(o.done||o.error)&&s&&t({published:!1,cancelled:!!o.error})}),o.showLogin?Q.createElement(ee,{flexDirection:"column"},Q.createElement(cA,{text:r,repoName:s}),Q.createElement(kx,{onComplete:(e,t)=>{o.setShowLogin(!1),e?Zv.resolveAuth():Zv.rejectAuth(t)},onCancel:()=>{o.setShowLogin(!1),Zv.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):Q.createElement(ee,{flexDirection:"column"},Q.createElement(cA,{text:r,repoName:s}),Q.createElement(nA,{isComplete:o.done&&!o.error,hasError:Boolean(o.error)}),Q.createElement(sA,{steps:o.steps,currentMessage:o.currentMessage}),Q.createElement(StatusPanel,{error:o.error,done:o.done,summary:o.summary,elapsedSeconds:o.elapsedSeconds,insights:o.insights,insightCount:o.insightCount}),Q.createElement(lA,{done:o.done,error:o.error}))}async function runRepoLearnProgress(e){return withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{Zv.reset();const r=new AbortController;let s,o,i=!1,a=!1;const l=__name(async()=>{try{s=await e.runTask(r.signal)}catch(e){r.signal.aborted||(o=e,Zv.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),Zv.markLearningComplete())}},"handleRunTask"),u=__name(({published:e,cancelled:l})=>{a||(a=!0,i=e,r.abort(),d.unmount(),Zv.reset(),o?n(o):t({result:s,published:i,cancelled:l}))},"handleExit"),d=oe(Q.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:u}));d.waitUntilExit().catch(e=>{Zv.reset(),n(e)})})}__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),rk();var uA=__name(e=>t=>{const n=parseInt(t,10);if(isNaN(n)||n<1)throw new Error(`${e} must be a positive integer`);return n},"parsePositiveInt");function createLearnCommand(){return new ve("learn").description("Learn coding taste from repository change history").argument("[source]","Local path, GitHub URL, or owner/repo (defaults to current directory)").option("--max-commits <number>","Maximum commits to analyze",uA("--max-commits"),200).addOption(new Ce("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(uA("--max-signals")).hideHelp()).option("--branch <name>","Branch to analyze (defaults to main/master)").action(async(e,t)=>{try{await learnTaste({source:e??".",maxCommits:t.maxCommits??200,maxSignals:t.maxSignals??50,branch:t.branch})}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`Error: ${t}`),process.exit(1)}})}async function learnTaste(t){const n=await D.stat(e.resolve(t.source)).then(e=>e.isDirectory()).catch(()=>!1),r=isTTY(),s=await resolveDisplayName(t.source),o=!await getAuthKey();if(o&&!r)return console.log(""),console.log(" Login required to learn taste."),console.log(""),console.log(" Run: cmd login"),console.log(` Then: npx taste learn ${t.source}`),void console.log("");let i;const a=__name(()=>{i?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",a);let l=!1;try{const e=__name(async e=>{const{summary:r,resolved:s}=await runLearnPipeline({...t,isLocalSource:n,needsAuth:o,signal:e});return i=s?.cleanup,r},"runTask");if(r){const t=n?void 0:[...JP];({cancelled:l}=await runRepoLearnProgress({runTask:e,repoName:s,stepOrder:t}))}else logLearnSummary({summary:await e((new AbortController).signal)})}finally{process.off("SIGINT",a),i&&await i()}r&&!l||process.exit(0),yC(),await _P({skipOnboarding:!0})}function getTastePath(t){const{target:n}=t;if("local-project"===n)return e.join(process.cwd(),".commandcode","taste");if("local-global"===n)return e.join(y.homedir(),".commandcode","taste");throw new Error(`Remote storage not yet implemented: ${n}`)}function getRootTasteFile(t){const{target:n}=t;return e.join(getTastePath({target:n}),"taste.md")}function getCategoryPath(t){const{target:n,category:r}=t;return e.join(getTastePath({target:n}),r)}function getCategoryTasteFile(t){const{target:n,category:r}=t;return e.join(getCategoryPath({target:n,category:r}),"taste.md")}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Ht(),Ht(),lw(),Ht(),Kt(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Ht(),Ht();var dA=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||dA.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const s=n[r].trim();return{endIdx:t+r,inclusive:dA.test(s)&&!s.startsWith("#")&&!s.startsWith("-")}}function joinMultiLineLearning(e,t,n){const{endIdx:r,inclusive:s}=findLookaheadEnd(e,t),o=s?r+1:r;return{combined:[n,...e.slice(t,o).map(e=>e.trim()).filter(e=>e.length>0)].join(" "),nextIdx:o}}function processRawLine(e,t){const n=e[t],r=t+1,s=n.trim();if(!s.startsWith("-"))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};if(dA.test(s))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:o,nextIdx:i}=joinMultiLineLearning(e,t+1,n);return{entry:{text:o,originalLineNum:r},nextIdx:i}}function preprocessLines(e){const t=[];let n=0;for(;n<e.length;){const{entry:r,nextIdx:s}=processRawLine(e,n);t.push(r),n=s}return t}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],s=t.substring(1).trim();if(!dA.test(s))return r.push({line:n,severity:"error",message:'Learning is missing "Confidence:" field',suggestion:'Format: "- Learning text. Confidence: 0.95" (value between 0.0 and 1.0)'}),r;const o=Array.from(s.matchAll(/confidence:\s*(\S+)/gi)),i=o.length>0?o[o.length-1]:null;if(!i)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const a=i[1],l=parseFloat(a);if(isNaN(l))return r.push({line:n,severity:"error",message:`Confidence value "${a}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;(l<0||l>1)&&r.push({line:n,severity:"error",message:`Confidence value ${l} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),l>=0&&l<=1&&0===l&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const u=void 0!==i.index?s.substring(0,i.index).trim():s.trim();return u&&0!==u.length?(u.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}),r):(r.push({line:n,severity:"error",message:'Learning has no text before "Confidence:"',suggestion:'Add descriptive text (e.g., "Use pnpm for package management")'}),r)}function hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=t.slice(n+1,n+4),s=r.findIndex(e=>e.trim().startsWith("# "));return(-1===s?r:r.slice(0,s)).some(e=>e.includes("See [")&&e.includes("taste.md"))}function buildResult(e){const{issues:t,filePath:n}=e,r=t.filter(e=>"error"===e.severity),s=t.filter(e=>"warning"===e.severity),o=0===r.length;if(0===t.length)return{valid:o,issues:[...t],summary:`${ke.tick} ${n} is valid`};const i=[];r.length>0&&i.push(`${r.length} error${r.length>1?"s":""}`),s.length>0&&i.push(`${s.length} warning${s.length>1?"s":""}`);const a=r.length>0?ke.cross:ke.warning;return{valid:o,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?le.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(le.dim(` → ${e.suggestion}`)),n}function formatIssueGroup(e,t,n){return 0===e.length?[]:[n,...e.flatMap(e=>formatSingleIssue(e,t)),""]}function formatValidationIssues(e){const{result:t,verbose:n=!0}=e;if(0===t.issues.length){const e=t.summary.charAt(0),n=t.summary.substring(2);return`${le.green(e)} ${le.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),s=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?le.red(t.summary):le.yellow(t.summary),"",...formatIssueGroup(r,le.red,le.bold(le.red("Errors:"))),...formatIssueGroup(s,le.yellow,le.bold(le.yellow("Warnings:")))].join("\n").trim()}__name(findLookaheadEnd,"findLookaheadEnd"),__name(joinMultiLineLearning,"joinMultiLineLearning"),__name(processRawLine,"processRawLine"),__name(preprocessLines,"preprocessLines"),__name(validateLearningLine,"validateLearningLine"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(buildResult,"buildResult"),Ht(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var mA=new Set(["# Taste (Continuously Learned by [CommandCode][cmd])","# Taste (Continuously Learned by CommandCode.ai)","# Taste (Continuously Learned by CommandCode)"]);function warnIfEmptyCategory(e,t){!e.currentCategory||e.learningsInCurrentCategory>0||hasReferenceAfterCategory({lines:t,categoryLineIndex:e.categoryLineNumber-1})||e.issues.push({line:e.categoryLineNumber,severity:"warning",message:`Category '${e.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function processHeading(e){const{line:t,lineNum:n,state:r,rawLines:s}=e;mA.has(t.trim())||(r.hasAnyCategory=!0,warnIfEmptyCategory(r,s),r.currentCategory=t.trim().substring(2).trim(),r.categoryLineNumber=n,r.learningsInCurrentCategory=0)}function processLearning(e){const{line:t,lineNum:n,state:r}=e;r.currentCategory?(r.learningsInCurrentCategory++,r.issues.push(...validateLearningLine({line:t.trim(),lineNum:n}))):r.issues.push({line:n,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'})}__name(warnIfEmptyCategory,"warnIfEmptyCategory"),__name(processHeading,"processHeading"),__name(processLearning,"processLearning");var pA=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,gA=/^\[cmd\]: https:\/\/commandcode\.ai\/$/i;function processLine(e){const{line:t,lineNum:n,state:r,rawLines:s}=e,o=t.trim();o&&(o.startsWith("# ")?processHeading({line:t,lineNum:n,state:r,rawLines:s}):o.startsWith("-")?processLearning({line:t,lineNum:n,state:r}):pA.test(o)||gA.test(o)||r.issues.push({line:n,severity:"error",message:"Invalid content - must be a category header (# name) or learning (- text)",suggestion:"Remove this line or format it as a category (# name) or learning (- text. Confidence: 0.XX)"}))}function checkFinalCategory(e){const{state:t,rawLines:n}=e;!t.currentCategory||t.learningsInCurrentCategory>0||!t.categoryLineNumber||hasReferenceAfterCategory({lines:n,categoryLineIndex:t.categoryLineNumber-1})||t.issues.push({line:t.categoryLineNumber,severity:"warning",message:`Category '${t.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function validateTasteFile(e){const{content:t,filePath:n}=e,r=[];if(!t.trim())return r.push({severity:"error",message:"File is empty",suggestion:"Add at least one category with learnings"}),buildResult({issues:r,filePath:n});const s=t.split("\n"),o=preprocessLines(s),i={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of o)processLine({line:e,lineNum:t,state:i,rawLines:s});return checkFinalCategory({state:i,rawLines:s}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var hA=__name(e=>"local-global"===e?"global":"project","locationLabel"),fA=__name(({file:e,error:t})=>({success:!1,filesLinted:[],errors:[{file:e,error:t}],totalErrors:0,totalWarnings:0}),"failResult");function resolvePackageFile(e,t){const n=getCategoryTasteFile({target:t,category:e});return C(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${hA(t)}`}}}function collectSpecificFiles(e){const{packages:t,target:n}=e,r=t.map(e=>resolvePackageFile(e,n));return{files:r.filter(e=>"result"in e).map(e=>e.result),errors:r.filter(e=>"error"in e).map(e=>e.error)}}async function collectAllFiles(e){const{tastePath:t,target:n}=e,r=[],s=getRootTasteFile({target:n});C(s)&&r.push({path:s,displayName:"taste.md"});const o=(await D.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>C(e)).map(({entry:e,categoryFile:t})=>({path:t,displayName:`${e.name}/taste.md`}));return r.push(...o),r}async function lintFile(e){let t=await D.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await D.writeFile(e.path,n,"utf-8"),t=n);const r=validateTasteFile({content:t,filePath:e.displayName}),s=r.issues.filter(e=>"error"===e.severity).length,o=r.issues.filter(e=>"warning"===e.severity).length,i=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:s,warnings:o,formatted:i}}async function lintSpecificPackages(e){const{packages:t,target:n}=e,{files:r,errors:s}=collectSpecificFiles({packages:t,target:n});if(0===r.length&&s.length>0)return{success:!1,filesLinted:[],errors:s,totalErrors:0,totalWarnings:0};if(0===r.length)return fA({file:"all",error:`No taste files found in ${hA(n)}`});const o=await Promise.all(r.map(lintFile)),i=o.reduce((e,t)=>e+t.errors,0),a=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid)&&0===s.length,filesLinted:o,errors:s,totalErrors:i,totalWarnings:a}}async function lintAllFiles(e){const{tastePath:t,target:n}=e,r=await collectAllFiles({tastePath:t,target:n});if(0===r.length)return fA({file:"all",error:`No taste files found in ${hA(n)}`});const s=await Promise.all(r.map(lintFile)),o=s.reduce((e,t)=>e+t.errors,0),i=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid),filesLinted:s,errors:[],totalErrors:o,totalWarnings:i}}async function lint(e){const{packages:t,target:n}=e,r=getTastePath({target:n});return C(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):fA({file:"all",error:`No taste directory found in ${hA(n)}`})}function resolveConflictStrategy(e){const t=[e.skip&&"skip",e.merge&&"merge",e.overwrite&&"overwrite"].filter(Boolean);return t.length>1&&exitWithError(`Cannot combine --${t[0]} and --${t[1]}. Choose one conflict strategy.`),t[0]}__name(resolvePackageFile,"resolvePackageFile"),__name(collectSpecificFiles,"collectSpecificFiles"),__name(collectAllFiles,"collectAllFiles"),__name(lintFile,"lintFile"),__name(lintSpecificPackages,"lintSpecificPackages"),__name(lintAllFiles,"lintAllFiles"),__name(lint,"lint"),Ht(),Cs(),__name(resolveConflictStrategy,"resolveConflictStrategy");var yA=le.bgGreen.black.bold(" TASTE ");function shortenPath(e){const t=process.env.HOME??process.env.USERPROFILE??"";return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function exitWithError(e){console.error(`${le.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`),process.exit(1)}function formatUsageLine(e){const t=e.match(/^(\s*(?:Usage:|or:)?\s*)(cmd)(\s+.+?)(\s+\(.*\))?$/);return t?`${le.dim(t[1])}${le.green(t[2])}${le.white(t[3]??"")}${t[4]?le.dim(t[4]):""}`:le.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${le.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`);for(const e of t)console.error(formatUsageLine(e));process.exit(1)}function resolveRemoteDefault(e){return e.global||e.remote?e:{...e,remote:!0}}__name(shortenPath,"shortenPath"),__name(exitWithError,"exitWithError"),__name(formatUsageLine,"formatUsageLine"),__name(exitWithUsage,"exitWithUsage"),__name(resolveRemoteDefault,"resolveRemoteDefault");var wA=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return ut(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:wA})}function getProfileLink(e){return ut(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:wA})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return ct(e,n,{trim:!1})}function formatMergeParts(e){const t=[];return e.added>0&&t.push(`${e.added} ${1===e.added?"learning":"learnings"} added`),e.updated>0&&t.push(`${e.updated} ${1===e.updated?"learning":"learnings"} updated`),e.unchanged>0&&t.push(`${e.unchanged} ${1===e.unchanged?"learning":"learnings"} unchanged`),t}function hasMergeConflictRisk(e){return(e.added>0||e.updated>0)&&e.unchanged>0}function hasMergeConflictRiskInRecord(e){return Object.values(e).some(hasMergeConflictRisk)}function logMergeReviewTip(){console.log(le.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function parseOwnerPackage(e){if(!e.includes("/"))return;const[t,n]=e.split("/");return t&&n?{owner:t,packageName:n}:void 0}function handleResultErrors(e){for(const t of e){const e=t.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${t.pkg}' `);console.error(`${le.red("Error:")} ${e}`)}process.exit(1)}function getTimeAgo(e){const t=Date.now()-e.getTime(),n=Math.floor(t/6e4),r=Math.floor(t/36e5),s=Math.floor(t/864e5);return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:r<24?`${r} hour${r>1?"s":""} ago`:`${s} day${s>1?"s":""} ago`}async function flushAndExit(e){await Promise.race([shutdownTelemetry(),new Promise(e=>setTimeout(e,500))]).catch(()=>{}),process.exit(e)}function withErrorHandler(e){return async(...t)=>{try{await e(...t),await flushAndExit(0)}catch(e){const t=e instanceof Error?e.message:String(e);console.error(le.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new ve("lint").argument("[package]","Taste package name").option("-g, --global","Validate taste packages from global storage (~/.commandcode)").option("--all","Validate all taste packages").description(`Validate taste package format ${le.dim("(structure, style, etc.)")}`).action(withErrorHandler(async(e,t)=>runLint({packageName:e,options:t})))}function validateLintOptions({packageName:e,options:t}){e||t.all||exitWithUsage({message:"Specify a taste package name or use --all to validate everything",usage:["cmd taste lint <package> validate a taste package","cmd taste lint --all validate all taste packages"]}),e&&t.all&&exitWithError("Use either a package name or --all, not both")}function logLintResults(e){for(const t of e.filesLinted)console.log(t.formatted);e.filesLinted.length>1&&logLintSummary(e),e.success||process.exit(1)}function logLintSummary({filesLinted:e,totalErrors:t,totalWarnings:n}){if(console.log(""),0===t&&0===n)return void console.log(`${le.green(ke.tick)} All ${le.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(le.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(le.yellow(`${n} warning${n>1?"s":""}`)),console.log(`Summary: ${r.join(", ")} across ${e.length} files`)}async function runLint({packageName:e,options:t}){console.log(""),validateLintOptions({packageName:e,options:t});const n=await lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(le.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}function parseSection(e){const{section:t,sourcePath:n}=e,r=t.split("\n"),s=r[0].trim(),o=r.map(e=>parseLearning({line:e})).filter(e=>null!==e);return 0===o.length?null:{category:normalizeCategory({category:s}),learnings:o,sourcePath:n}}function parsePackages(e){const{content:t,sourcePath:n}=e;return t.split(/^# /gm).filter(e=>e.trim()).filter(e=>!e.includes("See [")).map(e=>parseSection({section:e,sourcePath:n})).filter(e=>null!==e)}function parseLearning(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)[\.:,]?\s*confidence:\s*(\d*\.?\d+)/i);if(!n)return null;const r=parseFloat(n[2]);return isNaN(r)||r<0||r>1?null:{text:n[1].trim(),confidence:r}}function normalizeCategory(e){const{category:t}=e;return t.toLowerCase().replace(/\s+/g,"-")}function denormalizeCategory(e){const{slug:t}=e;return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function formatPackage(e){const{pkg:t}=e;let n=`# ${denormalizeCategory({slug:t.category})}\n`;for(const e of t.learnings)n+=`- ${e.text}. Confidence: ${e.confidence.toFixed(2)}\n`;return n}async function readAndMigrateFile(e){const{filePath:t}=e,n=await D.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await D.writeFile(t,r,"utf-8"),r)}function trimTrailingBlanks(e){const{lines:t,until:n}=e;let r=e.from;for(;r>n&&""===t[r].trim();)r--;return r}function findCategoryRange(e){const{lines:t,pattern:n}=e,r=t.findIndex(e=>n.test(e));if(-1===r)return null;const s=t.findIndex((e,t)=>t>r&&e.startsWith("# "));if(-1===s)return{start:r,end:t.length-1};const o=trimTrailingBlanks({lines:t,from:s-1,until:r});return{start:r,end:o}}function ensureHeader(e){if(!e)return nw+"\n\n";const t=e.trim();return t.startsWith(ew)||t.startsWith(rw)||t.startsWith(sw)?e:nw+"\n\n"+e}function ensureTrailingNewlines(e){return e?e.endsWith("\n\n")?e:e.endsWith("\n")?e+"\n":e+"\n\n":e}__name(getPackageLink,"getPackageLink"),__name(getProfileLink,"getProfileLink"),__name(wrapLine,"wrapLine"),__name(formatMergeParts,"formatMergeParts"),__name(hasMergeConflictRisk,"hasMergeConflictRisk"),__name(hasMergeConflictRiskInRecord,"hasMergeConflictRiskInRecord"),__name(logMergeReviewTip,"logMergeReviewTip"),__name(parseOwnerPackage,"parseOwnerPackage"),__name(handleResultErrors,"handleResultErrors"),__name(getTimeAgo,"getTimeAgo"),__name(flushAndExit,"flushAndExit"),__name(withErrorHandler,"withErrorHandler"),__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Ht(),Ls(),Ht(),Ht(),Ht(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Ht(),__name(formatPackage,"formatPackage"),Ht(),lw(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var SA="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:SA,category:e.name});return C(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await D.stat(e.sourcePath);return{category:e.category,learningCount:e.learnings.length,lastUpdated:t.mtime,filePath:e.sourcePath}}catch{return{category:e.category,learningCount:e.learnings.length,lastUpdated:new Date,filePath:e.sourcePath}}}async function getAllPackages(){const e=getTastePath({target:SA});if(!C(e))return[];const t=await D.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:SA,category:t});return C(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:SA});await D.mkdir(r,{recursive:!0});const s=getCategoryTasteFile({target:SA,category:n.category}),o=e.dirname(s);await D.mkdir(o,{recursive:!0});const i=formatPackage({pkg:n});await D.writeFile(s,i,"utf-8")}async function listPackages(){const e=await getAllPackages();return await Promise.all(e.map(getPackageInfo))}__name(loadCategoryPackages,"loadCategoryPackages"),__name(getPackageInfo,"getPackageInfo"),__name(getAllPackages,"getAllPackages"),__name(getPackage,"getPackage"),__name(writePackage,"writePackage"),__name(listPackages,"listPackages"),Ht(),Ht(),lw();var bA="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!C(n))return null;const r=migrateHeader({content:await D.readFile(n,"utf-8")}).split("\n"),s=findCategoryRange({lines:r,pattern:new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i")});if(!s)return null;const o=r.slice(0,s.start),i=s.end<r.length-1?r.slice(s.end+1):[],a={before:o.join("\n").trim(),after:i.join("\n").trim()},l=[...o,...i].join("\n").trim();return""===l&&await D.rm(n,{force:!0}),""!==l&&await D.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:bA}),s=await removeCategoryFromRoot({category:n,rootFile:r}),o=getCategoryTasteFile({target:bA,category:n}),i=e.dirname(o);return C(i)&&await D.rm(i,{recursive:!0,force:!0}),s}async function writeToRoot(e){const{pkg:t,rootFile:n,categoryPosition:r}=e,s=formatPackage({pkg:t});if(r){let e=ensureHeader(migrateHeader({content:r.before}));e=ensureTrailingNewlines(e);const t=r.after?"\n\n"+r.after:"";return e+=s.trim()+t,void await D.writeFile(n,e.trim()+"\n","utf-8")}let o="";C(n)&&(o=await D.readFile(n,"utf-8"),o=migrateHeader({content:o})),o=ensureHeader(o),o=ensureTrailingNewlines(o),o+=s,await D.writeFile(n,o.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:s}=t,o=getCategoryTasteFile({target:bA,category:n.category}),i=e.dirname(o);await D.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await D.writeFile(o,a,"utf-8");const l=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(s){let e=ensureHeader(migrateHeader({content:s.before}));e=ensureTrailingNewlines(e);const t=s.after?"\n\n"+s.after:"";return e+=l.trim()+t,void await D.writeFile(r,e.trim()+"\n","utf-8")}let u="";C(r)&&(u=await D.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await D.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var EA="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:EA,category:e.name});return C(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:EA});if(!C(e))return[];const t=[],n=getRootTasteFile({target:EA});if(C(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await D.readdir(e,{withFileTypes:!0}),s=(await Promise.all(r.map(loadCategoryPackages2))).flat();return t.push(...s),t}async function getPackage2(e){const{category:t}=e;return(await getAllPackages2()).find(e=>e.category===t)||null}async function writePackage2(e){const{pkg:t}=e,n=getTastePath({target:EA});await D.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:EA}),s=await removePackage({category:t.category});t.learnings.length<=5?await writeToRoot({pkg:t,rootFile:r,categoryPosition:s}):await writeToSubdirectory({pkg:t,rootFile:r,categoryPosition:s})}function exists2(){const e=getTastePath({target:EA});return C(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!C(n))return;const r=await D.readFile(n,"utf-8"),s=new Blob([r],{type:"text/markdown"}),o=new File([s],"taste.md",{type:"text/markdown"});e.append(`files[${t.category}/taste.md]`,o)}async function prepareUploadFormData(t){const{packageName:n,pkg:r,description:s,type:o="category",isPublic:i=!1,overwrite:a=!1}=t,l=new FormData;l.append("name",n),s&&l.append("description",s),l.append("type",o),l.append("isPublic",String(i)),l.append("overwrite",String(a));const u=formatPackage({pkg:r}),d=new Blob([u],{type:"text/markdown"}),m=new File([d],"taste.md",{type:"text/markdown"});if(l.append("files[taste.md]",m),"category"===o)return l;const g=getTastePath({target:"local-project"}),h=e.join(g,r.category);if(!C(h))return l;const f=getCategoryTasteFile({target:"local-project",category:r.category});if(!C(f))return l;const y=await D.readFile(f,"utf-8"),w=new Blob([y],{type:"text/markdown"}),S=new File([w],"taste.md",{type:"text/markdown"});return l.append(`files[${r.category}/taste.md]`,S),l}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:s=!1,overwrite:o=!1}=e,i=new FormData;i.append("name",n),r&&i.append("description",r),i.append("type","project"),i.append("isPublic",String(s)),i.append("overwrite",String(o));const a=getRootTasteFile({target:"local-project"});if(C(a)){const e=await D.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});i.append("files[taste.md]",n)}const l=t.map(e=>appendCategoryFile(i,e));return await Promise.all(l),i}function parseLearningLine(e){const t=e.match(/^-\s+(.+?)\.\s+Confidence:\s+([\d.]+)/);if(!t)return null;const n=t[1].trim(),r=parseFloat(t[2]);return!n||isNaN(r)?null:{text:n,confidence:r}}function parseTasteContent(e){return e.split("\n").filter(e=>{const t=e.trim();return t&&!t.startsWith("#")&&t.startsWith("-")}).map(e=>parseLearningLine(e.trim())).filter(e=>null!==e)}async function parseApiError(e){const{response:t,fallback:n}=e;try{const e=await t.json();return e.error?.message||e.message||n}catch{return n}}function throwTrackedError(e){const{message:t,label:n,heading:r,status:s,extra:o}=e,i=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:i,label:n}),context:{component:ys.TASTE_REMOTE_STORAGE,heading:r,"http.status":s,...o}}),i}async function requireAuthKey(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");return e}async function downloadPackage(e){const{owner:t,packageName:n}=e,r=getApiBaseUrl(),s=await tryPublicDownload({baseUrl:r,owner:t,packageName:n});if(s)return s;const o=await getAuthKey();if(!o)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");return tryAuthenticatedDownload({baseUrl:r,owner:t,packageName:n,apiKey:o})}async function tryPublicDownload(e){const{baseUrl:t,owner:n,packageName:r}=e,s=`${t}${kt.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",n).replace(":packageName",r)}`;let o;try{o=await fetch(s,{method:"GET"})}catch{return null}if(o.ok){const{data:e}=await o.json();return{type:e.type||"category",files:e.files||[],isPublic:!0}}if(404===o.status)return null;throwTrackedError({message:await parseApiError({response:o,fallback:`Failed to download taste package (${o.status})`}),label:"download_public_error",heading:"Failed to download taste package (public)",status:o.status})}async function tryAuthenticatedDownload(e){const{baseUrl:t,owner:n,packageName:r,apiKey:s}=e,o=`${t}${kt.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,i=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${s}`}});if(i.ok){const{data:e}=await i.json();return{type:e.type||"category",files:e.files||[],isPublic:e.isPublic??!1}}if(404===i.status)return null;throwTrackedError({message:await parseApiError({response:i,fallback:"Failed to download taste package"}),label:"download_auth_error",heading:"Failed to download taste package (authenticated)",status:i.status})}async function fetchSinglePackage(e){try{return await getPackage3({category:e.name})}catch(t){const n=t instanceof Error?t:new Error(String(t));return trackError({error:sanitizeErrorForTelemetry({error:n,label:"download_package_error"}),context:{component:ys.TASTE_REMOTE_STORAGE,heading:"Failed to download package","package.name":e.name}}),console.warn(`Warning: Failed to download package '${e.name}': ${n.message}`),null}}async function getAllPackages3(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${kt.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list taste packages",status:n.status});const{data:r}=await n.json(),s=r.packages||[];if(0===s.length)return[];const o=[];for(let e=0;e<s.length;e+=5){const t=s.slice(e,e+5),n=await Promise.all(t.map(fetchSinglePackage));o.push(...n.filter(e=>null!==e))}return o}async function getPackage3(e){const{category:t}=e;let n;await requireAuthKey();try{n=await getAuthenticatedEntity()}catch(e){const n=e instanceof Error?e:new Error(String(e));throw dlog(`[Auth] getPackage: entity endpoint unavailable — ${n.message}`),trackError({error:sanitizeErrorForTelemetry({error:n,label:"get_entity_error"}),context:{component:ys.TASTE_REMOTE_STORAGE,heading:"getAuthenticatedEntity failed in getPackage"}}),new Error(`Could not resolve your account to fetch '${t}'. Check your connection and try again.`)}if(!n.success||!n.user?.userName)throw new Error("Failed to get authenticated user information");return downloadRemotePackage({owner:n.user.userName,packageName:t})}async function downloadRemotePackage(e){const{owner:t,packageName:n}=e,r=await downloadPackage({owner:t,packageName:n});if(!r)return null;const s=r.files||[];if(0===s.length)return null;const o=s.find(e=>"taste.md"===e.file);if(!o)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(o.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async function writePackage3(e){const{pkg:t,owner:n,isPublic:r=!1,overwrite:s=!1}=e,o=await requireAuthKey(),i=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r,overwrite:s}),a=`${getApiBaseUrl()}${kt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:i});l.ok||throwTrackedError({message:await parseApiError({response:l,fallback:"Failed to upload taste package"}),label:"upload_package_error",heading:"Failed to upload taste package",status:l.status}),await l.json()}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:s=!1,overwrite:o=!1}=e,i=await requireAuthKey(),a=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:s,overwrite:o}),l=`${getApiBaseUrl()}${kt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,u=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${i}`},body:a});u.ok||throwTrackedError({message:await parseApiError({response:u,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:u.status,extra:{"package.count":t.length}}),await u.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${kt.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list packages",status:n.status});const{data:r}=await n.json();return(r.packages||[]).map(e=>({category:e.name,learningCount:e.learningCount||0,lastUpdated:e.createdAt?new Date(e.createdAt):new Date,filePath:"",isPublic:e.isPublic??!1,starCount:e.starCount??0,downloadCount:e.downloadCount??0,type:e.type??"category"}))}async function list(e){const{location:t}=e;if("local-global"===t)return listPackages();if("remote-project"===t||"remote-user"===t)return listPackages2();if("local-project"===t){const e=getRootTasteFile({target:"local-project"}),t=await getAllPackages2();return Promise.all(t.map(async t=>{let n;if(t.sourcePath!==e)try{n=(await D.stat(t.sourcePath)).mtime}catch{}return{category:t.category,learningCount:t.learnings.length,lastUpdated:n,filePath:t.sourcePath}}))}throw new Error(`Invalid location: ${t}`)}function createListCommand(){return new ve("list").alias("ls").option("-g, --global","List global packages").addOption(new Ce("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ce("--staging","Use staging environment").hideHelp()).description(`List available packages ${le.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}__name(loadCategoryPackages2,"loadCategoryPackages"),__name(getAllPackages2,"getAllPackages"),__name(getPackage2,"getPackage"),__name(writePackage2,"writePackage"),__name(exists2,"exists"),Ht(),Xy(),Ht(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),Kt(),Ht(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),sk(),Cs(),Ht(),rk(),Cs(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Ht(),Xy(),rk(),Kt(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),In(),__name(fetchSinglePackage,"fetchSinglePackage"),__name(getAllPackages3,"getAllPackages"),__name(getPackage3,"getPackage"),__name(downloadRemotePackage,"downloadRemotePackage"),__name(writePackage3,"writePackage"),__name(writePackages,"writePackages"),__name(listPackages2,"listPackages"),__name(list,"list"),__name(createListCommand,"createListCommand");var vA={remote:{location:"remote-project",name:"remote",subtitle:"commandcode.ai account"},global:{location:"local-global",name:"global",subtitle:"~/.commandcode/taste"},project:{location:"local-project",name:"project",subtitle:".commandcode/taste"}};function resolveStorage(e){return e.remote?vA.remote:e.global?vA.global:vA.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${ke.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${ke.arrowDown}${e.downloadCount}`.length),t}function formatPackageLine({pkg:e,maxLen:t}){const n=" ".repeat(t-getPackageDisplayLength(e)+2),r=e.lastUpdated?getTimeAgo(e.lastUpdated):null,s=r?`, updated ${r}`:"";return` ${le.white(e.category)}${e.isPublic?le.green(" [public]"):""}${e.isPublic&&e.starCount?le.yellow(` ${ke.star}${e.starCount}`):""}${e.downloadCount?le.gray(` ${ke.arrowDown}${e.downloadCount}`):""}${n}${le.dim.gray(`(${e.learningCount} learnings${s})`)}`}function validateListOptions(e){e.global&&e.remote&&exitWithError("Error: Cannot specify both --global and --remote flags")}async function fetchPackages({options:e}){const t=resolveStorage(e),n=e.remote?Te(`Fetching ${t.name} packages`).start():null,r=await list({location:t.location});return n?.stop(),{packages:r,storage:t}}async function getStorageLabel({options:e,fallback:t}){if(!e.remote)return t;const n=await getUserName();return n?getProfileLink(n):t}function printPackageTable({packages:e,subtitle:t}){console.log(`\n${yA} Packages`),console.log(`${le.gray("⎿")} ${le.dim(t)}\n`);const n=Math.max(...e.map(getPackageDisplayLength));let r=0;for(const t of e)r+=t.learningCount,console.log(formatPackageLine({pkg:t,maxLen:n}));console.log(le.dim(`\nTotal: ${e.length} packages, ${r} learnings\n`))}async function runList({options:e}){console.log(""),validateListOptions(e);const{packages:t,storage:n}=await fetchPackages({options:e});0!==t.length?printPackageTable({packages:t,subtitle:await getStorageLabel({options:e,fallback:n.subtitle})}):console.log(le.yellow(`No taste packages found in ${n.name}`))}async function fetchAllPackages(e){const{target:t}=e;return"local-project"===t?getAllPackages2():"local-global"===t?getAllPackages():getAllPackages3()}function handleOpenError(e){return e instanceof Error&&e.message.includes("$EDITOR environment variable")?{success:!1,error:getEditorSetupInstructions()}:{success:!1,error:e instanceof Error?e.message:String(e)}}async function readCategoryLineNumber(t){const{filePath:n,category:r}=t,s=await D.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const o=s.split("\n").findIndex(e=>e.trim().toLowerCase()===`# ${r.toLowerCase()}`);return o>=0?o+1:1}async function findCategoryLineNumber(e){try{return await readCategoryLineNumber(e)}catch{return 1}}async function openPackage(e){const{packageName:t,target:n}=e,r=(await fetchAllPackages({target:n})).find(e=>e.category===t);if(!r){let e="project";return"local-global"===n&&(e="global"),"remote-project"!==n&&"remote-user"!==n||(e="remote"),{success:!1,error:`Taste package '${t}' not found in ${e}`}}const s=r.sourcePath,o=await findCategoryLineNumber({filePath:s,category:t});return await it([{file:s,line:o}]),{success:!0,filePath:s,lineNumber:o}}__name(resolveStorage,"resolveStorage"),__name(getPackageDisplayLength,"getPackageDisplayLength"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),Ht(),Ht(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var CA=new Set(["local-project","local-global","remote-project","remote-user"]);async function open9(e){const{package:t,target:n}=e;if(!CA.has(n))return{success:!1,error:`Invalid target: ${n}`};try{return await openPackage({packageName:t,target:n})}catch(e){return handleOpenError(e)}}function getEditorSetupInstructions(){const e=dt.platform;if("win32"===e)return'Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n\nCommand Prompt (as Administrator):\n setx EDITOR "code" # VS Code\n setx EDITOR "notepad" # Notepad\n setx EDITOR "vim" # Vim (if installed via WSL/Git Bash)\n\nPowerShell:\n [Environment]::SetEnvironmentVariable("EDITOR", "code", "User")\n\nThen restart your terminal.';const t="darwin"===e?"~/.zshrc":"~/.bashrc";return`Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n echo 'export EDITOR="code"' >> ${t} # VS Code\n echo 'export EDITOR="vim"' >> ${t} # Vim\n echo 'export EDITOR="nano"' >> ${t} # Nano\n echo 'export EDITOR="subl"' >> ${t} # Sublime Text\n\nFor bash users ${"darwin"===e?"(or ~/.bash_profile for bash)":"(or ~/.zshrc for zsh)"}, replace ${t} with the appropriate file.\n\nThen restart your terminal or run: source ${t}`}function createOpenCommand(){return new ve("open").argument("[package]","Taste package name, or owner/package to open in browser").option("-g, --global","Open taste package from global storage (~/.commandcode)").description(`Open a taste package in your editor ${le.dim("(use owner/package to open in browser)")}`).action(withErrorHandler(async(e,t)=>runOpen({packageName:e,options:t})))}function validateOpenOptions(e){e||exitWithUsage({message:"Specify a taste package name to open",usage:["cmd taste open <package> open taste package in editor","cmd taste open <package> -g open global taste package in editor","cmd taste open owner/package open package page in browser"]})}async function runOpen({packageName:e,options:t}){console.log(""),validateOpenOptions(e);const n=parseOwnerPackage(e);n?await openInBrowser(n):await openInEditor3({packageName:e,options:t})}async function openInBrowser(e){const t=`https://commandcode.ai/${e.owner}/${e.packageName}`;await me(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${le.green(ke.tick)} Opened ${n} in browser`)}async function openInEditor3({packageName:e,options:t}){const n=t.global?"local-global":"local-project",r=await open9({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${le.green(ke.tick)} Opened ${le.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open9,"open"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor3,"openInEditor"),Ht(),Ht(),Ht(),Ht();var kA=null,TA=!1;function setActiveSpinner(e){kA=e}function stopActiveSpinner(e){kA&&(kA.stop(e),kA=null)}function setPrompted(e){TA=e}function wasPrompted(){return TA}function beginPrompt(e,t){stopActiveSpinner(),qe.intro(le.dim(e)),t&&qe.log.message(le.dim(t)),setPrompted(!0)}function handleCancel(e){qe.isCancel(e)&&(qe.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=qe.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=qe.spinner();r.start(t),setActiveSpinner({stop:__name(e=>r.stop(e??n),"stop"),cancel:__name(e=>r.cancel(e),"cancel"),error:__name(e=>r.error(e),"error")})}async function promptMergeStrategy(e){const{packageName:t,owner:n,localPkg:r,remoteLearningsCount:s}=e,o="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),qe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${le.green(`'${t}'`)} from ${n}`,o),qe.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${s} learnings ${le.dim(`(from ${n})`)}`);const i=await qe.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with remote (${r.learnings.length} → ${s} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});handleCancel(i);const a=i;return startStrategySpinner(a),a}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalPkg:r}=e,s="This package already exists in global storage";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),qe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${le.green(`'${t}'`)} to global`,s),qe.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const o=await qe.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace global with local (${r.learnings.length} → ${n} learnings)`},{value:"skip",label:"Skip",hint:"Keep global version, cancel push"}],initialValue:"merge"});handleCancel(o);const i=o;return startStrategySpinner(i),i}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e,s="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),qe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${le.green(`'${t}'`)} from global`,s),qe.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const o=await qe.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with global (${n.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore global"}],initialValue:"merge"});handleCancel(o);const i=o;return startStrategySpinner(i),i}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:s}=e,o=`Pushing local project taste to individual package '${t}'`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),qe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ut(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${le.green(`'${t}'`)} to ${n}`,o),qe.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${s} learnings) in ${n}`),qe.log.info(`Current package: ${le.cyan(i)} ${le.dim("(review)")}`);const a=await qe.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:"Replace individual remote package with local project taste"}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:s}=e,o=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),qe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ut(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${le.green(`'${t}'`)} to ${n}`,o),qe.log.message(`Local: ${r} learnings\nRemote: ${s} learnings`),qe.log.info(`Current package: ${le.cyan(i)} ${le.dim("(review)")}`);const a=await qe.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${s} → ${r} learnings)`}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}function mergeSingleLearning(e,t,n,r){const s=t.get(e.text);return s?e.confidence>s.confidence?(n.set(e.text,e),void r.updated++):void r.unchanged++:(n.set(e.text,e),void r.added++)}function mergePackages(e){const{source:t,target:n}=e,r={added:0,updated:0,unchanged:0},s=new Map(n.map(e=>[e.text,e])),o=new Map(s);for(const e of t)mergeSingleLearning(e,s,o,r);const i=new Set(t.map(e=>e.text)),a=n.filter(e=>!i.has(e.text)).length;return r.unchanged+=a,{merged:Array.from(o.values()),details:r}}function validateSinglePackage(e,t){const n=validateTasteFile({content:formatPackage({pkg:e}),filePath:`${e.category}/taste.md`});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:e.category,error:`Validation failed for taste package in ${t}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${e.category}' in ${t} has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validateSingleRemoteFile(e,t){const n=validateTasteFile({content:e.content,filePath:e.file});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:t,error:`Validation failed for ${e.file}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: File '${e.file}' has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validatePackages(e){const{packages:t,label:n}=e;return t.map(e=>validateSinglePackage(e,n)).filter(e=>null!==e)}function validateRemoteFiles(e){const{files:t,packageName:n}=e;return t.map(e=>validateSingleRemoteFile(e,n)).filter(e=>null!==e)}function mergeOrKeep(e){const{source:t,existing:n}=e;if(!n)return{pkg:t,details:{added:t.learnings.length,updated:0,unchanged:0}};const r=mergePackages({source:t.learnings,target:n.learnings});return{pkg:{...t,learnings:r.merged},details:r.details}}async function resolveRemotePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,tastePkg:s,owner:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r?promptMergeStrategy({packageName:s.category,owner:o,localPkg:r,remoteLearningsCount:s.learnings.length}):"merge"}async function executePackageStrategy(e){const{tastePkg:t,owner:n,overwrite:r,flagStrategy:s,result:o}=e,i=await getPackage2({category:t.category}),a=await resolveRemotePullStrategy({flagStrategy:s,overwrite:r,existingPkg:i,tastePkg:t,owner:n});if("skip"===a)return void o.skipped?.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),o.packagesPulled.push(t.category),o.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),o.packagesPulled.push(t.category),o.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});o.filePaths[t.category]=l}async function processPackage(e){const{tastePkg:t,result:n}=e;try{await executePackageStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullProjectPackage(e){const{files:t,packageName:n,owner:r,overwrite:s,flagStrategy:o,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(a){const e=parsePackages({content:a.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processPackage({tastePkg:t,owner:r,overwrite:s,flagStrategy:o,result:i})}const l=t.filter(e=>"taste.md"!==e.file);for(const e of l){const t=e.file.replace("/taste.md",""),a={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processPackage({tastePkg:a,owner:r,overwrite:s,flagStrategy:o,result:i})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:s,flagStrategy:o,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(!a)return i.success=!1,void i.errors.push({pkg:n,error:"No taste.md file found in category package"});const l={category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:l,owner:r,overwrite:s,flagStrategy:o,result:i})}__name(setActiveSpinner,"setActiveSpinner"),__name(stopActiveSpinner,"stopActiveSpinner"),__name(setPrompted,"setPrompted"),__name(wasPrompted,"wasPrompted"),__name(beginPrompt,"beginPrompt"),__name(handleCancel,"handleCancel"),__name(startStrategySpinner,"startStrategySpinner"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),Ht(),Ht(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Ht(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var _A=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),xA=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),PA=__name(e=>"local-global"===e?"global":"remote-project"===e?"remote project":"remote-user"===e?"remote":"source","sourceName");async function resolvePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,source:s,tastePkg:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===s?promptGlobalPullStrategy({packageName:o.category,localPkg:r,globalLearningsCount:o.learnings.length}):"merge"}async function executePullStrategy(e){const{tastePkg:t,source:n,flagStrategy:r,overwrite:s,result:o}=e,i=await getPackage2({category:t.category}),a=await resolvePullStrategy({flagStrategy:r,overwrite:s,existingPkg:i,source:n,tastePkg:t});if("skip"===a)return void o.skipped.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),o.packagesPulled.push(t.category),o.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),o.packagesPulled.push(t.category),o.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});o.filePaths[t.category]=l}async function pullSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePullStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pull(e){const{packages:t,source:n,overwrite:r=!1,strategy:s}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return _A({pkg:"all",error:`Invalid source: ${n}`});const o=PA(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return _A({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return _A({pkg:"all",error:`No taste packages found in ${o}`});const a=validatePackages({packages:i,label:o});if(a.length>0)return{success:!1,packagesPulled:[],errors:[...a],mergeDetails:{},overwritten:[],filePaths:{}};const l=t.length>0?i.filter(e=>t.includes(e.category)):i;if(t.length>0&&0===l.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${o}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=xA();for(const e of l)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:s,overwrite:r,result:u});return u}async function executePullRemote(e){const{owner:t,packageName:n,overwrite:r,flagStrategy:s,result:o}=e,i=await downloadPackage({owner:t,packageName:n});if(!i)return _A({pkg:n,error:"Taste package not found in remote"});const{type:a,files:l}=i,u=validateRemoteFiles({files:l,packageName:n});if(u.length>0)return{success:!1,packagesPulled:[],errors:[...u],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:l,packageName:n,owner:t,overwrite:r,flagStrategy:s,result:o};return"project"===a?(await pullProjectPackage(d),o):(await pullCategoryPackage(d),o)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:s}=e,o=xA();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:s,result:o})}catch(e){return _A({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return qe.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:s,mergeDetails:o}=e,i=wasPrompted()?"":`${ke.tick} `,a=r?le.dim(`\n ${shortenPath(r)}`):"";if(s.overwrite)return`${le.green(i)}Replaced ${le.green(`'${t}'`)} taste package in project`+a;if(o){const e=formatMergeParts(o);return`${le.green(i)}Pulled ${le.green(`'${t}'`)} taste package from ${n} ${le.gray(`(${e.join(", ")})`)}`+a}return`${le.green(i)}Pulled ${le.green(`'${t}'`)} taste package from ${n}`+a}function logPullSingleSuccess(e){const{result:t,sourceName:n,options:r}=e;if(1!==t.packagesPulled.length)return!1;const s=t.packagesPulled[0],o=t.filePaths?.[s],i=t.mergeDetails?.[s];return logResult(buildPullMessage({pkgName:s,sourceName:n,filePath:o,options:r,mergeDetails:i})),!r.overwrite&&!!i&&hasMergeConflictRisk(i)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],s=t.skipped??[],o=t.packagesPulled.filter(e=>!r.includes(e)),i=t.packagesPulled.length+s.length,a=`${i} ${1===i?"package":"packages"}`,l=[];return o.length>0&&l.push(wrapLine(`${le.green("Pulled")} (${o.length}) ${o.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${le.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),s.length>0&&l.push(wrapLine(`${le.dim("Skipped")} (${s.length}) ${le.dim(s.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&qe.log.message(l.join("\n")),qe.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${le.green(ke.tick)} ${a} from ${n}`),l.length>0&&console.log(l.join("\n")),hasMergeConflictRiskInRecord(t.mergeDetails??{}))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,s=t.skipped??[];t.packagesPulled.length+s.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():s.length>0?logResult(le.yellow(`Skipped '${s[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new ve("pull").argument("[package]","Taste package name, or owner/package to pull from remote").option("-g, --global","Pull taste package from global storage (~/.commandcode)").addOption(new Ce("--local","Use local server").hideHelp()).option("--remote","Pull taste package from commandcode.ai remote").option("--all","Pull all taste packages from global").option("--overwrite","Replace local package without prompting").option("--skip","Keep local package, skip conflicting pull").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new Ce("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${le.dim("(prompts on conflicts)")}`).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),{result:r,owner:s}=await runPull({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPullSuccess({result:r,sourceName:n.remote?s??"remote":"global",options:n})}))}function validatePullOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one source"),n.remote&&n.all&&exitWithUsage({message:"--all is not supported for remote pull — specify a package instead",usage:["cmd taste pull <owner>/<package> pull a taste package from remote"]}),n.remote&&!t&&exitWithUsage({message:"Specify a taste package to pull from remote",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),n.remote&&t&&!t.includes("/")&&exitWithUsage({message:`Remote pull requires owner/package format — got '${t}'`,usage:["cmd taste pull <owner>/<package> e.g. cmd taste pull ahmadawais/code-style"]}),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to pull everything",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}async function runPull(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePullOptions({packageName:t,options:r});const s=resolveConflictStrategy(r);return r.remote&&t?pullRemoteSingle({packageName:t,options:r,strategy:s}):pullGlobal({packageName:t,options:r,strategy:s})}async function pullRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,s=parseOwnerPackage(t);s||exitWithError("Invalid format — use owner/package (e.g. ahmadawais/code-style)"),setActiveSpinner(Te("Pulling taste package").start());const o=await pullRemote({owner:s.owner,packageName:s.packageName,overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:o,owner:s.owner}}async function pullGlobal(e){const{packageName:t,options:n,strategy:r}=e;setActiveSpinner(Te("Pulling taste package").start());const s=n.all||!t?[]:[t],o=await pull({packages:s,source:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:o}}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new xy({baseUrl:e}),n=await t.get({endpoint:kt.ALPHA.NAMESPACES});if(!n.success)throw new Error("Failed to fetch namespaces");if("org"===n.type)return{userName:n.org.login,orgs:[]};const r=n.orgs.map(e=>({id:e.id,login:e.login,name:e.name}));return{userName:n.user.userName,orgs:r}}function logResult2(e){if(wasPrompted())return qe.outro(e),void setPrompted(!1);console.log(e)}function logPushAllSuccess(t){const{result:n,options:r}=t;if(!r.all)return!1;if(0===n.packagesPushed.length){const e=n.skipped?.length??0;if(e>0){const t=wasPrompted()?"":`${ke.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${le.green(t)}Skipped ${n}`)}return!1}const s=n.packagesPushed.length,o=`${s} ${1===s?"package":"packages"}`,i=n.filePaths?.[n.packagesPushed[0]],a=r.global&&i?shortenPath(e.dirname(e.dirname(i))):i,l=wasPrompted()?"":`${ke.tick} `;if(!a)return logResult2(`${le.green(l)}Pushed ${o} to remote`),!1;if(r.overwrite||Boolean(n.overwritten?.length)){let e=0;if(n.mergeDetails)for(const t of Object.values(n.mergeDetails))e+=t.updated??0;const t=e>0?` ${le.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${le.green(l)}Replaced ${o} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${le.green(l)}Pushed ${o} to ${a}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const g=formatMergeParts({added:u,updated:d,unchanged:m}),h=g.length>0?` ${le.gray(`(${g.join(", ")})`)}`:"";return logResult2(`${le.green(l)}Pushed ${o} to ${a}${h}`),(u>0||d>0)&&m>0}function logPushSingleSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(1!==t.packagesPushed.length)return!1;const r=t.packagesPushed[0],s=t.filePaths?.[r],o=n.remote&&s,i=o?s:"global",a=wasPrompted()?"":`${ke.tick} `,l=!o&&s?le.dim(`\n ${shortenPath(s)}`):"";if(n.overwrite)return logResult2(`${le.green(a)}Replaced ${le.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${le.green(a)}Pushed ${le.green(`'${r}'`)} taste package to ${i} ${le.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${le.green(a)}Pushed ${le.green(`'${r}'`)} taste package to ${i}`+l),!1}function logPushMultiSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(t.packagesPushed.length<=1)return!1;const r=n.remote?"remote":"global",s=wasPrompted()?"":`${ke.tick} `;return logResult2(wrapLine(`${le.green(s)}Pushed ${le.green(t.packagesPushed.length)} taste packages ${le.green(`(${t.packagesPushed.join(", ")})`)} to ${r}`)),!(n.overwrite||!t.mergeDetails)&&hasMergeConflictRiskInRecord(t.mergeDetails)}function logPushUrls(e){const{result:t,options:n}=e;if(!n.remote||!t.filePaths)return;const r=new Set;for(const e of t.packagesPushed){const n=t.filePaths[e];if(!n||!n.includes("/"))continue;const[s,o]=n.split("/");if(!s||!o)continue;const i=getPackageLink({owner:s,packageName:o});r.has(i)||(r.add(i),console.log(le.gray(` ${i}`)))}}function logConflictSummary(e){const{result:t}=e,n=t.overwritten??[],r=t.skipped??[],s=t.packagesPushed.filter(e=>!n.includes(e)),o=t.packagesPushed.length+r.length,i=[];s.length>0&&i.push(wrapLine(`${le.green("Merged")} (${s.length}) ${s.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${le.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${le.dim("Skipped")} (${r.length}) ${le.dim(r.join(", "))}`,4)),i.length>0&&qe.log.message(i.join("\n"));const a=`${o} ${1===o?"package":"packages"}`;qe.outro(a)}function logPushBreakdown(e){const t=e.overwritten??[],n=e.skipped??[];if(0===n.length&&0===t.length)return;const r=e.packagesPushed.filter(e=>!t.includes(e)),s=[];r.length>0&&s.push(wrapLine(`${le.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&s.push(wrapLine(`${le.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&s.push(wrapLine(`${le.dim("Skipped")} (${n.length}) ${le.dim(n.join(", "))}`)),s.length>0&&console.log(s.join("\n"))}function logPushSuccess(e){const{result:t,options:n}=e;if(wasPrompted())return setPrompted(!1),logConflictSummary({result:t}),void logPushUrls({result:t,options:n});const r=logPushAllSuccess({result:t,options:n})||logPushSingleSuccess({result:t,options:n})||logPushMultiSuccess({result:t,options:n});n.all&&logPushBreakdown(t),logPushUrls({result:t,options:n}),r&&logMergeReviewTip()}__name(resolvePullStrategy,"resolvePullStrategy"),__name(executePullStrategy,"executePullStrategy"),__name(pullSinglePackage,"pullSinglePackage"),__name(pull,"pull"),__name(executePullRemote,"executePullRemote"),__name(pullRemote,"pullRemote"),Ht(),__name(logResult,"logResult"),__name(buildPullMessage,"buildPullMessage"),__name(logPullSingleSuccess,"logPullSingleSuccess"),__name(logPullSummary,"logPullSummary"),__name(logPullSuccess,"logPullSuccess"),__name(createPullCommand,"createPullCommand"),__name(validatePullOptions,"validatePullOptions"),__name(runPull,"runPull"),__name(pullRemoteSingle,"pullRemoteSingle"),__name(pullGlobal,"pullGlobal"),Ht(),In(),Ht(),Xy(),Wy(),Kt(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Ht(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Ht(),sk(),Ht();var AA=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),IA=__name(e=>e.reduce((e,t)=>t.file.endsWith("taste.md")?e+parseTasteContent(t.content).length:e,0),"countRemoteLearnings");async function resolvePushAllStrategy(e){const{flagStrategy:t,overwrite:n,existingProject:r,packagesToPush:s,projectName:o,owner:i}=e;if("skip"===t)return"skip";if("overwrite"===t||n)return"overwrite";if("merge"===t)return"overwrite";if(!r)return"overwrite";const a=r.type??"category",l=s.reduce((e,t)=>e+t.learnings.length,0),u=IA(r.files);return"project"!==a?promptTypeMismatchStrategy({packageName:o,owner:i,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:o,owner:i,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:s,isPublic:o,isPublicExplicitlySet:i,flagStrategy:a}=t,l=e.basename(process.cwd()),u={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:l}),m=await resolvePushAllStrategy({flagStrategy:a,overwrite:s,existingProject:d,packagesToPush:n,projectName:l,owner:r});if("skip"===m)return u.skipped.push(...n.map(e=>e.category)),u;await writePackages({packages:n,projectName:l,owner:r,isPublic:i?o:d?.isPublic??!1,overwrite:"overwrite"===m});for(const e of n)u.packagesPushed.push(e.category),u.filePaths[e.category]=`${r}/${l}`,u.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};return d&&u.overwritten.push(...n.map(e=>e.category)),u}async function pushAllRemote(e){try{return await executePushAllRemote(e)}catch(e){return AA({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var NA=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),RA=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:s,overwrite:o}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:s,overwrite:o})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var $A=__name(e=>{const{target:t,category:n,owner:r}=e;return"local-global"===t?getCategoryTasteFile({target:"local-global",category:n}):"remote-project"!==t&&"remote-user"!==t||!r?void 0:`${r}/${n}`},"getDestPath");async function getUserOwner(){try{const e=await getAuthenticatedEntity();if(e.success&&e.user?.userName)return e.user.userName}catch{}}async function resolveSinglePushStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,target:s,tastePkg:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===s?promptGlobalPushStrategy({packageName:o.category,localLearningsCount:o.learnings.length,globalPkg:r}):"merge"}async function executePushStrategy(e){const{tastePkg:t,target:n,flagStrategy:r,overwrite:s,userOwner:o,isPublic:i,result:a}=e,l="local-global"===n?await getPackage({category:t.category}):await getPackage3({category:t.category}),u=await resolveSinglePushStrategy({flagStrategy:r,overwrite:s,existingPkg:l,target:n,tastePkg:t});if("skip"===u)return void a.skipped.push(t.category);if("overwrite"===u&&(await writePkg({pkg:t,target:n,owner:o,isPublic:i,overwrite:!0}),a.packagesPushed.push(t.category),a.overwritten.push(t.category),a.mergeDetails[t.category]={added:0,updated:t.learnings.length,unchanged:0}),"merge"===u){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:l});await writePkg({pkg:e,target:n,owner:o,isPublic:i}),a.packagesPushed.push(t.category),a.mergeDetails[t.category]=r}const d=$A({target:n,category:t.category,owner:o});d&&(a.filePaths[t.category]=d)}async function pushSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePushStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function push(e){const t=void 0!==e.isPublic,{packages:n,target:r,overwrite:s=!1,isPublic:o=!1,strategy:i}=e;if(!exists2())return NA({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return NA({pkg:"all",error:"No taste packages found in project"});const l=validatePackages({packages:a,label:"project"});if(l.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const u=n.length>0?a.filter(e=>n.includes(e.category)):a;if(n.length>0&&0===u.length)return{success:!1,packagesPushed:[],skipped:[],errors:n.map(e=>({pkg:e,error:"Taste package not found in project"})),mergeDetails:{},overwritten:[],filePaths:{}};const d="remote-project"===r||"remote-user"===r?e.owner??await getUserOwner():void 0;if("remote-project"===r&&0===n.length)return d?pushAllRemote({packagesToPush:u,owner:d,overwrite:s,isPublic:o,isPublicExplicitlySet:t,flagStrategy:i}):NA({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return NA({pkg:"all",error:`Invalid target: ${r}`});const m=RA();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:i,overwrite:s,userOwner:d,isPublic:o,result:m});return m}async function executeRemotePush(e){const t=void 0!==e.isPublic,{owner:n,packageName:r,overwrite:s=!1,isPublic:o=!1,strategy:i}=e,a=await getPackage2({category:r});if(!a)return NA({pkg:r,error:`Taste package '${r}' not found in local project`});const l=validateTasteFile({content:formatPackage({pkg:a}),filePath:`${a.category}/taste.md`});if(!l.valid){const e=formatValidationIssues({result:l,verbose:!0});return NA({pkg:r,error:`Validation failed:\n${e}`})}l.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:l,verbose:!0})+"\n"));const u=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:i,overwrite:s,existingPkg:u,target:"remote-project",tastePkg:a}),m=t?o:u?.isPublic??!1,g=RA();if("skip"===d)return g.skipped.push(r),g;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m,overwrite:!0}),g.packagesPushed.push(r),g.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),g.packagesPushed.push(r),g.mergeDetails[r]=t}return g.filePaths[r]=`${n}/${r}`,g}async function pushRemote(e){const{packageName:t}=e;if(!exists2())return NA({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return NA({pkg:t,error:e instanceof Error?e.message:String(e)})}}async function promptOwnerSelection(e){const{userName:t,orgs:n}=e;if(0===n.length)return t;const r=[{value:t,label:t,hint:"Personal"},...n.map(e=>({value:e.login,label:e.name||e.login,hint:"Organization"}))],s=await qe.select({message:"Owner",options:r,initialValue:t});return qe.isCancel(s)&&(qe.cancel("Operation cancelled"),process.exit(0)),s}function createPushCommand(){return new ve("push").description(`Push taste packages to remote ${le.dim("(commandcode.ai)")} or global ${le.dim("(~/.commandcode)")}`).argument("[package]","Taste package name to push (omit with --all)").option("--all","Push all taste packages to remote").option("--remote","Push to commandcode.ai remote (default)").option("-g, --global","Push to local global storage (~/.commandcode)").addOption(new Ce("--local","Use local server").hideHelp()).option("--public","Make package publicly discoverable on commandcode.ai").option("--private","Make package private (not publicly discoverable)").option("--owner <owner>","Push under a specific owner or organization").option("--overwrite","Replace existing package without prompting").option("--skip","Keep existing package, skip conflicting push").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new Ce("--staging","Push to staging environment").hideHelp()).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),r=await runPush({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPushSuccess({result:r,options:n})}))}function validatePushOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one destination"),n.public&&n.private&&exitWithError("--public and --private are mutually exclusive — pick one visibility"),n.owner&&n.global&&exitWithError("--owner only applies to remote pushes, not --global"),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to push everything",usage:["cmd taste push <package> push a taste package to remote (default)","cmd taste push --all push all taste packages to remote","cmd taste push <package> -g push a taste package to global (~/.commandcode)"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}__name(getUserOwner,"getUserOwner"),__name(resolveSinglePushStrategy,"resolveSinglePushStrategy"),__name(executePushStrategy,"executePushStrategy"),__name(pushSinglePackage,"pushSinglePackage"),__name(push,"push"),__name(executeRemotePush,"executeRemotePush"),__name(pushRemote,"pushRemote"),Ht(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var MA=__name(e=>!!e.public||!e.private&&void 0,"resolveVisibility");async function validateOwnerAccess(e){let t;try{t=await fetchUserNamespaces()}catch(e){return void dlog(`[Auth] validateOwnerAccess: namespace service unavailable, skipping — ${e instanceof Error?e.message:String(e)}`)}const n=[t.userName,...t.orgs.map(e=>e.login)];n.includes(e)||exitWithError(`No push access to '${e}'. Available: ${n.join(", ")}`)}async function resolveOwnerForPush(e){const{packageName:t,owner:n}=e,r=parseOwnerPackage(t);if(r)return await validateOwnerAccess(r.owner),r;if(n)return await validateOwnerAccess(n),{owner:n,packageName:t};qe.intro(le.dim(`pushing ${t}`)),setPrompted(!0);const s=qe.spinner();s.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(s.error("Failed"),qe.outro(le.red(`Taste package '${t}' not found in project`)),process.exit(1));const o=await fetchUserNamespaces();return s.stop(o.orgs.length>0?"Select owner to push to":""),{owner:o.orgs.length>0?await promptOwnerSelection(o):o.userName,packageName:t}}async function runPush(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePushOptions({packageName:t,options:r});const s=resolveConflictStrategy(r);return r.remote&&r.all?pushRemoteAll({options:r,strategy:s}):r.remote?pushRemoteSingle({packageName:t,options:r,strategy:s}):pushGlobal({packageName:t,options:r,strategy:s})}async function pushRemoteAll(t){const{options:n,strategy:r}=t;n.owner&&await validateOwnerAccess(n.owner);const s=(await getAllPackages2()).length,o=`${s} ${1===s?"package":"packages"}`,i=e.basename(process.cwd()),a=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(le.dim(` Pushing ${o} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner(Te("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:MA(n),strategy:r,owner:n.owner});return stopActiveSpinner(),l}async function pushRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,{owner:s,packageName:o}=await resolveOwnerForPush({packageName:t,owner:n.owner});startPushSpinner({owner:s,pkgName:o});const i=await pushRemote({owner:s,packageName:o,overwrite:n.overwrite,isPublic:MA(n),strategy:r});return stopActiveSpinner(`Pushed to ${s}/${o}`),i}function resolveStrategyLabel(e){const{strategy:t,isRemote:n=!1}=e;return"overwrite"===t?" · overwrite":"skip"===t?" · skip conflicts":"merge"===t?" · auto-merge":n?"":" · will prompt on conflicts"}function startPushSpinner(e){const{owner:t,pkgName:n}=e;if(wasPrompted()){const e=qe.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Te("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,s=n.all||!t?[]:[t],o=await getAllPackages2(),i=s.length>0?s.length:o.length,a=`${i} ${1===i?"package":"packages"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(le.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner(Te("Pushing taste packages").start());const d=await push({packages:s,target:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),d}function createTasteCommand(){const e=new ve($t.TASTE);return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),isExperimentalEnabled()&&e.addCommand(createLearnCommand()),e}function formatVersion(e,t,n=!1){const r=n?ce.bold(ce.green(t)):ce.white(t);return`${ce.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${ce.bold(ce.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(ce.dim(`Run ${ce.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(ce.dim("Try updating manually:")),console.log(ce.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(ce.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=Te("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.stop(),console.log(""),console.log(`${ce.green(ke.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${ce.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=Te("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.text=`Updating ${t.currentVersion} ${ke.arrowRight} ${t.latestVersion}...`,(await performAutoUpdate({silent:!0,updateInfo:t})).success||(e.fail("Update failed"),trackError({error:sanitizeErrorForTelemetry({error:new Error("Update failed"),label:"cli_update_failed"}),context:{component:ys.UPDATE_COMMAND,heading:"CLI update failed","update.current_version":t.currentVersion,"update.target_version":t.latestVersion}}),showManualUpdateHint(t.latestVersion),await shutdownTelemetry(),process.exit(1)),e.succeed(`Updated to v${t.latestVersion}`),showUpdateSuccessHint()):e.succeed(`Up to date ${ce.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}__name(validateOwnerAccess,"validateOwnerAccess"),__name(resolveOwnerForPush,"resolveOwnerForPush"),__name(runPush,"runPush"),__name(pushRemoteAll,"pushRemoteAll"),__name(pushRemoteSingle,"pushRemoteSingle"),__name(resolveStrategyLabel,"resolveStrategyLabel"),__name(startPushSpinner,"startPushSpinner"),__name(pushGlobal,"pushGlobal"),xr(),__name(createTasteCommand,"createTasteCommand"),Ht(),Kt(),Cs(),__name(formatVersion,"formatVersion"),__name(showVersionDetails,"showVersionDetails"),__name(showUpdateSuccessHint,"showUpdateSuccessHint"),__name(showManualUpdateHint,"showManualUpdateHint"),__name(showCheckFailure,"showCheckFailure"),__name(checkAction,"checkAction"),__name(performUpdateAction,"performUpdateAction"),__name(updateAction,"updateAction");var LA=new ve("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Ht(),rk(),sk();var DA=__name((e,t)=>`${ke.info} ${e}: ${ce.cyan(t)}`,"formatInfoLine"),OA=__name(e=>ce.bold(`${e}:`),"formatSectionHeader"),FA=__name(e=>ce.red(e),"formatError"),qA=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),jA=__name(e=>["",OA("User Information"),DA("Name",e.name),DA("Email",e.email),DA("Username",e.userName)],"buildUserOutput"),BA=__name(e=>["",OA("Organization"),DA("Name",e.name),DA("Login",e.login)],"buildOrgOutput"),UA=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),zA=__name((e,t)=>{UA(jA(e)),t&&UA(BA(t)),console.log("")},"displayUserInfo"),WA=__name(e=>null!==e&&e.length>0,"validateApiKey"),GA=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=Te("Fetching user information...").start();try{const t=await getAuthKey();WA(t)||(e.fail(FA('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();GA(n)||(e.fail(FA("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),zA(n.user,n.org)}catch(t){e.fail(FA(`Error: ${qA(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var HA=new ve("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);function normalizeGitUrl(e){let t=e.trim();const n=t.match(/^git@([^:]+):(.+?)(?:\.git)?$/);return n?`https://${n[1]}/${n[2]}`:(t=t.replace(/\.git$/,""),t)}function validateGitRepo(){try{if("true"!==$("git rev-parse --is-inside-work-tree",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error("Not inside a git repository.")}catch{throw new Error("Sandbox requires a git repository with a GitHub remote.")}let e;try{e=$("git remote get-url origin",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("No GitHub remote found. Add one with: git remote add origin https://github.com/you/repo")}const t=normalizeGitUrl(e);let n;try{n=$("git branch --show-current",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("Failed to determine current branch.")}if(!n)throw new Error("Detached HEAD state. Please checkout a branch first.");if(!/^[\w./-]+$/.test(n))throw new Error("Branch name contains invalid characters. Please use a simpler branch name.");try{if(!$(`git ls-remote --heads origin ${n}`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}catch(e){if(e instanceof Error&&e.message.includes("not found on remote"))throw e;throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}return{repoUrl:t,branch:n,isClean:""===$("git status --porcelain",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}function getGitHubToken(){const e=process.env.GITHUB_TOKEN;if(e)return e;try{return $("gh auth token",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("GitHub authentication required.\nEither set GITHUB_TOKEN or run: gh auth login")}}Ht(),Ht(),Kt(),Wy(),Xy(),Zt(),Nr(),Ht(),__name(normalizeGitUrl,"normalizeGitUrl"),__name(validateGitRepo,"validateGitRepo"),Ht(),__name(getGitHubToken,"getGitHubToken"),Ht(),Xy(),rk(),Ht();var QA=["completed","failed","cancelled","timed_out"];function isTerminalStatus(e){return QA.includes(e)}__name(isTerminalStatus,"isTerminalStatus");var VA={setting_up:"Setting up sandbox...",cloning:"Cloning repository..."};function stopAllSpinners({state:e}){e.workingSpinner&&(e.workingSpinner.stop(),e.workingSpinner=null),e.currentSpinner&&(e.currentSpinner.stop(),e.currentSpinner=null)}function renderStatusEvent({event:e,state:t}){const n=e.data.status,r=VA[n],s="setup"===t.phase;if(t.isResume&&s&&!isTerminalStatus(n)&&"running"!==n)r&&t.workingSpinner&&(t.workingSpinner.text=r);else{if(r&&s&&(t.currentSpinner&&t.currentSpinner.succeed(),t.currentSpinner=Te({stream:process.stderr,text:r}).start()),"running"===n)return t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="running",void(t.workingSpinner||(t.workingSpinner=Te({stream:process.stderr}).start()));if("completed"===n){t.workingSpinner&&(t.workingSpinner.succeed("Session completed"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="done";const n=e.data.prUrl;return void(n&&console.error(`PR: ${ce.cyan(n)}`))}if("failed"===n){t.workingSpinner&&(t.workingSpinner.fail("Session failed"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail(),t.currentSpinner=null),t.phase="done";const n=e.data.message||"Unknown error";return void console.error(`${ke.cross} ${ce.red(n)}`)}if("timed_out"===n)return t.workingSpinner&&(t.workingSpinner.fail("Session timed out"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail("Timed out"),t.currentSpinner=null),void(t.phase="done");"cancelled"===n&&(stopAllSpinners({state:t}),t.phase="done",console.error(`\n${ce.yellow("Cancelled.")}`))}}function renderEvent({event:e,state:t}){if("status"!==e.type){if("pty"===e.type){const n=e.data.content;return void(n&&(t.workingSpinner&&t.workingSpinner.stop(),process.stdout.write(n),t.workingSpinner&&t.workingSpinner.start()))}if("error"===e.type){t.currentSpinner&&(t.currentSpinner.fail(),t.currentSpinner=null);const n=e.data.message;console.error(`${ke.cross} ${ce.red(n)}`)}}else renderStatusEvent({event:e,state:t})}function setupInputHandling({callbacks:e}){const t=__name(t=>{3===t[0]?e.onCancel():4===t[0]&&e.onDetach()},"onStdinData"),n=process.rawListeners("SIGINT").slice();return process.removeAllListeners("SIGINT"),process.stdin.isTTY?(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",t),process.on("SIGINT",()=>{})):process.on("SIGINT",()=>e.onCancel()),()=>{process.stdin.isTTY&&(process.stdin.removeListener("data",t),process.stdin.setRawMode(!1),process.stdin.pause()),process.removeAllListeners("SIGINT");for(const e of n)process.on("SIGINT",e)}}function setupResizeForwarding({ws:e}){const t=__name(()=>{e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({action:"resize",cols:process.stdout.columns,rows:process.stdout.rows}))},"onResize");return process.stdout.on("resize",t),()=>process.stdout.removeListener("resize",t)}function sendTerminalSize({ws:e}){e.send(JSON.stringify({action:"resize",cols:process.stdout.columns||120,rows:process.stdout.rows||30}))}async function streamSession({sessionId:e,prompt:t,lastEventId:n=0,isResume:r=!1}){const s=getApiBaseUrl().replace(/^http/,"ws"),o=await getAuthKey();if(!o)throw new Error("Not authenticated. Run: cmd login");const i=new URLSearchParams({token:o,...n>0?{lastEventId:String(n)}:{}}),a=`${s}/alpha/sandbox/stream/${e}?${i.toString()}`;return new Promise((t,s)=>{const o=new WebSocket(a),i={currentSpinner:null,workingSpinner:null,phase:"setup",lastEventId:n,isResume:r};r&&(i.currentSpinner=Te({stream:process.stderr,text:"Reconnecting..."}).start());const l=__name(()=>{i.phase="done",stopAllSpinners({state:i}),o.close(),console.error(`\n${ce.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${ce.cyan(`cmd --experimental sandbox --id ${e}`)}`),g(),t()},"detach"),u=__name(()=>{i.phase="done",stopAllSpinners({state:i}),o.readyState===WebSocket.OPEN&&o.send(JSON.stringify({action:"cancel"})),o.close(),console.error(`\n${ce.yellow("Sandbox stopped.")}`),g(),t()},"cancelSandbox"),d=setupResizeForwarding({ws:o}),m=setupInputHandling({callbacks:{onCancel:u,onDetach:l}});process.once("SIGTERM",l);const g=__name(()=>{d(),m(),process.removeListener("SIGTERM",l)},"teardown");o.addEventListener("open",()=>{sendTerminalSize({ws:o}),i.currentSpinner&&(i.currentSpinner.stop(),i.currentSpinner=null),console.error(""),console.error(`${ce.yellow("[Ctrl+C]")} ${ce.dim("stop")} ${ce.yellow("[Ctrl+D]")} ${ce.dim("detach")}`),console.error(`${ce.dim("Session:")} ${ce.gray(e)}`),console.error(""),r&&(i.workingSpinner=Te({stream:process.stderr}).start())}),o.addEventListener("message",e=>{try{const n="string"==typeof e.data?e.data:e.data.toString(),r=JSON.parse(n);renderEvent({event:r,state:i}),void 0!==r.id&&(i.lastEventId=r.id),"status"===r.type&&isTerminalStatus(r.data.status)&&(o.close(),g(),t())}catch{}}),o.addEventListener("error",()=>{g(),i.currentSpinner&&(i.currentSpinner.fail("Connection error"),i.currentSpinner=null),s(new Error("WebSocket connection failed"))}),o.addEventListener("close",()=>{"done"!==i.phase&&(i.phase="done",stopAllSpinners({state:i}),g(),console.error(`\n${ce.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${ce.cyan(`cmd --experimental sandbox --id ${e}`)}`),t())})})}function readLocalConfigFiles(){let e="",t="";try{e=E.readFileSync(getAuthFile(),"utf-8")}catch{}try{t=E.readFileSync(getConfigFile(),"utf-8")}catch{}return{auth:e,config:t}}async function askQuestion(e){const t=Je.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,e=>{t.close(),n(e)})})}async function startSandboxSession({repoUrl:e,branch:t,prompt:n,ghToken:r,isInternalTeam:s,configFiles:o}){return new xy({baseUrl:getApiBaseUrl()}).post({endpoint:kt.ALPHA.SANDBOX.START,body:{repoUrl:e,branch:t,prompt:n,ghToken:r,isInternalTeam:s,configFiles:o}})}async function sandboxMode({prompt:e,resume:t}){t&&(await streamSession({sessionId:t,isResume:!0}),process.exit(0)),await ensureAuthenticated()||process.exit(1);const n=validateGitRepo();n.isClean||console.error(ce.yellow("Warning: You have uncommitted changes. The sandbox clones from remote, so local changes won't be included."));const r=getGitHubToken(),s=isInternalTeamFlagPresent(),o=readLocalConfigFiles(),i=e||await askQuestion(`${ce.bold("What do you want to do?")}\n${ce.cyan(">")} `);if(!i.trim())return void console.error(ce.yellow("No prompt provided. Aborting."));const a=i.trim().slice(0,Mt.MAX_PROMPT_CHARS),l=Te({stream:process.stderr,text:"Starting sandbox session..."}).start();try{const e=await startSandboxSession({repoUrl:n.repoUrl,branch:n.branch,prompt:a,ghToken:r,isInternalTeam:s,configFiles:o});l.succeed("Sandbox started"),await streamSession({sessionId:e.sessionId,prompt:a}),process.exit(0)}catch(e){l.fail("Failed to start session");const t=e instanceof Error?e.message:"Unknown error";t.includes("401")||t.toLowerCase().includes("unauthorized")?console.error(ce.red("Authentication failed. Try logging in again: cmd login")):console.error(ce.red(t)),process.exit(1)}}function createSandboxCommand(){return new ve("sandbox").description("Run a task autonomously in a sandbox").argument("[prompt]","Task description").option("--id <sessionId>","Resume an existing sandbox session").enablePositionalOptions().action(async(e,t)=>{try{await sandboxMode({prompt:e,resume:t.id})}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(ce.red(t)),process.exit(1)}})}function validateSafeString(e,t){if(e.includes("..")||e.includes("\\"))throw new Error(`Invalid ${t}: path traversal sequences are not allowed.\nExpected format: owner/repo or owner/repo/path`);if(!/^[a-zA-Z0-9._/-]+$/.test(e))throw new Error(`Invalid ${t}: contains unsupported characters.\nOnly letters, numbers, hyphens, underscores, dots, and slashes are allowed.`)}function parseGitHubRepo(e){let t,n=e.replace(/^https?:\/\/github\.com\//,"");const r=n.lastIndexOf("@");r>0&&r<n.length-1&&(t=n.slice(r+1),n=n.slice(0,r),validateSafeString(t,"branch name"));const s=n.split("/");if(s.length<2)throw new Error("Invalid GitHub repository format. Expected: owner/repo or owner/repo/path");const[o,i,...a]=s;validateSafeString(o,"owner"),validateSafeString(i,"repository");const l=a.length>0?a.join("/"):void 0;return l&&validateSafeString(l,"path"),{owner:o,repo:i,path:l,branch:t}}function buildGigetSource(e){const{owner:t,repo:n,path:r,branch:s}=e;let o=`gh:${t}/${n}`;return r&&(o+=`/${r}`),s&&(o+=`#${s}`),o}async function fetchSkillFromGitHub(e){await cleanupStaleTempDirectories();const n=parseGitHubRepo(e),{owner:r,repo:s,path:o}=n;let i;if(o){const e=o.split("/").filter(Boolean);i=e[e.length-1]}else i=s;const a=t.join(w.tmpdir(),`commandcode-skill-${H()}`);await O.mkdir(a,{recursive:!0});try{const e=buildGigetSource(n),{downloadTemplate:o}=await import("giget");try{await o(e,{dir:a,force:!0,silent:!0})}catch(t){if(!isCorruptedArchiveError(t))throw t;await clearGigetCache(r,s),await o(e,{dir:a,force:!0,silent:!0})}const l=t.join(a,"SKILL.md"),u=t.join(a,"skill.md");let d=!1;try{await O.access(l),d=!0}catch{}if(!d)try{await O.access(u),d=!0}catch{}if(!d)throw new Error(`SKILL.md not found in ${e}. Make sure the repository contains a SKILL.md file.`);return{tempDir:a,skillName:i}}catch(e){if(await O.rm(a,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&e.message.includes("SKILL.md not found"))throw e;throw wrapFetchError(e,r,s)}}async function discoverSkillsInRepo(e,t){const n=parseGitHubRepo(e),{owner:r,repo:s,path:o,branch:i}=n,{keepTempDir:a=!1}=t||{},{discoverSkillsLocally:l}=await Promise.resolve().then(()=>(mk(),dk)),u=await l({owner:r,repo:s,path:o,branch:i,keepTempDir:a});if(0===u.skills.length)throw new Error(`No skills found in repository ${r}/${s}${o?` at path "${o}"`:""}. Ensure the repository contains SKILL.md files.`);return u}async function resolveSkillMdPath(e){const n=t.join(e,"SKILL.md");try{return await O.access(n),n}catch{}const r=t.join(e,"skill.md");try{return await O.access(r),r}catch{}throw new Error(`SKILL.md not found in ${e}`)}function validateSkillName(e){const t=e.trim();if(!t||0===t.length)throw new Error("Invalid skill name: name cannot be empty");if(t.includes("/")||t.includes("\\"))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain path separators (/ or \\).`);if(t.includes(".."))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain parent directory references (..).`);if(t.startsWith("."))throw new Error(`Invalid skill name: "${e}". Skill names cannot start with a dot.`);if(!/^[a-z0-9-]+$/.test(t))throw new Error(`Invalid skill name: "${e}". Skill names must contain only lowercase letters, numbers, and hyphens.`);return t}async function validateSkillContent(e){const t=await resolveSkillMdPath(e),n=await O.readFile(t,"utf-8"),{data:r}=Ne(n),s=th.parse(r);return{name:validateSkillName(s.name),description:s.description}}async function skillExists(e){const{skillName:n,location:r}=e,s="global"===r?getGlobalSkillsDir():getProjectSkillsDir(),o=t.join(s,n);try{return await O.access(o),!0}catch{return!1}}async function discoverSkills(e,t){return discoverSkillsInRepo(e,t)}async function installSkill(e){const{repoInput:n,options:r={}}=e,{global:s=!1,force:o=!1,skillName:i,discoveredSkill:a,cachedTempDir:l}=r;let u,d,m=n;if(i){let e;if(a)e=a;else{const t=await discoverSkillsInRepo(n);if(0===t.skills.length)throw new Error(`No skills found in repository: ${n}`);const r=t.skills.find(e=>e.name.toLowerCase()===i.toLowerCase());if(!r){const e=t.skills.map(e=>e.name).join(", ");throw new Error(`Skill "${i}" not found in repository. Available skills: ${e}`)}e=r}const t=parseGitHubRepo(n),r=[t.path,e.path&&"."!==e.path?e.path:void 0].filter(Boolean).join("/"),s=r?`${t.owner}/${t.repo}/${r}`:`${t.owner}/${t.repo}`;m=t.branch?`${s}@${t.branch}`:s}if(l&&a){u=a.path&&"."!==a.path?t.join(l,a.path):l,d=!1;try{await resolveSkillMdPath(u)}catch{const e=a.path&&"."!==a.path?`at ${a.path}`:"at root";throw new Error(`SKILL.md not found in cached directory ${e}. Make sure the repository contains a SKILL.md file.`)}}else u=(await fetchSkillFromGitHub(m)).tempDir,d=!0;try{const{name:e,description:n}=await validateSkillContent(u),r=e,i=s?"global":"project",a="global"===i?getGlobalSkillsDir():getProjectSkillsDir(),l=await skillExists({skillName:r,location:i});if(l&&!o)throw new Error(`Skill "${r}" already exists in ${"global"===i?"~/.commandcode/skills/":".commandcode/skills/"}. Use --force to overwrite.`);await O.mkdir(a,{recursive:!0});const d=t.join(a,r),{randomUUID:m}=await import("crypto"),g=t.join(a,`.${r}.tmp.${m()}`);try{await O.cp(u,g,{recursive:!0,force:!0,dereference:!1}),l&&o&&await O.rm(d,{recursive:!0,force:!0}),await O.rename(g,d)}catch(e){if(await O.rm(g,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&"code"in e&&("EEXIST"===e.code||"ENOTEMPTY"===e.code))throw new Error(`Skill "${r}" was created by another process during installation. Use --force to overwrite.`);throw e}let h;try{h=await resolveSkillMdPath(d)}catch{h=t.join(d,"SKILL.md")}return{name:r,description:n,location:i,path:h}}finally{d&&await O.rm(u,{recursive:!0,force:!0}).catch(()=>{})}}async function removeSkill(e){const{global:n=!1}=e,r=validateSkillName(e.skillName),s=n?"global":"project",o="global"===s?getGlobalSkillsDir():getProjectSkillsDir(),i=t.join(o,r);if(!await skillExists({skillName:r,location:s}))throw new Error(`Skill "${r}" not found in ${"global"===s?"global (~/.commandcode/skills/)":"project (.commandcode/skills/)"} skills.${"global"===s?"":" Use -g/--global to check global skills."}`);await O.rm(i,{recursive:!0,force:!0})}async function listSkills(){const{global:e,project:t}=await loadAllSkillSummaries();return{global:e.map(e=>({name:e.name,description:e.description,location:"global",path:e.filePath})),project:t.map(e=>({name:e.name,description:e.description,location:"project",path:e.filePath}))}}__name(stopAllSpinners,"stopAllSpinners"),__name(renderStatusEvent,"renderStatusEvent"),__name(renderEvent,"renderEvent"),__name(setupInputHandling,"setupInputHandling"),__name(setupResizeForwarding,"setupResizeForwarding"),__name(sendTerminalSize,"sendTerminalSize"),__name(streamSession,"streamSession"),__name(readLocalConfigFiles,"readLocalConfigFiles"),__name(askQuestion,"askQuestion"),__name(startSandboxSession,"startSandboxSession"),__name(sandboxMode,"sandboxMode"),__name(createSandboxCommand,"createSandboxCommand"),xr(),Ht(),Ht(),Ht(),Ht(),uk(),__name(validateSafeString,"validateSafeString"),__name(parseGitHubRepo,"parseGitHubRepo"),__name(buildGigetSource,"buildGigetSource"),__name(fetchSkillFromGitHub,"fetchSkillFromGitHub"),__name(discoverSkillsInRepo,"discoverSkillsInRepo"),mw(),Eh(),__name(resolveSkillMdPath,"resolveSkillMdPath"),__name(validateSkillName,"validateSkillName"),__name(validateSkillContent,"validateSkillContent"),__name(skillExists,"skillExists"),__name(discoverSkills,"discoverSkills"),__name(installSkill,"installSkill"),__name(removeSkill,"removeSkill"),__name(listSkills,"listSkills"),Kt();var KA=[`${ce.dim("Usage:")}`,` ${ce.cyan("cmd skills add")} ${ce.white("<owner/repo>")}`,"",`${ce.dim("Examples:")}`,` ${ce.cyan("cmd skills add")} ${ce.white("acme/my-skills")} ${ce.dim("# single-skill repo")}`,` ${ce.cyan("cmd skills add")} ${ce.white("acme/skills/path/to/skill")} ${ce.dim("# specific path in repo")}`,` ${ce.cyan("cmd skills add")} ${ce.white("acme/multi-skills -s my-skill")} ${ce.dim("# pick one from multi-skill repo")}`,` ${ce.cyan("cmd skills add")} ${ce.white("acme/repo@branch")} ${ce.dim("# specific branch")}`,` ${ce.cyan("cmd skills add")} ${ce.white("acme/repo --global")} ${ce.dim("# install to ~/.commandcode/skills/")}`],YA=__name((e,t)=>`${ce.green(ke.tick)} Installed ${ce.cyan(e)} ${ce.dim(`${ke.arrowRight} ${t}/`)}`,"formatInstalled"),JA=__name(e=>`${ce.red(ke.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){e&&await F(e,{recursive:!0,force:!0}).catch(()=>{}),process.exit(t)}function validateRepoFormat(e){(e.startsWith(".")||e.startsWith("/")||e.startsWith("~"))&&(console.error(JA("Local paths are not supported. Skills must be installed from GitHub.")),console.log(""),KA.forEach(e=>console.log(e)),process.exit(1));const t=e.replace(/^https?:\/\/github\.com\//,""),n=t.lastIndexOf("@");(n>0?t.slice(0,n):t).split("/").filter(Boolean).length<2&&(console.error(JA(`Invalid repository: "${e}"`)),console.log(""),console.log(`Expected format: ${ce.cyan("owner/repo")} or ${ce.cyan("owner/repo/path")}`),console.log(""),KA.forEach(e=>console.log(e)),process.exit(1))}async function addAction(e,t){const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"~/.commandcode/skills":".commandcode/skills";let s;validateRepoFormat(e);const o=Te({text:`Fetching ${ce.cyan(e)}...`,color:"cyan"});try{let i=[];o.start();const a=await discoverSkills(e,{keepTempDir:!0}),{skills:l,tempDir:u}=a;if(s=u,o.stop(),0===l.length&&(console.error(JA(`No skills found in ${ce.cyan(e)}`)),console.log(ce.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(s,1)),t.skill){const n=l.find(e=>e.name.toLowerCase()===t.skill.toLowerCase());n||(console.error(JA(`Skill "${t.skill}" not found in ${ce.cyan(e)}`)),console.log(""),console.log(ce.dim("Available skills:")),l.forEach(e=>console.log(` ${ce.cyan(e.name)}`)),await cleanupAndExit(s,1)),i=[n]}else if(1===l.length)i=[l[0]];else if(n){const t=await je({message:`Select skills to install from ${e}`,options:l.map(e=>({value:e.name,label:e.name})),required:!0});"symbol"==typeof t&&(console.log(ce.dim("Cancelled")),await cleanupAndExit(s,0));const n=t;i=l.filter(e=>n.includes(e.name))}else i=l;let d=0;for(const n of i)try{const o=Te({text:`Installing ${ce.cyan(n.name)}...`,color:"cyan"});o.start();const i=await installSkill({repoInput:e,options:{global:t.global,force:t.force,skillName:n.name,discoveredSkill:n,cachedTempDir:s}});o.stop(),console.log(YA(i.name,r))}catch(e){d++;const t=e instanceof Error?e.message:String(e);console.error(JA(`Failed to install "${n.name}"`)),console.log(ce.dim(` ${t}`))}await cleanupAndExit(s,d>0?1:0)}catch(e){o.stop();const t=e instanceof Error?e.message:String(e);console.error(JA(t)),await cleanupAndExit(s,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction,"addAction");var XA=new ve("add").description("Install a skill from a GitHub repository").argument("<repo>","GitHub repository (owner/repo or owner/repo/path)").option("-g, --global","Install to global skills (~/.commandcode/skills/)").option("-f, --force","Overwrite if skill already exists").option("-s, --skill <name>","Specific skill name to install from repo").addHelpText("after",`\n${KA.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(JA("No repository specified.")),console.log(""),KA.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction);Ht(),Kt();var ZA=__name((e,t)=>`${ce.green(ke.tick)} Removed ${ce.cyan(e)} from ${t} skills`,"formatRemoved"),eI=__name(e=>`${ce.red(ke.cross)} ${e}`,"formatError");function validateSkillNameEarly(e){return e.includes("/")||e.includes("\\")?`"${e}" is not a valid skill name — it cannot contain path separators.`:e.includes("..")?`"${e}" is not a valid skill name — it cannot contain "..".`:e.startsWith(".")?`"${e}" is not a valid skill name — it cannot start with a dot.`:/^[a-z0-9-]+$/.test(e.trim())?null:`"${e}" is not a valid skill name — use only lowercase letters, numbers, and hyphens.`}async function removeAction(e,t){try{const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"global":"project",s=validateSkillNameEarly(e);if(s&&(console.error(eI(s)),console.log(ce.dim(`Run ${ce.cyan("cmd skills list")} to see installed skills.`)),process.exit(1)),!t.yes&&n){const t=await Be({message:`Remove ${ce.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(ce.dim("Cancelled")),process.exit(0))}await removeSkill({skillName:e,global:t.global}),console.log(ZA(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill";r.includes("not found")?(console.error(eI(`Skill "${e}" not found in ${t.global?"global":"project"} skills`)),t.global||console.log(ce.dim(`Try ${ce.cyan(`cmd skills remove ${e} --global`)} to check global skills.`)),console.log(ce.dim(`Run ${ce.cyan("cmd skills list")} to see installed skills.`))):console.error(eI(r)),process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction,"removeAction");var tI=new ve("remove").description("Remove an installed skill").argument("<skill-name>","Name of the skill to remove").option("-g, --global","Remove from global skills (~/.commandcode/skills/)").option("-y, --yes","Skip confirmation prompt").action(removeAction);Ht(),mw(),MC(),Kt();var nI=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${ce.cyan(e)} ${ce.dim(`· ${n}`)}`},"formatSkillLine"),rI=__name((e,t)=>`${ce.bold(ce.white(e))} ${ce.dim(`(${t})`)}`,"formatSectionHeader"),sI=__name(()=>["",ce.dim("No skills installed."),"",ce.dim("Looking in:"),ce.dim(` ${getGlobalSkillsDir()} ${ce.white("(global)")}`),ce.dim(` ${getProjectSkillsDir()} ${ce.white("(project)")}`),ce.dim(` ${getGlobalAgentsCompatSkillsDir()} ${ce.white("(global, .agents)")}`),ce.dim(` ${getProjectAgentsCompatSkillsDir()} ${ce.white("(project, .agents)")}`),"",`Install a skill: ${ce.cyan("cmd skills add")} ${ce.dim("<owner/repo>")}`,""],"formatEmptyHint"),oI=__name(e=>{e.forEach(e=>console.log(e))},"printLines");async function listAction(){try{const{global:e,project:t}=await listSkills(),n=e.length+t.length;0===n&&(oI(sI()),process.exit(0)),console.log(""),console.log(heading({text:"Skills",sub:ce.dim(`${n} installed`)})),t.length>0&&(console.log(""),console.log(rI("Project",t.length)),t.forEach(e=>{console.log(nI(e.name,e.description))})),e.length>0&&(console.log(""),console.log(rI("Global",e.length)),e.forEach(e=>{console.log(nI(e.name,e.description))})),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${ce.red(ke.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction,"listAction");var iI=new ve("list").description("List all installed skills").action(listAction),aI=new ve("skills").description("Manage skills from GitHub repositories").addCommand(XA).addCommand(tI).addCommand(iI);handleUnhandledErrors(),setupTelemetry(),await preRun();var lI=createProgram();lI.action(interactiveModeAction),lI.addCommand(BP),lI.addCommand(UP),lI.addCommand(HA),lI.addCommand(LA),lI.addCommand(jP),lI.addCommand(createTasteCommand()),lI.addCommand(createMcpCommand()),lI.addCommand(zP),lI.addCommand(vs),lI.addCommand(GC),lI.addCommand(ek),lI.addCommand(aI),isExperimentalEnabled()&&lI.addCommand(createSandboxCommand()),setupCommanderHooks(lI),lI.parse();
281
+ This is an unexpected error. Please file a bug report at https://github.com/CommandCodeAI/command-code/issues/new`,error:e,skipTelemetry:!0,exit:!1}),shutdownTelemetry().finally(()=>{process.exit(1)})})}Cs(),__name(handleUnhandledErrors,"handleUnhandledErrors"),Ht(),Ht(),Ls(),Wy(),Xy(),Kt(),Zy(),xr(),Rr(),gn(),aw(),uw(),fw(),Qv(),vv(),PE(),Ds(),Mv();var wk=null,Sk=!1,bk=new Set([Gy.EDIT_FILE,Gy.WRITE_FILE,Gy.SHELL_COMMAND]);async function readStdin(){return new Promise((e,t)=>{let n="";const r=setTimeout(()=>{t(new Error("Timeout reading from stdin"))},3e4);process.stdin.setEncoding("utf8"),process.stdin.on("data",e=>{n+=e}),process.stdin.on("end",()=>{clearTimeout(r),e(n.trim())}),process.stdin.on("error",e=>{clearTimeout(r),t(e)}),process.stdin.resume()})}async function isAuthenticated(){return null!==await getAuthKey()}function setupSignalHandlers(){if(Sk)return;Sk=!0;const e=__name(e=>{wk?.abort(),process.stderr.write(`\n${e}\n`),process.exit(130)},"handleTermination");process.on("SIGINT",()=>e("Interrupted.")),process.on("SIGTERM",()=>e("Terminated.")),process.stdout.on("error",e=>{"EPIPE"===e.code&&process.exit(0),process.stderr.write(`Error writing to stdout: ${e.message}\n`),process.exit(1)})}async function printMode(e={}){setupSignalHandlers(),wk=new AbortController;let t=e.query||"";if(!t){process.stdin.isTTY&&(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1));try{t=await readStdin()}catch(e){const t=e instanceof Error?e.message:"Unknown error";process.stderr.write(`Error reading from stdin: ${t}\n`),process.exit(1)}}t.trim()||(process.stderr.write('Error: No query provided. Usage: cmd -p "your query"\n'),process.exit(1)),await isAuthenticated()||(process.stderr.write('Error: Not authenticated. Please run "cmd login" first.\n'),process.exit(3));try{e.model&&setModelOverride(e.model),e.benchmarkOutput&&setBenchmarkOutput(e.benchmarkOutput);const n=await processQuery({query:t,signal:wk.signal,dangerouslySkipPermissions:e.dangerouslySkipPermissions,maxTurns:e.maxTurns??Ek,verbose:e.verbose??!1});process.stdout.write(n),n.endsWith("\n")||process.stdout.write("\n"),process.exit(0)}catch(e){e instanceof Error&&"AbortError"===e.name&&(process.stderr.write("\nCancelled.\n"),process.exit(130)),e instanceof xs&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof Ps&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof Rs&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof Ts&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof $s&&(process.stderr.write("Error: The API server encountered an error. Please try again later.\n"),process.exit(7));const t=e instanceof Error?e.message:"Unknown error";/permission denied|access denied|not permitted|unauthorized/i.test(t)&&(process.stderr.write(`Error: ${t}\n`),process.exit(4)),process.stderr.write(`Error: ${t}\n`),process.exit(1)}}__name(readStdin,"readStdin"),__name(isAuthenticated,"isAuthenticated"),__name(setupSignalHandlers,"setupSignalHandlers"),__name(printMode,"printMode");var Ek=10;async function setupConversationContext(){const e=await getToolSchemas(),t=await getConfiguredProvider(),n=await isOAuthEnforced(),{token:r,oauthProvider:s}=await getOAuthCredentials({provider:t});validateOAuthToken({token:r,provider:t});const o=getEnvironmentContext(),i=await getMemoryContent([]),a=await getTasteContent(),l=generateSkillsXML(await loadAllSkillSummaries())||null,u=crypto.randomUUID(),d=await isTasteLearningEnabled(),m={[Ct.PROJECT_SLUG]:hv.getCurrentProjectDirName(),[Ct.TASTE_LEARNING]:d.toString(),[Ct.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(m[Ct.OAUTH_TOKEN]=`Bearer ${r}`,s&&(m[Ct.OAUTH_PROVIDER]=s)),{tools:e,config:o,memory:i,taste:a,skills:l,headers:m,sessionId:u}}async function callApi(e,t,n,r){const s={tools:t.tools,stream:!0,max_tokens:64e3,temperature:.3,messages:n,model:getConfiguredModel()},o={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:s,threadId:t.sessionId};return consumeSSEStream(await e.post({body:o,stream:!0,endpoint:kt.ALPHA.GENERATE,headers:t.headers,signal:r}))}async function executeToolCall(e,t,n){if(bk.has(e.toolName)&&!n)return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:`Error: Tool "${e.toolName}" requires permissions. Use --yolo (or --dangerously-skip-permissions) to enable file writes and shell commands in print mode.`}};try{const n=await executeTool(e.toolName,e.input,{abortSignal:t});return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"text",value:n}}}catch(t){if(t instanceof xs||t instanceof Ps||t instanceof Rs||t instanceof Ts||t instanceof $s)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,output:{type:"error-text",value:`Error: ${n}`}}}}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall");var vk=80;function truncate(e){return e.length<=vk?e:e.slice(0,vk)+"..."}function formatToolLabel(e){const t=e.input,n=__name(e=>truncate(String(t[e]??"")),"param");switch(e.toolName){case"shell_command":return`Shell: ${n("command")}`;case"read_file":return`Read: ${n("absolutePath")}`;case"edit_file":return`Edit: ${n("filePath")}`;case"write_file":return`Write: ${n("filePath")}`;case"grep":return`Search: ${n("pattern")}`;case"glob":return`Glob: ${n("pattern")}`;case"read_directory":return`List: ${n("path")}`;case"read_multiple_files":return`Read: ${truncate(String(t.include??""))}`;case"think":return"Thinking";case"explore":return"Exploring";case"todo_write":return"Updating todos";case"ask_user_question":return`Question: ${n("question")}`;case"kill_shell":return`Kill: ${n("processId")}`;case"web_search":return`Search: ${n("query")}`;case"web_fetch":return`Fetch: ${n("url")}`;case"get_diagnostics":return"Diagnostics";default:return e.toolName}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1,maxTurns:s,verbose:o}=e,i=getApiBaseUrl(),a=new xy({baseUrl:i}),l=[{role:"user",content:t}],u=await setupConversationContext(),d=createBenchmarkCollector();let m=0,g="";const h={stream:process.stderr,color:"cyan"},f=o?Te(h):null;try{for(;m<s;){if(m++,n.aborted)throw new Error("Cancelled");f?.start();const e=d?Date.now():0,t=await callApi(a,u,l,n),s=d?Date.now()-e:0;f?.stop();const i=t.usage,y=d?{turnNumber:m,apiDurationMs:s,toolCalls:[],toolDurationMs:0,inputTokens:i?.input_tokens??0,outputTokens:i?.output_tokens??0,cacheReadTokens:i?.cache_read_input_tokens??0,cacheCreationTokens:i?.cache_creation_input_tokens??0}:null,w=t.content.filter(e=>"text"===e.type),S=t.content.filter(e=>"tool-call"===e.type),E=w.map(e=>e.text).join("");if(E&&(g+=E),0===S.length){d&&y&&d.turnDetails.push(y);break}const v=[],C=d?Date.now():0;for(const e of S){if(n.aborted)throw new Error("Cancelled");let t=null;if(o){const n=formatToolLabel(e);t=Te({...h,text:n}).start()}const s=await executeToolCall(e,n,r);if(t){const e="error-text"===s.output.type?ke.cross:ke.tick;t.stopAndPersist({symbol:e})}const i="string"==typeof s.output?s.output:"value"in s.output?s.output.value:"";if(d&&"string"==typeof i){const{cleanContent:e,metrics:t}=extractAgentMetrics(i);t&&(d.agents.push(t),s.output={type:"text",value:e})}y&&y.toolCalls.push({name:e.toolName,isError:"error-text"===s.output.type}),v.push(s)}d&&y&&(y.toolDurationMs=Date.now()-C,d.turnDetails.push(y));const k=t.content.filter(e=>"tool-result"!==e.type);l.push({role:"assistant",content:k}),l.push({role:"tool",content:v})}m>=s&&(d&&(d.maxTurnsReached=!0),process.stderr.write(`Warning: Reached maximum conversation turns (${s}). The response may be incomplete. Use --max-turns to increase the limit.\n`))}finally{d&&writeBenchmarkMetrics(d)}return g}function getShellPathAndName(){const e=process.env.SHELL||"/bin/bash",t=e.split("/").pop()?.toLowerCase()||"bash";return{path:e,name:t}}function getShellType(e){return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":"unknown"}function detectUserShell(){const{path:e,name:t}=getShellPathAndName();return"win32"===process.platform?{type:"unknown",path:e}:{type:getShellType(t),path:e}}__name(truncate,"truncate"),__name(formatToolLabel,"formatToolLabel"),__name(processQuery,"processQuery"),Ht(),Ht(),Ht(),Ht(),hs(),bS(),Ht(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var Ck=["no job control","cannot set terminal process group"],kk=null;function getShellInfo(){return kk||(kk=detectUserShell()),kk}__name(getShellInfo,"getShellInfo");var Tk=__name(async(e,t={})=>{const{timeout:n=3e4,cwd:r=process.cwd(),env:s=process.env}=t;return new Promise(t=>{let o=!1;const i=__name(e=>{o||(o=!0,t(e))},"doResolve"),a=getShellInfo(),l="bash"===a.type||"zsh"===a.type,u=l?a.path:"/bin/bash",d=M(u,l?["-i","-c",e]:["-c",e],{cwd:r,env:{...s},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let m="",g="",h=null;n>0&&(h=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),i({stdout:m,stderr:g+(g?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(m.length+n.length>us){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void i({stdout:m,stderr:fS,exitCode:1,command:e})}m+=n}catch(e){g+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,d.kill("SIGTERM")}}),d.stderr?.on("data",e=>{try{const t=e.toString();if(g.length+t.length>ds)return void(g+="\n[Error output truncated: too large]");g+=t}catch(e){g+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{h&&clearTimeout(h);const n=l?g.split("\n").filter(e=>!Ck.some(t=>e.includes(t))).join("\n"):g;i({stdout:m.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{h&&clearTimeout(h),i({stdout:m,stderr:g+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),_k=__name(e=>{let t="";return e.stdout&&(t+=e.stdout),e.stderr&&(t&&(t+="\n"),t+=e.stderr),0===e.exitCode||e.stderr||(t&&(t+="\n"),t+=`[Process exited with code ${e.exitCode}]`),t||"(No output)"},"formatBashOutput");dv();var xk=__name(()=>{const[e,t]=K({isExecuting:!1,currentCommand:null});return{executeBash:Z(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await Tk(e,{timeout:3e4,cwd:process.cwd()}),s=_k(t);n(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--){const r=n[t];if("bash"===r.role&&"command"in r&&r.command===e&&!r.output){n[t]=ZE(r,s);break}}return n}),r()}catch(t){const s=t instanceof Error?t.message:"Unknown error occurred";n(t=>{const n=[...t];for(let t=n.length-1;t>=0;t--){const r=n[t];if("bash"===r.role&&"command"in r&&r.command===e&&!r.output){n[t]=ZE(r,`Error: ${s}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");function useUiOverlays(){const[e,t]=K(!1),[n,r]=K(!1),[s,o]=K(!1),[i,a]=K(!1),[l,u]=K(!1),[d,m]=K(!1),[g,h]=K(!1),[f,y]=K(!1),[w,S]=K(!1),[E,v]=K(!1),[C,k]=K(!1),[T,_]=K(!1),[x,P]=K(!1),[A,I]=K(!1),[N,R]=K(!1),[$,M]=K(!1),[L,D]=K(!1),[O,F]=K(0),[q,j]=K("off");return{showFileList:e,setShowFileList:t,showAgentsConfig:n,setShowAgentsConfig:r,showTasteConfig:s,setShowTasteConfig:o,showSkillsConfig:i,setShowSkillsConfig:a,showProviderSelector:l,setShowProviderSelector:u,showModelSelector:d,setShowModelSelector:m,showMemorySelector:g,setShowMemorySelector:h,showMcpManager:f,setShowMcpManager:y,showLearningFeed:w,setShowLearningFeed:S,showSessionSelector:E,setShowSessionSelector:v,showAddDirModal:C,setShowAddDirModal:k,showRewindSelector:T,setShowRewindSelector:_,showLoginOverlay:x,setShowLoginOverlay:P,showCompactModeSelector:A,setShowCompactModeSelector:I,showContextView:N,setShowContextView:R,showStatusView:$,setShowStatusView:M,showUsageOverlay:L,setShowUsageOverlay:D,staticKey:O,setStaticKey:F,transcriptMode:q,setTranscriptMode:j,expandedToolOutput:"off"!==q}}function useFeed(){const[e,t]=K([]),[n,r]=K([]),[s,o]=K([]),[i,a]=K(!1),l=Y([]);return J(()=>{l.current=s},[s]),{feed:e,setFeed:t,liveEntries:n,setLiveEntries:r,queuedMessages:s,setQueuedMessages:o,isCmdCodeBusy:i,setIsCmdCodeBusy:a,queuedMessagesRef:l}}function useSession(){const[e,t]=K(crypto.randomUUID()),[n,r]=K(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:Y(null)}}function useStatus(e){const[t,n]=K("Ready..."),r=Y(!1),[s,o]=K(""),i=Y(null),[a,l]=K(null),u=Y(a),[d,m]=K(null),[g,h]=K(!1),[f,y]=K(""),[w,S]=K(null),[E,v]=K(0),[C,k]=K(null),[T,_]=K(!1),[x,P]=K(e??null);J(()=>{u.current=a},[a]),J(()=>{if(x){const e=setTimeout(()=>{P(null)},3e4);return()=>clearTimeout(e)}},[x]);const A=__name(e=>{i.current&&clearTimeout(i.current),o(e),i.current=setTimeout(()=>{o(""),i.current=null},5e3)},"showHintMessage");return{status:t,setStatus:n,pinnedStatusRef:r,hintMessage:s,setHintMessage:o,hintTimerRef:i,shareInfo:a,setShareInfo:l,shareInfoRef:u,billingLink:d,setBillingLink:m,showShareNotification:g,setShowShareNotification:h,unshareNotificationMessage:f,setUnshareNotificationMessage:y,retryAttempt:w,setRetryAttempt:S,interactionTokens:E,setInteractionTokens:v,contextUsage:C,setContextUsage:k,tasteLearningEnabled:T,setTasteLearningEnabled:_,updateStatus:x,setUpdateStatus:P,showHintMessage:A}}function useAuth(){const[e,t]=K(null),[n,r]=K(getConfiguredModel()),[s,o]=K(!1),[i,a]=K(null),[l,u]=K(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,isOAuthMode:s,setIsOAuthMode:o,authComponentInfo:i,setAuthComponentInfo:a,showProviderNotification:l,setShowProviderNotification:u,providerNotificationTimer:Y(null),modelNotificationTimer:Y(null)}}Ht(),__name(useUiOverlays,"useUiOverlays"),Ht(),__name(useFeed,"useFeed"),Ht(),__name(useSession,"useSession"),Ht(),__name(useStatus,"useStatus"),Ht(),xr(),__name(useAuth,"useAuth"),Ht(),Ht(),Ht(),Kt();var Pk=class extends De{static{__name(this,"PermissionsService")}config;configPath;projectRoot;constructor(e,n){super(),this.projectRoot=e,this.configPath=n||t.join(e,".commandcode","settings.local.json"),this.config=this.getDefaultConfig(),this.loadConfig()}getDefaultConfig(){return{enabled:!0,defaultScope:"session",autoApprove:{create:!1,edit:!1,delete:!1,execute:!1,shellCommands:!1},trustedPaths:[],trustedCommands:[],sessionPermissions:new Map,projectPermissions:new Map,sessionShellPermissions:new Map,projectShellPermissions:new Map}}async loadConfig(){try{const e=await O.readFile(this.configPath,"utf-8"),t=JSON.parse(e);t.permissions&&("acceptEdits"===t.permissions.defaultMode&&(this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0),t.permissions.autoApprove&&(void 0!==t.permissions.autoApprove.create&&(this.config.autoApprove.create=t.permissions.autoApprove.create),void 0!==t.permissions.autoApprove.update&&(this.config.autoApprove.edit=t.permissions.autoApprove.update),void 0!==t.permissions.autoApprove.delete&&(this.config.autoApprove.delete=t.permissions.autoApprove.delete)),t.permissions.allow&&t.permissions.allow.forEach(e=>{if(e.startsWith("Bash(")&&e.endsWith(")")){const t=e.slice(5,-1);this.config.trustedCommands.push(t)}}))}catch(e){}}async requestPermission(e){if(!this.config.enabled)return{allowed:!0};const t=e.action;return this.config.autoApprove[e.action]||this.isTrustedPath(e.filePath)?{allowed:!0}:this.config.sessionPermissions.has(t)?{allowed:this.config.sessionPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("permission-request",e,n=>{this.handleUserChoice(e,n).then(t)})})}async handleUserChoice(e,t){const n=e.action,r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionPermissions.set(n,!0);break;case"project":await this.createCommandCodeSettings(),this.config.autoApprove.create=!0,this.config.autoApprove.edit=!0,this.config.autoApprove.delete=!0,this.config.autoApprove.execute=!0}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getFileKey(e){const n=t.relative(this.projectRoot,e.filePath);return`${e.action}:${n}`}isTrustedPath(e){const n=t.relative(this.projectRoot,e);return this.config.trustedPaths.some(t=>n.startsWith(t)||e.startsWith(t))}async requestShellPermission(e){if(!this.config.enabled)return{allowed:!0};const t=this.getCommandKey(e);return this.config.autoApprove.shellCommands||this.isTrustedCommand(e.command)?{allowed:!0}:this.config.projectShellPermissions.has(t)?{allowed:this.config.projectShellPermissions.get(t)||!1,scope:"project"}:this.config.sessionShellPermissions.has(t)?{allowed:this.config.sessionShellPermissions.get(t)||!1,scope:"session"}:new Promise(t=>{this.emit("shell-permission-request",e,n=>{this.handleShellUserChoice(e,n).then(t)})})}async handleShellUserChoice(e,t){const n=this.getCommandKey(e),r="no"!==t.value;if(r&&t.scope)switch(t.scope){case"session":this.config.sessionShellPermissions.set(n,!0);break;case"project":await this.addCommandToSettings(e.command),this.config.projectShellPermissions.set(n,!0)}return{allowed:r,scope:t.scope,dontAskAgain:"yes-project"===t.value}}getCommandKey(e){return`${e.command.split(" ")[0]}:${e.args?Array.isArray(e.args)?e.args.join(" "):e.args:""}`.trim()}isTrustedCommand(e){return!!["ls","ls -la","ls -l","ls -R","pwd","grep","tree","find","stat","file","dirname","basename","grep","git status","git log","git diff","git branch"].some(t=>e===t||!!e.startsWith(t+" "))||this.config.trustedCommands.some(t=>{if(t===e)return!0;if(t.endsWith(":*")){const n=t.slice(0,-2);return e===n||e.startsWith(n+" ")}return e.startsWith(t)})}clearSessionPermissions(){this.config.sessionPermissions.clear(),this.config.sessionShellPermissions.clear()}clearProjectPermissions(){this.config.projectPermissions.clear(),this.config.projectShellPermissions.clear()}setAutoApprove(e,t){this.config.autoApprove[e]=t}addTrustedPath(e){this.config.trustedPaths.includes(e)||this.config.trustedPaths.push(e)}removeTrustedPath(e){const t=this.config.trustedPaths.indexOf(e);t>-1&&this.config.trustedPaths.splice(t,1)}addTrustedCommand(e){this.config.trustedCommands.includes(e)||this.config.trustedCommands.push(e)}removeTrustedCommand(e){const t=this.config.trustedCommands.indexOf(e);t>-1&&this.config.trustedCommands.splice(t,1)}setEnabled(e){this.config.enabled=e}getConfig(){return{...this.config}}async createCommandCodeSettings(){const e=t.join(this.projectRoot,".commandcode"),n=t.join(e,"settings.local.json");try{await O.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await O.readFile(n,"utf-8"),r=JSON.parse(e);r.permissions&&r.permissions.allow&&(t.permissions.allow=[...new Set([...r.permissions.allow,...t.permissions.allow])]),r.permissions&&r.permissions.deny&&(t.permissions.deny=r.permissions.deny)}catch(e){}await O.writeFile(n,JSON.stringify(t,null,2),"utf-8")}catch(e){console.error("Failed to create .commandcode settings:",e)}}async addCommandToSettings(e){const n=t.join(this.projectRoot,".commandcode"),r=t.join(n,"settings.local.json"),s=`Bash(${e.split(" ")[0]}:*)`;try{let e;await O.mkdir(n,{recursive:!0});try{const t=await O.readFile(r,"utf-8");e=JSON.parse(t)}catch(t){e={permissions:{allow:[],deny:[],defaultMode:"ask"}}}e.permissions||(e.permissions={allow:[],deny:[],defaultMode:"ask"}),e.permissions.allow||(e.permissions.allow=[]),e.permissions.allow.includes(s)||e.permissions.allow.push(s),await O.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},Ak=__name((e={})=>{const[t,n]=K(null),[r,s]=K(null),[o,i]=K(!1);return J(()=>{const t=e.projectRoot||process.cwd(),r=new Pk(t);return r.on("permission-request",(t,n)=>{s(t),i(!0),e.onPermissionRequest&&e.onPermissionRequest(t),r._pendingCallback=n}),r.on("shell-permission-request",(t,n)=>{s(t),i(!0),e.onShellPermissionRequest&&e.onShellPermissionRequest(t),r._pendingShellCallback=n}),n(r),()=>{r.removeAllListeners()}},[e.projectRoot]),{requestPermission:Z(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:Z(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:Z(e=>{if(t)if(t._pendingShellCallback){const n=t._pendingShellCallback;t._pendingShellCallback=null,n(e),s(null),i(!1)}else if(t._pendingCallback){const n=t._pendingCallback;t._pendingCallback=null,n(e),s(null),i(!1)}},[t]),clearSessionPermissions:Z(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:Z(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:Z((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:Z(e=>{t?.setEnabled(e)},[t]),currentRequest:r,isPrompting:o,service:t}},"usePermissions");function applyAutoAcceptMode(e){const{enabled:t,service:n}=e,r="auto-accept"===("boolean"==typeof t?t?"auto-accept":"standard":t),s=["create","edit","delete","execute","shellCommands"];for(const e of s)n.setAutoApprove(e,r)}function usePermissionMode({initialPermissionMode:e,dangerouslySkipPermissions:t=!1,setPendingPermission:n,setStatus:r,contextEngineRef:s}){const[o,i]=K(()=>e||(t?"auto-accept":"standard")),a=Y(o);J(()=>{a.current=o},[o]);const{requestShellPermission:l,service:u,respondToPrompt:d,clearSessionPermissions:m,setEnabled:g}=Ak({projectRoot:process.cwd(),onPermissionRequest:__name(e=>{n({toolName:"edit"===e.action?"edit_file":"create"===e.action?"write_file":"delete"===e.action?"delete_file":"edit_file",params:e,resolve:__name(e=>{},"resolve")}),s.current&&r("Waiting for file edit permission...")},"onPermissionRequest"),onShellPermissionRequest:__name(e=>{n({toolName:"shell_command",params:e,resolve:__name(e=>{},"resolve")}),s.current&&r("Waiting for shell command permission...")},"onShellPermissionRequest"),onPermissionResponse:__name(e=>{e.allowed?r("Permission granted"):r("Permission denied")},"onPermissionResponse")});return J(()=>{u&&applyAutoAcceptMode({enabled:o,service:u})},[o,u]),{permissionMode:o,setPermissionMode:i,permissionModeRef:a,permissionsService:u,respondToPrompt:d,clearSessionPermissions:m}}function usePendingOps(){const[e,t]=K(null),[n,r]=K(null);return{pendingPermission:e,setPendingPermission:t,pendingQuestion:n,setPendingQuestion:r}}function useOnboarding(){const[e,t]=K(!1),[n,r]=K(!1),[s,o]=K(!0),[i,a]=K(!1),[l,u]=K(!1),[d,m]=K(null),[g,h]=K(!1);return{showTrustPrompt:e,setShowTrustPrompt:t,projectTrusted:n,setProjectTrusted:r,checkingProject:s,setCheckingProject:o,showTasteOnboarding:i,setShowTasteOnboarding:a,onboardingComplete:l,setOnboardingComplete:u,tasteOnboardingEntryId:d,setTasteOnboardingEntryId:m,autoLearnTaste:g,setAutoLearnTaste:h,tasteOnboardingCheckedRef:Y(!1)}}function useExit(){const[e,t]=K(!1),[n,r]=K(null),s=Y(null),o=Y(0),i=Y(null),a=Z(()=>{s.current=null,r(null),i.current&&(clearTimeout(i.current),i.current=null)},[]);return{shouldExit:e,setShouldExit:t,pendingExitKey:n,setPendingExitKey:r,pendingExitKeyRef:s,lastExitKeyTimeRef:o,exitConfirmationTimeoutRef:i,resetPendingExitKey:a}}function createKillShellPermissionRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:t,description:`Terminate process on ${t}`}}function buildShellPermissionRequest(e,t){const n=e.args,r=Array.isArray(n)?n.join(" "):"string"==typeof n?n:"";return{command:"string"==typeof e.command?e.command:"",args:"string"==typeof n?n:Array.isArray(n)?n.join(" "):void 0,workingDirectory:"string"==typeof e.directory?e.directory:void 0,description:t??`Execute shell command: ${String(e.command??"")} ${r}`}}function getFileAction(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function buildFilePermissionRequest(e,t){const n="edit_file"===e?t.oldValue:void 0,r="edit_file"===e?t.newValue:void 0;return{action:getFileAction(e),filePath:String(t.filePath??t.file_path??t.path??t.absolutePath??"unknown"),description:"string"==typeof t.description?t.description:`${e} operation`,oldContent:"string"==typeof n?n:void 0,newContent:"string"==typeof r?r:void 0}}function useContextEngine({sessionId:e,sessionLoaded:t,showSessionSelector:n,projectTrusted:r,setFeed:s,setLiveEntries:o,setQueuedMessages:i,queuedMessagesRef:a,setStatus:l,pinnedStatusRef:u,setRetryAttempt:d,setInteractionTokens:m,setContextUsage:g,setCurrentProvider:h,shareInfoRef:f,permissionsService:y,permissionModeRef:w,setPendingQuestion:S,contextEngineRef:E}){const v=Z(t=>({onFeedUpdate:__name(e=>{const t=e.metadata?.status;"running"!==t?(o(t=>0===t.length?t:t.filter(t=>t.id!==e.id)),s(t=>[...t,e])):o(t=>{const n=t.findIndex(t=>t.id===e.id);if(-1!==n){const r=[...t];return r[n]=e,r}return[...t,e]})},"onFeedUpdate"),getQueuedMessages:__name(()=>{const e=[...a.current];return a.current=[],i([]),e},"getQueuedMessages"),onInteractionTokenUpdate:__name(e=>{m(e)},"onInteractionTokenUpdate"),onContextUsageUpdate:__name(e=>{g(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{d(e)},"onRetryUpdate"),onProviderChange:__name(e=>{h(e)},"onProviderChange"),onStatusUpdate:__name(e=>{u.current=!0,l(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{const r=t??{};if(!y)return!0;if("shell_command"===e){const e=buildShellPermissionRequest(r,n);return(await y.requestShellPermission(e)).allowed}if("kill_shell"===e){const e=createKillShellPermissionRequest(r);return(await y.requestShellPermission(e)).allowed}const s=buildFilePermissionRequest(e,r);return(await y.requestPermission(s)).allowed},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{S({params:e,resolve:t,reject:n}),l("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const n=f.current;return n?{sessionId:t??e,secret:n.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>w.current,"getPermissionMode")}),[y,e]);return J(()=>{E.current||!r||n||t||(E.current=new gC(v(),e))},[e,n,t,r,v,E]),{createContextEngineCallbacks:v}}Ht(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),__name(usePermissionMode,"usePermissionMode"),Ht(),__name(usePendingOps,"usePendingOps"),Ht(),__name(useOnboarding,"useOnboarding"),Ht(),__name(useExit,"useExit"),Ht(),SC(),__name(createKillShellPermissionRequest,"createKillShellPermissionRequest"),__name(buildShellPermissionRequest,"buildShellPermissionRequest"),__name(getFileAction,"getFileAction"),__name(buildFilePermissionRequest,"buildFilePermissionRequest"),__name(useContextEngine,"useContextEngine"),Ht(),Ht(),Ht(),In();var Ik=5242880,Nk=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(y.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await D.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean).slice(-100);let t=0;this.buffer=e.map(e=>{try{return JSON.parse(e).p}catch{return t++,""}}).filter(Boolean),t>0&&dlog(`[PromptHistory] Skipped ${t} corrupted entries`)}catch(e){e instanceof Error&&"code"in e&&"ENOENT"===e.code||dlog(`[PromptHistory] Failed to load history: ${e instanceof Error?e.message:String(e)}`),this.buffer=[]}this.initialized=!0}}add(e){if(!e||0===e.trim().length)return;const t=e.length>5e4?e.slice(0,5e4)+"...":e;this.buffer[this.buffer.length-1]!==t&&(this.buffer.push(t),this.buffer.length>500&&(this.buffer=this.buffer.slice(-500)),this.writeQueue.push({p:t,t:Date.now()}),this.scheduleFlush())}getAt(e){if(e<0||e>=this.buffer.length)return;const t=this.buffer.length-1-e;return this.buffer[t]}count(){return this.buffer.length}getAll(){return[...this.buffer]}isInitialized(){return this.initialized}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,await this.flush()},100))}async flush(){if(0===this.writeQueue.length)return;if(this.isFlushing)return void this.scheduleFlush();if(this.writeFailures>=3)return void(this.writeQueue=[]);this.isFlushing=!0;const t=this.writeQueue;this.writeQueue=[];try{const n=e.dirname(this.filePath);await D.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await D.appendFile(this.filePath,r),this.writeFailures=0,await this.rotateIfNeeded()}catch(e){this.writeFailures++;const n=e instanceof Error?e.message:String(e);this.writeFailures<3?(this.writeQueue.unshift(...t),dlog(`[PromptHistory] Write failed, retrying (${this.writeFailures}/3): ${n}`)):dlog(`[PromptHistory] Write disabled after 3 failures: ${n}`)}finally{this.isFlushing=!1}}async rotateIfNeeded(){try{const e=await D.stat(this.filePath);if(e.size<=Ik)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await D.readFile(this.filePath,"utf-8")).trim().split("\n").filter(Boolean),n=Math.floor(2621440),r=[];let s=0;for(let e=t.length-1;e>=0;e--){const o=Buffer.byteLength(t[e],"utf-8")+1;if(s+o>n)break;s+=o,r.unshift(t[e])}await D.writeFile(this.filePath,r.join("\n")+"\n"),dlog(`[PromptHistory] Rotated: kept ${r.length} of ${t.length} entries (${s} bytes)`)}catch(e){dlog(`[PromptHistory] Rotation failed (non-critical): ${e instanceof Error?e.message:String(e)}`)}}async cleanup(){return this.cleanupPromise||(this.cleanupPromise=this.performCleanup().finally(()=>{this.cleanupPromise=null})),this.cleanupPromise}async performCleanup(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null);const e=Date.now();for(;this.isFlushing;){if(Date.now()-e>=5e3){dlog("[PromptHistory] Cleanup timed out waiting for flush after 5000ms");break}await new Promise(e=>setTimeout(e,10))}await this.flush()}};function createHistoryManager(){return new Nk}__name(createHistoryManager,"createHistoryManager"),hE(),vv(),bC(),Vv(),Ht(),Kt(),lw();var Rk=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await D.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await D.access(r);const e=await D.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await D.writeFile(r,t,"utf-8")}catch{await D.writeFile(r,nw+"\n\n","utf-8")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await D.access(n),!0}catch{return!1}}};xr(),Rr(),Ht(),SC(),dv(),bC(),Ht(),Kt(),Th(),Wy(),Xy();var{setText:$k}=Ke;async function loadShareInfo({contextEngineRef:e,setShareInfo:t}){const n=e.current?.getSessionManager();if(n){const e=await n.loadShareInfo();e&&t({url:e.url,secret:e.secret})}}async function handleShareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setShowShareNotification:s,contextEngineRef:o}){if(e){if(t)return await $k(t.url),r(""),s(!0),void setTimeout(()=>{s(!1)},3e3);try{r("Creating share link...");const t=o.current?.getMessages()||[],i=hh.sanitizeMessages(t,global.COMMAND_CODE_CWD||process.cwd()),a=new xy({baseUrl:getApiBaseUrl()}),l=await a.post({endpoint:kt.ALPHA.SHARE.CREATE,body:{sessionId:e,messages:i}});n({url:l.url,secret:l.secret});const u=o.current?.getSessionManager();u&&await u.saveShareInfo({url:l.url,secret:l.secret}),await $k(l.url),r(""),s(!0),setTimeout(()=>{s(!1)},5e3)}catch(e){r(`Failed to create share: ${e instanceof Error?e.message:"Unknown error"}`)}}else r("No active session to share")}async function handleUnshareCommand({sessionId:e,shareInfo:t,setShareInfo:n,setStatus:r,setUnshareNotificationMessage:s,contextEngineRef:o}){if(e){if(!t)return s("NOT SHARED: Session is not currently shared"),void setTimeout(()=>s(""),5e3);try{r("Removing share link...");const i=new xy({baseUrl:getApiBaseUrl()});await i.delete({endpoint:kt.ALPHA.SHARE.DELETE,body:{sessionId:e,secret:t.secret}});const a=o.current?.getSessionManager();a&&await a.deleteShareInfo(),s("UNSHARED: Sharing has stopped"),r(""),n(null),setTimeout(()=>{s("")},5e3)}catch(e){const t=`Failed to unshare: ${e instanceof Error?e.message:"Unknown error"}`;r(t),setTimeout(()=>r(""),5e3)}}else r("No active session to unshare")}async function handleSelectSession({selectedSessionId:e,sessionLoadIdRef:t,contextEngineRef:n,setFeed:r,setLiveEntries:s,setSessionId:o,setShowSessionSelector:i,setSessionLoaded:a,setPermissionMode:l,setStaticKey:u,setShareInfo:d,createContextEngineCallbacks:m}){const g=crypto.randomUUID();t.current=g;try{r([]),s([]),n.current=null,l("standard"),o(e),i(!1),a(!0),n.current=new gC(m(e),e);const{feedEntries:h,corruptedLines:f,totalLines:y}=await n.current.loadSession(e);if(t.current!==g)return;await loadShareInfo({contextEngineRef:n,setShareInfo:d});const w=[];if(0===h.length&&y>0&&w.push(VE(`Session could not be loaded. ${y} lines could not be parsed.`)),0===h.length&&0===y&&w.push(zE("Session loaded but contains no messages.")),h.length>0&&(f>0&&w.push(zE(`Warning: ${f} message(s) could not be loaded.`)),w.push(...h)),t.current!==g)return;r(w),yC(),u(e=>e+1)}catch(e){if(t.current!==g)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";r([VE(`Failed to load session: ${n}. Starting fresh session.`)]),i(!1),a(!1),o(crypto.randomUUID())}}async function handleNewSession({contextEngineRef:e,setFeed:t,setLiveEntries:n,setSessionId:r,setShowSessionSelector:s,setSessionLoaded:o,setPermissionMode:i}){t([]),n([]),e.current=null,i("standard"),r(crypto.randomUUID()),s(!1),o(!1)}async function submitInitialPrompt({initialPrompt:e,onCommand:t,submitAsUserMessage:n}){const r=e.trim();r.startsWith("/")&&t&&"handled"===(await t(r)).status||await n()}function useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:s,stdout:o,feedState:i,sessionState:a,statusState:l,authState:u,onboarding:d,uiOverlays:m,permissionState:g,contextEngineRef:h,isSubmittingRef:f,initialPromptSubmittedRef:y,historyManagerRef:w,executeBash:S,createContextEngineCallbacks:E,setInput:v,onCommand:C}){const k=Z(async()=>{try{const e=await isTasteLearningEnabled();l.setTasteLearningEnabled(e),e&&await Rk.initializeProject()}catch{}},[l.setTasteLearningEnabled]),T=Z(async()=>{const e=await getConfiguredProvider();u.setCurrentProvider(e);const t=await isOAuthEnforced();u.setIsOAuthMode(t)},[u.setCurrentProvider,u.setIsOAuthMode]),_=Z(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(()=>{})},[]),x=Z(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:a.sessionLoadIdRef,contextEngineRef:h,setFeed:i.setFeed,setLiveEntries:i.setLiveEntries,setSessionId:a.setSessionId,setShowSessionSelector:m.setShowSessionSelector,setSessionLoaded:a.setSessionLoaded,setPermissionMode:g.setPermissionMode,setStaticKey:m.setStaticKey,setShareInfo:l.setShareInfo,createContextEngineCallbacks:E})},[a,i,m,g,l,h,E]),P=Z(async()=>{if(n){const e=await hv.listSessions();return void(e.length>0&&x(e[0].id))}t?x(t):e&&m.setShowSessionSelector(!0)},[n,t,e,x,m]);J(()=>{(async()=>{await hv.isProjectInitialized()?(d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_(),await P()):r?(await hv.initializeProject(),d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_(),await P()):isDirectoryEmpty()?(await hv.initializeProject(),d.setProjectTrusted(!0),d.setCheckingProject(!1),k(),T(),_()):(d.setShowTrustPrompt(!0),d.setCheckingProject(!1))})()},[e,n,r]),J(()=>{if(!d.projectTrusted)return;const e=createHistoryManager();return w.current=e,e.init(),()=>{e.cleanup()}},[d.projectTrusted]),J(()=>{if(!o)return;const e=__name(()=>{m.showLearningFeed||(yC(),m.setStaticKey(e=>e+1))},"handleResize");return o.on("resize",e),()=>{o.off("resize",e)}},[o]),J(()=>{s&&d.projectTrusted&&!d.checkingProject&&h.current&&!m.showSessionSelector&&!y.current&&(y.current=!0,submitInitialPrompt({initialPrompt:s,onCommand:C,submitAsUserMessage:__name(()=>handleSubmit({role:"user",input:s,feed:i.feed,setFeed:i.setFeed,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,contextEngineRef:h,isSubmittingRef:f,setInput:v,setStaticKey:m.setStaticKey,executeBash:S}),"submitAsUserMessage")}))},[s,d.projectTrusted,d.checkingProject,m.showSessionSelector,C]);const A=Y(null);A.current={feed:i.feed,setFeed:i.setFeed,isCmdCodeBusy:i.isCmdCodeBusy,setIsCmdCodeBusy:i.setIsCmdCodeBusy,setQueuedMessages:i.setQueuedMessages,setStatus:l.setStatus,setInteractionTokens:l.setInteractionTokens,updateStatus:l.updateStatus,setUpdateStatus:l.setUpdateStatus,billingLink:l.billingLink,setBillingLink:l.setBillingLink,contextEngineRef:h,isSubmittingRef:f,setInput:v,setStaticKey:m.setStaticKey,executeBash:S,role:"",input:""};const I=Z(async({role:e,input:t,images:n,ideContext:r,displayMessage:s,isAutomated:o})=>handleSubmit({...A.current,role:e,input:t,images:n,ideContext:r,displayMessage:s,isAutomated:o}),[]);return{loadTasteStatus:k,loadCurrentProvider:T,initializeMcpInBackground:_,onSubmit:I}}__name(loadShareInfo,"loadShareInfo"),__name(handleShareCommand,"handleShareCommand"),__name(handleUnshareCommand,"handleUnshareCommand"),__name(handleSelectSession,"handleSelectSession"),__name(handleNewSession,"handleNewSession"),ak(),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Ht(),xn(),dv(),_n(),Ht(),Kt(),In(),Ht();var Mk={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return Mk[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Le(t);return e.join(w.homedir(),".commandcode","projects",n)}function getGlobalProjectSettingsPath(t=process.cwd()){return e.join(getGlobalProjectSettingsDir(t),"settings.json")}async function loadGlobalProjectSettings(e=process.cwd()){try{const t=getGlobalProjectSettingsPath(e),n=await D.readFile(t,"utf-8");return JSON.parse(n)}catch{return{}}}async function saveGlobalProjectSettings(t,n=process.cwd()){try{const r=getGlobalProjectSettingsPath(n),s=e.dirname(r);await D.mkdir(s,{recursive:!0}),await D.writeFile(r,JSON.stringify(t,null,2))}catch(e){const t=e instanceof Error?e.message:String(e);dlog("Error saving global project settings:",e),Zv.addEvent({type:"error",message:`Failed to save global project settings: ${t}`})}}async function loadLocalProjectSettings(t=process.cwd()){try{const n=e.join(t,".commandcode","settings.local.json"),r=await D.readFile(n,"utf-8");return JSON.parse(r)}catch{return{}}}async function loadMergedProjectSettings(e=process.cwd()){try{const t=mergeSettings(await loadGlobalProjectSettings(e),await loadLocalProjectSettings(e)),n=t.tasteOnboarding,r=n?.learnedSessions?.["claude-code"]?.length||0;return dlog(`[Config] project settings loaded (taste: ${n?.completed?"complete":n?.skipped?"skipped":"pending"}, learned: ${r} sessions)`),t}catch(e){return dlog("[Settings] error loading",e),{}}}function mergeSettings(e,t){const n={...e};return t.tasteOnboarding&&(n.tasteOnboarding={...e.tasteOnboarding,...t.tasteOnboarding},(e.tasteOnboarding?.learnedSessions||t.tasteOnboarding?.learnedSessions)&&(n.tasteOnboarding.learnedSessions={...e.tasteOnboarding?.learnedSessions,...t.tasteOnboarding?.learnedSessions})),n}__name(getAgentDisplayName,"getAgentDisplayName"),__name(getProjectDirName,"getProjectDirName"),Ht(),In(),tC(),Kt(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),Ht(),In();var Lk=e.join(y.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=A(e,{encoding:"utf8"}),n=Ye.createInterface({input:t,crlfDelay:1/0});for await(const e of n)if(e.trim()){try{const r=JSON.parse(e);if("session_meta"===r.type&&r.payload?.cwd)return n.close(),t.destroy(),{cwd:r.payload.cwd,id:r.payload.id,timestamp:r.payload.timestamp}}catch{}break}return n.close(),t.destroy(),null}catch{return null}}async function findAllSessionFiles(t,n){const r=[];try{await D.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const s=await D.readdir(t);for(const o of s){if(!/^\d{4}$/.test(o))continue;const s=e.join(t,o);if(!(await D.stat(s)).isDirectory())continue;const i=await D.readdir(s);for(const t of i){if(!/^\d{2}$/.test(t))continue;const i=e.join(s,t);if(!(await D.stat(i)).isDirectory())continue;const a=await D.readdir(i);for(const s of a){if(!/^\d{2}$/.test(s))continue;const a=e.join(i,s);if(!(await D.stat(a)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${o}/${t}/${s}`});const l=(await D.readdir(a)).filter(e=>e.endsWith(".jsonl")&&e.startsWith("rollout-")).map(t=>e.join(a,t));r.push(...l)}}}}catch(e){dlog("[Codex] error scanning sessions",e)}return r}async function processFilesInBatches(e,t,n=10,r){const s=[];for(let o=0;o<e.length;o+=n){const i=e.slice(o,o+n),a=await Promise.all(i.map(t));for(const e of a)null!==e&&s.push(e);r?.(Math.min(o+n,e.length),e.length)}return s}async function findCodexSessions(t,n,r=0){const s=t||process.cwd(),o=[];dlog(`[Codex] scanning for project: ${s}`);const i=await findAllSessionFiles(Lk,n);if(0===i.length)return dlog("[Codex] no session files found"),n?.({phase:"complete",totalFiles:0,processedFiles:0,matchedSessions:0}),[];dlog(`[Codex] found ${i.length} session files to scan`),n?.({phase:"reading",totalFiles:i.length,processedFiles:0,matchedSessions:0});let a=0;const l=await processFilesInBatches(i,async t=>{const n=await readSessionMeta(t);if(!n)return null;if(n.cwd===s)try{const r=await D.stat(t),s=e.basename(t,".jsonl");return{id:n.id||s,filePath:t,createdAt:new Date(n.timestamp||r.birthtime),lastModified:r.mtime,messageCount:0,agent:"codex",projectDir:n.cwd}}catch{return null}return null},10,(e,t)=>{a=o.length,n?.({phase:"reading",totalFiles:t,processedFiles:e,matchedSessions:a})});o.push(...l);const u=r>0?o.slice(0,r):o;return dlog(`[Codex] matched ${u.length} sessions for project`),n?.({phase:"complete",totalFiles:i.length,processedFiles:i.length,matchedSessions:u.length}),u.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime())}async function findCodexSessionIds(e){return(await findCodexSessions(e)).map(e=>e.id)}async function extractCodexPrompts(e){const t=[];try{const n=(await D.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("event_msg"===n.type&&"user_message"===n.payload?.type&&n.payload?.message){const e=n.payload.message;"string"==typeof e&&e.trim()&&t.push(e.trim())}}catch{continue}t.length>0&&dlog(`[Codex] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Codex] failed to extract prompts: ${e}`,t)}return t}__name(readSessionMeta,"readSessionMeta"),__name(findAllSessionFiles,"findAllSessionFiles"),__name(processFilesInBatches,"processFilesInBatches"),__name(findCodexSessions,"findCodexSessions"),__name(findCodexSessionIds,"findCodexSessionIds"),__name(extractCodexPrompts,"extractCodexPrompts"),Ht(),In();var Dk=e.join(y.homedir(),".cursor","projects");function getCursorProjectDirNames(e){const t=e.replace(/[/\\:]/g,"-"),n=t.replace(/^-+/,"");return[...new Set([n,t])].filter(Boolean)}async function findAgentTranscriptsDir(t){try{await D.access(Dk)}catch{return dlog("[Cursor] projects directory not found"),null}const n=getCursorProjectDirNames(t);dlog(`[Cursor] looking for project dirs: ${n.join(", ")}`);try{const t=await D.readdir(Dk);for(const r of n){if(!t.includes(r))continue;const n=e.join(Dk,r,"agent-transcripts");try{if((await D.stat(n)).isDirectory())return dlog(`[Cursor] found agent-transcripts at: ${n}`),n}catch{}}}catch(e){dlog("[Cursor] error scanning projects",e)}return null}async function findCursorSessions(t,n=0){const r=t||process.cwd(),s=[];dlog(`[Cursor] scanning for project: ${r}`);const o=await findAgentTranscriptsDir(r);if(!o)return dlog("[Cursor] no agent-transcripts found"),[];try{const t=await D.readdir(o);for(const n of t){const t=e.join(o,n);try{if(!(await D.stat(t)).isDirectory())continue;const r=e.join(t,`${n}.jsonl`);try{const e=await D.stat(r);s.push({id:n,filePath:r,createdAt:e.birthtime,lastModified:e.mtime,messageCount:0,agent:"cursor"})}catch{}}catch{}}}catch(e){dlog("[Cursor] error reading agent-transcripts",e)}const i=s.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime()),a=n>0?i.slice(0,n):i;return dlog(`[Cursor] matched ${a.length} sessions for project`),a}async function findCursorSessionIds(e){return(await findCursorSessions(e)).map(e=>e.id)}async function extractCursorPrompts(e){const t=[];try{const n=(await D.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"!==n.role)continue;const r=n.message?.content;if(!Array.isArray(r))continue;for(const e of r)if("text"===e.type&&"string"==typeof e.text){const n=e.text.trim().replace(/^<user_query>\n?/,"").replace(/\n?<\/user_query>$/,"").trim();n&&t.push(n)}}catch{continue}t.length>0&&dlog(`[Cursor] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Cursor] failed to extract prompts: ${e}`,t)}return t}async function loadProjectSettings(){return loadMergedProjectSettings()}async function saveProjectSettings(e){await saveGlobalProjectSettings(e)}function isOnboardingDone(e){return!0===e?.skipped||!0===e?.completed}function buildAgentSessionsList(e){return Object.entries(e).filter(([e,t])=>t&&t.length>0).map(([e,t])=>({agent:e,sessionIds:t,displayName:getAgentDisplayName(e)}))}async function checkOnboardingConditions(){try{const e=(await loadProjectSettings()).tasteOnboarding,t=e?.learnedSessions||{},n=e?.skippedSessions||{},r={};for(const e of new Set([...Object.keys(t),...Object.keys(n)]))r[e]=[...t[e]||[],...n[e]||[]];const s=await findNewSessions(r),o=s["claude-code"]?.length||0,i=o+(s.codex?.length||0)+(s.cursor?.length||0);return i>0?(dlog(`[Onboarding] found ${i} new sessions to learn from`),{shouldTrigger:!0,reason:"has_sessions",sessionCount:i,hasTasteContent:!0,agentSessions:buildAgentSessionsList(s)}):(isOnboardingDone(e)?dlog(`[Onboarding] ${e?.skipped?"user skipped":"already completed"}, no new sessions`):dlog("[Onboarding] no sessions to learn from, skipping"),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:isOnboardingDone(e),agentSessions:[]})}catch(e){return dlog("[Onboarding] error checking conditions",e),{shouldTrigger:!1,reason:"skip",sessionCount:0,hasTasteContent:!1,agentSessions:[]}}}async function getSessionFilesFromDir(e){try{return(await D.readdir(e)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints")).map(e=>e.replace(".jsonl",""))}catch{return[]}}async function findNewSessions(t){const n={},r=t["claude-code"]||[],s=t.codex||[],o=t.cursor||[];try{const t=e.join(y.homedir(),".claude","projects");await D.access(t);const s=getProjectDirName(process.cwd()),o=(await D.readdir(t)).filter(e=>e===s);for(const s of o){const o=e.join(t,s);if((await D.stat(o)).isDirectory()){const e=await getSessionFilesFromDir(o);e.length>0&&(n["claude-code"]=e.filter(e=>!r.includes(e)))}}dlog(`[Sessions] claude-code: ${n["claude-code"]?.length||0} new, ${r.length} learned`)}catch{dlog("[Sessions] claude projects dir not found")}try{const e=await findCodexSessionIds();e.length>0&&(n.codex=e.filter(e=>!s.includes(e)));dlog(`[Sessions] codex: ${n.codex?.length||0} new, ${s.length} learned`)}catch{dlog("[Sessions] codex sessions not found")}try{const e=await findCursorSessionIds();e.length>0&&(n.cursor=e.filter(e=>!o.includes(e)));dlog(`[Sessions] cursor: ${n.cursor?.length||0} new, ${o.length} learned`)}catch{dlog("[Sessions] cursor sessions not found")}return n}async function markSessionsAsLearned(e,t){const n=await loadProjectSettings();n.tasteOnboarding||(n.tasteOnboarding={}),n.tasteOnboarding.learnedSessions||(n.tasteOnboarding.learnedSessions={});const r=n.tasteOnboarding.learnedSessions[e]||[];if(n.tasteOnboarding.learnedSessions[e]=Array.from(new Set([...r,...t])),n.tasteOnboarding.skippedSessions?.[e]){const r=new Set(t);n.tasteOnboarding.skippedSessions[e]=n.tasteOnboarding.skippedSessions[e].filter(e=>!r.has(e)),0===n.tasteOnboarding.skippedSessions[e].length&&delete n.tasteOnboarding.skippedSessions[e]}n.tasteOnboarding.lastLearningDate=(new Date).toISOString(),await saveProjectSettings(n)}async function markOnboardingSkipped(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.skipped=!0;try{const t=e.tasteOnboarding.learnedSessions||{},n=await findNewSessions(t);e.tasteOnboarding.skippedSessions||(e.tasteOnboarding.skippedSessions={});for(const[t,r]of Object.entries(n))if(r.length>0){const n=e.tasteOnboarding.skippedSessions[t]||[];e.tasteOnboarding.skippedSessions[t]=Array.from(new Set([...n,...r]))}}catch{dlog("[Onboarding] failed to record skipped sessions, skip flag still set")}await saveProjectSettings(e)}async function markOnboardingCompleted(){const e=await loadProjectSettings();e.tasteOnboarding||(e.tasteOnboarding={}),e.tasteOnboarding.completed=!0,await saveProjectSettings(e)}async function triggerTasteOnboarding({projectTrusted:e,onboardingComplete:t,isOnboardingMode:n,tasteOnboardingCheckedRef:r,setIsOnboardingMode:s}){if(e)if(t)dlog("[Onboarding] skipped - already completed");else if(n)dlog("[Onboarding] skipped - already showing");else if(r.current)dlog("[Onboarding] skipped - already checked this session");else{r.current=!0,dlog("[Onboarding] checking if taste learning should start...");try{const e=await checkOnboardingConditions();e.shouldTrigger?(dlog(`[Onboarding] starting taste learning (${e.reason})`),s(!0)):dlog("[Onboarding] not needed")}catch(e){dlog("[Onboarding] error",e)}}else dlog("[Onboarding] skipped - project not yet trusted")}function useLifecycle({exit:e,feedState:t,exitState:n,statusState:r,authState:s,onboarding:o,uiOverlays:i,skipOnboarding:a}){J(()=>{if(n.shouldExit){r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),s.providerNotificationTimer.current&&clearTimeout(s.providerNotificationTimer.current),s.modelNotificationTimer.current&&clearTimeout(s.modelNotificationTimer.current);try{e()}catch{process.exit(0)}}},[n.shouldExit,e]),J(()=>()=>{r.hintTimerRef.current&&clearTimeout(r.hintTimerRef.current),n.exitConfirmationTimeoutRef.current&&clearTimeout(n.exitConfirmationTimeoutRef.current),s.providerNotificationTimer.current&&clearTimeout(s.providerNotificationTimer.current),s.modelNotificationTimer.current&&clearTimeout(s.modelNotificationTimer.current)},[]),J(()=>{(async()=>{if("anthropic"===s.currentProvider&&s.isOAuthMode)try{await Sn.getValidAccessToken()||r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}catch{r.setStatus("OAuth setup required. Use /provider to select Claude and authenticate.")}})()},[s.currentProvider,s.isOAuthMode]),J(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(sv())},7e3);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),J(()=>{a||triggerTasteOnboarding({projectTrusted:o.projectTrusted,onboardingComplete:o.onboardingComplete,isOnboardingMode:o.showTasteOnboarding,tasteOnboardingCheckedRef:o.tasteOnboardingCheckedRef,setIsOnboardingMode:o.setShowTasteOnboarding})},[o.projectTrusted,o.onboardingComplete,o.showTasteOnboarding,a]),J(()=>{if(o.showTasteOnboarding&&!o.tasteOnboardingEntryId){const e=KE();o.setTasteOnboardingEntryId(e.id),t.setFeed(t=>[...t,e])}!o.showTasteOnboarding&&o.tasteOnboardingEntryId&&(t.setFeed(e=>e.filter(e=>e.id!==o.tasteOnboardingEntryId)),o.setTasteOnboardingEntryId(null))},[o.showTasteOnboarding,o.tasteOnboardingEntryId])}__name(getCursorProjectDirNames,"getCursorProjectDirNames"),__name(findAgentTranscriptsDir,"findAgentTranscriptsDir"),__name(findCursorSessions,"findCursorSessions"),__name(findCursorSessionIds,"findCursorSessionIds"),__name(extractCursorPrompts,"extractCursorPrompts"),__name(loadProjectSettings,"loadProjectSettings"),__name(saveProjectSettings,"saveProjectSettings"),__name(isOnboardingDone,"isOnboardingDone"),__name(buildAgentSessionsList,"buildAgentSessionsList"),__name(checkOnboardingConditions,"checkOnboardingConditions"),__name(getSessionFilesFromDir,"getSessionFilesFromDir"),__name(findNewSessions,"findNewSessions"),__name(markSessionsAsLearned,"markSessionsAsLearned"),__name(markOnboardingSkipped,"markOnboardingSkipped"),__name(markOnboardingCompleted,"markOnboardingCompleted"),__name(triggerTasteOnboarding,"triggerTasteOnboarding"),__name(useLifecycle,"useLifecycle"),Ht(),bC(),vv(),dv(),Ht(),kn(),Rr(),bC(),Kt(),Ht();var Ok="└",Fk=" ",qk=`${Fk}TASTE${Fk}`;function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showProviderSelector:n,showModelSelector:r,showMemorySelector:s,showMcpManager:o,showLearningFeed:i,showRewindSelector:a,showLoginOverlay:l,showUsageOverlay:u,showAddDirModal:d,authComponentInfo:m,setShowLearningFeed:g,setShowModelSelector:h,setStaticKey:f,transcriptMode:y,setTranscriptMode:w,isCmdCodeBusy:S,liveEntries:E,queuedMessagesRef:v,setInput:C,setQueuedMessages:k,setFeed:T,setLiveEntries:_,setIsCmdCodeBusy:x,setRetryAttempt:P,setStatus:A,pendingExitKey:I,setPendingExitKey:N,pendingExitKeyRef:R,lastExitKeyTimeRef:$,exitConfirmationTimeoutRef:M,resetPendingExitKey:L,pendingPermission:D,setPendingPermission:O,pendingQuestion:F,setPendingQuestion:q,setShouldExit:j,contextEngineRef:B,handleToggleAutoAccept:U,handleDoubleEscapeEmpty:z,respondToPrompt:W,createErrorEntry:G}){const H=__name(()=>{if(!B.current)return;B.current.interrupt(!0);const e=E.length>0;if(x(!1),P(null),_([]),A("Interrupted by user"),!e){const e=G("Interrupted by user");T(t=>[...t,e])}if(v.current.length>0){const e=v.current.map(e=>e.displayMessage??e.input).join("\n");C(t=>t?e+"\n"+t:e),k([]),v.current=[]}},"handleInterrupt");se((E,v)=>{if(v.shift&&v.tab||""===E)U();else if(e||t||n||r||s||o||m||i||a||l||u||d)I&&L();else{if(""===E||v.ctrl&&"c"===E){if(S&&B.current)return void H();const e=Date.now(),t=e-$.current;return $.current=e,"ctrl-c"===R.current&&t<2e3?(M.current&&(clearTimeout(M.current),M.current=null),void j(!0)):(C(()=>""),R.current="ctrl-c",N("ctrl-c"),M.current&&clearTimeout(M.current),void(M.current=setTimeout(()=>{R.current=null,N(null),M.current=null},2e3)))}if(v.ctrl&&"t"===E)return yC(),g(!i),void f(e=>e+1);if(getIsExpandToolShortcut(v,E))return yC(),w("off"===y?"limited":"off"),void f(e=>e+1);if(v.ctrl&&"e"===E&&"off"!==y)return yC(),w("limited"===y?"full":"limited"),void f(e=>e+1);if(v.meta&&"p"===E||isAltP(E))h(!0);else if(v.escape){if(F)return F.reject(new Error("Question cancelled by user")),q(null),void A("Question cancelled");if(D)return W({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),D.resolve(!1),O(null),void A("Permission denied");S&&B.current&&H()}}})}function useHandlers({resume:e,feedState:t,onboarding:n,uiOverlays:r,exitState:s,pendingOps:o,permissionState:i,statusState:a,authState:l,contextEngineRef:u,loadTasteStatus:d,loadCurrentProvider:m,setInput:g}){const h=Z(()=>{i.setPermissionMode(e=>{let t="standard";if("standard"===e&&(t="auto-accept"),"auto-accept"===e&&(t="plan"),"auto-accept"===t&&o.pendingPermission){const e={label:"Yes",value:"yes",description:"Allow this action",scope:void 0};i.respondToPrompt(e),o.pendingPermission.resolve(!0),o.setPendingPermission(null)}return"plan"===t&&o.pendingPermission&&(o.pendingPermission.resolve(!1),o.setPendingPermission(null)),t})},[i.setPermissionMode,i.respondToPrompt,o.pendingPermission,o.setPendingPermission]),f=Z(()=>{const e=!t.isCmdCodeBusy&&!o.pendingPermission&&!o.pendingQuestion,n=u.current?.hasCheckpoints()??!1;e&&n&&r.setShowRewindSelector(!0)},[t.isCmdCodeBusy,o.pendingPermission,o.pendingQuestion,r.setShowRewindSelector]),y=Z(s=>{if(n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),yC(),s?.skipped){const e=zE("",{isTasteSkip:!0});t.setFeed(t=>[...t,e])}r.setStaticKey(e=>e+1),e&&r.setShowSessionSelector(!0)},[e,n,r,t]),w=Z(async()=>{try{if(await hv.initializeProject(),n.setShowTrustPrompt(!1),e)return console.log("No conversations found to resume."),void s.setShouldExit(!0);n.setProjectTrusted(!0),d(),m()}catch(e){console.error("Failed to initialize project:",e),n.setShowTrustPrompt(!1),s.setShouldExit(!0)}},[e,n,s,d,m]),S=Z(()=>{s.setShouldExit(!0)},[s.setShouldExit]);return useKeyboard({showTasteConfig:r.showTasteConfig,showSkillsConfig:r.showSkillsConfig,showProviderSelector:r.showProviderSelector,showModelSelector:r.showModelSelector,showMemorySelector:r.showMemorySelector,showMcpManager:r.showMcpManager,showLearningFeed:r.showLearningFeed,showRewindSelector:r.showRewindSelector,showLoginOverlay:r.showLoginOverlay,showUsageOverlay:r.showUsageOverlay,showAddDirModal:r.showAddDirModal,authComponentInfo:l.authComponentInfo,setShowLearningFeed:r.setShowLearningFeed,setShowModelSelector:r.setShowModelSelector,setStaticKey:r.setStaticKey,transcriptMode:r.transcriptMode,setTranscriptMode:r.setTranscriptMode,isCmdCodeBusy:t.isCmdCodeBusy,liveEntries:t.liveEntries,queuedMessagesRef:t.queuedMessagesRef,setInput:g,setQueuedMessages:t.setQueuedMessages,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setRetryAttempt:a.setRetryAttempt,setStatus:a.setStatus,pendingExitKey:s.pendingExitKey,setPendingExitKey:s.setPendingExitKey,pendingExitKeyRef:s.pendingExitKeyRef,lastExitKeyTimeRef:s.lastExitKeyTimeRef,exitConfirmationTimeoutRef:s.exitConfirmationTimeoutRef,resetPendingExitKey:s.resetPendingExitKey,pendingPermission:o.pendingPermission,setPendingPermission:o.setPendingPermission,pendingQuestion:o.pendingQuestion,setPendingQuestion:o.setPendingQuestion,setShouldExit:s.setShouldExit,contextEngineRef:u,handleToggleAutoAccept:h,handleDoubleEscapeEmpty:f,respondToPrompt:i.respondToPrompt,createErrorEntry:VE}),{handleToggleAutoAccept:h,handleDoubleEscapeEmpty:f,handleTasteOnboardingComplete:y,handleTrust:w,handleNoTrust:S}}__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Ht(),Ht(),Kt(),dv(),Nr(),Ht(),Ht(),Ht(),Kt(),In(),$r(),Ur(),Ht(),Kt();var jk=t.join(w.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(jk);v.existsSync(e)||v.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!v.existsSync(jk))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=v.readFileSync(jk,"utf-8");return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null,...JSON.parse(e)}}catch{return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}}}function writeUpdatesConfig(e){ensureDir(),v.writeFileSync(jk,JSON.stringify(e,null,2))}function updateUpdatesConfig(e){writeUpdatesConfig({...readUpdatesConfig(),...e})}function shouldCheckForUpdate(){const e=readUpdatesConfig();return!!e.autoUpdate&&Date.now()-e.lastCheckedAt>=e.checkIntervalMs}function recordUpdateCheck(){updateUpdatesConfig({lastCheckedAt:Date.now()})}function setPendingUpdate(e){updateUpdatesConfig({lastCheckedAt:Date.now(),pending:e})}function clearPendingUpdate(){updateUpdatesConfig({pending:null})}function getPendingUpdate(e){const t=readUpdatesConfig();return t.pending?t.pending.currentVersion!==e?(clearPendingUpdate(),null):t.pending:null}__name(function getDefaultConfig(){return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null}},"getDefaultConfig"),__name(ensureDir,"ensureDir"),__name(readUpdatesConfig,"readUpdatesConfig"),__name(writeUpdatesConfig,"writeUpdatesConfig"),__name(updateUpdatesConfig,"updateUpdatesConfig"),__name(shouldCheckForUpdate,"shouldCheckForUpdate"),__name(recordUpdateCheck,"recordUpdateCheck"),__name(setPendingUpdate,"setPendingUpdate"),__name(clearPendingUpdate,"clearPendingUpdate"),__name(getPendingUpdate,"getPendingUpdate"),Jv(),$r();var Bk=Xe(R),Uk=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!process.env.COMMANDCODE_SKIP_UPDATES||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=$("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","pipe"],env:{...process.env,NODE_NO_WARNINGS:"1"}});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return Uk.version}function isAlphaVersion(e){return e.includes("alpha")}function filterVersions(e){return{stable:e.filter(e=>!e.includes("alpha")),alpha:e.filter(e=>e.includes("alpha"))}}function getLatestVersion(e){return 0===e.length?null:e.sort(Ze.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&Ze.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&Ze.gt(t,e))return{latestVersion:t,updateAvailable:!0}}return{latestVersion:e,updateAvailable:!1}}async function checkForUpdateAvailable(){const e=fetchVersions();if(!e)return null;const t=getCurrentVersion(),{stable:n,alpha:r}=filterVersions(e),{latestVersion:s,updateAvailable:o}=determineUpdateTarget(t,n,r);return{currentVersion:t,latestVersion:s,updateAvailable:o}}async function executeUpdate(e){try{return await Bk(`npm i -g command-code@${e}`,{env:{...process.env,NODE_NO_WARNINGS:"1"},timeout:6e5}),!0}catch{return!1}}function checkForUpdateAsync(){shouldSkipUpdateSystem()||shouldCheckForUpdate()&&doUpdateCheck().catch(()=>{})}async function doUpdateCheck(){dlog("[Updater] Starting async update check");const e=await checkForUpdateAvailable();return e?e.updateAvailable?(dlog(`[Updater] Update available: ${e.currentVersion} -> ${e.latestVersion}`),void setPendingUpdate({targetVersion:e.latestVersion,currentVersion:e.currentVersion,detectedAt:Date.now()})):(dlog("[Updater] No update available"),void recordUpdateCheck()):(dlog("[Updater] Failed to fetch version info"),void recordUpdateCheck())}async function maybeRunPendingUpdate(){if(shouldSkipUpdateSystem())return;const e=getCurrentVersion(),t=getPendingUpdate(e);if(!t)return;if(!Ze.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=Te(`Updating ${e} → ${t.targetVersion}`).start(),r=await executeUpdate(t.targetVersion);if(clearPendingUpdate(),!r)return n.fail("Update failed"),void console.log("Run `cmd update` to try again.");n.succeed(`Updated to v${t.targetVersion}`),trackLifecycleEvent({eventType:"cli_updated",metadata:{fromVersion:e,toVersion:t.targetVersion}}).catch(()=>{})}async function performAutoUpdate(e){const{silent:t,updateInfo:n,onStart:r}=e||{};if(isLocalDevelopmentBuild())return{success:!1};const s=n||await checkForUpdateAvailable();return s?.updateAvailable?(r?.(s.latestVersion),await executeUpdate(s.latestVersion)?{success:!0,updateInfo:s}:(t||(console.error("\nFailed to update command-code automatically."),console.error("Please update manually using: npm i -g command-code")),{success:!1,updateInfo:s})):{success:!1}}function getCurrentGitBranch(){try{return $("git rev-parse --abbrev-ref HEAD",{encoding:"utf-8",stdio:["pipe","pipe","ignore"],cwd:process.cwd()}).trim()||null}catch(e){return null}}function getGitHeaderInfo(){return{branch:getCurrentGitBranch(),isLocal:isLocalDevelopmentBuild()}}__name(shouldSkipUpdateSystem,"shouldSkipUpdateSystem"),__name(fetchVersions,"fetchVersions"),__name(getCurrentVersion,"getCurrentVersion"),__name(isAlphaVersion,"isAlphaVersion"),__name(filterVersions,"filterVersions"),__name(getLatestVersion,"getLatestVersion"),__name(determineUpdateTarget,"determineUpdateTarget"),__name(checkForUpdateAvailable,"checkForUpdateAvailable"),__name(executeUpdate,"executeUpdate"),__name(checkForUpdateAsync,"checkForUpdateAsync"),__name(doUpdateCheck,"doUpdateCheck"),__name(maybeRunPendingUpdate,"maybeRunPendingUpdate"),__name(performAutoUpdate,"performAutoUpdate"),__name(getCurrentGitBranch,"getCurrentGitBranch"),__name(getGitHeaderInfo,"getGitHeaderInfo");var zk=new Set(["OPEN","MERGED","CLOSED"]),Wk=null;function getCachedPRInfo(e){if(Wk&&Wk.branch===e){if(!(Date.now()-Wk.timestamp>3e5))return Wk.result;Wk=null}}function setPRCache(e,t){Wk={branch:e,result:t,timestamp:Date.now()}}function execFileAsync({cmd:e,args:t,encoding:n,timeout:r}){return new Promise((s,o)=>{L(e,[...t],{encoding:n,timeout:r},(e,t)=>{e?o(e):s(t.trim())})})}function parsePRResponse(e){try{const t=JSON.parse(e);return t.number&&t.url&&t.state&&zk.has(t.state)?{number:t.number,title:t.title||"",url:t.url,state:t.state}:null}catch{return null}}function getCachedPR(e){return e?getCachedPRInfo(e)??null:null}__name(getCachedPRInfo,"getCachedPRInfo"),__name(setPRCache,"setPRCache"),__name(execFileAsync,"execFileAsync"),__name(parsePRResponse,"parsePRResponse"),__name(getCachedPR,"getCachedPR");var Gk=__name(async()=>{const e=getCurrentGitBranch();if(!e)return null;if("main"===e||"master"===e)return null;const t=getCachedPRInfo(e);if(void 0!==t)return t;try{const t=parsePRResponse(await execFileAsync({cmd:"gh",args:["pr","view","--json","number,title,url,state"],encoding:"utf-8",timeout:3e3}));return setPRCache(e,t),t}catch{return null}},"detectPR");Ht();var Hk='You are an expert code reviewer. Do follow these steps:\n\nGather PR context using the GitHub CLI:\n1. When no PR number is given, list open PRs with `gh pr list` and ask which one to review\n2. Fetch PR metadata via `gh pr view <number>`\n3. Retrieve the changeset with `gh pr diff <number>`\n4. One go gather context: Run gh pr view <number> && echo "---DIFF---" && gh pr diff <number>\n5. Analyze the changes and provide a thorough code review that includes:\n\t- Overview of the PR is doing\n\t- Analysis of the code quality and style\n\t- Give specific suggestions for improvement\n\t- Highlight any potential bugs/issues or risks\n\t- Score PR on a scale of 1-5 based on overall table with quality and readiness for merging\nKeep your review concise, less wordy, but thorough.\nFocus on:\n- Correctness of code\n- Following project conventions\n- Performance issues and implications\n- Test coverage\n- Security considerations\n\nBe less wordy. If you make a table, don\'t go over 60pts.\nFormat your review in sections and bullets.';function buildReviewPrompt({prNumber:e,autoDetected:t=!1}){const n=e.trim();return n?`${Hk}\n\nReview PR number: ${n}${t?"\n(Note: PR number auto-detected from current branch.)":""}`:`${Hk}\n\nReview PR number: `}function lastResponseHasComments(e){const t=e[e.length-1];if(!t||"assistant"!==t.message.role)return!1;const{content:n}=t.message;if("string"==typeof n)return n.includes("## Review Comments")||n.includes("## PR Comments");const r=n.filter(e=>"text"===e.type).map(e=>e.text).join("");return r.includes("## Review Comments")||r.includes("## PR Comments")}function loadCustomCommands(){const e=[],n=t.join(process.cwd(),".commandcode","commands"),r=t.join(w.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,s=""){if(v.existsSync(n))try{const o=v.readdirSync(n,{withFileTypes:!0});for(const i of o){const o=t.join(n,i.name);if(i.isDirectory())loadCommandsFromDirectory(o,r,s?`${s}/${i.name}`:i.name);else if(i.isFile()&&i.name.endsWith(".md")){const n=t.basename(i.name,".md"),a=v.readFileSync(o,"utf-8").trim();e.push({name:n,source:r,content:a,subdirectory:s})}}}catch(e){}}return __name(loadCommandsFromDirectory,"loadCommandsFromDirectory"),loadCommandsFromDirectory(r,"user"),loadCommandsFromDirectory(n,"project"),e}function customCommandsToMenuItems(e){return e.map(e=>{const t=`/${e.name}`;let n;return n=e.subdirectory?"project"===e.source?`(project: ${e.subdirectory})`:`(user: ${e.subdirectory})`:"project"===e.source?"(project)":"(user)",{command:t,description:`${e.content.replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim()} ${n}`}})}function getCustomCommandContent(e){const t=loadCustomCommands(),n=e.startsWith("/")?e.substring(1):e,r=t.find(e=>e.name===n);return r?r.content:null}__name(buildReviewPrompt,"buildReviewPrompt"),Ht(),__name(lastResponseHasComments,"lastResponseHasComments"),Ht(),Kt(),Ht(),Kt(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),Nr(),Ht();var Qk=["Code","Code - Insiders","VSCodium","Cursor"],Vk="Code",Kk={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},Yk=__name(e=>g(e).href,"formatPathForTerminal"),Jk=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),Xk=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),Zk=__name(({home:t,configSegments:n,variants:r})=>{for(const s of r){const r=Xk({home:t,configSegments:n,variant:s});if(E.existsSync(e.dirname(r)))return s}return null},"findExistingVariant"),eT=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&tT(t.when)},"isTerminalShiftEnterBinding"),tT=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),nT=__name(e=>{const t=et(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),rT=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),sT=__name(({error:e,content:t})=>{const n=e.message;return rT(t)&&(n.includes("Expected double-quoted property name")||n.includes("Unexpected token")||n.includes("is not valid JSON"))?"Invalid JSON: trailing comma detected. Remove the comma before the closing bracket.":n.includes("Expected")&&n.includes(",")&&n.includes("or")?"Invalid JSON: missing comma between elements.":n.includes("Unterminated string")||n.includes("Bad string")?"Invalid JSON: unterminated string. Check for missing closing quotes.":"Invalid JSON syntax. Please check the file format."},"formatJsonParseError"),oT=__name(e=>{let t="",n=!1,r=!1;for(let s=0;s<e.length;s++){const o=e[s];if(n)t+=o,r?r=!1:"\\"===o?r=!0:'"'===o&&(n=!1);else if('"'!==o){if(","===o){let t=s+1;for(;t<e.length&&/\s/.test(e[t]);)t++;if("}"===e[t]||"]"===e[t])continue}t+=o}else n=!0,t+=o}return t},"removeTrailingCommas"),iT=__name(e=>{try{const t=et(e),n=oT(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:sT({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),aT=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:Yk(t)}),"createSuccessResult"),lT=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:Yk(t)}),"createErrorResult"),cT=__name(()=>{const t=y.homedir(),n=y.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=Jk(n);if(!r)return Xk({home:t,configSegments:[".config"],variant:Vk});const s=Zk({home:t,configSegments:r,variants:Qk});return Xk({home:t,configSegments:r,variant:s??Vk})},"getVSCodeKeybindingsPath"),uT=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)eT(n)&&(n.command===Kk.command&&n.args?.text===Kk.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),dT=__name(t=>{try{if(!E.existsSync(t)){const n=e.dirname(t);return E.existsSync(n)||E.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=E.readFileSync(t,"utf-8");if(nT(n))return{rawContent:n,keybindings:[]};const r=iT(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:lT({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):lT({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return lT({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),mT=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(Kk,null,2);if(nT(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return lT({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const s=e.lastIndexOf("}",r);return-1===s?lT({message:"VSCode keybindings.json is malformed (missing closing brace).",keybindingsPath:t}):e.substring(0,s+1)+",\n"+n+e.substring(s+1)},"generateNewContent");function setupVSCodeTerminal(){const e=cT();try{const t=dT(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,s=uT(r);if(s.hasConflicting)return lT({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(s.hasCompatible)return aT({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const o=mT({rawContent:n,keybindingsPath:e});return"string"!=typeof o?o:(E.writeFileSync(e,o,"utf-8"),aT({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return lT({message:`Failed to configure VSCode key binding: ${t instanceof Error?t.message:"Unknown error"}`,keybindingsPath:e})}}function isVSCodeTerminal(){return"vscode"===process.env.TERM_PROGRAM}__name(setupVSCodeTerminal,"setupVSCodeTerminal"),__name(isVSCodeTerminal,"isVSCodeTerminal"),hs(),dr();var pT=(e=>(e.INIT="/init",e.EXIT="/exit",e.HELP="/help",e.CLEAR="/clear",e.SHARE="/share",e.TASTE="/taste",e.LEARN_TASTE="/learn-taste",e.SKILLS="/skills",e.RESUME="/resume",e.RENAME="/rename",e.MEMORY="/memory",e.UNSHARE="/unshare",e.PROVIDER="/provider",e.MODEL="/model",e.AGENTS="/agents",e.MCP="/mcp",e.COMPACT="/compact",e.COMPACT_MODE="/compact-mode",e.REWIND="/rewind",e.LOGIN="/login",e.LOGOUT="/logout",e.FEEDBACK="/feedback",e.TERMINAL_SETUP="/terminal-setup",e.IDE_SETUP="/ide",e.ADD_DIR="/add-dir",e.REVIEW="/review",e.PR_COMMENTS="/pr-comments",e.CONTEXT="/context",e.STATUS="/status",e.USAGE="/usage",e))(pT||{}),gT=new Set(["/exit","/clear","/help","/share","/unshare","/taste","/learn-taste","/skills","/resume","/rename","/provider","/model","/memory","/init","/agents","/mcp","/compact","/compact-mode","/rewind","/login","/logout","/feedback","/terminal-setup","/ide","/add-dir","/pr-comments","/context","/status","/usage"]),hT=[{command:"/add-dir",description:"Add directory to workspace context"},{command:"/agents",description:"Manage agent configurations"},{command:"/clear",description:"Clear the conversation history (reset, new)"},{command:"/compact",description:"Compact the conversation history"},{command:"/compact-mode",description:"Select a compact mode to compact sessions"},{command:"/context",description:"Show context window usage and breakdown"},{command:"/exit",description:"Exit Command Code"},{command:"/feedback",description:"Share feedback or report bugs"},{command:"/help",description:"Show available shortcuts"},{command:"/ide",description:"Install extension to fetch IDE context"},{command:"/init",description:"Initialize AGENTS.md for this project"},{command:"/learn-taste",description:"Learn taste from sessions with other coding agents (Claude Code, Cursor, etc)"},{command:"/login",description:"Authenticate with CommandCode via browser"},{command:"/logout",description:"Remove stored authentication"},{command:"/mcp",description:"Manage MCP server connections"},{command:"/memory",description:"Manage Command Code memory"},{command:"/model",description:"Switch between Command Code models"},{command:"/pr-comments",description:"Fetch all PR comments for current branch"},{command:"/provider",description:"Select AI provider (Command Code or Anthropic)"},{command:"/rename",description:"Rename the current session"},{command:"/resume",description:"Resume a past conversation"},{command:"/review",description:"Review a pull request (optional PR number)"},{command:"/rewind",description:"Restore to a previous checkpoint (Press Esc twice)"},{command:"/share",description:"Share conversation (copy link to clipboard)"},{command:"/skills",description:"Browse and open agent skills"},{command:"/status",description:"Show comprehensive environment status"},{command:"/taste",description:"Manage Taste learning and usage"},{command:"/terminal-setup",description:"Setup VSCode keybindings"},{command:"/unshare",description:"Stop sharing conversation"},{command:"/usage",description:"Display credits, plan, and usage metrics"}],fT=__name(({onSelectCommand:e,onInsertCommand:t,onClose:n,searchQuery:r=""})=>{const[s,o]=K(0),[i,a]=K(0),{stdout:l}=re(),u=l?.columns??80,d=Math.max(20,u-22-2-1-2),m=X(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...hT.filter(e=>!("/provider"===e.command&&!isInternalTeamFlagEnforced()||"/terminal-setup"===e.command&&!isVSCodeTerminal()))];if(!r)return e;const t=r.toLowerCase();return e.map(e=>{const n=e.command.toLowerCase(),r=e.description.toLowerCase();let s=0;return n.startsWith("/"+t)?s+=100:n.includes(t)&&(s+=50),r.includes(t)&&(s+=25),{...e,score:s}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).map(({score:e,...t})=>t)},[r]),g=X(()=>{const e=i,t=Math.min(e+8,m.length);return m.slice(e,t)},[m,i]);return J(()=>{o(0),a(0)},[r]),se((r,l)=>{if(l.escape)n();else if(l.upArrow)o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t});else if(l.downArrow)o(e=>{const t=Math.min(m.length-1,e+1);return t>=i+8&&a(Math.max(0,t-8+1)),t});else{if(l.return){const t=m[s];return void(t&&e(t.command))}if(l.tab||l.rightArrow){const e=m[s];return void(e&&t(e.command))}}}),0===m.length?Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Q.createElement(te,{color:jn.DIM},"No commands found")):(m.length,Q.createElement(ee,{flexDirection:"column",paddingLeft:1},Q.createElement(ee,{columnGap:2},Q.createElement(ee,{flexDirection:"column",width:22},g.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:n,color:s===n?jn.WHITE:jn.DIM,wrap:"truncate"},e.command)})),Q.createElement(ee,{flexDirection:"column"},g.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:n,color:s===n?jn.WHITE:jn.DIM,wrap:"truncate"},truncateString({text:e.description,maxChars:d}))})))))},"CommandMenu");aw(),Ht(),Ht(),Rr(),dr();var yT=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),wT=__name(e=>{const t=Math.floor(e/86400),n=Math.floor(e%86400/3600),r=Math.floor(e%3600/60);return t>0?`${t}d ${n}h ${r}m`:n>0?`${n}h ${r}m`:`${r}m`},"formatUptime"),ST=__name(({icon:e,label:t,children:n})=>Q.createElement(te,null,Q.createElement(te,{color:jn.CYAN},e," "),Q.createElement(te,{color:jn.DIM},t.padEnd(12)),n),"Row"),bT=__name(({title:e})=>Q.createElement(te,null,Q.createElement(te,{color:jn.GRAY},"───"),Q.createElement(te,{color:jn.WHITE}," ",e," "),Q.createElement(te,{color:jn.GRAY},"─".repeat(35))),"Header"),ET=__name(({title:e,marginTop:t=0,children:n})=>Q.createElement(ee,{flexDirection:"column",marginTop:t},Q.createElement(bT,{title:e}),Q.createElement(ee,{flexDirection:"column",paddingY:1},n)),"Section"),vT=__name(({cpuCount:e,totalMem:t})=>Q.createElement(ET,{title:"System Information"},Q.createElement(ST,{icon:ke.bullet,label:"Date"},Q.createElement(te,null,formatDate())),Q.createElement(ST,{icon:ke.pointer,label:"Platform"},Q.createElement(te,{color:jn.GREEN},yT(y.platform())),Q.createElement(te,{color:jn.DIM}," ","(",y.platform(),", ",y.arch(),")")),Q.createElement(ST,{icon:ke.triangleUp,label:"Hostname"},Q.createElement(te,null,y.hostname())),Q.createElement(ST,{icon:ke.bullet,label:"User"},Q.createElement(te,{color:jn.YELLOW},y.userInfo().username)),Q.createElement(ST,{icon:ke.bullet,label:"CPUs"},Q.createElement(te,{color:jn.MAGENTA},e," cores")),Q.createElement(ST,{icon:ke.bullet,label:"Memory"},Q.createElement(te,{color:jn.CYAN},t," GB")),Q.createElement(ST,{icon:ke.play,label:"Uptime"},Q.createElement(te,null,wT(y.uptime()))),Q.createElement(ST,{icon:ke.arrowRight,label:"Home"},Q.createElement(te,{color:jn.DIM},y.homedir())),Q.createElement(ST,{icon:ke.pointer,label:"Shell"},Q.createElement(te,null,process.env.SHELL||"N/A")),Q.createElement(ST,{icon:ke.bullet,label:"Node"},Q.createElement(te,{color:jn.GREEN},process.version))),"SystemInfoSection"),CT=__name(({cpus:e})=>Q.createElement(ET,{title:"CPU Details",marginTop:1},e.map((e,t)=>Q.createElement(ST,{key:t,icon:ke.bullet,label:`Core ${t}`},Q.createElement(te,null,e.model.trim()),Q.createElement(te,{color:jn.YELLOW}," @ ",e.speed," MHz")))),"CPUDetailsSection"),kT=__name(({networkInterfaces:e})=>Q.createElement(ET,{title:"Network",marginTop:1},Object.entries(e).map(([e,t])=>{const n=t?.filter(e=>"IPv4"===e.family&&!e.internal);return n&&0!==n.length?n.map((t,n)=>Q.createElement(ST,{key:`${e}-${n}`,icon:ke.bullet,label:e},Q.createElement(te,{color:jn.GREEN},t.address))):null})),"NetworkSection"),TT=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,null,"System Information"),Q.createElement(te,null,"─".repeat(40)),Q.createElement(te,null,"Date ",formatDate()),Q.createElement(te,null,"Platform ",yT(y.platform())," (",y.platform(),","," ",y.arch(),")"),Q.createElement(te,null,"Hostname ",y.hostname()),Q.createElement(te,null,"User ",y.userInfo().username),Q.createElement(te,null,"CPUs ",e.length," cores"),Q.createElement(te,null,"Memory ",t," GB"),Q.createElement(te,null,"Uptime ",wT(y.uptime())),Q.createElement(te,null,"Home ",y.homedir()),Q.createElement(te,null,"Shell ",process.env.SHELL||"N/A"),Q.createElement(te,null,"Node ",process.version),r&&Q.createElement(Q.Fragment,null,Q.createElement(te,null,"\n","CPU Details"),Q.createElement(te,null,"─".repeat(40)),e.map((e,t)=>Q.createElement(te,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),Q.createElement(te,null,"\n","Network"),Q.createElement(te,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>Q.createElement(te,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),_T=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>Q.createElement(ee,{flexDirection:"column"},Q.createElement(vT,{cpuCount:e.length,totalMem:t}),r&&Q.createElement(CT,{cpus:e}),r&&Q.createElement(kT,{networkInterfaces:n})),"StyledInfo"),xT=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=ie();J(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=y.cpus(),s=y.networkInterfaces(),o=Math.round(y.totalmem()/1024/1024/1024);return t?Q.createElement(TT,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e}):Q.createElement(_T,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e})},"InfoUI"),PT={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},AT=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),IT=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(AT("__CFBundleIdentifier","com.todesktop"))return"Cursor";const e=[process.env.VSCODE_GIT_ASKPASS_MAIN,process.env.VSCODE_GIT_ASKPASS_NODE,process.env.GIT_ASKPASS].filter(Boolean);for(const t of e){const e=t.toLowerCase();if(e.includes("cursor"))return"Cursor";if(e.includes("windsurf"))return"Windsurf"}return"vscode"===process.env.TERM_PROGRAM&&"1"===process.env.VSCODE_INJECTION?"VSCode":null},"detectIDE"),NT=__name(()=>{const e=IT();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&PT[t]?PT[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),RT=__name(()=>{if("win32"===w.platform()){const e=process.env.COMSPEC;return e?l(e):process.env.SHELL?l(process.env.SHELL):"cmd.exe"}if(process.env.FISH_VERSION)return"fish";if(process.env.ZSH_VERSION)return"zsh";if(process.env.BASH_VERSION)return"bash";try{const e=process.ppid;if(e){const t=$(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=l(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?l(e):"N/A"},"getShellName"),$T=__name(()=>{const e=IT();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),MT=__name(()=>{try{const e=$("cmd --version",{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:yT(w.platform()),terminal:NT(),shell:RT(),version:MT(),ide:$T()}}function buildGitHubIssueUrl(e){const t=getSystemInfo(),n=new URLSearchParams;if(n.append("template","1.bug_report.yml"),e){const t=e.slice(0,256).trim();t&&n.append("title",t)}return n.append("version",t.version),n.append("os",t.os),n.append("terminal",t.terminal),n.append("shell",t.shell),`https://github.com/CommandCodeAI/command-code/issues/new?${n.toString()}`}function parsePositionalArguments(e){const{input:t}=e;if(!t.trim())return[];const n=[];let r="",s=!1,o="";for(let e=0;e<t.length;e++){const i=t[e];'"'!==i&&"'"!==i||s?i===o&&s?(s=!1,o=""):" "!==i||s?r+=i:(r.trim()&&n.push(r.trim()),r=""):(s=!0,o=i)}return r.trim()&&n.push(r.trim()),n}function parseCommandInput(e){const{input:t}=e,n=t.trim();if(!n.startsWith("/"))return null;const r=n.indexOf(" ");if(-1===r)return{commandName:n,rawArguments:"",positionalArgs:[]};const s=n.substring(0,r),o=n.substring(r+1).trim();return{commandName:s,rawArguments:o,positionalArgs:parsePositionalArguments({input:o})}}function processCommandTemplate(e){const{template:t,rawArguments:n,positionalArgs:r}=e;let s=t;return s=s.replace(/\$ARGUMENTS/g,n),s=s.replace(/\$(\d+)/g,(e,t)=>{const n=parseInt(t,10)-1;return n>=0&&n<r.length?r[n]:""}),{content:s}}async function handleRenameCommand({name:e,contextEngineRef:t,setFeed:n}){const r=e?.trim();if(!r)return void n(e=>[...e,zE("Usage: /rename [name]")]);const s=t.current?.getSessionManager();if(!s)return void n(e=>[...e,zE("No active session to rename")]);const o=s.getSessionId();await hv.isSessionNameTaken({name:r,excludeSessionId:o})?n(e=>[...e,VE(`A session named "${r}" already exists. Choose a different name.`)]):await s.saveSessionTitle(r)?n(e=>[...e,zE(`Session renamed to "${r}"`)]):n(e=>[...e,VE("Failed to rename session. Please try again.")])}async function handleCompactCommand({contextEngineRef:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:s,setStaticKey:o}){if(e.current)if(e.current.isRequestInProgress())t(e=>[...e,zE("Cannot compact while Command Code is working. Please wait for the current operation to complete.")]);else try{r(!0),n("Compacting conversation...");const i=await e.current.manualCompact();yC(),o(e=>e+1);let a="Compacted conversation.";i.didCompact||(a="Conversation is already compact."),i.didCompact&&i.tokensSaved>0&&(a=`Compacted conversation, saved ~${i.tokensSaved.toLocaleString()} tokens.`),t(e=>[...e,zE(a)]),r(!1),n("Ready..."),s({current:e.current.getContextTokensUsed()||0,limit:pS})}catch(e){const s=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;t(e=>[...e,VE(s)]),r(!1),n("Ready...")}else t(e=>[...e,zE("No active conversation to compact.")])}function handleRewindCommand({contextEngineRef:e,setFeed:t,setShowRewindSelector:n}){e.current?e.current.hasCheckpoints()?n(!0):t(e=>[...e,zE("No checkpoints available. Start sending messages to create checkpoints.")]):t(e=>[...e,zE("No active conversation to rewind.")])}async function handleRewindSelect({messageId:e,mode:t,contextEngineRef:n,setFeed:r,setStatus:s,setShowRewindSelector:o,setStaticKey:i,setInput:a}){if(o(!1),n.current)try{const o=n.current.listCheckpoints().find(t=>t.messageId===e);s("Restoring checkpoint...");const l=await n.current.restoreToCheckpoint({messageId:e,mode:t});if(l.success){const e=n.current.getSessionManager(),t=n.current.getMessages();r(e.reconstructFeedFromMessages(t)),yC(),i(e=>e+1),o?.userPrompt&&a(o.userPrompt);const u=[];l.filesRestored>0&&u.push(`${l.filesRestored} file${l.filesRestored>1?"s":""} restored`),l.filesDeleted>0&&u.push(`${l.filesDeleted} file${l.filesDeleted>1?"s":""} deleted`),l.messagesRemoved>0&&u.push(`${l.messagesRemoved} message${l.messagesRemoved>1?"s":""} removed`);const d=u.length>0?`Restored to checkpoint: ${u.join(", ")}.`:"Restored to checkpoint.";return r(e=>[...e,zE(d)]),void s("Ready...")}r(e=>[...e,VE(`Failed to restore: ${l.error}`)]),s("Restore failed")}catch(e){const t=`Failed to restore checkpoint: ${e instanceof Error?e.message:"Unknown error"}`;r(e=>[...e,VE(t)]),s("Ready...")}}function handleRewindCancel({setShowRewindSelector:e}){e(!1)}async function handleLoginCommand({setFeed:e,setShowLoginOverlay:t}){const n=zt();if(await getAuthKey(n)){let t="";try{const e=await loadCredentials();t=e?.userName||""}catch(e){process.env.DEBUG&&console.error("Failed to load credentials for display:",e)}const n=t&&"API Key"!==t&&"Manual API Key"!==t?` as ${t}`:"";return void e(e=>[...e,zE(`Already logged in${n}`)])}t(!0)}function handleLoginComplete({success:e,message:t,setShowLoginOverlay:n,setFeed:r,setStatus:s,contextEngineRef:o}){if(n(!1),!e)return r(e=>[...e,VE(t)]),void s("Ready...");r(e=>[...e,zE(t)]),o.current&&o.current.refreshRequest(),s("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,zE("Authentication cancelled.")]),n("Ready...")}async function handleLogoutCommand({setFeed:e,contextEngineRef:t,setRetryAttempt:n,setIsCmdCodeBusy:r}){const s=await performLogout();if(!s.success)return void e(e=>[...e,VE(`Logout failed: ${s.error}`)]);if(n(null),r(!1),t.current&&(t.current.interrupt(),t.current.refreshRequest()),!s.wasAuthenticated)return void e(e=>[...e,zE("Not currently authenticated.")]);const o=s.warnings.length>0?`Successfully logged out from Command Code. Warnings: ${s.warnings.join(", ")}`:"Successfully logged out from Command Code.";e(e=>[...e,zE(o)])}__name(getSystemInfo,"getSystemInfo"),__name(buildGitHubIssueUrl,"buildGitHubIssueUrl"),LC(),Ht(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),bC(),Ht(),dv(),vv(),__name(handleRenameCommand,"handleRenameCommand"),Ht(),dv(),bC(),bS(),__name(handleCompactCommand,"handleCompactCommand"),Ht(),dv(),bC(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Ht(),dv(),rk(),_C(),tk(),Kt(),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Ht(),_b(),In(),xr();var LT=Xe(R);function getVsixPath(){try{const e=t.dirname(d(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return v.existsSync(n)?n:null}catch{return null}}async function getExtensionStatus(e){if(!e)return{installed:!1,version:null,connected:!1};const[t,n]=await Promise.all([checkInstalled(e),wb.isAvailable(500)]);return{...t,connected:n}}async function checkInstalled(e){try{const{stdout:t}=await LT(`${e} --list-extensions --show-versions`,{timeout:5e3}),n=t.match(new RegExp("commandcode.commandcode-vscode@([\\d.]+)","i"));return n?{installed:!0,version:n[1]}:{installed:!1,version:null}}catch{return{installed:!1,version:null}}}async function installExtension(e){if(!e)return{success:!1,error:"No IDE detected"};const t=getVsixPath();if(!t)return{success:!1,error:"VSIX not bundled"};try{return await LT(`${e} --install-extension "${t}" --force`,{timeout:3e4}),dlog(`[IDE] Extension installed for ${e}`),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}function installExtensionAsync(e){e&&installExtension(e).catch(()=>{})}async function isAutoInstallEnabled(){try{return!1!==(await loadUserConfig()).autoInstallExtension}catch{return!0}}__name(getVsixPath,"getVsixPath"),__name(getExtensionStatus,"getExtensionStatus"),__name(checkInstalled,"checkInstalled"),__name(installExtension,"installExtension"),__name(installExtensionAsync,"installExtensionAsync"),__name(isAutoInstallEnabled,"isAutoInstallEnabled");var DT={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"};async function ensureExtensionInstalled(){if(process.env.CI)return;const e=db();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:le.green("✔"),installed:le.green("✔"),needs_reload:le.yellow("◌"),failed:le.red("✖"),not_in_ide:le.yellow("◌")},n={connected:`Connected to ${e.ide}`,installed:`Installed for ${e.ide}`,needs_reload:`${e.ide} extension needs reload`,failed:e.ide?`${e.ide} install failed`:"Install failed",not_in_ide:"Not in IDE"};return["",`${t[e.status]} ${n[e.status]}`,...(e.details??[]).map(e=>le.dim(` ${e}`)),""]}async function runIDESetup(){const e=db(),t=e?DT[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new wb,r=await n.connect(500);if(n.disconnect(),r)return{status:"connected",ide:t};const{installed:s}=await checkInstalled(e);return s?{status:"needs_reload",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:(await installExtension(e)).success?{status:"installed",ide:t,details:['Reload IDE window to activate (Cmd+Shift+P → "Reload Window").']}:{status:"failed",ide:t,details:[`Make sure "${e}" is available in your PATH.`,"Then run /ide to retry installation."]}}async function handleHelpCommand({setFeed:e}){const{createSystemEntry:t}=await Promise.resolve().then(()=>(dv(),uv));e(e=>[...e,t("KEYBOARD SHORTCUTS\nCOMMANDS")])}async function handleTerminalSetupCommand({setFeed:e}){const t=UE(`/${$t.TERMINAL_SETUP}`),n=setupVSCodeTerminal(),r=YE(n.message,!n.success,n.details);e(e=>[...e,t,r])}async function handleIDESetupCommand({setFeed:e}){const t=await runIDESetup(),n=JE(t.status,t.ide,t.details);e(e=>[...e,n])}async function handleClearCommand({setFeed:e,setLiveEntries:t,setShareInfo:n,setShowShareNotification:r,setUnshareNotificationMessage:s,setStaticKey:o,setContextUsage:i,setInteractionTokens:a,contextEngineRef:l,setSessionId:u,createContextEngineCallbacks:d,clearSessionPermissions:m}){if(e([]),t([]),yC(),n(null),r(!1),s(""),l.current){const e=l.current.getSessionManager();e&&await e.deleteShareInfo(),l.current=null;const t=crypto.randomUUID();u(t),m();const{ContextEngine:n}=await Promise.resolve().then(()=>(SC(),fC));l.current=new n(d(t),t)}o(e=>e+1),i(null),a(0)}async function handleInitCommand({setFeed:e}){try{const t=process.cwd(),n=`Created AGENTS.md at ${await initProjectMemory(t)}. You can now edit it with /memory or open it in your editor.`;e(e=>[...e,zE(n)])}catch(t){const n=`Error: Failed to initialize AGENTS.md: ${t instanceof Error?t.message:"Unknown error"}`;e(e=>[...e,zE(n)])}}async function handleFeedbackCommand({setFeed:e},t){const n=buildGitHubIssueUrl(t);try{await me(n,{wait:!1,background:!0}),e(e=>[...e,zE(`Opened ${createOSC8Link(n,"GitHub issue")} in your browser`)])}catch{const{createSystemEntry:t,createErrorEntry:r}=await Promise.resolve().then(()=>(dv(),uv));e(e=>[...e,r("Failed to open browser"),t(createOSC8Link(n,"Open GitHub issue manually"))])}}function handleLearnCommand({setAutoLearnTaste:e,setShowTasteOnboarding:t,setTasteOnboardingEntryId:n,setFeed:r}){e(!0),t(!0);const s=KE();n(s.id),r(e=>[...e,s])}async function handleCommand(e,t){if(e.startsWith("/resume:")){const n=e.substring(8);return await handleSelectSession({selectedSessionId:n,sessionLoadIdRef:t.sessionLoadIdRef,contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:t.setSessionId,setShowSessionSelector:t.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setPermissionMode:t.setPermissionMode,setStaticKey:t.setStaticKey,setShareInfo:t.setShareInfo,createContextEngineCallbacks:t.createContextEngineCallbacks}),{status:"handled"}}const n=parseCommandInput({input:e});if(!n)return{status:"unknown"};const{commandName:r,rawArguments:s,positionalArgs:o}=n;if(gT.has(r)&&s.trim().length>0)return{status:"unknown"};if("/exit"===r)return t.setShouldExit(!0),{status:"handled"};if("/clear"===r)return await handleClearCommand(t),{status:"handled"};if("/help"===r)return await handleHelpCommand(t),{status:"handled"};if("/share"===r)return await handleShareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setShowShareNotification:t.setShowShareNotification,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/unshare"===r)return await handleUnshareCommand({sessionId:t.sessionId,shareInfo:t.shareInfo,setShareInfo:t.setShareInfo,setStatus:t.setStatus,setUnshareNotificationMessage:t.setUnshareNotificationMessage,contextEngineRef:t.contextEngineRef}),{status:"handled"};if("/taste"===r)return t.setShowTasteConfig(!0),{status:"handled"};if("/learn-taste"===r)return handleLearnCommand(t),{status:"handled"};if("/skills"===r)return t.setShowSkillsConfig(!0),{status:"handled"};if("/provider"===r)return isInternalTeamFlagEnforced()?(t.setShowProviderSelector(!0),{status:"handled"}):(t.setStatus("Provider selection not available"),{status:"handled"});if("/model"===r)return t.setShowModelSelector(!0),{status:"handled"};if("/memory"===r)return t.setShowMemorySelector(!0),{status:"handled"};if("/resume"===r)return t.setShowSessionSelector(!0),{status:"handled"};if("/init"===r)return await handleInitCommand(t),{status:"handled"};if("/agents"===r)return t.setShowAgentsConfig(!0),{status:"handled"};if("/mcp"===r)return t.setShowMcpManager(!0),{status:"handled"};if("/compact"===r)return await handleCompactCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setStatus:t.setStatus,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setContextUsage:t.setContextUsage,setStaticKey:t.setStaticKey}),{status:"handled"};if("/compact-mode"===r)return t.setShowCompactModeSelector(!0),{status:"handled"};if("/context"===r)return t.setShowContextView(!0),{status:"handled"};if("/rewind"===r)return handleRewindCommand({contextEngineRef:t.contextEngineRef,setFeed:t.setFeed,setShowRewindSelector:t.setShowRewindSelector}),{status:"handled"};if("/login"===r)return await handleLoginCommand({setFeed:t.setFeed,setShowLoginOverlay:t.setShowLoginOverlay}),{status:"handled"};if("/logout"===r)return await handleLogoutCommand({setFeed:t.setFeed,contextEngineRef:t.contextEngineRef,setRetryAttempt:t.setRetryAttempt,setIsCmdCodeBusy:t.setIsCmdCodeBusy}),{status:"handled"};if("/feedback"===r)return await handleFeedbackCommand(t),{status:"handled"};if("/terminal-setup"===r)return await handleTerminalSetupCommand(t),{status:"handled"};if("/ide"===r)return await handleIDESetupCommand(t),{status:"handled"};if("/add-dir"===r)return t.setShowAddDirModal(!0),{status:"handled"};if("/rename"===r)return await handleRenameCommand({name:s.trim(),contextEngineRef:t.contextEngineRef,setFeed:t.setFeed}),t.setInput(""),{status:"handled"};if("/usage"===r)return t.setShowUsageOverlay(!0),{status:"handled"};if("/review"===r){const e=s.trim(),{handleSubmit:n}=await Promise.resolve().then(()=>(ak(),ok));let r=e,o=!1;if(!e){const e=await Gk();r=e?String(e.number):"",o=!!e}return await n({input:buildReviewPrompt({prNumber:r,autoDetected:o}),role:"user",displayMessage:r?`/review ${r}`:"/review",isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}if("/pr-comments"===r)return await handleSubmit({input:"Fetch and display all comments from the current GitHub pull request.\n\n Run these commands in order:\n\n 1. `gh pr view --json number,headRepository` — if this fails, reply \"No comments found.\" and stop.\n 2. `gh api --paginate '/repos/{owner}/{repo}/issues/NUMBER/comments' --jq '.[] | {body,\n user: .user.login, id, created_at}' > /tmp/pr-NUMBER-issue-comments.json`\n 3. `gh api --paginate '/repos/{owner}/{repo}/pulls/NUMBER/comments' --jq '.[] | {body,\n diff_hunk: (.diff_hunk | split(\"\n\") | .[-5:] | join(\"\n\")), path, line, user: .user.login,\n in_reply_to_id, id, created_at}' > /tmp/pr-NUMBER-review-comments.json`\n\n If both return empty, reply \"No comments found.\"\n\n `{owner}` and `{repo}` are gh template variables — write them literally, never substitute. Always\n use `--jq` (not piped `| jq`).\n\n Read the temp JSON files to build output comments directly in markdown using the format:\n\n ## PR Comments\n\n - @author (date):\n > body\n\n ## Review Comments\n\n - @author path#line:\n ```diff (replace ```suggestion code blocks with ```diff to avoid rendering errors)\n [diff_hunk]\n ```\n > body [replies indented by in_reply_to_id]\n\n Number the comments in the order they were created (created_at).\n No explanatory text, no horizontal rules. No extra space in the end.",role:"user",displayMessage:"/pr-comments",isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),lastResponseHasComments(t.contextEngineRef.current?.getMessages()??[])&&t.setInput("Fix all review comments"),{status:"handled"};if("/status"===r)return t.setShowStatusView(!0),{status:"handled"};const i=getCustomCommandContent(r);if(i){const n=processCommandTemplate({template:i,rawArguments:s,positionalArgs:o}),{handleSubmit:r}=await Promise.resolve().then(()=>(ak(),ok));return await r({input:n.content,role:"user",displayMessage:e,isAutomated:!0,feed:t.feed,setFeed:t.setFeed,isCmdCodeBusy:t.isCmdCodeBusy,setIsCmdCodeBusy:t.setIsCmdCodeBusy,setQueuedMessages:t.setQueuedMessages,setStatus:t.setStatus,setInteractionTokens:t.setInteractionTokens,updateStatus:t.updateStatus,setUpdateStatus:t.setUpdateStatus,billingLink:t.billingLink,setBillingLink:t.setBillingLink,contextEngineRef:t.contextEngineRef,isSubmittingRef:t.isSubmittingRef,setInput:t.setInput,setStaticKey:t.setStaticKey,executeBash:t.executeBash}),{status:"handled"}}return{status:"unknown"}}function useCommandCtx({feedState:e,sessionState:t,statusState:n,uiOverlays:r,onboarding:s,exitState:o,permissionState:i,contextEngineRef:a,isSubmittingRef:l,executeBash:u,createContextEngineCallbacks:d,setInput:m}){const g=X(()=>({feed:e.feed,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setQueuedMessages:e.setQueuedMessages,setStatus:n.setStatus,setInteractionTokens:n.setInteractionTokens,setContextUsage:n.setContextUsage,setStaticKey:r.setStaticKey,updateStatus:n.updateStatus,setUpdateStatus:n.setUpdateStatus,billingLink:n.billingLink,setBillingLink:n.setBillingLink,shareInfo:n.shareInfo,setShareInfo:n.setShareInfo,setShowShareNotification:n.setShowShareNotification,setUnshareNotificationMessage:n.setUnshareNotificationMessage,setRetryAttempt:n.setRetryAttempt,setShowTasteConfig:r.setShowTasteConfig,setShowSkillsConfig:r.setShowSkillsConfig,setShowProviderSelector:r.setShowProviderSelector,setShowModelSelector:r.setShowModelSelector,setShowMemorySelector:r.setShowMemorySelector,setShowAgentsConfig:r.setShowAgentsConfig,setShowMcpManager:r.setShowMcpManager,setShowRewindSelector:r.setShowRewindSelector,setShowCompactModeSelector:r.setShowCompactModeSelector,setShowContextView:r.setShowContextView,setShowAddDirModal:r.setShowAddDirModal,setShowLoginOverlay:r.setShowLoginOverlay,setShowStatusView:r.setShowStatusView,setShowUsageOverlay:r.setShowUsageOverlay,setShowTasteOnboarding:s.setShowTasteOnboarding,setAutoLearnTaste:s.setAutoLearnTaste,setTasteOnboardingEntryId:s.setTasteOnboardingEntryId,sessionId:t.sessionId,setSessionId:t.setSessionId,sessionLoadIdRef:t.sessionLoadIdRef,sessionLoaded:t.sessionLoaded,setSessionLoaded:t.setSessionLoaded,setShowSessionSelector:r.setShowSessionSelector,setPermissionMode:i.setPermissionMode,contextEngineRef:a,clearSessionPermissions:i.clearSessionPermissions,createContextEngineCallbacks:d,setShouldExit:o.setShouldExit,setInput:m,isSubmittingRef:l,isCmdCodeBusy:e.isCmdCodeBusy,setIsCmdCodeBusy:e.setIsCmdCodeBusy,executeBash:u}),[e,t,n,r,s,o,i,a,l,u,d,m]),h=Y(g);return h.current=g,{commandCtx:g,onCommand:Z(e=>handleCommand(e,h.current),[])}}async function handleProviderSelect({provider:e,setCurrentProvider:t,setShowProviderSelector:n,setAuthComponentInfo:r,setStatus:s,setShowProviderNotification:o,providerNotificationTimer:i}){try{const a=getProviderConfig(e);if(a?.requiresAuth&&a.checkAuth&&!await a.checkAuth()&&a.authComponent)return void r({provider:e,Component:a.authComponent});await updateUserConfig({provider:e}),t(e),n(!1),s(`Provider set to ${getProviderDisplayName(e)}`),i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},5e3)}catch(e){console.error("Failed to set provider:",e),s("Failed to set provider"),n(!1)}}function handleProviderCancel({setShowProviderSelector:e}){e(!1)}function handleAuthSuccess({authComponentInfo:e,setAuthComponentInfo:t,setShowProviderSelector:n,setCurrentProvider:r,setStatus:s,setShowProviderNotification:o,providerNotificationTimer:i}){e&&(t(null),n(!1),r(e.provider),s(`${getProviderDisplayName(e.provider)} authentication successful`),i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},5e3))}function handleAuthCancel({setAuthComponentInfo:e}){e(null)}function getModelDisplayName(e){const t=Object.values(Dt).find(t=>t.id===e);return t?t.name:e}async function handleModelSelect({modelId:e,setCurrentModel:t,setShowModelSelector:n,setStatus:r,setStaticKey:s,modelNotificationTimer:o,setShowModelNotification:i}){try{await setSelectedModel({model:e}),t(e),n(!1),yC(),s(e=>e+1),r(`Model set to ${getModelDisplayName(e)}`),o.current&&clearTimeout(o.current),i(!0),o.current=setTimeout(()=>{i(!1),o.current=null},5e3)}catch(e){console.error("Failed to set model:",e),r("Failed to set model"),n(!1)}}function handleModelCancel({setShowModelSelector:e}){e(!1)}__name(ensureExtensionInstalled,"ensureExtensionInstalled"),__name(formatSetupResult,"formatSetupResult"),__name(runIDESetup,"runIDESetup"),ak(),__name(handleHelpCommand,"handleHelpCommand"),__name(handleTerminalSetupCommand,"handleTerminalSetupCommand"),__name(handleIDESetupCommand,"handleIDESetupCommand"),__name(handleClearCommand,"handleClearCommand"),__name(handleInitCommand,"handleInitCommand"),__name(handleFeedbackCommand,"handleFeedbackCommand"),__name(handleLearnCommand,"handleLearnCommand"),__name(handleCommand,"handleCommand"),__name(useCommandCtx,"useCommandCtx"),Ht(),Ht(),Nr(),xr(),__name(handleProviderSelect,"handleProviderSelect"),__name(handleProviderCancel,"handleProviderCancel"),__name(handleAuthSuccess,"handleAuthSuccess"),__name(handleAuthCancel,"handleAuthCancel"),Ht(),Kt(),xr(),bC(),__name(getModelDisplayName,"getModelDisplayName"),__name(handleModelSelect,"handleModelSelect"),__name(handleModelCancel,"handleModelCancel"),Ht(),xr();var OT={default:"Compact Normal",fast:"Compact Fast"};async function handleCompactModeSelect({mode:e,setShowCompactModeSelector:t,setStatus:n}){try{await setCompactMode({mode:e}),t(!1),n(`Compact mode set to: ${OT[e]}`)}catch{n("Failed to set compact mode"),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var FT=__name(e=>{},"noopBool");function useMainActionCallbacks({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l}){const u=Y({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l});return u.current={feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a,setInput:l},{onSelectSession:Z(e=>{const{feedState:t,sessionState:n,statusState:r,uiOverlays:s,permissionState:o,contextEngineRef:i,createContextEngineCallbacks:a}=u.current;handleSelectSession({selectedSessionId:e,sessionLoadIdRef:n.sessionLoadIdRef,contextEngineRef:i,setFeed:t.setFeed,setLiveEntries:t.setLiveEntries,setSessionId:n.setSessionId,setShowSessionSelector:s.setShowSessionSelector,setSessionLoaded:n.setSessionLoaded,setPermissionMode:o.setPermissionMode,setStaticKey:s.setStaticKey,setShareInfo:r.setShareInfo,createContextEngineCallbacks:a})},[]),onNewSession:Z(()=>{const{feedState:e,sessionState:t,uiOverlays:n,permissionState:r,contextEngineRef:s}=u.current;handleNewSession({contextEngineRef:s,setFeed:e.setFeed,setLiveEntries:e.setLiveEntries,setSessionId:t.setSessionId,setShowSessionSelector:n.setShowSessionSelector,setSessionLoaded:t.setSessionLoaded,setPermissionMode:r.setPermissionMode})},[]),onRewindSelect:Z(({messageId:e,mode:t})=>{const{feedState:n,statusState:r,uiOverlays:s,contextEngineRef:o,setInput:i}=u.current;handleRewindSelect({messageId:e,mode:t,contextEngineRef:o,setFeed:n.setFeed,setStatus:r.setStatus,setShowRewindSelector:s.setShowRewindSelector,setStaticKey:s.setStaticKey,setInput:i})},[]),onRewindCancel:Z(()=>{handleRewindCancel({setShowRewindSelector:u.current.uiOverlays.setShowRewindSelector})},[]),onLoginComplete:Z((e,t)=>{const{feedState:n,statusState:r,uiOverlays:s,contextEngineRef:o}=u.current;handleLoginComplete({success:e,message:t,setShowLoginOverlay:s.setShowLoginOverlay,setFeed:n.setFeed,setStatus:r.setStatus,contextEngineRef:o})},[]),onLoginCancel:Z(()=>{const{feedState:e,statusState:t,uiOverlays:n}=u.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),handleProviderSelect:Z(e=>{const{authState:t,statusState:n,uiOverlays:r}=u.current;handleProviderSelect({provider:e,setCurrentProvider:t.setCurrentProvider,setShowProviderSelector:r.setShowProviderSelector,setAuthComponentInfo:t.setAuthComponentInfo,setStatus:n.setStatus,setShowProviderNotification:t.setShowProviderNotification,providerNotificationTimer:t.providerNotificationTimer})},[]),handleProviderCancel:Z(()=>{handleProviderCancel({setShowProviderSelector:u.current.uiOverlays.setShowProviderSelector})},[]),handleModelSelect:Z(e=>{const{authState:t,statusState:n,uiOverlays:r}=u.current;handleModelSelect({modelId:e,setCurrentModel:t.setCurrentModel,setShowModelSelector:r.setShowModelSelector,setStatus:n.setStatus,setStaticKey:r.setStaticKey,modelNotificationTimer:t.modelNotificationTimer,setShowModelNotification:FT})},[]),handleModelCancel:Z(()=>{handleModelCancel({setShowModelSelector:u.current.uiOverlays.setShowModelSelector})},[]),handleCompactModeSelect:Z(e=>{const{statusState:t,uiOverlays:n}=u.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),handleCompactModeCancel:Z(()=>{handleCompactModeCancel({setShowCompactModeSelector:u.current.uiOverlays.setShowCompactModeSelector})},[]),handleAuthSuccess:Z(()=>{const{authState:e,statusState:t,uiOverlays:n}=u.current;handleAuthSuccess({authComponentInfo:e.authComponentInfo,setAuthComponentInfo:e.setAuthComponentInfo,setShowProviderSelector:n.setShowProviderSelector,setCurrentProvider:e.setCurrentProvider,setStatus:t.setStatus,setShowProviderNotification:e.setShowProviderNotification,providerNotificationTimer:e.providerNotificationTimer})},[]),handleAuthCancel:Z(()=>{handleAuthCancel({setAuthComponentInfo:u.current.authState.setAuthComponentInfo})},[])}}__name(useMainActionCallbacks,"useMainActionCallbacks"),Ht(),Xy(),Wy(),Ht(),Kt(),rk(),Ds(),Wy(),Xy();var qT=[{name:"Individual Pro",type:"individual",price:15,monthlyCredits:30},{name:"Individual Max",type:"individual",price:200,monthlyCredits:400},{name:"Teams Pro",type:"team",price:40,monthlyCredits:40},{name:"Teams Max",type:"team",price:400,monthlyCredits:400}];function formatCredits(e){return`$${e.toFixed(2)}`}function formatPercent(e){return`${e.toFixed(1)}%`}__name(formatCredits,"formatCredits"),__name(formatPercent,"formatPercent");var jT=[{keywords:["team","max"],tierIndex:3},{keywords:["team"],tierIndex:2},{keywords:["max"],tierIndex:1}];function getPlanInfo({planId:e}){if(!e)return null;if(void 0!==Nt[e]){const t=e.startsWith("team"),n=qT.find(n=>{if(n.type!==(t?"team":"individual"))return!1;const r=n.name.toLowerCase().replace(/\s+/g,"-");return e.startsWith(r)});if(n)return n}const t=qT.find(t=>e.toLowerCase().includes(t.name.toLowerCase().replace(/\s+/g,"-")));if(t)return t;const n=e.toLowerCase();for(const{keywords:e,tierIndex:t}of jT)if(e.every(e=>n.includes(e)))return qT[t]??null;return null}function getUsagePercent({used:e,total:t}){return t<=0?0:Math.min(e/t*100,100)}function getDaysRemaining(e){const t=new Date(e);return Number.isNaN(t.getTime())?null:Math.max(0,Math.ceil((t.getTime()-Date.now())/864e5))}function formatDateCompact(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return"N/A";const n=new Date,r={month:"short",day:"numeric",timeZone:"UTC"};return t.getUTCFullYear()!==n.getFullYear()&&(r.year="numeric"),t.toLocaleDateString("en-US",r)}async function safeFetch({request:e,endpoint:t}){try{return{data:await e.get({endpoint:t}),error:null}}catch(e){return e instanceof Ts?{data:null,error:"Network error: unable to reach API"}:e instanceof xs?{data:null,error:"Session expired"}:{data:null,error:`${t}: ${e instanceof Error?e.message:"Unknown error"}`}}}function buildEndpoint({endpoint:e,orgId:t}){return t?`${e}?orgId=${t}`:e}async function fetchCredits({request:e,orgId:t}){return safeFetch({request:e,endpoint:buildEndpoint({endpoint:"/alpha/billing/credits",orgId:t})})}async function fetchSubscription({request:e,orgId:t}){return safeFetch({request:e,endpoint:buildEndpoint({endpoint:"/alpha/billing/subscriptions",orgId:t})})}async function fetchWhoami({request:e}){return safeFetch({request:e,endpoint:"/alpha/whoami"})}async function fetchUsageSummary({request:e,orgId:t,since:n}){let r=buildEndpoint({endpoint:"/alpha/usage/summary",orgId:t});if(n){const e=r.includes("?")?"&":"?";r=`${r}${e}since=${encodeURIComponent(n)}`}return safeFetch({request:e,endpoint:r})}async function fetchUsageData(){if(!await getAuthKey())return{whoami:null,credits:null,subscription:null,summary:null,errors:["Not authenticated"]};const e=getApiBaseUrl(),t=new xy({baseUrl:e}),n=await fetchWhoami({request:t}),r=n.data?.org?.id??null,[s,o]=await Promise.all([fetchCredits({request:t,orgId:r}),fetchSubscription({request:t,orgId:r})]),i=o.data?.data?.currentPeriodStart??null,a=await fetchUsageSummary({request:t,orgId:r,since:i}),l=[n.error,s.error,o.error,a.error].filter(e=>null!==e);return{whoami:n.data,credits:s.data,subscription:o.data,summary:a.data,errors:l}}__name(getPlanInfo,"getPlanInfo"),__name(getUsagePercent,"getUsagePercent"),__name(getDaysRemaining,"getDaysRemaining"),__name(formatDateCompact,"formatDateCompact"),__name(safeFetch,"safeFetch"),__name(buildEndpoint,"buildEndpoint"),__name(fetchCredits,"fetchCredits"),__name(fetchSubscription,"fetchSubscription"),__name(fetchWhoami,"fetchWhoami"),__name(fetchUsageSummary,"fetchUsageSummary"),__name(fetchUsageData,"fetchUsageData");var BT=["○","◔","◐","◕","●"];function getCircleGauge(e){return e<=0?BT[0]:e<25?BT[1]:e<50?BT[2]:e<75?BT[3]:BT[4]}function findNewThreshold({depletionPct:e,warnedThresholds:t}){const n=[...Rt].sort((e,t)=>t-e);for(const r of n)if(e>=r&&!t.has(r))return r;return null}function getDepletionPct({planId:e,monthlyCredits:t}){const n=Nt[e];if(!n||n<=0)return null;const r=n-t;return Math.min(100,Math.max(0,r/n*100))}function buildWarningMessage({depletionPct:e,remainingCredits:t,billingUrl:n}){return`${Math.round(e)}% of plan credits used (${Number.isInteger(t)?String(t):t.toFixed(1)} remaining). Upgrade: ${n}`}function useCreditWarning({interactionTokens:e}){const[t,n]=K(null),r=Y(new Set),s=Y(null),o=Y(!1),i=Y(null),a=Y("https://commandcode.ai/settings/billing"),l=Y(null),u=Y(null),d=Z(async()=>{try{const e=getApiBaseUrl(),t=new xy({baseUrl:e});if(!o.current){o.current=!0;try{const e=await getAuthenticatedEntity();i.current=e.org?.id??null,a.current=e.org?`https://commandcode.ai/${e.org.login}/settings/billing`:"https://commandcode.ai/settings/billing";const n=await t.get({endpoint:buildEndpoint({endpoint:kt.ALPHA.BILLING.SUBSCRIPTIONS,orgId:i.current})});s.current=n}catch{return}}const l=s.current;if(!l?.success||!l.data)return;const{planId:d,status:m}=l.data;if("active"!==m&&"past_due"!==m)return;if(!Nt[d])return;let g;try{g=await t.get({endpoint:buildEndpoint({endpoint:kt.ALPHA.BILLING.CREDITS,orgId:i.current})})}catch{return}const{monthlyCredits:h}=g.credits,f=getDepletionPct({planId:d,monthlyCredits:h});if(null===f)return;const y=findNewThreshold({depletionPct:f,warnedThresholds:r.current});if(null===y)return;for(const e of Rt)e<=y&&r.current.add(e);const w=buildWarningMessage({depletionPct:f,remainingCredits:d.startsWith("individual-")?h/2:h,billingUrl:a.current});n(w),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{n(null),u.current=null},3e4)}catch{}},[]);return J(()=>{if(0!==e)return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{d(),l.current=null},2e3),()=>{l.current&&clearTimeout(l.current)}},[e,d]),J(()=>()=>{u.current&&clearTimeout(u.current),l.current&&clearTimeout(l.current)},[]),{creditWarning:t}}__name(getCircleGauge,"getCircleGauge"),sk(),Kt(),__name(findNewThreshold,"findNewThreshold"),__name(getDepletionPct,"getDepletionPct"),__name(buildWarningMessage,"buildWarningMessage"),__name(useCreditWarning,"useCreditWarning"),Ht(),Ht(),Ht();var UT=__name(({staticKey:e})=>Q.createElement(ne,{items:[{staticKey:e}],key:e},()=>Q.createElement(te,{key:e},"\0")),"Responsive");Ht(),Kt(),dr();var zT=__name(({onTrust:e,onExit:t})=>{const{exit:n}=ie(),[r,s]=K(1),o=process.cwd().replace(process.env.HOME||"","~");return se((o,i)=>{i.upArrow||i.downArrow?s(1===r?2:1):i.return?1===r?e():(t(),n()):"1"===o?e():("2"===o||i.escape||i.ctrl&&"c"===o)&&(t(),n())}),Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.YELLOW,padding:1},Q.createElement(te,{color:jn.YELLOW,bold:!0},"Do you trust the files in this folder?"),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY},o)),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(te,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),Q.createElement(ee,{marginTop:1},Q.createElement(te,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{color:1===r?jn.CYAN:jn.GRAY},1===r?ke.pointer:" "," 1. Yes, proceed")),Q.createElement(ee,null,Q.createElement(te,{color:2===r?jn.CYAN:jn.GRAY},2===r?ke.pointer:" "," 2. No, exit"))))},"TrustPrompt"),WT=V(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(zT,{onTrust:t,onExit:n}))},"TrustView"));Ht(),Ht(),vv(),hs(),dr();var GT=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=ie(),[r,s]=K([]),[o,i]=K(0),[a,l]=K(!0),[u,d]=K(0),m=30;J(()=>{g()},[]);const g=__name(async()=>{l(!0);const e=await hv.listSessions();s(e),l(!1)},"loadSessions");if(se((t,s)=>{s.upArrow?i(e=>{const t=Math.max(0,e-1);return t<u&&d(t),t}):s.downArrow?i(e=>{const t=Math.min(r.length-1,e+1);return t>=u+m&&d(t-m+1),t}):s.return?r.length>0&&e(r[o].id):(s.escape||s.ctrl&&"c"===t)&&n()}),a)return Q.createElement(ee,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(te,{color:jn.GRAY},"Loading sessions..."));const h=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),s=Math.floor(n/36e5),o=Math.floor(n/864e5),i=Math.floor(n/6048e5);return r<1?"just now":r<60?`${r} min ago`:s<24?`${s} hour${s>1?"s":""} ago`:o<7?`${o} day${o>1?"s":""} ago`:1===i?"1 week ago":`${i} weeks ago`},"formatRelativeTime"),f=__name(e=>truncateString({text:e,maxChars:ss}),"truncateMessage");if(0===r.length)return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.GRAY},"No sessions available"));const y=r.slice(u,u+m),w=u;return Q.createElement(ee,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM},"Showing ",u+1,"-",Math.min(u+m,r.length)," ","of ",r.length," sessions",u>0&&" (↑ for more)",u+m<r.length&&" (↓ for more)")),Q.createElement(ee,{columnGap:2,marginBottom:1},Q.createElement(ee,{width:7},Q.createElement(te,{color:jn.GRAY}," ")),Q.createElement(ee,{width:13},Q.createElement(te,{color:jn.GRAY},"Modified")),Q.createElement(ee,{width:11},Q.createElement(te,{color:jn.GRAY},"# Messages")),Q.createElement(ee,{width:20},Q.createElement(te,{color:jn.GRAY},"Git Branch")),Q.createElement(ee,null,Q.createElement(te,{color:jn.GRAY},"Summary"))),Q.createElement(ee,{columnGap:2},Q.createElement(ee,{flexDirection:"column",width:7},y.map((e,t)=>{const n=w+t;return Q.createElement(te,{key:`sel-${n}`,color:o===n?jn.CYAN:jn.GRAY},o===n?`${ke.pointer} ${n+1}.`:` ${n+1}.`)})),Q.createElement(ee,{flexDirection:"column",width:13},y.map((e,t)=>{const n=w+t;return Q.createElement(te,{key:`mod-${e.id}`,color:o===n?jn.WHITE:jn.GRAY},h(e.lastModified))})),Q.createElement(ee,{flexDirection:"column",width:11},y.map((e,t)=>{const n=w+t;return Q.createElement(te,{key:`msg-${e.id}`,color:o===n?jn.WHITE:jn.GRAY},e.messageCount)})),Q.createElement(ee,{flexDirection:"column",width:20},y.map((e,t)=>{const n=w+t;return Q.createElement(te,{key:`branch-${e.id}`,color:o===n?jn.WHITE:jn.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),Q.createElement(ee,{flexDirection:"column"},y.map((e,t)=>{const n=w+t;return Q.createElement(te,{key:`summary-${e.id}`,color:o===n?jn.WHITE:jn.GRAY},f(e.firstMessage))}))))},"SessionTable"),HT=V(__name(function SessionView2({onSelectSession:e,onNewSession:t}){return Q.createElement(GT,{onSelectSession:e,onNewSession:t})},"SessionView"));Ht(),Ht(),gr(),dr();var QT=__name((e,t)=>{if(!e.startsWith("option_"))return null;const n=e.slice(7),r=parseInt(n,10);return Number.isNaN(r)||r<0||r>t?null:r},"parseOptionIndex"),VT=__name(({questions:e,currentIndex:t,answeredQuestions:n,isReviewPage:r,hideReview:s=!1})=>{if(s&&1===e.length)return null;const o=[];if(e.forEach((s,i)=>{const a=i===t&&!r,l=n.has(i);let u,d;a?(u=ke.bullet,d=jn.CYAN):l?(u=ke.tick,d=jn.GREEN):(u=ke.circle,d=jn.GRAY),o.push(Q.createElement(te,{key:i},Q.createElement(te,{color:d},u),Q.createElement(te,{color:a?jn.CYAN:void 0}," ",s.header),i<e.length-1?Q.createElement(te,{color:jn.DIM}," | "):null))}),!s){const e=r;o.push(Q.createElement(te,{key:"review"},Q.createElement(te,{color:jn.DIM}," | "),Q.createElement(te,{color:e?jn.CYAN:jn.GRAY},e?ke.bullet:ke.circle),Q.createElement(te,{color:e?jn.CYAN:void 0,bold:e}," ","Review")))}return Q.createElement(ee,null,o)},"TabIndicator"),KT=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,s]=K(0),[o,i]=K(new Map),a=Y(new Map),[l,u]=K(""),[d,m]=K(new Set),[g,h]=K(null),[f,y]=K(!1),[w,S]=K(!1),[E,v]=K(!1),[C,k]=K(null),[T,_]=K(!1),x=e[r],P=x?.multiSelect??!1,A=o.get(r),I=x?[...x.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],N=I.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),R=new Map(N.map((e,t)=>[e.label,I[t]])),$=__name(e=>{"submit"===e.value?q():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),M=__name(()=>{if(!A||0===A.length)return 0;const e=A[0],t=x.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),L=__name(e=>{if(!f)if(P){const t=QT(e.value,x.options.length-1);if(null===t)return;const n=x.options[t]?.label||"";m(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=QT(e.value,x.options.length-1);if(null===t)return;y(!0);const n=x.options[t]?.label||"";F([n])}},"handleSelect"),D=__name(()=>{if(f)return;y(!0);const e=Array.from(d);F(e)},"handleMultiSelectDone"),O=__name(()=>{if(!f&&l.trim())if(P){const e=new Set(x.options.map(e=>e.label));m(t=>{const n=new Set;return t.forEach(t=>{e.has(t)&&n.add(t)}),n.add(l.trim()),n})}else y(!0),F([l.trim()])},"handleOtherSubmit"),F=__name(t=>{a.current.set(r,t);const o=new Map(a.current);i(o);const l=__name(t=>{const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n?.options.some(t=>t.label===e);u(t&&e?e:"")}},"restoreStateForQuestion");if(r<e.length-1){const e=r+1;l(e),s(e),y(!1),v(!1),k(null),_(!1)}else if(e.every((e,t)=>o.has(t))){if(n&&1===e.length)return void q();m(new Set),u(""),S(!0),y(!1)}else{const t=e.findIndex((e,t)=>!o.has(t));-1!==t&&(l(t),s(t)),y(!1),v(!1),k(null),_(!1)}},"finishQuestion"),q=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:a.current.get(t)||[]}));t({answers:n})},"submitAnswers"),j=__name(t=>{S(!1),s(t),_(!1),v(!1),k(null);const n=e[t],r=a.current.get(t);if(n?.multiSelect&&r){m(new Set(r));const e=r.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==r?.length)u("");else{const e=r[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}},"editQuestion"),B=__name(t=>{if(t<0||t>=e.length)return;P&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),y(!1),v(!1),k(null),_(!1);const n=e[t],o=a.current.get(t);if(n?.multiSelect&&o){m(new Set(o));const e=o.find(e=>!n.options.some(t=>t.label===e));u(e||"")}else if(m(new Set),n?.multiSelect||1!==o?.length)u("");else{const e=o[0],t=!n.options.some(t=>t.label===e);u(t&&e?e:"")}s(t)},"navigateToQuestion"),U=__name(()=>{if(!g||!P)return;if("done"===g.value)return;const e=QT(g.value,x.options.length-1);if(null===e)return;const t=x.options[e]?.label||"";m(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return se((t,s)=>{if(" "===t&&P&&!E&&U(),"d"!==t||!P||E||w||D(),!w&&!f){if(s.downArrow&&!E&&!T&&!n&&g&&N.length>0&&g.value===N[N.length-1]?.value&&v(!0),s.upArrow&&!E&&!T&&g&&N.length>0&&g.value===N[0]?.value&&(P?_(!0):n||(v(!0),k(N.length-1))),s.upArrow&&E){v(!1),k(N.length-1);const e=N[N.length-1];e&&h(e)}if(s.downArrow&&E)if(v(!1),P)_(!0);else{k(0);const e=N[0];e&&h(e)}if(s.upArrow&&T&&(_(!1),v(!0)),s.downArrow&&T){_(!1),k(0);const e=N[0];e&&h(e)}s.return&&T&&P&&D()}if(f||E||T||(w?s.leftArrow&&j(e.length-1):s.leftArrow&&r>0?B(r-1):s.rightArrow&&(r<e.length-1?B(r+1):(P&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),S(!0)))),s.escape&&!f)if(w)S(!1);else if(E){v(!1);const e=C??N.length-1;k(e);const t=N[e];t&&h(t)}else if(T){_(!1);const e=N[N.length-1];e&&h(e)}}),x||w?w?Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(VT,{questions:e,currentIndex:e.length,answeredQuestions:new Set(o.keys()),isReviewPage:!0})),e.map((e,t)=>Q.createElement(ee,{key:t,marginBottom:1,flexDirection:"column"},Q.createElement(te,{color:jn.DIM},t+1,". ",e.question),Q.createElement(te,{color:jn.GREEN}," ",o.get(t)?.join(", ")||"No answer"))),Q.createElement(tt,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:$,initialIndex:0,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.CYAN},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(te,{color:t?jn.CYAN:jn.WHITE},e)}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},ke.arrowLeft," to go back and edit"))):Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(VT,{questions:e,currentIndex:r,answeredQuestions:new Set(o.keys()),isReviewPage:!1,hideReview:n})),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{bold:!0},x.question)),E||T?Q.createElement(ee,{flexDirection:"column"},N.map((e,t)=>{const n=R.get(e.label),r=P&&n&&d.has(n.label),s=!P&&n&&A?.includes(n.label),o=r||s;return Q.createElement(ee,{key:t,flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,null," "),Q.createElement(te,{color:o?jn.GREEN:jn.WHITE}," ",t+1,"."," "),P&&(o?Q.createElement(te,{color:jn.GREEN},"[",ke.tick,"]"," "):Q.createElement(te,{color:jn.DIM},"[ ] ")),Q.createElement(te,{color:o?jn.GREEN:jn.WHITE},n?.label||""),!P&&o&&Q.createElement(te,{color:jn.GREEN}," ",ke.tick)),n?.description&&Q.createElement(ee,null,Q.createElement(te,null," "),Q.createElement(te,{color:jn.DIM},P?" ":" ",n.description)))})):Q.createElement(tt,{key:`${r}-${C??"default"}`,items:N,initialIndex:C??M(),onSelect:L,onHighlight:h,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.CYAN},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=R.get(e),r=P&&n&&d.has(n.label),s=!P&&n&&A?.includes(n.label),o=r||s,i=e.match(/^\s*(\d+)\.\s*(.*)$/),a=i?.[1]||"",l=i?.[2]||e;return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{color:t?jn.CYAN:o?jn.GREEN:jn.WHITE}," ",a,"."," "),P&&(o?Q.createElement(te,{color:jn.GREEN},"[",ke.tick,"]"," "):Q.createElement(te,{color:jn.DIM},"[ ] ")),Q.createElement(te,{color:t?jn.CYAN:o?jn.GREEN:jn.WHITE},l),!P&&o&&Q.createElement(te,{color:jn.GREEN}," ",ke.tick)),n?.description&&Q.createElement(te,{color:jn.DIM},P?" ":" ",n.description))}}),!n&&Q.createElement(ee,null,Q.createElement(te,{color:jn.CYAN},E?ke.pointer:" "),Q.createElement(te,{color:E?jn.CYAN:void 0}," ",N.length+1,"."," "),P&&(d.has(l.trim())?Q.createElement(te,{color:jn.GREEN},"[",ke.tick,"] "):Q.createElement(te,{color:jn.DIM},"[ ] ")),Q.createElement(TextInput,{value:l,onChange:e=>{const t=e.replace(/\r\n/g," ").replace(/[\r\n]/g," "),n=l.trim();u(t),P&&m(e=>{const r=new Set(e);return n&&r.has(n)&&r.delete(n),t.trim()&&r.add(t.trim()),r})},onSubmit:O,placeholder:"Type something...",focus:E,stripBracketedPaste:!0})),P&&Q.createElement(ee,null,Q.createElement(te,{color:jn.CYAN},T?ke.pointer:" "),Q.createElement(te,{color:T?jn.CYAN:void 0,bold:T}," ",r===e.length-1?"Submit":"Next")),e.length>1&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Enter to select | Arrow keys to navigate | Esc to cancel"))):null},"QuestionPrompt");function QuestionView({pendingQuestion:e,setPermissionMode:t,setPendingQuestion:n,setStatus:r,setStaticKey:s}){return Q.createElement(ee,{marginY:1},Q.createElement(KT,{questions:e.params.questions,hideCustomInput:e.params.hideCustomInput,onResponse:o=>{if(e.params.exitPlanMode){const e=o.answers[0]?.selectedOptions[0]||"";e.startsWith("Yes, auto-accept")?(t("auto-accept"),yC(),s(e=>e+1)):e.startsWith("Yes, exit")&&(t("standard"),yC(),s(e=>e+1))}if(e.params.enterPlanMode){const e=o.answers[0]?.selectedOptions[0];e?.startsWith("Yes")&&(t("plan"),yC(),s(e=>e+1))}e.resolve(o),n(null),r("Answers submitted")}}))}bC(),__name(QuestionView,"QuestionView"),Ht(),Ht(),Kt(),Vv(),Ht(),dr();var YT=/\[([^\]]+)\]/g;function BracketWrap({children:e,color:t,bold:n=!1}){return Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.DIMMEST,bold:n},"["),"string"==typeof e?Q.createElement(te,{color:t,bold:n},e):e,Q.createElement(te,{color:jn.DIMMEST,bold:n},"]"))}function BracketedText({text:e,color:t,bold:n=!1,wrap:r}){const s=X(()=>{const t=[];let n=0;for(const r of e.matchAll(YT)){const s=r.index??0;s>n&&t.push({type:"text",value:e.slice(n,s)}),t.push({type:"bracket",value:r[1]??""}),n=s+r[0].length}return n<e.length&&t.push({type:"text",value:e.slice(n)}),0===t.length&&t.push({type:"text",value:e}),t},[e]),o=X(()=>s.map((e,r)=>"bracket"===e.type?Q.createElement(BracketWrap,{key:`bracket-${r}`,color:t,bold:n},e.value):e.value),[s,t,n]);return Q.createElement(te,{color:t,bold:n,wrap:r},o)}__name(BracketWrap,"BracketWrap"),__name(BracketedText,"BracketedText"),dr(),Ht(),vw(),dv(),gn(),hs(),Rr(),dr(),Ht(),dr();var JT=class extends st{static{__name(this,"FixedTerminalRenderer")}text(e){if(e&&"object"==typeof e&&Array.isArray(e.tokens)&&e.tokens.length>0){try{const t=this.parser;if(t&&"function"==typeof t.parseInline)return t.parseInline(e.tokens)}catch{}return e.raw||e.text||String(e)}return super.text(e)}hr(){return"\n"+le.dim("───")+"\n"}blockquote(e){return"object"==typeof e&&(e=this.parser.parse(e.tokens)),this.o.blockquote(e.trim()).split("\n").map(e=>`│ ${e}`).join("\n")+"\n\n"}listDepth=0;list(e,t=!1,n=""){let r;this.listDepth++;try{r=super.list(e,t,n),r=r.replace(/\n[ \t]*(?:\u001b\[0m)+[ \t]*(?=\n)/g,""),1===this.listDepth&&(r=r.replace(/^ /gm,""))}finally{this.listDepth--}return r}},XT=new rt;XT.setOptions({renderer:new JT({strong:le.bold,em:le.italic,del:le.dim.strikethrough,codespan:le.hex(sr.CODE),code:le.hex(sr.CODE),heading:le.bold,firstHeading:le.bold.hex(sr.HEADING).underline,link:le.hex(jn.CYAN),href:le.hex(jn.CYAN).underline,blockquote:le.hex(jn.GRAY).italic,table:le.reset,tableOptions:{style:{head:[jn.CYAN],border:[jn.GRAY]}},hr:le.reset,paragraph:le.reset,html:le.hex(jn.GRAY),showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var ZT=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const s=X(()=>{if(!e)return"";const t=[],n=e.replace(ZT,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=XT.parse(n);if("string"!=typeof r)return e;return r.replace(/\{\{OSC8:(\d+)\}\}/g,(e,n)=>t[parseInt(n,10)]||"").replace(/^(\s*)\* /gm,"$1- ").replace(/\n{3,}/g,"\n\n").trim()}catch{return e}},[e]);return Q.createElement(te,{color:t,dimColor:n,wrap:r},s)}function buildTreeConnectors(e,t=!1){return e.split("\n").map((e,n,r)=>t||n!==r.length-1?"│":Ok).join("\n")}__name(Markdown,"Markdown"),Ht(),__name(buildTreeConnectors,"buildTreeConnectors");var e_=" │ ";function computeSimilarity({strA:e,strB:t}){const n=e.trim(),r=t.trim();if(n===r)return 1;if(!n||!r)return 0;const s=Object.create(null);for(let e=0;e<n.length;e++){const t=n[e];s[t]=(s[t]??0)+1}let o=0;for(let e=0;e<r.length;e++){const t=r[e],n=s[t];n&&(o++,s[t]=n-1)}return 2*o/(n.length+r.length)}function buildSimilarityMatrix(e,t,n){const r=new Float64Array(e.length*n);for(let s=0;s<e.length;s++)for(let o=0;o<n;o++)r[s*n+o]=computeSimilarity({strA:e[s],strB:t[o]});return r}function collectSimilarityCandidates(e,t,n){const r=[];for(let s=0;s<t;s++)for(let t=0;t<n;t++){const o=e[s*n+t];o>=.3&&r.push({score:o,removedIdx:s,addedIdx:t})}return r}function buildLinePairs(e,t){const n=e.length,r=t.length,s=new Map;if(n*r>200){const e=Math.min(n,r);for(let t=0;t<e;t++)s.set(t,t);return s}const o=collectSimilarityCandidates(buildSimilarityMatrix(e,t,r),n,r);o.sort((e,t)=>t.score-e.score);const i=new Set,a=new Set;for(const{removedIdx:e,addedIdx:t}of o)i.has(e)||a.has(t)||(s.set(e,t),i.add(e),a.add(t));return s}function groupAdjacentChanges(e){const t=[];let n=0;for(;n<e.length;){const r=e[n];if(!r.added&&!r.removed){const e=r.value.split("\n");""===e.at(-1)&&e.pop(),t.push({type:"context",contextLines:e,removedLines:[],addedLines:[]}),n++;continue}const s=[],o=[];for(;n<e.length&&(e[n].added||e[n].removed);){const t=e[n].value.split("\n");""===t.at(-1)&&t.pop(),e[n].removed?(s.push(...t),n++):(o.push(...t),n++)}t.push({type:"change",contextLines:[],removedLines:s,addedLines:o})}return t}function renderWordSegments({wordChanges:e,type:t,dimDiff:n}){const r="removed"===t?Gn.REMOVED_HIGHLIGHT_BG:Gn.ADDED_HIGHLIGHT_BG,s=[];let o=0;for(const i of e){if("removed"===t&&i.added)continue;if("added"===t&&i.removed)continue;const e="removed"===t?i.removed:i.added,a=i.value.replace(/\s/g," "),l=`${t}-${o++}-${e?"highlighted":"unchanged"}`;e?s.push(Q.createElement(te,{key:l,backgroundColor:r,dimColor:n},a)):s.push(Q.createElement(te,{key:l,color:jn.WHITE,dimColor:n},a))}return s}function renderContextLine({line:e,lineNum:t,lineNumWidth:n,dimDiff:r,nodeKey:s}){return Q.createElement(ee,{key:s,width:"100%"},Q.createElement(te,{color:Gn.LINE_NUM,dimColor:r}," "+t.toString().padStart(n)),Q.createElement(te,{color:Gn.LINE_NUM,dimColor:r},e_),Q.createElement(te,{color:jn.WHITE,dimColor:r}," ",e.replace(/\s/g," ")))}function renderContextGroup({lines:e,leadCount:t,trailCount:n,lineNumWidth:r,dimDiff:s,counters:o}){const i=[];if(t+n>=e.length){for(const t of e)i.push(renderContextLine({line:t,lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;return i}for(let n=0;n<t;n++)i.push(renderContextLine({line:e[n],lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;const a=e.length-t-n;a>0&&(o.oldLineNum+=a,o.newLineNum+=a,i.push(Q.createElement(ee,{key:"sep-"+o.nodeKey++},Q.createElement(te,{color:Gn.LINE_NUM,dimColor:s}," ".repeat(r+1)),Q.createElement(te,{color:Gn.LINE_NUM,dimColor:s},e_),Q.createElement(te,{color:Gn.LINE_NUM,dimColor:s},`⋮ ${a} line${1===a?"":"s"}`))));for(let t=e.length-n;t<e.length;t++)i.push(renderContextLine({line:e[t],lineNum:o.newLineNum,lineNumWidth:r,dimDiff:s,nodeKey:"ctx-"+o.nodeKey++})),o.oldLineNum++,o.newLineNum++;return i}function generateDiff({oldValue:e,newValue:t,filePath:n,permissionDenied:r=!1,showMetadata:s=!1,marginLeft:o=2,startLine:i=1,dimDiff:a=!1,maxLines:l}){const u=nt.diffLines(e,t);let d=0,m=0;for(const e of u)e.added&&(d+=e.count||1),e.removed&&(m+=e.count||1);const g=u.reduce((e,t)=>e+(t.added?0:t.count||1),0),h=u.reduce((e,t)=>e+(t.removed?0:t.count||1),0),f=Math.max(3,(i+g-1).toString().length,(i+h-1).toString().length),y=groupAdjacentChanges(u),w=[],S={oldLineNum:i,newLineNum:i,nodeKey:0};for(let e=0;e<y.length;e++){const t=y[e];if("context"===t.type){const n=t.contextLines,r=e>0&&"change"===y[e-1].type,s=e<y.length-1&&"change"===y[e+1].type;if(!r&&!s){S.oldLineNum+=n.length,S.newLineNum+=n.length;continue}const o=r?Math.min(3,n.length):0,i=s?Math.min(3,Math.max(0,n.length-o)):0;w.push(...renderContextGroup({lines:n,leadCount:o,trailCount:i,lineNumWidth:f,dimDiff:a,counters:S}));continue}const{removedLines:n,addedLines:r}=t,s=buildLinePairs(n,r),o=new Map,i=new Map;for(const[e,t]of s){const s=nt.diffWordsWithSpace(n[e],r[t]);o.set(e,s),i.set(t,s)}for(let e=0;e<n.length;e++){const t=o.get(e);w.push(Q.createElement(ee,{key:"rm-"+S.nodeKey++,width:"100%",backgroundColor:Gn.REMOVED_BG},Q.createElement(te,{color:Gn.REMOVED_TEXT,dimColor:a}," "+S.oldLineNum.toString().padStart(f)),Q.createElement(te,{color:Gn.LINE_NUM,dimColor:a},e_),Q.createElement(te,{color:Gn.REMOVED_TEXT,dimColor:a},"- "),t?renderWordSegments({wordChanges:t,type:"removed",dimDiff:a}):Q.createElement(te,{color:Gn.REMOVED_TEXT,dimColor:a},n[e].replace(/\s/g," ")))),S.oldLineNum++}for(let e=0;e<r.length;e++){const t=i.get(e);w.push(Q.createElement(ee,{key:"add-"+S.nodeKey++,width:"100%",backgroundColor:Gn.ADDED_BG},Q.createElement(te,{color:Gn.ADDED_TEXT,dimColor:a}," "+S.newLineNum.toString().padStart(f)),Q.createElement(te,{color:Gn.LINE_NUM,dimColor:a},e_),Q.createElement(te,{color:Gn.ADDED_TEXT,dimColor:a},"+ "),t?renderWordSegments({wordChanges:t,type:"added",dimDiff:a}):Q.createElement(te,{color:Gn.ADDED_TEXT,dimColor:a},r[e].replace(/\s/g," ")))),S.newLineNum++}}const E=void 0!==l&&w.length>l,v=E?w.slice(0,l):w;return{diffContent:Q.createElement(ee,{flexDirection:"column"},s&&!r&&(d>0||m>0)&&Q.createElement(te,{color:jn.GRAY},"Updated"," ",Q.createElement(te,{color:jn.WHITE,bold:!0},n)," ","with"," ",d>0&&Q.createElement(Q.Fragment,null,Q.createElement(te,{color:Kn.SUCCESS},d)," ","addition",1!==d?"s":"",m>0?" and ":""),m>0&&Q.createElement(Q.Fragment,null,Q.createElement(te,{color:Kn.ERROR},m)," ","removal",1!==m?"s":"")),r&&Q.createElement(te,{color:jn.RED},"Rejected update to",Q.createElement(te,{color:jn.RED},` ${n}`)),Q.createElement(ee,{flexDirection:"column",marginLeft:o,marginRight:o+4,width:(process.stdout.columns||80)-2*o-8},v)),isTruncated:E,totalLines:w.length}}function formatTodosForDisplay(e){const t=lv(e);return t?Q.createElement(ee,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?ke.checkboxOn:ke.checkboxOff;let r,s=!1;switch(e.status){case"completed":r=Kn.SUCCESS,s=!0;break;case"in_progress":r=Kn.IN_PROGRESS;break;default:r=jn.WHITE}return Q.createElement(ee,{key:e.id||t,flexDirection:"row"},Q.createElement(ee,{width:2},Q.createElement(te,{color:r},n)),Q.createElement(te,{color:r,bold:"in_progress"===e.status,strikethrough:s},e.content))})):Q.createElement(te,null,e)}function computeDisplayInput({input:e,isAgent:t,isShell:n,expandedOutput:r}){if(!e)return e;if(t){const t=e.split(/[.\n]/)[0];return t?t+(e.includes(".")||e.includes("\n")?".":""):e}return n&&!r?truncateCommand({command:e}):e}function formatToolInput({input:e,isShell:t}){return Q.createElement(BracketWrap,null,t?e:Q.createElement(Markdown,null,e))}function parseReadSummaryLine(e){if(!e)return null;const t=e.split("\n")[0]?.trim();return t?t.match(bw):null}function getReadToolInlineSummary({name:e,summaryMatch:t}){if(!t||"READ"!==e)return null;const n=t[3]?Number(t[3]):void 0;return{dimText:void 0===n?void 0:`${n} ${1===n?"line":"lines"}`}}function renderReadToolInlineSummary(e){return e?.dimText?Q.createElement(te,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:s}){if(e)return{symbolColor:jn.YELLOW,symbol:ke.arrowRight};if(t)return{symbolColor:jn.RED,symbol:ke.square};if(n)return{symbolColor:zn,symbol:"✻"};if(r&&s){const e=lv(s),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?Kn.SUCCESS:Kn.WARNING,symbol:ke.square}}return{symbolColor:Hn.BG,symbol:ke.square}}function renderToolHeader({isThinking:e,isTasteFile:t,tasteCategory:n,name:r,summaryMatch:s,expandedOutput:o,expandKey:i,output:a}){if(e){const e=a?Math.max(1,Math.round(a.length/500)):1;return Q.createElement(Q.Fragment,null,Q.createElement(te,{color:zn},`Thought for ${e} second${1!==e?"s":""}`," "),!o&&Q.createElement(BracketWrap,{color:jn.DIM},`${i}+o to expand`))}if(t)return Q.createElement(Q.Fragment,null,Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:Un.BADGE_BG,color:Un.BADGE_FG,bold:!0},qk)),Q.createElement(te,null," ","Using your taste"," ",n?"package of ":"packages",n&&Q.createElement(te,{bold:!0},n)));let l=r;return"READ[n]"===r&&s&&(l=`READ[${Number(s[1])}]`),Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:Hn.BG,color:Hn.FG,bold:!0},`${Fk}${l}${Fk}`))}function renderAgentStatus({agentStatus:e,hasError:t,output:n,elapsedSeconds:r,tokensUsed:s}){const o=`${formatTime2(r)} | ${formatTokens(s)}`;return"running"===e?Q.createElement(te,{color:jn.GRAY},"Running (",o,")"):"interrupted"===e||"Interrupted by user"===n?Q.createElement(te,{color:jn.RED,wrap:"wrap"},"Interrupted by user"):"error"===e||t?Q.createElement(te,{color:jn.RED,wrap:"wrap"},n," (",o,")"):Q.createElement(Q.Fragment,null,Q.createElement(te,{wrap:"wrap"},"Done"),Q.createElement(te,{color:jn.GRAY}," (",o,")"))}function getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}){if(n)return{text:e,isTruncated:!1,remainingLines:0,truncationMsg:null};const s=dedentText(e),{text:o,isTruncated:i,remainingLines:a}=truncateToVisualLines({output:s,maxVisualLines:"Question"===t?Jr:Yr,maxChars:"Question"===t?1/0:rs}),l=i&&"Question"!==t;return{text:o,isTruncated:l,remainingLines:a,truncationMsg:l?a>0?Q.createElement(BracketedText,{text:`... +${a} lines [${r}+o to expand]`,color:jn.DIM}):Q.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:jn.DIM}):null}}function renderTruncatedOutput({output:e,name:t,expandedOutput:n,expandKey:r}){const{text:s,isTruncated:o,truncationMsg:i}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r});return o?Q.createElement(Q.Fragment,null,s,"\n",i):s}function renderEditFileDiff({input:e,metadata:t,expandedOutput:n,isPermissionDenied:r,output:s,expandKey:o}){const i=n?void 0:Xr,{diffContent:a,isTruncated:l,totalLines:u}=generateDiff({filePath:e,showMetadata:!0,oldValue:t.oldValue,newValue:t.newValue,startLine:"number"==typeof t.startLine?t.startLine:1,dimDiff:r,permissionDenied:r,maxLines:i});return Q.createElement(ee,{flexDirection:"column"},a,l&&Q.createElement(ee,{marginTop:1},Q.createElement(BracketedText,{text:`… (${u-Xr} more lines) [${o}+o to expand]`,color:jn.DIM})),r&&s&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.RED,wrap:"wrap"},s)))}function renderWriteFileContent({input:e,metadata:t,expandedOutput:n,expandKey:r}){const s=t.content;if(!s)return Q.createElement(te,{color:jn.GRAY},"Created"," ",Q.createElement(te,{color:jn.WHITE,bold:!0},e)," ","(empty file)");const o=s.endsWith("\n")?s.slice(0,-1).split("\n"):s.split("\n"),i="number"==typeof t.totalLines?t.totalLines:o.length,a=n?void 0:Zr,l=void 0!==a&&i>a,u=l?o.slice(0,a):o,d=String(i).length;return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.GRAY},"Created"," ",Q.createElement(te,{color:jn.WHITE,bold:!0},e)," ","(",i," line",1!==i?"s":"",")"),Q.createElement(ee,{marginTop:1,flexDirection:"column"},u.map((e,t)=>Q.createElement(ee,{key:t,width:"100%",backgroundColor:Gn.ADDED_BG},Q.createElement(te,{color:Gn.ADDED_TEXT}," "+String(t+1).padStart(d)),Q.createElement(te,{color:Gn.LINE_NUM},e_),Q.createElement(te,{color:Gn.ADDED_TEXT,wrap:"truncate-end"},e.replace(/\s/g," "))))),l&&void 0!==a&&Q.createElement(ee,{marginTop:1},Q.createElement(BracketedText,{text:`… (${i-a} more lines) [${r}+o to expand]`,color:jn.DIM})))}function renderOutputContent({isTodos:e,isThinking:t,isEditFile:n,isWriteFile:r,metadata:s,output:o,expandedOutput:i,isPermissionDenied:a,input:l,hasError:u,name:d,expandKey:m,showTreeConnector:g}){if(e)return formatTodosForDisplay(o);if(t)return i?Q.createElement(ee,{width:"100%",flexDirection:"column"},Q.createElement(te,null," "),Q.createElement(te,{color:zn,wrap:"wrap",italic:!0},o)):null;if(n&&s?.oldValue&&s?.newValue){const e=renderEditFileDiff({input:l,metadata:s,expandedOutput:i,isPermissionDenied:a,output:o,expandKey:m});return g?Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:lr},Ok," "),e):e}if(r&&s&&"content"in s){const e=renderWriteFileContent({input:l,metadata:s,expandedOutput:i,expandKey:m});return g?Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:lr},Ok," "),e):e}return g?renderTextWithLongConnector({output:o,name:d,expandedOutput:i,expandKey:m,hasError:u}):Q.createElement(ee,{width:"100%"},Q.createElement(te,{color:u?jn.RED:"",wrap:"wrap"},renderTruncatedOutput({output:o,name:d,expandedOutput:i,expandKey:m})))}function renderTextWithLongConnector({output:e,name:t,expandedOutput:n,expandKey:r,hasError:s}){const{text:o,isTruncated:i,truncationMsg:a}=getTruncatedOutputParts({output:e,name:t,expandedOutput:n,expandKey:r}),l=s?jn.RED:void 0,u=buildTreeConnectors(o,i);return Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(ee,{columnGap:1,width:"100%"},Q.createElement(te,{color:lr},u),Q.createElement(ee,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(te,{color:l,wrap:"wrap"},o))),i&&Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:lr},Ok," "),a))}function ToolMessage({name:e,input:t,output:n,isPending:r=!1,hasError:s=!1,metadata:o,expandedOutput:i=!1}){const a="thinking…"===e,l="TODOS"===e,u="EDIT"===e,d="WRITE"===e,m="READ"===e||e.startsWith("READ[")&&e.endsWith("]"),g=!0===o?.isTasteFile,h=o?.tasteCategory,f=!0===o?.permissionDenied,y=!a&&!l&&!g,{name:w}=detectTerminal(),S="iTerm2"===w?"shift":"ctrl",E=!0===o?.isAgent,v=computeDisplayInput({input:t,isAgent:E,isShell:"SHELL"===e,expandedOutput:i}),C=!a&&v&&!g,k=o?.status,T=o?.tokensUsed||0,_="number"==typeof o?.elapsedSeconds?Math.floor(o.elapsedSeconds):0,x=m?parseReadSummaryLine(n):null,P=m?getReadToolInlineSummary({name:e,summaryMatch:x}):null,A=Boolean(n&&!g&&!E&&(!m||s)),{symbolColor:I,symbol:N}=resolveSymbol({isPending:r,hasError:s,isThinking:a,isTodos:l,output:n});return Q.createElement(ee,null,a&&Q.createElement(te,{color:I},N),Q.createElement(ee,{flexDirection:"column",marginLeft:a?1:0},Q.createElement(ee,null,renderToolHeader({isThinking:a,isTasteFile:g,tasteCategory:h,name:e,summaryMatch:x,expandedOutput:i,expandKey:S}),C&&Q.createElement(te,null," ",formatToolInput({input:v,isShell:"SHELL"===e})),renderReadToolInlineSummary(P)),E&&("running"===k||n)&&Q.createElement(ee,{columnGap:1,marginLeft:y?1:0},y&&Q.createElement(te,{color:lr},Ok," "),renderAgentStatus({agentStatus:k,hasError:s,output:n,elapsedSeconds:_,tokensUsed:T})),A&&Q.createElement(ee,{marginLeft:y?1:0},renderOutputContent({isTodos:l,isThinking:a,isEditFile:u,isWriteFile:d,metadata:o,output:n,expandedOutput:i,isPermissionDenied:f,input:t,hasError:s,name:e,expandKey:S,showTreeConnector:y})),r&&!E&&Q.createElement(ee,{columnGap:1,marginLeft:1},Q.createElement(te,{color:lr},Ok," "),Q.createElement(te,{color:jn.GRAY},"Processing…"))))}__name(computeSimilarity,"computeSimilarity"),__name(buildSimilarityMatrix,"buildSimilarityMatrix"),__name(collectSimilarityCandidates,"collectSimilarityCandidates"),__name(buildLinePairs,"buildLinePairs"),__name(groupAdjacentChanges,"groupAdjacentChanges"),__name(renderWordSegments,"renderWordSegments"),__name(renderContextLine,"renderContextLine"),__name(renderContextGroup,"renderContextGroup"),__name(generateDiff,"generateDiff"),__name(formatTodosForDisplay,"formatTodosForDisplay"),__name(computeDisplayInput,"computeDisplayInput"),__name(formatToolInput,"formatToolInput"),__name(parseReadSummaryLine,"parseReadSummaryLine"),__name(getReadToolInlineSummary,"getReadToolInlineSummary"),__name(renderReadToolInlineSummary,"renderReadToolInlineSummary"),__name(resolveSymbol,"resolveSymbol"),__name(renderToolHeader,"renderToolHeader"),__name(renderAgentStatus,"renderAgentStatus"),__name(getTruncatedOutputParts,"getTruncatedOutputParts"),__name(renderTruncatedOutput,"renderTruncatedOutput"),__name(renderEditFileDiff,"renderEditFileDiff"),__name(renderWriteFileContent,"renderWriteFileContent"),__name(renderOutputContent,"renderOutputContent"),__name(renderTextWithLongConnector,"renderTextWithLongConnector"),__name(ToolMessage,"ToolMessage");var t_=__name(({request:e,onResponse:n,onToggleAutoAccept:r})=>{const[s]=K(0),[o,i]=K(1);J(()=>{"edit"===e.action&&e.oldContent&&e.filePath&&resolveEditStartLine({filePath:e.filePath,oldContent:e.oldContent}).then(e=>{void 0!==e&&i(e)}).catch(()=>{})},[e.filePath,e.oldContent,e.action]);const a=[{label:"Yes",value:"yes",description:"Allow this edit",scope:void 0},{label:"Yes, allow all edits during this session [shift+tab]",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],l=__name(e=>{const t=a.find(t=>t.value===e.value);t&&("yes-session"===t.value&&r&&r(),n(t))},"handleSelect"),u=__name(()=>{switch(e.action){case"edit":return"make this edit to";case"create":return"create";case"delete":return"delete";case"execute":return"execute";default:return"modify"}},"getActionDescription"),d=__name(()=>{if("unknown"===e.filePath)return"unknown file";try{const n=t.basename(e.filePath),r=t.relative(process.cwd(),e.filePath);return r&&!r.startsWith("../")&&r.length<50?r:n||e.filePath}catch{return e.filePath}},"getDisplayPath"),m=__name(()=>{switch(e.action){case"edit":return"Edit File";case"create":return"Create File";case"delete":return"Delete File";case"execute":return"Execute File";default:return"File Operation"}},"getHeading");return Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.GRAY,paddingX:1,width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(te,{bold:!0,color:jn.YELLOW},`${m()} ${"edit"===e.action?d():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&Q.createElement(ee,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:d(),marginLeft:0,startLine:o}).diffContent),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{bold:!0},"Do you want to ",u()," ",Q.createElement(te,{color:jn.CYAN},d()),"?")),Q.createElement(tt,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:s,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.CYAN},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(te,{color:t?jn.CYAN:jn.WHITE},e.includes("[shift+tab]")?Q.createElement(Q.Fragment,null,e.split("[shift+tab]")[0],Q.createElement(BracketWrap,{color:t?jn.CYAN:jn.WHITE,bold:!0},"shift+tab")):e.includes("(")?Q.createElement(Q.Fragment,null,e.split("(")[0],Q.createElement(te,{color:jn.GRAY},"(",e.split("(")[1])):e)}))},"PermissionPrompt");Ht(),Kt(),dr();var n_=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=K(0),s=[{label:"Yes",value:"yes",description:"Allow this command",scope:void 0},{label:"Yes, allow all edits during this session [shift+tab]",value:"yes-session",description:"Allow and remember for this session",scope:"session"},{label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}],o=__name(e=>{const r=s.find(t=>t.value===e.value);r&&("yes-session"===r.value&&n&&n(),t(r))},"handleSelect"),i=__name(()=>{const t=e.args?Array.isArray(e.args)?e.args.join(" "):e.args:"";return t?`${e.command} ${t}`:e.command},"getCommandDisplay");return Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.GRAY,paddingX:1,width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(te,{bold:!0,color:jn.YELLOW},"Execute Shell Command")),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{bold:!0,wrap:"wrap"},"Command Code needs to execute ",Q.createElement(te,{color:jn.CYAN},i()),".")),e.workingDirectory&&Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.GRAY},"Working directory: ",e.workingDirectory)),e.description&&Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM,italic:!0},e.description)),Q.createElement(tt,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:r,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.CYAN},e?ke.pointer:" "),itemComponent:({label:e,isSelected:t})=>Q.createElement(te,{color:t?jn.CYAN:jn.WHITE},e.includes("[shift+tab]")?Q.createElement(Q.Fragment,null,e.split("[shift+tab]")[0],Q.createElement(BracketWrap,{color:t?jn.CYAN:jn.WHITE,bold:!0},"shift+tab")):e)}))},"ShellPermissionPrompt");function getKillShellRequest(e){const t=e.port?`port ${e.port}`:`PID ${e.pid}`;return{command:"kill",args:[t],description:`Terminate process on ${t}`}}function getFileAction2(e){return e.includes("write")?"create":e.includes("delete")?"delete":"edit"}function handlePermissionResponse({choice:e,resolve:t,setPendingPermission:n,respondToPrompt:r,setStatus:s,permissionMode:o,showHintMessage:i,allowedStatus:a,deniedStatus:l}){r(e);const u="no"!==e.value;t(u),n(null),u?(s(a),"standard"===o&&i("Use shift+tab to enable auto-accept")):s(l)}__name(getKillShellRequest,"getKillShellRequest"),__name(getFileAction2,"getFileAction"),__name(handlePermissionResponse,"handlePermissionResponse");var r_=V(__name(function PermissionView2({pendingPermission:e,permissionMode:t,setPendingPermission:n,setStatus:r,respondToPrompt:s,showHintMessage:o,handleToggleAutoAccept:i}){const a={resolve:e.resolve,setPendingPermission:n,respondToPrompt:s,setStatus:r,permissionMode:t,showHintMessage:o};if("shell_command"===e.toolName){const t=e.params;return Q.createElement(ee,{marginY:1},Q.createElement(n_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Shell command allowed",deniedStatus:"Shell command denied"}),onToggleAutoAccept:i}))}if("kill_shell"===e.toolName){const t=getKillShellRequest(e.params);return Q.createElement(ee,{marginY:1},Q.createElement(n_,{request:t,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"Process termination allowed",deniedStatus:"Process termination denied"}),onToggleAutoAccept:i}))}const l=e.params,u={action:getFileAction2(e.toolName),filePath:String(l.filePath??l.file_path??l.path??l.absolutePath??l.notebook_path??"unknown"),description:`Allow ${e.toolName} operation`,oldContent:"edit_file"===e.toolName&&"string"==typeof l.oldContent?l.oldContent:void 0,newContent:"edit_file"===e.toolName&&"string"==typeof l.newContent?l.newContent:void 0};return Q.createElement(ee,{marginY:1},Q.createElement(t_,{request:u,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onToggleAutoAccept:i}))},"PermissionView"));Ht(),bC(),Ht(),Ht(),Kt();var s_="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",o_="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░███████░███████████░░░░████░░░\n░░░███░███░███░███░███░███████░░░\n░░░███░░░░░███░███░███░███░███░░░\n░░░███░███░███░███░███░███░███░░░\n░░░███████░███░███░███░███████░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n";function getMaxLineWidth(e){return Math.max(...e.split("\n").map(e=>e.length))}__name(getMaxLineWidth,"getMaxLineWidth");var i_=getMaxLineWidth(s_),a_=getMaxLineWidth(o_),l_=i_+1,c_=a_+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var u_=__name(e=>{const t=e??getTerminalWidth();return t>=l_?s_:t>=c_?o_:d_},"getResponsiveCommandLogo"),d_="⌘ CMD\n",m_="░█▀▀░█▀▄▀█░█▀▄░\n░█░░░█░▀░█░█░█░\n░▀▀▀░▀░░░▀░▀▀░░",p_=getMaxLineWidth(m_),g_=c_,h_=__name(e=>{const t=e??getTerminalWidth();return t>=l_?"full":t>=g_?"compact":"minimal"},"getHeaderLayout");tC(),Ht(),dr();var f_=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:s=0,titleColor:o=jn.GRAY,dividerChar:i="─",dividerColor:a=jn.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*s),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",g=r?` ${r}`:"",h=d.length+m.length+g.length,f=i.repeat(Math.max(0,u-h));return Q.createElement(ee,{paddingLeft:s,paddingRight:s,marginBottom:1,...l},(t||n)&&Q.createElement(te,{color:a},d),e&&Q.createElement(te,{color:o},m),Q.createElement(te,{color:a},f),r&&Q.createElement(te,{color:jn.DIM},g))},"Divider");bC(),dr(),Ht(),dr();var y_=[{type:"user",text:"I always prefer pnpm",duration:2e3},{type:"learned",text:"Learned: pnpm (95% preference)",details:".commandcode/taste/taste.md",duration:2e3},{type:"user",text:"I prefer commander over meow",duration:2e3},{type:"updated",text:"Updated: commander boosted (60% → 95%), meow adjusted (90% → 35%)",details:".commandcode/taste/cli/taste.md",duration:2e3},{type:"user",text:"I prefer TypeScript for Node CLIs",duration:2e3},{type:"learned",text:"Learned: TypeScript for CLIs (90% preference)",details:".commandcode/taste/cli/taste.md",duration:2e3}],w_=__name(({onComplete:e,onExit:t})=>{const[n,r]=K(0),[s,o]=K(!1),i=n>=y_.length;return J(()=>{if(n>=y_.length)return;if(s)return;const e=y_[n],t=setTimeout(()=>{r(e=>Math.min(e+1,y_.length))},e.duration);return()=>clearTimeout(t)},[n,s]),se((n,s)=>{""===n||s.ctrl&&"c"===n?t?t():e():s.escape?e():i?(s.return||" "===n)&&e():" "===n?o(e=>!e):s.return&&r(e=>Math.min(e+1,y_.length))}),Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{bold:!0},"Meet Your Coding Taste")),Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"Command Code learns your coding style as you work.")),Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"Here's how your preferences evolve in real-time:")),Q.createElement(ee,{flexDirection:"column",marginY:1},y_.slice(0,n).map((e,t)=>"user"===e.type?Q.createElement(ee,{key:t},Q.createElement(te,null,ke.pointer," ",e.text)):Q.createElement(ee,{key:t,flexDirection:"column",marginBottom:1,marginLeft:1},Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"⎿ "),Q.createElement(te,{color:Un.TEXT},e.text)),e.details&&Q.createElement(ee,{marginLeft:3},Q.createElement(te,{color:jn.DIM},"Saved(",e.details,")"))))),i?Q.createElement(ee,{flexDirection:"column",marginY:1},Q.createElement(ee,null,Q.createElement(te,{bold:!0,color:Un.TEXT},"Demo Complete!")),Q.createElement(ee,null,Q.createElement(te,null,"Command Code will now use these preferences to generate")),Q.createElement(ee,null,Q.createElement(te,null,"better suggestions tailored to your coding style. The")),Q.createElement(ee,null,Q.createElement(te,null,"more you code, the smarter it gets.")),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press Enter to get started →"))):Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(s?" (paused)":""))))},"TasteDemoComponent"),S_=__name(({onClose:e,onExit:t})=>{const[n,r]=K(Zv.getEvents()),[s,o]=K(0);se((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),J(()=>{const e=__name(()=>{r(Zv.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return Zv.on("new-event",e),Zv.on("cleared",t),()=>{Zv.off("new-event",e),Zv.off("cleared",t)}},[]),J(()=>{const e=__name(()=>{yC(),o(e=>e+1)},"handleResize");return process.stdout.on("resize",e),()=>{process.stdout.off("resize",e)}},[]);const i=__name(e=>["learned","refactored"].includes(e),"isLearningEvent"),a=__name(e=>{const t=e.match(/^(learned|upgraded|downgraded|refactored|moved):\s*(.*)$/i);if(t){const e=t[1].toLowerCase();let n=t[2];const r=n.match(/^(.+?)\.?\s+Confidence:\s*(\d+\.?\d*)$/);let s=n,o=null;if(r){s=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);o=`confidence: ${parseFloat(e).toString()}%`}const i={learned:"Learned",upgraded:"Reinforced",downgraded:"Downgraded",refactored:"Refactored",moved:"Moved"}[e]||e.charAt(0).toUpperCase()+e.slice(1);return{type:e,label:i,content:s,confidence:o}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),l=__name(e=>{const t=e.match(/^(.+?)\s*\((\d+)%\s*(?:→|->)\s*(\d+)%\)$/);if(!t)return null;const n=t[1].trim(),r=parseInt(t[2],10),s=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:s,diff:s-r}},"parsePercentageChange"),u=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),s=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:s,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails"),d=X(()=>(process.stdout.rows??24)-1,[s]);return Q.createElement(ee,{flexDirection:"column",width:"100%",height:d,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ot,{name:"vice"},Q.createElement(te,null,u_()))),Q.createElement(f_,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),Q.createElement(ee,{flexDirection:"column"},0===n.length?Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ee,null,Q.createElement(te,null,"Start using Command Code and it will begin recording your coding taste.")),Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"Your preferences, patterns, and style will appear here in real-time."))),Q.createElement(ae,{count:2}),Q.createElement(f_,{title:"DEMO",titleColor:"white",subPrefix:!0}),Q.createElement(w_,{onComplete:()=>{e()},onExit:t})):Q.createElement(ee,{flexDirection:"column"},n.map(e=>{if(i(e.type)){const{type:t,label:n,content:r,confidence:s}=a(e.message),o="moved"===t?u(e.details):null,i="upgraded"===t||"downgraded"===t?l(r):null;return Q.createElement(ee,{key:e.id,marginBottom:1},Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:Un.BADGE_BG,color:Un.BADGE_FG,bold:!0},`${Fk}${n}${Fk}`)),o?Q.createElement(te,{color:jn.DIM}," ","(",o.fullPath,")"):e.details?Q.createElement(te,{color:jn.DIM}," ","(",e.details,")"):null),Q.createElement(ee,{marginLeft:1},Q.createElement(te,{color:jn.DIM},"⎿"," "),o?Q.createElement(Q.Fragment,null,Q.createElement(te,null," ",o.category," ","package ("),Q.createElement(te,{color:jn.DIM},o.oldPath),Q.createElement(te,null," ",ke.arrowRight," ",o.newPath),Q.createElement(te,null,")")):i?Q.createElement(Q.Fragment,null,Q.createElement(te,null," ",i.text," ","("),Q.createElement(te,{color:jn.DIM},"confidence:"," "),Q.createElement(te,{color:jn.DIM},i.oldPercent,"%"),Q.createElement(te,null," ",ke.arrowRight," "),Q.createElement(te,{color:i.diff>0?jn.GREEN:jn.RED},i.newPercent,"%"),Q.createElement(te,null,")")):Q.createElement(Q.Fragment,null,Q.createElement(te,null," ",r),s&&Q.createElement(te,{color:jn.DIM}," ","(",s,")")))))}return Q.createElement(ee,{key:e.id,marginBottom:1},Q.createElement(te,{color:jn.DIM},ke.pointerSmall," ",e.message))}))))},"LearningFeedFull");function LearningView({setShowLearningFeed:e,setStaticKey:t,onExit:n}){return Q.createElement(S_,{onClose:()=>{yC(),e(!1),t(e=>e+1)},onExit:n})}__name(LearningView,"LearningView"),Ht(),dr(),Ht(),dr(),bC(),xr();var b_=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,s]=K(!1),[o,i]=K(!0);J(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();s(e)}catch(e){}finally{i(!1)}},"loadSettings")()},[]),se((t,n)=>{if(!n.return&&" "!==t)return n.escape?(yC(),void e()):void 0;a()});const a=__name(async()=>{const e=!r;s(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){s(!e)}},"toggleTasteLearning");return o?Q.createElement(ee,{key:n,borderStyle:"single",borderColor:jn.BLUE,padding:1,flexDirection:"column"},Q.createElement(te,{color:jn.BLUE,bold:!0},"Taste Settings"),Q.createElement(te,{color:jn.DIM},"Loading configuration...")):Q.createElement(ee,{key:n,borderStyle:"single",borderColor:jn.GRAY,padding:1,flexDirection:"column"},Q.createElement(te,{bold:!0},"Taste Learning"),Q.createElement(te,{color:jn.DIM},"Configure taste learning preferences for this project"),Q.createElement(ee,{marginTop:1}),Q.createElement(ee,{justifyContent:"space-between"},Q.createElement(te,null,"Taste learning",Q.createElement(te,{color:jn.DIM}," - Learn from your interactions")),Q.createElement(te,{color:r?jn.GREEN:jn.GRAY},r?"enabled":"disabled")),Q.createElement(ee,{marginTop:1}),Q.createElement(te,{color:jn.DIM},"Taste data stored in .commandcode/taste/taste.md"),Q.createElement(te,{color:jn.DIM},"Enter/Space to toggle • Esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,setShowTasteConfig:t,loadTasteStatus:n}){return Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM},"Press Esc to return to conversation")),Q.createElement(b_,{onClose:()=>t(!1),onSettingsChange:n,staticKey:e})))}__name(TasteConfigView,"TasteConfigView"),Ht(),Ht(),Kt(),fw(),bC(),dr();var E_=__name(e=>Math.ceil(e.length/4),"estimateTokens"),v_=__name(e=>e.includes("/.agents/skills/")||e.includes("\\.agents\\skills\\"),"isAgentsSkill"),C_=__name(({onClose:e})=>{const[t,n]=K([]),[r,s]=K(!0),[o,i]=K(null),[a,l]=K(0);J(()=>{__name(async()=>{try{const{global:e,project:t}=await loadAllSkillSummaries(),r=[...e.map(e=>({label:e.name,value:e.filePath,location:"user",description:e.description,filePath:e.filePath})),...t.map(e=>({label:e.name,value:e.filePath,location:"project",description:e.description,filePath:e.filePath}))];n(r)}catch(e){i(e instanceof Error?e.message:"Failed to load skills")}finally{s(!1)}},"loadSkills")()},[]);const u=t.filter(e=>"project"===e.location),d=t.filter(e=>"user"===e.location),m=[...u,...d],g=__name(async t=>{try{await it([{file:t.filePath,line:1}]),yC(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?i(h()):i(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelectSkill");se((t,n)=>{if(n.escape)return yC(),void e();if(n.upArrow)l(e=>Math.max(0,e-1));else if(n.downArrow)l(e=>Math.min(m.length-1,e+1));else if(n.return){const e=m[a];e&&g(e)}});const h=__name(()=>{const e=process.platform;return"win32"===e?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===e?"~/.zshrc":"~/.bashrc")},"getEditorSetupMessage");return r?Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,{color:Bn,bold:!0},"Agent Skills"),Q.createElement(te,{color:jn.DIM},"Loading skills...")):o?Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,{color:jn.RED,bold:!0},"Agent Skills"),Q.createElement(te,{color:jn.DIM},o),Q.createElement(ee,{marginTop:1}),Q.createElement(te,{color:jn.DIM},"Press ",Q.createElement(te,{bold:!0},"Esc")," to close")):0===t.length?Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(te,{color:Bn,bold:!0},"Agent Skills"),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM},"No skills found")),Q.createElement(te,{color:jn.DIM},"Create skills in:"),Q.createElement(te,{color:jn.DIM}," ","~/",".commandcode","/","skills","/ (user)"),Q.createElement(te,{color:jn.DIM}," ","~/.agents/","skills","/ (user, .agents)"),Q.createElement(te,{color:jn.DIM}," ",".commandcode","/","skills","/ (project)"),Q.createElement(te,{color:jn.DIM}," ",".agents/","skills","/ (project, .agents)"),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press ",Q.createElement(te,{bold:!0},"Esc")," to close"))):Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ee,null,Q.createElement(te,{color:Bn,bold:!0},"Skills"," "),Q.createElement(te,{color:jn.DIM},m.length," skills")),u.length>0&&Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(ee,null,Q.createElement(te,{color:Jn,bold:!0},"Project skills"," "),Q.createElement(te,{color:Jn},"(",".commandcode","/","skills"," or .agents/","skills",")")),u.map((e,t)=>{const n=a===t,r=v_(e.filePath);return Q.createElement(ee,{key:e.value},Q.createElement(te,{color:n?jn.GREEN:jn.WHITE},e.label),r&&Q.createElement(te,{color:jn.DIM}," [.agents]"),Q.createElement(te,{color:jn.DIM}," · ~",E_(e.description)," description tokens"))})),d.length>0&&Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(ee,null,Q.createElement(te,{color:Jn,bold:!0},"User skills"," "),Q.createElement(te,{color:Jn},"(~/",".commandcode","/","skills"," or ~/.agents/","skills",")")),d.map((e,t)=>{const n=a===u.length+t,r=v_(e.filePath);return Q.createElement(ee,{key:e.value},Q.createElement(te,{color:n?jn.GREEN:jn.WHITE},e.label),r&&Q.createElement(te,{color:jn.DIM}," [.agents]"),Q.createElement(te,{color:jn.DIM}," · ~",E_(e.description)," description tokens"))})),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(te,{dimColor:!0},"Add skills: ",Q.createElement(te,{color:jn.CYAN},"cmd skills add ","<owner/repo>")),Q.createElement(te,{color:jn.DIM},"Press ",Q.createElement(te,{bold:!0},"Esc")," to close")))},"SkillsConfig");function SkillsConfigView({staticKey:e,setShowSkillsConfig:t}){return Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(C_,{onClose:()=>t(!1),staticKey:e})))}function useTerminalWidth(){const{stdout:e}=re(),[t,n]=K(()=>e.columns??80);return J(()=>{const t=__name(()=>n(e.columns??80),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}function getUsageColor(e){return e>=80?jn.RED:e>=50?jn.YELLOW:jn.GREEN}function buildProgressBar({percentage:e,width:t}){const n=Math.max(0,Math.min(100,e)),r=Math.round(n/100*t),s=t-r;return{filled:"━".repeat(r),empty:"━".repeat(s)}}__name(SkillsConfigView,"SkillsConfigView"),Ht(),Ht(),dr(),Pr(),Ht(),__name(useTerminalWidth,"useTerminalWidth"),Ht(),dr(),__name(getUsageColor,"getUsageColor"),__name(buildProgressBar,"buildProgressBar"),bC();var k_="https://commandcode.ai/settings/usage";function getLayoutSizes({terminalWidth:e}){return e<50?{labelWidth:14,progressBarWidth:Math.max(10,e-10),showTwoColumn:!1}:e<70?{labelWidth:16,progressBarWidth:Math.max(15,e-15),showTwoColumn:!1}:{labelWidth:22,progressBarWidth:Math.min(30,e-15),showTwoColumn:!0}}function getSuccessColor(e){return e>=90?jn.GREEN:e>=70?jn.YELLOW:jn.RED}function getDaysColor(e){if(null!==e)return e<3?jn.RED:e<7?jn.YELLOW:void 0}__name(getLayoutSizes,"getLayoutSizes"),__name(getSuccessColor,"getSuccessColor"),__name(getDaysColor,"getDaysColor");var T_=__name(({plan:e,status:t})=>Q.createElement(ee,{marginBottom:0},Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:jn.BLUE,color:"#f4f4f4",bold:!0},`${Fk}USAGE${Fk}`)),e&&Q.createElement(Q.Fragment,null,Q.createElement(te,null," "),Q.createElement(te,{color:jn.GRAY},e.name)),t&&Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{color:"active"===t?jn.GREEN:jn.YELLOW},t))),"UsageBadge"),__=__name(({label:e,labelWidth:t,children:n})=>Q.createElement(te,null,Q.createElement(te,{dimColor:!0},e.padEnd(t)),n),"Row"),x_=__name(({showRetry:e})=>Q.createElement(ee,{marginTop:1},e&&Q.createElement(te,{color:jn.DIM},Q.createElement(te,{bold:!0},"r")," to retry · "),Q.createElement(te,{color:jn.DIM},"Press ",Q.createElement(te,{bold:!0},"Esc")," to close")),"UsageFooter");function getCallsLabel(e){if(!e)return"Calls";const t=new Date(e);return Number.isNaN(t.getTime())?"Calls":`Calls (since ${t.toLocaleDateString("en-US",{month:"short",day:"numeric"})})`}function buildDataRows({credits:e,summary:t,sub:n}){const r=e?.freeCredits??0,s=getCallsLabel(n?.currentPeriodStart);return{left:[{label:"Purchased",value:Q.createElement(te,null,formatCredits(e?.purchasedCredits??0))},...r>0?[{label:"Free",value:Q.createElement(te,null,formatCredits(r))}]:[],{label:"Renews",value:Q.createElement(te,null,n?formatDateCompact(n.currentPeriodEnd):"—")}],right:[{label:s,value:Q.createElement(te,null,t?t.totalCount.toLocaleString():"—")},{label:"Success",value:t?Q.createElement(te,{color:getSuccessColor(t.successRate)},formatPercent(t.successRate)):Q.createElement(te,null,"—")}]}}__name(getCallsLabel,"getCallsLabel"),__name(buildDataRows,"buildDataRows");var P_=__name(({onClose:e})=>{const[t,n]=K("loading"),[r,s]=K(null),[o,i]=K(!1),a=useTerminalWidth(),l=X(()=>getLayoutSizes({terminalWidth:a}),[a]),u=Z(async e=>{try{i(!1);const t=await fetchUsageData();if(e.aborted)return;if(!t.whoami)return i(t.errors.includes("Not authenticated")),void n("error");s(t),n("loaded")}catch{if(e.aborted)return;n("error")}},[]),d=Q.useRef(null);se((r,s)=>{if(s.escape&&(yC(),e()),"r"===r&&"error"===t){n("loading"),d.current?.abort();const e=new AbortController;d.current=e,u(e.signal)}}),J(()=>{const e=new AbortController;return d.current=e,u(e.signal),()=>e.abort()},[u]);const m=r?.subscription?.data??null,g=m?getPlanInfo({planId:m.planId??""}):null;if("loading"===t)return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(T_,{plan:g,status:m?.status??null}),Q.createElement(te,{color:jn.DIM},"Loading…"),Q.createElement(x_,null));if("error"===t)return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(T_,{plan:g,status:m?.status??null}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},o?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),Q.createElement(x_,{showRetry:!o}));if(!r)return null;if(!r.credits&&!r.subscription)return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(T_,{plan:g,status:m?.status??null}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"No billing data found. Visit "),Q.createElement(Cr,{url:k_,text:"Studio",color:jn.CYAN}),Q.createElement(te,{color:jn.DIM}," for usage details.")),Q.createElement(x_,null));const h=r.credits?.credits,f=r.summary,y=g?.monthlyCredits??0,w=Math.max(0,h?.monthlyCredits??0),S=getUsagePercent({used:Math.max(0,y-w),total:y}),E=(h?.purchasedCredits??0)>0||(h?.freeCredits??0)>0||w>0,v=m?.currentPeriodEnd?getDaysRemaining(m.currentPeriodEnd):null,C=getUsageColor(S),k=buildProgressBar({percentage:S,width:l.progressBarWidth}),T=getCircleGauge(S),_=getDaysColor(v),{labelWidth:x,showTwoColumn:P}=l,A=buildDataRows({credits:h,summary:f,sub:m});return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ee,{marginBottom:1},Q.createElement(T_,{plan:g,status:m?.status??null})),y>0?Q.createElement(Q.Fragment,null,Q.createElement(ee,null,Q.createElement(te,{color:C},k.filled),Q.createElement(te,{color:Jn},k.empty),Q.createElement(te,{bold:!0,color:C},` ${Math.round(S)}%`)),Q.createElement(ee,null,Q.createElement(te,{color:C},T),Q.createElement(te,{bold:!0}," ",formatPercent(S)),Q.createElement(te,{color:jn.GRAY}," used"),null!==v&&Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{color:_},0===v?"expires today":`${v} day${1===v?"":"s"} left`)))):E?null:Q.createElement(te,{color:jn.DIM},"Plan details unavailable"),P?Q.createElement(ee,{flexDirection:"column",marginTop:1},Array.from({length:Math.max(A.left.length,A.right.length)}).map((e,t)=>{const n=A.left[t],r=A.right[t];return Q.createElement(ee,{key:`row-${n?.label??""}-${r?.label??""}`},Q.createElement(te,{dimColor:!0},(n?.label??"").padEnd(x)),Q.createElement(ee,{width:23},n?.value??Q.createElement(te,null)),r&&Q.createElement(Q.Fragment,null,Q.createElement(te,{dimColor:!0},r.label.padEnd(14)),r.value))})):Q.createElement(ee,{flexDirection:"column",marginTop:1},[...A.left,...A.right].map(e=>Q.createElement(__,{key:e.label,label:e.label,labelWidth:x},e.value))),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Full breakdown at "),Q.createElement(Cr,{url:k_,text:"commandcode.ai/settings/usage",color:jn.CYAN})),Q.createElement(x_,null))},"UsageOverlay");function UsageView({staticKey:e,setShowUsageOverlay:t}){return Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(P_,{onClose:()=>t(!1)})))}function countMessagesByRole({messages:e}){let t=0,n=0;for(const r of e)"user"===r.message.role&&t++,"assistant"===r.message.role&&n++;return{user:t,assistant:n}}function countToolCalls({messages:e}){let t=0,n=0;for(const r of e){const e=r.message.content;if(Array.isArray(e))for(const r of e)"tool-call"===r.type&&t++,"tool-result"===r.type&&n++}return{calls:t,results:n}}function countImages({messages:e}){let t=0;for(const n of e){const e=n.message.content;if(Array.isArray(e))for(const n of e)"image"===n.type&&t++}return t}function findCompactions({messages:e}){const t=[];for(const n of e)n.meta.isSummary&&t.push({type:"auto",timestamp:n.meta.timestamp});return t}function estimateConversationTokens({messages:e}){let t=0;for(const n of e)t+=estimateTokens(n.message);return t}function buildAutoCompactStatus({tokensUsed:e,tokenLimit:t}){const n=e/t,r=[{tier:1,threshold:Ut.TIER_1_THRESHOLD,description:`Prune to last ${Ut.TIER_1_KEEP_COUNT} tool calls`},{tier:2,threshold:Ut.TIER_2_THRESHOLD,description:`Prune to last ${Ut.TIER_2_KEEP_COUNT} tool calls`},{tier:3,threshold:Ut.TIER_3_THRESHOLD,description:"Full summarization"}];let s=0;const o=r.map(r=>{const o=Math.round(r.threshold*t),i=Math.max(0,o-e);let a="upcoming";return n>=r.threshold&&(a="passed",s=r.tier),{tier:r.tier,threshold:r.threshold,tokensAt:o,description:r.description,status:a,tokensAway:i}}),i=o.findIndex(e=>"upcoming"===e.status);return{tiers:-1!==i?o.map((e,t)=>t===i?{...e,status:"current"}:e):o,currentTier:s,keepRecentTokens:Ut.KEEP_RECENT_TOKENS}}function generateTips({percentage:e,conversationTokens:t,totalTokens:n,mcpToolCount:r,messageCount:s,imageCount:o}){const i=[];if(0===n)return i;const a=n>0?Math.round(t/n*100):0;e>=90&&i.push("Tier 3 auto-compact imminent — /compact now to control what gets summarized"),e>=80&&e<90&&i.push("Auto-compact Tier 3 triggers at 90% — /compact to free space before it kicks in");const l=a>60&&e>40;return l&&i.push(`${a}% is conversation — /compact to reclaim tokens`),r>0&&e>30&&i.push(`${r} MCP tools loaded — disconnect unused servers to save tokens`),o>0&&i.push(`${o} image${o>1?"s":""} in context — images use ~1.5k tokens each`),e>=50&&e<80&&!l&&i.push("/compact to free space · /model to switch models"),s>50&&e>40&&i.push(`${s} messages — consider starting a new session for a fresh context`),i}async function collectMemoryItems(){const e=(await discoverMemoryFiles(process.cwd())).filter(e=>e.exists),t=[];for(const n of e){const e=await loadMemoryFile(n.path),r=e?estimateTokens(e):0,s=process.env.HOME??"",o=s&&n.path.startsWith(s)?`~${n.path.slice(s.length)}`:n.path;t.push({name:n.description,tokens:r,source:o})}return t}function collectBuiltInTools(){const e=[];for(const t of jv){const n=JSON.stringify(t.input_schema??{}),r=estimateTokens(`${t.name} ${t.description??""} ${n}`);e.push({name:t.name,tokens:r})}for(const t of Bv){const n=estimateTokens(`${t.name} ${t.type}`);e.push({name:t.name,tokens:n})}return e}function collectMcpTools(){const e=getMcpConnectionManager().getConnectedServers(),t=[];for(const n of e)if("connected"===n.status)for(const e of n.tools){const r=JSON.stringify(e.inputSchema??{}),s=estimateTokens(`${e.name} ${e.description??""} ${r}`);t.push({name:e.name,tokens:s,source:n.name})}return t}async function collectSkillItems(){const e=await loadAllSkillSummaries(),t=[];for(const n of e.project){const e=estimateTokens(`${n.name} ${n.description}`);t.push({name:n.name,tokens:e,source:"project"})}for(const n of e.global){const e=estimateTokens(`${n.name} ${n.description}`);t.push({name:n.name,tokens:e,source:"user"})}return t}async function collectAgentItems(){const e=await loadAllAgents(),t=[];for(const n of e.project){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"project"})}for(const n of e.personal){const e=estimateTokens(`${n.name} ${n.description} ${n.systemPrompt}`);t.push({name:n.name,tokens:e,source:"user"})}return t}function sumTokens(e){let t=0;for(const n of e)t+=n.tokens;return t}async function analyzeContext({contextEngine:e}){const t=e.getContextTokensUsed(),n=pS,r=getConfiguredModel(),s=e.getHistory(),o=countMessagesByRole({messages:s}),i=countToolCalls({messages:s}),a=countImages({messages:s}),l=findCompactions({messages:s}),u=e.getCompactionCount(),d=Math.max(u,l.length),m=estimateConversationTokens({messages:s}),g=collectBuiltInTools(),h=collectMcpTools(),[f,y,w]=await Promise.all([collectSkillItems(),collectAgentItems(),collectMemoryItems()]),S=sumTokens(g),E=sumTokens(h),v=S+E+sumTokens(f)+sumTokens(y)+sumTokens(w),C=t>0,k=C?t:m+v,T=!C&&s.length>0,_=Math.min(k/n*100,100),x=Math.max(0,n-k),P=Math.max(0,k-m-v),A=[];if(k>0){m>0&&A.push({name:"Conversation",tokens:m,percentage:Math.round(m/k*100),detail:`${o.user+o.assistant} messages`}),P>0&&A.push({name:"System prompt",tokens:P,percentage:Math.round(P/k*100),detail:"identity, taste, skills"});const e=S+E;if(e>0){const t=g.length,n=h.length,r=n>0?`${t} built-in + ${n} MCP`:`${t} built-in`;A.push({name:"Tool schemas",tokens:e,percentage:Math.round(e/k*100),detail:r})}}A.sort((e,t)=>t.tokens-e.tokens);const I=s.length>0?s[0]?.meta.timestamp??null:null;return{tokensUsed:k,tokenLimit:n,percentage:_,tokensRemaining:x,isEstimated:T,model:r,breakdown:A,autoCompact:buildAutoCompactStatus({tokensUsed:k,tokenLimit:n}),stats:{messageCount:s.length,userMessages:o.user,assistantMessages:o.assistant,toolCalls:i.calls,toolResults:i.results,imageCount:a,compactionCount:d,sessionStartTime:I},compactions:l,tips:generateTips({percentage:_,conversationTokens:m,totalTokens:k,mcpToolCount:h.length,messageCount:s.length,imageCount:a})}}function getLayoutSizes2({terminalWidth:e}){const t=e;return t<50?{labelWidth:14,progressBarWidth:Math.max(10,t-10),breakdownBarWidth:0,showBreakdownBars:!1,showBreakdownDetail:!1}:t<70?{labelWidth:16,progressBarWidth:Math.max(15,t-15),breakdownBarWidth:8,showBreakdownBars:!0,showBreakdownDetail:!1}:{labelWidth:22,progressBarWidth:Math.min(30,t-15),breakdownBarWidth:16,showBreakdownBars:!0,showBreakdownDetail:!0}}function formatDuration(e){if(!e)return"N/A";const t=new Date(e).getTime();if(isNaN(t))return"N/A";const n=Date.now(),r=Math.round((n-t)/6e4);return r<1?"<1m":r<60?`${r}m`:`${Math.floor(r/60)}h ${r%60}m`}function ContextProgress({analysis:e,progressBarWidth:t}){const n=getUsageColor(e.percentage),r=buildProgressBar({percentage:e.percentage,width:t});return Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ee,{marginBottom:0},Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:jn.BLUE,color:"#f4f4f4",bold:!0},`${Fk}CONTEXT${Fk}`)),Q.createElement(te,null," "),Q.createElement(te,{color:jn.GRAY},e.model)),Q.createElement(ee,null,Q.createElement(te,{color:n},r.filled),Q.createElement(te,{color:Jn},r.empty),Q.createElement(te,{bold:!0,color:n},` ${e.percentage.toFixed(1)}%`)),Q.createElement(ee,null,Q.createElement(te,null,formatTokens(e.tokensUsed)),Q.createElement(te,{color:jn.GRAY},` / ${formatTokens(e.tokenLimit)}`),Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{color:n},formatTokens(e.tokensRemaining)),Q.createElement(te,{color:jn.GRAY}," remaining"),e.isEstimated&&Q.createElement(te,{color:jn.DIM}," (estimated)")),Q.createElement(CompactionDistance,{analysis:e}))}function BreakdownRow({item:e,maxTokens:t,labelWidth:n,barWidth:r,showBar:s,showDetail:o}){const i=s&&t>0?Math.round(e.tokens/t*r):0,a="█".repeat(i),l="░".repeat(r-i);return Q.createElement(ee,null,Q.createElement(te,null,e.name.padEnd(n)),s&&Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.CYAN},a),Q.createElement(te,{color:Jn},l)),Q.createElement(te,{bold:!0},` ${formatTokens(e.tokens)}`),Q.createElement(te,{color:jn.GRAY},` ${e.percentage}%`),o&&e.detail&&Q.createElement(te,{color:jn.DIM},` ${e.detail}`))}function ContextBreakdown({analysis:e,labelWidth:t,breakdownBarWidth:n,showBreakdownBars:r,showBreakdownDetail:s}){return 0===e.breakdown.length?null:Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{color:Jn,bold:!0},"Breakdown"),e.breakdown.map(o=>Q.createElement(BreakdownRow,{key:o.name,item:o,maxTokens:e.tokensUsed,labelWidth:t,barWidth:n,showBar:r,showDetail:s})))}function CompactionDistance({analysis:e}){const t=e.autoCompact.tiers.find(e=>3===e.tier);if(!t||"passed"===t.status)return null;const n=Math.round(100*t.threshold)-Math.round(e.percentage),r=n<=10?jn.RED:n<=25?jn.YELLOW:jn.GRAY;return Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"Full summarization"),Q.createElement(te,{color:r},` ${n}% away`))}function ContextSession({analysis:e,labelWidth:t}){return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Jn,bold:!0},"Session"),Q.createElement(ee,null,Q.createElement(te,null,"Messages".padEnd(t)),Q.createElement(te,{color:jn.GRAY},`${e.stats.messageCount} (${e.stats.userMessages} user, ${e.stats.assistantMessages} assistant)`)),Q.createElement(ee,null,Q.createElement(te,null,"Tool calls".padEnd(t)),Q.createElement(te,{color:jn.GRAY},`${e.stats.toolCalls} calls · ${e.stats.toolResults} results`)),e.stats.imageCount>0&&Q.createElement(ee,null,Q.createElement(te,null,"Images".padEnd(t)),Q.createElement(te,{color:jn.GRAY},`${e.stats.imageCount}`)),Q.createElement(ee,null,Q.createElement(te,null,"Duration".padEnd(t)),Q.createElement(te,{color:jn.GRAY},formatDuration(e.stats.sessionStartTime))))}function ContextTips({tips:e}){return 0===e.length?null:Q.createElement(ee,{flexDirection:"column"},e.map(e=>Q.createElement(ee,{key:e},Q.createElement(te,{color:jn.CYAN},ke.pointer),Q.createElement(te,{color:jn.GRAY}," ",e))))}function ContextHints(){return Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(ee,null,Q.createElement(te,{color:jn.GRAY},">"," "),Q.createElement(te,{color:jn.GRAY},"Auto-compact kicks in when context reaches its limit")),Q.createElement(ee,null,Q.createElement(te,{color:jn.GRAY},">"," "),Q.createElement(te,{color:jn.GRAY},"Run /compact to manually summarize your conversation and free up context")))}function ContextMessage({analysis:e}){const t=getLayoutSizes2({terminalWidth:useTerminalWidth()});return Q.createElement(ee,{flexDirection:"column",paddingTop:1},Q.createElement(ContextProgress,{analysis:e,progressBarWidth:t.progressBarWidth}),Q.createElement(ContextBreakdown,{analysis:e,labelWidth:t.labelWidth,breakdownBarWidth:t.breakdownBarWidth,showBreakdownBars:t.showBreakdownBars,showBreakdownDetail:t.showBreakdownDetail}),Q.createElement(ContextSession,{analysis:e,labelWidth:t.labelWidth}),Q.createElement(ContextTips,{tips:e.tips}),Q.createElement(ContextHints,null))}function ContextConfigView({staticKey:e,contextEngineRef:t,setShowContextView:n,setInput:r}){const[s,o]=K(null),[i,a]=K(null);return J(()=>{let e=!0;return __name(async()=>{if(t.current)try{const n=await analyzeContext({contextEngine:t.current});e&&o(n)}catch{e&&a("Failed to analyze context.")}else e&&a("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),se((e,t)=>{t.escape&&(yC(),r(""),n(!1))}),Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(ee,{flexDirection:"column",width:"100%"},i?Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Bn,bold:!0},"Context"),Q.createElement(te,{color:jn.DIM},i)):s?Q.createElement(ContextMessage,{analysis:s}):Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Bn,bold:!0},"Context"),Q.createElement(te,{color:jn.DIM},"Loading context analysis...")),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press Esc to return to conversation"))))}__name(UsageView,"UsageView"),Ht(),Ht(),Kt(),hE(),CE(),mw(),Qv(),aw(),bS(),xr(),__name(countMessagesByRole,"countMessagesByRole"),__name(countToolCalls,"countToolCalls"),__name(countImages,"countImages"),__name(findCompactions,"findCompactions"),__name(estimateConversationTokens,"estimateConversationTokens"),__name(buildAutoCompactStatus,"buildAutoCompactStatus"),__name(generateTips,"generateTips"),__name(collectMemoryItems,"collectMemoryItems"),__name(collectBuiltInTools,"collectBuiltInTools"),__name(collectMcpTools,"collectMcpTools"),__name(collectSkillItems,"collectSkillItems"),__name(collectAgentItems,"collectAgentItems"),__name(sumTokens,"sumTokens"),__name(analyzeContext,"analyzeContext"),bC(),Ht(),dr(),Rr(),__name(getLayoutSizes2,"getLayoutSizes"),__name(formatDuration,"formatDuration"),__name(ContextProgress,"ContextProgress"),__name(BreakdownRow,"BreakdownRow"),__name(ContextBreakdown,"ContextBreakdown"),__name(CompactionDistance,"CompactionDistance"),__name(ContextSession,"ContextSession"),__name(ContextTips,"ContextTips"),__name(ContextHints,"ContextHints"),__name(ContextMessage,"ContextMessage"),dr(),__name(ContextConfigView,"ContextConfigView"),Ht(),Ht(),Kt(),Ls(),CE(),mw(),Ur(),Nr(),xr();var A_="https://commandcode.ai/studio";function getVersionStatus(){try{return{current:getPackageJson().version,updateAvailable:null}}catch{return{current:"Unknown",updateAvailable:null}}}async function getAuthStatus(){try{const e=await checkAuthStatus(),t=e.userName||null;return{authenticated:e.authenticated,username:t}}catch{return{authenticated:!1,username:null}}}async function getModelStatus(){try{const e=await getSelectedModel(),t=getProviderDisplayName((await loadUserConfig()).provider||null);return{id:e,displayName:getModelDisplayName(e),provider:t}}catch{return{id:"Unknown",displayName:"Unknown",provider:"Unknown"}}}async function getSkillsAgentsStatus(){let e=0,t=0,n=0,r=0;try{const n=await loadAllSkillSummaries();e=n.global.length,t=n.project.length}catch{}try{const e=await loadAllAgents();n=e.personal.length,r=e.project.length}catch{}return{personalSkills:e,projectSkills:t,personalAgents:n,projectAgents:r}}function execGitAsync(e){return new Promise(t=>{L("git",e,{encoding:"utf8",cwd:process.cwd(),timeout:3e3},(e,n)=>{t(e?null:n.trim()||null)})})}async function getGitStatus2(){const e=await execGitAsync(["rev-parse","--abbrev-ref","HEAD"]);if(!e)return{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null};const[t,n]=await Promise.all([execGitAsync(["rev-parse","--show-toplevel"]),execGitAsync(["remote","get-url","origin"])]);return{branch:e,worktreePath:t,remoteUrl:n?formatRemoteUrl(n):null,remoteHttpUrl:n?buildHttpUrl(n):null}}function parseSSHUrl(e){const t=e.match(/@([^:]+):(.+?)(?:\.git)?$/);return t?.[1]&&t[2]?{host:t[1],path:t[2]}:null}function formatRemoteUrl(e){const t=parseSSHUrl(e);if(t)return t.path;const n=e.match(/\/\/[^/]+\/(.+?)(?:\.git)?$/);return n?.[1]?n[1]:e}function buildHttpUrl(e){const t=parseSSHUrl(e);if(t)return`https://${t.host}/${t.path}`;const n=e.match(/^ssh:\/\/[^@]+@([^/]+)\/(.+?)(?:\.git)?$/);return n?.[1]&&n[2]?`https://${n[1]}/${n[2]}`:/^https?:\/\//.test(e)?e.replace(/\.git$/,""):e}function getPrStatus(e){try{const t=getCachedPR(e);return t?{number:t.number,url:t.url,state:t.state}:null}catch{return null}}async function hasTasteMdFiles(e){if(!C(e))return!1;try{return(await U(e,{recursive:!0,encoding:"utf-8"})).some(e=>e.endsWith(".md"))}catch{return!1}}async function getTasteStatus(){const e=t.join(process.cwd(),".commandcode","taste"),n=t.join(e,"taste.md"),r=C(n),s=r||await hasTasteMdFiles(e);let o=!0;try{o=await isTasteLearningEnabled()}catch{}return{fileExists:s,filePath:r?n:e,learningEnabled:o}}function detectProxy(){const e=process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy;return e?sanitizeProxyUrl(e):null}function sanitizeProxyUrl(e){try{const t=new URL(e);return t.username="",t.password="",t.toString().replace(/\/$/,"")}catch{return"[malformed proxy URL]"}}function getSystemStatus(){let e,t,n,r;try{e=yT(w.platform()),t=NT(),n=RT(),r=$T()}catch{e="Unknown",t="Unknown",n="Unknown",r="N/A"}return{cwd:process.cwd(),os:e,arch:w.arch(),shell:n,terminal:t,nodeVersion:process.version,ide:"N/A"!==r?r:null,proxy:detectProxy()}}async function gatherStatusData(){const e=safeSync(getVersionStatus,{current:"Unknown",updateAvailable:null}),t=safeSync(getSystemStatus,{cwd:process.cwd(),os:"Unknown",arch:w.arch(),shell:"Unknown",terminal:"Unknown",nodeVersion:process.version,ide:null,proxy:null}),[n,r,s,o,i]=await Promise.all([safeAsync(getAuthStatus,{authenticated:!1,username:null}),safeAsync(getModelStatus,{id:"Unknown",displayName:"Unknown",provider:"Unknown"}),safeAsync(getTasteStatus,{fileExists:!1,filePath:"",learningEnabled:!1}),safeAsync(getSkillsAgentsStatus,{personalSkills:0,projectSkills:0,personalAgents:0,projectAgents:0}),safeAsync(getGitStatus2,{branch:null,worktreePath:null,remoteUrl:null,remoteHttpUrl:null})]),a=safeSync(()=>getPrStatus(i.branch),null);return{version:e,auth:n,model:r,git:i,pr:a,taste:s,skillsAgents:o,system:t}}function safeSync(e,t){try{return e()}catch{return t}}async function safeAsync(e,t){try{return await e()}catch{return t}}function formatCountValue(e,t){const n=e+t;return 0===n?"None":`${n} (${e} user, ${t} project)`}function formatSystemValue({system:e}){const t=[`${e.os} ${e.arch}`];return e.ide&&t.push(e.ide),!e.terminal||e.ide&&e.ide.toLowerCase().startsWith(e.terminal.toLowerCase())||t.push(e.terminal),t.push(e.shell),t.push(`Node ${e.nodeVersion}`),t.join(" · ")}__name(getVersionStatus,"getVersionStatus"),__name(getAuthStatus,"getAuthStatus"),__name(getModelStatus,"getModelStatus"),__name(getSkillsAgentsStatus,"getSkillsAgentsStatus"),__name(execGitAsync,"execGitAsync"),__name(getGitStatus2,"getGitStatus"),__name(parseSSHUrl,"parseSSHUrl"),__name(formatRemoteUrl,"formatRemoteUrl"),__name(buildHttpUrl,"buildHttpUrl"),__name(getPrStatus,"getPrStatus"),__name(hasTasteMdFiles,"hasTasteMdFiles"),__name(getTasteStatus,"getTasteStatus"),__name(detectProxy,"detectProxy"),__name(sanitizeProxyUrl,"sanitizeProxyUrl"),__name(getSystemStatus,"getSystemStatus"),__name(gatherStatusData,"gatherStatusData"),__name(safeSync,"safeSync"),__name(safeAsync,"safeAsync"),Ht(),Kt(),cv(),dr(),Pr(),__name(formatCountValue,"formatCountValue"),__name(formatSystemValue,"formatSystemValue");var I_=__name(({label:e,value:t,valueColor:n,dimValue:r})=>Q.createElement(ee,null,Q.createElement(te,{dimColor:!0},`${e}:`.padEnd(14)),r?Q.createElement(te,{dimColor:!0},t):Q.createElement(te,{color:n},t)),"Row");function StatusMessage({statusData:e}){const t=e,n=t.version.updateAvailable?`v${t.version.current} → v${t.version.updateAvailable} available`:`v${t.version.current}`,r=`${t.model.provider} · ${t.model.displayName}`,s=t.git.branch||"N/A",o=t.git.worktreePath?toRelativePath(t.git.worktreePath):null,i=t.auth.authenticated?ke.tick:ke.cross,a=t.auth.authenticated?jn.WHITE:Kn.ERROR,l=t.skillsAgents.personalSkills+t.skillsAgents.projectSkills,u=t.skillsAgents.personalAgents+t.skillsAgents.projectAgents,d=t.taste.fileExists?"Active · "+(t.taste.learningEnabled?"Learning on":"Learning off"):"No taste.md";return Q.createElement(ee,{flexDirection:"column",paddingX:0},Q.createElement(ee,null,Q.createElement(te,{color:Bn,bold:!0},"Command Code"," "),Q.createElement(te,{dimColor:!0},n)),Q.createElement(ee,null,Q.createElement(te,{dimColor:!0},"Visit "),Q.createElement(Cr,{url:A_,text:A_,color:jn.CYAN}),Q.createElement(te,{dimColor:!0}," for usage and billing")),Q.createElement(ee,{marginTop:1},Q.createElement(te,{dimColor:!0},"Account:".padEnd(14)),t.auth.authenticated&&t.auth.username?Q.createElement(Q.Fragment,null,Q.createElement(Cr,{url:`https://commandcode.ai/${t.auth.username}/`,text:t.auth.username,color:jn.CYAN}),Q.createElement(te,{color:a}," ",i)):t.auth.authenticated?Q.createElement(Q.Fragment,null,Q.createElement(te,null,"Authenticated"),Q.createElement(te,{color:a}," ",i)):Q.createElement(Q.Fragment,null,Q.createElement(te,{color:Kn.WARNING},"Not signed in"),Q.createElement(te,{color:a}," ",i),Q.createElement(te,{dimColor:!0}," — run "),Q.createElement(te,{bold:!0},"/login"))),Q.createElement(I_,{label:"Model",value:r}),Q.createElement(I_,{label:"Branch",value:s,dimValue:!t.git.branch}),o?Q.createElement(I_,{label:"Worktree",value:o}):null,t.git.remoteUrl?Q.createElement(ee,null,Q.createElement(te,{dimColor:!0},"Repository:".padEnd(14)),Q.createElement(Cr,{url:t.git.remoteHttpUrl||`https://github.com/${t.git.remoteUrl}`,text:t.git.remoteUrl,color:jn.CYAN}),t.pr?Q.createElement(Q.Fragment,null,Q.createElement(te,{dimColor:!0}," · "),Q.createElement(Cr,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?jn.CYAN:jn.GRAY}),Q.createElement(te,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null):t.pr?Q.createElement(ee,null,Q.createElement(te,{dimColor:!0},"Pull Request:".padEnd(14)),Q.createElement(Cr,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?jn.CYAN:jn.GRAY}),Q.createElement(te,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null,Q.createElement(I_,{label:"Taste",value:d,dimValue:!t.taste.fileExists}),Q.createElement(I_,{label:"Directory",value:toRelativePath(t.system.cwd)}),Q.createElement(I_,{label:"Skills",value:formatCountValue(t.skillsAgents.personalSkills,t.skillsAgents.projectSkills),dimValue:0===l}),Q.createElement(I_,{label:"Agents",value:formatCountValue(t.skillsAgents.personalAgents,t.skillsAgents.projectAgents),dimValue:0===u}),Q.createElement(I_,{label:"System",value:formatSystemValue({system:t.system})}),t.system.proxy?Q.createElement(I_,{label:"Proxy",value:t.system.proxy}):null)}function StatusConfigView({staticKey:e,setShowStatusView:t,setInput:n}){const[r,s]=K({phase:"loading"});return J(()=>{let e=!1;return gatherStatusData().then(t=>{e||s({phase:"ready",data:t})}).catch(t=>{if(e)return;const n=t instanceof Error?t.message:"Failed to gather status";s({phase:"error",message:n})}),()=>{e=!0}},[]),se((e,r)=>{r.escape&&(n(""),t(!1))}),Q.createElement(Q.Fragment,null,Q.createElement(UT,{staticKey:e}),Q.createElement(ee,{flexDirection:"column",width:"100%"},"ready"===r.phase?Q.createElement(StatusMessage,{statusData:r.data}):"error"===r.phase?Q.createElement(te,{dimColor:!0},"Could not load status: ",r.message):Q.createElement(te,{dimColor:!0},"Gathering status…"),Q.createElement(ee,{marginTop:1},Q.createElement(te,{dimColor:!0},"Press Esc to return to conversation"))))}function moveFocusDown(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?n>0?{...e,zone:"suggestions",suggestionIndex:0}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:e:"suggestions"===e.zone?e.suggestionIndex<n-1?{...e,suggestionIndex:e.suggestionIndex+1}:r>0?{...e,zone:"active-dir",activeDirIndex:0}:{...e,zone:"input"}:e.activeDirIndex<r-1?{...e,activeDirIndex:e.activeDirIndex+1}:{...e,zone:"input"}}function moveFocusUp(e,t){const{suggestionCount:n,activeDirCount:r}=t;return"input"===e.zone?r>0?{...e,zone:"active-dir",activeDirIndex:r-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:e:"suggestions"===e.zone?e.suggestionIndex>0?{...e,suggestionIndex:e.suggestionIndex-1}:{...e,zone:"input"}:e.activeDirIndex>0?{...e,activeDirIndex:e.activeDirIndex-1}:n>0?{...e,zone:"suggestions",suggestionIndex:n-1}:{...e,zone:"input"}}function getAdjustedSuggestionOffset(e){const{selectedIndex:t,currentOffset:n,maxVisible:r,totalSuggestions:s}=e;return s<=r?0:t<n?t:t>=n+r?t-r+1:n}function getSuggestionBase(e){const n=resolveDirectoryPath(e),r=/[\\/]$/.test(e),s=e.replace(/\\/g,"/");if(s.endsWith("/."))return{searchDirectory:n,prefix:".",outputPrefix:`${s.slice(0,-1)}`};if(r)return{searchDirectory:n,prefix:"",outputPrefix:s};const o=s.lastIndexOf("/");return-1===o?{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:""}:{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:s.slice(0,o+1)}}function getDirectorySuggestions(e){const t=e.trim();if(!t)return[];try{const{searchDirectory:e,prefix:n,outputPrefix:r}=getSuggestionBase(t),s=n.startsWith(".")||r.includes("/.");return v.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!!s||!e.name.startsWith(".")).filter(e=>!n||e.name.toLowerCase().startsWith(n.toLowerCase())).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>`${r}${e.name}/`)}catch(e){const t=e.code;return"ENOENT"!==t&&"ENOTDIR"!==t&&console.error(`Warning: Could not list directory suggestions: ${t}`),[]}}function getFooterText(e){return"active-dir"===e.focusZone?"[Del] Remove [↑↓] Navigate [Tab] Autocomplete [Esc] Close":"[Enter] Add [↑↓] Navigate [Tab] Autocomplete [Esc] Close"}__name(StatusMessage,"StatusMessage"),__name(StatusConfigView,"StatusConfigView"),Ht(),Ht(),en(),Ht(),en(),__name(function createInitialFocusState(){return{zone:"input",suggestionIndex:0,activeDirIndex:0}},"createInitialFocusState"),__name(moveFocusDown,"moveFocusDown"),__name(moveFocusUp,"moveFocusUp"),__name(getAdjustedSuggestionOffset,"getAdjustedSuggestionOffset"),__name(getSuggestionBase,"getSuggestionBase"),__name(getDirectorySuggestions,"getDirectorySuggestions"),__name(getFooterText,"getFooterText"),dr(),gr();var N_=__name(({onClose:e})=>{const[t,n]=K(""),[r,s]=K(null),[o,i]=K([]),[a,l]=K(getAdditionalDirectories()),[u,d]=K({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,g]=K(0);J(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),g(0)},[t]),J(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{s(null)},5e3);return()=>clearTimeout(e)},[r]);const h=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(s({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):s({tone:"warning",text:t.message}):s({tone:"error",text:t.message})},"submitPath"),f=__name(e=>{if(!removeAdditionalDirectory(e))return s({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void l(getAdditionalDirectories());s({tone:"success",text:`Removed ${formatDirectoryForDisplay(e)} from directory scope`}),l(getAdditionalDirectories()),d(e=>{if("active-dir"!==e.zone)return e;const t=Math.max(0,e.activeDirIndex-1);return{...e,activeDirIndex:t}})},"handleRemove");se((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&o[u.suggestionIndex]?void h(o[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])f(a[u.activeDirIndex]);else{if(r.tab&&o.length>0){const e=o[u.suggestionIndex]??o[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),s(null)))}r.downArrow?d(e=>moveFocusDown(e,{suggestionCount:o.length,activeDirCount:a.length})):r.upArrow&&d(e=>moveFocusUp(e,{suggestionCount:o.length,activeDirCount:a.length}))}}}),J(()=>{"suggestions"===u.zone&&g(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:o.length}))},[u,o.length]),J(()=>{d(e=>"suggestions"===e.zone&&e.suggestionIndex>=o.length?{...e,zone:"input",suggestionIndex:Math.max(0,o.length-1)}:"active-dir"===e.zone&&e.activeDirIndex>=a.length?{...e,zone:"input",activeDirIndex:Math.max(0,a.length-1)}:e)},[o.length,a.length]);const y=o.slice(m,m+8),w=getFooterText({focusZone:u.zone});return Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.CYAN,paddingX:1,paddingY:0},Q.createElement(te,{bold:!0,color:jn.CYAN},"Add directory to workspace"),Q.createElement(te,{color:jn.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(te,{color:jn.GRAY},"Added directories"),0===a.length?Q.createElement(te,{color:jn.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return Q.createElement(te,{key:e,color:n?jn.YELLOW:jn.GREEN,bold:n},n?` ${ke.pointer} `:" ",formatDirectoryForDisplay(e))})),Q.createElement(ee,{marginTop:1},Q.createElement(te,{bold:!0,color:jn.WHITE},"Path")),Q.createElement(ee,null,Q.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?ke.pointer:" "} `,prefixColor:"input"===u.zone?jn.CYAN:jn.GRAY,onChange:e=>{n(e),s(null)},onSubmit:h})),!t&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:{error:jn.RED,warning:jn.YELLOW,success:jn.GREEN}[r.tone]},r.text)),o.length>0&&Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(te,{color:jn.GRAY},"Suggestions"),y.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return Q.createElement(te,{key:e,color:r?jn.CYAN:jn.GRAY,bold:r},r?` ${ke.pointer} `:" ",e)})),Q.createElement(ee,{marginTop:1},Q.createElement(BracketedText,{text:w,color:jn.DIM})))},"AddDirModal");Ht(),Ht(),Kt(),Ht(),Ht(),Kt(),Qv(),dr();var R_=__name(()=>t.join(w.homedir(),".commandcode","agents"),"getRootAgentDir"),$_=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),M_=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[s,o]=K("idle"),[i,a]=K(""),l=[...jv.map(e=>e.name),...Bv.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return o("error"),void a("Agent configuration is incomplete");o("saving");try{const r="personal"===e.location?R_():$_();await O.mkdir(r,{recursive:!0});const s=`${e.agentType}.md`,o=t.join(r,s),i=Array.from(e.selectedTools).map(e=>Wv[e]||e).join(", "),a=0===e.selectedTools.size?"none":e.selectedTools.size===l.length?'"*"':JSON.stringify(i),u=`---\nname: "${e.agentType}"\ndescription: ${JSON.stringify(e.ccToolDefinition)}\ntools: ${a}\n---\n\n${e.sysPrompt}\n`;await O.writeFile(o,u,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),o("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");se((e,t)=>{r||!t.return||"idle"!==s&&"error"!==s||u()});const d=Array.from(e.selectedTools).map(e=>Wv[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return Q.createElement(ee,{flexDirection:"column",gap:1},Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"Name:"),Q.createElement(te,{color:jn.GRAY},e.agentType)),Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"Location:"),Q.createElement(te,{color:jn.GRAY},m)),Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"Tools:"),Q.createElement(te,{color:jn.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"Description"),Q.createElement(te,{color:jn.GRAY},"(Tells ","Command Code"," when to use this agent):")),Q.createElement(te,{color:jn.GRAY},e.ccToolDefinition),Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"System Prompt:")),Q.createElement(te,{color:jn.GRAY},e.sysPrompt),!r&&Q.createElement(ee,{marginTop:1},"idle"===s&&Q.createElement(ee,{gap:1},Q.createElement(te,{color:jn.GREEN,dimColor:!0},"Press"),Q.createElement(te,{color:jn.GREEN,bold:!0},"Enter"),Q.createElement(te,{color:jn.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===s&&Q.createElement(te,{color:jn.YELLOW},"Saving agent..."),"saved"===s&&Q.createElement(te,{color:jn.GREEN},ke.tick," ",i),"error"===s&&Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.RED},ke.cross," Error: ",i),Q.createElement(te,{color:jn.GRAY},"Press Enter to retry"))))},"AgentSummary");Qv(),dr();var L_=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[s,o]=K("menu"),i=[...jv.map(e=>e.name),...Bv.map(e=>e.name)];let a=new Set;if("*"===e.tools||'"*"'===e.tools)a=new Set(i);else if(e.tools&&"none"!==e.tools){const t=e.tools.replace(/^"|"$/g,"").split(",").map(e=>e.trim()).map(e=>Gv[e]||e);a=new Set(t)}const l={location:e.location,method:"manual",agentType:e.name,sysPrompt:e.sysPrompt,ccToolDefinition:e.description,recommendedMethodDescription:"",selectedTools:a},u=[{label:"1. View agent",value:"view"},...r?[]:[{label:"2. Delete agent",value:"delete"}],{label:r?"2. Back":"3. Back",value:"back"}],d=__name(e=>{"back"===e.value?t():"view"===e.value?o("view"):"edit"===e.value?o("edit"):"delete"===e.value&&o("delete")},"handleMenuSelect");if(se((e,n)=>{n.escape&&("menu"===s?t():o("menu")),n.return&&"view"===s&&o("menu")}),"view"===s)return Q.createElement(ee,{flexDirection:"column"},Q.createElement(M_,{config:l,onSaveComplete:()=>o("menu"),viewOnly:!0}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY},"Press Enter to go back")));if("edit"===s)return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.YELLOW},"Edit functionality coming soon..."),Q.createElement(te,{color:jn.GRAY},"Press Esc to go back"));if("delete"===s){const r=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],s=__name(async r=>{if("confirm-delete"===r.value)try{await O.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),o("menu")}else o("menu")},"handleDeleteSelect");return Q.createElement(ee,{flexDirection:"column",gap:1},Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.RED},"Delete agent"),Q.createElement(te,{color:jn.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),Q.createElement(ee,null,Q.createElement(tt,{items:r,onSelect:s,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},` ${t}`)})))}return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.WHITE,bold:!0},e.name),Q.createElement(ee,{marginTop:1},Q.createElement(tt,{items:u,onSelect:d,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},` ${t}`)})),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");SE(),dr();var D_=__name(({handleSelect:e,createdAgentName:n})=>{const[r,s]=K([]),[o,i]=K([]),[a,l]=K([]),[u,d]=K(!0),[m,g]=K(!1),[h,f]=K(null),[y,S]=K(!1),E=__name(()=>t.join(w.homedir(),".commandcode","agents"),"getRootAgentDir"),v=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),C=__name(async(e,n)=>{try{g(!1);const r=(await O.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const s=t.join(e,r),o=await O.readFile(s,"utf-8"),{data:i,content:a}=Ne(o);let l=i.tools||"";return"*"!==l&&'"*"'!==l||(l="*"),{name:i.name||r.replace(".md",""),description:i.description||"",tools:l,sysPrompt:a.trim(),location:n,filePath:s}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");J(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([C(E(),"personal"),C(v(),"project")]),n=yE.map(e=>({name:e.name,description:e.description,tools:Array.isArray(e.tools)?e.tools.join(", "):e.tools,sysPrompt:e.systemPrompt,location:"personal",filePath:`__builtin__:${e.name}`}));s(e),i(t),l(n),d(!1)},"loadAgents")()},[m]);const k=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{k.push({label:e.name,value:e.filePath})}),o.forEach(e=>{k.push({label:e.name,value:e.filePath})});const T=r.length+o.length,_=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...o].find(e=>e.filePath===t.value);e&&(f(e),S(!0))}},"handleAgentSelect");if(u)return Q.createElement(te,{color:jn.GRAY},"Loading agents...");if(y&&h){const e=h.filePath.startsWith("__builtin__:");return Q.createElement(L_,{agent:h,onBack:()=>{S(!1),f(null)},setRevalidateAgent:g,isReadOnly:e})}const x=__name(({isSelected:e,label:t})=>{const n=k.find(e=>e.label===t),s=n?.value||"",i=r[0]?.filePath===s,a=o[0]?.filePath===s;return Q.createElement(ee,{flexDirection:"column"},i&&r.length>0&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY,bold:!0},"User agents")),a&&o.length>0&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.GRAY,bold:!0},"Project agents")),Q.createElement(ee,null,Q.createElement(te,{color:jn.WHITE},e?">":" "),Q.createElement(te,{color:e?jn.WHITE:jn.GRAY}," ",t)))},"CustomItemComponent");return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.WHITE,bold:!0},"Agents"),T>0?Q.createElement(te,{color:jn.GRAY}," ","(",T," agent",T>1?"s":"",")"):Q.createElement(te,{color:jn.GRAY}," (No custom agents)")),n&&Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{color:jn.GREEN,dimColor:!0},"Created agent: ",n)),Q.createElement(tt,{items:k,onSelect:_,indicatorComponent:()=>null,itemComponent:x}),a.length>0&&Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(te,{color:jn.GRAY,bold:!0},"Default agents"),a.map(e=>Q.createElement(te,{key:e.filePath,color:jn.GRAY}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(te,{color:jn.GRAY},"Create specialized subagents that Command Code can delegate to."),Q.createElement(te,{color:jn.GRAY},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Ht(),Kt(),js(),dr(),Qv(),Ht(),Ht(),Kt(),dr();var O_=__name(({onSelect:e})=>Q.createElement(tt,{items:[{label:"1. Project (.commandcode/agents/)",value:"project"},{label:"2. Personal (~/.commandcode/agents/)",value:"personal"}],onSelect:t=>{"project"!==t.value&&"personal"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},` ${t}`)}),"LocationSelector");Ht(),gr(),Kt(),Qv(),yr(),vr(),bE(),dr();var F_=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:s,onSysPromptChange:o,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=K(!1),[g,h]=K(!1),f=Z(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||d){if(!d||t.isPasteEnd){if(d&&t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?o(e):t.cleanedContent&&o(t.cleanedContent))}o(e)}}else if(m(!0),t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?o(e):t.cleanedContent&&o(t.cleanedContent))}},[d,o]),y=Z(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||g){if(!g||t.isPasteEnd){if(g&&t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(h(!0),t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[g,i]);return"agentType"===e?Q.createElement(Q.Fragment,null,Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(Wv).some(e=>Le(e)===Le(t))||Object.keys(Wv).some(e=>Le(e)===Le(t)))&&Q.createElement(te,{color:jn.RED},ke.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Le(t))&&Q.createElement(te,{color:jn.RED},ke.warning," This name is reserved. Reserved names:"," ",fE.join(", "))),Q.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Le(t);Object.values(Wv).some(t=>Le(t)===e)||Object.keys(Wv).some(t=>Le(t)===e)||isReservedAgentName(e)||a()},onChange:s,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?Q.createElement(Q.Fragment,null,Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.WHITE},"Enter the system prompt for your agent:"),Q.createElement(te,{color:jn.GRAY},"Be comprehensive for best results.")),Q.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:f,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.WHITE},"When should ","Command Code"," use this agent?"),Q.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:y,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Ht(),dr();var q_=__name(({onSelect:e})=>Q.createElement(tt,{items:[{label:"1. Generate with Command Code (recommended)",value:"recommended"},{label:"2. Manual configuration",value:"manual"}],onSelect:t=>{"recommended"!==t.value&&"manual"!==t.value||e(t.value)},indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY},` ${t}`)}),"MethodSelector");Ht(),gr(),Ht(),dr();var j_=["·","○","◇","☆","✧","☆","◇","○","⌘"],B_=[12,5,4,4,4,4,4,5,16],U_=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<B_.length;e++)if(n+=B_[e],t<n)return j_[e];const r=t-58;n=0;for(let e=0;e<U_.length;e++)if(n+=U_[e],r<n)return j_[7-e];return j_[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=__name(e=>{const n=e-(t-5);return n>=0&&n<ir.length?ir[n]:ar},"getCharColor");return Q.createElement(te,null,e.split("").map((e,t)=>Q.createElement(te,{key:t,color:r(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return Q.createElement(te,{color:t??Bn,bold:!0},`${getWaveSymbol(e)} `)}function formatToken(e){return e<1e3?`${e}`:`${(e/1e3).toFixed(1)}k`}function formatTime3(e){return e<6e4?`${Math.floor(e/1e3)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}__name(getWaveSymbol,"getWaveSymbol"),__name(ShimmerText,"ShimmerText"),__name(CMDIcon,"CMDIcon"),__name(formatToken,"formatToken"),__name(formatTime3,"formatTime");var z_=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,s]=K(0),[o,i]=K(0),a=Y(n);a.current=n;const l=getTerminalWidth();J(()=>{const e=setInterval(()=>{s(e=>(e+1)%88),i(e=>{const t=a.current;if(e===t)return e;const n=t-e,r=e+Math.sign(n)*Math.max(1,Math.ceil(Math.abs(n)/10));return n>0?Math.min(r,t):Math.max(r,t)})},80);return()=>clearInterval(e)},[]);const u=r%(e.length+10),d=l>70,m=l>40&&l<=70;return Q.createElement(ee,{width:l,height:1,paddingLeft:0,marginLeft:0},Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:Qn.BG,color:Qn.FG}," "),Q.createElement(te,{backgroundColor:Qn.BG},Q.createElement(CMDIcon,{frame:4*r})),Q.createElement(ShimmerText,{text:e,offset:u,bg:Qn.BG}),Q.createElement(te,{backgroundColor:Qn.BG,color:Qn.FG}," ")),Q.createElement(te,null," "),d?Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:jn.DIM},formatTime3(t)),Q.createElement(te,{color:jn.DIM},"•"),Q.createElement(te,{color:jn.GRAY},ke.arrowDown),Q.createElement(te,{color:jn.DIM},formatToken(Math.round(o))),Q.createElement(te,{color:jn.DIM},"•"),Q.createElement(ee,{columnGap:1},Q.createElement(te,{bold:!0,color:jn.GRAY},"esc"),Q.createElement(te,{color:jn.DIM},"to interrupt"))):m?Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:jn.DIM},formatToken(Math.round(o)))):Q.createElement(Q.Fragment,null))},"Status");vr(),yr(),dr();var W_=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:s})=>{const[o,i]=K(!1),[a,l]=K(0),[u,d]=K(0);J(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=Z(()=>{0!==e.trim().length&&n()},[e,n]),g=Z(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||o){if(!o||n.isPasteEnd){if(o&&n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}t(e)}}else if(i(!0),n.isPasteEnd){i(!1);const e=await detectClipboardText();return void(e?(l(e=>e+1),t(e)):n.cleanedContent&&(l(e=>e+1),t(n.cleanedContent)))}},[o,t]);return Q.createElement(ee,{flexDirection:"column"},r?Q.createElement(ee,null,Q.createElement(CMDIcon,{frame:u}),Q.createElement(te,{color:jn.WHITE},"Generating agent from description...")):Q.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:g,onSubmit:m}),s&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.RED},`${ke.warning} ${s}`)))},"RecommendedFlow");Ht(),Qv(),dr();var G_=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[s,o]=K(!1),[i,a]=K(0),l=X(()=>[...jv.map(e=>e.name),...Bv.map(e=>e.name)],[]),u=X(()=>[{name:"All tools",tools:l},{name:"Read-only tools",tools:l.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:l.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:l.filter(e=>"shell_command"===e)},{name:"Search tools",tools:l.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:l.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].filter(e=>e.tools.length>0),[l]),d=X(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),s?(u.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-3"}),e.push({type:"toggle",value:"hide-advanced"}),e.push({type:"spacer",value:"spacer-1"}),e.push({type:"label",value:"Individual Tools:"}),l.forEach(t=>{e.push({type:"tool",value:t})})):(u.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[s,u,e,l]),m=d.map((t,n)=>{if("divider"===t.type)return{label:"─".repeat(30),value:n,type:"divider"};if("spacer"===t.type)return{label:"",value:n,type:"spacer"};if("label"===t.type)return{label:t.value,value:n,type:"label"};if("continue"===t.type)return{label:"[ Continue ]",value:n,type:"continue"};if("toggle"===t.type)return{label:"show-advanced"===t.value?"[ Show advanced options ]":"[ Hide advanced options ]",value:n,type:"toggle"};if("category"===t.type){const r=u.find(e=>e.name===t.value),s=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${s?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${Wv[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),g=m.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return se((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?g.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=g.length?0:t});else if(l.return||" "===e){const e=g[i];if(e){const i=d[e.value];if(!i)return;"continue"===i.type?r():"toggle"===i.type?(o(!s),a(0)):"category"===i.type?n(i.value):"tool"===i.type&&t(i.value)}}}),Q.createElement(ee,{flexDirection:"column"},m.map((e,t)=>{const n=g.findIndex(t=>t.value===e.value),r=-1!==n&&n===i;if("divider"===e.type)return Q.createElement(ee,{key:`divider-${t}`},Q.createElement(te,{color:jn.GRAY}," ",e.label));if("spacer"===e.type)return Q.createElement(ee,{key:`spacer-${t}`,height:1});if("label"===e.type)return Q.createElement(ee,{key:`label-${t}`},Q.createElement(te,{color:jn.GRAY}," ",e.label));const s="continue"===e.type;return Q.createElement(ee,{key:`item-${t}`},Q.createElement(te,{color:r?jn.WHITE:jn.GRAY,bold:s&&r},r?">":" "," ",e.label))}),Q.createElement(ee,{marginTop:1},e.size===l.length&&Q.createElement(te,{color:jn.GRAY},"All tools selected"),e.size>0&&e.size<l.length&&Q.createElement(te,{color:jn.GRAY},e.size," tools selected"),0===e.size&&Q.createElement(te,{color:jn.GRAY},"No tools selected")))},"ToolsSelector");Rr(),Xy(),Wy(),Ds(),ak(),xr();var H_=__name(({onComplete:e})=>{const[t,n]=K("location"),[r,s]=K(!1),[o,i]=K(null),[a,l]=K("agentType"),u=X(()=>[...jv.map(e=>e.name),...Bv.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,g]=K(d()),h=__name(t=>{n("location"),l("agentType"),g(d()),e(t)},"resetToDefaults"),f=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===a)return"Agent type (identifier)";if("sysPrompt"===a)return"System prompt";if("ccToolDefinition"===a)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),y=__name(e=>{g({...m,location:e}),n("method")},"handleLocationSelect"),w=__name(e=>{g({...m,method:e}),n("configuration")},"handleMethodSelect"),S=__name(async()=>{try{i(null),s(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced(),{token:r,oauthProvider:o}=await getOAuthCredentials({provider:e});validateOAuthToken({token:r,provider:e});const a={[Ct.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(a[Ct.OAUTH_TOKEN]=`Bearer ${r}`,o&&(a[Ct.OAUTH_PROVIDER]=o));const l=getApiBaseUrl(),u=new xy({baseUrl:l}),d=parseModelString(getConfiguredModel()).modelId,h=await u.post({headers:a,endpoint:kt.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:d}});g({...m,agentType:Le(h.agentName),sysPrompt:h.systemPrompt,ccToolDefinition:h.toolDescription}),n("tools")}catch(e){if(e instanceof _s&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")){const e=await getBillingLink({billingLink:null,setBillingLink:__name(()=>{},"setBillingLink")})??"https://commandcode.ai/settings/billing";i(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: ${e}`)}else i("An error occurred while generating the agent. Please try again.")}finally{s(!1)}},"handleRecommendedSubmit"),E=__name(()=>{g({...m,agentType:Le(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),v=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),C=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),T=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),g({...m,selectedTools:t})},"handleToggleTool"),_=__name(e=>{const t=[{name:"All tools",tools:u},{name:"Read-only tools",tools:u.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:u.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:u.filter(e=>"shell_command"===e)},{name:"Search tools",tools:u.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:u.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(m.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),g({...m,selectedTools:n})},"handleToggleCategory");return Q.createElement(ee,{flexDirection:"column",gap:1},Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.WHITE,bold:!0},"Create new agent"),Q.createElement(te,{color:jn.GRAY},f())),Q.createElement(ee,null,"location"===t&&Q.createElement(O_,{onSelect:y}),"method"===t&&Q.createElement(q_,{onSelect:w}),"configuration"===t&&"recommended"===m.method&&Q.createElement(W_,{description:m.recommendedMethodDescription,onChange:e=>g({...m,recommendedMethodDescription:e}),loading:r,errorMessage:o,onSubmit:S}),"configuration"===t&&"manual"===m.method&&Q.createElement(ee,{flexDirection:"column",gap:1},Q.createElement(F_,{step:a,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>g({...m,agentType:e}),onSysPromptChange:e=>g({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>g({...m,ccToolDefinition:e}),onAgentTypeSubmit:E,onSysPromptSubmit:v,onCCToolDefinitionSubmit:C})),"tools"===t&&Q.createElement(G_,{selectedTools:m.selectedTools,onToggleTool:T,onToggleCategory:_,onComplete:k}),"summary"===t&&Q.createElement(M_,{config:m,onSaveComplete:h})))},"AgentNew");dr();var Q_=__name(({onCancel:e})=>{const[t,n]=K(null),[r,s]=K(null),o=__name(e=>{n(e.value),s(null)},"handleSelect");return se((t,n)=>{n.escape&&e()}),Q.createElement(ee,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:jn.GRAY,borderStyle:"single",flexDirection:"column"},null===t&&Q.createElement(D_,{handleSelect:o,createdAgentName:r}),"create_new_agent"===t&&Q.createElement(H_,{onComplete:e=>{s(e),n(null)}}))},"AgentsConfig");dr(),Ht(),xr(),dr();var V_=[{label:"Compact Normal (default)",value:"default",description:"Summarize session when context limit reached."},{label:"Compact Fast",value:"fast",description:"Fast tiered compaction. Higher quality, uses more tokens."}],K_=__name(({onSelect:e,onCancel:t})=>{const[n,r]=K(null);J(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const s=__name(t=>{e(t.value)},"handleSelect");if(se((e,n)=>{n.escape&&t()}),null===n)return null;const o=V_.findIndex(e=>e.value===n);return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ee,null,Q.createElement(te,{color:Bn,bold:!0},"Select a compact mode to compact sessions")),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM},"Choose how Command Code handles automatic context compaction.")),Q.createElement(tt,{items:V_,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.CYAN},e?ke.pointer:" "),itemComponent:({isSelected:e,label:t})=>{const r=V_.find(e=>e.label===t),s=r?.value===n,o=V_.findIndex(e=>e.label===t);return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{color:e?jn.CYAN:s?jn.GREEN:jn.WHITE},` ${o+1}. ${r?.label??t}`),s&&Q.createElement(te,{color:jn.GREEN}," ",ke.tick)),Q.createElement(te,{color:jn.DIM},` ${r?.description??""}`))}}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press "),Q.createElement(te,{color:jn.DIM,bold:!0},"Esc"),Q.createElement(te,{color:jn.DIM}," to cancel")))},"CompactModeSelector");Ht(),dr(),Ht(),gr(),Kt(),yr(),kn(),Ht();var Y_=n(S(),"commandcode-images"),J_={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{C(Y_)||T(Y_,{recursive:!0});const r=J_[e.mediaType]||".png",s=`image-${t}-${Date.now()}${r}`,o=n(Y_,s),i=Buffer.from(e.data,"base64");return _(o,i),o}catch{return null}}function accumulateDelta(e,t,n){const r=n+t;return e===t||e===r?t:r&&e.startsWith(r)?t+e.slice(r.length):t&&e.startsWith(t)?t+e.slice(t.length):t+e}function useBracketedPaste(e){const{input:t,detectedContent:n,setInput:r,setDetectedImages:s,setDetectedContent:o,incrementInputKey:i}=e,a=Z((e,t)=>{s(t=>[...t,e]),r(t),i()},[s,r,i]),l=Y(!1),u=Y(""),d=Y(null),m=Y(""),g=Z(async(e,t)=>{let s=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const l=await detectDroppedImageFile(s);if(l)return void a(l,t);const u=await detectClipboardImage();if(u)return void a(u,t);let d=s;if(!d.trim()){const e=await detectClipboardText();d=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(d){if(d.length>300){const e=`[Text#${n.length+1}]`;o(e=>[...e,d]),r(t+e)}else r(t+d);i()}},[a,n.length,o,r,i]),h=Z(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(async()=>{if(l.current){const e=u.current,t=m.current;u.current="",m.current="",l.current=!1,d.current=null,e&&await g(e,t)}},500)},[g]);return{handlePaste:Z(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return l.current&&(l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)),await g(n.pastedContent??n.cleanedContent,n.textBeforePaste??""),!0;if(n.isPasteStart&&!l.current)return l.current=!0,m.current=n.textBeforePaste??t,u.current=n.pastedContent??n.cleanedContent,h(),!0;if(l.current&&!n.isPasteEnd)return void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current)),h(),!0;if(l.current&&n.isPasteEnd){d.current&&(clearTimeout(d.current),d.current=null),void 0!==n.pastedContent?u.current=n.pastedContent:n.cleanedContent&&(u.current=accumulateDelta(n.cleanedContent,u.current,m.current));const e=u.current,t=m.current;return u.current="",m.current="",l.current=!1,await g(e,t),!0}if(n.isPasteEnd&&!n.isPasteStart&&!l.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return a(e,t),!0}return!1},[t,g,h,a]),resetPasteState:Z(()=>{l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:Z(()=>l.current,[])}}__name(saveTempImage,"saveTempImage"),Mn(),Rr(),Ht(),vr(),yr(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),vr(),Ht(),Ht();var X_=["code --wait","cursor --wait","nano"],Z_=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return Z_.some(e=>n===e||n.endsWith(`/${e}`))?t.some(e=>"--wait"===e||"-w"===e)?e:`${n} --wait ${t.slice(1).join(" ")}`.trim():e}function isCommandAvailable(e){try{const t=e.split(" ")[0],n="win32"===process.platform?"where":"command -v";return $(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of X_)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var ex=class extends Error{static{__name(this,"NoEditorError")}constructor(){super("No editor configured"),this.name="NoEditorError"}};async function openInEditor2(e){let t=process.env.EDITOR||process.env.VISUAL||null;if(!t&&("true"===process.env.COMMAND_CODE_DISABLE_EDITOR_FALLBACK||(t=findFallbackEditor()),!t))throw new ex;t=ensureWaitFlag(t);const r=n(S(),`commandcode-${Date.now()}.md`);return await q(r,e),new Promise((e,n)=>{const s=t.split(" ").filter(e=>e.length>0),o=s[0],i=s.slice(1),a=M(o,[...i,r],{stdio:"inherit"});a.on("close",async()=>{try{const t=await j(r,"utf-8");await B(r),e(t.trimEnd())}catch(e){n(e)}}),a.on("error",async e=>{try{await B(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[s,o]=K(!1),[i,a]=K(null),l=Z(async()=>{if(!s){o(!0),a(null);try{const s=e.replace(/\n+$/,""),o=await openInEditor2(s);t(o),n(e=>e+1),r?.()}catch(e){a(e instanceof ex?"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/core-concepts/interactive-mode#setting-up-your-editor":`Editor error: ${e instanceof Error?e.message:String(e)}`)}finally{o(!1)}}},[e,t,r,s]),u=Z(()=>{a(null)},[]);return{isEditorOpen:s,editorError:i,handleOpenInEditor:l,clearEditorError:u}}__name(function getNoEditorMessage(){return"No text editor found. Set your EDITOR environment variable.\n\nSee: https://commandcode.ai/core-concepts/interactive-mode#setting-up-your-editor"},"getNoEditorMessage"),__name(openInEditor2,"openInEditor"),__name(useExternalEditor,"useExternalEditor"),Ht();var tx=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=K(null),s=Y(!1);return J(()=>{if(!t||s.current)return;let e=!0;return s.current=!0,Gk().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function loadGitignore(e){const t=at(),r=n(e,".gitignore");if(C(r))try{const e=k(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}dr(),Ht(),dr(),__name(loadGitignore,"loadGitignore");var nx=__name(({onSelectFile:e,onClose:t,searchQuery:s=""})=>{const[a,l]=K(process.cwd()),[u,d]=K([]),[m,g]=K(0),[h,f]=K(0),y=s.trim()?15:10,w=Z((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const s=n(t,e);try{const e=x(s),i=[];return e.forEach(e=>{const a=n(s,e);try{const e=P(a),n=o(t,a);if(r.ignores(n))return;i.push({name:n,path:a,isDirectory:e.isDirectory()})}catch{}}),i.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),i.slice(0,50)}catch{}}if(e.includes("/")){const s=e.split("/"),i=s.pop()||"",a=n(t,s.join("/"));try{const e=x(a),s=[],l=i.toLowerCase();return e.forEach(e=>{const u=e.toLowerCase();if(!i||u.includes(l)){const i=n(a,e);try{const e=P(i),n=o(t,i);if(r.ignores(n))return;s.push({name:n,path:i,isDirectory:e.isDirectory()})}catch{}}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),s.slice(0,50)}catch{}}const s=[],i=e.toLowerCase(),a=__name((e,l=0)=>{if(!(l>8))try{x(e).forEach(u=>{const d=n(e,u);try{const e=P(d),n=o(t,d);if(r.ignores(n))return;const m=n.toLowerCase();(u.toLowerCase().includes(i)||m.includes(i))&&s.push({name:n,path:d,isDirectory:e.isDirectory()}),e.isDirectory()&&"node_modules"!==u&&a(d,l+1)}catch(e){}})}catch(e){}},"searchRecursively");return a(t),s.sort((e,t)=>{const n=e.name.toLowerCase(),r=t.name.toLowerCase(),s=n===i,o=r===i;if(s&&!o)return-1;if(!s&&o)return 1;const a=n.split("/").pop()||"",l=r.split("/").pop()||"",u=a.includes(i),d=l.includes(i);if(u&&!d)return-1;if(!u&&d)return 1;const m=e.name.split("/").length,g=t.name.split("/").length;return m!==g?m-g:e.name.localeCompare(t.name)}),s.slice(0,50)},[]),S=Z(e=>{try{const t=x(e),s=[],i=process.cwd(),a=loadGitignore(i);"/"!==e&&s.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=n(e,t);try{const e=P(r),n=o(i,r);if(a.ignores(n))return;s.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),s.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(s),g(0),f(0)}catch{}},[]);J(()=>{if(s.trim()){const e=w(s);d(e),g(0),f(0)}else S(a)},[a,S,s,w]),se((n,r)=>{if(r.escape)t();else if(r.upArrow)g(e=>{const t=Math.max(0,e-1);return t<h&&f(t),t});else if(r.downArrow)g(e=>{const t=Math.min(u.length-1,e+1);return t>=h+y&&f(t-y+1),t});else{if(r.rightArrow){const e=u[m];if(!e)return;return void(e.isDirectory&&!s.trim()&&l(i(e.path)))}if(r.return){const t=u[m];if(!t)return;return void e(t.path)}}});const E=u.slice(h,h+y);return Q.createElement(ee,{flexDirection:"column",paddingLeft:1},Q.createElement(ee,{marginBottom:1,flexDirection:"column"},Q.createElement(te,{color:jn.DIM},s.trim()?`Searching for: "${s}"`:`Files: ${a}`),Q.createElement(te,{color:jn.DIM},s.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===E.length?Q.createElement(te,{color:jn.DIM},s.trim()?`No files found matching "${s}"`:"No files found in this directory"):E.map((e,t)=>{const n=h+t,r=e.name,s=n===m;return Q.createElement(te,{key:e.path,color:s?jn.GREEN:jn.DIM},e.isDirectory?`${r}/`:r)}))},"FileList");Ht(),Kt(),Nr(),dr(),Ht(),dr();var rx=__name(({usage:e})=>{if(!e)return null;const t=Math.min(e.current/e.limit*100,100),n=Math.max(0,Math.round(90-t));if(n>20)return null;const r=__name(e=>e>=90?jn.RED:e>=70?jn.YELLOW:jn.DIM,"getColor"),s=t>=90?6:Math.round(t/100*6),o=6-s,i=ke.square.repeat(s),a=ke.squareLightShade.repeat(o),l=r(t);return Q.createElement(ee,{paddingRight:3},Q.createElement(te,{color:l},`Context left before auto-compact ${n}% `),Q.createElement(te,{color:l},i),o>0&&Q.createElement(te,{color:jn.DIM},a))},"ContextUsage");Ht(),tC(),hs(),dr();var sx=__name(()=>{const[e,t]=K("continuous learning"),[n,r]=K(!1),[s,o]=K(!1),i=Y([]),a=Y(0),l=Y(null),u=Y(!1);J(()=>{const e=__name(e=>"analyzing"===e.type?(u.current=!0,r(!0),o(!1),i.current=[],a.current=0,l.current&&(clearTimeout(l.current),l.current=null),void t(e.message)):u.current&&"analyzed"!==e.type?void i.current.push(e):"analyzed"===e.type?(u.current=!1,void(i.current.length>0?(a.current=0,n()):(r(!1),o(!1),t("continuous learning")))):void 0,"handleNewEvent"),n=__name(()=>{if(a.current>=i.current.length)return r(!1),o(!1),t("continuous learning"),void(i.current=[]);const e=i.current[a.current];t(e.message);const s="learned"===e.type||"refactored"===e.type;o(s);const u="learned"===e.type||"refactored"===e.type||"no_learnings"===e.type||"error"===e.type?15e3:2e3;l.current=setTimeout(()=>{a.current++,n()},u)},"cycleThroughNextEvent");return Zv.on("new-event",e),()=>{Zv.off("new-event",e),l.current&&clearTimeout(l.current)}},[]);const d=` ${n?ke.squareSmallFilled:ke.squareSmall} TASTE`,m=9+e.length+d.length>os;let g=e;g=truncateString(m?{text:e,maxChars:os}:{text:e,maxChars:os-d.length-9-10});const h=s?void 0:jn.DIM;return Q.createElement(ee,{paddingRight:2},!m&&Q.createElement(Q.Fragment,null,Q.createElement(BracketWrap,{color:jn.DIM},"ctrl+t"),Q.createElement(te,{color:jn.DIM}," ")),Q.createElement(te,{color:h},g),!m&&Q.createElement(te,{color:Un.TEXT},d))},"LearningFeedMini");Ht(),dr();var ox=__name(({mode:e,pendingExitKey:t})=>t?Q.createElement(te,{color:jn.DIM},"Press Ctrl+C again to exit"):"auto-accept"===e?Q.createElement(ee,{flexDirection:"row"},Q.createElement(te,{color:tr},"» accept edits on "),Q.createElement(BracketWrap,{color:jn.DIM},"shift+tab")):"plan"===e?Q.createElement(ee,{flexDirection:"row"},Q.createElement(te,{color:er},"plan mode "),Q.createElement(BracketWrap,{color:jn.DIM},"shift+tab")):Q.createElement(te,{color:jn.DIM},"? for shortcuts"),"ModeIndicator");Ht(),dr(),Pr();var ix=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?jn.DIM:nr.MERGED;return Q.createElement(Q.Fragment,null,t&&Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{color:n},"PR "),Q.createElement(Cr,{url:e.url,text:`#${e.number}`,color:n}))},"PRLinkBadge"),ax=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?Q.createElement(Q.Fragment,null,t&&Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{color:"connected"===e.type?jn.GREEN:jn.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),lx=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:s,tasteLearning:o,contextUsage:i,connectionIndicator:a,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:g,isBashMode:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E})=>{const v=e>=60;return Q.createElement(Q.Fragment,null,Q.createElement(ee,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r||l?Q.createElement(ee,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(ee,{flexDirection:"row",columnGap:0},n&&!l?Q.createElement(te,{color:Yn},t):Q.createElement(ox,{mode:r,pendingExitKey:l}),!l&&Q.createElement(ix,{prInfo:s}),!l&&Q.createElement(ax,{indicator:a})),v&&Q.createElement(ee,{flexDirection:"column",alignItems:"flex-end"},o&&Q.createElement(sx,null),i&&Q.createElement(rx,{usage:i}))):Q.createElement(Q.Fragment,null,Q.createElement(ee,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(ox,{mode:r}),v&&o&&Q.createElement(sx,null)),Q.createElement(ee,{flexDirection:"row",justifyContent:"space-between",width:e-1},Q.createElement(ee,{flexDirection:"row",columnGap:0},Q.createElement(te,{color:n?Yn:jn.DIM},t),Q.createElement(ix,{prInfo:s}),Q.createElement(ax,{indicator:a})),v&&i&&Q.createElement(rx,{usage:i}))),(u||d||g&&m)&&Q.createElement(ee,{flexDirection:"row",columnGap:1},u&&Q.createElement(te,null,ke.tick," ","Command Code"," updated:"," ",Q.createElement(te,{color:jn.DIM},"v",u.updatedFrom),Q.createElement(te,{color:jn.DIM}," ",ke.arrowRight," "),Q.createElement(te,null,"v",u.updatedTo)),!u&&d&&Q.createElement(te,{color:jn.YELLOW,dimColor:!0},ke.info," Update available:"," ",d.currentVersion," ",ke.arrowRight," ",d.latestVersion),g&&m&&Q.createElement(te,{color:jn.GREEN,dimColor:!0},ke.bullet," Provider:"," ",getProviderDisplayName(m)))),h&&Q.createElement(ee,{paddingLeft:2},Q.createElement(te,{color:jn.GREEN},"! for bash mode")),y&&f&&Q.createElement(ee,{paddingLeft:2},Q.createElement(te,{color:Bn},"SHARED: ",f.url," (copied to clipboard)")),w&&Q.createElement(ee,{paddingLeft:2},Q.createElement(te,{color:w.includes("NOT SHARED")?jn.RED:Bn},w)),S&&Q.createElement(ee,{paddingLeft:2},Q.createElement(te,{color:Bn},S)),E&&Q.createElement(ee,{paddingLeft:2},Q.createElement(te,{color:jn.YELLOW},ke.warning," ",E)))},"BottomIndicator");Ht(),vv(),hs(),dr();var cx=12,ux=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),s=Math.floor(n/36e5),o=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:s<24?`${s}h ago`:`${o}d ago`},"formatRelativeTime"),dx=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),mx=__name(e=>truncateString({text:dx(e),maxChars:ss}),"truncateMessage"),px=__name(e=>e.title?dx(e.title):mx(e.firstMessage),"getSessionSummary"),gx=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=K([]),[s,o]=K(0),[i,a]=K(0),[l,u]=K(!0),[d,m]=K(!1),[g]=K(()=>getCurrentGitBranch());J(()=>{__name(async()=>{u(!0);const e=await hv.listSessions();r(e),u(!1)},"loadSessions")()},[]);const h=d&&g?n.filter(e=>e.gitBranch===g):n;if(se((n,r)=>{if(!r.escape)return r.ctrl&&"b"===n?(m(e=>!e),o(0),void a(0)):void(r.upArrow?o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):r.downArrow?o(e=>{const t=Math.min(h.length-1,e+1);return t>=i+cx&&a(t-cx+1),t}):r.return&&h.length>0&&s<h.length&&e(h[s].id));t()}),l)return Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Q.createElement(te,{color:jn.GRAY},"Loading sessions..."));if(0===h.length)return Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Q.createElement(te,{color:jn.GRAY},d&&g?`No sessions found for branch "${g}"`:"No previous sessions found"),Q.createElement(te,{color:jn.DIM},d?"Press ctrl+b to show all branches, ESC to cancel":"Press ESC to go back"));const f=h.slice(i,i+cx);return Q.createElement(ee,{flexDirection:"column",paddingLeft:1,width:"100%"},Q.createElement(te,{color:jn.CYAN,bold:!0},"Resume Session"),Q.createElement(ee,{marginTop:1}),Q.createElement(ee,{columnGap:2,marginBottom:1},Q.createElement(ee,{width:5},Q.createElement(te,{color:jn.GRAY}," ")),Q.createElement(ee,{width:13},Q.createElement(te,{color:jn.GRAY},"Modified")),Q.createElement(ee,{width:20},Q.createElement(te,{color:jn.GRAY},"Git Branch")),Q.createElement(ee,{width:11},Q.createElement(te,{color:jn.GRAY},"# Messages")),Q.createElement(ee,null,Q.createElement(te,{color:jn.GRAY},"Summary"))),Q.createElement(ee,{columnGap:2},Q.createElement(ee,{flexDirection:"column",width:5},f.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:`sel-${n}`,color:s===n?jn.WHITE:jn.GRAY},s===n?`${ke.pointer} ${n+1}.`:` ${n+1}.`)})),Q.createElement(ee,{flexDirection:"column",width:13},f.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:`mod-${e.id}`,color:s===n?jn.WHITE:jn.GRAY},ux(e.lastModified))})),Q.createElement(ee,{flexDirection:"column",width:20},f.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:`branch-${e.id}`,color:s===n?jn.WHITE:jn.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),Q.createElement(ee,{flexDirection:"column",width:11},f.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:`msg-${e.id}`,color:s===n?jn.WHITE:jn.GRAY},e.messageCount)})),Q.createElement(ee,{flexDirection:"column"},f.map((e,t)=>{const n=i+t;return Q.createElement(te,{key:`summary-${e.id}`,color:s===n?jn.WHITE:jn.GRAY,wrap:"truncate-end"},px(e))}))),Q.createElement(ee,{marginTop:1}),h.length>cx&&Q.createElement(te,{color:jn.DIM},"Showing ",i+1,"–",Math.min(i+cx,h.length)," ","of ",h.length,i>0?" · ↑ more":"",i+cx<h.length?" · ↓ more":""),Q.createElement(te,{color:jn.DIM},"↑↓ navigate · Enter select · ctrl+b ",d?`[branch: ${g??"unknown"}]`:"branch filter"," · ESC cancel"))},"SessionsResumeTable");function getImageHintText({selectedIndex:e,imageCount:t,inHistory:n}){return-1!==e?t>1?"← → · Delete to remove · Esc to deselect":"Delete to remove · Esc to deselect":n?"↓ · ↑ imgs":"↑ to select"}function buildImageRows({imageCount:e,rowWidth:t}){const n=[];let r=[],s=0;for(let o=0;o<e;o++){const e=`[Image #${o+1}]`.length,i=e+(r.length>0?1:0);r.length>0&&s+i>t?(n.push(r),r=[o],s=e):(r.push(o),s+=i)}return r.length>0&&n.push(r),n}function shouldSelectImageOnUpArrow({isOnFirstLine:e,imageCount:t,selectedImageIndex:n,historyIndex:r}){return e&&t>0&&-1===n&&-1===r}function nextImageIndex({currentIndex:e,imageCount:t}){return e===t-1?0:e+1}function prevImageIndex({currentIndex:e,imageCount:t}){return 0===e?t-1:e-1}function removeImageAt({images:e,index:t}){const n=e.filter((e,n)=>n!==t);return{remainingImages:n,nextSelectedIndex:n.length>0?n.length-1:-1}}function ImageLabel({index:e,isSelected:t,filePath:n,showSpaceBefore:r}){const s=`[Image #${e+1}]`,o=n?createOSC8Link(`file://${n}`,s,!1):s;return Q.createElement(te,null,r?" ":"",t?Q.createElement(te,{inverse:!0},s):o)}function ImageRowsDisplay({detectedImages:e,selectedImageIndex:t,imageTempPaths:n,termWidth:r,inHistory:s}){if(0===e.length)return null;const o=getImageHintText({selectedIndex:t,imageCount:e.length,inHistory:s}),i=Math.max(1,r-(o.length+2)),a=buildImageRows({imageCount:e.length,rowWidth:i});return Q.createElement(ee,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>Q.createElement(ee,{key:r,flexDirection:"row"},Q.createElement(ee,{flexShrink:0,marginRight:1},0===r&&Q.createElement(te,{color:jn.DIM},o)),Q.createElement(ee,{flexDirection:"row"},e.map((e,r)=>Q.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Ht(),dr(),Ht(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),LC(),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Ht(),_b();var hx=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,s]=K(null),[o,i]=K(!1),a=Y(!1),l=Y(null),[u,d]=K(!1),[m,g]=K("connected"),h=Y(null),f=Y(null),y=Z((e,t)=>{f.current&&(clearTimeout(f.current),f.current=null),g(e),d(!0),void 0!==t&&(f.current=setTimeout(()=>{d(!1)},t))},[]),w=Z(()=>{f.current&&(clearTimeout(f.current),f.current=null)},[]),S=Z(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new wb,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=h.current;if(null===r?n&&y("connected",3e3):r!==n&&(n?y("connected",2e3):y("disconnected",5e3)),h.current=n,i(n),n&&t){const n=e?500:1e3,r=await t.getContext(n);null!==r||t.isConnected||(t.disconnect(),l.current=null),s(r)}else s(null)}catch{!0===h.current&&y("disconnected",5e3),h.current=!1,i(!1),s(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[y]);J(()=>{if(!t||n)return;S(!0);const e=setInterval(()=>S(!1),500);return()=>{clearInterval(e),w(),l.current?.disconnect(),l.current=null}},[t,n,S,w]);const E={visible:u,message:"connected"===m?`IDE ${ke.tick}`:"IDE disconnected",type:m};return{context:r,connected:o,refresh:S,connectionIndicator:E}},"useVSCodeContext");Ht();var fx=__name(e=>{if(!e.activeFile&&!e.selection)return"";const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:s}=e.activeFile;t.push(`File: ${n} (${r}, line ${s.line})`)}if(e.selection){const{text:n,startLine:r,endLine:s}=e.selection,o=e.activeFile?.language??"";t.push(`Selected lines ${r}-${s}:`),t.push(`\`\`\`${o}`);const i=n.replace(/```/g,"` ` `").replace(/<\/ide-context>/gi,"&lt;/ide-context&gt;");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");Ht();var yx=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),wx=__name((e,t,n)=>{const r=e?t?.selection:null;if(r)return`${r.lineCount} lines selected`;const s=e?t?.activeFile:null;if(s?.relativePath){const e=s.relativePath.split("/").pop()||"",t=n<80?15:n<120?25:40;return`In ${e.length>t?e.slice(0,t-1)+"…":e}`}return"? for shortcuts"},"getIndicatorText"),Sx=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isPrecededByWhitespace,"isPrecededByWhitespace");var bx=__name(()=>Q.createElement(ee,{flexDirection:"column",paddingLeft:1},Q.createElement(te,{color:jn.DIM,bold:!0},"Available Shortcuts:"),Q.createElement(ee,{columnGap:4},Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.DIM},"! for bash mode"),Q.createElement(te,{color:jn.DIM},"/ for commands"),Q.createElement(te,{color:jn.DIM},"@ for file paths"),Q.createElement(te,{color:jn.DIM},"shift + tab to toggle auto-accept")),Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.DIM},"double tap esc to clear input"),Q.createElement(te,{color:jn.DIM},"ctrl + j / shift + ⏎ for newline"),Q.createElement(te,{color:jn.DIM},"ctrl + g to open in editor"),Q.createElement(te,{color:jn.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),Ex=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:s="Enter your input…",showFileList:i,setShowFileList:a,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:m,tasteLearning:g=!1,tasteUsage:h=!1,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:T,permissionMode:_="standard",onToggleAutoAccept:x,hintMessage:P,historyManager:A,pendingExitKey:I=null,onOverlayVisibilityChange:N,onDoubleEscapeEmpty:R,onAltP:$,isProcessing:M=!1,ideContextEnabled:L=!0})=>{const[D,O]=K(0),[F,q]=K(!1),[j,B]=K(!1),[U,z]=K(!1),[W,G]=K(!1),[H,V]=K(""),[ne,oe]=K(!1),ie=Y(0),ae=Y(0),[le,ce]=K([]),[ue,de]=K([]),[me,pe]=K(-1),[ge,he]=K(""),fe=Y(!1),ye=Y(!1),we=Y(void 0),[Se,be]=K(-1),[Ee,ve]=K(""),Ce=Y(0),{isEditorOpen:Te,editorError:_e,handleOpenInEditor:xe,clearEditorError:Pe}=useExternalEditor({input:e,setInput:n,setInputKey:O,onEditorClose:__name(()=>{fe.current=!1},"onEditorClose")}),{handlePaste:Ae,resetPasteState:Ie,isPasting:Ne}=useBracketedPaste({input:e,detectedContent:le,setInput:n,setDetectedImages:de,setDetectedContent:ce,incrementInputKey:__name(()=>O(e=>e+1),"incrementInputKey")}),{context:Re,connected:$e,refresh:Me,connectionIndicator:Le}=hx({enabled:L,paused:M}),{stdout:De}=re(),Oe=De?.columns??80,{pr:Fe}=tx();J(()=>{const e=i||W||ne;N?.(e)},[i,W,ne,N]);const qe=Z(()=>{de([]),pe(-1)},[]),je=Z(()=>{n(""),B(!1),G(!1),V(""),oe(!1),ce([]),qe(),he(""),Ie(),be(-1),ve(""),O(e=>e+1)},[n,Ie,qe]),Be=Z(()=>{fe.current=!0;const{text:t,cursor:r}=insertTextAt(e,Ce.current,"\n");n(t),we.current=r,O(e=>e+1),setTimeout(()=>{fe.current=!1},0)},[e,n]);se(async(t,r)=>{if(-1!==me&&r.leftArrow)return void pe(prevImageIndex({currentIndex:me,imageCount:ue.length}));if(-1!==me&&r.rightArrow)return void pe(nextImageIndex({currentIndex:me,imageCount:ue.length}));if(r.upArrow){if(i||W||ne)return;const t=e.indexOf("\n"),r=-1===t||Ce.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:ue.length,selectedImageIndex:me,historyIndex:Se}))return void pe(ue.length-1);if(-1!==me&&pe(-1),0!==e.length&&-1===Se&&!r)return;const s=A?.count()??0;if(0===s)return;-1===Se&&ve(e);const o=Math.min(Se+1,s-1);return void(o!==Se&&(be(o),n(A?.getAt(o)||""),O(e=>e+1)))}if(r.downArrow){if(i||W||ne)return;if(-1===Se)return;const t=e.lastIndexOf("\n");if(!(-1===t||Ce.current>t))return;const r=Se-1;return be(r),n(-1===r?Ee:A?.getAt(r)||""),void O(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void qe();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return fe.current=!0,void xe();if(getIsExpandToolShortcut(r,t))return fe.current=!0,n(e),O(e=>e+1),void setTimeout(()=>{fe.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Ne()}))return ye.current=!0,Be(),void setTimeout(()=>{ye.current=!1},0);if(r.meta&&r.backspace)return void je();if(r.meta&&"w"===t)return fe.current=!0,void je();const s=r.ctrl&&"v"===t||Sx.includes(t),o=r.meta&&"v"===t;if(s||o){if(s&&"darwin"===process.platform){const t=e;fe.current=!0;const r=await detectClipboardImage();return r&&(de(e=>[...e,r]),n(t),O(e=>e+1)),void(fe.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return z(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==me&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:ue,index:me});return de([...e]),void pe(t)}if(r.escape){if(-1!==me)return void pe(-1);if(W)return;if(ne)return oe(!1),n(ge),void O(e=>e+1);const t=Date.now();return t-ie.current<500?(e.length>0?je():R?.(),ie.current=0,ae.current=0):(ie.current=t,F||j||(ae.current=t)),q(!1),void B(!1)}F&&(r.backspace||r.delete)&&0===e.length&&q(!1)}});const Ue=Z(async t=>{if(Te)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void $?.();const s=processBracketedPaste(t);if((s.isPasteStart||s.isPasteEnd||Ne())&&await Ae(t))return;if(fe.current)return void(fe.current=!1);-1!==Se&&be(-1);const o=1===t.length,l=t.slice(-1);if(o){if("?"===l&&!F)return q(!0),n(""),void O(e=>e+1);if("!"===l&&!j)return q(!1),B(!0),n(""),void O(e=>e+1)}if("/"!==l||W||"/"!==t||(G(!0),V("")),W&&!t.startsWith("/")&&(G(!1),V("")),W&&t.startsWith("/")){const e=t.substring(1);e.includes(" ")?(G(!1),V("")):V(e)}"@"!==l||i||isPrecededByWhitespace(t.length>1?t[t.length-2]:"")&&(a(!0),u(""));const d=t.lastIndexOf("@");if(t.length<e.length&&-1!==d&&" "===e.charAt(e.length-1)&&" "!==t.charAt(t.length-1)){const e=t.substring(d+1),n=!e.includes(" "),r=d>0?t[d-1]:"";n&&isPrecededByWhitespace(r)&&(a(!0),u(e))}if(i)if(t.length<e.length){const e=t.lastIndexOf("@");if(-1===e)a(!1),u("");else{const n=t.substring(e+1);u(n)}}else{const e=t.lastIndexOf("@");if(-1!==e){const n=t.substring(e+1),r=n.indexOf(" ");if(-1!==r){const e=n.substring(0,r);u(e),a(!1)}else u(n)}}F&&(t!==e||t.length<e.length)&&q(!1),_e&&Pe(),0===t.length&&(B(!1),G(!1),V(""),oe(!1),ce([]),u(""),he(""),Ie()),n(t)},[F,e,n,i,a,W,j,ue,Se,Ae,Ie,$,_e,Pe,Te]),ze=Z(async()=>{if(Me(),ae.current=0,F)return void q(!1);let n=e.trim();if(!j&&n.startsWith("/")&&d&&"handled"===(await d(n)).status)return A?.add(n),B(!1),G(!1),V(""),qe(),ce([]),be(-1),void ve("");be(-1),ve("");let r=[];const s=ue.length>0,o=le.length>0;if(!j&&s&&(r=[...ue]),!j&&o){let e=n;le.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}n.length>0&&A?.add(n),t({input:n,role:j?"bash":"user",images:r,ideContext:Re?fx(Re):void 0}),B(!1),G(!1),V(""),qe(),ce([])},[t,d,F,e,j,ue,le,A,Me,qe]),We=Z(t=>{const r=o(process.cwd(),t);let s;if(i&&""!==l){const t=e.lastIndexOf("@");s=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else s=`${e}${r} `;n(s),a(!1),u(""),O(e=>e+1)},[n,a,e,i,l,u]),Ge=Z(()=>{a(!1),u("")},[a,u]),He=Z(t=>{if("/resume"===t)A?.add(t),be(-1),ve(""),he(e),G(!1),V(""),oe(!0),n(""),O(e=>e+1);else{const e=Object.values(pT).includes(t);G(!1),V(""),e?(A?.add(t),be(-1),ve(""),n(""),O(e=>e+1),d&&d(t)):(n(t+" "),O(e=>e+1))}},[d,n,e,A]),Qe=Z(e=>{G(!1),V(""),n(e+" "),O(e=>e+1)},[n]),Ve=Z(()=>{G(!1),V(""),n(""),be(-1),ve(""),O(e=>e+1)},[n]),Ke=Z(e=>{oe(!1),n(""),he(""),be(-1),ve(""),O(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),Ye=Z(()=>{oe(!1),n(ge),be(-1),ve(""),O(e=>e+1)},[ge,n]),Je=Z(e=>{Ce.current=e,we.current=void 0},[]),Xe=X(()=>{const t=Fe&&("OPEN"===Fe.state||"MERGED"===Fe.state);return"auto-accept"===_||"plan"===_||$e||t?!F&&!ne:!F&&0===e.length&&!j&&!ne},[F,e,j,ne,_,$e,Fe]),Ze=Y(new Map),et=X(()=>ue.map((e,t)=>{if(Ze.current.has(e))return Ze.current.get(e)??null;const n=saveTempImage(e,t+1);return Ze.current.set(e,n),n}),[ue]),tt=__name(()=>F||i||W||ne||U?0:Xe||I||j?3:4,"getBottomMargin");return Q.createElement(ee,{width:"100%",flexDirection:"column",marginBottom:tt()},!ne&&Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(ImageRowsDisplay,{detectedImages:ue,selectedImageIndex:me,imageTempPaths:et,termWidth:Oe,inHistory:-1!==Se}),Q.createElement(te,{color:j?jn.GREEN:jn.GRAY},ke.line.repeat(Oe)),Q.createElement(TextInput,{key:D,value:e,placeholder:Te?"Save and close the editor to continue...":s,onChange:Ue,onSubmit:()=>{if(!ye.current)return Date.now()-ae.current<100?(ae.current=0,void Be()):void(i||W||ne||Te||ze());ye.current=!1},showCursor:!Te&&r&&-1===me,onCursorChange:Je,initialCursor:we.current,prefix:`${j?"!":ke.pointer} `,prefixColor:j?jn.GREEN:jn.WHITE}),Q.createElement(te,{color:j?jn.GREEN:jn.GRAY},ke.line.repeat(Oe))),F&&Q.createElement(bx,null),U&&Q.createElement(ee,{paddingTop:1},Q.createElement(te,{color:jn.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&Q.createElement(nx,{onSelectFile:We,onClose:Ge,searchQuery:l}),W&&Q.createElement(fT,{onSelectCommand:He,onInsertCommand:Qe,onClose:Ve,searchQuery:H}),ne&&Q.createElement(gx,{onSelectSession:Ke,onClose:Ye}),!W&&(Xe||I)&&Q.createElement(lx,{termWidth:Oe,indicatorText:wx($e,Re,Oe),isIDEIndicator:yx($e,Re),permissionMode:_,prInfo:Fe,tasteLearning:g,contextUsage:m,connectionIndicator:Le,pendingExitKey:I,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:T,isBashMode:j,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E}),_e&&Q.createElement(ee,{paddingLeft:1,flexDirection:"column"},Q.createElement(te,{color:jn.YELLOW},_e)))},"InputBox");Ht(),hs(),dr();var vx=__name(({messages:e})=>0===e.length?null:Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ee,{marginBottom:0},Q.createElement(te,{color:Wn,inverse:!0},` Queued (${e.length}) `)),e.map((e,t)=>Q.createElement(ee,{key:t},Q.createElement(te,{color:jn.DIM},ke.pointerSmall," "),Q.createElement(te,{color:jn.DIM},truncateString({text:e.displayMessage??e.input,maxChars:80}))))),"QueuedMessages"),Cx=Q.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:s,setInput:o,onSubmit:i,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:g=0,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,showProviderInfo:x,permissionMode:P,onToggleAutoAccept:A,hintMessage:I,historyManager:N,pendingExitKey:R,onResetPendingExitKey:$,onDoubleEscapeEmpty:M,retryAttempt:L,onAltP:D})=>{const[O,F]=K(0),q=Y(s);return J(()=>{R&&s!==q.current&&s.length>0&&$?.(),q.current=s},[s,R,$]),J(()=>{if(!t)return void F(0);const e=setInterval(()=>{F(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),Q.createElement(ee,{flexDirection:"column"},Q.createElement(vx,{messages:e}),Q.createElement(ee,{flexDirection:"row",justifyContent:"space-between"},Q.createElement(ee,{flexDirection:"column"},(t||n.isExecuting)&&null===L&&Q.createElement(z_,{tokens:g,timeElapsed:O,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),I&&Q.createElement(ee,{marginLeft:1},Q.createElement(te,{color:jn.DIM}," ","⎿"," ","Tip: ",I)))),Q.createElement(Ex,{input:s,setInput:o,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,showProviderInfo:x,permissionMode:P,onToggleAutoAccept:A,hintMessage:I,historyManager:N,pendingExitKey:!R||t||n.isExecuting?null:R,onDoubleEscapeEmpty:M,onAltP:D,isProcessing:t}))});Ht(),xC(),RC(),Ar(),Nr();var kx=__name(({onComplete:e,onCancel:t})=>{const[n,r]=K(!1),[s,o]=K(""),{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:g}=useAuthFlow({onSuccess:__name((t,n)=>{const s=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";o(s),isInternalTeamFlagEnforced()?r(!0):e(!0,s?`Logged in as ${s}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return se((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,s?`Logged in as ${s}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");g()}}),n?Q.createElement(kr,{onSuccess:()=>{e(!0,s?`Logged in as ${s} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,s?`Logged in as ${s}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,s?`Logged in as ${s}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):Q.createElement(AC,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");async function discoverOAuthMetadata(e){const t=new m(e),n=`${t.protocol}//${t.host}`;try{const e=`${n}/.well-known/oauth-authorization-server`,t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const e=await t.json();if(e.authorization_endpoint&&e.token_endpoint)return{authorizationEndpoint:e.authorization_endpoint,tokenEndpoint:e.token_endpoint,registrationEndpoint:e.registration_endpoint,scopes:e.scopes_supported}}}catch(e){dlog("[MCP] OAuth discovery endpoint not available",e)}try{const e=`${n}/.well-known/openid-configuration`,t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const e=await t.json();if(e.authorization_endpoint&&e.token_endpoint)return{authorizationEndpoint:e.authorization_endpoint,tokenEndpoint:e.token_endpoint,registrationEndpoint:e.registration_endpoint,scopes:e.scopes_supported}}}catch(e){dlog("[MCP] OIDC discovery not available",e)}return null}async function checkServerAuthRequirements(e){try{const t=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",method:"initialize",id:0,params:{protocolVersion:Ub,capabilities:{},clientInfo:zb}})});return 401===t.status||403===t.status?{requiresAuth:!0,metadata:await discoverOAuthMetadata(e)||void 0}:{requiresAuth:!1}}catch(e){return{requiresAuth:!1,error:`Server unreachable: ${e instanceof Error?e.message:String(e)}`}}}async function registerOAuthClient({registrationEndpoint:e,clientName:t,redirectUris:n}){try{const r=await fetchWithTimeout(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:t,redirect_uris:n,token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"]})});if(r.ok){const e=await r.json();return{clientId:e.client_id,clientSecret:e.client_secret}}}catch(e){dlog("[MCP] OAuth client registration failed",e)}return null}Ht(),Ht(),eE(),Qb(),sE(),tE(),oE(),gE(),hE(),wE(),Ht(),hE(),wE(),Zb(),pE(),Ht(),lE(),Qb(),In(),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient"),dr();var Tx=__name(({onClose:e})=>{const[t,n]=K([]),[r,s]=K(!0),[o,i]=K(0),[a,l]=K("list"),[u,d]=K(null),m=Z(async()=>{s(!0);try{const e=await listMcpServers(),t=getMcpConnectionManager().getConnectedServers(),r=await Promise.all(e.map(async e=>{const n=t.find(t=>t.name===e.name);let r,s,o="disconnected";return!1===e.config.enabled?o="disabled":n&&"connected"===n.status?(o="connected",r=n.tools.length):n&&"error"===n.status?(o="error",s=n.error):e.config.oauth&&(o=await hasTokens(e.name)?"authenticated":"requires_auth"),{name:e.name,config:e.config,scope:e.scope,status:o,toolCount:r,error:s}}));n(r)}catch{}finally{s(!1)}},[]);J(()=>{m()},[m]);const g=X(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),h=g[o]??null;se((t,n)=>{if(n.ctrl&&"c"===t)e();else if(n.escape)"actions"===a||"confirm-remove"===a?(l("list"),d(null)):e();else if("list"===a){if(n.upArrow&&(i(e=>Math.max(0,e-1)),d(null)),n.downArrow){if(0===g.length)return;const e=Math.max(0,g.length-1);i(t=>Math.min(e,t+1)),d(null)}n.return&&h&&(l("actions"),d(null))}});const f=__name(e=>{switch(e){case"connected":return Q.createElement(te,{color:jn.GREEN},ke.tick);case"authenticated":return Q.createElement(te,{color:jn.CYAN},ke.tick);case"requires_auth":return Q.createElement(te,{color:jn.YELLOW},ke.warning);case"error":return Q.createElement(te,{color:jn.RED},ke.cross);default:return Q.createElement(te,{color:jn.GRAY},ke.circle)}},"getStatusIcon"),y=__name(e=>{switch(e.status){case"connected":return"connected"+(void 0!==e.toolCount?` · ${e.toolCount} tools`:"");case"authenticated":return"authenticated · not connected";case"requires_auth":return"requires authentication";case"error":return e.error||"error";case"disabled":return"disabled";default:return"not connected"}},"getStatusText"),w=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),S=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),E=__name(async e=>{if(h)if("back"!==e.value)if("connected"!==e.value)if("authenticated"!==e.value)if("connect"!==e.value)if("auth"!==e.value)if("remove"!==e.value)if("disable"!==e.value)if("enable"!==e.value);else{d({text:`Enabling ${h.name}...`,color:jn.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:h.name,enabled:!0,scope:h.scope}))return void d({text:`${ke.cross} Failed to enable ${h.name}, server may no longer exist in ${h.scope} scope`,color:jn.YELLOW});await m(),d({text:`${ke.tick} Enabled ${h.name}`,color:jn.GREEN})}catch(e){d({text:`${ke.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:jn.RED})}}else{d({text:`Disabling ${h.name}...`,color:jn.CYAN,loading:!0});try{const e=getMcpConnectionManager();if(!await updateMcpServerStatus({name:h.name,enabled:!1,scope:h.scope}))return void d({text:`${ke.cross} Failed to disable ${h.name}, server may no longer exist in ${h.scope} scope`,color:jn.YELLOW});await e.disconnectServer(h.name),await m(),d({text:`${ke.tick} Disabled ${h.name}`,color:jn.GREEN})}catch(e){d({text:`${ke.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:jn.RED})}}else l("confirm-remove");else{if(!h.config.oauth)return void d({text:"No OAuth configured for this server",color:jn.YELLOW});d({text:`Authenticating ${h.name}...`,color:jn.CYAN,loading:!0});try{const e={authorizationUrl:h.config.oauth.authorizationUrl,tokenUrl:h.config.oauth.tokenUrl,clientId:h.config.oauth.clientId,clientSecret:h.config.oauth.clientSecret,scopes:h.config.oauth.scopes},t=await performOAuthFlow(h.name,e,{onStatus:__name(()=>{},"onStatus")});if(t.success){d({text:`${ke.tick} Authenticated with ${h.name}`,color:jn.GREEN});try{const e=getMcpConnectionManager();await e.ensureServerConnection(h.name)}catch{}await m()}else d({text:`${ke.cross} Auth failed: ${t.error}`,color:jn.RED})}catch(e){d({text:`${ke.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:jn.RED})}}else{d({text:`Connecting ${h.name}...`,color:jn.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.ensureServerConnection(h.name),d({text:`${ke.tick} Connected to ${h.name}`,color:jn.GREEN}),await m()}catch(e){d({text:`${ke.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:jn.RED})}}else d({text:"Already authenticated",color:jn.GREEN});else d({text:"Already connected",color:jn.GREEN});else l("list")},"handleActionSelect"),v=__name(async e=>{if(h)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===h.status&&await e.disconnectServer(h.name),await removeMcpServer({name:h.name,scope:h.scope}),l("list"),await m(),i(e=>Math.min(e,Math.max(0,g.length-2)))}catch(e){d({text:`${ke.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:jn.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Bn,bold:!0},"Manage MCP servers"),Q.createElement(te,{color:jn.DIM},"Loading..."));if("confirm-remove"===a&&h)return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:jn.RED,bold:!0},"Remove ",h.name,"?"),Q.createElement(te,{color:jn.DIM},"This will remove the server from ",h.scope," config."),Q.createElement(ee,{marginTop:1},Q.createElement(tt,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:v,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY}," ",t)})),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&h){const e=[],t="disabled"===h.status,n="connected"===h.status,r="authenticated"===h.status||n;return t&&e.push({label:"Enable",value:"enable"}),!t&&n&&e.push({label:"Connected",value:"connected"}),t||n||e.push({label:"Connect",value:"connect"}),!t&&h.config.oauth&&r&&e.push({label:"Authenticated",value:"authenticated"}),t||!h.config.oauth||r||e.push({label:"Authenticate",value:"auth"}),t||e.push({label:"Disable",value:"disable"}),e.push({label:"Remove",value:"remove"}),e.push({label:"Back",value:"back"}),Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Bn,bold:!0},h.name),Q.createElement(ee,null,f(h.status),Q.createElement(te,{color:jn.DIM}," ",y(h))),Q.createElement(ee,{marginTop:1},Q.createElement(tt,{items:e,onSelect:E,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:jn.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.WHITE:jn.GRAY}," ",t)})),u&&Q.createElement(ee,{marginTop:1},u.loading&&Q.createElement(te,{color:u.color},Q.createElement(Fe,{type:"dots"})," "),Q.createElement(te,{color:u.color},u.text)),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"↑↓ navigate · Enter to select · Esc to go back")))}let C=null;return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:Bn,bold:!0},"Manage MCP servers"),Q.createElement(te,{color:jn.DIM},t.length," ",1===t.length?"server":"servers"),0===t.length?Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(te,{color:jn.DIM},"No MCP servers configured."),Q.createElement(te,{color:jn.DIM},'Use "cmd mcp add" to add a server.'),Q.createElement(te,{color:jn.DIM},"Docs: https://commandcode.ai/docs/mcp")):Q.createElement(ee,{marginTop:1,flexDirection:"column"},g.map((e,t)=>{const n=e.scope!==C;C=e.scope;const r=t===o;return Q.createElement(Q.Fragment,{key:e.name},n&&Q.createElement(ee,{marginTop:0===t?0:1},Q.createElement(te,{bold:!0},w(e.scope)),Q.createElement(te,{color:jn.DIM}," (",S(e.scope),")")),Q.createElement(ee,{paddingLeft:1},Q.createElement(te,{color:r?jn.WHITE:jn.GRAY},r?"› ":" "),Q.createElement(te,{color:r?jn.WHITE:void 0,bold:r},e.name),Q.createElement(te,{color:jn.DIM}," · "),f(e.status),Q.createElement(te,{color:"connected"===e.status?jn.GREEN:"authenticated"===e.status?jn.CYAN:"requires_auth"===e.status?jn.YELLOW:jn.GRAY}," ",y(e))))})),u&&Q.createElement(ee,{marginTop:1},u.loading&&Q.createElement(te,{color:u.color},Q.createElement(Fe,{type:"dots"})," "),Q.createElement(te,{color:u.color},u.text)),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Ht(),aw(),Kt(),_n(),dr();var _x=__name(({onClose:e})=>{const[t,n]=K([]),[r,s]=K(0),[o,i]=K(!0),[a,l]=K(null);J(()=>{__name(async()=>{try{const e=await discoverMemoryFiles(process.cwd());n(e),i(!1)}catch(e){l(e instanceof Error?e.message:"Failed to discover memory files"),i(!1)}},"loadMemoryFiles")()},[]);const u=__name(async t=>{try{await openInEditor(t.path),e()}catch(t){console.error("Error opening memory file. Please ensure you have an editor set up."),e()}},"handleOpenInEditor"),d=t.filter(e=>"project"===e.type||"user"===e.type);if(se((t,n)=>{n.escape?e():n.upArrow?s(e=>Math.max(0,e-1)):n.downArrow?s(e=>Math.min(d.length-1,e+1)):(n.return&&d[r]&&u(d[r]),"1"===t&&d[0]&&u(d[0]),"2"===t&&d[1]&&u(d[1]))}),o)return Q.createElement(ee,{paddingLeft:1,paddingTop:1},Q.createElement(te,{color:jn.DIM},"Loading memory files..."));if(a)return Q.createElement(ee,{paddingLeft:1,paddingTop:1},Q.createElement(te,{color:jn.RED},ke.cross," ",a));const m=d.map((e,t)=>{const n=t+1;let r="",s="";return"project"===e.type?(r=`${n}. Project memory`,s=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,s=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:s}});return Q.createElement(ee,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:jn.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},Q.createElement(ee,null,Q.createElement(te,{color:jn.WHITE,bold:!0},"Select memory to edit:")),Q.createElement(ee,{columnGap:4,marginTop:1},Q.createElement(ee,{flexDirection:"column"},m.map((e,t)=>Q.createElement(te,{key:t,color:r===t?jn.WHITE:jn.DIM},r===t?`${wn} `:" ",e.label))),Q.createElement(ee,{flexDirection:"column"},m.map((e,t)=>Q.createElement(te,{key:t,color:r===t?jn.WHITE:jn.DIM},e.description)))))},"MemorySelector");Ht(),Kt(),dv(),Ur(),Nr(),dr(),Ht(),dr();var xx=lt()?"⠶":"#";function AssistantMessage({content:e}){return Q.createElement(ee,null,Q.createElement(te,{color:Zn},xx),Q.createElement(ee,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(Markdown,null,e)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let s=jn.GREEN,o=ke.tick,i="default",a=t||"(No output)";n&&(s=jn.YELLOW,o=ke.arrowRight,i=jn.YELLOW,a="Executing…"),r&&(s=jn.RED,o=ke.cross,i=jn.RED);const l=X(()=>buildTreeConnectors(a),[a]);return Q.createElement(ee,null,Q.createElement(te,{color:s},o),Q.createElement(ee,{flexDirection:"column",marginLeft:1},Q.createElement(ee,null,Q.createElement(te,{color:jn.GRAY},"$ "),Q.createElement(te,{color:s,bold:!0},e)),Q.createElement(ee,{columnGap:1,marginLeft:1},Q.createElement(te,{color:lr},l),Q.createElement(te,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?jn.YELLOW:void 0,s=X(()=>buildTreeConnectors(e),[e]);return Q.createElement(ee,{flexDirection:"column",marginBottom:0,marginTop:-1},Q.createElement(ee,{columnGap:1},Q.createElement(te,{color:lr},s),Q.createElement(ee,{flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(te,{color:r},e))),t&&Q.createElement(ee,{marginLeft:3},Q.createElement(te,{color:jn.DIM},"See ",t)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return Q.createElement(ee,null,Q.createElement(te,{color:jn.RED},t?ke.pointer:ke.warning),Q.createElement(ee,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?Q.createElement(te,{color:jn.RED,wrap:"wrap"},e):Q.createElement(Markdown,{color:jn.RED},e)))}function IDEStatusMessage({status:e,ide:t,details:n}){return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,"connected"===e&&Q.createElement(te,null,Q.createElement(te,{color:jn.GREEN},ke.tick),Q.createElement(te,null," Connected to "),Q.createElement(te,{color:jn.CYAN},t)),"installed"===e&&Q.createElement(te,null,Q.createElement(te,{color:jn.GREEN},ke.tick),Q.createElement(te,null," Installed for "),Q.createElement(te,{color:jn.CYAN},t)),"needs_reload"===e&&Q.createElement(te,null,Q.createElement(te,{color:jn.YELLOW},ke.circle),Q.createElement(te,null," "),Q.createElement(te,{color:jn.CYAN},t),Q.createElement(te,null," extension needs reload")),"failed"===e&&Q.createElement(te,null,Q.createElement(te,{color:jn.RED},ke.cross),Q.createElement(te,null," Install failed")),"not_in_ide"===e&&Q.createElement(te,null,Q.createElement(te,{color:jn.YELLOW},ke.circle),Q.createElement(te,null," Not in IDE"))),n?.map((e,t)=>Q.createElement(te,{key:t,color:jn.DIM}," ",e)))}function AutoCompactMessage({content:e}){return Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},ke.info),Q.createElement(ee,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(te,{color:jn.DIM},e)))}function TasteSkipMessage(){return Q.createElement(ee,null,Q.createElement(ee,{flexShrink:0},Q.createElement(te,{backgroundColor:Un.BADGE_BG,color:Un.BADGE_FG,bold:!0},qk)),Q.createElement(te,{color:jn.DIM}," Skipped. Run "),Q.createElement(te,{color:sr.CODE},"/learn-taste"),Q.createElement(te,{color:jn.DIM}," or "),Q.createElement(te,{color:sr.CODE},"cmd learn-taste"),Q.createElement(te,{color:jn.DIM}," anytime."))}function InfoMessage({content:e,metadata:t}){return t?.isTasteSkip?Q.createElement(TasteSkipMessage,null):t?.isAutoCompact?Q.createElement(AutoCompactMessage,{content:e}):Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},ke.info),Q.createElement(ee,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},Q.createElement(te,{color:jn.DIM},e)))}__name(AssistantMessage,"AssistantMessage"),Ht(),dr(),__name(BashMessage,"BashMessage"),Ht(),dr(),__name(CommandResultMessage,"CommandResultMessage"),Ht(),dr(),__name(ErrorMessage,"ErrorMessage"),Ht(),dr(),__name(IDEStatusMessage,"IDEStatusMessage"),Ht(),dr(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(InfoMessage,"InfoMessage"),Ht(),Ht(),Kt();dr(),jb(),Ht(),Ur();var Px="cmd";function getBinNames(){const e=getPackageJson();return e.bin&&"object"==typeof e.bin?Object.keys(e.bin):e.bin&&"string"==typeof e.bin?[e.name]:[Px]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||Px;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||Px}catch{return Px}}function HelpMessage(){const e=getInvokedCommandName(),t=X(()=>$b.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return Q.createElement(ee,{flexDirection:"column",paddingY:1},Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ee,null,Q.createElement(te,{bold:!0},"Command Code"),Q.createElement(te,{color:jn.GRAY}," v","0.19.1")),Q.createElement(te,{color:jn.GRAY},Ab)),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Usage"),Q.createElement(ee,{paddingLeft:2},Q.createElement(te,null,e," <command> [options]"))),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Options"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Rb.map(t=>Q.createElement(ee,{key:t.key},Q.createElement(te,null,t.key.replace(/^cmd/,e).padEnd(Ib)),Q.createElement(te,{color:jn.GRAY},t.description))))),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Commands"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Mb.map(t=>Q.createElement(ee,{key:t.key},Q.createElement(te,null,t.key.replace(/^cmd/,e).padEnd(Ib)),Q.createElement(te,{color:jn.GRAY},t.description))))),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Slash Commands"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},t.map(e=>Q.createElement(ee,{key:e.key},Q.createElement(te,null,e.key.padEnd(Ib)),Q.createElement(te,{color:jn.GRAY},e.description))))),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Keyboard Shortcuts"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Nb.map(e=>Q.createElement(ee,{key:e.key},Q.createElement(te,null,e.key.padEnd(Ib)),Q.createElement(te,{color:jn.GRAY},e.description))))),Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(te,{bold:!0},"Examples"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Db.map(t=>Q.createElement(ee,{key:t.key},Q.createElement(te,null,t.key.replace(/^cmd/,e).padEnd(Ib)),Q.createElement(te,{color:jn.GRAY},t.description))))),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.CYAN},ke.pointer),Q.createElement(te,{color:jn.GRAY}," ",Ob.replace(/cmd/,e))),Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{bold:!0},"Links"),Q.createElement(ee,{flexDirection:"column",paddingLeft:2},Lb.map(e=>Q.createElement(ee,{key:e.key},Q.createElement(te,null,e.key.padEnd(Ib)),Q.createElement(te,{color:jn.CYAN},e.description))))))}function SystemMessage({content:e,metadata:t}){if(e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS"))return Q.createElement(HelpMessage,null);if("CONTEXT"===e){const e=t?.analysis;if(e)return Q.createElement(ContextMessage,{analysis:e})}return Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{wrap:"wrap"},Q.createElement(Markdown,null,e)))}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),Nr(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),Ht(),_n(),LC(),dr();var Ax={"Interrupted by user":"Interrupted by user","Insufficient credits":fn};function UserMessage({content:e,images:t,imageCount:n=0}){const r="Interrupted by user"===e,s="Insufficient credits"===e,o=e.startsWith("Error:"),i=r||s||o,a=i&&Ax[e]||e,l=null!=t?t.length:n,u=Y(null);null===u.current&&t&&t.length>0&&(u.current=t.map((e,t)=>saveTempImage(e,t+1)));const d=u.current??[];return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,{backgroundColor:i?void 0:Xn.BG,paddingRight:1},Q.createElement(te,{color:i?jn.RED:Xn.POINTER,bold:!i},ke.pointer),Q.createElement(ee,{marginLeft:1},Q.createElement(te,{color:i?jn.RED:jn.WHITE,wrap:"wrap"},a))),l>0&&Q.createElement(ee,{marginLeft:1},Q.createElement(te,{color:jn.DIM},"⎿"," ",Array.from({length:l},(e,t)=>{const n=d[t],r=`[Image #${t+1}]`;return null!=n?createOSC8Link(`file://${n}`,r,!1):r}).join(" "))))}function renderFeedEntry(e,t){if("user"===e.role){const t=Array.isArray(e.metadata?.images)?e.metadata.images:void 0;return Q.createElement(UserMessage,{content:e.input,images:t})}return"assistant"===e.role?Q.createElement(AssistantMessage,{content:e.input}):"tool"===e.role?Q.createElement(ToolMessage,{name:ov(e.name||""),input:e.input,output:e.output||"",isPending:nv(e),hasError:tv(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?Q.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:nv(e),hasError:tv(e)}):"system"===e.role?Q.createElement(SystemMessage,{content:e.input,metadata:e.metadata}):"info"===e.role?Q.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?Q.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?Q.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?Q.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName(e){const t=Object.values(Dt).find(t=>t.id===e);return t?t.name.toLowerCase().replace(" ","-"):e.includes("sonnet-4-6")?"sonnet-4.6":e.includes("sonnet")?"sonnet-4.5":e.includes("opus-4-6")?"opus-4.6":e.includes("opus")?"opus-4.5":"sonnet-4.6"}function TranscriptDivider({count:e,width:t}){const n=` ${e} hidden messages [ctrl+e to expand more] `,r=Math.max(0,Math.floor((t-n.length)/2)),s="─".repeat(r);return Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:Jn},s),Q.createElement(BracketedText,{text:n,color:Jn}),Q.createElement(te,{color:Jn},s))}__name(UserMessage,"UserMessage"),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName,"getModelShortName"),__name(TranscriptDivider,"TranscriptDivider");var Ix=Q.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:s,hiddenCount:o=0})=>{const i=o>0?{role:"transcript-divider",count:o}:null,a=[...t?["header"]:[],...i?[i]:[],...e],l=useTerminalWidth(),u=X(()=>u_(l),[l]),d=X(()=>h_(l),[l]),m=X(()=>getPackageJson().version||"0.0.0",[]),g=X(()=>getGitHeaderInfo(),[]),h=X(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),f=s?getModelShortName(s):"sonnet-4.6",y="taste-1",w=isInternalTeamFlagEnforced()&&!process.env.CMD_DEMO?" · co":"";return Q.createElement(ne,{items:a,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return Q.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:l});if("header"===e)return"compact"===d?Q.createElement(ee,{key:"header",marginBottom:1,flexDirection:"row"},Q.createElement(ee,{width:p_,flexShrink:0},Q.createElement(ot,{name:"vice"},Q.createElement(te,null,m_))),Q.createElement(ee,{flexDirection:"column",marginLeft:2},Q.createElement(ee,null,Q.createElement(te,{bold:!0},"Command Code"),Q.createElement(te,{color:Jn}," ","v",m)),Q.createElement(te,{color:Jn},"models: ",f," · ",y,w),Q.createElement(te,{color:Jn},h,g&&g.isLocal&&g.branch&&` (${g.branch})`))):Q.createElement(ee,{key:"header",marginBottom:1,flexDirection:"column"},Q.createElement(ot,{name:"vice"},Q.createElement(te,null,u.trimEnd())),Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(ee,null,Q.createElement(te,{color:Jn},"# "),Q.createElement(te,{bold:!0},"Command Code"),Q.createElement(te,{color:Jn}," v",m)),Q.createElement(te,{color:Jn},"# models: ",f," · ",y,w),Q.createElement(ee,null,Q.createElement(te,{color:Jn},"# ",h,g&&g.isLocal&&g.branch&&Q.createElement(te,{color:Jn}," ","(branch:"," ",g.branch,")")))));const t=e,n=renderFeedEntry(t,r);return Q.createElement(ee,{key:t.id,paddingBottom:1,width:"90%"},n)})});Ht(),dv(),Rr(),dr();var Nx=V(__name(function LiveAgentStatusInner2({entry:e}){const t=ov(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],s=r?r+(n.includes(".")||n.includes("\n")?".":""):n,o=e.metadata?.tokensUsed||0,i=e.metadata?.elapsedSeconds||0,a=e.metadata?.recentTools||[],[l,u]=K(".");return J(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),Q.createElement(ee,{flexDirection:"column",marginBottom:1,width:"90%"},Q.createElement(ee,null,Q.createElement(te,{backgroundColor:Vn.BG,color:Vn.FG,bold:!0},` ${t} `),s&&Q.createElement(te,null," ","(",s,")")),Q.createElement(ee,{columnGap:1,marginLeft:1},Q.createElement(te,null,"⎿"," "),Q.createElement(te,{color:jn.GRAY},"Running (",formatTime2(i)," | ",formatTokens(o),")",l)),a.length>0&&Q.createElement(ee,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=ov(e.name);return Q.createElement(ee,{key:t,columnGap:1},Q.createElement(te,{color:jn.GRAY},"⎿"),Q.createElement(te,{color:jn.GRAY}," ",n),e.input&&Q.createElement(te,{color:jn.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),Rx=V(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:Q.createElement(Nx,{entry:e})},"LiveAgentStatus"));Ht(),Kt(),xr(),Rr(),dr();var $x=Object.values(Dt),Mx=Object.keys(qt),Lx=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const[r,s]=K(""),[o,i]=K(0),[a,l]=K(null),[u,d]=K(null),m=X(()=>{if(!r.trim())return $x;const e=r.toLowerCase().split(""),t=__name(t=>{let n=0;for(const r of t)if(r===e[n]&&(n++,n===e.length))return!0;return!1},"fuzzyMatch");return $x.map(e=>{const n=e.name.toLowerCase(),r=e.label.toLowerCase(),s=e.provider.toLowerCase(),o=(e.description||"").toLowerCase();let i=0;return t(n)&&(i+=100),t(r)&&(i+=50),t(s)&&(i+=25),t(o)&&(i+=10),{model:e,score:i}}).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score).map(({model:e})=>e)},[r]);J(()=>{i(0)},[r]),J(()=>{if(n&&!r){const e=m.findIndex(e=>e.id===n);e>=0&&i(e)}},[n,m,r]),J(()=>{(async()=>{await isOAuthEnforced()&&d(await getConfiguredProvider())})()},[]),se((n,a)=>{if(a.escape&&r)s("");else if(a.escape)t();else if(a.backspace||a.delete)s(e=>e.slice(0,-1));else{if(a.upArrow)return l(null),void i(e=>e>0?e-1:m.length-1);if(a.downArrow)return l(null),void i(e=>e<m.length-1?e+1:0);if(a.return){const t=m[o];if(!t)return;if(u){const e=jt[u];if(e&&!e.includes(t.provider)){const e=qt[u]||u;return void l(`${e} OAuth does not support ${t.provider} models. Switch to GitHub Copilot via /provider.`)}}return void e(t.id)}!a.ctrl&&!a.meta&&!a.tab&&n&&1===n.length&&n>=" "&&s(e=>e+n)}});const g=X(()=>{const e=new Set(m.map(e=>e.provider));return Mx.filter(t=>e.has(t))},[m]);return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ee,null,Q.createElement(te,{color:Bn,bold:!0},"Select model")),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{dimColor:!0},"Switch between Command Code models. Applies to this session and future sessions.")),Q.createElement(ee,{marginBottom:2,flexDirection:"column",width:"100%"},Q.createElement(ee,{width:"100%"},Q.createElement(te,{color:jn.GRAY},ke.pointerSmall),Q.createElement(te,null," "),Q.createElement(te,{color:r?jn.WHITE:jn.GRAY},r||"Type to search models..."),r&&Q.createElement(te,{dimColor:!0}," (",m.length," found)"))),0===m.length?Q.createElement(ee,{marginY:1},Q.createElement(te,{color:jn.GRAY},'No models match "',r,'"')):g.map((e,t)=>{const r=m.filter(t=>t.provider===e);return 0===r.length?null:Q.createElement(ee,{key:e,flexDirection:"column",marginBottom:t<g.length-1?1:0},Q.createElement(te,{dimColor:!0,bold:!0},qt[e]),r.map(e=>{const t=m.indexOf(e)===o,r=e.id===n;return Q.createElement(ee,{key:e.id},Q.createElement(te,{color:t?jn.CYAN:jn.GRAY},t?`${ke.pointer} `:" "),Q.createElement(te,{color:t?jn.CYAN:r?jn.GREEN:jn.WHITE},e.label.padEnd(24)),e.description&&Q.createElement(te,{color:jn.DIM},e.description),r&&Q.createElement(te,{color:jn.GREEN}," ",ke.tick))}))}),a&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.RED},a)),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"type to search . up/down navigate . Enter to select"),r?Q.createElement(te,{color:jn.DIM}," . Esc to clear"):Q.createElement(te,{color:jn.DIM}," . Esc to cancel")))},"ModelSelector");Ht(),Nr(),dr();var Dx=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),s=__name(t=>{e(t.value)},"handleSelect");se((e,n)=>{n.escape&&t()});const o=n?r.findIndex(e=>e.value===n):0,i=n&&-1===o;return Q.createElement(ee,{flexDirection:"column",paddingX:0,width:"100%"},Q.createElement(ee,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},Q.createElement(ee,null,Q.createElement(te,{bold:!0},"Select AI Provider")),n&&Q.createElement(ee,{flexDirection:"row"},Q.createElement(te,{color:jn.DIM},"Current: "),Q.createElement(te,{color:jn.GREEN},getProviderDisplayName(n)),i&&Q.createElement(te,{color:jn.YELLOW}," [OAuth enforced]"))),Q.createElement(ee,{marginBottom:0},Q.createElement(te,{color:jn.DIM},"Available Providers:")),Q.createElement(tt,{items:r,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>Q.createElement(te,{color:e?jn.CYAN:jn.GRAY,bold:e},e?ke.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>Q.createElement(te,{color:e?jn.CYAN:jn.GRAY,bold:e},` ${t}`)}),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=K(0);if(J(()=>{if(null===e)return;const t=setInterval(()=>{n(e=>(e+1)%4)},500);return()=>clearInterval(t)},[e]),null===e)return null;const r=".".repeat(t).padEnd(3," ");return Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:rr,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Ht(),dr(),__name(RetryMessage,"RetryMessage"),Ht(),Dw(),hs(),_n(),dr();var Ox=[{mode:"both",label:"Both",description:"Restore conversation and code (recommended)"},{mode:"conversation",label:"Conversation only",description:"Rewind conversation, keep current code"},{mode:"files",label:"Code only",description:"Restore code, keep conversation"}],Fx=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=X(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[s,o]=K(Math.max(0,r.length-1)),[i,a]=K(Math.max(0,r.length-8)),[l,u]=K("checkpoint"),[d,m]=K(null),[g,h]=K(0),f=X(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),y=X(()=>f?Ox:Ox.filter(e=>"conversation"===e.mode),[f]);if(J(()=>{if(r.length>0){const e=r.length-1;o(e),a(Math.max(0,r.length-8))}},[r.length,8]),se((e,f)=>{f.escape?"mode"===l?(u("checkpoint"),m(null),h(0)):n():"checkpoint"===l?f.upArrow?o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):f.downArrow?o(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):f.return&&r.length>0&&(m(r[s]),u("mode"),h(0)):"mode"===l&&(f.upArrow?h(e=>Math.max(0,e-1)):f.downArrow?h(e=>Math.min(y.length-1,e+1)):f.return&&d&&y[g]&&t({messageId:d.messageId,mode:y[g].mode}))}),0===r.length)return Q.createElement(ee,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(te,{color:Bn,bold:!0},"Rewind"),Q.createElement(te,{color:jn.DIM},"No checkpoints available. Start a conversation to create checkpoints."),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press "),Q.createElement(te,{color:jn.DIM,bold:!0},"Esc"),Q.createElement(te,{color:jn.DIM}," to close")));if("mode"===l&&d)return Q.createElement(ee,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(te,{color:Bn,bold:!0},"Rewind"),Q.createElement(ee,{marginBottom:1},Q.createElement(te,{color:jn.DIM},"Restore to: "),Q.createElement(te,{color:jn.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),Q.createElement(ee,{flexDirection:"column"},y.map((e,t)=>{const n=g===t,r=t===y.length-1;return Q.createElement(ee,{key:e.mode,flexDirection:"column"},Q.createElement(ee,{flexDirection:"row"},Q.createElement(te,{color:n?Bn:void 0},n?`${wn} `:" "),Q.createElement(ee,{flexDirection:"column"},Q.createElement(te,{color:n?Bn:jn.WHITE},e.label),Q.createElement(te,{color:jn.DIM},e.description))),!r&&Q.createElement(te,null," "))})),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press "),Q.createElement(te,{color:jn.DIM,bold:!0},"Enter"),Q.createElement(te,{color:jn.DIM}," to confirm, "),Q.createElement(te,{color:jn.DIM,bold:!0},"Esc"),Q.createElement(te,{color:jn.DIM}," to go back")));const w=r.slice(i,i+8);return Q.createElement(ee,{flexDirection:"column",paddingLeft:2,paddingTop:1},Q.createElement(te,{color:Bn,bold:!0},"Rewind"),Q.createElement(te,{color:jn.DIM},"Select a checkpoint to restore your session"),r.length>8&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),Q.createElement(ee,{marginTop:1}),Q.createElement(ee,{flexDirection:"column"},w.map((e,t)=>{const n=i+t,o=s===n,a=e.filesModified.length,l=t===w.length-1,u=n===r.length-1;return Q.createElement(ee,{key:e.messageId,flexDirection:"column"},Q.createElement(ee,{flexDirection:"row"},Q.createElement(te,{color:o?Bn:void 0},o?`${wn} `:" "),Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{color:o?Bn:jn.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),Q.createElement(te,{color:jn.DIM}," • "),Q.createElement(te,{color:jn.DIM},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),Q.createElement(te,{color:jn.DIM},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&Q.createElement(te,null," "))})),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Press "),Q.createElement(te,{color:jn.DIM,bold:!0},"Enter"),Q.createElement(te,{color:jn.DIM}," to select, "),Q.createElement(te,{color:jn.DIM,bold:!0},"Esc"),Q.createElement(te,{color:jn.DIM}," to cancel")))},"RewindSelector");Ht(),In(),Ht(),Ht(),tC();var qx=__name(e=>{const[t,n]=K(e),[r,s]=K(null);return J(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),s(null)},"handleReset"),r=__name(e=>{"error"!==e.type?n(t=>{if("step_start"===e.type){const n=t.findIndex(t=>t.id===e.step);return n<0?t:t.map((t,r)=>r<n?{...t,active:!1,complete:!0}:r===n?{...t,active:!0,message:e.message||"",...e.label&&{label:e.label},..."complete"===e.step&&{complete:!0},...void 0!==e.learningCount&&void 0!==e.categories&&void 0!==e.storage&&t.summary&&{summary:{learningCount:e.learningCount,categories:e.categories,storage:e.storage}}}:t)}if("progress"===e.type){const n=t.findIndex(e=>e.active);return n<0?t:t.map((t,r)=>r===n?{...t,items:[...t.items,e.message]}:t)}if("insight"===e.type){const n=t.findIndex(e=>"learning"===e.id);return n<0?t:t.map((t,r)=>r===n?{...t,insights:[...t.insights,e.message]}:t)}return t}):s(e.message)},"handleNewEvent");return Zv.on("reset",t),Zv.on("new-event",r),()=>{Zv.off("reset",t),Zv.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:s}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new xy({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let s,o;try{const e=await getOAuthCredentials({provider:n});s=e.token,o=e.oauthProvider,validateOAuthToken({token:s,provider:n})}catch(e){dlog("Failed to get or validate OAuth token:",e instanceof Error?e.message:String(e))}const i={[Ct.PROJECT_SLUG]:hv.getCurrentProjectDirName(),[Ct.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return s&&(i[Ct.OAUTH_TOKEN]=`Bearer ${s}`,o&&(i[Ct.OAUTH_PROVIDER]=o)),{request:t,headers:i}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const s of e){const e=estimateTokens(s);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([s])):r+e>2e3?(n.length>0&&t.push(n),n=[s],r=e):(n.push(s),r+=e)}return n.length>0&&t.push(n),t}Ht(),Ht(),cC(),Wy(),Xy(),bS(),In(),tC(),Ht(),In(),tC(),bS(),Ht(),Ht(),Kt(),Wy(),Xy(),vv(),In(),xr(),Rr(),__name(createRequestClient,"createRequestClient"),Ht(),bS(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Ht(),Ht(),In(),gn(),tC(),Ht();var jx="claude-haiku-4-5-20251001";function buildObserverPrompt(e,t){return`Scan prompts. ${t} casual observations like a dev friend glancing at your work.\n\nPLAIN TEXT ONLY. No markdown, no formatting.\n\nBe natural and VARIED. Don't repeat the same sentence starters.\n\nGood (notice the variety):\npnpm over npm, nice\ndebugging that auth flow\nreact + typescript stack\ncircular deps came up\ntui flicker stuff\nah the classic memory leak\nsession persistence wip\nfighting with imports again\nhaiku model issues huh\n\nBad (too repetitive - NEVER do this):\nI see you prefer pnpm\nI see debugging auth\nI see react stack\nI see circular deps\noh, TUI issues\noh, memory leak\n\nRules:\n- plain text, lowercase is fine\n- vary your sentence starts - mix it up\n- max 6 words\n- sound human, not robotic\n\nPrompts:\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}function createInsightEmitter(){let e="",t=0;const n=__name(()=>{if(e.includes("\n")){const t=e.split("\n");for(let e=0;e<t.length-1;e++){const n=t[e].trim();n&&(dlog(`[ObserverAPI] emitting insight: ${n}`),Zv.addEvent({type:"insight",message:n}))}e=t[t.length-1]}},"emitCompletedLines");return{addText:__name(r=>{t++,dlog(`[ObserverAPI] text chunk ${t}: "${r.substring(0,50)}..."`),e+=r,n()},"addText"),emitRemaining:__name(()=>{e.trim()&&(dlog(`[ObserverAPI] emitting final insight: ${e.trim()}`),Zv.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function callObserverAPI(e,t,n){dlog(`[ObserverAPI] calling ${kt.ALPHA.GENERATE} with model: ${jx}`);const r={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:n}],model:jx,max_tokens:200,temperature:.7,stream:!0},threadId:Ee()},s=await e.post({endpoint:kt.ALPHA.GENERATE,body:r,headers:t,stream:!0});dlog("[ObserverAPI] got response stream");const o=createInsightEmitter();await consumeSSEStream(s,{onText:__name(e=>{o.addText(e)},"onText")}),dlog(`[ObserverAPI] stream complete, ${o.getChunkCount()} chunks received`),o.emitRemaining(),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,s){let o=0;for(const e of n)o+=estimateTokens(e);dlog(`[Observer] batch ${r}/${s}: ${n.length} prompts`);const i=buildObserverPrompt(n,4);await callObserverAPI(e,t,i)}async function observeSessionPrompts(e){if(Zv.observerHasRun)return;Zv.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${r.length} batches`);const s=Math.min(r.length,6);for(let t=0;t<s;t++){if(Zv.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const s=r[t];try{await processBatch(e,n,s,t+1,r.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),Zv.addEvent({type:"progress",message:"Continuing without live observations..."})}}Kt(),PE(),__name(buildObserverPrompt,"buildObserverPrompt"),__name(createInsightEmitter,"createInsightEmitter"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var Bx=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(y.homedir(),".claude","projects");await D.access(r);const s=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${s}`);const o=(await D.readdir(r)).filter(e=>e===s);for(const s of o){const o=e.join(r,s);try{if(!(await D.stat(o)).isDirectory())continue;const r=(await D.readdir(o)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const s of r){const r=e.join(o,s),i=await D.stat(r),a=s.replace(".jsonl","");if(n.push({id:a,filePath:r,createdAt:i.birthtime,lastModified:i.mtime,messageCount:0,agent:"claude-code"}),t>0&&n.length>=t)break}if(t>0&&n.length>=t)break}catch{continue}}}catch{dlog("[Import] no claude sessions dir")}return n}static async findCodexSessions(e=0,t){try{Zv.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&Zv.addEvent({type:"progress",message:`Scanning Codex: ${e.processedFiles}/${e.totalFiles} files (${e.matchedSessions} matched)`})},e);return dlog(`[Import] found ${n.length} Codex sessions`),n}catch(e){return dlog("[Import] no codex sessions",e),[]}}static async findCursorSessions(e=0){try{Zv.addEvent({type:"progress",message:"Scanning Cursor sessions..."});const t=await findCursorSessions(process.cwd(),e);return dlog(`[Import] found ${t.length} Cursor sessions`),t}catch(e){return dlog("[Import] no cursor sessions",e),[]}}static async extractUserPrompts(e){const t=[];try{const n=(await D.readFile(e,"utf-8")).trim().split("\n");for(const e of n)if(e.trim())try{const n=JSON.parse(e);if("user"===n.type&&n.message){const e=n.message;let r="";e.content&&"string"==typeof e.content&&(r=e.content),r.trim()&&t.push(r.trim())}}catch{continue}t.length>0&&dlog(`[Import] extracted ${t.length} prompts from session`)}catch(t){dlog(`[Import] failed: ${e}`,t)}return t}static splitPromptsIntoBatches(e,t=15e4){const n=[];let r=[],s=0;for(const o of e){const e=estimateTokens(o);if(e>t){r.length>0&&(n.push(r),r=[],s=0);const e=this.splitLargePrompt(o,t);for(const t of e)n.push([t])}else s+e<=t?(r.push(o),s+=e):(r.length>0&&n.push(r),r=[o],s=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let s="",o=0;for(const e of r){const r=estimateTokens(e);o+r<=t?(s+=(s?"\n":"")+e,o+=r):(s&&n.push(s),s=e,o=r)}return s&&n.push(s),n}static async importAndLearn(){const e=[],t=[],n=[],r=[],s=[];try{Zv.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const o=await loadProjectSettings(),i=o.tasteOnboarding?.learnedSessions||{},a=i["claude-code"]?.length||0,l=i.codex?.length||0,u=i.cursor?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${l} learned, cursor=${u} learned`);const d=await findNewSessions(i),m=d["claude-code"]||[],g=d.codex||[],h=d.cursor||[],f=m.length+g.length+h.length;if(dlog(`[Import] findNewSessions returned: claude-code=${m.length} new, codex=${g.length} new, cursor=${h.length} new`),0===f){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=await findCursorSessions(process.cwd()),r=e.length+t.length+n.length,s=[{name:"Claude Code",count:e.length},{name:"Codex",count:t.length},{name:"Cursor",count:n.length}].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>`${e.count} ${e.name}`);Zv.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:r>0?`From ${s.join(" + ")} sessions`:"No sessions found for this project"});const o=[];return e.length>0&&o.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&o.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),n.length>0&&o.push({agent:"cursor",sessionIds:n.map(e=>e.id),displayName:"Cursor"}),{success:!1,totalPrompts:0,preferencesLearned:0,errors:[],totalSessions:r,learnedSessions:a+l+u,agentSessions:o,status:"already-learned"}}if(m.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>m.includes(e.id));n.push(...e)}if(g.length>0){const e=(await this.findCodexSessions()).filter(e=>g.includes(e.id));r.push(...e)}if(h.length>0){const e=(await this.findCursorSessions()).filter(e=>h.includes(e.id));s.push(...e)}const y=n.length+r.length+s.length;dlog(`[Import] total sessions: ${y} (claude-code: ${n.length}, codex: ${r.length}, cursor: ${s.length})`),Zv.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const w=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts},{name:"Cursor",sessions:s,extractPrompts:extractCursorPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of w){Zv.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const S=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${S.length} batches`);const E=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});Zv.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${S.length} batch${1===S.length?"":"es"}`});try{const o=getApiBaseUrl(),i=new xy({baseUrl:o});let a=!0;for(let e=0;e<S.length;e++){const t=S[e],n=e+1,r=S.length;r>1&&Zv.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const s=this.formatBatchLearning(t),o=new rC({request:i,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:s}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await o.checkAndProcess({messages:l})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),Zv.markLearningComplete(),await E,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}if(s.length>0){const e=s.map(e=>e.id);await markSessionsAsLearned("cursor",e),dlog(`[Import] marked ${e.length} cursor sessions as learned`)}}else dlog("[Import] NOT marking sessions as learned due to batch failures");const l=await this.extractLearningSummary(),u=[];if(n.length>0&&u.push(`Claude Code (${n.length})`),r.length>0&&u.push(`Codex (${r.length})`),s.length>0&&u.push(`Cursor (${s.length})`),!a){const o="Learning failed - sessions not marked as learned";return e.push(o),Zv.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...s.length>0?[{agent:"cursor",sessionIds:s.map(e=>e.id),displayName:"Cursor"}]:[]]}}return Zv.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${u.join(" + ")}`,learningCount:l.totalLearnings,categories:l.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...s.length>0?[{agent:"cursor",sessionIds:s.map(e=>e.id),displayName:"Cursor"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),Zv.addEvent({type:"error",message:r}),{success:!1,totalPrompts:t.length,preferencesLearned:0,errors:e}}}catch(t){const n=t instanceof Error?t.message:String(t);return e.push(n),{success:!1,totalPrompts:0,preferencesLearned:0,errors:e}}}static async extractLearningSummary(){try{const t=e.join(process.cwd(),".commandcode","taste","taste.md"),n=await D.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),s=r?r.length:0;return{totalLearnings:s,categories:n.split("\n").filter(e=>e.startsWith("# ")).map(e=>e.replace(/^# /,"").trim()).filter(e=>e&&!e.toLowerCase().startsWith("taste"))}}catch{return{totalLearnings:0,categories:[]}}}static formatBatchLearning(e){return e.map((e,t)=>`${t+1}. ${e}`).join("\n\n")}};tC();var Ux=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),zx=__name(e=>{const[t,n]=K({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return J(()=>{Zv.reset(),Zv.markImportStarted(),(async()=>{try{const t=await Promise.race([Bx.importAndLearn(),Ux(12e4)]);if(t.success)return void n(e=>({...e,isImporting:!1,waitingForInput:!0}));if("already-learned"===t.status)return void n(e=>({...e,isImporting:!1,alreadyLearned:!0,learnedSessionCount:t.learnedSessions||0,totalSessionCount:t.totalSessions||0,agentSessions:t.agentSessions||[],waitingForInput:!0}));const r=t.errors.join("\n");n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}catch(t){const r=t instanceof Error?t.message:String(t);n(e=>({...e,isImporting:!1,waitingForInput:!0,error:r})),e&&e(r)}})()},[e]),t},"useImportProcess");Ht();var Wx=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{se((r,s)=>{n&&(s.escape&&e(),(s.return||"\n"===r)&&t())})},"useKeyboardInput");Ht(),In();var Gx=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=K(null),[s,o]=K(null),i=Y(!1);return J(()=>{if(i.current)return;let n=null;return(async()=>{try{i.current=!0,dlog("[Hook:Conditions] loading...");const n=await checkOnboardingConditions();r(n),n.shouldTrigger||e?dlog(`[Hook:Conditions] result: ${n.reason}, sessions: ${n.sessionCount}`):(dlog("[Hook:Conditions] no trigger, skipping"),t())}catch(e){const r=e instanceof Error?e.message:String(e);dlog("[Hook:Conditions] error",r),o(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:s,isLoading:!n&&!s}},"useOnboardingConditions");async function completeOnboarding(e){try{await markOnboardingCompleted(),dlog("[Helper] onboarding marked complete")}catch(e){dlog(`[Helper] complete error: ${e instanceof Error?e.message:String(e)}`)}finally{Zv.reset(),e()}}async function skipOnboarding(e){try{await markOnboardingSkipped(),dlog("[Helper] onboarding marked skipped")}catch(e){dlog(`[Helper] skip error: ${e instanceof Error?e.message:String(e)}`)}finally{Zv.reset(),e()}}Ht(),In(),Ht(),In(),tC(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var Hx=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=Y(n),s=Z(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),o=Z(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=Z(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=Z(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=Z(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]);return n!==r.current&&(r.current=n),{handleImportStart:s,handleImportComplete:o,handleImportError:i,handleErrorDismiss:a,handleSkip:l}},"useOnboardingHandlers");Ht(),In();var Qx=__name(({conditions:e,autoLearn:t})=>{const[n,r]=K("checking"),s=Y(!1);return J(()=>{if(e&&!s.current){if(s.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),J(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Ht(),Ht(),dr();var Vx=__name(({error:e})=>Q.createElement(ee,{padding:1},Q.createElement(ee,{flexDirection:"column",borderColor:jn.RED,padding:1},Q.createElement(ee,{marginBottom:1},Q.createElement(te,null,"Error initializing onboarding: ",e)),Q.createElement(ee,null,Q.createElement(te,null,"Continuing without onboarding...")))),"OnboardingError");Ht(),Ht(),Kt(),dr();var Kx=__name(()=>`(run /${$t.LEARN_TASTE} anytime)`,"getSkipHint"),Yx=__name(()=>Q.createElement(te,null,"Skip for now"," ",Q.createElement(te,{color:jn.DIM},Kx())),"SkipOptionText"),Jx=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[s,o]=K(1);return se((e,t)=>{t.escape?r():t.upArrow||t.downArrow?o(e=>1===e?2:1):"1"!==e?"2"!==e?t.return&&(1===s?n():r()):r():n()}),Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:Un.TEXT,paddingX:1,paddingY:0},Q.createElement(te,{color:Un.TEXT,bold:!0},"Build Your Coding Taste"),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(te,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),Q.createElement(ee,{marginTop:1},Q.createElement(te,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),Q.createElement(ee,{marginTop:1,flexDirection:"column"},Q.createElement(ee,null,Q.createElement(te,{color:1===s?Un.TEXT:jn.GRAY},1===s?ke.pointer:" "," 1. Yes, learn from my sessions (recommended)")),Q.createElement(ee,null,Q.createElement(te,{color:2===s?Un.TEXT:jn.GRAY},2===s?ke.pointer:" "," 2."," ",Q.createElement(Yx,null)))),Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice");Ht(),Ht(),dr();var Xx=__name(({error:e})=>Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.RED,paddingX:2,paddingY:1,marginBottom:2},Q.createElement(te,{color:jn.RED,bold:!0},"Oops, something went wrong:"),Q.createElement(ee,{marginTop:1},Q.createElement(te,null,e))),"ErrorSection");Ht(),Ht(),dr(),Ht(),Ht(),Ht(),dr(),Ht(),dr();var Zx=__name(()=>Q.createElement(te,{backgroundColor:Un.BADGE_BG,color:Un.BADGE_FG},qk),"TasteBadge");Ht(),dr(),Ht();var eP=["percolating","excavating","deciphering","triangulating","osmosing","metabolizing","grokking","spelunking","interpolating","marinating","crystallizing","synthesizing","calibrating","fermenting","coalescing","transmuting","simmering","distilling","ruminating","perusing","assimilating","untangling","decoding","absorbing","harmonizing","digesting","contemplating","extrapolating","materializing","finalizing"],tP="⎿",nP=__name(()=>{const[e,t]=K(()=>Math.floor(Math.random()*eP.length));return J(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*eP.length))},2e3);return()=>clearInterval(e)},[]),Q.createElement(te,{color:jn.YELLOW},eP[e],"...")},"PulsingText");Ht(),dr();var rP=[ke.bullet,ke.squareSmallFilled,ke.lozenge,ke.star,ke.triangleRight,ke.triangleUp,ke.circleFilled,ke.pointer],sP=__name(e=>String(e).padStart(3," "),"padNum"),oP=__name(e=>rP[e%rP.length],"getSymbol"),iP=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${sP(t)} ↓${sP(n)} (↑↓ scroll)`,"buildStatusLine"),aP=__name(({insights:e})=>{const[t,n]=K(0),[r,s]=K(!0),o=e.length,i=o>10,a=Math.max(0,o-10);if(J(()=>{r&&i&&n(a)},[o,r,i,a]),se((e,t)=>{if(i)return t.upArrow?(s(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(a,e+1);return t===a&&s(!0),t}))}),0===o)return null;const l=e.slice(t,t+10),u=t,d=o-t-10;return Q.createElement(ee,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&Q.createElement(te,{color:jn.DIM},iP(o,u,d,r)),l.map((e,n)=>{const r=t+n;return Q.createElement(ee,{key:r,marginBottom:0},Q.createElement(te,{color:jn.DIM},oP(r)," ",e))}))},"ScrollableInsights");Ht(),dr();var lP=__name(()=>{const[e,t]=K(!0);return J(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),Q.createElement(te,{color:jn.YELLOW},e?ke.circleFilled:ke.circle)},"PulsingDot"),cP=__name(({label:e,message:t,active:n,complete:r,items:s,insights:o,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return Q.createElement(ee,{flexDirection:"column",marginBottom:0},Q.createElement(Zx,null),Q.createElement(ee,{marginTop:0},Q.createElement(te,{color:jn.DIM},tP),Q.createElement(ee,{marginLeft:2},a?Q.createElement(te,{color:Un.TEXT},"learned your coding taste"):Q.createElement(nP,null))));const u=__name(()=>r?Q.createElement(te,{color:Hn.BG},ke.square):n?Q.createElement(lP,null):Q.createElement(te,{color:jn.DIM},ke.circle),"getStatusIcon"),d=s.length>0||o.length>0||t||l&&l.learningCount>0;return!r||n||d?Q.createElement(ee,{flexDirection:"column",marginBottom:0},(n||r)&&Q.createElement(ee,{marginBottom:0},Q.createElement(ee,{marginRight:1},u()),Q.createElement(te,{color:r?jn.WHITE:n?jn.YELLOW:jn.DIM},e)),r&&t&&(!l||0===l.learningCount)&&Q.createElement(ee,{marginLeft:3,marginBottom:0},Q.createElement(te,{color:jn.DIM},t)),s.length>0&&Q.createElement(ee,{flexDirection:"column",marginLeft:1,marginBottom:0},s.map((e,t)=>Q.createElement(te,{key:t,color:jn.DIM},`${ke.bullet} ${e}`))),o.length>0&&Q.createElement(aP,{insights:o}),r&&l&&l.learningCount>0&&Q.createElement(ee,{flexDirection:"column",marginLeft:1,marginBottom:0},Q.createElement(ee,{marginBottom:1,flexDirection:"row"},Q.createElement(te,null,tP),Q.createElement(ee,{marginLeft:2},Q.createElement(te,{color:Un.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),Q.createElement(ee,{flexDirection:"column",marginLeft:1},Q.createElement(te,{color:jn.DIM},ke.pointerSmall," Stored in"," ",l.storage),Q.createElement(te,{color:jn.DIM},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),uP=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return Q.createElement(ee,{flexDirection:"column",marginBottom:1},e.map((e,n)=>Q.createElement(ee,{key:e.id,marginLeft:0===n?0:3},Q.createElement(cP,{label:e.label,message:e.message,active:e.active,complete:e.complete,items:e.items,insights:e.insights,summary:e.summary,isIntro:0===n,isAllComplete:t}))))},"StepsSection"),dP=__name(({steps:e})=>Q.createElement(uP,{steps:e}),"ProgressSection");Ht(),dr();var mP=__name(({isImporting:e=!1,waitingForInput:t=!1})=>Q.createElement(Q.Fragment,null,e&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"ESC to cancel")),t&&Q.createElement(ee,{marginTop:1},Q.createElement(te,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Ht();var pP=[{id:"importing",label:"Initializing Taste Profile",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"batching",label:"Organizing your sessions",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"learning",label:"Learning your coding taste",message:"",active:!1,complete:!1,items:[],insights:[]},{id:"complete",label:"Learned your coding taste!",message:"",active:!1,complete:!1,items:[],insights:[],summary:{learningCount:0,categories:[],storage:".commandcode/taste/taste.md"}}],gP=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:s}=qx(pP),{isImporting:o,waitingForInput:i,error:a}=zx(t);return Wx({onEscape:e,onEnter:__name(()=>{i&&(a&&n?n():e())},"onEnter"),enabled:o||i}),Q.createElement(ee,{flexDirection:"column",padding:1},s&&Q.createElement(Xx,{error:s}),!s&&Q.createElement(dP,{steps:r}),Q.createElement(mP,{isImporting:o,waitingForInput:i}))},"ImportProgress"),hP=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:s,onErrorDismiss:o,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?Q.createElement(Jx,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?Q.createElement(gP,{onComplete:r,onError:s,onErrorDismiss:o}):null,"OnboardingStepRenderer"),fP=__name(({onComplete:e,autoLearn:t=!1})=>{J(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:s}=Gx({autoLearn:t,onShouldSkip:e}),{step:o,setStep:i}=Qx({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=Hx({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${o}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),s?null:r?Q.createElement(Vx,{error:r}):"done"===o?null:Q.createElement(hP,{step:o,conditions:n,onImportStart:a,onImportComplete:l,onImportError:u,onErrorDismiss:d,onSkip:m})},"TasteOnboarding");function getEntryCharCount(e){return("input"in e?e.input??"":"").length+("output"in e?e.output??"":"").length+("command"in e?e.command??"":"").length}function getBudgetedFeed(e,t){if(0===e.length)return[];const n=[...e].reverse();let r=t;const s=[];for(const e of n)if(s.unshift(e),r-=getEntryCharCount(e),r<=0)break;return s}__name(getEntryCharCount,"getEntryCharCount"),__name(getBudgetedFeed,"getBudgetedFeed");var yP=V(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:s,transcriptMode:o,tasteOnboardingEntryId:i,autoLearnTaste:a,retryAttempt:l,input:u,setInput:d,fileSearchQuery:m,setFileSearchQuery:g,showFileList:h,setShowFileList:f,showProviderSelector:y,showModelSelector:w,showMemorySelector:S,showMcpManager:E,showAgentsConfig:v,showRewindSelector:C,showLoginOverlay:k,showUsageOverlay:T,showAddDirModal:_,showCompactModeSelector:x,authComponentInfo:P,status:A,currentProvider:I,currentModel:N,showProviderNotification:R,shareInfo:$,showShareNotification:M,unshareNotificationMessage:L,updateStatus:D,updateFailedInfo:O,creditWarning:F,permissionMode:q,hintMessage:j,pendingExitKey:B,tasteLearningEnabled:U,interactionTokens:z,contextUsage:W,historyManagerRef:G,executionState:H,contextEngineRef:V,onSubmit:K,onCommand:Y,onToggleAutoAccept:J,onResetPendingExitKey:ne,onDoubleEscapeEmpty:re,onTasteOnboardingComplete:se,permissionPanel:oe,questionPanel:ie,onRewindSelect:ae,onRewindCancel:le,onLoginComplete:ce,onLoginCancel:ue,setShowProviderSelector:de,setShowModelSelector:me,setShowMemorySelector:pe,setShowMcpManager:ge,setShowAgentsConfig:he,setShowAddDirModal:fe,setShowUsageOverlay:ye,handleProviderSelect:we,handleProviderCancel:Se,handleModelSelect:be,handleModelCancel:Ee,handleCompactModeSelect:ve,handleCompactModeCancel:Ce,handleAuthSuccess:ke,handleAuthCancel:Te}){const _e=X(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),xe=useTerminalWidth(),Pe=X(()=>"off"===o?_e:getBudgetedFeed(_e,"limited"===o?15e3:5e4),[_e,o]),Ae=X(()=>"off"===o?0:Math.max(0,_e.length-Pe.length),[_e.length,Pe.length,o]),Ie=X(()=>0===Ae?Pe:Pe.filter(e=>"user"!==e.role),[Pe,Ae]),Ne=Z(()=>he(!1),[he]),Re=Z(()=>pe(!1),[pe]),$e=Z(()=>ge(!1),[ge]),Me=Z(()=>fe(!1),[fe]),Le=Z(()=>me(!0),[me]),De=!("off"!==o||oe||ie||y||w||P||S||E||v||C||k||T||_||x||i);return Q.createElement(ee,{flexDirection:"column",width:"100%"},Q.createElement(Ix,{staticKey:s,feed:Ie,showHeader:!0,expandedToolOutput:"off"!==o,currentModel:N,hiddenCount:Ae}),i&&Q.createElement(fP,{onComplete:se,autoLearn:a}),t.map(e=>e.metadata?.isAgent?Q.createElement(Rx,{key:e.id,entry:e}):Q.createElement(ee,{key:e.id,marginBottom:1,width:"90%"},renderFeedEntry(e,"off"!==o))),Q.createElement(RetryMessage,{attempt:l}),ie,oe,"off"!==o&&Q.createElement(ee,{flexDirection:"column",marginTop:1},Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},"─".repeat(xe))),Q.createElement(ee,{paddingRight:1},Q.createElement(te,{backgroundColor:Hn.BG,color:Hn.FG,bold:!0},`${Fk}DETAILED TRANSCRIPT${Fk}`),Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{bold:!0},"ctrl+o"),Q.createElement(te,{color:jn.DIM}," to toggle"),Q.createElement(te,{color:jn.DIM}," · "),Q.createElement(te,{bold:!0},"ctrl+e"),Q.createElement(te,{color:jn.DIM}," ","to"," ","limited"===o?"show all":"collapse"))),De&&Q.createElement(Cx,{queuedMessages:n,isProcessing:r,executionState:H,status:A,input:u,setInput:d,onSubmit:K,showFileList:h,setShowFileList:f,fileSearchQuery:m,setFileSearchQuery:g,onCommand:Y,outputTokens:z,contextUsage:W,tasteLearning:U,shareInfo:$,showShareNotification:M,unshareNotificationMessage:L,updateStatus:D,updateFailedInfo:O,creditWarning:F,currentProvider:I,showProviderInfo:R,permissionMode:q,onToggleAutoAccept:J,hintMessage:j,historyManager:G.current,pendingExitKey:B,onResetPendingExitKey:ne,onDoubleEscapeEmpty:re,retryAttempt:l,onAltP:Le}),y&&Q.createElement(ee,{marginY:1},Q.createElement(Dx,{onSelect:we,onCancel:Se,currentProvider:I})),w&&Q.createElement(ee,{marginY:1},Q.createElement(Lx,{onSelect:be,onCancel:Ee,currentModel:N})),x&&Q.createElement(ee,{marginY:1},Q.createElement(K_,{onSelect:ve,onCancel:Ce})),v&&Q.createElement(ee,{marginY:1},Q.createElement(Q_,{onCancel:Ne})),S&&Q.createElement(ee,{marginY:1},Q.createElement(_x,{onClose:Re})),E&&Q.createElement(ee,{marginY:1},Q.createElement(Tx,{onClose:$e})),C&&V.current&&Q.createElement(ee,{marginY:1},Q.createElement(Fx,{checkpoints:V.current.listCheckpoints(),onSelect:ae,onCancel:le})),P&&Q.createElement(ee,{marginY:1},Q.createElement(P.Component,{onSuccess:ke,onCancel:Te})),k&&Q.createElement(ee,{marginY:1},Q.createElement(kx,{onComplete:ce,onCancel:ue})),_&&Q.createElement(ee,{marginY:1},Q.createElement(N_,{onClose:Me})))},"MainView"));function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:s,onboarding:o,exitState:i,pendingOps:a,permissionState:l,contextEngineRef:u,historyManagerRef:d,executionState:m,actionCallbacks:g,onSubmit:h,onCommand:f,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,updateFailedInfo:v,creditWarning:C,handleTrust:k,handleNoTrust:T,handleToggleAutoAccept:_,handleDoubleEscapeEmpty:x,handleTasteOnboardingComplete:P,loadTasteStatus:A}){if(i.shouldExit)return null;if(o.checkingProject)return null;if(o.showTrustPrompt)return Q.createElement(WT,{staticKey:s.staticKey,onTrust:k,onExit:T});if(s.showSessionSelector)return Q.createElement(HT,{onSelectSession:g.onSelectSession,onNewSession:g.onNewSession});if(!o.projectTrusted)return null;const I=a.pendingQuestion?Q.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:s.setStaticKey}):null,N=a.pendingPermission?Q.createElement(r_,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:_}):null;return s.showLearningFeed?Q.createElement(LearningView,{setShowLearningFeed:s.setShowLearningFeed,setStaticKey:s.setStaticKey,onExit:()=>i.setShouldExit(!0)}):s.showTasteConfig?Q.createElement(TasteConfigView,{staticKey:s.staticKey,setShowTasteConfig:s.setShowTasteConfig,loadTasteStatus:A}):s.showSkillsConfig?Q.createElement(SkillsConfigView,{staticKey:s.staticKey,setShowSkillsConfig:s.setShowSkillsConfig}):s.showUsageOverlay?Q.createElement(UsageView,{staticKey:s.staticKey,setShowUsageOverlay:s.setShowUsageOverlay}):s.showContextView?Q.createElement(ContextConfigView,{staticKey:s.staticKey,contextEngineRef:u,setShowContextView:s.setShowContextView,setInput:w}):s.showStatusView?Q.createElement(StatusConfigView,{staticKey:s.staticKey,setShowStatusView:s.setShowStatusView,setInput:w}):Q.createElement(yP,{feed:e.feed,liveEntries:e.liveEntries,queuedMessages:e.queuedMessages,isCmdCodeBusy:e.isCmdCodeBusy,staticKey:s.staticKey,transcriptMode:s.transcriptMode,tasteOnboardingEntryId:o.tasteOnboardingEntryId,autoLearnTaste:o.autoLearnTaste,retryAttempt:n.retryAttempt,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,showFileList:s.showFileList,setShowFileList:s.setShowFileList,showProviderSelector:s.showProviderSelector,showModelSelector:s.showModelSelector,showMemorySelector:s.showMemorySelector,showMcpManager:s.showMcpManager,showAgentsConfig:s.showAgentsConfig,showRewindSelector:s.showRewindSelector,showLoginOverlay:s.showLoginOverlay,showUsageOverlay:s.showUsageOverlay,setShowUsageOverlay:s.setShowUsageOverlay,showAddDirModal:s.showAddDirModal,showCompactModeSelector:s.showCompactModeSelector,authComponentInfo:r.authComponentInfo,status:n.status,currentProvider:r.currentProvider,currentModel:r.currentModel,showProviderNotification:r.showProviderNotification,shareInfo:n.shareInfo,showShareNotification:n.showShareNotification,unshareNotificationMessage:n.unshareNotificationMessage,updateStatus:n.updateStatus,updateFailedInfo:v,creditWarning:C,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,tasteLearningEnabled:n.tasteLearningEnabled,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,historyManagerRef:d,executionState:m,contextEngineRef:u,onSubmit:h,onCommand:f,onToggleAutoAccept:_,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:x,onTasteOnboardingComplete:P,permissionPanel:N,questionPanel:I,onRewindSelect:g.onRewindSelect,onRewindCancel:g.onRewindCancel,onLoginComplete:g.onLoginComplete,onLoginCancel:g.onLoginCancel,setShowProviderSelector:s.setShowProviderSelector,setShowModelSelector:s.setShowModelSelector,setShowMemorySelector:s.setShowMemorySelector,setShowMcpManager:s.setShowMcpManager,setShowAgentsConfig:s.setShowAgentsConfig,setShowRewindSelector:s.setShowRewindSelector,setShowLoginOverlay:s.setShowLoginOverlay,setShowAddDirModal:s.setShowAddDirModal,handleProviderSelect:g.handleProviderSelect,handleProviderCancel:g.handleProviderCancel,handleModelSelect:g.handleModelSelect,handleModelCancel:g.handleModelCancel,handleCompactModeSelect:g.handleCompactModeSelect,handleCompactModeCancel:g.handleCompactModeCancel,handleAuthSuccess:g.handleAuthSuccess,handleAuthCancel:g.handleAuthCancel})}__name(renderView,"renderView");var wP=__name(({resume:e=!1,resumeSessionId:t,continue:n=!1,trust:r=!1,dangerouslySkipPermissions:s=!1,updateStatus:o,updateFailedInfo:i,initialPrompt:a,skipOnboarding:l=!1,initialPermissionMode:u})=>{const{exit:d}=ie(),{stdout:m}=re(),[g,h]=K(""),[f,y]=K(""),w=Y(!1),S=Y(!1),E=Y(null),v=Y(null),C=useUiOverlays(),k=useFeed(),T=useSession(),_=useStatus(o),x=useAuth(),P=usePendingOps(),A=useOnboarding(),I=useExit(),{executeBash:N,executionState:R}=xk(),$=usePermissionMode({initialPermissionMode:u,dangerouslySkipPermissions:s,setPendingPermission:P.setPendingPermission,setStatus:_.setStatus,contextEngineRef:v}),{createContextEngineCallbacks:M}=useContextEngine({sessionId:T.sessionId,sessionLoaded:T.sessionLoaded,showSessionSelector:C.showSessionSelector,projectTrusted:A.projectTrusted,setFeed:k.setFeed,setLiveEntries:k.setLiveEntries,setQueuedMessages:k.setQueuedMessages,queuedMessagesRef:k.queuedMessagesRef,setStatus:_.setStatus,pinnedStatusRef:_.pinnedStatusRef,setRetryAttempt:_.setRetryAttempt,setInteractionTokens:_.setInteractionTokens,setContextUsage:_.setContextUsage,setCurrentProvider:x.setCurrentProvider,shareInfoRef:_.shareInfoRef,permissionsService:$.permissionsService,permissionModeRef:$.permissionModeRef,setPendingQuestion:P.setPendingQuestion,contextEngineRef:v}),{onCommand:L}=useCommandCtx({feedState:k,sessionState:T,statusState:_,uiOverlays:C,onboarding:A,exitState:I,permissionState:$,contextEngineRef:v,isSubmittingRef:w,executeBash:N,createContextEngineCallbacks:M,setInput:h}),{loadTasteStatus:D,loadCurrentProvider:O,onSubmit:F}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:a,stdout:m,feedState:k,sessionState:T,statusState:_,authState:x,onboarding:A,uiOverlays:C,permissionState:$,contextEngineRef:v,isSubmittingRef:w,initialPromptSubmittedRef:S,historyManagerRef:E,executeBash:N,createContextEngineCallbacks:M,setInput:h,onCommand:L});useLifecycle({exit:d,feedState:k,exitState:I,statusState:_,authState:x,onboarding:A,uiOverlays:C,skipOnboarding:l});const{handleToggleAutoAccept:q,handleDoubleEscapeEmpty:j,handleTasteOnboardingComplete:B,handleTrust:U,handleNoTrust:z}=useHandlers({resume:e,feedState:k,onboarding:A,uiOverlays:C,exitState:I,pendingOps:P,permissionState:$,statusState:_,authState:x,contextEngineRef:v,loadTasteStatus:D,loadCurrentProvider:O,setInput:__name(e=>h(e),"setInput")}),W=useMainActionCallbacks({feedState:k,sessionState:T,statusState:_,authState:x,uiOverlays:C,permissionState:$,contextEngineRef:v,createContextEngineCallbacks:M,setInput:h}),{creditWarning:G}=useCreditWarning({interactionTokens:_.interactionTokens});return renderView({feedState:k,sessionState:T,statusState:_,authState:x,uiOverlays:C,onboarding:A,exitState:I,pendingOps:P,permissionState:$,contextEngineRef:v,historyManagerRef:E,executionState:R,actionCallbacks:W,onSubmit:F,onCommand:L,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,updateFailedInfo:i,creditWarning:G,handleTrust:U,handleNoTrust:z,handleToggleAutoAccept:q,handleDoubleEscapeEmpty:j,handleTasteOnboardingComplete:B,loadTasteStatus:D})},"InteractiveCLI");vr(),qn(),vv();var SP=__name(e=>e?{isValid:!0}:{isValid:!1,errorMessage:["Error: Interactive mode requires a TTY terminal.","Please run this command directly in your terminal, not through a pipe or redirect."].join("\n")},"validateTtyEnvironment"),bP=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),EP=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),vP=__name(({options:e,resumeSessionId:t})=>{let n;return e.permissionMode?n=e.permissionMode:e.plan&&(n="plan"),{resume:"boolean"==typeof e.resume?e.resume:void 0,resumeSessionId:t,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding,initialPermissionMode:n}},"buildInteractiveCLIProps"),CP=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),kP=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),TP=__name(()=>{kP()},"initializeTerminal"),_P=__name(async(e={})=>{const t=SP(process.stdin.isTTY);let n;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),TP(),"string"==typeof e.resume){const t=e.resume;await hv.isProjectInitialized()||(console.error("Project not initialized. Run cmd to start a conversation first."),process.exit(1));const r=await hv.findSessionByName(t);r||(console.error(`No session named "${t}" found.`),process.exit(1)),n=r.id}if(bP(e)&&!n){const e=await hv.isProjectInitialized(),t=e?await hv.listSessions():[],n=EP({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const r=vP({options:e,resumeSessionId:n}),s=CP();oe(Q.createElement(wP,{...r}),s)},"interactiveMode");en(),Ht(),Kt(),rk(),VC();var xP=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.error(`${ke.cross} Authentication failed. Please try again with: cmd login`),!1)}catch(e){return isUserCancellation(e)||(console.error(`${ke.cross} Login failed: ${getErrorMessage(e)}`),console.error("Please try again with: cmd login")),!1}},"attemptLogin");async function ensureAuthenticated(){try{return!!await getAuthKey()||xP()}catch(e){return console.error("Error checking authentication:",e),!1}}__name(ensureAuthenticated,"ensureAuthenticated");var PP=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),AP=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth"),IP=__name(e=>{const t={};return e.trust&&(t.trust=!0),e.dangerouslySkipPermissions&&(t.dangerouslySkipPermissions=!0,t.trust=!0),e.skipOnboarding&&(t.skipOnboarding=!0),e.plan&&(t.plan=!0),e.permissionMode&&(t.permissionMode=e.permissionMode),t},"buildRuntimeOptions"),NP=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:e.resume,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),RP=__name((e,t)=>"string"==typeof e.print&&e.print.trim()?e.print:t&&!t.startsWith("-")?t:"","extractPrintQuery");async function interactiveModeAction(e,t){if(t.addDir&&t.addDir.length>0)for(const e of t.addDir)addDirectory(e);if(void 0!==t.print){const n=RP(t,e);return void await printMode({query:n,dangerouslySkipPermissions:t.dangerouslySkipPermissions,maxTurns:t.maxTurns,verbose:t.verbose,model:t.model,benchmarkOutput:t.benchmarkOutput})}const n=PP(e);await AP();const r=IP(t),s=NP({options:t,runtimeOptions:r,initialPrompt:n});_P(s)}__name(interactiveModeAction,"interactiveModeAction"),Ht(),In(),Cs(),xr(),HC(),rk(),globalThis.COMMAND_CODE_CWD=process.cwd();var $P=__name(()=>process.cwd(),"getCwd"),MP=__name(()=>process.argv.slice(2),"getArgs"),LP=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),DP=__name(()=>{const e=$P(),t=MP(),n=LP(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){DP(),process.argv.includes("--ide-setup")&&(formatSetupResult(await runIDESetup()).forEach(e=>console.log(e)),process.exit(0)),await maybeRunPendingUpdate(),await migrateDeprecatedModel(),await getAuthKey()&&detectAndTrackFirstInstall().catch(()=>{}),checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100)}__name(preRun,"preRun"),Ht(),Kt(),In(),Ur(),jb(),Nr();var OP=getPackageJson(),FP=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=OP.version,t=getInvokedCommandName(),n=$b.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(le.bold("Command Code")+le.gray(` v${e}`)),console.log(le.gray(Ab)),console.log(),console.log(le.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(le.bold("Options"));for(const e of Rb){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ib)+le.gray(e.description))}console.log(),console.log(le.bold("Commands"));for(const e of Mb){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ib)+le.gray(e.description))}console.log(),console.log(le.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Ib)+le.gray(e.description));console.log(),console.log(le.bold("Keyboard Shortcuts"));for(const e of Nb)console.log(" "+e.key.padEnd(Ib)+le.gray(e.description));console.log(),console.log(le.bold("Examples"));for(const e of Db){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Ib)+le.gray(e.description))}console.log(),console.log(le.cyan("❯")+" "+le.gray(Ob.replace(/cmd/,t))),console.log(),console.log(le.bold("Links"));for(const e of Lb)console.log(" "+e.key.padEnd(Ib)+le.cyan(e.description));console.log()}function createProgram(){const e=new ve;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(OP.version,"-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume [name]","Resume a session by name, or pick from history").option("-c, --continue"," Continue the most recent session in the current directory").option("-t, --trust","Trust the project (skip initial trust permission prompt)").addOption(new Ce("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Ce("--yolo","Bypass all permission prompts (alias for --dangerously-skip-permissions)").implies({dangerouslySkipPermissions:!0})).option("--plan","Start in plan mode (read-only exploration and planning)").addOption(new Ce("--auto-accept","Start in auto-accept mode").implies({permissionMode:"auto-accept"})).addOption(new Ce("--permission-mode <mode>","Set permission mode").choices(["standard","plan","auto-accept"])).option("--skip-onboarding","Skip taste onboarding (for non-interactive/automated runs)").option("-p, --print [query]","Run in non-interactive mode, output response and exit").option("--max-turns <number>","Maximum conversation turns in print mode (default: 10)",e=>{const t=parseInt(e,10);if(isNaN(t)||t<1)throw new Error("--max-turns must be a positive integer");return t}).option("--verbose","Stream tool execution progress to stderr in print mode").option("--ide-setup","Setup extension to fetch IDE context").option("--add-dir <directory>","Add directory to workspace context",FP,[]).addOption(new Ce("--model <model>","Override model for this run").hideHelp()).addOption(new Ce("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Ce("--experimental","Enable experimental features").hideHelp()).addOption(new Ce(Et).hideHelp()).addOption(new Ce(vt).hideHelp()).addOption(new Ce("-d, --debug","Enable debug mode").hideHelp()).addOption(new Ce("--local","Use local server").hideHelp()).addOption(new Ce("--staging","Use staging server").hideHelp()).helpOption("-h, --help","Display help message").allowUnknownOption(),e.configureHelp({formatHelp:__name(()=>(displayCustomHelp(),""),"formatHelp")}),e}function setupCommanderHooks(e){e.hook("preAction",(e,t)=>{dlogSection("cmd");const n=t.name(),r=t.parent?.name();dlog(`[cmd] ${r&&r!==n?"subcommand":"running"}: ${n}`);const s=t.opts(),o=Object.entries(s).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");o&&dlog(`[cmd] options: ${o}`);const i=t.args;i.length>0&&dlog(`[cmd] arguments: ${i.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}function isTTY(){return Boolean(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.CI)}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Ht(),Cs(),Kr(),_C(),sk(),Jv(),Ur(),rk(),Ht(),__name(isTTY,"isTTY");var qP=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),trackCliSessionExistsEvent(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=y.platform(),n=y.arch();let r,s,o,i;try{const e=await getAuthenticatedEntity();e.success&&(r=e.user?.userName,s=e.user?.id,o=e.org?.login,i=e.org?.id)}catch{}if(!s)try{const e=await loadCredentials();s=e?.userId}catch{}systemInfo({userName:r,userId:s,orgLogin:o,orgId:i,nodeVersion:e,platform:t,arch:n})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){qP||(qP=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function trackCliSessionExistsEvent(){try{if(!await getAuthKey())return;const e=getSessionId();if(!e)return;const t=getPackageJson().version||"unknown",n=y.platform(),r=y.arch(),s=isTTY()?"interactive":"non-interactive";await trackLifecycleEvent({eventType:"cli_session_exists",metadata:{sessionId:e,cliVersion:t,mode:s,os:`${n}-${r}`}})}catch{}}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Te("Opening GitHub issues...").start();try{await me(t,{wait:!1,background:!0}),n.succeed(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`),console.log("")}catch(e){n.fail("Failed to open browser"),console.log(""),console.log(createOSC8Link(t,"Open GitHub issue manually")),console.log("")}}__name(setupTelemetry,"setupTelemetry"),__name(trackSystemInfo,"trackSystemInfo"),__name(registerCleanupHandlers,"registerCleanupHandlers"),__name(handleShutdownSignal,"handleShutdownSignal"),__name(trackCliSessionExistsEvent,"trackCliSessionExistsEvent"),rk(),Ht(),LC(),__name(openGitHubIssue,"openGitHubIssue");var jP=new ve("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Ht();var BP=new ve("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const{waitUntilExit:t}=oe(Q.createElement(xT,{verbose:e.verbose,text:e.text}));await t()}Ht(),Ht(),__name(runInfo,"runInfo");var UP=new ve("info").description("Display system information").option("--verbose","Show detailed CPU and network information").option("--text","Print plain text without colors").allowUnknownOption().allowExcessArguments().action(async e=>{await runInfo(e)});function runLearnTaste(){const{unmount:e}=oe(Q.createElement(gP,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}Ht(),Kt(),Ht(),__name(runLearnTaste,"runLearnTaste"),In(),Cs();var zP=new ve($t.LEARN_TASTE).description("Learn from your previous sessions - updates your taste profile").allowUnknownOption().allowExcessArguments().action(async()=>{try{runLearnTaste()}catch(e){trackError({error:sanitizeErrorForTelemetry({error:e instanceof Error?e:new Error(String(e)),label:"learn_taste_render_failed"}),context:{component:ys.LEARN_TASTE_COMMAND,heading:"Learn taste render failed"}}),dlog(`[/learn-taste] render failed: ${e instanceof Error?e.message:String(e)}`),await shutdownTelemetry(),process.exit(1)}});function addMcpCommand(){const e=new ve("add");return e.description("Add an MCP server").argument("<name>","Server name (unique identifier)").argument("[url]","Server URL (required for http transport)").option("-t, --transport <type>","Transport type (stdio or http)","stdio").addOption(new Ce("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("-e, --env <KEY=value>","Environment variable (repeatable)",collectKeyValue,{}).option("-H, --header <header>","HTTP header (repeatable, http only)",collectHeaders,{}).allowUnknownOption().allowExcessArguments().action(async(e,t,n,r)=>{const s=getInvokedCommandName();try{let o;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(le.red(`Error: Invalid server name '${e}'`)),console.error(le.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1)),"stdio"!==n.transport&&"http"!==n.transport&&(console.error(le.red(`Error: Invalid transport type '${n.transport}'`)),console.error(le.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(le.red("Error: URL is required for http transport")),console.error(le.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(le.red(`Error: Invalid URL '${t}'`)),process.exit(1)}o={transport:"http",enabled:!0,url:t,...Object.keys(n.header).length>0&&{headers:n.header},...Object.keys(n.env).length>0&&{env:n.env}},console.log(le.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(le.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(le.cyan("Server requires OAuth authentication."));let t,n="command-code";if(r.metadata.registrationEndpoint){console.log(le.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${iE}/callback`]});e&&(n=e.clientId,t=e.clientSecret)}o.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},console.log(le.gray("A browser window will open for authentication.\n"));const s=await performOAuthFlow(e,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:n,clientSecret:t,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(le.gray(` ${e}`))},"onStatus")});s.success?console.log(le.green("✓ Successfully authenticated")):(i=!0,console.log(le.yellow(`Warning: Authentication failed: ${s.error}`)),console.log(le.gray("You can retry with: cmd mcp auth "+e)),console.log(le.gray("Or authenticate via the /mcp menu in a session")))}}else{const s=r.args,i=process.argv.indexOf("--");let a,l=[];if(-1!==i){const e=process.argv.slice(i+1);0===e.length&&(console.error(le.red("Error: Command is required for stdio transport")),console.error(le.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),process.exit(1)),a=e[0],l=e.slice(1)}else if(t){a=t;const n=s.indexOf(e);-1!==n&&s.length>n+2&&(l=s.slice(n+2))}else console.error(le.red("Error: Command is required for stdio transport")),console.error(le.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(le.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);o={transport:"stdio",enabled:!0,command:a,...l.length>0&&{args:l},...Object.keys(n.env).length>0&&{env:n.env}}}await addMcpServer({name:e,serverConfig:o,scope:n.scope});const a="user"===n.scope?"global":"project"===n.scope?"project":"local";if(i?console.log(le.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(le.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===o.transport)console.log(le.gray(` URL: ${o.url}`));else{const e=[o.command,...o.args||[]].join(" ");console.log(le.gray(` Command: ${e}`))}console.log(""),console.log(le.cyan("Next steps:")),console.log(le.gray(`Start ${s} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function collectKeyValue(e,t){const[n,...r]=e.split("=");return n&&0!==r.length||(console.error(le.red(`Error: Invalid format '${e}', expected KEY=value`)),process.exit(1)),t[n]=r.join("="),t}function collectHeaders(e,t){const n=e.indexOf(":");-1===n&&(console.error(le.red(`Error: Invalid header format '${e}', expected 'Header: value'`)),process.exit(1));const r=e.substring(0,n).trim(),s=e.substring(n+1).trim();return r||(console.error(le.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=s,t}function listMcpCommand(){const e=new ve("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(le.yellow("\nNo MCP servers configured\n")),console.log(le.gray("Add a server with:")),console.log(le.gray(" cmd mcp add --transport http <name> <url>")),console.log(le.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(le.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(le.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(le.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const s of e){const e=s.config.enabled?le.green("enabled"):le.gray("disabled");let o;o=s.config.oauth?await hasTokens(s.name)?le.green(ke.tick):le.red(ke.cross):s.config.headers||s.config.env?le.green(ke.tick):le.gray("-"),console.log(` ${le.white(s.name.padEnd(t))} ${le.cyan(s.config.transport.padEnd(n))} ${le.gray(s.scope.padEnd(r))} ${o} ${e}`)}console.log(le.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new ve("get");return e.description("Show details for an MCP server").argument("<name>","Server name").action(async e=>{try{const t=await getMcpServer({name:e});t||(console.error(le.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(le.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${le.dim("Scope:")} ${r}`),console.log(` ${le.dim("Transport:")} ${n.transport}`),console.log(` ${le.dim("Status:")} ${n.enabled?le.green("enabled"):le.gray("disabled")}`),"http"===n.transport){if(console.log(` ${le.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${le.dim("Headers:")}`);for(const[e,t]of Object.entries(n.headers)){const n=e.toLowerCase().includes("auth")||e.toLowerCase().includes("token")||e.toLowerCase().includes("key")?"***":t;console.log(` ${e}: ${n}`)}}}else console.log(` ${le.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${le.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${le.dim("Environment:")}`);for(const[e,t]of Object.entries(n.env)){const n=e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token")||e.toLowerCase().includes("password")?"***":t;console.log(` ${e}=${n}`)}}console.log("")}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new ve("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Ce("-s, --scope <scope>","Scope to remove from (auto-detects if not specified)").choices(["local","project","user"])).action(async(e,t)=>{try{const n=await getMcpServer({name:e});n||(console.error(le.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(le.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(le.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const s="user"===r?"global":"project"===r?"project":"local";console.log(le.green(`✓ Removed MCP server '${e}' from ${s} config`))}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new ve("add-json");return e.description("Add an MCP server from JSON configuration").argument("<name>","Server name (unique identifier)").argument("<json>","Server configuration as JSON string").addOption(new Ce("-s, --scope <scope>","Configuration scope").choices(["local","project","user"]).default("local")).option("--client-secret <secret>","OAuth client secret (injected into oauth config)").action(async(e,t,n)=>{const r=getInvokedCommandName();try{let s,o;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(le.red(`Error: Invalid server name '${e}'`)),console.error(le.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1));try{s=JSON.parse(t)}catch{console.error(le.red("Error: Invalid JSON")),console.error(le.gray("Make sure to quote the JSON string properly")),console.error(le.gray(`Example: ${r} mcp add-json github '{"type":"stdio","command":"npx"}'`)),process.exit(1)}s&&"object"==typeof s&&"type"in s&&!("transport"in s)&&(s.transport=s.type,delete s.type),s?.oauth?.callbackPort&&(o=s.oauth.callbackPort,delete s.oauth.callbackPort),n.clientSecret&&s?.oauth&&(s.oauth.clientSecret=n.clientSecret);const i=Kb.safeParse(s);if(!i.success){console.error(le.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(le.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(le.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(le.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(le.cyan("Starting OAuth authentication...")),console.log(le.gray("A browser window will open for authentication.\n"));const t={authorizationUrl:a.oauth.authorizationUrl,tokenUrl:a.oauth.tokenUrl,clientId:a.oauth.clientId,clientSecret:a.oauth.clientSecret,scopes:a.oauth.scopes},n=await performOAuthFlow(e,t,{...o&&{port:o},onStatus:__name(e=>{console.log(le.gray(` ${e}`))},"onStatus")});n.success?console.log(le.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(le.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(le.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(le.gray("Or authenticate via the /mcp menu in a session")))}const u="user"===n.scope?"global":"project"===n.scope?"project":"local";if(l?console.log(le.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(le.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(le.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(le.gray(` Command: ${e}`))}console.log(""),console.log(le.cyan("Next steps:")),console.log(le.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new ve("auth");return e.description("Manage OAuth authentication for MCP servers").argument("[server]","Server name to authenticate").option("--status","Check authentication status").option("--clear","Clear stored authentication").option("--list","List servers with stored authentication").action(async(e,t)=>{const n=getInvokedCommandName();try{if(t.list){const e=await listServersWithTokens();if(0===e.length)return void console.log(le.yellow("No servers with stored authentication."));console.log(le.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?le.yellow("expired"):le.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(le.red("Error: Server name is required")),console.error(le.gray(`Usage: ${n} mcp auth <server>`)),console.error(le.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(le.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(le.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(le.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(le.gray(" A refresh token is available for re-authentication"));else{if(console.log(le.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(le.gray(` Expires in ${e} minutes`))}t.scope&&console.log(le.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(le.green(`✓ Cleared authentication for '${e}'`)):console.log(le.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(le.red(`Error: MCP server '${e}' not found`)),console.error(le.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),r.config.oauth||(console.error(le.red(`Error: Server '${e}' does not have OAuth configured`)),console.error(le.gray(`Add OAuth config using "${n} mcp add-json" with oauth field`)),process.exit(1));const s={authorizationUrl:r.config.oauth.authorizationUrl,tokenUrl:r.config.oauth.tokenUrl,clientId:r.config.oauth.clientId,clientSecret:r.config.oauth.clientSecret,scopes:r.config.oauth.scopes};console.log(le.cyan(`Authenticating with '${e}'...`)),console.log(le.gray("A browser window will open for authentication.\n"));const o=await performOAuthFlow(e,s,{onStatus:__name(e=>{console.log(le.gray(` ${e}`))},"onStatus")});if(o.success)return console.log(le.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(le.gray("Restart the session to connect with the authenticated server."));console.error(le.red(`\nError: Authentication failed: ${o.error}`)),console.log(le.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(le.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new ve("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}async function runCommand(e){return new Promise((t,n)=>{const r=M(e.cmd,e.args,{stdio:["ignore","pipe","pipe"],env:process.env});let s="",o="";r.stdout.on("data",e=>{s+=String(e)}),r.stderr.on("data",e=>{o+=String(e)}),r.on("error",n),r.on("close",r=>{0!==r?n(new Error(`${e.cmd} ${e.args.join(" ")} failed${o?`: ${o.trim()}`:""}`)):t({stdout:s,stderr:o})})})}async function detectDefaultBranch(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"symbolic-ref","refs/remotes/origin/HEAD","--short"]}),n=t.trim().replace(/^origin\//,"");if(n)return n}catch{}for(const t of["main","master"])try{return await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--verify",t]}),t}catch{}try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--abbrev-ref","HEAD"]});return t.trim()}catch{return"main"}}async function findGitRoot4(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.dir,"rev-parse","--show-toplevel"]});return t.trim()}catch{return null}}async function countLearnings(e){try{return(await D.readFile(e,"utf-8")).split("\n").filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:")).length}catch{return 0}}async function resolveSource(t){const n=t.source.trim(),r=e.resolve(n);try{if(!(await D.stat(r)).isDirectory())throw new Error(`Source must be a repository directory: ${n}`);return{type:"local",displayName:r,repoDir:r,repoName:e.basename(r),github:await inferGitHubRepo({repoDir:r})}}catch(e){if(e instanceof Error&&e.message.startsWith("Source must be"))throw e}const s=parseGitHubSource({source:n});if(!s){const e=n.startsWith("git@")?" SSH URLs are not supported. Use HTTPS or owner/repo instead.":"";throw new Error(`Unsupported source '${n}'.${e} Use a local path, GitHub HTTPS URL, or owner/repo.`)}const o=String(t.maxCommits??200),i=`https://github.com/${s.owner}/${s.repo}.git`,a=await D.mkdtemp(e.join(y.tmpdir(),"taste-learn-"));try{await runCommand({cmd:"git",args:["clone","--depth",o,"--single-branch",...t.branch?["--branch",t.branch]:[],"--",i,a]})}catch{throw await D.rm(a,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Repository not found: ${s.owner}/${s.repo}. Check the owner and repo name, or verify it's a public repository.`)}return{type:"github",displayName:`${s.owner}/${s.repo}`,repoDir:a,repoName:s.repo,github:s,cleanup:__name(async()=>{await D.rm(a,{recursive:!0,force:!0})},"cleanup")}}function getTastePathForDir(t){return e.join(t.projectRoot,".commandcode","taste")}async function resolveDisplayName(t){if(t.startsWith("/")||t.startsWith(".")){const n=e.resolve(t),r=await findGitRoot4({dir:n});return r?e.basename(r):e.basename(n)}return t}function parseGitHubSource(e){const t=e.source.match(/^([\w.-]+)\/([\w.-]+)$/);if(t)return{owner:t[1],repo:t[2].replace(/\.git$/,"")};try{const t=new URL(e.source);if("github.com"!==t.hostname)return null;const n=t.pathname.split("/").filter(Boolean);return n.length<2?null:{owner:n[0],repo:n[1].replace(/\.git$/,"")}}catch{return null}}async function inferGitHubRepo(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"remote","get-url","origin"]});return parseGitHubSource({source:t.trim()})??void 0}catch{return}}async function feedToLearningAgent(e){const t=await getConfiguredProvider(),n=await getOAuthCredentials({provider:t});if(await isOAuthEnforced()&&!n?.token)throw new Error("Authentication required. Run: cmd login");n?.token&&validateOAuthToken({token:n.token,provider:t});const r=getApiBaseUrl(),s=new xy({baseUrl:r}),o=new rC({request:s,sessionId:crypto.randomUUID(),projectRoot:e.outputDir}),i=[{role:"user",content:e.compiledContext}];await o.checkAndProcess({messages:i})}function logLearnSummary(e){const{summary:t}=e;console.log(le.cyan("\n ─── Results ───\n")),console.log(` Source: ${t.sourceName}`),console.log(` Signals: ${t.signalCount} extracted`),console.log(` Context: ${t.contextLength} chars compiled`),console.log(` Taste dir: ${t.tasteDir}`),console.log("")}function shouldContinueExtraction(e){return!(e.offset>=e.commitsLength||e.signalCount>=e.signalCap||e.commitsWithDiffs>=50)}async function extractAllSignals(e){e.onProgress?.("Collecting commits");const t=await collectCommits(e);if(0===t.length)return e.onProgress?.("No commits found"),{signals:[],commitCount:0};e.onProgress?.(`Found ${t.length} commits to analyze`);const n=e.maxSignals??50,r=[];let s=0;for(let o=0;shouldContinueExtraction({offset:o,commitsLength:t.length,signalCount:r.length,signalCap:n,commitsWithDiffs:s});o+=10){const i=t.slice(o,o+10);if(0===i.length)break;const a=await runBounded(5,i,async t=>({commit:t,subs:await getSubstitutions(e.repoDir,t.hash)}));for(const{commit:e,subs:t}of a){if(0===t.length)continue;s++;const o=groupCrossFilePatterns(t);for(const t of o.slice(0,5)){if(t.removed.length>200||t.added.length>200)continue;const s=[`Commit: ${e.subject}`];s.push(`File: ${t.file}`),t.context&&s.push(`In: ${t.context}`);const o=buildSnippet(t.codeBefore,t.added,t.codeAfter);if(o&&s.push(o),r.push({text:`${truncate2(t.removed,60)} → ${truncate2(t.added,60)}`,evidence:s,category:inferCategory(t.removed,t.added)}),r.length>=n)break}if(r.length>=n)break}}return e.onProgress?.(`Extracted ${r.length} diff signals from ${s} commits`),{signals:r,commitCount:t.length}}async function collectCommits(e){const t=buildAuthorPattern(e.author,e.authorAliases),n=t?.includes("|")??!1,r=t?[...n?["--extended-regexp"]:[],"--author",t,"--regexp-ignore-case"]:[],s=e.branch?[e.branch]:[],o=e.author?e.maxCommits:3*e.maxCommits,{stdout:i}=await runCommand({cmd:"git",args:["-C",e.repoDir,"log",...s,"--no-merges",...r,"--pretty=format:%H%x1f%aI%x1f%aN%x1f%s%x1e","-n",String(o)]});return i.split("").map(e=>e.trim()).filter(Boolean).map(e=>{const[t="",n="",r="",s=""]=e.split("");return{hash:t.trim(),subject:s.trim(),authorDate:n.trim(),authorName:r.trim()}}).filter(e=>!isDependencyBot(e.authorName,e.subject)).slice(0,e.maxCommits)}async function getSubstitutions(e,t){try{const{stdout:n}=await runCommand({cmd:"git",args:["-C",e,"show","--format=","-U3","--diff-algorithm=histogram","-b","--ignore-blank-lines","-M",t]}),r=[];let s="",o="",i=[],a=[],l=[];const u=2;let d=null;const m=__name(()=>{d&&(r.push({removed:d.removed,added:d.added,file:d.file,context:d.context,codeBefore:d.codeBefore.length>0?d.codeBefore:void 0,codeAfter:d.codeAfter.length>0?d.codeAfter:void 0}),d=null)},"commitPending"),g=__name(()=>{if(i.length>0&&a.length>0){const e=i.join("\n").trim(),t=a.join("\n").trim();e===t||isVersionBump(e,t)||isTrivialChange(e,t)||(m(),d={removed:e,added:t,file:s,context:o||void 0,codeBefore:[...l],codeAfter:[]})}i=[],a=[]},"flush");for(const e of n.split("\n")){if(e.startsWith("diff --git")){g(),m(),s=e.match(/b\/(.+)$/)?.[1]??"",o="",l=[],isNoiseFile(s)&&(s="");continue}if(e.startsWith("@@")){g(),m(),o=e.match(/@@ .+ @@\s*(.+)/)?.[1]?.trim()??"",l=[];continue}if(!s)continue;if(e.startsWith("-")&&!e.startsWith("---")){a.length>0&&g(),i.push(e.slice(1));continue}if(e.startsWith("+")&&!e.startsWith("+++")){a.push(e.slice(1));continue}g();const t=e.startsWith(" ")?e.slice(1):e;if(!t.trim())continue;const n=d;null!==n&&n.codeAfter.length<u&&(n.codeAfter.push(t),n.codeAfter.length>=u&&m()),l.push(t),l.length>u&&l.shift()}return g(),m(),r}catch(e){return process.env.DEBUG&&console.error(`[taste-learn] getSubstitutions failed for ${t}:`,e instanceof Error?e.message:e),[]}}function groupCrossFilePatterns(e){const t=new Map;for(const n of e){const e=`${n.removed.trim()}\0${n.added.trim()}`,r=t.get(e)??[];r.push(n),t.set(e,r)}const n=[];for(const[,e]of t)if(e.length>=2){const t=e.map(e=>e.file).join(", ");n.push({...e[0],file:t,context:`Same change across ${e.length} files`})}else n.push(e[0]);return n}Ht(),Ht(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Ht(),__name(listMcpCommand,"listMcpCommand"),Ht(),__name(getMcpCommand,"getMcpCommand"),Ht(),__name(removeMcpCommand,"removeMcpCommand"),Ht(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Ht(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Ht(),Kt(),Ht(),bC(),Ht(),Kt(),Ht(),__name(runCommand,"runCommand"),Ht(),__name(detectDefaultBranch,"detectDefaultBranch"),__name(findGitRoot4,"findGitRoot"),__name(countLearnings,"countLearnings"),__name(resolveSource,"resolveSource"),__name(getTastePathForDir,"getTastePathForDir"),__name(resolveDisplayName,"resolveDisplayName"),__name(parseGitHubSource,"parseGitHubSource"),__name(inferGitHubRepo,"inferGitHubRepo"),Ht(),cC(),Wy(),Xy(),xr(),Rr(),__name(feedToLearningAgent,"feedToLearningAgent"),__name(logLearnSummary,"logLearnSummary"),Ht(),tC(),Ht(),__name(shouldContinueExtraction,"shouldContinueExtraction"),__name(extractAllSignals,"extractAllSignals"),__name(collectCommits,"collectCommits"),__name(getSubstitutions,"getSubstitutions"),__name(groupCrossFilePatterns,"groupCrossFilePatterns");var WP=5,GP=3;function buildSnippet(e,t,n){const r=e??[],s=n??[],o=t.split("\n").map(e=>e.trimEnd());if(0===o.length&&0===r.length&&0===s.length)return;let i,a=0;o.length>GP?(i=o.slice(0,GP-1),a=o.length-i.length):i=o;const l=i.length+(a>0?1:0),u=Math.max(0,WP-l),d=Math.min(r.length,Math.ceil(u/2)),m=Math.min(s.length,u-d),g=[];for(const e of r.slice(-d))g.push(` ${e.trimEnd()}`);for(const e of i)g.push(`→ ${e}`);a>0&&g.push(`→ ... (+${a} more changed ${1===a?"line":"lines"})`);for(const e of s.slice(0,m))g.push(` ${e.trimEnd()}`);return 0!==g.length?`Snippet:\n${g.join("\n")}`:void 0}__name(buildSnippet,"buildSnippet");var HP=[/package-lock\.json$/,/pnpm-lock\.yaml$/,/yarn\.lock$/,/CHANGELOG\.(md|yml|yaml)$/i,/\.versionbot\//,/\.min\.(js|css)$/,/dist\//,/\.map$/];function isNoiseFile(e){return HP.some(t=>t.test(e))}function isTrivialChange(e,t){return e.trim().length<3&&t.trim().length<3}function isVersionBump(e,t){const n=/^"?version"?\s*:\s*"?\d+\.\d+/;return n.test(e.trim())&&n.test(t.trim())}function inferCategory(e,t){const n=`${e} ${t}`.toLowerCase();return/import|require|from\s+['"]/.test(n)?"imports":/function|=>|async|return/.test(n)?"code-style":/class|interface|type\s+/.test(n)?"types":/test|describe|it\(|expect/.test(n)?"testing":/console|log|debug|error/.test(n)?"logging":/try|catch|throw|Error/.test(n)?"error-handling":"code-style"}function buildAuthorPattern(e,t){return t&&t.length>0?t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"):e??void 0}__name(isNoiseFile,"isNoiseFile"),__name(isTrivialChange,"isTrivialChange"),__name(isVersionBump,"isVersionBump"),__name(inferCategory,"inferCategory"),__name(buildAuthorPattern,"buildAuthorPattern");var QP=new Set(["renovate[bot]","renovate","dependabot[bot]","dependabot","greenkeeper[bot]","snyk-bot"]),VP=[/^update .+ digest to /i,/^update .+ action to /i,/^update .+ to v?\d/i,/^update lock file maintenance/i,/^update dependency .+ to /i,/^chore\(deps\)/i,/^bump .+ from .+ to /i,/^lock file maintenance/i];function isDependencyBot(e,t){const n=e.toLowerCase();return!!QP.has(n)||!(!n.includes("[bot]")||!VP.some(e=>e.test(t)))}function truncate2(e,t){const n=e.replace(/\n/g," ").trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}async function runBounded(e,t,n){const r=[];let s=0;const o=__name(async()=>{for(;s<t.length;){const e=s++;r[e]=await n(t[e])}},"next");return await Promise.all(Array.from({length:Math.min(e,t.length)},()=>o())),r}function compileTasteContext(e){const{signals:t,repoName:n,author:r,commitCount:s}=e,o=r?`Target author: ${r}\n`:"",i=[];if(i.push(`# Dynamic Taste Analysis — Code Change Patterns\n\nRepository: ${n}\n${o}Commits analyzed: ${s}\nSignals extracted: ${t.length}\n\nThis analysis was generated by examining actual code changes (diffs, substitutions, refactoring patterns) rather than static file contents. Every signal below comes from real commits.`),t.length>0){const e=["## Correction Diffs — What Wrong→Right Looks Like"];for(const n of t.slice(0,50)){e.push(`\n**${n.text}**`);for(const t of n.evidence)e.push(`- ${t}`)}i.push(e.join("\n"))}const a=r?` for ${r}`:"";return i.push(`## Instructions for Taste Learning\n\nYou are analyzing code change patterns from a real repository${a}. Based on the correction diffs above, generate deeply personal and opinionated coding taste.\n\n**Critical guidelines:**\n\n1. **Be specific, not generic.** Instead of "Use TypeScript", write "Use branded types for IDs and explicit return types on every function. Prefer \`readonly\` arrays and objects by default."\n\n2. **Extract the WHY from patterns.** If you see verbose names being replaced with concise ones, don't just say "use short names" — say "Prefer concise variable names that derive meaning from context rather than encoding type information."\n\n3. **Look for recurring themes.** If multiple substitutions show the same pattern (e.g., nested if→guard clauses), that's a strong taste signal worth capturing.\n\n4. **Make it actionable.** Every taste entry should be specific enough that another developer could follow it and produce code that looks like it belongs in this repository.\n\n5. **Prioritize quality corrections** — these are the purest taste signals (wrong→right pairs with explicit WHY context from commit messages).\n\n6. **Capture anti-patterns too.** If you see code being removed in refactors, note what the developer avoids: "Never nest deeper than 2 levels — flatten with early returns."\n\n7. **Don't repeat generic tool preferences** like "Use pnpm" or "Use TypeScript" unless the substitutions show something specific about HOW they use those tools.\n\n8. **Prioritize opinionated preferences.** The goal is taste that makes someone's code distinctly theirs — not industry best practices.\n\nWrite the taste entries to the taste.md file using the standard format with confidence scores.`),i.join("\n\n")}async function runLearnPipeline(t){const n=__name(()=>({outputDir:"",tasteDir:"",sourceName:t.source,signalCount:0,contextLength:0}),"abortedResult");if(t.needsAuth){Zv.addEvent({type:"auth_required",step:"auth",message:"Login to synthesize your taste profile",label:"Signing in"});try{await Zv.waitForAuth()}catch{return Zv.emitStepStart({step:"complete",label:"Login skipped",message:"Login skipped",learningCount:0,storage:""}),Zv.markLearningComplete(),{summary:n()}}}t.isLocalSource||Zv.emitStepStart({step:"cloning",label:"Cloning repository",message:`Cloning ${t.source}`});const r=await resolveSource({source:t.source,maxCommits:t.maxCommits});if(t.signal.aborted)return{summary:n(),resolved:r};const s="github"===r.type,o=r.repoName,i=await findGitRoot4({dir:r.repoDir});if(!i)throw new Error(`Not a git repository: ${r.repoDir}. Run inside a git repo or pass the path: npx taste learn /path/to/repo`);const a=s?e.resolve(process.cwd(),o):i;s&&Zv.emitStepStart({step:"collecting",label:"Collecting commits",message:`Cloned ${r.displayName} → ${a}`});const l=t.branch??await detectDefaultBranch({repoDir:i});await D.mkdir(a,{recursive:!0}),Zv.emitStepStart({step:"collecting",label:"Collecting commits",message:`Fetching up to ${t.maxCommits} commits from ${l}`});const{signals:u,commitCount:d}=await extractAllSignals({repoDir:i,maxCommits:t.maxCommits,maxSignals:t.maxSignals,branch:l,onProgress:__name(e=>{Zv.emitProgress({step:"extracting",message:e})},"onProgress")});if(t.signal.aborted)return{summary:n(),resolved:r};if(0===u.length)throw new Error("No signals extracted. Check the repository has commit history.");Zv.emitStepStart({step:"extracting",label:"Extracting taste signals",message:`${u.length} before/after code changes extracted`}),Zv.emitStepStart({step:"compiling",label:"Compiling taste context",message:`Formatting ${u.length} signals for the learning agent`});const m=compileTasteContext({signals:u,repoName:o,commitCount:d});if(t.signal.aborted)return{summary:n(),resolved:r};Zv.emitStepStart({step:"learning",label:"Learning taste",message:"Interpreting code change patterns with AI"}),await feedToLearningAgent({compiledContext:m,outputDir:a});const g=getTastePathForDir({projectRoot:a}),h=e.join(g,"taste.md"),f=await countLearnings(h);return Zv.emitStepStart({step:"complete",label:"Taste learned",message:"Taste learned",learningCount:f,storage:h}),Zv.markLearningComplete(),{summary:{outputDir:a,tasteDir:g,sourceName:r.displayName,signalCount:u.length,contextLength:m.length},resolved:r}}__name(isDependencyBot,"isDependencyBot"),__name(truncate2,"truncate"),__name(runBounded,"runBounded"),Ht(),__name(compileTasteContext,"compileTasteContext"),__name(runLearnPipeline,"runLearnPipeline"),Ht(),Ht(),tC(),Ht();var KP=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return KP.some(t=>t.test(e))}function chunkToString(e){return"string"==typeof e?e:Buffer.isBuffer(e)?e.toString("utf-8"):""}async function withFilteredStderrNoise(e){const t=process.stderr.write.bind(process.stderr);process.stderr.write=(e,...n)=>{const r=chunkToString(e);return!(!r||!shouldIgnoreChunk(r))||("function"==typeof n[0]?t(e,n[0]):t(e,n[0],n[1]))};try{return await e()}finally{process.stderr.write=t}}function toRepoLearnErrorMessage(e){return e instanceof Error?e.message:String(e)}function isRepoLearnMetricLikeText(e){const t=e.trim().toLowerCase();return/^\d+\s/.test(t)||/^saved\s/.test(t)||/^output\s/.test(t)||/^target\s/.test(t)||/\bcandidates\b/.test(t)||/\bevidence records\b/.test(t)||/\bhistory and review signals\b/.test(t)}function truncateRepoLearnPanelText(e,t=12){return truncateString({text:e,maxChars:Math.min(96,getEffectiveWidth({padding:t}))})}__name(shouldIgnoreChunk,"shouldIgnoreChunk"),__name(chunkToString,"chunkToString"),__name(withFilteredStderrNoise,"withFilteredStderrNoise"),Ht(),hs(),__name(toRepoLearnErrorMessage,"toRepoLearnErrorMessage"),__name(isRepoLearnMetricLikeText,"isRepoLearnMetricLikeText"),__name(truncateRepoLearnPanelText,"truncateRepoLearnPanelText"),Ht(),tC(),Ht();var YP=[{id:"collecting",label:"Collecting commits from repository"},{id:"extracting",label:"Extracting taste signals from diffs"},{id:"compiling",label:"Compiling taste context"},{id:"learning",label:"Learning taste from change patterns"},{id:"complete",label:"Taste learned"}],JP=[{id:"cloning",label:"Cloning repository"},...YP],XP=[ke.bullet,ke.squareSmallFilled,ke.lozenge,ke.star,ke.triangleRight,ke.triangleUp];function createInitialRepoLearnSteps(e){return(e??YP).map(e=>({...e,status:"pending"}))}__name(createInitialRepoLearnSteps,"createInitialRepoLearnSteps"),Ht(),tC();var ZP={learningCount:0,storage:"",topLearnings:[]};function getStepStatus(e,t){return e<t?"complete":e===t?"active":"pending"}function deriveStepStates(e,t){return e.map((e,n)=>({...e,status:getStepStatus(n,t)}))}function parseSummaryMetric(e){if(e.startsWith("Maintainer: "))return{maintainerLabel:e.replace(/^Maintainer:\s+/,"")};const t=e.match(/^(\d+)\s+maintainer-specific preferences$/);if(t)return{maintainerCount:Number(t[1])};const n=e.match(/^(\d+)\s+repository conventions$/);return n?{repoCount:Number(n[1])}:null}__name(getStepStatus,"getStepStatus"),__name(deriveStepStates,"deriveStepStates"),__name(parseSummaryMetric,"parseSummaryMetric");var eA=__name(e=>e.map(e=>({...e,status:"complete"})),"markAllStepsComplete"),tA=__name(e=>e??ZP,"withBase");function useRepoLearnState(e){const t=e??YP,[n,r]=K(()=>createInitialRepoLearnSteps(t)),[s,o]=K(""),[i,a]=K([]),[l,u]=K(null),[d,m]=K(!1),[g,h]=K(!1),[f,y]=K(null),[w,S]=K(0),E=Y(null),[v,C]=K(null),k=Z(()=>{E.current=Date.now()},[]);return J(()=>{const e=__name(()=>{r(createInitialRepoLearnSteps(t)),o(""),a([]),u(null),h(!1),y(null),S(0),E.current=null,C(null),m(!1)},"handleReset"),n=__name(e=>{if("error"===e.type)return y(e.message),h(!0),r(eA),void o("");if("auth_required"!==e.type){if("step_start"===e.type&&e.step){const n=t.findIndex(t=>t.id===e.step);return n>=0&&r(deriveStepStates(t,n)),o(e.message||e.label||""),void("complete"===e.step&&u(t=>{const n=tA(t);return{...n,learningCount:e.learningCount??n.learningCount,storage:e.storage??n.storage}}))}"progress"!==e.type||"complete"!==e.step?"progress"!==e.type?"insight"===e.type&&(isRepoLearnMetricLikeText(e.message)||("complete"!==e.step?(S(e=>e+1),a(t=>[...t,e.message].slice(-4))):u(t=>{const n=tA(t);return{...n,topLearnings:[...n.topLearnings,e.message].slice(0,3)}}))):o(e.message):u(t=>{const n=tA(t),r=parseSummaryMetric(e.message);return r?{...n,...r}:n})}else m(!0)},"handleEvent"),s=__name(()=>{h(e=>e||(r(eA),!0)),o(""),E.current&&C(Math.round((Date.now()-E.current)/1e3))},"handleComplete");return Zv.on("reset",e),Zv.on("new-event",n),Zv.on("learning-complete",s),()=>{Zv.off("reset",e),Zv.off("new-event",n),Zv.off("learning-complete",s)}},[t]),{steps:n,currentMessage:s,insights:i,insightCount:w,summary:l,done:g,error:f,showLogin:d,setShowLogin:m,elapsedSeconds:v,markStarted:k}}__name(useRepoLearnState,"useRepoLearnState"),Ht(),Ht(),dr();var nA=__name(({isComplete:e,hasError:t})=>Q.createElement(ee,{flexDirection:"column",marginTop:1,marginBottom:0},Q.createElement(Zx,null),Q.createElement(ee,{marginTop:0},Q.createElement(te,{color:jn.DIM},tP),Q.createElement(ee,{marginLeft:2},t?Q.createElement(te,{color:jn.DIM},"learning interrupted"):e?Q.createElement(te,{color:Un.TEXT},"learned your coding taste"):Q.createElement(nP,null)))),"RepoLearnTastePill");Ht(),dr();var rA=__name(({status:e})=>"active"===e?Q.createElement(ee,null,Q.createElement(te,{color:jn.YELLOW},Q.createElement(Fe,{type:"dots"})),Q.createElement(te,null," ")):"complete"===e?Q.createElement(te,{color:Hn.BG},ke.square," "):Q.createElement(te,{color:jn.DIM},ke.circle," "),"StepStatusIndicator"),sA=__name(({steps:e,currentMessage:t})=>Q.createElement(ee,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return Q.createElement(ee,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},Q.createElement(ee,null,Q.createElement(ee,{marginRight:1},Q.createElement(rA,{status:e.status})),Q.createElement(te,{bold:n,color:"complete"===e.status?jn.WHITE:n?jn.YELLOW:jn.DIM},e.label)),n&&t?Q.createElement(ee,{marginLeft:3},Q.createElement(te,{color:jn.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Ht(),dr();var oA=__name(({insights:e,insightCount:t})=>0===e.length?null:Q.createElement(ee,{flexDirection:"column",marginTop:1,marginLeft:4},Q.createElement(te,{color:jn.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>Q.createElement(te,{key:`${t}-${e}`,color:jn.DIM},XP[t%XP.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Ht(),dr();var iA=__name(({message:e})=>Q.createElement(ee,{flexDirection:"column",borderStyle:"single",borderColor:jn.RED,paddingX:2,paddingY:1,marginTop:1},Q.createElement(te,{color:jn.RED,bold:!0},"Oops, something went wrong:"),Q.createElement(ee,{marginTop:1},Q.createElement(te,null,e))),"RepoLearnErrorPanel");Ht(),dr(),Pr();var aA=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),s=e.learningCount>0;return Q.createElement(ee,{flexDirection:"column",marginLeft:3},Q.createElement(ee,{marginBottom:1,flexDirection:"row"},Q.createElement(te,{color:jn.DIM},tP),Q.createElement(ee,{marginLeft:2},Q.createElement(te,{color:Un.TEXT},s?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),Q.createElement(ee,{flexDirection:"column",marginLeft:1},Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},ke.pointerSmall," Taste stored in"," "),Q.createElement(Cr,{url:`file://${e.storage}`,text:r||".commandcode/taste/taste.md",color:jn.CYAN})),Q.createElement(ee,null,Q.createElement(te,{color:jn.DIM},ke.pointerSmall," Share your coding taste: ",Q.createElement(te,{color:jn.CYAN},"npx taste push --all")))),Q.createElement(ee,{marginTop:1,marginLeft:1},Q.createElement(te,{color:jn.DIM},s?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Ht(),dr();var lA=__name(({done:e,error:t})=>t?Q.createElement(ee,{marginTop:1},Q.createElement(te,{bold:!0},"Press ESC to exit")):e?Q.createElement(ee,{marginTop:1},Q.createElement(te,{bold:!0},"Press ENTER to continue")):Q.createElement(ee,{marginTop:1},Q.createElement(te,{color:jn.DIM},"ESC to cancel")),"RepoLearnFooter");Ht(),dr();var cA=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=X(()=>u_(n),[n]);return Q.createElement(ee,{flexDirection:"column"},Q.createElement(ee,{flexDirection:"column",marginBottom:1},Q.createElement(ot,{name:"vice"},Q.createElement(te,null,r.trimEnd()))),e?Q.createElement(te,{color:jn.WHITE},e):Q.createElement(Q.Fragment,null,Q.createElement(te,{color:jn.WHITE},"Learning your coding taste from ",Q.createElement(te,{bold:!0,color:jn.CYAN},t??"repository")),Q.createElement(te,{color:jn.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:s,insightCount:o}){return e?Q.createElement(iA,{message:e}):t?Q.createElement(aA,{summary:n,elapsedSeconds:r}):Q.createElement(oA,{insights:s,insightCount:o})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:s}){const o=useRepoLearnState(n),i=Y(!1);return J(()=>{i.current||(i.current=!0,o.markStarted(),e().catch(()=>{}))},[e,o.markStarted]),se((e,n)=>{if(o.showLogin)return;const r=n.escape||""===e,s=n.return||"\n"===e||"\r"===e;r?t({published:!1,cancelled:!0}):(o.done||o.error)&&s&&t({published:!1,cancelled:!!o.error})}),o.showLogin?Q.createElement(ee,{flexDirection:"column"},Q.createElement(cA,{text:r,repoName:s}),Q.createElement(kx,{onComplete:(e,t)=>{o.setShowLogin(!1),e?Zv.resolveAuth():Zv.rejectAuth(t)},onCancel:()=>{o.setShowLogin(!1),Zv.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):Q.createElement(ee,{flexDirection:"column"},Q.createElement(cA,{text:r,repoName:s}),Q.createElement(nA,{isComplete:o.done&&!o.error,hasError:Boolean(o.error)}),Q.createElement(sA,{steps:o.steps,currentMessage:o.currentMessage}),Q.createElement(StatusPanel,{error:o.error,done:o.done,summary:o.summary,elapsedSeconds:o.elapsedSeconds,insights:o.insights,insightCount:o.insightCount}),Q.createElement(lA,{done:o.done,error:o.error}))}async function runRepoLearnProgress(e){return withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{Zv.reset();const r=new AbortController;let s,o,i=!1,a=!1;const l=__name(async()=>{try{s=await e.runTask(r.signal)}catch(e){r.signal.aborted||(o=e,Zv.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),Zv.markLearningComplete())}},"handleRunTask"),u=__name(({published:e,cancelled:l})=>{a||(a=!0,i=e,r.abort(),d.unmount(),Zv.reset(),o?n(o):t({result:s,published:i,cancelled:l}))},"handleExit"),d=oe(Q.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:u}));d.waitUntilExit().catch(e=>{Zv.reset(),n(e)})})}__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),rk();var uA=__name(e=>t=>{const n=parseInt(t,10);if(isNaN(n)||n<1)throw new Error(`${e} must be a positive integer`);return n},"parsePositiveInt");function createLearnCommand(){return new ve("learn").description("Learn coding taste from repository change history").argument("[source]","Local path, GitHub URL, or owner/repo (defaults to current directory)").option("--max-commits <number>","Maximum commits to analyze",uA("--max-commits"),200).addOption(new Ce("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(uA("--max-signals")).hideHelp()).option("--branch <name>","Branch to analyze (defaults to main/master)").action(async(e,t)=>{try{await learnTaste({source:e??".",maxCommits:t.maxCommits??200,maxSignals:t.maxSignals??50,branch:t.branch})}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`Error: ${t}`),process.exit(1)}})}async function learnTaste(t){const n=await D.stat(e.resolve(t.source)).then(e=>e.isDirectory()).catch(()=>!1),r=isTTY(),s=await resolveDisplayName(t.source),o=!await getAuthKey();if(o&&!r)return console.log(""),console.log(" Login required to learn taste."),console.log(""),console.log(" Run: cmd login"),console.log(` Then: npx taste learn ${t.source}`),void console.log("");let i;const a=__name(()=>{i?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",a);let l=!1;try{const e=__name(async e=>{const{summary:r,resolved:s}=await runLearnPipeline({...t,isLocalSource:n,needsAuth:o,signal:e});return i=s?.cleanup,r},"runTask");if(r){const t=n?void 0:[...JP];({cancelled:l}=await runRepoLearnProgress({runTask:e,repoName:s,stepOrder:t}))}else logLearnSummary({summary:await e((new AbortController).signal)})}finally{process.off("SIGINT",a),i&&await i()}r&&!l||process.exit(0),yC(),await _P({skipOnboarding:!0})}function getTastePath(t){const{target:n}=t;if("local-project"===n)return e.join(process.cwd(),".commandcode","taste");if("local-global"===n)return e.join(y.homedir(),".commandcode","taste");throw new Error(`Remote storage not yet implemented: ${n}`)}function getRootTasteFile(t){const{target:n}=t;return e.join(getTastePath({target:n}),"taste.md")}function getCategoryPath(t){const{target:n,category:r}=t;return e.join(getTastePath({target:n}),r)}function getCategoryTasteFile(t){const{target:n,category:r}=t;return e.join(getCategoryPath({target:n,category:r}),"taste.md")}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Ht(),Ht(),lw(),Ht(),Kt(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Ht(),Ht();var dA=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||dA.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const s=n[r].trim();return{endIdx:t+r,inclusive:dA.test(s)&&!s.startsWith("#")&&!s.startsWith("-")}}function joinMultiLineLearning(e,t,n){const{endIdx:r,inclusive:s}=findLookaheadEnd(e,t),o=s?r+1:r;return{combined:[n,...e.slice(t,o).map(e=>e.trim()).filter(e=>e.length>0)].join(" "),nextIdx:o}}function processRawLine(e,t){const n=e[t],r=t+1,s=n.trim();if(!s.startsWith("-"))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};if(dA.test(s))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:o,nextIdx:i}=joinMultiLineLearning(e,t+1,n);return{entry:{text:o,originalLineNum:r},nextIdx:i}}function preprocessLines(e){const t=[];let n=0;for(;n<e.length;){const{entry:r,nextIdx:s}=processRawLine(e,n);t.push(r),n=s}return t}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],s=t.substring(1).trim();if(!dA.test(s))return r.push({line:n,severity:"error",message:'Learning is missing "Confidence:" field',suggestion:'Format: "- Learning text. Confidence: 0.95" (value between 0.0 and 1.0)'}),r;const o=Array.from(s.matchAll(/confidence:\s*(\S+)/gi)),i=o.length>0?o[o.length-1]:null;if(!i)return r.push({line:n,severity:"error",message:"Confidence field is present but has no value",suggestion:'Add a number after "Confidence:" (e.g., Confidence: 0.95)'}),r;const a=i[1],l=parseFloat(a);if(isNaN(l))return r.push({line:n,severity:"error",message:`Confidence value "${a}" is not a valid number`,suggestion:"Use a decimal number between 0.0 and 1.0 (e.g., 0.95)"}),r;(l<0||l>1)&&r.push({line:n,severity:"error",message:`Confidence value ${l} is out of range`,suggestion:"Confidence must be between 0.0 and 1.0"}),l>=0&&l<=1&&0===l&&r.push({line:n,severity:"warning",message:"Confidence is 0.0 - this learning may not be useful",suggestion:"Consider removing learnings with 0 confidence"});const u=void 0!==i.index?s.substring(0,i.index).trim():s.trim();return u&&0!==u.length?(u.length<3&&r.push({line:n,severity:"warning",message:"Learning text is very short",suggestion:"Provide more descriptive text for clarity"}),r):(r.push({line:n,severity:"error",message:'Learning has no text before "Confidence:"',suggestion:'Add descriptive text (e.g., "Use pnpm for package management")'}),r)}function hasReferenceAfterCategory(e){const{lines:t,categoryLineIndex:n}=e,r=t.slice(n+1,n+4),s=r.findIndex(e=>e.trim().startsWith("# "));return(-1===s?r:r.slice(0,s)).some(e=>e.includes("See [")&&e.includes("taste.md"))}function buildResult(e){const{issues:t,filePath:n}=e,r=t.filter(e=>"error"===e.severity),s=t.filter(e=>"warning"===e.severity),o=0===r.length;if(0===t.length)return{valid:o,issues:[...t],summary:`${ke.tick} ${n} is valid`};const i=[];r.length>0&&i.push(`${r.length} error${r.length>1?"s":""}`),s.length>0&&i.push(`${s.length} warning${s.length>1?"s":""}`);const a=r.length>0?ke.cross:ke.warning;return{valid:o,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?le.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(le.dim(` → ${e.suggestion}`)),n}function formatIssueGroup(e,t,n){return 0===e.length?[]:[n,...e.flatMap(e=>formatSingleIssue(e,t)),""]}function formatValidationIssues(e){const{result:t,verbose:n=!0}=e;if(0===t.issues.length){const e=t.summary.charAt(0),n=t.summary.substring(2);return`${le.green(e)} ${le.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),s=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?le.red(t.summary):le.yellow(t.summary),"",...formatIssueGroup(r,le.red,le.bold(le.red("Errors:"))),...formatIssueGroup(s,le.yellow,le.bold(le.yellow("Warnings:")))].join("\n").trim()}__name(findLookaheadEnd,"findLookaheadEnd"),__name(joinMultiLineLearning,"joinMultiLineLearning"),__name(processRawLine,"processRawLine"),__name(preprocessLines,"preprocessLines"),__name(validateLearningLine,"validateLearningLine"),__name(hasReferenceAfterCategory,"hasReferenceAfterCategory"),__name(buildResult,"buildResult"),Ht(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var mA=new Set(["# Taste (Continuously Learned by [CommandCode][cmd])","# Taste (Continuously Learned by CommandCode.ai)","# Taste (Continuously Learned by CommandCode)"]);function warnIfEmptyCategory(e,t){!e.currentCategory||e.learningsInCurrentCategory>0||hasReferenceAfterCategory({lines:t,categoryLineIndex:e.categoryLineNumber-1})||e.issues.push({line:e.categoryLineNumber,severity:"warning",message:`Category '${e.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function processHeading(e){const{line:t,lineNum:n,state:r,rawLines:s}=e;mA.has(t.trim())||(r.hasAnyCategory=!0,warnIfEmptyCategory(r,s),r.currentCategory=t.trim().substring(2).trim(),r.categoryLineNumber=n,r.learningsInCurrentCategory=0)}function processLearning(e){const{line:t,lineNum:n,state:r}=e;r.currentCategory?(r.learningsInCurrentCategory++,r.issues.push(...validateLearningLine({line:t.trim(),lineNum:n}))):r.issues.push({line:n,severity:"error",message:"Learning found outside of any category",suggestion:'Add a category header (e.g., "# cli") before this learning'})}__name(warnIfEmptyCategory,"warnIfEmptyCategory"),__name(processHeading,"processHeading"),__name(processLearning,"processLearning");var pA=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,gA=/^\[cmd\]: https:\/\/commandcode\.ai\/$/i;function processLine(e){const{line:t,lineNum:n,state:r,rawLines:s}=e,o=t.trim();o&&(o.startsWith("# ")?processHeading({line:t,lineNum:n,state:r,rawLines:s}):o.startsWith("-")?processLearning({line:t,lineNum:n,state:r}):pA.test(o)||gA.test(o)||r.issues.push({line:n,severity:"error",message:"Invalid content - must be a category header (# name) or learning (- text)",suggestion:"Remove this line or format it as a category (# name) or learning (- text. Confidence: 0.XX)"}))}function checkFinalCategory(e){const{state:t,rawLines:n}=e;!t.currentCategory||t.learningsInCurrentCategory>0||!t.categoryLineNumber||hasReferenceAfterCategory({lines:n,categoryLineIndex:t.categoryLineNumber-1})||t.issues.push({line:t.categoryLineNumber,severity:"warning",message:`Category '${t.currentCategory}' has no learnings`,suggestion:"Add at least one learning or remove this category"})}function validateTasteFile(e){const{content:t,filePath:n}=e,r=[];if(!t.trim())return r.push({severity:"error",message:"File is empty",suggestion:"Add at least one category with learnings"}),buildResult({issues:r,filePath:n});const s=t.split("\n"),o=preprocessLines(s),i={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of o)processLine({line:e,lineNum:t,state:i,rawLines:s});return checkFinalCategory({state:i,rawLines:s}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var hA=__name(e=>"local-global"===e?"global":"project","locationLabel"),fA=__name(({file:e,error:t})=>({success:!1,filesLinted:[],errors:[{file:e,error:t}],totalErrors:0,totalWarnings:0}),"failResult");function resolvePackageFile(e,t){const n=getCategoryTasteFile({target:t,category:e});return C(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${hA(t)}`}}}function collectSpecificFiles(e){const{packages:t,target:n}=e,r=t.map(e=>resolvePackageFile(e,n));return{files:r.filter(e=>"result"in e).map(e=>e.result),errors:r.filter(e=>"error"in e).map(e=>e.error)}}async function collectAllFiles(e){const{tastePath:t,target:n}=e,r=[],s=getRootTasteFile({target:n});C(s)&&r.push({path:s,displayName:"taste.md"});const o=(await D.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>C(e)).map(({entry:e,categoryFile:t})=>({path:t,displayName:`${e.name}/taste.md`}));return r.push(...o),r}async function lintFile(e){let t=await D.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await D.writeFile(e.path,n,"utf-8"),t=n);const r=validateTasteFile({content:t,filePath:e.displayName}),s=r.issues.filter(e=>"error"===e.severity).length,o=r.issues.filter(e=>"warning"===e.severity).length,i=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:s,warnings:o,formatted:i}}async function lintSpecificPackages(e){const{packages:t,target:n}=e,{files:r,errors:s}=collectSpecificFiles({packages:t,target:n});if(0===r.length&&s.length>0)return{success:!1,filesLinted:[],errors:s,totalErrors:0,totalWarnings:0};if(0===r.length)return fA({file:"all",error:`No taste files found in ${hA(n)}`});const o=await Promise.all(r.map(lintFile)),i=o.reduce((e,t)=>e+t.errors,0),a=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid)&&0===s.length,filesLinted:o,errors:s,totalErrors:i,totalWarnings:a}}async function lintAllFiles(e){const{tastePath:t,target:n}=e,r=await collectAllFiles({tastePath:t,target:n});if(0===r.length)return fA({file:"all",error:`No taste files found in ${hA(n)}`});const s=await Promise.all(r.map(lintFile)),o=s.reduce((e,t)=>e+t.errors,0),i=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid),filesLinted:s,errors:[],totalErrors:o,totalWarnings:i}}async function lint(e){const{packages:t,target:n}=e,r=getTastePath({target:n});return C(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):fA({file:"all",error:`No taste directory found in ${hA(n)}`})}function resolveConflictStrategy(e){const t=[e.skip&&"skip",e.merge&&"merge",e.overwrite&&"overwrite"].filter(Boolean);return t.length>1&&exitWithError(`Cannot combine --${t[0]} and --${t[1]}. Choose one conflict strategy.`),t[0]}__name(resolvePackageFile,"resolvePackageFile"),__name(collectSpecificFiles,"collectSpecificFiles"),__name(collectAllFiles,"collectAllFiles"),__name(lintFile,"lintFile"),__name(lintSpecificPackages,"lintSpecificPackages"),__name(lintAllFiles,"lintAllFiles"),__name(lint,"lint"),Ht(),Cs(),__name(resolveConflictStrategy,"resolveConflictStrategy");var yA=le.bgGreen.black.bold(" TASTE ");function shortenPath(e){const t=process.env.HOME??process.env.USERPROFILE??"";return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function exitWithError(e){console.error(`${le.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`),process.exit(1)}function formatUsageLine(e){const t=e.match(/^(\s*(?:Usage:|or:)?\s*)(cmd)(\s+.+?)(\s+\(.*\))?$/);return t?`${le.dim(t[1])}${le.green(t[2])}${le.white(t[3]??"")}${t[4]?le.dim(t[4]):""}`:le.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${le.red("Error:")} ${e.replace(/^Error:\s*/i,"")}`);for(const e of t)console.error(formatUsageLine(e));process.exit(1)}function resolveRemoteDefault(e){return e.global||e.remote?e:{...e,remote:!0}}__name(shortenPath,"shortenPath"),__name(exitWithError,"exitWithError"),__name(formatUsageLine,"formatUsageLine"),__name(exitWithUsage,"exitWithUsage"),__name(resolveRemoteDefault,"resolveRemoteDefault");var wA=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return ut(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:wA})}function getProfileLink(e){return ut(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:wA})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return ct(e,n,{trim:!1})}function formatMergeParts(e){const t=[];return e.added>0&&t.push(`${e.added} ${1===e.added?"learning":"learnings"} added`),e.updated>0&&t.push(`${e.updated} ${1===e.updated?"learning":"learnings"} updated`),e.unchanged>0&&t.push(`${e.unchanged} ${1===e.unchanged?"learning":"learnings"} unchanged`),t}function hasMergeConflictRisk(e){return(e.added>0||e.updated>0)&&e.unchanged>0}function hasMergeConflictRiskInRecord(e){return Object.values(e).some(hasMergeConflictRisk)}function logMergeReviewTip(){console.log(le.yellow("\nTip: Review merged learnings to ensure no conflicting rules."))}function parseOwnerPackage(e){if(!e.includes("/"))return;const[t,n]=e.split("/");return t&&n?{owner:t,packageName:n}:void 0}function handleResultErrors(e){for(const t of e){const e=t.error.replace(/^Taste package(?: '.*?')? /,`Taste package '${t.pkg}' `);console.error(`${le.red("Error:")} ${e}`)}process.exit(1)}function getTimeAgo(e){const t=Date.now()-e.getTime(),n=Math.floor(t/6e4),r=Math.floor(t/36e5),s=Math.floor(t/864e5);return n<1?"just now":n<60?`${n} minute${n>1?"s":""} ago`:r<24?`${r} hour${r>1?"s":""} ago`:`${s} day${s>1?"s":""} ago`}async function flushAndExit(e){await Promise.race([shutdownTelemetry(),new Promise(e=>setTimeout(e,500))]).catch(()=>{}),process.exit(e)}function withErrorHandler(e){return async(...t)=>{try{await e(...t),await flushAndExit(0)}catch(e){const t=e instanceof Error?e.message:String(e);console.error(le.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new ve("lint").argument("[package]","Taste package name").option("-g, --global","Validate taste packages from global storage (~/.commandcode)").option("--all","Validate all taste packages").description(`Validate taste package format ${le.dim("(structure, style, etc.)")}`).action(withErrorHandler(async(e,t)=>runLint({packageName:e,options:t})))}function validateLintOptions({packageName:e,options:t}){e||t.all||exitWithUsage({message:"Specify a taste package name or use --all to validate everything",usage:["cmd taste lint <package> validate a taste package","cmd taste lint --all validate all taste packages"]}),e&&t.all&&exitWithError("Use either a package name or --all, not both")}function logLintResults(e){for(const t of e.filesLinted)console.log(t.formatted);e.filesLinted.length>1&&logLintSummary(e),e.success||process.exit(1)}function logLintSummary({filesLinted:e,totalErrors:t,totalWarnings:n}){if(console.log(""),0===t&&0===n)return void console.log(`${le.green(ke.tick)} All ${le.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(le.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(le.yellow(`${n} warning${n>1?"s":""}`)),console.log(`Summary: ${r.join(", ")} across ${e.length} files`)}async function runLint({packageName:e,options:t}){console.log(""),validateLintOptions({packageName:e,options:t});const n=await lint({packages:e?[e]:[],target:t.global?"local-global":"local-project"});if(n.errors.length>0){for(const e of n.errors)console.error(le.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}function parseSection(e){const{section:t,sourcePath:n}=e,r=t.split("\n"),s=r[0].trim(),o=r.map(e=>parseLearning({line:e})).filter(e=>null!==e);return 0===o.length?null:{category:normalizeCategory({category:s}),learnings:o,sourcePath:n}}function parsePackages(e){const{content:t,sourcePath:n}=e;return t.split(/^# /gm).filter(e=>e.trim()).filter(e=>!e.includes("See [")).map(e=>parseSection({section:e,sourcePath:n})).filter(e=>null!==e)}function parseLearning(e){const{line:t}=e,n=t.match(/^-?\s*(.+?)[\.:,]?\s*confidence:\s*(\d*\.?\d+)/i);if(!n)return null;const r=parseFloat(n[2]);return isNaN(r)||r<0||r>1?null:{text:n[1].trim(),confidence:r}}function normalizeCategory(e){const{category:t}=e;return t.toLowerCase().replace(/\s+/g,"-")}function denormalizeCategory(e){const{slug:t}=e;return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function formatPackage(e){const{pkg:t}=e;let n=`# ${denormalizeCategory({slug:t.category})}\n`;for(const e of t.learnings)n+=`- ${e.text}. Confidence: ${e.confidence.toFixed(2)}\n`;return n}async function readAndMigrateFile(e){const{filePath:t}=e,n=await D.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await D.writeFile(t,r,"utf-8"),r)}function trimTrailingBlanks(e){const{lines:t,until:n}=e;let r=e.from;for(;r>n&&""===t[r].trim();)r--;return r}function findCategoryRange(e){const{lines:t,pattern:n}=e,r=t.findIndex(e=>n.test(e));if(-1===r)return null;const s=t.findIndex((e,t)=>t>r&&e.startsWith("# "));if(-1===s)return{start:r,end:t.length-1};const o=trimTrailingBlanks({lines:t,from:s-1,until:r});return{start:r,end:o}}function ensureHeader(e){if(!e)return nw+"\n\n";const t=e.trim();return t.startsWith(ew)||t.startsWith(rw)||t.startsWith(sw)?e:nw+"\n\n"+e}function ensureTrailingNewlines(e){return e?e.endsWith("\n\n")?e:e.endsWith("\n")?e+"\n":e+"\n\n":e}__name(getPackageLink,"getPackageLink"),__name(getProfileLink,"getProfileLink"),__name(wrapLine,"wrapLine"),__name(formatMergeParts,"formatMergeParts"),__name(hasMergeConflictRisk,"hasMergeConflictRisk"),__name(hasMergeConflictRiskInRecord,"hasMergeConflictRiskInRecord"),__name(logMergeReviewTip,"logMergeReviewTip"),__name(parseOwnerPackage,"parseOwnerPackage"),__name(handleResultErrors,"handleResultErrors"),__name(getTimeAgo,"getTimeAgo"),__name(flushAndExit,"flushAndExit"),__name(withErrorHandler,"withErrorHandler"),__name(createLintCommand,"createLintCommand"),__name(validateLintOptions,"validateLintOptions"),__name(logLintResults,"logLintResults"),__name(logLintSummary,"logLintSummary"),__name(runLint,"runLint"),Ht(),Ls(),Ht(),Ht(),Ht(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Ht(),__name(formatPackage,"formatPackage"),Ht(),lw(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var SA="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:SA,category:e.name});return C(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await D.stat(e.sourcePath);return{category:e.category,learningCount:e.learnings.length,lastUpdated:t.mtime,filePath:e.sourcePath}}catch{return{category:e.category,learningCount:e.learnings.length,lastUpdated:new Date,filePath:e.sourcePath}}}async function getAllPackages(){const e=getTastePath({target:SA});if(!C(e))return[];const t=await D.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:SA,category:t});return C(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:SA});await D.mkdir(r,{recursive:!0});const s=getCategoryTasteFile({target:SA,category:n.category}),o=e.dirname(s);await D.mkdir(o,{recursive:!0});const i=formatPackage({pkg:n});await D.writeFile(s,i,"utf-8")}async function listPackages(){const e=await getAllPackages();return await Promise.all(e.map(getPackageInfo))}__name(loadCategoryPackages,"loadCategoryPackages"),__name(getPackageInfo,"getPackageInfo"),__name(getAllPackages,"getAllPackages"),__name(getPackage,"getPackage"),__name(writePackage,"writePackage"),__name(listPackages,"listPackages"),Ht(),Ht(),lw();var bA="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!C(n))return null;const r=migrateHeader({content:await D.readFile(n,"utf-8")}).split("\n"),s=findCategoryRange({lines:r,pattern:new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i")});if(!s)return null;const o=r.slice(0,s.start),i=s.end<r.length-1?r.slice(s.end+1):[],a={before:o.join("\n").trim(),after:i.join("\n").trim()},l=[...o,...i].join("\n").trim();return""===l&&await D.rm(n,{force:!0}),""!==l&&await D.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:bA}),s=await removeCategoryFromRoot({category:n,rootFile:r}),o=getCategoryTasteFile({target:bA,category:n}),i=e.dirname(o);return C(i)&&await D.rm(i,{recursive:!0,force:!0}),s}async function writeToRoot(e){const{pkg:t,rootFile:n,categoryPosition:r}=e,s=formatPackage({pkg:t});if(r){let e=ensureHeader(migrateHeader({content:r.before}));e=ensureTrailingNewlines(e);const t=r.after?"\n\n"+r.after:"";return e+=s.trim()+t,void await D.writeFile(n,e.trim()+"\n","utf-8")}let o="";C(n)&&(o=await D.readFile(n,"utf-8"),o=migrateHeader({content:o})),o=ensureHeader(o),o=ensureTrailingNewlines(o),o+=s,await D.writeFile(n,o.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:s}=t,o=getCategoryTasteFile({target:bA,category:n.category}),i=e.dirname(o);await D.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await D.writeFile(o,a,"utf-8");const l=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(s){let e=ensureHeader(migrateHeader({content:s.before}));e=ensureTrailingNewlines(e);const t=s.after?"\n\n"+s.after:"";return e+=l.trim()+t,void await D.writeFile(r,e.trim()+"\n","utf-8")}let u="";C(r)&&(u=await D.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await D.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var EA="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:EA,category:e.name});return C(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:EA});if(!C(e))return[];const t=[],n=getRootTasteFile({target:EA});if(C(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await D.readdir(e,{withFileTypes:!0}),s=(await Promise.all(r.map(loadCategoryPackages2))).flat();return t.push(...s),t}async function getPackage2(e){const{category:t}=e;return(await getAllPackages2()).find(e=>e.category===t)||null}async function writePackage2(e){const{pkg:t}=e,n=getTastePath({target:EA});await D.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:EA}),s=await removePackage({category:t.category});t.learnings.length<=5?await writeToRoot({pkg:t,rootFile:r,categoryPosition:s}):await writeToSubdirectory({pkg:t,rootFile:r,categoryPosition:s})}function exists2(){const e=getTastePath({target:EA});return C(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!C(n))return;const r=await D.readFile(n,"utf-8"),s=new Blob([r],{type:"text/markdown"}),o=new File([s],"taste.md",{type:"text/markdown"});e.append(`files[${t.category}/taste.md]`,o)}async function prepareUploadFormData(t){const{packageName:n,pkg:r,description:s,type:o="category",isPublic:i=!1,overwrite:a=!1}=t,l=new FormData;l.append("name",n),s&&l.append("description",s),l.append("type",o),l.append("isPublic",String(i)),l.append("overwrite",String(a));const u=formatPackage({pkg:r}),d=new Blob([u],{type:"text/markdown"}),m=new File([d],"taste.md",{type:"text/markdown"});if(l.append("files[taste.md]",m),"category"===o)return l;const g=getTastePath({target:"local-project"}),h=e.join(g,r.category);if(!C(h))return l;const f=getCategoryTasteFile({target:"local-project",category:r.category});if(!C(f))return l;const y=await D.readFile(f,"utf-8"),w=new Blob([y],{type:"text/markdown"}),S=new File([w],"taste.md",{type:"text/markdown"});return l.append(`files[${r.category}/taste.md]`,S),l}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:s=!1,overwrite:o=!1}=e,i=new FormData;i.append("name",n),r&&i.append("description",r),i.append("type","project"),i.append("isPublic",String(s)),i.append("overwrite",String(o));const a=getRootTasteFile({target:"local-project"});if(C(a)){const e=await D.readFile(a,"utf-8"),t=new Blob([e],{type:"text/markdown"}),n=new File([t],"taste.md",{type:"text/markdown"});i.append("files[taste.md]",n)}const l=t.map(e=>appendCategoryFile(i,e));return await Promise.all(l),i}function parseLearningLine(e){const t=e.match(/^-\s+(.+?)\.\s+Confidence:\s+([\d.]+)/);if(!t)return null;const n=t[1].trim(),r=parseFloat(t[2]);return!n||isNaN(r)?null:{text:n,confidence:r}}function parseTasteContent(e){return e.split("\n").filter(e=>{const t=e.trim();return t&&!t.startsWith("#")&&t.startsWith("-")}).map(e=>parseLearningLine(e.trim())).filter(e=>null!==e)}async function parseApiError(e){const{response:t,fallback:n}=e;try{const e=await t.json();return e.error?.message||e.message||n}catch{return n}}function throwTrackedError(e){const{message:t,label:n,heading:r,status:s,extra:o}=e,i=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:i,label:n}),context:{component:ys.TASTE_REMOTE_STORAGE,heading:r,"http.status":s,...o}}),i}async function requireAuthKey(){const e=await getAuthKey();if(!e)throw new Error("No API key found. Please authenticate with: cmd login");return e}async function downloadPackage(e){const{owner:t,packageName:n}=e,r=getApiBaseUrl(),s=await tryPublicDownload({baseUrl:r,owner:t,packageName:n});if(s)return s;const o=await getAuthKey();if(!o)throw new Error("Package not found. If this is a private package, please authenticate with `cmd login`");return tryAuthenticatedDownload({baseUrl:r,owner:t,packageName:n,apiKey:o})}async function tryPublicDownload(e){const{baseUrl:t,owner:n,packageName:r}=e,s=`${t}${kt.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",n).replace(":packageName",r)}`;let o;try{o=await fetch(s,{method:"GET"})}catch{return null}if(o.ok){const{data:e}=await o.json();return{type:e.type||"category",files:e.files||[],isPublic:!0}}if(404===o.status)return null;throwTrackedError({message:await parseApiError({response:o,fallback:`Failed to download taste package (${o.status})`}),label:"download_public_error",heading:"Failed to download taste package (public)",status:o.status})}async function tryAuthenticatedDownload(e){const{baseUrl:t,owner:n,packageName:r,apiKey:s}=e,o=`${t}${kt.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,i=await fetch(o,{method:"GET",headers:{Authorization:`Bearer ${s}`}});if(i.ok){const{data:e}=await i.json();return{type:e.type||"category",files:e.files||[],isPublic:e.isPublic??!1}}if(404===i.status)return null;throwTrackedError({message:await parseApiError({response:i,fallback:"Failed to download taste package"}),label:"download_auth_error",heading:"Failed to download taste package (authenticated)",status:i.status})}async function fetchSinglePackage(e){try{return await getPackage3({category:e.name})}catch(t){const n=t instanceof Error?t:new Error(String(t));return trackError({error:sanitizeErrorForTelemetry({error:n,label:"download_package_error"}),context:{component:ys.TASTE_REMOTE_STORAGE,heading:"Failed to download package","package.name":e.name}}),console.warn(`Warning: Failed to download package '${e.name}': ${n.message}`),null}}async function getAllPackages3(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${kt.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list taste packages",status:n.status});const{data:r}=await n.json(),s=r.packages||[];if(0===s.length)return[];const o=[];for(let e=0;e<s.length;e+=5){const t=s.slice(e,e+5),n=await Promise.all(t.map(fetchSinglePackage));o.push(...n.filter(e=>null!==e))}return o}async function getPackage3(e){const{category:t}=e;let n;await requireAuthKey();try{n=await getAuthenticatedEntity()}catch(e){const n=e instanceof Error?e:new Error(String(e));throw dlog(`[Auth] getPackage: entity endpoint unavailable — ${n.message}`),trackError({error:sanitizeErrorForTelemetry({error:n,label:"get_entity_error"}),context:{component:ys.TASTE_REMOTE_STORAGE,heading:"getAuthenticatedEntity failed in getPackage"}}),new Error(`Could not resolve your account to fetch '${t}'. Check your connection and try again.`)}if(!n.success||!n.user?.userName)throw new Error("Failed to get authenticated user information");return downloadRemotePackage({owner:n.user.userName,packageName:t})}async function downloadRemotePackage(e){const{owner:t,packageName:n}=e,r=await downloadPackage({owner:t,packageName:n});if(!r)return null;const s=r.files||[];if(0===s.length)return null;const o=s.find(e=>"taste.md"===e.file);if(!o)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(o.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async function writePackage3(e){const{pkg:t,owner:n,isPublic:r=!1,overwrite:s=!1}=e,o=await requireAuthKey(),i=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r,overwrite:s}),a=`${getApiBaseUrl()}${kt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`},body:i});l.ok||throwTrackedError({message:await parseApiError({response:l,fallback:"Failed to upload taste package"}),label:"upload_package_error",heading:"Failed to upload taste package",status:l.status}),await l.json()}async function writePackages(e){const{packages:t,projectName:n,owner:r,isPublic:s=!1,overwrite:o=!1}=e,i=await requireAuthKey(),a=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:s,overwrite:o}),l=`${getApiBaseUrl()}${kt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",r)}`,u=await fetch(l,{method:"POST",headers:{Authorization:`Bearer ${i}`},body:a});u.ok||throwTrackedError({message:await parseApiError({response:u,fallback:"Failed to upload taste packages"}),label:"upload_packages_error",heading:"Failed to upload taste packages",status:u.status,extra:{"package.count":t.length}}),await u.json()}async function listPackages2(){const e=await requireAuthKey(),t=`${getApiBaseUrl()}${kt.BETA.TASTE.PACKAGES.LIST}`,n=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});n.ok||throwTrackedError({message:await parseApiError({response:n,fallback:"Failed to list taste packages"}),label:"list_packages_error",heading:"Failed to list packages",status:n.status});const{data:r}=await n.json();return(r.packages||[]).map(e=>({category:e.name,learningCount:e.learningCount||0,lastUpdated:e.createdAt?new Date(e.createdAt):new Date,filePath:"",isPublic:e.isPublic??!1,starCount:e.starCount??0,downloadCount:e.downloadCount??0,type:e.type??"category"}))}async function list(e){const{location:t}=e;if("local-global"===t)return listPackages();if("remote-project"===t||"remote-user"===t)return listPackages2();if("local-project"===t){const e=getRootTasteFile({target:"local-project"}),t=await getAllPackages2();return Promise.all(t.map(async t=>{let n;if(t.sourcePath!==e)try{n=(await D.stat(t.sourcePath)).mtime}catch{}return{category:t.category,learningCount:t.learnings.length,lastUpdated:n,filePath:t.sourcePath}}))}throw new Error(`Invalid location: ${t}`)}function createListCommand(){return new ve("list").alias("ls").option("-g, --global","List global packages").addOption(new Ce("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ce("--staging","Use staging environment").hideHelp()).description(`List available packages ${le.dim("(project, global, or remote)")}`).action(withErrorHandler(async e=>runList({options:e})))}__name(loadCategoryPackages2,"loadCategoryPackages"),__name(getAllPackages2,"getAllPackages"),__name(getPackage2,"getPackage"),__name(writePackage2,"writePackage"),__name(exists2,"exists"),Ht(),Xy(),Ht(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),Kt(),Ht(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),sk(),Cs(),Ht(),rk(),Cs(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Ht(),Xy(),rk(),Kt(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),In(),__name(fetchSinglePackage,"fetchSinglePackage"),__name(getAllPackages3,"getAllPackages"),__name(getPackage3,"getPackage"),__name(downloadRemotePackage,"downloadRemotePackage"),__name(writePackage3,"writePackage"),__name(writePackages,"writePackages"),__name(listPackages2,"listPackages"),__name(list,"list"),__name(createListCommand,"createListCommand");var vA={remote:{location:"remote-project",name:"remote",subtitle:"commandcode.ai account"},global:{location:"local-global",name:"global",subtitle:"~/.commandcode/taste"},project:{location:"local-project",name:"project",subtitle:".commandcode/taste"}};function resolveStorage(e){return e.remote?vA.remote:e.global?vA.global:vA.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${ke.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${ke.arrowDown}${e.downloadCount}`.length),t}function formatPackageLine({pkg:e,maxLen:t}){const n=" ".repeat(t-getPackageDisplayLength(e)+2),r=e.lastUpdated?getTimeAgo(e.lastUpdated):null,s=r?`, updated ${r}`:"";return` ${le.white(e.category)}${e.isPublic?le.green(" [public]"):""}${e.isPublic&&e.starCount?le.yellow(` ${ke.star}${e.starCount}`):""}${e.downloadCount?le.gray(` ${ke.arrowDown}${e.downloadCount}`):""}${n}${le.dim.gray(`(${e.learningCount} learnings${s})`)}`}function validateListOptions(e){e.global&&e.remote&&exitWithError("Error: Cannot specify both --global and --remote flags")}async function fetchPackages({options:e}){const t=resolveStorage(e),n=e.remote?Te(`Fetching ${t.name} packages`).start():null,r=await list({location:t.location});return n?.stop(),{packages:r,storage:t}}async function getStorageLabel({options:e,fallback:t}){if(!e.remote)return t;const n=await getUserName();return n?getProfileLink(n):t}function printPackageTable({packages:e,subtitle:t}){console.log(`\n${yA} Packages`),console.log(`${le.gray("⎿")} ${le.dim(t)}\n`);const n=Math.max(...e.map(getPackageDisplayLength));let r=0;for(const t of e)r+=t.learningCount,console.log(formatPackageLine({pkg:t,maxLen:n}));console.log(le.dim(`\nTotal: ${e.length} packages, ${r} learnings\n`))}async function runList({options:e}){console.log(""),validateListOptions(e);const{packages:t,storage:n}=await fetchPackages({options:e});0!==t.length?printPackageTable({packages:t,subtitle:await getStorageLabel({options:e,fallback:n.subtitle})}):console.log(le.yellow(`No taste packages found in ${n.name}`))}async function fetchAllPackages(e){const{target:t}=e;return"local-project"===t?getAllPackages2():"local-global"===t?getAllPackages():getAllPackages3()}function handleOpenError(e){return e instanceof Error&&e.message.includes("$EDITOR environment variable")?{success:!1,error:getEditorSetupInstructions()}:{success:!1,error:e instanceof Error?e.message:String(e)}}async function readCategoryLineNumber(t){const{filePath:n,category:r}=t,s=await D.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const o=s.split("\n").findIndex(e=>e.trim().toLowerCase()===`# ${r.toLowerCase()}`);return o>=0?o+1:1}async function findCategoryLineNumber(e){try{return await readCategoryLineNumber(e)}catch{return 1}}async function openPackage(e){const{packageName:t,target:n}=e,r=(await fetchAllPackages({target:n})).find(e=>e.category===t);if(!r){let e="project";return"local-global"===n&&(e="global"),"remote-project"!==n&&"remote-user"!==n||(e="remote"),{success:!1,error:`Taste package '${t}' not found in ${e}`}}const s=r.sourcePath,o=await findCategoryLineNumber({filePath:s,category:t});return await it([{file:s,line:o}]),{success:!0,filePath:s,lineNumber:o}}__name(resolveStorage,"resolveStorage"),__name(getPackageDisplayLength,"getPackageDisplayLength"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),Ht(),Ht(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var CA=new Set(["local-project","local-global","remote-project","remote-user"]);async function open9(e){const{package:t,target:n}=e;if(!CA.has(n))return{success:!1,error:`Invalid target: ${n}`};try{return await openPackage({packageName:t,target:n})}catch(e){return handleOpenError(e)}}function getEditorSetupInstructions(){const e=dt.platform;if("win32"===e)return'Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n\nCommand Prompt (as Administrator):\n setx EDITOR "code" # VS Code\n setx EDITOR "notepad" # Notepad\n setx EDITOR "vim" # Vim (if installed via WSL/Git Bash)\n\nPowerShell:\n [Environment]::SetEnvironmentVariable("EDITOR", "code", "User")\n\nThen restart your terminal.';const t="darwin"===e?"~/.zshrc":"~/.bashrc";return`Error: No default editor found\n\nTo permanently set your default editor, run one of these commands:\n echo 'export EDITOR="code"' >> ${t} # VS Code\n echo 'export EDITOR="vim"' >> ${t} # Vim\n echo 'export EDITOR="nano"' >> ${t} # Nano\n echo 'export EDITOR="subl"' >> ${t} # Sublime Text\n\nFor bash users ${"darwin"===e?"(or ~/.bash_profile for bash)":"(or ~/.zshrc for zsh)"}, replace ${t} with the appropriate file.\n\nThen restart your terminal or run: source ${t}`}function createOpenCommand(){return new ve("open").argument("[package]","Taste package name, or owner/package to open in browser").option("-g, --global","Open taste package from global storage (~/.commandcode)").description(`Open a taste package in your editor ${le.dim("(use owner/package to open in browser)")}`).action(withErrorHandler(async(e,t)=>runOpen({packageName:e,options:t})))}function validateOpenOptions(e){e||exitWithUsage({message:"Specify a taste package name to open",usage:["cmd taste open <package> open taste package in editor","cmd taste open <package> -g open global taste package in editor","cmd taste open owner/package open package page in browser"]})}async function runOpen({packageName:e,options:t}){console.log(""),validateOpenOptions(e);const n=parseOwnerPackage(e);n?await openInBrowser(n):await openInEditor3({packageName:e,options:t})}async function openInBrowser(e){const t=`https://commandcode.ai/${e.owner}/${e.packageName}`;await me(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${le.green(ke.tick)} Opened ${n} in browser`)}async function openInEditor3({packageName:e,options:t}){const n=t.global?"local-global":"local-project",r=await open9({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${le.green(ke.tick)} Opened ${le.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open9,"open"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor3,"openInEditor"),Ht(),Ht(),Ht(),Ht();var kA=null,TA=!1;function setActiveSpinner(e){kA=e}function stopActiveSpinner(e){kA&&(kA.stop(e),kA=null)}function setPrompted(e){TA=e}function wasPrompted(){return TA}function beginPrompt(e,t){stopActiveSpinner(),qe.intro(le.dim(e)),t&&qe.log.message(le.dim(t)),setPrompted(!0)}function handleCancel(e){qe.isCancel(e)&&(qe.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=qe.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=qe.spinner();r.start(t),setActiveSpinner({stop:__name(e=>r.stop(e??n),"stop"),cancel:__name(e=>r.cancel(e),"cancel"),error:__name(e=>r.error(e),"error")})}async function promptMergeStrategy(e){const{packageName:t,owner:n,localPkg:r,remoteLearningsCount:s}=e,o="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),qe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${le.green(`'${t}'`)} from ${n}`,o),qe.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${s} learnings ${le.dim(`(from ${n})`)}`);const i=await qe.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with remote (${r.learnings.length} → ${s} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore remote"}],initialValue:"merge"});handleCancel(i);const a=i;return startStrategySpinner(a),a}async function promptGlobalPushStrategy(e){const{packageName:t,localLearningsCount:n,globalPkg:r}=e,s="This package already exists in global storage";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),qe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${le.green(`'${t}'`)} to global`,s),qe.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const o=await qe.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace global with local (${r.learnings.length} → ${n} learnings)`},{value:"skip",label:"Skip",hint:"Keep global version, cancel push"}],initialValue:"merge"});handleCancel(o);const i=o;return startStrategySpinner(i),i}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e,s="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),qe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${le.green(`'${t}'`)} from global`,s),qe.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const o=await qe.select({message:"What would you like to do?",options:[{value:"merge",label:"Merge",hint:"Combine both versions intelligently (default)"},{value:"overwrite",label:"Overwrite",hint:`Replace local with global (${n.learnings.length} → ${r} learnings)`},{value:"skip",label:"Skip",hint:"Keep local version, ignore global"}],initialValue:"merge"});handleCancel(o);const i=o;return startStrategySpinner(i),i}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:s}=e,o=`Pushing local project taste to individual package '${t}'`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),qe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ut(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${le.green(`'${t}'`)} to ${n}`,o),qe.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${s} learnings) in ${n}`),qe.log.info(`Current package: ${le.cyan(i)} ${le.dim("(review)")}`);const a=await qe.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:"Replace individual remote package with local project taste"}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}async function promptSameTypeStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:s}=e,o=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),qe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ut(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${le.green(`'${t}'`)} to ${n}`,o),qe.log.message(`Local: ${r} learnings\nRemote: ${s} learnings`),qe.log.info(`Current package: ${le.cyan(i)} ${le.dim("(review)")}`);const a=await qe.select({message:"What would you like to do?",options:[{value:"skip",label:"Skip",hint:"Keep remote version, cancel push"},{value:"overwrite",label:"Overwrite",hint:`Replace remote with local (${s} → ${r} learnings)`}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}function mergeSingleLearning(e,t,n,r){const s=t.get(e.text);return s?e.confidence>s.confidence?(n.set(e.text,e),void r.updated++):void r.unchanged++:(n.set(e.text,e),void r.added++)}function mergePackages(e){const{source:t,target:n}=e,r={added:0,updated:0,unchanged:0},s=new Map(n.map(e=>[e.text,e])),o=new Map(s);for(const e of t)mergeSingleLearning(e,s,o,r);const i=new Set(t.map(e=>e.text)),a=n.filter(e=>!i.has(e.text)).length;return r.unchanged+=a,{merged:Array.from(o.values()),details:r}}function validateSinglePackage(e,t){const n=validateTasteFile({content:formatPackage({pkg:e}),filePath:`${e.category}/taste.md`});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:e.category,error:`Validation failed for taste package in ${t}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${e.category}' in ${t} has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validateSingleRemoteFile(e,t){const n=validateTasteFile({content:e.content,filePath:e.file});if(!n.valid){const r=formatValidationIssues({result:n,verbose:!0});return{pkg:t,error:`Validation failed for ${e.file}:\n${r}`}}return n.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: File '${e.file}' has validation warnings:\n`),console.warn(formatValidationIssues({result:n,verbose:!0})+"\n")),null}function validatePackages(e){const{packages:t,label:n}=e;return t.map(e=>validateSinglePackage(e,n)).filter(e=>null!==e)}function validateRemoteFiles(e){const{files:t,packageName:n}=e;return t.map(e=>validateSingleRemoteFile(e,n)).filter(e=>null!==e)}function mergeOrKeep(e){const{source:t,existing:n}=e;if(!n)return{pkg:t,details:{added:t.learnings.length,updated:0,unchanged:0}};const r=mergePackages({source:t.learnings,target:n.learnings});return{pkg:{...t,learnings:r.merged},details:r.details}}async function resolveRemotePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,tastePkg:s,owner:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r?promptMergeStrategy({packageName:s.category,owner:o,localPkg:r,remoteLearningsCount:s.learnings.length}):"merge"}async function executePackageStrategy(e){const{tastePkg:t,owner:n,overwrite:r,flagStrategy:s,result:o}=e,i=await getPackage2({category:t.category}),a=await resolveRemotePullStrategy({flagStrategy:s,overwrite:r,existingPkg:i,tastePkg:t,owner:n});if("skip"===a)return void o.skipped?.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),o.packagesPulled.push(t.category),o.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),o.packagesPulled.push(t.category),o.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});o.filePaths[t.category]=l}async function processPackage(e){const{tastePkg:t,result:n}=e;try{await executePackageStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pullProjectPackage(e){const{files:t,packageName:n,owner:r,overwrite:s,flagStrategy:o,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(a){const e=parsePackages({content:a.content,sourcePath:`remote:${n}/taste.md`});for(const t of e)await processPackage({tastePkg:t,owner:r,overwrite:s,flagStrategy:o,result:i})}const l=t.filter(e=>"taste.md"!==e.file);for(const e of l){const t=e.file.replace("/taste.md",""),a={category:t,learnings:parseTasteContent(e.content),sourcePath:`remote:${n}/${t}`};await processPackage({tastePkg:a,owner:r,overwrite:s,flagStrategy:o,result:i})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:s,flagStrategy:o,result:i}=e,a=t.find(e=>"taste.md"===e.file);if(!a)return i.success=!1,void i.errors.push({pkg:n,error:"No taste.md file found in category package"});const l={category:n,learnings:parseTasteContent(a.content),sourcePath:`remote:${n}`};await processPackage({tastePkg:l,owner:r,overwrite:s,flagStrategy:o,result:i})}__name(setActiveSpinner,"setActiveSpinner"),__name(stopActiveSpinner,"stopActiveSpinner"),__name(setPrompted,"setPrompted"),__name(wasPrompted,"wasPrompted"),__name(beginPrompt,"beginPrompt"),__name(handleCancel,"handleCancel"),__name(startStrategySpinner,"startStrategySpinner"),__name(promptMergeStrategy,"promptMergeStrategy"),__name(promptGlobalPushStrategy,"promptGlobalPushStrategy"),__name(promptGlobalPullStrategy,"promptGlobalPullStrategy"),__name(promptTypeMismatchStrategy,"promptTypeMismatchStrategy"),__name(promptSameTypeStrategy,"promptSameTypeStrategy"),Ht(),Ht(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Ht(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var _A=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),xA=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),PA=__name(e=>"local-global"===e?"global":"remote-project"===e?"remote project":"remote-user"===e?"remote":"source","sourceName");async function resolvePullStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,source:s,tastePkg:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===s?promptGlobalPullStrategy({packageName:o.category,localPkg:r,globalLearningsCount:o.learnings.length}):"merge"}async function executePullStrategy(e){const{tastePkg:t,source:n,flagStrategy:r,overwrite:s,result:o}=e,i=await getPackage2({category:t.category}),a=await resolvePullStrategy({flagStrategy:r,overwrite:s,existingPkg:i,source:n,tastePkg:t});if("skip"===a)return void o.skipped.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),o.packagesPulled.push(t.category),o.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),o.packagesPulled.push(t.category),o.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});o.filePaths[t.category]=l}async function pullSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePullStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function pull(e){const{packages:t,source:n,overwrite:r=!1,strategy:s}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return _A({pkg:"all",error:`Invalid source: ${n}`});const o=PA(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return _A({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return _A({pkg:"all",error:`No taste packages found in ${o}`});const a=validatePackages({packages:i,label:o});if(a.length>0)return{success:!1,packagesPulled:[],errors:[...a],mergeDetails:{},overwritten:[],filePaths:{}};const l=t.length>0?i.filter(e=>t.includes(e.category)):i;if(t.length>0&&0===l.length)return{success:!1,packagesPulled:[],errors:t.map(e=>({pkg:e,error:`Taste package not found in ${o}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=xA();for(const e of l)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:s,overwrite:r,result:u});return u}async function executePullRemote(e){const{owner:t,packageName:n,overwrite:r,flagStrategy:s,result:o}=e,i=await downloadPackage({owner:t,packageName:n});if(!i)return _A({pkg:n,error:"Taste package not found in remote"});const{type:a,files:l}=i,u=validateRemoteFiles({files:l,packageName:n});if(u.length>0)return{success:!1,packagesPulled:[],errors:[...u],mergeDetails:{},overwritten:[],filePaths:{}};const d={files:l,packageName:n,owner:t,overwrite:r,flagStrategy:s,result:o};return"project"===a?(await pullProjectPackage(d),o):(await pullCategoryPackage(d),o)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:s}=e,o=xA();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:s,result:o})}catch(e){return _A({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return qe.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:s,mergeDetails:o}=e,i=wasPrompted()?"":`${ke.tick} `,a=r?le.dim(`\n ${shortenPath(r)}`):"";if(s.overwrite)return`${le.green(i)}Replaced ${le.green(`'${t}'`)} taste package in project`+a;if(o){const e=formatMergeParts(o);return`${le.green(i)}Pulled ${le.green(`'${t}'`)} taste package from ${n} ${le.gray(`(${e.join(", ")})`)}`+a}return`${le.green(i)}Pulled ${le.green(`'${t}'`)} taste package from ${n}`+a}function logPullSingleSuccess(e){const{result:t,sourceName:n,options:r}=e;if(1!==t.packagesPulled.length)return!1;const s=t.packagesPulled[0],o=t.filePaths?.[s],i=t.mergeDetails?.[s];return logResult(buildPullMessage({pkgName:s,sourceName:n,filePath:o,options:r,mergeDetails:i})),!r.overwrite&&!!i&&hasMergeConflictRisk(i)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],s=t.skipped??[],o=t.packagesPulled.filter(e=>!r.includes(e)),i=t.packagesPulled.length+s.length,a=`${i} ${1===i?"package":"packages"}`,l=[];return o.length>0&&l.push(wrapLine(`${le.green("Pulled")} (${o.length}) ${o.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${le.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),s.length>0&&l.push(wrapLine(`${le.dim("Skipped")} (${s.length}) ${le.dim(s.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&qe.log.message(l.join("\n")),qe.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${le.green(ke.tick)} ${a} from ${n}`),l.length>0&&console.log(l.join("\n")),hasMergeConflictRiskInRecord(t.mergeDetails??{}))}function logPullSuccess(e){const{result:t,sourceName:n,options:r}=e,s=t.skipped??[];t.packagesPulled.length+s.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():s.length>0?logResult(le.yellow(`Skipped '${s[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new ve("pull").argument("[package]","Taste package name, or owner/package to pull from remote").option("-g, --global","Pull taste package from global storage (~/.commandcode)").addOption(new Ce("--local","Use local server").hideHelp()).option("--remote","Pull taste package from commandcode.ai remote").option("--all","Pull all taste packages from global").option("--overwrite","Replace local package without prompting").option("--skip","Keep local package, skip conflicting pull").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new Ce("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${le.dim("(prompts on conflicts)")}`).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),{result:r,owner:s}=await runPull({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPullSuccess({result:r,sourceName:n.remote?s??"remote":"global",options:n})}))}function validatePullOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one source"),n.remote&&n.all&&exitWithUsage({message:"--all is not supported for remote pull — specify a package instead",usage:["cmd taste pull <owner>/<package> pull a taste package from remote"]}),n.remote&&!t&&exitWithUsage({message:"Specify a taste package to pull from remote",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),n.remote&&t&&!t.includes("/")&&exitWithUsage({message:`Remote pull requires owner/package format — got '${t}'`,usage:["cmd taste pull <owner>/<package> e.g. cmd taste pull ahmadawais/code-style"]}),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to pull everything",usage:["cmd taste pull <owner>/<package> pull a taste package from remote","cmd taste pull <package> -g pull a taste package from global","cmd taste pull --all -g pull all taste packages from global"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}async function runPull(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePullOptions({packageName:t,options:r});const s=resolveConflictStrategy(r);return r.remote&&t?pullRemoteSingle({packageName:t,options:r,strategy:s}):pullGlobal({packageName:t,options:r,strategy:s})}async function pullRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,s=parseOwnerPackage(t);s||exitWithError("Invalid format — use owner/package (e.g. ahmadawais/code-style)"),setActiveSpinner(Te("Pulling taste package").start());const o=await pullRemote({owner:s.owner,packageName:s.packageName,overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:o,owner:s.owner}}async function pullGlobal(e){const{packageName:t,options:n,strategy:r}=e;setActiveSpinner(Te("Pulling taste package").start());const s=n.all||!t?[]:[t],o=await pull({packages:s,source:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:o}}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new xy({baseUrl:e}),n=await t.get({endpoint:kt.ALPHA.NAMESPACES});if(!n.success)throw new Error("Failed to fetch namespaces");if("org"===n.type)return{userName:n.org.login,orgs:[]};const r=n.orgs.map(e=>({id:e.id,login:e.login,name:e.name}));return{userName:n.user.userName,orgs:r}}function logResult2(e){if(wasPrompted())return qe.outro(e),void setPrompted(!1);console.log(e)}function logPushAllSuccess(t){const{result:n,options:r}=t;if(!r.all)return!1;if(0===n.packagesPushed.length){const e=n.skipped?.length??0;if(e>0){const t=wasPrompted()?"":`${ke.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${le.green(t)}Skipped ${n}`)}return!1}const s=n.packagesPushed.length,o=`${s} ${1===s?"package":"packages"}`,i=n.filePaths?.[n.packagesPushed[0]],a=r.global&&i?shortenPath(e.dirname(e.dirname(i))):i,l=wasPrompted()?"":`${ke.tick} `;if(!a)return logResult2(`${le.green(l)}Pushed ${o} to remote`),!1;if(r.overwrite||Boolean(n.overwritten?.length)){let e=0;if(n.mergeDetails)for(const t of Object.values(n.mergeDetails))e+=t.updated??0;const t=e>0?` ${le.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${le.green(l)}Replaced ${o} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${le.green(l)}Pushed ${o} to ${a}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const g=formatMergeParts({added:u,updated:d,unchanged:m}),h=g.length>0?` ${le.gray(`(${g.join(", ")})`)}`:"";return logResult2(`${le.green(l)}Pushed ${o} to ${a}${h}`),(u>0||d>0)&&m>0}function logPushSingleSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(1!==t.packagesPushed.length)return!1;const r=t.packagesPushed[0],s=t.filePaths?.[r],o=n.remote&&s,i=o?s:"global",a=wasPrompted()?"":`${ke.tick} `,l=!o&&s?le.dim(`\n ${shortenPath(s)}`):"";if(n.overwrite)return logResult2(`${le.green(a)}Replaced ${le.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${le.green(a)}Pushed ${le.green(`'${r}'`)} taste package to ${i} ${le.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${le.green(a)}Pushed ${le.green(`'${r}'`)} taste package to ${i}`+l),!1}function logPushMultiSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(t.packagesPushed.length<=1)return!1;const r=n.remote?"remote":"global",s=wasPrompted()?"":`${ke.tick} `;return logResult2(wrapLine(`${le.green(s)}Pushed ${le.green(t.packagesPushed.length)} taste packages ${le.green(`(${t.packagesPushed.join(", ")})`)} to ${r}`)),!(n.overwrite||!t.mergeDetails)&&hasMergeConflictRiskInRecord(t.mergeDetails)}function logPushUrls(e){const{result:t,options:n}=e;if(!n.remote||!t.filePaths)return;const r=new Set;for(const e of t.packagesPushed){const n=t.filePaths[e];if(!n||!n.includes("/"))continue;const[s,o]=n.split("/");if(!s||!o)continue;const i=getPackageLink({owner:s,packageName:o});r.has(i)||(r.add(i),console.log(le.gray(` ${i}`)))}}function logConflictSummary(e){const{result:t}=e,n=t.overwritten??[],r=t.skipped??[],s=t.packagesPushed.filter(e=>!n.includes(e)),o=t.packagesPushed.length+r.length,i=[];s.length>0&&i.push(wrapLine(`${le.green("Merged")} (${s.length}) ${s.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${le.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${le.dim("Skipped")} (${r.length}) ${le.dim(r.join(", "))}`,4)),i.length>0&&qe.log.message(i.join("\n"));const a=`${o} ${1===o?"package":"packages"}`;qe.outro(a)}function logPushBreakdown(e){const t=e.overwritten??[],n=e.skipped??[];if(0===n.length&&0===t.length)return;const r=e.packagesPushed.filter(e=>!t.includes(e)),s=[];r.length>0&&s.push(wrapLine(`${le.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&s.push(wrapLine(`${le.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&s.push(wrapLine(`${le.dim("Skipped")} (${n.length}) ${le.dim(n.join(", "))}`)),s.length>0&&console.log(s.join("\n"))}function logPushSuccess(e){const{result:t,options:n}=e;if(wasPrompted())return setPrompted(!1),logConflictSummary({result:t}),void logPushUrls({result:t,options:n});const r=logPushAllSuccess({result:t,options:n})||logPushSingleSuccess({result:t,options:n})||logPushMultiSuccess({result:t,options:n});n.all&&logPushBreakdown(t),logPushUrls({result:t,options:n}),r&&logMergeReviewTip()}__name(resolvePullStrategy,"resolvePullStrategy"),__name(executePullStrategy,"executePullStrategy"),__name(pullSinglePackage,"pullSinglePackage"),__name(pull,"pull"),__name(executePullRemote,"executePullRemote"),__name(pullRemote,"pullRemote"),Ht(),__name(logResult,"logResult"),__name(buildPullMessage,"buildPullMessage"),__name(logPullSingleSuccess,"logPullSingleSuccess"),__name(logPullSummary,"logPullSummary"),__name(logPullSuccess,"logPullSuccess"),__name(createPullCommand,"createPullCommand"),__name(validatePullOptions,"validatePullOptions"),__name(runPull,"runPull"),__name(pullRemoteSingle,"pullRemoteSingle"),__name(pullGlobal,"pullGlobal"),Ht(),In(),Ht(),Xy(),Wy(),Kt(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Ht(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Ht(),sk(),Ht();var AA=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),IA=__name(e=>e.reduce((e,t)=>t.file.endsWith("taste.md")?e+parseTasteContent(t.content).length:e,0),"countRemoteLearnings");async function resolvePushAllStrategy(e){const{flagStrategy:t,overwrite:n,existingProject:r,packagesToPush:s,projectName:o,owner:i}=e;if("skip"===t)return"skip";if("overwrite"===t||n)return"overwrite";if("merge"===t)return"overwrite";if(!r)return"overwrite";const a=r.type??"category",l=s.reduce((e,t)=>e+t.learnings.length,0),u=IA(r.files);return"project"!==a?promptTypeMismatchStrategy({packageName:o,owner:i,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:o,owner:i,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:s,isPublic:o,isPublicExplicitlySet:i,flagStrategy:a}=t,l=e.basename(process.cwd()),u={success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}},d=await downloadPackage({owner:r,packageName:l}),m=await resolvePushAllStrategy({flagStrategy:a,overwrite:s,existingProject:d,packagesToPush:n,projectName:l,owner:r});if("skip"===m)return u.skipped.push(...n.map(e=>e.category)),u;await writePackages({packages:n,projectName:l,owner:r,isPublic:i?o:d?.isPublic??!1,overwrite:"overwrite"===m});for(const e of n)u.packagesPushed.push(e.category),u.filePaths[e.category]=`${r}/${l}`,u.mergeDetails[e.category]={added:e.learnings.length,updated:0,unchanged:0};return d&&u.overwritten.push(...n.map(e=>e.category)),u}async function pushAllRemote(e){try{return await executePushAllRemote(e)}catch(e){return AA({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var NA=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),RA=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:s,overwrite:o}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:s,overwrite:o})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var $A=__name(e=>{const{target:t,category:n,owner:r}=e;return"local-global"===t?getCategoryTasteFile({target:"local-global",category:n}):"remote-project"!==t&&"remote-user"!==t||!r?void 0:`${r}/${n}`},"getDestPath");async function getUserOwner(){try{const e=await getAuthenticatedEntity();if(e.success&&e.user?.userName)return e.user.userName}catch{}}async function resolveSinglePushStrategy(e){const{flagStrategy:t,overwrite:n,existingPkg:r,target:s,tastePkg:o}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===s?promptGlobalPushStrategy({packageName:o.category,localLearningsCount:o.learnings.length,globalPkg:r}):"merge"}async function executePushStrategy(e){const{tastePkg:t,target:n,flagStrategy:r,overwrite:s,userOwner:o,isPublic:i,result:a}=e,l="local-global"===n?await getPackage({category:t.category}):await getPackage3({category:t.category}),u=await resolveSinglePushStrategy({flagStrategy:r,overwrite:s,existingPkg:l,target:n,tastePkg:t});if("skip"===u)return void a.skipped.push(t.category);if("overwrite"===u&&(await writePkg({pkg:t,target:n,owner:o,isPublic:i,overwrite:!0}),a.packagesPushed.push(t.category),a.overwritten.push(t.category),a.mergeDetails[t.category]={added:0,updated:t.learnings.length,unchanged:0}),"merge"===u){const{pkg:e,details:r}=mergeOrKeep({source:t,existing:l});await writePkg({pkg:e,target:n,owner:o,isPublic:i}),a.packagesPushed.push(t.category),a.mergeDetails[t.category]=r}const d=$A({target:n,category:t.category,owner:o});d&&(a.filePaths[t.category]=d)}async function pushSinglePackage(e){const{tastePkg:t,result:n}=e;try{await executePushStrategy(e)}catch(e){n.success=!1,n.errors.push({pkg:t.category,error:e instanceof Error?e.message:String(e)})}}async function push(e){const t=void 0!==e.isPublic,{packages:n,target:r,overwrite:s=!1,isPublic:o=!1,strategy:i}=e;if(!exists2())return NA({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return NA({pkg:"all",error:"No taste packages found in project"});const l=validatePackages({packages:a,label:"project"});if(l.length>0)return{success:!1,packagesPushed:[],skipped:[],errors:[...l],mergeDetails:{},overwritten:[],filePaths:{}};const u=n.length>0?a.filter(e=>n.includes(e.category)):a;if(n.length>0&&0===u.length)return{success:!1,packagesPushed:[],skipped:[],errors:n.map(e=>({pkg:e,error:"Taste package not found in project"})),mergeDetails:{},overwritten:[],filePaths:{}};const d="remote-project"===r||"remote-user"===r?e.owner??await getUserOwner():void 0;if("remote-project"===r&&0===n.length)return d?pushAllRemote({packagesToPush:u,owner:d,overwrite:s,isPublic:o,isPublicExplicitlySet:t,flagStrategy:i}):NA({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return NA({pkg:"all",error:`Invalid target: ${r}`});const m=RA();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:i,overwrite:s,userOwner:d,isPublic:o,result:m});return m}async function executeRemotePush(e){const t=void 0!==e.isPublic,{owner:n,packageName:r,overwrite:s=!1,isPublic:o=!1,strategy:i}=e,a=await getPackage2({category:r});if(!a)return NA({pkg:r,error:`Taste package '${r}' not found in local project`});const l=validateTasteFile({content:formatPackage({pkg:a}),filePath:`${a.category}/taste.md`});if(!l.valid){const e=formatValidationIssues({result:l,verbose:!0});return NA({pkg:r,error:`Validation failed:\n${e}`})}l.issues.filter(e=>"warning"===e.severity).length>0&&(console.warn(`\nWarning: Taste package '${r}' has validation warnings:\n`),console.warn(formatValidationIssues({result:l,verbose:!0})+"\n"));const u=await downloadRemotePackage({owner:n,packageName:r}),d=await resolveSinglePushStrategy({flagStrategy:i,overwrite:s,existingPkg:u,target:"remote-project",tastePkg:a}),m=t?o:u?.isPublic??!1,g=RA();if("skip"===d)return g.skipped.push(r),g;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m,overwrite:!0}),g.packagesPushed.push(r),g.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),g.packagesPushed.push(r),g.mergeDetails[r]=t}return g.filePaths[r]=`${n}/${r}`,g}async function pushRemote(e){const{packageName:t}=e;if(!exists2())return NA({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return NA({pkg:t,error:e instanceof Error?e.message:String(e)})}}async function promptOwnerSelection(e){const{userName:t,orgs:n}=e;if(0===n.length)return t;const r=[{value:t,label:t,hint:"Personal"},...n.map(e=>({value:e.login,label:e.name||e.login,hint:"Organization"}))],s=await qe.select({message:"Owner",options:r,initialValue:t});return qe.isCancel(s)&&(qe.cancel("Operation cancelled"),process.exit(0)),s}function createPushCommand(){return new ve("push").description(`Push taste packages to remote ${le.dim("(commandcode.ai)")} or global ${le.dim("(~/.commandcode)")}`).argument("[package]","Taste package name to push (omit with --all)").option("--all","Push all taste packages to remote").option("--remote","Push to commandcode.ai remote (default)").option("-g, --global","Push to local global storage (~/.commandcode)").addOption(new Ce("--local","Use local server").hideHelp()).option("--public","Make package publicly discoverable on commandcode.ai").option("--private","Make package private (not publicly discoverable)").option("--owner <owner>","Push under a specific owner or organization").option("--overwrite","Replace existing package without prompting").option("--skip","Keep existing package, skip conflicting push").option("--merge","Auto-merge conflicting learnings without prompting").addOption(new Ce("--staging","Push to staging environment").hideHelp()).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),r=await runPush({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPushSuccess({result:r,options:n})}))}function validatePushOptions(e){const{packageName:t,options:n}=e;n.global&&n.remote&&exitWithError("--global and --remote are mutually exclusive — pick one destination"),n.public&&n.private&&exitWithError("--public and --private are mutually exclusive — pick one visibility"),n.owner&&n.global&&exitWithError("--owner only applies to remote pushes, not --global"),t||n.all||exitWithUsage({message:"Specify a taste package name or use --all to push everything",usage:["cmd taste push <package> push a taste package to remote (default)","cmd taste push --all push all taste packages to remote","cmd taste push <package> -g push a taste package to global (~/.commandcode)"]}),t&&n.all&&exitWithError("Use either a package name or --all, not both"),resolveConflictStrategy(n)}__name(getUserOwner,"getUserOwner"),__name(resolveSinglePushStrategy,"resolveSinglePushStrategy"),__name(executePushStrategy,"executePushStrategy"),__name(pushSinglePackage,"pushSinglePackage"),__name(push,"push"),__name(executeRemotePush,"executeRemotePush"),__name(pushRemote,"pushRemote"),Ht(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var MA=__name(e=>!!e.public||!e.private&&void 0,"resolveVisibility");async function validateOwnerAccess(e){let t;try{t=await fetchUserNamespaces()}catch(e){return void dlog(`[Auth] validateOwnerAccess: namespace service unavailable, skipping — ${e instanceof Error?e.message:String(e)}`)}const n=[t.userName,...t.orgs.map(e=>e.login)];n.includes(e)||exitWithError(`No push access to '${e}'. Available: ${n.join(", ")}`)}async function resolveOwnerForPush(e){const{packageName:t,owner:n}=e,r=parseOwnerPackage(t);if(r)return await validateOwnerAccess(r.owner),r;if(n)return await validateOwnerAccess(n),{owner:n,packageName:t};qe.intro(le.dim(`pushing ${t}`)),setPrompted(!0);const s=qe.spinner();s.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(s.error("Failed"),qe.outro(le.red(`Taste package '${t}' not found in project`)),process.exit(1));const o=await fetchUserNamespaces();return s.stop(o.orgs.length>0?"Select owner to push to":""),{owner:o.orgs.length>0?await promptOwnerSelection(o):o.userName,packageName:t}}async function runPush(e){const{packageName:t,options:n}=e;console.log("");const r=resolveRemoteDefault(n);validatePushOptions({packageName:t,options:r});const s=resolveConflictStrategy(r);return r.remote&&r.all?pushRemoteAll({options:r,strategy:s}):r.remote?pushRemoteSingle({packageName:t,options:r,strategy:s}):pushGlobal({packageName:t,options:r,strategy:s})}async function pushRemoteAll(t){const{options:n,strategy:r}=t;n.owner&&await validateOwnerAccess(n.owner);const s=(await getAllPackages2()).length,o=`${s} ${1===s?"package":"packages"}`,i=e.basename(process.cwd()),a=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(le.dim(` Pushing ${o} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner(Te("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:MA(n),strategy:r,owner:n.owner});return stopActiveSpinner(),l}async function pushRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,{owner:s,packageName:o}=await resolveOwnerForPush({packageName:t,owner:n.owner});startPushSpinner({owner:s,pkgName:o});const i=await pushRemote({owner:s,packageName:o,overwrite:n.overwrite,isPublic:MA(n),strategy:r});return stopActiveSpinner(`Pushed to ${s}/${o}`),i}function resolveStrategyLabel(e){const{strategy:t,isRemote:n=!1}=e;return"overwrite"===t?" · overwrite":"skip"===t?" · skip conflicts":"merge"===t?" · auto-merge":n?"":" · will prompt on conflicts"}function startPushSpinner(e){const{owner:t,pkgName:n}=e;if(wasPrompted()){const e=qe.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Te("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,s=n.all||!t?[]:[t],o=await getAllPackages2(),i=s.length>0?s.length:o.length,a=`${i} ${1===i?"package":"packages"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(le.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner(Te("Pushing taste packages").start());const d=await push({packages:s,target:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),d}function createTasteCommand(){const e=new ve($t.TASTE);return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),isExperimentalEnabled()&&e.addCommand(createLearnCommand()),e}function formatVersion(e,t,n=!1){const r=n?ce.bold(ce.green(t)):ce.white(t);return`${ce.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${ce.bold(ce.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(ce.dim(`Run ${ce.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(ce.dim("Try updating manually:")),console.log(ce.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(ce.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=Te("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.stop(),console.log(""),console.log(`${ce.green(ke.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${ce.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=Te("Checking for updates...").start(),t=await checkForUpdateAvailable();if(!t)return e.fail("Failed to check for updates"),void showCheckFailure();t.updateAvailable?(e.text=`Updating ${t.currentVersion} ${ke.arrowRight} ${t.latestVersion}...`,(await performAutoUpdate({silent:!0,updateInfo:t})).success||(e.fail("Update failed"),trackError({error:sanitizeErrorForTelemetry({error:new Error("Update failed"),label:"cli_update_failed"}),context:{component:ys.UPDATE_COMMAND,heading:"CLI update failed","update.current_version":t.currentVersion,"update.target_version":t.latestVersion}}),showManualUpdateHint(t.latestVersion),await shutdownTelemetry(),process.exit(1)),e.succeed(`Updated to v${t.latestVersion}`),showUpdateSuccessHint()):e.succeed(`Up to date ${ce.dim(`(${t.currentVersion})`)}`)}async function updateAction(e){e.checkOnly?await checkAction():await performUpdateAction()}__name(validateOwnerAccess,"validateOwnerAccess"),__name(resolveOwnerForPush,"resolveOwnerForPush"),__name(runPush,"runPush"),__name(pushRemoteAll,"pushRemoteAll"),__name(pushRemoteSingle,"pushRemoteSingle"),__name(resolveStrategyLabel,"resolveStrategyLabel"),__name(startPushSpinner,"startPushSpinner"),__name(pushGlobal,"pushGlobal"),xr(),__name(createTasteCommand,"createTasteCommand"),Ht(),Kt(),Cs(),__name(formatVersion,"formatVersion"),__name(showVersionDetails,"showVersionDetails"),__name(showUpdateSuccessHint,"showUpdateSuccessHint"),__name(showManualUpdateHint,"showManualUpdateHint"),__name(showCheckFailure,"showCheckFailure"),__name(checkAction,"checkAction"),__name(performUpdateAction,"performUpdateAction"),__name(updateAction,"updateAction");var LA=new ve("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Ht(),rk(),sk();var DA=__name((e,t)=>`${ke.info} ${e}: ${ce.cyan(t)}`,"formatInfoLine"),OA=__name(e=>ce.bold(`${e}:`),"formatSectionHeader"),FA=__name(e=>ce.red(e),"formatError"),qA=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),jA=__name(e=>["",OA("User Information"),DA("Name",e.name),DA("Email",e.email),DA("Username",e.userName)],"buildUserOutput"),BA=__name(e=>["",OA("Organization"),DA("Name",e.name),DA("Login",e.login)],"buildOrgOutput"),UA=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),zA=__name((e,t)=>{UA(jA(e)),t&&UA(BA(t)),console.log("")},"displayUserInfo"),WA=__name(e=>null!==e&&e.length>0,"validateApiKey"),GA=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=Te("Fetching user information...").start();try{const t=await getAuthKey();WA(t)||(e.fail(FA('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();GA(n)||(e.fail(FA("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),zA(n.user,n.org)}catch(t){e.fail(FA(`Error: ${qA(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var HA=new ve("whoami").description("Display current user information").allowUnknownOption().allowExcessArguments().action(whoamiAction);function normalizeGitUrl(e){let t=e.trim();const n=t.match(/^git@([^:]+):(.+?)(?:\.git)?$/);return n?`https://${n[1]}/${n[2]}`:(t=t.replace(/\.git$/,""),t)}function validateGitRepo(){try{if("true"!==$("git rev-parse --is-inside-work-tree",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error("Not inside a git repository.")}catch{throw new Error("Sandbox requires a git repository with a GitHub remote.")}let e;try{e=$("git remote get-url origin",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("No GitHub remote found. Add one with: git remote add origin https://github.com/you/repo")}const t=normalizeGitUrl(e);let n;try{n=$("git branch --show-current",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("Failed to determine current branch.")}if(!n)throw new Error("Detached HEAD state. Please checkout a branch first.");if(!/^[\w./-]+$/.test(n))throw new Error("Branch name contains invalid characters. Please use a simpler branch name.");try{if(!$(`git ls-remote --heads origin ${n}`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim())throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}catch(e){if(e instanceof Error&&e.message.includes("not found on remote"))throw e;throw new Error(`Branch "${n}" not found on remote. Push it first: git push -u origin ${n}`)}return{repoUrl:t,branch:n,isClean:""===$("git status --porcelain",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}function getGitHubToken(){const e=process.env.GITHUB_TOKEN;if(e)return e;try{return $("gh auth token",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{throw new Error("GitHub authentication required.\nEither set GITHUB_TOKEN or run: gh auth login")}}Ht(),Ht(),Kt(),Wy(),Xy(),Zt(),Nr(),Ht(),__name(normalizeGitUrl,"normalizeGitUrl"),__name(validateGitRepo,"validateGitRepo"),Ht(),__name(getGitHubToken,"getGitHubToken"),Ht(),Xy(),rk(),Ht();var QA=["completed","failed","cancelled","timed_out"];function isTerminalStatus(e){return QA.includes(e)}__name(isTerminalStatus,"isTerminalStatus");var VA={setting_up:"Setting up sandbox...",cloning:"Cloning repository..."};function stopAllSpinners({state:e}){e.workingSpinner&&(e.workingSpinner.stop(),e.workingSpinner=null),e.currentSpinner&&(e.currentSpinner.stop(),e.currentSpinner=null)}function renderStatusEvent({event:e,state:t}){const n=e.data.status,r=VA[n],s="setup"===t.phase;if(t.isResume&&s&&!isTerminalStatus(n)&&"running"!==n)r&&t.workingSpinner&&(t.workingSpinner.text=r);else{if(r&&s&&(t.currentSpinner&&t.currentSpinner.succeed(),t.currentSpinner=Te({stream:process.stderr,text:r}).start()),"running"===n)return t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="running",void(t.workingSpinner||(t.workingSpinner=Te({stream:process.stderr}).start()));if("completed"===n){t.workingSpinner&&(t.workingSpinner.succeed("Session completed"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.succeed(),t.currentSpinner=null),t.phase="done";const n=e.data.prUrl;return void(n&&console.error(`PR: ${ce.cyan(n)}`))}if("failed"===n){t.workingSpinner&&(t.workingSpinner.fail("Session failed"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail(),t.currentSpinner=null),t.phase="done";const n=e.data.message||"Unknown error";return void console.error(`${ke.cross} ${ce.red(n)}`)}if("timed_out"===n)return t.workingSpinner&&(t.workingSpinner.fail("Session timed out"),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail("Timed out"),t.currentSpinner=null),void(t.phase="done");"cancelled"===n&&(stopAllSpinners({state:t}),t.phase="done",console.error(`\n${ce.yellow("Cancelled.")}`))}}function renderEvent({event:e,state:t}){if("status"!==e.type){if("pty"===e.type){const n=e.data.content;return void(n&&(t.workingSpinner&&t.workingSpinner.stop(),process.stdout.write(n),t.workingSpinner&&t.workingSpinner.start()))}if("error"===e.type){t.currentSpinner&&(t.currentSpinner.fail(),t.currentSpinner=null);const n=e.data.message;console.error(`${ke.cross} ${ce.red(n)}`)}}else renderStatusEvent({event:e,state:t})}function setupInputHandling({callbacks:e}){const t=__name(t=>{3===t[0]?e.onCancel():4===t[0]&&e.onDetach()},"onStdinData"),n=process.rawListeners("SIGINT").slice();return process.removeAllListeners("SIGINT"),process.stdin.isTTY?(process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",t),process.on("SIGINT",()=>{})):process.on("SIGINT",()=>e.onCancel()),()=>{process.stdin.isTTY&&(process.stdin.removeListener("data",t),process.stdin.setRawMode(!1),process.stdin.pause()),process.removeAllListeners("SIGINT");for(const e of n)process.on("SIGINT",e)}}function setupResizeForwarding({ws:e}){const t=__name(()=>{e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({action:"resize",cols:process.stdout.columns,rows:process.stdout.rows}))},"onResize");return process.stdout.on("resize",t),()=>process.stdout.removeListener("resize",t)}function sendTerminalSize({ws:e}){e.send(JSON.stringify({action:"resize",cols:process.stdout.columns||120,rows:process.stdout.rows||30}))}async function streamSession({sessionId:e,prompt:t,lastEventId:n=0,isResume:r=!1}){const s=getApiBaseUrl().replace(/^http/,"ws"),o=await getAuthKey();if(!o)throw new Error("Not authenticated. Run: cmd login");const i=new URLSearchParams({token:o,...n>0?{lastEventId:String(n)}:{}}),a=`${s}/alpha/sandbox/stream/${e}?${i.toString()}`;return new Promise((t,s)=>{const o=new WebSocket(a),i={currentSpinner:null,workingSpinner:null,phase:"setup",lastEventId:n,isResume:r};r&&(i.currentSpinner=Te({stream:process.stderr,text:"Reconnecting..."}).start());const l=__name(()=>{i.phase="done",stopAllSpinners({state:i}),o.close(),console.error(`\n${ce.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${ce.cyan(`cmd --experimental sandbox --id ${e}`)}`),g(),t()},"detach"),u=__name(()=>{i.phase="done",stopAllSpinners({state:i}),o.readyState===WebSocket.OPEN&&o.send(JSON.stringify({action:"cancel"})),o.close(),console.error(`\n${ce.yellow("Sandbox stopped.")}`),g(),t()},"cancelSandbox"),d=setupResizeForwarding({ws:o}),m=setupInputHandling({callbacks:{onCancel:u,onDetach:l}});process.once("SIGTERM",l);const g=__name(()=>{d(),m(),process.removeListener("SIGTERM",l)},"teardown");o.addEventListener("open",()=>{sendTerminalSize({ws:o}),i.currentSpinner&&(i.currentSpinner.stop(),i.currentSpinner=null),console.error(""),console.error(`${ce.yellow("[Ctrl+C]")} ${ce.dim("stop")} ${ce.yellow("[Ctrl+D]")} ${ce.dim("detach")}`),console.error(`${ce.dim("Session:")} ${ce.gray(e)}`),console.error(""),r&&(i.workingSpinner=Te({stream:process.stderr}).start())}),o.addEventListener("message",e=>{try{const n="string"==typeof e.data?e.data:e.data.toString(),r=JSON.parse(n);renderEvent({event:r,state:i}),void 0!==r.id&&(i.lastEventId=r.id),"status"===r.type&&isTerminalStatus(r.data.status)&&(o.close(),g(),t())}catch{}}),o.addEventListener("error",()=>{g(),i.currentSpinner&&(i.currentSpinner.fail("Connection error"),i.currentSpinner=null),s(new Error("WebSocket connection failed"))}),o.addEventListener("close",()=>{"done"!==i.phase&&(i.phase="done",stopAllSpinners({state:i}),g(),console.error(`\n${ce.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${ce.cyan(`cmd --experimental sandbox --id ${e}`)}`),t())})})}function readLocalConfigFiles(){let e="",t="";try{e=E.readFileSync(getAuthFile(),"utf-8")}catch{}try{t=E.readFileSync(getConfigFile(),"utf-8")}catch{}return{auth:e,config:t}}async function askQuestion(e){const t=Je.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,e=>{t.close(),n(e)})})}async function startSandboxSession({repoUrl:e,branch:t,prompt:n,ghToken:r,isInternalTeam:s,configFiles:o}){return new xy({baseUrl:getApiBaseUrl()}).post({endpoint:kt.ALPHA.SANDBOX.START,body:{repoUrl:e,branch:t,prompt:n,ghToken:r,isInternalTeam:s,configFiles:o}})}async function sandboxMode({prompt:e,resume:t}){t&&(await streamSession({sessionId:t,isResume:!0}),process.exit(0)),await ensureAuthenticated()||process.exit(1);const n=validateGitRepo();n.isClean||console.error(ce.yellow("Warning: You have uncommitted changes. The sandbox clones from remote, so local changes won't be included."));const r=getGitHubToken(),s=isInternalTeamFlagPresent(),o=readLocalConfigFiles(),i=e||await askQuestion(`${ce.bold("What do you want to do?")}\n${ce.cyan(">")} `);if(!i.trim())return void console.error(ce.yellow("No prompt provided. Aborting."));const a=i.trim().slice(0,Mt.MAX_PROMPT_CHARS),l=Te({stream:process.stderr,text:"Starting sandbox session..."}).start();try{const e=await startSandboxSession({repoUrl:n.repoUrl,branch:n.branch,prompt:a,ghToken:r,isInternalTeam:s,configFiles:o});l.succeed("Sandbox started"),await streamSession({sessionId:e.sessionId,prompt:a}),process.exit(0)}catch(e){l.fail("Failed to start session");const t=e instanceof Error?e.message:"Unknown error";t.includes("401")||t.toLowerCase().includes("unauthorized")?console.error(ce.red("Authentication failed. Try logging in again: cmd login")):console.error(ce.red(t)),process.exit(1)}}function createSandboxCommand(){return new ve("sandbox").description("Run a task autonomously in a sandbox").argument("[prompt]","Task description").option("--id <sessionId>","Resume an existing sandbox session").enablePositionalOptions().action(async(e,t)=>{try{await sandboxMode({prompt:e,resume:t.id})}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(ce.red(t)),process.exit(1)}})}function validateSafeString(e,t){if(e.includes("..")||e.includes("\\"))throw new Error(`Invalid ${t}: path traversal sequences are not allowed.\nExpected format: owner/repo or owner/repo/path`);if(!/^[a-zA-Z0-9._/-]+$/.test(e))throw new Error(`Invalid ${t}: contains unsupported characters.\nOnly letters, numbers, hyphens, underscores, dots, and slashes are allowed.`)}function parseGitHubRepo(e){let t,n=e.replace(/^https?:\/\/github\.com\//,"");const r=n.lastIndexOf("@");r>0&&r<n.length-1&&(t=n.slice(r+1),n=n.slice(0,r),validateSafeString(t,"branch name"));const s=n.split("/");if(s.length<2)throw new Error("Invalid GitHub repository format. Expected: owner/repo or owner/repo/path");const[o,i,...a]=s;validateSafeString(o,"owner"),validateSafeString(i,"repository");const l=a.length>0?a.join("/"):void 0;return l&&validateSafeString(l,"path"),{owner:o,repo:i,path:l,branch:t}}function buildGigetSource(e){const{owner:t,repo:n,path:r,branch:s}=e;let o=`gh:${t}/${n}`;return r&&(o+=`/${r}`),s&&(o+=`#${s}`),o}async function fetchSkillFromGitHub(e){await cleanupStaleTempDirectories();const n=parseGitHubRepo(e),{owner:r,repo:s,path:o}=n;let i;if(o){const e=o.split("/").filter(Boolean);i=e[e.length-1]}else i=s;const a=t.join(w.tmpdir(),`commandcode-skill-${H()}`);await O.mkdir(a,{recursive:!0});try{const e=buildGigetSource(n),{downloadTemplate:o}=await import("giget");try{await o(e,{dir:a,force:!0,silent:!0})}catch(t){if(!isCorruptedArchiveError(t))throw t;await clearGigetCache(r,s),await o(e,{dir:a,force:!0,silent:!0})}const l=t.join(a,"SKILL.md"),u=t.join(a,"skill.md");let d=!1;try{await O.access(l),d=!0}catch{}if(!d)try{await O.access(u),d=!0}catch{}if(!d)throw new Error(`SKILL.md not found in ${e}. Make sure the repository contains a SKILL.md file.`);return{tempDir:a,skillName:i}}catch(e){if(await O.rm(a,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&e.message.includes("SKILL.md not found"))throw e;throw wrapFetchError(e,r,s)}}async function discoverSkillsInRepo(e,t){const n=parseGitHubRepo(e),{owner:r,repo:s,path:o,branch:i}=n,{keepTempDir:a=!1}=t||{},{discoverSkillsLocally:l}=await Promise.resolve().then(()=>(mk(),dk)),u=await l({owner:r,repo:s,path:o,branch:i,keepTempDir:a});if(0===u.skills.length)throw new Error(`No skills found in repository ${r}/${s}${o?` at path "${o}"`:""}. Ensure the repository contains SKILL.md files.`);return u}async function resolveSkillMdPath(e){const n=t.join(e,"SKILL.md");try{return await O.access(n),n}catch{}const r=t.join(e,"skill.md");try{return await O.access(r),r}catch{}throw new Error(`SKILL.md not found in ${e}`)}function validateSkillName(e){const t=e.trim();if(!t||0===t.length)throw new Error("Invalid skill name: name cannot be empty");if(t.includes("/")||t.includes("\\"))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain path separators (/ or \\).`);if(t.includes(".."))throw new Error(`Invalid skill name: "${e}". Skill names cannot contain parent directory references (..).`);if(t.startsWith("."))throw new Error(`Invalid skill name: "${e}". Skill names cannot start with a dot.`);if(!/^[a-z0-9-]+$/.test(t))throw new Error(`Invalid skill name: "${e}". Skill names must contain only lowercase letters, numbers, and hyphens.`);return t}async function validateSkillContent(e){const t=await resolveSkillMdPath(e),n=await O.readFile(t,"utf-8"),{data:r}=Ne(n),s=th.parse(r);return{name:validateSkillName(s.name),description:s.description}}async function skillExists(e){const{skillName:n,location:r}=e,s="global"===r?getGlobalSkillsDir():getProjectSkillsDir(),o=t.join(s,n);try{return await O.access(o),!0}catch{return!1}}async function discoverSkills(e,t){return discoverSkillsInRepo(e,t)}async function installSkill(e){const{repoInput:n,options:r={}}=e,{global:s=!1,force:o=!1,skillName:i,discoveredSkill:a,cachedTempDir:l}=r;let u,d,m=n;if(i){let e;if(a)e=a;else{const t=await discoverSkillsInRepo(n);if(0===t.skills.length)throw new Error(`No skills found in repository: ${n}`);const r=t.skills.find(e=>e.name.toLowerCase()===i.toLowerCase());if(!r){const e=t.skills.map(e=>e.name).join(", ");throw new Error(`Skill "${i}" not found in repository. Available skills: ${e}`)}e=r}const t=parseGitHubRepo(n),r=[t.path,e.path&&"."!==e.path?e.path:void 0].filter(Boolean).join("/"),s=r?`${t.owner}/${t.repo}/${r}`:`${t.owner}/${t.repo}`;m=t.branch?`${s}@${t.branch}`:s}if(l&&a){u=a.path&&"."!==a.path?t.join(l,a.path):l,d=!1;try{await resolveSkillMdPath(u)}catch{const e=a.path&&"."!==a.path?`at ${a.path}`:"at root";throw new Error(`SKILL.md not found in cached directory ${e}. Make sure the repository contains a SKILL.md file.`)}}else u=(await fetchSkillFromGitHub(m)).tempDir,d=!0;try{const{name:e,description:n}=await validateSkillContent(u),r=e,i=s?"global":"project",a="global"===i?getGlobalSkillsDir():getProjectSkillsDir(),l=await skillExists({skillName:r,location:i});if(l&&!o)throw new Error(`Skill "${r}" already exists in ${"global"===i?"~/.commandcode/skills/":".commandcode/skills/"}. Use --force to overwrite.`);await O.mkdir(a,{recursive:!0});const d=t.join(a,r),{randomUUID:m}=await import("crypto"),g=t.join(a,`.${r}.tmp.${m()}`);try{await O.cp(u,g,{recursive:!0,force:!0,dereference:!1}),l&&o&&await O.rm(d,{recursive:!0,force:!0}),await O.rename(g,d)}catch(e){if(await O.rm(g,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&"code"in e&&("EEXIST"===e.code||"ENOTEMPTY"===e.code))throw new Error(`Skill "${r}" was created by another process during installation. Use --force to overwrite.`);throw e}let h;try{h=await resolveSkillMdPath(d)}catch{h=t.join(d,"SKILL.md")}return{name:r,description:n,location:i,path:h}}finally{d&&await O.rm(u,{recursive:!0,force:!0}).catch(()=>{})}}async function removeSkill(e){const{global:n=!1}=e,r=validateSkillName(e.skillName),s=n?"global":"project",o="global"===s?getGlobalSkillsDir():getProjectSkillsDir(),i=t.join(o,r);if(!await skillExists({skillName:r,location:s}))throw new Error(`Skill "${r}" not found in ${"global"===s?"global (~/.commandcode/skills/)":"project (.commandcode/skills/)"} skills.${"global"===s?"":" Use -g/--global to check global skills."}`);await O.rm(i,{recursive:!0,force:!0})}async function listSkills(){const{global:e,project:t}=await loadAllSkillSummaries();return{global:e.map(e=>({name:e.name,description:e.description,location:"global",path:e.filePath})),project:t.map(e=>({name:e.name,description:e.description,location:"project",path:e.filePath}))}}__name(stopAllSpinners,"stopAllSpinners"),__name(renderStatusEvent,"renderStatusEvent"),__name(renderEvent,"renderEvent"),__name(setupInputHandling,"setupInputHandling"),__name(setupResizeForwarding,"setupResizeForwarding"),__name(sendTerminalSize,"sendTerminalSize"),__name(streamSession,"streamSession"),__name(readLocalConfigFiles,"readLocalConfigFiles"),__name(askQuestion,"askQuestion"),__name(startSandboxSession,"startSandboxSession"),__name(sandboxMode,"sandboxMode"),__name(createSandboxCommand,"createSandboxCommand"),xr(),Ht(),Ht(),Ht(),Ht(),uk(),__name(validateSafeString,"validateSafeString"),__name(parseGitHubRepo,"parseGitHubRepo"),__name(buildGigetSource,"buildGigetSource"),__name(fetchSkillFromGitHub,"fetchSkillFromGitHub"),__name(discoverSkillsInRepo,"discoverSkillsInRepo"),mw(),Eh(),__name(resolveSkillMdPath,"resolveSkillMdPath"),__name(validateSkillName,"validateSkillName"),__name(validateSkillContent,"validateSkillContent"),__name(skillExists,"skillExists"),__name(discoverSkills,"discoverSkills"),__name(installSkill,"installSkill"),__name(removeSkill,"removeSkill"),__name(listSkills,"listSkills"),Kt();var KA=[`${ce.dim("Usage:")}`,` ${ce.cyan("cmd skills add")} ${ce.white("<owner/repo>")}`,"",`${ce.dim("Examples:")}`,` ${ce.cyan("cmd skills add")} ${ce.white("acme/my-skills")} ${ce.dim("# single-skill repo")}`,` ${ce.cyan("cmd skills add")} ${ce.white("acme/skills/path/to/skill")} ${ce.dim("# specific path in repo")}`,` ${ce.cyan("cmd skills add")} ${ce.white("acme/multi-skills -s my-skill")} ${ce.dim("# pick one from multi-skill repo")}`,` ${ce.cyan("cmd skills add")} ${ce.white("acme/repo@branch")} ${ce.dim("# specific branch")}`,` ${ce.cyan("cmd skills add")} ${ce.white("acme/repo --global")} ${ce.dim("# install to ~/.commandcode/skills/")}`],YA=__name((e,t)=>`${ce.green(ke.tick)} Installed ${ce.cyan(e)} ${ce.dim(`${ke.arrowRight} ${t}/`)}`,"formatInstalled"),JA=__name(e=>`${ce.red(ke.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){e&&await F(e,{recursive:!0,force:!0}).catch(()=>{}),process.exit(t)}function validateRepoFormat(e){(e.startsWith(".")||e.startsWith("/")||e.startsWith("~"))&&(console.error(JA("Local paths are not supported. Skills must be installed from GitHub.")),console.log(""),KA.forEach(e=>console.log(e)),process.exit(1));const t=e.replace(/^https?:\/\/github\.com\//,""),n=t.lastIndexOf("@");(n>0?t.slice(0,n):t).split("/").filter(Boolean).length<2&&(console.error(JA(`Invalid repository: "${e}"`)),console.log(""),console.log(`Expected format: ${ce.cyan("owner/repo")} or ${ce.cyan("owner/repo/path")}`),console.log(""),KA.forEach(e=>console.log(e)),process.exit(1))}async function addAction(e,t){const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"~/.commandcode/skills":".commandcode/skills";let s;validateRepoFormat(e);const o=Te({text:`Fetching ${ce.cyan(e)}...`,color:"cyan"});try{let i=[];o.start();const a=await discoverSkills(e,{keepTempDir:!0}),{skills:l,tempDir:u}=a;if(s=u,o.stop(),0===l.length&&(console.error(JA(`No skills found in ${ce.cyan(e)}`)),console.log(ce.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(s,1)),t.skill){const n=l.find(e=>e.name.toLowerCase()===t.skill.toLowerCase());n||(console.error(JA(`Skill "${t.skill}" not found in ${ce.cyan(e)}`)),console.log(""),console.log(ce.dim("Available skills:")),l.forEach(e=>console.log(` ${ce.cyan(e.name)}`)),await cleanupAndExit(s,1)),i=[n]}else if(1===l.length)i=[l[0]];else if(n){const t=await je({message:`Select skills to install from ${e}`,options:l.map(e=>({value:e.name,label:e.name})),required:!0});"symbol"==typeof t&&(console.log(ce.dim("Cancelled")),await cleanupAndExit(s,0));const n=t;i=l.filter(e=>n.includes(e.name))}else i=l;let d=0;for(const n of i)try{const o=Te({text:`Installing ${ce.cyan(n.name)}...`,color:"cyan"});o.start();const i=await installSkill({repoInput:e,options:{global:t.global,force:t.force,skillName:n.name,discoveredSkill:n,cachedTempDir:s}});o.stop(),console.log(YA(i.name,r))}catch(e){d++;const t=e instanceof Error?e.message:String(e);console.error(JA(`Failed to install "${n.name}"`)),console.log(ce.dim(` ${t}`))}await cleanupAndExit(s,d>0?1:0)}catch(e){o.stop();const t=e instanceof Error?e.message:String(e);console.error(JA(t)),await cleanupAndExit(s,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction,"addAction");var XA=new ve("add").description("Install a skill from a GitHub repository").argument("<repo>","GitHub repository (owner/repo or owner/repo/path)").option("-g, --global","Install to global skills (~/.commandcode/skills/)").option("-f, --force","Overwrite if skill already exists").option("-s, --skill <name>","Specific skill name to install from repo").addHelpText("after",`\n${KA.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(JA("No repository specified.")),console.log(""),KA.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction);Ht(),Kt();var ZA=__name((e,t)=>`${ce.green(ke.tick)} Removed ${ce.cyan(e)} from ${t} skills`,"formatRemoved"),eI=__name(e=>`${ce.red(ke.cross)} ${e}`,"formatError");function validateSkillNameEarly(e){return e.includes("/")||e.includes("\\")?`"${e}" is not a valid skill name — it cannot contain path separators.`:e.includes("..")?`"${e}" is not a valid skill name — it cannot contain "..".`:e.startsWith(".")?`"${e}" is not a valid skill name — it cannot start with a dot.`:/^[a-z0-9-]+$/.test(e.trim())?null:`"${e}" is not a valid skill name — use only lowercase letters, numbers, and hyphens.`}async function removeAction(e,t){try{const n=process.stdout.isTTY&&process.stdin.isTTY,r=t.global?"global":"project",s=validateSkillNameEarly(e);if(s&&(console.error(eI(s)),console.log(ce.dim(`Run ${ce.cyan("cmd skills list")} to see installed skills.`)),process.exit(1)),!t.yes&&n){const t=await Be({message:`Remove ${ce.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(ce.dim("Cancelled")),process.exit(0))}await removeSkill({skillName:e,global:t.global}),console.log(ZA(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill";r.includes("not found")?(console.error(eI(`Skill "${e}" not found in ${t.global?"global":"project"} skills`)),t.global||console.log(ce.dim(`Try ${ce.cyan(`cmd skills remove ${e} --global`)} to check global skills.`)),console.log(ce.dim(`Run ${ce.cyan("cmd skills list")} to see installed skills.`))):console.error(eI(r)),process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction,"removeAction");var tI=new ve("remove").description("Remove an installed skill").argument("<skill-name>","Name of the skill to remove").option("-g, --global","Remove from global skills (~/.commandcode/skills/)").option("-y, --yes","Skip confirmation prompt").action(removeAction);Ht(),mw(),MC(),Kt();var nI=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${ce.cyan(e)} ${ce.dim(`· ${n}`)}`},"formatSkillLine"),rI=__name((e,t)=>`${ce.bold(ce.white(e))} ${ce.dim(`(${t})`)}`,"formatSectionHeader"),sI=__name(()=>["",ce.dim("No skills installed."),"",ce.dim("Looking in:"),ce.dim(` ${getGlobalSkillsDir()} ${ce.white("(global)")}`),ce.dim(` ${getProjectSkillsDir()} ${ce.white("(project)")}`),ce.dim(` ${getGlobalAgentsCompatSkillsDir()} ${ce.white("(global, .agents)")}`),ce.dim(` ${getProjectAgentsCompatSkillsDir()} ${ce.white("(project, .agents)")}`),"",`Install a skill: ${ce.cyan("cmd skills add")} ${ce.dim("<owner/repo>")}`,""],"formatEmptyHint"),oI=__name(e=>{e.forEach(e=>console.log(e))},"printLines");async function listAction(){try{const{global:e,project:t}=await listSkills(),n=e.length+t.length;0===n&&(oI(sI()),process.exit(0)),console.log(""),console.log(heading({text:"Skills",sub:ce.dim(`${n} installed`)})),t.length>0&&(console.log(""),console.log(rI("Project",t.length)),t.forEach(e=>{console.log(nI(e.name,e.description))})),e.length>0&&(console.log(""),console.log(rI("Global",e.length)),e.forEach(e=>{console.log(nI(e.name,e.description))})),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${ce.red(ke.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction,"listAction");var iI=new ve("list").description("List all installed skills").action(listAction),aI=new ve("skills").description("Manage skills from GitHub repositories").addCommand(XA).addCommand(tI).addCommand(iI);handleUnhandledErrors(),setupTelemetry(),await preRun();var lI=createProgram();lI.action(interactiveModeAction),lI.addCommand(BP),lI.addCommand(UP),lI.addCommand(HA),lI.addCommand(LA),lI.addCommand(jP),lI.addCommand(createTasteCommand()),lI.addCommand(createMcpCommand()),lI.addCommand(zP),lI.addCommand(vs),lI.addCommand(GC),lI.addCommand(ek),lI.addCommand(aI),isExperimentalEnabled()&&lI.addCommand(createSandboxCommand()),setupCommanderHooks(lI),lI.parse();