command-code 0.18.2 → 0.18.4
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 +3 -3
- package/package.json +1 -1
- package/vsix/commandcode-vscode.vsix +0 -0
package/dist/index.mjs
CHANGED
|
@@ -274,6 +274,6 @@ import*as e from"path";import t,{join as n,dirname as r,relative as s,resolve as
|
|
|
274
274
|
WHERE user_id = ${Gy}
|
|
275
275
|
AND role IN ('owner', 'admin')
|
|
276
276
|
)
|
|
277
|
-
`})])),b(Ky)}}),fw=__esm({"../shared/src/database/schema/index.ts"(){Ft(),$h(),ow(),iw(),Rh(),aw(),lw(),cw(),uw(),dw(),mw(),pw(),gw(),hw(),Mh()}}),yw=__esm({"../shared/src/database/config/database.ts"(){Ft(),sw(),fw()}}),ww=__esm({"../shared/src/database/index.ts"(){Ft(),yw(),fw()}}),Sw=__esm({"../shared/src/index.ts"(){Ft(),fo(),yo(),Yh(),Jh(),Xh(),zt(),jt(),ww()}}),bw=__esm({"src/api/request.ts"(){Ft(),po(),ho(),gs(),jr(),Tr(),Sw(),Yy=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}),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 eo({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",[vt.CLI_ENVIRONMENT]:a,...n?{Authorization:`Bearer ${n}`}:{},...o?{traceparent:o}:{},...e}}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:Zs.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"})}}}}),Ew=__esm({"../shared/src/constants/tools.ts"(){Ft(),Jy={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"},Xy={WEB_SEARCH:"web_search",WEB_FETCH:"web_fetch"},Zy=__name(e=>e===Xy.WEB_SEARCH,"isWebSearchTool"),ew=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],tw=__name(({serverToolBlock:e,contentBlocks:t})=>{const n=t.find(t=>("web_search_tool_result"===t.type||"web_fetch_tool_result"===t.type)&&t.tool_use_id===e.id);return ew.includes(n?.content?.type)?{message:`Error: ${n?.content?.error_code||"unknown_error"}`,isError:!0}:Zy(e.name)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage"),nw=["create_file","delete_file",Jy.EDIT_FILE,Jy.WRITE_FILE,Jy.SHELL_COMMAND],rw=[Jy.SHELL_COMMAND]}});function getEnterpriseMemoryPath(){switch(h.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=h.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:v(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(v(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:v(s),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return v(e)&&_(e).isFile()?await M.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(h.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(v(s)){const e=await loadMemoryFile(s);if(e){const t=await processImports(e,s);r.set(s,t)}}const o=getUserMemoryPath();if(v(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(v(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(v(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 v(r)||await M.mkdir(r,{recursive:!0}),v(t)||await M.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const s=R(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 v(n)||await M.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 vw,Cw,kw,Tw,_w,xw,Pw,Aw=__esm({"src/utils/memory.ts"(){Ft(),zt(),__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(vw))return t.includes(kw)?t:t.includes(Cw)?t.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"").replace(vw,kw):t.replace(vw,kw);let n=t;return n.includes(Cw)&&(n=n.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"")),xw.test(n)?n=n.replace(xw,`$1${kw}`):Pw.test(n)&&(n=n.replace(Pw,`$1${kw}`)),n}var Iw=__esm({"src/commands/taste/utils/header-migration.ts"(){Ft(),kw=`${vw="# Taste (Continuously Learned by [CommandCode][cmd])"}\n\n${Cw="[cmd]: https://commandcode.ai/"}`,Tw="# Taste (Continuously Learned by CommandCode)",_w="# Taste (Continuously Learned by CommandCode.ai)",xw=/^(\s*)# Taste \(Continuously Learned by CommandCode\)(?!\.ai)/,Pw=/^(\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(!v(n))return null;const r=await M.readFile(n,"utf-8"),s=r.trim();return s&&s!==kw&&s!==vw&&s!==_w&&s!==Tw?r:null}catch(e){return null}}var Nw=__esm({"src/utils/taste/get-taste-content.ts"(){Ft(),zt(),Iw(),__name(getTasteContent,"getTasteContent")}}),Rw=__esm({"src/tools/skills/types.ts"(){Ft()}});function getGlobalSkillsDir(){return t.join(f.homedir(),".commandcode","skills")}function getProjectSkillsDir(){let e,n=process.cwd(),r=n;for(;;){if(v(t.join(r,".git"))){e=r;break}const n=t.dirname(r);if(n===r)break;r=n}if(e)return t.join(e,".commandcode","skills");for(r=n;;){const e=t.join(r,".commandcode");if(v(e))return t.join(e,"skills");const n=t.dirname(r);if(n===r)break;r=n}return t.join(process.cwd(),".commandcode","skills")}async function resolveSkillFilePath(e){const{skillDir:n}=e,r=t.join(n,"SKILL.md");try{return await D.access(r),r}catch{}const s=t.join(n,"skill.md");try{return await D.access(s),s}catch{return null}}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await D.access(n);const e=await D.readdir(n,{withFileTypes:!0}),r=(await Promise.all(e.map(async e=>{if(e.isDirectory())return e;if(e.isSymbolicLink())try{return(await D.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 D.readFile(r,"utf-8"),{data:o}=Fe(s),i=Ih.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[]}}async function loadAllSkillSummaries(){const[e,t]=await Promise.all([loadSkillSummariesFromDirectory({dir:getGlobalSkillsDir()}),loadSkillSummariesFromDirectory({dir:getProjectSkillsDir()})]);return{global:e,project:t}}var $w=__esm({"src/tools/skills/loader.ts"(){Ft(),Qh(),zt(),__name(getGlobalSkillsDir,"getGlobalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(resolveSkillFilePath,"resolveSkillFilePath"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries")}});function escapeXML(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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 Mw,Dw,Lw=__esm({"src/tools/skills/xml-generator.ts"(){Ft(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML")}}),Ow=__esm({"src/tools/skills/index.ts"(){Ft(),Rw(),$w(),Lw()}}),qw=__esm({"src/tools/read-file/types.ts"(){Ft(),Mw=g.object({absolutePath:g.string().describe("The absolute path to the file to read"),offset:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional()).describe("Optional line number to start reading from (0-based index)"),limit:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional()).describe("Optional number of lines to read")}),g.object({content:g.union([g.string(),g.instanceof(Buffer)]),contentType:g.enum(["text","binary"]),fileType:g.string(),size:g.number(),linesRead:g.number().optional()}),Dw=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 Fw,jw=__esm({"src/utils/index.ts"(){Ft(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath")}});async function readFileContent(t){const{absolutePath:n,offset:r,limit:s}=t;if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new Dw("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=e.normalize(n);try{await M.access(o,w.constants.F_OK|w.constants.R_OK)}catch{throw new Dw(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await M.stat(o)).isFile())throw new Dw("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 Dw("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new Dw("Offset must be >= 0","INVALID_OFFSET");if(void 0!==s&&s<=0)throw new Dw("Limit must be > 0","INVALID_LIMIT");try{if(a){const e=await M.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 M.readFile(o,"utf8");return{content:e,fileType:i,contentType:"text",size:Buffer.byteLength(e,"utf8")}}}catch(e){if(e instanceof Dw)throw e;throw new Dw(`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",...Fw}[n]||"unknown"}function isBinaryFile(e){return Object.values(Fw).includes(e)}async function readTextFileLines(e,t,n){const r=(await M.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,zw=__esm({"src/tools/read-file/read-file.ts"(){Ft(),jw(),qw(),__name(readFileContent,"readFileContent"),Fw={".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 Uw=__esm({"src/tools/utils/read-summary.ts"(){Ft(),__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 Ww,Gw,Hw,Qw,Vw,Kw=__esm({"src/tools/read-file/formatter.ts"(){Ft(),Uw(),__name(formatOutput,"formatOutput")}}),Yw=__esm({"src/tools/read-file/index.ts"(){Ft(),qw(),zw(),Kw(),Ww={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=Mw.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading file"}},"execute")}}}),Jw=__esm({"src/tools/edit-file/types.ts"(){Ft(),Gw=g.object({filePath:g.string().describe("The absolute path to the file to edit"),oldValue:g.string().describe("The text to replace"),newValue:g.string().describe("The new text to insert"),replacementCount:g.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:g.boolean().optional().describe("Whether to replace all occurrences (default: false)")}),g.object({path:g.string(),replacementsCount:g.number(),oldContent:g.string(),newContent:g.string()}),g.object({name:g.string(),message:g.string(),code:g.string().optional()})}}),Xw=__esm({"src/lib/checkpoints/types.ts"(){Ft(),Hw=g.object({backupFileName:g.string().nullable(),version:g.number().int().positive(),backupTime:g.string().datetime()}),Qw=g.object({messageId:g.string().uuid(),trackedFileBackups:g.record(g.string(),Hw),timestamp:g.string().datetime()}),g.object({type:g.literal("file-history-snapshot"),messageId:g.string().uuid(),snapshot:Qw,isSnapshotUpdate:g.boolean()}),g.object({maxFileSize:g.number().int().positive().default(10485760),retentionDays:g.number().int().positive().default(30)}),Vw=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`${U.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(f.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 D.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 D.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await D.writeFile(r,n);const e=await D.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 D.rename(r,t)}catch(e){try{await D.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await D.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await D.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 Zw,eS,tS,nS,rS=__esm({"src/lib/checkpoints/utils.ts"(){Ft(),zt(),__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")}}),sS=__esm({"src/lib/checkpoints/file-history.ts"(){Ft(),Xw(),rS(),gs(),Zw={maxFileSize:10485760,retentionDays:30},eS=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...Zw,...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 D.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:ls.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 D.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new Vw(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:ls.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const s=await D.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 D.access(t,D.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 D.readdir(n);for(const s of e)if(!s.endsWith(".tmp")&&!t.has(s))try{await D.unlink(`${n}/${s}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await D.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}}}}),oS=__esm({"src/lib/checkpoints/checkpoint-manager.ts"(){Ft(),sS(),rS(),os(),gs(),tS=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new eS({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:ls.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 nS=new tS({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return nS?nS.backupFile({filePath:t}):{success:!0,backup:null}}var iS=__esm({"src/lib/checkpoints/checkpoint-service.ts"(){Ft(),oS(),nS=null,__name(initializeCheckpointService,"initializeCheckpointService"),__name(backupFileBeforeEdit,"backupFileBeforeEdit")}}),aS=__esm({"src/lib/checkpoints/index.ts"(){Ft(),Xw(),sS(),oS(),rS(),iS()}});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 P.access(n,A.F_OK|A.R_OK|A.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 P.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 lS=__esm({"src/tools/edit-file/edit-file.ts"(){Ft(),zw(),jw(),Jw(),aS(),__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 cS,uS,dS,mS=__esm({"src/tools/edit-file/formatter.ts"(){Ft(),__name(formatOutput2,"formatOutput")}}),pS=__esm({"src/tools/edit-file/index.ts"(){Ft(),Jw(),lS(),mS(),cS={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=Gw.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while editing file"}},"execute")}}}),gS=__esm({"src/tools/read-directory/types.ts"(){Ft(),uS=g.object({path:g.string().describe("The absolute path to the directory to read"),exclude:g.array(g.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:g.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")}),g.object({files:g.array(g.string()),directories:g.array(g.string())}),dS=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 dS("Path must be absolute, not relative","INVALID_PATH");try{if(!(await M.stat(n)).isDirectory())throw new dS("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof dS)throw e;throw new dS(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await M.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 M.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 dS)throw e;throw new dS(`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 findGitRoot(t);for(;r&&isWithinGitRoot(r,s);){const t=e.join(r,".gitignore");try{const e=(await M.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 findGitRoot(e)}catch{return!1}}async function findGitRoot(t){let n=e.resolve(t);for(;;){try{const t=e.join(n,".git");if((await M.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(je(e,n))return!0;return!1}var hS=__esm({"src/tools/read-directory/read-directory.ts"(){Ft(),gS(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"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 fS,yS,wS=__esm({"src/tools/read-directory/formatter.ts"(){Ft(),__name(formatOutput3,"formatOutput")}}),SS=__esm({"src/tools/read-directory/index.ts"(){Ft(),gS(),hS(),wS(),fS={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=uS.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading directory"}},"execute")}}}),bS=__esm({"src/tools/write-file/types.ts"(){Ft(),yS=g.object({filePath:g.string().describe("The absolute path where the file should be written"),content:g.string().describe("The content to write to the file")}),g.object({success:g.boolean(),message:g.string(),path:g.string().optional()})}});async function writeFile3({filePath:e,content:n}){const s=e.startsWith("~/")?t.join(f.homedir(),e.slice(2)):e;if(!l(s))throw new Error(`Invalid file path: '${s}'. Only absolute paths are supported.`);try{const e=r(s);return v(e)||await B(e,{recursive:!0}),await backupFileBeforeEdit({filePath:s}),await O(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"(){Ft(),aS(),__name(writeFile3,"writeFile")}});function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}var vS,CS,kS,TS,_S,xS=__esm({"src/tools/write-file/formatter.ts"(){Ft(),__name(formatOutput4,"formatOutput")}}),PS=__esm({"src/tools/write-file/index.ts"(){Ft(),bS(),ES(),xS(),vS={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=yS.parse(e),n=await writeFile3(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")}}}),AS=__esm({"src/tools/read-multiple-files/types.ts"(){Ft(),CS=g.object({include:g.array(g.string()).describe("Array of glob patterns to include files"),exclude:g.array(g.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:g.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:g.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:g.string().optional().describe("Base directory for relative paths. Default: current working directory")}),kS=g.object({filePath:g.string(),content:g.string(),fileType:g.string(),size:g.number()}),g.object({content:g.string(),filesRead:g.array(g.string()),errors:g.array(g.object({file:g.string(),error:g.string()})),fileDetails:g.array(kS)}),TS=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 Be(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 TS("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(..._S);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 TS)throw e;throw new TS(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}var IS=__esm({"src/tools/read-multiple-files/read-multiple-files.ts"(){Ft(),zw(),AS(),_S=["**/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 NS,RS,$S=__esm({"src/tools/read-multiple-files/formatter.ts"(){Ft(),Uw(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput")}}),MS=__esm({"src/tools/read-multiple-files/index.ts"(){Ft(),AS(),IS(),$S(),NS={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=CS.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")}}}),DS=__esm({"src/tools/grep/types.ts"(){Ft(),RS=g.object({pattern:g.string().min(1,"Pattern is required"),include:g.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},g.array(g.string()).optional()),directory:g.string().optional()})}});function execCommand({args:e,command:t}){return new Promise((n,r)=>{const s=R(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>es)return i="Output too large (max 25,000 tokens allowed). Try using grep with more specific patterns to filter results.",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>ts)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 LS=__esm({"src/tools/grep/grep.ts"(){Ft(),os(),__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 OS,qS,FS,jS=__esm({"src/tools/grep/formatter.ts"(){Ft(),__name(formatGrepResults,"formatGrepResults")}}),BS=__esm({"src/tools/grep/index.ts"(){Ft(),DS(),LS(),jS(),OS={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=RS.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while searching files"}},"execute")}}}),zS=__esm({"src/tools/glob/types.ts"(){Ft(),qS=g.object({pattern:g.string().min(1,"Pattern is required"),path:g.string().optional()}),FS=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 FS("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new FS("Search path must be within the current working directory or an added directory","INVALID_PATH");const s=await Be(n,{cwd:e,ignore:Mt,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 D.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 FS)throw e;if(e instanceof Error)throw new FS(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new FS("Unknown error occurred during file search","UNKNOWN_ERROR")}}var US=__esm({"src/tools/glob/glob.ts"(){Ft(),zS(),zt(),Qt(),__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 WS,GS,HS,QS=__esm({"src/tools/glob/formatter.ts"(){Ft(),__name(formatGlobResults,"formatGlobResults")}}),VS=__esm({"src/tools/glob/index.ts"(){Ft(),zS(),US(),QS(),WS={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=qS.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while finding files"}},"execute")}}}),KS=__esm({"src/tools/shell-command/types.ts"(){Ft(),GS=g.object({command:g.string().min(1,"Command cannot be empty"),args:g.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},g.array(g.string()).optional()),directory:g.string().optional(),timeout:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional())}),HS=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 HS("Command cannot be empty","EMPTY_COMMAND");let a;if(s){if(e.isAbsolute(s))throw new HS("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");a=e.resolve(process.cwd(),s)}else a=process.cwd();try{if(!(await D.stat(a)).isDirectory())throw new HS(`Path is not a directory: ${s}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof HS)throw e;throw new HS(`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;const d=r.length>0?ze([n,...r]):n,m=setTimeout(()=>{if(!u){p.kill("SIGTERM");const e=Date.now()-i;s(new HS(`Command timed out after ${o}ms`,"TIMEOUT",null,"SIGTERM",a,l,e))}},o),p=R(d,[],e);p.stdout?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>es)return l="Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",void p.kill("SIGTERM");a+=t}catch(e){l+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,p.kill("SIGTERM")}}),p.stderr?.on("data",e=>{try{const t=e.toString();if(l.length+t.length>ts)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"}]`}}),p.on("close",(e,n)=>{u=!0,clearTimeout(m);const r=Date.now()-i;0===e?t({stdout:a.trim(),stderr:l.trim(),exitCode:e,signal:n,duration:r}):s(new HS(`Command failed with exit code ${e}`,"COMMAND_FAILED",e,n,a.trim(),l.trim(),r))}),p.on("error",e=>{u=!0,clearTimeout(m);const t=Date.now()-i;s(new HS(`Failed to start command: ${e.message}`,"START_FAILED",null,null,a.trim(),l.trim(),t))})})}catch(e){if(e instanceof HS)throw e;throw new HS(`Unexpected error: ${e instanceof Error?e.message:String(e)}`,"UNEXPECTED_ERROR")}}var YS=__esm({"src/tools/shell-command/shell-command.ts"(){Ft(),KS(),os(),__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 JS,XS=__esm({"src/tools/shell-command/formatter.ts"(){Ft(),__name(formatShellCommandResult,"formatShellCommandResult")}}),ZS=__esm({"src/tools/shell-command/index.ts"(){Ft(),KS(),YS(),XS(),JS={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=GS.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof Error){const t=e;if(t.stdout||t.stderr){let n=`ERROR: ${e.message}`;return t.stdout&&(n+=`\nOutput:\n${t.stdout}`),t.stderr&&(n+=`\nError output:\n${t.stderr}`),n}return`ERROR: ${e.message}`}return"ERROR: Unknown error occurred while executing command"}},"execute")}}});async function think(e){const{thought:t}=e;return`${t}`}var eb,tb=__esm({"src/tools/thinking/thinking.ts"(){Ft(),__name(think,"think")}}),nb=__esm({"src/tools/thinking/index.ts"(){Ft(),tb(),eb={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 rb,sb=__esm({"src/tools/todo-write/todo-write.ts"(){Ft(),__name(todoWrite,"todoWrite")}}),ob=__esm({"src/tools/todo-write/index.ts"(){Ft(),sb(),rb={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 ib=__esm({"src/tools/ask-user-question/ask-user-question.ts"(){Ft(),__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 ab,lb,cb,ub=__esm({"src/tools/ask-user-question/formatter.ts"(){Ft(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput")}}),db=__esm({"src/tools/ask-user-question/index.ts"(){Ft(),ib(),ub(),ub(),ab={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")}}}),mb=__esm({"src/tools/killshell/types.ts"(){Ft(),lb=g.object({port:g.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:g.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"}),cb=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=R(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 cb(`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 cb("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 cb(`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 pb=__esm({"src/tools/killshell/killshell.ts"(){Ft(),mb(),__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(`${ve.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}var gb,hb,fb,yb,wb,Sb,bb,Eb,vb,Cb,kb,Tb,_b,xb,Pb,Ab,Ib,Nb,Rb,$b,Mb=__esm({"src/tools/killshell/formatter.ts"(){Ft(),__name(formatKillshellResult,"formatKillshellResult")}}),Db=__esm({"src/tools/killshell/index.ts"(){Ft(),mb(),pb(),Mb(),gb={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=lb.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")}}}),Lb=__esm({"src/tools/exit-plan-mode/index.ts"(){Ft(),hb={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")}}}),Ob=__esm({"src/tools/enter-plan-mode/index.ts"(){Ft(),fb={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")}}}),qb=__esm({"src/tools/web-search/index.ts"(){Ft(),yb={type:"web_search_20250305",name:"web_search",max_uses:5}}}),Fb=__esm({"src/tools/web-fetch/index.ts"(){Ft(),wb={type:"web_fetch_20250910",name:"web_fetch"}}}),jb=__esm({"src/tools/get-diagnostics/types.ts"(){Ft(),Sb=g.preprocess(e=>{if("string"==typeof e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{return[e]}return e},g.array(g.string()).optional()),bb=g.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.')})}}),Bb=__esm({"src/tui/vscode-context/ipc-client.ts"(){Ft(),Cn(),Eb=t.join(f.homedir(),".commandcode","ide"),vb=__name(e=>{const n=t.resolve(e);let r=n;try{r=S.realpathSync(n)}catch{}return"win32"===process.platform?r.toLowerCase():r},"normalizePathForComparison"),Cb=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),kb=__name(e=>{if("win32"===process.platform)return null;try{const t=N(`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"),Tb=__name((e,t,n=kb)=>{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"),_b=__name(()=>"vscode"!==process.env.TERM_PROGRAM?null:process.env.CURSOR_TRACE_ID?"cursor":process.env.WINDSURF_SESSION_ID?"windsurf":"code","detectIDE"),xb=__name((e,n)=>{try{S.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{S.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),Pb=__name((e,n={})=>{const{sessionDir:r=Eb,parentPidFn:s=kb,startPid:o=process.ppid}=n;try{if(!S.existsSync(r))return null;const n=`${e}-`,i=S.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(S.readFileSync(n,"utf-8"));if(!Cb(s.pid)){xb(n,r);continue}a.push({session:s,file:e})}catch{continue}if(0===a.length)return null;const l=Tb(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=vb(process.cwd());let d=null,m=0;for(const{session:e}of a)for(const n of e.workspaceFolders){const r=vb(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"),Ab=__name(()=>{const e=_b();return e?Pb(e):null},"resolveSocketPath"),Ib=__name(()=>({type:"request",id:W(),payload:{action:"getContext"}}),"createContextRequest"),Nb=__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"),Rb=__name((e,t)=>{try{const n=JSON.parse(e.toString());if(!Nb(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"),$b=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??Ab()}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=_e.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=Ib();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=Rb(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:W(),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(!_b())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 $b;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 zb=__esm({"src/tools/get-diagnostics/get-diagnostics.ts"(){Ft(),Bb(),Cn(),__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 Ub,Wb,Gb,Hb,Qb,Vb,Kb,Yb,Jb,Xb,Zb=__esm({"src/tools/get-diagnostics/formatter.ts"(){Ft(),__name(formatDiagnostics,"formatDiagnostics")}}),eE=__esm({"src/tools/get-diagnostics/index.ts"(){Ft(),jb(),zb(),Zb(),Ub={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=bb.parse(e);return formatDiagnostics(await fetchDiagnostics(t.filePaths))},"execute")}}}),tE=__esm({"src/utils/help-data.ts"(){Ft(),zt(),Wb="Coding agent that continuously learns your taste of writing code.",Gb=34,Hb=[{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"}],Qb=[{key:"cmd",description:"Start interactive session"},{key:'cmd "message"',description:"Start with initial message"},{key:"-r, --resume",description:"Resume a conversation"},{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"}],Vb=[{key:"/init",description:"Initialize AGENTS.md for this project"},{key:"/memory",description:"Manage Command Code memory"},{key:"/resume",description:"Resume a past conversation"},{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:"/help",description:"Display help information"},{key:"/exit",description:"Exit Command Code"}],Kb=[{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 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"}],Yb=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],Jb=[{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 -p "your query"',description:"Run non-interactive query"},{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"}],Xb='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(Hb)}\n\n## SLASH COMMANDS (type these in the chat input)\n${formatHelpItems(Vb)}\n\n## CLI SUBCOMMANDS\n${formatHelpItems(Kb)}\n\n## CLI EXAMPLES\n${formatHelpItems(Jb)}\n\n## CLI OPTIONS (flags when launching cmd)\n${formatHelpItems(Qb)}\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/)\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/), 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(Yb)}`}var nE,rE,sE,oE,iE=__esm({"src/tools/get-self-knowledge/get-self-knowledge.ts"(){Ft(),tE(),__name(formatHelpItems,"formatHelpItems"),__name(getSelfKnowledge,"getSelfKnowledge")}}),aE=__esm({"src/tools/get-self-knowledge/index.ts"(){Ft(),iE(),nE={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")}}}),lE=__esm({"src/mcp/constants.ts"(){Ft(),rE="2025-03-26",sE={name:"command-code",version:"1.0.0"},Promise.resolve().then(()=>($r(),_r)).then(({getPackageJson:e})=>{sE.version=e().version??"1.0.0"}).catch(()=>{})}});function getTokenFilePath(){return e.join(f.homedir(),".commandcode",oE)}async function loadTokenStorage(){try{const e=getTokenFilePath(),t=await M.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 M.mkdir(r,{recursive:!0}),await M.writeFile(n,JSON.stringify(t,null,2),{mode:384}),await M.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 cE,uE,dE,mE,pE,gE=__esm({"src/mcp/auth/token-storage.ts"(){Ft(),zt(),Cn(),oE="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")}}),hE=__esm({"src/mcp/types.ts"(){Ft(),cE=g.object({authorizationUrl:g.string(),tokenUrl:g.string(),clientId:g.string(),clientSecret:g.string().optional(),scopes:g.array(g.string()).optional()}),uE=g.object({transport:g.enum(["stdio","http"]),enabled:g.boolean().default(!0),command:g.string().optional(),args:g.array(g.string()).optional(),url:g.string().optional(),headers:g.record(g.string(),g.string()).optional(),oauth:cE.optional(),env:g.record(g.string(),g.string()).optional()}),dE=g.object({mcpServers:g.record(g.string(),uE)})}});function getUserMcpConfigPath(){return e.join(f.homedir(),".commandcode",mE)}function getLocalMcpConfigPath(t=process.cwd()){const n=Ue(t);return e.join(f.homedir(),".commandcode","projects",n,mE)}function getProjectMcpConfigPath(t=process.cwd()){return e.join(t,pE)}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 fE=__esm({"src/mcp/config/scopes.ts"(){Ft(),zt(),mE="mcp.json",pE=".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 M.readFile(n,"utf-8"),s=JSON.parse(r),o=dE.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 M.mkdir(o,{recursive:!0}),await M.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 yE,wE,SE=__esm({"src/mcp/config/mcp-config.ts"(){Ft(),Cn(),gE(),hE(),fE(),__name(loadMcpConfig,"loadMcpConfig"),__name(saveMcpConfig,"saveMcpConfig"),__name(loadMergedMcpConfig,"loadMergedMcpConfig"),__name(addMcpServer,"addMcpServer"),__name(removeMcpServer,"removeMcpServer"),__name(updateMcpServerStatus,"updateMcpServerStatus"),__name(getMcpServer,"getMcpServer"),__name(listMcpServers,"listMcpServers")}}),bE=__esm({"src/mcp/client/stdio-transport.ts"(){Ft(),yE=class _StdioTransport extends We{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=R(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(),wE);return fetch(e,{...t,signal:n.signal}).finally(()=>clearTimeout(r))}var EE,vE,CE=__esm({"src/mcp/fetch.ts"(){Ft(),wE=8e4,__name(fetchWithTimeout,"fetchWithTimeout")}}),kE={};function generateRandomString(e){return z.randomBytes(e).toString("base64url").slice(0,e)}function generatePKCE(){const e=generateRandomString(64);return{verifier:e,challenge:z.createHash("sha256").update(e).digest("base64url")}}function escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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=ke.createServer((n,r)=>{const i=new d(n.url||"/",`http://${vE}:${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,vE,()=>{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||EE,s=n?.timeout||12e4,o=n?.onStatus||(()=>{});let i=null;try{const n=generatePKCE(),a=generateRandomString(32),l=`http://${vE}:${r}/callback`;o("Starting authentication server...");const{server:u,getCode:m}=await startCallbackServer(r,a);i=u;const p=new d(t.authorizationUrl);if(p.searchParams.set("response_type","code"),p.searchParams.set("client_id",t.clientId),p.searchParams.set("redirect_uri",l),p.searchParams.set("state",a),p.searchParams.set("code_challenge",n.challenge),p.searchParams.set("code_challenge_method","S256"),t.scopes&&t.scopes.length>0&&p.searchParams.set("scope",t.scopes.join(" ")),t.extraParams)for(const[e,n]of Object.entries(t.extraParams))p.searchParams.set(e,n);o("Opening browser for authentication..."),await ue(p.toString()),o("Waiting for authorization...");const g=m();let h;const f=new Promise((e,t)=>{h=setTimeout(()=>t(new Error("Authentication timed out")),s)}),y=await Promise.race([g,f]);clearTimeout(h),o("Exchanging authorization code for tokens...");const w=await exchangeCodeForTokens(t,y,n.verifier,l);return await storeTokens(e,w),o("Authentication successful!"),{success:!0,tokens:w}}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(kE,{DEFAULT_OAUTH_CALLBACK_PORT:()=>EE,LOCALHOST_IP:()=>vE,createRefreshCallback:()=>createRefreshCallback,performOAuthFlow:()=>performOAuthFlow,refreshAccessToken:()=>refreshAccessToken});var TE,_E,xE,PE=__esm({"src/mcp/auth/oauth-flow.ts"(){Ft(),gE(),CE(),EE=8085,vE="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")}}),AE=__esm({"src/mcp/client/http-transport.ts"(){Ft(),lE(),gE(),CE(),TE=class _HttpTransport extends We{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":`${sE.name}/${sE.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(),kE));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(),wE);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(),wE);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 xE||(xE=new _E),xE}var IE=__esm({"src/mcp/client/connection-manager.ts"(){Ft(),lE(),SE(),bE(),AE(),$E(),_E=class extends We{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 yE?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?yE.fromConfig(e):TE.fromConfig({config:e,serverName:t})}async initializeProtocol(e){const t=await e.transport.request("initialize",{protocolVersion:rE,capabilities:{roots:{}},clientInfo:sE});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}},xE=null,__name(getMcpConnectionManager,"getMcpConnectionManager")}});function mcpToolToSchema({serverName:e,tool:t}){return{name:`mcp__${e}__${t.name}`,description:t.description||`MCP tool: ${t.name} (from ${e})`,input_schema:{type:"object",properties:t.inputSchema.properties??{},required:t.inputSchema.required}}}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 NE,RE,$E=__esm({"src/mcp/client/tool-adapter.ts"(){Ft(),IE(),__name(mcpToolToSchema,"mcpToolToSchema"),__name(getAllMcpToolSchemas,"getAllMcpToolSchemas"),__name(isMcpTool,"isMcpTool"),__name(parseMcpToolName,"parseMcpToolName"),__name(executeMcpTool,"executeMcpTool")}}),ME=__esm({"src/tools/agents/defaults.ts"(){Ft(),NE=["explore","plan","review","general"],RE=[{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&&NE.includes(e.toLowerCase())}var DE=__esm({"src/tools/agents/utils.ts"(){Ft(),ME(),__name(isReservedAgentName,"isReservedAgentName")}});function getRootAgentDir(){return t.join(f.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await D.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const s=t.join(e,r),o=await D.readFile(s,"utf-8"),{data:i,content:a}=Fe(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 LE=__esm({"src/tools/agents/loader.ts"(){Ft(),zt(),DE(),__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents")}});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 OE,qE,FE,jE,BE,zE,UE,WE,GE,HE,QE,VE,KE,YE,JE,XE,ZE,ev,tv,nv,rv,sv,ov,iv,av,lv,cv,uv,dv,mv,pv,gv,hv,fv,yv=__esm({"src/tools/utils/path-display.ts"(){Ft(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText")}}),wv={};__export(wv,{FeedEntrySchema:()=>KE,LLM_STATUS_MESSAGES:()=>dv,createAgentToolEntry:()=>iv,createAssistantEntry:()=>XE,createBashEntry:()=>ev,createCommandResultEntry:()=>sv,createErrorEntry:()=>nv,createIDEStatusEntry:()=>ov,createInfoEntry:()=>JE,createSystemEntry:()=>tv,createTasteOnboardingEntry:()=>rv,createToolEntry:()=>ZE,createUserEntry:()=>YE,formatError:()=>lv,getRandomLLMStatus:()=>mv,getToolDisplayName:()=>pv,getToolInputContent:()=>hv,isErrorEntry:()=>cv,isPendingEntry:()=>uv,parseTodosFromOutput:()=>fv,updateEntryWithOutput:()=>av});var Sv=__esm({"src/types/feed.ts"(){Ft(),Ew(),$E(),yv(),os(),OE=g.object({id:g.string(),timestamp:g.number(),type:g.literal("image"),source:g.object({type:g.enum(["base64","url"]),media_type:g.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:g.string()})}),qE=g.object({id:g.string(),timestamp:g.number(),input:g.string(),output:g.string().optional(),metadata:g.record(g.string(),g.any()).optional(),images:g.array(OE).optional().default([])}),FE=qE.extend({role:g.literal("user")}),jE=qE.extend({role:g.literal("assistant")}),BE=qE.extend({role:g.literal("tool"),name:g.string(),description:g.string().optional()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),zE=qE.extend({role:g.literal("bash"),command:g.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),UE=qE.extend({role:g.literal("system")}),WE=qE.extend({role:g.literal("error")}),GE=qE.extend({role:g.literal("info")}),HE=qE.extend({role:g.literal("taste-onboarding")}),QE=qE.extend({role:g.literal("command-result"),hasError:g.boolean().optional(),details:g.string().optional()}),VE=qE.extend({role:g.literal("ide-status"),status:g.enum(["connected","installed","needs_reload","not_in_ide","failed"]),ide:g.string().nullable(),details:g.array(g.string()).optional()}),KE=g.discriminatedUnion("role",[FE,jE,BE,zE,UE,WE,GE,HE,QE,VE]),YE=__name((e,t)=>KE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),JE=__name((e,t)=>KE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e,metadata:t}),"createInfoEntry"),XE=__name(e=>KE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),ZE=__name((e,t,n)=>KE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),ev=__name(e=>KE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),tv=__name((e,t)=>KE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e,metadata:t}),"createSystemEntry"),nv=__name(e=>KE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),rv=__name(()=>KE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),sv=__name((e,t=!1,n)=>KE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),ov=__name((e,t,n)=>KE.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"ide-status",input:"",status:e,ide:t,details:n}),"createIDEStatusEntry"),iv=__name(({name:e,input:t})=>{const n=Date.now();return KE.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"),av=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return KE.parse(n)},"updateEntryWithOutput"),lv=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),cv=__name(e=>/^error:/i.test(e.output??""),"isErrorEntry"),uv=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),dv=["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…"],mv=__name(()=>dv[Math.floor(Math.random()*dv.length)],"getRandomLLMStatus"),pv=__name(e=>{switch(e){case Jy.READ_FILE:return"READ";case Jy.EDIT_FILE:return"EDIT";case Jy.WRITE_FILE:return"WRITE";case Jy.READ_DIRECTORY:return"LIST";case Jy.READ_MULTIPLE_FILES:return"READ[n]";case Jy.GREP:return"SEARCH";case Jy.SHELL_COMMAND:return"SHELL";case Jy.TODO_WRITE:return"TODOS";case Jy.THINKING:return"thinking…";case Xy.WEB_SEARCH:return"WEB SEARCH";case Xy.WEB_FETCH:return"WEB FETCH";case Jy.QUESTION:return"QUESTION";case Jy.EXPLORE:return"EXPLORE";case Jy.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"),gv=__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:Jr})}${t.length>1?` (+${t.length-1} more)`:""}`},"formatMcpToolParams"),hv=__name((e,t)=>{try{switch(e){case Jy.READ_FILE:case Jy.WRITE_FILE:const n=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(n);case Jy.EDIT_FILE:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Jy.READ_DIRECTORY:return toRelativePath(t.path||"directory");case Jy.GREP:const r=t.path||"files";return`"${t.pattern}" in ${toRelativePath(r)}`;case Jy.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 Jy.TODO_WRITE:let s;try{s="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=fv(s);return`${e?e.length:0} items`}catch{return"items"}case Jy.THINKING:return t.content||"planning";case Jy.READ_MULTIPLE_FILES:const o=t.include||[];if(!Array.isArray(o)||0===o.length)return"multiple files";const i=o.slice(0,Zr).map(toRelativePath).join(", "),a=o.length-Zr;return a>0?`${i} (+${a} more)`:i;case Xy.WEB_SEARCH:return t.query||"search";case Xy.WEB_FETCH:return t.url||"fetch";case Jy.QUESTION:return"User answered questions";case Jy.KILL_SHELL:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";case Jy.ENTER_PLAN_MODE:case Jy.EXIT_PLAN_MODE:return"";default:{if(isMcpTool(e)&&t&&"object"==typeof t)return gv(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:Xr})}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),fv=__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 bv,Ev,vv,Cv,kv,Tv,_v,xv,Pv=__esm({"src/utils/file-references.ts"(){Ft(),zw(),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent")}}),Av=__esm({"src/utils/strip-ide-context.ts"(){Ft(),bv=__name(e=>e.replace(/<ide-context>[\s\S]*?<\/ide-context>\s*/g,""),"stripIdeContext")}}),Iv=__esm({"src/sessions/index.ts"(){Ft(),Sv(),Pv(),zt(),gs(),Cn(),Av(),Ev=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(f.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Ue(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=N("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await D.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:ls.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await D.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,...t?.metadata||{}}};r.push(JSON.stringify(s)),this.lastMessageId=e}await D.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 D.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()),t=[];let n=0;for(const r of e)try{const e=JSON.parse(r);"user"!==e.role&&"assistant"!==e.role||t.push({message:{role:e.role,content:e.content},meta:{timestamp:e.timestamp,source:"cli",...e.metadata||{}}})}catch(e){n++,console.error("Error parsing session line:",e)}return{messages:t,corruptedLines:n,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("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)if("text"===t.type)n+=t.text;else if("tool_result"===t.type)continue;n=bv(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_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=hv(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}else if("server_tool_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=hv(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,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 D.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 D.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await D.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 D.access(n)}catch{return[]}const e=(await D.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 D.stat(o),s=(await D.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=bv(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 D.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 D.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 D.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await D.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};await D.writeFile(this.getMetaFilePath(),JSON.stringify(t,null,2))}catch(e){dlog("Session",`Failed to save session meta: ${e}`)}}async saveSessionTitle(e){await this.saveSessionMeta({title:e})}async loadSessionTitle(){const e=await this.loadSessionMeta();return e?.title||null}static async loadSessionMetaForId(e,n){const r=t.join(n,`${e}.meta.json`);try{const e=await D.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 D.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 D.writeFile(r,o)}else await D.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 D.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 D.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 D.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=bv(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 getRequest(){return xv||(xv=new Yy({baseUrl:getApiBaseUrl()})),xv}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)}`}function buildRequestBody(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:Pt,max_tokens:Tv,temperature:_v,stream:!0},threadId:crypto.randomUUID()}}async function getAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced(),{token:n,oauthProvider:r}=await getOAuthCredentials({provider:e});validateOAuthToken({token:n,provider:e});const s={[vt.PROJECT_SLUG]:Ev.getCurrentProjectDirName(),[vt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};return n&&(s[vt.OAUTH_TOKEN]=`Bearer ${n}`,r&&(s[vt.OAUTH_PROVIDER]=r)),s}async function generateToolDescription(e,t){const n=generateCacheKey(e,t),r=Cv.get(n);if(r)return Cv.delete(n),Cv.set(n,r),dlog(`[ToolDescription] cache hit for ${e}: "${r}"`),r;dlog(`[ToolDescription] generating for ${e}`);try{const e=getRequest(),r=await getAuthHeaders(),s=buildRequestBody(createPrompt(t));dlog(`[ToolDescription] calling ${Ct.ALPHA.GENERATE} with model: ${Pt}`);const o=e.post({endpoint:Ct.ALPHA.GENERATE,body:s,headers:r,stream:!0}),i=await Promise.race([o,new Promise((e,t)=>setTimeout(()=>t(new Error("Timeout")),5e3))]);if(!i)return dlog("[ToolDescription] no response stream"),null;dlog("[ToolDescription] got response stream");const a=Ge.fromReadableStream(i);let l="",u=null;if(a.on("text",e=>{l+=e}),a.on("error",e=>{u=e}),await a.finalMessage(),u)throw u;dlog(`[ToolDescription] raw response: "${l}"`);const d=cleanDescription(l);if(d){if(Cv.size>=vv){const e=Cv.keys().next().value;void 0!==e&&Cv.delete(e)}Cv.set(n,d),dlog(`[ToolDescription] cached: "${d}"`)}else dlog("[ToolDescription] description rejected after cleaning");return d}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,kv)}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 Nv=__esm({"src/utils/tool-description-generator.ts"(){Ft(),zt(),bw(),Cs(),Iv(),an(),Sr(),Cr(),Cn(),vv=100,Cv=new Map,kv=4e3,Tv=80,_v=.3,xv=null,__name(getRequest,"getRequest"),__name(stableStringify,"stableStringify"),__name(generateCacheKey,"generateCacheKey"),__name(buildRequestBody,"buildRequestBody"),__name(getAuthHeaders,"getAuthHeaders"),__name(generateToolDescription,"generateToolDescription"),__name(sanitize,"sanitize"),__name(createPrompt,"createPrompt"),__name(cleanDescription,"cleanDescription")}});function isPlanPath(e){const{filePath:n}=e;if(!n||"string"!=typeof n)return!1;const r=f.homedir(),s=n.startsWith("~/")?t.join(r,n.slice(2)):n,o=t.resolve(s),i=t.join(r,".commandcode","plans");return o.startsWith(i+t.sep)||o===i}var Rv,$v,Mv,Dv=__esm({"src/utils/plan-path-validator.ts"(){Ft(),zt(),__name(isPlanPath,"isPlanPath")}});function getToolsForMode(e){const{allTools:t,mode:n}=e;return"standard"===n||"auto-accept"===n?t.filter(e=>!$v.includes(e.name)):"plan"===n?t.filter(e=>!Rv.includes(e.name)&&!Mv.includes(e.name)):t.filter(e=>!$v.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 Rv.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 Lv,Ov,qv,Fv,jv=__esm({"src/tools/get-tools-for-mode.ts"(){Ft(),Dv(),$E(),Rv=["edit_file","delete_file","shell_command","todo_write","kill_shell"],$v=["exit_plan_mode"],Mv=["enter_plan_mode"],__name(getToolsForMode,"getToolsForMode"),__name(isToolAllowedInMode,"isToolAllowedInMode")}});function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(t*Fv));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&&"source"in n&&"base64"===n.source.type)t+=estimateImageTokens(n.source.data);else if("tool_use"===n.type)t+=5,"name"in n&&n.name&&(t+=estimateTextTokens(n.name)),"input"in n&&n.input&&(t+=estimateTextTokens(JSON.stringify(n.input))*Fv);else if("tool_result"===n.type&&(t+=3,"content"in n&&n.content))if("string"==typeof n.content)t+=estimateTextTokens(n.content);else if(Array.isArray(n.content))for(const e of n.content)"text"===e.type&&"text"in e&&(t+=estimateTextTokens(e.text));return Math.ceil(t)}function estimateTextTokens(e){if(!e)return 0;let t=e.length/qv;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)>Lv}function getOversizedOutputError(e,t){return"Error: Output too large (max 25,000 tokens). Use grep/ripgrep with more specific patterns to filter results."}function checkToolOutputTokensLimit(e,t){return exceedsOutputTokenLimit(e)?(estimateTokens(e),"Error: Output too large (max 25,000 tokens). Use grep/ripgrep with more specific patterns to filter results."):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 Bv=__esm({"src/utils/tokens.ts"(){Ft(),os(),Lv=ns,Ov=2e5,qv=3.5,Fv=1.1,__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),__name(getOversizedOutputError,"getOversizedOutputError"),__name(checkToolOutputTokensLimit,"checkToolOutputTokensLimit"),__name(calculateUsageFromResponse,"calculateUsageFromResponse")}});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 zv,Uv,Wv,Gv,Hv=__esm({"src/utils/sleep.ts"(){Ft(),__name(sleep,"sleep")}}),Qv=__esm({"src/utils/logger.ts"(){Ft(),Cn(),zv=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${ve.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${ve.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${ve.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${ve.warning} ${e}`)}debug(e,t){dlog(`[${this.prefix}] ${e}`,t)}}}});function setBenchmarkOutput(e){Uv=e}function createBenchmarkCollector(){return Uv?{startTime:Date.now(),turnDetails:[],agents:[],maxTurnsReached:!1}:null}function buildAgentMetricsMarker(e){return`\n${Wv}${JSON.stringify(e)}${Gv}`}function extractAgentMetrics(e){const t=e.indexOf(Wv);if(-1===t)return{cleanContent:e,metrics:null};const n=t+Wv.length,r=e.indexOf(Gv,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+Gv.length),metrics:o}}catch{return{cleanContent:e,metrics:null}}}function createAgentBenchmarkTracker(){return Uv?{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(!Uv)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{w.writeFileSync(Uv,JSON.stringify(l,null,2))}catch{}}var Vv,Kv=__esm({"src/utils/benchmark-collector.ts"(){Ft(),__name(setBenchmarkOutput,"setBenchmarkOutput"),__name(createBenchmarkCollector,"createBenchmarkCollector"),Wv="\x3c!-- BENCHMARK_AGENT_METRICS:",Gv=" --\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"}}},required:["messages"]},execute:__name(async(n,a)=>{let l=null;const u=Date.now();let d=null;try{const m=a?.permissionMode||"standard",p=filterToolsForMode({tools:getAvailableTools(t,{clientTools:r,serverTools:s,toolsMap:o,displayNameToToolName:i}),clientTools:r,serverTools:s,mode:m});let g=Date.now();const h=10,f=[];if(a?.onFeedUpdate){const e=hv(t.name,n);l=iv({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 y=createAgentBenchmarkTracker(),w=await getConfiguredProvider(),S=await isOAuthEnforced(),{token:E,oauthProvider:v}=await getOAuthCredentials({provider:w});validateOAuthToken({token:E,provider:w});const C=getApiBaseUrl(),k=new Yy({baseUrl:C});let T=0;const _=[];let x=n?.messages;if("string"==typeof x)try{x=JSON.parse(x)}catch(e){x=[]}if(Array.isArray(x)&&x.length>0)for(const e of x)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&_.push({role:"user",content:t})}const P={stream:!0,messages:_,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:p,model:`anthropic:${getConfiguredModel()}`},A=await isTasteLearningEnabled(),I={[vt.PROJECT_SLUG]:Ev.getCurrentProjectDirName(),[vt.TASTE_LEARNING]:A.toString(),[vt.INTERNAL_TEAM_FLAG_HEADER]:S.toString()};E&&(I[vt.OAUTH_TOKEN]=`Bearer ${E}`,v&&(I[vt.OAUTH_PROVIDER]=v));const N=getEnvironmentContext(),R=await getMemoryContent([]),$=crypto.randomUUID();let M="",D=!0;const L=__name(()=>{Vv.debug("[Agent] Abort signal triggered, stopping immediately"),D=!1,d&&(clearInterval(d),d=null)},"abortHandler");a?.abortSignal&&a.abortSignal.addEventListener("abort",L);try{for(;D;){if(a?.abortSignal?.aborted)throw Vv.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:k,body:{mode:"custom-agent",config:N,memory:R,threadId:$,params:{...P,messages:_}},headers:I,abortSignal:a?.abortSignal,onTextDelta:__name(e=>{T+=estimateTokens(e);const t=Date.now();if(a?.onFeedUpdate&&l&&t-g>=h){const e=Math.floor((t-u)/1e3);l={...l,metadata:{...l.metadata,tokensUsed:T,elapsedSeconds:e}},a.onFeedUpdate(l),g=t}},"onTextDelta")});if(trackAgentTurn(y),a?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(T=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool_use"===e.type);if(M=t.content.filter(e=>"server_tool_use"===e.type).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);e.length>0&&_.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&&_.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=nw.includes(t.name),p=rw.includes(t.name)?generateToolDescription(t.name,n).catch(()=>null):Promise.resolve(null);if(r&&a?.onPermissionRequest){d&&(clearInterval(d),d=null);const e=await p;if(!await a.onPermissionRequest(t.name,n,e)){Vv.debug(`Permission denied for tool: ${t.name}`),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,Vv.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,Vv.debug(`Resolved input for ${t.name}: ${hv(t.name,n)}`)):Vv.debug(`No path resolution needed for ${t.name}: ${hv(t.name,n)}`)}if(a?.onFeedUpdate&&l){const e=hv(t.name,n);f.push({name:t.name,input:e}),f.length>3&&f.shift();const r=Date.now(),s=Math.floor((r-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:T,elapsedSeconds:s,recentTools:[...f]}},Vv.debug(`Updating agent with recentTools (${f.length} tools): ${JSON.stringify(f)}`),a.onFeedUpdate(l)}const g=await executeTool(t.name,n,{abortSignal:a?.abortSignal,permissionMode:m});if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");const h=checkToolOutputTokensLimit(g,t.name);if(s.push({type:"tool_result",tool_use_id:t.id,content:h}),o.add(t.id),trackAgentToolCall({tracker:y,toolName:t.name,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:T,elapsedSeconds:t,recentTools:[...f]}},a.onFeedUpdate(l)}Vv.debug(`Tool executed successfully: ${t.name}`)}catch(e){const n=e instanceof Error?e.message:"Unknown error";s.push({type:"tool_result",tool_use_id:t.id,content:`Error: ${n}`,is_error:!0}),o.add(t.id),trackAgentToolCall({tracker:y,toolName:t.name,isError:!0}),Vv.error(`Tool execution failed: ${t.name} - ${n}`)}}if(i){const e=_[_.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?o.has(e.id):"text"===e.type);t.length>0?e.content=t:_.pop()}D=!1;break}const p=[...s];_.push({role:"user",content:p})}}finally{a?.abortSignal&&a.abortSignal.removeEventListener("abort",L)}if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const e=Date.now(),t=(e-u)/1e3;l={...l,output:M||"DONE",metadata:{isAgent:!0,status:"done",startTime:u,endTime:e,tokensUsed:T,elapsedSeconds:t}},a.onFeedUpdate(l)}return buildAgentResult({result:M||"DONE",tracker:y,agentName:t.name,startTime:u,tokens:T})}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:Ct.ALPHA.GENERATE,signal:s,headers:r}),i=Ge.fromReadableStream(e);o&&i.on("text",o);let a=null;i.on("error",e=>{a="AbortError"===e.name||s?.aborted?new Error("Interrupted by user"):e});const l=await i.finalMessage();if(a)throw a;return l}catch(t){if(i=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);Vv.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 to&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof ro||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"].some(t=>e.message.includes(t))}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 to&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof ro||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=>"server_tool_use"===e.type).length)return"";let n="";const r=e.content;for(const e of r)if("text"===e.type)n+=e.text;else if("server_tool_use"===e.type&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const{message:n,isError:s}=tw({serverToolBlock:e,contentBlocks:r}),o=hv(e.name,e.input),i={id:`${e.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:o,output:s?lv(n):n};t.onFeedUpdate(i)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}var Yv,Jv,Xv=__esm({"src/tools/agents/execute.ts"(){Ft(),zt(),Cr(),bw(),Cs(),an(),ho(),lC(),Nv(),Ew(),jv(),Bv(),Hv(),Qv(),Sv(),Aw(),Iv(),Sr(),Ew(),Kv(),Vv=new zv("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){Jv=e}async function loadAgentTools(){if(!Jv)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");Yv.clear();for(const e of RE){const t=agentToTool(e,Jv);Yv.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,Jv);Yv.set(t.name,t)}}async function getAgentTools(){return 0===Yv.size&&await loadAgentTools(),Array.from(Yv.values())}async function getAgentTool(e){return 0===Yv.size&&await loadAgentTools(),Yv.get(e)}var Zv=__esm({"src/tools/agents/manager.ts"(){Ft(),LE(),Xv(),ME(),Yv=new Map,Jv=null,__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool")}}),eC=__esm({"src/tools/agents/index.ts"(){Ft(),Zv()}});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(h.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 tC,nC,rC,sC,oC,iC,aC=__esm({"src/utils/taste-path-validator.ts"(){Ft(),zt(),__name(isPathInTasteDirectory,"isPathInTasteDirectory"),__name(getTasteFileInfo,"getTasteFileInfo"),__name(getTasteAccessError,"getTasteAccessError")}});function isAgentTool(e){return!sC.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=rC.get(e);if(o||(o=await getAgentTool(e)),!o){const t=await getAgentTools(),n=[...Array.from(rC.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=(!rC.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!==_b()?[...tC]:tC.filter(e=>e.name!==Jy.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,...nC]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}var lC=__esm({"src/tools/index.ts"(){Ft(),Yw(),pS(),SS(),PS(),MS(),BS(),VS(),ZS(),nb(),ob(),db(),Db(),Lb(),Ob(),qb(),Fb(),eE(),aE(),Bb(),Ew(),$E(),IE(),eC(),aC(),gs(),jv(),tC=[Ww,cS,fS,vS,NS,OS,WS,JS,eb,rb,ab,gb,hb,fb,Ub,nE],nC=[yb,wb],rC=new Map(tC.map(e=>[e.name,e])),sC=new Set([...tC.map(e=>e.name),...nC.map(e=>e.name)]),__name(isAgentTool,"isAgentTool"),__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase"),oC={},tC.forEach(e=>{oC[e.name]=toPascalCase(e.name)}),nC.forEach(e=>{oC[e.name]=toPascalCase(e.name)}),iC={},Object.entries(oC).forEach(([e,t])=>{iC[t]=e}),initializeAgentManager({clientTools:tC,serverTools:nC,toolsMap:rC,displayNameToToolName:iC})}});async function resolveEditStartLine({filePath:e,oldContent:t}){const n=await P.readFile(e,"utf-8"),r=n.indexOf(t);if(-1!==r)return n.substring(0,r).split("\n").length}function isDirectoryEmpty(){try{return 0===T(process.cwd()).length}catch{return!1}}var cC=__esm({"src/utils/fs.ts"(){Ft(),__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}function parseErrorLine(e){try{const t=JSON.parse(e);if("error"===t?.type&&t?.error?.type&&t?.error?.message)return{type:t.error.type,message:t.error.message}}catch{}return null}function interceptStreamErrors(e){const{responseStream:t}=e;let n=null,r="";const s=new TextDecoder,o=new TransformStream({transform(e,t){const o=s.decode(e,{stream:!0});r+=o;const i=r.split("\n");r=i.pop()??"";for(const e of i){const r=e.trim();if(!r){t.enqueue((new TextEncoder).encode(e+"\n"));continue}const s=parseErrorLine(r);if(s)return n=s,void t.error(new Error(`Error: Stream error: ${s.type} - ${s.message}`));t.enqueue((new TextEncoder).encode(e+"\n"))}},flush(e){const t=r.trim();if(t){const s=parseErrorLine(t);if(s)return n=s,void e.error(new Error(`Error: Stream error: ${s.type} - ${s.message}`));e.enqueue((new TextEncoder).encode(r))}}});return{stream:t.pipeThrough(o),getStreamError:__name(()=>n,"getStreamError")}}var uC,dC,mC=__esm({"src/utils/stream-error-interceptor.ts"(){Ft(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),__name(parseErrorLine,"parseErrorLine"),__name(interceptStreamErrors,"interceptStreamErrors")}}),pC=__esm({"src/utils/learning-events.ts"(){Ft(),uC=class extends We{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;_observerHasRun=!1;_importHasStarted=!1;_learningComplete=!1;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)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this.emit("reset")}},dC=new uC}});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 gC,hC,fC,yC,wC,SC,bC=__esm({"src/utils/learning-parser.ts"(){Ft(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings")}}),EC=__esm({"src/agent/learning-agent.ts"(){Ft(),zt(),Iv(),lC(),Hv(),Cn(),pC(),bC(),Qv(),Sr(),Cr(),gs(),gC=new zv("LearningAgent"),hC=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:ls.LEARNING_AGENT,heading:"Learning pass failed"}}),dC.addEvent({type:"error",message:"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)];dC.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.name).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:"user",content:n}),u++}u>=this.maxTurns&&gC.debug("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||dC.addEvent({type:"no_learnings",message:"no changes to taste"}),dC.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool_use"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let s="",o="";if("write_file"===e.name||"edit_file"===e.name){const e=t;if(o=String(e.filePath||e.file_path||""),o)try{s=await w.promises.readFile(o,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const i=await executeTool(e.name,t,{allowTasteWrite:!0});let a="";if(("write_file"===e.name||"edit_file"===e.name)&&o)try{a=await w.promises.readFile(o,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){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=>{dC.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{dC.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{dC.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool_result",tool_use_id:e.id,content:i})}catch(t){n.push({type:"tool_result",tool_use_id:e.id,is_error:!0,content: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(!w.existsSync(this.tasteDir)){w.mkdirSync(this.tasteDir,{recursive:!0});const t=e.join(this.tasteDir,"taste.md");w.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!w.existsSync(t))return!1;const n=w.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");w.mkdirSync(r,{recursive:!0}),dC.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const i=`# ${t.name}\n${t.learnings.join("\n")}\n`;w.writeFileSync(o,i,"utf-8");const a=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;s=s.replace(t.fullSection,a)}return w.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 w.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=w.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=(w.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={[vt.PROJECT_SLUG]:Ev.getCurrentProjectDirName(),[vt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};s&&(i[vt.OAUTH_TOKEN]=`Bearer ${s}`,o&&(i[vt.OAUTH_PROVIDER]=o));const a=await this.getTasteTools(),l=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (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:Ct.ALPHA.TASTE.LEARN,body:u,headers:i,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}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;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:ls.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:ls.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 w.existsSync(r)}}}}),vC=__esm({"src/agent/compact-agent.ts"(){Ft(),zt(),Iv(),an(),Sr(),Cr(),Cn(),fC="claude-haiku-4-5-20251001",yC=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={[vt.PROJECT_SLUG]:Ev.getCurrentProjectDirName(),[vt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};s&&(i[vt.OAUTH_TOKEN]=`Bearer ${s}`,o&&(i[vt.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:`anthropic:${fC}`,max_tokens:16e3,stream:!0},threadId:this.sessionId};let u=0,d=null;for(;u<=this.maxApiRetries;)try{dlog(`[CompactAgent] calling ${Ct.ALPHA.GENERATE} with model: ${fC}`);const e=await this.request.post({endpoint:Ct.ALPHA.GENERATE,body:l,headers:i,stream:!0});if(!e)throw new Error("No response stream received");const t=Ge.fromReadableStream(e);let n="",r=null;t.on("text",e=>{n+=e}),t.on("error",e=>{r=e});const s=await t.finalMessage();if(r)throw r;return dlog("[CompactAgent] API response received"),{summary:n,tokensUsed:{input:s.usage.input_tokens,output:s.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;const n=1e3*Math.pow(2,u);dlog(`[CompactAgent] retrying API call (${u}/${this.maxApiRetries})`),await new Promise(e=>setTimeout(e,n))}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={[vt.PROJECT_SLUG]:Ev.getCurrentProjectDirName(),[vt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()},{token:r,oauthProvider:s}=await getOAuthCredentials({provider:e});return r&&(n[vt.OAUTH_TOKEN]=`Bearer ${r}`,s&&(n[vt.OAUTH_PROVIDER]=s)),dlog("[TitleGen] buildAuthHeaders",{provider:e,oauthEnforced:t,hasOAuthToken:!!n[vt.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,request:r}=e;if(!hasUserAndAssistantMessage(t))return;if(await n.loadSessionTitle())return;let s="",o="";for(const e of t)if(s||"user"!==e.message.role||(s=extractMessageText(e.message.content).slice(0,SC)),o||"assistant"!==e.message.role||(o=extractMessageText(e.message.content).slice(0,SC)),s&&o)break;if(!s||!o)return;const i=`${wC}\n\nSession description:\n<description>User: ${s}\n\n---\n\nAssistant: ${o}</description>\n\nGenerate the session title now.`,a={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:i}],model:Pt,max_tokens:50,temperature:.3,stream:!0},threadId:n.getSessionId()},l=await buildAuthHeaders(),u=await r.post({endpoint:Ct.ALPHA.GENERATE,body:a,headers:l,stream:!0}),d=Ge.fromReadableStream(u);let m="";d.on("text",e=>{m+=e}),await d.finalMessage(),m=m.trim(),m&&(await n.saveSessionTitle(m),dlog("Session",`Title generated: ${m}`))}var CC,kC,TC,_C=__esm({"src/chat/title-generator.ts"(){Ft(),Iv(),an(),Sr(),Cr(),Cn(),zt(),wC="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",SC=1e3,__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle")}}),xC={};__export(xC,{ContextEngine:()=>TC});var PC,AC=__esm({"src/chat/context-engine.ts"(){Ft(),cC(),Ow(),ho(),Pv(),Sv(),Ew(),lC(),Hv(),mC(),Qv(),aC(),Bv(),Iv(),gs(),aS(),Cs(),bw(),Jh(),zt(),an(),Sr(),Cr(),Aw(),EC(),vC(),Nw(),Cn(),_C(),os(),Nv(),CC=new zv("ContextEngine"),kC=200,TC=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;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 Yy({baseUrl:n}),this.callbacks=e,this.sessionManager=new Ev(t),this.learningAgent=new hC({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new yC({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new Yy({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,CC.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_use"===e.type),r=[];if(n.length>0){const e=n.map(e=>({type:"tool_result",tool_use_id:e.id,content:"Interrupted by user",is_error:!0}));r.push(...e),CC.debug(`Added tool_result blocks for ${e.length} interrupted tool calls`)}e&&r.push({type:"text",text:"Interrupted by user"}),r.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:r},{isAutomated:!0}))}if(e){const e=YE("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>CC.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=YE(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",source:{type:"base64",media_type:e.mediaType,data: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 p=this.createMessageWithMeta(u,m);this.addMessageAndSync(p),this.checkpointManager.createSnapshot({messageId:d}).catch(e=>CC.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,a).catch(e=>CC.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const g=await this.processMessages();return this.triggerTitleGeneration(),g}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){CC.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}triggerTitleGeneration(){this.titleGenerationInFlight||(this.titleGenerationInFlight=!0,generateSessionTitle({messages:this.messages,sessionManager:this.sessionManager,request:this.request}).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{body:t,headers:r}=await this.prepareAPICall(),s=await this.callAPIWithRetry({body:t,headers:r});this.checkIfInterrupted(),this.updateContextUsage(s),await this.checkAndCompactIfNeeded();const o=s.content.filter(e=>"tool_use"===e.type),i=s.content.filter(e=>"server_tool_use"===e.type);if(e=i.length>0?this.processServerToolBlocks(s):s.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===o.length){const t=s.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===i.length){const t=XE(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>CC.error(`Failed to save messages: ${e}`))}if(0!==i.length&&this.sessionManager.saveMessages(this.messages).catch(e=>CC.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=YE(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=>CC.error(`Failed to save messages: ${e}`)),t&&this.triggerLearningAgent();continue}}break}const a=s.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(a.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:a})),e.trim()){const t=XE(e);this.callbacks.onFeedUpdate(t)}const l=await this.executeToolBlocks({toolBlocks:o}),{toolResults:u,executedToolIds:d,permissionDenied:m}=l;if(m){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_use"===e.type?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}let p=!1,g=!1;if(u.length>0&&(this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:[...u]},{isAutomated:!0})),p=!0),this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){const e=YE(t.displayMessage??t.input);this.callbacks.onFeedUpdate(e);const n=this.getAutomatedMessageMeta(t);this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t.input},n)),p=!0,g=!0}}p&&this.sessionManager.saveMessages(this.messages).catch(e=>CC.error(`Failed to save messages: ${e}`)),g&&this.triggerLearningAgent()}catch(e){throw this.isNonRetryableError(e)&&CC.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){CC.error(`Failed to load checkpoints for session ${e}: ${t}`)}const s=this.sessionManager.reconstructFeedFromMessages(t);return CC.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("user"===n.role&&Array.isArray(n.content)){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_use"===t.type&&r.add(t.id);const s=n.content.filter(e=>"tool_result"!==e.type||r.has(e.tool_use_id));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};CC.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_use"===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:Ov}),{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=>"object"==typeof e&&null!==e&&"type"in e&&"tool_result"===e.type)}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=Bh.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:Ct.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 prepareAPICall(){const e=this.callbacks.getPermissionMode?.()||"standard",t=await getToolSchemas({mode:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();n&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(n);const{token:s,oauthProvider:o}=await getOAuthCredentials({provider:n});validateOAuthToken({token:s,provider:n}),dlog("[ContextEngine] prepareAPICall",{provider:n,oauthProvider:o,hasToken:!!s});const i={tools:t,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},a={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:i,threadId:this.sessionManager.getSessionId(),permissionMode:e};CC.debug(`calling API (${i.model}, ${this.messages.length} msgs, ${t.length} tools)`);const l=await isTasteLearningEnabled(),u={[vt.PROJECT_SLUG]:Ev.getCurrentProjectDirName(),[vt.TASTE_LEARNING]:l.toString(),[vt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return s&&(u[vt.OAUTH_TOKEN]=`Bearer ${s}`,o&&(u[vt.OAUTH_PROVIDER]=o)),{body:a,headers:u}}async callAPIWithRetry(e){let t=null;for(let n=0;n<10;n++){let r;try{const t=interceptStreamErrors({responseStream:await this.request.post({body:e.body,stream:!0,endpoint:Ct.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers})}),n=t.stream;r=t.getStreamError;const s=Ge.fromReadableStream(n);s.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let o=null;s.on("error",e=>{o="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const i=await s.finalMessage();if(o)throw o;return this.callbacks.onRetryUpdate?.(null),i}catch(e){const s=r?.(),o=s?Object.assign(new Error(s.message),{type:s.type,error:{type:s.type,message:s.message}}):e;if(t=o,this.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(o))throw trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"non_retryable_api_error"}),context:{component:ls.CONTEXT_ENGINE,heading:"Non-retryable API error",code:o?.status||o?.statusCode}}),this.formatAPIError(o);if(9===n)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"max_retries_exceeded"}),context:{heading:"Max retries exceeded",component:ls.CONTEXT_ENGINE,code:o?.status||o?.statusCode,"retry.attempts":10}}),this.formatAPIError(o);trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"generate_retry_attempt"}),context:{heading:"Generate API retry",component:ls.CONTEXT_ENGINE,code:o?.status||o?.statusCode,"retry.attempt":n+1,"retry.max":10}});const i=Math.min(n,10),a=100*Math.pow(2,i),l=Math.max(a,1e3),u=Math.min(l,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:u,signal:this.abortController?.signal})}}throw t||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=e instanceof no||401===e?.status||e instanceof ro||403===e?.status,i=e?.type||e?.error?.type,a="rate_limit_error"===i||429===e?.status||n.includes("rate limit"),l="overloaded_error"===i||529===e?.status||n.includes("overloaded");return r||s||o||a||l}extractErrorMessage(e){dlog("Extracting error message from:",e);const t=e?.status||e?.statusCode||null;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;dlog("API error occurred:",e),dlog("Extracted error details:",t),dlog("Error type:",r),dlog("Error message:",s);const o=s?.toLowerCase().includes("insufficient credits");if(o)return new Error("Insufficient credits");const i=s?.toLowerCase().includes("oauth authentication required");if(i)return e;if(e instanceof ro||403===e?.status)return e;if(e instanceof no||401===e?.status)return new Error('Error: Authentication failed. Your API key may be invalid or expired. Run "cmd login" to sign in again.');const a=getSupportId();let l="";if(s)if(s.includes("Invalid 'Authorization' header"))l='Error: Authentication failed. Run "cmd login" to sign in again.';else{let e=s;for(;e.startsWith("Error: ");)e=e.substring(7);e.includes("Unexpected event order")&&(e="The API returned an error. This may be due to high traffic or a temporary issue.");let t=e.replace(/(?<!\.)Anthropic(?!\.)/gi,"Command Code");t.length>kC&&(t=t.substring(0,kC)+"..."),l=`Error: ${[n,r?r.charAt(0).toUpperCase()+r.slice(1):null,t].filter(Boolean).join(" ")}`;const o=s.toLowerCase(),i="overloaded_error"===r||o.includes("overloaded"),u="rate_limit_error"===r||o.includes("rate limit");l+=i?"\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.':'\n\nType "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord',"unknown"!==a&&(l+=`\nRequest ID: ${a}`)}else if(e.toString){const t=e.toString();l=t.length>kC?t.substring(0,kC)+"...":t}else l="Error: Unknown error occurred";return new Error(l)}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=nw.includes(o.name),a=rw.includes(o.name)?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",tool_use_id:o.id,content:`Error: ${r}`,is_error:!0}}),t.add(o.id);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.id);if(r.length>0){const e=await Promise.allSettled(r.map(async({toolBlock:e,entryId:t,description:n})=>{this.checkIfInterrupted(),isAgentTool(e.name)||e.name===Jy.GET_SELF_KNOWLEDGE||this.showToolRunning(e,t,n);const r="edit_file"===e.name?await resolveEditStartLine({filePath:e.input.filePath,oldContent:e.input.oldValue}).catch(()=>{}):void 0,s=await this.executeSingleTool(e);return isAgentTool(e.name)||e.name===Jy.GET_SELF_KNOWLEDGE||this.showToolSuccess(e,s,t,n,r),{toolBlock:e,toolResult:{type:"tool_result",tool_use_id:e.id,content: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.id);else{const e=s.reason instanceof Error?s.reason.message:"Unknown error";"Interrupted by user"===e&&isAgentTool(i.name)?t.add(i.id):(o.push({type:"tool_result",tool_use_id:i.id,content:`Error: ${e}`,is_error:!0}),t.add(i.id),i.name!==Jy.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.name,e.input),new Promise(e=>setTimeout(()=>e(null),6e3))])}catch(t){return CC.debug(`Failed to generate description for ${e.name}: ${t instanceof Error?t.message:"Unknown error"}`),this.callbacks.onToolDescriptionError&&this.callbacks.onToolDescriptionError(e.name,t),null}}async checkToolPermission(e,t){return nw.includes(e.name)&&this.callbacks.onPermissionRequest?{needsPermission:!0,allowed:await this.callbacks.onPermissionRequest(e.name,e.input,t)}:{needsPermission:!1,allowed:!0}}async executeSingleTool(e){const t=this.callbacks.getPermissionMode?.()||"standard",n=await executeTool(e.name,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,e.name),s=estimateTokens(r);return this.currentInteractionTokens+=s,this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens),r}handlePermissionDenied(e,t){const n=hv(e.name,e.input),r={..."edit_file"===e.name?e.input:{},permissionDenied:!0},s={...ZE(e.name,n,r),id:t},o=av(s,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o)}buildToolMetadata({toolBlock:e,editStartLine:t}){if("edit_file"===e.name)return{...e.input,...void 0!==t?{startLine:t}:{}};if("write_file"===e.name){const t=e.input,n="string"==typeof t.content?t.content:"",r=n.split("\n"),s=r.length>Gr?r.slice(0,Gr).join("\n"):n;return{...t,content:s,totalLines:r.length}}}showToolRunning(e,t,n){const r=hv(e.name,e.input),s={...ZE(e.name,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.name){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=hv(e.name,i),l={...ZE(e.name,a,o),id:n,...r?{description:r}:{}},u=av(l,t);this.callbacks.onFeedUpdate(u)}showToolError(e,t,n,r){const s=hv(e.name,e.input),o="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,i={...ZE(e.name,s,o),id:n,...r?{description:r}:{}},a=av(i,lv(t));this.callbacks.onFeedUpdate(a)}processServerToolBlocks(e){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let t="";const n=e.content;for(const e of n)if("text"===e.type)t+=e.text;else if("server_tool_use"===e.type){if(t.trim()){const e=XE(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:s}=tw({serverToolBlock:e,contentBlocks:n}),o=hv(e.name,e.input),i=ZE(e.name,o),a=av(i,s?lv(r):r);this.callbacks.onFeedUpdate(a)}if(t.trim()){const e=XE(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:Ov})}async checkAndCompactIfNeeded(){const e=Math.floor(Ov*Dt.TIER_1_THRESHOLD),t=Math.floor(Ov*Dt.TIER_2_THRESHOLD),n=Math.floor(Ov*Dt.TIER_3_THRESHOLD),r=getCompactMode();try{if(this.contextTokensUsed>n){CC.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){CC.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${t}), removing all except last ${Dt.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(Dt.TIER_2_KEEP_COUNT);return CC.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=Dt.TIER_1_KEEP_COUNT;if(t>n){CC.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${e}), keeping last ${n} tool calls`);const t=await this.removeToolCallsExceptLast(n);CC.debug(`Tier 1 compaction completed: removed ${t.toolsRemoved} tool calls, saved ${t.tokensSaved} tokens`),this.emitAutoCompactInfo(t.tokensSaved)}}}catch(e){CC.debug(`Failed to automatically compact conversation: ${e}`)}}emitAutoCompactInfo(e){this.compactionCount++,e>0&&this.callbacks.onFeedUpdate(JE(`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_use"===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_use"===t[n].type&&r.push({id:t[n].id,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("user"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_result"!==e.type||!o.has(e.tool_use_id)||(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_use"!==e.type||!o.has(e.id)||(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:Ov}),{toolsRemoved:o.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return CC.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(Dt.TIER_2_KEEP_COUNT);CC.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});CC.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:Ov}),CC.debug(`Tier 3 summarization complete: reduced from ${o} to ~${l} tokens`)}catch(e){CC.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(Dt.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=Dt.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:Ov})),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()}}}}),IC=__esm({"src/utils/clear-console.ts"(){Ft(),PC=__name(()=>process.stdout.write("win32"===process.platform?"[2J[0f":"[2J[3J[H"),"clearConsole")}});async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new Yy({baseUrl:e});return await t.get({endpoint:Ct.ALPHA.WHOAMI})}var NC=__esm({"src/utils/get-entity.ts"(){Ft(),Cs(),bw(),zt(),__name(getAuthenticatedEntity,"getAuthenticatedEntity")}}),RC={};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:p,updateStatus:g,setUpdateStatus:h,billingLink:f,setBillingLink:y,contextEngineRef:w,isSubmittingRef:S,setInput:E,setStaticKey:v,executeBash:C}){if(!t.length)return;if(g&&h(null),p(0),"bash"===e){if(S.current)return;S.current=!0;const e=ev(t);return a([...i,e]),E(""),await C(t,e=>{a(e)},()=>{PC(),v(e=>e+1)}),void(S.current=!1)}if(l)return d(e=>[...e,{input:t,displayMessage:s,isAutomated:o}]),void E("");if(S.current)return;S.current=!0,u(!0),m(mv()),E("");let k=!1;try{w.current&&await w.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(k=!0);if(k=!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:f,setBillingLink:y})}`;return void a(t=>[...t,nv(e)])}if(e.message.startsWith("Error:"))return m("Error"),void a(t=>[...t,nv(e.message)]);m("Error");const t=e.message||"An unexpected error occurred";a(e=>[...e,nv(t)])}finally{u(!1),k||m("Ready..."),S.current=!1}}__export(RC,{getBillingLink:()=>getBillingLink,handleSubmit:()=>handleSubmit});var $C,MC=__esm({"src/tui/actions/submit.ts"(){Ft(),Sv(),po(),NC(),zt(),IC(),__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(f.homedir(),".cache","giget","gh",`${e}-${n}`);await D.rm(r,{recursive:!0,force:!0}).catch(()=>{})}async function cleanupStaleTempDirectories(){try{const e=f.tmpdir(),n=await D.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 D.stat(n)).mtimeMs>$C&&await D.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 DC,LC,OC=__esm({"src/services/skill-utils.ts"(){Ft(),$C=864e5,__name(isCorruptedArchiveError,"isCorruptedArchiveError"),__name(clearGigetCache,"clearGigetCache"),__name(cleanupStaleTempDirectories,"cleanupStaleTempDirectories"),__name(wrapFetchError,"wrapFetchError")}}),qC={};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>=DC)return[];const a=[];try{const e=await D.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 D.stat(e)).size>LC);else{const r=await D.readFile(e,"utf-8"),{data:s}=Fe(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(f.tmpdir(),`commandcode-skill-discovery-${W()}`);try{await D.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 D.rm(a,{recursive:!0,force:!0}).catch(()=>{}),{skills:l})}catch(e){throw await D.rm(a,{recursive:!0,force:!0}).catch(()=>{}),wrapFetchError(e,n,r)}}__export(qC,{discoverSkillsLocally:()=>discoverSkillsLocally});var FC=__esm({"src/services/local-skill-discovery.ts"(){Ft(),OC(),DC=100,LC=1048576,__name(findSkillMdFiles,"findSkillMdFiles"),__name(discoverSkillsLocally,"discoverSkillsLocally")}});Ft(),Ft();var jC=process.argv.includes("-d")||process.argv.includes("--debug");jC&&(process.env.DEBUG="true"),jC||(process.removeAllListeners("warning"),process.on("warning",()=>{})),Ft(),Ft(),gs();var{red:BC,yellow:zC,dim:UC}=ie,WC=__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:ls.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${Qe.error} ${BC(t)}`),console.log(`${Qe.error} ${BC("ERROR →")} ${n.name}`),console.log(`${Qe.info} ${BC("REASON →")} ${n.message}`),console.log(`${Qe.info} ${BC("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${Qe.info} ${UC(`Request ID: ${e}`)}`),console.log(`${UC(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${Qe.warning} ${zC(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:ls.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),WC({heading:He`CRITICAL: Unhandled Promise Rejection!
|
|
278
|
-
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:ls.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),
|
|
279
|
-
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)})})}gs(),__name(handleUnhandledErrors,"handleUnhandledErrors"),Ft(),Ft(),fs(),bw(),Cs(),zt(),Ew(),Sr(),Cr(),an(),Aw(),Nw(),Ow(),lC(),Iv(),ho(),Kv();var GC=null,HC=!1,QC=new Set([Jy.EDIT_FILE,Jy.WRITE_FILE,Jy.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(HC)return;HC=!0;const e=__name(e=>{GC?.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(),GC=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:GC.signal,dangerouslySkipPermissions:e.dangerouslySkipPermissions,maxTurns:e.maxTurns??VC,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 no&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof ro&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof ao&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof eo&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof lo&&(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 VC=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={[vt.PROJECT_SLUG]:Ev.getCurrentProjectDirName(),[vt.TASTE_LEARNING]:d.toString(),[vt.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(m[vt.OAUTH_TOKEN]=`Bearer ${r}`,s&&(m[vt.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:`anthropic:${getConfiguredModel()}`},o={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:s,threadId:t.sessionId},i=await e.post({body:o,stream:!0,endpoint:Ct.ALPHA.GENERATE,headers:t.headers,signal:r});return Ge.fromReadableStream(i).finalMessage()}async function executeToolCall(e,t,n){if(QC.has(e.name)&&!n)return{type:"tool_result",tool_use_id:e.id,content:`Error: Tool "${e.name}" requires permissions. Use --yolo (or --dangerously-skip-permissions) to enable file writes and shell commands in print mode.`,is_error:!0};try{const n=await executeTool(e.name,e.input,{abortSignal:t});return{type:"tool_result",tool_use_id:e.id,content:n}}catch(t){if(t instanceof no||t instanceof ro||t instanceof ao||t instanceof eo||t instanceof lo)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}}}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall");var KC=80;function truncate(e){return e.length<=KC?e:e.slice(0,KC)+"..."}function formatToolLabel(e){const t=e.input,n=__name(e=>truncate(String(t[e]??"")),"param");switch(e.name){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.name}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1,maxTurns:s,verbose:o}=e,i=getApiBaseUrl(),a=new Yy({baseUrl:i}),l=[{role:"user",content:t}],u=await setupConversationContext(),d=createBenchmarkCollector();let m=0,p="";const g={stream:process.stderr,color:"cyan"},h=o?Ce(g):null;try{for(;m<s;){if(m++,n.aborted)throw new Error("Cancelled");h?.start();const e=d?Date.now():0,t=await callApi(a,u,l,n),s=d?Date.now()-e:0;h?.stop();const i=t.usage,f=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,y=t.content.filter(e=>"text"===e.type),w=t.content.filter(e=>"tool_use"===e.type),S=y.map(e=>e.text).join("");if(S&&(p+=S),0===w.length){d&&f&&d.turnDetails.push(f);break}const E=[],v=d?Date.now():0;for(const e of w){if(n.aborted)throw new Error("Cancelled");let t=null;if(o){const n=formatToolLabel(e);t=Ce({...g,text:n}).start()}const s=await executeToolCall(e,n,r);if(t){const e=s.is_error?ve.cross:ve.tick;t.stopAndPersist({symbol:e})}if(d&&"string"==typeof s.content){const{cleanContent:e,metrics:t}=extractAgentMetrics(s.content);t&&(d.agents.push(t),s.content=e)}f&&f.toolCalls.push({name:e.name,isError:s.is_error??!1}),E.push(s)}d&&f&&(f.toolDurationMs=Date.now()-v,d.turnDetails.push(f)),l.push({role:"assistant",content:t.content}),l.push({role:"user",content:E})}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 p}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"),Ft(),Ft(),Ft(),Ft(),os(),Ft(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var YC=["no job control","cannot set terminal process group"],JC=null;function getShellInfo(){return JC||(JC=detectUserShell()),JC}__name(getShellInfo,"getShellInfo");var XC=__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=R(u,l?["-i","-c",e]:["-c",e],{cwd:r,env:{...s},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let m="",p="",g=null;n>0&&(g=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),i({stdout:m,stderr:p+(p?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(m.length+n.length>es){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void i({stdout:m,stderr:"Output too large (max 25,000 tokens allowed). Try limiting command output or redirecting to a file.",exitCode:1,command:e})}m+=n}catch(e){p+=`\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(p.length+t.length>ts)return void(p+="\n[Error output truncated: too large]");p+=t}catch(e){p+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{g&&clearTimeout(g);const n=l?p.split("\n").filter(e=>!YC.some(t=>e.includes(t))).join("\n"):p;i({stdout:m.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{g&&clearTimeout(g),i({stdout:m,stderr:p+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),ZC=__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");Sv();var ek=__name(()=>{const[e,t]=Q({isExecuting:!1,currentCommand:null});return{executeBash:J(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await XC(e,{timeout:3e4,cwd:process.cwd()}),s=ZC(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]=av(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]=av(r,`Error: ${s}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");function useUiOverlays(){const[e,t]=Q(!1),[n,r]=Q(!1),[s,o]=Q(!1),[i,a]=Q(!1),[l,u]=Q(!1),[d,m]=Q(!1),[p,g]=Q(!1),[h,f]=Q(!1),[y,w]=Q(!1),[S,E]=Q(!1),[v,C]=Q(!1),[k,T]=Q(!1),[_,x]=Q(!1),[P,A]=Q(!1),[I,N]=Q(!1),[R,$]=Q(!1),[M,D]=Q(0),[L,O]=Q("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:p,setShowMemorySelector:g,showMcpManager:h,setShowMcpManager:f,showLearningFeed:y,setShowLearningFeed:w,showSessionSelector:S,setShowSessionSelector:E,showAddDirModal:v,setShowAddDirModal:C,showRewindSelector:k,setShowRewindSelector:T,showLoginOverlay:_,setShowLoginOverlay:x,showCompactModeSelector:P,setShowCompactModeSelector:A,showContextView:I,setShowContextView:N,showStatusView:R,setShowStatusView:$,staticKey:M,setStaticKey:D,transcriptMode:L,setTranscriptMode:O,expandedToolOutput:"off"!==L}}function useFeed(){const[e,t]=Q([]),[n,r]=Q([]),[s,o]=Q([]),[i,a]=Q(!1),l=V([]);return K(()=>{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]=Q(crypto.randomUUID()),[n,r]=Q(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:V(null)}}function useStatus(e){const[t,n]=Q("Ready..."),r=V(!1),[s,o]=Q(""),i=V(null),[a,l]=Q(null),u=V(a),[d,m]=Q(null),[p,g]=Q(!1),[h,f]=Q(""),[y,w]=Q(null),[S,E]=Q(0),[v,C]=Q(null),[k,T]=Q(!1),[_,x]=Q(e??null);K(()=>{u.current=a},[a]),K(()=>{if(_){const e=setTimeout(()=>{x(null)},3e4);return()=>clearTimeout(e)}},[_]);const P=__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:p,setShowShareNotification:g,unshareNotificationMessage:h,setUnshareNotificationMessage:f,retryAttempt:y,setRetryAttempt:w,interactionTokens:S,setInteractionTokens:E,contextUsage:v,setContextUsage:C,tasteLearningEnabled:k,setTasteLearningEnabled:T,updateStatus:_,setUpdateStatus:x,showHintMessage:P}}function useAuth(){const[e,t]=Q(null),[n,r]=Q(getConfiguredModel()),[s,o]=Q(!1),[i,a]=Q(null),[l,u]=Q(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,isOAuthMode:s,setIsOAuthMode:o,authComponentInfo:i,setAuthComponentInfo:a,showProviderNotification:l,setShowProviderNotification:u,providerNotificationTimer:V(null),modelNotificationTimer:V(null)}}Ft(),__name(useUiOverlays,"useUiOverlays"),Ft(),__name(useFeed,"useFeed"),Ft(),__name(useSession,"useSession"),Ft(),__name(useStatus,"useStatus"),Ft(),Sr(),__name(useAuth,"useAuth"),Ft(),Ft(),Ft(),zt();var tk=class extends We{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 D.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 D.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await D.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 D.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 D.mkdir(n,{recursive:!0});try{const t=await D.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 D.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},nk=__name((e={})=>{const[t,n]=Q(null),[r,s]=Q(null),[o,i]=Q(!1);return K(()=>{const t=e.projectRoot||process.cwd(),r=new tk(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:J(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:J(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:J(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:J(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:J(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:J((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:J(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]=Q(()=>e||(t?"auto-accept":"standard")),a=V(o);K(()=>{a.current=o},[o]);const{requestShellPermission:l,service:u,respondToPrompt:d,clearSessionPermissions:m,setEnabled:p}=nk({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 K(()=>{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]=Q(null),[n,r]=Q(null);return{pendingPermission:e,setPendingPermission:t,pendingQuestion:n,setPendingQuestion:r}}function useOnboarding(){const[e,t]=Q(!1),[n,r]=Q(!1),[s,o]=Q(!0),[i,a]=Q(!1),[l,u]=Q(!1),[d,m]=Q(null),[p,g]=Q(!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:p,setAutoLearnTaste:g,tasteOnboardingCheckedRef:V(!1)}}function useExit(){const[e,t]=Q(!1),[n,r]=Q(null),s=V(null),o=V(0),i=V(null),a=J(()=>{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:p,setCurrentProvider:g,shareInfoRef:h,permissionsService:f,permissionModeRef:y,setPendingQuestion:w,contextEngineRef:S}){const E=J(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=>{p(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{d(e)},"onRetryUpdate"),onProviderChange:__name(e=>{g(e)},"onProviderChange"),onStatusUpdate:__name(e=>{u.current=!0,l(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{const r=t??{};if(!f)return!0;if("shell_command"===e){const e=buildShellPermissionRequest(r,n);return(await f.requestShellPermission(e)).allowed}if("kill_shell"===e){const e=createKillShellPermissionRequest(r);return(await f.requestShellPermission(e)).allowed}const s=buildFilePermissionRequest(e,r);return(await f.requestPermission(s)).allowed},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{w({params:e,resolve:t,reject:n}),l("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const n=h.current;return n?{sessionId:t??e,secret:n.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>y.current,"getPermissionMode")}),[f,e]);return K(()=>{S.current||!r||n||t||(S.current=new TC(E(),e))},[e,n,t,r,E,S]),{createContextEngineCallbacks:E}}Ft(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),__name(usePermissionMode,"usePermissionMode"),Ft(),__name(usePendingOps,"usePendingOps"),Ft(),__name(useOnboarding,"useOnboarding"),Ft(),__name(useExit,"useExit"),Ft(),AC(),__name(createKillShellPermissionRequest,"createKillShellPermissionRequest"),__name(buildShellPermissionRequest,"buildShellPermissionRequest"),__name(getFileAction,"getFileAction"),__name(buildFilePermissionRequest,"buildFilePermissionRequest"),__name(useContextEngine,"useContextEngine"),Ft(),Ft(),Ft(),Cn();var rk=5242880,sk=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(h.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await M.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 M.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await M.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 M.stat(this.filePath);if(e.size<=rk)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await M.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 M.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 sk}__name(createHistoryManager,"createHistoryManager"),IE(),Iv(),IC(),cC(),Ft(),zt(),Iw();var ok=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await M.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await M.access(r);const e=await M.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await M.writeFile(r,t,"utf-8")}catch{await M.writeFile(r,kw+"\n\n","utf-8")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await M.access(n),!0}catch{return!1}}};Sr(),Cr(),Ft(),AC(),Sv(),IC(),Ft(),zt(),Jh(),bw(),Cs();var{setText:ik}=Ve;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 ik(t.url),r(""),s(!0),void setTimeout(()=>{s(!1)},3e3);try{r("Creating share link...");const t=o.current?.getMessages()||[],i=Bh.sanitizeMessages(t,global.COMMAND_CODE_CWD||process.cwd()),a=new Yy({baseUrl:getApiBaseUrl()}),l=await a.post({endpoint:Ct.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 ik(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 Yy({baseUrl:getApiBaseUrl()});await i.delete({endpoint:Ct.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 p=crypto.randomUUID();t.current=p;try{r([]),s([]),n.current=null,l("standard"),o(e),i(!1),a(!0),n.current=new TC(m(e),e);const{feedEntries:g,corruptedLines:h,totalLines:f}=await n.current.loadSession(e);if(t.current!==p)return;await loadShareInfo({contextEngineRef:n,setShareInfo:d});const y=[];if(0===g.length&&f>0&&y.push(nv(`Session could not be loaded. ${f} lines could not be parsed.`)),0===g.length&&0===f&&y.push(JE("Session loaded but contains no messages.")),g.length>0&&(h>0&&y.push(JE(`Warning: ${h} message(s) could not be loaded.`)),y.push(...g)),t.current!==p)return;r(y),PC(),u(e=>e+1)}catch(e){if(t.current!==p)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";r([nv(`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,continueLatest:t,trust:n,initialPrompt:r,stdout:s,feedState:o,sessionState:i,statusState:a,authState:l,onboarding:u,uiOverlays:d,permissionState:m,contextEngineRef:p,isSubmittingRef:g,initialPromptSubmittedRef:h,historyManagerRef:f,executeBash:y,createContextEngineCallbacks:w,setInput:S,onCommand:E}){const v=J(async()=>{try{const e=await isTasteLearningEnabled();a.setTasteLearningEnabled(e),e&&await ok.initializeProject()}catch{}},[a.setTasteLearningEnabled]),C=J(async()=>{const e=await getConfiguredProvider();l.setCurrentProvider(e);const t=await isOAuthEnforced();l.setIsOAuthMode(t)},[l.setCurrentProvider,l.setIsOAuthMode]),k=J(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(()=>{})},[]),T=J(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:i.sessionLoadIdRef,contextEngineRef:p,setFeed:o.setFeed,setLiveEntries:o.setLiveEntries,setSessionId:i.setSessionId,setShowSessionSelector:d.setShowSessionSelector,setSessionLoaded:i.setSessionLoaded,setPermissionMode:m.setPermissionMode,setStaticKey:d.setStaticKey,setShareInfo:a.setShareInfo,createContextEngineCallbacks:w})},[i,o,d,m,a,p,w]),_=J(async()=>{if(t){const e=await Ev.listSessions();return void(e.length>0&&T(e[0].id))}e&&d.setShowSessionSelector(!0)},[t,e,T,d]);K(()=>{(async()=>{await Ev.isProjectInitialized()?(u.setProjectTrusted(!0),u.setCheckingProject(!1),v(),C(),k(),await _()):n?(await Ev.initializeProject(),u.setProjectTrusted(!0),u.setCheckingProject(!1),v(),C(),k(),await _()):isDirectoryEmpty()?(await Ev.initializeProject(),u.setProjectTrusted(!0),u.setCheckingProject(!1),v(),C(),k()):(u.setShowTrustPrompt(!0),u.setCheckingProject(!1))})()},[e,t,n]),K(()=>{if(!u.projectTrusted)return;const e=createHistoryManager();return f.current=e,e.init(),()=>{e.cleanup()}},[u.projectTrusted]),K(()=>{if(!s)return;const e=__name(()=>{d.showLearningFeed||(PC(),d.setStaticKey(e=>e+1))},"handleResize");return s.on("resize",e),()=>{s.off("resize",e)}},[s]),K(()=>{r&&u.projectTrusted&&!u.checkingProject&&p.current&&!d.showSessionSelector&&!h.current&&(h.current=!0,submitInitialPrompt({initialPrompt:r,onCommand:E,submitAsUserMessage:__name(()=>handleSubmit({role:"user",input:r,feed:o.feed,setFeed:o.setFeed,isCmdCodeBusy:o.isCmdCodeBusy,setIsCmdCodeBusy:o.setIsCmdCodeBusy,setQueuedMessages:o.setQueuedMessages,setStatus:a.setStatus,setInteractionTokens:a.setInteractionTokens,updateStatus:a.updateStatus,setUpdateStatus:a.setUpdateStatus,billingLink:a.billingLink,setBillingLink:a.setBillingLink,contextEngineRef:p,isSubmittingRef:g,setInput:S,setStaticKey:d.setStaticKey,executeBash:y}),"submitAsUserMessage")}))},[r,u.projectTrusted,u.checkingProject,d.showSessionSelector,E]);const x=V(null);x.current={feed:o.feed,setFeed:o.setFeed,isCmdCodeBusy:o.isCmdCodeBusy,setIsCmdCodeBusy:o.setIsCmdCodeBusy,setQueuedMessages:o.setQueuedMessages,setStatus:a.setStatus,setInteractionTokens:a.setInteractionTokens,updateStatus:a.updateStatus,setUpdateStatus:a.setUpdateStatus,billingLink:a.billingLink,setBillingLink:a.setBillingLink,contextEngineRef:p,isSubmittingRef:g,setInput:S,setStaticKey:d.setStaticKey,executeBash:y,role:"",input:""};const P=J(async({role:e,input:t,images:n,ideContext:r,displayMessage:s,isAutomated:o})=>handleSubmit({...x.current,role:e,input:t,images:n,ideContext:r,displayMessage:s,isAutomated:o}),[]);return{loadTasteStatus:v,loadCurrentProvider:C,initializeMcpInBackground:k,onSubmit:P}}__name(loadShareInfo,"loadShareInfo"),__name(handleShareCommand,"handleShareCommand"),__name(handleUnshareCommand,"handleUnshareCommand"),__name(handleSelectSession,"handleSelectSession"),__name(handleNewSession,"handleNewSession"),MC(),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Ft(),bn(),Sv(),Sn(),Ft(),zt(),Cn(),Ft();var ak={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return ak[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Ue(t);return e.join(f.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 M.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 M.mkdir(s,{recursive:!0}),await M.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),dC.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 M.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"),Ft(),Cn(),pC(),zt(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),Ft(),Cn();var lk=e.join(h.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=x(e,{encoding:"utf8"}),n=Ke.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 M.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const s=await M.readdir(t);for(const o of s){if(!/^\d{4}$/.test(o))continue;const s=e.join(t,o);if(!(await M.stat(s)).isDirectory())continue;const i=await M.readdir(s);for(const t of i){if(!/^\d{2}$/.test(t))continue;const i=e.join(s,t);if(!(await M.stat(i)).isDirectory())continue;const a=await M.readdir(i);for(const s of a){if(!/^\d{2}$/.test(s))continue;const a=e.join(i,s);if(!(await M.stat(a)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${o}/${t}/${s}`});const l=(await M.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 M.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 M.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"),Ft(),Cn();var ck=e.join(h.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 M.access(ck)}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 M.readdir(ck);for(const r of n){if(!t.includes(r))continue;const n=e.join(ck,r,"agent-transcripts");try{if((await M.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 M.readdir(o);for(const n of t){const t=e.join(o,n);try{if(!(await M.stat(t)).isDirectory())continue;const r=e.join(t,`${n}.jsonl`);try{const e=await M.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 M.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 M.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(h.homedir(),".claude","projects");await M.access(t);const s=getProjectDirName(process.cwd()),o=(await M.readdir(t)).filter(e=>e===s);for(const s of o){const o=e.join(t,s);if((await M.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}){K(()=>{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]),K(()=>()=>{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)},[]),K(()=>{(async()=>{if("anthropic"===s.currentProvider&&s.isOAuthMode)try{await mn.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]),K(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(mv())},7e3);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),K(()=>{a||triggerTasteOnboarding({projectTrusted:o.projectTrusted,onboardingComplete:o.onboardingComplete,isOnboardingMode:o.showTasteOnboarding,tasteOnboardingCheckedRef:o.tasteOnboardingCheckedRef,setIsOnboardingMode:o.setShowTasteOnboarding})},[o.projectTrusted,o.onboardingComplete,o.showTasteOnboarding,a]),K(()=>{if(o.showTasteOnboarding&&!o.tasteOnboardingEntryId){const e=rv();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"),Ft(),IC(),Iv(),Sv(),Ft(),yn(),Cr(),IC(),zt(),Ft();var uk="└",dk=" ",mk=`${dk}TASTE${dk}`;function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showProviderSelector:n,showModelSelector:r,showMemorySelector:s,showMcpManager:o,showLearningFeed:i,showRewindSelector:a,showLoginOverlay:l,showAddDirModal:u,authComponentInfo:d,setShowLearningFeed:m,setShowModelSelector:p,setStaticKey:g,transcriptMode:h,setTranscriptMode:f,isCmdCodeBusy:y,liveEntries:w,queuedMessagesRef:S,setInput:E,setQueuedMessages:v,setFeed:C,setLiveEntries:k,setIsCmdCodeBusy:T,setRetryAttempt:_,setStatus:x,pendingExitKey:P,setPendingExitKey:A,pendingExitKeyRef:I,lastExitKeyTimeRef:N,exitConfirmationTimeoutRef:R,resetPendingExitKey:$,pendingPermission:M,setPendingPermission:D,pendingQuestion:L,setPendingQuestion:O,setShouldExit:q,contextEngineRef:F,handleToggleAutoAccept:j,handleDoubleEscapeEmpty:B,respondToPrompt:z,createErrorEntry:U}){const W=__name(()=>{if(!F.current)return;F.current.interrupt(!0);const e=w.length>0;if(T(!1),_(null),k([]),x("Interrupted by user"),!e){const e=U("Interrupted by user");C(t=>[...t,e])}if(S.current.length>0){const e=S.current.map(e=>e.displayMessage??e.input).join("\n");E(t=>t?e+"\n"+t:e),v([]),S.current=[]}},"handleInterrupt");ne((w,S)=>{if(S.shift&&S.tab||"[Z"===w)j();else if(e||t||n||r||s||o||d||i||a||l||u)P&&$();else{if(""===w||S.ctrl&&"c"===w){if(y&&F.current)return void W();const e=Date.now(),t=e-N.current;return N.current=e,"ctrl-c"===I.current&&t<2e3?(R.current&&(clearTimeout(R.current),R.current=null),void q(!0)):(E(()=>""),I.current="ctrl-c",A("ctrl-c"),R.current&&clearTimeout(R.current),void(R.current=setTimeout(()=>{I.current=null,A(null),R.current=null},2e3)))}if(S.ctrl&&"t"===w)return PC(),m(!i),void g(e=>e+1);if(getIsExpandToolShortcut(S,w))return PC(),f("off"===h?"limited":"off"),void g(e=>e+1);if(S.ctrl&&"e"===w&&"off"!==h)return PC(),f("limited"===h?"full":"limited"),void g(e=>e+1);if(S.meta&&"p"===w||isAltP(w))p(!0);else if(S.escape){if(L)return L.reject(new Error("Question cancelled by user")),O(null),void x("Question cancelled");if(M)return z({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),M.resolve(!1),D(null),void x("Permission denied");y&&F.current&&W()}}})}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:p}){const g=J(()=>{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]),h=J(()=>{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]),f=J(s=>{if(n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),PC(),s?.skipped){const e=JE("",{isTasteSkip:!0});t.setFeed(t=>[...t,e])}r.setStaticKey(e=>e+1),e&&r.setShowSessionSelector(!0)},[e,n,r,t]),y=J(async()=>{try{if(await Ev.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]),w=J(()=>{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,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:p,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:g,handleDoubleEscapeEmpty:h,respondToPrompt:i.respondToPrompt,createErrorEntry:nv}),{handleToggleAutoAccept:g,handleDoubleEscapeEmpty:h,handleTasteOnboardingComplete:f,handleTrust:y,handleNoTrust:w}}__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Ft(),Ft(),zt(),Sv(),vr(),Ft(),Ft(),Ft(),zt(),Cn(),kr(),$r(),Ft(),zt();var pk=t.join(f.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(pk);S.existsSync(e)||S.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!S.existsSync(pk))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=S.readFileSync(pk,"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(),S.writeFileSync(pk,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"),kr();var gk=Je(I),hk=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!process.env.COMMANDCODE_SKIP_UPDATES||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=N("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return hk.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(Xe.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&Xe.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&Xe.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 gk(`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(!Xe.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=Ce(`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}`)}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 N("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 fk=new Set(["OPEN","MERGED","CLOSED"]),yk=null;function getCachedPRInfo(e){if(yk&&yk.branch===e){if(!(Date.now()-yk.timestamp>3e5))return yk.result;yk=null}}function setPRCache(e,t){yk={branch:e,result:t,timestamp:Date.now()}}function execFileAsync({cmd:e,args:t,encoding:n,timeout:r}){return new Promise((s,o)=>{$(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&&fk.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 wk=__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");Ft();var Sk='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?`${Sk}\n\nReview PR number: ${n}${t?"\n(Note: PR number auto-detected from current branch.)":""}`:`${Sk}\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(f.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,s=""){if(S.existsSync(n))try{const o=S.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=S.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"),Ft(),__name(lastResponseHasComments,"lastResponseHasComments"),Ft(),zt(),Ft(),zt(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),vr(),Ft();var bk=["Code","Code - Insiders","VSCodium","Cursor"],Ek="Code",vk={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},Ck=__name(e=>m(e).href,"formatPathForTerminal"),kk=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),Tk=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),_k=__name(({home:t,configSegments:n,variants:r})=>{for(const s of r){const r=Tk({home:t,configSegments:n,variant:s});if(w.existsSync(e.dirname(r)))return s}return null},"findExistingVariant"),xk=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&Pk(t.when)},"isTerminalShiftEnterBinding"),Pk=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),Ak=__name(e=>{const t=Ze(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),Ik=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),Nk=__name(({error:e,content:t})=>{const n=e.message;return Ik(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"),Rk=__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"),$k=__name(e=>{try{const t=Ze(e),n=Rk(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:Nk({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),Mk=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:Ck(t)}),"createSuccessResult"),Dk=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:Ck(t)}),"createErrorResult"),Lk=__name(()=>{const t=h.homedir(),n=h.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=kk(n);if(!r)return Tk({home:t,configSegments:[".config"],variant:Ek});const s=_k({home:t,configSegments:r,variants:bk});return Tk({home:t,configSegments:r,variant:s??Ek})},"getVSCodeKeybindingsPath"),Ok=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)xk(n)&&(n.command===vk.command&&n.args?.text===vk.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),qk=__name(t=>{try{if(!w.existsSync(t)){const n=e.dirname(t);return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=w.readFileSync(t,"utf-8");if(Ak(n))return{rawContent:n,keybindings:[]};const r=$k(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:Dk({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):Dk({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return Dk({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),Fk=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(vk,null,2);if(Ak(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return Dk({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const s=e.lastIndexOf("}",r);return-1===s?Dk({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=Lk();try{const t=qk(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,s=Ok(r);if(s.hasConflicting)return Dk({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(s.hasCompatible)return Mk({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const o=Fk({rawContent:n,keybindingsPath:e});return"string"!=typeof o?o:(w.writeFileSync(e,o,"utf-8"),Mk({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return Dk({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"),os(),rr();var jk=(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.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))(jk||{}),Bk=new Set(["/exit","/clear","/help","/share","/unshare","/taste","/learn-taste","/skills","/resume","/provider","/model","/memory","/init","/agents","/mcp","/compact","/compact-mode","/rewind","/login","/logout","/feedback","/terminal-setup","/ide","/add-dir","/pr-comments","/context","/status"]),zk=[{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:"/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"}],Uk=__name(({onSelectCommand:e,onInsertCommand:t,onClose:n,searchQuery:r=""})=>{const[s,o]=Q(0),[i,a]=Q(0),{stdout:l}=te(),u=l?.columns??80,d=Math.max(20,u-22-2-1-2),m=Y(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...zk.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]),p=Y(()=>{const e=i,t=Math.min(e+8,m.length);return m.slice(e,t)},[m,i]);return K(()=>{o(0),a(0)},[r]),ne((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?G.createElement(X,{flexDirection:"column",paddingLeft:2},G.createElement(Z,{color:$n.DIM},"No commands found")):(m.length,G.createElement(X,{flexDirection:"column",paddingLeft:1},G.createElement(X,{columnGap:2},G.createElement(X,{flexDirection:"column",width:22},p.map((e,t)=>{const n=i+t;return G.createElement(Z,{key:n,color:s===n?$n.WHITE:$n.DIM,wrap:"truncate"},e.command)})),G.createElement(X,{flexDirection:"column"},p.map((e,t)=>{const n=i+t;return G.createElement(Z,{key:n,color:s===n?$n.WHITE:$n.DIM,wrap:"truncate"},truncateString({text:e.description,maxChars:d}))})))))},"CommandMenu");Aw(),Ft(),Ft(),Cr(),rr();var Wk=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),Gk=__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"),Hk=__name(({icon:e,label:t,children:n})=>G.createElement(Z,null,G.createElement(Z,{color:$n.CYAN},e," "),G.createElement(Z,{color:$n.DIM},t.padEnd(12)),n),"Row"),Qk=__name(({title:e})=>G.createElement(Z,null,G.createElement(Z,{color:$n.GRAY},"───"),G.createElement(Z,{color:$n.WHITE}," ",e," "),G.createElement(Z,{color:$n.GRAY},"─".repeat(35))),"Header"),Vk=__name(({title:e,marginTop:t=0,children:n})=>G.createElement(X,{flexDirection:"column",marginTop:t},G.createElement(Qk,{title:e}),G.createElement(X,{flexDirection:"column",paddingY:1},n)),"Section"),Kk=__name(({cpuCount:e,totalMem:t})=>G.createElement(Vk,{title:"System Information"},G.createElement(Hk,{icon:ve.bullet,label:"Date"},G.createElement(Z,null,formatDate())),G.createElement(Hk,{icon:ve.pointer,label:"Platform"},G.createElement(Z,{color:$n.GREEN},Wk(h.platform())),G.createElement(Z,{color:$n.DIM}," ","(",h.platform(),", ",h.arch(),")")),G.createElement(Hk,{icon:ve.triangleUp,label:"Hostname"},G.createElement(Z,null,h.hostname())),G.createElement(Hk,{icon:ve.bullet,label:"User"},G.createElement(Z,{color:$n.YELLOW},h.userInfo().username)),G.createElement(Hk,{icon:ve.bullet,label:"CPUs"},G.createElement(Z,{color:$n.MAGENTA},e," cores")),G.createElement(Hk,{icon:ve.bullet,label:"Memory"},G.createElement(Z,{color:$n.CYAN},t," GB")),G.createElement(Hk,{icon:ve.play,label:"Uptime"},G.createElement(Z,null,Gk(h.uptime()))),G.createElement(Hk,{icon:ve.arrowRight,label:"Home"},G.createElement(Z,{color:$n.DIM},h.homedir())),G.createElement(Hk,{icon:ve.pointer,label:"Shell"},G.createElement(Z,null,process.env.SHELL||"N/A")),G.createElement(Hk,{icon:ve.bullet,label:"Node"},G.createElement(Z,{color:$n.GREEN},process.version))),"SystemInfoSection"),Yk=__name(({cpus:e})=>G.createElement(Vk,{title:"CPU Details",marginTop:1},e.map((e,t)=>G.createElement(Hk,{key:t,icon:ve.bullet,label:`Core ${t}`},G.createElement(Z,null,e.model.trim()),G.createElement(Z,{color:$n.YELLOW}," @ ",e.speed," MHz")))),"CPUDetailsSection"),Jk=__name(({networkInterfaces:e})=>G.createElement(Vk,{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)=>G.createElement(Hk,{key:`${e}-${n}`,icon:ve.bullet,label:e},G.createElement(Z,{color:$n.GREEN},t.address))):null})),"NetworkSection"),Xk=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>G.createElement(X,{flexDirection:"column"},G.createElement(Z,null,"System Information"),G.createElement(Z,null,"─".repeat(40)),G.createElement(Z,null,"Date ",formatDate()),G.createElement(Z,null,"Platform ",Wk(h.platform())," (",h.platform(),","," ",h.arch(),")"),G.createElement(Z,null,"Hostname ",h.hostname()),G.createElement(Z,null,"User ",h.userInfo().username),G.createElement(Z,null,"CPUs ",e.length," cores"),G.createElement(Z,null,"Memory ",t," GB"),G.createElement(Z,null,"Uptime ",Gk(h.uptime())),G.createElement(Z,null,"Home ",h.homedir()),G.createElement(Z,null,"Shell ",process.env.SHELL||"N/A"),G.createElement(Z,null,"Node ",process.version),r&&G.createElement(G.Fragment,null,G.createElement(Z,null,"\n","CPU Details"),G.createElement(Z,null,"─".repeat(40)),e.map((e,t)=>G.createElement(Z,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),G.createElement(Z,null,"\n","Network"),G.createElement(Z,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>G.createElement(Z,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),Zk=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>G.createElement(X,{flexDirection:"column"},G.createElement(Kk,{cpuCount:e.length,totalMem:t}),r&&G.createElement(Yk,{cpus:e}),r&&G.createElement(Jk,{networkInterfaces:n})),"StyledInfo"),eT=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=se();K(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=h.cpus(),s=h.networkInterfaces(),o=Math.round(h.totalmem()/1024/1024/1024);return t?G.createElement(Xk,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e}):G.createElement(Zk,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e})},"InfoUI"),tT={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},nT=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),rT=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(nT("__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"),sT=__name(()=>{const e=rT();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&tT[t]?tT[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),oT=__name(()=>{if("win32"===f.platform()){const e=process.env.COMSPEC;return e?a(e):process.env.SHELL?a(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=N(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=a(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?a(e):"N/A"},"getShellName"),iT=__name(()=>{const e=rT();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),aT=__name(()=>{try{const e=N("cmd --version",{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:Wk(f.platform()),terminal:sT(),shell:oT(),version:aT(),ide:iT()}}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 handleCompactCommand({contextEngineRef:e,setFeed:t,setStatus:n,setIsCmdCodeBusy:r,setContextUsage:s,setStaticKey:o}){if(e.current)if(e.current.isRequestInProgress())t(e=>[...e,JE("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();PC(),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,JE(a)]),r(!1),n("Ready..."),s({current:e.current.getContextTokensUsed()||0,limit:Ov})}catch(e){const s=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;t(e=>[...e,nv(s)]),r(!1),n("Ready...")}else t(e=>[...e,JE("No active conversation to compact.")])}function handleRewindCommand({contextEngineRef:e,setFeed:t,setShowRewindSelector:n}){e.current?e.current.hasCheckpoints()?n(!0):t(e=>[...e,JE("No checkpoints available. Start sending messages to create checkpoints.")]):t(e=>[...e,JE("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)),PC(),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,JE(d)]),void s("Ready...")}r(e=>[...e,nv(`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,nv(t)]),s("Ready...")}}function handleRewindCancel({setShowRewindSelector:e}){e(!1)}async function handleLoginCommand({setFeed:e,setShowLoginOverlay:t}){const n=Lt();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,JE(`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,nv(t)]),void s("Ready...");r(e=>[...e,JE(t)]),o.current&&o.current.refreshRequest(),s("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,JE("Authentication cancelled.")]),n("Ready...")}async function handleLogoutCommand({setFeed:e,contextEngineRef:t}){const n=await performLogout();if(!n.success)return void e(e=>[...e,nv(`Logout failed: ${n.error}`)]);if(t.current&&t.current.refreshRequest(),!n.wasAuthenticated)return void e(e=>[...e,JE("Not currently authenticated.")]);const r=n.warnings.length>0?`Successfully logged out from Command Code. Warnings: ${n.warnings.join(", ")}`:"Successfully logged out from Command Code.";e(e=>[...e,JE(r)])}__name(getSystemInfo,"getSystemInfo"),__name(buildGitHubIssueUrl,"buildGitHubIssueUrl"),Ms(),Ft(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),IC(),Ft(),Sv(),IC(),Bv(),__name(handleCompactCommand,"handleCompactCommand"),Ft(),Sv(),IC(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Ft(),Sv(),po(),Ss(),Xs(),zt(),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Ft(),Bb(),Cn(),Sr();var lT=Je(I);function getVsixPath(){try{const e=t.dirname(u(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return S.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),$b.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 cT={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"};async function ensureExtensionInstalled(){if(process.env.CI)return;const e=_b();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:ie.green("✔"),installed:ie.green("✔"),needs_reload:ie.yellow("◌"),failed:ie.red("✖"),not_in_ide:ie.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=>ie.dim(` ${e}`)),""]}async function runIDESetup(){const e=_b(),t=e?cT[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new $b,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(()=>(Sv(),wv));e(e=>[...e,t("KEYBOARD SHORTCUTS\nCOMMANDS")])}async function handleTerminalSetupCommand({setFeed:e}){const t=YE(`/${At.TERMINAL_SETUP}`),n=setupVSCodeTerminal(),r=sv(n.message,!n.success,n.details);e(e=>[...e,t,r])}async function handleIDESetupCommand({setFeed:e}){const t=await runIDESetup(),n=ov(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([]),PC(),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(()=>(AC(),xC));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,JE(n)])}catch(t){const n=`Error: Failed to initialize AGENTS.md: ${t instanceof Error?t.message:"Unknown error"}`;e(e=>[...e,JE(n)])}}async function handleFeedbackCommand({setFeed:e},t){const n=buildGitHubIssueUrl(t);try{await ue(n,{wait:!1,background:!0}),e(e=>[...e,JE(`Opened ${createOSC8Link(n,"GitHub issue")} in your browser`)])}catch{const{createSystemEntry:t,createErrorEntry:r}=await Promise.resolve().then(()=>(Sv(),wv));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=rv();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(Bk.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}),{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("/review"===r){const e=s.trim(),{handleSubmit:n}=await Promise.resolve().then(()=>(MC(),RC));let r=e,o=!1;if(!e){const e=await wk();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(()=>(MC(),RC));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 p=Y(()=>({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,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,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]),g=V(p);return g.current=p,{commandCtx:p,onCommand:J(e=>handleCommand(e,g.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(Nt).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),PC(),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"),MC(),__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"),Ft(),Ft(),vr(),Sr(),__name(handleProviderSelect,"handleProviderSelect"),__name(handleProviderCancel,"handleProviderCancel"),__name(handleAuthSuccess,"handleAuthSuccess"),__name(handleAuthCancel,"handleAuthCancel"),Ft(),zt(),Sr(),IC(),__name(getModelDisplayName,"getModelDisplayName"),__name(handleModelSelect,"handleModelSelect"),__name(handleModelCancel,"handleModelCancel"),Ft(),Sr();var uT={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: ${uT[e]}`)}catch{n("Failed to set compact mode"),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var dT=__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=V({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:J(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:J(()=>{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:J(({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:J(()=>{handleRewindCancel({setShowRewindSelector:u.current.uiOverlays.setShowRewindSelector})},[]),onLoginComplete:J((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:J(()=>{const{feedState:e,statusState:t,uiOverlays:n}=u.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),handleProviderSelect:J(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:J(()=>{handleProviderCancel({setShowProviderSelector:u.current.uiOverlays.setShowProviderSelector})},[]),handleModelSelect:J(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:dT})},[]),handleModelCancel:J(()=>{handleModelCancel({setShowModelSelector:u.current.uiOverlays.setShowModelSelector})},[]),handleCompactModeSelect:J(e=>{const{statusState:t,uiOverlays:n}=u.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),handleCompactModeCancel:J(()=>{handleCompactModeCancel({setShowCompactModeSelector:u.current.uiOverlays.setShowCompactModeSelector})},[]),handleAuthSuccess:J(()=>{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:J(()=>{handleAuthCancel({setAuthComponentInfo:u.current.authState.setAuthComponentInfo})},[])}}__name(useMainActionCallbacks,"useMainActionCallbacks"),Ft(),Ft(),Ft();var mT=__name(({staticKey:e})=>G.createElement(ee,{items:[{staticKey:e}],key:e},()=>G.createElement(Z,{key:e},"\0")),"Responsive");Ft(),zt(),rr();var pT=__name(({onTrust:e,onExit:t})=>{const{exit:n}=se(),[r,s]=Q(1),o=process.cwd().replace(process.env.HOME||"","~");return ne((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())}),G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.YELLOW,padding:1},G.createElement(Z,{color:$n.YELLOW,bold:!0},"Do you trust the files in this folder?"),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY},o)),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(Z,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),G.createElement(X,{marginTop:1},G.createElement(Z,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{color:1===r?$n.CYAN:$n.GRAY},1===r?ve.pointer:" "," 1. Yes, proceed")),G.createElement(X,null,G.createElement(Z,{color:2===r?$n.CYAN:$n.GRAY},2===r?ve.pointer:" "," 2. No, exit"))))},"TrustPrompt"),gT=H(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return G.createElement(G.Fragment,null,G.createElement(mT,{staticKey:e}),G.createElement(pT,{onTrust:t,onExit:n}))},"TrustView"));Ft(),Ft(),Iv(),os(),rr();var hT=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=se(),[r,s]=Q([]),[o,i]=Q(0),[a,l]=Q(!0),[u,d]=Q(0),m=30;K(()=>{p()},[]);const p=__name(async()=>{l(!0);const e=await Ev.listSessions();s(e),l(!1)},"loadSessions");if(ne((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 G.createElement(X,{flexDirection:"column",paddingLeft:2,paddingTop:1},G.createElement(Z,{color:$n.GRAY},"Loading sessions..."));const g=__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"),h=__name(e=>truncateString({text:e,maxChars:Kr}),"truncateMessage");if(0===r.length)return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.GRAY},"No sessions available"));const f=r.slice(u,u+m),y=u;return G.createElement(X,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"Showing ",u+1,"-",Math.min(u+m,r.length)," ","of ",r.length," sessions",u>0&&" (↑ for more)",u+m<r.length&&" (↓ for more)")),G.createElement(X,{columnGap:2,marginBottom:1},G.createElement(X,{width:7},G.createElement(Z,{color:$n.GRAY}," ")),G.createElement(X,{width:13},G.createElement(Z,{color:$n.GRAY},"Modified")),G.createElement(X,{width:11},G.createElement(Z,{color:$n.GRAY},"# Messages")),G.createElement(X,{width:20},G.createElement(Z,{color:$n.GRAY},"Git Branch")),G.createElement(X,null,G.createElement(Z,{color:$n.GRAY},"Summary"))),G.createElement(X,{columnGap:2},G.createElement(X,{flexDirection:"column",width:7},f.map((e,t)=>{const n=y+t;return G.createElement(Z,{key:`sel-${n}`,color:o===n?$n.CYAN:$n.GRAY},o===n?`${ve.pointer} ${n+1}.`:` ${n+1}.`)})),G.createElement(X,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return G.createElement(Z,{key:`mod-${e.id}`,color:o===n?$n.WHITE:$n.GRAY},g(e.lastModified))})),G.createElement(X,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return G.createElement(Z,{key:`msg-${e.id}`,color:o===n?$n.WHITE:$n.GRAY},e.messageCount)})),G.createElement(X,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return G.createElement(Z,{key:`branch-${e.id}`,color:o===n?$n.WHITE:$n.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),G.createElement(X,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return G.createElement(Z,{key:`summary-${e.id}`,color:o===n?$n.WHITE:$n.GRAY},h(e.firstMessage))}))))},"SessionTable"),fT=H(__name(function SessionView2({onSelectSession:e,onNewSession:t}){return G.createElement(hT,{onSelectSession:e,onNewSession:t})},"SessionView"));Ft(),Ft(),ar(),rr();var yT=__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"),wT=__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=ve.bullet,d=$n.CYAN):l?(u=ve.tick,d=$n.GREEN):(u=ve.circle,d=$n.GRAY),o.push(G.createElement(Z,{key:i},G.createElement(Z,{color:d},u),G.createElement(Z,{color:a?$n.CYAN:void 0}," ",s.header),i<e.length-1?G.createElement(Z,{color:$n.DIM}," | "):null))}),!s){const e=r;o.push(G.createElement(Z,{key:"review"},G.createElement(Z,{color:$n.DIM}," | "),G.createElement(Z,{color:e?$n.CYAN:$n.GRAY},e?ve.bullet:ve.circle),G.createElement(Z,{color:e?$n.CYAN:void 0,bold:e}," ","Review")))}return G.createElement(X,null,o)},"TabIndicator"),ST=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,s]=Q(0),[o,i]=Q(new Map),a=V(new Map),[l,u]=Q(""),[d,m]=Q(new Set),[p,g]=Q(null),[h,f]=Q(!1),[y,w]=Q(!1),[S,E]=Q(!1),[v,C]=Q(null),[k,T]=Q(!1),_=e[r],x=_?.multiSelect??!1,P=o.get(r),A=_?[..._.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],I=A.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),N=new Map(I.map((e,t)=>[e.label,A[t]])),R=__name(e=>{"submit"===e.value?q():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),$=__name(()=>{if(!P||0===P.length)return 0;const e=P[0],t=_.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),M=__name(e=>{if(!h)if(x){const t=yT(e.value,_.options.length-1);if(null===t)return;const n=_.options[t]?.label||"";m(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=yT(e.value,_.options.length-1);if(null===t)return;f(!0);const n=_.options[t]?.label||"";O([n])}},"handleSelect"),D=__name(()=>{if(h)return;f(!0);const e=Array.from(d);O(e)},"handleMultiSelectDone"),L=__name(()=>{if(!h&&l.trim())if(x){const e=new Set(_.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 f(!0),O([l.trim()])},"handleOtherSubmit"),O=__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),f(!1),E(!1),C(null),T(!1)}else if(e.every((e,t)=>o.has(t))){if(n&&1===e.length)return void q();m(new Set),u(""),w(!0),f(!1)}else{const t=e.findIndex((e,t)=>!o.has(t));-1!==t&&(l(t),s(t)),f(!1),E(!1),C(null),T(!1)}},"finishQuestion"),q=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:a.current.get(t)||[]}));t({answers:n})},"submitAnswers"),F=__name(t=>{w(!1),s(t),T(!1),E(!1),C(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"),j=__name(t=>{if(t<0||t>=e.length)return;x&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),f(!1),E(!1),C(null),T(!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"),B=__name(()=>{if(!p||!x)return;if("done"===p.value)return;const e=yT(p.value,_.options.length-1);if(null===e)return;const t=_.options[e]?.label||"";m(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return ne((t,s)=>{if(" "===t&&x&&!S&&B(),"d"!==t||!x||S||y||D(),!y&&!h){if(s.downArrow&&!S&&!k&&!n&&p&&I.length>0&&p.value===I[I.length-1]?.value&&E(!0),s.upArrow&&!S&&!k&&p&&I.length>0&&p.value===I[0]?.value&&(x?T(!0):n||(E(!0),C(I.length-1))),s.upArrow&&S){E(!1),C(I.length-1);const e=I[I.length-1];e&&g(e)}if(s.downArrow&&S)if(E(!1),x)T(!0);else{C(0);const e=I[0];e&&g(e)}if(s.upArrow&&k&&(T(!1),E(!0)),s.downArrow&&k){T(!1),C(0);const e=I[0];e&&g(e)}s.return&&k&&x&&D()}if(h||S||k||(y?s.leftArrow&&F(e.length-1):s.leftArrow&&r>0?j(r-1):s.rightArrow&&(r<e.length-1?j(r+1):(x&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),w(!0)))),s.escape&&!h)if(y)w(!1);else if(S){E(!1);const e=v??I.length-1;C(e);const t=I[e];t&&g(t)}else if(k){T(!1);const e=I[I.length-1];e&&g(e)}}),_||y?y?G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},G.createElement(X,{marginBottom:1},G.createElement(wT,{questions:e,currentIndex:e.length,answeredQuestions:new Set(o.keys()),isReviewPage:!0})),e.map((e,t)=>G.createElement(X,{key:t,marginBottom:1,flexDirection:"column"},G.createElement(Z,{color:$n.DIM},t+1,". ",e.question),G.createElement(Z,{color:$n.GREEN}," ",o.get(t)?.join(", ")||"No answer"))),G.createElement(et,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:R,initialIndex:0,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.CYAN},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>G.createElement(Z,{color:t?$n.CYAN:$n.WHITE},e)}),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},ve.arrowLeft," to go back and edit"))):G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},G.createElement(X,{marginBottom:1},G.createElement(wT,{questions:e,currentIndex:r,answeredQuestions:new Set(o.keys()),isReviewPage:!1,hideReview:n})),G.createElement(X,{marginBottom:1},G.createElement(Z,{bold:!0},_.question)),S||k?G.createElement(X,{flexDirection:"column"},I.map((e,t)=>{const n=N.get(e.label),r=x&&n&&d.has(n.label),s=!x&&n&&P?.includes(n.label),o=r||s;return G.createElement(X,{key:t,flexDirection:"column"},G.createElement(X,null,G.createElement(Z,null," "),G.createElement(Z,{color:o?$n.GREEN:$n.WHITE}," ",t+1,"."," "),x&&(o?G.createElement(Z,{color:$n.GREEN},"[",ve.tick,"]"," "):G.createElement(Z,{color:$n.DIM},"[ ] ")),G.createElement(Z,{color:o?$n.GREEN:$n.WHITE},n?.label||""),!x&&o&&G.createElement(Z,{color:$n.GREEN}," ",ve.tick)),n?.description&&G.createElement(X,null,G.createElement(Z,null," "),G.createElement(Z,{color:$n.DIM},x?" ":" ",n.description)))})):G.createElement(et,{key:`${r}-${v??"default"}`,items:I,initialIndex:v??$(),onSelect:M,onHighlight:g,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.CYAN},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=N.get(e),r=x&&n&&d.has(n.label),s=!x&&n&&P?.includes(n.label),o=r||s,i=e.match(/^\s*(\d+)\.\s*(.*)$/),a=i?.[1]||"",l=i?.[2]||e;return G.createElement(X,{flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{color:t?$n.CYAN:o?$n.GREEN:$n.WHITE}," ",a,"."," "),x&&(o?G.createElement(Z,{color:$n.GREEN},"[",ve.tick,"]"," "):G.createElement(Z,{color:$n.DIM},"[ ] ")),G.createElement(Z,{color:t?$n.CYAN:o?$n.GREEN:$n.WHITE},l),!x&&o&&G.createElement(Z,{color:$n.GREEN}," ",ve.tick)),n?.description&&G.createElement(Z,{color:$n.DIM},x?" ":" ",n.description))}}),!n&&G.createElement(X,null,G.createElement(Z,{color:$n.CYAN},S?ve.pointer:" "),G.createElement(Z,{color:S?$n.CYAN:void 0}," ",I.length+1,"."," "),x&&(d.has(l.trim())?G.createElement(Z,{color:$n.GREEN},"[",ve.tick,"] "):G.createElement(Z,{color:$n.DIM},"[ ] ")),G.createElement(TextInput,{value:l,onChange:e=>{const t=e.replace(/\r\n/g," ").replace(/[\r\n]/g," "),n=l.trim();u(t),x&&m(e=>{const r=new Set(e);return n&&r.has(n)&&r.delete(n),t.trim()&&r.add(t.trim()),r})},onSubmit:L,placeholder:"Type something...",focus:S,stripBracketedPaste:!0})),x&&G.createElement(X,null,G.createElement(Z,{color:$n.CYAN},k?ve.pointer:" "),G.createElement(Z,{color:k?$n.CYAN:void 0,bold:k}," ",r===e.length-1?"Submit":"Next")),e.length>1&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.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 G.createElement(X,{marginY:1},G.createElement(ST,{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"),PC(),s(e=>e+1)):e.startsWith("Yes, exit")&&(t("standard"),PC(),s(e=>e+1))}if(e.params.enterPlanMode){const e=o.answers[0]?.selectedOptions[0];e?.startsWith("Yes")&&(t("plan"),PC(),s(e=>e+1))}e.resolve(o),n(null),r("Answers submitted")}}))}IC(),__name(QuestionView,"QuestionView"),Ft(),Ft(),zt(),cC(),Ft(),rr();var bT=/\[([^\]]+)\]/g;function BracketWrap({children:e,color:t,bold:n=!1}){return G.createElement(G.Fragment,null,G.createElement(Z,{color:$n.DIMMEST,bold:n},"["),"string"==typeof e?G.createElement(Z,{color:t,bold:n},e):e,G.createElement(Z,{color:$n.DIMMEST,bold:n},"]"))}function BracketedText({text:e,color:t,bold:n=!1,wrap:r}){const s=Y(()=>{const t=[];let n=0;for(const r of e.matchAll(bT)){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=Y(()=>s.map((e,r)=>"bracket"===e.type?G.createElement(BracketWrap,{key:`bracket-${r}`,color:t,bold:n},e.value):e.value),[s,t,n]);return G.createElement(Z,{color:t,bold:n,wrap:r},o)}__name(BracketWrap,"BracketWrap"),__name(BracketedText,"BracketedText"),rr(),Ft(),Uw(),Sv(),an(),os(),Cr(),rr(),Ft(),rr();var ET=class extends rt{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"+ie.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}},vT=new nt;vT.setOptions({renderer:new ET({strong:ie.bold,em:ie.italic,del:ie.dim.strikethrough,codespan:ie.hex(Jn.CODE),code:ie.hex(Jn.CODE),heading:ie.bold,firstHeading:ie.bold.hex(Jn.HEADING).underline,link:ie.hex($n.CYAN),href:ie.hex($n.CYAN).underline,blockquote:ie.hex($n.GRAY).italic,table:ie.reset,tableOptions:{style:{head:[$n.CYAN],border:[$n.GRAY]}},hr:ie.reset,paragraph:ie.reset,html:ie.hex($n.GRAY),showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var CT=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const s=Y(()=>{if(!e)return"";const t=[],n=e.replace(CT,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=vT.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 G.createElement(Z,{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?"│":uk).join("\n")}__name(Markdown,"Markdown"),Ft(),__name(buildTreeConnectors,"buildTreeConnectors");var kT=" │ ";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?qn.REMOVED_HIGHLIGHT_BG:qn.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(G.createElement(Z,{key:l,backgroundColor:r,dimColor:n},a)):s.push(G.createElement(Z,{key:l,color:$n.WHITE,dimColor:n},a))}return s}function renderContextLine({line:e,lineNum:t,lineNumWidth:n,dimDiff:r,nodeKey:s}){return G.createElement(X,{key:s,width:"100%"},G.createElement(Z,{color:qn.LINE_NUM,dimColor:r}," "+t.toString().padStart(n)),G.createElement(Z,{color:qn.LINE_NUM,dimColor:r},kT),G.createElement(Z,{color:$n.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(G.createElement(X,{key:"sep-"+o.nodeKey++},G.createElement(Z,{color:qn.LINE_NUM,dimColor:s}," ".repeat(r+1)),G.createElement(Z,{color:qn.LINE_NUM,dimColor:s},kT),G.createElement(Z,{color:qn.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=tt.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 p=u.reduce((e,t)=>e+(t.added?0:t.count||1),0),g=u.reduce((e,t)=>e+(t.removed?0:t.count||1),0),h=Math.max(3,(i+p-1).toString().length,(i+g-1).toString().length),f=groupAdjacentChanges(u),y=[],w={oldLineNum:i,newLineNum:i,nodeKey:0};for(let e=0;e<f.length;e++){const t=f[e];if("context"===t.type){const n=t.contextLines,r=e>0&&"change"===f[e-1].type,s=e<f.length-1&&"change"===f[e+1].type;if(!r&&!s){w.oldLineNum+=n.length,w.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;y.push(...renderContextGroup({lines:n,leadCount:o,trailCount:i,lineNumWidth:h,dimDiff:a,counters:w}));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=tt.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);y.push(G.createElement(X,{key:"rm-"+w.nodeKey++,width:"100%",backgroundColor:qn.REMOVED_BG},G.createElement(Z,{color:qn.REMOVED_TEXT,dimColor:a}," "+w.oldLineNum.toString().padStart(h)),G.createElement(Z,{color:qn.LINE_NUM,dimColor:a},kT),G.createElement(Z,{color:qn.REMOVED_TEXT,dimColor:a},"- "),t?renderWordSegments({wordChanges:t,type:"removed",dimDiff:a}):G.createElement(Z,{color:qn.REMOVED_TEXT,dimColor:a},n[e].replace(/\s/g," ")))),w.oldLineNum++}for(let e=0;e<r.length;e++){const t=i.get(e);y.push(G.createElement(X,{key:"add-"+w.nodeKey++,width:"100%",backgroundColor:qn.ADDED_BG},G.createElement(Z,{color:qn.ADDED_TEXT,dimColor:a}," "+w.newLineNum.toString().padStart(h)),G.createElement(Z,{color:qn.LINE_NUM,dimColor:a},kT),G.createElement(Z,{color:qn.ADDED_TEXT,dimColor:a},"+ "),t?renderWordSegments({wordChanges:t,type:"added",dimDiff:a}):G.createElement(Z,{color:qn.ADDED_TEXT,dimColor:a},r[e].replace(/\s/g," ")))),w.newLineNum++}}const S=void 0!==l&&y.length>l,E=S?y.slice(0,l):y;return{diffContent:G.createElement(X,{flexDirection:"column"},s&&!r&&(d>0||m>0)&&G.createElement(Z,{color:$n.GRAY},"Updated"," ",G.createElement(Z,{color:$n.WHITE,bold:!0},n)," ","with"," ",d>0&&G.createElement(G.Fragment,null,G.createElement(Z,{color:zn.SUCCESS},d)," ","addition",1!==d?"s":"",m>0?" and ":""),m>0&&G.createElement(G.Fragment,null,G.createElement(Z,{color:zn.ERROR},m)," ","removal",1!==m?"s":"")),r&&G.createElement(Z,{color:$n.RED},"Rejected update to",G.createElement(Z,{color:$n.RED},` ${n}`)),G.createElement(X,{flexDirection:"column",marginLeft:o,marginRight:o+4,width:(process.stdout.columns||80)-2*o-8},E)),isTruncated:S,totalLines:y.length}}function formatTodosForDisplay(e){const t=fv(e);return t?G.createElement(X,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?ve.checkboxOn:ve.checkboxOff;let r,s=!1;switch(e.status){case"completed":r=zn.SUCCESS,s=!0;break;case"in_progress":r=zn.IN_PROGRESS;break;default:r=$n.WHITE}return G.createElement(X,{key:e.id||t,flexDirection:"row"},G.createElement(X,{width:2},G.createElement(Z,{color:r},n)),G.createElement(Z,{color:r,bold:"in_progress"===e.status,strikethrough:s},e.content))})):G.createElement(Z,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 G.createElement(BracketWrap,null,t?e:G.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?G.createElement(Z,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:s}){if(e)return{symbolColor:$n.YELLOW,symbol:ve.arrowRight};if(t)return{symbolColor:$n.RED,symbol:ve.square};if(n)return{symbolColor:Ln,symbol:"✻"};if(r&&s){const e=fv(s),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?zn.SUCCESS:zn.WARNING,symbol:ve.square}}return{symbolColor:Fn.BG,symbol:ve.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 G.createElement(G.Fragment,null,G.createElement(Z,{color:Ln},`Thought for ${e} second${1!==e?"s":""}`," "),!o&&G.createElement(BracketWrap,{color:$n.DIM},`${i}+o to expand`))}if(t)return G.createElement(G.Fragment,null,G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:Dn.BADGE_BG,color:Dn.BADGE_FG,bold:!0},mk)),G.createElement(Z,null," ","Using your taste"," ",n?"package of ":"packages",n&&G.createElement(Z,{bold:!0},n)));let l=r;return"READ[n]"===r&&s&&(l=`READ[${Number(s[1])}]`),G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:Fn.BG,color:Fn.FG,bold:!0},`${dk}${l}${dk}`))}function renderAgentStatus({agentStatus:e,hasError:t,output:n,elapsedSeconds:r,tokensUsed:s}){const o=`${formatTime2(r)} | ${formatTokens(s)}`;return"running"===e?G.createElement(Z,{color:$n.GRAY},"Running (",o,")"):"interrupted"===e||"Interrupted by user"===n?G.createElement(Z,{color:$n.RED,wrap:"wrap"},"Interrupted by user"):"error"===e||t?G.createElement(Z,{color:$n.RED,wrap:"wrap"},n," (",o,")"):G.createElement(G.Fragment,null,G.createElement(Z,{wrap:"wrap"},"Done"),G.createElement(Z,{color:$n.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?zr:Br,maxChars:"Question"===t?1/0:Vr}),l=i&&"Question"!==t;return{text:o,isTruncated:l,remainingLines:a,truncationMsg:l?a>0?G.createElement(BracketedText,{text:`... +${a} lines [${r}+o to expand]`,color:$n.DIM}):G.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:$n.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?G.createElement(G.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:Ur,{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 G.createElement(X,{flexDirection:"column"},a,l&&G.createElement(X,{marginTop:1},G.createElement(BracketedText,{text:`… (${u-Ur} more lines) [${o}+o to expand]`,color:$n.DIM})),r&&s&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.RED,wrap:"wrap"},s)))}function renderWriteFileContent({input:e,metadata:t,expandedOutput:n,expandKey:r}){const s=t.content;if(!s)return G.createElement(Z,{color:$n.GRAY},"Created"," ",G.createElement(Z,{color:$n.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:Wr,l=void 0!==a&&i>a,u=l?o.slice(0,a):o,d=String(i).length;return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.GRAY},"Created"," ",G.createElement(Z,{color:$n.WHITE,bold:!0},e)," ","(",i," line",1!==i?"s":"",")"),G.createElement(X,{marginTop:1,flexDirection:"column"},u.map((e,t)=>G.createElement(X,{key:t,width:"100%",backgroundColor:qn.ADDED_BG},G.createElement(Z,{color:qn.ADDED_TEXT}," "+String(t+1).padStart(d)),G.createElement(Z,{color:qn.LINE_NUM},kT),G.createElement(Z,{color:qn.ADDED_TEXT,wrap:"truncate-end"},e.replace(/\s/g," "))))),l&&void 0!==a&&G.createElement(X,{marginTop:1},G.createElement(BracketedText,{text:`… (${i-a} more lines) [${r}+o to expand]`,color:$n.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:p}){if(e)return formatTodosForDisplay(o);if(t)return i?G.createElement(X,{width:"100%",flexDirection:"column"},G.createElement(Z,null," "),G.createElement(Z,{color:Ln,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 p?G.createElement(X,{columnGap:1},G.createElement(Z,{color:er},uk," "),e):e}if(r&&s&&"content"in s){const e=renderWriteFileContent({input:l,metadata:s,expandedOutput:i,expandKey:m});return p?G.createElement(X,{columnGap:1},G.createElement(Z,{color:er},uk," "),e):e}return p?renderTextWithLongConnector({output:o,name:d,expandedOutput:i,expandKey:m,hasError:u}):G.createElement(X,{width:"100%"},G.createElement(Z,{color:u?$n.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?$n.RED:void 0,u=buildTreeConnectors(o,i);return G.createElement(X,{flexDirection:"column",width:"100%"},G.createElement(X,{columnGap:1,width:"100%"},G.createElement(Z,{color:er},u),G.createElement(Z,{color:l,wrap:"wrap"},o)),i&&G.createElement(X,{columnGap:1},G.createElement(Z,{color:er},uk," "),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("]"),p=!0===o?.isTasteFile,g=o?.tasteCategory,h=!0===o?.permissionDenied,f=!a&&!l&&!p,{name:y}=detectTerminal(),w="iTerm2"===y?"shift":"ctrl",S=!0===o?.isAgent,E=computeDisplayInput({input:t,isAgent:S,isShell:"SHELL"===e,expandedOutput:i}),v=!a&&E&&!p,C=o?.status,k=o?.tokensUsed||0,T="number"==typeof o?.elapsedSeconds?Math.floor(o.elapsedSeconds):0,_=m?parseReadSummaryLine(n):null,x=m?getReadToolInlineSummary({name:e,summaryMatch:_}):null,P=Boolean(n&&!p&&!S&&(!m||s)),{symbolColor:A,symbol:I}=resolveSymbol({isPending:r,hasError:s,isThinking:a,isTodos:l,output:n});return G.createElement(X,null,a&&G.createElement(Z,{color:A},I),G.createElement(X,{flexDirection:"column",marginLeft:a?1:0},G.createElement(X,null,renderToolHeader({isThinking:a,isTasteFile:p,tasteCategory:g,name:e,summaryMatch:_,expandedOutput:i,expandKey:w}),v&&G.createElement(Z,null," ",formatToolInput({input:E,isShell:"SHELL"===e})),renderReadToolInlineSummary(x)),S&&("running"===C||n)&&G.createElement(X,{columnGap:1,marginLeft:f?1:0},f&&G.createElement(Z,{color:er},uk," "),renderAgentStatus({agentStatus:C,hasError:s,output:n,elapsedSeconds:T,tokensUsed:k})),P&&G.createElement(X,{marginLeft:f?1:0},renderOutputContent({isTodos:l,isThinking:a,isEditFile:u,isWriteFile:d,metadata:o,output:n,expandedOutput:i,isPermissionDenied:h,input:t,hasError:s,name:e,expandKey:w,showTreeConnector:f})),r&&!S&&G.createElement(X,{columnGap:1,marginLeft:1},G.createElement(Z,{color:er},uk," "),G.createElement(Z,{color:$n.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 TT=__name(({request:e,onResponse:n,onToggleAutoAccept:r})=>{const[s]=Q(0),[o,i]=Q(1);K(()=>{"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 G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.GRAY,paddingX:1,width:"100%"},G.createElement(X,{marginBottom:1},G.createElement(Z,{bold:!0,color:$n.YELLOW},`${m()} ${"edit"===e.action?d():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&G.createElement(X,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:d(),marginLeft:0,startLine:o}).diffContent),G.createElement(X,{marginBottom:1},G.createElement(Z,{bold:!0},"Do you want to ",u()," ",G.createElement(Z,{color:$n.CYAN},d()),"?")),G.createElement(et,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:s,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.CYAN},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>G.createElement(Z,{color:t?$n.CYAN:$n.WHITE},e.includes("[shift+tab]")?G.createElement(G.Fragment,null,e.split("[shift+tab]")[0],G.createElement(BracketWrap,{color:t?$n.CYAN:$n.WHITE,bold:!0},"shift+tab")):e.includes("(")?G.createElement(G.Fragment,null,e.split("(")[0],G.createElement(Z,{color:$n.GRAY},"(",e.split("(")[1])):e)}))},"PermissionPrompt");Ft(),zt(),rr();var _T=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=Q(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 G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.GRAY,paddingX:1,width:"100%"},G.createElement(X,{marginBottom:1},G.createElement(Z,{bold:!0,color:$n.YELLOW},"Execute Shell Command")),G.createElement(X,{marginBottom:1},G.createElement(Z,{bold:!0,wrap:"wrap"},"Command Code needs to execute ",G.createElement(Z,{color:$n.CYAN},i()),".")),e.workingDirectory&&G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.GRAY},"Working directory: ",e.workingDirectory)),e.description&&G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM,italic:!0},e.description)),G.createElement(et,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:r,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.CYAN},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>G.createElement(Z,{color:t?$n.CYAN:$n.WHITE},e.includes("[shift+tab]")?G.createElement(G.Fragment,null,e.split("[shift+tab]")[0],G.createElement(BracketWrap,{color:t?$n.CYAN:$n.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 xT=H(__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 G.createElement(X,{marginY:1},G.createElement(_T,{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 G.createElement(X,{marginY:1},G.createElement(_T,{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 G.createElement(X,{marginY:1},G.createElement(TT,{request:u,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onToggleAutoAccept:i}))},"PermissionView"));Ft(),IC(),Ft(),Ft(),zt();var PT="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",AT="\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 IT=getMaxLineWidth(PT),NT=getMaxLineWidth(AT),RT=IT+1,$T=NT+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var MT=__name(e=>{const t=e??getTerminalWidth();return t>=RT?PT:t>=$T?AT:DT},"getResponsiveCommandLogo"),DT="⌘ CMD\n",LT="░█▀▀░█▀▄▀█░█▀▄░\n░█░░░█░▀░█░█░█░\n░▀▀▀░▀░░░▀░▀▀░░",OT=getMaxLineWidth(LT),qT=$T,FT=__name(e=>{const t=e??getTerminalWidth();return t>=RT?"full":t>=qT?"compact":"minimal"},"getHeaderLayout");pC(),Ft(),rr();var jT=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:s=0,titleColor:o=$n.GRAY,dividerChar:i="─",dividerColor:a=$n.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*s),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",p=r?` ${r}`:"",g=d.length+m.length+p.length,h=i.repeat(Math.max(0,u-g));return G.createElement(X,{paddingLeft:s,paddingRight:s,marginBottom:1,...l},(t||n)&&G.createElement(Z,{color:a},d),e&&G.createElement(Z,{color:o},m),G.createElement(Z,{color:a},h),r&&G.createElement(Z,{color:$n.DIM},p))},"Divider");IC(),rr(),Ft(),rr();var BT=[{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}],zT=__name(({onComplete:e,onExit:t})=>{const[n,r]=Q(0),[s,o]=Q(!1),i=n>=BT.length;return K(()=>{if(n>=BT.length)return;if(s)return;const e=BT[n],t=setTimeout(()=>{r(e=>Math.min(e+1,BT.length))},e.duration);return()=>clearTimeout(t)},[n,s]),ne((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,BT.length))}),G.createElement(X,{flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{bold:!0},"Meet Your Coding Taste")),G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"Command Code learns your coding style as you work.")),G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"Here's how your preferences evolve in real-time:")),G.createElement(X,{flexDirection:"column",marginY:1},BT.slice(0,n).map((e,t)=>"user"===e.type?G.createElement(X,{key:t},G.createElement(Z,null,ve.pointer," ",e.text)):G.createElement(X,{key:t,flexDirection:"column",marginBottom:1,marginLeft:1},G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"⎿ "),G.createElement(Z,{color:Dn.TEXT},e.text)),e.details&&G.createElement(X,{marginLeft:3},G.createElement(Z,{color:$n.DIM},"Saved(",e.details,")"))))),i?G.createElement(X,{flexDirection:"column",marginY:1},G.createElement(X,null,G.createElement(Z,{bold:!0,color:Dn.TEXT},"Demo Complete!")),G.createElement(X,null,G.createElement(Z,null,"Command Code will now use these preferences to generate")),G.createElement(X,null,G.createElement(Z,null,"better suggestions tailored to your coding style. The")),G.createElement(X,null,G.createElement(Z,null,"more you code, the smarter it gets.")),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press Enter to get started →"))):G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(s?" (paused)":""))))},"TasteDemoComponent"),UT=__name(({onClose:e,onExit:t})=>{const[n,r]=Q(dC.getEvents()),[s,o]=Q(0);ne((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),K(()=>{const e=__name(()=>{r(dC.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return dC.on("new-event",e),dC.on("cleared",t),()=>{dC.off("new-event",e),dC.off("cleared",t)}},[]),K(()=>{const e=__name(()=>{PC(),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=Y(()=>(process.stdout.rows??24)-1,[s]);return G.createElement(X,{flexDirection:"column",width:"100%",height:d,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(st,{name:"vice"},G.createElement(Z,null,MT()))),G.createElement(jT,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),G.createElement(X,{flexDirection:"column"},0===n.length?G.createElement(X,{flexDirection:"column"},G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(X,null,G.createElement(Z,null,"Start using Command Code and it will begin recording your coding taste.")),G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"Your preferences, patterns, and style will appear here in real-time."))),G.createElement(oe,{count:2}),G.createElement(jT,{title:"DEMO",titleColor:"white",subPrefix:!0}),G.createElement(zT,{onComplete:()=>{e()},onExit:t})):G.createElement(X,{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 G.createElement(X,{key:e.id,marginBottom:1},G.createElement(X,{flexDirection:"column"},G.createElement(X,null,G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:Dn.BADGE_BG,color:Dn.BADGE_FG,bold:!0},`${dk}${n}${dk}`)),o?G.createElement(Z,{color:$n.DIM}," ","(",o.fullPath,")"):e.details?G.createElement(Z,{color:$n.DIM}," ","(",e.details,")"):null),G.createElement(X,{marginLeft:1},G.createElement(Z,{color:$n.DIM},"⎿"," "),o?G.createElement(G.Fragment,null,G.createElement(Z,null," ",o.category," ","package ("),G.createElement(Z,{color:$n.DIM},o.oldPath),G.createElement(Z,null," ",ve.arrowRight," ",o.newPath),G.createElement(Z,null,")")):i?G.createElement(G.Fragment,null,G.createElement(Z,null," ",i.text," ","("),G.createElement(Z,{color:$n.DIM},"confidence:"," "),G.createElement(Z,{color:$n.DIM},i.oldPercent,"%"),G.createElement(Z,null," ",ve.arrowRight," "),G.createElement(Z,{color:i.diff>0?$n.GREEN:$n.RED},i.newPercent,"%"),G.createElement(Z,null,")")):G.createElement(G.Fragment,null,G.createElement(Z,null," ",r),s&&G.createElement(Z,{color:$n.DIM}," ","(",s,")")))))}return G.createElement(X,{key:e.id,marginBottom:1},G.createElement(Z,{color:$n.DIM},ve.pointerSmall," ",e.message))}))))},"LearningFeedFull");function LearningView({setShowLearningFeed:e,setStaticKey:t,onExit:n}){return G.createElement(UT,{onClose:()=>{PC(),e(!1),t(e=>e+1)},onExit:n})}__name(LearningView,"LearningView"),Ft(),rr(),Ft(),rr(),IC(),Sr();var WT=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,s]=Q(!1),[o,i]=Q(!0);K(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();s(e)}catch(e){}finally{i(!1)}},"loadSettings")()},[]),ne((t,n)=>{if(!n.return&&" "!==t)return n.escape?(PC(),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?G.createElement(X,{key:n,borderStyle:"single",borderColor:$n.BLUE,padding:1,flexDirection:"column"},G.createElement(Z,{color:$n.BLUE,bold:!0},"Taste Settings"),G.createElement(Z,{color:$n.DIM},"Loading configuration...")):G.createElement(X,{key:n,borderStyle:"single",borderColor:$n.GRAY,padding:1,flexDirection:"column"},G.createElement(Z,{bold:!0},"Taste Learning"),G.createElement(Z,{color:$n.DIM},"Configure taste learning preferences for this project"),G.createElement(X,{marginTop:1}),G.createElement(X,{justifyContent:"space-between"},G.createElement(Z,null,"Taste learning",G.createElement(Z,{color:$n.DIM}," - Learn from your interactions")),G.createElement(Z,{color:r?$n.GREEN:$n.GRAY},r?"enabled":"disabled")),G.createElement(X,{marginTop:1}),G.createElement(Z,{color:$n.DIM},"Taste data stored in .commandcode/taste/taste.md"),G.createElement(Z,{color:$n.DIM},"Enter/Space to toggle • Esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,setShowTasteConfig:t,loadTasteStatus:n}){return G.createElement(G.Fragment,null,G.createElement(mT,{staticKey:e}),G.createElement(X,{flexDirection:"column",width:"100%"},G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"Press Esc to return to conversation")),G.createElement(WT,{onClose:()=>t(!1),onSettingsChange:n,staticKey:e})))}__name(TasteConfigView,"TasteConfigView"),Ft(),Ft(),zt(),Ow(),IC(),rr();var GT=__name(e=>Math.ceil(e.length/4),"estimateTokens"),HT=__name(({onClose:e})=>{const[t,n]=Q([]),[r,s]=Q(!0),[o,i]=Q(null),[a,l]=Q(0);K(()=>{__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],p=__name(async t=>{try{await ot([{file:t.filePath,line:1}]),PC(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?i(g()):i(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelectSkill");ne((t,n)=>{if(n.escape)return PC(),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&&p(e)}});const g=__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?G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(Z,{color:Mn,bold:!0},"Agent Skills"),G.createElement(Z,{color:$n.DIM},"Loading skills...")):o?G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(Z,{color:$n.RED,bold:!0},"Agent Skills"),G.createElement(Z,{color:$n.DIM},o),G.createElement(X,{marginTop:1}),G.createElement(Z,{color:$n.DIM},"Press ",G.createElement(Z,{bold:!0},"Esc")," to close")):0===t.length?G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(Z,{color:Mn,bold:!0},"Agent Skills"),G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"No skills found")),G.createElement(Z,{color:$n.DIM},"Create skills in:"),G.createElement(Z,{color:$n.DIM}," ","~/",".commandcode","/","skills","/ (user)"),G.createElement(Z,{color:$n.DIM}," ",".commandcode","/","skills","/ (project)"),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press ",G.createElement(Z,{bold:!0},"Esc")," to close"))):G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(X,null,G.createElement(Z,{color:Mn,bold:!0},"Skills"," "),G.createElement(Z,{color:$n.DIM},m.length," skills")),u.length>0&&G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(X,null,G.createElement(Z,{color:Wn,bold:!0},"Project skills"," "),G.createElement(Z,{color:Wn},"(",".commandcode","/","skills",")")),u.map((e,t)=>{const n=a===t;return G.createElement(X,{key:e.value},G.createElement(Z,{color:n?$n.GREEN:$n.WHITE},e.label),G.createElement(Z,{color:$n.DIM}," · ~",GT(e.description)," description tokens"))})),d.length>0&&G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(X,null,G.createElement(Z,{color:Wn,bold:!0},"User skills"," "),G.createElement(Z,{color:Wn},"(~/",".commandcode","/","skills",")")),d.map((e,t)=>{const n=a===u.length+t;return G.createElement(X,{key:e.value},G.createElement(Z,{color:n?$n.GREEN:$n.WHITE},e.label),G.createElement(Z,{color:$n.DIM}," · ~",GT(e.description)," description tokens"))})),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(Z,{dimColor:!0},"Add skills: ",G.createElement(Z,{color:$n.CYAN},"cmd skills add ","<owner/repo>")),G.createElement(Z,{color:$n.DIM},"Press ",G.createElement(Z,{bold:!0},"Esc")," to close")))},"SkillsConfig");function SkillsConfigView({staticKey:e,setShowSkillsConfig:t}){return G.createElement(G.Fragment,null,G.createElement(mT,{staticKey:e}),G.createElement(X,{flexDirection:"column",width:"100%"},G.createElement(HT,{onClose:()=>t(!1),staticKey:e})))}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_use"===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:Dt.TIER_1_THRESHOLD,description:`Prune to last ${Dt.TIER_1_KEEP_COUNT} tool calls`},{tier:2,threshold:Dt.TIER_2_THRESHOLD,description:`Prune to last ${Dt.TIER_2_KEEP_COUNT} tool calls`},{tier:3,threshold:Dt.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:Dt.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 tC){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 nC){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=Ov,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}),p=collectBuiltInTools(),g=collectMcpTools(),[h,f,y]=await Promise.all([collectSkillItems(),collectAgentItems(),collectMemoryItems()]),w=sumTokens(p),S=sumTokens(g),E=w+S+sumTokens(h)+sumTokens(f)+sumTokens(y),v=t>0,C=v?t:m+E,k=!v&&s.length>0,T=Math.min(C/n*100,100),_=Math.max(0,n-C),x=Math.max(0,C-m-E),P=[];if(C>0){m>0&&P.push({name:"Conversation",tokens:m,percentage:Math.round(m/C*100),detail:`${o.user+o.assistant} messages`}),x>0&&P.push({name:"System prompt",tokens:x,percentage:Math.round(x/C*100),detail:"identity, taste, skills"});const e=w+S;if(e>0){const t=p.length,n=g.length,r=n>0?`${t} built-in + ${n} MCP`:`${t} built-in`;P.push({name:"Tool schemas",tokens:e,percentage:Math.round(e/C*100),detail:r})}}P.sort((e,t)=>t.tokens-e.tokens);const A=s.length>0?s[0]?.meta.timestamp??null:null;return{tokensUsed:C,tokenLimit:n,percentage:T,tokensRemaining:_,isEstimated:k,model:r,breakdown:P,autoCompact:buildAutoCompactStatus({tokensUsed:C,tokenLimit:n}),stats:{messageCount:s.length,userMessages:o.user,assistantMessages:o.assistant,toolCalls:i.calls,toolResults:i.results,imageCount:a,compactionCount:d,sessionStartTime:A},compactions:l,tips:generateTips({percentage:T,conversationTokens:m,totalTokens:C,mcpToolCount:g.length,messageCount:s.length,imageCount:a})}}function useTerminalWidth(){const{stdout:e}=te(),[t,n]=Q(()=>e.columns??80);return K(()=>{const t=__name(()=>n(e.columns??80),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}function getLayoutSizes({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 getUsageColor(e){return e>=80?$n.RED:e>=50?$n.YELLOW:$n.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)}}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 G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(X,{marginBottom:0},G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:$n.BLUE,color:"#f4f4f4",bold:!0},`${dk}CONTEXT${dk}`)),G.createElement(Z,null," "),G.createElement(Z,{color:$n.GRAY},e.model)),G.createElement(X,null,G.createElement(Z,{color:n},r.filled),G.createElement(Z,{color:Wn},r.empty),G.createElement(Z,{bold:!0,color:n},` ${e.percentage.toFixed(1)}%`)),G.createElement(X,null,G.createElement(Z,null,formatTokens(e.tokensUsed)),G.createElement(Z,{color:$n.GRAY},` / ${formatTokens(e.tokenLimit)}`),G.createElement(Z,{color:$n.DIM}," · "),G.createElement(Z,{color:n},formatTokens(e.tokensRemaining)),G.createElement(Z,{color:$n.GRAY}," remaining"),e.isEstimated&&G.createElement(Z,{color:$n.DIM}," (estimated)")),G.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 G.createElement(X,null,G.createElement(Z,null,e.name.padEnd(n)),s&&G.createElement(G.Fragment,null,G.createElement(Z,{color:$n.CYAN},a),G.createElement(Z,{color:Wn},l)),G.createElement(Z,{bold:!0},` ${formatTokens(e.tokens)}`),G.createElement(Z,{color:$n.GRAY},` ${e.percentage}%`),o&&e.detail&&G.createElement(Z,{color:$n.DIM},` ${e.detail}`))}function ContextBreakdown({analysis:e,labelWidth:t,breakdownBarWidth:n,showBreakdownBars:r,showBreakdownDetail:s}){return 0===e.breakdown.length?null:G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{color:Wn,bold:!0},"Breakdown"),e.breakdown.map(o=>G.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?$n.RED:n<=25?$n.YELLOW:$n.GRAY;return G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"Full summarization"),G.createElement(Z,{color:r},` ${n}% away`))}function ContextSession({analysis:e,labelWidth:t}){return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Wn,bold:!0},"Session"),G.createElement(X,null,G.createElement(Z,null,"Messages".padEnd(t)),G.createElement(Z,{color:$n.GRAY},`${e.stats.messageCount} (${e.stats.userMessages} user, ${e.stats.assistantMessages} assistant)`)),G.createElement(X,null,G.createElement(Z,null,"Tool calls".padEnd(t)),G.createElement(Z,{color:$n.GRAY},`${e.stats.toolCalls} calls · ${e.stats.toolResults} results`)),e.stats.imageCount>0&&G.createElement(X,null,G.createElement(Z,null,"Images".padEnd(t)),G.createElement(Z,{color:$n.GRAY},`${e.stats.imageCount}`)),G.createElement(X,null,G.createElement(Z,null,"Duration".padEnd(t)),G.createElement(Z,{color:$n.GRAY},formatDuration(e.stats.sessionStartTime))))}function ContextTips({tips:e}){return 0===e.length?null:G.createElement(X,{flexDirection:"column"},e.map(e=>G.createElement(X,{key:e},G.createElement(Z,{color:$n.CYAN},ve.pointer),G.createElement(Z,{color:$n.GRAY}," ",e))))}function ContextHints(){return G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(X,null,G.createElement(Z,{color:$n.GRAY},">"," "),G.createElement(Z,{color:$n.GRAY},"Auto-compact kicks in when context reaches its limit")),G.createElement(X,null,G.createElement(Z,{color:$n.GRAY},">"," "),G.createElement(Z,{color:$n.GRAY},"Run /compact to manually summarize your conversation and free up context")))}function ContextMessage({analysis:e}){const t=getLayoutSizes({terminalWidth:useTerminalWidth()});return G.createElement(X,{flexDirection:"column",paddingTop:1},G.createElement(ContextProgress,{analysis:e,progressBarWidth:t.progressBarWidth}),G.createElement(ContextBreakdown,{analysis:e,labelWidth:t.labelWidth,breakdownBarWidth:t.breakdownBarWidth,showBreakdownBars:t.showBreakdownBars,showBreakdownDetail:t.showBreakdownDetail}),G.createElement(ContextSession,{analysis:e,labelWidth:t.labelWidth}),G.createElement(ContextTips,{tips:e.tips}),G.createElement(ContextHints,null))}function ContextConfigView({staticKey:e,contextEngineRef:t,setShowContextView:n,setInput:r}){const[s,o]=Q(null),[i,a]=Q(null);return K(()=>{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]),ne((e,t)=>{t.escape&&(PC(),r(""),n(!1))}),G.createElement(G.Fragment,null,G.createElement(mT,{staticKey:e}),G.createElement(X,{flexDirection:"column",width:"100%"},i?G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Mn,bold:!0},"Context"),G.createElement(Z,{color:$n.DIM},i)):s?G.createElement(ContextMessage,{analysis:s}):G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Mn,bold:!0},"Context"),G.createElement(Z,{color:$n.DIM},"Loading context analysis...")),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press Esc to return to conversation"))))}__name(SkillsConfigView,"SkillsConfigView"),Ft(),Ft(),zt(),IE(),LE(),$w(),lC(),Aw(),Bv(),Sr(),__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"),IC(),Ft(),rr(),Ft(),__name(useTerminalWidth,"useTerminalWidth"),Cr(),__name(getLayoutSizes,"getLayoutSizes"),__name(getUsageColor,"getUsageColor"),__name(buildProgressBar,"buildProgressBar"),__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"),rr(),__name(ContextConfigView,"ContextConfigView"),Ft(),Ft(),zt(),fs(),LE(),$w(),$r(),vr(),Sr();var QT="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=>{$("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(!v(e))return!1;try{return(await j(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=v(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=Wk(f.platform()),t=sT(),n=oT(),r=iT()}catch{e="Unknown",t="Unknown",n="Unknown",r="N/A"}return{cwd:process.cwd(),os:e,arch:f.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:f.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"),Ft(),zt(),yv(),rr(),Is(),__name(formatCountValue,"formatCountValue"),__name(formatSystemValue,"formatSystemValue");var VT=__name(({label:e,value:t,valueColor:n,dimValue:r})=>G.createElement(X,null,G.createElement(Z,{dimColor:!0},`${e}:`.padEnd(14)),r?G.createElement(Z,{dimColor:!0},t):G.createElement(Z,{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?ve.tick:ve.cross,a=t.auth.authenticated?$n.WHITE:zn.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 G.createElement(X,{flexDirection:"column",paddingX:0},G.createElement(X,null,G.createElement(Z,{color:Mn,bold:!0},"Command Code"," "),G.createElement(Z,{dimColor:!0},n)),G.createElement(X,null,G.createElement(Z,{dimColor:!0},"Visit "),G.createElement(Ts,{url:QT,text:QT,color:$n.CYAN}),G.createElement(Z,{dimColor:!0}," for usage and billing")),G.createElement(X,{marginTop:1},G.createElement(Z,{dimColor:!0},"Account:".padEnd(14)),t.auth.authenticated&&t.auth.username?G.createElement(G.Fragment,null,G.createElement(Ts,{url:`https://commandcode.ai/${t.auth.username}/`,text:t.auth.username,color:$n.CYAN}),G.createElement(Z,{color:a}," ",i)):t.auth.authenticated?G.createElement(G.Fragment,null,G.createElement(Z,null,"Authenticated"),G.createElement(Z,{color:a}," ",i)):G.createElement(G.Fragment,null,G.createElement(Z,{color:zn.WARNING},"Not signed in"),G.createElement(Z,{color:a}," ",i),G.createElement(Z,{dimColor:!0}," — run "),G.createElement(Z,{bold:!0},"/login"))),G.createElement(VT,{label:"Model",value:r}),G.createElement(VT,{label:"Branch",value:s,dimValue:!t.git.branch}),o?G.createElement(VT,{label:"Worktree",value:o}):null,t.git.remoteUrl?G.createElement(X,null,G.createElement(Z,{dimColor:!0},"Repository:".padEnd(14)),G.createElement(Ts,{url:t.git.remoteHttpUrl||`https://github.com/${t.git.remoteUrl}`,text:t.git.remoteUrl,color:$n.CYAN}),t.pr?G.createElement(G.Fragment,null,G.createElement(Z,{dimColor:!0}," · "),G.createElement(Ts,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?$n.CYAN:$n.GRAY}),G.createElement(Z,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null):t.pr?G.createElement(X,null,G.createElement(Z,{dimColor:!0},"Pull Request:".padEnd(14)),G.createElement(Ts,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?$n.CYAN:$n.GRAY}),G.createElement(Z,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null,G.createElement(VT,{label:"Taste",value:d,dimValue:!t.taste.fileExists}),G.createElement(VT,{label:"Directory",value:toRelativePath(t.system.cwd)}),G.createElement(VT,{label:"Skills",value:formatCountValue(t.skillsAgents.personalSkills,t.skillsAgents.projectSkills),dimValue:0===l}),G.createElement(VT,{label:"Agents",value:formatCountValue(t.skillsAgents.personalAgents,t.skillsAgents.projectAgents),dimValue:0===u}),G.createElement(VT,{label:"System",value:formatSystemValue({system:t.system})}),t.system.proxy?G.createElement(VT,{label:"Proxy",value:t.system.proxy}):null)}function StatusConfigView({staticKey:e,setShowStatusView:t,setInput:n}){const[r,s]=Q({phase:"loading"});return K(()=>{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}},[]),ne((e,r)=>{r.escape&&(n(""),t(!1))}),G.createElement(G.Fragment,null,G.createElement(mT,{staticKey:e}),G.createElement(X,{flexDirection:"column",width:"100%"},"ready"===r.phase?G.createElement(StatusMessage,{statusData:r.data}):"error"===r.phase?G.createElement(Z,{dimColor:!0},"Could not load status: ",r.message):G.createElement(Z,{dimColor:!0},"Gathering status…"),G.createElement(X,{marginTop:1},G.createElement(Z,{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 S.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"),Ft(),Ft(),Qt(),Ft(),Qt(),__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"),rr(),ar();var KT=__name(({onClose:e})=>{const[t,n]=Q(""),[r,s]=Q(null),[o,i]=Q([]),[a,l]=Q(getAdditionalDirectories()),[u,d]=Q({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,p]=Q(0);K(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),p(0)},[t]),K(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{s(null)},5e3);return()=>clearTimeout(e)},[r]);const g=__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"),h=__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");ne((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&o[u.suggestionIndex]?void g(o[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])h(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}))}}}),K(()=>{"suggestions"===u.zone&&p(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:o.length}))},[u,o.length]),K(()=>{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 f=o.slice(m,m+8),y=getFooterText({focusZone:u.zone});return G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.CYAN,paddingX:1,paddingY:0},G.createElement(Z,{bold:!0,color:$n.CYAN},"Add directory to workspace"),G.createElement(Z,{color:$n.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(Z,{color:$n.GRAY},"Added directories"),0===a.length?G.createElement(Z,{color:$n.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return G.createElement(Z,{key:e,color:n?$n.YELLOW:$n.GREEN,bold:n},n?` ${ve.pointer} `:" ",formatDirectoryForDisplay(e))})),G.createElement(X,{marginTop:1},G.createElement(Z,{bold:!0,color:$n.WHITE},"Path")),G.createElement(X,null,G.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?ve.pointer:" "} `,prefixColor:"input"===u.zone?$n.CYAN:$n.GRAY,onChange:e=>{n(e),s(null)},onSubmit:g})),!t&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:{error:$n.RED,warning:$n.YELLOW,success:$n.GREEN}[r.tone]},r.text)),o.length>0&&G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(Z,{color:$n.GRAY},"Suggestions"),f.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return G.createElement(Z,{key:e,color:r?$n.CYAN:$n.GRAY,bold:r},r?` ${ve.pointer} `:" ",e)})),G.createElement(X,{marginTop:1},G.createElement(BracketedText,{text:y,color:$n.DIM})))},"AddDirModal");Ft(),Ft(),zt(),Ft(),Ft(),zt(),lC(),rr();var YT=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),JT=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),XT=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[s,o]=Q("idle"),[i,a]=Q(""),l=[...tC.map(e=>e.name),...nC.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?YT():JT();await D.mkdir(r,{recursive:!0});const s=`${e.agentType}.md`,o=t.join(r,s),i=Array.from(e.selectedTools).map(e=>oC[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 D.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");ne((e,t)=>{r||!t.return||"idle"!==s&&"error"!==s||u()});const d=Array.from(e.selectedTools).map(e=>oC[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return G.createElement(X,{flexDirection:"column",gap:1},G.createElement(X,{flexDirection:"column"},G.createElement(X,{gap:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"Name:"),G.createElement(Z,{color:$n.GRAY},e.agentType)),G.createElement(X,{gap:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"Location:"),G.createElement(Z,{color:$n.GRAY},m)),G.createElement(X,{gap:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"Tools:"),G.createElement(Z,{color:$n.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),G.createElement(X,{gap:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"Description"),G.createElement(Z,{color:$n.GRAY},"(Tells ","Command Code"," when to use this agent):")),G.createElement(Z,{color:$n.GRAY},e.ccToolDefinition),G.createElement(X,{gap:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"System Prompt:")),G.createElement(Z,{color:$n.GRAY},e.sysPrompt),!r&&G.createElement(X,{marginTop:1},"idle"===s&&G.createElement(X,{gap:1},G.createElement(Z,{color:$n.GREEN,dimColor:!0},"Press"),G.createElement(Z,{color:$n.GREEN,bold:!0},"Enter"),G.createElement(Z,{color:$n.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===s&&G.createElement(Z,{color:$n.YELLOW},"Saving agent..."),"saved"===s&&G.createElement(Z,{color:$n.GREEN},ve.tick," ",i),"error"===s&&G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.RED},ve.cross," Error: ",i),G.createElement(Z,{color:$n.GRAY},"Press Enter to retry"))))},"AgentSummary");lC(),rr();var ZT=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[s,o]=Q("menu"),i=[...tC.map(e=>e.name),...nC.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=>iC[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(ne((e,n)=>{n.escape&&("menu"===s?t():o("menu")),n.return&&"view"===s&&o("menu")}),"view"===s)return G.createElement(X,{flexDirection:"column"},G.createElement(XT,{config:l,onSaveComplete:()=>o("menu"),viewOnly:!0}),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY},"Press Enter to go back")));if("edit"===s)return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.YELLOW},"Edit functionality coming soon..."),G.createElement(Z,{color:$n.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 D.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),o("menu")}else o("menu")},"handleDeleteSelect");return G.createElement(X,{flexDirection:"column",gap:1},G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.RED},"Delete agent"),G.createElement(Z,{color:$n.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),G.createElement(X,null,G.createElement(et,{items:r,onSelect:s,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},` ${t}`)})))}return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.WHITE,bold:!0},e.name),G.createElement(X,{marginTop:1},G.createElement(et,{items:u,onSelect:d,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},` ${t}`)})),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");ME(),rr();var e_=__name(({handleSelect:e,createdAgentName:n})=>{const[r,s]=Q([]),[o,i]=Q([]),[a,l]=Q([]),[u,d]=Q(!0),[m,p]=Q(!1),[g,h]=Q(null),[y,w]=Q(!1),S=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),E=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),v=__name(async(e,n)=>{try{p(!1);const r=(await D.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const s=t.join(e,r),o=await D.readFile(s,"utf-8"),{data:i,content:a}=Fe(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");K(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([v(S(),"personal"),v(E(),"project")]),n=RE.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 C=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{C.push({label:e.name,value:e.filePath})}),o.forEach(e=>{C.push({label:e.name,value:e.filePath})});const k=r.length+o.length,T=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...o].find(e=>e.filePath===t.value);e&&(h(e),w(!0))}},"handleAgentSelect");if(u)return G.createElement(Z,{color:$n.GRAY},"Loading agents...");if(y&&g){const e=g.filePath.startsWith("__builtin__:");return G.createElement(ZT,{agent:g,onBack:()=>{w(!1),h(null)},setRevalidateAgent:p,isReadOnly:e})}const _=__name(({isSelected:e,label:t})=>{const n=C.find(e=>e.label===t),s=n?.value||"",i=r[0]?.filePath===s,a=o[0]?.filePath===s;return G.createElement(X,{flexDirection:"column"},i&&r.length>0&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY,bold:!0},"User agents")),a&&o.length>0&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY,bold:!0},"Project agents")),G.createElement(X,null,G.createElement(Z,{color:$n.WHITE},e?">":" "),G.createElement(Z,{color:e?$n.WHITE:$n.GRAY}," ",t)))},"CustomItemComponent");return G.createElement(X,{flexDirection:"column"},G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"Agents"),k>0?G.createElement(Z,{color:$n.GRAY}," ","(",k," agent",k>1?"s":"",")"):G.createElement(Z,{color:$n.GRAY}," (No custom agents)")),n&&G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{color:$n.GREEN,dimColor:!0},"Created agent: ",n)),G.createElement(et,{items:C,onSelect:T,indicatorComponent:()=>null,itemComponent:_}),a.length>0&&G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(Z,{color:$n.GRAY,bold:!0},"Default agents"),a.map(e=>G.createElement(Z,{key:e.filePath,color:$n.GRAY}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(Z,{color:$n.GRAY},"Create specialized subagents that Command Code can delegate to."),G.createElement(Z,{color:$n.GRAY},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Ft(),zt(),rr(),lC(),Ft(),Ft(),zt(),rr();var t_=__name(({onSelect:e})=>G.createElement(et,{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})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},` ${t}`)}),"LocationSelector");Ft(),ar(),zt(),lC(),ur(),hr(),DE(),rr();var n_=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:s,onSysPromptChange:o,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=Q(!1),[p,g]=Q(!1),h=J(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]),f=J(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||p){if(!p||t.isPasteEnd){if(p&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[p,i]);return"agentType"===e?G.createElement(G.Fragment,null,G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(oC).some(e=>Ue(e)===Ue(t))||Object.keys(oC).some(e=>Ue(e)===Ue(t)))&&G.createElement(Z,{color:$n.RED},ve.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Ue(t))&&G.createElement(Z,{color:$n.RED},ve.warning," This name is reserved. Reserved names:"," ",NE.join(", "))),G.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Ue(t);Object.values(oC).some(t=>Ue(t)===e)||Object.keys(oC).some(t=>Ue(t)===e)||isReservedAgentName(e)||a()},onChange:s,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?G.createElement(G.Fragment,null,G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.WHITE},"Enter the system prompt for your agent:"),G.createElement(Z,{color:$n.GRAY},"Be comprehensive for best results.")),G.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:h,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?G.createElement(G.Fragment,null,G.createElement(Z,{color:$n.WHITE},"When should ","Command Code"," use this agent?"),G.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:f,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Ft(),rr();var r_=__name(({onSelect:e})=>G.createElement(et,{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})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},` ${t}`)}),"MethodSelector");Ft(),ar(),Ft(),rr();var s_=["·","○","◇","☆","✧","☆","◇","○","⌘"],o_=[12,5,4,4,4,4,4,5,16],i_=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<o_.length;e++)if(n+=o_[e],t<n)return s_[e];const r=t-58;n=0;for(let e=0;e<i_.length;e++)if(n+=i_[e],r<n)return s_[7-e];return s_[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=__name(e=>{const n=e-(t-5);return n>=0&&n<Xn.length?Xn[n]:Zn},"getCharColor");return G.createElement(Z,null,e.split("").map((e,t)=>G.createElement(Z,{key:t,color:r(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return G.createElement(Z,{color:t??Mn,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 a_=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,s]=Q(0),[o,i]=Q(0),a=V(n);a.current=n;const l=getTerminalWidth();K(()=>{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 G.createElement(X,{width:l,height:1,paddingLeft:0,marginLeft:0},G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:jn.BG,color:jn.FG}," "),G.createElement(Z,{backgroundColor:jn.BG},G.createElement(CMDIcon,{frame:4*r})),G.createElement(ShimmerText,{text:e,offset:u,bg:jn.BG}),G.createElement(Z,{backgroundColor:jn.BG,color:jn.FG}," ")),G.createElement(Z,null," "),d?G.createElement(X,{columnGap:1},G.createElement(Z,{color:$n.DIM},formatTime3(t)),G.createElement(Z,{color:$n.DIM},"•"),G.createElement(Z,{color:$n.GRAY},ve.arrowDown),G.createElement(Z,{color:$n.DIM},formatToken(Math.round(o))),G.createElement(Z,{color:$n.DIM},"•"),G.createElement(X,{columnGap:1},G.createElement(Z,{bold:!0,color:$n.GRAY},"esc"),G.createElement(Z,{color:$n.DIM},"to interrupt"))):m?G.createElement(X,{columnGap:1},G.createElement(Z,{color:$n.DIM},formatToken(Math.round(o)))):G.createElement(G.Fragment,null))},"Status");hr(),ur(),rr();var l_=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:s})=>{const[o,i]=Q(!1),[a,l]=Q(0),[u,d]=Q(0);K(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=J(()=>{0!==e.trim().length&&n()},[e,n]),p=J(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 G.createElement(X,{flexDirection:"column"},r?G.createElement(X,null,G.createElement(CMDIcon,{frame:u}),G.createElement(Z,{color:$n.WHITE},"Generating agent from description...")):G.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:p,onSubmit:m}),s&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.RED},`${ve.warning} ${s}`)))},"RecommendedFlow");Ft(),lC(),rr();var c_=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[s,o]=Q(!1),[i,a]=Q(0),l=Y(()=>[...tC.map(e=>e.name),...nC.map(e=>e.name)],[]),u=Y(()=>[{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=Y(()=>{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]":"[ ]"} ${oC[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),p=m.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return ne((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?p.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=p.length?0:t});else if(l.return||" "===e){const e=p[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)}}}),G.createElement(X,{flexDirection:"column"},m.map((e,t)=>{const n=p.findIndex(t=>t.value===e.value),r=-1!==n&&n===i;if("divider"===e.type)return G.createElement(X,{key:`divider-${t}`},G.createElement(Z,{color:$n.GRAY}," ",e.label));if("spacer"===e.type)return G.createElement(X,{key:`spacer-${t}`,height:1});if("label"===e.type)return G.createElement(X,{key:`label-${t}`},G.createElement(Z,{color:$n.GRAY}," ",e.label));const s="continue"===e.type;return G.createElement(X,{key:`item-${t}`},G.createElement(Z,{color:r?$n.WHITE:$n.GRAY,bold:s&&r},r?">":" "," ",e.label))}),G.createElement(X,{marginTop:1},e.size===l.length&&G.createElement(Z,{color:$n.GRAY},"All tools selected"),e.size>0&&e.size<l.length&&G.createElement(Z,{color:$n.GRAY},e.size," tools selected"),0===e.size&&G.createElement(Z,{color:$n.GRAY},"No tools selected")))},"ToolsSelector");Cr(),bn(),Cs(),bw(),ho(),Sn(),Sr();var u_=__name(({onComplete:e})=>{const[t,n]=Q("location"),[r,s]=Q(!1),[o,i]=Q(null),[a,l]=Q("agentType"),u=Y(()=>[...tC.map(e=>e.name),...nC.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,p]=Q(d()),g=__name(t=>{n("location"),l("agentType"),p(d()),e(t)},"resetToDefaults"),h=__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"),f=__name(e=>{p({...m,location:e}),n("method")},"handleLocationSelect"),y=__name(e=>{p({...m,method:e}),n("configuration")},"handleMethodSelect"),w=__name(async()=>{try{i(null),s(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===_t.ANTHROPIC&&(r=await mn.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const o={[vt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(o[vt.OAUTH_TOKEN]=`Bearer ${r}`);const a=getApiBaseUrl(),l=new Yy({baseUrl:a}),u=await l.post({headers:o,endpoint:Ct.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});p({...m,agentType:Ue(u.agentName),sysPrompt:u.systemPrompt,ccToolDefinition:u.toolDescription}),n("tools")}catch(e){e instanceof to&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?i(cn):i("An error occurred while generating the agent. Please try again.")}finally{s(!1)}},"handleRecommendedSubmit"),S=__name(()=>{p({...m,agentType:Ue(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),E=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),v=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),C=__name(()=>{n("summary")},"handleToolsComplete"),k=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),p({...m,selectedTools:t})},"handleToggleTool"),T=__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)),p({...m,selectedTools:n})},"handleToggleCategory");return G.createElement(X,{flexDirection:"column",gap:1},G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.WHITE,bold:!0},"Create new agent"),G.createElement(Z,{color:$n.GRAY},h())),G.createElement(X,null,"location"===t&&G.createElement(t_,{onSelect:f}),"method"===t&&G.createElement(r_,{onSelect:y}),"configuration"===t&&"recommended"===m.method&&G.createElement(l_,{description:m.recommendedMethodDescription,onChange:e=>p({...m,recommendedMethodDescription:e}),loading:r,errorMessage:o,onSubmit:w}),"configuration"===t&&"manual"===m.method&&G.createElement(X,{flexDirection:"column",gap:1},G.createElement(n_,{step:a,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>p({...m,agentType:e}),onSysPromptChange:e=>p({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>p({...m,ccToolDefinition:e}),onAgentTypeSubmit:S,onSysPromptSubmit:E,onCCToolDefinitionSubmit:v})),"tools"===t&&G.createElement(c_,{selectedTools:m.selectedTools,onToggleTool:k,onToggleCategory:T,onComplete:C}),"summary"===t&&G.createElement(XT,{config:m,onSaveComplete:g})))},"AgentNew");rr();var d_=__name(({onCancel:e})=>{const[t,n]=Q(null),[r,s]=Q(null),o=__name(e=>{n(e.value),s(null)},"handleSelect");return ne((t,n)=>{n.escape&&e()}),G.createElement(X,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:$n.GRAY,borderStyle:"single",flexDirection:"column"},null===t&&G.createElement(e_,{handleSelect:o,createdAgentName:r}),"create_new_agent"===t&&G.createElement(u_,{onComplete:e=>{s(e),n(null)}}))},"AgentsConfig");rr(),Ft(),Sr(),rr();var m_=[{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."}],p_=__name(({onSelect:e,onCancel:t})=>{const[n,r]=Q(null);K(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const s=__name(t=>{e(t.value)},"handleSelect");if(ne((e,n)=>{n.escape&&t()}),null===n)return null;const o=m_.findIndex(e=>e.value===n);return G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(X,null,G.createElement(Z,{color:Mn,bold:!0},"Select a compact mode to compact sessions")),G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"Choose how Command Code handles automatic context compaction.")),G.createElement(et,{items:m_,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.CYAN},e?ve.pointer:" "),itemComponent:({isSelected:e,label:t})=>{const r=m_.find(e=>e.label===t),s=r?.value===n,o=m_.findIndex(e=>e.label===t);return G.createElement(X,{flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{color:e?$n.CYAN:s?$n.GREEN:$n.WHITE},` ${o+1}. ${r?.label??t}`),s&&G.createElement(Z,{color:$n.GREEN}," ",ve.tick)),G.createElement(Z,{color:$n.DIM},` ${r?.description??""}`))}}),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press "),G.createElement(Z,{color:$n.DIM,bold:!0},"Esc"),G.createElement(Z,{color:$n.DIM}," to cancel")))},"CompactModeSelector");Ft(),rr(),Ft(),ar(),zt(),ur(),yn(),Ft();var g_=n(y(),"commandcode-images"),h_={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{v(g_)||C(g_,{recursive:!0});const r=h_[e.mediaType]||".png",s=`image-${t}-${Date.now()}${r}`,o=n(g_,s),i=Buffer.from(e.data,"base64");return k(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=J((e,t)=>{s(t=>[...t,e]),r(t),i()},[s,r,i]),l=V(!1),u=V(""),d=V(null),m=V(""),p=J(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]),g=J(()=>{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 p(e,t)}},500)},[p]);return{handlePaste:J(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 p(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,g(),!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)),g(),!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 p(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,p,g,a]),resetPasteState:J(()=>{l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:J(()=>l.current,[])}}__name(saveTempImage,"saveTempImage"),xn(),Cr(),Ft(),hr(),ur(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),hr(),Ft(),Ft();var f_=["code --wait","cursor --wait","nano"],y_=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return y_.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(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of f_)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var w_=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 w_;t=ensureWaitFlag(t);const r=n(y(),`commandcode-${Date.now()}.md`);return await O(r,e),new Promise((e,n)=>{const s=t.split(" ").filter(e=>e.length>0),o=s[0],i=s.slice(1),a=R(o,[...i,r],{stdio:"inherit"});a.on("close",async()=>{try{const t=await q(r,"utf-8");await F(r),e(t.trimEnd())}catch(e){n(e)}}),a.on("error",async e=>{try{await F(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[s,o]=Q(!1),[i,a]=Q(null),l=J(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 w_?"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=J(()=>{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"),Ft();var S_=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=Q(null),s=V(!1);return K(()=>{if(!t||s.current)return;let e=!0;return s.current=!0,wk().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function loadGitignore(e){const t=it(),r=n(e,".gitignore");if(v(r))try{const e=E(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}rr(),Ft(),rr(),__name(loadGitignore,"loadGitignore");var b_=__name(({onSelectFile:e,onClose:t,searchQuery:i=""})=>{const[a,l]=Q(process.cwd()),[u,d]=Q([]),[m,p]=Q(0),[g,h]=Q(0),f=i.trim()?15:10,y=J((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const o=n(t,e);try{const e=T(o),i=[];return e.forEach(e=>{const a=n(o,e);try{const e=_(a),n=s(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 o=e.split("/"),i=o.pop()||"",a=n(t,o.join("/"));try{const e=T(a),o=[],l=i.toLowerCase();return e.forEach(e=>{const u=e.toLowerCase();if(!i||u.includes(l)){const i=n(a,e);try{const e=_(i),n=s(t,i);if(r.ignores(n))return;o.push({name:n,path:i,isDirectory:e.isDirectory()})}catch{}}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),o.slice(0,50)}catch{}}const o=[],i=e.toLowerCase(),a=__name((e,l=0)=>{if(!(l>8))try{T(e).forEach(u=>{const d=n(e,u);try{const e=_(d),n=s(t,d);if(r.ignores(n))return;const m=n.toLowerCase();(u.toLowerCase().includes(i)||m.includes(i))&&o.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),o.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,p=t.name.split("/").length;return m!==p?m-p:e.name.localeCompare(t.name)}),o.slice(0,50)},[]),w=J(e=>{try{const t=T(e),o=[],i=process.cwd(),a=loadGitignore(i);"/"!==e&&o.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=n(e,t);try{const e=_(r),n=s(i,r);if(a.ignores(n))return;o.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(o),p(0),h(0)}catch{}},[]);K(()=>{if(i.trim()){const e=y(i);d(e),p(0),h(0)}else w(a)},[a,w,i,y]),ne((n,r)=>{if(r.escape)t();else if(r.upArrow)p(e=>{const t=Math.max(0,e-1);return t<g&&h(t),t});else if(r.downArrow)p(e=>{const t=Math.min(u.length-1,e+1);return t>=g+f&&h(t-f+1),t});else{if(r.rightArrow){const e=u[m];if(!e)return;return void(e.isDirectory&&!i.trim()&&l(o(e.path)))}if(r.return){const t=u[m];if(!t)return;return void e(t.path)}}});const S=u.slice(g,g+f);return G.createElement(X,{flexDirection:"column",paddingLeft:1},G.createElement(X,{marginBottom:1,flexDirection:"column"},G.createElement(Z,{color:$n.DIM},i.trim()?`Searching for: "${i}"`:`Files: ${a}`),G.createElement(Z,{color:$n.DIM},i.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===S.length?G.createElement(Z,{color:$n.DIM},i.trim()?`No files found matching "${i}"`:"No files found in this directory"):S.map((e,t)=>{const n=g+t,r=e.name,s=n===m;return G.createElement(Z,{key:e.path,color:s?$n.GREEN:$n.DIM},e.isDirectory?`${r}/`:r)}))},"FileList");Ft(),zt(),vr(),rr(),Ft(),rr();var E_=__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?$n.RED:e>=70?$n.YELLOW:$n.DIM,"getColor"),s=t>=90?6:Math.round(t/100*6),o=6-s,i=ve.square.repeat(s),a=ve.squareLightShade.repeat(o),l=r(t);return G.createElement(X,{paddingRight:3},G.createElement(Z,{color:l},`Context left before auto-compact ${n}% `),G.createElement(Z,{color:l},i),o>0&&G.createElement(Z,{color:$n.DIM},a))},"ContextUsage");Ft(),pC(),os(),rr();var v_=__name(()=>{const[e,t]=Q("continuous learning"),[n,r]=Q(!1),[s,o]=Q(!1),i=V([]),a=V(0),l=V(null),u=V(!1);K(()=>{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 dC.on("new-event",e),()=>{dC.off("new-event",e),l.current&&clearTimeout(l.current)}},[]);const d=` ${n?ve.squareSmallFilled:ve.squareSmall} TASTE`,m=9+e.length+d.length>Yr;let p=e;p=truncateString(m?{text:e,maxChars:Yr}:{text:e,maxChars:Yr-d.length-9-10});const g=s?void 0:$n.DIM;return G.createElement(X,{paddingRight:2},!m&&G.createElement(G.Fragment,null,G.createElement(BracketWrap,{color:$n.DIM},"ctrl+t"),G.createElement(Z,{color:$n.DIM}," ")),G.createElement(Z,{color:g},p),!m&&G.createElement(Z,{color:Dn.TEXT},d))},"LearningFeedMini");Ft(),rr();var C_=__name(({mode:e,pendingExitKey:t})=>t?G.createElement(Z,{color:$n.DIM},"Press Ctrl+C again to exit"):"auto-accept"===e?G.createElement(X,{flexDirection:"row"},G.createElement(Z,{color:Vn},"» accept edits on "),G.createElement(BracketWrap,{color:$n.DIM},"shift+tab")):"plan"===e?G.createElement(X,{flexDirection:"row"},G.createElement(Z,{color:Qn},"plan mode "),G.createElement(BracketWrap,{color:$n.DIM},"shift+tab")):G.createElement(Z,{color:$n.DIM},"? for shortcuts"),"ModeIndicator");Ft(),rr(),Is();var k_=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?$n.DIM:Kn.MERGED;return G.createElement(G.Fragment,null,t&&G.createElement(Z,{color:$n.DIM}," · "),G.createElement(Z,{color:n},"PR "),G.createElement(Ts,{url:e.url,text:`#${e.number}`,color:n}))},"PRLinkBadge"),T_=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?G.createElement(G.Fragment,null,t&&G.createElement(Z,{color:$n.DIM}," · "),G.createElement(Z,{color:"connected"===e.type?$n.GREEN:$n.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),__=__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:p,isBashMode:g,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w})=>{const S=e>=60;return G.createElement(G.Fragment,null,G.createElement(X,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r||l?G.createElement(X,{flexDirection:"row",justifyContent:"space-between",width:e-1},G.createElement(X,{flexDirection:"row",columnGap:0},n&&!l?G.createElement(Z,{color:Un},t):G.createElement(C_,{mode:r,pendingExitKey:l}),!l&&G.createElement(k_,{prInfo:s}),!l&&G.createElement(T_,{indicator:a})),S&&G.createElement(X,{flexDirection:"column",alignItems:"flex-end"},o&&G.createElement(v_,null),i&&G.createElement(E_,{usage:i}))):G.createElement(G.Fragment,null,G.createElement(X,{flexDirection:"row",justifyContent:"space-between",width:e-1},G.createElement(C_,{mode:r}),S&&o&&G.createElement(v_,null)),G.createElement(X,{flexDirection:"row",justifyContent:"space-between",width:e-1},G.createElement(X,{flexDirection:"row",columnGap:0},G.createElement(Z,{color:n?Un:$n.DIM},t),G.createElement(k_,{prInfo:s}),G.createElement(T_,{indicator:a})),S&&i&&G.createElement(E_,{usage:i}))),(u||d||p&&m)&&G.createElement(X,{flexDirection:"row",columnGap:1},u&&G.createElement(Z,null,ve.tick," ","Command Code"," updated:"," ",G.createElement(Z,{color:$n.DIM},"v",u.updatedFrom),G.createElement(Z,{color:$n.DIM}," ",ve.arrowRight," "),G.createElement(Z,null,"v",u.updatedTo)),!u&&d&&G.createElement(Z,{color:$n.YELLOW,dimColor:!0},ve.info," Update available:"," ",d.currentVersion," ",ve.arrowRight," ",d.latestVersion),p&&m&&G.createElement(Z,{color:$n.GREEN,dimColor:!0},ve.bullet," Provider:"," ",getProviderDisplayName(m)))),g&&G.createElement(X,{paddingLeft:2},G.createElement(Z,{color:$n.GREEN},"! for bash mode")),f&&h&&G.createElement(X,{paddingLeft:2},G.createElement(Z,{color:Mn},"SHARED: ",h.url," (copied to clipboard)")),y&&G.createElement(X,{paddingLeft:2},G.createElement(Z,{color:y.includes("NOT SHARED")?$n.RED:Mn},y)),w&&G.createElement(X,{paddingLeft:2},G.createElement(Z,{color:Mn},w)))},"BottomIndicator");Ft(),Iv(),os(),rr();var x_=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=Q([]),[s,o]=Q(0),[i,a]=Q(!0);K(()=>{l()},[]);const l=__name(async()=>{a(!0);const e=await Ev.listSessions();r(e.slice(0,30)),a(!1)},"loadSessions");if(ne((r,i)=>{i.escape?t():i.upArrow?o(e=>Math.max(0,e-1)):i.downArrow?o(e=>Math.min(n.length-1,e+1)):i.return&&n.length>0&&s<n.length&&e(n[s].id)}),i)return G.createElement(X,{flexDirection:"column",paddingLeft:2},G.createElement(Z,{color:$n.GRAY},"Loading sessions..."));if(0===n.length)return G.createElement(X,{flexDirection:"column",paddingLeft:2},G.createElement(Z,{color:$n.GRAY},"No previous sessions found"),G.createElement(Z,{color:$n.DIM},"Press ESC to go back"));const u=__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"),d=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),m=__name(e=>truncateString({text:d(e),maxChars:Kr}),"truncateMessage"),p=__name(e=>e.title?d(e.title):m(e.firstMessage),"getSessionSummary");return G.createElement(X,{flexDirection:"column",paddingLeft:1,width:"100%"},G.createElement(Z,{color:$n.CYAN,bold:!0},"Resume Session"),G.createElement(Z,{color:$n.DIM},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),G.createElement(X,{marginTop:1}),G.createElement(X,{columnGap:2,marginBottom:1},G.createElement(X,{width:5},G.createElement(Z,{color:$n.GRAY}," ")),G.createElement(X,{width:13},G.createElement(Z,{color:$n.GRAY},"Modified")),G.createElement(X,{width:20},G.createElement(Z,{color:$n.GRAY},"Git Branch")),G.createElement(X,{width:11},G.createElement(Z,{color:$n.GRAY},"# Messages")),G.createElement(X,null,G.createElement(Z,{color:$n.GRAY},"Summary"))),G.createElement(X,{columnGap:2},G.createElement(X,{flexDirection:"column",width:5},n.map((e,t)=>G.createElement(Z,{key:`sel-${t}`,color:s===t?$n.WHITE:$n.GRAY},s===t?`${ve.pointer} ${t+1}.`:` ${t+1}.`))),G.createElement(X,{flexDirection:"column",width:13},n.map((e,t)=>G.createElement(Z,{key:`mod-${e.id}`,color:s===t?$n.WHITE:$n.GRAY},u(e.lastModified)))),G.createElement(X,{flexDirection:"column",width:20},n.map((e,t)=>G.createElement(Z,{key:`branch-${e.id}`,color:s===t?$n.WHITE:$n.GRAY,wrap:"truncate-end"},e.gitBranch||"-"))),G.createElement(X,{flexDirection:"column",width:11},n.map((e,t)=>G.createElement(Z,{key:`msg-${e.id}`,color:s===t?$n.WHITE:$n.GRAY},e.messageCount))),G.createElement(X,{flexDirection:"column"},n.map((e,t)=>G.createElement(Z,{key:`summary-${e.id}`,color:s===t?$n.WHITE:$n.GRAY,wrap:"truncate-end"},p(e))))))},"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 G.createElement(Z,null,r?" ":"",t?G.createElement(Z,{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 G.createElement(X,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>G.createElement(X,{key:r,flexDirection:"row"},G.createElement(X,{flexShrink:0,marginRight:1},0===r&&G.createElement(Z,{color:$n.DIM},o)),G.createElement(X,{flexDirection:"row"},e.map((e,r)=>G.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Ft(),rr(),Ft(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),Ms(),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Ft(),Bb();var P_=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,s]=Q(null),[o,i]=Q(!1),a=V(!1),l=V(null),[u,d]=Q(!1),[m,p]=Q("connected"),g=V(null),h=V(null),f=J((e,t)=>{h.current&&(clearTimeout(h.current),h.current=null),p(e),d(!0),void 0!==t&&(h.current=setTimeout(()=>{d(!1)},t))},[]),y=J(()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]),w=J(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new $b,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=g.current;if(null===r?n&&f("connected",3e3):r!==n&&(n?f("connected",2e3):f("disconnected",5e3)),g.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===g.current&&f("disconnected",5e3),g.current=!1,i(!1),s(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[f]);K(()=>{if(!t||n)return;w(!0);const e=setInterval(()=>w(!1),500);return()=>{clearInterval(e),y(),l.current?.disconnect(),l.current=null}},[t,n,w,y]);const S={visible:u,message:"connected"===m?`IDE ${ve.tick}`:"IDE disconnected",type:m};return{context:r,connected:o,refresh:w,connectionIndicator:S}},"useVSCodeContext");Ft();var A_=__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,"</ide-context>");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");Ft();var I_=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),N_=__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"),R_=["","[118;5u","[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 $_=__name(()=>G.createElement(X,{flexDirection:"column",paddingLeft:1},G.createElement(Z,{color:$n.DIM,bold:!0},"Available Shortcuts:"),G.createElement(X,{columnGap:4},G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.DIM},"! for bash mode"),G.createElement(Z,{color:$n.DIM},"/ for commands"),G.createElement(Z,{color:$n.DIM},"@ for file paths"),G.createElement(Z,{color:$n.DIM},"shift + tab to toggle auto-accept")),G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.DIM},"double tap esc to clear input"),G.createElement(Z,{color:$n.DIM},"ctrl + j / shift + ⏎ for newline"),G.createElement(Z,{color:$n.DIM},"ctrl + g to open in editor"),G.createElement(Z,{color:$n.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),M_=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:i,setShowFileList:a,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:m,tasteLearning:p=!1,tasteUsage:g=!1,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w,updateStatus:S,updateFailedInfo:E,currentProvider:v,showProviderInfo:C,permissionMode:k="standard",onToggleAutoAccept:T,hintMessage:_,historyManager:x,pendingExitKey:P=null,onOverlayVisibilityChange:A,onDoubleEscapeEmpty:I,onAltP:N,isProcessing:R=!1,ideContextEnabled:$=!0})=>{const[M,D]=Q(0),[L,O]=Q(!1),[q,F]=Q(!1),[j,B]=Q(!1),[z,U]=Q(!1),[W,H]=Q(""),[ee,re]=Q(!1),se=V(0),oe=V(0),[ie,ae]=Q([]),[le,ce]=Q([]),[ue,de]=Q(-1),[me,pe]=Q(""),ge=V(!1),he=V(!1),fe=V(void 0),[ye,we]=Q(-1),[Se,be]=Q(""),Ee=V(0),{isEditorOpen:Ce,editorError:ke,handleOpenInEditor:Te,clearEditorError:_e}=useExternalEditor({input:e,setInput:n,setInputKey:D,onEditorClose:__name(()=>{ge.current=!1},"onEditorClose")}),{handlePaste:xe,resetPasteState:Pe,isPasting:Ae}=useBracketedPaste({input:e,detectedContent:ie,setInput:n,setDetectedImages:ce,setDetectedContent:ae,incrementInputKey:__name(()=>D(e=>e+1),"incrementInputKey")}),{context:Ie,connected:Ne,refresh:Re,connectionIndicator:$e}=P_({enabled:$,paused:R}),{stdout:Me}=te(),De=Me?.columns??80,{pr:Le}=S_();K(()=>{const e=i||z||ee;A?.(e)},[i,z,ee,A]);const Oe=J(()=>{ce([]),de(-1)},[]),qe=J(()=>{n(""),F(!1),U(!1),H(""),re(!1),ae([]),Oe(),pe(""),Pe(),we(-1),be(""),D(e=>e+1)},[n,Pe,Oe]),Fe=J(()=>{ge.current=!0;const{text:t,cursor:r}=insertTextAt(e,Ee.current,"\n");n(t),fe.current=r,D(e=>e+1),setTimeout(()=>{ge.current=!1},0)},[e,n]);ne(async(t,r)=>{if(-1!==ue&&r.leftArrow)return void de(prevImageIndex({currentIndex:ue,imageCount:le.length}));if(-1!==ue&&r.rightArrow)return void de(nextImageIndex({currentIndex:ue,imageCount:le.length}));if(r.upArrow){if(i||z||ee)return;const t=e.indexOf("\n"),r=-1===t||Ee.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:le.length,selectedImageIndex:ue,historyIndex:ye}))return void de(le.length-1);if(-1!==ue&&de(-1),0!==e.length&&-1===ye&&!r)return;const s=x?.count()??0;if(0===s)return;-1===ye&&be(e);const o=Math.min(ye+1,s-1);return void(o!==ye&&(we(o),n(x?.getAt(o)||""),D(e=>e+1)))}if(r.downArrow){if(i||z||ee)return;if(-1===ye)return;const t=e.lastIndexOf("\n");if(!(-1===t||Ee.current>t))return;const r=ye-1;return we(r),n(-1===r?Se:x?.getAt(r)||""),void D(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void Oe();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return ge.current=!0,void Te();if(getIsExpandToolShortcut(r,t))return ge.current=!0,n(e),D(e=>e+1),void setTimeout(()=>{ge.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Ae()}))return he.current=!0,Fe(),void setTimeout(()=>{he.current=!1},0);if(r.meta&&r.backspace)return void qe();if(r.meta&&"w"===t)return ge.current=!0,void qe();const s=r.ctrl&&"v"===t||R_.includes(t),o=r.meta&&"v"===t;if(s||o){if(s&&"darwin"===process.platform){const t=e;ge.current=!0;const r=await detectClipboardImage();return r&&(ce(e=>[...e,r]),n(t),D(e=>e+1)),void(ge.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return B(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==ue&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:le,index:ue});return ce([...e]),void de(t)}if(r.escape){if(-1!==ue)return void de(-1);if(z)return;if(ee)return re(!1),n(me),void D(e=>e+1);const t=Date.now();return t-se.current<500?(e.length>0?qe():I?.(),se.current=0,oe.current=0):(se.current=t,L||q||(oe.current=t)),O(!1),void F(!1)}L&&(r.backspace||r.delete)&&0===e.length&&O(!1)}});const je=J(async t=>{if(Ce)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void N?.();const s=processBracketedPaste(t);if((s.isPasteStart||s.isPasteEnd||Ae())&&await xe(t))return;if(ge.current)return void(ge.current=!1);-1!==ye&&we(-1);const o=1===t.length,l=t.slice(-1);if(o){if("?"===l&&!L)return O(!0),n(""),void D(e=>e+1);if("!"===l&&!q)return O(!1),F(!0),n(""),void D(e=>e+1)}if("/"!==l||z||"/"!==t||(U(!0),H("")),z&&!t.startsWith("/")&&(U(!1),H("")),z&&t.startsWith("/")){const e=t.substring(1);e.includes(" ")?(U(!1),H("")):H(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)}}L&&(t!==e||t.length<e.length)&&O(!1),ke&&_e(),0===t.length&&(F(!1),U(!1),H(""),re(!1),ae([]),u(""),pe(""),Pe()),n(t)},[L,e,n,i,a,z,q,le,ye,xe,Pe,N,ke,_e,Ce]),Be=J(async()=>{if(Re(),oe.current=0,L)return void O(!1);let n=e.trim();if(!q&&n.startsWith("/")&&d&&"handled"===(await d(n)).status)return x?.add(n),F(!1),U(!1),H(""),Oe(),ae([]),we(-1),void be("");we(-1),be("");let r=[];const s=le.length>0,o=ie.length>0;if(!q&&s&&(r=[...le]),!q&&o){let e=n;ie.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}n.length>0&&x?.add(n),t({input:n,role:q?"bash":"user",images:r,ideContext:Ie?A_(Ie):void 0}),F(!1),U(!1),H(""),Oe(),ae([])},[t,d,L,e,q,le,ie,x,Re,Oe]),ze=J(t=>{const r=s(process.cwd(),t);let o;if(i&&""!==l){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),a(!1),u(""),D(e=>e+1)},[n,a,e,i,l,u]),Ue=J(()=>{a(!1),u("")},[a,u]),We=J(t=>{if("/resume"===t)x?.add(t),we(-1),be(""),pe(e),U(!1),H(""),re(!0),n(""),D(e=>e+1);else{const e=Object.values(jk).includes(t);U(!1),H(""),e?(x?.add(t),we(-1),be(""),n(""),D(e=>e+1),d&&d(t)):(n(t+" "),D(e=>e+1))}},[d,n,e,x]),Ge=J(e=>{U(!1),H(""),n(e+" "),D(e=>e+1)},[n]),He=J(()=>{U(!1),H(""),n(""),we(-1),be(""),D(e=>e+1)},[n]),Qe=J(e=>{re(!1),n(""),pe(""),we(-1),be(""),D(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),Ve=J(()=>{re(!1),n(me),we(-1),be(""),D(e=>e+1)},[me,n]),Ke=J(e=>{Ee.current=e,fe.current=void 0},[]),Ye=Y(()=>{const t=Le&&("OPEN"===Le.state||"MERGED"===Le.state);return"auto-accept"===k||"plan"===k||Ne||t?!L&&!ee:!L&&0===e.length&&!q&&!ee},[L,e,q,ee,k,Ne,Le]),Je=V(new Map),Xe=Y(()=>le.map((e,t)=>{if(Je.current.has(e))return Je.current.get(e)??null;const n=saveTempImage(e,t+1);return Je.current.set(e,n),n}),[le]),Ze=__name(()=>L||i||z||ee||j?0:Ye||P||q?3:4,"getBottomMargin");return G.createElement(X,{width:"100%",flexDirection:"column",marginBottom:Ze()},!ee&&G.createElement(X,{flexDirection:"column",width:"100%"},G.createElement(ImageRowsDisplay,{detectedImages:le,selectedImageIndex:ue,imageTempPaths:Xe,termWidth:De,inHistory:-1!==ye}),G.createElement(Z,{color:q?$n.GREEN:$n.GRAY},ve.line.repeat(De)),G.createElement(TextInput,{key:M,value:e,placeholder:Ce?"Save and close the editor to continue...":o,onChange:je,onSubmit:()=>{if(!he.current)return Date.now()-oe.current<100?(oe.current=0,void Fe()):void(i||z||ee||Ce||Be());he.current=!1},showCursor:!Ce&&r&&-1===ue,onCursorChange:Ke,initialCursor:fe.current,prefix:`${q?"!":ve.pointer} `,prefixColor:q?$n.GREEN:$n.WHITE}),G.createElement(Z,{color:q?$n.GREEN:$n.GRAY},ve.line.repeat(De))),L&&G.createElement($_,null),j&&G.createElement(X,{paddingTop:1},G.createElement(Z,{color:$n.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&G.createElement(b_,{onSelectFile:ze,onClose:Ue,searchQuery:l}),z&&G.createElement(Uk,{onSelectCommand:We,onInsertCommand:Ge,onClose:He,searchQuery:W}),ee&&G.createElement(x_,{onSelectSession:Qe,onClose:Ve}),!z&&(Ye||P)&&G.createElement(__,{termWidth:De,indicatorText:N_(Ne,Ie,De),isIDEIndicator:I_(Ne,Ie),permissionMode:k,prInfo:Le,tasteLearning:p,contextUsage:m,connectionIndicator:$e,pendingExitKey:P,updateStatus:S,updateFailedInfo:E,currentProvider:v,showProviderInfo:C,isBashMode:q,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w}),ke&&G.createElement(X,{paddingLeft:1,flexDirection:"column"},G.createElement(Z,{color:$n.YELLOW},ke)))},"InputBox");Ft(),os(),rr();var D_=__name(({messages:e})=>0===e.length?null:G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(X,{marginBottom:0},G.createElement(Z,{color:On,inverse:!0},` Queued (${e.length}) `)),e.map((e,t)=>G.createElement(X,{key:t},G.createElement(Z,{color:$n.DIM},ve.pointerSmall," "),G.createElement(Z,{color:$n.DIM},truncateString({text:e.displayMessage??e.input,maxChars:80}))))),"QueuedMessages"),L_=G.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:p=0,contextUsage:g,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:E,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:T,permissionMode:_,onToggleAutoAccept:x,hintMessage:P,historyManager:A,pendingExitKey:I,onResetPendingExitKey:N,onDoubleEscapeEmpty:R,retryAttempt:$,onAltP:M})=>{const[D,L]=Q(0),O=V(s);return K(()=>{I&&s!==O.current&&s.length>0&&N?.(),O.current=s},[s,I,N]),K(()=>{if(!t)return void L(0);const e=setInterval(()=>{L(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),G.createElement(X,{flexDirection:"column"},G.createElement(D_,{messages:e}),G.createElement(X,{flexDirection:"row",justifyContent:"space-between"},G.createElement(X,{flexDirection:"column"},(t||n.isExecuting)&&null===$&&G.createElement(a_,{tokens:p,timeElapsed:D,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),P&&G.createElement(X,{marginLeft:1},G.createElement(Z,{color:$n.DIM}," ","⎿"," ","Tip: ",P)))),G.createElement(M_,{input:s,setInput:o,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:g,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:E,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:T,permissionMode:_,onToggleAutoAccept:x,hintMessage:P,historyManager:A,pendingExitKey:!I||t||n.isExecuting?null:I,onDoubleEscapeEmpty:R,onAltP:M,isProcessing:t}))});Ft(),ks(),Ns(),br(),vr();var O_=__name(({onComplete:e,onCancel:t})=>{const[n,r]=Q(!1),[s,o]=Q(""),{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:p}=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 ne((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.");p()}}),n?G.createElement(fr,{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}`)}}):G.createElement(xs,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");async function discoverOAuthMetadata(e){const t=new d(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:rE,capabilities:{},clientInfo:sE}})});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}Ft(),Ft(),hE(),lE(),SE(),fE(),bE(),AE(),IE(),$E(),Ft(),IE(),$E(),gE(),PE(),Ft(),CE(),lE(),Cn(),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient"),rr();var q_=__name(({onClose:e})=>{const[t,n]=Q([]),[r,s]=Q(!0),[o,i]=Q(0),[a,l]=Q("list"),[u,d]=Q(null),m=J(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)}},[]);K(()=>{m()},[m]);const p=Y(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),g=p[o]??null;ne((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===p.length)return;const e=Math.max(0,p.length-1);i(t=>Math.min(e,t+1)),d(null)}n.return&&g&&(l("actions"),d(null))}});const h=__name(e=>{switch(e){case"connected":return G.createElement(Z,{color:$n.GREEN},ve.tick);case"authenticated":return G.createElement(Z,{color:$n.CYAN},ve.tick);case"requires_auth":return G.createElement(Z,{color:$n.YELLOW},ve.warning);case"error":return G.createElement(Z,{color:$n.RED},ve.cross);default:return G.createElement(Z,{color:$n.GRAY},ve.circle)}},"getStatusIcon"),f=__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"),y=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),w=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),S=__name(async e=>{if(g)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 ${g.name}...`,color:$n.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:g.name,enabled:!0,scope:g.scope}))return void d({text:`${ve.cross} Failed to enable ${g.name}, server may no longer exist in ${g.scope} scope`,color:$n.YELLOW});await m(),d({text:`${ve.tick} Enabled ${g.name}`,color:$n.GREEN})}catch(e){d({text:`${ve.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:$n.RED})}}else{d({text:`Disabling ${g.name}...`,color:$n.CYAN,loading:!0});try{const e=getMcpConnectionManager();if(!await updateMcpServerStatus({name:g.name,enabled:!1,scope:g.scope}))return void d({text:`${ve.cross} Failed to disable ${g.name}, server may no longer exist in ${g.scope} scope`,color:$n.YELLOW});await e.disconnectServer(g.name),await m(),d({text:`${ve.tick} Disabled ${g.name}`,color:$n.GREEN})}catch(e){d({text:`${ve.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:$n.RED})}}else l("confirm-remove");else{if(!g.config.oauth)return void d({text:"No OAuth configured for this server",color:$n.YELLOW});d({text:`Authenticating ${g.name}...`,color:$n.CYAN,loading:!0});try{const e={authorizationUrl:g.config.oauth.authorizationUrl,tokenUrl:g.config.oauth.tokenUrl,clientId:g.config.oauth.clientId,clientSecret:g.config.oauth.clientSecret,scopes:g.config.oauth.scopes},t=await performOAuthFlow(g.name,e,{onStatus:__name(()=>{},"onStatus")});if(t.success){d({text:`${ve.tick} Authenticated with ${g.name}`,color:$n.GREEN});try{const e=getMcpConnectionManager();await e.ensureServerConnection(g.name)}catch{}await m()}else d({text:`${ve.cross} Auth failed: ${t.error}`,color:$n.RED})}catch(e){d({text:`${ve.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:$n.RED})}}else{d({text:`Connecting ${g.name}...`,color:$n.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.ensureServerConnection(g.name),d({text:`${ve.tick} Connected to ${g.name}`,color:$n.GREEN}),await m()}catch(e){d({text:`${ve.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:$n.RED})}}else d({text:"Already authenticated",color:$n.GREEN});else d({text:"Already connected",color:$n.GREEN});else l("list")},"handleActionSelect"),E=__name(async e=>{if(g)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===g.status&&await e.disconnectServer(g.name),await removeMcpServer({name:g.name,scope:g.scope}),l("list"),await m(),i(e=>Math.min(e,Math.max(0,p.length-2)))}catch(e){d({text:`${ve.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:$n.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Mn,bold:!0},"Manage MCP servers"),G.createElement(Z,{color:$n.DIM},"Loading..."));if("confirm-remove"===a&&g)return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.RED,bold:!0},"Remove ",g.name,"?"),G.createElement(Z,{color:$n.DIM},"This will remove the server from ",g.scope," config."),G.createElement(X,{marginTop:1},G.createElement(et,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:E,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY}," ",t)})),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&g){const e=[],t="disabled"===g.status,n="connected"===g.status,r="authenticated"===g.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&&g.config.oauth&&r&&e.push({label:"Authenticated",value:"authenticated"}),t||!g.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"}),G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Mn,bold:!0},g.name),G.createElement(X,null,h(g.status),G.createElement(Z,{color:$n.DIM}," ",f(g))),G.createElement(X,{marginTop:1},G.createElement(et,{items:e,onSelect:S,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY}," ",t)})),u&&G.createElement(X,{marginTop:1},u.loading&&G.createElement(Z,{color:u.color},G.createElement(xe,{type:"dots"})," "),G.createElement(Z,{color:u.color},u.text)),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"↑↓ navigate · Enter to select · Esc to go back")))}let v=null;return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Mn,bold:!0},"Manage MCP servers"),G.createElement(Z,{color:$n.DIM},t.length," ",1===t.length?"server":"servers"),0===t.length?G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(Z,{color:$n.DIM},"No MCP servers configured."),G.createElement(Z,{color:$n.DIM},'Use "cmd mcp add" to add a server.'),G.createElement(Z,{color:$n.DIM},"Docs: https://commandcode.ai/docs/mcp")):G.createElement(X,{marginTop:1,flexDirection:"column"},p.map((e,t)=>{const n=e.scope!==v;v=e.scope;const r=t===o;return G.createElement(G.Fragment,{key:e.name},n&&G.createElement(X,{marginTop:0===t?0:1},G.createElement(Z,{bold:!0},y(e.scope)),G.createElement(Z,{color:$n.DIM}," (",w(e.scope),")")),G.createElement(X,{paddingLeft:1},G.createElement(Z,{color:r?$n.WHITE:$n.GRAY},r?"› ":" "),G.createElement(Z,{color:r?$n.WHITE:void 0,bold:r},e.name),G.createElement(Z,{color:$n.DIM}," · "),h(e.status),G.createElement(Z,{color:"connected"===e.status?$n.GREEN:"authenticated"===e.status?$n.CYAN:"requires_auth"===e.status?$n.YELLOW:$n.GRAY}," ",f(e))))})),u&&G.createElement(X,{marginTop:1},u.loading&&G.createElement(Z,{color:u.color},G.createElement(xe,{type:"dots"})," "),G.createElement(Z,{color:u.color},u.text)),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Ft(),Aw(),zt(),Sn(),rr();var F_=__name(({onClose:e})=>{const[t,n]=Q([]),[r,s]=Q(0),[o,i]=Q(!0),[a,l]=Q(null);K(()=>{__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(ne((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 G.createElement(X,{paddingLeft:1,paddingTop:1},G.createElement(Z,{color:$n.DIM},"Loading memory files..."));if(a)return G.createElement(X,{paddingLeft:1,paddingTop:1},G.createElement(Z,{color:$n.RED},ve.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 G.createElement(X,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:$n.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},G.createElement(X,null,G.createElement(Z,{color:$n.WHITE,bold:!0},"Select memory to edit:")),G.createElement(X,{columnGap:4,marginTop:1},G.createElement(X,{flexDirection:"column"},m.map((e,t)=>G.createElement(Z,{key:t,color:r===t?$n.WHITE:$n.DIM},r===t?`${dn} `:" ",e.label))),G.createElement(X,{flexDirection:"column"},m.map((e,t)=>G.createElement(Z,{key:t,color:r===t?$n.WHITE:$n.DIM},e.description)))))},"MemorySelector");Ft(),zt(),Sv(),$r(),vr(),rr(),Ft(),rr();var j_=at()?"⠶":"#";function AssistantMessage({content:e}){return G.createElement(X,null,G.createElement(Z,{color:Hn},j_),G.createElement(X,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},G.createElement(Markdown,null,e)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let s=$n.GREEN,o=ve.tick,i="default",a=t||"(No output)";n&&(s=$n.YELLOW,o=ve.arrowRight,i=$n.YELLOW,a="Executing…"),r&&(s=$n.RED,o=ve.cross,i=$n.RED);const l=Y(()=>buildTreeConnectors(a),[a]);return G.createElement(X,null,G.createElement(Z,{color:s},o),G.createElement(X,{flexDirection:"column",marginLeft:1},G.createElement(X,null,G.createElement(Z,{color:$n.GRAY},"$ "),G.createElement(Z,{color:s,bold:!0},e)),G.createElement(X,{columnGap:1,marginLeft:1},G.createElement(Z,{color:er},l),G.createElement(Z,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?$n.YELLOW:void 0,s=Y(()=>buildTreeConnectors(e),[e]);return G.createElement(X,{flexDirection:"column",marginBottom:0,marginTop:-1},G.createElement(X,{columnGap:1},G.createElement(Z,{color:er},s),G.createElement(X,{flexGrow:1,flexShrink:1,minWidth:0},G.createElement(Z,{color:r},e))),t&&G.createElement(X,{marginLeft:3},G.createElement(Z,{color:$n.DIM},"See ",t)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return G.createElement(X,null,G.createElement(Z,{color:$n.RED},t?ve.pointer:ve.warning),G.createElement(X,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?G.createElement(Z,{color:$n.RED,wrap:"wrap"},e):G.createElement(Markdown,{color:$n.RED},e)))}function IDEStatusMessage({status:e,ide:t,details:n}){return G.createElement(X,{flexDirection:"column"},G.createElement(X,null,"connected"===e&&G.createElement(Z,null,G.createElement(Z,{color:$n.GREEN},ve.tick),G.createElement(Z,null," Connected to "),G.createElement(Z,{color:$n.CYAN},t)),"installed"===e&&G.createElement(Z,null,G.createElement(Z,{color:$n.GREEN},ve.tick),G.createElement(Z,null," Installed for "),G.createElement(Z,{color:$n.CYAN},t)),"needs_reload"===e&&G.createElement(Z,null,G.createElement(Z,{color:$n.YELLOW},ve.circle),G.createElement(Z,null," "),G.createElement(Z,{color:$n.CYAN},t),G.createElement(Z,null," extension needs reload")),"failed"===e&&G.createElement(Z,null,G.createElement(Z,{color:$n.RED},ve.cross),G.createElement(Z,null," Install failed")),"not_in_ide"===e&&G.createElement(Z,null,G.createElement(Z,{color:$n.YELLOW},ve.circle),G.createElement(Z,null," Not in IDE"))),n?.map((e,t)=>G.createElement(Z,{key:t,color:$n.DIM}," ",e)))}function AutoCompactMessage({content:e}){return G.createElement(X,null,G.createElement(Z,{color:$n.DIM},ve.info),G.createElement(X,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},G.createElement(Z,{color:$n.DIM},e)))}function TasteSkipMessage(){return G.createElement(X,null,G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:Dn.BADGE_BG,color:Dn.BADGE_FG,bold:!0},mk)),G.createElement(Z,{color:$n.DIM}," Skipped. Run "),G.createElement(Z,{color:Jn.CODE},"/learn-taste"),G.createElement(Z,{color:$n.DIM}," or "),G.createElement(Z,{color:Jn.CODE},"cmd learn-taste"),G.createElement(Z,{color:$n.DIM}," anytime."))}function InfoMessage({content:e,metadata:t}){return t?.isTasteSkip?G.createElement(TasteSkipMessage,null):t?.isAutoCompact?G.createElement(AutoCompactMessage,{content:e}):G.createElement(X,null,G.createElement(Z,{color:$n.DIM},ve.info),G.createElement(X,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},G.createElement(Z,{color:$n.DIM},e)))}__name(AssistantMessage,"AssistantMessage"),Ft(),rr(),__name(BashMessage,"BashMessage"),Ft(),rr(),__name(CommandResultMessage,"CommandResultMessage"),Ft(),rr(),__name(ErrorMessage,"ErrorMessage"),Ft(),rr(),__name(IDEStatusMessage,"IDEStatusMessage"),Ft(),rr(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(InfoMessage,"InfoMessage"),Ft(),Ft(),zt();rr(),tE(),Ft(),$r();var B_="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]:[B_]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||B_;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||B_}catch{return B_}}function HelpMessage(){const e=getInvokedCommandName(),t=Y(()=>Vb.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return G.createElement(X,{flexDirection:"column",paddingY:1},G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(X,null,G.createElement(Z,{bold:!0},"Command Code"),G.createElement(Z,{color:$n.GRAY}," v","0.18.2")),G.createElement(Z,{color:$n.GRAY},Wb)),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Usage"),G.createElement(X,{paddingLeft:2},G.createElement(Z,null,e," <command> [options]"))),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Options"),G.createElement(X,{flexDirection:"column",paddingLeft:2},Qb.map(t=>G.createElement(X,{key:t.key},G.createElement(Z,null,t.key.replace(/^cmd/,e).padEnd(Gb)),G.createElement(Z,{color:$n.GRAY},t.description))))),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Commands"),G.createElement(X,{flexDirection:"column",paddingLeft:2},Kb.map(t=>G.createElement(X,{key:t.key},G.createElement(Z,null,t.key.replace(/^cmd/,e).padEnd(Gb)),G.createElement(Z,{color:$n.GRAY},t.description))))),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Slash Commands"),G.createElement(X,{flexDirection:"column",paddingLeft:2},t.map(e=>G.createElement(X,{key:e.key},G.createElement(Z,null,e.key.padEnd(Gb)),G.createElement(Z,{color:$n.GRAY},e.description))))),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Keyboard Shortcuts"),G.createElement(X,{flexDirection:"column",paddingLeft:2},Hb.map(e=>G.createElement(X,{key:e.key},G.createElement(Z,null,e.key.padEnd(Gb)),G.createElement(Z,{color:$n.GRAY},e.description))))),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Examples"),G.createElement(X,{flexDirection:"column",paddingLeft:2},Jb.map(t=>G.createElement(X,{key:t.key},G.createElement(Z,null,t.key.replace(/^cmd/,e).padEnd(Gb)),G.createElement(Z,{color:$n.GRAY},t.description))))),G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.CYAN},ve.pointer),G.createElement(Z,{color:$n.GRAY}," ",Xb.replace(/cmd/,e))),G.createElement(X,{flexDirection:"column"},G.createElement(Z,{bold:!0},"Links"),G.createElement(X,{flexDirection:"column",paddingLeft:2},Yb.map(e=>G.createElement(X,{key:e.key},G.createElement(Z,null,e.key.padEnd(Gb)),G.createElement(Z,{color:$n.CYAN},e.description))))))}function SystemMessage({content:e,metadata:t}){if(e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS"))return G.createElement(HelpMessage,null);if("CONTEXT"===e){const e=t?.analysis;if(e)return G.createElement(ContextMessage,{analysis:e})}return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{wrap:"wrap"},G.createElement(Markdown,null,e)))}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),vr(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),Ft(),Sn(),Ms(),rr();var z_={"Interrupted by user":"Interrupted by user","Insufficient credits":cn};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&&z_[e]||e,l=null!=t?t.length:n,u=V(null);null===u.current&&t&&t.length>0&&(u.current=t.map((e,t)=>saveTempImage(e,t+1)));const d=u.current??[];return G.createElement(X,{flexDirection:"column"},G.createElement(X,{backgroundColor:i?void 0:Gn.BG,paddingRight:1},G.createElement(Z,{color:i?$n.RED:Gn.POINTER,bold:!i},ve.pointer),G.createElement(X,{marginLeft:1},G.createElement(Z,{color:i?$n.RED:$n.WHITE,wrap:"wrap"},a))),l>0&&G.createElement(X,{marginLeft:1},G.createElement(Z,{color:$n.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 G.createElement(UserMessage,{content:e.input,images:t})}return"assistant"===e.role?G.createElement(AssistantMessage,{content:e.input}):"tool"===e.role?G.createElement(ToolMessage,{name:pv(e.name||""),input:e.input,output:e.output||"",isPending:uv(e),hasError:cv(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?G.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:uv(e),hasError:cv(e)}):"system"===e.role?G.createElement(SystemMessage,{content:e.input,metadata:e.metadata}):"info"===e.role?G.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?G.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?G.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?G.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName(e){const t=Object.values(Nt).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 G.createElement(X,{marginBottom:1},G.createElement(Z,{color:Wn},s),G.createElement(BracketedText,{text:n,color:Wn}),G.createElement(Z,{color:Wn},s))}__name(UserMessage,"UserMessage"),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName,"getModelShortName"),__name(TranscriptDivider,"TranscriptDivider");var U_=G.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=Y(()=>MT(l),[l]),d=Y(()=>FT(l),[l]),m=Y(()=>getPackageJson().version||"0.0.0",[]),p=Y(()=>getGitHeaderInfo(),[]),g=Y(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),h=s?getModelShortName(s):"sonnet-4.6",f="taste-1",y=isInternalTeamFlagEnforced()?" · co":"";return G.createElement(ee,{items:a,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return G.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:l});if("header"===e)return"compact"===d?G.createElement(X,{key:"header",marginBottom:1,flexDirection:"row"},G.createElement(X,{width:OT,flexShrink:0},G.createElement(st,{name:"vice"},G.createElement(Z,null,LT))),G.createElement(X,{flexDirection:"column",marginLeft:2},G.createElement(X,null,G.createElement(Z,{bold:!0},"Command Code"),G.createElement(Z,{color:Wn}," ","v",m)),G.createElement(Z,{color:Wn},"models: ",h," · ",f,y),G.createElement(Z,{color:Wn},g,p&&p.isLocal&&p.branch&&` (${p.branch})`))):G.createElement(X,{key:"header",marginBottom:1,flexDirection:"column"},G.createElement(st,{name:"vice"},G.createElement(Z,null,u.trimEnd())),G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(X,null,G.createElement(Z,{color:Wn},"# "),G.createElement(Z,{bold:!0},"Command Code"),G.createElement(Z,{color:Wn}," v",m)),G.createElement(Z,{color:Wn},"# models: ",h," · ",f,y),G.createElement(X,null,G.createElement(Z,{color:Wn},"# ",g,p&&p.isLocal&&p.branch&&G.createElement(Z,{color:Wn}," ","(branch:"," ",p.branch,")")))));const t=e,n=renderFeedEntry(t,r);return G.createElement(X,{key:t.id,paddingBottom:1,width:"90%"},n)})});Ft(),Sv(),Cr(),rr();var W_=H(__name(function LiveAgentStatusInner2({entry:e}){const t=pv(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]=Q(".");return K(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),G.createElement(X,{flexDirection:"column",marginBottom:1,width:"90%"},G.createElement(X,null,G.createElement(Z,{backgroundColor:Bn.BG,color:Bn.FG,bold:!0},` ${t} `),s&&G.createElement(Z,null," ","(",s,")")),G.createElement(X,{columnGap:1,marginLeft:1},G.createElement(Z,null,"⎿"," "),G.createElement(Z,{color:$n.GRAY},"Running (",formatTime2(i)," | ",formatTokens(o),")",l)),a.length>0&&G.createElement(X,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=pv(e.name);return G.createElement(X,{key:t,columnGap:1},G.createElement(Z,{color:$n.GRAY},"⎿"),G.createElement(Z,{color:$n.GRAY}," ",n),e.input&&G.createElement(Z,{color:$n.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),G_=H(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:G.createElement(W_,{entry:e})},"LiveAgentStatus"));function getModelOptions(){return Object.values(Nt).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}Ft(),zt(),rr(),__name(getModelOptions,"getModelOptions");var H_=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),s=__name(t=>{e(t.value)},"handleSelect");ne((e,n)=>{n.escape&&t()});const o=n?r.findIndex(e=>e.value===n):0;return G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(X,null,G.createElement(Z,{color:Mn,bold:!0},"Select model")),G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),G.createElement(et,{items:r,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:e?$n.GREEN:$n.GRAY},e?ve.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>{const s=r.find(e=>e.label===t),o=s?.value===n,i=e?$n.GREEN:$n.GRAY;return G.createElement(X,null,G.createElement(Z,{color:i},` ${(s?.label||t).padEnd(24)}`),G.createElement(Z,{color:$n.DIM},s?.description),o&&G.createElement(Z,{color:$n.GREEN}," ",ve.tick))}}),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press "),G.createElement(Z,{color:$n.DIM,bold:!0},"Esc"),G.createElement(Z,{color:$n.DIM}," to cancel")))},"ModelSelector");Ft(),vr(),rr();var Q_=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),s=__name(t=>{e(t.value)},"handleSelect");ne((e,n)=>{n.escape&&t()});const o=n?r.findIndex(e=>e.value===n):0,i=n&&-1===o;return G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(X,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},G.createElement(X,null,G.createElement(Z,{bold:!0},"Select AI Provider")),n&&G.createElement(X,{flexDirection:"row"},G.createElement(Z,{color:$n.DIM},"Current: "),G.createElement(Z,{color:$n.GREEN},getProviderDisplayName(n)),i&&G.createElement(Z,{color:$n.YELLOW}," [OAuth enforced]"))),G.createElement(X,{marginBottom:0},G.createElement(Z,{color:$n.DIM},"Available Providers:")),G.createElement(et,{items:r,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:e?$n.CYAN:$n.GRAY,bold:e},e?ve.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.CYAN:$n.GRAY,bold:e},` ${t}`)}),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=Q(0);if(K(()=>{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 G.createElement(X,{marginBottom:1},G.createElement(Z,{color:Yn,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Ft(),rr(),__name(RetryMessage,"RetryMessage"),Ft(),rS(),os(),Sn(),rr();var V_=[{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"}],K_=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=Y(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[s,o]=Q(Math.max(0,r.length-1)),[i,a]=Q(Math.max(0,r.length-8)),[l,u]=Q("checkpoint"),[d,m]=Q(null),[p,g]=Q(0),h=Y(()=>{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]),f=Y(()=>h?V_:V_.filter(e=>"conversation"===e.mode),[h]);if(K(()=>{if(r.length>0){const e=r.length-1;o(e),a(Math.max(0,r.length-8))}},[r.length,8]),ne((e,h)=>{h.escape?"mode"===l?(u("checkpoint"),m(null),g(0)):n():"checkpoint"===l?h.upArrow?o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):h.downArrow?o(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):h.return&&r.length>0&&(m(r[s]),u("mode"),g(0)):"mode"===l&&(h.upArrow?g(e=>Math.max(0,e-1)):h.downArrow?g(e=>Math.min(f.length-1,e+1)):h.return&&d&&f[p]&&t({messageId:d.messageId,mode:f[p].mode}))}),0===r.length)return G.createElement(X,{flexDirection:"column",paddingLeft:2,paddingTop:1},G.createElement(Z,{color:Mn,bold:!0},"Rewind"),G.createElement(Z,{color:$n.DIM},"No checkpoints available. Start a conversation to create checkpoints."),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press "),G.createElement(Z,{color:$n.DIM,bold:!0},"Esc"),G.createElement(Z,{color:$n.DIM}," to close")));if("mode"===l&&d)return G.createElement(X,{flexDirection:"column",paddingLeft:2,paddingTop:1},G.createElement(Z,{color:Mn,bold:!0},"Rewind"),G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"Restore to: "),G.createElement(Z,{color:$n.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),G.createElement(X,{flexDirection:"column"},f.map((e,t)=>{const n=p===t,r=t===f.length-1;return G.createElement(X,{key:e.mode,flexDirection:"column"},G.createElement(X,{flexDirection:"row"},G.createElement(Z,{color:n?Mn:void 0},n?`${dn} `:" "),G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:n?Mn:$n.WHITE},e.label),G.createElement(Z,{color:$n.DIM},e.description))),!r&&G.createElement(Z,null," "))})),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press "),G.createElement(Z,{color:$n.DIM,bold:!0},"Enter"),G.createElement(Z,{color:$n.DIM}," to confirm, "),G.createElement(Z,{color:$n.DIM,bold:!0},"Esc"),G.createElement(Z,{color:$n.DIM}," to go back")));const y=r.slice(i,i+8);return G.createElement(X,{flexDirection:"column",paddingLeft:2,paddingTop:1},G.createElement(Z,{color:Mn,bold:!0},"Rewind"),G.createElement(Z,{color:$n.DIM},"Select a checkpoint to restore your session"),r.length>8&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),G.createElement(X,{marginTop:1}),G.createElement(X,{flexDirection:"column"},y.map((e,t)=>{const n=i+t,o=s===n,a=e.filesModified.length,l=t===y.length-1,u=n===r.length-1;return G.createElement(X,{key:e.messageId,flexDirection:"column"},G.createElement(X,{flexDirection:"row"},G.createElement(Z,{color:o?Mn:void 0},o?`${dn} `:" "),G.createElement(X,{flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{color:o?Mn:$n.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),G.createElement(Z,{color:$n.DIM}," • "),G.createElement(Z,{color:$n.DIM},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),G.createElement(Z,{color:$n.DIM},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&G.createElement(Z,null," "))})),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press "),G.createElement(Z,{color:$n.DIM,bold:!0},"Enter"),G.createElement(Z,{color:$n.DIM}," to select, "),G.createElement(Z,{color:$n.DIM,bold:!0},"Esc"),G.createElement(Z,{color:$n.DIM}," to cancel")))},"RewindSelector");Ft(),Cn(),Ft(),Ft(),pC();var Y_=__name(e=>{const[t,n]=Q(e),[r,s]=Q(null);return K(()=>{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 dC.on("reset",t),dC.on("new-event",r),()=>{dC.off("reset",t),dC.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:s}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new Yy({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={[vt.PROJECT_SLUG]:Ev.getCurrentProjectDirName(),[vt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return s&&(i[vt.OAUTH_TOKEN]=`Bearer ${s}`,o&&(i[vt.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}Ft(),Ft(),EC(),bw(),Cs(),Bv(),Cn(),pC(),Ft(),Cn(),pC(),Bv(),Ft(),Ft(),zt(),bw(),Cs(),Iv(),Cn(),Sr(),Cr(),__name(createRequestClient,"createRequestClient"),Ft(),Bv(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Ft(),Ft(),zt(),Cn(),an(),pC(),Ft();var J_="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 buildRequestBody2(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:`anthropic:${J_}`,max_tokens:200,temperature:.7,stream:!0},threadId:Se()}}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}`),dC.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()}`),dC.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=Ge.fromReadableStream(e),dlog("[ObserverAPI] created MessageStream")}catch(e){throw dlog(`[ObserverAPI] MessageStream creation failed: ${e instanceof Error?e.message:String(e)}`),e}const n=createInsightEmitter();t.on("text",e=>{n.addText(e)});try{await t.finalMessage(),dlog(`[ObserverAPI] stream complete, ${n.getChunkCount()} chunks received`)}catch(e){throw dlog(`[ObserverAPI] stream failed: ${e instanceof Error?e.message:String(e)}`),e}n.emitRemaining()}async function callObserverAPI(e,t,n){dlog(`[ObserverAPI] calling ${Ct.ALPHA.GENERATE} with model: ${J_}`);const r=buildRequestBody2(n);let s;try{s=await e.post({endpoint:Ct.ALPHA.GENERATE,body:r,headers:t,stream:!0}),dlog("[ObserverAPI] got response stream")}catch(e){throw dlog(`[ObserverAPI] request failed: ${e instanceof Error?e.message:String(e)}`),e}await processStream(s),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(dC.observerHasRun)return;dC.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(dC.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)}`),dC.addEvent({type:"progress",message:"Continuing without live observations..."})}}__name(buildObserverPrompt,"buildObserverPrompt"),__name(buildRequestBody2,"buildRequestBody"),__name(createInsightEmitter,"createInsightEmitter"),__name(processStream,"processStream"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var X_=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(h.homedir(),".claude","projects");await M.access(r);const s=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${s}`);const o=(await M.readdir(r)).filter(e=>e===s);for(const s of o){const o=e.join(r,s);try{if(!(await M.stat(o)).isDirectory())continue;const r=(await M.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 M.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{dC.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&dC.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{dC.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 M.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{dC.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"]||[],p=d.codex||[],g=d.cursor||[],h=m.length+p.length+g.length;if(dlog(`[Import] findNewSessions returned: claude-code=${m.length} new, codex=${p.length} new, cursor=${g.length} new`),0===h){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}`);dC.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(p.length>0){const e=(await this.findCodexSessions()).filter(e=>p.includes(e.id));r.push(...e)}if(g.length>0){const e=(await this.findCursorSessions()).filter(e=>g.includes(e.id));s.push(...e)}const f=n.length+r.length+s.length;dlog(`[Import] total sessions: ${f} (claude-code: ${n.length}, codex: ${r.length}, cursor: ${s.length})`),dC.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const y=[{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 y){dC.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 w=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${w.length} batches`);const S=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});dC.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${w.length} batch${1===w.length?"":"es"}`});try{const o=getApiBaseUrl(),i=new Yy({baseUrl:o});let a=!0;for(let e=0;e<w.length;e++){const t=w[e],n=e+1,r=w.length;r>1&&dC.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const s=this.formatBatchLearning(t),o=new hC({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}`),dC.markLearningComplete(),await S,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),dC.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:f,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 dC.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:f,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),dC.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 M.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")}};pC();var Z_=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),ex=__name(e=>{const[t,n]=Q({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return K(()=>{dC.reset(),dC.markImportStarted(),(async()=>{try{const t=await Promise.race([X_.importAndLearn(),Z_(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");Ft();var tx=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{ne((r,s)=>{n&&(s.escape&&e(),(s.return||"\n"===r)&&t())})},"useKeyboardInput");Ft(),Cn();var nx=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=Q(null),[s,o]=Q(null),i=V(!1);return K(()=>{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{dC.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{dC.reset(),e()}}Ft(),Cn(),Ft(),Cn(),pC(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var rx=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=V(n),s=J(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),o=J(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=J(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=J(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=J(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");Ft(),Cn();var sx=__name(({conditions:e,autoLearn:t})=>{const[n,r]=Q("checking"),s=V(!1);return K(()=>{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]),K(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Ft(),Ft(),rr();var ox=__name(({error:e})=>G.createElement(X,{padding:1},G.createElement(X,{flexDirection:"column",borderColor:$n.RED,padding:1},G.createElement(X,{marginBottom:1},G.createElement(Z,null,"Error initializing onboarding: ",e)),G.createElement(X,null,G.createElement(Z,null,"Continuing without onboarding...")))),"OnboardingError");Ft(),Ft(),zt(),rr();var ix=__name(()=>`(run /${At.LEARN_TASTE} anytime)`,"getSkipHint"),ax=__name(()=>G.createElement(Z,null,"Skip for now"," ",G.createElement(Z,{color:$n.DIM},ix())),"SkipOptionText"),lx=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[s,o]=Q(1);return ne((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()}),G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:Dn.TEXT,paddingX:1,paddingY:0},G.createElement(Z,{color:Dn.TEXT,bold:!0},"Build Your Coding Taste"),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(Z,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),G.createElement(X,{marginTop:1},G.createElement(Z,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{color:1===s?Dn.TEXT:$n.GRAY},1===s?ve.pointer:" "," 1. Yes, learn from my sessions (recommended)")),G.createElement(X,null,G.createElement(Z,{color:2===s?Dn.TEXT:$n.GRAY},2===s?ve.pointer:" "," 2."," ",G.createElement(ax,null)))),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice");Ft(),Ft(),rr();var cx=__name(({error:e})=>G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.RED,paddingX:2,paddingY:1,marginBottom:2},G.createElement(Z,{color:$n.RED,bold:!0},"Oops, something went wrong:"),G.createElement(X,{marginTop:1},G.createElement(Z,null,e))),"ErrorSection");Ft(),Ft(),rr(),Ft(),Ft(),Ft(),rr();var ux=[ve.bullet,ve.squareSmallFilled,ve.lozenge,ve.star,ve.triangleRight,ve.triangleUp,ve.circleFilled,ve.pointer],dx=__name(()=>G.createElement(Z,{backgroundColor:Dn.BADGE_BG,color:Dn.BADGE_FG},mk),"TasteBadge"),mx=["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"],px=__name(()=>{const[e,t]=Q(()=>Math.floor(Math.random()*mx.length));K(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*mx.length))},2e3);return()=>clearInterval(e)},[]);const n=mx[e];return G.createElement(Z,{color:$n.YELLOW},n,"...")},"PulsingText"),gx=__name(e=>String(e).padStart(3," "),"padNum"),hx=__name(e=>ux[e%ux.length],"getSymbol"),fx=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${gx(t)} ↓${gx(n)} (↑↓ scroll)`,"buildStatusLine"),yx=__name(({insights:e})=>{const[t,n]=Q(0),[r,s]=Q(!0),o=e.length,i=o>10,a=Math.max(0,o-10);if(K(()=>{r&&i&&n(a)},[o,r,i,a]),ne((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 G.createElement(X,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&G.createElement(Z,{color:$n.DIM},fx(o,u,d,r)),l.map((e,n)=>{const r=t+n;return G.createElement(X,{key:r,marginBottom:0},G.createElement(Z,{color:$n.DIM},hx(r)," ",e))}))},"ScrollableInsights"),wx=__name(({label:e,message:t,active:n,complete:r,items:s,insights:o,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return G.createElement(X,{flexDirection:"column",marginBottom:0},G.createElement(dx,null),G.createElement(X,{marginTop:0},G.createElement(Z,{color:$n.DIM},"⎿"),G.createElement(X,{marginLeft:2},a?G.createElement(Z,{color:Dn.TEXT},"learned your coding taste"):G.createElement(px,null))));const u=__name(()=>{const[e,t]=Q(!0);return K(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),G.createElement(Z,{color:$n.YELLOW},e?ve.circleFilled:ve.circle)},"PulsingDot"),d=__name(()=>r?G.createElement(Z,{color:Fn.BG},ve.square):n?G.createElement(u,null):G.createElement(Z,{color:$n.DIM},ve.circle),"getStatusIcon"),m=s.length>0||o.length>0||t||l&&l.learningCount>0;return!r||n||m?G.createElement(X,{flexDirection:"column",marginBottom:0},(n||r)&&G.createElement(X,{marginBottom:0},G.createElement(X,{marginRight:1},d()),G.createElement(Z,{color:r?$n.WHITE:n?$n.YELLOW:$n.DIM},e)),r&&t&&(!l||0===l.learningCount)&&G.createElement(X,{marginLeft:3,marginBottom:0},G.createElement(Z,{color:$n.DIM},t)),s.length>0&&G.createElement(X,{flexDirection:"column",marginLeft:1,marginBottom:0},s.map((e,t)=>G.createElement(Z,{key:t,color:$n.DIM},`${ve.bullet} ${e}`))),o.length>0&&G.createElement(yx,{insights:o}),r&&l&&l.learningCount>0&&G.createElement(X,{flexDirection:"column",marginLeft:1,marginBottom:0},G.createElement(X,{marginBottom:1,flexDirection:"row"},G.createElement(Z,null,"⎿"),G.createElement(X,{marginLeft:2},G.createElement(Z,{color:Dn.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),G.createElement(X,{flexDirection:"column",marginLeft:1},G.createElement(Z,{color:$n.DIM},ve.pointerSmall," Stored in"," ",l.storage),G.createElement(Z,{color:$n.DIM},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),Sx=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return G.createElement(X,{flexDirection:"column",marginBottom:1},e.map((e,n)=>G.createElement(X,{key:e.id,marginLeft:0===n?0:3},G.createElement(wx,{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"),bx=__name(({steps:e})=>G.createElement(Sx,{steps:e}),"ProgressSection");Ft(),rr();var Ex=__name(({isImporting:e=!1,waitingForInput:t=!1})=>G.createElement(G.Fragment,null,e&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"ESC to cancel")),t&&G.createElement(X,{marginTop:1},G.createElement(Z,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Ft();var vx=[{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"}}],Cx=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:s}=Y_(vx),{isImporting:o,waitingForInput:i,error:a}=ex(t);return tx({onEscape:e,onEnter:__name(()=>{i&&(a&&n?n():e())},"onEnter"),enabled:o||i}),G.createElement(X,{flexDirection:"column",padding:1},s&&G.createElement(cx,{error:s}),!s&&G.createElement(bx,{steps:r}),G.createElement(Ex,{isImporting:o,waitingForInput:i}))},"ImportProgress"),kx=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:s,onErrorDismiss:o,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?G.createElement(lx,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?G.createElement(Cx,{onComplete:r,onError:s,onErrorDismiss:o}):null,"OnboardingStepRenderer"),Tx=__name(({onComplete:e,autoLearn:t=!1})=>{K(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:s}=nx({autoLearn:t,onShouldSkip:e}),{step:o,setStep:i}=sx({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=rx({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?G.createElement(ox,{error:r}):"done"===o?null:G.createElement(kx,{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 _x=H(__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:p,showFileList:g,setShowFileList:h,showProviderSelector:f,showModelSelector:y,showMemorySelector:w,showMcpManager:S,showAgentsConfig:E,showRewindSelector:v,showLoginOverlay:C,showAddDirModal:k,showCompactModeSelector:T,authComponentInfo:_,status:x,currentProvider:P,currentModel:A,showProviderNotification:I,shareInfo:N,showShareNotification:R,unshareNotificationMessage:$,updateStatus:M,updateFailedInfo:D,permissionMode:L,hintMessage:O,pendingExitKey:q,tasteLearningEnabled:F,interactionTokens:j,contextUsage:B,historyManagerRef:z,executionState:U,contextEngineRef:W,onSubmit:H,onCommand:Q,onToggleAutoAccept:V,onResetPendingExitKey:K,onDoubleEscapeEmpty:ee,onTasteOnboardingComplete:te,permissionPanel:ne,questionPanel:re,onRewindSelect:se,onRewindCancel:oe,onLoginComplete:ie,onLoginCancel:ae,setShowProviderSelector:le,setShowModelSelector:ce,setShowMemorySelector:ue,setShowMcpManager:de,setShowAgentsConfig:me,setShowAddDirModal:pe,handleProviderSelect:ge,handleProviderCancel:he,handleModelSelect:fe,handleModelCancel:ye,handleCompactModeSelect:we,handleCompactModeCancel:Se,handleAuthSuccess:be,handleAuthCancel:Ee}){const ve=Y(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Ce=useTerminalWidth(),ke=Y(()=>"off"===o?ve:getBudgetedFeed(ve,"limited"===o?15e3:5e4),[ve,o]),Te=Y(()=>"off"===o?0:Math.max(0,ve.length-ke.length),[ve.length,ke.length,o]),_e=Y(()=>0===Te?ke:ke.filter(e=>"user"!==e.role),[ke,Te]),xe=J(()=>me(!1),[me]),Pe=J(()=>ue(!1),[ue]),Ae=J(()=>de(!1),[de]),Ie=J(()=>pe(!1),[pe]),Ne=J(()=>ce(!0),[ce]),Re=!("off"!==o||ne||re||f||y||_||w||S||E||v||C||k||T||i);return G.createElement(X,{flexDirection:"column",width:"100%"},G.createElement(U_,{staticKey:s,feed:_e,showHeader:!0,expandedToolOutput:"off"!==o,currentModel:A,hiddenCount:Te}),i&&G.createElement(Tx,{onComplete:te,autoLearn:a}),t.map(e=>e.metadata?.isAgent?G.createElement(G_,{key:e.id,entry:e}):G.createElement(X,{key:e.id,marginBottom:1,width:"90%"},renderFeedEntry(e,"off"!==o))),G.createElement(RetryMessage,{attempt:l}),re,ne,"off"!==o&&G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"─".repeat(Ce))),G.createElement(X,{paddingRight:1},G.createElement(Z,{backgroundColor:Fn.BG,color:Fn.FG,bold:!0},`${dk}DETAILED TRANSCRIPT${dk}`),G.createElement(Z,{color:$n.DIM}," · "),G.createElement(Z,{bold:!0},"ctrl+o"),G.createElement(Z,{color:$n.DIM}," to toggle"),G.createElement(Z,{color:$n.DIM}," · "),G.createElement(Z,{bold:!0},"ctrl+e"),G.createElement(Z,{color:$n.DIM}," ","to"," ","limited"===o?"show all":"collapse"))),Re&&G.createElement(L_,{queuedMessages:n,isProcessing:r,executionState:U,status:x,input:u,setInput:d,onSubmit:H,showFileList:g,setShowFileList:h,fileSearchQuery:m,setFileSearchQuery:p,onCommand:Q,outputTokens:j,contextUsage:B,tasteLearning:F,shareInfo:N,showShareNotification:R,unshareNotificationMessage:$,updateStatus:M,updateFailedInfo:D,currentProvider:P,showProviderInfo:I,permissionMode:L,onToggleAutoAccept:V,hintMessage:O,historyManager:z.current,pendingExitKey:q,onResetPendingExitKey:K,onDoubleEscapeEmpty:ee,retryAttempt:l,onAltP:Ne}),f&&G.createElement(X,{marginY:1},G.createElement(Q_,{onSelect:ge,onCancel:he,currentProvider:P})),y&&G.createElement(X,{marginY:1},G.createElement(H_,{onSelect:fe,onCancel:ye,currentModel:A})),T&&G.createElement(X,{marginY:1},G.createElement(p_,{onSelect:we,onCancel:Se})),E&&G.createElement(X,{marginY:1},G.createElement(d_,{onCancel:xe})),w&&G.createElement(X,{marginY:1},G.createElement(F_,{onClose:Pe})),S&&G.createElement(X,{marginY:1},G.createElement(q_,{onClose:Ae})),v&&W.current&&G.createElement(X,{marginY:1},G.createElement(K_,{checkpoints:W.current.listCheckpoints(),onSelect:se,onCancel:oe})),_&&G.createElement(X,{marginY:1},G.createElement(_.Component,{onSuccess:be,onCancel:Ee})),C&&G.createElement(X,{marginY:1},G.createElement(O_,{onComplete:ie,onCancel:ae})),k&&G.createElement(X,{marginY:1},G.createElement(KT,{onClose:Ie})))},"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:p,onSubmit:g,onCommand:h,input:f,setInput:y,fileSearchQuery:w,setFileSearchQuery:S,updateFailedInfo:E,handleTrust:v,handleNoTrust:C,handleToggleAutoAccept:k,handleDoubleEscapeEmpty:T,handleTasteOnboardingComplete:_,loadTasteStatus:x}){if(i.shouldExit)return null;if(o.checkingProject)return null;if(o.showTrustPrompt)return G.createElement(gT,{staticKey:s.staticKey,onTrust:v,onExit:C});if(s.showSessionSelector)return G.createElement(fT,{onSelectSession:p.onSelectSession,onNewSession:p.onNewSession});if(!o.projectTrusted)return null;const P=a.pendingQuestion?G.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:s.setStaticKey}):null,A=a.pendingPermission?G.createElement(xT,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:k}):null;return s.showLearningFeed?G.createElement(LearningView,{setShowLearningFeed:s.setShowLearningFeed,setStaticKey:s.setStaticKey,onExit:()=>i.setShouldExit(!0)}):s.showTasteConfig?G.createElement(TasteConfigView,{staticKey:s.staticKey,setShowTasteConfig:s.setShowTasteConfig,loadTasteStatus:x}):s.showSkillsConfig?G.createElement(SkillsConfigView,{staticKey:s.staticKey,setShowSkillsConfig:s.setShowSkillsConfig}):s.showContextView?G.createElement(ContextConfigView,{staticKey:s.staticKey,contextEngineRef:u,setShowContextView:s.setShowContextView,setInput:y}):s.showStatusView?G.createElement(StatusConfigView,{staticKey:s.staticKey,setShowStatusView:s.setShowStatusView,setInput:y}):G.createElement(_x,{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:f,setInput:y,fileSearchQuery:w,setFileSearchQuery:S,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,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:E,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:g,onCommand:h,onToggleAutoAccept:k,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:T,onTasteOnboardingComplete:_,permissionPanel:A,questionPanel:P,onRewindSelect:p.onRewindSelect,onRewindCancel:p.onRewindCancel,onLoginComplete:p.onLoginComplete,onLoginCancel:p.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:p.handleProviderSelect,handleProviderCancel:p.handleProviderCancel,handleModelSelect:p.handleModelSelect,handleModelCancel:p.handleModelCancel,handleCompactModeSelect:p.handleCompactModeSelect,handleCompactModeCancel:p.handleCompactModeCancel,handleAuthSuccess:p.handleAuthSuccess,handleAuthCancel:p.handleAuthCancel})}__name(renderView,"renderView");var xx=__name(({resume:e=!1,continue:t=!1,trust:n=!1,dangerouslySkipPermissions:r=!1,updateStatus:s,updateFailedInfo:o,initialPrompt:i,skipOnboarding:a=!1,initialPermissionMode:l})=>{const{exit:u}=se(),{stdout:d}=te(),[m,p]=Q(""),[g,h]=Q(""),f=V(!1),y=V(!1),w=V(null),S=V(null),E=useUiOverlays(),v=useFeed(),C=useSession(),k=useStatus(s),T=useAuth(),_=usePendingOps(),x=useOnboarding(),P=useExit(),{executeBash:A,executionState:I}=ek(),N=usePermissionMode({initialPermissionMode:l,dangerouslySkipPermissions:r,setPendingPermission:_.setPendingPermission,setStatus:k.setStatus,contextEngineRef:S}),{createContextEngineCallbacks:R}=useContextEngine({sessionId:C.sessionId,sessionLoaded:C.sessionLoaded,showSessionSelector:E.showSessionSelector,projectTrusted:x.projectTrusted,setFeed:v.setFeed,setLiveEntries:v.setLiveEntries,setQueuedMessages:v.setQueuedMessages,queuedMessagesRef:v.queuedMessagesRef,setStatus:k.setStatus,pinnedStatusRef:k.pinnedStatusRef,setRetryAttempt:k.setRetryAttempt,setInteractionTokens:k.setInteractionTokens,setContextUsage:k.setContextUsage,setCurrentProvider:T.setCurrentProvider,shareInfoRef:k.shareInfoRef,permissionsService:N.permissionsService,permissionModeRef:N.permissionModeRef,setPendingQuestion:_.setPendingQuestion,contextEngineRef:S}),{onCommand:$}=useCommandCtx({feedState:v,sessionState:C,statusState:k,uiOverlays:E,onboarding:x,exitState:P,permissionState:N,contextEngineRef:S,isSubmittingRef:f,executeBash:A,createContextEngineCallbacks:R,setInput:p}),{loadTasteStatus:M,loadCurrentProvider:D,onSubmit:L}=useStartup({resume:e,continueLatest:t,trust:n,initialPrompt:i,stdout:d,feedState:v,sessionState:C,statusState:k,authState:T,onboarding:x,uiOverlays:E,permissionState:N,contextEngineRef:S,isSubmittingRef:f,initialPromptSubmittedRef:y,historyManagerRef:w,executeBash:A,createContextEngineCallbacks:R,setInput:p,onCommand:$});useLifecycle({exit:u,feedState:v,exitState:P,statusState:k,authState:T,onboarding:x,uiOverlays:E,skipOnboarding:a});const{handleToggleAutoAccept:O,handleDoubleEscapeEmpty:q,handleTasteOnboardingComplete:F,handleTrust:j,handleNoTrust:B}=useHandlers({resume:e,feedState:v,onboarding:x,uiOverlays:E,exitState:P,pendingOps:_,permissionState:N,statusState:k,authState:T,contextEngineRef:S,loadTasteStatus:M,loadCurrentProvider:D,setInput:__name(e=>p(e),"setInput")});return renderView({feedState:v,sessionState:C,statusState:k,authState:T,uiOverlays:E,onboarding:x,exitState:P,pendingOps:_,permissionState:N,contextEngineRef:S,historyManagerRef:w,executionState:I,actionCallbacks:useMainActionCallbacks({feedState:v,sessionState:C,statusState:k,authState:T,uiOverlays:E,permissionState:N,contextEngineRef:S,createContextEngineCallbacks:R,setInput:p}),onSubmit:L,onCommand:$,input:m,setInput:p,fileSearchQuery:g,setFileSearchQuery:h,updateFailedInfo:o,handleTrust:j,handleNoTrust:B,handleToggleAutoAccept:O,handleDoubleEscapeEmpty:q,handleTasteOnboardingComplete:F,loadTasteStatus:M})},"InteractiveCLI");hr(),Rn(),Iv();var Px=__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"),Ax=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),Ix=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),Nx=__name(({options:e})=>{let t;return e.permissionMode?t=e.permissionMode:e.plan&&(t="plan"),{resume:e.resume,continue:e.continue,trust:e.trust,dangerouslySkipPermissions:e.dangerouslySkipPermissions,initialPrompt:e.initialPrompt,skipOnboarding:e.skipOnboarding,initialPermissionMode:t}},"buildInteractiveCLIProps"),Rx=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),$x=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),Mx=__name(()=>{$x()},"initializeTerminal"),Dx=__name(async(e={})=>{const t=Px(process.stdin.isTTY);if(t.isValid||(console.error(t.errorMessage),process.exit(1)),Mx(),Ax(e)){const e=await Ev.isProjectInitialized(),t=e?await Ev.listSessions():[],n=Ix({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const n=Nx({options:e}),r=Rx();re(G.createElement(xx,{...n}),r)},"interactiveMode");Qt(),Ft(),zt(),po(),Gs();var Lx=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.error(`${ve.cross} Authentication failed. Please try again with: cmd login`),!1)}catch(e){return isUserCancellation(e)||(console.error(`${ve.cross} Login failed: ${getErrorMessage(e)}`),console.error("Please try again with: cmd login")),!1}},"attemptLogin");async function ensureAuthenticated(){try{return!!await getAuthKey()||Lx()}catch(e){return console.error("Error checking authentication:",e),!1}}__name(ensureAuthenticated,"ensureAuthenticated");var Ox=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),qx=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth"),Fx=__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"),jx=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:!0,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),Bx=__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=Bx(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=Ox(e);await qx();const r=Fx(t),s=jx({options:t,runtimeOptions:r,initialPrompt:n});Dx(s)}__name(interactiveModeAction,"interactiveModeAction"),Ft(),Cn(),gs(),Sr(),globalThis.COMMAND_CODE_CWD=process.cwd();var zx=__name(()=>process.cwd(),"getCwd"),Ux=__name(()=>process.argv.slice(2),"getArgs"),Wx=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),Gx=__name(()=>{const e=zx(),t=Ux(),n=Wx(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){Gx(),process.argv.includes("--ide-setup")&&(formatSetupResult(await runIDESetup()).forEach(e=>console.log(e)),process.exit(0)),await maybeRunPendingUpdate(),await migrateDeprecatedModel(),checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100)}__name(preRun,"preRun"),Ft(),zt(),Cn(),$r(),tE(),vr();var Hx=getPackageJson(),Qx=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=Hx.version,t=getInvokedCommandName(),n=Vb.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(ie.bold("Command Code")+ie.gray(` v${e}`)),console.log(ie.gray(Wb)),console.log(),console.log(ie.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ie.bold("Options"));for(const e of Qb){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Gb)+ie.gray(e.description))}console.log(),console.log(ie.bold("Commands"));for(const e of Kb){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Gb)+ie.gray(e.description))}console.log(),console.log(ie.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Gb)+ie.gray(e.description));console.log(),console.log(ie.bold("Keyboard Shortcuts"));for(const e of Hb)console.log(" "+e.key.padEnd(Gb)+ie.gray(e.description));console.log(),console.log(ie.bold("Examples"));for(const e of Jb){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Gb)+ie.gray(e.description))}console.log(),console.log(ie.cyan("❯")+" "+ie.gray(Xb.replace(/cmd/,t))),console.log(),console.log(ie.bold("Links"));for(const e of Yb)console.log(" "+e.key.padEnd(Gb)+ie.cyan(e.description));console.log()}function createProgram(){const e=new be;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(Hx.version,"-v, --version","display the version number").argument("[prompt]","Your prompt to run in interactive mode").option("-r, --resume","Resume a session (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 Ee("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Ee("--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 Ee("--auto-accept","Start in auto-accept mode").implies({permissionMode:"auto-accept"})).addOption(new Ee("--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",Qx,[]).addOption(new Ee("--model <model>","Override model for this run").hideHelp()).addOption(new Ee("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Ee("--experimental","Enable experimental features").hideHelp()).addOption(new Ee(bt).hideHelp()).addOption(new Ee(Et).hideHelp()).addOption(new Ee("-d, --debug","Enable debug mode").hideHelp()).addOption(new Ee("--local","Use local server").hideHelp()).addOption(new Ee("--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")})}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Ft(),gs(),Ss(),NC();var Vx=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=h.platform(),n=h.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(){Vx||(Vx=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Ce("Opening GitHub issues...").start();try{await ue(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"),po(),Ft(),Ms(),__name(openGitHubIssue,"openGitHubIssue");var Kx=new be("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Ft();var Yx=new be("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const{waitUntilExit:t}=re(G.createElement(eT,{verbose:e.verbose,text:e.text}));await t()}Ft(),Ft(),__name(runInfo,"runInfo");var Jx=new be("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}=re(G.createElement(Cx,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}Ft(),zt(),Ft(),__name(runLearnTaste,"runLearnTaste"),Cn(),gs();var Xx=new be(At.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:ls.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 be("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 Ee("-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(ie.red(`Error: Invalid server name '${e}'`)),console.error(ie.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(ie.red(`Error: Invalid transport type '${n.transport}'`)),console.error(ie.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(ie.red("Error: URL is required for http transport")),console.error(ie.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(ie.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(ie.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(ie.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(ie.cyan("Server requires OAuth authentication."));let t,n="command-code";if(r.metadata.registrationEndpoint){console.log(ie.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${EE}/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(ie.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(ie.gray(` ${e}`))},"onStatus")});s.success?console.log(ie.green("✓ Successfully authenticated")):(i=!0,console.log(ie.yellow(`Warning: Authentication failed: ${s.error}`)),console.log(ie.gray("You can retry with: cmd mcp auth "+e)),console.log(ie.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(ie.red("Error: Command is required for stdio transport")),console.error(ie.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(ie.red("Error: Command is required for stdio transport")),console.error(ie.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(ie.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(ie.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(ie.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===o.transport)console.log(ie.gray(` URL: ${o.url}`));else{const e=[o.command,...o.args||[]].join(" ");console.log(ie.gray(` Command: ${e}`))}console.log(""),console.log(ie.cyan("Next steps:")),console.log(ie.gray(`Start ${s} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ie.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(ie.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(ie.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(ie.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=s,t}function listMcpCommand(){const e=new be("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(ie.yellow("\nNo MCP servers configured\n")),console.log(ie.gray("Add a server with:")),console.log(ie.gray(" cmd mcp add --transport http <name> <url>")),console.log(ie.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(ie.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ie.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ie.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const s of e){const e=s.config.enabled?ie.green("enabled"):ie.gray("disabled");let o;o=s.config.oauth?await hasTokens(s.name)?ie.green(ve.tick):ie.red(ve.cross):s.config.headers||s.config.env?ie.green(ve.tick):ie.gray("-"),console.log(` ${ie.white(s.name.padEnd(t))} ${ie.cyan(s.config.transport.padEnd(n))} ${ie.gray(s.scope.padEnd(r))} ${o} ${e}`)}console.log(ie.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ie.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new be("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(ie.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(ie.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ie.dim("Scope:")} ${r}`),console.log(` ${ie.dim("Transport:")} ${n.transport}`),console.log(` ${ie.dim("Status:")} ${n.enabled?ie.green("enabled"):ie.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ie.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${ie.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(` ${ie.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ie.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${ie.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(ie.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new be("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Ee("-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(ie.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(ie.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(ie.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const s="user"===r?"global":"project"===r?"project":"local";console.log(ie.green(`✓ Removed MCP server '${e}' from ${s} config`))}catch(e){console.error(ie.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new be("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 Ee("-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(ie.red(`Error: Invalid server name '${e}'`)),console.error(ie.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(ie.red("Error: Invalid JSON")),console.error(ie.gray("Make sure to quote the JSON string properly")),console.error(ie.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=uE.safeParse(s);if(!i.success){console.error(ie.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(ie.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(ie.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(ie.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(ie.cyan("Starting OAuth authentication...")),console.log(ie.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(ie.gray(` ${e}`))},"onStatus")});n.success?console.log(ie.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(ie.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(ie.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ie.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(ie.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(ie.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(ie.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(ie.gray(` Command: ${e}`))}console.log(""),console.log(ie.cyan("Next steps:")),console.log(ie.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ie.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new be("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(ie.yellow("No servers with stored authentication."));console.log(ie.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?ie.yellow("expired"):ie.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(ie.red("Error: Server name is required")),console.error(ie.gray(`Usage: ${n} mcp auth <server>`)),console.error(ie.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(ie.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(ie.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(ie.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(ie.gray(" A refresh token is available for re-authentication"));else{if(console.log(ie.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(ie.gray(` Expires in ${e} minutes`))}t.scope&&console.log(ie.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(ie.green(`✓ Cleared authentication for '${e}'`)):console.log(ie.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(ie.red(`Error: MCP server '${e}' not found`)),console.error(ie.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),r.config.oauth||(console.error(ie.red(`Error: Server '${e}' does not have OAuth configured`)),console.error(ie.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(ie.cyan(`Authenticating with '${e}'...`)),console.log(ie.gray("A browser window will open for authentication.\n"));const o=await performOAuthFlow(e,s,{onStatus:__name(e=>{console.log(ie.gray(` ${e}`))},"onStatus")});if(o.success)return console.log(ie.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(ie.gray("Restart the session to connect with the authenticated server."));console.error(ie.red(`\nError: Authentication failed: ${o.error}`)),console.log(ie.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(ie.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new be("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}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(h.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")}Ft(),Ft(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Ft(),__name(listMcpCommand,"listMcpCommand"),Ft(),__name(getMcpCommand,"getMcpCommand"),Ft(),__name(removeMcpCommand,"removeMcpCommand"),Ft(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Ft(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Ft(),zt(),Ft(),Ft(),Iw(),Ft(),zt(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Ft(),Ft();var Zx=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||Zx.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const s=n[r].trim();return{endIdx:t+r,inclusive:Zx.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(Zx.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(!Zx.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:`${ve.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?ve.cross:ve.warning;return{valid:o,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?ie.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ie.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`${ie.green(e)} ${ie.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?ie.red(t.summary):ie.yellow(t.summary),"",...formatIssueGroup(r,ie.red,ie.bold(ie.red("Errors:"))),...formatIssueGroup(s,ie.yellow,ie.bold(ie.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"),Ft(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var eP=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;eP.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 tP=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,nP=/^\[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}):tP.test(o)||nP.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 rP=__name(e=>"local-global"===e?"global":"project","locationLabel"),sP=__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 v(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${rP(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});v(s)&&r.push({path:s,displayName:"taste.md"});const o=(await M.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>v(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 M.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await M.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 sP({file:"all",error:`No taste files found in ${rP(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 sP({file:"all",error:`No taste files found in ${rP(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 v(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):sP({file:"all",error:`No taste directory found in ${rP(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"),Ft(),gs(),__name(resolveConflictStrategy,"resolveConflictStrategy");var oP=ie.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(`${ie.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?`${ie.dim(t[1])}${ie.green(t[2])}${ie.white(t[3]??"")}${t[4]?ie.dim(t[4]):""}`:ie.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ie.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 iP=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return ct(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:iP})}function getProfileLink(e){return ct(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:iP})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return lt(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(ie.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(`${ie.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(ie.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new be("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 ${ie.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(`${ie.green(ve.tick)} All ${ie.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ie.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ie.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(ie.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 M.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await M.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 kw+"\n\n";const t=e.trim();return t.startsWith(vw)||t.startsWith(Tw)||t.startsWith(_w)?e:kw+"\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"),Ft(),fs(),Ft(),Ft(),Ft(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Ft(),__name(formatPackage,"formatPackage"),Ft(),Iw(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var aP="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:aP,category:e.name});return v(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await M.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:aP});if(!v(e))return[];const t=await M.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:aP,category:t});return v(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:aP});await M.mkdir(r,{recursive:!0});const s=getCategoryTasteFile({target:aP,category:n.category}),o=e.dirname(s);await M.mkdir(o,{recursive:!0});const i=formatPackage({pkg:n});await M.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"),Ft(),Ft(),Iw();var lP="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!v(n))return null;const r=migrateHeader({content:await M.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 M.rm(n,{force:!0}),""!==l&&await M.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:lP}),s=await removeCategoryFromRoot({category:n,rootFile:r}),o=getCategoryTasteFile({target:lP,category:n}),i=e.dirname(o);return v(i)&&await M.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 M.writeFile(n,e.trim()+"\n","utf-8")}let o="";v(n)&&(o=await M.readFile(n,"utf-8"),o=migrateHeader({content:o})),o=ensureHeader(o),o=ensureTrailingNewlines(o),o+=s,await M.writeFile(n,o.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:s}=t,o=getCategoryTasteFile({target:lP,category:n.category}),i=e.dirname(o);await M.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await M.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 M.writeFile(r,e.trim()+"\n","utf-8")}let u="";v(r)&&(u=await M.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await M.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var cP="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:cP,category:e.name});return v(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:cP});if(!v(e))return[];const t=[],n=getRootTasteFile({target:cP});if(v(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await M.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:cP});await M.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:cP}),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:cP});return v(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!v(n))return;const r=await M.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 p=getTastePath({target:"local-project"}),g=e.join(p,r.category);if(!v(g))return l;const h=getCategoryTasteFile({target:"local-project",category:r.category});if(!v(h))return l;const f=await M.readFile(h,"utf-8"),y=new Blob([f],{type:"text/markdown"}),w=new File([y],"taste.md",{type:"text/markdown"});return l.append(`files[${r.category}/taste.md]`,w),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(v(a)){const e=await M.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:ls.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}${Ct.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}${Ct.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:ls.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()}${Ct.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:ls.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()}${Ct.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()}${Ct.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()}${Ct.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 M.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 be("list").alias("ls").option("-g, --global","List global packages").addOption(new Ee("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ee("--staging","Use staging environment").hideHelp()).description(`List available packages ${ie.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"),Ft(),Cs(),Ft(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),zt(),Ft(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),NC(),gs(),Ft(),po(),gs(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Ft(),Cs(),po(),zt(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),Cn(),__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 uP={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?uP.remote:e.global?uP.global:uP.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${ve.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${ve.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` ${ie.white(e.category)}${e.isPublic?ie.green(" [public]"):""}${e.isPublic&&e.starCount?ie.yellow(` ${ve.star}${e.starCount}`):""}${e.downloadCount?ie.gray(` ${ve.arrowDown}${e.downloadCount}`):""}${n}${ie.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?Ce(`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${oP} Packages`),console.log(`${ie.gray("⎿")} ${ie.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(ie.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(ie.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 M.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 ot([{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"),Ft(),Ft(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var dP=new Set(["local-project","local-global","remote-project","remote-user"]);async function open9(e){const{package:t,target:n}=e;if(!dP.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=ut.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 be("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 ${ie.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 ue(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ie.green(ve.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(`${ie.green(ve.tick)} Opened ${ie.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"),Ft(),Ft(),Ft(),Ft();var mP=null,pP=!1;function setActiveSpinner(e){mP=e}function stopActiveSpinner(e){mP&&(mP.stop(e),mP=null)}function setPrompted(e){pP=e}function wasPrompted(){return pP}function beginPrompt(e,t){stopActiveSpinner(),Pe.intro(ie.dim(e)),t&&Pe.log.message(ie.dim(t)),setPrompted(!0)}function handleCancel(e){Pe.isCancel(e)&&(Pe.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Pe.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Pe.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),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ie.green(`'${t}'`)} from ${n}`,o),Pe.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${s} learnings ${ie.dim(`(from ${n})`)}`);const i=await Pe.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),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${ie.green(`'${t}'`)} to global`,s),Pe.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const o=await Pe.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),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ie.green(`'${t}'`)} from global`,s),Pe.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const o=await Pe.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),Pe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ct(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ie.green(`'${t}'`)} to ${n}`,o),Pe.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${s} learnings) in ${n}`),Pe.log.info(`Current package: ${ie.cyan(i)} ${ie.dim("(review)")}`);const a=await Pe.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),Pe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ct(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ie.green(`'${t}'`)} to ${n}`,o),Pe.log.message(`Local: ${r} learnings\nRemote: ${s} learnings`),Pe.log.info(`Current package: ${ie.cyan(i)} ${ie.dim("(review)")}`);const a=await Pe.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"),Ft(),Ft(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Ft(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var gP=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),hP=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),fP=__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 gP({pkg:"all",error:`Invalid source: ${n}`});const o=fP(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return gP({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return gP({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=hP();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 gP({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=hP();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:s,result:o})}catch(e){return gP({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Pe.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()?"":`${ve.tick} `,a=r?ie.dim(`\n ${shortenPath(r)}`):"";if(s.overwrite)return`${ie.green(i)}Replaced ${ie.green(`'${t}'`)} taste package in project`+a;if(o){const e=formatMergeParts(o);return`${ie.green(i)}Pulled ${ie.green(`'${t}'`)} taste package from ${n} ${ie.gray(`(${e.join(", ")})`)}`+a}return`${ie.green(i)}Pulled ${ie.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(`${ie.green("Pulled")} (${o.length}) ${o.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${ie.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),s.length>0&&l.push(wrapLine(`${ie.dim("Skipped")} (${s.length}) ${ie.dim(s.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&Pe.log.message(l.join("\n")),Pe.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${ie.green(ve.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(ie.yellow(`Skipped '${s[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new be("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 Ee("--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 Ee("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ie.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(Ce("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(Ce("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 Yy({baseUrl:e}),n=await t.get({endpoint:Ct.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 Pe.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()?"":`${ve.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${ie.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()?"":`${ve.tick} `;if(!a)return logResult2(`${ie.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?` ${ie.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${ie.green(l)}Replaced ${o} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${ie.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 p=formatMergeParts({added:u,updated:d,unchanged:m}),g=p.length>0?` ${ie.gray(`(${p.join(", ")})`)}`:"";return logResult2(`${ie.green(l)}Pushed ${o} to ${a}${g}`),(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()?"":`${ve.tick} `,l=!o&&s?ie.dim(`\n ${shortenPath(s)}`):"";if(n.overwrite)return logResult2(`${ie.green(a)}Replaced ${ie.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${ie.green(a)}Pushed ${ie.green(`'${r}'`)} taste package to ${i} ${ie.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${ie.green(a)}Pushed ${ie.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()?"":`${ve.tick} `;return logResult2(wrapLine(`${ie.green(s)}Pushed ${ie.green(t.packagesPushed.length)} taste packages ${ie.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(ie.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(`${ie.green("Merged")} (${s.length}) ${s.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${ie.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${ie.dim("Skipped")} (${r.length}) ${ie.dim(r.join(", "))}`,4)),i.length>0&&Pe.log.message(i.join("\n"));const a=`${o} ${1===o?"package":"packages"}`;Pe.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(`${ie.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&s.push(wrapLine(`${ie.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&s.push(wrapLine(`${ie.dim("Skipped")} (${n.length}) ${ie.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"),Ft(),__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"),Ft(),Cn(),Ft(),Cs(),bw(),zt(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Ft(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Ft(),NC(),Ft();var yP=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),wP=__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=wP(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 yP({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var SP=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),bP=__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 EP=__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=EP({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 SP({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return SP({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}):SP({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return SP({pkg:"all",error:`Invalid target: ${r}`});const m=bP();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 SP({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 SP({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,p=bP();if("skip"===d)return p.skipped.push(r),p;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m,overwrite:!0}),p.packagesPushed.push(r),p.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),p.packagesPushed.push(r),p.mergeDetails[r]=t}return p.filePaths[r]=`${n}/${r}`,p}async function pushRemote(e){const{packageName:t}=e;if(!exists2())return SP({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return SP({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 Pe.select({message:"Owner",options:r,initialValue:t});return Pe.isCancel(s)&&(Pe.cancel("Operation cancelled"),process.exit(0)),s}function createPushCommand(){return new be("push").description(`Push taste packages to remote ${ie.dim("(commandcode.ai)")} or global ${ie.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 Ee("--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 Ee("--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"),Ft(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var vP=__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};Pe.intro(ie.dim(`pushing ${t}`)),setPrompted(!0);const s=Pe.spinner();s.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(s.error("Failed"),Pe.outro(ie.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(ie.dim(` Pushing ${o} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner(Ce("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:vP(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:vP(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=Pe.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Ce("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(ie.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner(Ce("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 be(At.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()),e}function formatVersion(e,t,n=!1){const r=n?ae.bold(ae.green(t)):ae.white(t);return`${ae.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${ae.bold(ae.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(ae.dim(`Run ${ae.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(ae.dim("Try updating manually:")),console.log(ae.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(ae.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=Ce("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(`${ae.green(ve.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${ae.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=Ce("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} ${ve.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:ls.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 ${ae.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"),__name(createTasteCommand,"createTasteCommand"),Ft(),zt(),gs(),__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 CP=new be("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Ft(),po(),NC();var kP=__name((e,t)=>`${ve.info} ${e}: ${ae.cyan(t)}`,"formatInfoLine"),TP=__name(e=>ae.bold(`${e}:`),"formatSectionHeader"),_P=__name(e=>ae.red(e),"formatError"),xP=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),PP=__name(e=>["",TP("User Information"),kP("Name",e.name),kP("Email",e.email),kP("Username",e.userName)],"buildUserOutput"),AP=__name(e=>["",TP("Organization"),kP("Name",e.name),kP("Login",e.login)],"buildOrgOutput"),IP=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),NP=__name((e,t)=>{IP(PP(e)),t&&IP(AP(t)),console.log("")},"displayUserInfo"),RP=__name(e=>null!==e&&e.length>0,"validateApiKey"),$P=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=Ce("Fetching user information...").start();try{const t=await getAuthKey();RP(t)||(e.fail(_P('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();$P(n)||(e.fail(_P("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),NP(n.user,n.org)}catch(t){e.fail(_P(`Error: ${xP(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var MP=new be("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"!==N("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=N("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=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(!N(`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:""===N("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 N("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")}}Ft(),Ft(),zt(),bw(),Cs(),Ht(),vr(),Ft(),__name(normalizeGitUrl,"normalizeGitUrl"),__name(validateGitRepo,"validateGitRepo"),Ft(),__name(getGitHubToken,"getGitHubToken"),Ft(),Cs(),po(),Ft();var DP=["completed","failed","cancelled","timed_out"];function isTerminalStatus(e){return DP.includes(e)}__name(isTerminalStatus,"isTerminalStatus");var LP={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=LP[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=Ce({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=Ce({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: ${ae.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(`${ve.cross} ${ae.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${ae.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(`${ve.cross} ${ae.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=Ce({stream:process.stderr,text:"Reconnecting..."}).start());const l=__name(()=>{i.phase="done",stopAllSpinners({state:i}),o.close(),console.error(`\n${ae.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${ae.cyan(`cmd --experimental sandbox --id ${e}`)}`),p(),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${ae.yellow("Sandbox stopped.")}`),p(),t()},"cancelSandbox"),d=setupResizeForwarding({ws:o}),m=setupInputHandling({callbacks:{onCancel:u,onDetach:l}});process.once("SIGTERM",l);const p=__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(`${ae.yellow("[Ctrl+C]")} ${ae.dim("stop")} ${ae.yellow("[Ctrl+D]")} ${ae.dim("detach")}`),console.error(`${ae.dim("Session:")} ${ae.gray(e)}`),console.error(""),r&&(i.workingSpinner=Ce({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(),p(),t())}catch{}}),o.addEventListener("error",()=>{p(),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}),p(),console.error(`\n${ae.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${ae.cyan(`cmd --experimental sandbox --id ${e}`)}`),t())})})}function readLocalConfigFiles(){let e="",t="";try{e=w.readFileSync(getAuthFile(),"utf-8")}catch{}try{t=w.readFileSync(getConfigFile(),"utf-8")}catch{}return{auth:e,config:t}}async function askQuestion(e){const t=Ye.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 Yy({baseUrl:getApiBaseUrl()}).post({endpoint:Ct.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(ae.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(`${ae.bold("What do you want to do?")}\n${ae.cyan(">")} `);if(!i.trim())return void console.error(ae.yellow("No prompt provided. Aborting."));const a=i.trim().slice(0,It.MAX_PROMPT_CHARS),l=Ce({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(ae.red("Authentication failed. Try logging in again: cmd login")):console.error(ae.red(t)),process.exit(1)}}function createSandboxCommand(){return new be("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(ae.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(f.tmpdir(),`commandcode-skill-${W()}`);await D.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 D.access(l),d=!0}catch{}if(!d)try{await D.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 D.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(()=>(FC(),qC)),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 D.access(n),n}catch{}const r=t.join(e,"skill.md");try{return await D.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 D.readFile(t,"utf-8"),{data:r}=Fe(n),s=Ih.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 D.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 D.mkdir(a,{recursive:!0});const d=t.join(a,r),{randomUUID:m}=await import("crypto"),p=t.join(a,`.${r}.tmp.${m()}`);try{await D.cp(u,p,{recursive:!0,force:!0,dereference:!1}),l&&o&&await D.rm(d,{recursive:!0,force:!0}),await D.rename(p,d)}catch(e){if(await D.rm(p,{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 g;try{g=await resolveSkillMdPath(d)}catch{g=t.join(d,"SKILL.md")}return{name:r,description:n,location:i,path:g}}finally{d&&await D.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 D.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"),Sr(),Ft(),Ft(),Ft(),Ft(),OC(),__name(validateSafeString,"validateSafeString"),__name(parseGitHubRepo,"parseGitHubRepo"),__name(buildGigetSource,"buildGigetSource"),__name(fetchSkillFromGitHub,"fetchSkillFromGitHub"),__name(discoverSkillsInRepo,"discoverSkillsInRepo"),$w(),Qh(),__name(resolveSkillMdPath,"resolveSkillMdPath"),__name(validateSkillName,"validateSkillName"),__name(validateSkillContent,"validateSkillContent"),__name(skillExists,"skillExists"),__name(discoverSkills,"discoverSkills"),__name(installSkill,"installSkill"),__name(removeSkill,"removeSkill"),__name(listSkills,"listSkills"),zt();var OP=[`${ae.dim("Usage:")}`,` ${ae.cyan("cmd skills add")} ${ae.white("<owner/repo>")}`,"",`${ae.dim("Examples:")}`,` ${ae.cyan("cmd skills add")} ${ae.white("acme/my-skills")} ${ae.dim("# single-skill repo")}`,` ${ae.cyan("cmd skills add")} ${ae.white("acme/skills/path/to/skill")} ${ae.dim("# specific path in repo")}`,` ${ae.cyan("cmd skills add")} ${ae.white("acme/multi-skills -s my-skill")} ${ae.dim("# pick one from multi-skill repo")}`,` ${ae.cyan("cmd skills add")} ${ae.white("acme/repo@branch")} ${ae.dim("# specific branch")}`,` ${ae.cyan("cmd skills add")} ${ae.white("acme/repo --global")} ${ae.dim("# install to ~/.commandcode/skills/")}`],qP=__name((e,t)=>`${ae.green(ve.tick)} Installed ${ae.cyan(e)} ${ae.dim(`${ve.arrowRight} ${t}/`)}`,"formatInstalled"),FP=__name(e=>`${ae.red(ve.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){e&&await L(e,{recursive:!0,force:!0}).catch(()=>{}),process.exit(t)}function validateRepoFormat(e){(e.startsWith(".")||e.startsWith("/")||e.startsWith("~"))&&(console.error(FP("Local paths are not supported. Skills must be installed from GitHub.")),console.log(""),OP.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(FP(`Invalid repository: "${e}"`)),console.log(""),console.log(`Expected format: ${ae.cyan("owner/repo")} or ${ae.cyan("owner/repo/path")}`),console.log(""),OP.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=Ce({text:`Fetching ${ae.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(FP(`No skills found in ${ae.cyan(e)}`)),console.log(ae.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(FP(`Skill "${t.skill}" not found in ${ae.cyan(e)}`)),console.log(""),console.log(ae.dim("Available skills:")),l.forEach(e=>console.log(` ${ae.cyan(e.name)}`)),await cleanupAndExit(s,1)),i=[n]}else if(1===l.length)i=[l[0]];else if(n){const t=await Ae({message:`Select skills to install from ${e}`,options:l.map(e=>({value:e.name,label:e.name})),required:!0});"symbol"==typeof t&&(console.log(ae.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=Ce({text:`Installing ${ae.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(qP(i.name,r))}catch(e){d++;const t=e instanceof Error?e.message:String(e);console.error(FP(`Failed to install "${n.name}"`)),console.log(ae.dim(` ${t}`))}await cleanupAndExit(s,d>0?1:0)}catch(e){o.stop();const t=e instanceof Error?e.message:String(e);console.error(FP(t)),await cleanupAndExit(s,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction,"addAction");var jP=new be("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${OP.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(FP("No repository specified.")),console.log(""),OP.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction);Ft(),zt();var BP=__name((e,t)=>`${ae.green(ve.tick)} Removed ${ae.cyan(e)} from ${t} skills`,"formatRemoved"),zP=__name(e=>`${ae.red(ve.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(zP(s)),console.log(ae.dim(`Run ${ae.cyan("cmd skills list")} to see installed skills.`)),process.exit(1)),!t.yes&&n){const t=await Ie({message:`Remove ${ae.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(ae.dim("Cancelled")),process.exit(0))}await removeSkill({skillName:e,global:t.global}),console.log(BP(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill";r.includes("not found")?(console.error(zP(`Skill "${e}" not found in ${t.global?"global":"project"} skills`)),t.global||console.log(ae.dim(`Try ${ae.cyan(`cmd skills remove ${e} --global`)} to check global skills.`)),console.log(ae.dim(`Run ${ae.cyan("cmd skills list")} to see installed skills.`))):console.error(zP(r)),process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction,"removeAction");var UP=new be("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);Ft(),$w(),$s(),zt();var WP=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${ae.cyan(e)} ${ae.dim(`· ${n}`)}`},"formatSkillLine"),GP=__name((e,t)=>`${ae.bold(ae.white(e))} ${ae.dim(`(${t})`)}`,"formatSectionHeader"),HP=__name(()=>["",ae.dim("No skills installed."),"",ae.dim("Looking in:"),ae.dim(` ${getGlobalSkillsDir()} ${ae.white("(global)")}`),ae.dim(` ${getProjectSkillsDir()} ${ae.white("(project)")}`),"",`Install a skill: ${ae.cyan("cmd skills add")} ${ae.dim("<owner/repo>")}`,""],"formatEmptyHint"),QP=__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&&(QP(HP()),process.exit(0)),console.log(""),console.log(heading({text:"Skills",sub:ae.dim(`${n} installed`)})),t.length>0&&(console.log(""),console.log(GP("Project",t.length)),t.forEach(e=>{console.log(WP(e.name,e.description))})),e.length>0&&(console.log(""),console.log(GP("Global",e.length)),e.forEach(e=>{console.log(WP(e.name,e.description))})),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${ae.red(ve.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction,"listAction");var VP=new be("list").description("List all installed skills").action(listAction),KP=new be("skills").description("Manage skills from GitHub repositories").addCommand(jP).addCommand(UP).addCommand(VP);handleUnhandledErrors(),setupTelemetry(),await preRun();var YP=createProgram();YP.action(interactiveModeAction),YP.addCommand(Yx),YP.addCommand(Jx),YP.addCommand(MP),YP.addCommand(CP),YP.addCommand(Kx),YP.addCommand(createTasteCommand()),YP.addCommand(createMcpCommand()),YP.addCommand(Xx),YP.addCommand(ps),YP.addCommand(zs),YP.addCommand(Js),YP.addCommand(KP),isExperimentalEnabled()&&YP.addCommand(createSandboxCommand()),setupCommanderHooks(YP),YP.parse();
|
|
277
|
+
`})])),b(Ky)}}),fw=__esm({"../shared/src/database/schema/index.ts"(){Ft(),$h(),ow(),iw(),Rh(),aw(),lw(),cw(),uw(),dw(),mw(),pw(),gw(),hw(),Mh()}}),yw=__esm({"../shared/src/database/config/database.ts"(){Ft(),sw(),fw()}}),ww=__esm({"../shared/src/database/index.ts"(){Ft(),yw(),fw()}}),Sw=__esm({"../shared/src/index.ts"(){Ft(),fo(),yo(),Yh(),Jh(),Xh(),zt(),jt(),ww()}}),bw=__esm({"src/api/request.ts"(){Ft(),po(),ho(),gs(),jr(),Tr(),Sw(),Yy=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}),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 eo({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",[vt.CLI_ENVIRONMENT]:a,...n?{Authorization:`Bearer ${n}`}:{},...o?{traceparent:o}:{},...e}}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:Zs.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"})}}}}),Ew=__esm({"../shared/src/constants/tools.ts"(){Ft(),Jy={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"},Xy={WEB_SEARCH:"web_search",WEB_FETCH:"web_fetch"},Zy=__name(e=>e===Xy.WEB_SEARCH,"isWebSearchTool"),ew=["web_search_tool_result_error","web_search_tool_error","web_fetch_tool_result_error","web_fetch_tool_error"],tw=__name(({serverToolBlock:e,contentBlocks:t})=>{const n=t.find(t=>("web_search_tool_result"===t.type||"web_fetch_tool_result"===t.type)&&t.tool_use_id===e.id);return ew.includes(n?.content?.type)?{message:`Error: ${n?.content?.error_code||"unknown_error"}`,isError:!0}:Zy(e.name)?{message:"Found 10 results",isError:!1}:{message:"Content fetched",isError:!1}},"getServerToolOutputMessage"),nw=["create_file","delete_file",Jy.EDIT_FILE,Jy.WRITE_FILE,Jy.SHELL_COMMAND],rw=[Jy.SHELL_COMMAND]}});function getEnterpriseMemoryPath(){switch(h.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=h.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:v(n),description:"Organization-wide instructions"});const r=process.cwd();if(r){const e=getProjectMemoryPaths(r);for(const n of e)if(v(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:v(s),description:"Personal preferences for all projects"}),t}async function loadMemoryFile(e){try{return v(e)&&_(e).isFile()?await M.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(h.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(v(s)){const e=await loadMemoryFile(s);if(e){const t=await processImports(e,s);r.set(s,t)}}const o=getUserMemoryPath();if(v(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(v(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(v(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 v(r)||await M.mkdir(r,{recursive:!0}),v(t)||await M.writeFile(t,"# AGENTS.md\n\n","utf-8"),new Promise((e,r)=>{const s=R(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 v(n)||await M.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 vw,Cw,kw,Tw,_w,xw,Pw,Aw=__esm({"src/utils/memory.ts"(){Ft(),zt(),__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(vw))return t.includes(kw)?t:t.includes(Cw)?t.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"").replace(vw,kw):t.replace(vw,kw);let n=t;return n.includes(Cw)&&(n=n.replace(/\n{0,2}\[cmd\]: https:\/\/commandcode\.ai\/\n?/g,"")),xw.test(n)?n=n.replace(xw,`$1${kw}`):Pw.test(n)&&(n=n.replace(Pw,`$1${kw}`)),n}var Iw=__esm({"src/commands/taste/utils/header-migration.ts"(){Ft(),kw=`${vw="# Taste (Continuously Learned by [CommandCode][cmd])"}\n\n${Cw="[cmd]: https://commandcode.ai/"}`,Tw="# Taste (Continuously Learned by CommandCode)",_w="# Taste (Continuously Learned by CommandCode.ai)",xw=/^(\s*)# Taste \(Continuously Learned by CommandCode\)(?!\.ai)/,Pw=/^(\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(!v(n))return null;const r=await M.readFile(n,"utf-8"),s=r.trim();return s&&s!==kw&&s!==vw&&s!==_w&&s!==Tw?r:null}catch(e){return null}}var Nw=__esm({"src/utils/taste/get-taste-content.ts"(){Ft(),zt(),Iw(),__name(getTasteContent,"getTasteContent")}}),Rw=__esm({"src/tools/skills/types.ts"(){Ft()}});function getGlobalSkillsDir(){return t.join(f.homedir(),".commandcode","skills")}function getProjectSkillsDir(){let e,n=process.cwd(),r=n;for(;;){if(v(t.join(r,".git"))){e=r;break}const n=t.dirname(r);if(n===r)break;r=n}if(e)return t.join(e,".commandcode","skills");for(r=n;;){const e=t.join(r,".commandcode");if(v(e))return t.join(e,"skills");const n=t.dirname(r);if(n===r)break;r=n}return t.join(process.cwd(),".commandcode","skills")}async function resolveSkillFilePath(e){const{skillDir:n}=e,r=t.join(n,"SKILL.md");try{return await D.access(r),r}catch{}const s=t.join(n,"skill.md");try{return await D.access(s),s}catch{return null}}async function loadSkillSummariesFromDirectory(e){const{dir:n}=e;try{await D.access(n);const e=await D.readdir(n,{withFileTypes:!0}),r=(await Promise.all(e.map(async e=>{if(e.isDirectory())return e;if(e.isSymbolicLink())try{return(await D.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 D.readFile(r,"utf-8"),{data:o}=Fe(s),i=Ih.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[]}}async function loadAllSkillSummaries(){const[e,t]=await Promise.all([loadSkillSummariesFromDirectory({dir:getGlobalSkillsDir()}),loadSkillSummariesFromDirectory({dir:getProjectSkillsDir()})]);return{global:e,project:t}}var $w=__esm({"src/tools/skills/loader.ts"(){Ft(),Qh(),zt(),__name(getGlobalSkillsDir,"getGlobalSkillsDir"),__name(getProjectSkillsDir,"getProjectSkillsDir"),__name(resolveSkillFilePath,"resolveSkillFilePath"),__name(loadSkillSummariesFromDirectory,"loadSkillSummariesFromDirectory"),__name(loadAllSkillSummaries,"loadAllSkillSummaries")}});function escapeXML(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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 Mw,Dw,Lw=__esm({"src/tools/skills/xml-generator.ts"(){Ft(),__name(escapeXML,"escapeXML"),__name(generateSkillsXML,"generateSkillsXML")}}),Ow=__esm({"src/tools/skills/index.ts"(){Ft(),Rw(),$w(),Lw()}}),qw=__esm({"src/tools/read-file/types.ts"(){Ft(),Mw=g.object({absolutePath:g.string().describe("The absolute path to the file to read"),offset:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional()).describe("Optional line number to start reading from (0-based index)"),limit:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional()).describe("Optional number of lines to read")}),g.object({content:g.union([g.string(),g.instanceof(Buffer)]),contentType:g.enum(["text","binary"]),fileType:g.string(),size:g.number(),linesRead:g.number().optional()}),Dw=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 Fw,jw=__esm({"src/utils/index.ts"(){Ft(),__name(isWindowsAbsolutePath,"isWindowsAbsolutePath")}});async function readFileContent(t){const{absolutePath:n,offset:r,limit:s}=t;if(!e.isAbsolute(n)&&!isWindowsAbsolutePath(n))throw new Dw("Path must be absolute (start with / on Unix/Linux/macOS or C:\\ on Windows)","INVALID_PATH");const o=e.normalize(n);try{await M.access(o,w.constants.F_OK|w.constants.R_OK)}catch{throw new Dw(`File not found or not readable: ${o}`,"FILE_ACCESS_ERROR")}if(!(await M.stat(o)).isFile())throw new Dw("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 Dw("Both offset and limit must be provided together for line-based reading","INVALID_PARAMS");if(void 0!==r&&r<0)throw new Dw("Offset must be >= 0","INVALID_OFFSET");if(void 0!==s&&s<=0)throw new Dw("Limit must be > 0","INVALID_LIMIT");try{if(a){const e=await M.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 M.readFile(o,"utf8");return{content:e,fileType:i,contentType:"text",size:Buffer.byteLength(e,"utf8")}}}catch(e){if(e instanceof Dw)throw e;throw new Dw(`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",...Fw}[n]||"unknown"}function isBinaryFile(e){return Object.values(Fw).includes(e)}async function readTextFileLines(e,t,n){const r=(await M.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,zw=__esm({"src/tools/read-file/read-file.ts"(){Ft(),jw(),qw(),__name(readFileContent,"readFileContent"),Fw={".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 Uw=__esm({"src/tools/utils/read-summary.ts"(){Ft(),__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 Ww,Gw,Hw,Qw,Vw,Kw=__esm({"src/tools/read-file/formatter.ts"(){Ft(),Uw(),__name(formatOutput,"formatOutput")}}),Yw=__esm({"src/tools/read-file/index.ts"(){Ft(),qw(),zw(),Kw(),Ww={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=Mw.parse(e);return formatOutput(await readFileContent(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading file"}},"execute")}}}),Jw=__esm({"src/tools/edit-file/types.ts"(){Ft(),Gw=g.object({filePath:g.string().describe("The absolute path to the file to edit"),oldValue:g.string().describe("The text to replace"),newValue:g.string().describe("The new text to insert"),replacementCount:g.number().optional().describe("The number of replacements to make (default: 1, used only when replaceAll is false)"),replaceAll:g.boolean().optional().describe("Whether to replace all occurrences (default: false)")}),g.object({path:g.string(),replacementsCount:g.number(),oldContent:g.string(),newContent:g.string()}),g.object({name:g.string(),message:g.string(),code:g.string().optional()})}}),Xw=__esm({"src/lib/checkpoints/types.ts"(){Ft(),Hw=g.object({backupFileName:g.string().nullable(),version:g.number().int().positive(),backupTime:g.string().datetime()}),Qw=g.object({messageId:g.string().uuid(),trackedFileBackups:g.record(g.string(),Hw),timestamp:g.string().datetime()}),g.object({type:g.literal("file-history-snapshot"),messageId:g.string().uuid(),snapshot:Qw,isSnapshotUpdate:g.boolean()}),g.object({maxFileSize:g.number().int().positive().default(10485760),retentionDays:g.number().int().positive().default(30)}),Vw=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`${U.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(f.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 D.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 D.mkdir(t,{recursive:!0})}async function atomicWriteFile(e){const{filePath:t,content:n}=e,r=`${t}.tmp`;try{await D.writeFile(r,n);const e=await D.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 D.rename(r,t)}catch(e){try{await D.unlink(r)}catch{}throw e}}async function getFileSizeBytes(e){const{filePath:t}=e;try{return(await D.stat(t)).size}catch{return-1}}async function fileExists(e){const{filePath:t}=e;try{return await D.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 Zw,eS,tS,nS,rS=__esm({"src/lib/checkpoints/utils.ts"(){Ft(),zt(),__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")}}),sS=__esm({"src/lib/checkpoints/file-history.ts"(){Ft(),Xw(),rS(),gs(),Zw={maxFileSize:10485760,retentionDays:30},eS=class{static{__name(this,"FileHistoryManager")}sessionId;config;status;trackedState;noticeDismissed;constructor(e){const{sessionId:t,config:n}=e;this.sessionId=t,this.config={...Zw,...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 D.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:ls.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 D.unlink(t));const r=getBackupFilePath({sessionId:this.sessionId,backupFileName:n.backupFileName});if(!await fileExists({filePath:r})){const e=new Vw(`Backup file not found: ${n.backupFileName}`,"BACKUP_FILE_MISSING");throw trackError({error:sanitizeErrorForTelemetry({error:e,label:"backup_file_missing"}),context:{component:ls.FILE_HISTORY,heading:"Backup file missing during restore",code:e.code}}),e}const s=await D.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 D.access(t,D.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 D.readdir(n);for(const s of e)if(!s.endsWith(".tmp")&&!t.has(s))try{await D.unlink(`${n}/${s}`),r++}catch{}}catch{}return r}async deleteAllBackups(){const e=getFileHistoryPath({sessionId:this.sessionId});try{await D.rm(e,{recursive:!0,force:!0})}catch{}this.trackedState.files.clear(),this.trackedState.versions.clear()}getSessionId(){return this.sessionId}}}}),oS=__esm({"src/lib/checkpoints/checkpoint-manager.ts"(){Ft(),sS(),rS(),os(),gs(),tS=class{static{__name(this,"CheckpointManager")}fileHistoryManager;sessionStore;snapshots;config;constructor(e){const{sessionId:t,sessionStore:n,config:r}=e;this.fileHistoryManager=new eS({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:ls.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 nS=new tS({sessionId:t})}async function backupFileBeforeEdit(e){const{filePath:t}=e;return nS?nS.backupFile({filePath:t}):{success:!0,backup:null}}var iS=__esm({"src/lib/checkpoints/checkpoint-service.ts"(){Ft(),oS(),nS=null,__name(initializeCheckpointService,"initializeCheckpointService"),__name(backupFileBeforeEdit,"backupFileBeforeEdit")}}),aS=__esm({"src/lib/checkpoints/index.ts"(){Ft(),Xw(),sS(),oS(),rS(),iS()}});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 P.access(n,A.F_OK|A.R_OK|A.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 P.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 lS=__esm({"src/tools/edit-file/edit-file.ts"(){Ft(),zw(),jw(),Jw(),aS(),__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 cS,uS,dS,mS=__esm({"src/tools/edit-file/formatter.ts"(){Ft(),__name(formatOutput2,"formatOutput")}}),pS=__esm({"src/tools/edit-file/index.ts"(){Ft(),Jw(),lS(),mS(),cS={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=Gw.parse(e);return formatOutput2(await editFile(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while editing file"}},"execute")}}}),gS=__esm({"src/tools/read-directory/types.ts"(){Ft(),uS=g.object({path:g.string().describe("The absolute path to the directory to read"),exclude:g.array(g.string()).optional().describe("Optional array of glob patterns to exclude"),respectGitIgnore:g.boolean().optional().describe("Whether to respect .gitignore patterns (default: true)")}),g.object({files:g.array(g.string()),directories:g.array(g.string())}),dS=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 dS("Path must be absolute, not relative","INVALID_PATH");try{if(!(await M.stat(n)).isDirectory())throw new dS("Path is not a directory","NOT_A_DIRECTORY")}catch(e){if(e instanceof dS)throw e;throw new dS(`Directory does not exist or is not accessible: ${n}`,"DIRECTORY_ACCESS_ERROR")}try{const t=await M.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 M.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 dS)throw e;throw new dS(`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 findGitRoot(t);for(;r&&isWithinGitRoot(r,s);){const t=e.join(r,".gitignore");try{const e=(await M.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 findGitRoot(e)}catch{return!1}}async function findGitRoot(t){let n=e.resolve(t);for(;;){try{const t=e.join(n,".git");if((await M.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(je(e,n))return!0;return!1}var hS=__esm({"src/tools/read-directory/read-directory.ts"(){Ft(),gS(),__name(readDirectory,"readDirectory"),__name(loadGitIgnorePatterns,"loadGitIgnorePatterns"),__name(isInGitRepository,"isInGitRepository"),__name(findGitRoot,"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 fS,yS,wS=__esm({"src/tools/read-directory/formatter.ts"(){Ft(),__name(formatOutput3,"formatOutput")}}),SS=__esm({"src/tools/read-directory/index.ts"(){Ft(),gS(),hS(),wS(),fS={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=uS.parse(e);return formatOutput3(await readDirectory(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while reading directory"}},"execute")}}}),bS=__esm({"src/tools/write-file/types.ts"(){Ft(),yS=g.object({filePath:g.string().describe("The absolute path where the file should be written"),content:g.string().describe("The content to write to the file")}),g.object({success:g.boolean(),message:g.string(),path:g.string().optional()})}});async function writeFile3({filePath:e,content:n}){const s=e.startsWith("~/")?t.join(f.homedir(),e.slice(2)):e;if(!l(s))throw new Error(`Invalid file path: '${s}'. Only absolute paths are supported.`);try{const e=r(s);return v(e)||await B(e,{recursive:!0}),await backupFileBeforeEdit({filePath:s}),await O(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"(){Ft(),aS(),__name(writeFile3,"writeFile")}});function formatOutput4(e){return e.success?`File written: ${e.path}`:`Error: ${e.message}`}var vS,CS,kS,TS,_S,xS=__esm({"src/tools/write-file/formatter.ts"(){Ft(),__name(formatOutput4,"formatOutput")}}),PS=__esm({"src/tools/write-file/index.ts"(){Ft(),bS(),ES(),xS(),vS={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=yS.parse(e),n=await writeFile3(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")}}}),AS=__esm({"src/tools/read-multiple-files/types.ts"(){Ft(),CS=g.object({include:g.array(g.string()).describe("Array of glob patterns to include files"),exclude:g.array(g.string()).optional().describe("Array of glob patterns to exclude files"),defaultExclude:g.boolean().optional().describe("Whether to apply default exclusions (node_modules, dist, etc.). Default: true"),gitIgnore:g.boolean().optional().describe("Whether to respect .gitignore files. Default: true"),targetDirectory:g.string().optional().describe("Base directory for relative paths. Default: current working directory")}),kS=g.object({filePath:g.string(),content:g.string(),fileType:g.string(),size:g.number()}),g.object({content:g.string(),filesRead:g.array(g.string()),errors:g.array(g.object({file:g.string(),error:g.string()})),fileDetails:g.array(kS)}),TS=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 Be(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 TS("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(..._S);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 TS)throw e;throw new TS(`Failed to read files: ${e instanceof Error?e.message:String(e)}`,"READ_ERROR")}}var IS=__esm({"src/tools/read-multiple-files/read-multiple-files.ts"(){Ft(),zw(),AS(),_S=["**/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 NS,RS,$S,MS,DS,LS,OS,qS=__esm({"src/tools/read-multiple-files/formatter.ts"(){Ft(),Uw(),__name(getReadSummary,"getReadSummary"),__name(formatOutput5,"formatOutput")}}),FS=__esm({"src/tools/read-multiple-files/index.ts"(){Ft(),AS(),IS(),qS(),NS={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=CS.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")}}}),jS=__esm({"src/tools/grep/types.ts"(){Ft(),RS=g.object({pattern:g.string().min(1,"Pattern is required"),include:g.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},g.array(g.string()).optional()),directory:g.string().optional()})}});function estimateTokens(e){let t=0;if("string"==typeof e)t=estimateTextTokens(e),(e.startsWith("{")||e.startsWith("["))&&(t=Math.ceil(t*LS));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&&"source"in n&&"base64"===n.source.type)t+=estimateImageTokens(n.source.data);else if("tool_use"===n.type)t+=5,"name"in n&&n.name&&(t+=estimateTextTokens(n.name)),"input"in n&&n.input&&(t+=estimateTextTokens(JSON.stringify(n.input))*LS);else if("tool_result"===n.type&&(t+=3,"content"in n&&n.content))if("string"==typeof n.content)t+=estimateTextTokens(n.content);else if(Array.isArray(n.content))for(const e of n.content)"text"===e.type&&"text"in e&&(t+=estimateTextTokens(e.text));return Math.ceil(t)}function estimateTextTokens(e){if(!e)return 0;let t=e.length/DS;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)>$S}function checkToolOutputTokensLimit(e){return exceedsOutputTokenLimit(e)?OS: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"(){Ft(),os(),$S=ns,MS=2e5,DS=3.5,LS=1.1,__name(estimateTokens,"estimateTokens"),__name(estimateTextTokens,"estimateTextTokens"),__name(estimateImageTokens,"estimateImageTokens"),__name(getImageDimensions,"getImageDimensions"),__name(exceedsOutputTokenLimit,"exceedsOutputTokenLimit"),OS="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=R(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>es)return i=OS,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>ts)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 zS=__esm({"src/tools/grep/grep.ts"(){Ft(),os(),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 US,WS,GS,HS=__esm({"src/tools/grep/formatter.ts"(){Ft(),__name(formatGrepResults,"formatGrepResults")}}),QS=__esm({"src/tools/grep/index.ts"(){Ft(),jS(),zS(),HS(),BS(),US={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=RS.parse(e);return formatGrepResults(await grepSearchInDirectory(t))}catch(e){return e instanceof Error?e.message===OS?e.message:`ERROR: ${e.message}`:"ERROR: Unknown error occurred while searching files"}},"execute")}}}),VS=__esm({"src/tools/glob/types.ts"(){Ft(),WS=g.object({pattern:g.string().min(1,"Pattern is required"),path:g.string().optional()}),GS=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 GS("Pattern parameter is required","INVALID_PATTERN");try{const e=t.resolve(process.cwd(),r);if(!isPathInWorkspace(e))throw new GS("Search path must be within the current working directory or an added directory","INVALID_PATH");const s=await Be(n,{cwd:e,ignore:Mt,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 D.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 GS)throw e;if(e instanceof Error)throw new GS(`Failed to search for files: ${e.message}`,"SEARCH_ERROR");throw new GS("Unknown error occurred during file search","UNKNOWN_ERROR")}}var KS=__esm({"src/tools/glob/glob.ts"(){Ft(),VS(),zt(),Qt(),__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 YS,JS,XS,ZS=__esm({"src/tools/glob/formatter.ts"(){Ft(),__name(formatGlobResults,"formatGlobResults")}}),eb=__esm({"src/tools/glob/index.ts"(){Ft(),VS(),KS(),ZS(),YS={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=WS.parse(e);return formatGlobResults(await globSearch(t))}catch(e){return e instanceof Error?`ERROR: ${e.message}`:"ERROR: Unknown error occurred while finding files"}},"execute")}}}),tb=__esm({"src/tools/shell-command/types.ts"(){Ft(),JS=g.object({command:g.string().min(1,"Command cannot be empty"),args:g.preprocess(e=>{if("string"==typeof e){try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return[e]}return e},g.array(g.string()).optional()),directory:g.string().optional(),timeout:g.preprocess(e=>"string"==typeof e?parseInt(e,10):e,g.number().optional())}),XS=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 XS("Command cannot be empty","EMPTY_COMMAND");let a;if(s){if(e.isAbsolute(s))throw new XS("Directory cannot be absolute. Please use relative paths.","ABSOLUTE_PATH");a=e.resolve(process.cwd(),s)}else a=process.cwd();try{if(!(await D.stat(a)).isDirectory())throw new XS(`Path is not a directory: ${s}`,"NOT_A_DIRECTORY")}catch(e){if(e instanceof XS)throw e;throw new XS(`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?ze([n,...r]):n,p=setTimeout(()=>{if(!u){g.kill("SIGTERM");const e=Date.now()-i;s(new XS(`Command timed out after ${o}ms`,"TIMEOUT",null,"SIGTERM",a,l,e))}},o),g=R(m,[],e);g.stdout?.on("data",e=>{try{const t=e.toString();if(a.length+t.length>es)return l=OS,d=!0,void g.kill("SIGTERM");a+=t}catch(e){l+=`\n[Error processing stdout: ${e instanceof Error?e.message:"Unknown error"}]`,g.kill("SIGTERM")}}),g.stderr?.on("data",e=>{try{const t=e.toString();if(l.length+t.length>ts)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"}]`}}),g.on("close",(e,n)=>{u=!0,clearTimeout(p);const r=Date.now()-i;0===e?t({stdout:a.trim(),stderr:l.trim(),exitCode:e,signal:n,duration:r}):s(new XS(d?OS:`Command failed with exit code ${e}`,d?"OUTPUT_TRUNCATED":"COMMAND_FAILED",e,n,a.trim(),l.trim(),r))}),g.on("error",e=>{u=!0,clearTimeout(p);const t=Date.now()-i;s(new XS(`Failed to start command: ${e.message}`,"START_FAILED",null,null,a.trim(),l.trim(),t))})})}catch(e){if(e instanceof XS)throw e;throw new XS(`Unexpected error: ${e instanceof Error?e.message:String(e)}`,"UNEXPECTED_ERROR")}}var nb=__esm({"src/tools/shell-command/shell-command.ts"(){Ft(),tb(),os(),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 rb,sb=__esm({"src/tools/shell-command/formatter.ts"(){Ft(),__name(formatShellCommandResult,"formatShellCommandResult")}}),ob=__esm({"src/tools/shell-command/index.ts"(){Ft(),tb(),nb(),sb(),BS(),rb={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=JS.parse(e);return formatShellCommandResult(await executeShellCommand(t))}catch(e){if(e instanceof XS){if("OUTPUT_TRUNCATED"===e.code)return[e.stdout,OS].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 ib,ab=__esm({"src/tools/thinking/thinking.ts"(){Ft(),__name(think,"think")}}),lb=__esm({"src/tools/thinking/index.ts"(){Ft(),ab(),ib={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 cb,ub=__esm({"src/tools/todo-write/todo-write.ts"(){Ft(),__name(todoWrite,"todoWrite")}}),db=__esm({"src/tools/todo-write/index.ts"(){Ft(),ub(),cb={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 mb=__esm({"src/tools/ask-user-question/ask-user-question.ts"(){Ft(),__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 pb,gb,hb,fb=__esm({"src/tools/ask-user-question/formatter.ts"(){Ft(),__name(isErrorResponse,"isErrorResponse"),__name(formatOutput6,"formatOutput")}}),yb=__esm({"src/tools/ask-user-question/index.ts"(){Ft(),mb(),fb(),fb(),pb={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")}}}),wb=__esm({"src/tools/killshell/types.ts"(){Ft(),gb=g.object({port:g.number().int().min(1,{message:"Port must be between 1 and 65535"}).max(65535,{message:"Port must be between 1 and 65535"}).optional(),pid:g.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"}),hb=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=R(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 hb(`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 hb("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 hb(`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 Sb=__esm({"src/tools/killshell/killshell.ts"(){Ft(),wb(),__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(`${ve.tick} ${e.message}`),e.pid&&t.push(`PID: ${e.pid}`),e.processName&&t.push(`Process: ${e.processName}`),t.join("\n")}var bb,Eb,vb,Cb,kb,Tb,_b,xb,Pb,Ab,Ib,Nb,Rb,$b,Mb,Db,Lb,Ob,qb,Fb,jb=__esm({"src/tools/killshell/formatter.ts"(){Ft(),__name(formatKillshellResult,"formatKillshellResult")}}),Bb=__esm({"src/tools/killshell/index.ts"(){Ft(),wb(),Sb(),jb(),bb={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=gb.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")}}}),zb=__esm({"src/tools/exit-plan-mode/index.ts"(){Ft(),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")}}}),Ub=__esm({"src/tools/enter-plan-mode/index.ts"(){Ft(),vb={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")}}}),Wb=__esm({"src/tools/web-search/index.ts"(){Ft(),Cb={type:"web_search_20250305",name:"web_search",max_uses:5}}}),Gb=__esm({"src/tools/web-fetch/index.ts"(){Ft(),kb={type:"web_fetch_20250910",name:"web_fetch"}}}),Hb=__esm({"src/tools/get-diagnostics/types.ts"(){Ft(),Tb=g.preprocess(e=>{if("string"==typeof e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{return[e]}return e},g.array(g.string()).optional()),_b=g.object({filePaths:Tb.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.')})}}),Qb=__esm({"src/tui/vscode-context/ipc-client.ts"(){Ft(),Cn(),xb=t.join(f.homedir(),".commandcode","ide"),Pb=__name(e=>{const n=t.resolve(e);let r=n;try{r=S.realpathSync(n)}catch{}return"win32"===process.platform?r.toLowerCase():r},"normalizePathForComparison"),Ab=__name(e=>{try{return process.kill(e,0),!0}catch{return!1}},"isProcessAlive"),Ib=__name(e=>{if("win32"===process.platform)return null;try{const t=N(`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"),Nb=__name((e,t,n=Ib)=>{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"),Rb=__name(()=>"vscode"!==process.env.TERM_PROGRAM?null:process.env.CURSOR_TRACE_ID?"cursor":process.env.WINDSURF_SESSION_ID?"windsurf":"code","detectIDE"),$b=__name((e,n)=>{try{S.unlinkSync(e)}catch{}const r=t.basename(e,".json")+".sock";try{S.unlinkSync(t.join(n,r))}catch{}},"removeStaleSession"),Mb=__name((e,n={})=>{const{sessionDir:r=xb,parentPidFn:s=Ib,startPid:o=process.ppid}=n;try{if(!S.existsSync(r))return null;const n=`${e}-`,i=S.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(S.readFileSync(n,"utf-8"));if(!Ab(s.pid)){$b(n,r);continue}a.push({session:s,file:e})}catch{continue}if(0===a.length)return null;const l=Nb(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=Pb(process.cwd());let d=null,m=0;for(const{session:e}of a)for(const n of e.workspaceFolders){const r=Pb(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"),Db=__name(()=>{const e=Rb();return e?Mb(e):null},"resolveSocketPath"),Lb=__name(()=>({type:"request",id:W(),payload:{action:"getContext"}}),"createContextRequest"),Ob=__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"),qb=__name((e,t)=>{try{const n=JSON.parse(e.toString());if(!Ob(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"),Fb=class _VSCodeIPCClient{static{__name(this,"VSCodeIPCClient")}socket=null;socketPath;connected=!1;constructor(e){this.socketPath=e??Db()}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=_e.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=Lb();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=qb(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:W(),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(!Rb())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 Fb;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 Vb=__esm({"src/tools/get-diagnostics/get-diagnostics.ts"(){Ft(),Qb(),Cn(),__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 Kb,Yb,Jb,Xb,Zb,eE,tE,nE,rE,sE,oE=__esm({"src/tools/get-diagnostics/formatter.ts"(){Ft(),__name(formatDiagnostics,"formatDiagnostics")}}),iE=__esm({"src/tools/get-diagnostics/index.ts"(){Ft(),Hb(),Vb(),oE(),Kb={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=_b.parse(e);return formatDiagnostics(await fetchDiagnostics(t.filePaths))},"execute")}}}),aE=__esm({"src/utils/help-data.ts"(){Ft(),zt(),Yb="Coding agent that continuously learns your taste of writing code.",Jb=34,Xb=[{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"}],Zb=[{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"}],eE=[{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:"/help",description:"Display help information"},{key:"/exit",description:"Exit Command Code"}],tE=[{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 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"}],nE=[{key:"Documentation",description:"https://commandcode.ai/docs"},{key:"Discord Community",description:"https://commandcode.ai/discord"}],rE=[{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 --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"}],sE='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(Xb)}\n\n## SLASH COMMANDS (type these in the chat input)\n${formatHelpItems(eE)}\n\n## CLI SUBCOMMANDS\n${formatHelpItems(tE)}\n\n## CLI EXAMPLES\n${formatHelpItems(rE)}\n\n## CLI OPTIONS (flags when launching cmd)\n${formatHelpItems(Zb)}\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/)\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/), 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(nE)}`}var lE,cE,uE,dE,mE=__esm({"src/tools/get-self-knowledge/get-self-knowledge.ts"(){Ft(),aE(),__name(formatHelpItems,"formatHelpItems"),__name(getSelfKnowledge,"getSelfKnowledge")}}),pE=__esm({"src/tools/get-self-knowledge/index.ts"(){Ft(),mE(),lE={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")}}}),gE=__esm({"src/mcp/constants.ts"(){Ft(),cE="2025-03-26",uE={name:"command-code",version:"1.0.0"},Promise.resolve().then(()=>($r(),_r)).then(({getPackageJson:e})=>{uE.version=e().version??"1.0.0"}).catch(()=>{})}});function getTokenFilePath(){return e.join(f.homedir(),".commandcode",dE)}async function loadTokenStorage(){try{const e=getTokenFilePath(),t=await M.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 M.mkdir(r,{recursive:!0}),await M.writeFile(n,JSON.stringify(t,null,2),{mode:384}),await M.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 hE,fE,yE,wE,SE,bE=__esm({"src/mcp/auth/token-storage.ts"(){Ft(),zt(),Cn(),dE="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"(){Ft(),hE=g.object({authorizationUrl:g.string(),tokenUrl:g.string(),clientId:g.string(),clientSecret:g.string().optional(),scopes:g.array(g.string()).optional()}),fE=g.object({transport:g.enum(["stdio","http"]),enabled:g.boolean().default(!0),command:g.string().optional(),args:g.array(g.string()).optional(),url:g.string().optional(),headers:g.record(g.string(),g.string()).optional(),oauth:hE.optional(),env:g.record(g.string(),g.string()).optional()}),yE=g.object({mcpServers:g.record(g.string(),fE)})}});function getUserMcpConfigPath(){return e.join(f.homedir(),".commandcode",wE)}function getLocalMcpConfigPath(t=process.cwd()){const n=Ue(t);return e.join(f.homedir(),".commandcode","projects",n,wE)}function getProjectMcpConfigPath(t=process.cwd()){return e.join(t,SE)}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 vE=__esm({"src/mcp/config/scopes.ts"(){Ft(),zt(),wE="mcp.json",SE=".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 M.readFile(n,"utf-8"),s=JSON.parse(r),o=yE.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 M.mkdir(o,{recursive:!0}),await M.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 CE,kE,TE=__esm({"src/mcp/config/mcp-config.ts"(){Ft(),Cn(),bE(),EE(),vE(),__name(loadMcpConfig,"loadMcpConfig"),__name(saveMcpConfig,"saveMcpConfig"),__name(loadMergedMcpConfig,"loadMergedMcpConfig"),__name(addMcpServer,"addMcpServer"),__name(removeMcpServer,"removeMcpServer"),__name(updateMcpServerStatus,"updateMcpServerStatus"),__name(getMcpServer,"getMcpServer"),__name(listMcpServers,"listMcpServers")}}),_E=__esm({"src/mcp/client/stdio-transport.ts"(){Ft(),CE=class _StdioTransport extends We{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=R(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(),kE);return fetch(e,{...t,signal:n.signal}).finally(()=>clearTimeout(r))}var xE,PE,AE=__esm({"src/mcp/fetch.ts"(){Ft(),kE=8e4,__name(fetchWithTimeout,"fetchWithTimeout")}}),IE={};function generateRandomString(e){return z.randomBytes(e).toString("base64url").slice(0,e)}function generatePKCE(){const e=generateRandomString(64);return{verifier:e,challenge:z.createHash("sha256").update(e).digest("base64url")}}function escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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=ke.createServer((n,r)=>{const i=new d(n.url||"/",`http://${PE}:${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,PE,()=>{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||xE,s=n?.timeout||12e4,o=n?.onStatus||(()=>{});let i=null;try{const n=generatePKCE(),a=generateRandomString(32),l=`http://${PE}:${r}/callback`;o("Starting authentication server...");const{server:u,getCode:m}=await startCallbackServer(r,a);i=u;const p=new d(t.authorizationUrl);if(p.searchParams.set("response_type","code"),p.searchParams.set("client_id",t.clientId),p.searchParams.set("redirect_uri",l),p.searchParams.set("state",a),p.searchParams.set("code_challenge",n.challenge),p.searchParams.set("code_challenge_method","S256"),t.scopes&&t.scopes.length>0&&p.searchParams.set("scope",t.scopes.join(" ")),t.extraParams)for(const[e,n]of Object.entries(t.extraParams))p.searchParams.set(e,n);o("Opening browser for authentication..."),await ue(p.toString()),o("Waiting for authorization...");const g=m();let h;const f=new Promise((e,t)=>{h=setTimeout(()=>t(new Error("Authentication timed out")),s)}),y=await Promise.race([g,f]);clearTimeout(h),o("Exchanging authorization code for tokens...");const w=await exchangeCodeForTokens(t,y,n.verifier,l);return await storeTokens(e,w),o("Authentication successful!"),{success:!0,tokens:w}}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(IE,{DEFAULT_OAUTH_CALLBACK_PORT:()=>xE,LOCALHOST_IP:()=>PE,createRefreshCallback:()=>createRefreshCallback,performOAuthFlow:()=>performOAuthFlow,refreshAccessToken:()=>refreshAccessToken});var NE,RE,$E,ME=__esm({"src/mcp/auth/oauth-flow.ts"(){Ft(),bE(),AE(),xE=8085,PE="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")}}),DE=__esm({"src/mcp/client/http-transport.ts"(){Ft(),gE(),bE(),AE(),NE=class _HttpTransport extends We{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":`${uE.name}/${uE.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(()=>(ME(),IE));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(),kE);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(),kE);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 $E||($E=new RE),$E}var LE=__esm({"src/mcp/client/connection-manager.ts"(){Ft(),gE(),TE(),_E(),DE(),FE(),RE=class extends We{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 CE?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?CE.fromConfig(e):NE.fromConfig({config:e,serverName:t})}async initializeProtocol(e){const t=await e.transport.request("initialize",{protocolVersion:cE,capabilities:{roots:{}},clientInfo:uE});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}},$E=null,__name(getMcpConnectionManager,"getMcpConnectionManager")}});function mcpToolToSchema({serverName:e,tool:t}){return{name:`mcp__${e}__${t.name}`,description:t.description||`MCP tool: ${t.name} (from ${e})`,input_schema:{type:"object",properties:t.inputSchema.properties??{},required:t.inputSchema.required}}}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 OE,qE,FE=__esm({"src/mcp/client/tool-adapter.ts"(){Ft(),LE(),__name(mcpToolToSchema,"mcpToolToSchema"),__name(getAllMcpToolSchemas,"getAllMcpToolSchemas"),__name(isMcpTool,"isMcpTool"),__name(parseMcpToolName,"parseMcpToolName"),__name(executeMcpTool,"executeMcpTool")}}),jE=__esm({"src/tools/agents/defaults.ts"(){Ft(),OE=["explore","plan","review","general"],qE=[{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&&OE.includes(e.toLowerCase())}var BE=__esm({"src/tools/agents/utils.ts"(){Ft(),jE(),__name(isReservedAgentName,"isReservedAgentName")}});function getRootAgentDir(){return t.join(f.homedir(),".commandcode","agents")}function getLocalAgentDir(){return t.join(process.cwd(),".commandcode","agents")}async function loadAgentsFromDirectory(e,n){try{const r=(await D.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const s=t.join(e,r),o=await D.readFile(s,"utf-8"),{data:i,content:a}=Fe(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 zE=__esm({"src/tools/agents/loader.ts"(){Ft(),zt(),BE(),__name(getRootAgentDir,"getRootAgentDir"),__name(getLocalAgentDir,"getLocalAgentDir"),__name(loadAgentsFromDirectory,"loadAgentsFromDirectory"),__name(loadAllAgents,"loadAllAgents")}});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 UE,WE,GE,HE,QE,VE,KE,YE,JE,XE,ZE,ev,tv,nv,rv,sv,ov,iv,av,lv,cv,uv,dv,mv,pv,gv,hv,fv,yv,wv,Sv,bv,Ev,vv,Cv=__esm({"src/tools/utils/path-display.ts"(){Ft(),__name(toRelativePath,"toRelativePath"),__name(replacePathsInText,"replacePathsInText")}}),kv={};__export(kv,{FeedEntrySchema:()=>tv,LLM_STATUS_MESSAGES:()=>yv,createAgentToolEntry:()=>mv,createAssistantEntry:()=>sv,createBashEntry:()=>iv,createCommandResultEntry:()=>uv,createErrorEntry:()=>lv,createIDEStatusEntry:()=>dv,createInfoEntry:()=>rv,createSystemEntry:()=>av,createTasteOnboardingEntry:()=>cv,createToolEntry:()=>ov,createUserEntry:()=>nv,formatError:()=>gv,getRandomLLMStatus:()=>wv,getToolDisplayName:()=>Sv,getToolInputContent:()=>Ev,isErrorEntry:()=>hv,isPendingEntry:()=>fv,parseTodosFromOutput:()=>vv,updateEntryWithOutput:()=>pv});var Tv=__esm({"src/types/feed.ts"(){Ft(),Ew(),FE(),Cv(),os(),UE=g.object({id:g.string(),timestamp:g.number(),type:g.literal("image"),source:g.object({type:g.enum(["base64","url"]),media_type:g.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:g.string()})}),WE=g.object({id:g.string(),timestamp:g.number(),input:g.string(),output:g.string().optional(),metadata:g.record(g.string(),g.any()).optional(),images:g.array(UE).optional().default([])}),GE=WE.extend({role:g.literal("user")}),HE=WE.extend({role:g.literal("assistant")}),QE=WE.extend({role:g.literal("tool"),name:g.string(),description:g.string().optional()}).refine(e=>e.name&&!("command"in e),{message:"Tool entries must have 'name' and cannot have 'command'"}),VE=WE.extend({role:g.literal("bash"),command:g.string()}).refine(e=>e.command&&!("name"in e),{message:"Bash entries must have 'command' and cannot have 'name'"}),KE=WE.extend({role:g.literal("system")}),YE=WE.extend({role:g.literal("error")}),JE=WE.extend({role:g.literal("info")}),XE=WE.extend({role:g.literal("taste-onboarding")}),ZE=WE.extend({role:g.literal("command-result"),hasError:g.boolean().optional(),details:g.string().optional()}),ev=WE.extend({role:g.literal("ide-status"),status:g.enum(["connected","installed","needs_reload","not_in_ide","failed"]),ide:g.string().nullable(),details:g.array(g.string()).optional()}),tv=g.discriminatedUnion("role",[GE,HE,QE,VE,KE,YE,JE,XE,ZE,ev]),nv=__name((e,t)=>tv.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"user",input:e,images:t||[]}),"createUserEntry"),rv=__name((e,t)=>tv.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"info",input:e,metadata:t}),"createInfoEntry"),sv=__name(e=>tv.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:e}),"createAssistantEntry"),ov=__name((e,t,n)=>tv.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:e,input:t,metadata:n}),"createToolEntry"),iv=__name(e=>tv.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"bash",command:e,input:`$ ${e}`}),"createBashEntry"),av=__name((e,t)=>tv.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"system",input:e,metadata:t}),"createSystemEntry"),lv=__name(e=>tv.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"error",input:e}),"createErrorEntry"),cv=__name(()=>tv.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"taste-onboarding",input:""}),"createTasteOnboardingEntry"),uv=__name((e,t=!1,n)=>tv.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"command-result",input:e,hasError:t,details:n}),"createCommandResultEntry"),dv=__name((e,t,n)=>tv.parse({id:crypto.randomUUID(),timestamp:Date.now(),role:"ide-status",input:"",status:e,ide:t,details:n}),"createIDEStatusEntry"),mv=__name(({name:e,input:t})=>{const n=Date.now();return tv.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"),pv=__name((e,t)=>{const n={...e,output:replacePathsInText(t)};return tv.parse(n)},"updateEntryWithOutput"),gv=__name(e=>e.startsWith("Error:")?e:`Error: ${e}`,"formatError"),hv=__name(e=>/^error:/i.test(e.output??""),"isErrorEntry"),fv=__name(e=>void 0===e.output&&("tool"===e.role||"bash"===e.role),"isPendingEntry"),yv=["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…"],wv=__name(()=>yv[Math.floor(Math.random()*yv.length)],"getRandomLLMStatus"),Sv=__name(e=>{switch(e){case Jy.READ_FILE:return"READ";case Jy.EDIT_FILE:return"EDIT";case Jy.WRITE_FILE:return"WRITE";case Jy.READ_DIRECTORY:return"LIST";case Jy.READ_MULTIPLE_FILES:return"READ[n]";case Jy.GREP:return"SEARCH";case Jy.SHELL_COMMAND:return"SHELL";case Jy.TODO_WRITE:return"TODOS";case Jy.THINKING:return"thinking…";case Xy.WEB_SEARCH:return"WEB SEARCH";case Xy.WEB_FETCH:return"WEB FETCH";case Jy.QUESTION:return"QUESTION";case Jy.EXPLORE:return"EXPLORE";case Jy.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"),bv=__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:Jr})}${t.length>1?` (+${t.length-1} more)`:""}`},"formatMcpToolParams"),Ev=__name((e,t)=>{try{switch(e){case Jy.READ_FILE:case Jy.WRITE_FILE:const n=t.absolutePath||t.file_path||t.filePath||t.path||"file";return t.isTasteFile?t.tasteCategory||"":toRelativePath(n);case Jy.EDIT_FILE:return toRelativePath(t.absolutePath||t.file_path||t.filePath||t.path||"file");case Jy.READ_DIRECTORY:return toRelativePath(t.path||"directory");case Jy.GREP:const r=t.path||"files";return`"${t.pattern}" in ${toRelativePath(r)}`;case Jy.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 Jy.TODO_WRITE:let s;try{s="string"==typeof t.todos?t.todos:JSON.stringify(t.todos);const e=vv(s);return`${e?e.length:0} items`}catch{return"items"}case Jy.THINKING:return t.content||"planning";case Jy.READ_MULTIPLE_FILES:const o=t.include||[];if(!Array.isArray(o)||0===o.length)return"multiple files";const i=o.slice(0,Zr).map(toRelativePath).join(", "),a=o.length-Zr;return a>0?`${i} (+${a} more)`:i;case Xy.WEB_SEARCH:return t.query||"search";case Xy.WEB_FETCH:return t.url||"fetch";case Jy.QUESTION:return"User answered questions";case Jy.KILL_SHELL:return t.port?`Kill port: ${t.port}`:t.pid?`Kill PID: ${t.pid}`:"kill process";case Jy.ENTER_PLAN_MODE:case Jy.EXIT_PLAN_MODE:return"";default:{if(isMcpTool(e)&&t&&"object"==typeof t)return bv(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:Xr})}}return JSON.stringify(t||{})}}}catch{return"parameters"}},"getToolInputContent"),vv=__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 _v,xv,Pv,Av,Iv,Nv,Rv,$v,Mv=__esm({"src/utils/file-references.ts"(){Ft(),zw(),__name(processFileReferences,"processFileReferences"),__name(reconstructContent,"reconstructContent")}}),Dv=__esm({"src/utils/strip-ide-context.ts"(){Ft(),_v=__name(e=>e.replace(/<ide-context>[\s\S]*?<\/ide-context>\s*/g,""),"stripIdeContext")}}),Lv=__esm({"src/sessions/index.ts"(){Ft(),Tv(),Mv(),zt(),gs(),Cn(),Dv(),xv=class _SessionManager{static{__name(this,"SessionManager")}sessionId;projectPath;sessionFilePath;messageIdMap=new Map;lastMessageId=null;gitBranch;lastSavedMessagesHash="";static getProjectsBasePath(){return t.join(f.homedir(),".commandcode","projects")}static getCurrentProjectDirName(){return Ue(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=N("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{this.gitBranch="-"}}async initializeProject(){try{return await D.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:ls.SESSION_MANAGER,heading:"Project initialization failed"}}),!1}}async isProjectInitialized(){try{return(await D.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,...t?.metadata||{}}};r.push(JSON.stringify(s)),this.lastMessageId=e}await D.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 D.readFile(r,"utf-8")).trim().split("\n").filter(e=>e.trim()),t=[];let n=0;for(const r of e)try{const e=JSON.parse(r);"user"!==e.role&&"assistant"!==e.role||t.push({message:{role:e.role,content:e.content},meta:{timestamp:e.timestamp,source:"cli",...e.metadata||{}}})}catch(e){n++,console.error("Error parsing session line:",e)}return{messages:t,corruptedLines:n,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("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)if("text"===t.type)n+=t.text;else if("tool_result"===t.type)continue;n=_v(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_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=Ev(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,input:e,output:"Completed",images:[]})}else if("server_tool_use"===r.type){n.trim()&&(t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"assistant",input:n.trim(),images:[]}),n="");const e=Ev(r.name,r.input);t.push({id:crypto.randomUUID(),timestamp:Date.now(),role:"tool",name:r.name,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 D.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 D.stat(r)).isDirectory()}catch{return!1}}static async initializeProject(){const e=_SessionManager.getProjectsBasePath(),n=_SessionManager.getCurrentProjectDirName(),r=t.join(e,n);try{return await D.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 D.access(n)}catch{return[]}const e=(await D.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 D.stat(o),s=(await D.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=_v(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 D.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 D.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 D.unlink(e)}catch(e){}}getMetaFilePath(){return t.join(this.projectPath,`${this.sessionId}.meta.json`)}async loadSessionMeta(){try{const e=await D.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 D.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 D.access(n)}catch{return[]}const r=(await D.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 D.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 D.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 D.writeFile(r,o)}else await D.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 D.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 D.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 D.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=_v(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 getRequest(){return $v||($v=new Yy({baseUrl:getApiBaseUrl()})),$v}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)}`}function buildRequestBody(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:Pt,max_tokens:Nv,temperature:Rv,stream:!0},threadId:crypto.randomUUID()}}async function getAuthHeaders(){const e=await getConfiguredProvider(),t=await isOAuthEnforced(),{token:n,oauthProvider:r}=await getOAuthCredentials({provider:e});validateOAuthToken({token:n,provider:e});const s={[vt.PROJECT_SLUG]:xv.getCurrentProjectDirName(),[vt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};return n&&(s[vt.OAUTH_TOKEN]=`Bearer ${n}`,r&&(s[vt.OAUTH_PROVIDER]=r)),s}async function generateToolDescription(e,t){const n=generateCacheKey(e,t),r=Av.get(n);if(r)return Av.delete(n),Av.set(n,r),dlog(`[ToolDescription] cache hit for ${e}: "${r}"`),r;dlog(`[ToolDescription] generating for ${e}`);try{const e=getRequest(),r=await getAuthHeaders(),s=buildRequestBody(createPrompt(t));dlog(`[ToolDescription] calling ${Ct.ALPHA.GENERATE} with model: ${Pt}`);const o=e.post({endpoint:Ct.ALPHA.GENERATE,body:s,headers:r,stream:!0}),i=await Promise.race([o,new Promise((e,t)=>setTimeout(()=>t(new Error("Timeout")),5e3))]);if(!i)return dlog("[ToolDescription] no response stream"),null;dlog("[ToolDescription] got response stream");const a=Ge.fromReadableStream(i);let l="",u=null;if(a.on("text",e=>{l+=e}),a.on("error",e=>{u=e}),await a.finalMessage(),u)throw u;dlog(`[ToolDescription] raw response: "${l}"`);const d=cleanDescription(l);if(d){if(Av.size>=Pv){const e=Av.keys().next().value;void 0!==e&&Av.delete(e)}Av.set(n,d),dlog(`[ToolDescription] cached: "${d}"`)}else dlog("[ToolDescription] description rejected after cleaning");return d}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,Iv)}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 Ov=__esm({"src/utils/tool-description-generator.ts"(){Ft(),zt(),bw(),Cs(),Lv(),an(),Sr(),Cr(),Cn(),Pv=100,Av=new Map,Iv=4e3,Nv=80,Rv=.3,$v=null,__name(getRequest,"getRequest"),__name(stableStringify,"stableStringify"),__name(generateCacheKey,"generateCacheKey"),__name(buildRequestBody,"buildRequestBody"),__name(getAuthHeaders,"getAuthHeaders"),__name(generateToolDescription,"generateToolDescription"),__name(sanitize,"sanitize"),__name(createPrompt,"createPrompt"),__name(cleanDescription,"cleanDescription")}});function isPlanPath(e){const{filePath:n}=e;if(!n||"string"!=typeof n)return!1;const r=f.homedir(),s=n.startsWith("~/")?t.join(r,n.slice(2)):n,o=t.resolve(s),i=t.join(r,".commandcode","plans");return o.startsWith(i+t.sep)||o===i}var qv,Fv,jv,Bv=__esm({"src/utils/plan-path-validator.ts"(){Ft(),zt(),__name(isPlanPath,"isPlanPath")}});function getToolsForMode(e){const{allTools:t,mode:n}=e;return"standard"===n||"auto-accept"===n?t.filter(e=>!Fv.includes(e.name)):"plan"===n?t.filter(e=>!qv.includes(e.name)&&!jv.includes(e.name)):t.filter(e=>!Fv.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 qv.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 zv=__esm({"src/tools/get-tools-for-mode.ts"(){Ft(),Bv(),FE(),qv=["edit_file","delete_file","shell_command","todo_write","kill_shell"],Fv=["exit_plan_mode"],jv=["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 Uv,Wv,Gv,Hv,Qv=__esm({"src/utils/sleep.ts"(){Ft(),__name(sleep,"sleep")}}),Vv=__esm({"src/utils/logger.ts"(){Ft(),Cn(),Uv=class{static{__name(this,"Logger")}prefix;constructor(e="CLI"){this.prefix=e}info(e){console.log(`[${this.prefix}] ${ve.info} ${e}`)}success(e){console.log(`[${this.prefix}] ${ve.tick} ${e}`)}error(e){console.error(`[${this.prefix}] ${ve.cross} ${e}`)}warn(e){console.warn(`[${this.prefix}] ${ve.warning} ${e}`)}debug(e,t){dlog(`[${this.prefix}] ${e}`,t)}}}});function setBenchmarkOutput(e){Wv=e}function createBenchmarkCollector(){return Wv?{startTime:Date.now(),turnDetails:[],agents:[],maxTurnsReached:!1}:null}function buildAgentMetricsMarker(e){return`\n${Gv}${JSON.stringify(e)}${Hv}`}function extractAgentMetrics(e){const t=e.indexOf(Gv);if(-1===t)return{cleanContent:e,metrics:null};const n=t+Gv.length,r=e.indexOf(Hv,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+Hv.length),metrics:o}}catch{return{cleanContent:e,metrics:null}}}function createAgentBenchmarkTracker(){return Wv?{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(!Wv)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{w.writeFileSync(Wv,JSON.stringify(l,null,2))}catch{}}var Kv,Yv=__esm({"src/utils/benchmark-collector.ts"(){Ft(),__name(setBenchmarkOutput,"setBenchmarkOutput"),__name(createBenchmarkCollector,"createBenchmarkCollector"),Gv="\x3c!-- BENCHMARK_AGENT_METRICS:",Hv=" --\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"}}},required:["messages"]},execute:__name(async(n,a)=>{let l=null;const u=Date.now();let d=null;try{const m=a?.permissionMode||"standard",p=filterToolsForMode({tools:getAvailableTools(t,{clientTools:r,serverTools:s,toolsMap:o,displayNameToToolName:i}),clientTools:r,serverTools:s,mode:m});let g=Date.now();const h=10,f=[];if(a?.onFeedUpdate){const e=Ev(t.name,n);l=mv({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 y=createAgentBenchmarkTracker(),w=await getConfiguredProvider(),S=await isOAuthEnforced(),{token:E,oauthProvider:v}=await getOAuthCredentials({provider:w});validateOAuthToken({token:E,provider:w});const C=getApiBaseUrl(),k=new Yy({baseUrl:C});let T=0;const _=[];let x=n?.messages;if("string"==typeof x)try{x=JSON.parse(x)}catch(e){x=[]}if(Array.isArray(x)&&x.length>0)for(const e of x)if("object"==typeof e&&"content"in e){const t=e.content;"string"==typeof t&&_.push({role:"user",content:t})}const P={stream:!0,messages:_,max_tokens:64e3,system:t.systemPrompt,temperature:.3,tools:p,model:`anthropic:${getConfiguredModel()}`},A=await isTasteLearningEnabled(),I={[vt.PROJECT_SLUG]:xv.getCurrentProjectDirName(),[vt.TASTE_LEARNING]:A.toString(),[vt.INTERNAL_TEAM_FLAG_HEADER]:S.toString()};E&&(I[vt.OAUTH_TOKEN]=`Bearer ${E}`,v&&(I[vt.OAUTH_PROVIDER]=v));const N=getEnvironmentContext(),R=await getMemoryContent([]),$=crypto.randomUUID();let M="",D=!0;const L=__name(()=>{Kv.debug("[Agent] Abort signal triggered, stopping immediately"),D=!1,d&&(clearInterval(d),d=null)},"abortHandler");a?.abortSignal&&a.abortSignal.addEventListener("abort",L);try{for(;D;){if(a?.abortSignal?.aborted)throw Kv.debug("[Agent] Detected abort signal, stopping conversation"),new Error("Interrupted by user");const t=await callAPIWithRetry({request:k,body:{mode:"custom-agent",config:N,memory:R,threadId:$,params:{...P,messages:_}},headers:I,abortSignal:a?.abortSignal,onTextDelta:__name(e=>{T+=estimateTokens(e);const t=Date.now();if(a?.onFeedUpdate&&l&&t-g>=h){const e=Math.floor((t-u)/1e3);l={...l,metadata:{...l.metadata,tokensUsed:T,elapsedSeconds:e}},a.onFeedUpdate(l),g=t}},"onTextDelta")});if(trackAgentTurn(y),a?.abortSignal?.aborted)throw new Error("Interrupted by user");t.usage&&(T=calculateUsageFromResponse(t.usage));const n=t.content.filter(e=>"tool_use"===e.type);if(M=t.content.filter(e=>"server_tool_use"===e.type).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);e.length>0&&_.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&&_.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=nw.includes(t.name),p=rw.includes(t.name)?generateToolDescription(t.name,n).catch(()=>null):Promise.resolve(null);if(r&&a?.onPermissionRequest){d&&(clearInterval(d),d=null);const e=await p;if(!await a.onPermissionRequest(t.name,n,e)){Kv.debug(`Permission denied for tool: ${t.name}`),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,Kv.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,Kv.debug(`Resolved input for ${t.name}: ${Ev(t.name,n)}`)):Kv.debug(`No path resolution needed for ${t.name}: ${Ev(t.name,n)}`)}if(a?.onFeedUpdate&&l){const e=Ev(t.name,n);f.push({name:t.name,input:e}),f.length>3&&f.shift();const r=Date.now(),s=Math.floor((r-u)/1e3);l={...l,metadata:{isAgent:!0,status:"running",startTime:u,tokensUsed:T,elapsedSeconds:s,recentTools:[...f]}},Kv.debug(`Updating agent with recentTools (${f.length} tools): ${JSON.stringify(f)}`),a.onFeedUpdate(l)}const g=await executeTool(t.name,n,{abortSignal:a?.abortSignal,permissionMode:m});if(a?.abortSignal?.aborted)throw new Error("Interrupted by user");const h=checkToolOutputTokensLimit(g);if(s.push({type:"tool_result",tool_use_id:t.id,content:h}),o.add(t.id),trackAgentToolCall({tracker:y,toolName:t.name,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:T,elapsedSeconds:t,recentTools:[...f]}},a.onFeedUpdate(l)}Kv.debug(`Tool executed successfully: ${t.name}`)}catch(e){const n=e instanceof Error?e.message:"Unknown error";s.push({type:"tool_result",tool_use_id:t.id,content:`Error: ${n}`,is_error:!0}),o.add(t.id),trackAgentToolCall({tracker:y,toolName:t.name,isError:!0}),Kv.error(`Tool execution failed: ${t.name} - ${n}`)}}if(i){const e=_[_.length-1];if("assistant"===e?.role&&Array.isArray(e.content)){const t=e.content.filter(e=>"tool_use"===e.type?o.has(e.id):"text"===e.type);t.length>0?e.content=t:_.pop()}D=!1;break}const p=[...s];_.push({role:"user",content:p})}}finally{a?.abortSignal&&a.abortSignal.removeEventListener("abort",L)}if(d&&(clearInterval(d),d=null),a?.onFeedUpdate&&l){const e=Date.now(),t=(e-u)/1e3;l={...l,output:M||"DONE",metadata:{isAgent:!0,status:"done",startTime:u,endTime:e,tokensUsed:T,elapsedSeconds:t}},a.onFeedUpdate(l)}return buildAgentResult({result:M||"DONE",tracker:y,agentName:t.name,startTime:u,tokens:T})}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:Ct.ALPHA.GENERATE,signal:s,headers:r}),i=Ge.fromReadableStream(e);o&&i.on("text",o);let a=null;i.on("error",e=>{a="AbortError"===e.name||s?.aborted?new Error("Interrupted by user"):e});const l=await i.finalMessage();if(a)throw a;return l}catch(t){if(i=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);Kv.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 to&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")||e instanceof ro||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"].some(t=>e.message.includes(t))}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 to&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits"))return new Error("Insufficient credits");if(e instanceof ro||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=>"server_tool_use"===e.type).length)return"";let n="";const r=e.content;for(const e of r)if("text"===e.type)n+=e.text;else if("server_tool_use"===e.type&&(n.trim()&&t?.onFeedUpdate&&(n=""),t?.onFeedUpdate)){const{message:n,isError:s}=tw({serverToolBlock:e,contentBlocks:r}),o=Ev(e.name,e.input),i={id:`${e.name}-server-${Date.now()}`,timestamp:Date.now(),role:"tool",name:e.name,input:o,output:s?gv(n):n};t.onFeedUpdate(i)}return e.content.filter(e=>"text"===e.type).map(e=>e.text).join("")}var Jv,Xv,Zv=__esm({"src/tools/agents/execute.ts"(){Ft(),zt(),Cr(),bw(),Cs(),an(),ho(),cC(),Ov(),Ew(),zv(),BS(),Qv(),Vv(),Tv(),Aw(),Lv(),Sr(),Ew(),Yv(),Kv=new Uv("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){Xv=e}async function loadAgentTools(){if(!Xv)throw new Error("Agent manager not initialized. Call initializeAgentManager first.");Jv.clear();for(const e of qE){const t=agentToTool(e,Xv);Jv.set(t.name,t)}const{personal:e,project:t}=await loadAllAgents(),n=[...e,...t];for(const e of n){const t=agentToTool(e,Xv);Jv.set(t.name,t)}}async function getAgentTools(){return 0===Jv.size&&await loadAgentTools(),Array.from(Jv.values())}async function getAgentTool(e){return 0===Jv.size&&await loadAgentTools(),Jv.get(e)}var eC=__esm({"src/tools/agents/manager.ts"(){Ft(),zE(),Zv(),jE(),Jv=new Map,Xv=null,__name(initializeAgentManager,"initializeAgentManager"),__name(loadAgentTools,"loadAgentTools"),__name(getAgentTools,"getAgentTools"),__name(getAgentTool,"getAgentTool")}}),tC=__esm({"src/tools/agents/index.ts"(){Ft(),eC()}});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(h.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 nC,rC,sC,oC,iC,aC,lC=__esm({"src/utils/taste-path-validator.ts"(){Ft(),zt(),__name(isPathInTasteDirectory,"isPathInTasteDirectory"),__name(getTasteFileInfo,"getTasteFileInfo"),__name(getTasteAccessError,"getTasteAccessError")}});function isAgentTool(e){return!oC.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=sC.get(e);if(o||(o=await getAgentTool(e)),!o){const t=await getAgentTools(),n=[...Array.from(sC.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=(!sC.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!==Rb()?[...nC]:nC.filter(e=>e.name!==Jy.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,...rC]}function toPascalCase(e){return e.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}var cC=__esm({"src/tools/index.ts"(){Ft(),Yw(),pS(),SS(),PS(),FS(),QS(),eb(),ob(),lb(),db(),yb(),Bb(),zb(),Ub(),Wb(),Gb(),iE(),pE(),Qb(),Ew(),FE(),LE(),tC(),lC(),gs(),zv(),nC=[Ww,cS,fS,vS,NS,US,YS,rb,ib,cb,pb,bb,Eb,vb,Kb,lE],rC=[Cb,kb],sC=new Map(nC.map(e=>[e.name,e])),oC=new Set([...nC.map(e=>e.name),...rC.map(e=>e.name)]),__name(isAgentTool,"isAgentTool"),__name(executeTool,"executeTool"),__name(getToolSchemas,"getToolSchemas"),__name(toPascalCase,"toPascalCase"),iC={},nC.forEach(e=>{iC[e.name]=toPascalCase(e.name)}),rC.forEach(e=>{iC[e.name]=toPascalCase(e.name)}),aC={},Object.entries(iC).forEach(([e,t])=>{aC[t]=e}),initializeAgentManager({clientTools:nC,serverTools:rC,toolsMap:sC,displayNameToToolName:aC})}});async function resolveEditStartLine({filePath:e,oldContent:t}){const n=await P.readFile(e,"utf-8"),r=n.indexOf(t);if(-1!==r)return n.substring(0,r).split("\n").length}function isDirectoryEmpty(){try{return 0===T(process.cwd()).length}catch{return!1}}var uC=__esm({"src/utils/fs.ts"(){Ft(),__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}function parseErrorLine(e){try{const t=JSON.parse(e);if("error"===t?.type&&t?.error?.type&&t?.error?.message)return{type:t.error.type,message:t.error.message}}catch{}return null}function interceptStreamErrors(e){const{responseStream:t}=e;let n=null,r="";const s=new TextDecoder,o=new TransformStream({transform(e,t){const o=s.decode(e,{stream:!0});r+=o;const i=r.split("\n");r=i.pop()??"";for(const e of i){const r=e.trim();if(!r){t.enqueue((new TextEncoder).encode(e+"\n"));continue}const s=parseErrorLine(r);if(s)return n=s,void t.error(new Error(`Error: Stream error: ${s.type} - ${s.message}`));t.enqueue((new TextEncoder).encode(e+"\n"))}},flush(e){const t=r.trim();if(t){const s=parseErrorLine(t);if(s)return n=s,void e.error(new Error(`Error: Stream error: ${s.type} - ${s.message}`));e.enqueue((new TextEncoder).encode(r))}}});return{stream:t.pipeThrough(o),getStreamError:__name(()=>n,"getStreamError")}}var dC,mC,pC=__esm({"src/utils/stream-error-interceptor.ts"(){Ft(),__name(parseEmbeddedErrorJSON,"parseEmbeddedErrorJSON"),__name(parseErrorLine,"parseErrorLine"),__name(interceptStreamErrors,"interceptStreamErrors")}}),gC=__esm({"src/utils/learning-events.ts"(){Ft(),dC=class extends We{static{__name(this,"LearningEventsStore")}events=[];maxEvents=50;_observerHasRun=!1;_importHasStarted=!1;_learningComplete=!1;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)}getEvents(){return[...this.events]}getLatestEvent(){return this.events.length>0?this.events[0]:null}clear(){this.events=[],this.emit("cleared")}reset(){this.events=[],this._observerHasRun=!1,this._importHasStarted=!1,this._learningComplete=!1,this.emit("reset")}},mC=new dC}});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 hC,fC,yC,wC,SC,bC,EC=__esm({"src/utils/learning-parser.ts"(){Ft(),__name(extractLearningWithConfidence,"extractLearningWithConfidence"),__name(extractLearnings,"extractLearnings"),__name(compareLearnings,"compareLearnings")}}),vC=__esm({"src/agent/learning-agent.ts"(){Ft(),zt(),Lv(),cC(),Qv(),Cn(),gC(),EC(),Vv(),Sr(),Cr(),gs(),hC=new Uv("LearningAgent"),fC=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:ls.LEARNING_AGENT,heading:"Learning pass failed"}}),mC.addEvent({type:"error",message:"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)];mC.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.name).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:"user",content:n}),u++}u>=this.maxTurns&&hC.debug("Learning loop reached max turns"),await this.reorganizeIfNeeded(),d||mC.addEvent({type:"no_learnings",message:"no changes to taste"}),mC.addEvent({type:"analyzed",message:"finished learning pass"})}extractToolCalls(e){const{content:t}=e;return t.filter(e=>"tool_use"===e.type)}async executeTools(e){const{toolCalls:t}=e,n=[];let r=!1;for(const e of t)try{this.validateTastePath({toolName:e.name,input:e.input});const t=this.adjustPathsForTaste({toolName:e.name,input:e.input});let s="",o="";if("write_file"===e.name||"edit_file"===e.name){const e=t;if(o=String(e.filePath||e.file_path||""),o)try{s=await w.promises.readFile(o,"utf-8")}catch{}}if("write_file"===e.name||"edit_file"===e.name){const e=t.filePath;e&&this.validateFinalTastePath(e)}const i=await executeTool(e.name,t,{allowTasteWrite:!0});let a="";if(("write_file"===e.name||"edit_file"===e.name)&&o)try{a=await w.promises.readFile(o,"utf-8")}catch{}if("write_file"===e.name||"edit_file"===e.name){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=>{mC.addEvent({type:"learned",message:`learned: ${t.text} (${Math.round(100*t.confidence)}%)`,details:e})}),t.upgraded.forEach(t=>{mC.addEvent({type:"learned",message:`upgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})}),t.downgraded.forEach(t=>{mC.addEvent({type:"learned",message:`downgraded: ${t.text} (${Math.round(100*t.oldConfidence)}% → ${Math.round(100*t.newConfidence)}%)`,details:e})})}n.push({type:"tool_result",tool_use_id:e.id,content:i})}catch(t){n.push({type:"tool_result",tool_use_id:e.id,is_error:!0,content: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(!w.existsSync(this.tasteDir)){w.mkdirSync(this.tasteDir,{recursive:!0});const t=e.join(this.tasteDir,"taste.md");w.writeFileSync(t,"","utf-8")}}async reorganizeIfNeeded(){const t=e.join(this.tasteDir,"taste.md");if(!w.existsSync(t))return!1;const n=w.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");w.mkdirSync(r,{recursive:!0}),mC.addEvent({type:"refactored",message:`moved: ${t.name} package`,details:`moved to ${n}/taste.md`});const i=`# ${t.name}\n${t.learnings.join("\n")}\n`;w.writeFileSync(o,i,"utf-8");const a=`# ${t.name}\nSee [${n}/taste.md](${n}/taste.md)\n`;s=s.replace(t.fullSection,a)}return w.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 w.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=w.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=(w.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={[vt.PROJECT_SLUG]:xv.getCurrentProjectDirName(),[vt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};s&&(i[vt.OAUTH_TOKEN]=`Bearer ${s}`,o&&(i[vt.OAUTH_PROVIDER]=o));const a=await this.getTasteTools(),l=`anthropic:${getConfiguredModel()}`;dlog(`[LearningAgent] calling API (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:Ct.ALPHA.TASTE.LEARN,body:u,headers:i,signal:this.abortSignal});return dlog("[LearningAgent] API response received"),e}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;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:ls.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:ls.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 w.existsSync(r)}}}}),CC=__esm({"src/agent/compact-agent.ts"(){Ft(),zt(),Lv(),an(),Sr(),Cr(),Cn(),yC="claude-haiku-4-5-20251001",wC=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={[vt.PROJECT_SLUG]:xv.getCurrentProjectDirName(),[vt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};s&&(i[vt.OAUTH_TOKEN]=`Bearer ${s}`,o&&(i[vt.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:`anthropic:${yC}`,max_tokens:16e3,stream:!0},threadId:this.sessionId};let u=0,d=null;for(;u<=this.maxApiRetries;)try{dlog(`[CompactAgent] calling ${Ct.ALPHA.GENERATE} with model: ${yC}`);const e=await this.request.post({endpoint:Ct.ALPHA.GENERATE,body:l,headers:i,stream:!0});if(!e)throw new Error("No response stream received");const t=Ge.fromReadableStream(e);let n="",r=null;t.on("text",e=>{n+=e}),t.on("error",e=>{r=e});const s=await t.finalMessage();if(r)throw r;return dlog("[CompactAgent] API response received"),{summary:n,tokensUsed:{input:s.usage.input_tokens,output:s.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;const n=1e3*Math.pow(2,u);dlog(`[CompactAgent] retrying API call (${u}/${this.maxApiRetries})`),await new Promise(e=>setTimeout(e,n))}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={[vt.PROJECT_SLUG]:xv.getCurrentProjectDirName(),[vt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()},{token:r,oauthProvider:s}=await getOAuthCredentials({provider:e});return r&&(n[vt.OAUTH_TOKEN]=`Bearer ${r}`,s&&(n[vt.OAUTH_PROVIDER]=s)),dlog("[TitleGen] buildAuthHeaders",{provider:e,oauthEnforced:t,hasOAuthToken:!!n[vt.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,request:r}=e;if(!hasUserAndAssistantMessage(t))return;if(await n.loadSessionTitle())return;let s="",o="";for(const e of t)if(s||"user"!==e.message.role||(s=extractMessageText(e.message.content).slice(0,bC)),o||"assistant"!==e.message.role||(o=extractMessageText(e.message.content).slice(0,bC)),s&&o)break;if(!s||!o)return;const i=`${SC}\n\nSession description:\n<description>User: ${s}\n\n---\n\nAssistant: ${o}</description>\n\nGenerate the session title now.`,a={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:i}],model:Pt,max_tokens:50,temperature:.3,stream:!0},threadId:n.getSessionId()},l=await buildAuthHeaders(),u=await r.post({endpoint:Ct.ALPHA.GENERATE,body:a,headers:l,stream:!0}),d=Ge.fromReadableStream(u);let m="";d.on("text",e=>{m+=e}),await d.finalMessage(),m=m.trim(),m&&(await n.saveSessionTitle(m),dlog("Session",`Title generated: ${m}`))}var kC,TC,_C,xC=__esm({"src/chat/title-generator.ts"(){Ft(),Lv(),an(),Sr(),Cr(),Cn(),zt(),SC="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",bC=1e3,__name(extractMessageText,"extractMessageText"),__name(buildAuthHeaders,"buildAuthHeaders"),__name(hasUserAndAssistantMessage,"hasUserAndAssistantMessage"),__name(generateSessionTitle,"generateSessionTitle")}}),PC={};__export(PC,{ContextEngine:()=>_C});var AC,IC=__esm({"src/chat/context-engine.ts"(){Ft(),uC(),Ow(),ho(),Mv(),Tv(),Ew(),cC(),Qv(),pC(),Vv(),lC(),BS(),Lv(),gs(),aS(),Cs(),bw(),Jh(),zt(),an(),Sr(),Cr(),Aw(),vC(),CC(),Nw(),Cn(),xC(),os(),Ov(),kC=new Uv("ContextEngine"),TC=200,_C=class{static{__name(this,"ContextEngine")}request;messages=[];anthropic=null;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 Yy({baseUrl:n}),this.callbacks=e,this.sessionManager=new xv(t),this.learningAgent=new fC({request:this.request,sessionId:this.sessionManager.getSessionId(),projectRoot:process.cwd()}),this.compactAgent=new wC({request:this.request,sessionId:this.sessionManager.getSessionId()}),this.checkpointManager=initializeCheckpointService({sessionId:this.sessionManager.getSessionId()}),this.setupCheckpointSessionStore()}refreshRequest(){const e=getApiBaseUrl();this.request=new Yy({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,kC.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_use"===e.type),r=[];if(n.length>0){const e=n.map(e=>({type:"tool_result",tool_use_id:e.id,content:"Interrupted by user",is_error:!0}));r.push(...e),kC.debug(`Added tool_result blocks for ${e.length} interrupted tool calls`)}e&&r.push({type:"text",text:"Interrupted by user"}),r.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:r},{isAutomated:!0}))}if(e){const e=nv("Interrupted by user");this.sessionManager.saveMessages(this.messages,e).catch(e=>kC.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=nv(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",source:{type:"base64",media_type:e.mediaType,data: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 p=this.createMessageWithMeta(u,m);this.addMessageAndSync(p),this.checkpointManager.createSnapshot({messageId:d}).catch(e=>kC.error(`Failed to create checkpoint snapshot: ${e}`)),this.sessionManager.saveMessages(this.messages,a).catch(e=>kC.error(`Failed to save messages to session: ${e}`)),this.triggerLearningAgent();const g=await this.processMessages();return this.triggerTitleGeneration(),g}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){kC.error(`Learning agent failed: ${e instanceof Error?e.message:String(e)}`)}})()}triggerTitleGeneration(){this.titleGenerationInFlight||(this.titleGenerationInFlight=!0,generateSessionTitle({messages:this.messages,sessionManager:this.sessionManager,request:this.request}).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{body:t,headers:r}=await this.prepareAPICall(),s=await this.callAPIWithRetry({body:t,headers:r});this.checkIfInterrupted(),this.updateContextUsage(s),await this.checkAndCompactIfNeeded();const o=s.content.filter(e=>"tool_use"===e.type),i=s.content.filter(e=>"server_tool_use"===e.type);if(e=i.length>0?this.processServerToolBlocks(s):s.content.filter(e=>"text"===e.type).map(e=>e.text).join(""),0===o.length){const t=s.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(t.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:t})),e.trim()&&0===i.length){const t=sv(e);this.callbacks.onFeedUpdate(t),this.sessionManager.saveMessages(this.messages,t).catch(e=>kC.error(`Failed to save messages: ${e}`))}if(0!==i.length&&this.sessionManager.saveMessages(this.messages).catch(e=>kC.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=nv(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=>kC.error(`Failed to save messages: ${e}`)),t&&this.triggerLearningAgent();continue}}break}const a=s.content.filter(e=>"text"!==e.type||e.text.trim().length>0);if(a.length>0&&this.addMessageAndSync(this.createMessageWithMeta({role:"assistant",content:a})),e.trim()){const t=sv(e);this.callbacks.onFeedUpdate(t)}const l=await this.executeToolBlocks({toolBlocks:o}),{toolResults:u,executedToolIds:d,permissionDenied:m}=l;if(m){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_use"===e.type?d.has(e.id):"text"===e.type);t.length>0?e.message.content=t:this.messages.pop()}break}let p=!1,g=!1;if(u.length>0&&(this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:[...u]},{isAutomated:!0})),p=!0),this.callbacks.getQueuedMessages){const e=this.callbacks.getQueuedMessages();if(e.length>0)for(const t of e){const e=nv(t.displayMessage??t.input);this.callbacks.onFeedUpdate(e);const n=this.getAutomatedMessageMeta(t);this.addMessageAndSync(this.createMessageWithMeta({role:"user",content:t.input},n)),p=!0,g=!0}}p&&this.sessionManager.saveMessages(this.messages).catch(e=>kC.error(`Failed to save messages: ${e}`)),g&&this.triggerLearningAgent()}catch(e){throw this.isNonRetryableError(e)&&kC.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){kC.error(`Failed to load checkpoints for session ${e}: ${t}`)}const s=this.sessionManager.reconstructFeedFromMessages(t);return kC.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("user"===n.role&&Array.isArray(n.content)){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_use"===t.type&&r.add(t.id);const s=n.content.filter(e=>"tool_result"!==e.type||r.has(e.tool_use_id));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};kC.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_use"===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:MS}),{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=>"object"==typeof e&&null!==e&&"type"in e&&"tool_result"===e.type)}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=Bh.sanitizeMessage(t,global.COMMAND_CODE_CWD||process.cwd()),r={sessionId:e.sessionId,secret:e.secret,message:n};await this.request.post({body:r,endpoint:Ct.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 prepareAPICall(){const e=this.callbacks.getPermissionMode?.()||"standard",t=await getToolSchemas({mode:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();n&&this.callbacks.onProviderChange&&this.callbacks.onProviderChange(n);const{token:s,oauthProvider:o}=await getOAuthCredentials({provider:n});validateOAuthToken({token:s,provider:n}),dlog("[ContextEngine] prepareAPICall",{provider:n,oauthProvider:o,hasToken:!!s});const i={tools:t,stream:!0,max_tokens:64e3,temperature:.3,messages:this.getRawMessages(),model:`anthropic:${getConfiguredModel()}`},a={config:getEnvironmentContext(),memory:await getMemoryContent(this.lastFileContexts),taste:await getTasteContent(),skills:generateSkillsXML(await loadAllSkillSummaries())||null,params:i,threadId:this.sessionManager.getSessionId(),permissionMode:e};kC.debug(`calling API (${i.model}, ${this.messages.length} msgs, ${t.length} tools)`);const l=await isTasteLearningEnabled(),u={[vt.PROJECT_SLUG]:xv.getCurrentProjectDirName(),[vt.TASTE_LEARNING]:l.toString(),[vt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return s&&(u[vt.OAUTH_TOKEN]=`Bearer ${s}`,o&&(u[vt.OAUTH_PROVIDER]=o)),{body:a,headers:u}}async callAPIWithRetry(e){let t=null;for(let n=0;n<10;n++){let r;try{const t=interceptStreamErrors({responseStream:await this.request.post({body:e.body,stream:!0,endpoint:Ct.ALPHA.GENERATE,signal:this.abortController?.signal,headers:e.headers})}),n=t.stream;r=t.getStreamError;const s=Ge.fromReadableStream(n);s.on("text",e=>{this.currentInteractionTokens+=estimateTokens(e),this.callbacks.onInteractionTokenUpdate&&this.callbacks.onInteractionTokenUpdate(this.currentInteractionTokens)});let o=null;s.on("error",e=>{o="AbortError"===e.name||this.abortController?.signal.aborted?new Error("Interrupted by user"):e});const i=await s.finalMessage();if(o)throw o;return this.callbacks.onRetryUpdate?.(null),i}catch(e){const s=r?.(),o=s?Object.assign(new Error(s.message),{type:s.type,error:{type:s.type,message:s.message}}):e;if(t=o,this.requestInterrupted||this.abortController?.signal.aborted)throw this.callbacks.onRetryUpdate?.(null),new Error("Interrupted by user");if(this.isNonRetryableError(o))throw trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"non_retryable_api_error"}),context:{component:ls.CONTEXT_ENGINE,heading:"Non-retryable API error",code:o?.status||o?.statusCode}}),this.formatAPIError(o);if(9===n)throw this.callbacks.onRetryUpdate?.(null),trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"max_retries_exceeded"}),context:{heading:"Max retries exceeded",component:ls.CONTEXT_ENGINE,code:o?.status||o?.statusCode,"retry.attempts":10}}),this.formatAPIError(o);trackError({error:sanitizeErrorForTelemetry({error:o instanceof Error?o:new Error(String(o)),label:"generate_retry_attempt"}),context:{heading:"Generate API retry",component:ls.CONTEXT_ENGINE,code:o?.status||o?.statusCode,"retry.attempt":n+1,"retry.max":10}});const i=Math.min(n,10),a=100*Math.pow(2,i),l=Math.max(a,1e3),u=Math.min(l,1e4);n>=2&&this.callbacks.onRetryUpdate?.(n+1),await sleep({delay:u,signal:this.abortController?.signal})}}throw t||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=e instanceof no||401===e?.status||e instanceof ro||403===e?.status,i=e?.type||e?.error?.type,a="rate_limit_error"===i||429===e?.status||n.includes("rate limit"),l="overloaded_error"===i||529===e?.status||n.includes("overloaded");return r||s||o||a||l}extractErrorMessage(e){dlog("Extracting error message from:",e);const t=e?.status||e?.statusCode||null;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;dlog("API error occurred:",e),dlog("Extracted error details:",t),dlog("Error type:",r),dlog("Error message:",s);const o=s?.toLowerCase().includes("insufficient credits");if(o)return new Error("Insufficient credits");const i=s?.toLowerCase().includes("oauth authentication required");if(i)return e;if(e instanceof ro||403===e?.status)return e;if(e instanceof no||401===e?.status)return new Error('Error: Authentication failed. Your API key may be invalid or expired. Run "cmd login" to sign in again.');const a=getSupportId();let l="";if(s)if(s.includes("Invalid 'Authorization' header"))l='Error: Authentication failed. Run "cmd login" to sign in again.';else{let e=s;for(;e.startsWith("Error: ");)e=e.substring(7);e.includes("Unexpected event order")&&(e="The API returned an error. This may be due to high traffic or a temporary issue.");let t=e.replace(/(?<!\.)Anthropic(?!\.)/gi,"Command Code");t.length>TC&&(t=t.substring(0,TC)+"..."),l=`Error: ${[n,r?r.charAt(0).toUpperCase()+r.slice(1):null,t].filter(Boolean).join(" ")}`;const o=s.toLowerCase(),i="overloaded_error"===r||o.includes("overloaded"),u="rate_limit_error"===r||o.includes("rate limit");l+=i?"\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.':'\n\nType "continue" to try again. If the issue persists, contact support: https://commandcode.ai/discord',"unknown"!==a&&(l+=`\nRequest ID: ${a}`)}else if(e.toString){const t=e.toString();l=t.length>TC?t.substring(0,TC)+"...":t}else l="Error: Unknown error occurred";return new Error(l)}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=nw.includes(o.name),a=rw.includes(o.name)?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",tool_use_id:o.id,content:`Error: ${r}`,is_error:!0}}),t.add(o.id);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.id);if(r.length>0){const e=await Promise.allSettled(r.map(async({toolBlock:e,entryId:t,description:n})=>{this.checkIfInterrupted(),isAgentTool(e.name)||e.name===Jy.GET_SELF_KNOWLEDGE||this.showToolRunning(e,t,n);const r="edit_file"===e.name?await resolveEditStartLine({filePath:e.input.filePath,oldContent:e.input.oldValue}).catch(()=>{}):void 0,s=await this.executeSingleTool(e);return isAgentTool(e.name)||e.name===Jy.GET_SELF_KNOWLEDGE||this.showToolSuccess(e,s,t,n,r),{toolBlock:e,toolResult:{type:"tool_result",tool_use_id:e.id,content: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.id);else{const e=s.reason instanceof Error?s.reason.message:"Unknown error";"Interrupted by user"===e&&isAgentTool(i.name)?t.add(i.id):(o.push({type:"tool_result",tool_use_id:i.id,content:`Error: ${e}`,is_error:!0}),t.add(i.id),i.name!==Jy.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.name,e.input),new Promise(e=>setTimeout(()=>e(null),6e3))])}catch(t){return kC.debug(`Failed to generate description for ${e.name}: ${t instanceof Error?t.message:"Unknown error"}`),this.callbacks.onToolDescriptionError&&this.callbacks.onToolDescriptionError(e.name,t),null}}async checkToolPermission(e,t){return nw.includes(e.name)&&this.callbacks.onPermissionRequest?{needsPermission:!0,allowed:await this.callbacks.onPermissionRequest(e.name,e.input,t)}:{needsPermission:!1,allowed:!0}}async executeSingleTool(e){const t=this.callbacks.getPermissionMode?.()||"standard",n=await executeTool(e.name,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=Ev(e.name,e.input),r={..."edit_file"===e.name?e.input:{},permissionDenied:!0},s={...ov(e.name,n,r),id:t},o=pv(s,"No (tell Command Code what to do differently)");this.callbacks.onFeedUpdate(o)}buildToolMetadata({toolBlock:e,editStartLine:t}){if("edit_file"===e.name)return{...e.input,...void 0!==t?{startLine:t}:{}};if("write_file"===e.name){const t=e.input,n="string"==typeof t.content?t.content:"",r=n.split("\n"),s=r.length>Gr?r.slice(0,Gr).join("\n"):n;return{...t,content:s,totalLines:r.length}}}showToolRunning(e,t,n){const r=Ev(e.name,e.input),s={...ov(e.name,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.name){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=Ev(e.name,i),l={...ov(e.name,a,o),id:n,...r?{description:r}:{}},u=pv(l,t);this.callbacks.onFeedUpdate(u)}showToolError(e,t,n,r){const s=Ev(e.name,e.input),o="edit_file"===e.name?{...e.input,permissionDenied:!0}:void 0,i={...ov(e.name,s,o),id:n,...r?{description:r}:{}},a=pv(i,gv(t));this.callbacks.onFeedUpdate(a)}processServerToolBlocks(e){if(0===e.content.filter(e=>"server_tool_use"===e.type).length)return"";let t="";const n=e.content;for(const e of n)if("text"===e.type)t+=e.text;else if("server_tool_use"===e.type){if(t.trim()){const e=sv(t.trim());this.callbacks.onFeedUpdate(e),t=""}const{message:r,isError:s}=tw({serverToolBlock:e,contentBlocks:n}),o=Ev(e.name,e.input),i=ov(e.name,o),a=pv(i,s?gv(r):r);this.callbacks.onFeedUpdate(a)}if(t.trim()){const e=sv(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:MS})}async checkAndCompactIfNeeded(){const e=Math.floor(MS*Dt.TIER_1_THRESHOLD),t=Math.floor(MS*Dt.TIER_2_THRESHOLD),n=Math.floor(MS*Dt.TIER_3_THRESHOLD),r=getCompactMode();try{if(this.contextTokensUsed>n){kC.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){kC.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 2 threshold (${t}), removing all except last ${Dt.TIER_2_KEEP_COUNT} tool calls`);const e=await this.removeToolCallsExceptLast(Dt.TIER_2_KEEP_COUNT);return kC.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=Dt.TIER_1_KEEP_COUNT;if(t>n){kC.debug(`Context tokens (${this.contextTokensUsed}) exceeded Tier 1 threshold (${e}), keeping last ${n} tool calls`);const t=await this.removeToolCallsExceptLast(n);kC.debug(`Tier 1 compaction completed: removed ${t.toolsRemoved} tool calls, saved ${t.tokensSaved} tokens`),this.emitAutoCompactInfo(t.tokensSaved)}}}catch(e){kC.debug(`Failed to automatically compact conversation: ${e}`)}}emitAutoCompactInfo(e){this.compactionCount++,e>0&&this.callbacks.onFeedUpdate(rv(`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_use"===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_use"===t[n].type&&r.push({id:t[n].id,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("user"===t&&Array.isArray(r)){const t=r.filter(e=>"tool_result"!==e.type||!o.has(e.tool_use_id)||(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_use"!==e.type||!o.has(e.id)||(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:MS}),{toolsRemoved:o.size,tokensSaved:n}}async summarizeAndCompact(){try{const{messagesToSummarize:e,messagesToKeep:t}=this.selectMessagesForSummarization();if(e.length<5)return kC.debug(`Not enough messages to summarize (${e.length}), falling back to Tier 2`),void await this.removeToolCallsExceptLast(Dt.TIER_2_KEEP_COUNT);kC.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});kC.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:MS}),kC.debug(`Tier 3 summarization complete: reduced from ${o} to ~${l} tokens`)}catch(e){kC.debug(`Summarization failed, falling back to tool removal: ${e}`),await this.removeToolCallsExceptLast(Dt.TIER_2_KEEP_COUNT)}}selectMessagesForSummarization(){const e=Dt.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:MS})),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()}}}}),NC=__esm({"src/utils/clear-console.ts"(){Ft(),AC=__name(()=>process.stdout.write("win32"===process.platform?"[2J[0f":"[2J[3J[H"),"clearConsole")}});async function getAuthenticatedEntity(){const e=getApiBaseUrl(),t=new Yy({baseUrl:e});return await t.get({endpoint:Ct.ALPHA.WHOAMI})}var RC=__esm({"src/utils/get-entity.ts"(){Ft(),Cs(),bw(),zt(),__name(getAuthenticatedEntity,"getAuthenticatedEntity")}}),$C={};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:p,updateStatus:g,setUpdateStatus:h,billingLink:f,setBillingLink:y,contextEngineRef:w,isSubmittingRef:S,setInput:E,setStaticKey:v,executeBash:C}){if(!t.length)return;if(g&&h(null),p(0),"bash"===e){if(S.current)return;S.current=!0;const e=iv(t);return a([...i,e]),E(""),await C(t,e=>{a(e)},()=>{AC(),v(e=>e+1)}),void(S.current=!1)}if(l)return d(e=>[...e,{input:t,displayMessage:s,isAutomated:o}]),void E("");if(S.current)return;S.current=!0,u(!0),m(wv()),E("");let k=!1;try{w.current&&await w.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(k=!0);if(k=!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:f,setBillingLink:y})}`;return void a(t=>[...t,lv(e)])}if(e.message.startsWith("Error:"))return m("Error"),void a(t=>[...t,lv(e.message)]);m("Error");const t=e.message||"An unexpected error occurred";a(e=>[...e,lv(t)])}finally{u(!1),k||m("Ready..."),S.current=!1}}__export($C,{getBillingLink:()=>getBillingLink,handleSubmit:()=>handleSubmit});var MC,DC=__esm({"src/tui/actions/submit.ts"(){Ft(),Tv(),po(),RC(),zt(),NC(),__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(f.homedir(),".cache","giget","gh",`${e}-${n}`);await D.rm(r,{recursive:!0,force:!0}).catch(()=>{})}async function cleanupStaleTempDirectories(){try{const e=f.tmpdir(),n=await D.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 D.stat(n)).mtimeMs>MC&&await D.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 LC,OC,qC=__esm({"src/services/skill-utils.ts"(){Ft(),MC=864e5,__name(isCorruptedArchiveError,"isCorruptedArchiveError"),__name(clearGigetCache,"clearGigetCache"),__name(cleanupStaleTempDirectories,"cleanupStaleTempDirectories"),__name(wrapFetchError,"wrapFetchError")}}),FC={};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>=LC)return[];const a=[];try{const e=await D.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 D.stat(e)).size>OC);else{const r=await D.readFile(e,"utf-8"),{data:s}=Fe(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(f.tmpdir(),`commandcode-skill-discovery-${W()}`);try{await D.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 D.rm(a,{recursive:!0,force:!0}).catch(()=>{}),{skills:l})}catch(e){throw await D.rm(a,{recursive:!0,force:!0}).catch(()=>{}),wrapFetchError(e,n,r)}}__export(FC,{discoverSkillsLocally:()=>discoverSkillsLocally});var jC=__esm({"src/services/local-skill-discovery.ts"(){Ft(),qC(),LC=100,OC=1048576,__name(findSkillMdFiles,"findSkillMdFiles"),__name(discoverSkillsLocally,"discoverSkillsLocally")}});Ft(),Ft();var BC=process.argv.includes("-d")||process.argv.includes("--debug");BC&&(process.env.DEBUG="true"),BC||(process.removeAllListeners("warning"),process.on("warning",()=>{})),Ft(),Ft(),gs();var{red:zC,yellow:UC,dim:WC}=ie,GC=__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:ls.CLI_ERROR_HANDLER,heading:t}}),console.log(),r){if(console.log(`${Qe.error} ${zC(t)}`),console.log(`${Qe.error} ${zC("ERROR →")} ${n.name}`),console.log(`${Qe.info} ${zC("REASON →")} ${n.message}`),console.log(`${Qe.info} ${zC("ERROR STACK ↓ \n")} ${n.stack}\n`),isTelemetryInitialized()){const e=getSupportId();console.log(`${Qe.info} ${WC(`Request ID: ${e}`)}`),console.log(`${WC(" Share this ID with support to help debug your issue.")}\n`)}}else console.log(`${Qe.warning} ${UC(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:ls.UNHANDLED_REJECTION,heading:"Unhandled Promise Rejection"}}),GC({heading:He`CRITICAL: Unhandled Promise Rejection!
|
|
278
|
+
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:ls.UNCAUGHT_EXCEPTION,heading:"Uncaught Exception"}}),GC({heading:He`CRITICAL: Uncaught Exception!
|
|
279
|
+
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)})})}gs(),__name(handleUnhandledErrors,"handleUnhandledErrors"),Ft(),Ft(),fs(),bw(),Cs(),zt(),Ew(),Sr(),Cr(),an(),Aw(),Nw(),Ow(),cC(),Lv(),ho(),Yv();var HC=null,QC=!1,VC=new Set([Jy.EDIT_FILE,Jy.WRITE_FILE,Jy.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(QC)return;QC=!0;const e=__name(e=>{HC?.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(),HC=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:HC.signal,dangerouslySkipPermissions:e.dangerouslySkipPermissions,maxTurns:e.maxTurns??KC,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 no&&(process.stderr.write('Error: Authentication failed. Please run "cmd login" first.\n'),process.exit(3)),e instanceof ro&&(process.stderr.write(`Error: ${e.message}\n`),process.exit(4)),e instanceof ao&&(process.stderr.write("Error: Rate limit exceeded. Please wait a moment and try again.\n"),process.exit(5)),e instanceof eo&&(process.stderr.write("Error: Unable to connect to the API. Please check your network connection.\n"),process.exit(6)),e instanceof lo&&(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 KC=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={[vt.PROJECT_SLUG]:xv.getCurrentProjectDirName(),[vt.TASTE_LEARNING]:d.toString(),[vt.INTERNAL_TEAM_FLAG_HEADER]:n.toString()};return r&&(m[vt.OAUTH_TOKEN]=`Bearer ${r}`,s&&(m[vt.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:`anthropic:${getConfiguredModel()}`},o={config:t.config,memory:t.memory,taste:t.taste,skills:t.skills,params:s,threadId:t.sessionId},i=await e.post({body:o,stream:!0,endpoint:Ct.ALPHA.GENERATE,headers:t.headers,signal:r});return Ge.fromReadableStream(i).finalMessage()}async function executeToolCall(e,t,n){if(VC.has(e.name)&&!n)return{type:"tool_result",tool_use_id:e.id,content:`Error: Tool "${e.name}" requires permissions. Use --yolo (or --dangerously-skip-permissions) to enable file writes and shell commands in print mode.`,is_error:!0};try{const n=await executeTool(e.name,e.input,{abortSignal:t});return{type:"tool_result",tool_use_id:e.id,content:n}}catch(t){if(t instanceof no||t instanceof ro||t instanceof ao||t instanceof eo||t instanceof lo)throw t;if(t instanceof Error&&"AbortError"===t.name)throw t;const n=t instanceof Error?t.message:"Unknown error";return{type:"tool_result",tool_use_id:e.id,content:`Error: ${n}`,is_error:!0}}}__name(setupConversationContext,"setupConversationContext"),__name(callApi,"callApi"),__name(executeToolCall,"executeToolCall");var YC=80;function truncate(e){return e.length<=YC?e:e.slice(0,YC)+"..."}function formatToolLabel(e){const t=e.input,n=__name(e=>truncate(String(t[e]??"")),"param");switch(e.name){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.name}}async function processQuery(e){const{query:t,signal:n,dangerouslySkipPermissions:r=!1,maxTurns:s,verbose:o}=e,i=getApiBaseUrl(),a=new Yy({baseUrl:i}),l=[{role:"user",content:t}],u=await setupConversationContext(),d=createBenchmarkCollector();let m=0,p="";const g={stream:process.stderr,color:"cyan"},h=o?Ce(g):null;try{for(;m<s;){if(m++,n.aborted)throw new Error("Cancelled");h?.start();const e=d?Date.now():0,t=await callApi(a,u,l,n),s=d?Date.now()-e:0;h?.stop();const i=t.usage,f=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,y=t.content.filter(e=>"text"===e.type),w=t.content.filter(e=>"tool_use"===e.type),S=y.map(e=>e.text).join("");if(S&&(p+=S),0===w.length){d&&f&&d.turnDetails.push(f);break}const E=[],v=d?Date.now():0;for(const e of w){if(n.aborted)throw new Error("Cancelled");let t=null;if(o){const n=formatToolLabel(e);t=Ce({...g,text:n}).start()}const s=await executeToolCall(e,n,r);if(t){const e=s.is_error?ve.cross:ve.tick;t.stopAndPersist({symbol:e})}if(d&&"string"==typeof s.content){const{cleanContent:e,metrics:t}=extractAgentMetrics(s.content);t&&(d.agents.push(t),s.content=e)}f&&f.toolCalls.push({name:e.name,isError:s.is_error??!1}),E.push(s)}d&&f&&(f.toolDurationMs=Date.now()-v,d.turnDetails.push(f)),l.push({role:"assistant",content:t.content}),l.push({role:"user",content:E})}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 p}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"),Ft(),Ft(),Ft(),Ft(),os(),BS(),Ft(),__name(getShellPathAndName,"getShellPathAndName"),__name(getShellType,"getShellType"),__name(detectUserShell,"detectUserShell");var JC=["no job control","cannot set terminal process group"],XC=null;function getShellInfo(){return XC||(XC=detectUserShell()),XC}__name(getShellInfo,"getShellInfo");var ZC=__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=R(u,l?["-i","-c",e]:["-c",e],{cwd:r,env:{...s},stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform});d.stdin?.end();let m="",p="",g=null;n>0&&(g=setTimeout(()=>{if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}d.kill("SIGTERM"),i({stdout:m,stderr:p+(p?"\n":"")+"[Command timed out]",exitCode:124,command:e})},n)),d.stdout?.on("data",t=>{try{const n=t.toString();if(m.length+n.length>es){if("win32"!==process.platform&&d.pid)try{process.kill(-d.pid,"SIGTERM")}catch{}return d.kill("SIGTERM"),void i({stdout:m,stderr:OS,exitCode:1,command:e})}m+=n}catch(e){p+=`\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(p.length+t.length>ts)return void(p+="\n[Error output truncated: too large]");p+=t}catch(e){p+=`\n[Error processing stderr: ${e instanceof Error?e.message:"Unknown error"}]`}}),d.on("close",t=>{g&&clearTimeout(g);const n=l?p.split("\n").filter(e=>!JC.some(t=>e.includes(t))).join("\n"):p;i({stdout:m.trim(),stderr:n.trim(),exitCode:t??0,command:e})}),d.on("error",t=>{g&&clearTimeout(g),i({stdout:m,stderr:p+`\n[Error: ${t.message}]`,exitCode:1,command:e})})})},"executeBashCommand"),ek=__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");Tv();var tk=__name(()=>{const[e,t]=Q({isExecuting:!1,currentCommand:null});return{executeBash:J(async(e,n,r)=>{t({isExecuting:!0,currentCommand:e});try{const t=await ZC(e,{timeout:3e4,cwd:process.cwd()}),s=ek(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]=pv(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]=pv(r,`Error: ${s}`);break}}return n}),r()}finally{t({isExecuting:!1,currentCommand:null})}},[]),executionState:e}},"useBashExecution");function useUiOverlays(){const[e,t]=Q(!1),[n,r]=Q(!1),[s,o]=Q(!1),[i,a]=Q(!1),[l,u]=Q(!1),[d,m]=Q(!1),[p,g]=Q(!1),[h,f]=Q(!1),[y,w]=Q(!1),[S,E]=Q(!1),[v,C]=Q(!1),[k,T]=Q(!1),[_,x]=Q(!1),[P,A]=Q(!1),[I,N]=Q(!1),[R,$]=Q(!1),[M,D]=Q(0),[L,O]=Q("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:p,setShowMemorySelector:g,showMcpManager:h,setShowMcpManager:f,showLearningFeed:y,setShowLearningFeed:w,showSessionSelector:S,setShowSessionSelector:E,showAddDirModal:v,setShowAddDirModal:C,showRewindSelector:k,setShowRewindSelector:T,showLoginOverlay:_,setShowLoginOverlay:x,showCompactModeSelector:P,setShowCompactModeSelector:A,showContextView:I,setShowContextView:N,showStatusView:R,setShowStatusView:$,staticKey:M,setStaticKey:D,transcriptMode:L,setTranscriptMode:O,expandedToolOutput:"off"!==L}}function useFeed(){const[e,t]=Q([]),[n,r]=Q([]),[s,o]=Q([]),[i,a]=Q(!1),l=V([]);return K(()=>{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]=Q(crypto.randomUUID()),[n,r]=Q(!1);return{sessionId:e,setSessionId:t,sessionLoaded:n,setSessionLoaded:r,sessionLoadIdRef:V(null)}}function useStatus(e){const[t,n]=Q("Ready..."),r=V(!1),[s,o]=Q(""),i=V(null),[a,l]=Q(null),u=V(a),[d,m]=Q(null),[p,g]=Q(!1),[h,f]=Q(""),[y,w]=Q(null),[S,E]=Q(0),[v,C]=Q(null),[k,T]=Q(!1),[_,x]=Q(e??null);K(()=>{u.current=a},[a]),K(()=>{if(_){const e=setTimeout(()=>{x(null)},3e4);return()=>clearTimeout(e)}},[_]);const P=__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:p,setShowShareNotification:g,unshareNotificationMessage:h,setUnshareNotificationMessage:f,retryAttempt:y,setRetryAttempt:w,interactionTokens:S,setInteractionTokens:E,contextUsage:v,setContextUsage:C,tasteLearningEnabled:k,setTasteLearningEnabled:T,updateStatus:_,setUpdateStatus:x,showHintMessage:P}}function useAuth(){const[e,t]=Q(null),[n,r]=Q(getConfiguredModel()),[s,o]=Q(!1),[i,a]=Q(null),[l,u]=Q(!1);return{currentProvider:e,setCurrentProvider:t,currentModel:n,setCurrentModel:r,isOAuthMode:s,setIsOAuthMode:o,authComponentInfo:i,setAuthComponentInfo:a,showProviderNotification:l,setShowProviderNotification:u,providerNotificationTimer:V(null),modelNotificationTimer:V(null)}}Ft(),__name(useUiOverlays,"useUiOverlays"),Ft(),__name(useFeed,"useFeed"),Ft(),__name(useSession,"useSession"),Ft(),__name(useStatus,"useStatus"),Ft(),Sr(),__name(useAuth,"useAuth"),Ft(),Ft(),Ft(),zt();var nk=class extends We{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 D.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 D.mkdir(e,{recursive:!0});let t={permissions:{allow:[],deny:[],defaultMode:"acceptEdits"}};try{const e=await D.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 D.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 D.mkdir(n,{recursive:!0});try{const t=await D.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 D.writeFile(r,JSON.stringify(e,null,2),"utf-8")}catch(e){console.error("Failed to add command to .commandcode settings:",e)}}},rk=__name((e={})=>{const[t,n]=Q(null),[r,s]=Q(null),[o,i]=Q(!1);return K(()=>{const t=e.projectRoot||process.cwd(),r=new nk(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:J(async n=>{if(!t)return{allowed:!0};const r=await t.requestPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),requestShellPermission:J(async n=>{if(!t)return{allowed:!0};const r=await t.requestShellPermission(n);return e.onPermissionResponse&&e.onPermissionResponse(r),r},[t,e.onPermissionResponse]),respondToPrompt:J(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:J(()=>{t?.clearSessionPermissions()},[t]),clearProjectPermissions:J(()=>{t?.clearProjectPermissions()},[t]),setAutoApprove:J((e,n)=>{t?.setAutoApprove(e,n)},[t]),setEnabled:J(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]=Q(()=>e||(t?"auto-accept":"standard")),a=V(o);K(()=>{a.current=o},[o]);const{requestShellPermission:l,service:u,respondToPrompt:d,clearSessionPermissions:m,setEnabled:p}=rk({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 K(()=>{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]=Q(null),[n,r]=Q(null);return{pendingPermission:e,setPendingPermission:t,pendingQuestion:n,setPendingQuestion:r}}function useOnboarding(){const[e,t]=Q(!1),[n,r]=Q(!1),[s,o]=Q(!0),[i,a]=Q(!1),[l,u]=Q(!1),[d,m]=Q(null),[p,g]=Q(!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:p,setAutoLearnTaste:g,tasteOnboardingCheckedRef:V(!1)}}function useExit(){const[e,t]=Q(!1),[n,r]=Q(null),s=V(null),o=V(0),i=V(null),a=J(()=>{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:p,setCurrentProvider:g,shareInfoRef:h,permissionsService:f,permissionModeRef:y,setPendingQuestion:w,contextEngineRef:S}){const E=J(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=>{p(e)},"onContextUsageUpdate"),onRetryUpdate:__name(e=>{d(e)},"onRetryUpdate"),onProviderChange:__name(e=>{g(e)},"onProviderChange"),onStatusUpdate:__name(e=>{u.current=!0,l(e)},"onStatusUpdate"),onPermissionRequest:__name(async(e,t,n)=>{const r=t??{};if(!f)return!0;if("shell_command"===e){const e=buildShellPermissionRequest(r,n);return(await f.requestShellPermission(e)).allowed}if("kill_shell"===e){const e=createKillShellPermissionRequest(r);return(await f.requestShellPermission(e)).allowed}const s=buildFilePermissionRequest(e,r);return(await f.requestPermission(s)).allowed},"onPermissionRequest"),onQuestionRequest:__name(async e=>new Promise((t,n)=>{w({params:e,resolve:t,reject:n}),l("Waiting for your response...")}),"onQuestionRequest"),getShareInfo:__name(()=>{const n=h.current;return n?{sessionId:t??e,secret:n.secret}:null},"getShareInfo"),getPermissionMode:__name(()=>y.current,"getPermissionMode")}),[f,e]);return K(()=>{S.current||!r||n||t||(S.current=new _C(E(),e))},[e,n,t,r,E,S]),{createContextEngineCallbacks:E}}Ft(),__name(applyAutoAcceptMode,"applyAutoAcceptMode"),__name(usePermissionMode,"usePermissionMode"),Ft(),__name(usePendingOps,"usePendingOps"),Ft(),__name(useOnboarding,"useOnboarding"),Ft(),__name(useExit,"useExit"),Ft(),IC(),__name(createKillShellPermissionRequest,"createKillShellPermissionRequest"),__name(buildShellPermissionRequest,"buildShellPermissionRequest"),__name(getFileAction,"getFileAction"),__name(buildFilePermissionRequest,"buildFilePermissionRequest"),__name(useContextEngine,"useContextEngine"),Ft(),Ft(),Ft(),Cn();var sk=5242880,ok=class{static{__name(this,"PromptHistoryManager")}buffer=[];filePath;initialized=!1;writeQueue=[];flushTimer=null;writeFailures=0;isFlushing=!1;cleanupPromise=null;constructor(){this.filePath=e.join(h.homedir(),".commandcode","history.jsonl")}async init(){if(!this.initialized){try{const e=(await M.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 M.mkdir(n,{recursive:!0});const r=t.map(e=>JSON.stringify(e)).join("\n")+"\n";await M.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 M.stat(this.filePath);if(e.size<=sk)return;dlog(`[PromptHistory] File size ${e.size} exceeds threshold, rotating`);const t=(await M.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 M.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 ok}__name(createHistoryManager,"createHistoryManager"),LE(),Lv(),NC(),uC(),Ft(),zt(),Iw();var ik=class{static{__name(this,"TasteManager")}static async initializeProject(){const t=process.cwd(),n=e.join(t,".commandcode","taste");await M.mkdir(n,{recursive:!0});const r=e.join(n,"taste.md");try{await M.access(r);const e=await M.readFile(r,"utf-8"),t=migrateHeader({content:e});t!==e&&await M.writeFile(r,t,"utf-8")}catch{await M.writeFile(r,kw+"\n\n","utf-8")}}static async isInitialized(){const t=process.cwd(),n=e.join(t,".commandcode","taste");try{return await M.access(n),!0}catch{return!1}}};Sr(),Cr(),Ft(),IC(),Tv(),NC(),Ft(),zt(),Jh(),bw(),Cs();var{setText:ak}=Ve;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 ak(t.url),r(""),s(!0),void setTimeout(()=>{s(!1)},3e3);try{r("Creating share link...");const t=o.current?.getMessages()||[],i=Bh.sanitizeMessages(t,global.COMMAND_CODE_CWD||process.cwd()),a=new Yy({baseUrl:getApiBaseUrl()}),l=await a.post({endpoint:Ct.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 ak(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 Yy({baseUrl:getApiBaseUrl()});await i.delete({endpoint:Ct.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 p=crypto.randomUUID();t.current=p;try{r([]),s([]),n.current=null,l("standard"),o(e),i(!1),a(!0),n.current=new _C(m(e),e);const{feedEntries:g,corruptedLines:h,totalLines:f}=await n.current.loadSession(e);if(t.current!==p)return;await loadShareInfo({contextEngineRef:n,setShareInfo:d});const y=[];if(0===g.length&&f>0&&y.push(lv(`Session could not be loaded. ${f} lines could not be parsed.`)),0===g.length&&0===f&&y.push(rv("Session loaded but contains no messages.")),g.length>0&&(h>0&&y.push(rv(`Warning: ${h} message(s) could not be loaded.`)),y.push(...g)),t.current!==p)return;r(y),AC(),u(e=>e+1)}catch(e){if(t.current!==p)return;console.error("Failed to load session:",e);const n=e instanceof Error?e.message:"Unknown error";r([lv(`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:p,contextEngineRef:g,isSubmittingRef:h,initialPromptSubmittedRef:f,historyManagerRef:y,executeBash:w,createContextEngineCallbacks:S,setInput:E,onCommand:v}){const C=J(async()=>{try{const e=await isTasteLearningEnabled();l.setTasteLearningEnabled(e),e&&await ik.initializeProject()}catch{}},[l.setTasteLearningEnabled]),k=J(async()=>{const e=await getConfiguredProvider();u.setCurrentProvider(e);const t=await isOAuthEnforced();u.setIsOAuthMode(t)},[u.setCurrentProvider,u.setIsOAuthMode]),T=J(()=>{const e=getMcpConnectionManager();e.isInitialized||e.initialize().catch(()=>{})},[]),_=J(e=>{handleSelectSession({selectedSessionId:e,sessionLoadIdRef:a.sessionLoadIdRef,contextEngineRef:g,setFeed:i.setFeed,setLiveEntries:i.setLiveEntries,setSessionId:a.setSessionId,setShowSessionSelector:m.setShowSessionSelector,setSessionLoaded:a.setSessionLoaded,setPermissionMode:p.setPermissionMode,setStaticKey:m.setStaticKey,setShareInfo:l.setShareInfo,createContextEngineCallbacks:S})},[a,i,m,p,l,g,S]),x=J(async()=>{if(n){const e=await xv.listSessions();return void(e.length>0&&_(e[0].id))}t?_(t):e&&m.setShowSessionSelector(!0)},[n,t,e,_,m]);K(()=>{(async()=>{await xv.isProjectInitialized()?(d.setProjectTrusted(!0),d.setCheckingProject(!1),C(),k(),T(),await x()):r?(await xv.initializeProject(),d.setProjectTrusted(!0),d.setCheckingProject(!1),C(),k(),T(),await x()):isDirectoryEmpty()?(await xv.initializeProject(),d.setProjectTrusted(!0),d.setCheckingProject(!1),C(),k(),T()):(d.setShowTrustPrompt(!0),d.setCheckingProject(!1))})()},[e,n,r]),K(()=>{if(!d.projectTrusted)return;const e=createHistoryManager();return y.current=e,e.init(),()=>{e.cleanup()}},[d.projectTrusted]),K(()=>{if(!o)return;const e=__name(()=>{m.showLearningFeed||(AC(),m.setStaticKey(e=>e+1))},"handleResize");return o.on("resize",e),()=>{o.off("resize",e)}},[o]),K(()=>{s&&d.projectTrusted&&!d.checkingProject&&g.current&&!m.showSessionSelector&&!f.current&&(f.current=!0,submitInitialPrompt({initialPrompt:s,onCommand:v,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:g,isSubmittingRef:h,setInput:E,setStaticKey:m.setStaticKey,executeBash:w}),"submitAsUserMessage")}))},[s,d.projectTrusted,d.checkingProject,m.showSessionSelector,v]);const P=V(null);P.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:g,isSubmittingRef:h,setInput:E,setStaticKey:m.setStaticKey,executeBash:w,role:"",input:""};const A=J(async({role:e,input:t,images:n,ideContext:r,displayMessage:s,isAutomated:o})=>handleSubmit({...P.current,role:e,input:t,images:n,ideContext:r,displayMessage:s,isAutomated:o}),[]);return{loadTasteStatus:C,loadCurrentProvider:k,initializeMcpInBackground:T,onSubmit:A}}__name(loadShareInfo,"loadShareInfo"),__name(handleShareCommand,"handleShareCommand"),__name(handleUnshareCommand,"handleUnshareCommand"),__name(handleSelectSession,"handleSelectSession"),__name(handleNewSession,"handleNewSession"),DC(),__name(submitInitialPrompt,"submitInitialPrompt"),__name(useStartup,"useStartup"),Ft(),bn(),Tv(),Sn(),Ft(),zt(),Cn(),Ft();var lk={"claude-code":"Claude Code",cursor:"Cursor",aider:"Aider",cline:"Cline",codex:"Codex","pi-agent":"Pi Agent",factory:"Factory"};function getAgentDisplayName(e){return lk[e]||e}function getProjectDirName(e){return e.replace(/\//g,"-")}function getGlobalProjectSettingsDir(t=process.cwd()){const n=Ue(t);return e.join(f.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 M.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 M.mkdir(s,{recursive:!0}),await M.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),mC.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 M.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"),Ft(),Cn(),gC(),zt(),__name(getGlobalProjectSettingsDir,"getGlobalProjectSettingsDir"),__name(getGlobalProjectSettingsPath,"getGlobalProjectSettingsPath"),__name(loadGlobalProjectSettings,"loadGlobalProjectSettings"),__name(saveGlobalProjectSettings,"saveGlobalProjectSettings"),__name(loadLocalProjectSettings,"loadLocalProjectSettings"),__name(loadMergedProjectSettings,"loadMergedProjectSettings"),__name(mergeSettings,"mergeSettings"),Ft(),Cn();var ck=e.join(h.homedir(),".codex","sessions");async function readSessionMeta(e){try{const t=x(e,{encoding:"utf8"}),n=Ke.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 M.access(t)}catch{return dlog("[Codex] sessions directory not found"),[]}try{const s=await M.readdir(t);for(const o of s){if(!/^\d{4}$/.test(o))continue;const s=e.join(t,o);if(!(await M.stat(s)).isDirectory())continue;const i=await M.readdir(s);for(const t of i){if(!/^\d{2}$/.test(t))continue;const i=e.join(s,t);if(!(await M.stat(i)).isDirectory())continue;const a=await M.readdir(i);for(const s of a){if(!/^\d{2}$/.test(s))continue;const a=e.join(i,s);if(!(await M.stat(a)).isDirectory())continue;n?.({phase:"scanning",totalFiles:r.length,processedFiles:0,matchedSessions:0,currentDir:`${o}/${t}/${s}`});const l=(await M.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(ck,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 M.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 M.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"),Ft(),Cn();var uk=e.join(h.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 M.access(uk)}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 M.readdir(uk);for(const r of n){if(!t.includes(r))continue;const n=e.join(uk,r,"agent-transcripts");try{if((await M.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 M.readdir(o);for(const n of t){const t=e.join(o,n);try{if(!(await M.stat(t)).isDirectory())continue;const r=e.join(t,`${n}.jsonl`);try{const e=await M.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 M.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 M.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(h.homedir(),".claude","projects");await M.access(t);const s=getProjectDirName(process.cwd()),o=(await M.readdir(t)).filter(e=>e===s);for(const s of o){const o=e.join(t,s);if((await M.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}){K(()=>{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]),K(()=>()=>{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)},[]),K(()=>{(async()=>{if("anthropic"===s.currentProvider&&s.isOAuthMode)try{await mn.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]),K(()=>{if(!t.isCmdCodeBusy)return void(r.pinnedStatusRef.current=!1);if(null!==r.retryAttempt)return;const e=setInterval(()=>{r.pinnedStatusRef.current||r.setStatus(wv())},7e3);return()=>clearInterval(e)},[t.isCmdCodeBusy,r.retryAttempt]),K(()=>{a||triggerTasteOnboarding({projectTrusted:o.projectTrusted,onboardingComplete:o.onboardingComplete,isOnboardingMode:o.showTasteOnboarding,tasteOnboardingCheckedRef:o.tasteOnboardingCheckedRef,setIsOnboardingMode:o.setShowTasteOnboarding})},[o.projectTrusted,o.onboardingComplete,o.showTasteOnboarding,a]),K(()=>{if(o.showTasteOnboarding&&!o.tasteOnboardingEntryId){const e=cv();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"),Ft(),NC(),Lv(),Tv(),Ft(),yn(),Cr(),NC(),zt(),Ft();var dk="└",mk=" ",pk=`${mk}TASTE${mk}`;function useKeyboard({showTasteConfig:e,showSkillsConfig:t,showProviderSelector:n,showModelSelector:r,showMemorySelector:s,showMcpManager:o,showLearningFeed:i,showRewindSelector:a,showLoginOverlay:l,showAddDirModal:u,authComponentInfo:d,setShowLearningFeed:m,setShowModelSelector:p,setStaticKey:g,transcriptMode:h,setTranscriptMode:f,isCmdCodeBusy:y,liveEntries:w,queuedMessagesRef:S,setInput:E,setQueuedMessages:v,setFeed:C,setLiveEntries:k,setIsCmdCodeBusy:T,setRetryAttempt:_,setStatus:x,pendingExitKey:P,setPendingExitKey:A,pendingExitKeyRef:I,lastExitKeyTimeRef:N,exitConfirmationTimeoutRef:R,resetPendingExitKey:$,pendingPermission:M,setPendingPermission:D,pendingQuestion:L,setPendingQuestion:O,setShouldExit:q,contextEngineRef:F,handleToggleAutoAccept:j,handleDoubleEscapeEmpty:B,respondToPrompt:z,createErrorEntry:U}){const W=__name(()=>{if(!F.current)return;F.current.interrupt(!0);const e=w.length>0;if(T(!1),_(null),k([]),x("Interrupted by user"),!e){const e=U("Interrupted by user");C(t=>[...t,e])}if(S.current.length>0){const e=S.current.map(e=>e.displayMessage??e.input).join("\n");E(t=>t?e+"\n"+t:e),v([]),S.current=[]}},"handleInterrupt");ne((w,S)=>{if(S.shift&&S.tab||"[Z"===w)j();else if(e||t||n||r||s||o||d||i||a||l||u)P&&$();else{if(""===w||S.ctrl&&"c"===w){if(y&&F.current)return void W();const e=Date.now(),t=e-N.current;return N.current=e,"ctrl-c"===I.current&&t<2e3?(R.current&&(clearTimeout(R.current),R.current=null),void q(!0)):(E(()=>""),I.current="ctrl-c",A("ctrl-c"),R.current&&clearTimeout(R.current),void(R.current=setTimeout(()=>{I.current=null,A(null),R.current=null},2e3)))}if(S.ctrl&&"t"===w)return AC(),m(!i),void g(e=>e+1);if(getIsExpandToolShortcut(S,w))return AC(),f("off"===h?"limited":"off"),void g(e=>e+1);if(S.ctrl&&"e"===w&&"off"!==h)return AC(),f("limited"===h?"full":"limited"),void g(e=>e+1);if(S.meta&&"p"===w||isAltP(w))p(!0);else if(S.escape){if(L)return L.reject(new Error("Question cancelled by user")),O(null),void x("Question cancelled");if(M)return z({label:"No, and tell Command Code what to do differently",value:"no",description:"Deny and provide feedback",scope:void 0}),M.resolve(!1),D(null),void x("Permission denied");y&&F.current&&W()}}})}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:p}){const g=J(()=>{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]),h=J(()=>{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]),f=J(s=>{if(n.setOnboardingComplete(!0),n.setShowTasteOnboarding(!1),n.setAutoLearnTaste(!1),AC(),s?.skipped){const e=rv("",{isTasteSkip:!0});t.setFeed(t=>[...t,e])}r.setStaticKey(e=>e+1),e&&r.setShowSessionSelector(!0)},[e,n,r,t]),y=J(async()=>{try{if(await xv.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]),w=J(()=>{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,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:p,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:g,handleDoubleEscapeEmpty:h,respondToPrompt:i.respondToPrompt,createErrorEntry:lv}),{handleToggleAutoAccept:g,handleDoubleEscapeEmpty:h,handleTasteOnboardingComplete:f,handleTrust:y,handleNoTrust:w}}__name(useKeyboard,"useKeyboard"),__name(useHandlers,"useHandlers"),Ft(),Ft(),zt(),Tv(),vr(),Ft(),Ft(),Ft(),zt(),Cn(),kr(),$r(),Ft(),zt();var gk=t.join(f.homedir(),".commandcode","updates.json");function ensureDir(){const e=t.dirname(gk);S.existsSync(e)||S.mkdirSync(e,{recursive:!0})}function readUpdatesConfig(){try{if(!S.existsSync(gk))return{autoUpdate:!0,lastCheckedAt:0,checkIntervalMs:36e5,pending:null};const e=S.readFileSync(gk,"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(),S.writeFileSync(gk,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"),kr();var hk=Je(I),fk=getPackageJson();function shouldSkipUpdateSystem(){return!!process.env.CI||!!process.env.COMMANDCODE_SKIP_UPDATES||!!isLocalDevelopmentBuild()}function fetchVersions(){try{const e=N("npm view command-code versions --json",{encoding:"utf-8",timeout:5e3});return JSON.parse(e)}catch{return null}}function getCurrentVersion(){return fk.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(Xe.rcompare)[0]}function determineUpdateTarget(e,t,n){const r=getLatestVersion(t);if(r&&Xe.gt(r,e))return{latestVersion:r,updateAvailable:!0};if(isAlphaVersion(e)){const t=getLatestVersion(n);if(t&&Xe.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 hk(`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(!Xe.gt(t.targetVersion,e))return dlog("[Updater] Pending update no longer valid"),void clearPendingUpdate();dlog(`[Updater] Running pending update: ${e} -> ${t.targetVersion}`);const n=Ce(`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}`)}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 N("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 yk=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)=>{$(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&&yk.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 Sk=__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");Ft();var bk='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?`${bk}\n\nReview PR number: ${n}${t?"\n(Note: PR number auto-detected from current branch.)":""}`:`${bk}\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(f.homedir(),".commandcode","commands");function loadCommandsFromDirectory(n,r,s=""){if(S.existsSync(n))try{const o=S.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=S.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"),Ft(),__name(lastResponseHasComments,"lastResponseHasComments"),Ft(),zt(),Ft(),zt(),__name(loadCustomCommands,"loadCustomCommands"),__name(customCommandsToMenuItems,"customCommandsToMenuItems"),__name(getCustomCommandContent,"getCustomCommandContent"),vr(),Ft();var Ek=["Code","Code - Insiders","VSCodium","Cursor"],vk="Code",Ck={key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:"\r"},when:"terminalFocus"},kk=__name(e=>m(e).href,"formatPathForTerminal"),Tk=__name(e=>{switch(e){case"darwin":return["Library","Application Support"];case"win32":return["AppData","Roaming"];default:return[".config"]}},"getConfigPathSegments"),_k=__name(({home:t,configSegments:n,variant:r})=>e.join(t,...n,r,"User","keybindings.json"),"buildKeybindingsPath"),xk=__name(({home:t,configSegments:n,variants:r})=>{for(const s of r){const r=_k({home:t,configSegments:n,variant:s});if(w.existsSync(e.dirname(r)))return s}return null},"findExistingVariant"),Pk=__name(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"shift+enter"===t.key&&Ak(t.when)},"isTerminalShiftEnterBinding"),Ak=__name(e=>"string"==typeof e?e.includes("terminalFocus"):!!Array.isArray(e)&&e.some(e=>"string"==typeof e&&e.includes("terminalFocus")),"hasTerminalFocusCondition"),Ik=__name(e=>{const t=Ze(e).trim();return!t||/^\[\s*\]$/.test(t)},"isEmptyKeybindingsContent"),Nk=__name(e=>/,\s*[}\]]/s.test(e),"hasTrailingComma"),Rk=__name(({error:e,content:t})=>{const n=e.message;return Nk(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"),$k=__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"),Mk=__name(e=>{try{const t=Ze(e),n=$k(t);return{success:!0,data:JSON.parse(n)}}catch(t){return t instanceof Error?{success:!1,error:Rk({error:t,content:e})}:{success:!1,error:"Unknown parse error"}}},"safeParseJson"),Dk=__name(({message:e,keybindingsPath:t})=>({success:!0,message:e,details:kk(t)}),"createSuccessResult"),Lk=__name(({message:e,keybindingsPath:t})=>({success:!1,message:e,details:kk(t)}),"createErrorResult"),Ok=__name(()=>{const t=h.homedir(),n=h.platform();if(process.env.VSCODE_PORTABLE)return e.join(process.env.VSCODE_PORTABLE,"user-data","User","keybindings.json");const r=Tk(n);if(!r)return _k({home:t,configSegments:[".config"],variant:vk});const s=xk({home:t,configSegments:r,variants:Ek});return _k({home:t,configSegments:r,variant:s??vk})},"getVSCodeKeybindingsPath"),qk=__name(e=>{const t={hasCompatible:!1,hasConflicting:!1};for(const n of e)Pk(n)&&(n.command===Ck.command&&n.args?.text===Ck.args.text?t.hasCompatible=!0:(t.hasConflicting=!0,t.conflictingText="string"==typeof n.args?.text?n.args.text:n.command));return t},"checkExistingShiftEnterBindings"),Fk=__name(t=>{try{if(!w.existsSync(t)){const n=e.dirname(t);return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{rawContent:"",keybindings:[]}}const n=w.readFileSync(t,"utf-8");if(Ik(n))return{rawContent:n,keybindings:[]};const r=Mk(n.trim());return r.success?Array.isArray(r.data)?{rawContent:n,keybindings:r.data}:Lk({message:"VSCode keybindings.json does not contain an array. Please fix the file format.",keybindingsPath:t}):Lk({message:`Failed to parse existing VSCode key bindings: ${r.error}`,keybindingsPath:t})}catch(e){const n=e instanceof Error?e.message:"Unknown error";return Lk({message:`Failed to read keybindings file: ${n}`,keybindingsPath:t})}},"readKeybindingsFile"),jk=__name(({rawContent:e,keybindingsPath:t})=>{const n=JSON.stringify(Ck,null,2);if(Ik(e))return`[\n${n}\n]\n`;const r=e.lastIndexOf("]");if(-1===r)return Lk({message:"VSCode keybindings.json is malformed (missing closing bracket).",keybindingsPath:t});const s=e.lastIndexOf("}",r);return-1===s?Lk({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=Ok();try{const t=Fk(e);if("success"in t)return t;const{rawContent:n,keybindings:r}=t,s=qk(r);if(s.hasConflicting)return Lk({message:"Conflicting VSCode terminal Shift+Enter key binding already exists. Please remove the key binding and try again.",keybindingsPath:e});if(s.hasCompatible)return Dk({message:"VSCode terminal Shift+Enter key binding already configured.",keybindingsPath:e});const o=jk({rawContent:n,keybindingsPath:e});return"string"!=typeof o?o:(w.writeFileSync(e,o,"utf-8"),Dk({message:"Installed VSCode terminal Shift+Enter key binding",keybindingsPath:e}))}catch(t){return Lk({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"),os(),rr();var Bk=(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))(Bk||{}),zk=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"]),Uk=[{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"}],Wk=__name(({onSelectCommand:e,onInsertCommand:t,onClose:n,searchQuery:r=""})=>{const[s,o]=Q(0),[i,a]=Q(0),{stdout:l}=te(),u=l?.columns??80,d=Math.max(20,u-22-2-1-2),m=Y(()=>{const e=[...customCommandsToMenuItems(loadCustomCommands()),...Uk.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]),p=Y(()=>{const e=i,t=Math.min(e+8,m.length);return m.slice(e,t)},[m,i]);return K(()=>{o(0),a(0)},[r]),ne((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?G.createElement(X,{flexDirection:"column",paddingLeft:2},G.createElement(Z,{color:$n.DIM},"No commands found")):(m.length,G.createElement(X,{flexDirection:"column",paddingLeft:1},G.createElement(X,{columnGap:2},G.createElement(X,{flexDirection:"column",width:22},p.map((e,t)=>{const n=i+t;return G.createElement(Z,{key:n,color:s===n?$n.WHITE:$n.DIM,wrap:"truncate"},e.command)})),G.createElement(X,{flexDirection:"column"},p.map((e,t)=>{const n=i+t;return G.createElement(Z,{key:n,color:s===n?$n.WHITE:$n.DIM,wrap:"truncate"},truncateString({text:e.description,maxChars:d}))})))))},"CommandMenu");Aw(),Ft(),Ft(),Cr(),rr();var Gk=__name(e=>({darwin:"macOS",linux:"Linux",win32:"Windows",freebsd:"FreeBSD",sunos:"SunOS"}[e]||e),"getPlatformName"),Hk=__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"),Qk=__name(({icon:e,label:t,children:n})=>G.createElement(Z,null,G.createElement(Z,{color:$n.CYAN},e," "),G.createElement(Z,{color:$n.DIM},t.padEnd(12)),n),"Row"),Vk=__name(({title:e})=>G.createElement(Z,null,G.createElement(Z,{color:$n.GRAY},"───"),G.createElement(Z,{color:$n.WHITE}," ",e," "),G.createElement(Z,{color:$n.GRAY},"─".repeat(35))),"Header"),Kk=__name(({title:e,marginTop:t=0,children:n})=>G.createElement(X,{flexDirection:"column",marginTop:t},G.createElement(Vk,{title:e}),G.createElement(X,{flexDirection:"column",paddingY:1},n)),"Section"),Yk=__name(({cpuCount:e,totalMem:t})=>G.createElement(Kk,{title:"System Information"},G.createElement(Qk,{icon:ve.bullet,label:"Date"},G.createElement(Z,null,formatDate())),G.createElement(Qk,{icon:ve.pointer,label:"Platform"},G.createElement(Z,{color:$n.GREEN},Gk(h.platform())),G.createElement(Z,{color:$n.DIM}," ","(",h.platform(),", ",h.arch(),")")),G.createElement(Qk,{icon:ve.triangleUp,label:"Hostname"},G.createElement(Z,null,h.hostname())),G.createElement(Qk,{icon:ve.bullet,label:"User"},G.createElement(Z,{color:$n.YELLOW},h.userInfo().username)),G.createElement(Qk,{icon:ve.bullet,label:"CPUs"},G.createElement(Z,{color:$n.MAGENTA},e," cores")),G.createElement(Qk,{icon:ve.bullet,label:"Memory"},G.createElement(Z,{color:$n.CYAN},t," GB")),G.createElement(Qk,{icon:ve.play,label:"Uptime"},G.createElement(Z,null,Hk(h.uptime()))),G.createElement(Qk,{icon:ve.arrowRight,label:"Home"},G.createElement(Z,{color:$n.DIM},h.homedir())),G.createElement(Qk,{icon:ve.pointer,label:"Shell"},G.createElement(Z,null,process.env.SHELL||"N/A")),G.createElement(Qk,{icon:ve.bullet,label:"Node"},G.createElement(Z,{color:$n.GREEN},process.version))),"SystemInfoSection"),Jk=__name(({cpus:e})=>G.createElement(Kk,{title:"CPU Details",marginTop:1},e.map((e,t)=>G.createElement(Qk,{key:t,icon:ve.bullet,label:`Core ${t}`},G.createElement(Z,null,e.model.trim()),G.createElement(Z,{color:$n.YELLOW}," @ ",e.speed," MHz")))),"CPUDetailsSection"),Xk=__name(({networkInterfaces:e})=>G.createElement(Kk,{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)=>G.createElement(Qk,{key:`${e}-${n}`,icon:ve.bullet,label:e},G.createElement(Z,{color:$n.GREEN},t.address))):null})),"NetworkSection"),Zk=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>G.createElement(X,{flexDirection:"column"},G.createElement(Z,null,"System Information"),G.createElement(Z,null,"─".repeat(40)),G.createElement(Z,null,"Date ",formatDate()),G.createElement(Z,null,"Platform ",Gk(h.platform())," (",h.platform(),","," ",h.arch(),")"),G.createElement(Z,null,"Hostname ",h.hostname()),G.createElement(Z,null,"User ",h.userInfo().username),G.createElement(Z,null,"CPUs ",e.length," cores"),G.createElement(Z,null,"Memory ",t," GB"),G.createElement(Z,null,"Uptime ",Hk(h.uptime())),G.createElement(Z,null,"Home ",h.homedir()),G.createElement(Z,null,"Shell ",process.env.SHELL||"N/A"),G.createElement(Z,null,"Node ",process.version),r&&G.createElement(G.Fragment,null,G.createElement(Z,null,"\n","CPU Details"),G.createElement(Z,null,"─".repeat(40)),e.map((e,t)=>G.createElement(Z,{key:t},"Core ",String(t).padEnd(10),e.model," @ ",e.speed," MHz")),G.createElement(Z,null,"\n","Network"),G.createElement(Z,null,"─".repeat(40)),Object.entries(n).map(([e,t])=>t?.filter(e=>"IPv4"===e.family&&!e.internal).map((t,n)=>G.createElement(Z,{key:`${e}-${n}`},e.padEnd(12),t.address))))),"PlainTextInfo"),eT=__name(({cpus:e,totalMem:t,networkInterfaces:n,verbose:r})=>G.createElement(X,{flexDirection:"column"},G.createElement(Yk,{cpuCount:e.length,totalMem:t}),r&&G.createElement(Jk,{cpus:e}),r&&G.createElement(Xk,{networkInterfaces:n})),"StyledInfo"),tT=__name(({verbose:e=!1,text:t=!1})=>{const{exit:n}=se();K(()=>{const e=setTimeout(()=>n(),50);return()=>clearTimeout(e)},[n]);const r=h.cpus(),s=h.networkInterfaces(),o=Math.round(h.totalmem()/1024/1024/1024);return t?G.createElement(Zk,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e}):G.createElement(eT,{cpus:r,totalMem:o,networkInterfaces:s,verbose:e})},"InfoUI"),nT={"iTerm.app":"iTerm2",Apple_Terminal:"Terminal",WezTerm:"WezTerm",Hyper:"Hyper",Alacritty:"Alacritty"},rT=__name((e,t)=>{const n=process.env[e];return!!n&&n.toLowerCase().includes(t)},"hasEnvContaining"),sT=__name(()=>{if(process.env.CURSOR_TRACE_ID)return"Cursor";if(rT("__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"),oT=__name(()=>{const e=sT();if(e)return e;const t=process.env.TERM_PROGRAM;return t&&nT[t]?nT[t]:t||process.env.TERMINAL_EMULATOR||"Unknown"},"getTerminalName"),iT=__name(()=>{if("win32"===f.platform()){const e=process.env.COMSPEC;return e?a(e):process.env.SHELL?a(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=N(`ps -p ${e} -o comm=`,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(t){const e=a(t).replace(/^-/,"");if(e&&"node"!==e)return e}}}catch{}const e=process.env.SHELL;return e?a(e):"N/A"},"getShellName"),aT=__name(()=>{const e=sT();if(!e)return"N/A";const t=process.env.TERM_PROGRAM_VERSION;return t?`${e} ${t}`:e},"getIDEInfo"),lT=__name(()=>{try{const e=N("cmd --version",{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(e)return e}catch{}return"Unknown"},"getCommandCodeVersion");function getSystemInfo(){return{os:Gk(f.platform()),terminal:oT(),shell:iT(),version:lT(),ide:aT()}}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,rv("Usage: /rename [name]")]);const s=t.current?.getSessionManager();if(!s)return void n(e=>[...e,rv("No active session to rename")]);const o=s.getSessionId();await xv.isSessionNameTaken({name:r,excludeSessionId:o})?n(e=>[...e,lv(`A session named "${r}" already exists. Choose a different name.`)]):await s.saveSessionTitle(r)?n(e=>[...e,rv(`Session renamed to "${r}"`)]):n(e=>[...e,lv("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,rv("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();AC(),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,rv(a)]),r(!1),n("Ready..."),s({current:e.current.getContextTokensUsed()||0,limit:MS})}catch(e){const s=`Failed to compact conversation: ${e instanceof Error?e.message:"Unknown error"}`;t(e=>[...e,lv(s)]),r(!1),n("Ready...")}else t(e=>[...e,rv("No active conversation to compact.")])}function handleRewindCommand({contextEngineRef:e,setFeed:t,setShowRewindSelector:n}){e.current?e.current.hasCheckpoints()?n(!0):t(e=>[...e,rv("No checkpoints available. Start sending messages to create checkpoints.")]):t(e=>[...e,rv("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)),AC(),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,rv(d)]),void s("Ready...")}r(e=>[...e,lv(`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,lv(t)]),s("Ready...")}}function handleRewindCancel({setShowRewindSelector:e}){e(!1)}async function handleLoginCommand({setFeed:e,setShowLoginOverlay:t}){const n=Lt();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,rv(`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,lv(t)]),void s("Ready...");r(e=>[...e,rv(t)]),o.current&&o.current.refreshRequest(),s("Ready...")}function handleLoginCancel({setShowLoginOverlay:e,setFeed:t,setStatus:n}){e(!1),t(e=>[...e,rv("Authentication cancelled.")]),n("Ready...")}async function handleLogoutCommand({setFeed:e,contextEngineRef:t}){const n=await performLogout();if(!n.success)return void e(e=>[...e,lv(`Logout failed: ${n.error}`)]);if(t.current&&t.current.refreshRequest(),!n.wasAuthenticated)return void e(e=>[...e,rv("Not currently authenticated.")]);const r=n.warnings.length>0?`Successfully logged out from Command Code. Warnings: ${n.warnings.join(", ")}`:"Successfully logged out from Command Code.";e(e=>[...e,rv(r)])}__name(getSystemInfo,"getSystemInfo"),__name(buildGitHubIssueUrl,"buildGitHubIssueUrl"),Ms(),Ft(),__name(parsePositionalArguments,"parsePositionalArguments"),__name(parseCommandInput,"parseCommandInput"),__name(processCommandTemplate,"processCommandTemplate"),NC(),Ft(),Tv(),Lv(),__name(handleRenameCommand,"handleRenameCommand"),Ft(),Tv(),NC(),BS(),__name(handleCompactCommand,"handleCompactCommand"),Ft(),Tv(),NC(),__name(handleRewindCommand,"handleRewindCommand"),__name(handleRewindSelect,"handleRewindSelect"),__name(handleRewindCancel,"handleRewindCancel"),Ft(),Tv(),po(),Ss(),Xs(),zt(),__name(handleLoginCommand,"handleLoginCommand"),__name(handleLoginComplete,"handleLoginComplete"),__name(handleLoginCancel,"handleLoginCancel"),__name(handleLogoutCommand,"handleLogoutCommand"),Ft(),Qb(),Cn(),Sr();var cT=Je(I);function getVsixPath(){try{const e=t.dirname(u(import.meta.url)),n=t.join(e,"..","vsix","commandcode-vscode.vsix");return S.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),Fb.isAvailable(500)]);return{...t,connected:n}}async function checkInstalled(e){try{const{stdout:t}=await cT(`${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 cT(`${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 uT={code:"VS Code",cursor:"Cursor",windsurf:"Windsurf"};async function ensureExtensionInstalled(){if(process.env.CI)return;const e=Rb();e&&await isAutoInstallEnabled()&&((await getExtensionStatus(e)).installed||installExtensionAsync(e))}function formatSetupResult(e){const t={connected:ie.green("✔"),installed:ie.green("✔"),needs_reload:ie.yellow("◌"),failed:ie.red("✖"),not_in_ide:ie.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=>ie.dim(` ${e}`)),""]}async function runIDESetup(){const e=Rb(),t=e?uT[e]||e:null;if(!e)return{status:"not_in_ide",ide:null,details:["Run Command Code from IDE's integrated terminal."]};const n=new Fb,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(()=>(Tv(),kv));e(e=>[...e,t("KEYBOARD SHORTCUTS\nCOMMANDS")])}async function handleTerminalSetupCommand({setFeed:e}){const t=nv(`/${At.TERMINAL_SETUP}`),n=setupVSCodeTerminal(),r=uv(n.message,!n.success,n.details);e(e=>[...e,t,r])}async function handleIDESetupCommand({setFeed:e}){const t=await runIDESetup(),n=dv(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([]),AC(),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(()=>(IC(),PC));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,rv(n)])}catch(t){const n=`Error: Failed to initialize AGENTS.md: ${t instanceof Error?t.message:"Unknown error"}`;e(e=>[...e,rv(n)])}}async function handleFeedbackCommand({setFeed:e},t){const n=buildGitHubIssueUrl(t);try{await ue(n,{wait:!1,background:!0}),e(e=>[...e,rv(`Opened ${createOSC8Link(n,"GitHub issue")} in your browser`)])}catch{const{createSystemEntry:t,createErrorEntry:r}=await Promise.resolve().then(()=>(Tv(),kv));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=cv();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(zk.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}),{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("/review"===r){const e=s.trim(),{handleSubmit:n}=await Promise.resolve().then(()=>(DC(),$C));let r=e,o=!1;if(!e){const e=await Sk();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(()=>(DC(),$C));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 p=Y(()=>({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,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,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]),g=V(p);return g.current=p,{commandCtx:p,onCommand:J(e=>handleCommand(e,g.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(Nt).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),AC(),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"),DC(),__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"),Ft(),Ft(),vr(),Sr(),__name(handleProviderSelect,"handleProviderSelect"),__name(handleProviderCancel,"handleProviderCancel"),__name(handleAuthSuccess,"handleAuthSuccess"),__name(handleAuthCancel,"handleAuthCancel"),Ft(),zt(),Sr(),NC(),__name(getModelDisplayName,"getModelDisplayName"),__name(handleModelSelect,"handleModelSelect"),__name(handleModelCancel,"handleModelCancel"),Ft(),Sr();var dT={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: ${dT[e]}`)}catch{n("Failed to set compact mode"),t(!1)}}function handleCompactModeCancel({setShowCompactModeSelector:e}){e(!1)}__name(handleCompactModeSelect,"handleCompactModeSelect"),__name(handleCompactModeCancel,"handleCompactModeCancel");var mT=__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=V({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:J(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:J(()=>{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:J(({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:J(()=>{handleRewindCancel({setShowRewindSelector:u.current.uiOverlays.setShowRewindSelector})},[]),onLoginComplete:J((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:J(()=>{const{feedState:e,statusState:t,uiOverlays:n}=u.current;handleLoginCancel({setShowLoginOverlay:n.setShowLoginOverlay,setFeed:e.setFeed,setStatus:t.setStatus})},[]),handleProviderSelect:J(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:J(()=>{handleProviderCancel({setShowProviderSelector:u.current.uiOverlays.setShowProviderSelector})},[]),handleModelSelect:J(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:mT})},[]),handleModelCancel:J(()=>{handleModelCancel({setShowModelSelector:u.current.uiOverlays.setShowModelSelector})},[]),handleCompactModeSelect:J(e=>{const{statusState:t,uiOverlays:n}=u.current;handleCompactModeSelect({mode:e,setShowCompactModeSelector:n.setShowCompactModeSelector,setStatus:t.setStatus})},[]),handleCompactModeCancel:J(()=>{handleCompactModeCancel({setShowCompactModeSelector:u.current.uiOverlays.setShowCompactModeSelector})},[]),handleAuthSuccess:J(()=>{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:J(()=>{handleAuthCancel({setAuthComponentInfo:u.current.authState.setAuthComponentInfo})},[])}}__name(useMainActionCallbacks,"useMainActionCallbacks"),Ft(),Ft(),Ft();var pT=__name(({staticKey:e})=>G.createElement(ee,{items:[{staticKey:e}],key:e},()=>G.createElement(Z,{key:e},"\0")),"Responsive");Ft(),zt(),rr();var gT=__name(({onTrust:e,onExit:t})=>{const{exit:n}=se(),[r,s]=Q(1),o=process.cwd().replace(process.env.HOME||"","~");return ne((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())}),G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.YELLOW,padding:1},G.createElement(Z,{color:$n.YELLOW,bold:!0},"Do you trust the files in this folder?"),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY},o)),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(Z,null,"Command Code may read files in this folder. Reading untrusted files may lead Command Code to behave in unexpected ways."),G.createElement(X,{marginTop:1},G.createElement(Z,null,"With your permission Command Code may execute files in this folder. Executing untrusted code is unsafe."))),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{color:1===r?$n.CYAN:$n.GRAY},1===r?ve.pointer:" "," 1. Yes, proceed")),G.createElement(X,null,G.createElement(Z,{color:2===r?$n.CYAN:$n.GRAY},2===r?ve.pointer:" "," 2. No, exit"))))},"TrustPrompt"),hT=H(__name(function TrustView2({staticKey:e,onTrust:t,onExit:n}){return G.createElement(G.Fragment,null,G.createElement(pT,{staticKey:e}),G.createElement(gT,{onTrust:t,onExit:n}))},"TrustView"));Ft(),Ft(),Lv(),os(),rr();var fT=__name(({onSelectSession:e,onNewSession:t})=>{const{exit:n}=se(),[r,s]=Q([]),[o,i]=Q(0),[a,l]=Q(!0),[u,d]=Q(0),m=30;K(()=>{p()},[]);const p=__name(async()=>{l(!0);const e=await xv.listSessions();s(e),l(!1)},"loadSessions");if(ne((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 G.createElement(X,{flexDirection:"column",paddingLeft:2,paddingTop:1},G.createElement(Z,{color:$n.GRAY},"Loading sessions..."));const g=__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"),h=__name(e=>truncateString({text:e,maxChars:Kr}),"truncateMessage");if(0===r.length)return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.GRAY},"No sessions available"));const f=r.slice(u,u+m),y=u;return G.createElement(X,{flexDirection:"column",paddingLeft:1,width:"100%"},r.length>m&&G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"Showing ",u+1,"-",Math.min(u+m,r.length)," ","of ",r.length," sessions",u>0&&" (↑ for more)",u+m<r.length&&" (↓ for more)")),G.createElement(X,{columnGap:2,marginBottom:1},G.createElement(X,{width:7},G.createElement(Z,{color:$n.GRAY}," ")),G.createElement(X,{width:13},G.createElement(Z,{color:$n.GRAY},"Modified")),G.createElement(X,{width:11},G.createElement(Z,{color:$n.GRAY},"# Messages")),G.createElement(X,{width:20},G.createElement(Z,{color:$n.GRAY},"Git Branch")),G.createElement(X,null,G.createElement(Z,{color:$n.GRAY},"Summary"))),G.createElement(X,{columnGap:2},G.createElement(X,{flexDirection:"column",width:7},f.map((e,t)=>{const n=y+t;return G.createElement(Z,{key:`sel-${n}`,color:o===n?$n.CYAN:$n.GRAY},o===n?`${ve.pointer} ${n+1}.`:` ${n+1}.`)})),G.createElement(X,{flexDirection:"column",width:13},f.map((e,t)=>{const n=y+t;return G.createElement(Z,{key:`mod-${e.id}`,color:o===n?$n.WHITE:$n.GRAY},g(e.lastModified))})),G.createElement(X,{flexDirection:"column",width:11},f.map((e,t)=>{const n=y+t;return G.createElement(Z,{key:`msg-${e.id}`,color:o===n?$n.WHITE:$n.GRAY},e.messageCount)})),G.createElement(X,{flexDirection:"column",width:20},f.map((e,t)=>{const n=y+t;return G.createElement(Z,{key:`branch-${e.id}`,color:o===n?$n.WHITE:$n.GRAY,wrap:"truncate-end"},e.gitBranch||"-")})),G.createElement(X,{flexDirection:"column"},f.map((e,t)=>{const n=y+t;return G.createElement(Z,{key:`summary-${e.id}`,color:o===n?$n.WHITE:$n.GRAY},h(e.firstMessage))}))))},"SessionTable"),yT=H(__name(function SessionView2({onSelectSession:e,onNewSession:t}){return G.createElement(fT,{onSelectSession:e,onNewSession:t})},"SessionView"));Ft(),Ft(),ar(),rr();var wT=__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"),ST=__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=ve.bullet,d=$n.CYAN):l?(u=ve.tick,d=$n.GREEN):(u=ve.circle,d=$n.GRAY),o.push(G.createElement(Z,{key:i},G.createElement(Z,{color:d},u),G.createElement(Z,{color:a?$n.CYAN:void 0}," ",s.header),i<e.length-1?G.createElement(Z,{color:$n.DIM}," | "):null))}),!s){const e=r;o.push(G.createElement(Z,{key:"review"},G.createElement(Z,{color:$n.DIM}," | "),G.createElement(Z,{color:e?$n.CYAN:$n.GRAY},e?ve.bullet:ve.circle),G.createElement(Z,{color:e?$n.CYAN:void 0,bold:e}," ","Review")))}return G.createElement(X,null,o)},"TabIndicator"),bT=__name(({questions:e,onResponse:t,hideCustomInput:n=!1})=>{const[r,s]=Q(0),[o,i]=Q(new Map),a=V(new Map),[l,u]=Q(""),[d,m]=Q(new Set),[p,g]=Q(null),[h,f]=Q(!1),[y,w]=Q(!1),[S,E]=Q(!1),[v,C]=Q(null),[k,T]=Q(!1),_=e[r],x=_?.multiSelect??!1,P=o.get(r),A=_?[..._.options.map((e,t)=>({label:e.label,value:`option_${t}`,description:e.description}))]:[],I=A.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),N=new Map(I.map((e,t)=>[e.label,A[t]])),R=__name(e=>{"submit"===e.value?q():"cancel"===e.value&&t({answers:[]})},"handleReviewSelect"),$=__name(()=>{if(!P||0===P.length)return 0;const e=P[0],t=_.options.findIndex(t=>t.label===e);return t>=0?t:0},"getInitialIndex"),M=__name(e=>{if(!h)if(x){const t=wT(e.value,_.options.length-1);if(null===t)return;const n=_.options[t]?.label||"";m(e=>{const t=new Set(e);return t.has(n)?t.delete(n):t.add(n),t})}else{const t=wT(e.value,_.options.length-1);if(null===t)return;f(!0);const n=_.options[t]?.label||"";O([n])}},"handleSelect"),D=__name(()=>{if(h)return;f(!0);const e=Array.from(d);O(e)},"handleMultiSelectDone"),L=__name(()=>{if(!h&&l.trim())if(x){const e=new Set(_.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 f(!0),O([l.trim()])},"handleOtherSubmit"),O=__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),f(!1),E(!1),C(null),T(!1)}else if(e.every((e,t)=>o.has(t))){if(n&&1===e.length)return void q();m(new Set),u(""),w(!0),f(!1)}else{const t=e.findIndex((e,t)=>!o.has(t));-1!==t&&(l(t),s(t)),f(!1),E(!1),C(null),T(!1)}},"finishQuestion"),q=__name(()=>{const n=e.map((e,t)=>({questionIndex:t,selectedOptions:a.current.get(t)||[]}));t({answers:n})},"submitAnswers"),F=__name(t=>{w(!1),s(t),T(!1),E(!1),C(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"),j=__name(t=>{if(t<0||t>=e.length)return;x&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),f(!1),E(!1),C(null),T(!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"),B=__name(()=>{if(!p||!x)return;if("done"===p.value)return;const e=wT(p.value,_.options.length-1);if(null===e)return;const t=_.options[e]?.label||"";m(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})},"toggleMultiSelection");return ne((t,s)=>{if(" "===t&&x&&!S&&B(),"d"!==t||!x||S||y||D(),!y&&!h){if(s.downArrow&&!S&&!k&&!n&&p&&I.length>0&&p.value===I[I.length-1]?.value&&E(!0),s.upArrow&&!S&&!k&&p&&I.length>0&&p.value===I[0]?.value&&(x?T(!0):n||(E(!0),C(I.length-1))),s.upArrow&&S){E(!1),C(I.length-1);const e=I[I.length-1];e&&g(e)}if(s.downArrow&&S)if(E(!1),x)T(!0);else{C(0);const e=I[0];e&&g(e)}if(s.upArrow&&k&&(T(!1),E(!0)),s.downArrow&&k){T(!1),C(0);const e=I[0];e&&g(e)}s.return&&k&&x&&D()}if(h||S||k||(y?s.leftArrow&&F(e.length-1):s.leftArrow&&r>0?j(r-1):s.rightArrow&&(r<e.length-1?j(r+1):(x&&(d.size>0?a.current.set(r,Array.from(d)):a.current.delete(r),i(new Map(a.current))),w(!0)))),s.escape&&!h)if(y)w(!1);else if(S){E(!1);const e=v??I.length-1;C(e);const t=I[e];t&&g(t)}else if(k){T(!1);const e=I[I.length-1];e&&g(e)}}),_||y?y?G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},G.createElement(X,{marginBottom:1},G.createElement(ST,{questions:e,currentIndex:e.length,answeredQuestions:new Set(o.keys()),isReviewPage:!0})),e.map((e,t)=>G.createElement(X,{key:t,marginBottom:1,flexDirection:"column"},G.createElement(Z,{color:$n.DIM},t+1,". ",e.question),G.createElement(Z,{color:$n.GREEN}," ",o.get(t)?.join(", ")||"No answer"))),G.createElement(et,{items:[{label:" 1. Submit",value:"submit"},{label:" 2. Cancel",value:"cancel"}],onSelect:R,initialIndex:0,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.CYAN},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>G.createElement(Z,{color:t?$n.CYAN:$n.WHITE},e)}),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},ve.arrowLeft," to go back and edit"))):G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.GRAY,borderTop:!0,borderBottom:!1,borderLeft:!1,borderRight:!1,width:"100%"},G.createElement(X,{marginBottom:1},G.createElement(ST,{questions:e,currentIndex:r,answeredQuestions:new Set(o.keys()),isReviewPage:!1,hideReview:n})),G.createElement(X,{marginBottom:1},G.createElement(Z,{bold:!0},_.question)),S||k?G.createElement(X,{flexDirection:"column"},I.map((e,t)=>{const n=N.get(e.label),r=x&&n&&d.has(n.label),s=!x&&n&&P?.includes(n.label),o=r||s;return G.createElement(X,{key:t,flexDirection:"column"},G.createElement(X,null,G.createElement(Z,null," "),G.createElement(Z,{color:o?$n.GREEN:$n.WHITE}," ",t+1,"."," "),x&&(o?G.createElement(Z,{color:$n.GREEN},"[",ve.tick,"]"," "):G.createElement(Z,{color:$n.DIM},"[ ] ")),G.createElement(Z,{color:o?$n.GREEN:$n.WHITE},n?.label||""),!x&&o&&G.createElement(Z,{color:$n.GREEN}," ",ve.tick)),n?.description&&G.createElement(X,null,G.createElement(Z,null," "),G.createElement(Z,{color:$n.DIM},x?" ":" ",n.description)))})):G.createElement(et,{key:`${r}-${v??"default"}`,items:I,initialIndex:v??$(),onSelect:M,onHighlight:g,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.CYAN},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>{const n=N.get(e),r=x&&n&&d.has(n.label),s=!x&&n&&P?.includes(n.label),o=r||s,i=e.match(/^\s*(\d+)\.\s*(.*)$/),a=i?.[1]||"",l=i?.[2]||e;return G.createElement(X,{flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{color:t?$n.CYAN:o?$n.GREEN:$n.WHITE}," ",a,"."," "),x&&(o?G.createElement(Z,{color:$n.GREEN},"[",ve.tick,"]"," "):G.createElement(Z,{color:$n.DIM},"[ ] ")),G.createElement(Z,{color:t?$n.CYAN:o?$n.GREEN:$n.WHITE},l),!x&&o&&G.createElement(Z,{color:$n.GREEN}," ",ve.tick)),n?.description&&G.createElement(Z,{color:$n.DIM},x?" ":" ",n.description))}}),!n&&G.createElement(X,null,G.createElement(Z,{color:$n.CYAN},S?ve.pointer:" "),G.createElement(Z,{color:S?$n.CYAN:void 0}," ",I.length+1,"."," "),x&&(d.has(l.trim())?G.createElement(Z,{color:$n.GREEN},"[",ve.tick,"] "):G.createElement(Z,{color:$n.DIM},"[ ] ")),G.createElement(TextInput,{value:l,onChange:e=>{const t=e.replace(/\r\n/g," ").replace(/[\r\n]/g," "),n=l.trim();u(t),x&&m(e=>{const r=new Set(e);return n&&r.has(n)&&r.delete(n),t.trim()&&r.add(t.trim()),r})},onSubmit:L,placeholder:"Type something...",focus:S,stripBracketedPaste:!0})),x&&G.createElement(X,null,G.createElement(Z,{color:$n.CYAN},k?ve.pointer:" "),G.createElement(Z,{color:k?$n.CYAN:void 0,bold:k}," ",r===e.length-1?"Submit":"Next")),e.length>1&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.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 G.createElement(X,{marginY:1},G.createElement(bT,{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"),AC(),s(e=>e+1)):e.startsWith("Yes, exit")&&(t("standard"),AC(),s(e=>e+1))}if(e.params.enterPlanMode){const e=o.answers[0]?.selectedOptions[0];e?.startsWith("Yes")&&(t("plan"),AC(),s(e=>e+1))}e.resolve(o),n(null),r("Answers submitted")}}))}NC(),__name(QuestionView,"QuestionView"),Ft(),Ft(),zt(),uC(),Ft(),rr();var ET=/\[([^\]]+)\]/g;function BracketWrap({children:e,color:t,bold:n=!1}){return G.createElement(G.Fragment,null,G.createElement(Z,{color:$n.DIMMEST,bold:n},"["),"string"==typeof e?G.createElement(Z,{color:t,bold:n},e):e,G.createElement(Z,{color:$n.DIMMEST,bold:n},"]"))}function BracketedText({text:e,color:t,bold:n=!1,wrap:r}){const s=Y(()=>{const t=[];let n=0;for(const r of e.matchAll(ET)){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=Y(()=>s.map((e,r)=>"bracket"===e.type?G.createElement(BracketWrap,{key:`bracket-${r}`,color:t,bold:n},e.value):e.value),[s,t,n]);return G.createElement(Z,{color:t,bold:n,wrap:r},o)}__name(BracketWrap,"BracketWrap"),__name(BracketedText,"BracketedText"),rr(),Ft(),Uw(),Tv(),an(),os(),Cr(),rr(),Ft(),rr();var vT=class extends rt{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"+ie.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}},CT=new nt;CT.setOptions({renderer:new vT({strong:ie.bold,em:ie.italic,del:ie.dim.strikethrough,codespan:ie.hex(Jn.CODE),code:ie.hex(Jn.CODE),heading:ie.bold,firstHeading:ie.bold.hex(Jn.HEADING).underline,link:ie.hex($n.CYAN),href:ie.hex($n.CYAN).underline,blockquote:ie.hex($n.GRAY).italic,table:ie.reset,tableOptions:{style:{head:[$n.CYAN],border:[$n.GRAY]}},hr:ie.reset,paragraph:ie.reset,html:ie.hex($n.GRAY),showSectionPrefix:!1,unescape:!0,emoji:!0,tab:2}),breaks:!0,gfm:!0});var kT=/\u001b\]8;;([^\u0007]*)\u0007([^\u001b]*)\u001b\]8;;\u0007/g;function Markdown({children:e,color:t,dimColor:n,wrap:r}){const s=Y(()=>{if(!e)return"";const t=[],n=e.replace(kT,e=>{const n=t.length;return t.push(e),`{{OSC8:${n}}}`});try{const r=CT.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 G.createElement(Z,{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?"│":dk).join("\n")}__name(Markdown,"Markdown"),Ft(),__name(buildTreeConnectors,"buildTreeConnectors");var TT=" │ ";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?qn.REMOVED_HIGHLIGHT_BG:qn.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(G.createElement(Z,{key:l,backgroundColor:r,dimColor:n},a)):s.push(G.createElement(Z,{key:l,color:$n.WHITE,dimColor:n},a))}return s}function renderContextLine({line:e,lineNum:t,lineNumWidth:n,dimDiff:r,nodeKey:s}){return G.createElement(X,{key:s,width:"100%"},G.createElement(Z,{color:qn.LINE_NUM,dimColor:r}," "+t.toString().padStart(n)),G.createElement(Z,{color:qn.LINE_NUM,dimColor:r},TT),G.createElement(Z,{color:$n.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(G.createElement(X,{key:"sep-"+o.nodeKey++},G.createElement(Z,{color:qn.LINE_NUM,dimColor:s}," ".repeat(r+1)),G.createElement(Z,{color:qn.LINE_NUM,dimColor:s},TT),G.createElement(Z,{color:qn.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=tt.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 p=u.reduce((e,t)=>e+(t.added?0:t.count||1),0),g=u.reduce((e,t)=>e+(t.removed?0:t.count||1),0),h=Math.max(3,(i+p-1).toString().length,(i+g-1).toString().length),f=groupAdjacentChanges(u),y=[],w={oldLineNum:i,newLineNum:i,nodeKey:0};for(let e=0;e<f.length;e++){const t=f[e];if("context"===t.type){const n=t.contextLines,r=e>0&&"change"===f[e-1].type,s=e<f.length-1&&"change"===f[e+1].type;if(!r&&!s){w.oldLineNum+=n.length,w.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;y.push(...renderContextGroup({lines:n,leadCount:o,trailCount:i,lineNumWidth:h,dimDiff:a,counters:w}));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=tt.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);y.push(G.createElement(X,{key:"rm-"+w.nodeKey++,width:"100%",backgroundColor:qn.REMOVED_BG},G.createElement(Z,{color:qn.REMOVED_TEXT,dimColor:a}," "+w.oldLineNum.toString().padStart(h)),G.createElement(Z,{color:qn.LINE_NUM,dimColor:a},TT),G.createElement(Z,{color:qn.REMOVED_TEXT,dimColor:a},"- "),t?renderWordSegments({wordChanges:t,type:"removed",dimDiff:a}):G.createElement(Z,{color:qn.REMOVED_TEXT,dimColor:a},n[e].replace(/\s/g," ")))),w.oldLineNum++}for(let e=0;e<r.length;e++){const t=i.get(e);y.push(G.createElement(X,{key:"add-"+w.nodeKey++,width:"100%",backgroundColor:qn.ADDED_BG},G.createElement(Z,{color:qn.ADDED_TEXT,dimColor:a}," "+w.newLineNum.toString().padStart(h)),G.createElement(Z,{color:qn.LINE_NUM,dimColor:a},TT),G.createElement(Z,{color:qn.ADDED_TEXT,dimColor:a},"+ "),t?renderWordSegments({wordChanges:t,type:"added",dimDiff:a}):G.createElement(Z,{color:qn.ADDED_TEXT,dimColor:a},r[e].replace(/\s/g," ")))),w.newLineNum++}}const S=void 0!==l&&y.length>l,E=S?y.slice(0,l):y;return{diffContent:G.createElement(X,{flexDirection:"column"},s&&!r&&(d>0||m>0)&&G.createElement(Z,{color:$n.GRAY},"Updated"," ",G.createElement(Z,{color:$n.WHITE,bold:!0},n)," ","with"," ",d>0&&G.createElement(G.Fragment,null,G.createElement(Z,{color:zn.SUCCESS},d)," ","addition",1!==d?"s":"",m>0?" and ":""),m>0&&G.createElement(G.Fragment,null,G.createElement(Z,{color:zn.ERROR},m)," ","removal",1!==m?"s":"")),r&&G.createElement(Z,{color:$n.RED},"Rejected update to",G.createElement(Z,{color:$n.RED},` ${n}`)),G.createElement(X,{flexDirection:"column",marginLeft:o,marginRight:o+4,width:(process.stdout.columns||80)-2*o-8},E)),isTruncated:S,totalLines:y.length}}function formatTodosForDisplay(e){const t=vv(e);return t?G.createElement(X,{flexDirection:"column"},t.map((e,t)=>{const n="completed"===e.status?ve.checkboxOn:ve.checkboxOff;let r,s=!1;switch(e.status){case"completed":r=zn.SUCCESS,s=!0;break;case"in_progress":r=zn.IN_PROGRESS;break;default:r=$n.WHITE}return G.createElement(X,{key:e.id||t,flexDirection:"row"},G.createElement(X,{width:2},G.createElement(Z,{color:r},n)),G.createElement(Z,{color:r,bold:"in_progress"===e.status,strikethrough:s},e.content))})):G.createElement(Z,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 G.createElement(BracketWrap,null,t?e:G.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?G.createElement(Z,{dimColor:!0}," ",e.dimText):null}function resolveSymbol({isPending:e,hasError:t,isThinking:n,isTodos:r,output:s}){if(e)return{symbolColor:$n.YELLOW,symbol:ve.arrowRight};if(t)return{symbolColor:$n.RED,symbol:ve.square};if(n)return{symbolColor:Ln,symbol:"✻"};if(r&&s){const e=vv(s),t=e?.every(e=>"completed"===e.status);return{symbolColor:t?zn.SUCCESS:zn.WARNING,symbol:ve.square}}return{symbolColor:Fn.BG,symbol:ve.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 G.createElement(G.Fragment,null,G.createElement(Z,{color:Ln},`Thought for ${e} second${1!==e?"s":""}`," "),!o&&G.createElement(BracketWrap,{color:$n.DIM},`${i}+o to expand`))}if(t)return G.createElement(G.Fragment,null,G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:Dn.BADGE_BG,color:Dn.BADGE_FG,bold:!0},pk)),G.createElement(Z,null," ","Using your taste"," ",n?"package of ":"packages",n&&G.createElement(Z,{bold:!0},n)));let l=r;return"READ[n]"===r&&s&&(l=`READ[${Number(s[1])}]`),G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:Fn.BG,color:Fn.FG,bold:!0},`${mk}${l}${mk}`))}function renderAgentStatus({agentStatus:e,hasError:t,output:n,elapsedSeconds:r,tokensUsed:s}){const o=`${formatTime2(r)} | ${formatTokens(s)}`;return"running"===e?G.createElement(Z,{color:$n.GRAY},"Running (",o,")"):"interrupted"===e||"Interrupted by user"===n?G.createElement(Z,{color:$n.RED,wrap:"wrap"},"Interrupted by user"):"error"===e||t?G.createElement(Z,{color:$n.RED,wrap:"wrap"},n," (",o,")"):G.createElement(G.Fragment,null,G.createElement(Z,{wrap:"wrap"},"Done"),G.createElement(Z,{color:$n.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?zr:Br,maxChars:"Question"===t?1/0:Vr}),l=i&&"Question"!==t;return{text:o,isTruncated:l,remainingLines:a,truncationMsg:l?a>0?G.createElement(BracketedText,{text:`... +${a} lines [${r}+o to expand]`,color:$n.DIM}):G.createElement(BracketedText,{text:`... [${r}+o to expand]`,color:$n.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?G.createElement(G.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:Ur,{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 G.createElement(X,{flexDirection:"column"},a,l&&G.createElement(X,{marginTop:1},G.createElement(BracketedText,{text:`… (${u-Ur} more lines) [${o}+o to expand]`,color:$n.DIM})),r&&s&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.RED,wrap:"wrap"},s)))}function renderWriteFileContent({input:e,metadata:t,expandedOutput:n,expandKey:r}){const s=t.content;if(!s)return G.createElement(Z,{color:$n.GRAY},"Created"," ",G.createElement(Z,{color:$n.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:Wr,l=void 0!==a&&i>a,u=l?o.slice(0,a):o,d=String(i).length;return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.GRAY},"Created"," ",G.createElement(Z,{color:$n.WHITE,bold:!0},e)," ","(",i," line",1!==i?"s":"",")"),G.createElement(X,{marginTop:1,flexDirection:"column"},u.map((e,t)=>G.createElement(X,{key:t,width:"100%",backgroundColor:qn.ADDED_BG},G.createElement(Z,{color:qn.ADDED_TEXT}," "+String(t+1).padStart(d)),G.createElement(Z,{color:qn.LINE_NUM},TT),G.createElement(Z,{color:qn.ADDED_TEXT,wrap:"truncate-end"},e.replace(/\s/g," "))))),l&&void 0!==a&&G.createElement(X,{marginTop:1},G.createElement(BracketedText,{text:`… (${i-a} more lines) [${r}+o to expand]`,color:$n.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:p}){if(e)return formatTodosForDisplay(o);if(t)return i?G.createElement(X,{width:"100%",flexDirection:"column"},G.createElement(Z,null," "),G.createElement(Z,{color:Ln,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 p?G.createElement(X,{columnGap:1},G.createElement(Z,{color:er},dk," "),e):e}if(r&&s&&"content"in s){const e=renderWriteFileContent({input:l,metadata:s,expandedOutput:i,expandKey:m});return p?G.createElement(X,{columnGap:1},G.createElement(Z,{color:er},dk," "),e):e}return p?renderTextWithLongConnector({output:o,name:d,expandedOutput:i,expandKey:m,hasError:u}):G.createElement(X,{width:"100%"},G.createElement(Z,{color:u?$n.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?$n.RED:void 0,u=buildTreeConnectors(o,i);return G.createElement(X,{flexDirection:"column",width:"100%"},G.createElement(X,{columnGap:1,width:"100%"},G.createElement(Z,{color:er},u),G.createElement(X,{flexGrow:1,flexShrink:1,minWidth:0},G.createElement(Z,{color:l,wrap:"wrap"},o))),i&&G.createElement(X,{columnGap:1},G.createElement(Z,{color:er},dk," "),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("]"),p=!0===o?.isTasteFile,g=o?.tasteCategory,h=!0===o?.permissionDenied,f=!a&&!l&&!p,{name:y}=detectTerminal(),w="iTerm2"===y?"shift":"ctrl",S=!0===o?.isAgent,E=computeDisplayInput({input:t,isAgent:S,isShell:"SHELL"===e,expandedOutput:i}),v=!a&&E&&!p,C=o?.status,k=o?.tokensUsed||0,T="number"==typeof o?.elapsedSeconds?Math.floor(o.elapsedSeconds):0,_=m?parseReadSummaryLine(n):null,x=m?getReadToolInlineSummary({name:e,summaryMatch:_}):null,P=Boolean(n&&!p&&!S&&(!m||s)),{symbolColor:A,symbol:I}=resolveSymbol({isPending:r,hasError:s,isThinking:a,isTodos:l,output:n});return G.createElement(X,null,a&&G.createElement(Z,{color:A},I),G.createElement(X,{flexDirection:"column",marginLeft:a?1:0},G.createElement(X,null,renderToolHeader({isThinking:a,isTasteFile:p,tasteCategory:g,name:e,summaryMatch:_,expandedOutput:i,expandKey:w}),v&&G.createElement(Z,null," ",formatToolInput({input:E,isShell:"SHELL"===e})),renderReadToolInlineSummary(x)),S&&("running"===C||n)&&G.createElement(X,{columnGap:1,marginLeft:f?1:0},f&&G.createElement(Z,{color:er},dk," "),renderAgentStatus({agentStatus:C,hasError:s,output:n,elapsedSeconds:T,tokensUsed:k})),P&&G.createElement(X,{marginLeft:f?1:0},renderOutputContent({isTodos:l,isThinking:a,isEditFile:u,isWriteFile:d,metadata:o,output:n,expandedOutput:i,isPermissionDenied:h,input:t,hasError:s,name:e,expandKey:w,showTreeConnector:f})),r&&!S&&G.createElement(X,{columnGap:1,marginLeft:1},G.createElement(Z,{color:er},dk," "),G.createElement(Z,{color:$n.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]=Q(0),[o,i]=Q(1);K(()=>{"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 G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.GRAY,paddingX:1,width:"100%"},G.createElement(X,{marginBottom:1},G.createElement(Z,{bold:!0,color:$n.YELLOW},`${m()} ${"edit"===e.action?d():""}`)),"edit"===e.action&&e.oldContent&&e.newContent&&G.createElement(X,{marginBottom:1},generateDiff({oldValue:e.oldContent,newValue:e.newContent,filePath:d(),marginLeft:0,startLine:o}).diffContent),G.createElement(X,{marginBottom:1},G.createElement(Z,{bold:!0},"Do you want to ",u()," ",G.createElement(Z,{color:$n.CYAN},d()),"?")),G.createElement(et,{items:a.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:l,initialIndex:s,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.CYAN},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>G.createElement(Z,{color:t?$n.CYAN:$n.WHITE},e.includes("[shift+tab]")?G.createElement(G.Fragment,null,e.split("[shift+tab]")[0],G.createElement(BracketWrap,{color:t?$n.CYAN:$n.WHITE,bold:!0},"shift+tab")):e.includes("(")?G.createElement(G.Fragment,null,e.split("(")[0],G.createElement(Z,{color:$n.GRAY},"(",e.split("(")[1])):e)}))},"PermissionPrompt");Ft(),zt(),rr();var xT=__name(({request:e,onResponse:t,onToggleAutoAccept:n})=>{const[r]=Q(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 G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.GRAY,paddingX:1,width:"100%"},G.createElement(X,{marginBottom:1},G.createElement(Z,{bold:!0,color:$n.YELLOW},"Execute Shell Command")),G.createElement(X,{marginBottom:1},G.createElement(Z,{bold:!0,wrap:"wrap"},"Command Code needs to execute ",G.createElement(Z,{color:$n.CYAN},i()),".")),e.workingDirectory&&G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.GRAY},"Working directory: ",e.workingDirectory)),e.description&&G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM,italic:!0},e.description)),G.createElement(et,{items:s.map((e,t)=>({label:` ${t+1}. ${e.label}`,value:e.value})),onSelect:o,initialIndex:r,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.CYAN},e?ve.pointer:" "),itemComponent:({label:e,isSelected:t})=>G.createElement(Z,{color:t?$n.CYAN:$n.WHITE},e.includes("[shift+tab]")?G.createElement(G.Fragment,null,e.split("[shift+tab]")[0],G.createElement(BracketWrap,{color:t?$n.CYAN:$n.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 PT=H(__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 G.createElement(X,{marginY:1},G.createElement(xT,{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 G.createElement(X,{marginY:1},G.createElement(xT,{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 G.createElement(X,{marginY:1},G.createElement(_T,{request:u,onResponse:e=>handlePermissionResponse({...a,choice:e,allowedStatus:"File operation allowed",deniedStatus:"File operation denied"}),onToggleAutoAccept:i}))},"PermissionView"));Ft(),NC(),Ft(),Ft(),zt();var AT="\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░███████░███████░███████████░███████████░███████░████████░░░░████░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░███░░░░░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███░███░██░░███░███░███░███░███░███░███░███████░███░░███░███░███░░░░░\n░░░░░███████░███████░███░███░███░███░███░███░███░███░███░░███░███████░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n",IT="\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 NT=getMaxLineWidth(AT),RT=getMaxLineWidth(IT),$T=NT+1,MT=RT+1;function getTerminalWidth(){return process.stdout.columns||80}__name(getTerminalWidth,"getTerminalWidth");var DT=__name(e=>{const t=e??getTerminalWidth();return t>=$T?AT:t>=MT?IT:LT},"getResponsiveCommandLogo"),LT="⌘ CMD\n",OT="░█▀▀░█▀▄▀█░█▀▄░\n░█░░░█░▀░█░█░█░\n░▀▀▀░▀░░░▀░▀▀░░",qT=getMaxLineWidth(OT),FT=MT,jT=__name(e=>{const t=e??getTerminalWidth();return t>=$T?"full":t>=FT?"compact":"minimal"},"getHeaderLayout");gC(),Ft(),rr();var BT=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:s=0,titleColor:o=$n.GRAY,dividerChar:i="─",dividerColor:a=$n.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*s),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",p=r?` ${r}`:"",g=d.length+m.length+p.length,h=i.repeat(Math.max(0,u-g));return G.createElement(X,{paddingLeft:s,paddingRight:s,marginBottom:1,...l},(t||n)&&G.createElement(Z,{color:a},d),e&&G.createElement(Z,{color:o},m),G.createElement(Z,{color:a},h),r&&G.createElement(Z,{color:$n.DIM},p))},"Divider");NC(),rr(),Ft(),rr();var zT=[{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}],UT=__name(({onComplete:e,onExit:t})=>{const[n,r]=Q(0),[s,o]=Q(!1),i=n>=zT.length;return K(()=>{if(n>=zT.length)return;if(s)return;const e=zT[n],t=setTimeout(()=>{r(e=>Math.min(e+1,zT.length))},e.duration);return()=>clearTimeout(t)},[n,s]),ne((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,zT.length))}),G.createElement(X,{flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{bold:!0},"Meet Your Coding Taste")),G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"Command Code learns your coding style as you work.")),G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"Here's how your preferences evolve in real-time:")),G.createElement(X,{flexDirection:"column",marginY:1},zT.slice(0,n).map((e,t)=>"user"===e.type?G.createElement(X,{key:t},G.createElement(Z,null,ve.pointer," ",e.text)):G.createElement(X,{key:t,flexDirection:"column",marginBottom:1,marginLeft:1},G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"⎿ "),G.createElement(Z,{color:Dn.TEXT},e.text)),e.details&&G.createElement(X,{marginLeft:3},G.createElement(Z,{color:$n.DIM},"Saved(",e.details,")"))))),i?G.createElement(X,{flexDirection:"column",marginY:1},G.createElement(X,null,G.createElement(Z,{bold:!0,color:Dn.TEXT},"Demo Complete!")),G.createElement(X,null,G.createElement(Z,null,"Command Code will now use these preferences to generate")),G.createElement(X,null,G.createElement(Z,null,"better suggestions tailored to your coding style. The")),G.createElement(X,null,G.createElement(Z,null,"more you code, the smarter it gets.")),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press Enter to get started →"))):G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(s?" (paused)":""))))},"TasteDemoComponent"),WT=__name(({onClose:e,onExit:t})=>{const[n,r]=Q(mC.getEvents()),[s,o]=Q(0);ne((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),K(()=>{const e=__name(()=>{r(mC.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return mC.on("new-event",e),mC.on("cleared",t),()=>{mC.off("new-event",e),mC.off("cleared",t)}},[]),K(()=>{const e=__name(()=>{AC(),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=Y(()=>(process.stdout.rows??24)-1,[s]);return G.createElement(X,{flexDirection:"column",width:"100%",height:d,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(st,{name:"vice"},G.createElement(Z,null,DT()))),G.createElement(BT,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),G.createElement(X,{flexDirection:"column"},0===n.length?G.createElement(X,{flexDirection:"column"},G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(X,null,G.createElement(Z,null,"Start using Command Code and it will begin recording your coding taste.")),G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"Your preferences, patterns, and style will appear here in real-time."))),G.createElement(oe,{count:2}),G.createElement(BT,{title:"DEMO",titleColor:"white",subPrefix:!0}),G.createElement(UT,{onComplete:()=>{e()},onExit:t})):G.createElement(X,{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 G.createElement(X,{key:e.id,marginBottom:1},G.createElement(X,{flexDirection:"column"},G.createElement(X,null,G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:Dn.BADGE_BG,color:Dn.BADGE_FG,bold:!0},`${mk}${n}${mk}`)),o?G.createElement(Z,{color:$n.DIM}," ","(",o.fullPath,")"):e.details?G.createElement(Z,{color:$n.DIM}," ","(",e.details,")"):null),G.createElement(X,{marginLeft:1},G.createElement(Z,{color:$n.DIM},"⎿"," "),o?G.createElement(G.Fragment,null,G.createElement(Z,null," ",o.category," ","package ("),G.createElement(Z,{color:$n.DIM},o.oldPath),G.createElement(Z,null," ",ve.arrowRight," ",o.newPath),G.createElement(Z,null,")")):i?G.createElement(G.Fragment,null,G.createElement(Z,null," ",i.text," ","("),G.createElement(Z,{color:$n.DIM},"confidence:"," "),G.createElement(Z,{color:$n.DIM},i.oldPercent,"%"),G.createElement(Z,null," ",ve.arrowRight," "),G.createElement(Z,{color:i.diff>0?$n.GREEN:$n.RED},i.newPercent,"%"),G.createElement(Z,null,")")):G.createElement(G.Fragment,null,G.createElement(Z,null," ",r),s&&G.createElement(Z,{color:$n.DIM}," ","(",s,")")))))}return G.createElement(X,{key:e.id,marginBottom:1},G.createElement(Z,{color:$n.DIM},ve.pointerSmall," ",e.message))}))))},"LearningFeedFull");function LearningView({setShowLearningFeed:e,setStaticKey:t,onExit:n}){return G.createElement(WT,{onClose:()=>{AC(),e(!1),t(e=>e+1)},onExit:n})}__name(LearningView,"LearningView"),Ft(),rr(),Ft(),rr(),NC(),Sr();var GT=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,s]=Q(!1),[o,i]=Q(!0);K(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();s(e)}catch(e){}finally{i(!1)}},"loadSettings")()},[]),ne((t,n)=>{if(!n.return&&" "!==t)return n.escape?(AC(),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?G.createElement(X,{key:n,borderStyle:"single",borderColor:$n.BLUE,padding:1,flexDirection:"column"},G.createElement(Z,{color:$n.BLUE,bold:!0},"Taste Settings"),G.createElement(Z,{color:$n.DIM},"Loading configuration...")):G.createElement(X,{key:n,borderStyle:"single",borderColor:$n.GRAY,padding:1,flexDirection:"column"},G.createElement(Z,{bold:!0},"Taste Learning"),G.createElement(Z,{color:$n.DIM},"Configure taste learning preferences for this project"),G.createElement(X,{marginTop:1}),G.createElement(X,{justifyContent:"space-between"},G.createElement(Z,null,"Taste learning",G.createElement(Z,{color:$n.DIM}," - Learn from your interactions")),G.createElement(Z,{color:r?$n.GREEN:$n.GRAY},r?"enabled":"disabled")),G.createElement(X,{marginTop:1}),G.createElement(Z,{color:$n.DIM},"Taste data stored in .commandcode/taste/taste.md"),G.createElement(Z,{color:$n.DIM},"Enter/Space to toggle • Esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,setShowTasteConfig:t,loadTasteStatus:n}){return G.createElement(G.Fragment,null,G.createElement(pT,{staticKey:e}),G.createElement(X,{flexDirection:"column",width:"100%"},G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"Press Esc to return to conversation")),G.createElement(GT,{onClose:()=>t(!1),onSettingsChange:n,staticKey:e})))}__name(TasteConfigView,"TasteConfigView"),Ft(),Ft(),zt(),Ow(),NC(),rr();var HT=__name(e=>Math.ceil(e.length/4),"estimateTokens"),QT=__name(({onClose:e})=>{const[t,n]=Q([]),[r,s]=Q(!0),[o,i]=Q(null),[a,l]=Q(0);K(()=>{__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],p=__name(async t=>{try{await ot([{file:t.filePath,line:1}]),AC(),e()}catch(e){e instanceof Error&&e.message.includes("$EDITOR environment variable")?i(g()):i(e instanceof Error?e.message:"Failed to open skill in editor")}},"handleSelectSkill");ne((t,n)=>{if(n.escape)return AC(),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&&p(e)}});const g=__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?G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(Z,{color:Mn,bold:!0},"Agent Skills"),G.createElement(Z,{color:$n.DIM},"Loading skills...")):o?G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(Z,{color:$n.RED,bold:!0},"Agent Skills"),G.createElement(Z,{color:$n.DIM},o),G.createElement(X,{marginTop:1}),G.createElement(Z,{color:$n.DIM},"Press ",G.createElement(Z,{bold:!0},"Esc")," to close")):0===t.length?G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(Z,{color:Mn,bold:!0},"Agent Skills"),G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"No skills found")),G.createElement(Z,{color:$n.DIM},"Create skills in:"),G.createElement(Z,{color:$n.DIM}," ","~/",".commandcode","/","skills","/ (user)"),G.createElement(Z,{color:$n.DIM}," ",".commandcode","/","skills","/ (project)"),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press ",G.createElement(Z,{bold:!0},"Esc")," to close"))):G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(X,null,G.createElement(Z,{color:Mn,bold:!0},"Skills"," "),G.createElement(Z,{color:$n.DIM},m.length," skills")),u.length>0&&G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(X,null,G.createElement(Z,{color:Wn,bold:!0},"Project skills"," "),G.createElement(Z,{color:Wn},"(",".commandcode","/","skills",")")),u.map((e,t)=>{const n=a===t;return G.createElement(X,{key:e.value},G.createElement(Z,{color:n?$n.GREEN:$n.WHITE},e.label),G.createElement(Z,{color:$n.DIM}," · ~",HT(e.description)," description tokens"))})),d.length>0&&G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(X,null,G.createElement(Z,{color:Wn,bold:!0},"User skills"," "),G.createElement(Z,{color:Wn},"(~/",".commandcode","/","skills",")")),d.map((e,t)=>{const n=a===u.length+t;return G.createElement(X,{key:e.value},G.createElement(Z,{color:n?$n.GREEN:$n.WHITE},e.label),G.createElement(Z,{color:$n.DIM}," · ~",HT(e.description)," description tokens"))})),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(Z,{dimColor:!0},"Add skills: ",G.createElement(Z,{color:$n.CYAN},"cmd skills add ","<owner/repo>")),G.createElement(Z,{color:$n.DIM},"Press ",G.createElement(Z,{bold:!0},"Esc")," to close")))},"SkillsConfig");function SkillsConfigView({staticKey:e,setShowSkillsConfig:t}){return G.createElement(G.Fragment,null,G.createElement(pT,{staticKey:e}),G.createElement(X,{flexDirection:"column",width:"100%"},G.createElement(QT,{onClose:()=>t(!1),staticKey:e})))}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_use"===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:Dt.TIER_1_THRESHOLD,description:`Prune to last ${Dt.TIER_1_KEEP_COUNT} tool calls`},{tier:2,threshold:Dt.TIER_2_THRESHOLD,description:`Prune to last ${Dt.TIER_2_KEEP_COUNT} tool calls`},{tier:3,threshold:Dt.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:Dt.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 nC){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 rC){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=MS,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}),p=collectBuiltInTools(),g=collectMcpTools(),[h,f,y]=await Promise.all([collectSkillItems(),collectAgentItems(),collectMemoryItems()]),w=sumTokens(p),S=sumTokens(g),E=w+S+sumTokens(h)+sumTokens(f)+sumTokens(y),v=t>0,C=v?t:m+E,k=!v&&s.length>0,T=Math.min(C/n*100,100),_=Math.max(0,n-C),x=Math.max(0,C-m-E),P=[];if(C>0){m>0&&P.push({name:"Conversation",tokens:m,percentage:Math.round(m/C*100),detail:`${o.user+o.assistant} messages`}),x>0&&P.push({name:"System prompt",tokens:x,percentage:Math.round(x/C*100),detail:"identity, taste, skills"});const e=w+S;if(e>0){const t=p.length,n=g.length,r=n>0?`${t} built-in + ${n} MCP`:`${t} built-in`;P.push({name:"Tool schemas",tokens:e,percentage:Math.round(e/C*100),detail:r})}}P.sort((e,t)=>t.tokens-e.tokens);const A=s.length>0?s[0]?.meta.timestamp??null:null;return{tokensUsed:C,tokenLimit:n,percentage:T,tokensRemaining:_,isEstimated:k,model:r,breakdown:P,autoCompact:buildAutoCompactStatus({tokensUsed:C,tokenLimit:n}),stats:{messageCount:s.length,userMessages:o.user,assistantMessages:o.assistant,toolCalls:i.calls,toolResults:i.results,imageCount:a,compactionCount:d,sessionStartTime:A},compactions:l,tips:generateTips({percentage:T,conversationTokens:m,totalTokens:C,mcpToolCount:g.length,messageCount:s.length,imageCount:a})}}function useTerminalWidth(){const{stdout:e}=te(),[t,n]=Q(()=>e.columns??80);return K(()=>{const t=__name(()=>n(e.columns??80),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}function getLayoutSizes({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 getUsageColor(e){return e>=80?$n.RED:e>=50?$n.YELLOW:$n.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)}}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 G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(X,{marginBottom:0},G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:$n.BLUE,color:"#f4f4f4",bold:!0},`${mk}CONTEXT${mk}`)),G.createElement(Z,null," "),G.createElement(Z,{color:$n.GRAY},e.model)),G.createElement(X,null,G.createElement(Z,{color:n},r.filled),G.createElement(Z,{color:Wn},r.empty),G.createElement(Z,{bold:!0,color:n},` ${e.percentage.toFixed(1)}%`)),G.createElement(X,null,G.createElement(Z,null,formatTokens(e.tokensUsed)),G.createElement(Z,{color:$n.GRAY},` / ${formatTokens(e.tokenLimit)}`),G.createElement(Z,{color:$n.DIM}," · "),G.createElement(Z,{color:n},formatTokens(e.tokensRemaining)),G.createElement(Z,{color:$n.GRAY}," remaining"),e.isEstimated&&G.createElement(Z,{color:$n.DIM}," (estimated)")),G.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 G.createElement(X,null,G.createElement(Z,null,e.name.padEnd(n)),s&&G.createElement(G.Fragment,null,G.createElement(Z,{color:$n.CYAN},a),G.createElement(Z,{color:Wn},l)),G.createElement(Z,{bold:!0},` ${formatTokens(e.tokens)}`),G.createElement(Z,{color:$n.GRAY},` ${e.percentage}%`),o&&e.detail&&G.createElement(Z,{color:$n.DIM},` ${e.detail}`))}function ContextBreakdown({analysis:e,labelWidth:t,breakdownBarWidth:n,showBreakdownBars:r,showBreakdownDetail:s}){return 0===e.breakdown.length?null:G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{color:Wn,bold:!0},"Breakdown"),e.breakdown.map(o=>G.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?$n.RED:n<=25?$n.YELLOW:$n.GRAY;return G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"Full summarization"),G.createElement(Z,{color:r},` ${n}% away`))}function ContextSession({analysis:e,labelWidth:t}){return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Wn,bold:!0},"Session"),G.createElement(X,null,G.createElement(Z,null,"Messages".padEnd(t)),G.createElement(Z,{color:$n.GRAY},`${e.stats.messageCount} (${e.stats.userMessages} user, ${e.stats.assistantMessages} assistant)`)),G.createElement(X,null,G.createElement(Z,null,"Tool calls".padEnd(t)),G.createElement(Z,{color:$n.GRAY},`${e.stats.toolCalls} calls · ${e.stats.toolResults} results`)),e.stats.imageCount>0&&G.createElement(X,null,G.createElement(Z,null,"Images".padEnd(t)),G.createElement(Z,{color:$n.GRAY},`${e.stats.imageCount}`)),G.createElement(X,null,G.createElement(Z,null,"Duration".padEnd(t)),G.createElement(Z,{color:$n.GRAY},formatDuration(e.stats.sessionStartTime))))}function ContextTips({tips:e}){return 0===e.length?null:G.createElement(X,{flexDirection:"column"},e.map(e=>G.createElement(X,{key:e},G.createElement(Z,{color:$n.CYAN},ve.pointer),G.createElement(Z,{color:$n.GRAY}," ",e))))}function ContextHints(){return G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(X,null,G.createElement(Z,{color:$n.GRAY},">"," "),G.createElement(Z,{color:$n.GRAY},"Auto-compact kicks in when context reaches its limit")),G.createElement(X,null,G.createElement(Z,{color:$n.GRAY},">"," "),G.createElement(Z,{color:$n.GRAY},"Run /compact to manually summarize your conversation and free up context")))}function ContextMessage({analysis:e}){const t=getLayoutSizes({terminalWidth:useTerminalWidth()});return G.createElement(X,{flexDirection:"column",paddingTop:1},G.createElement(ContextProgress,{analysis:e,progressBarWidth:t.progressBarWidth}),G.createElement(ContextBreakdown,{analysis:e,labelWidth:t.labelWidth,breakdownBarWidth:t.breakdownBarWidth,showBreakdownBars:t.showBreakdownBars,showBreakdownDetail:t.showBreakdownDetail}),G.createElement(ContextSession,{analysis:e,labelWidth:t.labelWidth}),G.createElement(ContextTips,{tips:e.tips}),G.createElement(ContextHints,null))}function ContextConfigView({staticKey:e,contextEngineRef:t,setShowContextView:n,setInput:r}){const[s,o]=Q(null),[i,a]=Q(null);return K(()=>{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]),ne((e,t)=>{t.escape&&(AC(),r(""),n(!1))}),G.createElement(G.Fragment,null,G.createElement(pT,{staticKey:e}),G.createElement(X,{flexDirection:"column",width:"100%"},i?G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Mn,bold:!0},"Context"),G.createElement(Z,{color:$n.DIM},i)):s?G.createElement(ContextMessage,{analysis:s}):G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Mn,bold:!0},"Context"),G.createElement(Z,{color:$n.DIM},"Loading context analysis...")),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press Esc to return to conversation"))))}__name(SkillsConfigView,"SkillsConfigView"),Ft(),Ft(),zt(),LE(),zE(),$w(),cC(),Aw(),BS(),Sr(),__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"),NC(),Ft(),rr(),Ft(),__name(useTerminalWidth,"useTerminalWidth"),Cr(),__name(getLayoutSizes,"getLayoutSizes"),__name(getUsageColor,"getUsageColor"),__name(buildProgressBar,"buildProgressBar"),__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"),rr(),__name(ContextConfigView,"ContextConfigView"),Ft(),Ft(),zt(),fs(),zE(),$w(),$r(),vr(),Sr();var VT="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=>{$("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(!v(e))return!1;try{return(await j(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=v(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=Gk(f.platform()),t=oT(),n=iT(),r=aT()}catch{e="Unknown",t="Unknown",n="Unknown",r="N/A"}return{cwd:process.cwd(),os:e,arch:f.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:f.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"),Ft(),zt(),Cv(),rr(),Is(),__name(formatCountValue,"formatCountValue"),__name(formatSystemValue,"formatSystemValue");var KT=__name(({label:e,value:t,valueColor:n,dimValue:r})=>G.createElement(X,null,G.createElement(Z,{dimColor:!0},`${e}:`.padEnd(14)),r?G.createElement(Z,{dimColor:!0},t):G.createElement(Z,{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?ve.tick:ve.cross,a=t.auth.authenticated?$n.WHITE:zn.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 G.createElement(X,{flexDirection:"column",paddingX:0},G.createElement(X,null,G.createElement(Z,{color:Mn,bold:!0},"Command Code"," "),G.createElement(Z,{dimColor:!0},n)),G.createElement(X,null,G.createElement(Z,{dimColor:!0},"Visit "),G.createElement(Ts,{url:VT,text:VT,color:$n.CYAN}),G.createElement(Z,{dimColor:!0}," for usage and billing")),G.createElement(X,{marginTop:1},G.createElement(Z,{dimColor:!0},"Account:".padEnd(14)),t.auth.authenticated&&t.auth.username?G.createElement(G.Fragment,null,G.createElement(Ts,{url:`https://commandcode.ai/${t.auth.username}/`,text:t.auth.username,color:$n.CYAN}),G.createElement(Z,{color:a}," ",i)):t.auth.authenticated?G.createElement(G.Fragment,null,G.createElement(Z,null,"Authenticated"),G.createElement(Z,{color:a}," ",i)):G.createElement(G.Fragment,null,G.createElement(Z,{color:zn.WARNING},"Not signed in"),G.createElement(Z,{color:a}," ",i),G.createElement(Z,{dimColor:!0}," — run "),G.createElement(Z,{bold:!0},"/login"))),G.createElement(KT,{label:"Model",value:r}),G.createElement(KT,{label:"Branch",value:s,dimValue:!t.git.branch}),o?G.createElement(KT,{label:"Worktree",value:o}):null,t.git.remoteUrl?G.createElement(X,null,G.createElement(Z,{dimColor:!0},"Repository:".padEnd(14)),G.createElement(Ts,{url:t.git.remoteHttpUrl||`https://github.com/${t.git.remoteUrl}`,text:t.git.remoteUrl,color:$n.CYAN}),t.pr?G.createElement(G.Fragment,null,G.createElement(Z,{dimColor:!0}," · "),G.createElement(Ts,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?$n.CYAN:$n.GRAY}),G.createElement(Z,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null):t.pr?G.createElement(X,null,G.createElement(Z,{dimColor:!0},"Pull Request:".padEnd(14)),G.createElement(Ts,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?$n.CYAN:$n.GRAY}),G.createElement(Z,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null,G.createElement(KT,{label:"Taste",value:d,dimValue:!t.taste.fileExists}),G.createElement(KT,{label:"Directory",value:toRelativePath(t.system.cwd)}),G.createElement(KT,{label:"Skills",value:formatCountValue(t.skillsAgents.personalSkills,t.skillsAgents.projectSkills),dimValue:0===l}),G.createElement(KT,{label:"Agents",value:formatCountValue(t.skillsAgents.personalAgents,t.skillsAgents.projectAgents),dimValue:0===u}),G.createElement(KT,{label:"System",value:formatSystemValue({system:t.system})}),t.system.proxy?G.createElement(KT,{label:"Proxy",value:t.system.proxy}):null)}function StatusConfigView({staticKey:e,setShowStatusView:t,setInput:n}){const[r,s]=Q({phase:"loading"});return K(()=>{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}},[]),ne((e,r)=>{r.escape&&(n(""),t(!1))}),G.createElement(G.Fragment,null,G.createElement(pT,{staticKey:e}),G.createElement(X,{flexDirection:"column",width:"100%"},"ready"===r.phase?G.createElement(StatusMessage,{statusData:r.data}):"error"===r.phase?G.createElement(Z,{dimColor:!0},"Could not load status: ",r.message):G.createElement(Z,{dimColor:!0},"Gathering status…"),G.createElement(X,{marginTop:1},G.createElement(Z,{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 S.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"),Ft(),Ft(),Qt(),Ft(),Qt(),__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"),rr(),ar();var YT=__name(({onClose:e})=>{const[t,n]=Q(""),[r,s]=Q(null),[o,i]=Q([]),[a,l]=Q(getAdditionalDirectories()),[u,d]=Q({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,p]=Q(0);K(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),p(0)},[t]),K(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{s(null)},5e3);return()=>clearTimeout(e)},[r]);const g=__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"),h=__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");ne((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&o[u.suggestionIndex]?void g(o[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])h(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}))}}}),K(()=>{"suggestions"===u.zone&&p(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:o.length}))},[u,o.length]),K(()=>{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 f=o.slice(m,m+8),y=getFooterText({focusZone:u.zone});return G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.CYAN,paddingX:1,paddingY:0},G.createElement(Z,{bold:!0,color:$n.CYAN},"Add directory to workspace"),G.createElement(Z,{color:$n.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(Z,{color:$n.GRAY},"Added directories"),0===a.length?G.createElement(Z,{color:$n.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return G.createElement(Z,{key:e,color:n?$n.YELLOW:$n.GREEN,bold:n},n?` ${ve.pointer} `:" ",formatDirectoryForDisplay(e))})),G.createElement(X,{marginTop:1},G.createElement(Z,{bold:!0,color:$n.WHITE},"Path")),G.createElement(X,null,G.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?ve.pointer:" "} `,prefixColor:"input"===u.zone?$n.CYAN:$n.GRAY,onChange:e=>{n(e),s(null)},onSubmit:g})),!t&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:{error:$n.RED,warning:$n.YELLOW,success:$n.GREEN}[r.tone]},r.text)),o.length>0&&G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(Z,{color:$n.GRAY},"Suggestions"),f.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return G.createElement(Z,{key:e,color:r?$n.CYAN:$n.GRAY,bold:r},r?` ${ve.pointer} `:" ",e)})),G.createElement(X,{marginTop:1},G.createElement(BracketedText,{text:y,color:$n.DIM})))},"AddDirModal");Ft(),Ft(),zt(),Ft(),Ft(),zt(),cC(),rr();var JT=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),XT=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),ZT=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[s,o]=Q("idle"),[i,a]=Q(""),l=[...nC.map(e=>e.name),...rC.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?JT():XT();await D.mkdir(r,{recursive:!0});const s=`${e.agentType}.md`,o=t.join(r,s),i=Array.from(e.selectedTools).map(e=>iC[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 D.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");ne((e,t)=>{r||!t.return||"idle"!==s&&"error"!==s||u()});const d=Array.from(e.selectedTools).map(e=>iC[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return G.createElement(X,{flexDirection:"column",gap:1},G.createElement(X,{flexDirection:"column"},G.createElement(X,{gap:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"Name:"),G.createElement(Z,{color:$n.GRAY},e.agentType)),G.createElement(X,{gap:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"Location:"),G.createElement(Z,{color:$n.GRAY},m)),G.createElement(X,{gap:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"Tools:"),G.createElement(Z,{color:$n.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),G.createElement(X,{gap:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"Description"),G.createElement(Z,{color:$n.GRAY},"(Tells ","Command Code"," when to use this agent):")),G.createElement(Z,{color:$n.GRAY},e.ccToolDefinition),G.createElement(X,{gap:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"System Prompt:")),G.createElement(Z,{color:$n.GRAY},e.sysPrompt),!r&&G.createElement(X,{marginTop:1},"idle"===s&&G.createElement(X,{gap:1},G.createElement(Z,{color:$n.GREEN,dimColor:!0},"Press"),G.createElement(Z,{color:$n.GREEN,bold:!0},"Enter"),G.createElement(Z,{color:$n.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===s&&G.createElement(Z,{color:$n.YELLOW},"Saving agent..."),"saved"===s&&G.createElement(Z,{color:$n.GREEN},ve.tick," ",i),"error"===s&&G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.RED},ve.cross," Error: ",i),G.createElement(Z,{color:$n.GRAY},"Press Enter to retry"))))},"AgentSummary");cC(),rr();var e_=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[s,o]=Q("menu"),i=[...nC.map(e=>e.name),...rC.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=>aC[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(ne((e,n)=>{n.escape&&("menu"===s?t():o("menu")),n.return&&"view"===s&&o("menu")}),"view"===s)return G.createElement(X,{flexDirection:"column"},G.createElement(ZT,{config:l,onSaveComplete:()=>o("menu"),viewOnly:!0}),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY},"Press Enter to go back")));if("edit"===s)return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.YELLOW},"Edit functionality coming soon..."),G.createElement(Z,{color:$n.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 D.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),o("menu")}else o("menu")},"handleDeleteSelect");return G.createElement(X,{flexDirection:"column",gap:1},G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.RED},"Delete agent"),G.createElement(Z,{color:$n.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),G.createElement(X,null,G.createElement(et,{items:r,onSelect:s,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},` ${t}`)})))}return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.WHITE,bold:!0},e.name),G.createElement(X,{marginTop:1},G.createElement(et,{items:u,onSelect:d,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},` ${t}`)})),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");jE(),rr();var t_=__name(({handleSelect:e,createdAgentName:n})=>{const[r,s]=Q([]),[o,i]=Q([]),[a,l]=Q([]),[u,d]=Q(!0),[m,p]=Q(!1),[g,h]=Q(null),[y,w]=Q(!1),S=__name(()=>t.join(f.homedir(),".commandcode","agents"),"getRootAgentDir"),E=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),v=__name(async(e,n)=>{try{p(!1);const r=(await D.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const s=t.join(e,r),o=await D.readFile(s,"utf-8"),{data:i,content:a}=Fe(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");K(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([v(S(),"personal"),v(E(),"project")]),n=qE.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 C=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{C.push({label:e.name,value:e.filePath})}),o.forEach(e=>{C.push({label:e.name,value:e.filePath})});const k=r.length+o.length,T=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...o].find(e=>e.filePath===t.value);e&&(h(e),w(!0))}},"handleAgentSelect");if(u)return G.createElement(Z,{color:$n.GRAY},"Loading agents...");if(y&&g){const e=g.filePath.startsWith("__builtin__:");return G.createElement(e_,{agent:g,onBack:()=>{w(!1),h(null)},setRevalidateAgent:p,isReadOnly:e})}const _=__name(({isSelected:e,label:t})=>{const n=C.find(e=>e.label===t),s=n?.value||"",i=r[0]?.filePath===s,a=o[0]?.filePath===s;return G.createElement(X,{flexDirection:"column"},i&&r.length>0&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY,bold:!0},"User agents")),a&&o.length>0&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.GRAY,bold:!0},"Project agents")),G.createElement(X,null,G.createElement(Z,{color:$n.WHITE},e?">":" "),G.createElement(Z,{color:e?$n.WHITE:$n.GRAY}," ",t)))},"CustomItemComponent");return G.createElement(X,{flexDirection:"column"},G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.WHITE,bold:!0},"Agents"),k>0?G.createElement(Z,{color:$n.GRAY}," ","(",k," agent",k>1?"s":"",")"):G.createElement(Z,{color:$n.GRAY}," (No custom agents)")),n&&G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{color:$n.GREEN,dimColor:!0},"Created agent: ",n)),G.createElement(et,{items:C,onSelect:T,indicatorComponent:()=>null,itemComponent:_}),a.length>0&&G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(Z,{color:$n.GRAY,bold:!0},"Default agents"),a.map(e=>G.createElement(Z,{key:e.filePath,color:$n.GRAY}," ",e.name.charAt(0).toUpperCase()+e.name.slice(1)))),G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(Z,{color:$n.GRAY},"Create specialized subagents that Command Code can delegate to."),G.createElement(Z,{color:$n.GRAY},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Ft(),zt(),rr(),cC(),Ft(),Ft(),zt(),rr();var n_=__name(({onSelect:e})=>G.createElement(et,{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})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},` ${t}`)}),"LocationSelector");Ft(),ar(),zt(),cC(),ur(),hr(),BE(),rr();var r_=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:s,onSysPromptChange:o,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=Q(!1),[p,g]=Q(!1),h=J(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]),f=J(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||p){if(!p||t.isPasteEnd){if(p&&t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(g(!0),t.isPasteEnd){g(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[p,i]);return"agentType"===e?G.createElement(G.Fragment,null,G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(iC).some(e=>Ue(e)===Ue(t))||Object.keys(iC).some(e=>Ue(e)===Ue(t)))&&G.createElement(Z,{color:$n.RED},ve.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Ue(t))&&G.createElement(Z,{color:$n.RED},ve.warning," This name is reserved. Reserved names:"," ",OE.join(", "))),G.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Ue(t);Object.values(iC).some(t=>Ue(t)===e)||Object.keys(iC).some(t=>Ue(t)===e)||isReservedAgentName(e)||a()},onChange:s,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?G.createElement(G.Fragment,null,G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.WHITE},"Enter the system prompt for your agent:"),G.createElement(Z,{color:$n.GRAY},"Be comprehensive for best results.")),G.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:h,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?G.createElement(G.Fragment,null,G.createElement(Z,{color:$n.WHITE},"When should ","Command Code"," use this agent?"),G.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:f,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Ft(),rr();var s_=__name(({onSelect:e})=>G.createElement(et,{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})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY},` ${t}`)}),"MethodSelector");Ft(),ar(),Ft(),rr();var o_=["·","○","◇","☆","✧","☆","◇","○","⌘"],i_=[12,5,4,4,4,4,4,5,16],a_=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<i_.length;e++)if(n+=i_[e],t<n)return o_[e];const r=t-58;n=0;for(let e=0;e<a_.length;e++)if(n+=a_[e],r<n)return o_[7-e];return o_[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=__name(e=>{const n=e-(t-5);return n>=0&&n<Xn.length?Xn[n]:Zn},"getCharColor");return G.createElement(Z,null,e.split("").map((e,t)=>G.createElement(Z,{key:t,color:r(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return G.createElement(Z,{color:t??Mn,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 l_=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,s]=Q(0),[o,i]=Q(0),a=V(n);a.current=n;const l=getTerminalWidth();K(()=>{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 G.createElement(X,{width:l,height:1,paddingLeft:0,marginLeft:0},G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:jn.BG,color:jn.FG}," "),G.createElement(Z,{backgroundColor:jn.BG},G.createElement(CMDIcon,{frame:4*r})),G.createElement(ShimmerText,{text:e,offset:u,bg:jn.BG}),G.createElement(Z,{backgroundColor:jn.BG,color:jn.FG}," ")),G.createElement(Z,null," "),d?G.createElement(X,{columnGap:1},G.createElement(Z,{color:$n.DIM},formatTime3(t)),G.createElement(Z,{color:$n.DIM},"•"),G.createElement(Z,{color:$n.GRAY},ve.arrowDown),G.createElement(Z,{color:$n.DIM},formatToken(Math.round(o))),G.createElement(Z,{color:$n.DIM},"•"),G.createElement(X,{columnGap:1},G.createElement(Z,{bold:!0,color:$n.GRAY},"esc"),G.createElement(Z,{color:$n.DIM},"to interrupt"))):m?G.createElement(X,{columnGap:1},G.createElement(Z,{color:$n.DIM},formatToken(Math.round(o)))):G.createElement(G.Fragment,null))},"Status");hr(),ur(),rr();var c_=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:s})=>{const[o,i]=Q(!1),[a,l]=Q(0),[u,d]=Q(0);K(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=J(()=>{0!==e.trim().length&&n()},[e,n]),p=J(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 G.createElement(X,{flexDirection:"column"},r?G.createElement(X,null,G.createElement(CMDIcon,{frame:u}),G.createElement(Z,{color:$n.WHITE},"Generating agent from description...")):G.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:p,onSubmit:m}),s&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.RED},`${ve.warning} ${s}`)))},"RecommendedFlow");Ft(),cC(),rr();var u_=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[s,o]=Q(!1),[i,a]=Q(0),l=Y(()=>[...nC.map(e=>e.name),...rC.map(e=>e.name)],[]),u=Y(()=>[{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=Y(()=>{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]":"[ ]"} ${iC[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),p=m.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type);return ne((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?p.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=p.length?0:t});else if(l.return||" "===e){const e=p[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)}}}),G.createElement(X,{flexDirection:"column"},m.map((e,t)=>{const n=p.findIndex(t=>t.value===e.value),r=-1!==n&&n===i;if("divider"===e.type)return G.createElement(X,{key:`divider-${t}`},G.createElement(Z,{color:$n.GRAY}," ",e.label));if("spacer"===e.type)return G.createElement(X,{key:`spacer-${t}`,height:1});if("label"===e.type)return G.createElement(X,{key:`label-${t}`},G.createElement(Z,{color:$n.GRAY}," ",e.label));const s="continue"===e.type;return G.createElement(X,{key:`item-${t}`},G.createElement(Z,{color:r?$n.WHITE:$n.GRAY,bold:s&&r},r?">":" "," ",e.label))}),G.createElement(X,{marginTop:1},e.size===l.length&&G.createElement(Z,{color:$n.GRAY},"All tools selected"),e.size>0&&e.size<l.length&&G.createElement(Z,{color:$n.GRAY},e.size," tools selected"),0===e.size&&G.createElement(Z,{color:$n.GRAY},"No tools selected")))},"ToolsSelector");Cr(),bn(),Cs(),bw(),ho(),Sn(),Sr();var d_=__name(({onComplete:e})=>{const[t,n]=Q("location"),[r,s]=Q(!1),[o,i]=Q(null),[a,l]=Q("agentType"),u=Y(()=>[...nC.map(e=>e.name),...rC.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,p]=Q(d()),g=__name(t=>{n("location"),l("agentType"),p(d()),e(t)},"resetToDefaults"),h=__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"),f=__name(e=>{p({...m,location:e}),n("method")},"handleLocationSelect"),y=__name(e=>{p({...m,method:e}),n("configuration")},"handleMethodSelect"),w=__name(async()=>{try{i(null),s(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced();let r;e===_t.ANTHROPIC&&(r=await mn.getValidAccessToken(),validateOAuthToken({token:r,provider:e}));const o={[vt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(o[vt.OAUTH_TOKEN]=`Bearer ${r}`);const a=getApiBaseUrl(),l=new Yy({baseUrl:a}),u=await l.post({headers:o,endpoint:Ct.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:`anthropic:${getConfiguredModel()}`}});p({...m,agentType:Ue(u.agentName),sysPrompt:u.systemPrompt,ccToolDefinition:u.toolDescription}),n("tools")}catch(e){e instanceof to&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")?i(cn):i("An error occurred while generating the agent. Please try again.")}finally{s(!1)}},"handleRecommendedSubmit"),S=__name(()=>{p({...m,agentType:Ue(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),E=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),v=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),C=__name(()=>{n("summary")},"handleToolsComplete"),k=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),p({...m,selectedTools:t})},"handleToggleTool"),T=__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)),p({...m,selectedTools:n})},"handleToggleCategory");return G.createElement(X,{flexDirection:"column",gap:1},G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.WHITE,bold:!0},"Create new agent"),G.createElement(Z,{color:$n.GRAY},h())),G.createElement(X,null,"location"===t&&G.createElement(n_,{onSelect:f}),"method"===t&&G.createElement(s_,{onSelect:y}),"configuration"===t&&"recommended"===m.method&&G.createElement(c_,{description:m.recommendedMethodDescription,onChange:e=>p({...m,recommendedMethodDescription:e}),loading:r,errorMessage:o,onSubmit:w}),"configuration"===t&&"manual"===m.method&&G.createElement(X,{flexDirection:"column",gap:1},G.createElement(r_,{step:a,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>p({...m,agentType:e}),onSysPromptChange:e=>p({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>p({...m,ccToolDefinition:e}),onAgentTypeSubmit:S,onSysPromptSubmit:E,onCCToolDefinitionSubmit:v})),"tools"===t&&G.createElement(u_,{selectedTools:m.selectedTools,onToggleTool:k,onToggleCategory:T,onComplete:C}),"summary"===t&&G.createElement(ZT,{config:m,onSaveComplete:g})))},"AgentNew");rr();var m_=__name(({onCancel:e})=>{const[t,n]=Q(null),[r,s]=Q(null),o=__name(e=>{n(e.value),s(null)},"handleSelect");return ne((t,n)=>{n.escape&&e()}),G.createElement(X,{gap:1,paddingLeft:1,paddingRight:1,width:"100%",borderColor:$n.GRAY,borderStyle:"single",flexDirection:"column"},null===t&&G.createElement(t_,{handleSelect:o,createdAgentName:r}),"create_new_agent"===t&&G.createElement(d_,{onComplete:e=>{s(e),n(null)}}))},"AgentsConfig");rr(),Ft(),Sr(),rr();var p_=[{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."}],g_=__name(({onSelect:e,onCancel:t})=>{const[n,r]=Q(null);K(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const s=__name(t=>{e(t.value)},"handleSelect");if(ne((e,n)=>{n.escape&&t()}),null===n)return null;const o=p_.findIndex(e=>e.value===n);return G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(X,null,G.createElement(Z,{color:Mn,bold:!0},"Select a compact mode to compact sessions")),G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"Choose how Command Code handles automatic context compaction.")),G.createElement(et,{items:p_,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.CYAN},e?ve.pointer:" "),itemComponent:({isSelected:e,label:t})=>{const r=p_.find(e=>e.label===t),s=r?.value===n,o=p_.findIndex(e=>e.label===t);return G.createElement(X,{flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{color:e?$n.CYAN:s?$n.GREEN:$n.WHITE},` ${o+1}. ${r?.label??t}`),s&&G.createElement(Z,{color:$n.GREEN}," ",ve.tick)),G.createElement(Z,{color:$n.DIM},` ${r?.description??""}`))}}),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press "),G.createElement(Z,{color:$n.DIM,bold:!0},"Esc"),G.createElement(Z,{color:$n.DIM}," to cancel")))},"CompactModeSelector");Ft(),rr(),Ft(),ar(),zt(),ur(),yn(),Ft();var h_=n(y(),"commandcode-images"),f_={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{v(h_)||C(h_,{recursive:!0});const r=f_[e.mediaType]||".png",s=`image-${t}-${Date.now()}${r}`,o=n(h_,s),i=Buffer.from(e.data,"base64");return k(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=J((e,t)=>{s(t=>[...t,e]),r(t),i()},[s,r,i]),l=V(!1),u=V(""),d=V(null),m=V(""),p=J(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]),g=J(()=>{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 p(e,t)}},500)},[p]);return{handlePaste:J(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 p(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,g(),!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)),g(),!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 p(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,p,g,a]),resetPasteState:J(()=>{l.current=!1,u.current="",m.current="",d.current&&(clearTimeout(d.current),d.current=null)},[]),isPasting:J(()=>l.current,[])}}__name(saveTempImage,"saveTempImage"),xn(),Cr(),Ft(),hr(),ur(),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),hr(),Ft(),Ft();var y_=["code --wait","cursor --wait","nano"],w_=["code","cursor","subl","atom","zed"];function ensureWaitFlag(e){const t=e.split(" ").filter(e=>e.length>0),n=t[0];return w_.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(`${n} ${t}`,{stdio:"ignore",encoding:"utf-8"}),!0}catch{return!1}}function findFallbackEditor(){for(const e of y_)if(isCommandAvailable(e))return e;return null}__name(ensureWaitFlag,"ensureWaitFlag"),__name(isCommandAvailable,"isCommandAvailable"),__name(findFallbackEditor,"findFallbackEditor");var S_=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 S_;t=ensureWaitFlag(t);const r=n(y(),`commandcode-${Date.now()}.md`);return await O(r,e),new Promise((e,n)=>{const s=t.split(" ").filter(e=>e.length>0),o=s[0],i=s.slice(1),a=R(o,[...i,r],{stdio:"inherit"});a.on("close",async()=>{try{const t=await q(r,"utf-8");await F(r),e(t.trimEnd())}catch(e){n(e)}}),a.on("error",async e=>{try{await F(r)}catch{}n(e)})})}function useExternalEditor({input:e,setInput:t,setInputKey:n,onEditorClose:r}){const[s,o]=Q(!1),[i,a]=Q(null),l=J(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 S_?"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=J(()=>{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"),Ft();var b_=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=Q(null),s=V(!1);return K(()=>{if(!t||s.current)return;let e=!0;return s.current=!0,Sk().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");function loadGitignore(e){const t=it(),r=n(e,".gitignore");if(v(r))try{const e=E(r,"utf8");t.add(e)}catch{}return t.add(".git"),t}rr(),Ft(),rr(),__name(loadGitignore,"loadGitignore");var E_=__name(({onSelectFile:e,onClose:t,searchQuery:i=""})=>{const[a,l]=Q(process.cwd()),[u,d]=Q([]),[m,p]=Q(0),[g,h]=Q(0),f=i.trim()?15:10,y=J((e,t=process.cwd())=>{if(!e.trim())return[];const r=loadGitignore(t);if(e.endsWith("/")){const o=n(t,e);try{const e=T(o),i=[];return e.forEach(e=>{const a=n(o,e);try{const e=_(a),n=s(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 o=e.split("/"),i=o.pop()||"",a=n(t,o.join("/"));try{const e=T(a),o=[],l=i.toLowerCase();return e.forEach(e=>{const u=e.toLowerCase();if(!i||u.includes(l)){const i=n(a,e);try{const e=_(i),n=s(t,i);if(r.ignores(n))return;o.push({name:n,path:i,isDirectory:e.isDirectory()})}catch{}}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),o.slice(0,50)}catch{}}const o=[],i=e.toLowerCase(),a=__name((e,l=0)=>{if(!(l>8))try{T(e).forEach(u=>{const d=n(e,u);try{const e=_(d),n=s(t,d);if(r.ignores(n))return;const m=n.toLowerCase();(u.toLowerCase().includes(i)||m.includes(i))&&o.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),o.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,p=t.name.split("/").length;return m!==p?m-p:e.name.localeCompare(t.name)}),o.slice(0,50)},[]),w=J(e=>{try{const t=T(e),o=[],i=process.cwd(),a=loadGitignore(i);"/"!==e&&o.push({name:"..",path:r(e),isDirectory:!0}),t.forEach(t=>{const r=n(e,t);try{const e=_(r),n=s(i,r);if(a.ignores(n))return;o.push({name:t,path:r,isDirectory:e.isDirectory()})}catch{}}),o.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)),d(o),p(0),h(0)}catch{}},[]);K(()=>{if(i.trim()){const e=y(i);d(e),p(0),h(0)}else w(a)},[a,w,i,y]),ne((n,r)=>{if(r.escape)t();else if(r.upArrow)p(e=>{const t=Math.max(0,e-1);return t<g&&h(t),t});else if(r.downArrow)p(e=>{const t=Math.min(u.length-1,e+1);return t>=g+f&&h(t-f+1),t});else{if(r.rightArrow){const e=u[m];if(!e)return;return void(e.isDirectory&&!i.trim()&&l(o(e.path)))}if(r.return){const t=u[m];if(!t)return;return void e(t.path)}}});const S=u.slice(g,g+f);return G.createElement(X,{flexDirection:"column",paddingLeft:1},G.createElement(X,{marginBottom:1,flexDirection:"column"},G.createElement(Z,{color:$n.DIM},i.trim()?`Searching for: "${i}"`:`Files: ${a}`),G.createElement(Z,{color:$n.DIM},i.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===S.length?G.createElement(Z,{color:$n.DIM},i.trim()?`No files found matching "${i}"`:"No files found in this directory"):S.map((e,t)=>{const n=g+t,r=e.name,s=n===m;return G.createElement(Z,{key:e.path,color:s?$n.GREEN:$n.DIM},e.isDirectory?`${r}/`:r)}))},"FileList");Ft(),zt(),vr(),rr(),Ft(),rr();var v_=__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?$n.RED:e>=70?$n.YELLOW:$n.DIM,"getColor"),s=t>=90?6:Math.round(t/100*6),o=6-s,i=ve.square.repeat(s),a=ve.squareLightShade.repeat(o),l=r(t);return G.createElement(X,{paddingRight:3},G.createElement(Z,{color:l},`Context left before auto-compact ${n}% `),G.createElement(Z,{color:l},i),o>0&&G.createElement(Z,{color:$n.DIM},a))},"ContextUsage");Ft(),gC(),os(),rr();var C_=__name(()=>{const[e,t]=Q("continuous learning"),[n,r]=Q(!1),[s,o]=Q(!1),i=V([]),a=V(0),l=V(null),u=V(!1);K(()=>{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 mC.on("new-event",e),()=>{mC.off("new-event",e),l.current&&clearTimeout(l.current)}},[]);const d=` ${n?ve.squareSmallFilled:ve.squareSmall} TASTE`,m=9+e.length+d.length>Yr;let p=e;p=truncateString(m?{text:e,maxChars:Yr}:{text:e,maxChars:Yr-d.length-9-10});const g=s?void 0:$n.DIM;return G.createElement(X,{paddingRight:2},!m&&G.createElement(G.Fragment,null,G.createElement(BracketWrap,{color:$n.DIM},"ctrl+t"),G.createElement(Z,{color:$n.DIM}," ")),G.createElement(Z,{color:g},p),!m&&G.createElement(Z,{color:Dn.TEXT},d))},"LearningFeedMini");Ft(),rr();var k_=__name(({mode:e,pendingExitKey:t})=>t?G.createElement(Z,{color:$n.DIM},"Press Ctrl+C again to exit"):"auto-accept"===e?G.createElement(X,{flexDirection:"row"},G.createElement(Z,{color:Vn},"» accept edits on "),G.createElement(BracketWrap,{color:$n.DIM},"shift+tab")):"plan"===e?G.createElement(X,{flexDirection:"row"},G.createElement(Z,{color:Qn},"plan mode "),G.createElement(BracketWrap,{color:$n.DIM},"shift+tab")):G.createElement(Z,{color:$n.DIM},"? for shortcuts"),"ModeIndicator");Ft(),rr(),Is();var T_=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?$n.DIM:Kn.MERGED;return G.createElement(G.Fragment,null,t&&G.createElement(Z,{color:$n.DIM}," · "),G.createElement(Z,{color:n},"PR "),G.createElement(Ts,{url:e.url,text:`#${e.number}`,color:n}))},"PRLinkBadge"),__=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?G.createElement(G.Fragment,null,t&&G.createElement(Z,{color:$n.DIM}," · "),G.createElement(Z,{color:"connected"===e.type?$n.GREEN:$n.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),x_=__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:p,isBashMode:g,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w})=>{const S=e>=60;return G.createElement(G.Fragment,null,G.createElement(X,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r||l?G.createElement(X,{flexDirection:"row",justifyContent:"space-between",width:e-1},G.createElement(X,{flexDirection:"row",columnGap:0},n&&!l?G.createElement(Z,{color:Un},t):G.createElement(k_,{mode:r,pendingExitKey:l}),!l&&G.createElement(T_,{prInfo:s}),!l&&G.createElement(__,{indicator:a})),S&&G.createElement(X,{flexDirection:"column",alignItems:"flex-end"},o&&G.createElement(C_,null),i&&G.createElement(v_,{usage:i}))):G.createElement(G.Fragment,null,G.createElement(X,{flexDirection:"row",justifyContent:"space-between",width:e-1},G.createElement(k_,{mode:r}),S&&o&&G.createElement(C_,null)),G.createElement(X,{flexDirection:"row",justifyContent:"space-between",width:e-1},G.createElement(X,{flexDirection:"row",columnGap:0},G.createElement(Z,{color:n?Un:$n.DIM},t),G.createElement(T_,{prInfo:s}),G.createElement(__,{indicator:a})),S&&i&&G.createElement(v_,{usage:i}))),(u||d||p&&m)&&G.createElement(X,{flexDirection:"row",columnGap:1},u&&G.createElement(Z,null,ve.tick," ","Command Code"," updated:"," ",G.createElement(Z,{color:$n.DIM},"v",u.updatedFrom),G.createElement(Z,{color:$n.DIM}," ",ve.arrowRight," "),G.createElement(Z,null,"v",u.updatedTo)),!u&&d&&G.createElement(Z,{color:$n.YELLOW,dimColor:!0},ve.info," Update available:"," ",d.currentVersion," ",ve.arrowRight," ",d.latestVersion),p&&m&&G.createElement(Z,{color:$n.GREEN,dimColor:!0},ve.bullet," Provider:"," ",getProviderDisplayName(m)))),g&&G.createElement(X,{paddingLeft:2},G.createElement(Z,{color:$n.GREEN},"! for bash mode")),f&&h&&G.createElement(X,{paddingLeft:2},G.createElement(Z,{color:Mn},"SHARED: ",h.url," (copied to clipboard)")),y&&G.createElement(X,{paddingLeft:2},G.createElement(Z,{color:y.includes("NOT SHARED")?$n.RED:Mn},y)),w&&G.createElement(X,{paddingLeft:2},G.createElement(Z,{color:Mn},w)))},"BottomIndicator");Ft(),Lv(),os(),rr();var P_=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=Q([]),[s,o]=Q(0),[i,a]=Q(!0);K(()=>{l()},[]);const l=__name(async()=>{a(!0);const e=await xv.listSessions();r(e.slice(0,30)),a(!1)},"loadSessions");if(ne((r,i)=>{i.escape?t():i.upArrow?o(e=>Math.max(0,e-1)):i.downArrow?o(e=>Math.min(n.length-1,e+1)):i.return&&n.length>0&&s<n.length&&e(n[s].id)}),i)return G.createElement(X,{flexDirection:"column",paddingLeft:2},G.createElement(Z,{color:$n.GRAY},"Loading sessions..."));if(0===n.length)return G.createElement(X,{flexDirection:"column",paddingLeft:2},G.createElement(Z,{color:$n.GRAY},"No previous sessions found"),G.createElement(Z,{color:$n.DIM},"Press ESC to go back"));const u=__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"),d=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),m=__name(e=>truncateString({text:d(e),maxChars:Kr}),"truncateMessage"),p=__name(e=>e.title?d(e.title):m(e.firstMessage),"getSessionSummary");return G.createElement(X,{flexDirection:"column",paddingLeft:1,width:"100%"},G.createElement(Z,{color:$n.CYAN,bold:!0},"Resume Session"),G.createElement(Z,{color:$n.DIM},"Use ↑↓ to navigate, Enter to select, ESC to cancel"),G.createElement(X,{marginTop:1}),G.createElement(X,{columnGap:2,marginBottom:1},G.createElement(X,{width:5},G.createElement(Z,{color:$n.GRAY}," ")),G.createElement(X,{width:13},G.createElement(Z,{color:$n.GRAY},"Modified")),G.createElement(X,{width:20},G.createElement(Z,{color:$n.GRAY},"Git Branch")),G.createElement(X,{width:11},G.createElement(Z,{color:$n.GRAY},"# Messages")),G.createElement(X,null,G.createElement(Z,{color:$n.GRAY},"Summary"))),G.createElement(X,{columnGap:2},G.createElement(X,{flexDirection:"column",width:5},n.map((e,t)=>G.createElement(Z,{key:`sel-${t}`,color:s===t?$n.WHITE:$n.GRAY},s===t?`${ve.pointer} ${t+1}.`:` ${t+1}.`))),G.createElement(X,{flexDirection:"column",width:13},n.map((e,t)=>G.createElement(Z,{key:`mod-${e.id}`,color:s===t?$n.WHITE:$n.GRAY},u(e.lastModified)))),G.createElement(X,{flexDirection:"column",width:20},n.map((e,t)=>G.createElement(Z,{key:`branch-${e.id}`,color:s===t?$n.WHITE:$n.GRAY,wrap:"truncate-end"},e.gitBranch||"-"))),G.createElement(X,{flexDirection:"column",width:11},n.map((e,t)=>G.createElement(Z,{key:`msg-${e.id}`,color:s===t?$n.WHITE:$n.GRAY},e.messageCount))),G.createElement(X,{flexDirection:"column"},n.map((e,t)=>G.createElement(Z,{key:`summary-${e.id}`,color:s===t?$n.WHITE:$n.GRAY,wrap:"truncate-end"},p(e))))))},"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 G.createElement(Z,null,r?" ":"",t?G.createElement(Z,{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 G.createElement(X,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>G.createElement(X,{key:r,flexDirection:"row"},G.createElement(X,{flexShrink:0,marginRight:1},0===r&&G.createElement(Z,{color:$n.DIM},o)),G.createElement(X,{flexDirection:"row"},e.map((e,r)=>G.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Ft(),rr(),Ft(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),Ms(),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Ft(),Qb();var A_=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,s]=Q(null),[o,i]=Q(!1),a=V(!1),l=V(null),[u,d]=Q(!1),[m,p]=Q("connected"),g=V(null),h=V(null),f=J((e,t)=>{h.current&&(clearTimeout(h.current),h.current=null),p(e),d(!0),void 0!==t&&(h.current=setTimeout(()=>{d(!1)},t))},[]),y=J(()=>{h.current&&(clearTimeout(h.current),h.current=null)},[]),w=J(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new Fb,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=g.current;if(null===r?n&&f("connected",3e3):r!==n&&(n?f("connected",2e3):f("disconnected",5e3)),g.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===g.current&&f("disconnected",5e3),g.current=!1,i(!1),s(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[f]);K(()=>{if(!t||n)return;w(!0);const e=setInterval(()=>w(!1),500);return()=>{clearInterval(e),y(),l.current?.disconnect(),l.current=null}},[t,n,w,y]);const S={visible:u,message:"connected"===m?`IDE ${ve.tick}`:"IDE disconnected",type:m};return{context:r,connected:o,refresh:w,connectionIndicator:S}},"useVSCodeContext");Ft();var I_=__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,"</ide-context>");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");Ft();var N_=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),R_=__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"),$_=["","[118;5u","[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 M_=__name(()=>G.createElement(X,{flexDirection:"column",paddingLeft:1},G.createElement(Z,{color:$n.DIM,bold:!0},"Available Shortcuts:"),G.createElement(X,{columnGap:4},G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.DIM},"! for bash mode"),G.createElement(Z,{color:$n.DIM},"/ for commands"),G.createElement(Z,{color:$n.DIM},"@ for file paths"),G.createElement(Z,{color:$n.DIM},"shift + tab to toggle auto-accept")),G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.DIM},"double tap esc to clear input"),G.createElement(Z,{color:$n.DIM},"ctrl + j / shift + ⏎ for newline"),G.createElement(Z,{color:$n.DIM},"ctrl + g to open in editor"),G.createElement(Z,{color:$n.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),D_=__name(({input:e,onSubmit:t,setInput:n,showCursor:r=!0,placeholder:o="Enter your input…",showFileList:i,setShowFileList:a,fileSearchQuery:l,setFileSearchQuery:u,onCommand:d,contextUsage:m,tasteLearning:p=!1,tasteUsage:g=!1,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w,updateStatus:S,updateFailedInfo:E,currentProvider:v,showProviderInfo:C,permissionMode:k="standard",onToggleAutoAccept:T,hintMessage:_,historyManager:x,pendingExitKey:P=null,onOverlayVisibilityChange:A,onDoubleEscapeEmpty:I,onAltP:N,isProcessing:R=!1,ideContextEnabled:$=!0})=>{const[M,D]=Q(0),[L,O]=Q(!1),[q,F]=Q(!1),[j,B]=Q(!1),[z,U]=Q(!1),[W,H]=Q(""),[ee,re]=Q(!1),se=V(0),oe=V(0),[ie,ae]=Q([]),[le,ce]=Q([]),[ue,de]=Q(-1),[me,pe]=Q(""),ge=V(!1),he=V(!1),fe=V(void 0),[ye,we]=Q(-1),[Se,be]=Q(""),Ee=V(0),{isEditorOpen:Ce,editorError:ke,handleOpenInEditor:Te,clearEditorError:_e}=useExternalEditor({input:e,setInput:n,setInputKey:D,onEditorClose:__name(()=>{ge.current=!1},"onEditorClose")}),{handlePaste:xe,resetPasteState:Pe,isPasting:Ae}=useBracketedPaste({input:e,detectedContent:ie,setInput:n,setDetectedImages:ce,setDetectedContent:ae,incrementInputKey:__name(()=>D(e=>e+1),"incrementInputKey")}),{context:Ie,connected:Ne,refresh:Re,connectionIndicator:$e}=A_({enabled:$,paused:R}),{stdout:Me}=te(),De=Me?.columns??80,{pr:Le}=b_();K(()=>{const e=i||z||ee;A?.(e)},[i,z,ee,A]);const Oe=J(()=>{ce([]),de(-1)},[]),qe=J(()=>{n(""),F(!1),U(!1),H(""),re(!1),ae([]),Oe(),pe(""),Pe(),we(-1),be(""),D(e=>e+1)},[n,Pe,Oe]),Fe=J(()=>{ge.current=!0;const{text:t,cursor:r}=insertTextAt(e,Ee.current,"\n");n(t),fe.current=r,D(e=>e+1),setTimeout(()=>{ge.current=!1},0)},[e,n]);ne(async(t,r)=>{if(-1!==ue&&r.leftArrow)return void de(prevImageIndex({currentIndex:ue,imageCount:le.length}));if(-1!==ue&&r.rightArrow)return void de(nextImageIndex({currentIndex:ue,imageCount:le.length}));if(r.upArrow){if(i||z||ee)return;const t=e.indexOf("\n"),r=-1===t||Ee.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:le.length,selectedImageIndex:ue,historyIndex:ye}))return void de(le.length-1);if(-1!==ue&&de(-1),0!==e.length&&-1===ye&&!r)return;const s=x?.count()??0;if(0===s)return;-1===ye&&be(e);const o=Math.min(ye+1,s-1);return void(o!==ye&&(we(o),n(x?.getAt(o)||""),D(e=>e+1)))}if(r.downArrow){if(i||z||ee)return;if(-1===ye)return;const t=e.lastIndexOf("\n");if(!(-1===t||Ee.current>t))return;const r=ye-1;return we(r),n(-1===r?Se:x?.getAt(r)||""),void D(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void Oe();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return ge.current=!0,void Te();if(getIsExpandToolShortcut(r,t))return ge.current=!0,n(e),D(e=>e+1),void setTimeout(()=>{ge.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Ae()}))return he.current=!0,Fe(),void setTimeout(()=>{he.current=!1},0);if(r.meta&&r.backspace)return void qe();if(r.meta&&"w"===t)return ge.current=!0,void qe();const s=r.ctrl&&"v"===t||$_.includes(t),o=r.meta&&"v"===t;if(s||o){if(s&&"darwin"===process.platform){const t=e;ge.current=!0;const r=await detectClipboardImage();return r&&(ce(e=>[...e,r]),n(t),D(e=>e+1)),void(ge.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return B(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==ue&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:le,index:ue});return ce([...e]),void de(t)}if(r.escape){if(-1!==ue)return void de(-1);if(z)return;if(ee)return re(!1),n(me),void D(e=>e+1);const t=Date.now();return t-se.current<500?(e.length>0?qe():I?.(),se.current=0,oe.current=0):(se.current=t,L||q||(oe.current=t)),O(!1),void F(!1)}L&&(r.backspace||r.delete)&&0===e.length&&O(!1)}});const je=J(async t=>{if(Ce)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void N?.();const s=processBracketedPaste(t);if((s.isPasteStart||s.isPasteEnd||Ae())&&await xe(t))return;if(ge.current)return void(ge.current=!1);-1!==ye&&we(-1);const o=1===t.length,l=t.slice(-1);if(o){if("?"===l&&!L)return O(!0),n(""),void D(e=>e+1);if("!"===l&&!q)return O(!1),F(!0),n(""),void D(e=>e+1)}if("/"!==l||z||"/"!==t||(U(!0),H("")),z&&!t.startsWith("/")&&(U(!1),H("")),z&&t.startsWith("/")){const e=t.substring(1);e.includes(" ")?(U(!1),H("")):H(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)}}L&&(t!==e||t.length<e.length)&&O(!1),ke&&_e(),0===t.length&&(F(!1),U(!1),H(""),re(!1),ae([]),u(""),pe(""),Pe()),n(t)},[L,e,n,i,a,z,q,le,ye,xe,Pe,N,ke,_e,Ce]),Be=J(async()=>{if(Re(),oe.current=0,L)return void O(!1);let n=e.trim();if(!q&&n.startsWith("/")&&d&&"handled"===(await d(n)).status)return x?.add(n),F(!1),U(!1),H(""),Oe(),ae([]),we(-1),void be("");we(-1),be("");let r=[];const s=le.length>0,o=ie.length>0;if(!q&&s&&(r=[...le]),!q&&o){let e=n;ie.forEach((t,n)=>{const r=`[Text#${n+1}]`;e.includes(r)&&(e=e.replace(r,t))}),n=e}n.length>0&&x?.add(n),t({input:n,role:q?"bash":"user",images:r,ideContext:Ie?I_(Ie):void 0}),F(!1),U(!1),H(""),Oe(),ae([])},[t,d,L,e,q,le,ie,x,Re,Oe]),ze=J(t=>{const r=s(process.cwd(),t);let o;if(i&&""!==l){const t=e.lastIndexOf("@");o=-1!==t?e.substring(0,t+1)+r+" ":r+" "}else o=`${e}${r} `;n(o),a(!1),u(""),D(e=>e+1)},[n,a,e,i,l,u]),Ue=J(()=>{a(!1),u("")},[a,u]),We=J(t=>{if("/resume"===t)x?.add(t),we(-1),be(""),pe(e),U(!1),H(""),re(!0),n(""),D(e=>e+1);else{const e=Object.values(Bk).includes(t);U(!1),H(""),e?(x?.add(t),we(-1),be(""),n(""),D(e=>e+1),d&&d(t)):(n(t+" "),D(e=>e+1))}},[d,n,e,x]),Ge=J(e=>{U(!1),H(""),n(e+" "),D(e=>e+1)},[n]),He=J(()=>{U(!1),H(""),n(""),we(-1),be(""),D(e=>e+1)},[n]),Qe=J(e=>{re(!1),n(""),pe(""),we(-1),be(""),D(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),Ve=J(()=>{re(!1),n(me),we(-1),be(""),D(e=>e+1)},[me,n]),Ke=J(e=>{Ee.current=e,fe.current=void 0},[]),Ye=Y(()=>{const t=Le&&("OPEN"===Le.state||"MERGED"===Le.state);return"auto-accept"===k||"plan"===k||Ne||t?!L&&!ee:!L&&0===e.length&&!q&&!ee},[L,e,q,ee,k,Ne,Le]),Je=V(new Map),Xe=Y(()=>le.map((e,t)=>{if(Je.current.has(e))return Je.current.get(e)??null;const n=saveTempImage(e,t+1);return Je.current.set(e,n),n}),[le]),Ze=__name(()=>L||i||z||ee||j?0:Ye||P||q?3:4,"getBottomMargin");return G.createElement(X,{width:"100%",flexDirection:"column",marginBottom:Ze()},!ee&&G.createElement(X,{flexDirection:"column",width:"100%"},G.createElement(ImageRowsDisplay,{detectedImages:le,selectedImageIndex:ue,imageTempPaths:Xe,termWidth:De,inHistory:-1!==ye}),G.createElement(Z,{color:q?$n.GREEN:$n.GRAY},ve.line.repeat(De)),G.createElement(TextInput,{key:M,value:e,placeholder:Ce?"Save and close the editor to continue...":o,onChange:je,onSubmit:()=>{if(!he.current)return Date.now()-oe.current<100?(oe.current=0,void Fe()):void(i||z||ee||Ce||Be());he.current=!1},showCursor:!Ce&&r&&-1===ue,onCursorChange:Ke,initialCursor:fe.current,prefix:`${q?"!":ve.pointer} `,prefixColor:q?$n.GREEN:$n.WHITE}),G.createElement(Z,{color:q?$n.GREEN:$n.GRAY},ve.line.repeat(De))),L&&G.createElement(M_,null),j&&G.createElement(X,{paddingTop:1},G.createElement(Z,{color:$n.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&G.createElement(E_,{onSelectFile:ze,onClose:Ue,searchQuery:l}),z&&G.createElement(Wk,{onSelectCommand:We,onInsertCommand:Ge,onClose:He,searchQuery:W}),ee&&G.createElement(P_,{onSelectSession:Qe,onClose:Ve}),!z&&(Ye||P)&&G.createElement(x_,{termWidth:De,indicatorText:R_(Ne,Ie,De),isIDEIndicator:N_(Ne,Ie),permissionMode:k,prInfo:Le,tasteLearning:p,contextUsage:m,connectionIndicator:$e,pendingExitKey:P,updateStatus:S,updateFailedInfo:E,currentProvider:v,showProviderInfo:C,isBashMode:q,shareInfo:h,showShareNotification:f,unshareNotificationMessage:y,tasteNotificationMessage:w}),ke&&G.createElement(X,{paddingLeft:1,flexDirection:"column"},G.createElement(Z,{color:$n.YELLOW},ke)))},"InputBox");Ft(),os(),rr();var L_=__name(({messages:e})=>0===e.length?null:G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(X,{marginBottom:0},G.createElement(Z,{color:On,inverse:!0},` Queued (${e.length}) `)),e.map((e,t)=>G.createElement(X,{key:t},G.createElement(Z,{color:$n.DIM},ve.pointerSmall," "),G.createElement(Z,{color:$n.DIM},truncateString({text:e.displayMessage??e.input,maxChars:80}))))),"QueuedMessages"),O_=G.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:p=0,contextUsage:g,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:E,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:T,permissionMode:_,onToggleAutoAccept:x,hintMessage:P,historyManager:A,pendingExitKey:I,onResetPendingExitKey:N,onDoubleEscapeEmpty:R,retryAttempt:$,onAltP:M})=>{const[D,L]=Q(0),O=V(s);return K(()=>{I&&s!==O.current&&s.length>0&&N?.(),O.current=s},[s,I,N]),K(()=>{if(!t)return void L(0);const e=setInterval(()=>{L(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),G.createElement(X,{flexDirection:"column"},G.createElement(L_,{messages:e}),G.createElement(X,{flexDirection:"row",justifyContent:"space-between"},G.createElement(X,{flexDirection:"column"},(t||n.isExecuting)&&null===$&&G.createElement(l_,{tokens:p,timeElapsed:D,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),P&&G.createElement(X,{marginLeft:1},G.createElement(Z,{color:$n.DIM}," ","⎿"," ","Tip: ",P)))),G.createElement(D_,{input:s,setInput:o,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:g,tasteLearning:h,tasteUsage:f,shareInfo:y,showShareNotification:w,unshareNotificationMessage:S,tasteNotificationMessage:E,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:T,permissionMode:_,onToggleAutoAccept:x,hintMessage:P,historyManager:A,pendingExitKey:!I||t||n.isExecuting?null:I,onDoubleEscapeEmpty:R,onAltP:M,isProcessing:t}))});Ft(),ks(),Ns(),br(),vr();var q_=__name(({onComplete:e,onCancel:t})=>{const[n,r]=Q(!1),[s,o]=Q(""),{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:p}=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 ne((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.");p()}}),n?G.createElement(fr,{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}`)}}):G.createElement(xs,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");async function discoverOAuthMetadata(e){const t=new d(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:cE,capabilities:{},clientInfo:uE}})});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}Ft(),Ft(),EE(),gE(),TE(),vE(),_E(),DE(),LE(),FE(),Ft(),LE(),FE(),bE(),ME(),Ft(),AE(),gE(),Cn(),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient"),rr();var F_=__name(({onClose:e})=>{const[t,n]=Q([]),[r,s]=Q(!0),[o,i]=Q(0),[a,l]=Q("list"),[u,d]=Q(null),m=J(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)}},[]);K(()=>{m()},[m]);const p=Y(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),g=p[o]??null;ne((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===p.length)return;const e=Math.max(0,p.length-1);i(t=>Math.min(e,t+1)),d(null)}n.return&&g&&(l("actions"),d(null))}});const h=__name(e=>{switch(e){case"connected":return G.createElement(Z,{color:$n.GREEN},ve.tick);case"authenticated":return G.createElement(Z,{color:$n.CYAN},ve.tick);case"requires_auth":return G.createElement(Z,{color:$n.YELLOW},ve.warning);case"error":return G.createElement(Z,{color:$n.RED},ve.cross);default:return G.createElement(Z,{color:$n.GRAY},ve.circle)}},"getStatusIcon"),f=__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"),y=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),w=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),S=__name(async e=>{if(g)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 ${g.name}...`,color:$n.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:g.name,enabled:!0,scope:g.scope}))return void d({text:`${ve.cross} Failed to enable ${g.name}, server may no longer exist in ${g.scope} scope`,color:$n.YELLOW});await m(),d({text:`${ve.tick} Enabled ${g.name}`,color:$n.GREEN})}catch(e){d({text:`${ve.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:$n.RED})}}else{d({text:`Disabling ${g.name}...`,color:$n.CYAN,loading:!0});try{const e=getMcpConnectionManager();if(!await updateMcpServerStatus({name:g.name,enabled:!1,scope:g.scope}))return void d({text:`${ve.cross} Failed to disable ${g.name}, server may no longer exist in ${g.scope} scope`,color:$n.YELLOW});await e.disconnectServer(g.name),await m(),d({text:`${ve.tick} Disabled ${g.name}`,color:$n.GREEN})}catch(e){d({text:`${ve.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:$n.RED})}}else l("confirm-remove");else{if(!g.config.oauth)return void d({text:"No OAuth configured for this server",color:$n.YELLOW});d({text:`Authenticating ${g.name}...`,color:$n.CYAN,loading:!0});try{const e={authorizationUrl:g.config.oauth.authorizationUrl,tokenUrl:g.config.oauth.tokenUrl,clientId:g.config.oauth.clientId,clientSecret:g.config.oauth.clientSecret,scopes:g.config.oauth.scopes},t=await performOAuthFlow(g.name,e,{onStatus:__name(()=>{},"onStatus")});if(t.success){d({text:`${ve.tick} Authenticated with ${g.name}`,color:$n.GREEN});try{const e=getMcpConnectionManager();await e.ensureServerConnection(g.name)}catch{}await m()}else d({text:`${ve.cross} Auth failed: ${t.error}`,color:$n.RED})}catch(e){d({text:`${ve.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:$n.RED})}}else{d({text:`Connecting ${g.name}...`,color:$n.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.ensureServerConnection(g.name),d({text:`${ve.tick} Connected to ${g.name}`,color:$n.GREEN}),await m()}catch(e){d({text:`${ve.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:$n.RED})}}else d({text:"Already authenticated",color:$n.GREEN});else d({text:"Already connected",color:$n.GREEN});else l("list")},"handleActionSelect"),E=__name(async e=>{if(g)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===g.status&&await e.disconnectServer(g.name),await removeMcpServer({name:g.name,scope:g.scope}),l("list"),await m(),i(e=>Math.min(e,Math.max(0,p.length-2)))}catch(e){d({text:`${ve.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:$n.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Mn,bold:!0},"Manage MCP servers"),G.createElement(Z,{color:$n.DIM},"Loading..."));if("confirm-remove"===a&&g)return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:$n.RED,bold:!0},"Remove ",g.name,"?"),G.createElement(Z,{color:$n.DIM},"This will remove the server from ",g.scope," config."),G.createElement(X,{marginTop:1},G.createElement(et,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:E,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY}," ",t)})),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&g){const e=[],t="disabled"===g.status,n="connected"===g.status,r="authenticated"===g.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&&g.config.oauth&&r&&e.push({label:"Authenticated",value:"authenticated"}),t||!g.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"}),G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Mn,bold:!0},g.name),G.createElement(X,null,h(g.status),G.createElement(Z,{color:$n.DIM}," ",f(g))),G.createElement(X,{marginTop:1},G.createElement(et,{items:e,onSelect:S,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:$n.WHITE},e?">":" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.WHITE:$n.GRAY}," ",t)})),u&&G.createElement(X,{marginTop:1},u.loading&&G.createElement(Z,{color:u.color},G.createElement(xe,{type:"dots"})," "),G.createElement(Z,{color:u.color},u.text)),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"↑↓ navigate · Enter to select · Esc to go back")))}let v=null;return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:Mn,bold:!0},"Manage MCP servers"),G.createElement(Z,{color:$n.DIM},t.length," ",1===t.length?"server":"servers"),0===t.length?G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(Z,{color:$n.DIM},"No MCP servers configured."),G.createElement(Z,{color:$n.DIM},'Use "cmd mcp add" to add a server.'),G.createElement(Z,{color:$n.DIM},"Docs: https://commandcode.ai/docs/mcp")):G.createElement(X,{marginTop:1,flexDirection:"column"},p.map((e,t)=>{const n=e.scope!==v;v=e.scope;const r=t===o;return G.createElement(G.Fragment,{key:e.name},n&&G.createElement(X,{marginTop:0===t?0:1},G.createElement(Z,{bold:!0},y(e.scope)),G.createElement(Z,{color:$n.DIM}," (",w(e.scope),")")),G.createElement(X,{paddingLeft:1},G.createElement(Z,{color:r?$n.WHITE:$n.GRAY},r?"› ":" "),G.createElement(Z,{color:r?$n.WHITE:void 0,bold:r},e.name),G.createElement(Z,{color:$n.DIM}," · "),h(e.status),G.createElement(Z,{color:"connected"===e.status?$n.GREEN:"authenticated"===e.status?$n.CYAN:"requires_auth"===e.status?$n.YELLOW:$n.GRAY}," ",f(e))))})),u&&G.createElement(X,{marginTop:1},u.loading&&G.createElement(Z,{color:u.color},G.createElement(xe,{type:"dots"})," "),G.createElement(Z,{color:u.color},u.text)),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Ft(),Aw(),zt(),Sn(),rr();var j_=__name(({onClose:e})=>{const[t,n]=Q([]),[r,s]=Q(0),[o,i]=Q(!0),[a,l]=Q(null);K(()=>{__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(ne((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 G.createElement(X,{paddingLeft:1,paddingTop:1},G.createElement(Z,{color:$n.DIM},"Loading memory files..."));if(a)return G.createElement(X,{paddingLeft:1,paddingTop:1},G.createElement(Z,{color:$n.RED},ve.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 G.createElement(X,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:$n.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},G.createElement(X,null,G.createElement(Z,{color:$n.WHITE,bold:!0},"Select memory to edit:")),G.createElement(X,{columnGap:4,marginTop:1},G.createElement(X,{flexDirection:"column"},m.map((e,t)=>G.createElement(Z,{key:t,color:r===t?$n.WHITE:$n.DIM},r===t?`${dn} `:" ",e.label))),G.createElement(X,{flexDirection:"column"},m.map((e,t)=>G.createElement(Z,{key:t,color:r===t?$n.WHITE:$n.DIM},e.description)))))},"MemorySelector");Ft(),zt(),Tv(),$r(),vr(),rr(),Ft(),rr();var B_=at()?"⠶":"#";function AssistantMessage({content:e}){return G.createElement(X,null,G.createElement(Z,{color:Hn},B_),G.createElement(X,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},G.createElement(Markdown,null,e)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let s=$n.GREEN,o=ve.tick,i="default",a=t||"(No output)";n&&(s=$n.YELLOW,o=ve.arrowRight,i=$n.YELLOW,a="Executing…"),r&&(s=$n.RED,o=ve.cross,i=$n.RED);const l=Y(()=>buildTreeConnectors(a),[a]);return G.createElement(X,null,G.createElement(Z,{color:s},o),G.createElement(X,{flexDirection:"column",marginLeft:1},G.createElement(X,null,G.createElement(Z,{color:$n.GRAY},"$ "),G.createElement(Z,{color:s,bold:!0},e)),G.createElement(X,{columnGap:1,marginLeft:1},G.createElement(Z,{color:er},l),G.createElement(Z,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?$n.YELLOW:void 0,s=Y(()=>buildTreeConnectors(e),[e]);return G.createElement(X,{flexDirection:"column",marginBottom:0,marginTop:-1},G.createElement(X,{columnGap:1},G.createElement(Z,{color:er},s),G.createElement(X,{flexGrow:1,flexShrink:1,minWidth:0},G.createElement(Z,{color:r},e))),t&&G.createElement(X,{marginLeft:3},G.createElement(Z,{color:$n.DIM},"See ",t)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return G.createElement(X,null,G.createElement(Z,{color:$n.RED},t?ve.pointer:ve.warning),G.createElement(X,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?G.createElement(Z,{color:$n.RED,wrap:"wrap"},e):G.createElement(Markdown,{color:$n.RED},e)))}function IDEStatusMessage({status:e,ide:t,details:n}){return G.createElement(X,{flexDirection:"column"},G.createElement(X,null,"connected"===e&&G.createElement(Z,null,G.createElement(Z,{color:$n.GREEN},ve.tick),G.createElement(Z,null," Connected to "),G.createElement(Z,{color:$n.CYAN},t)),"installed"===e&&G.createElement(Z,null,G.createElement(Z,{color:$n.GREEN},ve.tick),G.createElement(Z,null," Installed for "),G.createElement(Z,{color:$n.CYAN},t)),"needs_reload"===e&&G.createElement(Z,null,G.createElement(Z,{color:$n.YELLOW},ve.circle),G.createElement(Z,null," "),G.createElement(Z,{color:$n.CYAN},t),G.createElement(Z,null," extension needs reload")),"failed"===e&&G.createElement(Z,null,G.createElement(Z,{color:$n.RED},ve.cross),G.createElement(Z,null," Install failed")),"not_in_ide"===e&&G.createElement(Z,null,G.createElement(Z,{color:$n.YELLOW},ve.circle),G.createElement(Z,null," Not in IDE"))),n?.map((e,t)=>G.createElement(Z,{key:t,color:$n.DIM}," ",e)))}function AutoCompactMessage({content:e}){return G.createElement(X,null,G.createElement(Z,{color:$n.DIM},ve.info),G.createElement(X,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},G.createElement(Z,{color:$n.DIM},e)))}function TasteSkipMessage(){return G.createElement(X,null,G.createElement(X,{flexShrink:0},G.createElement(Z,{backgroundColor:Dn.BADGE_BG,color:Dn.BADGE_FG,bold:!0},pk)),G.createElement(Z,{color:$n.DIM}," Skipped. Run "),G.createElement(Z,{color:Jn.CODE},"/learn-taste"),G.createElement(Z,{color:$n.DIM}," or "),G.createElement(Z,{color:Jn.CODE},"cmd learn-taste"),G.createElement(Z,{color:$n.DIM}," anytime."))}function InfoMessage({content:e,metadata:t}){return t?.isTasteSkip?G.createElement(TasteSkipMessage,null):t?.isAutoCompact?G.createElement(AutoCompactMessage,{content:e}):G.createElement(X,null,G.createElement(Z,{color:$n.DIM},ve.info),G.createElement(X,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},G.createElement(Z,{color:$n.DIM},e)))}__name(AssistantMessage,"AssistantMessage"),Ft(),rr(),__name(BashMessage,"BashMessage"),Ft(),rr(),__name(CommandResultMessage,"CommandResultMessage"),Ft(),rr(),__name(ErrorMessage,"ErrorMessage"),Ft(),rr(),__name(IDEStatusMessage,"IDEStatusMessage"),Ft(),rr(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(InfoMessage,"InfoMessage"),Ft(),Ft(),zt();rr(),aE(),Ft(),$r();var z_="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]:[z_]}function getInvokedCommandName(){try{const e=getBinNames(),n=process.argv[1];if(!n)return e[0]||z_;const r=t.basename(n).replace(/\.(m?[jt]s|cjs)$/,"");return e.includes(r)?r:e[0]||z_}catch{return z_}}function HelpMessage(){const e=getInvokedCommandName(),t=Y(()=>eE.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return G.createElement(X,{flexDirection:"column",paddingY:1},G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(X,null,G.createElement(Z,{bold:!0},"Command Code"),G.createElement(Z,{color:$n.GRAY}," v","0.18.4")),G.createElement(Z,{color:$n.GRAY},Yb)),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Usage"),G.createElement(X,{paddingLeft:2},G.createElement(Z,null,e," <command> [options]"))),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Options"),G.createElement(X,{flexDirection:"column",paddingLeft:2},Zb.map(t=>G.createElement(X,{key:t.key},G.createElement(Z,null,t.key.replace(/^cmd/,e).padEnd(Jb)),G.createElement(Z,{color:$n.GRAY},t.description))))),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Commands"),G.createElement(X,{flexDirection:"column",paddingLeft:2},tE.map(t=>G.createElement(X,{key:t.key},G.createElement(Z,null,t.key.replace(/^cmd/,e).padEnd(Jb)),G.createElement(Z,{color:$n.GRAY},t.description))))),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Slash Commands"),G.createElement(X,{flexDirection:"column",paddingLeft:2},t.map(e=>G.createElement(X,{key:e.key},G.createElement(Z,null,e.key.padEnd(Jb)),G.createElement(Z,{color:$n.GRAY},e.description))))),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Keyboard Shortcuts"),G.createElement(X,{flexDirection:"column",paddingLeft:2},Xb.map(e=>G.createElement(X,{key:e.key},G.createElement(Z,null,e.key.padEnd(Jb)),G.createElement(Z,{color:$n.GRAY},e.description))))),G.createElement(X,{flexDirection:"column",marginBottom:1},G.createElement(Z,{bold:!0},"Examples"),G.createElement(X,{flexDirection:"column",paddingLeft:2},rE.map(t=>G.createElement(X,{key:t.key},G.createElement(Z,null,t.key.replace(/^cmd/,e).padEnd(Jb)),G.createElement(Z,{color:$n.GRAY},t.description))))),G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.CYAN},ve.pointer),G.createElement(Z,{color:$n.GRAY}," ",sE.replace(/cmd/,e))),G.createElement(X,{flexDirection:"column"},G.createElement(Z,{bold:!0},"Links"),G.createElement(X,{flexDirection:"column",paddingLeft:2},nE.map(e=>G.createElement(X,{key:e.key},G.createElement(Z,null,e.key.padEnd(Jb)),G.createElement(Z,{color:$n.CYAN},e.description))))))}function SystemMessage({content:e,metadata:t}){if(e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS"))return G.createElement(HelpMessage,null);if("CONTEXT"===e){const e=t?.analysis;if(e)return G.createElement(ContextMessage,{analysis:e})}return G.createElement(X,{flexDirection:"column"},G.createElement(Z,{wrap:"wrap"},G.createElement(Markdown,null,e)))}__name(getBinNames,"getBinNames"),__name(getInvokedCommandName,"getInvokedCommandName"),vr(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),Ft(),Sn(),Ms(),rr();var U_={"Interrupted by user":"Interrupted by user","Insufficient credits":cn};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&&U_[e]||e,l=null!=t?t.length:n,u=V(null);null===u.current&&t&&t.length>0&&(u.current=t.map((e,t)=>saveTempImage(e,t+1)));const d=u.current??[];return G.createElement(X,{flexDirection:"column"},G.createElement(X,{backgroundColor:i?void 0:Gn.BG,paddingRight:1},G.createElement(Z,{color:i?$n.RED:Gn.POINTER,bold:!i},ve.pointer),G.createElement(X,{marginLeft:1},G.createElement(Z,{color:i?$n.RED:$n.WHITE,wrap:"wrap"},a))),l>0&&G.createElement(X,{marginLeft:1},G.createElement(Z,{color:$n.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 G.createElement(UserMessage,{content:e.input,images:t})}return"assistant"===e.role?G.createElement(AssistantMessage,{content:e.input}):"tool"===e.role?G.createElement(ToolMessage,{name:Sv(e.name||""),input:e.input,output:e.output||"",isPending:fv(e),hasError:hv(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?G.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:fv(e),hasError:hv(e)}):"system"===e.role?G.createElement(SystemMessage,{content:e.input,metadata:e.metadata}):"info"===e.role?G.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?G.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?G.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?G.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName(e){const t=Object.values(Nt).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 G.createElement(X,{marginBottom:1},G.createElement(Z,{color:Wn},s),G.createElement(BracketedText,{text:n,color:Wn}),G.createElement(Z,{color:Wn},s))}__name(UserMessage,"UserMessage"),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName,"getModelShortName"),__name(TranscriptDivider,"TranscriptDivider");var W_=G.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=Y(()=>DT(l),[l]),d=Y(()=>jT(l),[l]),m=Y(()=>getPackageJson().version||"0.0.0",[]),p=Y(()=>getGitHeaderInfo(),[]),g=Y(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),h=s?getModelShortName(s):"sonnet-4.6",f="taste-1",y=isInternalTeamFlagEnforced()?" · co":"";return G.createElement(ee,{items:a,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return G.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:l});if("header"===e)return"compact"===d?G.createElement(X,{key:"header",marginBottom:1,flexDirection:"row"},G.createElement(X,{width:qT,flexShrink:0},G.createElement(st,{name:"vice"},G.createElement(Z,null,OT))),G.createElement(X,{flexDirection:"column",marginLeft:2},G.createElement(X,null,G.createElement(Z,{bold:!0},"Command Code"),G.createElement(Z,{color:Wn}," ","v",m)),G.createElement(Z,{color:Wn},"models: ",h," · ",f,y),G.createElement(Z,{color:Wn},g,p&&p.isLocal&&p.branch&&` (${p.branch})`))):G.createElement(X,{key:"header",marginBottom:1,flexDirection:"column"},G.createElement(st,{name:"vice"},G.createElement(Z,null,u.trimEnd())),G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(X,null,G.createElement(Z,{color:Wn},"# "),G.createElement(Z,{bold:!0},"Command Code"),G.createElement(Z,{color:Wn}," v",m)),G.createElement(Z,{color:Wn},"# models: ",h," · ",f,y),G.createElement(X,null,G.createElement(Z,{color:Wn},"# ",g,p&&p.isLocal&&p.branch&&G.createElement(Z,{color:Wn}," ","(branch:"," ",p.branch,")")))));const t=e,n=renderFeedEntry(t,r);return G.createElement(X,{key:t.id,paddingBottom:1,width:"90%"},n)})});Ft(),Tv(),Cr(),rr();var G_=H(__name(function LiveAgentStatusInner2({entry:e}){const t=Sv(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]=Q(".");return K(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),G.createElement(X,{flexDirection:"column",marginBottom:1,width:"90%"},G.createElement(X,null,G.createElement(Z,{backgroundColor:Bn.BG,color:Bn.FG,bold:!0},` ${t} `),s&&G.createElement(Z,null," ","(",s,")")),G.createElement(X,{columnGap:1,marginLeft:1},G.createElement(Z,null,"⎿"," "),G.createElement(Z,{color:$n.GRAY},"Running (",formatTime2(i)," | ",formatTokens(o),")",l)),a.length>0&&G.createElement(X,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=Sv(e.name);return G.createElement(X,{key:t,columnGap:1},G.createElement(Z,{color:$n.GRAY},"⎿"),G.createElement(Z,{color:$n.GRAY}," ",n),e.input&&G.createElement(Z,{color:$n.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),H_=H(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:G.createElement(G_,{entry:e})},"LiveAgentStatus"));function getModelOptions(){return Object.values(Nt).map(e=>({label:e.label,value:e.id,modelName:e.name,description:e.description}))}Ft(),zt(),rr(),__name(getModelOptions,"getModelOptions");var Q_=__name(({onSelect:e,onCancel:t,currentModel:n})=>{const r=getModelOptions(),s=__name(t=>{e(t.value)},"handleSelect");ne((e,n)=>{n.escape&&t()});const o=n?r.findIndex(e=>e.value===n):0;return G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(X,null,G.createElement(Z,{color:Mn,bold:!0},"Select model")),G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"Switch between Command Code models. Applies to this session and future Command Code sessions.")),G.createElement(et,{items:r,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:e?$n.GREEN:$n.GRAY},e?ve.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>{const s=r.find(e=>e.label===t),o=s?.value===n,i=e?$n.GREEN:$n.GRAY;return G.createElement(X,null,G.createElement(Z,{color:i},` ${(s?.label||t).padEnd(24)}`),G.createElement(Z,{color:$n.DIM},s?.description),o&&G.createElement(Z,{color:$n.GREEN}," ",ve.tick))}}),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press "),G.createElement(Z,{color:$n.DIM,bold:!0},"Esc"),G.createElement(Z,{color:$n.DIM}," to cancel")))},"ModelSelector");Ft(),vr(),rr();var V_=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),s=__name(t=>{e(t.value)},"handleSelect");ne((e,n)=>{n.escape&&t()});const o=n?r.findIndex(e=>e.value===n):0,i=n&&-1===o;return G.createElement(X,{flexDirection:"column",paddingX:0,width:"100%"},G.createElement(X,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},G.createElement(X,null,G.createElement(Z,{bold:!0},"Select AI Provider")),n&&G.createElement(X,{flexDirection:"row"},G.createElement(Z,{color:$n.DIM},"Current: "),G.createElement(Z,{color:$n.GREEN},getProviderDisplayName(n)),i&&G.createElement(Z,{color:$n.YELLOW}," [OAuth enforced]"))),G.createElement(X,{marginBottom:0},G.createElement(Z,{color:$n.DIM},"Available Providers:")),G.createElement(et,{items:r,onSelect:s,initialIndex:o>=0?o:0,indicatorComponent:({isSelected:e})=>G.createElement(Z,{color:e?$n.CYAN:$n.GRAY,bold:e},e?ve.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>G.createElement(Z,{color:e?$n.CYAN:$n.GRAY,bold:e},` ${t}`)}),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=Q(0);if(K(()=>{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 G.createElement(X,{marginBottom:1},G.createElement(Z,{color:Yn,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Ft(),rr(),__name(RetryMessage,"RetryMessage"),Ft(),rS(),os(),Sn(),rr();var K_=[{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"}],Y_=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=Y(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[s,o]=Q(Math.max(0,r.length-1)),[i,a]=Q(Math.max(0,r.length-8)),[l,u]=Q("checkpoint"),[d,m]=Q(null),[p,g]=Q(0),h=Y(()=>{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]),f=Y(()=>h?K_:K_.filter(e=>"conversation"===e.mode),[h]);if(K(()=>{if(r.length>0){const e=r.length-1;o(e),a(Math.max(0,r.length-8))}},[r.length,8]),ne((e,h)=>{h.escape?"mode"===l?(u("checkpoint"),m(null),g(0)):n():"checkpoint"===l?h.upArrow?o(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):h.downArrow?o(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):h.return&&r.length>0&&(m(r[s]),u("mode"),g(0)):"mode"===l&&(h.upArrow?g(e=>Math.max(0,e-1)):h.downArrow?g(e=>Math.min(f.length-1,e+1)):h.return&&d&&f[p]&&t({messageId:d.messageId,mode:f[p].mode}))}),0===r.length)return G.createElement(X,{flexDirection:"column",paddingLeft:2,paddingTop:1},G.createElement(Z,{color:Mn,bold:!0},"Rewind"),G.createElement(Z,{color:$n.DIM},"No checkpoints available. Start a conversation to create checkpoints."),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press "),G.createElement(Z,{color:$n.DIM,bold:!0},"Esc"),G.createElement(Z,{color:$n.DIM}," to close")));if("mode"===l&&d)return G.createElement(X,{flexDirection:"column",paddingLeft:2,paddingTop:1},G.createElement(Z,{color:Mn,bold:!0},"Rewind"),G.createElement(X,{marginBottom:1},G.createElement(Z,{color:$n.DIM},"Restore to: "),G.createElement(Z,{color:$n.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),G.createElement(X,{flexDirection:"column"},f.map((e,t)=>{const n=p===t,r=t===f.length-1;return G.createElement(X,{key:e.mode,flexDirection:"column"},G.createElement(X,{flexDirection:"row"},G.createElement(Z,{color:n?Mn:void 0},n?`${dn} `:" "),G.createElement(X,{flexDirection:"column"},G.createElement(Z,{color:n?Mn:$n.WHITE},e.label),G.createElement(Z,{color:$n.DIM},e.description))),!r&&G.createElement(Z,null," "))})),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press "),G.createElement(Z,{color:$n.DIM,bold:!0},"Enter"),G.createElement(Z,{color:$n.DIM}," to confirm, "),G.createElement(Z,{color:$n.DIM,bold:!0},"Esc"),G.createElement(Z,{color:$n.DIM}," to go back")));const y=r.slice(i,i+8);return G.createElement(X,{flexDirection:"column",paddingLeft:2,paddingTop:1},G.createElement(Z,{color:Mn,bold:!0},"Rewind"),G.createElement(Z,{color:$n.DIM},"Select a checkpoint to restore your session"),r.length>8&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),G.createElement(X,{marginTop:1}),G.createElement(X,{flexDirection:"column"},y.map((e,t)=>{const n=i+t,o=s===n,a=e.filesModified.length,l=t===y.length-1,u=n===r.length-1;return G.createElement(X,{key:e.messageId,flexDirection:"column"},G.createElement(X,{flexDirection:"row"},G.createElement(Z,{color:o?Mn:void 0},o?`${dn} `:" "),G.createElement(X,{flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{color:o?Mn:$n.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),G.createElement(Z,{color:$n.DIM}," • "),G.createElement(Z,{color:$n.DIM},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),G.createElement(Z,{color:$n.DIM},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&G.createElement(Z,null," "))})),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Press "),G.createElement(Z,{color:$n.DIM,bold:!0},"Enter"),G.createElement(Z,{color:$n.DIM}," to select, "),G.createElement(Z,{color:$n.DIM,bold:!0},"Esc"),G.createElement(Z,{color:$n.DIM}," to cancel")))},"RewindSelector");Ft(),Cn(),Ft(),Ft(),gC();var J_=__name(e=>{const[t,n]=Q(e),[r,s]=Q(null);return K(()=>{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 mC.on("reset",t),mC.on("new-event",r),()=>{mC.off("reset",t),mC.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:s}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new Yy({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={[vt.PROJECT_SLUG]:xv.getCurrentProjectDirName(),[vt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return s&&(i[vt.OAUTH_TOKEN]=`Bearer ${s}`,o&&(i[vt.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}Ft(),Ft(),vC(),bw(),Cs(),BS(),Cn(),gC(),Ft(),Cn(),gC(),BS(),Ft(),Ft(),zt(),bw(),Cs(),Lv(),Cn(),Sr(),Cr(),__name(createRequestClient,"createRequestClient"),Ft(),BS(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Ft(),Ft(),zt(),Cn(),an(),gC(),Ft();var X_="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 buildRequestBody2(e){return{config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:e}],model:`anthropic:${X_}`,max_tokens:200,temperature:.7,stream:!0},threadId:Se()}}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}`),mC.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()}`),mC.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function processStream(e){let t;try{t=Ge.fromReadableStream(e),dlog("[ObserverAPI] created MessageStream")}catch(e){throw dlog(`[ObserverAPI] MessageStream creation failed: ${e instanceof Error?e.message:String(e)}`),e}const n=createInsightEmitter();t.on("text",e=>{n.addText(e)});try{await t.finalMessage(),dlog(`[ObserverAPI] stream complete, ${n.getChunkCount()} chunks received`)}catch(e){throw dlog(`[ObserverAPI] stream failed: ${e instanceof Error?e.message:String(e)}`),e}n.emitRemaining()}async function callObserverAPI(e,t,n){dlog(`[ObserverAPI] calling ${Ct.ALPHA.GENERATE} with model: ${X_}`);const r=buildRequestBody2(n);let s;try{s=await e.post({endpoint:Ct.ALPHA.GENERATE,body:r,headers:t,stream:!0}),dlog("[ObserverAPI] got response stream")}catch(e){throw dlog(`[ObserverAPI] request failed: ${e instanceof Error?e.message:String(e)}`),e}await processStream(s),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(mC.observerHasRun)return;mC.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(mC.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)}`),mC.addEvent({type:"progress",message:"Continuing without live observations..."})}}__name(buildObserverPrompt,"buildObserverPrompt"),__name(buildRequestBody2,"buildRequestBody"),__name(createInsightEmitter,"createInsightEmitter"),__name(processStream,"processStream"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var Z_=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(h.homedir(),".claude","projects");await M.access(r);const s=process.cwd().replace(/\//g,"-");dlog(`[Import] scanning project: ${s}`);const o=(await M.readdir(r)).filter(e=>e===s);for(const s of o){const o=e.join(r,s);try{if(!(await M.stat(o)).isDirectory())continue;const r=(await M.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 M.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{mC.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&mC.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{mC.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 M.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{mC.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"]||[],p=d.codex||[],g=d.cursor||[],h=m.length+p.length+g.length;if(dlog(`[Import] findNewSessions returned: claude-code=${m.length} new, codex=${p.length} new, cursor=${g.length} new`),0===h){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}`);mC.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(p.length>0){const e=(await this.findCodexSessions()).filter(e=>p.includes(e.id));r.push(...e)}if(g.length>0){const e=(await this.findCursorSessions()).filter(e=>g.includes(e.id));s.push(...e)}const f=n.length+r.length+s.length;dlog(`[Import] total sessions: ${f} (claude-code: ${n.length}, codex: ${r.length}, cursor: ${s.length})`),mC.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const y=[{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 y){mC.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 w=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${w.length} batches`);const S=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});mC.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${w.length} batch${1===w.length?"":"es"}`});try{const o=getApiBaseUrl(),i=new Yy({baseUrl:o});let a=!0;for(let e=0;e<w.length;e++){const t=w[e],n=e+1,r=w.length;r>1&&mC.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const s=this.formatBatchLearning(t),o=new fC({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}`),mC.markLearningComplete(),await S,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),mC.addEvent({type:"error",message:o}),{success:!1,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:f,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 mC.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:f,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),mC.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 M.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")}};gC();var ex=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),tx=__name(e=>{const[t,n]=Q({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return K(()=>{mC.reset(),mC.markImportStarted(),(async()=>{try{const t=await Promise.race([Z_.importAndLearn(),ex(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");Ft();var nx=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{ne((r,s)=>{n&&(s.escape&&e(),(s.return||"\n"===r)&&t())})},"useKeyboardInput");Ft(),Cn();var rx=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=Q(null),[s,o]=Q(null),i=V(!1);return K(()=>{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{mC.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{mC.reset(),e()}}Ft(),Cn(),Ft(),Cn(),gC(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var sx=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=V(n),s=J(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),o=J(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=J(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=J(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=J(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");Ft(),Cn();var ox=__name(({conditions:e,autoLearn:t})=>{const[n,r]=Q("checking"),s=V(!1);return K(()=>{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]),K(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Ft(),Ft(),rr();var ix=__name(({error:e})=>G.createElement(X,{padding:1},G.createElement(X,{flexDirection:"column",borderColor:$n.RED,padding:1},G.createElement(X,{marginBottom:1},G.createElement(Z,null,"Error initializing onboarding: ",e)),G.createElement(X,null,G.createElement(Z,null,"Continuing without onboarding...")))),"OnboardingError");Ft(),Ft(),zt(),rr();var ax=__name(()=>`(run /${At.LEARN_TASTE} anytime)`,"getSkipHint"),lx=__name(()=>G.createElement(Z,null,"Skip for now"," ",G.createElement(Z,{color:$n.DIM},ax())),"SkipOptionText"),cx=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[s,o]=Q(1);return ne((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()}),G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:Dn.TEXT,paddingX:1,paddingY:0},G.createElement(Z,{color:Dn.TEXT,bold:!0},"Build Your Coding Taste"),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(Z,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),G.createElement(X,{marginTop:1},G.createElement(Z,null,"Want me to analyze"," ",1===e?"that session":"those sessions"," ","and build your coding taste profile?"))),G.createElement(X,{marginTop:1,flexDirection:"column"},G.createElement(X,null,G.createElement(Z,{color:1===s?Dn.TEXT:$n.GRAY},1===s?ve.pointer:" "," 1. Yes, learn from my sessions (recommended)")),G.createElement(X,null,G.createElement(Z,{color:2===s?Dn.TEXT:$n.GRAY},2===s?ve.pointer:" "," 2."," ",G.createElement(lx,null)))),G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"Use arrow keys or numbers to select, Enter to confirm")))},"ImportChoice");Ft(),Ft(),rr();var ux=__name(({error:e})=>G.createElement(X,{flexDirection:"column",borderStyle:"single",borderColor:$n.RED,paddingX:2,paddingY:1,marginBottom:2},G.createElement(Z,{color:$n.RED,bold:!0},"Oops, something went wrong:"),G.createElement(X,{marginTop:1},G.createElement(Z,null,e))),"ErrorSection");Ft(),Ft(),rr(),Ft(),Ft(),Ft(),rr();var dx=[ve.bullet,ve.squareSmallFilled,ve.lozenge,ve.star,ve.triangleRight,ve.triangleUp,ve.circleFilled,ve.pointer],mx=__name(()=>G.createElement(Z,{backgroundColor:Dn.BADGE_BG,color:Dn.BADGE_FG},pk),"TasteBadge"),px=["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"],gx=__name(()=>{const[e,t]=Q(()=>Math.floor(Math.random()*px.length));K(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*px.length))},2e3);return()=>clearInterval(e)},[]);const n=px[e];return G.createElement(Z,{color:$n.YELLOW},n,"...")},"PulsingText"),hx=__name(e=>String(e).padStart(3," "),"padNum"),fx=__name(e=>dx[e%dx.length],"getSymbol"),yx=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${hx(t)} ↓${hx(n)} (↑↓ scroll)`,"buildStatusLine"),wx=__name(({insights:e})=>{const[t,n]=Q(0),[r,s]=Q(!0),o=e.length,i=o>10,a=Math.max(0,o-10);if(K(()=>{r&&i&&n(a)},[o,r,i,a]),ne((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 G.createElement(X,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&G.createElement(Z,{color:$n.DIM},yx(o,u,d,r)),l.map((e,n)=>{const r=t+n;return G.createElement(X,{key:r,marginBottom:0},G.createElement(Z,{color:$n.DIM},fx(r)," ",e))}))},"ScrollableInsights"),Sx=__name(({label:e,message:t,active:n,complete:r,items:s,insights:o,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return G.createElement(X,{flexDirection:"column",marginBottom:0},G.createElement(mx,null),G.createElement(X,{marginTop:0},G.createElement(Z,{color:$n.DIM},"⎿"),G.createElement(X,{marginLeft:2},a?G.createElement(Z,{color:Dn.TEXT},"learned your coding taste"):G.createElement(gx,null))));const u=__name(()=>{const[e,t]=Q(!0);return K(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),G.createElement(Z,{color:$n.YELLOW},e?ve.circleFilled:ve.circle)},"PulsingDot"),d=__name(()=>r?G.createElement(Z,{color:Fn.BG},ve.square):n?G.createElement(u,null):G.createElement(Z,{color:$n.DIM},ve.circle),"getStatusIcon"),m=s.length>0||o.length>0||t||l&&l.learningCount>0;return!r||n||m?G.createElement(X,{flexDirection:"column",marginBottom:0},(n||r)&&G.createElement(X,{marginBottom:0},G.createElement(X,{marginRight:1},d()),G.createElement(Z,{color:r?$n.WHITE:n?$n.YELLOW:$n.DIM},e)),r&&t&&(!l||0===l.learningCount)&&G.createElement(X,{marginLeft:3,marginBottom:0},G.createElement(Z,{color:$n.DIM},t)),s.length>0&&G.createElement(X,{flexDirection:"column",marginLeft:1,marginBottom:0},s.map((e,t)=>G.createElement(Z,{key:t,color:$n.DIM},`${ve.bullet} ${e}`))),o.length>0&&G.createElement(wx,{insights:o}),r&&l&&l.learningCount>0&&G.createElement(X,{flexDirection:"column",marginLeft:1,marginBottom:0},G.createElement(X,{marginBottom:1,flexDirection:"row"},G.createElement(Z,null,"⎿"),G.createElement(X,{marginLeft:2},G.createElement(Z,{color:Dn.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),G.createElement(X,{flexDirection:"column",marginLeft:1},G.createElement(Z,{color:$n.DIM},ve.pointerSmall," Stored in"," ",l.storage),G.createElement(Z,{color:$n.DIM},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),bx=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return G.createElement(X,{flexDirection:"column",marginBottom:1},e.map((e,n)=>G.createElement(X,{key:e.id,marginLeft:0===n?0:3},G.createElement(Sx,{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"),Ex=__name(({steps:e})=>G.createElement(bx,{steps:e}),"ProgressSection");Ft(),rr();var vx=__name(({isImporting:e=!1,waitingForInput:t=!1})=>G.createElement(G.Fragment,null,e&&G.createElement(X,{marginTop:1},G.createElement(Z,{color:$n.DIM},"ESC to cancel")),t&&G.createElement(X,{marginTop:1},G.createElement(Z,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Ft();var Cx=[{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"}}],kx=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:s}=J_(Cx),{isImporting:o,waitingForInput:i,error:a}=tx(t);return nx({onEscape:e,onEnter:__name(()=>{i&&(a&&n?n():e())},"onEnter"),enabled:o||i}),G.createElement(X,{flexDirection:"column",padding:1},s&&G.createElement(ux,{error:s}),!s&&G.createElement(Ex,{steps:r}),G.createElement(vx,{isImporting:o,waitingForInput:i}))},"ImportProgress"),Tx=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:s,onErrorDismiss:o,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?G.createElement(cx,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?G.createElement(kx,{onComplete:r,onError:s,onErrorDismiss:o}):null,"OnboardingStepRenderer"),_x=__name(({onComplete:e,autoLearn:t=!1})=>{K(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:s}=rx({autoLearn:t,onShouldSkip:e}),{step:o,setStep:i}=ox({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=sx({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?G.createElement(ix,{error:r}):"done"===o?null:G.createElement(Tx,{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 xx=H(__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:p,showFileList:g,setShowFileList:h,showProviderSelector:f,showModelSelector:y,showMemorySelector:w,showMcpManager:S,showAgentsConfig:E,showRewindSelector:v,showLoginOverlay:C,showAddDirModal:k,showCompactModeSelector:T,authComponentInfo:_,status:x,currentProvider:P,currentModel:A,showProviderNotification:I,shareInfo:N,showShareNotification:R,unshareNotificationMessage:$,updateStatus:M,updateFailedInfo:D,permissionMode:L,hintMessage:O,pendingExitKey:q,tasteLearningEnabled:F,interactionTokens:j,contextUsage:B,historyManagerRef:z,executionState:U,contextEngineRef:W,onSubmit:H,onCommand:Q,onToggleAutoAccept:V,onResetPendingExitKey:K,onDoubleEscapeEmpty:ee,onTasteOnboardingComplete:te,permissionPanel:ne,questionPanel:re,onRewindSelect:se,onRewindCancel:oe,onLoginComplete:ie,onLoginCancel:ae,setShowProviderSelector:le,setShowModelSelector:ce,setShowMemorySelector:ue,setShowMcpManager:de,setShowAgentsConfig:me,setShowAddDirModal:pe,handleProviderSelect:ge,handleProviderCancel:he,handleModelSelect:fe,handleModelCancel:ye,handleCompactModeSelect:we,handleCompactModeCancel:Se,handleAuthSuccess:be,handleAuthCancel:Ee}){const ve=Y(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Ce=useTerminalWidth(),ke=Y(()=>"off"===o?ve:getBudgetedFeed(ve,"limited"===o?15e3:5e4),[ve,o]),Te=Y(()=>"off"===o?0:Math.max(0,ve.length-ke.length),[ve.length,ke.length,o]),_e=Y(()=>0===Te?ke:ke.filter(e=>"user"!==e.role),[ke,Te]),xe=J(()=>me(!1),[me]),Pe=J(()=>ue(!1),[ue]),Ae=J(()=>de(!1),[de]),Ie=J(()=>pe(!1),[pe]),Ne=J(()=>ce(!0),[ce]),Re=!("off"!==o||ne||re||f||y||_||w||S||E||v||C||k||T||i);return G.createElement(X,{flexDirection:"column",width:"100%"},G.createElement(W_,{staticKey:s,feed:_e,showHeader:!0,expandedToolOutput:"off"!==o,currentModel:A,hiddenCount:Te}),i&&G.createElement(_x,{onComplete:te,autoLearn:a}),t.map(e=>e.metadata?.isAgent?G.createElement(H_,{key:e.id,entry:e}):G.createElement(X,{key:e.id,marginBottom:1,width:"90%"},renderFeedEntry(e,"off"!==o))),G.createElement(RetryMessage,{attempt:l}),re,ne,"off"!==o&&G.createElement(X,{flexDirection:"column",marginTop:1},G.createElement(X,null,G.createElement(Z,{color:$n.DIM},"─".repeat(Ce))),G.createElement(X,{paddingRight:1},G.createElement(Z,{backgroundColor:Fn.BG,color:Fn.FG,bold:!0},`${mk}DETAILED TRANSCRIPT${mk}`),G.createElement(Z,{color:$n.DIM}," · "),G.createElement(Z,{bold:!0},"ctrl+o"),G.createElement(Z,{color:$n.DIM}," to toggle"),G.createElement(Z,{color:$n.DIM}," · "),G.createElement(Z,{bold:!0},"ctrl+e"),G.createElement(Z,{color:$n.DIM}," ","to"," ","limited"===o?"show all":"collapse"))),Re&&G.createElement(O_,{queuedMessages:n,isProcessing:r,executionState:U,status:x,input:u,setInput:d,onSubmit:H,showFileList:g,setShowFileList:h,fileSearchQuery:m,setFileSearchQuery:p,onCommand:Q,outputTokens:j,contextUsage:B,tasteLearning:F,shareInfo:N,showShareNotification:R,unshareNotificationMessage:$,updateStatus:M,updateFailedInfo:D,currentProvider:P,showProviderInfo:I,permissionMode:L,onToggleAutoAccept:V,hintMessage:O,historyManager:z.current,pendingExitKey:q,onResetPendingExitKey:K,onDoubleEscapeEmpty:ee,retryAttempt:l,onAltP:Ne}),f&&G.createElement(X,{marginY:1},G.createElement(V_,{onSelect:ge,onCancel:he,currentProvider:P})),y&&G.createElement(X,{marginY:1},G.createElement(Q_,{onSelect:fe,onCancel:ye,currentModel:A})),T&&G.createElement(X,{marginY:1},G.createElement(g_,{onSelect:we,onCancel:Se})),E&&G.createElement(X,{marginY:1},G.createElement(m_,{onCancel:xe})),w&&G.createElement(X,{marginY:1},G.createElement(j_,{onClose:Pe})),S&&G.createElement(X,{marginY:1},G.createElement(F_,{onClose:Ae})),v&&W.current&&G.createElement(X,{marginY:1},G.createElement(Y_,{checkpoints:W.current.listCheckpoints(),onSelect:se,onCancel:oe})),_&&G.createElement(X,{marginY:1},G.createElement(_.Component,{onSuccess:be,onCancel:Ee})),C&&G.createElement(X,{marginY:1},G.createElement(q_,{onComplete:ie,onCancel:ae})),k&&G.createElement(X,{marginY:1},G.createElement(YT,{onClose:Ie})))},"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:p,onSubmit:g,onCommand:h,input:f,setInput:y,fileSearchQuery:w,setFileSearchQuery:S,updateFailedInfo:E,handleTrust:v,handleNoTrust:C,handleToggleAutoAccept:k,handleDoubleEscapeEmpty:T,handleTasteOnboardingComplete:_,loadTasteStatus:x}){if(i.shouldExit)return null;if(o.checkingProject)return null;if(o.showTrustPrompt)return G.createElement(hT,{staticKey:s.staticKey,onTrust:v,onExit:C});if(s.showSessionSelector)return G.createElement(yT,{onSelectSession:p.onSelectSession,onNewSession:p.onNewSession});if(!o.projectTrusted)return null;const P=a.pendingQuestion?G.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:s.setStaticKey}):null,A=a.pendingPermission?G.createElement(PT,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:k}):null;return s.showLearningFeed?G.createElement(LearningView,{setShowLearningFeed:s.setShowLearningFeed,setStaticKey:s.setStaticKey,onExit:()=>i.setShouldExit(!0)}):s.showTasteConfig?G.createElement(TasteConfigView,{staticKey:s.staticKey,setShowTasteConfig:s.setShowTasteConfig,loadTasteStatus:x}):s.showSkillsConfig?G.createElement(SkillsConfigView,{staticKey:s.staticKey,setShowSkillsConfig:s.setShowSkillsConfig}):s.showContextView?G.createElement(ContextConfigView,{staticKey:s.staticKey,contextEngineRef:u,setShowContextView:s.setShowContextView,setInput:y}):s.showStatusView?G.createElement(StatusConfigView,{staticKey:s.staticKey,setShowStatusView:s.setShowStatusView,setInput:y}):G.createElement(xx,{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:f,setInput:y,fileSearchQuery:w,setFileSearchQuery:S,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,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:E,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:g,onCommand:h,onToggleAutoAccept:k,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:T,onTasteOnboardingComplete:_,permissionPanel:A,questionPanel:P,onRewindSelect:p.onRewindSelect,onRewindCancel:p.onRewindCancel,onLoginComplete:p.onLoginComplete,onLoginCancel:p.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:p.handleProviderSelect,handleProviderCancel:p.handleProviderCancel,handleModelSelect:p.handleModelSelect,handleModelCancel:p.handleModelCancel,handleCompactModeSelect:p.handleCompactModeSelect,handleCompactModeCancel:p.handleCompactModeCancel,handleAuthSuccess:p.handleAuthSuccess,handleAuthCancel:p.handleAuthCancel})}__name(renderView,"renderView");var Px=__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}=se(),{stdout:m}=te(),[p,g]=Q(""),[h,f]=Q(""),y=V(!1),w=V(!1),S=V(null),E=V(null),v=useUiOverlays(),C=useFeed(),k=useSession(),T=useStatus(o),_=useAuth(),x=usePendingOps(),P=useOnboarding(),A=useExit(),{executeBash:I,executionState:N}=tk(),R=usePermissionMode({initialPermissionMode:u,dangerouslySkipPermissions:s,setPendingPermission:x.setPendingPermission,setStatus:T.setStatus,contextEngineRef:E}),{createContextEngineCallbacks:$}=useContextEngine({sessionId:k.sessionId,sessionLoaded:k.sessionLoaded,showSessionSelector:v.showSessionSelector,projectTrusted:P.projectTrusted,setFeed:C.setFeed,setLiveEntries:C.setLiveEntries,setQueuedMessages:C.setQueuedMessages,queuedMessagesRef:C.queuedMessagesRef,setStatus:T.setStatus,pinnedStatusRef:T.pinnedStatusRef,setRetryAttempt:T.setRetryAttempt,setInteractionTokens:T.setInteractionTokens,setContextUsage:T.setContextUsage,setCurrentProvider:_.setCurrentProvider,shareInfoRef:T.shareInfoRef,permissionsService:R.permissionsService,permissionModeRef:R.permissionModeRef,setPendingQuestion:x.setPendingQuestion,contextEngineRef:E}),{onCommand:M}=useCommandCtx({feedState:C,sessionState:k,statusState:T,uiOverlays:v,onboarding:P,exitState:A,permissionState:R,contextEngineRef:E,isSubmittingRef:y,executeBash:I,createContextEngineCallbacks:$,setInput:g}),{loadTasteStatus:D,loadCurrentProvider:L,onSubmit:O}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:a,stdout:m,feedState:C,sessionState:k,statusState:T,authState:_,onboarding:P,uiOverlays:v,permissionState:R,contextEngineRef:E,isSubmittingRef:y,initialPromptSubmittedRef:w,historyManagerRef:S,executeBash:I,createContextEngineCallbacks:$,setInput:g,onCommand:M});useLifecycle({exit:d,feedState:C,exitState:A,statusState:T,authState:_,onboarding:P,uiOverlays:v,skipOnboarding:l});const{handleToggleAutoAccept:q,handleDoubleEscapeEmpty:F,handleTasteOnboardingComplete:j,handleTrust:B,handleNoTrust:z}=useHandlers({resume:e,feedState:C,onboarding:P,uiOverlays:v,exitState:A,pendingOps:x,permissionState:R,statusState:T,authState:_,contextEngineRef:E,loadTasteStatus:D,loadCurrentProvider:L,setInput:__name(e=>g(e),"setInput")});return renderView({feedState:C,sessionState:k,statusState:T,authState:_,uiOverlays:v,onboarding:P,exitState:A,pendingOps:x,permissionState:R,contextEngineRef:E,historyManagerRef:S,executionState:N,actionCallbacks:useMainActionCallbacks({feedState:C,sessionState:k,statusState:T,authState:_,uiOverlays:v,permissionState:R,contextEngineRef:E,createContextEngineCallbacks:$,setInput:g}),onSubmit:O,onCommand:M,input:p,setInput:g,fileSearchQuery:h,setFileSearchQuery:f,updateFailedInfo:i,handleTrust:B,handleNoTrust:z,handleToggleAutoAccept:q,handleDoubleEscapeEmpty:F,handleTasteOnboardingComplete:j,loadTasteStatus:D})},"InteractiveCLI");hr(),Rn(),Lv();var Ax=__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"),Ix=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),Nx=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),Rx=__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"),$x=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),Mx=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),Dx=__name(()=>{Mx()},"initializeTerminal"),Lx=__name(async(e={})=>{const t=Ax(process.stdin.isTTY);let n;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),Dx(),"string"==typeof e.resume){const t=e.resume;await xv.isProjectInitialized()||(console.error("Project not initialized. Run cmd to start a conversation first."),process.exit(1));const r=await xv.findSessionByName(t);r||(console.error(`No session named "${t}" found.`),process.exit(1)),n=r.id}if(Ix(e)&&!n){const e=await xv.isProjectInitialized(),t=e?await xv.listSessions():[],n=Nx({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const r=Rx({options:e,resumeSessionId:n}),s=$x();re(G.createElement(Px,{...r}),s)},"interactiveMode");Qt(),Ft(),zt(),po(),Gs();var Ox=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.error(`${ve.cross} Authentication failed. Please try again with: cmd login`),!1)}catch(e){return isUserCancellation(e)||(console.error(`${ve.cross} Login failed: ${getErrorMessage(e)}`),console.error("Please try again with: cmd login")),!1}},"attemptLogin");async function ensureAuthenticated(){try{return!!await getAuthKey()||Ox()}catch(e){return console.error("Error checking authentication:",e),!1}}__name(ensureAuthenticated,"ensureAuthenticated");var qx=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),Fx=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth"),jx=__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"),Bx=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>e.resume?{resume:e.resume,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n},"getInteractiveConfig"),zx=__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=zx(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=qx(e);await Fx();const r=jx(t),s=Bx({options:t,runtimeOptions:r,initialPrompt:n});Lx(s)}__name(interactiveModeAction,"interactiveModeAction"),Ft(),Cn(),gs(),Sr(),globalThis.COMMAND_CODE_CWD=process.cwd();var Ux=__name(()=>process.cwd(),"getCwd"),Wx=__name(()=>process.argv.slice(2),"getArgs"),Gx=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),Hx=__name(()=>{const e=Ux(),t=Wx(),n=Gx(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){Hx(),process.argv.includes("--ide-setup")&&(formatSetupResult(await runIDESetup()).forEach(e=>console.log(e)),process.exit(0)),await maybeRunPendingUpdate(),await migrateDeprecatedModel(),checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100)}__name(preRun,"preRun"),Ft(),zt(),Cn(),$r(),aE(),vr();var Qx=getPackageJson(),Vx=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=Qx.version,t=getInvokedCommandName(),n=eE.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(ie.bold("Command Code")+ie.gray(` v${e}`)),console.log(ie.gray(Yb)),console.log(),console.log(ie.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ie.bold("Options"));for(const e of Zb){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Jb)+ie.gray(e.description))}console.log(),console.log(ie.bold("Commands"));for(const e of tE){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Jb)+ie.gray(e.description))}console.log(),console.log(ie.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Jb)+ie.gray(e.description));console.log(),console.log(ie.bold("Keyboard Shortcuts"));for(const e of Xb)console.log(" "+e.key.padEnd(Jb)+ie.gray(e.description));console.log(),console.log(ie.bold("Examples"));for(const e of rE){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Jb)+ie.gray(e.description))}console.log(),console.log(ie.cyan("❯")+" "+ie.gray(sE.replace(/cmd/,t))),console.log(),console.log(ie.bold("Links"));for(const e of nE)console.log(" "+e.key.padEnd(Jb)+ie.cyan(e.description));console.log()}function createProgram(){const e=new be;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(Qx.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 Ee("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Ee("--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 Ee("--auto-accept","Start in auto-accept mode").implies({permissionMode:"auto-accept"})).addOption(new Ee("--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",Vx,[]).addOption(new Ee("--model <model>","Override model for this run").hideHelp()).addOption(new Ee("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Ee("--experimental","Enable experimental features").hideHelp()).addOption(new Ee(bt).hideHelp()).addOption(new Ee(Et).hideHelp()).addOption(new Ee("-d, --debug","Enable debug mode").hideHelp()).addOption(new Ee("--local","Use local server").hideHelp()).addOption(new Ee("--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")})}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Ft(),gs(),Ss(),RC();var Kx=!1;function setupTelemetry(){initTelemetry()&&(startSession(),trackSystemInfo(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=process.version,t=h.platform(),n=h.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(){Kx||(Kx=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=Ce("Opening GitHub issues...").start();try{await ue(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"),po(),Ft(),Ms(),__name(openGitHubIssue,"openGitHubIssue");var Yx=new be("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Ft();var Jx=new be("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const{waitUntilExit:t}=re(G.createElement(tT,{verbose:e.verbose,text:e.text}));await t()}Ft(),Ft(),__name(runInfo,"runInfo");var Xx=new be("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}=re(G.createElement(kx,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onError:__name(()=>{e(),process.exit(1)},"onError")}))}Ft(),zt(),Ft(),__name(runLearnTaste,"runLearnTaste"),Cn(),gs();var Zx=new be(At.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:ls.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 be("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 Ee("-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(ie.red(`Error: Invalid server name '${e}'`)),console.error(ie.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(ie.red(`Error: Invalid transport type '${n.transport}'`)),console.error(ie.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(ie.red("Error: URL is required for http transport")),console.error(ie.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(ie.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(ie.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(ie.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(ie.cyan("Server requires OAuth authentication."));let t,n="command-code";if(r.metadata.registrationEndpoint){console.log(ie.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${xE}/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(ie.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(ie.gray(` ${e}`))},"onStatus")});s.success?console.log(ie.green("✓ Successfully authenticated")):(i=!0,console.log(ie.yellow(`Warning: Authentication failed: ${s.error}`)),console.log(ie.gray("You can retry with: cmd mcp auth "+e)),console.log(ie.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(ie.red("Error: Command is required for stdio transport")),console.error(ie.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(ie.red("Error: Command is required for stdio transport")),console.error(ie.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(ie.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(ie.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(ie.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===o.transport)console.log(ie.gray(` URL: ${o.url}`));else{const e=[o.command,...o.args||[]].join(" ");console.log(ie.gray(` Command: ${e}`))}console.log(""),console.log(ie.cyan("Next steps:")),console.log(ie.gray(`Start ${s} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ie.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(ie.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(ie.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(ie.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=s,t}function listMcpCommand(){const e=new be("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(ie.yellow("\nNo MCP servers configured\n")),console.log(ie.gray("Add a server with:")),console.log(ie.gray(" cmd mcp add --transport http <name> <url>")),console.log(ie.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(ie.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ie.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ie.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const s of e){const e=s.config.enabled?ie.green("enabled"):ie.gray("disabled");let o;o=s.config.oauth?await hasTokens(s.name)?ie.green(ve.tick):ie.red(ve.cross):s.config.headers||s.config.env?ie.green(ve.tick):ie.gray("-"),console.log(` ${ie.white(s.name.padEnd(t))} ${ie.cyan(s.config.transport.padEnd(n))} ${ie.gray(s.scope.padEnd(r))} ${o} ${e}`)}console.log(ie.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ie.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new be("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(ie.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(ie.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ie.dim("Scope:")} ${r}`),console.log(` ${ie.dim("Transport:")} ${n.transport}`),console.log(` ${ie.dim("Status:")} ${n.enabled?ie.green("enabled"):ie.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ie.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${ie.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(` ${ie.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ie.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${ie.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(ie.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new be("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Ee("-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(ie.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(ie.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(ie.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const s="user"===r?"global":"project"===r?"project":"local";console.log(ie.green(`✓ Removed MCP server '${e}' from ${s} config`))}catch(e){console.error(ie.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new be("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 Ee("-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(ie.red(`Error: Invalid server name '${e}'`)),console.error(ie.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(ie.red("Error: Invalid JSON")),console.error(ie.gray("Make sure to quote the JSON string properly")),console.error(ie.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=fE.safeParse(s);if(!i.success){console.error(ie.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(ie.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(ie.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(ie.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(ie.cyan("Starting OAuth authentication...")),console.log(ie.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(ie.gray(` ${e}`))},"onStatus")});n.success?console.log(ie.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(ie.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(ie.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ie.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(ie.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(ie.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(ie.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(ie.gray(` Command: ${e}`))}console.log(""),console.log(ie.cyan("Next steps:")),console.log(ie.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ie.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new be("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(ie.yellow("No servers with stored authentication."));console.log(ie.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?ie.yellow("expired"):ie.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(ie.red("Error: Server name is required")),console.error(ie.gray(`Usage: ${n} mcp auth <server>`)),console.error(ie.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(ie.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(ie.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(ie.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(ie.gray(" A refresh token is available for re-authentication"));else{if(console.log(ie.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(ie.gray(` Expires in ${e} minutes`))}t.scope&&console.log(ie.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(ie.green(`✓ Cleared authentication for '${e}'`)):console.log(ie.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(ie.red(`Error: MCP server '${e}' not found`)),console.error(ie.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),r.config.oauth||(console.error(ie.red(`Error: Server '${e}' does not have OAuth configured`)),console.error(ie.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(ie.cyan(`Authenticating with '${e}'...`)),console.log(ie.gray("A browser window will open for authentication.\n"));const o=await performOAuthFlow(e,s,{onStatus:__name(e=>{console.log(ie.gray(` ${e}`))},"onStatus")});if(o.success)return console.log(ie.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(ie.gray("Restart the session to connect with the authenticated server."));console.error(ie.red(`\nError: Authentication failed: ${o.error}`)),console.log(ie.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(ie.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new be("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}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(h.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")}Ft(),Ft(),__name(addMcpCommand,"addMcpCommand"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Ft(),__name(listMcpCommand,"listMcpCommand"),Ft(),__name(getMcpCommand,"getMcpCommand"),Ft(),__name(removeMcpCommand,"removeMcpCommand"),Ft(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Ft(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Ft(),zt(),Ft(),Ft(),Iw(),Ft(),zt(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Ft(),Ft();var eP=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||eP.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const s=n[r].trim();return{endIdx:t+r,inclusive:eP.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(eP.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(!eP.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:`${ve.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?ve.cross:ve.warning;return{valid:o,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?ie.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ie.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`${ie.green(e)} ${ie.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?ie.red(t.summary):ie.yellow(t.summary),"",...formatIssueGroup(r,ie.red,ie.bold(ie.red("Errors:"))),...formatIssueGroup(s,ie.yellow,ie.bold(ie.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"),Ft(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var tP=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;tP.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 nP=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,rP=/^\[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}):nP.test(o)||rP.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 sP=__name(e=>"local-global"===e?"global":"project","locationLabel"),oP=__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 v(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${sP(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});v(s)&&r.push({path:s,displayName:"taste.md"});const o=(await M.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>v(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 M.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await M.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 oP({file:"all",error:`No taste files found in ${sP(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 oP({file:"all",error:`No taste files found in ${sP(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 v(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):oP({file:"all",error:`No taste directory found in ${sP(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"),Ft(),gs(),__name(resolveConflictStrategy,"resolveConflictStrategy");var iP=ie.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(`${ie.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?`${ie.dim(t[1])}${ie.green(t[2])}${ie.white(t[3]??"")}${t[4]?ie.dim(t[4]):""}`:ie.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ie.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 aP=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return ct(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:aP})}function getProfileLink(e){return ct(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:aP})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return lt(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(ie.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(`${ie.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(ie.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new be("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 ${ie.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(`${ie.green(ve.tick)} All ${ie.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ie.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ie.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(ie.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 M.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await M.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 kw+"\n\n";const t=e.trim();return t.startsWith(vw)||t.startsWith(Tw)||t.startsWith(_w)?e:kw+"\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"),Ft(),fs(),Ft(),Ft(),Ft(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Ft(),__name(formatPackage,"formatPackage"),Ft(),Iw(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var lP="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:lP,category:e.name});return v(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await M.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:lP});if(!v(e))return[];const t=await M.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:lP,category:t});return v(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:lP});await M.mkdir(r,{recursive:!0});const s=getCategoryTasteFile({target:lP,category:n.category}),o=e.dirname(s);await M.mkdir(o,{recursive:!0});const i=formatPackage({pkg:n});await M.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"),Ft(),Ft(),Iw();var cP="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!v(n))return null;const r=migrateHeader({content:await M.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 M.rm(n,{force:!0}),""!==l&&await M.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:cP}),s=await removeCategoryFromRoot({category:n,rootFile:r}),o=getCategoryTasteFile({target:cP,category:n}),i=e.dirname(o);return v(i)&&await M.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 M.writeFile(n,e.trim()+"\n","utf-8")}let o="";v(n)&&(o=await M.readFile(n,"utf-8"),o=migrateHeader({content:o})),o=ensureHeader(o),o=ensureTrailingNewlines(o),o+=s,await M.writeFile(n,o.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:s}=t,o=getCategoryTasteFile({target:cP,category:n.category}),i=e.dirname(o);await M.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await M.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 M.writeFile(r,e.trim()+"\n","utf-8")}let u="";v(r)&&(u=await M.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await M.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var uP="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:uP,category:e.name});return v(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:uP});if(!v(e))return[];const t=[],n=getRootTasteFile({target:uP});if(v(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await M.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:uP});await M.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:uP}),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:uP});return v(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!v(n))return;const r=await M.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 p=getTastePath({target:"local-project"}),g=e.join(p,r.category);if(!v(g))return l;const h=getCategoryTasteFile({target:"local-project",category:r.category});if(!v(h))return l;const f=await M.readFile(h,"utf-8"),y=new Blob([f],{type:"text/markdown"}),w=new File([y],"taste.md",{type:"text/markdown"});return l.append(`files[${r.category}/taste.md]`,w),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(v(a)){const e=await M.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:ls.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}${Ct.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}${Ct.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:ls.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()}${Ct.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:ls.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()}${Ct.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()}${Ct.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()}${Ct.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 M.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 be("list").alias("ls").option("-g, --global","List global packages").addOption(new Ee("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Ee("--staging","Use staging environment").hideHelp()).description(`List available packages ${ie.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"),Ft(),Cs(),Ft(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),zt(),Ft(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),RC(),gs(),Ft(),po(),gs(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Ft(),Cs(),po(),zt(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),Cn(),__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 dP={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?dP.remote:e.global?dP.global:dP.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${ve.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${ve.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` ${ie.white(e.category)}${e.isPublic?ie.green(" [public]"):""}${e.isPublic&&e.starCount?ie.yellow(` ${ve.star}${e.starCount}`):""}${e.downloadCount?ie.gray(` ${ve.arrowDown}${e.downloadCount}`):""}${n}${ie.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?Ce(`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${iP} Packages`),console.log(`${ie.gray("⎿")} ${ie.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(ie.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(ie.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 M.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 ot([{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"),Ft(),Ft(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var mP=new Set(["local-project","local-global","remote-project","remote-user"]);async function open9(e){const{package:t,target:n}=e;if(!mP.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=ut.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 be("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 ${ie.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 ue(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ie.green(ve.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(`${ie.green(ve.tick)} Opened ${ie.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"),Ft(),Ft(),Ft(),Ft();var pP=null,gP=!1;function setActiveSpinner(e){pP=e}function stopActiveSpinner(e){pP&&(pP.stop(e),pP=null)}function setPrompted(e){gP=e}function wasPrompted(){return gP}function beginPrompt(e,t){stopActiveSpinner(),Pe.intro(ie.dim(e)),t&&Pe.log.message(ie.dim(t)),setPrompted(!0)}function handleCancel(e){Pe.isCancel(e)&&(Pe.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=Pe.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=Pe.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),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ie.green(`'${t}'`)} from ${n}`,o),Pe.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${s} learnings ${ie.dim(`(from ${n})`)}`);const i=await Pe.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),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${ie.green(`'${t}'`)} to global`,s),Pe.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const o=await Pe.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),Pe.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ie.green(`'${t}'`)} from global`,s),Pe.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const o=await Pe.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),Pe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ct(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ie.green(`'${t}'`)} to ${n}`,o),Pe.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${s} learnings) in ${n}`),Pe.log.info(`Current package: ${ie.cyan(i)} ${ie.dim("(review)")}`);const a=await Pe.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),Pe.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=ct(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ie.green(`'${t}'`)} to ${n}`,o),Pe.log.message(`Local: ${r} learnings\nRemote: ${s} learnings`),Pe.log.info(`Current package: ${ie.cyan(i)} ${ie.dim("(review)")}`);const a=await Pe.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"),Ft(),Ft(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Ft(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var hP=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),fP=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),yP=__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 hP({pkg:"all",error:`Invalid source: ${n}`});const o=yP(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return hP({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return hP({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=fP();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 hP({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=fP();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:s,result:o})}catch(e){return hP({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return Pe.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()?"":`${ve.tick} `,a=r?ie.dim(`\n ${shortenPath(r)}`):"";if(s.overwrite)return`${ie.green(i)}Replaced ${ie.green(`'${t}'`)} taste package in project`+a;if(o){const e=formatMergeParts(o);return`${ie.green(i)}Pulled ${ie.green(`'${t}'`)} taste package from ${n} ${ie.gray(`(${e.join(", ")})`)}`+a}return`${ie.green(i)}Pulled ${ie.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(`${ie.green("Pulled")} (${o.length}) ${o.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${ie.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),s.length>0&&l.push(wrapLine(`${ie.dim("Skipped")} (${s.length}) ${ie.dim(s.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&Pe.log.message(l.join("\n")),Pe.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${ie.green(ve.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(ie.yellow(`Skipped '${s[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new be("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 Ee("--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 Ee("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ie.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(Ce("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(Ce("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 Yy({baseUrl:e}),n=await t.get({endpoint:Ct.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 Pe.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()?"":`${ve.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${ie.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()?"":`${ve.tick} `;if(!a)return logResult2(`${ie.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?` ${ie.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${ie.green(l)}Replaced ${o} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${ie.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 p=formatMergeParts({added:u,updated:d,unchanged:m}),g=p.length>0?` ${ie.gray(`(${p.join(", ")})`)}`:"";return logResult2(`${ie.green(l)}Pushed ${o} to ${a}${g}`),(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()?"":`${ve.tick} `,l=!o&&s?ie.dim(`\n ${shortenPath(s)}`):"";if(n.overwrite)return logResult2(`${ie.green(a)}Replaced ${ie.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${ie.green(a)}Pushed ${ie.green(`'${r}'`)} taste package to ${i} ${ie.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${ie.green(a)}Pushed ${ie.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()?"":`${ve.tick} `;return logResult2(wrapLine(`${ie.green(s)}Pushed ${ie.green(t.packagesPushed.length)} taste packages ${ie.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(ie.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(`${ie.green("Merged")} (${s.length}) ${s.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${ie.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${ie.dim("Skipped")} (${r.length}) ${ie.dim(r.join(", "))}`,4)),i.length>0&&Pe.log.message(i.join("\n"));const a=`${o} ${1===o?"package":"packages"}`;Pe.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(`${ie.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&s.push(wrapLine(`${ie.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&s.push(wrapLine(`${ie.dim("Skipped")} (${n.length}) ${ie.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"),Ft(),__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"),Ft(),Cn(),Ft(),Cs(),bw(),zt(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Ft(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Ft(),RC(),Ft();var wP=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),SP=__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=SP(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 wP({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var bP=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),EP=__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 vP=__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=vP({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 bP({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return bP({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}):bP({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return bP({pkg:"all",error:`Invalid target: ${r}`});const m=EP();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 bP({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 bP({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,p=EP();if("skip"===d)return p.skipped.push(r),p;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m,overwrite:!0}),p.packagesPushed.push(r),p.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),p.packagesPushed.push(r),p.mergeDetails[r]=t}return p.filePaths[r]=`${n}/${r}`,p}async function pushRemote(e){const{packageName:t}=e;if(!exists2())return bP({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return bP({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 Pe.select({message:"Owner",options:r,initialValue:t});return Pe.isCancel(s)&&(Pe.cancel("Operation cancelled"),process.exit(0)),s}function createPushCommand(){return new be("push").description(`Push taste packages to remote ${ie.dim("(commandcode.ai)")} or global ${ie.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 Ee("--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 Ee("--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"),Ft(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var CP=__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};Pe.intro(ie.dim(`pushing ${t}`)),setPrompted(!0);const s=Pe.spinner();s.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(s.error("Failed"),Pe.outro(ie.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(ie.dim(` Pushing ${o} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner(Ce("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:CP(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:CP(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=Pe.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner(Ce("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(ie.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner(Ce("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 be(At.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()),e}function formatVersion(e,t,n=!1){const r=n?ae.bold(ae.green(t)):ae.white(t);return`${ae.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${ae.bold(ae.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(ae.dim(`Run ${ae.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(ae.dim("Try updating manually:")),console.log(ae.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(ae.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=Ce("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(`${ae.green(ve.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${ae.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=Ce("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} ${ve.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:ls.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 ${ae.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"),__name(createTasteCommand,"createTasteCommand"),Ft(),zt(),gs(),__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 kP=new be("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Ft(),po(),RC();var TP=__name((e,t)=>`${ve.info} ${e}: ${ae.cyan(t)}`,"formatInfoLine"),_P=__name(e=>ae.bold(`${e}:`),"formatSectionHeader"),xP=__name(e=>ae.red(e),"formatError"),PP=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),AP=__name(e=>["",_P("User Information"),TP("Name",e.name),TP("Email",e.email),TP("Username",e.userName)],"buildUserOutput"),IP=__name(e=>["",_P("Organization"),TP("Name",e.name),TP("Login",e.login)],"buildOrgOutput"),NP=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),RP=__name((e,t)=>{NP(AP(e)),t&&NP(IP(t)),console.log("")},"displayUserInfo"),$P=__name(e=>null!==e&&e.length>0,"validateApiKey"),MP=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=Ce("Fetching user information...").start();try{const t=await getAuthKey();$P(t)||(e.fail(xP('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();MP(n)||(e.fail(xP("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),RP(n.user,n.org)}catch(t){e.fail(xP(`Error: ${PP(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var DP=new be("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"!==N("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=N("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=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(!N(`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:""===N("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 N("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")}}Ft(),Ft(),zt(),bw(),Cs(),Ht(),vr(),Ft(),__name(normalizeGitUrl,"normalizeGitUrl"),__name(validateGitRepo,"validateGitRepo"),Ft(),__name(getGitHubToken,"getGitHubToken"),Ft(),Cs(),po(),Ft();var LP=["completed","failed","cancelled","timed_out"];function isTerminalStatus(e){return LP.includes(e)}__name(isTerminalStatus,"isTerminalStatus");var OP={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=OP[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=Ce({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=Ce({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: ${ae.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(`${ve.cross} ${ae.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${ae.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(`${ve.cross} ${ae.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=Ce({stream:process.stderr,text:"Reconnecting..."}).start());const l=__name(()=>{i.phase="done",stopAllSpinners({state:i}),o.close(),console.error(`\n${ae.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${ae.cyan(`cmd --experimental sandbox --id ${e}`)}`),p(),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${ae.yellow("Sandbox stopped.")}`),p(),t()},"cancelSandbox"),d=setupResizeForwarding({ws:o}),m=setupInputHandling({callbacks:{onCancel:u,onDetach:l}});process.once("SIGTERM",l);const p=__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(`${ae.yellow("[Ctrl+C]")} ${ae.dim("stop")} ${ae.yellow("[Ctrl+D]")} ${ae.dim("detach")}`),console.error(`${ae.dim("Session:")} ${ae.gray(e)}`),console.error(""),r&&(i.workingSpinner=Ce({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(),p(),t())}catch{}}),o.addEventListener("error",()=>{p(),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}),p(),console.error(`\n${ae.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${ae.cyan(`cmd --experimental sandbox --id ${e}`)}`),t())})})}function readLocalConfigFiles(){let e="",t="";try{e=w.readFileSync(getAuthFile(),"utf-8")}catch{}try{t=w.readFileSync(getConfigFile(),"utf-8")}catch{}return{auth:e,config:t}}async function askQuestion(e){const t=Ye.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 Yy({baseUrl:getApiBaseUrl()}).post({endpoint:Ct.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(ae.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(`${ae.bold("What do you want to do?")}\n${ae.cyan(">")} `);if(!i.trim())return void console.error(ae.yellow("No prompt provided. Aborting."));const a=i.trim().slice(0,It.MAX_PROMPT_CHARS),l=Ce({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(ae.red("Authentication failed. Try logging in again: cmd login")):console.error(ae.red(t)),process.exit(1)}}function createSandboxCommand(){return new be("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(ae.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(f.tmpdir(),`commandcode-skill-${W()}`);await D.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 D.access(l),d=!0}catch{}if(!d)try{await D.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 D.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(()=>(jC(),FC)),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 D.access(n),n}catch{}const r=t.join(e,"skill.md");try{return await D.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 D.readFile(t,"utf-8"),{data:r}=Fe(n),s=Ih.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 D.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 D.mkdir(a,{recursive:!0});const d=t.join(a,r),{randomUUID:m}=await import("crypto"),p=t.join(a,`.${r}.tmp.${m()}`);try{await D.cp(u,p,{recursive:!0,force:!0,dereference:!1}),l&&o&&await D.rm(d,{recursive:!0,force:!0}),await D.rename(p,d)}catch(e){if(await D.rm(p,{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 g;try{g=await resolveSkillMdPath(d)}catch{g=t.join(d,"SKILL.md")}return{name:r,description:n,location:i,path:g}}finally{d&&await D.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 D.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"),Sr(),Ft(),Ft(),Ft(),Ft(),qC(),__name(validateSafeString,"validateSafeString"),__name(parseGitHubRepo,"parseGitHubRepo"),__name(buildGigetSource,"buildGigetSource"),__name(fetchSkillFromGitHub,"fetchSkillFromGitHub"),__name(discoverSkillsInRepo,"discoverSkillsInRepo"),$w(),Qh(),__name(resolveSkillMdPath,"resolveSkillMdPath"),__name(validateSkillName,"validateSkillName"),__name(validateSkillContent,"validateSkillContent"),__name(skillExists,"skillExists"),__name(discoverSkills,"discoverSkills"),__name(installSkill,"installSkill"),__name(removeSkill,"removeSkill"),__name(listSkills,"listSkills"),zt();var qP=[`${ae.dim("Usage:")}`,` ${ae.cyan("cmd skills add")} ${ae.white("<owner/repo>")}`,"",`${ae.dim("Examples:")}`,` ${ae.cyan("cmd skills add")} ${ae.white("acme/my-skills")} ${ae.dim("# single-skill repo")}`,` ${ae.cyan("cmd skills add")} ${ae.white("acme/skills/path/to/skill")} ${ae.dim("# specific path in repo")}`,` ${ae.cyan("cmd skills add")} ${ae.white("acme/multi-skills -s my-skill")} ${ae.dim("# pick one from multi-skill repo")}`,` ${ae.cyan("cmd skills add")} ${ae.white("acme/repo@branch")} ${ae.dim("# specific branch")}`,` ${ae.cyan("cmd skills add")} ${ae.white("acme/repo --global")} ${ae.dim("# install to ~/.commandcode/skills/")}`],FP=__name((e,t)=>`${ae.green(ve.tick)} Installed ${ae.cyan(e)} ${ae.dim(`${ve.arrowRight} ${t}/`)}`,"formatInstalled"),jP=__name(e=>`${ae.red(ve.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){e&&await L(e,{recursive:!0,force:!0}).catch(()=>{}),process.exit(t)}function validateRepoFormat(e){(e.startsWith(".")||e.startsWith("/")||e.startsWith("~"))&&(console.error(jP("Local paths are not supported. Skills must be installed from GitHub.")),console.log(""),qP.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(jP(`Invalid repository: "${e}"`)),console.log(""),console.log(`Expected format: ${ae.cyan("owner/repo")} or ${ae.cyan("owner/repo/path")}`),console.log(""),qP.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=Ce({text:`Fetching ${ae.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(jP(`No skills found in ${ae.cyan(e)}`)),console.log(ae.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(jP(`Skill "${t.skill}" not found in ${ae.cyan(e)}`)),console.log(""),console.log(ae.dim("Available skills:")),l.forEach(e=>console.log(` ${ae.cyan(e.name)}`)),await cleanupAndExit(s,1)),i=[n]}else if(1===l.length)i=[l[0]];else if(n){const t=await Ae({message:`Select skills to install from ${e}`,options:l.map(e=>({value:e.name,label:e.name})),required:!0});"symbol"==typeof t&&(console.log(ae.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=Ce({text:`Installing ${ae.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(FP(i.name,r))}catch(e){d++;const t=e instanceof Error?e.message:String(e);console.error(jP(`Failed to install "${n.name}"`)),console.log(ae.dim(` ${t}`))}await cleanupAndExit(s,d>0?1:0)}catch(e){o.stop();const t=e instanceof Error?e.message:String(e);console.error(jP(t)),await cleanupAndExit(s,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction,"addAction");var BP=new be("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${qP.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(jP("No repository specified.")),console.log(""),qP.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction);Ft(),zt();var zP=__name((e,t)=>`${ae.green(ve.tick)} Removed ${ae.cyan(e)} from ${t} skills`,"formatRemoved"),UP=__name(e=>`${ae.red(ve.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(UP(s)),console.log(ae.dim(`Run ${ae.cyan("cmd skills list")} to see installed skills.`)),process.exit(1)),!t.yes&&n){const t=await Ie({message:`Remove ${ae.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(ae.dim("Cancelled")),process.exit(0))}await removeSkill({skillName:e,global:t.global}),console.log(zP(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill";r.includes("not found")?(console.error(UP(`Skill "${e}" not found in ${t.global?"global":"project"} skills`)),t.global||console.log(ae.dim(`Try ${ae.cyan(`cmd skills remove ${e} --global`)} to check global skills.`)),console.log(ae.dim(`Run ${ae.cyan("cmd skills list")} to see installed skills.`))):console.error(UP(r)),process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction,"removeAction");var WP=new be("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);Ft(),$w(),$s(),zt();var GP=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${ae.cyan(e)} ${ae.dim(`· ${n}`)}`},"formatSkillLine"),HP=__name((e,t)=>`${ae.bold(ae.white(e))} ${ae.dim(`(${t})`)}`,"formatSectionHeader"),QP=__name(()=>["",ae.dim("No skills installed."),"",ae.dim("Looking in:"),ae.dim(` ${getGlobalSkillsDir()} ${ae.white("(global)")}`),ae.dim(` ${getProjectSkillsDir()} ${ae.white("(project)")}`),"",`Install a skill: ${ae.cyan("cmd skills add")} ${ae.dim("<owner/repo>")}`,""],"formatEmptyHint"),VP=__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&&(VP(QP()),process.exit(0)),console.log(""),console.log(heading({text:"Skills",sub:ae.dim(`${n} installed`)})),t.length>0&&(console.log(""),console.log(HP("Project",t.length)),t.forEach(e=>{console.log(GP(e.name,e.description))})),e.length>0&&(console.log(""),console.log(HP("Global",e.length)),e.forEach(e=>{console.log(GP(e.name,e.description))})),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${ae.red(ve.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction,"listAction");var KP=new be("list").description("List all installed skills").action(listAction),YP=new be("skills").description("Manage skills from GitHub repositories").addCommand(BP).addCommand(WP).addCommand(KP);handleUnhandledErrors(),setupTelemetry(),await preRun();var JP=createProgram();JP.action(interactiveModeAction),JP.addCommand(Jx),JP.addCommand(Xx),JP.addCommand(DP),JP.addCommand(kP),JP.addCommand(Yx),JP.addCommand(createTasteCommand()),JP.addCommand(createMcpCommand()),JP.addCommand(Zx),JP.addCommand(ps),JP.addCommand(zs),JP.addCommand(Js),JP.addCommand(YP),isExperimentalEnabled()&&JP.addCommand(createSandboxCommand()),setupCommanderHooks(JP),JP.parse();
|