command-code 0.35.1 → 0.35.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -321,4 +321,4 @@ import*as e from"path";import t,{join as n,dirname as r,parse as o,relative as s
321
321
  ░█▀▀░█▀▄▀█░█▀▄░
322
322
  ░█░░░█░▀░█░█░█░
323
323
  ░▀▀▀░▀░░░▀░▀▀░░
324
- `,fA=getMaxLineWidth(hA),yA=mA,wA=__name(e=>{const t=e??getTerminalWidth();return t>=dA?"full":t>=yA?"compact":"minimal"},"getHeaderLayout");Ut(),jr();var SA=__name(({children:e})=>{const t=[];let n="",r=!0;const o=__name(()=>{0!==n.length&&(t.push({text:n,panel:r}),n="")},"flush");for(const t of e){const e="░"===t;0===n.length?r=e:e!==r&&(o(),r=e),n+=t}return o(),re.createElement(Y,null,t.map((e,t)=>re.createElement(Y,{key:t,color:e.panel?Or.BG:Or.TEXT},e.text)))},"CommandLogoBanner");Ut(),jr();var bA=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:o=0,titleColor:s=gr.GRAY,dividerChar:i="─",dividerColor:a=gr.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*o),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",g=r?` ${r}`:"",h=d.length+m.length+g.length,f=i.repeat(Math.max(0,u-h));return re.createElement(K,{paddingLeft:o,paddingRight:o,marginBottom:1,...l},(t||n)&&re.createElement(Y,{color:a},d),e&&re.createElement(Y,{color:s},m),re.createElement(Y,{color:a},f),r&&re.createElement(Y,{color:gr.DIM},g))},"Divider");GE(),jr(),Ut(),jr();var EA=[{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}],vA=__name(({onComplete:e,onExit:t})=>{const[n,r]=se(0),[o,s]=se(!1),i=n>=EA.length;return ae(()=>{if(n>=EA.length)return;if(o)return;const e=EA[n],t=setTimeout(()=>{r(e=>Math.min(e+1,EA.length))},e.duration);return()=>clearTimeout(t)},[n,o]),Z((n,o)=>{""===n||o.ctrl&&"c"===n?t?t():e():o.escape?e():i?(o.return||" "===n)&&e():" "===n?s(e=>!e):o.return&&r(e=>Math.min(e+1,EA.length))}),re.createElement(K,{flexDirection:"column"},re.createElement(K,null,re.createElement(Y,{bold:!0},"Meet Your Coding Taste")),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"Command Code learns your coding style as you work.")),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"Here's how your preferences evolve in real-time:")),re.createElement(K,{flexDirection:"column",marginY:1},EA.slice(0,n).map((e,t)=>"user"===e.type?re.createElement(K,{key:t},re.createElement(Y,null,Me.pointer," ",e.text)):re.createElement(K,{key:t,flexDirection:"column",marginBottom:1,marginLeft:1},re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"⎿ "),re.createElement(Y,{color:fr.TEXT},e.text)),e.details&&re.createElement(K,{marginLeft:3},re.createElement(Y,{color:gr.DIM},"Saved(",e.details,")"))))),i?re.createElement(K,{flexDirection:"column",marginY:1},re.createElement(K,null,re.createElement(Y,{bold:!0,color:fr.TEXT},"Demo Complete!")),re.createElement(K,null,re.createElement(Y,null,"Command Code will now use these preferences to generate")),re.createElement(K,null,re.createElement(Y,null,"better suggestions tailored to your coding style. The")),re.createElement(K,null,re.createElement(Y,null,"more you code, the smarter it gets.")),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press Enter to get started →"))):re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(o?" (paused)":""))))},"TasteDemoComponent"),CA=__name(({onClose:e,onExit:t})=>{const[n,r]=se(BT.getEvents()),[o,s]=se(0);Z((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),ae(()=>{const e=__name(()=>{r(BT.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return BT.on("new-event",e),BT.on("cleared",t),()=>{BT.off("new-event",e),BT.off("cleared",t)}},[]),ae(()=>{const e=__name(()=>{WE(),s(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=le(()=>n.find(e=>"analyzing"===e.type),[n]),l=le(()=>n.find(e=>"analyzed"===e.type),[n]),u=le(()=>n.find(e=>"no_learnings"===e.type),[n]),d=le(()=>n.find(e=>"learned"===e.type||"refactored"===e.type),[n]),m=u?n.indexOf(u):1/0,g=d?n.indexOf(d):1/0,h=!!u&&m<g,f=!!a||!!l||h,y=le(()=>n.filter(e=>"analyzing"!==e.type&&"analyzed"!==e.type&&"no_learnings"!==e.type),[n]),w=le(()=>[...y].reverse(),[y]),S=__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 o=n,s=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);s=`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:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),E=__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),o=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:o,diff:o-r}},"parsePercentageChange"),v=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),o=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:o,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails"),C=le(()=>(process.stdout.rows??24)-1,[o]);return re.createElement(K,{flexDirection:"column",width:"100%",height:C,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(SA,null,pA())),re.createElement(bA,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),re.createElement(K,{flexDirection:"column"},0===n.length?re.createElement(K,{flexDirection:"column"},re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(K,null,re.createElement(Y,null,"Start using Command Code and it will begin recording your coding taste.")),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"Your preferences, patterns, and style will appear here in real-time."))),re.createElement(ne,{count:2}),re.createElement(bA,{title:"DEMO",titleColor:"white",subPrefix:!0}),re.createElement(vA,{onComplete:()=>{e()},onExit:t})):re.createElement(K,{flexDirection:"column"},y.length>0&&re.createElement(K,{flexDirection:"column",gap:1},w.map(e=>{if(i(e.type)){const{type:t,label:n,content:r,confidence:o}=S(e.message),s="moved"===t?v(e.details):null,i="upgraded"===t||"downgraded"===t?E(r):null,a=s?.fullPath??e.details;let l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",r),o&&re.createElement(Y,{color:gr.DIM}," ","(",o,")"));return i&&(l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",i.text," ("),re.createElement(Y,{color:gr.DIM},"confidence:"," "),re.createElement(Y,{color:gr.DIM},i.oldPercent,"%"),re.createElement(Y,null," ",Me.arrowRight," "),re.createElement(Y,{color:i.diff>0?gr.GREEN:gr.RED},i.newPercent,"%"),re.createElement(Y,null,")"))),s&&(l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",s.category," ","package ("),re.createElement(Y,{color:gr.DIM},s.oldPath),re.createElement(Y,null," ",Me.arrowRight," ",s.newPath),re.createElement(Y,null,")"))),re.createElement(K,{key:e.id},re.createElement(K,{flexDirection:"column"},re.createElement(K,null,re.createElement(K,{flexShrink:0},re.createElement(Y,{backgroundColor:fr.BADGE_BG,color:fr.BADGE_FG,bold:!0},`${p_}${n}${p_}`)),a&&re.createElement(Y,{color:gr.DIM}," ","(",a,")")),re.createElement(K,{marginLeft:1},re.createElement(Y,{color:gr.DIM},"⎿"," "),l)))}return re.createElement(K,{key:e.id},re.createElement(Y,{color:gr.DIM},Me.pointerSmall," ",e.message))})),f&&re.createElement(K,{flexDirection:"column",marginTop:y.length>0?1:0},a&&re.createElement(K,null,re.createElement(Y,{color:gr.DIM},Me.pointerSmall," ",a.message)),l&&re.createElement(K,null,re.createElement(Y,{color:gr.DIM},Me.pointerSmall," ",l.message)),h&&u&&re.createElement(K,null,re.createElement(Y,{color:gr.DIM},Me.pointerSmall," ",u.message))))))},"LearningFeedFull");function LearningView({setShowLearningFeed:e,setStaticKey:t,onExit:n}){return re.createElement(CA,{onClose:()=>{WE(),e(!1),t(e=>e+1)},onExit:n})}__name(LearningView,"LearningView"),Ut(),jr(),Ut(),jr(),GE(),co();var kA=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=se(!1),[s,i]=se(!0);ae(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{i(!1)}},"loadSettings")()},[]),Z((t,n)=>{if(!n.return&&" "!==t)return n.escape?(WE(),void e()):void 0;a()});const a=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return s?re.createElement(K,{key:n,borderStyle:"single",borderColor:gr.BLUE,padding:1,flexDirection:"column"},re.createElement(Y,{color:gr.BLUE,bold:!0},"Taste Settings"),re.createElement(Y,{color:gr.DIM},"Loading configuration...")):re.createElement(K,{key:n,borderStyle:"single",borderColor:gr.GRAY,padding:1,flexDirection:"column"},re.createElement(Y,{bold:!0},"Taste Learning"),re.createElement(Y,{color:gr.DIM},"Configure taste learning preferences for this project"),re.createElement(K,{marginTop:1}),re.createElement(K,{justifyContent:"space-between"},re.createElement(Y,null,"Taste learning",re.createElement(Y,{color:gr.DIM}," ","- Learn from your interactions")),re.createElement(Y,{color:r?gr.GREEN:gr.GRAY},r?"enabled":"disabled")),re.createElement(K,{marginTop:1}),re.createElement(Y,{color:gr.DIM},"Taste data stored in .commandcode/taste/taste.md"),re.createElement(Y,{color:gr.DIM},"Enter/Space to toggle • Esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,setShowTasteConfig:t,loadTasteStatus:n}){return re.createElement(re.Fragment,null,re.createElement(Bx,{staticKey:e}),re.createElement(K,{flexDirection:"column",width:"100%"},re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"Press Esc to return to conversation")),re.createElement(kA,{onClose:()=>t(!1),onSettingsChange:n,staticKey:e})))}function fuzzyMatch(e,t){let n=0;for(const r of e)if(r===t[n]&&(n++,n===t.length))return!0;return!1}function fuzzyScore(e,t){let n=0;for(const r of e)fuzzyMatch(r.text.toLowerCase(),t)&&(n+=r.weight);return n}function fuzzyFilter(e,t,n){if(!t.trim())return e;const r=t.toLowerCase().split("");return e.map(e=>({item:e,score:fuzzyScore(n(e),r)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score).map(({item:e})=>e)}__name(TasteConfigView,"TasteConfigView"),Ut(),Ut(),kn(),Ut(),__name(fuzzyMatch,"fuzzyMatch"),__name(fuzzyScore,"fuzzyScore"),__name(fuzzyFilter,"fuzzyFilter"),jr(),Ut(),jr();var TA=__name(({query:e,resultCount:t,placeholder:n="Type to search..."})=>re.createElement(K,{width:"100%"},re.createElement(Y,{color:gr.GRAY},Me.pointerSmall," "),re.createElement(Y,{color:e?gr.WHITE:gr.GRAY},e||n),e&&void 0!==t&&re.createElement(Y,{dimColor:!0}," (",t," found)")),"SearchInput");function useListNavigation({items:e,onSelect:t,onCancel:n,validate:r,initialIndex:o=0,searchCursorIndex:s=0,searchQuery:i,onSearchChange:a,isActive:l=!0,disableSearch:u=!1,selectByNumber:d=!1,onReset:m}){const[g,h]=se(o),[f,y]=se(null);ae(()=>{i||h(o)},[o,i]);const w=e.length-1,S=__name(e=>{a(e),h(s)},"updateSearch");return Z((o,s)=>{if(s.escape)return!u&&i?void S(""):void n();if(u||!s.backspace&&!s.delete){if(u&&m&&"r"===o&&!s.ctrl&&!s.meta){const t=e[g];return void(t&&m(t))}if(0!==e.length){if(s.upArrow)return y(null),void h(e=>Math.max(e-1,0));if(s.downArrow)return y(null),void h(e=>Math.min(e+1,w));if(s.return){const n=e[g];if(!n)return;if(r){const e=r(n);if(e)return void y(e)}return void t(n)}if(d&&1===o.length&&o>="1"&&o<="9"&&!s.ctrl&&!s.meta){const n=Number(o)-1,s=e[n];if(!s)return;if(h(n),r){const e=r(s);if(e)return void y(e)}return void t(s)}!u&&!s.ctrl&&!s.meta&&!s.tab&&o&&1===o.length&&o>=" "&&S(i+o)}}else S(i.slice(0,-1))},{isActive:l}),{cursor:g,error:f,setError:y}}function useTerminalHeight(){const{stdout:e}=X(),[t,n]=se(()=>e?.rows??24);return ae(()=>{const t=__name(()=>n(e?.rows??24),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}function skillIdentifier(e){const n=t.basename(e);return"skill.md"===n.toLowerCase()?t.basename(t.dirname(e)):n}Ut(),__name(useListNavigation,"useListNavigation"),Ut(),__name(useTerminalHeight,"useTerminalHeight"),Ut(),kn(),jr(),Ut(),GE(),jr(),uo(),Ut(),__name(skillIdentifier,"skillIdentifier");var _A=new Set(["Invalid YAML","Missing fields","Missing SKILL.md"]);function categoryColor(e){return _A.has(e)?gr.RED:gr.YELLOW}function formatWarningsAsMarkdown(e){const t=groupWarnings(e),n=[`# Skipped skills (${e.length})`,""];for(const e of t){n.push(`## ${e.category} (${e.items.length})`,"");for(const t of e.items)n.push(`- \`${skillIdentifier(t.path)}\` — \`${t.path}\``),n.push(` - ${t.reason}`);n.push("")}return n.join("\n").replace(/\n+$/,"")+"\n"}async function copyAllWarnings(e,t){try{const{isClipboardAvailable:n}=await Promise.resolve().then(()=>(Kr(),Qr));if(!n())return void t({text:"Clipboard unavailable — copy the skipped skill paths manually",color:gr.YELLOW});const r=await import("@crosscopy/clipboard");await r.default.setText(formatWarningsAsMarkdown(e));const o=e.length;t({text:`Copied ${o} issue${1===o?"":"s"} to clipboard`,color:gr.GREEN})}catch{t({text:"Clipboard write failed",color:gr.YELLOW})}}__name(categoryColor,"categoryColor"),__name(formatWarningsAsMarkdown,"formatWarningsAsMarkdown"),__name(copyAllWarnings,"copyAllWarnings");var xA=__name(({warnings:e,onClose:t,isActive:n=!0})=>{const r=groupWarnings(e),o=e.length>0,[s,i]=se(null),a=ie(null),l=ie(!0);ae(()=>()=>{l.current=!1,a.current&&(clearTimeout(a.current),a.current=null)},[]);const u=__name(e=>{l.current&&(a.current&&clearTimeout(a.current),i(e),a.current=setTimeout(()=>{l.current&&(i(null),a.current=null)},3e3))},"showStatus");return Z((n,r)=>r.escape||" "===n&&o?(WE(),void t()):void("c"===n&&o&&copyAllWarnings(e,u)),{isActive:n}),re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Skills"," "),re.createElement(Y,{color:gr.DIM},"› "),re.createElement(Y,{color:hr,bold:!0},"Skipped"," "),re.createElement(Y,{color:gr.WHITE},e.length)),o&&re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"Press c to copy all issues")),o?re.createElement(K,{flexDirection:"column"},r.map(e=>re.createElement(K,{key:e.category,flexDirection:"column"},re.createElement(K,null,re.createElement(Y,{color:categoryColor(e.category)},e.category)),e.items.map(e=>re.createElement(K,{key:e.path,flexDirection:"column",marginBottom:1},re.createElement(K,{paddingLeft:2},re.createElement(ao,{url:m(e.path).href,text:skillIdentifier(e.path),color:gr.WHITE})),re.createElement(K,{paddingLeft:4},re.createElement(Y,{color:gr.WHITE},e.reason))))))):re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"No issues — every skill loaded.")),s&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:s.color},s.text)),re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:gr.DIM},o?"c copy all issues · esc back to skills":"esc back to skills")))},"SkillsConfigIssues"),AA=__name(({warnings:e=[],onClose:t})=>{const[n,r]=se("list");return Z((o,s)=>{"list"===n&&(s.escape&&t?t():" "===o&&!s.ctrl&&!s.meta&&e.length>0&&r("issues"))},{isActive:"list"===n}),"issues"===n?re.createElement(xA,{warnings:e,onClose:()=>r("list"),isActive:!0}):re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Skills"),e.length>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:gr.YELLOW},e.length," skipped"))),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"No skills found")),re.createElement(Y,{color:gr.DIM},"Create skills in:"),re.createElement(Y,{color:gr.DIM}," ","~/",".commandcode","/","skills","/ (user)"),re.createElement(Y,{color:gr.DIM}," ","~/.agents/","skills","/ (user, .agents)"),re.createElement(Y,{color:gr.DIM}," ",".commandcode","/","skills","/ (project)"),re.createElement(Y,{color:gr.DIM}," ",".agents/","skills","/ (project, .agents)"),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},e.length>0&&"space to view issues · ","Press ",re.createElement(Y,{bold:!0},"Esc")," to close")))},"SkillsConfigEmpty");function clampScrollOffset(e){const{cursor:t,total:n,maxVisible:r,currentOffset:o}=e;if(n<=r)return 0;let s=o;t<s?s=t:t>=s+r&&(s=t-r+1);const i=Math.max(0,n-r);return Math.min(Math.max(0,s),i)}function sliceSectionForWindow(e){const{section:t,sectionBase:n,windowStart:r,windowEnd:o}=e,s=Math.min(Math.max(r-n,0),t.length),i=Math.min(Math.max(o-n,0),t.length);return{rows:t.slice(s,i),baseIndex:n+s}}Ut(),__name(clampScrollOffset,"clampScrollOffset"),__name(sliceSectionForWindow,"sliceSectionForWindow"),Ut();var PA=__name(e=>Math.ceil(e.length/4),"estimateTokens"),IA=__name(e=>e.includes("/.agents/skills/")||e.includes("\\.agents\\skills\\"),"isAgentsSkill"),MA={user:"user settings",projectShared:"project shared",projectLocal:"project local"},NA=__name(()=>"win32"===process.platform?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===process.platform?"~/.zshrc":"~/.bashrc"),"getEditorSetupMessage");Ut(),jr();var RA=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(K,null,re.createElement(Y,{color:Tr,bold:!0},e," "),re.createElement(Y,{color:Tr},t)),n.map((e,t)=>{const n=r+t===o,i=s.has(e.label),a=IA(e.filePath),l=n?xr:void 0;return re.createElement(K,{key:e.filePath},re.createElement(Y,{color:i?gr.DIM:gr.GREEN,backgroundColor:l},i?"[off] ":"[on] "),re.createElement(Y,{color:i?gr.DIM:gr.WHITE,backgroundColor:l},e.label),a&&re.createElement(Y,{color:gr.DIM,backgroundColor:l}," [.agents]"),re.createElement(Y,{color:gr.DIM,backgroundColor:l}," · ~",PA(e.description)," tokens "))})),"SkillSection");Ut();var $A=__name(e=>[{text:e.label,weight:100}],"SKILL_SEARCH_FIELDS"),LA=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se([]),[s,i]=se(!0),[a,l]=se(null),[u,d]=se(""),[m,g]=se(new Set),[h,f]=se(new Map),[y,w]=se(!1),[S,E]=se(null),[v,C]=se("list"),[k,T]=se(0),_=useTerminalHeight(),x=ie(!1);ae(()=>{__name(async()=>{try{const e=findGitRoot(),t=getBundledSkillsDir(),[{global:r,project:s,warnings:i},a]=await Promise.all([loadAllSkillSummariesWithWarnings(),loadDisabledSkills({projectRoot:e})]),l=__name(e=>isBundledSkillPath({filePath:e,bundledDir:t}),"isBundled"),u=[...s.map(e=>({label:e.name,location:"project",description:e.description,filePath:e.filePath})),...r.filter(e=>!l(e.filePath)).map(e=>({label:e.name,location:"user",description:e.description,filePath:e.filePath})),...r.filter(e=>l(e.filePath)).map(e=>({label:e.name,location:"bundled",description:e.description,filePath:e.filePath}))];u.sort((e,t)=>{if(e.location!==t.location){const n={project:0,user:1,bundled:2};return n[e.location]-n[t.location]}return e.label.localeCompare(t.label)}),n(u),o(i),g(new Set(a.names)),f(new Map(a.bySkill)),w(a.noProjectRoot)}catch(e){l(e instanceof Error?e.message:"Failed to load skills")}finally{i(!1)}},"load")()},[]);const A=le(()=>fuzzyFilter(t.filter(e=>"project"===e.location),u,$A),[t,u]),P=le(()=>fuzzyFilter(t.filter(e=>"user"===e.location),u,$A),[t,u]),I=le(()=>fuzzyFilter(t.filter(e=>"bundled"===e.location),u,$A),[t,u]),M=le(()=>[...A,...P,...I],[A,P,I]),N=_-1,R=(A.length>0?1:0)+(P.length>0?1:0)+(I.length>0?1:0),$=Math.max(4,N-12-2*R),L=__name(async e=>{if(x.current)return;const t=m.has(e.label),n=h.get(e.label);if(t&&void 0!==n&&"projectLocal"!==n&&!y)return void E(`Cannot enable: "${e.label}" is disabled in ${MA[n]}. Edit that file to override.`);x.current=!0;const r=new Set(m);t&&r.delete(e.label),t||r.add(e.label),g(r),E(null);try{const n=findGitRoot(),r=await setSkillEnabled(e.label,t,{projectRoot:n}),o=new Map(h);t&&o.delete(e.label),t||o.set(e.label,r),f(o),"user"===r&&E("Saved to user settings — no project found.")}catch(e){g(m),E(`Failed to save: ${e instanceof Error?e.message:String(e)}`)}finally{x.current=!1}},"toggleSkill");ae(()=>{"issues"===v&&d("")},[v]);const D="list"===v&&t.length>0,{cursor:O}=useListNavigation({items:M,onSelect:L,onCancel:e,searchQuery:u,onSearchChange:d,initialIndex:0,isActive:D});if(ae(()=>{T(e=>clampScrollOffset({cursor:O,total:M.length,maxVisible:$,currentOffset:e}))},[O,M.length,$]),Z((t,n)=>{if(!n.tab)return;const r=M[O];r&&(async()=>{try{await St([{file:r.filePath,line:1}]),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void l(NA());l(e instanceof Error?e.message:"Failed to open skill in editor")}})()},{isActive:D}),Z((e,n)=>{"list"===v&&0!==t.length&&" "===e&&!n.ctrl&&!n.meta&&r.length>0&&0===u.length&&C("issues")},{isActive:"list"===v&&t.length>0}),s)return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Y,{color:hr,bold:!0},"Skills"),re.createElement(Y,{color:gr.DIM},"Loading skills..."));if(a)return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Y,{color:gr.RED,bold:!0},"Skills"),re.createElement(Y,{color:gr.DIM},a),re.createElement(K,{marginTop:1}),re.createElement(Y,{color:gr.DIM},"Press ",re.createElement(Y,{bold:!0},"Esc")," to close"));if(0===t.length)return re.createElement(AA,{warnings:r,onClose:e});if("issues"===v)return re.createElement(xA,{warnings:r,onClose:()=>C("list"),isActive:!0});const F=t.filter(e=>m.has(e.label)).length,U=k,j=k+$,B=sliceSectionForWindow({section:A,sectionBase:0,windowStart:U,windowEnd:j}),q=sliceSectionForWindow({section:P,sectionBase:A.length,windowStart:U,windowEnd:j}),z=sliceSectionForWindow({section:I,sectionBase:A.length+P.length,windowStart:U,windowEnd:j}),W=M.length>$;return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Skills"," "),re.createElement(Y,{color:gr.DIM},t.length," skill",1===t.length?"":"s"),F>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:gr.YELLOW},F," off")),r.length>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:gr.YELLOW},r.length," skipped"))),re.createElement(K,{marginBottom:1},re.createElement(Y,{dimColor:!0},y?"No project found — toggles will be saved to user settings.":"Toggle skills on or off for this project.")),re.createElement(K,{marginBottom:1,flexDirection:"column",width:"100%"},re.createElement(TA,{query:u,resultCount:u?M.length:void 0,placeholder:"Type to search skills..."})),0===M.length?re.createElement(K,{marginY:1},re.createElement(Y,{color:gr.GRAY},'No skills match "',u,'"')):re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"column"},B.rows.length>0&&re.createElement(RA,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:B.rows,baseIndex:B.baseIndex,cursor:O,disabled:m}),q.rows.length>0&&re.createElement(RA,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:q.rows,baseIndex:q.baseIndex,cursor:O,disabled:m}),z.rows.length>0&&re.createElement(RA,{title:"Bundled skills",subtitle:"(ships with Command Code)",skills:z.rows,baseIndex:z.baseIndex,cursor:O,disabled:m})),W&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",U+1,"–",Math.min(j,M.length)," of"," ",M.length,U>0?" · ↑ more":"",j<M.length?" · ↓ more":""))),S&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.YELLOW},S)),re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:gr.DIM},"type to search · ↑/↓ navigate · enter to toggle · tab to edit",r.length>0&&!u&&re.createElement(re.Fragment,null," · space to view issues"),u?" · esc to clear":" · esc to close"),re.createElement(Y,{color:gr.DIM},"add skills:"," ",re.createElement(Y,{color:gr.CYAN},"cmd skills add ","<owner/repo>"))))},"SkillsConfig");function SkillsConfigView({staticKey:e,setShowSkillsConfig:t,setStaticKey:n}){re.useEffect(()=>{hardResetForResize()},[]);const r=__name(()=>{hardResetForResize(),n(e=>e+1),t(!1)},"handleClose");return re.createElement(re.Fragment,null,re.createElement(Bx,{staticKey:e}),re.createElement(K,{flexDirection:"column",width:"100%"},re.createElement(LA,{onClose:r,staticKey:e})))}function getUsageColor(e){return e>=80?gr.RED:e>=50?gr.YELLOW:gr.GREEN}function buildBlockBar({percentage:e,width:t}){const n=Math.max(0,Math.min(100,e));let r=Math.round(n/100*t);n>.5&&0===r&&(r=1),n<99.5&&r===t&&(r=t-1);const o=t-r;return{filled:"█".repeat(r),empty:"░".repeat(o)}}function getStudioUsageUrl(e){const t=e?.org?.login??e?.user?.userName;return t?`https://commandcode.ai/${t}/settings/usage`:null}__name(SkillsConfigView,"SkillsConfigView"),Ut(),Ut(),io(),GE(),jr(),Ut(),jr(),__name(getUsageColor,"getUsageColor"),__name(buildBlockBar,"buildBlockBar"),uo(),__name(getStudioUsageUrl,"getStudioUsageUrl");var DA=__name(e=>e.replace(/^https?:\/\//,""),"stripScheme");function getProgressBarWidth({terminalWidth:e}){return e<50?Math.max(10,e-10):e<70?Math.max(15,e-15):Math.min(30,e-15)}function getDaysColor(e){if(null!==e)return e<3?gr.RED:e<7?gr.YELLOW:void 0}__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var OA=__name(({plan:e,status:t})=>re.createElement(K,{marginBottom:0},re.createElement(K,{flexShrink:0},re.createElement(Y,{backgroundColor:gr.BLUE,color:"#f4f4f4",bold:!0},`${p_}USAGE${p_}`)),e&&re.createElement(re.Fragment,null,re.createElement(Y,null," "),re.createElement(Y,{color:gr.GRAY},`${e.name} Plan`)),t&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:"active"===t?gr.GREEN:gr.YELLOW},t))),"UsageBadge"),FA=__name(({showRetry:e})=>re.createElement(K,{marginTop:1},e&&re.createElement(Y,{color:gr.DIM},re.createElement(Y,{bold:!0},"r")," to retry · "),re.createElement(Y,{color:gr.DIM},"Press ",re.createElement(Y,{bold:!0},"Esc")," to close")),"UsageFooter"),UA=__name(({models:e,grandTotal:t})=>{if(0===e.length)return null;const n=e.map(e=>({...e,displayName:getModelDisplayName(e.model),costLabel:formatCredits(e.totalCost)})),r=Math.max(...n.map(e=>e.displayName.length)),o=Math.min(24,Math.max(10,r)),s=Math.max(...n.map(e=>e.costLabel.length)),i=Math.max(8,s+2);return re.createElement(K,{flexDirection:"column",marginTop:1},n.map(({model:e,displayName:n,costLabel:r,totalCost:s})=>{const a=t>0?Math.round(s/t*100):0,l=n.length>o?n.slice(0,o-1)+"…":n;return re.createElement(K,{key:e},re.createElement(Y,null,l.padEnd(o+2)),re.createElement(Y,null,r.padEnd(i)),re.createElement(Y,{color:gr.DIM},`${a}%`))}))},"ModelBreakdownRows"),jA=__name(({onClose:e})=>{const[t,n]=se("loading"),[r,o]=se(null),[s,i]=se(!1),a=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=ce(async e=>{try{i(!1);const t=await fetchUsageData();if(e.aborted)return;if(!t.whoami){const e=t.errors.some(isAuthErrorMessage);return i(e),void n("error")}o(t),n("loaded")}catch{if(e.aborted)return;n("error")}},[]),u=re.useRef(null);Z((r,o)=>{if(o.escape&&(WE(),e()),"r"===r&&"error"===t){n("loading"),u.current?.abort();const e=new AbortController;u.current=e,l(e.signal)}}),ae(()=>{const e=new AbortController;return u.current=e,l(e.signal),()=>e.abort()},[l]);const d=r?.subscription?.data??null,m=d?getPlanInfo({planId:d.planId??""}):null;if("loading"===t)return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(OA,{plan:m,status:d?.status??null}),re.createElement(Y,{color:gr.DIM},"Loading…"),re.createElement(FA,null));if("error"===t)return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(OA,{plan:m,status:d?.status??null}),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),re.createElement(FA,{showRetry:!s}));if(!r)return null;const g=r.credits||r.subscription,h=getStudioUsageUrl(r.whoami);if(!g)return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(OA,{plan:m,status:d?.status??null}),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"No billing data found."),h&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," Visit "),re.createElement(ao,{url:h,text:"Studio",color:gr.CYAN}),re.createElement(Y,{color:gr.DIM}," for usage details."))),re.createElement(FA,null));const f=r.credits?.credits,y=r.summary,w=r.modelBreakdown,S=null!=w&&w.length>0,E=Math.max(0,f?.monthlyCredits??0)+Math.max(0,f?.purchasedCredits??0)+Math.max(0,f?.freeCredits??0),v=Math.max(0,y?.totalCost??0),C=getUsagePercent({used:v,total:v+E}),k=E>0||v>0,T=d?.currentPeriodEnd?getDaysRemaining(d.currentPeriodEnd):null,_=getDaysColor(T),x=getUsageColor(C),A=buildBlockBar({percentage:C,width:a}),P=S?w.reduce((e,t)=>e+t.totalCost,0):0;return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,{marginBottom:1},re.createElement(OA,{plan:m,status:d?.status??null})),k?re.createElement(K,null,re.createElement(Y,{color:x},A.filled),re.createElement(Y,{color:Tr},A.empty),re.createElement(Y,{bold:!0,color:x},` ${Math.round(C)}% used`)):re.createElement(Y,{color:gr.DIM},"Plan details unavailable"),k&&re.createElement(K,null,d?.currentPeriodEnd&&re.createElement(Y,{color:gr.DIM},"Cycle: "),re.createElement(Y,null,formatCredits(E)),re.createElement(Y,{color:gr.DIM}," left"),y&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,null,y.totalCount.toLocaleString()),re.createElement(Y,{color:gr.DIM}," requests")),null!==T&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),0===T?re.createElement(Y,{color:_},"renewal today"):re.createElement(re.Fragment,null,re.createElement(Y,{color:_},`${T} day${1===T?"":"s"}`),re.createElement(Y,{color:gr.DIM}," to renewal")))),S&&re.createElement(UA,{models:w,grandTotal:P}),h&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Full breakdown at "),re.createElement(ao,{url:h,text:DA(h),color:gr.CYAN})),re.createElement(FA,null))},"UsageOverlay");function UsageView({staticKey:e,setShowUsageOverlay:t}){return re.createElement(re.Fragment,null,re.createElement(Bx,{staticKey:e}),re.createElement(K,{flexDirection:"column",width:"100%"},re.createElement(jA,{onClose:()=>t(!1)})))}__name(UsageView,"UsageView"),Ut(),Ut(),kn(),pb(),jS(),co();var BA="System prompt",qA="Messages";function countMessagesByRole({messages:e}){let t=0,n=0;for(const r of e)"user"===r.message.role&&!isHiddenTranscriptMessage({message:r})&&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){if(isHiddenTranscriptMessage({message:r}))continue;const e=r.message.content;if(Array.isArray(e))for(const r of e)"tool-call"===r.type&&t++,"tool-result"===r.type&&n++}return{calls:t,results:n}}function countImages({messages:e}){let t=0;for(const n of e){if(isHiddenTranscriptMessage({message:n}))continue;const e=n.message.content;if(Array.isArray(e))for(const n of e)"image"===n.type&&t++}return t}function estimateConversationTokens({messages:e}){let t=0;for(const n of e)isHiddenTranscriptMessage({message:n})||(t+=estimateTokens(n.message));return t}function buildAutoCompactStatus({tokensUsed:e,tokenLimit:t}){const n=e/t,r=[{tier:1,threshold:En.TIER_1_THRESHOLD,description:`Prune to last ${En.TIER_1_KEEP_COUNT} tool calls`},{tier:2,threshold:En.TIER_2_THRESHOLD,description:`Prune to last ${En.TIER_2_KEEP_COUNT} tool calls`},{tier:3,threshold:En.TIER_3_THRESHOLD,description:"Full summarization"}];let o=0;const s=r.map(r=>{const s=Math.round(r.threshold*t),i=Math.max(0,s-e);let a="upcoming";return n>=r.threshold&&(a="passed",o=r.tier),{tier:r.tier,threshold:r.threshold,tokensAt:s,description:r.description,status:a,tokensAway:i}}),i=s.findIndex(e=>"upcoming"===e.status);return{tiers:-1!==i?s.map((e,t)=>t===i?{...e,status:"current"}:e):s,currentTier:o,keepRecentTokens:En.KEEP_RECENT_TOKENS}}function getPrimaryTip({percentage:e,conversationPct:t}){return e>=90?"Tier 3 auto-compact imminent — /compact now to control what gets summarized":e>=80?"Auto-compact Tier 3 triggers at 90% — /compact to free space before it kicks in":t>60&&e>40?`${t}% is conversation — /compact to reclaim tokens`:e>=50?"/compact to free space · /model to switch models":null}function getSecondaryTip({mcpToolCount:e,imageCount:t,messageCount:n,percentage:r}){return e>0&&r>30?`${e} MCP tools loaded — disconnect unused servers to save tokens`:t>0&&r>30?`${t} image${t>1?"s":""} in context — images use ~1.5k tokens each`:n>50&&r>40?`${n} messages — consider starting a new session for a fresh context`:null}function generateTips({percentage:e,conversationTokens:t,totalTokens:n,mcpToolCount:r,messageCount:o,imageCount:s}){if(0===n)return[];const i=getPrimaryTip({percentage:e,conversationPct:Math.min(100,Math.round(t/n*100))}),a=getSecondaryTip({mcpToolCount:r,imageCount:s,messageCount:o,percentage:e}),l=[];return i&&l.push(i),a&&l.push(a),0===l.length&&l.push("/compact to summarize and free context · /model to switch models"),l}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,o=process.env.HOME??"",s=o&&n.path.startsWith(o)?`~${n.path.slice(o.length)}`:n.path;t.push({name:n.description,tokens:r,source:s})}return t}function collectBuiltInTools(){const e=[];for(const t of pT){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 gT){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??{}),o=estimateTokens(`${e.name} ${e.description??""} ${r}`);t.push({name:e.name,tokens:o,source:n.name})}return t}async function collectSkillItems(){const[e,{names:t}]=await Promise.all([loadAllSkillSummaries(),loadDisabledSkills()]);return deduplicateSkills({project:e.project.filter(e=>!t.has(e.name)),global:e.global.filter(e=>!t.has(e.name))}).map(e=>({name:e.name,tokens:estimateTokens(`${e.name} ${e.description}`)}))}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=e.getSystemPromptBreakdown(),r=getConfiguredModel(),o=getContextLimit(r),s=e.getHistory(),i=countMessagesByRole({messages:s}),a=countToolCalls({messages:s}),l=countImages({messages:s}),u=estimateConversationTokens({messages:s}),d=collectBuiltInTools(),m=collectMcpTools(),[g,h,f]=await Promise.all([collectSkillItems(),collectAgentItems(),collectMemoryItems()]),y=sumTokens(d),w=sumTokens(m),S=sumTokens(g),E=sumTokens(h),v=sumTokens(f),C=t>0,k=n?n.memory:v,T=null!==n&&Math.abs(v-n.memory)>50,_=n?n.taste:0,x=y+w+S+E,A=C?t:u+x+k+_,P=!C&&s.length>0,I=Math.min(A/o*100,100),M=Math.max(0,o-A),N=[];if(A>0){const e=n?n.systemPrompt:Math.max(0,A-u-x-k-_);if(e>0&&N.push({name:BA,tokens:e,detail:n?"identity":"identity + taste"}),k>0&&N.push({name:"Memory",tokens:k,detail:T?"memory files (modified, refreshes next request)":"memory files"}),_>0&&N.push({name:"Taste",tokens:_,detail:"taste.md"}),y>0&&N.push({name:"System tools",tokens:y,detail:`${d.length} built-in`}),w>0){const e=Array.from(new Set(m.map(e=>e.source).filter(e=>"string"==typeof e)));let t=`${m.length} tools`;e.length>3&&(t=`${e.length} servers`),e.length>=1&&e.length<=3&&(t=e.join(", ")),N.push({name:"MCP",tokens:w,detail:t})}S>0&&N.push({name:"Skills",tokens:S,detail:`${g.length} loaded`}),E>0&&N.push({name:"Subagents",tokens:E,detail:`${h.length} loaded`});const r=e+k+_+x,o=C?Math.max(0,t-r):u;o>0&&N.push({name:qA,tokens:o,detail:`${i.user} user · ${i.assistant} assistant`})}N.sort((e,t)=>e.name===BA?-1:t.name===BA||e.name===qA?1:t.name===qA?-1:t.tokens-e.tokens);const R=s.length>0?s[0]?.meta.timestamp??null:null;return{tokensUsed:A,tokenLimit:o,percentage:I,tokensRemaining:M,isEstimated:P,model:r,breakdown:N,autoCompact:buildAutoCompactStatus({tokensUsed:A,tokenLimit:o}),stats:{messageCount:s.length,userMessages:i.user,assistantMessages:i.assistant,toolCalls:a.calls,toolResults:a.results,imageCount:l,sessionStartTime:R},tips:generateTips({percentage:I,conversationTokens:u,totalTokens:A,mcpToolCount:m.length,messageCount:s.length,imageCount:l})}}function formatK(e){if(e<1e3)return String(e);if(e>=1e6){const t=Math.round(e/1e5)/10;return Number.isInteger(t)?`${t}M`:`${t.toFixed(1)}M`}const t=e/1e3;return Number.isInteger(t)?`${t}k`:`${t.toFixed(1)}k`}function formatBreakdownValue(e){return e<1e3?String(e):`${(e/1e3).toFixed(1)}k`}function getLayoutSizes({terminalWidth:e}){const t=Math.max(20,e),n=Math.min(50,Math.max(30,Math.floor(.5*t)));return{labelWidth:16,progressBarWidth:Math.max(10,Math.min(n,t-10)),showBreakdownDetail:t>=70}}function ContextProgress({analysis:e,progressBarWidth:t}){const n=getUsageColor(e.percentage),r=buildBlockBar({percentage:e.percentage,width:t});return re.createElement(K,{flexDirection:"column"},re.createElement(K,{marginBottom:1},re.createElement(K,{flexShrink:0},re.createElement(Y,{backgroundColor:gr.BLUE,color:"#f4f4f4",bold:!0},`${p_}CONTEXT${p_}`)),re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:gr.GRAY},getModelDisplayName(e.model))),re.createElement(K,null,re.createElement(Y,{color:n},r.filled),re.createElement(Y,{color:Tr},r.empty),re.createElement(Y,{bold:!0,color:n},` ${e.percentage.toFixed(1)}%`)),re.createElement(K,null,re.createElement(Y,null,formatK(e.tokensUsed)),re.createElement(Y,{color:gr.GRAY},` / ${formatK(e.tokenLimit)}`),re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:n},formatK(e.tokensRemaining)),re.createElement(Y,{color:gr.GRAY}," remaining"),e.isEstimated&&re.createElement(Y,{color:gr.DIM}," (estimated)")))}function CompactionDistance({analysis:e}){if(e.percentage<40)return null;const t=e.autoCompact.tiers.find(e=>3===e.tier);if(!t||"passed"===t.status)return null;const{tokensAway:n}=t;let r=gr.GRAY;return n<=5e4&&(r=gr.YELLOW),n<=2e4&&(r=gr.RED),re.createElement(K,{marginTop:1},re.createElement(Y,{color:r},`~${formatK(n)}`),re.createElement(Y,{color:gr.DIM}," until auto-compact"))}function BreakdownRow({item:e,labelWidth:t,numWidth:n,showDetail:r}){return re.createElement(K,null,re.createElement(Y,null,e.name.padEnd(t)),re.createElement(Y,{bold:!0},formatBreakdownValue(e.tokens).padStart(n)),re.createElement(Y,{color:gr.GRAY}," tokens"),r&&e.detail&&re.createElement(Y,{color:gr.DIM},` · ${e.detail}`))}function ContextBreakdown({analysis:e,labelWidth:t,showBreakdownDetail:n}){const r=e.breakdown.filter(e=>e.tokens>0);if(0===r.length)return null;const o=Math.max(4,...r.map(e=>formatBreakdownValue(e.tokens).length));return re.createElement(K,{flexDirection:"column",marginTop:1},r.map(e=>re.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t,numWidth:o,showDetail:n})))}function ContextTips({tips:e}){return 0===e.length?null:re.createElement(K,{flexDirection:"column",marginTop:1},e.map(e=>re.createElement(K,{key:e},re.createElement(Y,{color:gr.CYAN},Me.pointer),re.createElement(Y,{color:gr.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=getLayoutSizes({terminalWidth:useTerminalWidth()});return re.createElement(K,{flexDirection:"column",paddingTop:1},re.createElement(ContextProgress,{analysis:e,progressBarWidth:t.progressBarWidth}),re.createElement(CompactionDistance,{analysis:e}),re.createElement(ContextBreakdown,{analysis:e,labelWidth:t.labelWidth,showBreakdownDetail:t.showBreakdownDetail}),re.createElement(ContextTips,{tips:e.tips}))}function ContextConfigView({staticKey:e,contextEngineRef:t,setShowContextView:n,setInput:r}){const[o,s]=se(null),[i,a]=se(null);return ae(()=>{let e=!0;return __name(async()=>{if(t.current)try{const n=await analyzeContext({contextEngine:t.current});e&&s(n)}catch{e&&a("Failed to analyze context.")}else e&&a("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),Z((e,t)=>{t.escape&&(WE(),r(""),n(!1))}),re.createElement(re.Fragment,null,re.createElement(Bx,{staticKey:e}),re.createElement(K,{flexDirection:"column",width:"100%"},i?re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:hr,bold:!0},"Context"),re.createElement(Y,{color:gr.DIM},i)):o?re.createElement(ContextMessage,{analysis:o}):re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:hr,bold:!0},"Context"),re.createElement(Y,{color:gr.DIM},"Loading context analysis...")),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press Esc to return to conversation"))))}__name(countMessagesByRole,"countMessagesByRole"),__name(countToolCalls,"countToolCalls"),__name(countImages,"countImages"),__name(estimateConversationTokens,"estimateConversationTokens"),__name(buildAutoCompactStatus,"buildAutoCompactStatus"),__name(getPrimaryTip,"getPrimaryTip"),__name(getSecondaryTip,"getSecondaryTip"),__name(generateTips,"generateTips"),__name(collectMemoryItems,"collectMemoryItems"),__name(collectBuiltInTools,"collectBuiltInTools"),__name(collectMcpTools,"collectMcpTools"),__name(collectSkillItems,"collectSkillItems"),__name(collectAgentItems,"collectAgentItems"),__name(sumTokens,"sumTokens"),__name(analyzeContext,"analyzeContext"),GE(),Ut(),io(),jr(),__name(formatK,"formatK"),__name(formatBreakdownValue,"formatBreakdownValue"),__name(getLayoutSizes,"getLayoutSizes"),__name(ContextProgress,"ContextProgress"),__name(CompactionDistance,"CompactionDistance"),__name(BreakdownRow,"BreakdownRow"),__name(ContextBreakdown,"ContextBreakdown"),__name(ContextTips,"ContextTips"),__name(ContextMessage,"ContextMessage"),jr(),__name(ContextConfigView,"ContextConfigView"),Ut(),Ut(),kn(),Hs(),jS(),$o(),bo(),co();var zA="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,o=0;try{const r=await loadAllSkillSummaries();e=r.global.length,t=r.project.length;const{names:o}=await loadDisabledSkills();n=[...r.global,...r.project].filter(e=>o.has(e.name)).length}catch{}try{const e=await loadAllAgents();r=e.personal.length,o=e.project.length}catch{}return{personalSkills:e,projectSkills:t,disabledSkills:n,personalAgents:r,projectAgents:o}}function execGitAsync(e){return new Promise(t=>{Te("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(!O(e))return!1;try{return(await I(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=O(n),o=r||await hasTasteMdFiles(e);let s=!0;try{s=await isTasteLearningEnabled()}catch{}return{fileExists:o,filePath:r?n:e,learningEnabled:s}}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=L_(S.platform()),t=J_(),n=X_(),r=Z_()}catch{e="Unknown",t="Unknown",n="Unknown",r="N/A"}return{cwd:process.cwd(),os:e,arch:S.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:S.arch(),shell:"Unknown",terminal:"Unknown",nodeVersion:process.version,ide:null,proxy:null}),[n,r,o,s,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,disabledSkills: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:o,skillsAgents:s,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 formatSkillsValue(e){const{personal:t,project:n,disabled:r}=e,o=t+n;return 0===o?"None":0===r?formatCountValue(t,n):`${o-r} active · ${r} off · (${t} user, ${n} project installed)`}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"),Ut(),kn(),Jb(),jr(),uo(),__name(formatCountValue,"formatCountValue"),__name(formatSkillsValue,"formatSkillsValue"),__name(formatSystemValue,"formatSystemValue");var WA=__name(({label:e,value:t,valueColor:n,dimValue:r})=>re.createElement(K,null,re.createElement(Y,{dimColor:!0},`${e}:`.padEnd(14)),r?re.createElement(Y,{dimColor:!0},t):re.createElement(Y,{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}`,o=t.git.branch||"N/A",s=t.git.worktreePath?toRelativePath(t.git.worktreePath):null,i=t.auth.authenticated?Me.tick:Me.cross,a=t.auth.authenticated?gr.WHITE:Cr.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 re.createElement(K,{flexDirection:"column",paddingX:0},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Command Code"," "),re.createElement(Y,{dimColor:!0},n)),re.createElement(K,null,re.createElement(Y,{dimColor:!0},"Visit "),re.createElement(ao,{url:zA,text:zA,color:gr.CYAN}),re.createElement(Y,{dimColor:!0}," for usage and billing")),re.createElement(K,{marginTop:1},re.createElement(Y,{dimColor:!0},"Account:".padEnd(14)),t.auth.authenticated&&t.auth.username?re.createElement(re.Fragment,null,re.createElement(ao,{url:`https://commandcode.ai/${t.auth.username}/`,text:t.auth.username,color:gr.CYAN}),re.createElement(Y,{color:a}," ",i)):t.auth.authenticated?re.createElement(re.Fragment,null,re.createElement(Y,null,"Authenticated"),re.createElement(Y,{color:a}," ",i)):re.createElement(re.Fragment,null,re.createElement(Y,{color:Cr.WARNING},"Not signed in"),re.createElement(Y,{color:a}," ",i),re.createElement(Y,{dimColor:!0}," — run "),re.createElement(Y,{bold:!0},"/login"))),re.createElement(WA,{label:"Model",value:r}),re.createElement(WA,{label:"Branch",value:o,dimValue:!t.git.branch}),s?re.createElement(WA,{label:"Worktree",value:s}):null,t.git.remoteUrl?re.createElement(K,null,re.createElement(Y,{dimColor:!0},"Repository:".padEnd(14)),re.createElement(ao,{url:t.git.remoteHttpUrl||`https://github.com/${t.git.remoteUrl}`,text:t.git.remoteUrl,color:gr.CYAN}),t.pr?re.createElement(re.Fragment,null,re.createElement(Y,{dimColor:!0}," · "),re.createElement(ao,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?gr.CYAN:gr.GRAY}),re.createElement(Y,{dimColor:!0}," ","(",t.pr.state.toLowerCase(),")")):null):t.pr?re.createElement(K,null,re.createElement(Y,{dimColor:!0},"Pull Request:".padEnd(14)),re.createElement(ao,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?gr.CYAN:gr.GRAY}),re.createElement(Y,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null,re.createElement(WA,{label:"Taste",value:d,dimValue:!t.taste.fileExists}),re.createElement(WA,{label:"Directory",value:toRelativePath(t.system.cwd)}),re.createElement(WA,{label:"Skills",value:formatSkillsValue({personal:t.skillsAgents.personalSkills,project:t.skillsAgents.projectSkills,disabled:t.skillsAgents.disabledSkills}),dimValue:0===l}),re.createElement(WA,{label:"Agents",value:formatCountValue(t.skillsAgents.personalAgents,t.skillsAgents.projectAgents),dimValue:0===u}),re.createElement(WA,{label:"System",value:formatSystemValue({system:t.system})}),t.system.proxy?re.createElement(WA,{label:"Proxy",value:t.system.proxy}):null)}function StatusConfigView({staticKey:e,setShowStatusView:t,setInput:n}){const[r,o]=se({phase:"loading"});return ae(()=>{let e=!1;return gatherStatusData().then(t=>{e||o({phase:"ready",data:t})}).catch(t=>{if(e)return;const n=t instanceof Error?t.message:"Failed to gather status";o({phase:"error",message:n})}),()=>{e=!0}},[]),Z((e,r)=>{r.escape&&(n(""),t(!1))}),re.createElement(re.Fragment,null,re.createElement(Bx,{staticKey:e}),re.createElement(K,{flexDirection:"column",width:"100%"},"ready"===r.phase?re.createElement(StatusMessage,{statusData:r.data}):"error"===r.phase?re.createElement(Y,{dimColor:!0},"Could not load status: ",r.message):re.createElement(Y,{dimColor:!0},"Gathering status…"),re.createElement(K,{marginTop:1},re.createElement(Y,{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:o}=e;return o<=r?0:t<n?t:t>=n+r?t-r+1:n}function getSuggestionBase(e){const n=resolveDirectoryPath(e),r=/[\\/]$/.test(e),o=e.replace(/\\/g,"/");if(o.endsWith("/."))return{searchDirectory:n,prefix:".",outputPrefix:`${o.slice(0,-1)}`};if(r)return{searchDirectory:n,prefix:"",outputPrefix:o};const s=o.lastIndexOf("/");return-1===s?{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:""}:{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:o.slice(0,s+1)}}function getDirectorySuggestions(e){const t=e.trim();if(!t)return[];try{const{searchDirectory:e,prefix:n,outputPrefix:r}=getSuggestionBase(t),o=n.startsWith(".")||r.includes("/.");return D.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!!o||!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"),Ut(),Ut(),jo(),Ut(),jo(),__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"),jr(),zr();var HA=__name(({onClose:e})=>{const[t,n]=se(""),[r,o]=se(null),[s,i]=se([]),[a,l]=se(getAdditionalDirectories()),[u,d]=se({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,g]=se(0);ae(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),g(0)},[t]),ae(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const h=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),f=__name(e=>{if(!removeAdditionalDirectory(e))return o({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void l(getAdditionalDirectories());o({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");Z((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&s[u.suggestionIndex]?void h(s[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])f(a[u.activeDirIndex]);else{if(r.tab&&s.length>0){const e=s[u.suggestionIndex]??s[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),o(null)))}r.downArrow?d(e=>moveFocusDown(e,{suggestionCount:s.length,activeDirCount:a.length})):r.upArrow&&d(e=>moveFocusUp(e,{suggestionCount:s.length,activeDirCount:a.length}))}}}),ae(()=>{"suggestions"===u.zone&&g(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:s.length}))},[u,s.length]),ae(()=>{d(e=>"suggestions"===e.zone&&e.suggestionIndex>=s.length?{...e,zone:"input",suggestionIndex:Math.max(0,s.length-1)}:"active-dir"===e.zone&&e.activeDirIndex>=a.length?{...e,zone:"input",activeDirIndex:Math.max(0,a.length-1)}:e)},[s.length,a.length]);const y=s.slice(m,m+8),w=getFooterText({focusZone:u.zone});return re.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:gr.CYAN,paddingX:1,paddingY:0},re.createElement(Y,{bold:!0,color:gr.CYAN},"Add directory to workspace"),re.createElement(Y,{color:gr.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:gr.GRAY},"Added directories"),0===a.length?re.createElement(Y,{color:gr.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return re.createElement(Y,{key:e,color:n?gr.YELLOW:gr.GREEN,bold:n},n?` ${Me.pointer} `:" ",formatDirectoryForDisplay(e))})),re.createElement(K,{marginTop:1},re.createElement(Y,{bold:!0,color:gr.WHITE},"Path")),re.createElement(K,null,re.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?Me.pointer:" "} `,prefixColor:"input"===u.zone?gr.CYAN:gr.GRAY,onChange:e=>{n(e),o(null)},onSubmit:h})),!t&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:{error:gr.RED,warning:gr.YELLOW,success:gr.GREEN}[r.tone]},r.text)),s.length>0&&re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:gr.GRAY},"Suggestions"),y.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return re.createElement(Y,{key:e,color:r?gr.CYAN:gr.GRAY,bold:r},r?` ${Me.pointer} `:" ",e)})),re.createElement(K,{marginTop:1},re.createElement(BracketedText,{text:w,color:gr.DIM})))},"AddDirModal");Ut(),Ut(),kn(),Ut(),Ut(),kn(),jr();var GA=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),VA=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),QA=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=se("idle"),[i,a]=se(""),l=[...pT.map(e=>e.name),...gT.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void a("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?GA():VA();await k.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),i=Array.from(e.selectedTools).map(e=>yT[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 k.writeFile(s,u,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),s("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");Z((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||u()});const d=Array.from(e.selectedTools).map(e=>yT[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return re.createElement(K,{flexDirection:"column",gap:1},re.createElement(K,{flexDirection:"column"},re.createElement(K,{gap:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"Name:"),re.createElement(Y,{color:gr.GRAY},e.agentType)),re.createElement(K,{gap:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"Location:"),re.createElement(Y,{color:gr.GRAY},m)),re.createElement(K,{gap:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"Tools:"),re.createElement(Y,{color:gr.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),re.createElement(K,{gap:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"Description"),re.createElement(Y,{color:gr.GRAY},"(Tells ","Command Code"," when to use this agent):")),re.createElement(Y,{color:gr.GRAY},e.ccToolDefinition),re.createElement(K,{gap:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"System Prompt:")),re.createElement(Y,{color:gr.GRAY},e.sysPrompt),!r&&re.createElement(K,{marginTop:1},"idle"===o&&re.createElement(K,{gap:1},re.createElement(Y,{color:gr.GREEN,dimColor:!0},"Press"),re.createElement(Y,{color:gr.GREEN,bold:!0},"Enter"),re.createElement(Y,{color:gr.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===o&&re.createElement(Y,{color:gr.YELLOW},"Saving agent..."),"saved"===o&&re.createElement(Y,{color:gr.GREEN},Me.tick," ",i),"error"===o&&re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.RED},Me.cross," Error: ",i),re.createElement(Y,{color:gr.GRAY},"Press Enter to retry"))))},"AgentSummary");jr();var KA=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=se("menu"),i=[...pT.map(e=>e.name),...gT.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=>wT[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?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect"),m=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],g=__name(async r=>{if("confirm-delete"===r.value)try{await k.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return Z((e,n)=>{if(n.escape)"menu"===o?t():s("menu");else if(n.return&&"view"===o)s("menu");else if(1===e.length&&e>="1"&&e<="9"){const t=Number(e)-1;if("menu"===o){const e=u[t];e&&d(e)}else if("delete"===o){const e=m[t];e&&g(e)}}}),"view"===o?re.createElement(K,{flexDirection:"column"},re.createElement(QA,{config:l,onSaveComplete:()=>s("menu"),viewOnly:!0}),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.GRAY},"Press Enter to go back"))):"edit"===o?re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.YELLOW},"Edit functionality coming soon..."),re.createElement(Y,{color:gr.GRAY},"Press Esc to go back")):"delete"===o?re.createElement(K,{flexDirection:"column",gap:1},re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.RED},"Delete agent"),re.createElement(Y,{color:gr.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),re.createElement(K,null,re.createElement(gt,{items:m,onSelect:g,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY,backgroundColor:e?xr:void 0,bold:e},` ${t} `)}))):re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.WHITE,bold:!0},e.name),re.createElement(K,{marginTop:1},re.createElement(gt,{items:u,onSelect:d,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY,backgroundColor:e?xr:void 0,bold:e},` ${t} `)})),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");jr();var YA=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=se([]),[s,i]=se([]),[a,l]=se([]),[u,d]=se(!0),[m,g]=se(!1),[h,f]=se(null),[y,w]=se(!1),[E,v]=se(0),[C,T]=se(0),_=useTerminalHeight(),x=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),A=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),P=__name(async(e,n)=>{try{g(!1);const r=(await k.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await k.readFile(o,"utf-8"),{data:i,content:a}=je(s);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:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");ae(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([P(x(),"personal"),P(A(),"project")]),n=jk.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}`}));o(e),i(t),l(n),d(!1)},"loadAgents")()},[m]);const I=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{I.push({label:e.name,value:e.filePath})}),s.forEach(e=>{I.push({label:e.name,value:e.filePath})});const M=r.length+s.length,N=(r.length>0?1:0)+(s.length>0?1:0),R=__name(e=>0===e?"action":e<=r.length?"user":"project","sectionOf"),$=_-1,L=Math.max(4,$-11-a.length-2*N),D=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(f(e),w(!0))}},"handleAgentSelect");if(Z((e,t)=>{if(t.upArrow)v(e=>Math.max(0,e-1));else if(t.downArrow)v(e=>Math.min(I.length-1,e+1));else if(t.return){const e=I[E];e&&D(e)}},{isActive:!u&&!y}),ae(()=>{v(e=>Math.min(e,Math.max(0,I.length-1)))},[I.length]),ae(()=>{T(e=>clampScrollOffset({cursor:E,total:I.length,maxVisible:L,currentOffset:e}))},[E,I.length,L]),u)return re.createElement(Y,{color:gr.GRAY},"Loading agents...");if(y&&h){const e=h.filePath.startsWith("__builtin__:");return re.createElement(KA,{agent:h,onBack:()=>{w(!1),f(null)},setRevalidateAgent:g,isReadOnly:e})}const O=C,F=C+L,U=I.slice(O,F),j=I.length>L;let B=null;return re.createElement(K,{flexDirection:"column"},re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"Agents"),M>0?re.createElement(Y,{color:gr.GRAY}," ","(",M," agent",M>1?"s":"",")"):re.createElement(Y,{color:gr.GRAY}," (No custom agents)")),n&&re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{color:gr.GREEN,dimColor:!0},"Created agent: ",n)),re.createElement(K,{flexDirection:"column"},U.map((e,t)=>{const n=O+t,r=R(n),o="action"!==r&&r!==B;B=r;const s=n===E,i="user"===r?"User agents":"Project agents";return re.createElement(re.Fragment,{key:e.value},o&&re.createElement(K,{marginTop:0===t?0:1},re.createElement(Y,{color:Tr,bold:!0},i)),re.createElement(K,null,re.createElement(Y,{color:s?gr.WHITE:gr.GRAY,backgroundColor:s?xr:void 0,bold:s},e.label," ")))})),j&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",O+1,"–",Math.min(F,I.length)," of ",I.length,O>0?" · ↑ more":"",F<I.length?" · ↓ more":"")),a.length>0&&re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:Tr,bold:!0},"Default agents"),a.map(e=>re.createElement(Y,{key:e.filePath,color:gr.DIM},e.name.charAt(0).toUpperCase()+e.name.slice(1)))),re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:gr.DIM},"Create specialized subagents that Command Code can delegate to."),re.createElement(Y,{color:gr.DIM},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Ut(),kn(),Ys(),jr(),Ut(),Ut(),kn(),jr();var JA=__name(({onSelect:e})=>re.createElement(gt,{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})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY},` ${t}`)}),"LocationSelector");Ut(),zr(),kn(),Kr(),Zr(),jr();var XA=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=se(!1),[g,h]=se(!1),f=ce(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?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(m(!0),t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),y=ce(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||g){if(!g||t.isPasteEnd){if(g&&t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(h(!0),t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[g,i]);return"agentType"===e?re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(yT).some(e=>Be(e)===Be(t))||Object.keys(yT).some(e=>Be(e)===Be(t)))&&re.createElement(Y,{color:gr.RED},Me.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Be(t))&&re.createElement(Y,{color:gr.RED},Me.warning," This name is reserved. Reserved names: ",Uk.join(", "))),re.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Be(t);Object.values(yT).some(t=>Be(t)===e)||Object.keys(yT).some(t=>Be(t)===e)||isReservedAgentName(e)||a()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.WHITE},"Enter the system prompt for your agent:"),re.createElement(Y,{color:gr.GRAY},"Be comprehensive for best results.")),re.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:f,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.WHITE},"When should ","Command Code"," use this agent?"),re.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:y,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Ut(),jr();var ZA=__name(({onSelect:e})=>re.createElement(gt,{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})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY},` ${t}`)}),"MethodSelector");Ut(),zr(),Ut(),HE(),jr();var eP=["·","○","◇","☆","✧","☆","◇","○","⌘"],tP=[12,5,4,4,4,4,4,5,16],nP=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<tP.length;e++)if(n+=tP[e],t<n)return eP[e];const r=t-58;n=0;for(let e=0;e<nP.length;e++)if(n+=nP[e],r<n)return eP[7-e];return eP[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=le(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<$r.length?$r[n]:Lr},"getCharColor");return re.createElement(Y,null,r.map((e,t)=>re.createElement(Y,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return re.createElement(Y,{color:t??hr,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 rP=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=se(0),[s,i]=se(0),a=ie(n);a.current=n;const l=getTerminalWidth(),[u,d]=se(()=>l>=72?"all":l>=42?"medium":"none");ae(()=>{d(e=>"all"===e?l<68?l>=42?"medium":"none":"all":"medium"===e?l>=72?"all":l<38?"none":"medium":l>=72?"all":l>=42?"medium":"none")},[l]),ae(()=>{const e=setInterval(()=>{o(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 m=r%(e.length+10),g="all"===u,h="medium"===u;return BE.statusRender({width:l,layoutMode:u,status:e,frame:r}),re.createElement(K,{width:l,height:1,paddingLeft:0,marginLeft:0},re.createElement(K,{flexShrink:0},re.createElement(Y,{backgroundColor:Er.BG,color:Er.FG}," "),re.createElement(Y,{backgroundColor:Er.BG},re.createElement(CMDIcon,{frame:4*r})),re.createElement(ShimmerText,{text:e,offset:m,bg:Er.BG}),re.createElement(Y,{backgroundColor:Er.BG,color:Er.FG}," ")),g&&re.createElement(K,{columnGap:1,marginLeft:1},re.createElement(Y,{bold:!0,color:gr.GRAY},"esc"),re.createElement(Y,{color:gr.DIM},"to interrupt"),re.createElement(Y,{color:gr.DIM},"•"),re.createElement(Y,{color:gr.DIM},formatTime3(t)),re.createElement(Y,{color:gr.DIM},"•"),re.createElement(Y,{color:gr.GRAY},Me.arrowDown),re.createElement(Y,{color:gr.DIM},formatToken(Math.round(s)))),h&&re.createElement(K,{marginLeft:1},re.createElement(Y,{color:gr.DIM},formatToken(Math.round(s)))))},"Status");Zr(),Kr(),jr();var oP=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,i]=se(!1),[a,l]=se(0),[u,d]=se(0);ae(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=ce(()=>{0!==e.trim().length&&n()},[e,n]),g=ce(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&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)))}},[s,t]);return re.createElement(K,{flexDirection:"column"},r?re.createElement(K,null,re.createElement(CMDIcon,{frame:u}),re.createElement(Y,{color:gr.WHITE},"Generating agent from description...")):re.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:g,onSubmit:m}),o&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.RED},`${Me.warning} ${o}`)))},"RecommendedFlow");Ut(),jr();var sP=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=se(!1),[i,a]=se(0),[l,u]=se(0),d=useTerminalHeight(),m=le(()=>[...pT.map(e=>e.name),...gT.map(e=>e.name)],[]),g=le(()=>[{name:"All tools",tools:m},{name:"Read-only tools",tools:m.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:m.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:m.filter(e=>"shell_command"===e)},{name:"Search tools",tools:m.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:m.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),[m]),h=le(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(g.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:"}),m.forEach(t=>{e.push({type:"tool",value:t})})):(g.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[o,g,e,m]),f=h.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=g.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${o?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${yT[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),y=f.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type),w=Math.max(5,d-1-10),S=y[i]?.value??0;ae(()=>{u(e=>clampScrollOffset({cursor:S,total:f.length,maxVisible:w,currentOffset:e}))},[S,f.length,w]);const E=l,v=l+w,C=f.slice(E,v),k=f.length>w;return Z((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?y.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=y.length?0:t});else if(l.return||" "===e){const e=y[i];if(e){const i=h[e.value];if(!i)return;"continue"===i.type?r():"toggle"===i.type?(s(!o),a(0)):"category"===i.type?n(i.value):"tool"===i.type&&t(i.value)}}}),re.createElement(K,{flexDirection:"column"},C.map(e=>{const t=y.findIndex(t=>t.value===e.value),n=-1!==t&&t===i;if("divider"===e.type)return re.createElement(K,{key:`divider-${e.value}`},re.createElement(Y,{color:gr.GRAY}," ",e.label));if("spacer"===e.type)return re.createElement(K,{key:`spacer-${e.value}`,height:1});if("label"===e.type)return re.createElement(K,{key:`label-${e.value}`},re.createElement(Y,{color:gr.GRAY}," ",e.label));const r="continue"===e.type;return re.createElement(K,{key:`item-${e.value}`},re.createElement(Y,{color:n?gr.WHITE:gr.GRAY,bold:r&&n},n?">":" "," ",e.label))}),k&&re.createElement(K,null,re.createElement(Y,{color:gr.GRAY}," ","Showing ",E+1,"–",Math.min(v,f.length)," of"," ",f.length,E>0?" · ↑ more":"",v<f.length?" · ↓ more":"")),re.createElement(K,{marginTop:1},e.size===m.length&&re.createElement(Y,{color:gr.GRAY},"All tools selected"),e.size>0&&e.size<m.length&&re.createElement(Y,{color:gr.GRAY},e.size," tools selected"),0===e.size&&re.createElement(Y,{color:gr.GRAY},"No tools selected")))},"ToolsSelector");Eo(),LS(),vS(),Gs(),YE(),co();var iP=__name(({onComplete:e})=>{const[t,n]=se("location"),[r,o]=se(!1),[s,i]=se(null),[a,l]=se("agentType"),u=le(()=>[...pT.map(e=>e.name),...gT.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,g]=se(d()),h=__name(t=>{n("location"),l("agentType"),g(d()),e(t)},"resetToDefaults"),f=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===a)return"Agent type (identifier)";if("sysPrompt"===a)return"System prompt";if("ccToolDefinition"===a)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),y=__name(e=>{g({...m,location:e}),n("method")},"handleLocationSelect"),w=__name(e=>{g({...m,method:e}),n("configuration")},"handleMethodSelect"),S=__name(async()=>{try{i(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced(),{token:r,oauthProvider:s}=await getOAuthCredentials({provider:e});validateOAuthToken({token:r,provider:e});const a={[zt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(a[zt.OAUTH_TOKEN]=`Bearer ${r}`,s&&(a[zt.OAUTH_PROVIDER]=s));const l=getApiBaseUrl(),u=new rS({baseUrl:l}),d=parseModelString(getConfiguredModel()).modelId,h=await u.post({headers:a,endpoint:Wt.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:d}});g({...m,agentType:Be(h.agentName),sysPrompt:h.systemPrompt,ccToolDefinition:h.toolDescription}),n("tools")}catch(e){if(e instanceof Ls&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")){const e=await getBillingLink({billingLink:null,setBillingLink:__name(()=>{},"setBillingLink")})??"https://commandcode.ai/billing";i(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: ${e}`)}else i("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),E=__name(()=>{g({...m,agentType:Be(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),v=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),C=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),T=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),g({...m,selectedTools:t})},"handleToggleTool"),_=__name(e=>{const t=[{name:"All tools",tools:u},{name:"Read-only tools",tools:u.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:u.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:u.filter(e=>"shell_command"===e)},{name:"Search tools",tools:u.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:u.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(m.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),g({...m,selectedTools:n})},"handleToggleCategory");return re.createElement(K,{flexDirection:"column",gap:1},re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.WHITE,bold:!0},"Create new agent"),re.createElement(Y,{color:gr.GRAY},f())),re.createElement(K,null,"location"===t&&re.createElement(JA,{onSelect:y}),"method"===t&&re.createElement(ZA,{onSelect:w}),"configuration"===t&&"recommended"===m.method&&re.createElement(oP,{description:m.recommendedMethodDescription,onChange:e=>g({...m,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:S}),"configuration"===t&&"manual"===m.method&&re.createElement(K,{flexDirection:"column",gap:1},re.createElement(XA,{step:a,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>g({...m,agentType:e}),onSysPromptChange:e=>g({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>g({...m,ccToolDefinition:e}),onAgentTypeSubmit:E,onSysPromptSubmit:v,onCCToolDefinitionSubmit:C})),"tools"===t&&re.createElement(sP,{selectedTools:m.selectedTools,onToggleTool:T,onToggleCategory:_,onComplete:k}),"summary"===t&&re.createElement(QA,{config:m,onSaveComplete:h})))},"AgentNew"),aP=__name(({onCancel:e})=>{const[t,n]=se(null),[r,o]=se(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return Z((t,n)=>{n.escape&&e()}),re.createElement(K,{width:"100%",flexDirection:"column"},null===t&&re.createElement(YA,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&re.createElement(iP,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");jr(),Ut(),co(),jr();var lP=[{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."}],cP=__name(({onSelect:e,onCancel:t})=>{const[n,r]=se(null);ae(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(Z((e,n)=>{n.escape&&t()}),null===n)return null;const s=lP.findIndex(e=>e.value===n);return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Select a compact mode to compact sessions")),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"Choose how Command Code handles automatic context compaction.")),re.createElement(gt,{items:lP,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>{const r=lP.find(e=>e.label===t),o=r?.value===n,s=lP.findIndex(e=>e.label===t),i=e?xr:void 0;return re.createElement(K,{flexDirection:"column"},re.createElement(K,null,re.createElement(Y,{color:e||!o?gr.WHITE:gr.GREEN,backgroundColor:i,bold:e},` ${s+1}. ${r?.label??t} `),o&&re.createElement(Y,{color:gr.GREEN}," ",Me.tick)),re.createElement(Y,{color:e?gr.WHITE:gr.DIM,backgroundColor:i},` ${r?.description??""} `))}}),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press "),re.createElement(Y,{color:gr.DIM,bold:!0},"Esc"),re.createElement(Y,{color:gr.DIM}," to cancel")))},"CompactModeSelector");Ut(),kn(),io(),bo(),co(),yo(),Ut(),kn(),jr();var uP=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o,showDefaultBadge:s=!0})=>{const i=yn[t],a=o??i?.showProviderLabelInSelector??!1,l=e.vendorLabel??hn[e.provider],u=s&&e.id===gn,d="free"===e.badge,m=u?`${e.label} (default)`:e.label,g=d?" (FREE)":"",h=" ".repeat(Math.max(0,32-m.length-g.length)),f=n?xr:void 0,y=e.description?`${a?`${l} · `:""}${e.description}`:"",w=useTerminalWidth()>=70&&y;return re.createElement(K,null,re.createElement(Y,{backgroundColor:f,color:r?gr.GREEN:gr.WHITE},m),d&&re.createElement(Y,{backgroundColor:f,color:gr.GREEN,bold:!0},g),w&&re.createElement(re.Fragment,null,re.createElement(Y,{backgroundColor:f},h),re.createElement(Y,{backgroundColor:f,color:gr.DIM},y)),re.createElement(Y,{backgroundColor:f,color:gr.GREEN},r?` ${Me.tick} `:" "))},"ModelRow");jr();var dP=__name(e=>[{text:e.name,weight:100},{text:e.label,weight:50},{text:e.provider,weight:25},{text:e.description||"",weight:10}],"MODEL_SEARCH_FIELDS");function searchGroups(e,t){if(!t.trim())return e;const n=[];for(const r of e){const e=fuzzyFilter(r.models,t,dP);e.length>0&&n.push({...r,models:e})}return n}function groupByModelProvider(e,t){return groupModelsByDisplayOrder(e).map(e=>({providerId:t,label:e.label,models:e.models}))}__name(searchGroups,"searchGroups"),__name(groupByModelProvider,"groupByModelProvider");var mP=__name(({featureLabel:e,defaultLabel:t,currentModelId:n,onPick:r,onBack:o})=>{const[s,i]=se(""),a=le(()=>isInternalTeamFlagEnforced(),[]),[l,u]=se(()=>getCachedBillingContext());ae(()=>{if(l)return;let e=!0;return getBillingContext().then(t=>{e&&u(t)}),()=>{e=!1}},[l]);const d=null!==l,m=le(()=>a?wn:groupByModelProvider(Sn.flatMap(e=>e.models),yn["command-code"].id),[a]),g=le(()=>l?m.map(e=>({...e,models:e.models.filter(e=>checkModelAccess({model:{id:e.id,provider:e.provider,name:e.name},planId:l.planId,purchasedCredits:l.purchasedCredits,freeCredits:l.freeCredits}).allowed)})).filter(e=>e.models.length>0):[],[m,l]),h=le(()=>searchGroups(g,s),[g,s]),f=le(()=>{const e=[];for(const t of h)for(const n of t.models)e.push({kind:"model",providerId:t.providerId,model:n});return[{kind:"reset"},...e]},[h]),y=le(()=>{if(!n)return 0;const e=f.findIndex(e=>"model"===e.kind&&e.model.id===n);return e>=0?e:0},[f,n]),{cursor:w}=useListNavigation({items:f,initialIndex:y,searchCursorIndex:1,searchQuery:s,onSearchChange:i,onSelect:__name(e=>{d&&r("reset"===e.kind?void 0:e.model.id)},"onSelect"),onCancel:o}),[S,E]=se(0),v=useTerminalHeight()-1,C=Math.max(4,v-11-2*h.length);ae(()=>{E(e=>clampScrollOffset({cursor:w,total:f.length,maxVisible:C,currentOffset:e}))},[w,f.length,C]);const k=S,T=S+C,_=0===k;let x=1;const A=h.map(e=>{const t=sliceSectionForWindow({section:e.models,sectionBase:x,windowStart:k,windowEnd:T});return x+=e.models.length,{group:e,groupWindow:t}}).filter(e=>e.groupWindow.rows.length>0),P=f.length>C;return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},e," › select model")),re.createElement(K,{marginBottom:1},re.createElement(Y,{dimColor:!0},"Pick a model for this task, or reset it to the default.")),isCmdZdrEnabled()&&re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.YELLOW},"Your pick is saved but stays paused until CMD_ZDR is unset.")),re.createElement(K,{marginBottom:2,flexDirection:"column",width:"100%"},re.createElement(TA,{query:s,resultCount:s?f.length-1:void 0,placeholder:"Type to search models..."})),d?re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"column"},_&&re.createElement(K,{flexDirection:"column"},re.createElement(Y,{bold:!0,dimColor:!0},"Default"),re.createElement(K,null,re.createElement(Y,{backgroundColor:0===w?xr:void 0,color:n?gr.WHITE:gr.GREEN},t," "),!n&&re.createElement(Y,{color:gr.GREEN},Me.tick))),A.map(({group:e,groupWindow:t},r)=>re.createElement(K,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:0!==r||_?1:0},re.createElement(Y,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>re.createElement(uP,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===w,isCurrent:r.id===n,showProviderLabel:!!a&&void 0,showDefaultBadge:!1}))))),P&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",k+1,"–",Math.min(T,f.length)," of"," ",f.length,k>0?" · ↑ more":"",T<f.length?" · ↓ more":""))):re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"Loading available models…")),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"type to search · ↑/↓ navigate · enter select"),s?re.createElement(Y,{color:gr.DIM}," · esc to clear"):re.createElement(Y,{color:gr.DIM}," · esc back")))},"FeatureModelPicker");function sanitizeFeatureOverrides(e){const t={};for(const{key:n}of Zk){const r=e?.[n];"string"==typeof r&&r&&(t[n]=r)}return t}__name(sanitizeFeatureOverrides,"sanitizeFeatureOverrides");var pP=__name(({onClose:e})=>{const[t,n]=se(null),[r,o]=se(null),[s,i]=se(null);ae(()=>{loadUserConfig().then(e=>{n(sanitizeFeatureOverrides(e.featureModels))})},[]);const a=r?"picker":"list",{cursor:l}=useListNavigation({items:Zk,initialIndex:0,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,isActive:"list"===a&&null!==t,onSelect:__name(e=>{i(null),o(e.key)},"onSelect"),onCancel:e,onReset:__name(async e=>{try{await setFeatureModel({feature:e.key,model:void 0}),n(t=>{const n={...t??{}};return delete n[e.key],n}),i({text:`${e.label} reset to default`})}catch{i({text:`Couldn't reset ${e.label} — try again`,error:!0})}},"onReset")});if(null===t)return null;const u=Zk.find(e=>e.key===r)??null;if("picker"===a&&u)return re.createElement(mP,{featureLabel:u.label,defaultLabel:getFeatureDefaultLabel(u),currentModelId:t[u.key],onBack:()=>o(null),onPick:async e=>{try{await setFeatureModel({feature:u.key,model:e}),n(t=>{const n={...t??{}};return void 0===e?delete n[u.key]:n[u.key]=e,n}),i({text:void 0===e?`${u.label} reset to default`:`${u.label} → ${getModelDisplayName(e)}`})}catch{i({text:`Couldn't save ${u.label} — try again`,error:!0})}o(null)}});const d=isCmdZdrEnabled();return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Configure models")),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"Pick a model for each task. Applies to all sessions."," ",createOSC8Link("https://commandcode.ai/docs/troubleshooting/faqs#why-do-i-see-small-background-requests","Why background requests?",!1))),d&&re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.YELLOW},"Model overrides were reverted to ZDR safe defaults. Your overrides will be restored when CMD_ZDR is unset.")),Zk.map((e,n)=>{const r=t[e.key],o=e.defaultLabel?`Default (${getFeatureDefaultLabel(e)})`:`Uses current model (${getFeatureDefaultLabel(e)})`,s=r?getModelDisplayName(r):null,i=!!r&&!d,a=i&&s?s:o,u=n===l;return re.createElement(K,{key:e.key},re.createElement(Y,{backgroundColor:u?xr:void 0,color:gr.WHITE},e.label.padEnd(20)),re.createElement(Y,{backgroundColor:u?xr:void 0},re.createElement(Y,{color:i?gr.GREEN:gr.DIM},a),s&&d&&re.createElement(Y,{color:gr.DIM},` · ${s} paused`)))}),s&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:s.error?gr.RED:gr.GREEN},s.text)),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"↑/↓ navigate · enter to change · r to reset · esc to close")))},"ConfigureModelsSelector");function settingsFilePaths(e){return[getProjectLocalPath(e),getProjectSharedPath(e),getUserSettingsPath()]}function readInputSettings(e){try{const t=L.readFileSync(e,"utf-8");return parseJSON(t)?.input}catch{return}}function shouldCollapsePastedText(e=process.cwd()){for(const t of settingsFilePaths(e)){const e=readInputSettings(t)?.collapsePastedText;if("boolean"==typeof e)return e}return!0}Ut(),jr(),Ut(),zr(),kn(),Kr(),Ut(),Eo(),__name(settingsFilePaths,"settingsFilePaths"),__name(readInputSettings,"readInputSettings"),__name(shouldCollapsePastedText,"shouldCollapsePastedText"),Qn(),Ut();var gP=n(E(),"commandcode-images"),hP={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{O(gP)||B(gP,{recursive:!0});const r=hP[e.mediaType]||".png",o=`image-${t}-${Date.now()}${r}`,s=n(gP,o),i=Buffer.from(e.data,"base64");return q(s,i),s}catch{return null}}function stripInputAfterSuffix(e,t){return t&&e.endsWith(t)?e.slice(0,e.length-t.length):e}function extractAppendedChunk(e,t,n){const r=t+n;return e.length>=r.length&&e.startsWith(r)?e.slice(r.length):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:o,setDetectedContent:s,incrementInputKey:i,setInitialCursor:a,collapsePastedText:l=!0}=e,u=ce((e,t,n="")=>{o(t=>[...t,e]),r(t+n),a(t.length),i()},[o,r,a,i]),d=ie(!1),m=ie(""),g=ie(null),h=ie(""),f=ie(""),y=ce(async(e,t,o)=>{let d=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const m=await detectDroppedImageFile(d);if(m)return void u(m,t,o);const g=await detectClipboardImage();if(g)return void u(g,t,o);let h=d;if(0===h.length){const e=await detectClipboardText();h=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(!h&&!o)return;if(!h)return r(t+o),a(t.length),void i();if(l&&h.length>300){const e=t+`[Text#${n.length+1}]`;return s(e=>[...e,h]),r(e+o),a(e.length),void i()}const f=t+h;r(f+o),a(f.length),i()},[u,n.length,s,r,a,i,l]),w=ce(()=>{g.current&&clearTimeout(g.current),g.current=setTimeout(async()=>{if(d.current){const e=m.current,t=h.current,n=f.current;m.current="",h.current="",f.current="",d.current=!1,g.current=null,e?await y(e,t,n):n&&await y("",t,n)}},500)},[y]);return{handlePaste:ce(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return d.current&&(d.current=!1,m.current="",h.current="",f.current="",g.current&&(clearTimeout(g.current),g.current=null)),await y(n.pastedContent??n.cleanedContent,n.textBeforePaste??"",n.textAfterPaste??""),!0;if(n.isPasteStart&&!d.current){d.current=!0;const e=n.textBeforePaste??t,r=t.slice(e.length);h.current=e,f.current=r;const o=n.pastedContent??n.cleanedContent;return m.current=stripInputAfterSuffix(o,r),w(),!0}if(d.current&&!n.isPasteEnd){const e=h.current,t=f.current;if(void 0!==n.pastedContent)m.current=stripInputAfterSuffix(n.pastedContent,t);else if(n.cleanedContent){const r=extractAppendedChunk(n.cleanedContent,e,t);m.current=null!==r?m.current+r:accumulateDelta(n.cleanedContent,m.current,e)}return w(),!0}if(d.current&&n.isPasteEnd){g.current&&(clearTimeout(g.current),g.current=null);const e=h.current,t=f.current,r=n.textAfterPaste??"";let o=n.cleanedContent??"";if(r&&o.endsWith(r)&&(o=o.slice(0,o.length-r.length)),void 0!==n.pastedContent)m.current=stripInputAfterSuffix(n.pastedContent,t);else if(o){const n=extractAppendedChunk(o,e,t);m.current=null!==n?m.current+n:accumulateDelta(o,m.current,e)}const s=m.current,i=e,a=r||t;return m.current="",h.current="",f.current="",d.current=!1,await y(s,i,a),!0}if(n.isPasteEnd&&!n.isPasteStart&&!d.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return u(e,t),!0}return!1},[t,y,w,u]),resetPasteState:ce(()=>{d.current=!1,m.current="",h.current="",f.current="",g.current&&(clearTimeout(g.current),g.current=null)},[]),isPasting:ce(()=>d.current,[])}}function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[i,a]=se(!1),[l,u]=se(null),d=ce(async()=>{if(!i){a(!0),u(null);try{let i=e.replace(/\n+$/,"");r.forEach((e,t)=>{const n=`[Text#${t+1}]`;i.includes(n)&&(i=i.replace(n,e))});const a=await openInEditor2(i);t(a),o([]),n(e=>e+1),s?.()}catch(e){u(e instanceof T_?"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{a(!1)}}},[e,t,n,r,o,s,i]),m=ce(()=>{u(null)},[]);return{isEditorOpen:i,editorError:l,handleOpenInEditor:d,clearEditorError:m}}__name(saveTempImage,"saveTempImage"),mr(),Eo(),Ut(),Zr(),Kr(),__name(stripInputAfterSuffix,"stripInputAfterSuffix"),__name(extractAppendedChunk,"extractAppendedChunk"),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),Zr(),Ut(),__name(useExternalEditor,"useExternalEditor"),Ut();var fP=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=se(null),o=ie(!1);return ae(()=>{if(!t||o.current)return;let e=!0;return o.current=!0,v_().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");jr(),Ut(),Ut();var yP=1e5,wP=null,SP=new Map;function memoKey(e,t){return`${e}\0${t}`}function memoize(e,t){if(SP.size>=128){const e=SP.keys().next().value;void 0!==e&&SP.delete(e)}return SP.set(e,t),t}function loadGitignore(e){const t=ot(),r=n(e,".gitignore");if(O(r))try{t.add(U(r,"utf8"))}catch{}return t.add(".git"),t}function isIgnored(e,t,n){return!!e.ignores(t)||n&&e.ignores(`${t}/`)}function listDirectory(e,t){const r=loadGitignore(t),o=[],i=W(e,{withFileTypes:!0});for(const a of i){const i=n(e,a.name),l=a.isDirectory();isIgnored(r,s(t,i),l)||o.push({name:a.name,path:i,isDirectory:l})}return sortDirectoriesFirst(o)}function sortDirectoriesFirst(e){return e.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name))}function buildFileIndex(e){const t=loadGitignore(e),r=[],o=[{dirPath:e,depth:0}];for(let i=0;i<o.length;i++){const{dirPath:a,depth:l}=o[i];if(r.length>=yP)break;let u;try{u=W(a,{withFileTypes:!0})}catch{continue}for(const i of u){if(r.length>=yP)break;const u=n(a,i.name),d=s(e,u),m=i.isDirectory();isIgnored(t,d,m)||(r.push({name:d,path:u,isDirectory:m,nameLower:d.toLowerCase(),filenameLower:i.name.toLowerCase(),depth:l+1}),m&&"node_modules"!==i.name&&l<8&&o.push({dirPath:u,depth:l+1}))}}return r}function getFileIndex(e){if(wP&&wP.basePath===e&&Date.now()-wP.builtAt<3e4)return wP.entries;const t=buildFileIndex(e);return wP={basePath:e,entries:t,builtAt:Date.now()},SP.clear(),t}function invalidateFileIndex(){wP=null,SP.clear()}function compareByRelevance(e,t,n){const r=e.nameLower===n,o=t.nameLower===n;if(r&&!o)return-1;if(!r&&o)return 1;const s=e.filenameLower.includes(n),i=t.filenameLower.includes(n);return s&&!i?-1:!s&&i?1:e.depth!==t.depth?e.depth-t.depth:e.name.localeCompare(t.name)}function searchIndex(e,t){const n=e.toLowerCase(),r=[];for(const e of getFileIndex(t)){if(!e.nameLower.includes(n))continue;if(50===r.length&&compareByRelevance(e,r[r.length-1],n)>=0)continue;let t=0,o=r.length;for(;t<o;){const s=t+o>>1;compareByRelevance(e,r[s],n)<0?o=s:t=s+1}r.splice(t,0,e),r.length>50&&r.pop()}return r.map(({name:e,path:t,isDirectory:n})=>({name:e,path:t,isDirectory:n}))}function searchFiles(e,t=process.cwd()){if(!e.trim())return[];const r=memoKey(t,e),o=SP.get(r);if(o)return o;if(e.endsWith("/"))try{return memoize(r,listDirectory(n(t,e),t).map(e=>({...e,name:s(t,e.path)})).slice(0,50))}catch{}if(e.includes("/")){const o=e.split("/"),i=(o.pop()||"").toLowerCase();try{return memoize(r,listDirectory(n(t,o.join("/")),t).filter(e=>!i||e.name.toLowerCase().includes(i)).map(e=>({...e,name:s(t,e.path)})).slice(0,50))}catch{}}return memoize(r,searchIndex(e,t))}__name(memoKey,"memoKey"),__name(memoize,"memoize"),__name(loadGitignore,"loadGitignore"),__name(isIgnored,"isIgnored"),__name(listDirectory,"listDirectory"),__name(sortDirectoriesFirst,"sortDirectoriesFirst"),__name(buildFileIndex,"buildFileIndex"),__name(getFileIndex,"getFileIndex"),__name(invalidateFileIndex,"invalidateFileIndex"),__name(compareByRelevance,"compareByRelevance"),__name(searchIndex,"searchIndex"),__name(searchFiles,"searchFiles"),jr();var bP=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[o,s]=se(process.cwd()),[i,l]=se([]),[u,d]=se(0),[m,g]=se(0),h=n.trim()?15:10;ae(()=>{invalidateFileIndex()},[]);const f=ce(e=>{try{const t=[];"/"!==e&&t.push({name:"..",path:r(e),isDirectory:!0}),t.push(...listDirectory(e,process.cwd())),l(t),d(0),g(0)}catch{}},[]);ae(()=>{if(n.trim()){const e=searchFiles(n);l(e),d(0),g(0)}else f(o)},[o,f,n]),Z((r,o)=>{if(o.escape)t();else if(o.upArrow)d(e=>{const t=Math.max(0,e-1);return t<m&&g(t),t});else if(o.downArrow)d(e=>{const t=Math.min(i.length-1,e+1);return t>=m+h&&g(t-h+1),t});else{if(o.rightArrow){const e=i[u];if(!e)return;return void(e.isDirectory&&!n.trim()&&s(a(e.path)))}if(o.return){const t=i[u];if(!t)return;return void e(t.path)}}});const y=i.slice(m,m+h);return re.createElement(K,{flexDirection:"column",paddingLeft:1},re.createElement(K,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{color:gr.DIM},n.trim()?`Searching for: "${n}"`:`Files: ${o}`),re.createElement(Y,{color:gr.DIM},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===y.length?re.createElement(Y,{color:gr.DIM},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):y.map((e,t)=>{const n=m+t,r=e.name,o=n===u;return re.createElement(Y,{key:e.path,color:o?gr.GREEN:gr.DIM},e.isDirectory?`${r}/`:r)}))},"FileList");Ut(),kn(),bo(),jr(),Ut(),jr();var EP=__name(e=>{if(e>=1e6){const t=e/1e6;return`${t%1==0?t.toFixed(0):t.toFixed(1)}M`}return`${Math.round(e/1e3)}k`},"formatTokens"),vP=__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&&e.current>=18e4)return re.createElement(K,{paddingRight:3},re.createElement(Y,{color:gr.DIM},"~",EP(e.current)," tokens in context · try"," "),re.createElement(Y,{color:gr.DIM,bold:!0},"/compact"));if(n>20)return null;const r=__name(e=>e>=90?gr.RED:e>=70?gr.YELLOW:gr.DIM,"getColor"),o=t>=90?6:Math.round(t/100*6),s=6-o,i=Me.square.repeat(o),a=Me.squareLightShade.repeat(s),l=r(t);return re.createElement(K,{paddingRight:3},re.createElement(Y,{color:l},`Context left before auto-compact ${n}% `),re.createElement(Y,{color:l},i),s>0&&re.createElement(Y,{color:gr.DIM},a))},"ContextUsage");Ut(),bs(),jr();var CP=__name(()=>{const[e,t]=se("continuous learning"),[n,r]=se(!1),[o,s]=se(!1),i=ie([]),a=ie(0),l=ie(null),u=ie(!1);ae(()=>{const e=__name(e=>"analyzing"===e.type?(u.current=!0,r(!0),s(!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),s(!1),t("continuous learning")))):void 0,"handleNewEvent"),n=__name(()=>{if(a.current>=i.current.length)return r(!1),s(!1),t("continuous learning"),void(i.current=[]);const e=i.current[a.current];t(e.message);const o="learned"===e.type||"refactored"===e.type;s(o);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 BT.on("new-event",e),()=>{BT.off("new-event",e),l.current&&clearTimeout(l.current)}},[]);const d=` ${n?Me.squareSmallFilled:Me.squareSmall} TASTE`,m=9+e.length+d.length>ds;let g=e;g=truncateString(m?{text:e,maxChars:ds}:{text:e,maxChars:ds-d.length-9-10});const h=o?void 0:gr.DIM;return re.createElement(K,{paddingRight:2},!m&&re.createElement(re.Fragment,null,re.createElement(BracketWrap,{color:gr.DIM},"ctrl+t"),re.createElement(Y,{color:gr.DIM}," ")),re.createElement(Y,{color:h},g),!m&&re.createElement(Y,{color:fr.TEXT},d))},"LearningFeedMini");Ut(),jr();var kP=__name(({mode:e,pendingExitKey:t})=>t?re.createElement(Y,{color:gr.DIM},"Press Ctrl+C again to exit"):"bypass"===e?re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:gr.RED},"» permission bypass on "),re.createElement(BracketWrap,{color:gr.DIM},"shift+tab")):"auto-accept"===e?re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:Ir},"» accept edits on "),re.createElement(BracketWrap,{color:gr.DIM},"shift+tab")):"plan"===e?re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:Pr},"plan mode "),re.createElement(BracketWrap,{color:gr.DIM},"shift+tab")):re.createElement(Y,{color:gr.DIM},"? for shortcuts"),"ModeIndicator");Ut(),jr(),uo();var TP=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?gr.DIM:Mr.MERGED;return re.createElement(re.Fragment,null,t&&re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:n},"PR "),re.createElement(ao,{url:e.url,text:`#${e.number}`,color:n}))},"PRLinkBadge"),_P=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?re.createElement(re.Fragment,null,t&&re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:"connected"===e.type?gr.GREEN:gr.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),xP=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:o,tasteLearning:s,contextUsage:i,connectionIndicator:a,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:g,isBashMode:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E})=>{const v=e>=60;return re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r||l?re.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(K,{flexDirection:"row",columnGap:0},n&&!l?re.createElement(Y,{color:kr},t):re.createElement(kP,{mode:r,pendingExitKey:l}),!l&&re.createElement(TP,{prInfo:o}),!l&&re.createElement(_P,{indicator:a})),v&&re.createElement(K,{flexDirection:"column",alignItems:"flex-end"},s&&re.createElement(CP,null),i&&re.createElement(vP,{usage:i}))):re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(kP,{mode:r}),v&&s&&re.createElement(CP,null)),re.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(K,{flexDirection:"row",columnGap:0},re.createElement(Y,{color:n?kr:gr.DIM},t),re.createElement(TP,{prInfo:o}),re.createElement(_P,{indicator:a})),v&&i&&re.createElement(vP,{usage:i}))),(u||d||g&&m)&&re.createElement(K,{flexDirection:"row",columnGap:1},u&&re.createElement(Y,null,Me.tick," ","Command Code"," updated:"," ",re.createElement(Y,{color:gr.DIM},"v",u.updatedFrom),re.createElement(Y,{color:gr.DIM}," ",Me.arrowRight," "),re.createElement(Y,null,"v",u.updatedTo)),!u&&d&&re.createElement(Y,{color:gr.YELLOW,dimColor:!0},Me.info," Update available:"," ",d.currentVersion," ",Me.arrowRight," ",d.latestVersion),g&&m&&re.createElement(Y,{color:gr.GREEN,dimColor:!0},Me.bullet," Provider:"," ",getProviderDisplayName(m)))),h&&re.createElement(K,{paddingLeft:2},re.createElement(Y,{color:gr.GREEN},"! for bash mode")),y&&f&&re.createElement(K,{paddingLeft:2},re.createElement(Y,{color:hr},"SHARED: ",f.url," (copied to clipboard)")),w&&re.createElement(K,{paddingLeft:2},re.createElement(Y,{color:w.includes("NOT SHARED")?gr.RED:hr},w)),S&&re.createElement(K,{paddingLeft:2},re.createElement(Y,{color:hr},S)),E&&re.createElement(K,{paddingLeft:2},re.createElement(Y,{color:gr.YELLOW},Me.warning," ",E)))},"BottomIndicator");Ut(),bs(),jr();var AP=__name((e,t)=>e.padEnd(t),"padCell"),PP=__name(e=>e instanceof Error&&e.message?e.message:"Unknown error","getDeleteErrorMessage"),IP=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),MP=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),NP=__name(e=>truncateString({text:MP(e),maxChars:cs}),"truncateMessage"),RP=__name(e=>e.title?MP(e.title):NP(e.firstMessage),"getSessionSummary"),$P=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=se([]),[o,s]=se(0),[i,a]=se(0),[l,u]=se(!0),[d,m]=se(!1),[g,h]=se(!1),[f,y]=se(null),[w]=se(()=>getCurrentGitBranch()),S=useTerminalHeight(),E=Math.max(6,S-14),v=ce(async()=>{u(!0);const e=await Hk.listSessions();r(e),u(!1)},[]);ae(()=>{v()},[v]);const C=ce(async e=>{try{await Hk.deleteSession(e),h(!1),y(null),s(0),a(0),await v()}catch(e){h(!1),y(`Failed to delete session: ${PP(e)}`)}},[v]),k=d&&w?n.filter(e=>e.gitBranch===w):n;if(Z((n,r)=>{if(g)if(r.return){if(k.length>0&&o<k.length){const e=k[o];C(e.id)}}else h(!1);else if(r.delete||r.ctrl&&"d"===n)k.length>0&&(y(null),h(!0));else{if(!r.escape)return r.ctrl&&"b"===n?(m(e=>!e),s(0),void a(0)):void(r.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):r.downArrow?s(e=>{const t=Math.min(k.length-1,e+1);return t>=i+E&&a(t-E+1),t}):r.return&&k.length>0&&o<k.length&&e(k[o].id));t()}}),l)return re.createElement(K,{flexDirection:"column",paddingLeft:2},re.createElement(Y,{color:gr.GRAY},"Loading sessions..."));if(0===k.length)return re.createElement(K,{flexDirection:"column",paddingLeft:2},re.createElement(Y,{color:gr.GRAY},d&&w?`No sessions found for branch "${w}"`:"No previous sessions found"),re.createElement(Y,{color:gr.DIM},d?"Press ctrl+b to show all branches, ESC to cancel":"Press ESC to go back"));const T=k.slice(i,i+E),_=o<k.length?k[o]:null,x=g&&_?`Delete "${RP(_)}"? Press Enter to confirm, any other key to cancel.`:null;return re.createElement(K,{flexDirection:"column",paddingLeft:1,width:"100%"},re.createElement(Y,{color:gr.CYAN,bold:!0},"Resume Session"),re.createElement(K,{marginTop:1}),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:Tr,bold:!0},AP("#",6),AP("Modified",12),AP("Git Branch",22),AP("Messages",12),"Summary")),re.createElement(K,{flexDirection:"column"},T.map((e,t)=>{const n=i+t,r=o===n,s=truncateString({text:e.gitBranch||"-",maxChars:20});return re.createElement(Y,{key:e.id,color:r?gr.WHITE:gr.GRAY,backgroundColor:r?xr:void 0,bold:r,wrap:"truncate-end"},AP(`${n+1}.`,6),AP(IP(e.lastModified),12),AP(s,22),AP(String(e.messageCount),12),RP(e)," ")})),re.createElement(K,{marginTop:1}),x&&re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.RED},x)),f&&re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.RED},f)),k.length>E&&re.createElement(Y,{color:gr.DIM},"Showing ",i+1,"–",Math.min(i+E,k.length)," ","of ",k.length,i>0?" · ↑ more":"",i+E<k.length?" · ↓ more":""),re.createElement(Y,{color:gr.DIM},"↑↓ navigate · Enter select · Del delete · ctrl+b ",d?`[branch: ${w??"unknown"}]`:"branch filter"," · ESC cancel"))},"SessionsResumeTable");function getImageHintText({selectedIndex:e,imageCount:t,inHistory:n}){return-1!==e?t>1?"← → · Delete to remove · Esc to deselect":"Delete to remove · Esc to deselect":n?"↓ · ↑ imgs":"↑ to select"}function buildImageRows({imageCount:e,rowWidth:t}){const n=[];let r=[],o=0;for(let s=0;s<e;s++){const e=`[Image #${s+1}]`.length,i=e+(r.length>0?1:0);r.length>0&&o+i>t?(n.push(r),r=[s],o=e):(r.push(s),o+=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 o=`[Image #${e+1}]`,s=n?createOSC8Link(`file://${n}`,o,!1):o;return re.createElement(Y,null,r?" ":"",t?re.createElement(Y,{inverse:!0},o):s)}function ImageRowsDisplay({detectedImages:e,selectedImageIndex:t,imageTempPaths:n,termWidth:r,inHistory:o}){if(0===e.length)return null;const s=getImageHintText({selectedIndex:t,imageCount:e.length,inHistory:o}),i=Math.max(1,r-(s.length+2)),a=buildImageRows({imageCount:e.length,rowWidth:i});return re.createElement(K,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>re.createElement(K,{key:r,flexDirection:"row"},re.createElement(K,{flexShrink:0,marginRight:1},0===r&&re.createElement(Y,{color:gr.DIM},s)),re.createElement(K,{flexDirection:"row"},e.map((e,r)=>re.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Ut(),jr(),Ut(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),yo(),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Ut();var LP=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=se(null),[s,i]=se(!1),a=ie(!1),l=ie(null),u=ie(n),[d,m]=se(!1),[g,h]=se("connected"),f=ie(null),y=ie(null),w=ce((e,t)=>{y.current&&(clearTimeout(y.current),y.current=null),h(e),m(!0),void 0!==t&&(y.current=setTimeout(()=>{m(!1)},t))},[]),S=ce(()=>{y.current&&(clearTimeout(y.current),y.current=null)},[]),E=ce(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new kk,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=f.current;if(null===r?n&&w("connected",3e3):r!==n&&(n?w("connected",2e3):w("disconnected",5e3)),f.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),o(r)}else o(null)}catch{!0===f.current&&w("disconnected",5e3),f.current=!1,i(!1),o(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[w]);ae(()=>{const e=u.current;u.current=n,e&&!n&&t&&null!==gk()&&E(!1)},[n,t,E]),ae(()=>{if(!t)return;if(null===gk())return;let e=null,n=!1,r=0;function schedule(t){n||(e=setTimeout(()=>{tick(!1)},t))}async function tick(e){if(u.current)return void schedule(500);if(await E(e),n)return;if(l.current?.isConnected)return r=0,void schedule(500);r+=1;const t=Math.min(r,6);schedule(Math.min(3e4,500*2**t)+250*Math.random())}return __name(schedule,"schedule"),__name(tick,"tick"),tick(!0),()=>{n=!0,e&&clearTimeout(e),S(),l.current?.disconnect(),l.current=null}},[t,E,S]);const v=gk(),C={visible:d,message:"connected"===g?`${v?N_[v]??"IDE":"IDE"} ${Me.tick}`:"run /ide",type:g};return{context:r,connected:s,refresh:E,connectionIndicator:C}},"useVSCodeContext");Ut();var DP=__name(e=>{if(!e.activeFile&&!e.selection)return"";const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:o}=e.activeFile;t.push(`File: ${n} (${r}, line ${o.line})`)}if(e.selection){const{text:n,startLine:r,endLine:o}=e.selection,s=e.activeFile?.language??"";t.push(`Selected lines ${r}-${o}:`),t.push(`\`\`\`${s}`);const i=n.replace(/```/g,"` ` `").replace(/<\/ide-context>/gi,"&lt;/ide-context&gt;").replace(/[\u202A-\u202E\u2066-\u2069\u200B-\u200D\uFEFF]/g,"");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");function resolvePastedTextTokens({input:e,detectedContent:t}){return t.reduce((e,t,n)=>{const r=`[Text#${n+1}]`;return e.includes(r)?e.replace(r,()=>t):e},e)}Ut(),__name(resolvePastedTextTokens,"resolvePastedTextTokens");var OP=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),FP=__name((e,t,n)=>{const r=e?t?.selection:null;if(r)return`${r.lineCount} lines selected`;const o=e?t?.activeFile:null;if(o?.relativePath){const e=o.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");function getModelShortName(e){const t=findModelById(e);if(t){const e=t.name.toLowerCase().replaceAll(" ","-");return"free"===t.badge?`${e} (free)`:e}return e}function getModelHintLayout(e){const{currentModel:t,terminalWidth:n}=e,r=getCommandMenuDescriptionWidth(n),o=modelSupportsReasoningEffort(t)?getReasoningEffort(t):null,s=o?` with ${o} effort`:"";return{descriptionWidth:r,text:truncateString({text:`${getModelShortName(t)}${s} (current)`,maxChars:r})}}Ut(),io(),co(),bs(),__name(getModelShortName,"getModelShortName"),__name(getModelHintLayout,"getModelHintLayout");var UP=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}function getCommandMenuStateFromQuery(e){return isDesignSubmenu(e)?{showMenu:!0,query:e}:e.includes(" ")?{showMenu:!1,query:""}:{showMenu:!0,query:e}}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isPrecededByWhitespace,"isPrecededByWhitespace"),__name(getCommandMenuStateFromQuery,"getCommandMenuStateFromQuery");var jP=__name(()=>re.createElement(K,{flexDirection:"column",paddingLeft:1},re.createElement(Y,{color:gr.DIM,bold:!0},"Available Shortcuts:"),re.createElement(K,{columnGap:4},re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.DIM},"! for bash mode"),re.createElement(Y,{color:gr.DIM},"/ for commands"),re.createElement(Y,{color:gr.DIM},"@ for file paths"),re.createElement(Y,{color:gr.DIM},"shift + tab to toggle auto-accept")),re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.DIM},"double tap esc to clear input"),re.createElement(Y,{color:gr.DIM},"ctrl + j / shift + ⏎ for newline"),re.createElement(Y,{color:gr.DIM},"ctrl + g to open in editor"),re.createElement(Y,{color:gr.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),BP=__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:g=!1,tasteUsage:h=!1,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E,updateStatus:v,updateFailedInfo:C,currentProvider:k,currentModel:T,showProviderInfo:_,permissionMode:x="standard",onToggleAutoAccept:A,hintMessage:P,historyManager:I,pendingExitKey:M=null,onOverlayVisibilityChange:N,onDoubleEscapeEmpty:R,onAltP:$,isProcessing:L=!1,ideContextEnabled:D=!0})=>{const[O,F]=se(0),[U,j]=se(!1),[B,q]=se(!1),[z,W]=se(!1),[H,G]=se(!1),[V,Q]=se(""),[J,ee]=se(null),[te,ne]=se(!1),oe=ie(0),ue=ie(0),[de,me]=se([]),[pe,ge]=se([]),[he,fe]=se(-1),[ye,we]=se(""),Se=ie(!1),be=ie(!1),Ee=ie(void 0),[ve,Ce]=se(-1),[ke,Te]=se(""),_e=ie(0),{isEditorOpen:xe,editorError:Ae,handleOpenInEditor:Pe,clearEditorError:Ie}=useExternalEditor({input:e,setInput:n,setInputKey:F,detectedContent:de,setDetectedContent:me,onEditorClose:__name(()=>{Se.current=!1},"onEditorClose")}),Ne=le(()=>shouldCollapsePastedText(),[]),{handlePaste:Re,resetPasteState:$e,isPasting:Le}=useBracketedPaste({input:e,detectedContent:de,setInput:n,setDetectedImages:ge,setDetectedContent:me,incrementInputKey:__name(()=>F(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Ee.current=e},"setInitialCursor"),collapsePastedText:Ne}),{context:De,connected:Oe,refresh:Fe,connectionIndicator:Ue}=LP({enabled:D,paused:L}),{stdout:je}=X(),Be=je?.columns??80,{pr:qe}=fP();ae(()=>{const e=i||H||te;N?.(e)},[i,H,te,N]);const ze=ce(()=>{ge([]),fe(-1)},[]),We=ce(()=>{G(!1),ee(null)},[]),He=ce(()=>{n(""),q(!1),We(),Q(""),ne(!1),me([]),ze(),we(""),$e(),Ce(-1),Te(""),F(e=>e+1)},[n,$e,ze,We]),Ge=ce(()=>{Se.current=!0;const{text:t,cursor:r}=insertTextAt(e,_e.current,"\n");n(t),Ee.current=r,F(e=>e+1),setTimeout(()=>{Se.current=!1},0)},[e,n]);Z(async(t,r)=>{if(-1!==he&&r.leftArrow)return void fe(prevImageIndex({currentIndex:he,imageCount:pe.length}));if(-1!==he&&r.rightArrow)return void fe(nextImageIndex({currentIndex:he,imageCount:pe.length}));if(r.upArrow){if(i||H||te)return;const t=e.indexOf("\n"),r=-1===t||_e.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:pe.length,selectedImageIndex:he,historyIndex:ve}))return void fe(pe.length-1);if(-1!==he&&fe(-1),0!==e.length&&-1===ve&&!r)return;const o=I?.count()??0;if(0===o)return;-1===ve&&Te(e);const s=Math.min(ve+1,o-1);return void(s!==ve&&(Ce(s),n(I?.getAt(s)||""),F(e=>e+1)))}if(r.downArrow){if(i||H||te)return;if(-1===ve)return;const t=e.lastIndexOf("\n");if(!(-1===t||_e.current>t))return;const r=ve-1;return Ce(r),n(-1===r?ke:I?.getAt(r)||""),void F(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void ze();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return Se.current=!0,void Pe();if(getIsExpandToolShortcut(r,t))return Se.current=!0,n(e),F(e=>e+1),void setTimeout(()=>{Se.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Le()}))return be.current=!0,Ge(),void setTimeout(()=>{be.current=!1},0);if(r.meta&&r.backspace)return void He();if(r.meta&&"w"===t)return Se.current=!0,void He();const o=r.ctrl&&"v"===t||UP.includes(t),s=r.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e;Se.current=!0;const r=await detectClipboardImage();return r&&(ge(e=>[...e,r]),n(t),F(e=>e+1)),void(Se.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return W(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==he&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:pe,index:he});return ge([...e]),void fe(t)}if(r.escape){if(-1!==he)return void fe(-1);if(H)return;if(te)return ne(!1),n(ye),void F(e=>e+1);const t=Date.now();return t-oe.current<500?(e.length>0?He():R?.(),oe.current=0,ue.current=0):(oe.current=t,U||B||(ue.current=t)),j(!1),void q(!1)}U&&(r.backspace||r.delete)&&0===e.length&&j(!1)}});const Ve=ce(async t=>{if(xe)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void $?.();const o=processBracketedPaste(t);if((o.isPasteStart||o.isPasteEnd||Le())&&await Re(t))return;if(Se.current)return void(Se.current=!1);-1!==ve&&Ce(-1);const s=1===t.length,l=t.slice(-1);if(s){if("?"===l&&!U)return j(!0),n(""),void F(e=>e+1);if("!"===l&&!B)return j(!1),q(!0),n(""),void F(e=>e+1)}if("/"!==l||H||"/"!==t||(G(!0),Q("")),H)if(t.startsWith("/")){const e=t.substring(1),{showMenu:n,query:r}=getCommandMenuStateFromQuery(e);n?G(!0):We(),Q(r)}else We(),Q("");"@"!==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)}}U&&(t!==e||t.length<e.length)&&j(!1),Ae&&Ie(),0===t.length&&(q(!1),We(),Q(""),ne(!1),me([]),u(""),we(""),$e()),n(t)},[U,e,n,i,a,H,B,pe,ve,Re,$e,$,Ae,Ie,xe,We]),Qe=ce(async()=>{if(Fe(),ue.current=0,U)return void j(!1);const r=e.trim(),o=!B&&r.startsWith("/");let s=r;if(!B&&de.length>0&&(s=resolvePastedTextTokens({input:s,detectedContent:de})),o&&d&&(n(""),"handled"===(await d(s)).status))return I?.add(s),q(!1),We(),Q(""),ze(),me([]),Ce(-1),void Te("");Ce(-1),Te("");let i=[];const a=pe.length>0;!B&&a&&(i=[...pe]),s.length>0&&I?.add(s);const l=De?.selection?{lines:De.selection.lineCount,file:De.activeFile?.relativePath?.split("/").pop()??De.activeFile?.path?.split("/").pop()??"unknown",ide:N_[gk()??""]??"IDE"}:void 0;t({input:s,role:B?"bash":"user",images:i,ideContext:De?DP(De):void 0,ideHint:l}),q(!1),We(),Q(""),ze(),me([])},[t,d,U,e,B,pe,de,I,Fe,ze,We,n]),Ke=ce(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(""),F(e=>e+1)},[n,a,e,i,l,u]),Ye=ce(()=>{a(!1),u("")},[a,u]),Je=ce(e=>{const t=Px.has(e),r="/design"===e.trimEnd();if(t||r){const t=e.trimEnd();n(t+" "),Q(t.substring(1)+" ")}else We(),Q(""),n(e+" ");F(e=>e+1)},[n,We]),Xe=ce(t=>{if("/resume"===t||"/sessions"===t)return I?.add(t),Ce(-1),Te(""),we(e),We(),Q(""),ne(!0),n(""),void F(e=>e+1);if("/design help"===t)return We(),Q(""),n(""),F(e=>e+1),I?.add(t),void d?.("/design help");if(Ax.has(t))return We(),Q(""),I?.add(t),Ce(-1),Te(""),n(""),F(e=>e+1),void d?.(t);const r=Px.has(t),o=Ix.has(t);r?Je(t):(We(),Q(""),o?(I?.add(t),Ce(-1),Te(""),n(""),F(e=>e+1),d?.(t)):(n(t+" "),F(e=>e+1)))},[d,n,e,I,Je,We]),Ze=ce(()=>{We(),Q(""),n(""),Ce(-1),Te(""),F(e=>e+1)},[n,We]),et=ce(e=>{ne(!1),n(""),we(""),Ce(-1),Te(""),F(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),tt=ce(()=>{ne(!1),n(ye),Ce(-1),Te(""),F(e=>e+1)},[ye,n]),nt=ce(e=>{_e.current=e,Ee.current=void 0},[]),rt=le(()=>{const t=qe&&("OPEN"===qe.state||"MERGED"===qe.state);return"auto-accept"===x||"plan"===x||"bypass"===x||Oe||t?!U&&!te:!U&&0===e.length&&!B&&!te},[U,e,B,te,x,Oe,qe]),ot=ie(new Map),st=le(()=>pe.map((e,t)=>{if(ot.current.has(e))return ot.current.get(e)??null;const n=saveTempImage(e,t+1);return ot.current.set(e,n),n}),[pe]),it=__name(()=>U||i||H||te||z?0:rt||M||B?3:4,"getBottomMargin");return re.createElement(K,{width:"100%",flexDirection:"column",marginBottom:it()},!te&&re.createElement(K,{flexDirection:"column",width:"100%"},re.createElement(ImageRowsDisplay,{detectedImages:pe,selectedImageIndex:he,imageTempPaths:st,termWidth:Be,inHistory:-1!==ve}),re.createElement(Y,{color:B?gr.GREEN:gr.GRAY},Me.line.repeat(Be)),(()=>{const t=__name(()=>{if(!be.current)return Date.now()-ue.current<100?(ue.current=0,void Ge()):void(i||H||te||xe||Qe());be.current=!1},"handleTextInputSubmit"),n=__name(n=>re.createElement(TextInput,{key:O,value:e,placeholder:xe?"Save and close the editor to continue...":o,onChange:Ve,onSubmit:t,showCursor:!xe&&r&&-1===he,onCursorChange:nt,initialCursor:Ee.current,prefix:`${B?"!":Me.pointer} `,prefixColor:B?gr.GREEN:gr.WHITE,singleLine:n?.singleLine,maxWidth:n?.maxWidth}),"renderTextInput");if(H&&T&&"/model"===J){const e=getModelHintLayout({currentModel:T,terminalWidth:Be});return re.createElement(K,{flexDirection:"row",width:"100%"},re.createElement(K,{width:25},n({singleLine:!0,maxWidth:25})),re.createElement(K,{width:e.descriptionWidth},re.createElement(Y,{color:gr.DIM,wrap:"truncate"},e.text)))}return n()})(),re.createElement(Y,{color:B?gr.GREEN:gr.GRAY},Me.line.repeat(Be))),U&&re.createElement(jP,null),z&&re.createElement(K,{paddingTop:1},re.createElement(Y,{color:gr.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&re.createElement(bP,{onSelectFile:Ke,onClose:Ye,searchQuery:l}),H&&re.createElement(Rx,{onSelectCommand:Xe,onInsertCommand:Je,onClose:Ze,searchQuery:V,onSelectedCommandChange:ee}),te&&re.createElement($P,{onSelectSession:et,onClose:tt}),!H&&(rt||M)&&re.createElement(xP,{termWidth:Be,indicatorText:FP(Oe,De,Be),isIDEIndicator:OP(Oe,De),permissionMode:x,prInfo:qe,tasteLearning:g,contextUsage:m,connectionIndicator:Ue,pendingExitKey:M,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:_,isBashMode:B,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E}),Ae&&re.createElement(K,{paddingLeft:1,flexDirection:"column"},re.createElement(Y,{color:gr.YELLOW},Ae)))},"InputBox");Ut(),bs(),jr();var qP=__name(({messages:e})=>0===e.length?null:re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(K,{marginBottom:0},re.createElement(Y,{color:wr,inverse:!0},` Queued (${e.length}) `)),e.map((e,t)=>re.createElement(K,{key:t},re.createElement(Y,{color:gr.DIM},Me.pointerSmall," "),re.createElement(Y,{color:gr.DIM},truncateString({text:e.displayMessage??e.input,maxChars:80}))))),"QueuedMessages"),zP=re.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:i,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:g=0,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,currentModel:x,showProviderInfo:A,permissionMode:P,onToggleAutoAccept:I,hintMessage:M,historyManager:N,pendingExitKey:R,onResetPendingExitKey:$,onDoubleEscapeEmpty:L,retryAttempt:D,onAltP:O})=>{const[F,U]=se(0),j=ie(o);return ae(()=>{R&&o!==j.current&&o.length>0&&$?.(),j.current=o},[o,R,$]),ae(()=>{if(!t)return void U(0);const e=setInterval(()=>{U(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),re.createElement(K,{flexDirection:"column"},re.createElement(qP,{messages:e}),re.createElement(K,{flexDirection:"row",justifyContent:"space-between"},re.createElement(K,{flexDirection:"column"},(t||n.isExecuting)&&null===D&&re.createElement(rP,{tokens:g,timeElapsed:F,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),M&&re.createElement(K,{marginLeft:1},re.createElement(Y,{color:gr.DIM}," ","⎿"," ","Tip: ",M)))),re.createElement(BP,{input:o,setInput:s,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,currentModel:x,showProviderInfo:A,permissionMode:P,onToggleAutoAccept:I,hintMessage:M,historyManager:N,pendingExitKey:!R||t||n.isExecuting?null:R,onDoubleEscapeEmpty:L,onAltP:O,isProcessing:t}))});Ut(),iE(),dE(),mo(),bo();var WP=__name(({onComplete:e,onCancel:t})=>{const[n,r]=se(!1),[o,s]=se(""),{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:g}=useAuthFlow({onSuccess:__name((t,n)=>{const o=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";s(o),isInternalTeamFlagEnforced()?r(!0):e(!0,o?`Logged in as ${o}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return Z((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");g()}}),n?re.createElement(lo,{onSuccess:()=>{e(!0,o?`Logged in as ${o} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,o?`Logged in as ${o}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):re.createElement(lE,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");function buildOAuthMetadataUrl(e){const t=new g(e),n="/"===t.pathname?"":t.pathname.replace(/\/+$/,"");return t.pathname=`/.well-known/oauth-authorization-server${n}`,t.search="",t.hash="",t.toString()}function buildOidcMetadataUrl(e){const t=new g(e),n=t.pathname.replace(/\/+$/,"");return t.pathname=`${n}/.well-known/openid-configuration`,t.search="",t.hash="",t.toString()}async function tryFetchAsMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return n.authorization_endpoint&&n.token_endpoint?{authorizationEndpoint:n.authorization_endpoint,tokenEndpoint:n.token_endpoint,registrationEndpoint:n.registration_endpoint,scopes:n.scopes_supported}:null}catch(t){return dlog(`[MCP] OAuth metadata fetch failed for ${e}`,t),null}}async function discoverOAuthMetadataFromIssuer(e){return await tryFetchAsMetadata(buildOAuthMetadataUrl(e))||await tryFetchAsMetadata(buildOidcMetadataUrl(e))}async function discoverOAuthMetadata(e){const t=new g(e),n=`${t.protocol}//${t.host}`;return await tryFetchAsMetadata(`${n}/.well-known/oauth-authorization-server`)||await tryFetchAsMetadata(`${n}/.well-known/openid-configuration`)}function parseResourceMetadataUrl(e){if(!e)return null;const t=e.match(/resource_metadata\s*=\s*"([^"]+)"|resource_metadata\s*=\s*([^\s,]+)/i);return t?t[1]??t[2]??null:null}async function fetchProtectedResourceMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return{authorizationServers:n.authorization_servers,scopesSupported:n.scopes_supported}}catch(e){return dlog("[MCP] Protected resource metadata fetch failed",e),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:OS,capabilities:{},clientInfo:FS}})});if(401===t.status||403===t.status){const n=parseResourceMetadataUrl(t.headers?.get?.("www-authenticate")??null);if(n){const e=await fetchProtectedResourceMetadata(n),t=e?.authorizationServers?.[0];if(t){const n=await discoverOAuthMetadataFromIssuer(t);if(n)return e?.scopesSupported&&(n.scopes=e.scopesSupported),{requiresAuth:!0,metadata:n}}}return{requiresAuth:!0,metadata:await discoverOAuthMetadata(e)||void 0}}return{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}async function discoverAndAuthenticate({serverName:e,serverUrl:t,onStatus:n}){const r=n??(()=>{});r("Probing server for OAuth requirements...");const o=await checkServerAuthRequirements(t);if(o.error)return{success:!1,error:o.error};if(!o.requiresAuth)return{success:!1,error:"Server does not require authentication"};if(!o.metadata)return{success:!1,error:"Server returned 401 but did not advertise OAuth metadata. Add `oauth` config manually via `mcp add-json`."};const{authorizationEndpoint:s,tokenEndpoint:i,registrationEndpoint:a,scopes:l}=o.metadata;if(!a)return{success:!1,error:"Server requires pre-registered OAuth credentials (no Dynamic Client Registration endpoint advertised). Register an OAuth client with the server, then add it via `mcp add-json` with an `oauth.clientId` field."};const u=`http://${rb}:${nb}/callback`;r("Registering OAuth client...");const d=await registerOAuthClient({registrationEndpoint:a,clientName:FS.name,redirectUris:[u]});if(!d)return{success:!1,error:"Dynamic client registration failed at "+a};const m={authorizationUrl:s,tokenUrl:i,clientId:d.clientId,clientSecret:d.clientSecret,scopes:l},g=await performOAuthFlow(e,t,m,{onStatus:n});return g.success&&(await storeDiscoveredClient(e,{authorizationUrl:s,tokenUrl:i,clientId:d.clientId,scopes:l}),d.clientSecret?await storeClientSecret(e,d.clientSecret):await deleteClientSecret(e)),g}Ut(),Ut(),QS(),BS(),JS(),KS(),ZS(),cb(),pb(),gb(),Ut(),pb(),gb(),HS(),lb(),Ut(),tb(),BS(),rr(),__name(buildOAuthMetadataUrl,"buildOAuthMetadataUrl"),__name(buildOidcMetadataUrl,"buildOidcMetadataUrl"),__name(tryFetchAsMetadata,"tryFetchAsMetadata"),__name(discoverOAuthMetadataFromIssuer,"discoverOAuthMetadataFromIssuer"),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(parseResourceMetadataUrl,"parseResourceMetadataUrl"),__name(fetchProtectedResourceMetadata,"fetchProtectedResourceMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient"),Ut(),BS(),lb(),HS(),__name(discoverAndAuthenticate,"discoverAndAuthenticate"),jr(),uo();var HP=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se(!0),[s,i]=se(0),[a,l]=se("list"),[u,d]=se(null),[m,g]=se(0),h=useTerminalHeight(),f=ce(async()=>{o(!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,o,s="disconnected";return!1===e.config.enabled?s="disabled":n&&"connected"===n.status?(s="connected",r=n.tools.length):n&&"error"===n.status?(s="error",o=n.error):(e.config.oauth||"http"===e.config.transport)&&(await hasTokens(e.name)?s="authenticated":e.config.oauth&&(s="requires_auth")),{name:e.name,config:e.config,scope:e.scope,status:s,toolCount:r,error:o}}));n(r)}catch{}finally{o(!1)}},[]);ae(()=>{f()},[f]);const y=le(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),w=y[s]??null,S=h-1,E=le(()=>new Set(y.map(e=>e.scope)).size,[y]),v=Math.max(4,S-8-2*E);ae(()=>{g(e=>clampScrollOffset({cursor:s,total:y.length,maxVisible:v,currentOffset:e}))},[s,y.length,v]),Z((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===y.length)return;const e=Math.max(0,y.length-1);i(t=>Math.min(e,t+1)),d(null)}n.return&&w&&(l("actions"),d(null))}});const C=__name((e,t)=>{const n=__name((e,n)=>re.createElement(Y,{color:e,backgroundColor:t},n),"icon");switch(e){case"connected":return n(gr.GREEN,Me.tick);case"authenticated":return n(gr.CYAN,Me.tick);case"requires_auth":return n(gr.YELLOW,Me.warning);case"error":return n(gr.RED,Me.cross);default:return n(gr.GRAY,Me.circle)}},"getStatusIcon"),k=__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"),T=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),_=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),x=__name(async e=>{if(w)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 ${w.name}...`,color:gr.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:w.name,enabled:!0,scope:w.scope}))return void d({text:`${Me.cross} Failed to enable ${w.name}, server may no longer exist in ${w.scope} scope`,color:gr.YELLOW});await f(),d({text:`${Me.tick} Enabled ${w.name}`,color:gr.GREEN})}catch(e){d({text:`${Me.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:gr.RED})}}else{d({text:`Disabling ${w.name}...`,color:gr.CYAN,loading:!0});try{const e=getMcpConnectionManager();if(!await updateMcpServerStatus({name:w.name,enabled:!1,scope:w.scope}))return void d({text:`${Me.cross} Failed to disable ${w.name}, server may no longer exist in ${w.scope} scope`,color:gr.YELLOW});await e.disconnectServer(w.name),await f(),d({text:`${Me.tick} Disabled ${w.name}`,color:gr.GREEN})}catch(e){d({text:`${Me.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:gr.RED})}}else l("confirm-remove");else{if(!(w.config.oauth||"http"===w.config.transport&&w.config.url))return void d({text:"Authentication requires an http server with a url",color:gr.YELLOW});d({text:`Authenticating ${w.name}...`,color:gr.CYAN,loading:!0});try{let e;if(w.config.oauth){const t={authorizationUrl:w.config.oauth.authorizationUrl,tokenUrl:w.config.oauth.tokenUrl,clientId:w.config.oauth.clientId,clientSecret:w.config.oauth.clientSecret,scopes:w.config.oauth.scopes};e=await performOAuthFlow(w.name,w.config.url??"",t,{onStatus:__name(()=>{},"onStatus")})}else e=await discoverAndAuthenticate({serverName:w.name,serverUrl:w.config.url});if(e.success){d({text:`${Me.tick} Authenticated with ${w.name}`,color:gr.GREEN});try{const e=getMcpConnectionManager();await e.ensureServerConnection(w.name)}catch{}await f()}else d({text:`${Me.cross} Auth failed: ${e.error}`,color:gr.RED})}catch(e){d({text:`${Me.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:gr.RED})}}else{d({text:`Connecting ${w.name}...`,color:gr.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.ensureServerConnection(w.name),d({text:`${Me.tick} Connected to ${w.name}`,color:gr.GREEN}),await f()}catch(e){d({text:`${Me.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:gr.RED})}}else d({text:"Already authenticated",color:gr.GREEN});else d({text:"Already connected",color:gr.GREEN});else l("list")},"handleActionSelect"),A=__name(async e=>{if(w)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===w.status&&await e.disconnectServer(w.name),await removeMcpServer({name:w.name,scope:w.scope}),l("list"),await f(),i(e=>Math.min(e,Math.max(0,y.length-2)))}catch(e){d({text:`${Me.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:gr.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:hr,bold:!0},"Manage MCP servers"),re.createElement(Y,{color:gr.DIM},"Loading..."));if("confirm-remove"===a&&w)return re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.RED,bold:!0},"Remove ",w.name,"?"),re.createElement(Y,{color:gr.DIM},"This will remove the server from ",w.scope," ","config."),re.createElement(K,{marginTop:1},re.createElement(gt,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:A,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY,backgroundColor:e?xr:void 0,bold:e}," ",t," ")})),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&w){const e=[],t="disabled"===w.status,n="connected"===w.status,r="authenticated"===w.status||n;t&&e.push({label:"Enable",value:"enable"}),!t&&n&&e.push({label:"Connected",value:"connected"}),t||n||e.push({label:"Connect",value:"connect"});const o=!t&&(w.config.oauth||"http"===w.config.transport);return o&&r&&e.push({label:"Authenticated",value:"authenticated"}),o&&!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"}),re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:hr,bold:!0},w.name),re.createElement(K,null,C(w.status),re.createElement(Y,{color:gr.DIM}," ",k(w))),re.createElement(K,{marginTop:1},re.createElement(gt,{items:e,onSelect:x,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY,backgroundColor:e?xr:void 0,bold:e}," ",t," ")})),u&&re.createElement(K,{marginTop:1},u.loading&&re.createElement(Y,{color:u.color},re.createElement(ze,{type:"dots"})," "),re.createElement(Y,{color:u.color},u.text)),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"↑↓ navigate · Enter to select · Esc to go back")))}let P=null;const I=m,M=m+v,N=y.slice(I,M),R=y.length>v;return re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:hr,bold:!0},"Manage MCP servers"),re.createElement(Y,{color:gr.DIM},t.length," ",1===t.length?"server":"servers"),0===t.length?re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:gr.DIM},"No MCP servers configured."),re.createElement(Y,{color:gr.DIM},'Use "cmd mcp add" to add a server.'),re.createElement(ao,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:gr.CYAN,dimColor:!0})):re.createElement(K,{marginTop:1,flexDirection:"column"},N.map((e,t)=>{const n=I+t,r=e.scope!==P;P=e.scope;const o=n===s;return re.createElement(re.Fragment,{key:e.name},r&&re.createElement(K,{marginTop:0===t?0:1},re.createElement(Y,{bold:!0},T(e.scope)),re.createElement(Y,{color:gr.DIM}," ","(",_(e.scope),")")),re.createElement(K,null,re.createElement(Y,{color:o?gr.WHITE:void 0,backgroundColor:o?xr:void 0,bold:o},e.name),re.createElement(Y,{color:gr.DIM,backgroundColor:o?xr:void 0}," · "),C(e.status,o?xr:void 0),re.createElement(Y,{color:"connected"===e.status?gr.GREEN:"authenticated"===e.status?gr.CYAN:"requires_auth"===e.status?gr.YELLOW:gr.GRAY,backgroundColor:o?xr:void 0}," ",k(e)," ")))})),R&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",I+1,"–",Math.min(M,y.length)," of"," ",y.length,I>0?" · ↑ more":"",M<y.length?" · ↓ more":"")),u&&re.createElement(K,{marginTop:1},u.loading&&re.createElement(Y,{color:u.color},re.createElement(ze,{type:"dots"})," "),re.createElement(Y,{color:u.color},u.text)),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},0===t.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Ut(),kn(),Yn(),jr();var GP=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se(0),[s,i]=se(!0),[a,l]=se(null);ae(()=>{__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(Z((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(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]))}),s)return re.createElement(K,{paddingLeft:1,paddingTop:1},re.createElement(Y,{color:gr.DIM},"Loading memory files..."));if(a)return re.createElement(K,{paddingLeft:1,paddingTop:1},re.createElement(Y,{color:gr.RED},Me.cross," ",a));const m=d.map((e,t)=>{const n=t+1;let r="",o="";return"project"===e.type?(r=`${n}. Project memory`,o=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,o=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:o}});return re.createElement(K,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:gr.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},re.createElement(K,null,re.createElement(Y,{color:gr.WHITE,bold:!0},"Select memory to edit:")),re.createElement(K,{columnGap:4,marginTop:1},re.createElement(K,{flexDirection:"column"},m.map((e,t)=>re.createElement(Y,{key:t,color:r===t?gr.WHITE:gr.DIM},r===t?`${qn} `:" ",e.label))),re.createElement(K,{flexDirection:"column"},m.map((e,t)=>re.createElement(Y,{key:t,color:r===t?gr.WHITE:gr.DIM},e.description)))))},"MemorySelector");function AutoCompactMessage({content:e}){return re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},Me.bullet," ",e))}function ZdrPausedMessage(){return re.createElement(K,{marginTop:1,marginBottom:1},re.createElement(Y,null,re.createElement(Y,{color:gr.DIM},Me.bullet," "),re.createElement(Y,{color:gr.DIM},"Per-task model overrides reverted to ZDR safe defaults. Run"," "),re.createElement(Y,{color:Rr.CODE},"/configure-models"),re.createElement(Y,{color:gr.DIM}," to review · esc to dismiss")))}function TasteSkipMessage(){return re.createElement(K,{marginTop:1,marginBottom:1},re.createElement(K,{flexShrink:0},re.createElement(Y,{backgroundColor:fr.BADGE_BG,color:fr.BADGE_FG,bold:!0},g_)),re.createElement(Y,{color:gr.DIM}," Skipped. Run "),re.createElement(Y,{color:Rr.CODE},"/learn-taste"),re.createElement(Y,{color:gr.DIM}," or "),re.createElement(Y,{color:Rr.CODE},"cmd learn-taste"),re.createElement(Y,{color:gr.DIM}," anytime."))}function HookWarningMessage({content:e}){return re.createElement(K,null,re.createElement(Y,{color:gr.YELLOW},Me.warning),re.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.YELLOW},e)))}function HookLineMessage({content:e}){return re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},` ${e}`))}function HookLineContinuationMessage({content:e}){return re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},` ${e}`))}function HookFrameMessage({lines:e,header:t}){return re.createElement(K,{flexDirection:"column"},void 0!==t&&re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},` ${t}`)),e.map((e,t)=>re.createElement(K,{key:t,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},e.primary?` └ ${e.text}`:` ${e.text}`))))}function InfoMessage({content:e,metadata:t}){return t?.isTasteSkip?re.createElement(TasteSkipMessage,null):t?.isAutoCompact?re.createElement(AutoCompactMessage,{content:e}):t?.hookFrame&&t.hookFrame.length>0?re.createElement(HookFrameMessage,{lines:t.hookFrame,header:t.hookFrameHeader}):t?.isHookLine?re.createElement(HookLineMessage,{content:e}):t?.isHookLineContinuation?re.createElement(HookLineContinuationMessage,{content:e}):t?.isHookWarning?re.createElement(HookWarningMessage,{content:e}):t?.isSuccess?re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.GREEN},Me.tick," ",e)):re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},Me.bullet," ",e))}Ut(),jr(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(ZdrPausedMessage,"ZdrPausedMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(HookWarningMessage,"HookWarningMessage"),__name(HookLineMessage,"HookLineMessage"),__name(HookLineContinuationMessage,"HookLineContinuationMessage"),__name(HookFrameMessage,"HookFrameMessage"),__name(InfoMessage,"InfoMessage"),Ut(),kn(),io(),Zb(),$o(),bo(),co(),jr(),Ut(),jr();var VP=wt()?"⠶":"#";function AssistantMessage({content:e}){return re.createElement(K,null,re.createElement(Y,{color:Ar},VP),re.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Markdown,null,e)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=gr.GREEN,s=Me.tick,i="default",a=t||"(No output)";n&&(o=gr.YELLOW,s=Me.arrowRight,i=gr.YELLOW,a="Executing…"),r&&(o=gr.RED,s=Me.cross,i=gr.RED);const l=le(()=>buildTreeConnectors(a),[a]);return re.createElement(K,null,re.createElement(Y,{color:o},s),re.createElement(K,{flexDirection:"column",marginLeft:1},re.createElement(K,null,re.createElement(Y,{color:gr.GRAY},"$ "),re.createElement(Y,{color:o,bold:!0},e)),re.createElement(K,{columnGap:1,marginLeft:1},re.createElement(Y,{color:Dr},l),re.createElement(Y,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?gr.YELLOW:void 0,o=le(()=>buildTreeConnectors(e),[e]);return re.createElement(K,{flexDirection:"column",marginBottom:0,marginTop:-1},re.createElement(K,{columnGap:1},re.createElement(Y,{color:Dr},o),re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:r},e))),t&&re.createElement(K,{marginLeft:3},re.createElement(Y,{color:gr.DIM},"See ",t)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return re.createElement(K,null,re.createElement(Y,{color:gr.RED},t?Me.pointer:Me.warning),re.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?re.createElement(Y,{color:gr.RED,wrap:"wrap"},e):re.createElement(Markdown,{color:gr.RED},e)))}__name(AssistantMessage,"AssistantMessage"),Ut(),jr(),__name(BashMessage,"BashMessage"),Ut(),jr(),__name(CommandResultMessage,"CommandResultMessage"),Ut(),jr(),__name(ErrorMessage,"ErrorMessage"),Ut(),jr();var QP={connected:{char:Me.tick,color:gr.GREEN},installed:{char:Me.tick,color:gr.GREEN},up_to_date:{char:Me.tick,color:gr.GREEN},needs_reload:{char:Me.circle,color:gr.YELLOW},failed:{char:Me.cross,color:gr.RED},not_in_ide:{char:Me.circle,color:gr.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getStatusHeadline(e,t),i=QP[e];return re.createElement(K,{flexDirection:"column"},re.createElement(K,null,re.createElement(Y,null,re.createElement(Y,{color:i.color},i.char),re.createElement(Y,null," ",r),o&&re.createElement(Y,{color:gr.CYAN},o),s&&re.createElement(Y,null,s))),n?.map((e,t)=>re.createElement(Y,{key:t,color:gr.DIM}," ",e)))}function ReasoningMessage({content:e,expandedOutput:t,expandKey:n,isStreaming:r=!1}){const o=e?Math.max(1,Math.round(e.length/500)):1,s=Boolean(e),i=(s?e.split("\n"):[]).length,a=`${r?"Thinking…":`Thought for ${o} second${1!==o?"s":""}`}${r&&!t&&i>0?` (${i} line${1!==i?"s":""})`:""}`,l=t&&s,u=!t&&s,d=r&&t&&e.length>560,m=d?e.length-560:0,g=80*Math.floor(m/80),h=d?(e.slice(0,g).match(/\n/g)??[]).length:0,f=d?e.slice(g):e;return re.createElement(K,{flexDirection:"column",width:"90%"},re.createElement(K,null,re.createElement(Y,{color:yr},"✻"," "),re.createElement(Y,{color:yr},u?`${a} `:a),u&&re.createElement(BracketWrap,{color:gr.DIM},`${n}+o to expand`)),l&&d&&re.createElement(K,{marginLeft:2},re.createElement(Y,{color:gr.DIM},h>0?`… (${h} more line${1!==h?"s":""})`:"…")),l&&re.createElement(K,{marginLeft:2,flexDirection:"column"},re.createElement(Y,{color:yr,wrap:"wrap",italic:!0},f)))}__name(IDEStatusMessage,"IDEStatusMessage"),Ut(),jr(),__name(ReasoningMessage,"ReasoningMessage"),Ut(),Ut(),kn();function HelpMessage(){const e=getInvokedCommandName(),t=le(()=>Rk.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return re.createElement(K,{flexDirection:"column",paddingY:1},re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(K,null,re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:gr.GRAY}," v","0.35.1")),re.createElement(Y,{color:gr.GRAY},Ak)),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Usage"),re.createElement(K,{paddingLeft:2},re.createElement(Y,null,e," <command> [options]"))),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Options"),re.createElement(K,{flexDirection:"column",paddingLeft:2},Nk.map(t=>re.createElement(K,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(Pk)),re.createElement(Y,{color:gr.GRAY},t.description))))),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Commands"),re.createElement(K,{flexDirection:"column",paddingLeft:2},$k.map(t=>re.createElement(K,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(Pk)),re.createElement(Y,{color:gr.GRAY},t.description))))),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Slash Commands"),re.createElement(K,{flexDirection:"column",paddingLeft:2},t.map(e=>re.createElement(K,{key:e.key},re.createElement(Y,null,e.key.padEnd(Pk)),re.createElement(Y,{color:gr.GRAY},e.description))))),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Keyboard Shortcuts"),re.createElement(K,{flexDirection:"column",paddingLeft:2},Mk.map(e=>re.createElement(K,{key:e.key},re.createElement(Y,null,e.key.padEnd(Pk)),re.createElement(Y,{color:gr.GRAY},e.description))))),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Examples"),re.createElement(K,{flexDirection:"column",paddingLeft:2},Dk.map(t=>re.createElement(K,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(Pk)),re.createElement(Y,{color:gr.GRAY},t.description))))),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.CYAN},Me.pointer),re.createElement(Y,{color:gr.GRAY}," ",Ok.replace(/cmd/,e))),re.createElement(K,{flexDirection:"column"},re.createElement(Y,{bold:!0},"Links"),re.createElement(K,{flexDirection:"column",paddingLeft:2},Lk.map(e=>re.createElement(K,{key:e.key},re.createElement(Y,null,e.key.padEnd(Pk)),re.createElement(Y,{color:gr.CYAN},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?re.createElement(HelpMessage,null):re.createElement(K,{flexDirection:"column"},re.createElement(Y,{wrap:"wrap"},re.createElement(Markdown,null,e)))}jr(),ob(),bo(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),Ut(),Yn(),yo(),jr();var KP={"Interrupted by user":"Interrupted by user","Insufficient credits":jn};function UserMessage({content:e,images:t,imageCount:n=0,ideHint:r}){const o="Interrupted by user"===e,s="Insufficient credits"===e,i=e.startsWith("Error:"),a=o||s||i,l=a&&KP[e]||e,u=null!=t?t.length:n,d=ie(null);null===d.current&&t&&t.length>0&&(d.current=t.map((e,t)=>saveTempImage(e,t+1)));const m=d.current??[];return re.createElement(K,{flexDirection:"column"},re.createElement(K,{backgroundColor:a?void 0:_r.BG,paddingRight:1},re.createElement(Y,{color:a?gr.RED:_r.POINTER,bold:!a},Me.pointer),re.createElement(K,{marginLeft:1},re.createElement(Y,{color:a?gr.RED:gr.WHITE,wrap:"wrap"},l))),u>0&&re.createElement(K,{marginLeft:1},re.createElement(Y,{color:gr.DIM},"⎿"," ",Array.from({length:u},(e,t)=>{const n=m[t],r=`[Image #${t+1}]`;return null!=n?createOSC8Link(`file://${n}`,r,!1):r}).join(" "))),r&&!a&&re.createElement(K,{marginLeft:2},re.createElement(Y,{color:Dr},d_),re.createElement(Y,{color:gr.DIM}," ","Selected ",r.lines," ",1===r.lines?"line":"lines"," from"," ",r.file," in ",r.ide)))}function renderFeedEntry(e,t){if("user"===e.role){const t=Array.isArray(e.metadata?.images)?e.metadata.images:void 0,n=e.metadata?.ideHint;return re.createElement(UserMessage,{content:e.input,images:t,ideHint:n})}return"assistant"===e.role?re.createElement(AssistantMessage,{content:e.input}):"reasoning"===e.role?re.createElement(ReasoningMessage,{content:e.input,expandedOutput:t,expandKey:"ctrl",isStreaming:"running"===e.metadata?.status}):"tool"===e.role?re.createElement(ToolMessage,{name:Vb(e.name||""),input:e.input,output:e.output||"",isPending:Wb(e),hasError:zb(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?re.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:Wb(e),hasError:zb(e)}):"system"===e.role?re.createElement(SystemMessage,{content:e.input}):"info"===e.role?re.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?re.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?re.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?re.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName2(e){const t=findModelById(e);if(t){const e=t.name.toLowerCase().replaceAll(" ","-");return"free"===t.badge?`${e} (free)`:e}return e}function getProviderShortName(e){return e?yn[e]?.shortLabel??e.slice(0,4):""}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)),o="─".repeat(r);return re.createElement(K,{marginBottom:1},re.createElement(Y,{color:Tr},o),re.createElement(BracketedText,{text:n,color:Tr}),re.createElement(Y,{color:Tr},o))}__name(UserMessage,"UserMessage"),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName2,"getModelShortName"),__name(getProviderShortName,"getProviderShortName"),__name(TranscriptDivider,"TranscriptDivider");var YP=re.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o,currentProvider:s,hiddenCount:i=0})=>{const a=i>0?{role:"transcript-divider",count:i}:null,l=[...t?["header"]:[],...a?[a]:[],...e],u=useTerminalWidth(),d=le(()=>pA(u),[u]),m=le(()=>wA(u),[u]),g=le(()=>getPackageJson().version||"0.0.0",[]),h=le(()=>getGitHeaderInfo(),[]),f=le(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),y=o?getModelShortName2(o):"sonnet-4.6",w="taste-1",S=le(()=>{if(!o)return"";if(!modelSupportsReasoningEffort(o))return"";const e=getReasoningEffort(o);return e?` with ${e} effort`:""},[o,n]),E=isInternalTeamFlagEnforced()&&!process.env.CMD_DEMO,v=E?" · co":"",C=E&&s?` · ${getProviderShortName(s)}`:"";return re.createElement(J,{items:l,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return re.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:u});if("header"===e)return"compact"===m?re.createElement(K,{key:"header",marginBottom:1,flexDirection:"row"},re.createElement(K,{width:fA,flexShrink:0},re.createElement(SA,null,hA)),re.createElement(K,{flexDirection:"column",marginLeft:2},re.createElement(K,null,re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:Tr}," ","v",g)),re.createElement(Y,{color:Tr},"models: ",y,S," ·"," ",w,v),re.createElement(Y,{color:Tr},f,h&&h.isLocal&&h.branch&&` (${h.branch})`))):re.createElement(K,{key:"header",marginBottom:1,flexDirection:"column"},re.createElement(SA,null,d.trimEnd()),re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(K,null,re.createElement(Y,{color:Tr},"# "),re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:Tr}," v",g)),re.createElement(Y,{color:Tr},"# models: ",y,S," · ",w,C,v),re.createElement(K,null,re.createElement(Y,{color:Tr},"# ",f,h&&h.isLocal&&h.branch&&re.createElement(Y,{color:Tr}," ","(branch:"," ",h.branch,")")))));const t=e,n=renderFeedEntry(t,r);return re.createElement(K,{key:t.id,paddingBottom:1,width:"90%"},n)})});Ut(),Zb(),Eo(),jr();var JP=oe(__name(function LiveAgentStatusInner2({entry:e}){const t=Vb(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],o=r?r+(n.includes(".")||n.includes("\n")?".":""):n,s=e.metadata?.tokensUsed||0,i=e.metadata?.elapsedSeconds||0,a=e.metadata?.recentTools||[],[l,u]=se(".");return ae(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),re.createElement(K,{flexDirection:"column",marginBottom:1,width:"90%"},re.createElement(K,null,re.createElement(Y,{backgroundColor:vr.BG,color:vr.FG,bold:!0},` ${t} `),o&&re.createElement(Y,null," (",o,")")),re.createElement(K,{columnGap:1,marginLeft:1},re.createElement(Y,null,"⎿"," "),re.createElement(Y,{color:gr.GRAY},"Running (",formatTime2(i)," |"," ",formatTokens(s),")",l)),a.length>0&&re.createElement(K,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=Vb(e.name);return re.createElement(K,{key:t,columnGap:1},re.createElement(Y,{color:gr.GRAY},"⎿"),re.createElement(Y,{color:gr.GRAY}," ",n),e.input&&re.createElement(Y,{color:gr.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),XP=oe(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:re.createElement(JP,{entry:e})},"LiveAgentStatus"));Ut(),kn(),io(),co(),Eo(),bo(),jr(),Ut(),jr();var ZP={low:"Fast responses with lighter reasoning",medium:"Balances speed and reasoning depth for everyday tasks",high:"Greater reasoning depth for complex problems",xhigh:"Extra reasoning depth for complex problems",max:"Maximum reasoning budget for the hardest problems"},eI={value:void 0,label:"Default",description:"Use the provider default reasoning level"},tI=__name(({modelLabel:e,supportedEfforts:t,currentEffort:n,onSelect:r,onCancel:o})=>{const s=le(()=>[eI,...t.map(e=>({value:e,label:e,description:ZP[e]}))],[t]),i=le(()=>{if(void 0===n)return 0;const e=s.findIndex(e=>e.value===n);return e>=0?e:0},[s,n]),a=__name((e,t)=>`${e+1}. ${t}`,"labelText"),l=le(()=>Math.max(...s.map((e,t)=>a(t,e.label).length))+4,[s]),{cursor:u}=useListNavigation({items:s,onSelect:__name(e=>r(e.value),"onSelect"),onCancel:o,initialIndex:i,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,selectByNumber:!0});return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,{marginBottom:1},re.createElement(Y,{color:hr,bold:!0},`Select reasoning effort for ${e}`)),re.createElement(K,{flexDirection:"column"},s.map((e,t)=>{const r=t===u,o=e.value===n;return re.createElement(K,{key:e.label},re.createElement(Y,{color:r||!o?gr.WHITE:gr.GREEN,backgroundColor:r?xr:void 0,bold:r},a(t,e.label).padEnd(l)),re.createElement(Y,{color:r?gr.WHITE:gr.DIM,backgroundColor:r?xr:void 0},e.description," "),o&&re.createElement(Y,{color:gr.GREEN}," ",Me.tick))})),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"↑/↓ navigate · enter to select · esc to go back")))},"ReasoningEffortSelector");rr();var nI="Loading plan info…",rI=__name(e=>[{text:e.name,weight:100},{text:e.label,weight:50},{text:e.provider,weight:25},{text:e.description||"",weight:10}],"MODEL_SEARCH_FIELDS");function searchGroups2(e,t){if(!t.trim())return e;const n=[];for(const r of e){const e=fuzzyFilter(r.models,t,rI);e.length>0&&n.push({...r,models:e})}return n}function flattenGroups(e){const t=[];for(const n of e)for(const e of n.models)t.push({providerId:n.providerId,model:e});return t}function groupByModelProvider2(e,t){return groupModelsByDisplayOrder(e).map(e=>({providerId:t,label:e.label,models:e.models}))}__name(searchGroups2,"searchGroups"),__name(flattenGroups,"flattenGroups"),__name(groupByModelProvider2,"groupByModelProvider");var oI=__name(({onSelect:e,onCancel:t,currentModel:n,currentProvider:r,planId:o,purchasedCredits:s=0,freeCredits:i=0,refreshBanner:a})=>{const[l,u]=se(""),[d,m]=se(null),[g,h]=se(()=>new Set),f=le(()=>isInternalTeamFlagEnforced(),[]),y=le(()=>f?wn:groupByModelProvider2(Sn.flatMap(e=>e.models),yn["command-code"].id),[f]),w=le(()=>searchGroups2(y,l),[y,l]),S=le(()=>flattenGroups(w),[w]),[E,v]=se(0),C=useTerminalHeight()-1,k=Math.max(4,C-14-2*w.length),T=void 0!==o,_=le(()=>T?null:getCachedBillingContext(),[T]),[x,A]=se(_),[P,I]=se(!T&&!_);ae(()=>{if(T)return;if(x)return;let e=!0;return getBillingContext().then(t=>{e&&(A(t),I(!1))}),()=>{e=!1}},[T,x]);const M=!T&&!0===x?.fetchFailed,N=T?o:x?.planId??null,R=T?s:x?.purchasedCredits??0,$=T?i:x?.freeCredits??0,L=f?yn.anthropic.id:yn["command-code"].id,D=r??L,O=n?Math.max(0,S.findIndex(e=>e.model.id===n&&e.providerId===D)):0,[F,U]=se("model"),[j,B]=se(null),{cursor:q,error:z,setError:W}=useListNavigation({items:S,onSelect:__name(t=>{const n=getSupportedEfforts(t.model.id);if(n&&n.length>0)return B(t),void U("effort");e(t.model.id,t.providerId)},"onSelect"),onCancel:t,initialIndex:O,searchQuery:l,onSearchChange:u,isActive:"model"===F,validate:__name(e=>{if(g.has(e.providerId))return`Run /provider to authenticate with ${getProviderConfig(e.providerId)?.displayName??e.providerId} first`;if(d&&!f){const t=yn[d]?.supportedModelProviders;if(t&&!t.includes(e.model.provider))return`${yn[d]?.label??d} does not support ${e.model.provider} models. Switch provider via /provider.`}if(P)return nI;const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:N,purchasedCredits:R,freeCredits:$});return t.allowed?null:t.errorMessage??"Model not available for your plan"},"validate")});ae(()=>{v(e=>clampScrollOffset({cursor:q,total:S.length,maxVisible:k,currentOffset:e}))},[q,S.length,k]);const H=ie(!1),G=__name(t=>{if(!j||H.current)return;H.current=!0;const{model:r,providerId:o}=j,s=getReasoningEffort(r.id),i=t!==s,l=r.id===n;(async()=>{try{i&&(await setReasoningEffort({modelId:r.id,effort:t}),l&&a?.())}catch(e){dlog(`[Model] Failed to persist reasoning effort: ${e}`)}finally{e(r.id,o)}})()},"handleEffortSelect"),V=__name(()=>{H.current||(B(null),U("model"))},"handleEffortCancel");if(ae(()=>{if(P)return;if(z!==nI)return;const e=S[q];if(!e||M)return void W(null);const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:N,purchasedCredits:R,freeCredits:$});W(t.allowed?null:t.errorMessage??"Model not available for your plan")},[P,M,z,W,S,q,N,R,$]),ae(()=>{(async()=>{await isOAuthEnforced()&&m(await getConfiguredProvider())})()},[]),ae(()=>{(async()=>{const e=new Set(y.map(e=>e.providerId)),t=new Set;for(const n of e){const e=getProviderConfig(n);e?.requiresAuth&&e.checkAuth&&(await e.checkAuth()||t.add(n))}h(t)})()},[y]),"effort"===F&&j){const e=getSupportedEfforts(j.model.id)??[];return re.createElement(tI,{modelLabel:j.model.label,supportedEfforts:e,currentEffort:getReasoningEffort(j.model.id),onSelect:G,onCancel:V})}const Q=E,J=E+k;let X=0;const Z=w.map(e=>{const t=sliceSectionForWindow({section:e.models,sectionBase:X,windowStart:Q,windowEnd:J});return X+=e.models.length,{group:e,groupWindow:t}}).filter(e=>e.groupWindow.rows.length>0),ee=S.length>k;return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Select model")),re.createElement(K,{marginBottom:1},re.createElement(Y,{dimColor:!0},f?"Select a model and provider. Sets the default for new sessions; other open sessions are unaffected. Provider is saved.":"Switch between Command Code models. Sets the default for new sessions; other open sessions are unaffected.")),re.createElement(K,{marginBottom:2,flexDirection:"column",width:"100%"},re.createElement(TA,{query:l,resultCount:l?S.length:void 0,placeholder:"Type to search models..."})),0===S.length?re.createElement(K,{marginY:1},re.createElement(Y,{color:gr.GRAY},'No models match "',l,'"')):re.createElement(K,{flexDirection:"column"},Z.map(({group:e,groupWindow:t},r)=>re.createElement(K,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:r>0?1:0},f?re.createElement(Y,{bold:!0,color:hr},e.label):re.createElement(Y,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>re.createElement(uP,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===q,isCurrent:r.id===n&&e.providerId===D,showProviderLabel:!!f&&void 0}))))),ee&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",Q+1,"–",Math.min(J,S.length)," of ",S.length,Q>0?" · ↑ more":"",J<S.length?" · ↓ more":"")),z&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.GRAY},z)),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"type to search · ↑/↓ navigate · enter to select"),l?re.createElement(Y,{color:gr.DIM}," · esc to clear"):re.createElement(Y,{color:gr.DIM}," · esc to cancel")))},"ModelSelector");Ut(),io(),co(),rr();var sI=__name(({currentModel:e,onClose:t,refreshBanner:n})=>{const r=getSupportedEfforts(e)??[],o=findModelById(e)?.label??getModelDisplayName(e),s=ie(!1),i=__name(r=>{if(s.current)return;s.current=!0;const o=r!==getReasoningEffort(e);(async()=>{try{o&&(await setReasoningEffort({modelId:e,effort:r}),n())}catch(e){dlog(`[Effort] Failed to persist reasoning effort: ${e}`)}finally{t()}})()},"handleSelect"),a=__name(()=>{s.current||t()},"handleCancel");return re.createElement(tI,{modelLabel:o,supportedEfforts:r,currentEffort:getReasoningEffort(e),onSelect:i,onCancel:a})},"EffortSelector");Ut(),bo(),jr();var iI=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,i=n&&-1===s;return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},re.createElement(K,null,re.createElement(Y,{bold:!0},"Select AI Provider")),n&&re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:gr.DIM},"Current: "),re.createElement(Y,{color:gr.GREEN},getProviderDisplayName(n)),i&&re.createElement(Y,{color:gr.YELLOW}," ","[OAuth enforced]"))),re.createElement(K,{marginBottom:0},re.createElement(Y,{color:gr.DIM},"Available Providers:")),re.createElement(gt,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>re.createElement(Y,{color:e?gr.CYAN:gr.GRAY,bold:e},e?Me.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.CYAN:gr.GRAY,bold:e},` ${t}`)}),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=se(0);if(ae(()=>{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 re.createElement(K,{marginBottom:1},re.createElement(Y,{color:Nr,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Ut(),jr(),__name(RetryMessage,"RetryMessage"),Ut(),bs(),Yn(),jr();var aI=[{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"}],lI=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=le(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=se(Math.max(0,r.length-1)),[i,a]=se(Math.max(0,r.length-8)),[l,u]=se("checkpoint"),[d,m]=se(null),[g,h]=se(0),f=le(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),y=le(()=>f?aI:aI.filter(e=>"conversation"===e.mode),[f]);if(ae(()=>{if(r.length>0){const e=r.length-1;s(e),a(Math.max(0,r.length-8))}},[r.length,8]),Z((e,f)=>{f.escape?"mode"===l?(u("checkpoint"),m(null),h(0)):n():"checkpoint"===l?f.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):f.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):f.return&&r.length>0&&(m(r[o]),u("mode"),h(0)):"mode"===l&&(f.upArrow?h(e=>Math.max(0,e-1)):f.downArrow?h(e=>Math.min(y.length-1,e+1)):f.return&&d&&y[g]&&t({messageId:d.messageId,mode:y[g].mode}))}),0===r.length)return re.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:hr,bold:!0},"Rewind"),re.createElement(Y,{color:gr.DIM},"No checkpoints available. Start a conversation to create checkpoints."),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press "),re.createElement(Y,{color:gr.DIM,bold:!0},"Esc"),re.createElement(Y,{color:gr.DIM}," to close")));if("mode"===l&&d)return re.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:hr,bold:!0},"Rewind"),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"Restore to: "),re.createElement(Y,{color:gr.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),re.createElement(K,{flexDirection:"column"},y.map((e,t)=>{const n=g===t,r=t===y.length-1;return re.createElement(K,{key:e.mode,flexDirection:"column"},re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:n?hr:void 0},n?`${qn} `:" "),re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:n?hr:gr.WHITE},e.label),re.createElement(Y,{color:gr.DIM},e.description))),!r&&re.createElement(Y,null," "))})),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press "),re.createElement(Y,{color:gr.DIM,bold:!0},"Enter"),re.createElement(Y,{color:gr.DIM}," to confirm, "),re.createElement(Y,{color:gr.DIM,bold:!0},"Esc"),re.createElement(Y,{color:gr.DIM}," to go back")));const w=r.slice(i,i+8);return re.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:hr,bold:!0},"Rewind"),re.createElement(Y,{color:gr.DIM},"Select a checkpoint to restore your session"),r.length>8&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),re.createElement(K,{marginTop:1}),re.createElement(K,{flexDirection:"column"},w.map((e,t)=>{const n=i+t,s=o===n,a=e.filesModified.length,l=t===w.length-1,u=n===r.length-1;return re.createElement(K,{key:e.messageId,flexDirection:"column"},re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:s?hr:void 0},s?`${qn} `:" "),re.createElement(K,{flexDirection:"column"},re.createElement(K,null,re.createElement(Y,{color:s?hr:gr.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),re.createElement(Y,{color:gr.DIM}," • "),re.createElement(Y,{color:gr.DIM},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),re.createElement(Y,{color:gr.DIM},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&re.createElement(Y,null," "))})),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press "),re.createElement(Y,{color:gr.DIM,bold:!0},"Enter"),re.createElement(Y,{color:gr.DIM}," to select, "),re.createElement(Y,{color:gr.DIM,bold:!0},"Esc"),re.createElement(Y,{color:gr.DIM}," to cancel")))},"RewindSelector");Ut(),jr();var cI=[{label:"Complete brief",desc:"If the target, goal, audience, or artifact is clear, act without asking."},{label:"Composition",desc:"Choose layout from the work pattern: monitor, operate, compare, configure, learn, decide, or explore."},{label:"Scope",desc:"Broad prompts get the full mode pass. Narrow prompts stay narrow."},{label:"Truth",desc:"Only claim changes that exist in files and are visible or verifiable."},{label:"Templates",desc:"design-html and report-html are documentation templates, not UI inspiration."},{label:"Reports",desc:"Follow-up modes read markdown reports, apply relevant findings, then still run their own full mode pass."}],uI=['/design redesign "Make this dashboard feel like an operator console"','/design motion "Animate the whole page and add missing interactions"','/design checkup "Audit this UI and generate the design report"','/design "Build a landing page for a privacy-first contract review tool"'],dI=__name(({onCancel:e})=>(Z((t,n)=>{n.escape&&e()}),re.createElement(K,{flexDirection:"column",paddingLeft:2,paddingRight:2},re.createElement(K,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:hr},"Use"),re.createElement(K,{paddingLeft:2,flexDirection:"column"},re.createElement(Y,{color:gr.DIM},'/design <mode> "target or request"'),re.createElement(Y,{color:gr.DIM},'/design "freeform request" also works. The closest mode is inferred.'))),re.createElement(K,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:hr},"Modes"),re.createElement(K,{paddingLeft:2,flexDirection:"column"},kx.map(e=>re.createElement(K,{key:e.name,columnGap:2},re.createElement(K,{width:18,flexShrink:0},re.createElement(Y,{color:gr.CYAN},"/design ",e.name)),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},e.description)))))),re.createElement(K,{marginBottom:1,marginTop:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:hr},"Working rules"),re.createElement(K,{paddingLeft:2,flexDirection:"column"},cI.map(e=>re.createElement(K,{key:e.label,columnGap:2},re.createElement(K,{width:16,flexShrink:0},re.createElement(Y,{color:gr.CYAN},e.label)),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},e.desc)))))),re.createElement(K,{marginBottom:1,marginTop:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:hr},"Quick examples:"),re.createElement(K,{paddingLeft:2,flexDirection:"column"},uI.map(e=>re.createElement(Y,{key:e,color:gr.DIM},e)))),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press Esc to close. Type /design help anytime to return.")))),"DesignGuide");Ut(),rr(),Ut(),Ut();var mI=__name(e=>{const[t,n]=se(e),[r,o]=se(null);return ae(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),o(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}):o(e.message)},"handleNewEvent");return BT.on("reset",t),BT.on("new-event",r),()=>{BT.off("reset",t),BT.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new rS({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o,s;try{const e=await getOAuthCredentials({provider:n});o=e.token,s=e.oauthProvider,validateOAuthToken({token:o,provider:n})}catch(e){dlog("Failed to get or validate OAuth token:",e instanceof Error?e.message:String(e))}const i={[zt.PROJECT_SLUG]:Hk.getCurrentProjectDirName(),[zt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(i[zt.OAUTH_TOKEN]=`Bearer ${o}`,s&&(i[zt.OAUTH_PROVIDER]=s)),{request:t,headers:i}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const o of e){const e=estimateTokens(o);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([o])):r+e>2e3?(n.length>0&&t.push(n),n=[o],r=e):(n.push(o),r+=e)}return n.length>0&&t.push(n),t}function buildObserverPrompt(e,t){return`Produce ${t} varied observations for these prompts:\n\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}function createInsightEmitter(){let e="",t=0;const n=__name(()=>{if(e.includes("\n")){const t=e.split("\n");for(let e=0;e<t.length-1;e++){const n=t[e].trim();n&&(dlog(`[ObserverAPI] emitting insight: ${n}`),BT.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()}`),BT.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function callObserverAPI(e,t,n){const r=getTasteObserverModel();dlog(`[ObserverAPI] calling ${Wt.ALPHA.GENERATE} with model: ${r}`);const o={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:n}],model:r,system:"You scan prompts and produce casual observations like a dev friend glancing at someone's 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 per observation\n- one observation per line\n- sound human, not robotic\n- output only the observations, no preamble",max_tokens:200,temperature:.7,stream:!0},threadId:Ie()},s=await e.post({endpoint:Wt.ALPHA.GENERATE,body:o,headers:t,stream:!0});dlog("[ObserverAPI] got response stream");const i=createInsightEmitter();await consumeSSEStream(s,{onText:__name(e=>{i.addText(e)},"onText")}),dlog(`[ObserverAPI] stream complete, ${i.getChunkCount()} chunks received`),i.emitRemaining(),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,o){let s=0;for(const e of n)s+=estimateTokens(e);dlog(`[Observer] batch ${r}/${o}: ${n.length} prompts`);const i=buildObserverPrompt(n,4);await callObserverAPI(e,t,i)}async function observeSessionPrompts(e){if(BT.observerHasRun)return;BT.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r={...n,[zt.SESSION_ID]:`observer-${Ie()}`},o=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${o.length} batches`);const s=Math.min(o.length,6);for(let t=0;t<s;t++){if(BT.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const n=o[t];try{await processBatch(e,r,n,t+1,o.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),BT.addEvent({type:"progress",message:"Continuing without live observations..."})}}Ut(),Ut(),vS(),LS(),rr(),Ut(),kn(),rr(),Ut(),Ut(),kn(),vS(),LS(),rr(),co(),Eo(),__name(createRequestClient,"createRequestClient"),Ut(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Ut(),Ut(),rr(),Go(),Ut(),kn(),__name(buildObserverPrompt,"buildObserverPrompt"),__name(createInsightEmitter,"createInsightEmitter"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var pI=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(w.homedir(),".claude","projects");await C.access(r);const o=process.cwd().replace(/[/\\]/g,"-");dlog(`[Import] scanning project: ${o}`);const s=(await C.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await C.stat(s)).isDirectory())continue;const r=(await C.readdir(s)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const o of r){const r=e.join(s,o),i=await C.stat(r),a=o.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{BT.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&BT.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{BT.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 C.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=[],o=0;for(const s of e){const e=estimateTokens(s);if(e>t){r.length>0&&(n.push(r),r=[],o=0);const e=this.splitLargePrompt(s,t);for(const t of e)n.push([t])}else o+e<=t?(r.push(s),o+=e):(r.length>0&&n.push(r),r=[s],o=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let o="",s=0;for(const e of r){const r=estimateTokens(e);s+r<=t?(o+=(o?"\n":"")+e,s+=r):(o&&n.push(o),o=e,s=r)}return o&&n.push(o),n}static async importAndLearn(){const e=[],t=[],n=[],r=[],o=[];try{BT.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const s=await loadProjectSettings(),i=s.tasteOnboarding?.learnedSessions||{},a=i["claude-code"]?.length||0,l=i.codex?.length||0,u=i.cursor?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${l} learned, cursor=${u} learned`);const d=await findNewSessions(i),m=d["claude-code"]||[],g=d.codex||[],h=d.cursor||[],f=m.length+g.length+h.length;if(dlog(`[Import] findNewSessions returned: claude-code=${m.length} new, codex=${g.length} new, cursor=${h.length} new`),0===f){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=await findCursorSessions(process.cwd()),r=e.length+t.length+n.length,o=[{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}`);BT.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:r>0?`From ${o.join(" + ")} sessions`:"No sessions found for this project"});const s=[];return e.length>0&&s.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&s.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),n.length>0&&s.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:s,status:"already-learned"}}if(m.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>m.includes(e.id));n.push(...e)}if(g.length>0){const e=(await this.findCodexSessions()).filter(e=>g.includes(e.id));r.push(...e)}if(h.length>0){const e=(await this.findCursorSessions()).filter(e=>h.includes(e.id));o.push(...e)}const y=n.length+r.length+o.length;dlog(`[Import] total sessions: ${y} (claude-code: ${n.length}, codex: ${r.length}, cursor: ${o.length})`),BT.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const w=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts},{name:"Cursor",sessions:o,extractPrompts:extractCursorPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of w){BT.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const S=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${S.length} batches`);const E=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});BT.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${S.length} batch${1===S.length?"":"es"}`});try{const s=getApiBaseUrl(),i=new rS({baseUrl:s});let a=!0;for(let e=0;e<S.length;e++){const t=S[e],n=e+1,r=S.length;r>1&&BT.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),s=new HT({request:i,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await s.checkAndProcess({messages:l})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),BT.markLearningComplete(),await E,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}if(o.length>0){const e=o.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})`),o.length>0&&u.push(`Cursor (${o.length})`),!a){const s=BT.getEvents().some(e=>"error"===e.type&&e.message?.toLowerCase().includes("insufficient credits")),i="Learning failed - sessions not marked as learned";return e.push(i),s||BT.addEvent({type:"error",message:i}),{success:!1,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}return BT.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${u.join(" + ")}`,learningCount:l.totalLearnings,categories:l.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),BT.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 C.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),o=r?r.length:0;return{totalLearnings:o,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")}},gI=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),hI=__name(e=>{const[t,n]=se({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return ae(()=>{BT.reset(),BT.markImportStarted(),(async()=>{try{const t=await Promise.race([pI.importAndLearn(),gI(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");Ut();var fI=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{Z((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");Ut(),rr();var yI=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=se(null),[o,s]=se(null),i=ie(!1);return ae(()=>{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),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,isLoading:!n&&!o}},"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{BT.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{BT.reset(),e()}}Ut(),rr(),Ut(),rr(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var wI=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=ie(n),o=ce(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=ce(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=ce(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=ce(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=ce(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:i,handleErrorDismiss:a,handleSkip:l}},"useOnboardingHandlers");Ut(),rr();var SI=__name(({conditions:e,autoLearn:t})=>{const[n,r]=se("checking"),o=ie(!1);return ae(()=>{if(e&&!o.current){if(o.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),ae(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Ut(),Ut(),jr();var bI=__name(({error:e})=>re.createElement(K,{padding:1},re.createElement(K,{flexDirection:"column",borderColor:gr.RED,padding:1},re.createElement(K,{marginBottom:1},re.createElement(Y,null,"Error initializing onboarding: ",e)),re.createElement(K,null,re.createElement(Y,null,"Continuing without onboarding...")))),"OnboardingError");Ut(),Ut(),jr();var EI=__name(()=>re.createElement(Y,null,"Skip"),"SkipOptionText"),vI=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=se(1);return Z((e,t)=>{t.escape?r():"n"!==e&&"N"!==e?t.upArrow||t.downArrow?s(e=>1===e?2:1):"1"!==e?"2"!==e?t.return&&(1===o?n():r()):r():n():dismissOnboardingForeverForProject().then(()=>r())}),re.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:fr.TEXT,paddingX:1,paddingY:0},re.createElement(Y,{color:fr.TEXT,bold:!0},"Build Your Coding Taste"),re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(Y,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),re.createElement(K,{marginTop:1},re.createElement(Y,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(K,null,re.createElement(Y,{color:1===o?fr.TEXT:gr.GRAY},1===o?Me.pointer:" "," 1. Yes, learn (recommended)")),re.createElement(K,null,re.createElement(Y,{color:2===o?fr.TEXT:gr.GRAY},2===o?Me.pointer:" "," 2."," ",re.createElement(EI,null)))),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"↑↓ · "),re.createElement(Y,{color:Rr.CODE},"enter"),re.createElement(Y,{color:gr.DIM}," ok · "),re.createElement(Y,{color:Rr.CODE},"esc"),re.createElement(Y,{color:gr.DIM}," skip · "),re.createElement(Y,{color:Rr.CODE},"n"),re.createElement(Y,{color:gr.DIM}," never")))},"ImportChoice");Ut(),Ut(),jr();var CI=__name(({error:e})=>re.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:gr.RED,paddingX:2,paddingY:1,marginBottom:2},re.createElement(Y,{color:gr.RED,bold:!0},"Oops, something went wrong:"),re.createElement(K,{marginTop:1},re.createElement(Y,null,e))),"ErrorSection");Ut(),Ut(),jr(),Ut(),Ut(),Ut(),jr(),Ut(),jr();var kI=__name(()=>re.createElement(Y,{backgroundColor:fr.BADGE_BG,color:fr.BADGE_FG},g_),"TasteBadge");Ut(),jr(),Ut();var TI=["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"],_I="⎿",xI=__name(()=>{const[e,t]=se(()=>Math.floor(Math.random()*TI.length));return ae(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*TI.length))},2e3);return()=>clearInterval(e)},[]),re.createElement(Y,{color:gr.YELLOW},TI[e],"...")},"PulsingText");Ut(),jr();var AI=[Me.bullet,Me.squareSmallFilled,Me.lozenge,Me.star,Me.triangleRight,Me.triangleUp,Me.circleFilled,Me.pointer],PI=__name(e=>String(e).padStart(3," "),"padNum"),II=__name(e=>AI[e%AI.length],"getSymbol"),MI=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${PI(t)} ↓${PI(n)} (↑↓ scroll)`,"buildStatusLine"),NI=__name(({insights:e})=>{const[t,n]=se(0),[r,o]=se(!0),s=e.length,i=s>10,a=Math.max(0,s-10);if(ae(()=>{r&&i&&n(a)},[s,r,i,a]),Z((e,t)=>{if(i)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(a,e+1);return t===a&&o(!0),t}))}),0===s)return null;const l=e.slice(t,t+10),u=t,d=s-t-10;return re.createElement(K,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&re.createElement(Y,{color:gr.DIM},MI(s,u,d,r)),l.map((e,n)=>{const r=t+n;return re.createElement(K,{key:r,marginBottom:0},re.createElement(Y,{color:gr.DIM},II(r)," ",e))}))},"ScrollableInsights");Ut(),jr();var RI=__name(()=>{const[e,t]=se(!0);return ae(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),re.createElement(Y,{color:gr.YELLOW},e?Me.circleFilled:Me.circle)},"PulsingDot"),$I=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return re.createElement(K,{flexDirection:"column",marginBottom:0},re.createElement(kI,null),re.createElement(K,{marginTop:0},re.createElement(Y,{color:gr.DIM},_I),re.createElement(K,{marginLeft:2},a?re.createElement(Y,{color:fr.TEXT},"learned your coding taste"):re.createElement(xI,null))));const u=__name(()=>r?re.createElement(Y,{color:br.BG},Me.square):n?re.createElement(RI,null):re.createElement(Y,{color:gr.DIM},Me.circle),"getStatusIcon"),d=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||d?re.createElement(K,{flexDirection:"column",marginBottom:0},(n||r)&&re.createElement(K,{marginBottom:0},re.createElement(K,{marginRight:1},u()),re.createElement(Y,{color:r?gr.WHITE:n?gr.YELLOW:gr.DIM},e)),r&&t&&(!l||0===l.learningCount)&&re.createElement(K,{marginLeft:3,marginBottom:0},re.createElement(Y,{color:gr.DIM},t)),o.length>0&&re.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>re.createElement(Y,{key:t,color:gr.DIM},`${Me.bullet} ${e}`))),s.length>0&&re.createElement(NI,{insights:s}),r&&l&&l.learningCount>0&&re.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},re.createElement(K,{marginBottom:1,flexDirection:"row"},re.createElement(Y,null,_I),re.createElement(K,{marginLeft:2},re.createElement(Y,{color:fr.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),re.createElement(K,{flexDirection:"column",marginLeft:1},re.createElement(Y,{color:gr.DIM},Me.pointerSmall," Stored in ",l.storage),re.createElement(Y,{color:gr.DIM},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),LI=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return re.createElement(K,{flexDirection:"column",marginBottom:1},e.map((e,n)=>re.createElement(K,{key:e.id,marginLeft:0===n?0:3},re.createElement($I,{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"),DI=__name(({steps:e})=>re.createElement(LI,{steps:e}),"ProgressSection");Ut(),jr();var OI=__name(({isImporting:e=!1,waitingForInput:t=!1})=>re.createElement(re.Fragment,null,e&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"ESC to cancel")),t&&re.createElement(K,{marginTop:1},re.createElement(Y,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Ut();var FI=[{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"}}],UI=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=mI(FI),{isImporting:s,waitingForInput:i,error:a}=hI(t);return fI({onEscape:__name(()=>{i&&((a||o)&&n?n():e())},"onEscape"),onEnter:__name(()=>{i&&((a||o)&&n?n():e())},"onEnter"),enabled:s||i}),re.createElement(K,{flexDirection:"column",padding:1},o&&re.createElement(CI,{error:o}),!o&&re.createElement(DI,{steps:r}),re.createElement(OI,{isImporting:s,waitingForInput:i}))},"ImportProgress"),jI=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?re.createElement(vI,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?re.createElement(UI,{onComplete:r,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),BI=__name(({onComplete:e,autoLearn:t=!1})=>{ae(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=yI({autoLearn:t,onShouldSkip:e}),{step:s,setStep:i}=SI({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=wI({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?re.createElement(bI,{error:r}):"done"===s?null:re.createElement(jI,{step:s,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 o=[];for(const e of n)if(o.unshift(e),r-=getEntryCharCount(e),r<=0)break;return o}__name(getEntryCharCount,"getEntryCharCount"),__name(getBudgetedFeed,"getBudgetedFeed");var qI=oe(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,setStaticKey:s,transcriptMode:i,tasteOnboardingEntryId:a,autoLearnTaste:l,showTasteSkipBanner:u,showZdrNotice:d,retryAttempt:m,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,showFileList:w,setShowFileList:S,showProviderSelector:E,showModelSelector:v,showEffortSelector:C,showMemorySelector:k,showMcpManager:T,showAgentsConfig:_,showRewindSelector:x,showLoginOverlay:A,showUsageOverlay:P,showAddDirModal:I,showCompactModeSelector:M,showConfigureModels:N,setShowConfigureModels:R,authComponentInfo:$,status:L,currentProvider:D,currentModel:O,showProviderNotification:F,shareInfo:U,showShareNotification:j,unshareNotificationMessage:B,updateStatus:q,updateFailedInfo:z,creditWarning:W,permissionMode:H,hintMessage:G,pendingExitKey:V,tasteLearningEnabled:Q,interactionTokens:J,contextUsage:X,historyManagerRef:Z,executionState:ee,contextEngineRef:te,onSubmit:ne,onCommand:oe,onToggleAutoAccept:se,onResetPendingExitKey:ie,onDoubleEscapeEmpty:ae,onTasteOnboardingComplete:ue,permissionPanel:de,questionPanel:me,designSuggestionPanel:pe,onRewindSelect:ge,onRewindCancel:he,onLoginComplete:fe,onLoginCancel:ye,setShowProviderSelector:we,setShowModelSelector:Se,setShowEffortSelector:be,setShowMemorySelector:Ee,setShowMcpManager:ve,setShowAgentsConfig:Ce,setShowAddDirModal:ke,setShowUsageOverlay:Te,handleProviderSelect:_e,handleProviderCancel:xe,handleModelSelect:Ae,handleModelCancel:Pe,handleCompactModeSelect:Ie,handleCompactModeCancel:Me,handleAuthSuccess:Ne,handleAuthCancel:Re,showDesignGuide:$e,setShowDesignGuide:Le}){const De=le(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Oe=ce(()=>Le(!1),[Le]),Fe=useTerminalWidth(),Ue=le(()=>"off"===i?De:getBudgetedFeed(De,"limited"===i?15e3:5e4),[De,i]),je=le(()=>"off"===i?0:Math.max(0,De.length-Ue.length),[De.length,Ue.length,i]),Be=le(()=>0===je?Ue:Ue.filter(e=>"user"!==e.role),[Ue,je]),qe=ce(()=>Ce(!1),[Ce]),ze=ce(()=>Ee(!1),[Ee]),We=ce(()=>ve(!1),[ve]),He=ce(()=>ke(!1),[ke]),Ge=ce(()=>Se(!0),[Se]),Ve=ce(()=>be(!1),[be]),Qe=ce(()=>{hardResetForResize(),s(e=>e+1)},[s]),Ke=!("off"!==i||de||me||pe||E||v||C||$||k||T||_||x||A||P||I||M||N||$e||a);return re.createElement(K,{flexDirection:"column",width:"100%"},re.createElement(YP,{staticKey:o,feed:Be,showHeader:!0,expandedToolOutput:"off"!==i,currentModel:O,currentProvider:D,hiddenCount:je}),a&&re.createElement(BI,{onComplete:ue,autoLearn:l}),u&&re.createElement(TasteSkipMessage,null),d&&re.createElement(ZdrPausedMessage,null),t.map(e=>e.metadata?.isAgent?re.createElement(XP,{key:e.id,entry:e}):re.createElement(K,{key:e.id,marginBottom:1,width:"90%"},renderFeedEntry(e,"off"!==i))),re.createElement(RetryMessage,{attempt:m}),pe,me,de,"off"!==i&&re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"─".repeat(Fe))),re.createElement(K,{paddingRight:1},re.createElement(Y,{backgroundColor:br.BG,color:br.FG,bold:!0},`${p_}DETAILED TRANSCRIPT${p_}`),re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{bold:!0},"ctrl+o"),re.createElement(Y,{color:gr.DIM}," to toggle"),re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{bold:!0},"ctrl+e"),re.createElement(Y,{color:gr.DIM}," ","to"," ","limited"===i?"show all":"collapse"),re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{bold:!0},"esc"),re.createElement(Y,{color:gr.DIM}," to exit"))),Ke&&re.createElement(zP,{queuedMessages:n,isProcessing:r,executionState:ee,status:L,input:g,setInput:h,onSubmit:ne,showFileList:w,setShowFileList:S,fileSearchQuery:f,setFileSearchQuery:y,onCommand:oe,outputTokens:J,contextUsage:X,tasteLearning:Q,shareInfo:U,showShareNotification:j,unshareNotificationMessage:B,updateStatus:q,updateFailedInfo:z,creditWarning:W,currentProvider:D,currentModel:O,showProviderInfo:F,permissionMode:H,onToggleAutoAccept:se,hintMessage:G,historyManager:Z.current,pendingExitKey:V,onResetPendingExitKey:ie,onDoubleEscapeEmpty:ae,retryAttempt:m,onAltP:Ge}),E&&re.createElement(K,{marginY:1},re.createElement(iI,{onSelect:_e,onCancel:xe,currentProvider:D})),v&&re.createElement(K,{marginY:1},re.createElement(oI,{onSelect:Ae,onCancel:Pe,currentModel:O,currentProvider:D,refreshBanner:Qe})),C&&re.createElement(K,{marginY:1},re.createElement(sI,{currentModel:O,onClose:Ve,refreshBanner:Qe})),$e&&re.createElement(K,{marginY:1},re.createElement(dI,{onCancel:Oe})),M&&re.createElement(K,{marginY:1},re.createElement(cP,{onSelect:Ie,onCancel:Me})),N&&re.createElement(K,{marginY:1},re.createElement(pP,{onClose:()=>R(!1)})),_&&re.createElement(K,{marginY:1},re.createElement(aP,{onCancel:qe})),k&&re.createElement(K,{marginY:1},re.createElement(GP,{onClose:ze})),T&&re.createElement(K,{marginY:1},re.createElement(HP,{onClose:We})),x&&te.current&&re.createElement(K,{marginY:1},re.createElement(lI,{checkpoints:te.current.listCheckpoints(),onSelect:ge,onCancel:he})),$&&re.createElement(K,{marginY:1},re.createElement($.Component,{onSuccess:Ne,onCancel:Re})),A&&re.createElement(K,{marginY:1},re.createElement(WP,{onComplete:fe,onCancel:ye})),I&&re.createElement(K,{marginY:1},re.createElement(HA,{onClose:He})))},"MainView"));function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,pendingOps:a,permissionState:l,contextEngineRef:u,historyManagerRef:d,executionState:m,actionCallbacks:g,onSubmit:h,onCommand:f,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,updateFailedInfo:v,creditWarning:C,handleTrust:k,handleNoTrust:T,handleToggleAutoAccept:_,handleDoubleEscapeEmpty:x,handleTasteOnboardingComplete:A,loadTasteStatus:P}){if(i.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return re.createElement(zx,{staticKey:o.staticKey,onTrust:k,onExit:T});if(o.showSessionSelector)return re.createElement(Vx,{onSelectSession:g.onSelectSession,onNewSession:g.onNewSession});if(!s.projectTrusted)return null;const I=o.pendingDesignSuggestion?re.createElement(jx,{suggestion:o.pendingDesignSuggestion,onSelect:e=>{f(`/design ${e}`)},onClose:()=>o.setPendingDesignSuggestion(null)}):null,M=a.pendingQuestion?re.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,N=a.pendingPermission?re.createElement(iA,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:_}):null;return o.showLearningFeed?re.createElement(LearningView,{setShowLearningFeed:o.setShowLearningFeed,setStaticKey:o.setStaticKey,onExit:()=>i.setShouldExit(!0)}):o.showTasteConfig?re.createElement(TasteConfigView,{staticKey:o.staticKey,setShowTasteConfig:o.setShowTasteConfig,loadTasteStatus:P}):o.showSkillsConfig?re.createElement(SkillsConfigView,{staticKey:o.staticKey,setShowSkillsConfig:o.setShowSkillsConfig,setStaticKey:o.setStaticKey}):o.showUsageOverlay?re.createElement(UsageView,{staticKey:o.staticKey,setShowUsageOverlay:o.setShowUsageOverlay}):o.showContextView?re.createElement(ContextConfigView,{staticKey:o.staticKey,contextEngineRef:u,setShowContextView:o.setShowContextView,setInput:w}):o.showStatusView?re.createElement(StatusConfigView,{staticKey:o.staticKey,setShowStatusView:o.setShowStatusView,setInput:w}):re.createElement(qI,{feed:e.feed,liveEntries:e.liveEntries,queuedMessages:e.queuedMessages,isCmdCodeBusy:e.isCmdCodeBusy,staticKey:o.staticKey,setStaticKey:o.setStaticKey,transcriptMode:o.transcriptMode,tasteOnboardingEntryId:s.tasteOnboardingEntryId,autoLearnTaste:s.autoLearnTaste,showTasteSkipBanner:o.showTasteSkipBanner,showZdrNotice:o.showZdrNotice,retryAttempt:n.retryAttempt,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,showFileList:o.showFileList,setShowFileList:o.setShowFileList,showProviderSelector:o.showProviderSelector,showModelSelector:o.showModelSelector,showEffortSelector:o.showEffortSelector,showMemorySelector:o.showMemorySelector,showMcpManager:o.showMcpManager,showAgentsConfig:o.showAgentsConfig,showRewindSelector:o.showRewindSelector,showLoginOverlay:o.showLoginOverlay,showUsageOverlay:o.showUsageOverlay,setShowUsageOverlay:o.setShowUsageOverlay,showAddDirModal:o.showAddDirModal,showCompactModeSelector:o.showCompactModeSelector,showConfigureModels:o.showConfigureModels,setShowConfigureModels:o.setShowConfigureModels,authComponentInfo:r.authComponentInfo,status:n.status,currentProvider:r.currentProvider,currentModel:r.currentModel,showProviderNotification:r.showProviderNotification,shareInfo:n.shareInfo,showShareNotification:n.showShareNotification,unshareNotificationMessage:n.unshareNotificationMessage,updateStatus:n.updateStatus,updateFailedInfo:v,creditWarning:C,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,tasteLearningEnabled:n.tasteLearningEnabled,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,historyManagerRef:d,executionState:m,contextEngineRef:u,onSubmit:h,onCommand:f,onToggleAutoAccept:_,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:x,onTasteOnboardingComplete:A,permissionPanel:N,questionPanel:M,designSuggestionPanel:I,onRewindSelect:g.onRewindSelect,onRewindCancel:g.onRewindCancel,onLoginComplete:g.onLoginComplete,onLoginCancel:g.onLoginCancel,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowEffortSelector:o.setShowEffortSelector,setShowMemorySelector:o.setShowMemorySelector,setShowMcpManager:o.setShowMcpManager,setShowAgentsConfig:o.setShowAgentsConfig,setShowRewindSelector:o.setShowRewindSelector,setShowLoginOverlay:o.setShowLoginOverlay,setShowAddDirModal:o.setShowAddDirModal,handleProviderSelect:g.handleProviderSelect,handleProviderCancel:g.handleProviderCancel,handleModelSelect:g.handleModelSelect,handleModelCancel:g.handleModelCancel,handleCompactModeSelect:g.handleCompactModeSelect,handleCompactModeCancel:g.handleCompactModeCancel,handleAuthSuccess:g.handleAuthSuccess,handleAuthCancel:g.handleAuthCancel,showDesignGuide:o.showDesignGuide,setShowDesignGuide:o.setShowDesignGuide})}__name(renderView,"renderView");var zI=__name(({resume:e=!1,resumeSessionId:t,continue:n=!1,trust:r=!1,dangerouslySkipPermissions:o=!1,updateStatus:s,updateFailedInfo:i,initialPrompt:a,skipOnboarding:l=!1,initialPermissionMode:u,sessionTitleHolder:d})=>{const{exit:m}=te(),{stdout:g}=X();ae(()=>{prefetchBillingContext()},[]);const[h,f]=se(""),[y,w]=se(""),S=ie(!1),E=ie(!1),v=ie(null),C=ie(null),k=useUiOverlays(),T=useFeed(),_=useSession(),x=useStatus(s),A=useAuth(),P=usePendingOps(),I=useOnboarding(),M=useExit(),{executeBash:N,executionState:R}=AT(),$=usePermissionMode({initialPermissionMode:u,dangerouslySkipPermissions:o,setPendingPermission:P.setPendingPermission,setStatus:x.setStatus,contextEngineRef:C}),{createContextEngineCallbacks:L}=useContextEngine({sessionId:_.sessionId,sessionLoaded:_.sessionLoaded,showSessionSelector:k.showSessionSelector,projectTrusted:I.projectTrusted,setFeed:T.setFeed,setLiveEntries:T.setLiveEntries,setQueuedMessages:T.setQueuedMessages,queuedMessagesRef:T.queuedMessagesRef,setStatus:x.setStatus,pinnedStatusRef:x.pinnedStatusRef,setRetryAttempt:x.setRetryAttempt,setInteractionTokens:x.setInteractionTokens,setContextUsage:x.setContextUsage,setCurrentProvider:A.setCurrentProvider,shareInfoRef:x.shareInfoRef,permissionsService:$.permissionsService,permissionModeRef:$.permissionModeRef,setPendingQuestion:P.setPendingQuestion,contextEngineRef:C}),{onCommand:D}=useCommandCtx({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:M,permissionState:$,contextEngineRef:C,isSubmittingRef:S,executeBash:N,createContextEngineCallbacks:L,setInput:f}),{loadTasteStatus:O,loadCurrentProvider:F,onSubmit:U}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:a,stdout:g,feedState:T,sessionState:_,statusState:x,authState:A,onboarding:I,uiOverlays:k,permissionState:$,contextEngineRef:C,isSubmittingRef:S,initialPromptSubmittedRef:E,historyManagerRef:v,executeBash:N,createContextEngineCallbacks:L,setInput:f,onCommand:D});useLifecycle({exit:m,feedState:T,exitState:M,statusState:x,authState:A,onboarding:I,uiOverlays:k,skipOnboarding:l,contextEngineRef:C,sessionTitleHolder:d});const{handleToggleAutoAccept:j,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:q,handleTrust:z,handleNoTrust:W}=useHandlers({resume:e,feedState:T,onboarding:I,uiOverlays:k,exitState:M,pendingOps:P,permissionState:$,statusState:x,authState:A,contextEngineRef:C,loadTasteStatus:O,loadCurrentProvider:F,setInput:__name(e=>f(e),"setInput")}),H=useMainActionCallbacks({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,permissionState:$,contextEngineRef:C,createContextEngineCallbacks:L,setInput:f}),{creditWarning:G}=useCreditWarning({interactionTokens:x.interactionTokens});return renderView({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:M,pendingOps:P,permissionState:$,contextEngineRef:C,historyManagerRef:v,executionState:R,actionCallbacks:H,onSubmit:U,onCommand:D,input:h,setInput:f,fileSearchQuery:y,setFileSearchQuery:w,updateFailedInfo:i,creditWarning:G,handleTrust:z,handleNoTrust:W,handleToggleAutoAccept:j,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:q,loadTasteStatus:O})},"InteractiveCLI");Zr(),ob(),lr(),jr();var WI=__name(e=>e.replace(/\x1B\[[0-9;]*[A-Za-z]/g,"").replace(/[\x00-\x1F\x7F]/g," ").trim(),"sanitizeTitleForOutput"),HI=ue.hex(gr.DIM),GI=__name(e=>{const t=getInvokedCommandName(),n=rt([e]);return`${HI("To continue this session, run:")}\n${HI(`${t} --resume ${n}`)}\n`},"formatResumeHint"),VI=__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"),QI=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),KI=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),YI=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{let r;return e.permissionMode?r=e.permissionMode:e.plan&&(r="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:r,sessionTitleHolder:n}},"buildInteractiveCLIProps"),JI=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),XI=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),ZI=__name(()=>{XI()},"initializeTerminal"),eM=__name(async(e={})=>{const t=VI(process.stdin.isTTY);let n;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),ZI(),"string"==typeof e.resume){const t=e.resume;await Hk.isProjectInitialized()||(console.error("Project not initialized. Run cmd to start a conversation first."),process.exit(1));const r=await Hk.findSessionByName(t);r||(console.error(`No session named "${t}" found.`),process.exit(1)),n=r.id}if(QI(e)&&!n){const e=await Hk.isProjectInitialized(),t=e?await Hk.listSessions():[],n=KI({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const r={},o=YI({options:e,resumeSessionId:n,sessionTitleHolder:r}),s=JI(),i=ee(re.createElement(zI,{...o}),s);registerInkControl({clear:i.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await i.waitUntilExit();const a=await(r.loadTitle?.());if(a){const e=WI(a);e&&process.stdout.write(GI(e))}},"interactiveMode");jo(),Ut(),kn(),zE(),AE();var tM=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.error(`${Me.cross} Authentication failed. Please try again with: cmd login`),!1)}catch(e){return isUserCancellation(e)||(console.error(`${Me.cross} Login failed: ${getErrorMessage2(e)}`),console.error("Please try again with: cmd login")),!1}},"attemptLogin");async function ensureAuthenticated(){try{return!!await getAuthKey()||tM()}catch(e){return console.error("Error checking authentication:",e),!1}}__name(ensureAuthenticated,"ensureAuthenticated"),co(),Ut(),kn(),io();var nM={bold:__name((e,t)=>t?`${e}`:e,"bold"),dim:__name((e,t)=>t?`${e}`:e,"dim"),green:__name((e,t)=>t?`${e}`:e,"green")};function modelNameOf(e){const t=e.lastIndexOf("/");return(-1===t?e:e.slice(t+1)).toLowerCase()}function displayModelId(e){return e.replace(Jr,"")}function resolveModelFlag({model:e}){const t=resolveKnownModelId(e);if(t)return t;const n=modelNameOf(e),r=getAllModelOptions().filter(e=>modelNameOf(e.id)===n);return 1===r.length?r[0].id:void 0}function editDistance(e,t){const n=e.length+1,r=t.length+1;let o=Array.from({length:r},(e,t)=>t);for(let s=1;s<n;s++){const n=[s];for(let i=1;i<r;i++){const r=e[s-1]===t[i-1]?0:1;n[i]=Math.min(o[i]+1,n[i-1]+1,o[i-1]+r)}o=n}return o[r-1]}function suggestModel(e){const t=e.trim().toLowerCase();if(!t)return;let n;for(const e of getAllModelOptions()){const r=displayModelId(e.id),o=Math.min(editDistance(t,r.toLowerCase()),editDistance(t,modelNameOf(r)));(!n||o<n.distance)&&(n={id:r,distance:o})}if(!n)return;const r=Math.min(4,Math.ceil(t.length/3));return n.distance<=r?n.id:void 0}function formatModelList(e={}){const t=e.color??!1,n=getModelGroupsInOrder(),r=n.flatMap(e=>e.models),o=Math.max(...r.map(e=>displayModelId(e.id).length)),s=n.map(e=>{const n=e.models.map(e=>{const n=displayModelId(e.id).padEnd(o),r=nM.dim(e.description,t);return`${n} ${"free"===e.badge?`${nM.green("FREE",t)} `:""}${r}${e.id===gn?` ${nM.green("(default)",t)}`:""}`});return[nM.bold(e.label,t),"",...n].join("\n")});return[`${nM.bold("Available models",t)} ${nM.dim(`· ${r.length} models`,t)}`,"",s.join("\n\n"),"",nM.dim('Pass the full id, or just the short name after the last "/":',t),"cmd --model moonshotai/Kimi-K2.5","cmd --model kimi-k2.5","","Docs: https://commandcode.ai/docs/reference/cli/models"].join("\n")}function printModelList(){const e=Boolean(process.stdout.isTTY)&&void 0===process.env.NO_COLOR;process.stdout.write(`${formatModelList({color:e})}\n`)}function resolveModelFlagOrExit({model:e}){const t=resolveModelFlag({model:e});if(t)return t;const n=suggestModel(e),r=n?` Did you mean "${n}"?`:"";process.stderr.write(`Error: unknown model "${e}".${r}\nRun "cmd --list-models" to see all available models\n`),process.exit(1)}__name(modelNameOf,"modelNameOf"),__name(displayModelId,"displayModelId"),__name(resolveModelFlag,"resolveModelFlag"),__name(editDistance,"editDistance"),__name(suggestModel,"suggestModel"),__name(formatModelList,"formatModelList"),__name(printModelList,"printModelList"),__name(resolveModelFlagOrExit,"resolveModelFlagOrExit");var rM=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),oM=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth"),sM=__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"),iM=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>{const r=e.resume??e.sessions;return r?{resume:r,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n}},"getInteractiveConfig"),aM=__name((e,t)=>"string"==typeof e.print&&e.print.trim()?e.print:t&&!t.startsWith("-")?t:"","extractPrintQuery");async function interactiveModeAction(e,t){if(t.listModels)return void printModelList();if(t.addDir&&t.addDir.length>0)for(const e of t.addDir)addDirectory(e);const n=t.model?resolveModelFlagOrExit({model:t.model}):void 0;if(void 0!==t.print){const r=aM(t,e);return void await printMode({query:r,dangerouslySkipPermissions:t.dangerouslySkipPermissions,maxTurns:t.maxTurns,verbose:t.verbose,model:n,benchmarkOutput:t.benchmarkOutput})}n&&setModelOverride(n);const r=rM(e);await oM();const o=sM(t),s=iM({options:t,runtimeOptions:o,initialPrompt:r});await eM(s)}__name(interactiveModeAction,"interactiveModeAction"),Ut(),rr(),Ps(),co(),_E(),zE();var lM=new Set(["update"]),cM=__name(()=>process.argv.slice(2).find(e=>!e.startsWith("-")),"getInvokedCommand");globalThis.COMMAND_CODE_CWD=process.cwd();var uM=__name(()=>process.cwd(),"getCwd"),dM=__name(()=>process.argv.slice(2),"getArgs"),mM=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),pM=__name(()=>{const e=uM(),t=dM(),n=mM(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){if(pM(),process.argv.includes("--ide-setup")){const e=await runIDESetup();formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}const e=lM.has(cM()??"");e||(notifyCompletedUpdate(),maybeRunPendingUpdate()),await migrateDeprecatedModel(),await getAuthKey()&&detectAndTrackFirstInstall().catch(()=>{}),e||checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100).unref()}__name(preRun,"preRun"),Ut(),kn(),rr(),$o(),ob(),bo();var gM=getPackageJson(),hM=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=gM.version,t=getInvokedCommandName(),n=Rk.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(ue.bold("Command Code")+ue.gray(` v${e}`)),console.log(ue.gray(Ak)),console.log(),console.log(ue.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ue.bold("Options"));for(const e of Nk){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Pk)+ue.gray(e.description))}console.log(),console.log(ue.bold("Commands"));for(const e of $k){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Pk)+ue.gray(e.description))}console.log(),console.log(ue.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Pk)+ue.gray(e.description));console.log(),console.log(ue.bold("Keyboard Shortcuts"));for(const e of Mk)console.log(" "+e.key.padEnd(Pk)+ue.gray(e.description));console.log(),console.log(ue.bold("Examples"));for(const e of Dk){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Pk)+ue.gray(e.description))}console.log(),console.log(ue.cyan("❯")+" "+ue.gray(Ok.replace(/cmd/,t))),console.log(),console.log(ue.bold("Links"));for(const e of Lk)console.log(" "+e.key.padEnd(Pk)+ue.cyan(e.description));console.log()}function createProgram(){const e=new Ne;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(gM.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("--sessions [name]","Alias of --resume — 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 Re("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Re("--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 Re("--auto-accept","Start in auto-accept mode").implies({permissionMode:"auto-accept"})).addOption(new Re("--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",Ik).option("--add-dir <directory>","Add directory to workspace context",hM,[]).option("-m, --model <model>","Run on a specific model this session (e.g. claude-sonnet-4-6, kimi-k2.5). Unknown ids are rejected; see --list-models.").option("--list-models","List the models available for use").addOption(new Re("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Re("--experimental","Enable experimental features").hideHelp()).addOption(new Re(Bt).hideHelp()).addOption(new Re(qt).hideHelp()).addOption(new Re("-d, --debug","Enable debug mode").hideHelp()).addOption(new Re("--local","Use local server").hideHelp()).addOption(new Re("--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 o=t.opts(),s=Object.entries(o).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");s&&dlog(`[cmd] options: ${s}`);const i=t.args;i.length>0&&dlog(`[cmd] arguments: ${i.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}function isTTY(){return Boolean(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.CI)}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Ut(),Ps(),Ko(),sE(),VE(),wE(),$o(),zE(),Ut(),__name(isTTY,"isTTY");var fM=!1;function setupTelemetry(){initTelemetry()&&(startSession(),registerStartupTask(trackSystemInfo()),trackCliSessionExistsEvent(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=w.platform(),t=w.arch();let n,r,o,s;try{const e=await getAuthenticatedEntity();e.success&&(n=e.user?.userName,r=e.user?.id,o=e.org?.login,s=e.org?.id)}catch{}if(!r)try{const e=await loadCredentials();r=e?.userId}catch{}systemInfo({userName:n,userId:r,orgLogin:o,orgId:s,platform:e,arch:t})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){fM||(fM=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function trackCliSessionExistsEvent(){try{if(!await getAuthKey())return;const e=getSessionId();if(!e)return;const t=getPackageJson().version||"unknown",n=w.platform(),r=w.arch(),o=isTTY()?"interactive":"non-interactive";await trackLifecycleEvent({eventType:"cli_session_exists",metadata:{sessionId:e,cliVersion:t,mode:o,os:`${n}-${r}`}})}catch{}}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=$e("Opening GitHub issues...").start();try{await he(t,{wait:!1,background:!0}),n.succeed(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`),console.log("")}catch(e){n.fail("Failed to open browser"),console.log(""),console.log(createOSC8Link(t,"Open GitHub issue manually")),console.log("")}}__name(setupTelemetry,"setupTelemetry"),__name(trackSystemInfo,"trackSystemInfo"),__name(registerCleanupHandlers,"registerCleanupHandlers"),__name(handleShutdownSignal,"handleShutdownSignal"),__name(trackCliSessionExistsEvent,"trackCliSessionExistsEvent"),zE(),Ut(),yo(),__name(openGitHubIssue,"openGitHubIssue");var yM=new Ne("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Ut();var wM=new Ne("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const t=getSystemInfo(),{waitUntilExit:n}=ee(re.createElement(H_,{verbose:e.verbose,text:e.text,systemInfo:t}));await n()}Ut(),Ut(),__name(runInfo,"runInfo");var SM=new Ne("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}=ee(re.createElement(UI,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onErrorDismiss:__name(()=>{e(),process.exit(1)},"onErrorDismiss")}))}Ut(),kn(),Ut(),__name(runLearnTaste,"runLearnTaste"),rr(),Ps();var bM=new Ne(on.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:vs.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 Ne("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 Re("-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 o=getInvokedCommandName();try{let s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ue.red(`Error: Invalid server name '${e}'`)),console.error(ue.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(ue.red(`Error: Invalid transport type '${n.transport}'`)),console.error(ue.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(ue.red("Error: URL is required for http transport")),console.error(ue.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(ue.red(`Error: Invalid URL '${t}'`)),process.exit(1)}s={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(ue.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(ue.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(ue.cyan("Server requires OAuth authentication.")),isSecureOrLoopback(t)||(console.error(ue.red(`Error: Server '${e}' requires OAuth, but URL '${t}' is not secure.`)),console.error(ue.gray("OAuth requires https:// (http:// is only allowed for loopback hosts: localhost, 127.0.0.1, [::1]).")),console.error(ue.gray("Switch the URL to https:// or use a non-OAuth server.")),process.exit(1));let n,o="command-code";if(r.metadata.registrationEndpoint){console.log(ue.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${nb}/callback`]});e&&(o=e.clientId,n=e.clientSecret)}s.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},console.log(ue.gray("A browser window will open for authentication.\n"));const a=await performOAuthFlow(e,t,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus")});a.success?console.log(ue.green("✓ Successfully authenticated")):(i=!0,console.log(ue.yellow(`Warning: Authentication failed: ${a.error}`)),console.log(ue.gray("You can retry with: cmd mcp auth "+e)),console.log(ue.gray("Or authenticate via the /mcp menu in a session")))}}else{const o=r.args,i=process.argv.indexOf("--");let a,l=[];if(-1!==i){const e=process.argv.slice(i+1);0===e.length&&(console.error(ue.red("Error: Command is required for stdio transport")),console.error(ue.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=o.indexOf(e);-1!==n&&o.length>n+2&&(l=o.slice(n+2))}else console.error(ue.red("Error: Command is required for stdio transport")),console.error(ue.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(ue.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);looksLikeHttpUrl2(a)&&(console.error(ue.red(`Error: '${a}' looks like a URL, not a local command.`)),console.error(ue.gray(`Did you mean: cmd mcp add --transport http ${e} ${a}`)),process.exit(1)),s={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:s,scope:n.scope});const a="user"===n.scope?"global":"project"===n.scope?"project":"local";if(i?console.log(ue.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(ue.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===s.transport)console.log(ue.gray(` URL: ${s.url}`));else{const e=[s.command,...s.args||[]].join(" ");console.log(ue.gray(` Command: ${e}`))}console.log(""),console.log(ue.cyan("Next steps:")),console.log(ue.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function looksLikeHttpUrl2(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function collectKeyValue(e,t){const[n,...r]=e.split("=");return n&&0!==r.length||(console.error(ue.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(ue.red(`Error: Invalid header format '${e}', expected 'Header: value'`)),process.exit(1));const r=e.substring(0,n).trim(),o=e.substring(n+1).trim();return r||(console.error(ue.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=o,t}function listMcpCommand(){const e=new Ne("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(ue.yellow("\nNo MCP servers configured\n")),console.log(ue.gray("Add a server with:")),console.log(ue.gray(" cmd mcp add --transport http <name> <url>")),console.log(ue.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(ue.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ue.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ue.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.config.enabled?ue.green("enabled"):ue.gray("disabled");let s;s=o.config.oauth?await hasTokens(o.name)?ue.green(Me.tick):ue.red(Me.cross):o.config.headers||o.config.env?ue.green(Me.tick):ue.gray("-"),console.log(` ${ue.white(o.name.padEnd(t))} ${ue.cyan(o.config.transport.padEnd(n))} ${ue.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(ue.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new Ne("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(ue.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(ue.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ue.dim("Scope:")} ${r}`),console.log(` ${ue.dim("Transport:")} ${n.transport}`),console.log(` ${ue.dim("Status:")} ${n.enabled?ue.green("enabled"):ue.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ue.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${ue.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(` ${ue.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ue.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${ue.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(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new Ne("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Re("-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(ue.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(ue.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(ue.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const o="user"===r?"global":"project"===r?"project":"local";console.log(ue.green(`✓ Removed MCP server '${e}' from ${o} config`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new Ne("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 Re("-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 o,s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ue.red(`Error: Invalid server name '${e}'`)),console.error(ue.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1));try{o=JSON.parse(t)}catch{console.error(ue.red("Error: Invalid JSON")),console.error(ue.gray("Make sure to quote the JSON string properly")),console.error(ue.gray(`Example: ${r} mcp add-json github '{"type":"stdio","command":"npx"}'`)),process.exit(1)}o?.oauth?.callbackPort&&(s=o.oauth.callbackPort,delete o.oauth.callbackPort),n.clientSecret&&o?.oauth&&(o.oauth.clientSecret=n.clientSecret);const i=WS.safeParse(o);if(!i.success){console.error(ue.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(ue.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(ue.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(ue.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(ue.cyan("Starting OAuth authentication...")),console.log(ue.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,a.url??"",t,{...s&&{port:s},onStatus:__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus")});n.success?console.log(ue.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(ue.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(ue.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ue.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(ue.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(ue.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(ue.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(ue.gray(` Command: ${e}`))}console.log(""),console.log(ue.cyan("Next steps:")),console.log(ue.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new Ne("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(ue.yellow("No servers with stored authentication."));console.log(ue.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?ue.yellow("expired"):ue.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(ue.red("Error: Server name is required")),console.error(ue.gray(`Usage: ${n} mcp auth <server>`)),console.error(ue.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(ue.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(ue.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(ue.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(ue.gray(" A refresh token is available for re-authentication"));else{if(console.log(ue.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(ue.gray(` Expires in ${e} minutes`))}t.scope&&console.log(ue.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(ue.green(`✓ Cleared authentication for '${e}'`)):console.log(ue.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(ue.red(`Error: MCP server '${e}' not found`)),console.error(ue.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),console.log(ue.cyan(`Authenticating with '${e}'...`)),console.log(ue.gray("A browser window will open for authentication.\n"));const o=__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus");let s;if(r.config.oauth){const t={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};s=await performOAuthFlow(e,r.config.url??"",t,{onStatus:o})}else"http"===r.config.transport&&r.config.url||(console.error(ue.red("Error: Discovery-based auth requires an http server with a url")),process.exit(1)),s=await discoverAndAuthenticate({serverName:e,serverUrl:r.config.url,onStatus:o});if(s.success)return console.log(ue.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(ue.gray("Restart the session to connect with the authenticated server."));console.error(ue.red(`\nError: Authentication failed: ${s.error}`)),console.log(ue.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new Ne("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}async function runCommand(e){return new Promise((t,n)=>{const r=Ce(e.cmd,e.args,{stdio:["ignore","pipe","pipe"],env:process.env});let o="",s="";r.stdout.on("data",e=>{o+=String(e)}),r.stderr.on("data",e=>{s+=String(e)}),r.on("error",n),r.on("close",r=>{0!==r?n(new Error(`${e.cmd} ${e.args.join(" ")} failed${s?`: ${s.trim()}`:""}`)):t({stdout:o,stderr:s})})})}async function detectDefaultBranch(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"symbolic-ref","refs/remotes/origin/HEAD","--short"]}),n=t.trim().replace(/^origin\//,"");if(n)return n}catch{}for(const t of["main","master"])try{return await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--verify",t]}),t}catch{}try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--abbrev-ref","HEAD"]});return t.trim()}catch{return"main"}}async function findGitRoot4(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.dir,"rev-parse","--show-toplevel"]});return t.trim()}catch{return null}}async function countLearnings(e){try{return(await C.readFile(e,"utf-8")).split("\n").filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:")).length}catch{return 0}}async function resolveSource(t){const n=t.source.trim(),r=e.resolve(n);try{if(!(await C.stat(r)).isDirectory())throw new Error(`Source must be a repository directory: ${n}`);return{type:"local",displayName:r,repoDir:r,repoName:e.basename(r),github:await inferGitHubRepo({repoDir:r})}}catch(e){if(e instanceof Error&&e.message.startsWith("Source must be"))throw e}const o=parseGitHubSource({source:n});if(!o){const e=n.startsWith("git@")?" SSH URLs are not supported. Use HTTPS or owner/repo instead.":"";throw new Error(`Unsupported source '${n}'.${e} Use a local path, GitHub HTTPS URL, or owner/repo.`)}const s=String(t.maxCommits??200),i=`https://github.com/${o.owner}/${o.repo}.git`,a=await C.mkdtemp(e.join(w.tmpdir(),"taste-learn-"));try{await runCommand({cmd:"git",args:["clone","--depth",s,"--single-branch",...t.branch?["--branch",t.branch]:[],"--",i,a]})}catch{throw await C.rm(a,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Repository not found: ${o.owner}/${o.repo}. Check the owner and repo name, or verify it's a public repository.`)}return{type:"github",displayName:`${o.owner}/${o.repo}`,repoDir:a,repoName:o.repo,github:o,cleanup:__name(async()=>{await C.rm(a,{recursive:!0,force:!0})},"cleanup")}}function getTastePathForDir(t){return e.join(t.projectRoot,".commandcode","taste")}async function resolveDisplayName(t){if(t.startsWith("/")||t.startsWith(".")){const n=e.resolve(t),r=await findGitRoot4({dir:n});return r?e.basename(r):e.basename(n)}return t}function parseGitHubSource(e){const t=e.source.match(/^([\w.-]+)\/([\w.-]+)$/);if(t)return{owner:t[1],repo:t[2].replace(/\.git$/,"")};try{const t=new URL(e.source);if("github.com"!==t.hostname)return null;const n=t.pathname.split("/").filter(Boolean);return n.length<2?null:{owner:n[0],repo:n[1].replace(/\.git$/,"")}}catch{return null}}async function inferGitHubRepo(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"remote","get-url","origin"]});return parseGitHubSource({source:t.trim()})??void 0}catch{return}}async function feedToLearningAgent(e){const t=await getConfiguredProvider(),n=await getOAuthCredentials({provider:t});if(await isOAuthEnforced()&&!n?.token)throw new Error("Authentication required. Run: cmd login");n?.token&&validateOAuthToken({token:n.token,provider:t});const r=getApiBaseUrl(),o=new rS({baseUrl:r}),s=new HT({request:o,sessionId:crypto.randomUUID(),projectRoot:e.outputDir}),i=[{role:"user",content:e.compiledContext}];await s.checkAndProcess({messages:i})}function logLearnSummary(e){const{summary:t}=e;console.log(ue.cyan("\n ─── Results ───\n")),console.log(` Source: ${t.sourceName}`),console.log(` Signals: ${t.signalCount} extracted`),console.log(` Context: ${t.contextLength} chars compiled`),console.log(` Taste dir: ${t.tasteDir}`),console.log("")}function shouldContinueExtraction(e){return!(e.offset>=e.commitsLength||e.signalCount>=e.signalCap||e.commitsWithDiffs>=50)}async function extractAllSignals(e){e.onProgress?.("Collecting commits");const t=await collectCommits(e);if(0===t.length)return e.onProgress?.("No commits found"),{signals:[],commitCount:0};e.onProgress?.(`Found ${t.length} commits to analyze`);const n=e.maxSignals??50,r=[];let o=0;for(let s=0;shouldContinueExtraction({offset:s,commitsLength:t.length,signalCount:r.length,signalCap:n,commitsWithDiffs:o});s+=10){const i=t.slice(s,s+10);if(0===i.length)break;const a=await runBounded(5,i,async t=>({commit:t,subs:await getSubstitutions(e.repoDir,t.hash)}));for(const{commit:e,subs:t}of a){if(0===t.length)continue;o++;const s=groupCrossFilePatterns(t);for(const t of s.slice(0,5)){if(t.removed.length>200||t.added.length>200)continue;const o=[`Commit: ${e.subject}`];o.push(`File: ${t.file}`),t.context&&o.push(`In: ${t.context}`);const s=buildSnippet(t.codeBefore,t.added,t.codeAfter);if(s&&o.push(s),r.push({text:`${truncate3(t.removed,60)} → ${truncate3(t.added,60)}`,evidence:o,category:inferCategory(t.removed,t.added)}),r.length>=n)break}if(r.length>=n)break}}return e.onProgress?.(`Extracted ${r.length} diff signals from ${o} commits`),{signals:r,commitCount:t.length}}async function collectCommits(e){const t=buildAuthorPattern(e.author,e.authorAliases),n=t?.includes("|")??!1,r=t?[...n?["--extended-regexp"]:[],"--author",t,"--regexp-ignore-case"]:[],o=e.branch?[e.branch]:[],s=e.author?e.maxCommits:3*e.maxCommits,{stdout:i}=await runCommand({cmd:"git",args:["-C",e.repoDir,"log",...o,"--no-merges",...r,"--pretty=format:%H%x1f%aI%x1f%aN%x1f%s%x1e","-n",String(s)]});return i.split("").map(e=>e.trim()).filter(Boolean).map(e=>{const[t="",n="",r="",o=""]=e.split("");return{hash:t.trim(),subject:o.trim(),authorDate:n.trim(),authorName:r.trim()}}).filter(e=>!isDependencyBot(e.authorName,e.subject)).slice(0,e.maxCommits)}async function getSubstitutions(e,t){try{const{stdout:n}=await runCommand({cmd:"git",args:["-C",e,"show","--format=","-U3","--diff-algorithm=histogram","-b","--ignore-blank-lines","-M",t]}),r=[];let o="",s="",i=[],a=[],l=[];const u=2;let d=null;const m=__name(()=>{d&&(r.push({removed:d.removed,added:d.added,file:d.file,context:d.context,codeBefore:d.codeBefore.length>0?d.codeBefore:void 0,codeAfter:d.codeAfter.length>0?d.codeAfter:void 0}),d=null)},"commitPending"),g=__name(()=>{if(i.length>0&&a.length>0){const e=i.join("\n").trim(),t=a.join("\n").trim();e===t||isVersionBump(e,t)||isTrivialChange(e,t)||(m(),d={removed:e,added:t,file:o,context:s||void 0,codeBefore:[...l],codeAfter:[]})}i=[],a=[]},"flush");for(const e of n.split("\n")){if(e.startsWith("diff --git")){g(),m(),o=e.match(/b\/(.+)$/)?.[1]??"",s="",l=[],isNoiseFile(o)&&(o="");continue}if(e.startsWith("@@")){g(),m(),s=e.match(/@@ .+ @@\s*(.+)/)?.[1]?.trim()??"",l=[];continue}if(!o)continue;if(e.startsWith("-")&&!e.startsWith("---")){a.length>0&&g(),i.push(e.slice(1));continue}if(e.startsWith("+")&&!e.startsWith("+++")){a.push(e.slice(1));continue}g();const t=e.startsWith(" ")?e.slice(1):e;if(!t.trim())continue;const n=d;null!==n&&n.codeAfter.length<u&&(n.codeAfter.push(t),n.codeAfter.length>=u&&m()),l.push(t),l.length>u&&l.shift()}return g(),m(),r}catch(e){return process.env.DEBUG&&console.error(`[taste-learn] getSubstitutions failed for ${t}:`,e instanceof Error?e.message:e),[]}}function groupCrossFilePatterns(e){const t=new Map;for(const n of e){const e=`${n.removed.trim()}\0${n.added.trim()}`,r=t.get(e)??[];r.push(n),t.set(e,r)}const n=[];for(const[,e]of t)if(e.length>=2){const t=e.map(e=>e.file).join(", ");n.push({...e[0],file:t,context:`Same change across ${e.length} files`})}else n.push(e[0]);return n}Ut(),Ut(),ob(),__name(addMcpCommand,"addMcpCommand"),__name(looksLikeHttpUrl2,"looksLikeHttpUrl"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Ut(),__name(listMcpCommand,"listMcpCommand"),Ut(),__name(getMcpCommand,"getMcpCommand"),Ut(),__name(removeMcpCommand,"removeMcpCommand"),Ut(),ob(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Ut(),ob(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Ut(),kn(),Ut(),GE(),Ut(),kn(),Ut(),__name(runCommand,"runCommand"),Ut(),__name(detectDefaultBranch,"detectDefaultBranch"),__name(findGitRoot4,"findGitRoot"),__name(countLearnings,"countLearnings"),__name(resolveSource,"resolveSource"),__name(getTastePathForDir,"getTastePathForDir"),__name(resolveDisplayName,"resolveDisplayName"),__name(parseGitHubSource,"parseGitHubSource"),__name(inferGitHubRepo,"inferGitHubRepo"),Ut(),vS(),LS(),co(),Eo(),__name(feedToLearningAgent,"feedToLearningAgent"),__name(logLearnSummary,"logLearnSummary"),Ut(),Ut(),__name(shouldContinueExtraction,"shouldContinueExtraction"),__name(extractAllSignals,"extractAllSignals"),__name(collectCommits,"collectCommits"),__name(getSubstitutions,"getSubstitutions"),__name(groupCrossFilePatterns,"groupCrossFilePatterns");var EM=5,vM=3;function buildSnippet(e,t,n){const r=e??[],o=n??[],s=t.split("\n").map(e=>e.trimEnd());if(0===s.length&&0===r.length&&0===o.length)return;let i,a=0;s.length>vM?(i=s.slice(0,vM-1),a=s.length-i.length):i=s;const l=i.length+(a>0?1:0),u=Math.max(0,EM-l),d=Math.min(r.length,Math.ceil(u/2)),m=Math.min(o.length,u-d),g=[];for(const e of r.slice(-d))g.push(` ${e.trimEnd()}`);for(const e of i)g.push(`→ ${e}`);a>0&&g.push(`→ ... (+${a} more changed ${1===a?"line":"lines"})`);for(const e of o.slice(0,m))g.push(` ${e.trimEnd()}`);return 0!==g.length?`Snippet:\n${g.join("\n")}`:void 0}__name(buildSnippet,"buildSnippet");var CM=[/package-lock\.json$/,/pnpm-lock\.yaml$/,/yarn\.lock$/,/CHANGELOG\.(md|yml|yaml)$/i,/\.versionbot\//,/\.min\.(js|css)$/,/dist\//,/\.map$/];function isNoiseFile(e){return CM.some(t=>t.test(e))}function isTrivialChange(e,t){return e.trim().length<3&&t.trim().length<3}function isVersionBump(e,t){const n=/^"?version"?\s*:\s*"?\d+\.\d+/;return n.test(e.trim())&&n.test(t.trim())}function inferCategory(e,t){const n=`${e} ${t}`.toLowerCase();return/import|require|from\s+['"]/.test(n)?"imports":/function|=>|async|return/.test(n)?"code-style":/class|interface|type\s+/.test(n)?"types":/test|describe|it\(|expect/.test(n)?"testing":/console|log|debug|error/.test(n)?"logging":/try|catch|throw|Error/.test(n)?"error-handling":"code-style"}function buildAuthorPattern(e,t){return t&&t.length>0?t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"):e??void 0}__name(isNoiseFile,"isNoiseFile"),__name(isTrivialChange,"isTrivialChange"),__name(isVersionBump,"isVersionBump"),__name(inferCategory,"inferCategory"),__name(buildAuthorPattern,"buildAuthorPattern");var kM=new Set(["renovate[bot]","renovate","dependabot[bot]","dependabot","greenkeeper[bot]","snyk-bot"]),TM=[/^update .+ digest to /i,/^update .+ action to /i,/^update .+ to v?\d/i,/^update lock file maintenance/i,/^update dependency .+ to /i,/^chore\(deps\)/i,/^bump .+ from .+ to /i,/^lock file maintenance/i];function isDependencyBot(e,t){const n=e.toLowerCase();return!!kM.has(n)||!(!n.includes("[bot]")||!TM.some(e=>e.test(t)))}function truncate3(e,t){const n=e.replace(/\n/g," ").trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}async function runBounded(e,t,n){const r=[];let o=0;const s=__name(async()=>{for(;o<t.length;){const e=o++;r[e]=await n(t[e])}},"next");return await Promise.all(Array.from({length:Math.min(e,t.length)},()=>s())),r}function compileTasteContext(e){const{signals:t,repoName:n,author:r,commitCount:o}=e,s=r?`Target author: ${r}\n`:"",i=[];if(i.push(`# Dynamic Taste Analysis — Code Change Patterns\n\nRepository: ${n}\n${s}Commits analyzed: ${o}\nSignals extracted: ${t.length}\n\nThis analysis was generated by examining actual code changes (diffs, substitutions, refactoring patterns) rather than static file contents. Every signal below comes from real commits.`),t.length>0){const e=["## Correction Diffs — What Wrong→Right Looks Like"];for(const n of t.slice(0,50)){e.push(`\n**${n.text}**`);for(const t of n.evidence)e.push(`- ${t}`)}i.push(e.join("\n"))}const a=r?` for ${r}`:"";return i.push(`## Instructions for Taste Learning\n\nYou are analyzing code change patterns from a real repository${a}. Based on the correction diffs above, generate deeply personal and opinionated coding taste.\n\n**Critical guidelines:**\n\n1. **Be specific, not generic.** Instead of "Use TypeScript", write "Use branded types for IDs and explicit return types on every function. Prefer \`readonly\` arrays and objects by default."\n\n2. **Extract the WHY from patterns.** If you see verbose names being replaced with concise ones, don't just say "use short names" — say "Prefer concise variable names that derive meaning from context rather than encoding type information."\n\n3. **Look for recurring themes.** If multiple substitutions show the same pattern (e.g., nested if→guard clauses), that's a strong taste signal worth capturing.\n\n4. **Make it actionable.** Every taste entry should be specific enough that another developer could follow it and produce code that looks like it belongs in this repository.\n\n5. **Prioritize quality corrections** — these are the purest taste signals (wrong→right pairs with explicit WHY context from commit messages).\n\n6. **Capture anti-patterns too.** If you see code being removed in refactors, note what the developer avoids: "Never nest deeper than 2 levels — flatten with early returns."\n\n7. **Don't repeat generic tool preferences** like "Use pnpm" or "Use TypeScript" unless the substitutions show something specific about HOW they use those tools.\n\n8. **Prioritize opinionated preferences.** The goal is taste that makes someone's code distinctly theirs — not industry best practices.\n\nWrite the taste entries to the taste.md file using the standard format with confidence scores.`),i.join("\n\n")}async function runLearnPipeline(t){const n=__name(()=>({outputDir:"",tasteDir:"",sourceName:t.source,signalCount:0,contextLength:0}),"abortedResult");if(t.needsAuth){BT.addEvent({type:"auth_required",step:"auth",message:"Login to synthesize your taste profile",label:"Signing in"});try{await BT.waitForAuth()}catch{return BT.emitStepStart({step:"complete",label:"Login skipped",message:"Login skipped",learningCount:0,storage:""}),BT.markLearningComplete(),{summary:n()}}}t.isLocalSource||BT.emitStepStart({step:"cloning",label:"Cloning repository",message:`Cloning ${t.source}`});const r=await resolveSource({source:t.source,maxCommits:t.maxCommits});if(t.signal.aborted)return{summary:n(),resolved:r};const o="github"===r.type,s=r.repoName,i=await findGitRoot4({dir:r.repoDir});if(!i)throw new Error(`Not a git repository: ${r.repoDir}. Run inside a git repo or pass the path: npx taste learn /path/to/repo`);const a=o?e.resolve(process.cwd(),s):i;o&&BT.emitStepStart({step:"collecting",label:"Collecting commits",message:`Cloned ${r.displayName} → ${a}`});const l=t.branch??await detectDefaultBranch({repoDir:i});await C.mkdir(a,{recursive:!0}),BT.emitStepStart({step:"collecting",label:"Collecting commits",message:`Fetching up to ${t.maxCommits} commits from ${l}`});const{signals:u,commitCount:d}=await extractAllSignals({repoDir:i,maxCommits:t.maxCommits,maxSignals:t.maxSignals,branch:l,onProgress:__name(e=>{BT.emitProgress({step:"extracting",message:e})},"onProgress")});if(t.signal.aborted)return{summary:n(),resolved:r};if(0===u.length)throw new Error("No signals extracted. Check the repository has commit history.");BT.emitStepStart({step:"extracting",label:"Extracting taste signals",message:`${u.length} before/after code changes extracted`}),BT.emitStepStart({step:"compiling",label:"Compiling taste context",message:`Formatting ${u.length} signals for the learning agent`});const m=compileTasteContext({signals:u,repoName:s,commitCount:d});if(t.signal.aborted)return{summary:n(),resolved:r};BT.emitStepStart({step:"learning",label:"Learning taste",message:"Interpreting code change patterns with AI"}),await feedToLearningAgent({compiledContext:m,outputDir:a});const g=getTastePathForDir({projectRoot:a}),h=e.join(g,"taste.md"),f=await countLearnings(h);return BT.emitStepStart({step:"complete",label:"Taste learned",message:"Taste learned",learningCount:f,storage:h}),BT.markLearningComplete(),{summary:{outputDir:a,tasteDir:g,sourceName:r.displayName,signalCount:u.length,contextLength:m.length},resolved:r}}__name(isDependencyBot,"isDependencyBot"),__name(truncate3,"truncate"),__name(runBounded,"runBounded"),Ut(),__name(compileTasteContext,"compileTasteContext"),__name(runLearnPipeline,"runLearnPipeline"),Ut(),Ut(),Ut();var _M=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return _M.some(t=>t.test(e))}function chunkToString(e){return"string"==typeof e?e:Buffer.isBuffer(e)?e.toString("utf-8"):""}async function withFilteredStderrNoise(e){const t=process.stderr.write.bind(process.stderr);process.stderr.write=(e,...n)=>{const r=chunkToString(e);return!(!r||!shouldIgnoreChunk(r))||("function"==typeof n[0]?t(e,n[0]):t(e,n[0],n[1]))};try{return await e()}finally{process.stderr.write=t}}function toRepoLearnErrorMessage(e){return e instanceof Error?e.message:String(e)}function isRepoLearnMetricLikeText(e){const t=e.trim().toLowerCase();return/^\d+\s/.test(t)||/^saved\s/.test(t)||/^output\s/.test(t)||/^target\s/.test(t)||/\bcandidates\b/.test(t)||/\bevidence records\b/.test(t)||/\bhistory and review signals\b/.test(t)}function truncateRepoLearnPanelText(e,t=12){return truncateString({text:e,maxChars:Math.min(96,getEffectiveWidth({padding:t}))})}__name(shouldIgnoreChunk,"shouldIgnoreChunk"),__name(chunkToString,"chunkToString"),__name(withFilteredStderrNoise,"withFilteredStderrNoise"),Ut(),bs(),__name(toRepoLearnErrorMessage,"toRepoLearnErrorMessage"),__name(isRepoLearnMetricLikeText,"isRepoLearnMetricLikeText"),__name(truncateRepoLearnPanelText,"truncateRepoLearnPanelText"),Ut(),Ut();var xM=[{id:"collecting",label:"Collecting commits from repository"},{id:"extracting",label:"Extracting taste signals from diffs"},{id:"compiling",label:"Compiling taste context"},{id:"learning",label:"Learning taste from change patterns"},{id:"complete",label:"Taste learned"}],AM=[{id:"cloning",label:"Cloning repository"},...xM],PM=[Me.bullet,Me.squareSmallFilled,Me.lozenge,Me.star,Me.triangleRight,Me.triangleUp];function createInitialRepoLearnSteps(e){return(e??xM).map(e=>({...e,status:"pending"}))}__name(createInitialRepoLearnSteps,"createInitialRepoLearnSteps"),Ut();var IM={learningCount:0,storage:"",topLearnings:[]};function getStepStatus(e,t){return e<t?"complete":e===t?"active":"pending"}function deriveStepStates(e,t){return e.map((e,n)=>({...e,status:getStepStatus(n,t)}))}function parseSummaryMetric(e){if(e.startsWith("Maintainer: "))return{maintainerLabel:e.replace(/^Maintainer:\s+/,"")};const t=e.match(/^(\d+)\s+maintainer-specific preferences$/);if(t)return{maintainerCount:Number(t[1])};const n=e.match(/^(\d+)\s+repository conventions$/);return n?{repoCount:Number(n[1])}:null}__name(getStepStatus,"getStepStatus"),__name(deriveStepStates,"deriveStepStates"),__name(parseSummaryMetric,"parseSummaryMetric");var MM=__name(e=>e.map(e=>({...e,status:"complete"})),"markAllStepsComplete"),NM=__name(e=>e??IM,"withBase");function useRepoLearnState(e){const t=e??xM,[n,r]=se(()=>createInitialRepoLearnSteps(t)),[o,s]=se(""),[i,a]=se([]),[l,u]=se(null),[d,m]=se(!1),[g,h]=se(!1),[f,y]=se(null),[w,S]=se(0),E=ie(null),[v,C]=se(null),k=ce(()=>{E.current=Date.now()},[]);return ae(()=>{const e=__name(()=>{r(createInitialRepoLearnSteps(t)),s(""),a([]),u(null),h(!1),y(null),S(0),E.current=null,C(null),m(!1)},"handleReset"),n=__name(e=>{if("error"===e.type)return y(e.message),h(!0),r(MM),void s("");if("auth_required"!==e.type){if("step_start"===e.type&&e.step){const n=t.findIndex(t=>t.id===e.step);return n>=0&&r(deriveStepStates(t,n)),s(e.message||e.label||""),void("complete"===e.step&&u(t=>{const n=NM(t);return{...n,learningCount:e.learningCount??n.learningCount,storage:e.storage??n.storage}}))}"progress"!==e.type||"complete"!==e.step?"progress"!==e.type?"insight"===e.type&&(isRepoLearnMetricLikeText(e.message)||("complete"!==e.step?(S(e=>e+1),a(t=>[...t,e.message].slice(-4))):u(t=>{const n=NM(t);return{...n,topLearnings:[...n.topLearnings,e.message].slice(0,3)}}))):s(e.message):u(t=>{const n=NM(t),r=parseSummaryMetric(e.message);return r?{...n,...r}:n})}else m(!0)},"handleEvent"),o=__name(()=>{h(e=>e||(r(MM),!0)),s(""),E.current&&C(Math.round((Date.now()-E.current)/1e3))},"handleComplete");return BT.on("reset",e),BT.on("new-event",n),BT.on("learning-complete",o),()=>{BT.off("reset",e),BT.off("new-event",n),BT.off("learning-complete",o)}},[t]),{steps:n,currentMessage:o,insights:i,insightCount:w,summary:l,done:g,error:f,showLogin:d,setShowLogin:m,elapsedSeconds:v,markStarted:k}}__name(useRepoLearnState,"useRepoLearnState"),Ut(),Ut(),jr();var RM=__name(({isComplete:e,hasError:t})=>re.createElement(K,{flexDirection:"column",marginTop:1,marginBottom:0},re.createElement(kI,null),re.createElement(K,{marginTop:0},re.createElement(Y,{color:gr.DIM},_I),re.createElement(K,{marginLeft:2},t?re.createElement(Y,{color:gr.DIM},"learning interrupted"):e?re.createElement(Y,{color:fr.TEXT},"learned your coding taste"):re.createElement(xI,null)))),"RepoLearnTastePill");Ut(),jr();var $M=__name(({status:e})=>"active"===e?re.createElement(K,null,re.createElement(Y,{color:gr.YELLOW},re.createElement(ze,{type:"dots"})),re.createElement(Y,null," ")):"complete"===e?re.createElement(Y,{color:br.BG},Me.square," "):re.createElement(Y,{color:gr.DIM},Me.circle," "),"StepStatusIndicator"),LM=__name(({steps:e,currentMessage:t})=>re.createElement(K,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return re.createElement(K,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},re.createElement(K,null,re.createElement(K,{marginRight:1},re.createElement($M,{status:e.status})),re.createElement(Y,{bold:n,color:"complete"===e.status?gr.WHITE:n?gr.YELLOW:gr.DIM},e.label)),n&&t?re.createElement(K,{marginLeft:3},re.createElement(Y,{color:gr.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Ut(),jr();var DM=__name(({insights:e,insightCount:t})=>0===e.length?null:re.createElement(K,{flexDirection:"column",marginTop:1,marginLeft:4},re.createElement(Y,{color:gr.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>re.createElement(Y,{key:`${t}-${e}`,color:gr.DIM},PM[t%PM.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Ut(),jr();var OM=__name(({message:e})=>re.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:gr.RED,paddingX:2,paddingY:1,marginTop:1},re.createElement(Y,{color:gr.RED,bold:!0},"Oops, something went wrong:"),re.createElement(K,{marginTop:1},re.createElement(Y,null,e))),"RepoLearnErrorPanel");Ut(),jr(),uo();var FM=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return re.createElement(K,{flexDirection:"column",marginLeft:3},re.createElement(K,{marginBottom:1,flexDirection:"row"},re.createElement(Y,{color:gr.DIM},_I),re.createElement(K,{marginLeft:2},re.createElement(Y,{color:fr.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),re.createElement(K,{flexDirection:"column",marginLeft:1},re.createElement(K,null,re.createElement(Y,{color:gr.DIM},Me.pointerSmall," Taste stored in"," "),re.createElement(ao,{url:`file://${e.storage}`,text:r||".commandcode/taste/taste.md",color:gr.CYAN})),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},Me.pointerSmall," Share your coding taste:"," ",re.createElement(Y,{color:gr.CYAN},"npx taste push --all")))),re.createElement(K,{marginTop:1,marginLeft:1},re.createElement(Y,{color:gr.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Ut(),jr();var UM=__name(({done:e,error:t})=>t?re.createElement(K,{marginTop:1},re.createElement(Y,{bold:!0},"Press ESC to exit")):e?re.createElement(K,{marginTop:1},re.createElement(Y,{bold:!0},"Press ENTER to continue")):re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"ESC to cancel")),"RepoLearnFooter");Ut(),jr();var jM=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=le(()=>pA(n),[n]);return re.createElement(K,{flexDirection:"column"},re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(SA,null,r.trimEnd())),e?re.createElement(Y,{color:gr.WHITE},e):re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.WHITE},"Learning your coding taste from"," ",re.createElement(Y,{bold:!0,color:gr.CYAN},t??"repository")),re.createElement(Y,{color:gr.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:o,insightCount:s}){return e?re.createElement(OM,{message:e}):t?re.createElement(FM,{summary:n,elapsedSeconds:r}):re.createElement(DM,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),i=ie(!1);return ae(()=>{i.current||(i.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),Z((e,n)=>{if(s.showLogin)return;const r=n.escape||""===e,o=n.return||"\n"===e||"\r"===e;r?t({published:!1,cancelled:!0}):(s.done||s.error)&&o&&t({published:!1,cancelled:!!s.error})}),s.showLogin?re.createElement(K,{flexDirection:"column"},re.createElement(jM,{text:r,repoName:o}),re.createElement(WP,{onComplete:(e,t)=>{s.setShowLogin(!1),e?BT.resolveAuth():BT.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),BT.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):re.createElement(K,{flexDirection:"column"},re.createElement(jM,{text:r,repoName:o}),re.createElement(RM,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),re.createElement(LM,{steps:s.steps,currentMessage:s.currentMessage}),re.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),re.createElement(UM,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{BT.reset();const r=new AbortController;let o,s,i=!1,a=!1;const l=__name(async()=>{try{o=await e.runTask(r.signal)}catch(e){r.signal.aborted||(s=e,BT.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),BT.markLearningComplete())}},"handleRunTask"),u=__name(({published:e,cancelled:l})=>{a||(a=!0,i=e,r.abort(),d.unmount(),BT.reset(),s?n(s):t({result:o,published:i,cancelled:l}))},"handleExit"),d=ee(re.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:u}));d.waitUntilExit().catch(e=>{BT.reset(),n(e)})})}__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),zE();var BM=__name(e=>t=>{const n=parseInt(t,10);if(isNaN(n)||n<1)throw new Error(`${e} must be a positive integer`);return n},"parsePositiveInt");function createLearnCommand(){return new Ne("learn").description("Learn coding taste from repository change history").argument("[source]","Local path, GitHub URL, or owner/repo (defaults to current directory)").option("--max-commits <number>","Maximum commits to analyze",BM("--max-commits"),200).addOption(new Re("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(BM("--max-signals")).hideHelp()).option("--branch <name>","Branch to analyze (defaults to main/master)").action(async(e,t)=>{try{await learnTaste({source:e??".",maxCommits:t.maxCommits??200,maxSignals:t.maxSignals??50,branch:t.branch})}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`Error: ${t}`),process.exit(1)}})}async function learnTaste(t){const n=await C.stat(e.resolve(t.source)).then(e=>e.isDirectory()).catch(()=>!1),r=isTTY(),o=await resolveDisplayName(t.source),s=!await getAuthKey();if(s&&!r)return console.log(""),console.log(" Login required to learn taste."),console.log(""),console.log(" Run: cmd login"),console.log(` Then: npx taste learn ${t.source}`),void console.log("");let i;const a=__name(()=>{i?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",a);let l=!1;try{const e=__name(async e=>{const{summary:r,resolved:o}=await runLearnPipeline({...t,isLocalSource:n,needsAuth:s,signal:e});return i=o?.cleanup,r},"runTask");if(r){const t=n?void 0:[...AM];({cancelled:l}=await runRepoLearnProgress({runTask:e,repoName:o,stepOrder:t}))}else logLearnSummary({summary:await e((new AbortController).signal)})}finally{process.off("SIGINT",a),i&&await i()}r&&!l||process.exit(0),WE(),await eM({skipOnboarding:!0})}function getTastePath(t){const{target:n}=t;if("local-project"===n)return e.join(process.cwd(),".commandcode","taste");if("local-global"===n)return e.join(w.homedir(),".commandcode","taste");throw new Error(`Remote storage not yet implemented: ${n}`)}function getRootTasteFile(t){const{target:n}=t;return e.join(getTastePath({target:n}),"taste.md")}function getCategoryPath(t){const{target:n,category:r}=t;return e.join(getTastePath({target:n}),r)}function getCategoryTasteFile(t){const{target:n,category:r}=t;return e.join(getCategoryPath({target:n,category:r}),"taste.md")}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Ut(),Ut(),Ut(),kn(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Ut(),Ut();var qM=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||qM.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const o=n[r].trim();return{endIdx:t+r,inclusive:qM.test(o)&&!o.startsWith("#")&&!o.startsWith("-")}}function joinMultiLineLearning(e,t,n){const{endIdx:r,inclusive:o}=findLookaheadEnd(e,t),s=o?r+1:r;return{combined:[n,...e.slice(t,s).map(e=>e.trim()).filter(e=>e.length>0)].join(" "),nextIdx:s}}function processRawLine(e,t){const n=e[t],r=t+1,o=n.trim();if(!o.startsWith("-"))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};if(qM.test(o))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:s,nextIdx:i}=joinMultiLineLearning(e,t+1,n);return{entry:{text:s,originalLineNum:r},nextIdx:i}}function preprocessLines(e){const t=[];let n=0;for(;n<e.length;){const{entry:r,nextIdx:o}=processRawLine(e,n);t.push(r),n=o}return t}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],o=t.substring(1).trim();if(!qM.test(o))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 s=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),i=s.length>0?s[s.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?o.substring(0,i.index).trim():o.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),o=r.findIndex(e=>e.trim().startsWith("# "));return(-1===o?r:r.slice(0,o)).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),o=t.filter(e=>"warning"===e.severity),s=0===r.length;if(0===t.length)return{valid:s,issues:[...t],summary:`${Me.tick} ${n} is valid`};const i=[];r.length>0&&i.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&i.push(`${o.length} warning${o.length>1?"s":""}`);const a=r.length>0?Me.cross:Me.warning;return{valid:s,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?ue.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ue.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`${ue.green(e)} ${ue.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?ue.red(t.summary):ue.yellow(t.summary),"",...formatIssueGroup(r,ue.red,ue.bold(ue.red("Errors:"))),...formatIssueGroup(o,ue.yellow,ue.bold(ue.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"),Ut(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var zM=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:o}=e;zM.has(t.trim())||(r.hasAnyCategory=!0,warnIfEmptyCategory(r,o),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 WM=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,HM=/^\[cmd\]: https:\/\/commandcode\.ai\/$/i;function processLine(e){const{line:t,lineNum:n,state:r,rawLines:o}=e,s=t.trim();s&&(s.startsWith("# ")?processHeading({line:t,lineNum:n,state:r,rawLines:o}):s.startsWith("-")?processLearning({line:t,lineNum:n,state:r}):WM.test(s)||HM.test(s)||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 o=t.split("\n"),s=preprocessLines(o),i={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of s)processLine({line:e,lineNum:t,state:i,rawLines:o});return checkFinalCategory({state:i,rawLines:o}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var GM=__name(e=>"local-global"===e?"global":"project","locationLabel"),VM=__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 O(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${GM(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=[],o=getRootTasteFile({target:n});O(o)&&r.push({path:o,displayName:"taste.md"});const s=(await C.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>O(e)).map(({entry:e,categoryFile:t})=>({path:t,displayName:`${e.name}/taste.md`}));return r.push(...s),r}async function lintFile(e){let t=await C.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await C.writeFile(e.path,n,"utf-8"),t=n);const r=validateTasteFile({content:t,filePath:e.displayName}),o=r.issues.filter(e=>"error"===e.severity).length,s=r.issues.filter(e=>"warning"===e.severity).length,i=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:o,warnings:s,formatted:i}}async function lintSpecificPackages(e){const{packages:t,target:n}=e,{files:r,errors:o}=collectSpecificFiles({packages:t,target:n});if(0===r.length&&o.length>0)return{success:!1,filesLinted:[],errors:o,totalErrors:0,totalWarnings:0};if(0===r.length)return VM({file:"all",error:`No taste files found in ${GM(n)}`});const s=await Promise.all(r.map(lintFile)),i=s.reduce((e,t)=>e+t.errors,0),a=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid)&&0===o.length,filesLinted:s,errors:o,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 VM({file:"all",error:`No taste files found in ${GM(n)}`});const o=await Promise.all(r.map(lintFile)),s=o.reduce((e,t)=>e+t.errors,0),i=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid),filesLinted:o,errors:[],totalErrors:s,totalWarnings:i}}async function lint(e){const{packages:t,target:n}=e,r=getTastePath({target:n});return O(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):VM({file:"all",error:`No taste directory found in ${GM(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"),Ut(),Ps(),__name(resolveConflictStrategy,"resolveConflictStrategy");var QM=ue.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(`${ue.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?`${ue.dim(t[1])}${ue.green(t[2])}${ue.white(t[3]??"")}${t[4]?ue.dim(t[4]):""}`:ue.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ue.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 KM=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return Et(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:KM})}function getProfileLink(e){return Et(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:KM})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return bt(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(ue.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(`${ue.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),o=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`:`${o} day${o>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(ue.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new Ne("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 ${ue.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(`${ue.green(Me.tick)} All ${ue.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ue.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ue.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(ue.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}function parseSection(e){const{section:t,sourcePath:n}=e,r=t.split("\n"),o=r[0].trim(),s=r.map(e=>parseLearning({line:e})).filter(e=>null!==e);return 0===s.length?null:{category:normalizeCategory({category:o}),learnings:s,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 C.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await C.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 o=t.findIndex((e,t)=>t>r&&e.startsWith("# "));if(-1===o)return{start:r,end:t.length-1};const s=trimTrailingBlanks({lines:t,from:o-1,until:r});return{start:r,end:s}}function ensureHeader(e){if(!e)return cv+"\n\n";const t=e.trim();return t.startsWith(av)||t.startsWith(uv)||t.startsWith(dv)?e:cv+"\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"),Ut(),Hs(),Ut(),Ut(),Ut(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Ut(),__name(formatPackage,"formatPackage"),Ut(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var YM="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:YM,category:e.name});return O(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await C.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:YM});if(!O(e))return[];const t=await C.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:YM,category:t});return O(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:YM});await C.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:YM,category:n.category}),s=e.dirname(o);await C.mkdir(s,{recursive:!0});const i=formatPackage({pkg:n});await C.writeFile(o,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"),Ut(),Ut();var JM="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!O(n))return null;const r=migrateHeader({content:await C.readFile(n,"utf-8")}).split("\n"),o=findCategoryRange({lines:r,pattern:new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i")});if(!o)return null;const s=r.slice(0,o.start),i=o.end<r.length-1?r.slice(o.end+1):[],a={before:s.join("\n").trim(),after:i.join("\n").trim()},l=[...s,...i].join("\n").trim();return""===l&&await C.rm(n,{force:!0}),""!==l&&await C.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:JM}),o=await removeCategoryFromRoot({category:n,rootFile:r}),s=getCategoryTasteFile({target:JM,category:n}),i=e.dirname(s);return O(i)&&await C.rm(i,{recursive:!0,force:!0}),o}async function writeToRoot(e){const{pkg:t,rootFile:n,categoryPosition:r}=e,o=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+=o.trim()+t,void await C.writeFile(n,e.trim()+"\n","utf-8")}let s="";O(n)&&(s=await C.readFile(n,"utf-8"),s=migrateHeader({content:s})),s=ensureHeader(s),s=ensureTrailingNewlines(s),s+=o,await C.writeFile(n,s.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:JM,category:n.category}),i=e.dirname(s);await C.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await C.writeFile(s,a,"utf-8");const l=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(o){let e=ensureHeader(migrateHeader({content:o.before}));e=ensureTrailingNewlines(e);const t=o.after?"\n\n"+o.after:"";return e+=l.trim()+t,void await C.writeFile(r,e.trim()+"\n","utf-8")}let u="";O(r)&&(u=await C.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await C.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var XM="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:XM,category:e.name});return O(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:XM});if(!O(e))return[];const t=[],n=getRootTasteFile({target:XM});if(O(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await C.readdir(e,{withFileTypes:!0}),o=(await Promise.all(r.map(loadCategoryPackages2))).flat();return t.push(...o),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:XM});await C.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:XM}),o=await removePackage({category:t.category});t.learnings.length<=5?await writeToRoot({pkg:t,rootFile:r,categoryPosition:o}):await writeToSubdirectory({pkg:t,rootFile:r,categoryPosition:o})}function exists2(){const e=getTastePath({target:XM});return O(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!O(n))return;const r=await C.readFile(n,"utf-8"),o=new Blob([r],{type:"text/markdown"}),s=new File([o],"taste.md",{type:"text/markdown"});e.append(`files[${t.category}/taste.md]`,s)}async function prepareUploadFormData(t){const{packageName:n,pkg:r,description:o,type:s="category",isPublic:i=!1,overwrite:a=!1}=t,l=new FormData;l.append("name",n),o&&l.append("description",o),l.append("type",s),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"===s)return l;const g=getTastePath({target:"local-project"}),h=e.join(g,r.category);if(!O(h))return l;const f=getCategoryTasteFile({target:"local-project",category:r.category});if(!O(f))return l;const y=await C.readFile(f,"utf-8"),w=new Blob([y],{type:"text/markdown"}),S=new File([w],"taste.md",{type:"text/markdown"});return l.append(`files[${r.category}/taste.md]`,S),l}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:o=!1,overwrite:s=!1}=e,i=new FormData;i.append("name",n),r&&i.append("description",r),i.append("type","project"),i.append("isPublic",String(o)),i.append("overwrite",String(s));const a=getRootTasteFile({target:"local-project"});if(O(a)){const e=await C.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:o,extra:s}=e,i=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:i,label:n}),context:{component:vs.TASTE_REMOTE_STORAGE,heading:r,"http.status":o,...s}}),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(),o=await tryPublicDownload({baseUrl:r,owner:t,packageName:n});if(o)return o;const s=await getAuthKey();if(!s)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:s})}async function tryPublicDownload(e){const{baseUrl:t,owner:n,packageName:r}=e,o=`${t}${Wt.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",n).replace(":packageName",r)}`;let s;try{s=await fetch(o,{method:"GET"})}catch{return null}if(s.ok){const{data:e}=await s.json();return{type:e.type||"category",files:e.files||[],isPublic:!0}}if(404===s.status)return null;throwTrackedError({message:await parseApiError({response:s,fallback:`Failed to download taste package (${s.status})`}),label:"download_public_error",heading:"Failed to download taste package (public)",status:s.status})}async function tryAuthenticatedDownload(e){const{baseUrl:t,owner:n,packageName:r,apiKey:o}=e,s=`${t}${Wt.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${o}`}});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:vs.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()}${Wt.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(),o=r.packages||[];if(0===o.length)return[];const s=[];for(let e=0;e<o.length;e+=5){const t=o.slice(e,e+5),n=await Promise.all(t.map(fetchSinglePackage));s.push(...n.filter(e=>null!==e))}return s}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:vs.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 o=r.files||[];if(0===o.length)return null;const s=o.find(e=>"taste.md"===e.file);if(!s)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(s.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async function writePackage3(e){const{pkg:t,owner:n,isPublic:r=!1,overwrite:o=!1}=e,s=await requireAuthKey(),i=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r,overwrite:o}),a=`${getApiBaseUrl()}${Wt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${s}`},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:o=!1,overwrite:s=!1}=e,i=await requireAuthKey(),a=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:o,overwrite:s}),l=`${getApiBaseUrl()}${Wt.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()}${Wt.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 C.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 Ne("list").alias("ls").option("-g, --global","List global packages").addOption(new Re("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Re("--staging","Use staging environment").hideHelp()).description(`List available packages ${ue.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"),Ut(),LS(),Ut(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),kn(),Ut(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),VE(),Ps(),Ut(),zE(),Ps(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Ut(),LS(),zE(),kn(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),rr(),__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 ZM={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?ZM.remote:e.global?ZM.global:ZM.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${Me.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${Me.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,o=r?`, updated ${r}`:"";return` ${ue.white(e.category)}${e.isPublic?ue.green(" [public]"):""}${e.isPublic&&e.starCount?ue.yellow(` ${Me.star}${e.starCount}`):""}${e.downloadCount?ue.gray(` ${Me.arrowDown}${e.downloadCount}`):""}${n}${ue.dim.gray(`(${e.learningCount} learnings${o})`)}`}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?$e(`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${QM} Packages`),console.log(`${ue.gray("⎿")} ${ue.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(ue.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(ue.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,o=await C.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const s=o.split("\n").findIndex(e=>e.trim().toLowerCase()===`# ${r.toLowerCase()}`);return s>=0?s+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 o=r.sourcePath,s=await findCategoryLineNumber({filePath:o,category:t});return await St([{file:o,line:s}]),{success:!0,filePath:o,lineNumber:s}}__name(resolveStorage,"resolveStorage"),__name(getPackageDisplayLength,"getPackageDisplayLength"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),Ut(),Ut(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var eN=new Set(["local-project","local-global","remote-project","remote-user"]);async function open11(e){const{package:t,target:n}=e;if(!eN.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=vt.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 Ne("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 ${ue.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 he(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ue.green(Me.tick)} Opened ${n} in browser`)}async function openInEditor3({packageName:e,options:t}){const n=t.global?"local-global":"local-project",r=await open11({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${ue.green(Me.tick)} Opened ${ue.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open11,"open"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor3,"openInEditor"),Ut(),Ut(),Ut(),Ut();var tN=null,nN=!1;function setActiveSpinner(e){tN=e}function stopActiveSpinner(e){tN&&(tN.stop(e),tN=null)}function setPrompted(e){nN=e}function wasPrompted(){return nN}function beginPrompt(e,t){stopActiveSpinner(),We.intro(ue.dim(e)),t&&We.log.message(ue.dim(t)),setPrompted(!0)}function handleCancel(e){We.isCancel(e)&&(We.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=We.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=We.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:o}=e,s="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),We.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ue.green(`'${t}'`)} from ${n}`,s),We.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${o} learnings ${ue.dim(`(from ${n})`)}`);const i=await We.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} → ${o} 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,o="This package already exists in global storage";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),We.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${ue.green(`'${t}'`)} to global`,o),We.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const s=await We.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(s);const i=s;return startStrategySpinner(i),i}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e,o="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),We.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ue.green(`'${t}'`)} from global`,o),We.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const s=await We.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(s);const i=s;return startStrategySpinner(i),i}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`Pushing local project taste to individual package '${t}'`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),We.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=Et(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ue.green(`'${t}'`)} to ${n}`,s),We.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${o} learnings) in ${n}`),We.log.info(`Current package: ${ue.cyan(i)} ${ue.dim("(review)")}`);const a=await We.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:o}=e,s=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),We.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=Et(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ue.green(`'${t}'`)} to ${n}`,s),We.log.message(`Local: ${r} learnings\nRemote: ${o} learnings`),We.log.info(`Current package: ${ue.cyan(i)} ${ue.dim("(review)")}`);const a=await We.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 (${o} → ${r} learnings)`}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}function mergeSingleLearning(e,t,n,r){const o=t.get(e.text);return o?e.confidence>o.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},o=new Map(n.map(e=>[e.text,e])),s=new Map(o);for(const e of t)mergeSingleLearning(e,o,s,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(s.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:o,owner:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r?promptMergeStrategy({packageName:o.category,owner:s,localPkg:r,remoteLearningsCount:o.learnings.length}):"merge"}async function executePackageStrategy(e){const{tastePkg:t,owner:n,overwrite:r,flagStrategy:o,result:s}=e,i=await getPackage2({category:t.category}),a=await resolveRemotePullStrategy({flagStrategy:o,overwrite:r,existingPkg:i,tastePkg:t,owner:n});if("skip"===a)return void s.skipped?.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});s.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:o,flagStrategy:s,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:o,flagStrategy:s,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:o,flagStrategy:s,result:i})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:o,flagStrategy:s,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:o,flagStrategy:s,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"),Ut(),Ut(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Ut(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var rN=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),oN=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),sN=__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:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPullStrategy({packageName:s.category,localPkg:r,globalLearningsCount:s.learnings.length}):"merge"}async function executePullStrategy(e){const{tastePkg:t,source:n,flagStrategy:r,overwrite:o,result:s}=e,i=await getPackage2({category:t.category}),a=await resolvePullStrategy({flagStrategy:r,overwrite:o,existingPkg:i,source:n,tastePkg:t});if("skip"===a)return void s.skipped.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});s.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:o}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return rN({pkg:"all",error:`Invalid source: ${n}`});const s=sN(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return rN({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return rN({pkg:"all",error:`No taste packages found in ${s}`});const a=validatePackages({packages:i,label:s});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 ${s}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=oN();for(const e of l)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:o,overwrite:r,result:u});return u}async function executePullRemote(e){const{owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s}=e,i=await downloadPackage({owner:t,packageName:n});if(!i)return rN({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:o,result:s};return"project"===a?(await pullProjectPackage(d),s):(await pullCategoryPackage(d),s)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:o}=e,s=oN();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s})}catch(e){return rN({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return We.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:o,mergeDetails:s}=e,i=wasPrompted()?"":`${Me.tick} `,a=r?ue.dim(`\n ${shortenPath(r)}`):"";if(o.overwrite)return`${ue.green(i)}Replaced ${ue.green(`'${t}'`)} taste package in project`+a;if(s){const e=formatMergeParts(s);return`${ue.green(i)}Pulled ${ue.green(`'${t}'`)} taste package from ${n} ${ue.gray(`(${e.join(", ")})`)}`+a}return`${ue.green(i)}Pulled ${ue.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 o=t.packagesPulled[0],s=t.filePaths?.[o],i=t.mergeDetails?.[o];return logResult(buildPullMessage({pkgName:o,sourceName:n,filePath:s,options:r,mergeDetails:i})),!r.overwrite&&!!i&&hasMergeConflictRisk(i)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],o=t.skipped??[],s=t.packagesPulled.filter(e=>!r.includes(e)),i=t.packagesPulled.length+o.length,a=`${i} ${1===i?"package":"packages"}`,l=[];return s.length>0&&l.push(wrapLine(`${ue.green("Pulled")} (${s.length}) ${s.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${ue.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),o.length>0&&l.push(wrapLine(`${ue.dim("Skipped")} (${o.length}) ${ue.dim(o.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&We.log.message(l.join("\n")),We.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${ue.green(Me.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,o=t.skipped??[];t.packagesPulled.length+o.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():o.length>0?logResult(ue.yellow(`Skipped '${o[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new Ne("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 Re("--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 Re("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ue.dim("(prompts on conflicts)")}`).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),{result:r,owner:o}=await runPull({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPullSuccess({result:r,sourceName:n.remote?o??"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 o=resolveConflictStrategy(r);return r.remote&&t?pullRemoteSingle({packageName:t,options:r,strategy:o}):pullGlobal({packageName:t,options:r,strategy:o})}async function pullRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,o=parseOwnerPackage(t);o||exitWithError("Invalid format — use owner/package (e.g. ahmadawais/code-style)"),setActiveSpinner($e("Pulling taste package").start());const s=await pullRemote({owner:o.owner,packageName:o.packageName,overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s,owner:o.owner}}async function pullGlobal(e){const{packageName:t,options:n,strategy:r}=e;setActiveSpinner($e("Pulling taste package").start());const o=n.all||!t?[]:[t],s=await pull({packages:o,source:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s}}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new rS({baseUrl:e}),n=await t.get({endpoint:Wt.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 We.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()?"":`${Me.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${ue.green(t)}Skipped ${n}`)}return!1}const o=n.packagesPushed.length,s=`${o} ${1===o?"package":"packages"}`,i=n.filePaths?.[n.packagesPushed[0]],a=r.global&&i?shortenPath(e.dirname(e.dirname(i))):i,l=wasPrompted()?"":`${Me.tick} `;if(!a)return logResult2(`${ue.green(l)}Pushed ${s} 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?` ${ue.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${ue.green(l)}Replaced ${s} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${ue.green(l)}Pushed ${s} to ${a}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const g=formatMergeParts({added:u,updated:d,unchanged:m}),h=g.length>0?` ${ue.gray(`(${g.join(", ")})`)}`:"";return logResult2(`${ue.green(l)}Pushed ${s} to ${a}${h}`),(u>0||d>0)&&m>0}function logPushSingleSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(1!==t.packagesPushed.length)return!1;const r=t.packagesPushed[0],o=t.filePaths?.[r],s=n.remote&&o,i=s?o:"global",a=wasPrompted()?"":`${Me.tick} `,l=!s&&o?ue.dim(`\n ${shortenPath(o)}`):"";if(n.overwrite)return logResult2(`${ue.green(a)}Replaced ${ue.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${ue.green(a)}Pushed ${ue.green(`'${r}'`)} taste package to ${i} ${ue.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${ue.green(a)}Pushed ${ue.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",o=wasPrompted()?"":`${Me.tick} `;return logResult2(wrapLine(`${ue.green(o)}Pushed ${ue.green(t.packagesPushed.length)} taste packages ${ue.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[o,s]=n.split("/");if(!o||!s)continue;const i=getPackageLink({owner:o,packageName:s});r.has(i)||(r.add(i),console.log(ue.gray(` ${i}`)))}}function logConflictSummary(e){const{result:t}=e,n=t.overwritten??[],r=t.skipped??[],o=t.packagesPushed.filter(e=>!n.includes(e)),s=t.packagesPushed.length+r.length,i=[];o.length>0&&i.push(wrapLine(`${ue.green("Merged")} (${o.length}) ${o.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${ue.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${ue.dim("Skipped")} (${r.length}) ${ue.dim(r.join(", "))}`,4)),i.length>0&&We.log.message(i.join("\n"));const a=`${s} ${1===s?"package":"packages"}`;We.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)),o=[];r.length>0&&o.push(wrapLine(`${ue.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&o.push(wrapLine(`${ue.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&o.push(wrapLine(`${ue.dim("Skipped")} (${n.length}) ${ue.dim(n.join(", "))}`)),o.length>0&&console.log(o.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"),Ut(),__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"),Ut(),rr(),Ut(),LS(),vS(),kn(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Ut(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Ut(),VE(),Ut();var iN=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),aN=__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:o,projectName:s,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=o.reduce((e,t)=>e+t.learnings.length,0),u=aN(r.files);return"project"!==a?promptTypeMismatchStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:o,isPublic:s,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:o,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?s: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 iN({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var lN=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),cN=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:o,overwrite:s}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:o,overwrite:s})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var uN=__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:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPushStrategy({packageName:s.category,localLearningsCount:s.learnings.length,globalPkg:r}):"merge"}async function executePushStrategy(e){const{tastePkg:t,target:n,flagStrategy:r,overwrite:o,userOwner:s,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:o,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:s,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:s,isPublic:i}),a.packagesPushed.push(t.category),a.mergeDetails[t.category]=r}const d=uN({target:n,category:t.category,owner:s});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:o=!1,isPublic:s=!1,strategy:i}=e;if(!exists2())return lN({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return lN({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:o,isPublic:s,isPublicExplicitlySet:t,flagStrategy:i}):lN({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return lN({pkg:"all",error:`Invalid target: ${r}`});const m=cN();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:i,overwrite:o,userOwner:d,isPublic:s,result:m});return m}async function executeRemotePush(e){const t=void 0!==e.isPublic,{owner:n,packageName:r,overwrite:o=!1,isPublic:s=!1,strategy:i}=e,a=await getPackage2({category:r});if(!a)return lN({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 lN({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:o,existingPkg:u,target:"remote-project",tastePkg:a}),m=t?s:u?.isPublic??!1,g=cN();if("skip"===d)return g.skipped.push(r),g;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m,overwrite:!0}),g.packagesPushed.push(r),g.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),g.packagesPushed.push(r),g.mergeDetails[r]=t}return g.filePaths[r]=`${n}/${r}`,g}async function pushRemote(e){const{packageName:t}=e;if(!exists2())return lN({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return lN({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"}))],o=await We.select({message:"Owner",options:r,initialValue:t});return We.isCancel(o)&&(We.cancel("Operation cancelled"),process.exit(0)),o}function createPushCommand(){return new Ne("push").description(`Push taste packages to remote ${ue.dim("(commandcode.ai)")} or global ${ue.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 Re("--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 Re("--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"),Ut(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var dN=__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};We.intro(ue.dim(`pushing ${t}`)),setPrompted(!0);const o=We.spinner();o.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(o.error("Failed"),We.outro(ue.red(`Taste package '${t}' not found in project`)),process.exit(1));const s=await fetchUserNamespaces();return o.stop(s.orgs.length>0?"Select owner to push to":""),{owner:s.orgs.length>0?await promptOwnerSelection(s):s.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 o=resolveConflictStrategy(r);return r.remote&&r.all?pushRemoteAll({options:r,strategy:o}):r.remote?pushRemoteSingle({packageName:t,options:r,strategy:o}):pushGlobal({packageName:t,options:r,strategy:o})}async function pushRemoteAll(t){const{options:n,strategy:r}=t;n.owner&&await validateOwnerAccess(n.owner);const o=(await getAllPackages2()).length,s=`${o} ${1===o?"package":"packages"}`,i=e.basename(process.cwd()),a=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(ue.dim(` Pushing ${s} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner($e("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:dN(n),strategy:r,owner:n.owner});return stopActiveSpinner(),l}async function pushRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,{owner:o,packageName:s}=await resolveOwnerForPush({packageName:t,owner:n.owner});startPushSpinner({owner:o,pkgName:s});const i=await pushRemote({owner:o,packageName:s,overwrite:n.overwrite,isPublic:dN(n),strategy:r});return stopActiveSpinner(`Pushed to ${o}/${s}`),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=We.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner($e("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,o=n.all||!t?[]:[t],s=await getAllPackages2(),i=o.length>0?o.length:s.length,a=`${i} ${1===i?"package":"packages"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(ue.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner($e("Pushing taste packages").start());const d=await push({packages:o,target:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),d}function createTasteCommand(){const e=new Ne(on.TASTE);return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),isExperimentalEnabled()&&e.addCommand(createLearnCommand()),e}function formatVersion(e,t,n=!1){const r=n?de.bold(de.green(t)):de.white(t);return`${de.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${de.bold(de.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(de.dim(`Run ${de.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(de.dim("Try updating manually:")),console.log(de.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(de.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=$e("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(`${de.green(Me.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${de.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=$e("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} ${Me.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:vs.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 ${de.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"),co(),__name(createTasteCommand,"createTasteCommand"),Ut(),kn(),Ps(),__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 mN=new Ne("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Ut(),zE(),VE();var pN=__name((e,t)=>`${Me.info} ${e}: ${de.cyan(t)}`,"formatInfoLine"),gN=__name(e=>de.bold(`${e}:`),"formatSectionHeader"),hN=__name(e=>de.red(e),"formatError"),fN=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),yN=__name(e=>["",gN("User Information"),pN("Name",e.name),pN("Email",e.email),pN("Username",e.userName)],"buildUserOutput"),wN=__name(e=>["",gN("Organization"),pN("Name",e.name),pN("Login",e.login)],"buildOrgOutput"),SN=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),bN=__name((e,t)=>{SN(yN(e)),t&&SN(wN(t)),console.log("")},"displayUserInfo"),EN=__name(e=>null!==e&&e.length>0,"validateApiKey"),vN=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=$e("Fetching user information...").start();try{const t=await getAuthKey();EN(t)||(e.fail(hN('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();vN(n)||(e.fail(hN("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),bN(n.user,n.org)}catch(t){e.fail(hN(`Error: ${fN(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var CN=new Ne("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"!==Ee("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=Ee("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=Ee("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(!Ee(`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:""===Ee("git status --porcelain",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}Ut(),Ut(),kn(),vS(),Gs(),LS(),Fn(),bo(),Ut(),__name(normalizeGitUrl,"normalizeGitUrl"),__name(validateGitRepo,"validateGitRepo"),Ut(),LS(),zE(),Ut();var kN=["completed","failed","cancelled","timed_out"];function isTerminalStatus(e){return kN.includes(e)}__name(isTerminalStatus,"isTerminalStatus");var TN={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=TN[n],o="setup"===t.phase;if(t.isResume&&o&&!isTerminalStatus(n)&&"running"!==n)r&&t.workingSpinner&&(t.workingSpinner.text=r);else{if(r&&o&&(t.currentSpinner&&t.currentSpinner.succeed(),t.currentSpinner=$e({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=$e({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: ${de.cyan(n)}`))}if("failed"===n){const n=e.data.message||"Unknown error";return t.workingSpinner&&(t.workingSpinner.fail(n),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail(n),t.currentSpinner=null),void(t.phase="done")}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${de.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(`${Me.cross} ${de.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 o=getApiBaseUrl().replace(/^http/,"ws"),s=await getAuthKey();if(!s)throw new Error("Not authenticated. Run: cmd login");const i=new URLSearchParams({token:s,...n>0?{lastEventId:String(n)}:{}}),a=`${o}/alpha/sandbox/stream/${e}?${i.toString()}`;return new Promise((t,o)=>{const s=new WebSocket(a),i={currentSpinner:null,workingSpinner:null,phase:"setup",lastEventId:n,isResume:r};r&&(i.currentSpinner=$e({stream:process.stderr,text:"Reconnecting..."}).start());const l=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.close(),console.error(`\n${de.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${de.cyan(`cmd --experimental sandbox --id ${e}`)}`),g(),t()},"detach"),u=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.readyState===WebSocket.OPEN&&s.send(JSON.stringify({action:"cancel"})),s.close(),console.error(`\n${de.yellow("Sandbox stopped.")}`),g(),t()},"cancelSandbox"),d=setupResizeForwarding({ws:s}),m=setupInputHandling({callbacks:{onCancel:u,onDetach:l}});process.once("SIGTERM",l);const g=__name(()=>{d(),m(),process.removeListener("SIGTERM",l)},"teardown");s.addEventListener("open",()=>{sendTerminalSize({ws:s}),i.currentSpinner&&(i.currentSpinner.stop(),i.currentSpinner=null),console.error(""),console.error(`${de.yellow("[Ctrl+C]")} ${de.dim("stop")} ${de.yellow("[Ctrl+D]")} ${de.dim("detach")}`),console.error(`${de.dim("Session:")} ${de.gray(e)}`),console.error(""),r&&(i.workingSpinner=$e({stream:process.stderr}).start())}),s.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)&&(s.close(),g(),t())}catch{}}),s.addEventListener("error",()=>{g(),i.currentSpinner&&(i.currentSpinner.fail("Connection error"),i.currentSpinner=null),o(new Error("WebSocket connection failed"))}),s.addEventListener("close",()=>{"done"!==i.phase&&(i.phase="done",stopAllSpinners({state:i}),g(),console.error(`\n${de.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${de.cyan(`cmd --experimental sandbox --id ${e}`)}`),t())})})}function readLocalConfigFiles(){let e="",t="";try{e=L.readFileSync(getAuthFile(),"utf-8")}catch{}try{t=L.readFileSync(getConfigFile(),"utf-8")}catch{}return{auth:e,config:t}}async function askQuestion(e){const t=ct.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,isInternalTeam:r,configFiles:o}){return new rS({baseUrl:getApiBaseUrl()}).post({endpoint:Wt.ALPHA.SANDBOX.START,body:{repoUrl:e,branch:t,prompt:n,isInternalTeam:r,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(de.yellow("Warning: You have uncommitted changes. The sandbox clones from remote, so local changes won't be included."));const r=isInternalTeamFlagPresent(),o=readLocalConfigFiles(),s=e||await askQuestion(`${de.bold("What do you want to do?")}\n${de.cyan(">")} `);if(!s.trim())return void console.error(de.yellow("No prompt provided. Aborting."));const i=s.trim().slice(0,sn.MAX_PROMPT_CHARS),a=$e({stream:process.stderr,text:"Starting sandbox session..."}).start();try{const e=await startSandboxSession({repoUrl:n.repoUrl,branch:n.branch,prompt:i,isInternalTeam:r,configFiles:o});a.succeed("Sandbox started"),await streamSession({sessionId:e.sessionId,prompt:i}),process.exit(0)}catch(e){a.fail("Failed to start sandbox session");const t=e instanceof Rs,r=t?e.code:void 0;if(401===(t?e.status:void 0)||"UNAUTHORIZED"===r)console.error(de.red("\nAuthentication failed. Try logging in again: cmd login"));else if("GITHUB_APP_NOT_INSTALLED"===r){const e=de.cyan(de.underline(n.repoUrl)),t=de.cyan(de.underline("https://github.com/apps/command-code-ai/installations/new"));console.error(`\n${de.red("✖")} Command Code GitHub App isn't installed on ${e}`),console.error(` Install it here: ${t}`),console.error(de.dim(" Then run this command again."))}else{const n=t&&"string"==typeof e.message?e.message:"Something went wrong. Please try again.";console.error(de.red(`\n${n}`))}process.exit(1)}}function createSandboxCommand(){return new Ne("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(de.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 o=n.split("/");if(o.length<2)throw new Error("Invalid GitHub repository format. Expected: owner/repo or owner/repo/path");const[s,i,...a]=o;validateSafeString(s,"owner"),validateSafeString(i,"repository");const l=a.length>0?a.join("/"):void 0;return l&&validateSafeString(l,"path"),{owner:s,repo:i,path:l,branch:t}}function buildGigetSource(e){const{owner:t,repo:n,path:r,branch:o}=e;let s=`gh:${t}/${n}`;return r&&(s+=`/${r}`),o&&(s+=`#${o}`),s}async function fetchSkillFromGitHub(e){await cleanupStaleTempDirectories();const n=parseGitHubRepo(e),{owner:r,repo:o,path:s}=n;let i;if(s){const e=s.split("/").filter(Boolean);i=e[e.length-1]}else i=o;const a=t.join(S.tmpdir(),`commandcode-skill-${R()}`);await k.mkdir(a,{recursive:!0});try{const e=buildGigetSource(n),{downloadTemplate:s}=await import("giget");try{await s(e,{dir:a,force:!0,silent:!0})}catch(t){if(!isCorruptedArchiveError(t))throw t;await clearGigetCache(r,o),await s(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 k.access(l),d=!0}catch{}if(!d)try{await k.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 k.rm(a,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&e.message.includes("SKILL.md not found"))throw e;throw wrapFetchError(e,r,o)}}async function discoverSkillsInRepo(e,t){const n=parseGitHubRepo(e),{owner:r,repo:o,path:s,branch:i}=n,{keepTempDir:a=!1}=t||{},{discoverSkillsLocally:l}=await Promise.resolve().then(()=>(tv(),ev)),u=await l({owner:r,repo:o,path:s,branch:i,keepTempDir:a});if(0===u.skills.length)throw new Error(`No skills found in repository ${r}/${o}${s?` at path "${s}"`:""}. Ensure the repository contains SKILL.md files.`);return u}async function resolveSkillMdPath(e){const n=t.join(e,"SKILL.md");try{return await k.access(n),n}catch{}const r=t.join(e,"skill.md");try{return await k.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 k.readFile(t,"utf-8"),{data:r}=je(n),o=Mf.parse(r);return{name:validateSkillName(o.name),description:o.description}}async function skillExists(e){const{skillName:n,location:r}=e,o="global"===r?getGlobalSkillsDir():getProjectSkillsDir(),s=t.join(o,n);try{return await k.access(s),!0}catch{return!1}}async function discoverSkills(e,t){return discoverSkillsInRepo(e,t)}async function installSkill(e){const{repoInput:n,options:r={}}=e,{global:o=!1,force:s=!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("/"),o=r?`${t.owner}/${t.repo}/${r}`:`${t.owner}/${t.repo}`;m=t.branch?`${o}@${t.branch}`:o}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=o?"global":"project",a="global"===i?getGlobalSkillsDir():getProjectSkillsDir(),l=await skillExists({skillName:r,location:i});if(l&&!s)throw new Error(`Skill "${r}" already exists in ${"global"===i?"~/.commandcode/skills/":".commandcode/skills/"}. Use --force to overwrite.`);await k.mkdir(a,{recursive:!0});const d=t.join(a,r),{randomUUID:m}=await import("crypto"),g=t.join(a,`.${r}.tmp.${m()}`);try{await k.cp(u,g,{recursive:!0,force:!0,dereference:!1}),l&&s&&await k.rm(d,{recursive:!0,force:!0}),await k.rename(g,d)}catch(e){if(await k.rm(g,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&"code"in e&&("EEXIST"===e.code||"ENOTEMPTY"===e.code))throw new Error(`Skill "${r}" was created by another process during installation. Use --force to overwrite.`);throw e}let h;try{h=await resolveSkillMdPath(d)}catch{h=t.join(d,"SKILL.md")}return{name:r,description:n,location:i,path:h}}finally{d&&await k.rm(u,{recursive:!0,force:!0}).catch(()=>{})}}async function removeSkill(e){const{global:n=!1}=e,r=validateSkillName(e.skillName),o=n?"global":"project",s="global"===o?getGlobalSkillsDir():getProjectSkillsDir(),i=t.join(s,r);if(!await skillExists({skillName:r,location:o}))throw new Error(`Skill "${r}" not found in ${"global"===o?"global (~/.commandcode/skills/)":"project (.commandcode/skills/)"} skills.${"global"===o?"":" Use -g/--global to check global skills."}`);await k.rm(i,{recursive:!0,force:!0})}async function listSkills(){const{global:e,project:t,warnings:n}=await loadAllSkillSummariesWithWarnings(),r=getBundledSkillsDir(),o=[],s=[];for(const t of e){const e={name:t.name,description:t.description,location:isBundledSkillPath({filePath:t.filePath,bundledDir:r})?"bundled":"global",path:t.filePath};("bundled"===e.location?o:s).push(e)}return{global:s,project:t.map(e=>({name:e.name,description:e.description,location:"project",path:e.filePath})),bundled:o,warnings:n}}__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"),co(),Ut(),Ut(),Ut(),Ut(),ZE(),__name(validateSafeString,"validateSafeString"),__name(parseGitHubRepo,"parseGitHubRepo"),__name(buildGigetSource,"buildGigetSource"),__name(fetchSkillFromGitHub,"fetchSkillFromGitHub"),__name(discoverSkillsInRepo,"discoverSkillsInRepo"),jS(),Qf(),__name(resolveSkillMdPath,"resolveSkillMdPath"),__name(validateSkillName,"validateSkillName"),__name(validateSkillContent,"validateSkillContent"),__name(skillExists,"skillExists"),__name(discoverSkills,"discoverSkills"),__name(installSkill,"installSkill"),__name(removeSkill,"removeSkill"),__name(listSkills,"listSkills"),kn();var _N=[`${de.dim("Usage:")}`,` ${de.cyan("cmd skills add")} ${de.white("<owner/repo>")}`,"",`${de.dim("Examples:")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/my-skills")} ${de.dim("# single-skill repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/skills/path/to/skill")} ${de.dim("# specific path in repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/multi-skills -s my-skill")} ${de.dim("# pick one from multi-skill repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/repo@branch")} ${de.dim("# specific branch")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/repo --global")} ${de.dim("# install to ~/.commandcode/skills/")}`],xN=__name((e,t)=>`${de.green(Me.tick)} Installed ${de.cyan(e)} ${de.dim(`${Me.arrowRight} ${t}/`)}`,"formatInstalled"),AN=__name(e=>`${de.red(Me.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){e&&await x(e,{recursive:!0,force:!0}).catch(()=>{}),process.exit(t)}function validateRepoFormat(e){(e.startsWith(".")||e.startsWith("/")||e.startsWith("~"))&&(console.error(AN("Local paths are not supported. Skills must be installed from GitHub.")),console.log(""),_N.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(AN(`Invalid repository: "${e}"`)),console.log(""),console.log(`Expected format: ${de.cyan("owner/repo")} or ${de.cyan("owner/repo/path")}`),console.log(""),_N.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 o;validateRepoFormat(e);const s=$e({text:`Fetching ${de.cyan(e)}...`,color:"cyan"});try{let i=[];s.start();const a=await discoverSkills(e,{keepTempDir:!0}),{skills:l,tempDir:u}=a;if(o=u,s.stop(),0===l.length&&(console.error(AN(`No skills found in ${de.cyan(e)}`)),console.log(de.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),t.skill){const n=l.find(e=>e.name.toLowerCase()===t.skill.toLowerCase());n||(console.error(AN(`Skill "${t.skill}" not found in ${de.cyan(e)}`)),console.log(""),console.log(de.dim("Available skills:")),l.forEach(e=>console.log(` ${de.cyan(e.name)}`)),await cleanupAndExit(o,1)),i=[n]}else if(1===l.length)i=[l[0]];else if(n){const t=await He({message:`Select skills to install from ${e}`,options:l.map(e=>({value:e.name,label:e.name})),required:!0});"symbol"==typeof t&&(console.log(de.dim("Cancelled")),await cleanupAndExit(o,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 s=$e({text:`Installing ${de.cyan(n.name)}...`,color:"cyan"});s.start();const i=await installSkill({repoInput:e,options:{global:t.global,force:t.force,skillName:n.name,discoveredSkill:n,cachedTempDir:o}});s.stop(),console.log(xN(i.name,r))}catch(e){d++;const t=e instanceof Error?e.message:String(e);console.error(AN(`Failed to install "${n.name}"`)),console.log(de.dim(` ${t}`))}await cleanupAndExit(o,d>0?1:0)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(AN(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction,"addAction");var PN=new Ne("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${_N.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(AN("No repository specified.")),console.log(""),_N.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction);Ut(),kn();var IN=__name((e,t)=>`${de.green(Me.tick)} Removed ${de.cyan(e)} from ${t} skills`,"formatRemoved"),MN=__name(e=>`${de.red(Me.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",o=validateSkillNameEarly(e);if(o&&(console.error(MN(o)),console.log(de.dim(`Run ${de.cyan("cmd skills list")} to see installed skills.`)),process.exit(1)),!t.yes&&n){const t=await Ge({message:`Remove ${de.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(de.dim("Cancelled")),process.exit(0))}await removeSkill({skillName:e,global:t.global}),console.log(IN(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill";r.includes("not found")?(console.error(MN(`Skill "${e}" not found in ${t.global?"global":"project"} skills`)),t.global||console.log(de.dim(`Try ${de.cyan(`cmd skills remove ${e} --global`)} to check global skills.`)),console.log(de.dim(`Run ${de.cyan("cmd skills list")} to see installed skills.`))):console.error(MN(r)),process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction,"removeAction");var NN=new Ne("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);Ut(),jS(),pE(),kn();var RN=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${de.cyan(e)} ${de.dim(`· ${n}`)}`},"formatSkillLine"),$N=__name((e,t)=>`${de.bold(de.white(e))} ${de.dim(`(${t})`)}`,"formatSectionHeader"),LN=__name(e=>{if(0===e.length)return;const t=groupWarnings(e);console.log(""),console.log(`${de.bold(de.yellow("Skipped"))} ${de.dim(`(${e.length})`)}`);for(const e of t){console.log(""),console.log(` ${de.bold(e.category)} ${de.dim(`(${e.items.length})`)}`);for(const t of e.items)console.log(` ${de.bold(skillIdentifier(t.path))}`),console.log(` ${de.dim(t.reason)}`)}},"printWarnings"),DN=__name(()=>{const e=process.cwd(),n=t.join(e,".commandcode","skills"),r=t.join(e,".agents","skills"),o=getProjectSkillsDir(),s=getProjectAgentsCompatSkillsDir(),i=["",de.dim("No skills installed."),"",de.dim("Looking in:"),de.dim(` ${getGlobalSkillsDir()} ${de.white("(global)")}`),de.dim(` ${getGlobalAgentsCompatSkillsDir()} ${de.white("(global, .agents)")}`)];return n!==o&&i.push(de.dim(` ${n} ${de.white("(cwd)")}`)),r!==s&&i.push(de.dim(` ${r} ${de.white("(cwd, .agents)")}`)),i.push(de.dim(` ${o} ${de.white("(project)")}`),de.dim(` ${s} ${de.white("(project, .agents)")}`),"",`Install a skill: ${de.cyan("cmd skills add")} ${de.dim("<owner/repo>")}`,""),i},"formatEmptyHint"),ON=__name(e=>{e.forEach(e=>console.log(e))},"printLines");async function listAction(){const e="true"===process.env.DEBUG;try{const{global:t,project:n,bundled:r,warnings:o}=await listSkills(),s=t.length+n.length,i=__name(()=>{e||0===o.length||(console.log(""),console.log(de.dim(`${o.length} skill${1===o.length?"":"s"} skipped · run with ${de.cyan("--debug")} to see issues`)))},"printDebugHint");0===s&&(ON(DN()),r.length>0&&(console.log($N("Bundled",r.length)),r.forEach(e=>{console.log(RN(e.name,e.description))}),console.log("")),e&&(LN(o),o.length>0&&console.log("")),e||(i(),console.log("")),process.exit(0)),console.log(""),console.log(heading({text:"Skills",sub:de.dim(`${s} installed`)})),n.length>0&&(console.log(""),console.log($N("Project",n.length)),n.forEach(e=>{console.log(RN(e.name,e.description))})),t.length>0&&(console.log(""),console.log($N("Global",t.length)),t.forEach(e=>{console.log(RN(e.name,e.description))})),r.length>0&&(console.log(""),console.log($N("Bundled",r.length)),r.forEach(e=>{console.log(RN(e.name,e.description))})),e&&LN(o),e||i(),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${de.red(Me.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction,"listAction");var FN=new Ne("list").description("List all installed skills. Run with -d/--debug to also see why any skills were skipped.").action(listAction),UN=new Ne("skills").description("Manage skills from GitHub repositories").addCommand(PN).addCommand(NN).addCommand(FN);handleUnhandledErrors(),setupTelemetry(),await preRun();var jN=createProgram();jN.action(interactiveModeAction),jN.addCommand(wM),jN.addCommand(SM),jN.addCommand(CN),jN.addCommand(mN),jN.addCommand(yM),jN.addCommand(createTasteCommand()),jN.addCommand(createMcpCommand()),jN.addCommand(bM),jN.addCommand(Ms),jN.addCommand(TE),jN.addCommand($E),jN.addCommand(UN),isExperimentalEnabled()&&jN.addCommand(createSandboxCommand()),setupCommanderHooks(jN),jN.parse();
324
+ `,fA=getMaxLineWidth(hA),yA=mA,wA=__name(e=>{const t=e??getTerminalWidth();return t>=dA?"full":t>=yA?"compact":"minimal"},"getHeaderLayout");Ut(),jr();var SA=__name(({children:e})=>{const t=[];let n="",r=!0;const o=__name(()=>{0!==n.length&&(t.push({text:n,panel:r}),n="")},"flush");for(const t of e){const e="░"===t;0===n.length?r=e:e!==r&&(o(),r=e),n+=t}return o(),re.createElement(Y,null,t.map((e,t)=>re.createElement(Y,{key:t,color:e.panel?Or.BG:Or.TEXT},e.text)))},"CommandLogoBanner");Ut(),jr();var bA=__name(({title:e,hashPrefix:t=!1,subPrefix:n=!1,suffix:r,padding:o=0,titleColor:s=gr.GRAY,dividerChar:i="─",dividerColor:a=gr.GRAY,boxProps:l})=>{const u=Math.max(0,(process.stdout.columns??80)-2*o),d=t?`# ${i}${i} `:n?`${i}${i} `:"",m=e?`${e} `:"",g=r?` ${r}`:"",h=d.length+m.length+g.length,f=i.repeat(Math.max(0,u-h));return re.createElement(K,{paddingLeft:o,paddingRight:o,marginBottom:1,...l},(t||n)&&re.createElement(Y,{color:a},d),e&&re.createElement(Y,{color:s},m),re.createElement(Y,{color:a},f),r&&re.createElement(Y,{color:gr.DIM},g))},"Divider");GE(),jr(),Ut(),jr();var EA=[{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}],vA=__name(({onComplete:e,onExit:t})=>{const[n,r]=se(0),[o,s]=se(!1),i=n>=EA.length;return ae(()=>{if(n>=EA.length)return;if(o)return;const e=EA[n],t=setTimeout(()=>{r(e=>Math.min(e+1,EA.length))},e.duration);return()=>clearTimeout(t)},[n,o]),Z((n,o)=>{""===n||o.ctrl&&"c"===n?t?t():e():o.escape?e():i?(o.return||" "===n)&&e():" "===n?s(e=>!e):o.return&&r(e=>Math.min(e+1,EA.length))}),re.createElement(K,{flexDirection:"column"},re.createElement(K,null,re.createElement(Y,{bold:!0},"Meet Your Coding Taste")),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"Command Code learns your coding style as you work.")),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"Here's how your preferences evolve in real-time:")),re.createElement(K,{flexDirection:"column",marginY:1},EA.slice(0,n).map((e,t)=>"user"===e.type?re.createElement(K,{key:t},re.createElement(Y,null,Me.pointer," ",e.text)):re.createElement(K,{key:t,flexDirection:"column",marginBottom:1,marginLeft:1},re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"⎿ "),re.createElement(Y,{color:fr.TEXT},e.text)),e.details&&re.createElement(K,{marginLeft:3},re.createElement(Y,{color:gr.DIM},"Saved(",e.details,")"))))),i?re.createElement(K,{flexDirection:"column",marginY:1},re.createElement(K,null,re.createElement(Y,{bold:!0,color:fr.TEXT},"Demo Complete!")),re.createElement(K,null,re.createElement(Y,null,"Command Code will now use these preferences to generate")),re.createElement(K,null,re.createElement(Y,null,"better suggestions tailored to your coding style. The")),re.createElement(K,null,re.createElement(Y,null,"more you code, the smarter it gets.")),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press Enter to get started →"))):re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"[SPACE: pause] [ENTER: next] [ESC: skip]"+(o?" (paused)":""))))},"TasteDemoComponent"),CA=__name(({onClose:e,onExit:t})=>{const[n,r]=se(BT.getEvents()),[o,s]=se(0);Z((n,r)=>{""===n||r.ctrl&&"c"===n?t():r.ctrl&&"t"===n&&e()},{isActive:!0}),ae(()=>{const e=__name(()=>{r(BT.getEvents())},"handleNewEvent"),t=__name(()=>{r([])},"handleCleared");return BT.on("new-event",e),BT.on("cleared",t),()=>{BT.off("new-event",e),BT.off("cleared",t)}},[]),ae(()=>{const e=__name(()=>{WE(),s(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=le(()=>n.find(e=>"analyzing"===e.type),[n]),l=le(()=>n.find(e=>"analyzed"===e.type),[n]),u=le(()=>n.find(e=>"no_learnings"===e.type),[n]),d=le(()=>n.find(e=>"learned"===e.type||"refactored"===e.type),[n]),m=u?n.indexOf(u):1/0,g=d?n.indexOf(d):1/0,h=!!u&&m<g,f=!!a||!!l||h,y=le(()=>n.filter(e=>"analyzing"!==e.type&&"analyzed"!==e.type&&"no_learnings"!==e.type),[n]),w=le(()=>[...y].reverse(),[y]),S=__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 o=n,s=null;if(r){o=r[1].trim();const e=(100*parseFloat(r[2])).toFixed(2);s=`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:o,confidence:s}}return{type:null,label:null,content:e,confidence:null}},"formatLearningMessage"),E=__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),o=parseInt(t[3],10);return{text:n,oldPercent:r,newPercent:o,diff:o-r}},"parsePercentageChange"),v=__name(e=>{if(!e)return null;const t=e.match(/moved to (.+)/);if(!t)return null;const n=t[1],r=n.split("/"),o=r[r.length-1];return{category:r.slice(0,-1).join("/"),oldPath:o,newPath:n,fullPath:`.commandcode/taste/${n}`}},"formatMovedDetails"),C=le(()=>(process.stdout.rows??24)-1,[o]);return re.createElement(K,{flexDirection:"column",width:"100%",height:C,justifyContent:"flex-start",alignItems:"flex-start",padding:0,margin:0},re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(SA,null,pA())),re.createElement(bA,{hashPrefix:!0,title:"Taste Feed",titleColor:"white",suffix:"ctrl+t to close"}),re.createElement(K,{flexDirection:"column"},0===n.length?re.createElement(K,{flexDirection:"column"},re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(K,null,re.createElement(Y,null,"Start using Command Code and it will begin recording your coding taste.")),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"Your preferences, patterns, and style will appear here in real-time."))),re.createElement(ne,{count:2}),re.createElement(bA,{title:"DEMO",titleColor:"white",subPrefix:!0}),re.createElement(vA,{onComplete:()=>{e()},onExit:t})):re.createElement(K,{flexDirection:"column"},y.length>0&&re.createElement(K,{flexDirection:"column",gap:1},w.map(e=>{if(i(e.type)){const{type:t,label:n,content:r,confidence:o}=S(e.message),s="moved"===t?v(e.details):null,i="upgraded"===t||"downgraded"===t?E(r):null,a=s?.fullPath??e.details;let l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",r),o&&re.createElement(Y,{color:gr.DIM}," ","(",o,")"));return i&&(l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",i.text," ("),re.createElement(Y,{color:gr.DIM},"confidence:"," "),re.createElement(Y,{color:gr.DIM},i.oldPercent,"%"),re.createElement(Y,null," ",Me.arrowRight," "),re.createElement(Y,{color:i.diff>0?gr.GREEN:gr.RED},i.newPercent,"%"),re.createElement(Y,null,")"))),s&&(l=re.createElement(re.Fragment,null,re.createElement(Y,null," ",s.category," ","package ("),re.createElement(Y,{color:gr.DIM},s.oldPath),re.createElement(Y,null," ",Me.arrowRight," ",s.newPath),re.createElement(Y,null,")"))),re.createElement(K,{key:e.id},re.createElement(K,{flexDirection:"column"},re.createElement(K,null,re.createElement(K,{flexShrink:0},re.createElement(Y,{backgroundColor:fr.BADGE_BG,color:fr.BADGE_FG,bold:!0},`${p_}${n}${p_}`)),a&&re.createElement(Y,{color:gr.DIM}," ","(",a,")")),re.createElement(K,{marginLeft:1},re.createElement(Y,{color:gr.DIM},"⎿"," "),l)))}return re.createElement(K,{key:e.id},re.createElement(Y,{color:gr.DIM},Me.pointerSmall," ",e.message))})),f&&re.createElement(K,{flexDirection:"column",marginTop:y.length>0?1:0},a&&re.createElement(K,null,re.createElement(Y,{color:gr.DIM},Me.pointerSmall," ",a.message)),l&&re.createElement(K,null,re.createElement(Y,{color:gr.DIM},Me.pointerSmall," ",l.message)),h&&u&&re.createElement(K,null,re.createElement(Y,{color:gr.DIM},Me.pointerSmall," ",u.message))))))},"LearningFeedFull");function LearningView({setShowLearningFeed:e,setStaticKey:t,onExit:n}){return re.createElement(CA,{onClose:()=>{WE(),e(!1),t(e=>e+1)},onExit:n})}__name(LearningView,"LearningView"),Ut(),jr(),Ut(),jr(),GE(),co();var kA=__name(({onClose:e,onSettingsChange:t,staticKey:n})=>{const[r,o]=se(!1),[s,i]=se(!0);ae(()=>{__name(async()=>{try{const e=await isTasteLearningEnabled();o(e)}catch(e){}finally{i(!1)}},"loadSettings")()},[]),Z((t,n)=>{if(!n.return&&" "!==t)return n.escape?(WE(),void e()):void 0;a()});const a=__name(async()=>{const e=!r;o(e);try{await setTasteLearning({tasteLearning:e}),t?.()}catch(t){o(!e)}},"toggleTasteLearning");return s?re.createElement(K,{key:n,borderStyle:"single",borderColor:gr.BLUE,padding:1,flexDirection:"column"},re.createElement(Y,{color:gr.BLUE,bold:!0},"Taste Settings"),re.createElement(Y,{color:gr.DIM},"Loading configuration...")):re.createElement(K,{key:n,borderStyle:"single",borderColor:gr.GRAY,padding:1,flexDirection:"column"},re.createElement(Y,{bold:!0},"Taste Learning"),re.createElement(Y,{color:gr.DIM},"Configure taste learning preferences for this project"),re.createElement(K,{marginTop:1}),re.createElement(K,{justifyContent:"space-between"},re.createElement(Y,null,"Taste learning",re.createElement(Y,{color:gr.DIM}," ","- Learn from your interactions")),re.createElement(Y,{color:r?gr.GREEN:gr.GRAY},r?"enabled":"disabled")),re.createElement(K,{marginTop:1}),re.createElement(Y,{color:gr.DIM},"Taste data stored in .commandcode/taste/taste.md"),re.createElement(Y,{color:gr.DIM},"Enter/Space to toggle • Esc to close"))},"TasteConfig");function TasteConfigView({staticKey:e,setShowTasteConfig:t,loadTasteStatus:n}){return re.createElement(re.Fragment,null,re.createElement(Bx,{staticKey:e}),re.createElement(K,{flexDirection:"column",width:"100%"},re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"Press Esc to return to conversation")),re.createElement(kA,{onClose:()=>t(!1),onSettingsChange:n,staticKey:e})))}function fuzzyMatch(e,t){let n=0;for(const r of e)if(r===t[n]&&(n++,n===t.length))return!0;return!1}function fuzzyScore(e,t){let n=0;for(const r of e)fuzzyMatch(r.text.toLowerCase(),t)&&(n+=r.weight);return n}function fuzzyFilter(e,t,n){if(!t.trim())return e;const r=t.toLowerCase().split("");return e.map(e=>({item:e,score:fuzzyScore(n(e),r)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score).map(({item:e})=>e)}__name(TasteConfigView,"TasteConfigView"),Ut(),Ut(),kn(),Ut(),__name(fuzzyMatch,"fuzzyMatch"),__name(fuzzyScore,"fuzzyScore"),__name(fuzzyFilter,"fuzzyFilter"),jr(),Ut(),jr();var TA=__name(({query:e,resultCount:t,placeholder:n="Type to search..."})=>re.createElement(K,{width:"100%"},re.createElement(Y,{color:gr.GRAY},Me.pointerSmall," "),re.createElement(Y,{color:e?gr.WHITE:gr.GRAY},e||n),e&&void 0!==t&&re.createElement(Y,{dimColor:!0}," (",t," found)")),"SearchInput");function useListNavigation({items:e,onSelect:t,onCancel:n,validate:r,initialIndex:o=0,searchCursorIndex:s=0,searchQuery:i,onSearchChange:a,isActive:l=!0,disableSearch:u=!1,selectByNumber:d=!1,onReset:m}){const[g,h]=se(o),[f,y]=se(null);ae(()=>{i||h(o)},[o,i]);const w=e.length-1,S=__name(e=>{a(e),h(s)},"updateSearch");return Z((o,s)=>{if(s.escape)return!u&&i?void S(""):void n();if(u||!s.backspace&&!s.delete){if(u&&m&&"r"===o&&!s.ctrl&&!s.meta){const t=e[g];return void(t&&m(t))}if(0!==e.length){if(s.upArrow)return y(null),void h(e=>Math.max(e-1,0));if(s.downArrow)return y(null),void h(e=>Math.min(e+1,w));if(s.return){const n=e[g];if(!n)return;if(r){const e=r(n);if(e)return void y(e)}return void t(n)}if(d&&1===o.length&&o>="1"&&o<="9"&&!s.ctrl&&!s.meta){const n=Number(o)-1,s=e[n];if(!s)return;if(h(n),r){const e=r(s);if(e)return void y(e)}return void t(s)}!u&&!s.ctrl&&!s.meta&&!s.tab&&o&&1===o.length&&o>=" "&&S(i+o)}}else S(i.slice(0,-1))},{isActive:l}),{cursor:g,error:f,setError:y}}function useTerminalHeight(){const{stdout:e}=X(),[t,n]=se(()=>e?.rows??24);return ae(()=>{const t=__name(()=>n(e?.rows??24),"onResize");return e.on("resize",t),()=>{e.off("resize",t)}},[e]),t}function skillIdentifier(e){const n=t.basename(e);return"skill.md"===n.toLowerCase()?t.basename(t.dirname(e)):n}Ut(),__name(useListNavigation,"useListNavigation"),Ut(),__name(useTerminalHeight,"useTerminalHeight"),Ut(),kn(),jr(),Ut(),GE(),jr(),uo(),Ut(),__name(skillIdentifier,"skillIdentifier");var _A=new Set(["Invalid YAML","Missing fields","Missing SKILL.md"]);function categoryColor(e){return _A.has(e)?gr.RED:gr.YELLOW}function formatWarningsAsMarkdown(e){const t=groupWarnings(e),n=[`# Skipped skills (${e.length})`,""];for(const e of t){n.push(`## ${e.category} (${e.items.length})`,"");for(const t of e.items)n.push(`- \`${skillIdentifier(t.path)}\` — \`${t.path}\``),n.push(` - ${t.reason}`);n.push("")}return n.join("\n").replace(/\n+$/,"")+"\n"}async function copyAllWarnings(e,t){try{const{isClipboardAvailable:n}=await Promise.resolve().then(()=>(Kr(),Qr));if(!n())return void t({text:"Clipboard unavailable — copy the skipped skill paths manually",color:gr.YELLOW});const r=await import("@crosscopy/clipboard");await r.default.setText(formatWarningsAsMarkdown(e));const o=e.length;t({text:`Copied ${o} issue${1===o?"":"s"} to clipboard`,color:gr.GREEN})}catch{t({text:"Clipboard write failed",color:gr.YELLOW})}}__name(categoryColor,"categoryColor"),__name(formatWarningsAsMarkdown,"formatWarningsAsMarkdown"),__name(copyAllWarnings,"copyAllWarnings");var xA=__name(({warnings:e,onClose:t,isActive:n=!0})=>{const r=groupWarnings(e),o=e.length>0,[s,i]=se(null),a=ie(null),l=ie(!0);ae(()=>()=>{l.current=!1,a.current&&(clearTimeout(a.current),a.current=null)},[]);const u=__name(e=>{l.current&&(a.current&&clearTimeout(a.current),i(e),a.current=setTimeout(()=>{l.current&&(i(null),a.current=null)},3e3))},"showStatus");return Z((n,r)=>r.escape||" "===n&&o?(WE(),void t()):void("c"===n&&o&&copyAllWarnings(e,u)),{isActive:n}),re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Skills"," "),re.createElement(Y,{color:gr.DIM},"› "),re.createElement(Y,{color:hr,bold:!0},"Skipped"," "),re.createElement(Y,{color:gr.WHITE},e.length)),o&&re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"Press c to copy all issues")),o?re.createElement(K,{flexDirection:"column"},r.map(e=>re.createElement(K,{key:e.category,flexDirection:"column"},re.createElement(K,null,re.createElement(Y,{color:categoryColor(e.category)},e.category)),e.items.map(e=>re.createElement(K,{key:e.path,flexDirection:"column",marginBottom:1},re.createElement(K,{paddingLeft:2},re.createElement(ao,{url:m(e.path).href,text:skillIdentifier(e.path),color:gr.WHITE})),re.createElement(K,{paddingLeft:4},re.createElement(Y,{color:gr.WHITE},e.reason))))))):re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"No issues — every skill loaded.")),s&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:s.color},s.text)),re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:gr.DIM},o?"c copy all issues · esc back to skills":"esc back to skills")))},"SkillsConfigIssues"),AA=__name(({warnings:e=[],onClose:t})=>{const[n,r]=se("list");return Z((o,s)=>{"list"===n&&(s.escape&&t?t():" "===o&&!s.ctrl&&!s.meta&&e.length>0&&r("issues"))},{isActive:"list"===n}),"issues"===n?re.createElement(xA,{warnings:e,onClose:()=>r("list"),isActive:!0}):re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Skills"),e.length>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:gr.YELLOW},e.length," skipped"))),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"No skills found")),re.createElement(Y,{color:gr.DIM},"Create skills in:"),re.createElement(Y,{color:gr.DIM}," ","~/",".commandcode","/","skills","/ (user)"),re.createElement(Y,{color:gr.DIM}," ","~/.agents/","skills","/ (user, .agents)"),re.createElement(Y,{color:gr.DIM}," ",".commandcode","/","skills","/ (project)"),re.createElement(Y,{color:gr.DIM}," ",".agents/","skills","/ (project, .agents)"),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},e.length>0&&"space to view issues · ","Press ",re.createElement(Y,{bold:!0},"Esc")," to close")))},"SkillsConfigEmpty");function clampScrollOffset(e){const{cursor:t,total:n,maxVisible:r,currentOffset:o}=e;if(n<=r)return 0;let s=o;t<s?s=t:t>=s+r&&(s=t-r+1);const i=Math.max(0,n-r);return Math.min(Math.max(0,s),i)}function sliceSectionForWindow(e){const{section:t,sectionBase:n,windowStart:r,windowEnd:o}=e,s=Math.min(Math.max(r-n,0),t.length),i=Math.min(Math.max(o-n,0),t.length);return{rows:t.slice(s,i),baseIndex:n+s}}Ut(),__name(clampScrollOffset,"clampScrollOffset"),__name(sliceSectionForWindow,"sliceSectionForWindow"),Ut();var PA=__name(e=>Math.ceil(e.length/4),"estimateTokens"),IA=__name(e=>e.includes("/.agents/skills/")||e.includes("\\.agents\\skills\\"),"isAgentsSkill"),MA={user:"user settings",projectShared:"project shared",projectLocal:"project local"},NA=__name(()=>"win32"===process.platform?'No editor found. Set $EDITOR: setx EDITOR "code"':"No editor found. Set $EDITOR: echo 'export EDITOR=\"code\"' >> "+("darwin"===process.platform?"~/.zshrc":"~/.bashrc"),"getEditorSetupMessage");Ut(),jr();var RA=__name(({title:e,subtitle:t,skills:n,baseIndex:r,cursor:o,disabled:s})=>re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(K,null,re.createElement(Y,{color:Tr,bold:!0},e," "),re.createElement(Y,{color:Tr},t)),n.map((e,t)=>{const n=r+t===o,i=s.has(e.label),a=IA(e.filePath),l=n?xr:void 0;return re.createElement(K,{key:e.filePath},re.createElement(Y,{color:i?gr.DIM:gr.GREEN,backgroundColor:l},i?"[off] ":"[on] "),re.createElement(Y,{color:i?gr.DIM:gr.WHITE,backgroundColor:l},e.label),a&&re.createElement(Y,{color:gr.DIM,backgroundColor:l}," [.agents]"),re.createElement(Y,{color:gr.DIM,backgroundColor:l}," · ~",PA(e.description)," tokens "))})),"SkillSection");Ut();var $A=__name(e=>[{text:e.label,weight:100}],"SKILL_SEARCH_FIELDS"),LA=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se([]),[s,i]=se(!0),[a,l]=se(null),[u,d]=se(""),[m,g]=se(new Set),[h,f]=se(new Map),[y,w]=se(!1),[S,E]=se(null),[v,C]=se("list"),[k,T]=se(0),_=useTerminalHeight(),x=ie(!1);ae(()=>{__name(async()=>{try{const e=findGitRoot(),t=getBundledSkillsDir(),[{global:r,project:s,warnings:i},a]=await Promise.all([loadAllSkillSummariesWithWarnings(),loadDisabledSkills({projectRoot:e})]),l=__name(e=>isBundledSkillPath({filePath:e,bundledDir:t}),"isBundled"),u=[...s.map(e=>({label:e.name,location:"project",description:e.description,filePath:e.filePath})),...r.filter(e=>!l(e.filePath)).map(e=>({label:e.name,location:"user",description:e.description,filePath:e.filePath})),...r.filter(e=>l(e.filePath)).map(e=>({label:e.name,location:"bundled",description:e.description,filePath:e.filePath}))];u.sort((e,t)=>{if(e.location!==t.location){const n={project:0,user:1,bundled:2};return n[e.location]-n[t.location]}return e.label.localeCompare(t.label)}),n(u),o(i),g(new Set(a.names)),f(new Map(a.bySkill)),w(a.noProjectRoot)}catch(e){l(e instanceof Error?e.message:"Failed to load skills")}finally{i(!1)}},"load")()},[]);const A=le(()=>fuzzyFilter(t.filter(e=>"project"===e.location),u,$A),[t,u]),P=le(()=>fuzzyFilter(t.filter(e=>"user"===e.location),u,$A),[t,u]),I=le(()=>fuzzyFilter(t.filter(e=>"bundled"===e.location),u,$A),[t,u]),M=le(()=>[...A,...P,...I],[A,P,I]),N=_-1,R=(A.length>0?1:0)+(P.length>0?1:0)+(I.length>0?1:0),$=Math.max(4,N-12-2*R),L=__name(async e=>{if(x.current)return;const t=m.has(e.label),n=h.get(e.label);if(t&&void 0!==n&&"projectLocal"!==n&&!y)return void E(`Cannot enable: "${e.label}" is disabled in ${MA[n]}. Edit that file to override.`);x.current=!0;const r=new Set(m);t&&r.delete(e.label),t||r.add(e.label),g(r),E(null);try{const n=findGitRoot(),r=await setSkillEnabled(e.label,t,{projectRoot:n}),o=new Map(h);t&&o.delete(e.label),t||o.set(e.label,r),f(o),"user"===r&&E("Saved to user settings — no project found.")}catch(e){g(m),E(`Failed to save: ${e instanceof Error?e.message:String(e)}`)}finally{x.current=!1}},"toggleSkill");ae(()=>{"issues"===v&&d("")},[v]);const D="list"===v&&t.length>0,{cursor:O}=useListNavigation({items:M,onSelect:L,onCancel:e,searchQuery:u,onSearchChange:d,initialIndex:0,isActive:D});if(ae(()=>{T(e=>clampScrollOffset({cursor:O,total:M.length,maxVisible:$,currentOffset:e}))},[O,M.length,$]),Z((t,n)=>{if(!n.tab)return;const r=M[O];r&&(async()=>{try{await St([{file:r.filePath,line:1}]),e()}catch(e){if(e instanceof Error&&e.message.includes("$EDITOR environment variable"))return void l(NA());l(e instanceof Error?e.message:"Failed to open skill in editor")}})()},{isActive:D}),Z((e,n)=>{"list"===v&&0!==t.length&&" "===e&&!n.ctrl&&!n.meta&&r.length>0&&0===u.length&&C("issues")},{isActive:"list"===v&&t.length>0}),s)return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Y,{color:hr,bold:!0},"Skills"),re.createElement(Y,{color:gr.DIM},"Loading skills..."));if(a)return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(Y,{color:gr.RED,bold:!0},"Skills"),re.createElement(Y,{color:gr.DIM},a),re.createElement(K,{marginTop:1}),re.createElement(Y,{color:gr.DIM},"Press ",re.createElement(Y,{bold:!0},"Esc")," to close"));if(0===t.length)return re.createElement(AA,{warnings:r,onClose:e});if("issues"===v)return re.createElement(xA,{warnings:r,onClose:()=>C("list"),isActive:!0});const F=t.filter(e=>m.has(e.label)).length,U=k,j=k+$,B=sliceSectionForWindow({section:A,sectionBase:0,windowStart:U,windowEnd:j}),q=sliceSectionForWindow({section:P,sectionBase:A.length,windowStart:U,windowEnd:j}),z=sliceSectionForWindow({section:I,sectionBase:A.length+P.length,windowStart:U,windowEnd:j}),W=M.length>$;return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Skills"," "),re.createElement(Y,{color:gr.DIM},t.length," skill",1===t.length?"":"s"),F>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:gr.YELLOW},F," off")),r.length>0&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:gr.YELLOW},r.length," skipped"))),re.createElement(K,{marginBottom:1},re.createElement(Y,{dimColor:!0},y?"No project found — toggles will be saved to user settings.":"Toggle skills on or off for this project.")),re.createElement(K,{marginBottom:1,flexDirection:"column",width:"100%"},re.createElement(TA,{query:u,resultCount:u?M.length:void 0,placeholder:"Type to search skills..."})),0===M.length?re.createElement(K,{marginY:1},re.createElement(Y,{color:gr.GRAY},'No skills match "',u,'"')):re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"column"},B.rows.length>0&&re.createElement(RA,{title:"Project skills",subtitle:"(.commandcode/skills or .agents/skills)",skills:B.rows,baseIndex:B.baseIndex,cursor:O,disabled:m}),q.rows.length>0&&re.createElement(RA,{title:"User skills",subtitle:"(~/.commandcode/skills or ~/.agents/skills)",skills:q.rows,baseIndex:q.baseIndex,cursor:O,disabled:m}),z.rows.length>0&&re.createElement(RA,{title:"Bundled skills",subtitle:"(ships with Command Code)",skills:z.rows,baseIndex:z.baseIndex,cursor:O,disabled:m})),W&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",U+1,"–",Math.min(j,M.length)," of"," ",M.length,U>0?" · ↑ more":"",j<M.length?" · ↓ more":""))),S&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.YELLOW},S)),re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:gr.DIM},"type to search · ↑/↓ navigate · enter to toggle · tab to edit",r.length>0&&!u&&re.createElement(re.Fragment,null," · space to view issues"),u?" · esc to clear":" · esc to close"),re.createElement(Y,{color:gr.DIM},"add skills:"," ",re.createElement(Y,{color:gr.CYAN},"cmd skills add ","<owner/repo>"))))},"SkillsConfig");function SkillsConfigView({staticKey:e,setShowSkillsConfig:t,setStaticKey:n}){re.useEffect(()=>{hardResetForResize()},[]);const r=__name(()=>{hardResetForResize(),n(e=>e+1),t(!1)},"handleClose");return re.createElement(re.Fragment,null,re.createElement(Bx,{staticKey:e}),re.createElement(K,{flexDirection:"column",width:"100%"},re.createElement(LA,{onClose:r,staticKey:e})))}function getUsageColor(e){return e>=80?gr.RED:e>=50?gr.YELLOW:gr.GREEN}function buildBlockBar({percentage:e,width:t}){const n=Math.max(0,Math.min(100,e));let r=Math.round(n/100*t);n>.5&&0===r&&(r=1),n<99.5&&r===t&&(r=t-1);const o=t-r;return{filled:"█".repeat(r),empty:"░".repeat(o)}}function getStudioUsageUrl(e){const t=e?.org?.login??e?.user?.userName;return t?`https://commandcode.ai/${t}/settings/usage`:null}__name(SkillsConfigView,"SkillsConfigView"),Ut(),Ut(),io(),GE(),jr(),Ut(),jr(),__name(getUsageColor,"getUsageColor"),__name(buildBlockBar,"buildBlockBar"),uo(),__name(getStudioUsageUrl,"getStudioUsageUrl");var DA=__name(e=>e.replace(/^https?:\/\//,""),"stripScheme");function getProgressBarWidth({terminalWidth:e}){return e<50?Math.max(10,e-10):e<70?Math.max(15,e-15):Math.min(30,e-15)}function getDaysColor(e){if(null!==e)return e<3?gr.RED:e<7?gr.YELLOW:void 0}__name(getProgressBarWidth,"getProgressBarWidth"),__name(getDaysColor,"getDaysColor");var OA=__name(({plan:e,status:t})=>re.createElement(K,{marginBottom:0},re.createElement(K,{flexShrink:0},re.createElement(Y,{backgroundColor:gr.BLUE,color:"#f4f4f4",bold:!0},`${p_}USAGE${p_}`)),e&&re.createElement(re.Fragment,null,re.createElement(Y,null," "),re.createElement(Y,{color:gr.GRAY},`${e.name} Plan`)),t&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:"active"===t?gr.GREEN:gr.YELLOW},t))),"UsageBadge"),FA=__name(({showRetry:e})=>re.createElement(K,{marginTop:1},e&&re.createElement(Y,{color:gr.DIM},re.createElement(Y,{bold:!0},"r")," to retry · "),re.createElement(Y,{color:gr.DIM},"Press ",re.createElement(Y,{bold:!0},"Esc")," to close")),"UsageFooter"),UA=__name(({models:e,grandTotal:t})=>{if(0===e.length)return null;const n=e.map(e=>({...e,displayName:getModelDisplayName(e.model),costLabel:formatCredits(e.totalCost)})),r=Math.max(...n.map(e=>e.displayName.length)),o=Math.min(24,Math.max(10,r)),s=Math.max(...n.map(e=>e.costLabel.length)),i=Math.max(8,s+2);return re.createElement(K,{flexDirection:"column",marginTop:1},n.map(({model:e,displayName:n,costLabel:r,totalCost:s})=>{const a=t>0?Math.round(s/t*100):0,l=n.length>o?n.slice(0,o-1)+"…":n;return re.createElement(K,{key:e},re.createElement(Y,null,l.padEnd(o+2)),re.createElement(Y,null,r.padEnd(i)),re.createElement(Y,{color:gr.DIM},`${a}%`))}))},"ModelBreakdownRows"),jA=__name(({onClose:e})=>{const[t,n]=se("loading"),[r,o]=se(null),[s,i]=se(!1),a=getProgressBarWidth({terminalWidth:useTerminalWidth()}),l=ce(async e=>{try{i(!1);const t=await fetchUsageData();if(e.aborted)return;if(!t.whoami){const e=t.errors.some(isAuthErrorMessage);return i(e),void n("error")}o(t),n("loaded")}catch{if(e.aborted)return;n("error")}},[]),u=re.useRef(null);Z((r,o)=>{if(o.escape&&(WE(),e()),"r"===r&&"error"===t){n("loading"),u.current?.abort();const e=new AbortController;u.current=e,l(e.signal)}}),ae(()=>{const e=new AbortController;return u.current=e,l(e.signal),()=>e.abort()},[l]);const d=r?.subscription?.data??null,m=d?getPlanInfo({planId:d.planId??""}):null;if("loading"===t)return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(OA,{plan:m,status:d?.status??null}),re.createElement(Y,{color:gr.DIM},"Loading…"),re.createElement(FA,null));if("error"===t)return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(OA,{plan:m,status:d?.status??null}),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},s?"Not authenticated. Run /login to connect your account.":"Something went wrong.")),re.createElement(FA,{showRetry:!s}));if(!r)return null;const g=r.credits||r.subscription,h=getStudioUsageUrl(r.whoami);if(!g)return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(OA,{plan:m,status:d?.status??null}),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"No billing data found."),h&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," Visit "),re.createElement(ao,{url:h,text:"Studio",color:gr.CYAN}),re.createElement(Y,{color:gr.DIM}," for usage details."))),re.createElement(FA,null));const f=r.credits?.credits,y=r.summary,w=r.modelBreakdown,S=null!=w&&w.length>0,E=Math.max(0,f?.monthlyCredits??0)+Math.max(0,f?.purchasedCredits??0)+Math.max(0,f?.freeCredits??0),v=Math.max(0,y?.totalCost??0),C=getUsagePercent({used:v,total:v+E}),k=E>0||v>0,T=d?.currentPeriodEnd?getDaysRemaining(d.currentPeriodEnd):null,_=getDaysColor(T),x=getUsageColor(C),A=buildBlockBar({percentage:C,width:a}),P=S?w.reduce((e,t)=>e+t.totalCost,0):0;return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,{marginBottom:1},re.createElement(OA,{plan:m,status:d?.status??null})),k?re.createElement(K,null,re.createElement(Y,{color:x},A.filled),re.createElement(Y,{color:Tr},A.empty),re.createElement(Y,{bold:!0,color:x},` ${Math.round(C)}% used`)):re.createElement(Y,{color:gr.DIM},"Plan details unavailable"),k&&re.createElement(K,null,d?.currentPeriodEnd&&re.createElement(Y,{color:gr.DIM},"Cycle: "),re.createElement(Y,null,formatCredits(E)),re.createElement(Y,{color:gr.DIM}," left"),y&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,null,y.totalCount.toLocaleString()),re.createElement(Y,{color:gr.DIM}," requests")),null!==T&&re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.DIM}," · "),0===T?re.createElement(Y,{color:_},"renewal today"):re.createElement(re.Fragment,null,re.createElement(Y,{color:_},`${T} day${1===T?"":"s"}`),re.createElement(Y,{color:gr.DIM}," to renewal")))),S&&re.createElement(UA,{models:w,grandTotal:P}),h&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Full breakdown at "),re.createElement(ao,{url:h,text:DA(h),color:gr.CYAN})),re.createElement(FA,null))},"UsageOverlay");function UsageView({staticKey:e,setShowUsageOverlay:t}){return re.createElement(re.Fragment,null,re.createElement(Bx,{staticKey:e}),re.createElement(K,{flexDirection:"column",width:"100%"},re.createElement(jA,{onClose:()=>t(!1)})))}__name(UsageView,"UsageView"),Ut(),Ut(),kn(),pb(),jS(),co();var BA="System prompt",qA="Messages";function countMessagesByRole({messages:e}){let t=0,n=0;for(const r of e)"user"===r.message.role&&!isHiddenTranscriptMessage({message:r})&&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){if(isHiddenTranscriptMessage({message:r}))continue;const e=r.message.content;if(Array.isArray(e))for(const r of e)"tool-call"===r.type&&t++,"tool-result"===r.type&&n++}return{calls:t,results:n}}function countImages({messages:e}){let t=0;for(const n of e){if(isHiddenTranscriptMessage({message:n}))continue;const e=n.message.content;if(Array.isArray(e))for(const n of e)"image"===n.type&&t++}return t}function estimateConversationTokens({messages:e}){let t=0;for(const n of e)isHiddenTranscriptMessage({message:n})||(t+=estimateTokens(n.message));return t}function buildAutoCompactStatus({tokensUsed:e,tokenLimit:t}){const n=e/t,r=[{tier:1,threshold:En.TIER_1_THRESHOLD,description:`Prune to last ${En.TIER_1_KEEP_COUNT} tool calls`},{tier:2,threshold:En.TIER_2_THRESHOLD,description:`Prune to last ${En.TIER_2_KEEP_COUNT} tool calls`},{tier:3,threshold:En.TIER_3_THRESHOLD,description:"Full summarization"}];let o=0;const s=r.map(r=>{const s=Math.round(r.threshold*t),i=Math.max(0,s-e);let a="upcoming";return n>=r.threshold&&(a="passed",o=r.tier),{tier:r.tier,threshold:r.threshold,tokensAt:s,description:r.description,status:a,tokensAway:i}}),i=s.findIndex(e=>"upcoming"===e.status);return{tiers:-1!==i?s.map((e,t)=>t===i?{...e,status:"current"}:e):s,currentTier:o,keepRecentTokens:En.KEEP_RECENT_TOKENS}}function getPrimaryTip({percentage:e,conversationPct:t}){return e>=90?"Tier 3 auto-compact imminent — /compact now to control what gets summarized":e>=80?"Auto-compact Tier 3 triggers at 90% — /compact to free space before it kicks in":t>60&&e>40?`${t}% is conversation — /compact to reclaim tokens`:e>=50?"/compact to free space · /model to switch models":null}function getSecondaryTip({mcpToolCount:e,imageCount:t,messageCount:n,percentage:r}){return e>0&&r>30?`${e} MCP tools loaded — disconnect unused servers to save tokens`:t>0&&r>30?`${t} image${t>1?"s":""} in context — images use ~1.5k tokens each`:n>50&&r>40?`${n} messages — consider starting a new session for a fresh context`:null}function generateTips({percentage:e,conversationTokens:t,totalTokens:n,mcpToolCount:r,messageCount:o,imageCount:s}){if(0===n)return[];const i=getPrimaryTip({percentage:e,conversationPct:Math.min(100,Math.round(t/n*100))}),a=getSecondaryTip({mcpToolCount:r,imageCount:s,messageCount:o,percentage:e}),l=[];return i&&l.push(i),a&&l.push(a),0===l.length&&l.push("/compact to summarize and free context · /model to switch models"),l}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,o=process.env.HOME??"",s=o&&n.path.startsWith(o)?`~${n.path.slice(o.length)}`:n.path;t.push({name:n.description,tokens:r,source:s})}return t}function collectBuiltInTools(){const e=[];for(const t of pT){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 gT){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??{}),o=estimateTokens(`${e.name} ${e.description??""} ${r}`);t.push({name:e.name,tokens:o,source:n.name})}return t}async function collectSkillItems(){const[e,{names:t}]=await Promise.all([loadAllSkillSummaries(),loadDisabledSkills()]);return deduplicateSkills({project:e.project.filter(e=>!t.has(e.name)),global:e.global.filter(e=>!t.has(e.name))}).map(e=>({name:e.name,tokens:estimateTokens(`${e.name} ${e.description}`)}))}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=e.getSystemPromptBreakdown(),r=getConfiguredModel(),o=getContextLimit(r),s=e.getHistory(),i=countMessagesByRole({messages:s}),a=countToolCalls({messages:s}),l=countImages({messages:s}),u=estimateConversationTokens({messages:s}),d=collectBuiltInTools(),m=collectMcpTools(),[g,h,f]=await Promise.all([collectSkillItems(),collectAgentItems(),collectMemoryItems()]),y=sumTokens(d),w=sumTokens(m),S=sumTokens(g),E=sumTokens(h),v=sumTokens(f),C=t>0,k=n?n.memory:v,T=null!==n&&Math.abs(v-n.memory)>50,_=n?n.taste:0,x=y+w+S+E,A=C?t:u+x+k+_,P=!C&&s.length>0,I=Math.min(A/o*100,100),M=Math.max(0,o-A),N=[];if(A>0){const e=n?n.systemPrompt:Math.max(0,A-u-x-k-_);if(e>0&&N.push({name:BA,tokens:e,detail:n?"identity":"identity + taste"}),k>0&&N.push({name:"Memory",tokens:k,detail:T?"memory files (modified, refreshes next request)":"memory files"}),_>0&&N.push({name:"Taste",tokens:_,detail:"taste.md"}),y>0&&N.push({name:"System tools",tokens:y,detail:`${d.length} built-in`}),w>0){const e=Array.from(new Set(m.map(e=>e.source).filter(e=>"string"==typeof e)));let t=`${m.length} tools`;e.length>3&&(t=`${e.length} servers`),e.length>=1&&e.length<=3&&(t=e.join(", ")),N.push({name:"MCP",tokens:w,detail:t})}S>0&&N.push({name:"Skills",tokens:S,detail:`${g.length} loaded`}),E>0&&N.push({name:"Subagents",tokens:E,detail:`${h.length} loaded`});const r=e+k+_+x,o=C?Math.max(0,t-r):u;o>0&&N.push({name:qA,tokens:o,detail:`${i.user} user · ${i.assistant} assistant`})}N.sort((e,t)=>e.name===BA?-1:t.name===BA||e.name===qA?1:t.name===qA?-1:t.tokens-e.tokens);const R=s.length>0?s[0]?.meta.timestamp??null:null;return{tokensUsed:A,tokenLimit:o,percentage:I,tokensRemaining:M,isEstimated:P,model:r,breakdown:N,autoCompact:buildAutoCompactStatus({tokensUsed:A,tokenLimit:o}),stats:{messageCount:s.length,userMessages:i.user,assistantMessages:i.assistant,toolCalls:a.calls,toolResults:a.results,imageCount:l,sessionStartTime:R},tips:generateTips({percentage:I,conversationTokens:u,totalTokens:A,mcpToolCount:m.length,messageCount:s.length,imageCount:l})}}function formatK(e){if(e<1e3)return String(e);if(e>=1e6){const t=Math.round(e/1e5)/10;return Number.isInteger(t)?`${t}M`:`${t.toFixed(1)}M`}const t=e/1e3;return Number.isInteger(t)?`${t}k`:`${t.toFixed(1)}k`}function formatBreakdownValue(e){return e<1e3?String(e):`${(e/1e3).toFixed(1)}k`}function getLayoutSizes({terminalWidth:e}){const t=Math.max(20,e),n=Math.min(50,Math.max(30,Math.floor(.5*t)));return{labelWidth:16,progressBarWidth:Math.max(10,Math.min(n,t-10)),showBreakdownDetail:t>=70}}function ContextProgress({analysis:e,progressBarWidth:t}){const n=getUsageColor(e.percentage),r=buildBlockBar({percentage:e.percentage,width:t});return re.createElement(K,{flexDirection:"column"},re.createElement(K,{marginBottom:1},re.createElement(K,{flexShrink:0},re.createElement(Y,{backgroundColor:gr.BLUE,color:"#f4f4f4",bold:!0},`${p_}CONTEXT${p_}`)),re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:gr.GRAY},getModelDisplayName(e.model))),re.createElement(K,null,re.createElement(Y,{color:n},r.filled),re.createElement(Y,{color:Tr},r.empty),re.createElement(Y,{bold:!0,color:n},` ${e.percentage.toFixed(1)}%`)),re.createElement(K,null,re.createElement(Y,null,formatK(e.tokensUsed)),re.createElement(Y,{color:gr.GRAY},` / ${formatK(e.tokenLimit)}`),re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:n},formatK(e.tokensRemaining)),re.createElement(Y,{color:gr.GRAY}," remaining"),e.isEstimated&&re.createElement(Y,{color:gr.DIM}," (estimated)")))}function CompactionDistance({analysis:e}){if(e.percentage<40)return null;const t=e.autoCompact.tiers.find(e=>3===e.tier);if(!t||"passed"===t.status)return null;const{tokensAway:n}=t;let r=gr.GRAY;return n<=5e4&&(r=gr.YELLOW),n<=2e4&&(r=gr.RED),re.createElement(K,{marginTop:1},re.createElement(Y,{color:r},`~${formatK(n)}`),re.createElement(Y,{color:gr.DIM}," until auto-compact"))}function BreakdownRow({item:e,labelWidth:t,numWidth:n,showDetail:r}){return re.createElement(K,null,re.createElement(Y,null,e.name.padEnd(t)),re.createElement(Y,{bold:!0},formatBreakdownValue(e.tokens).padStart(n)),re.createElement(Y,{color:gr.GRAY}," tokens"),r&&e.detail&&re.createElement(Y,{color:gr.DIM},` · ${e.detail}`))}function ContextBreakdown({analysis:e,labelWidth:t,showBreakdownDetail:n}){const r=e.breakdown.filter(e=>e.tokens>0);if(0===r.length)return null;const o=Math.max(4,...r.map(e=>formatBreakdownValue(e.tokens).length));return re.createElement(K,{flexDirection:"column",marginTop:1},r.map(e=>re.createElement(BreakdownRow,{key:e.name,item:e,labelWidth:t,numWidth:o,showDetail:n})))}function ContextTips({tips:e}){return 0===e.length?null:re.createElement(K,{flexDirection:"column",marginTop:1},e.map(e=>re.createElement(K,{key:e},re.createElement(Y,{color:gr.CYAN},Me.pointer),re.createElement(Y,{color:gr.GRAY}," ",e))))}function ContextMessage({analysis:e}){const t=getLayoutSizes({terminalWidth:useTerminalWidth()});return re.createElement(K,{flexDirection:"column",paddingTop:1},re.createElement(ContextProgress,{analysis:e,progressBarWidth:t.progressBarWidth}),re.createElement(CompactionDistance,{analysis:e}),re.createElement(ContextBreakdown,{analysis:e,labelWidth:t.labelWidth,showBreakdownDetail:t.showBreakdownDetail}),re.createElement(ContextTips,{tips:e.tips}))}function ContextConfigView({staticKey:e,contextEngineRef:t,setShowContextView:n,setInput:r}){const[o,s]=se(null),[i,a]=se(null);return ae(()=>{let e=!0;return __name(async()=>{if(t.current)try{const n=await analyzeContext({contextEngine:t.current});e&&s(n)}catch{e&&a("Failed to analyze context.")}else e&&a("No active conversation. Start chatting first.")},"load")(),()=>{e=!1}},[t]),Z((e,t)=>{t.escape&&(WE(),r(""),n(!1))}),re.createElement(re.Fragment,null,re.createElement(Bx,{staticKey:e}),re.createElement(K,{flexDirection:"column",width:"100%"},i?re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:hr,bold:!0},"Context"),re.createElement(Y,{color:gr.DIM},i)):o?re.createElement(ContextMessage,{analysis:o}):re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:hr,bold:!0},"Context"),re.createElement(Y,{color:gr.DIM},"Loading context analysis...")),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press Esc to return to conversation"))))}__name(countMessagesByRole,"countMessagesByRole"),__name(countToolCalls,"countToolCalls"),__name(countImages,"countImages"),__name(estimateConversationTokens,"estimateConversationTokens"),__name(buildAutoCompactStatus,"buildAutoCompactStatus"),__name(getPrimaryTip,"getPrimaryTip"),__name(getSecondaryTip,"getSecondaryTip"),__name(generateTips,"generateTips"),__name(collectMemoryItems,"collectMemoryItems"),__name(collectBuiltInTools,"collectBuiltInTools"),__name(collectMcpTools,"collectMcpTools"),__name(collectSkillItems,"collectSkillItems"),__name(collectAgentItems,"collectAgentItems"),__name(sumTokens,"sumTokens"),__name(analyzeContext,"analyzeContext"),GE(),Ut(),io(),jr(),__name(formatK,"formatK"),__name(formatBreakdownValue,"formatBreakdownValue"),__name(getLayoutSizes,"getLayoutSizes"),__name(ContextProgress,"ContextProgress"),__name(CompactionDistance,"CompactionDistance"),__name(BreakdownRow,"BreakdownRow"),__name(ContextBreakdown,"ContextBreakdown"),__name(ContextTips,"ContextTips"),__name(ContextMessage,"ContextMessage"),jr(),__name(ContextConfigView,"ContextConfigView"),Ut(),Ut(),kn(),Hs(),jS(),$o(),bo(),co();var zA="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,o=0;try{const r=await loadAllSkillSummaries();e=r.global.length,t=r.project.length;const{names:o}=await loadDisabledSkills();n=[...r.global,...r.project].filter(e=>o.has(e.name)).length}catch{}try{const e=await loadAllAgents();r=e.personal.length,o=e.project.length}catch{}return{personalSkills:e,projectSkills:t,disabledSkills:n,personalAgents:r,projectAgents:o}}function execGitAsync(e){return new Promise(t=>{Te("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(!O(e))return!1;try{return(await I(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=O(n),o=r||await hasTasteMdFiles(e);let s=!0;try{s=await isTasteLearningEnabled()}catch{}return{fileExists:o,filePath:r?n:e,learningEnabled:s}}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=L_(S.platform()),t=J_(),n=X_(),r=Z_()}catch{e="Unknown",t="Unknown",n="Unknown",r="N/A"}return{cwd:process.cwd(),os:e,arch:S.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:S.arch(),shell:"Unknown",terminal:"Unknown",nodeVersion:process.version,ide:null,proxy:null}),[n,r,o,s,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,disabledSkills: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:o,skillsAgents:s,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 formatSkillsValue(e){const{personal:t,project:n,disabled:r}=e,o=t+n;return 0===o?"None":0===r?formatCountValue(t,n):`${o-r} active · ${r} off · (${t} user, ${n} project installed)`}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"),Ut(),kn(),Jb(),jr(),uo(),__name(formatCountValue,"formatCountValue"),__name(formatSkillsValue,"formatSkillsValue"),__name(formatSystemValue,"formatSystemValue");var WA=__name(({label:e,value:t,valueColor:n,dimValue:r})=>re.createElement(K,null,re.createElement(Y,{dimColor:!0},`${e}:`.padEnd(14)),r?re.createElement(Y,{dimColor:!0},t):re.createElement(Y,{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}`,o=t.git.branch||"N/A",s=t.git.worktreePath?toRelativePath(t.git.worktreePath):null,i=t.auth.authenticated?Me.tick:Me.cross,a=t.auth.authenticated?gr.WHITE:Cr.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 re.createElement(K,{flexDirection:"column",paddingX:0},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Command Code"," "),re.createElement(Y,{dimColor:!0},n)),re.createElement(K,null,re.createElement(Y,{dimColor:!0},"Visit "),re.createElement(ao,{url:zA,text:zA,color:gr.CYAN}),re.createElement(Y,{dimColor:!0}," for usage and billing")),re.createElement(K,{marginTop:1},re.createElement(Y,{dimColor:!0},"Account:".padEnd(14)),t.auth.authenticated&&t.auth.username?re.createElement(re.Fragment,null,re.createElement(ao,{url:`https://commandcode.ai/${t.auth.username}/`,text:t.auth.username,color:gr.CYAN}),re.createElement(Y,{color:a}," ",i)):t.auth.authenticated?re.createElement(re.Fragment,null,re.createElement(Y,null,"Authenticated"),re.createElement(Y,{color:a}," ",i)):re.createElement(re.Fragment,null,re.createElement(Y,{color:Cr.WARNING},"Not signed in"),re.createElement(Y,{color:a}," ",i),re.createElement(Y,{dimColor:!0}," — run "),re.createElement(Y,{bold:!0},"/login"))),re.createElement(WA,{label:"Model",value:r}),re.createElement(WA,{label:"Branch",value:o,dimValue:!t.git.branch}),s?re.createElement(WA,{label:"Worktree",value:s}):null,t.git.remoteUrl?re.createElement(K,null,re.createElement(Y,{dimColor:!0},"Repository:".padEnd(14)),re.createElement(ao,{url:t.git.remoteHttpUrl||`https://github.com/${t.git.remoteUrl}`,text:t.git.remoteUrl,color:gr.CYAN}),t.pr?re.createElement(re.Fragment,null,re.createElement(Y,{dimColor:!0}," · "),re.createElement(ao,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?gr.CYAN:gr.GRAY}),re.createElement(Y,{dimColor:!0}," ","(",t.pr.state.toLowerCase(),")")):null):t.pr?re.createElement(K,null,re.createElement(Y,{dimColor:!0},"Pull Request:".padEnd(14)),re.createElement(ao,{url:t.pr.url,text:`#${t.pr.number}`,color:"OPEN"===t.pr.state?gr.CYAN:gr.GRAY}),re.createElement(Y,{dimColor:!0}," (",t.pr.state.toLowerCase(),")")):null,re.createElement(WA,{label:"Taste",value:d,dimValue:!t.taste.fileExists}),re.createElement(WA,{label:"Directory",value:toRelativePath(t.system.cwd)}),re.createElement(WA,{label:"Skills",value:formatSkillsValue({personal:t.skillsAgents.personalSkills,project:t.skillsAgents.projectSkills,disabled:t.skillsAgents.disabledSkills}),dimValue:0===l}),re.createElement(WA,{label:"Agents",value:formatCountValue(t.skillsAgents.personalAgents,t.skillsAgents.projectAgents),dimValue:0===u}),re.createElement(WA,{label:"System",value:formatSystemValue({system:t.system})}),t.system.proxy?re.createElement(WA,{label:"Proxy",value:t.system.proxy}):null)}function StatusConfigView({staticKey:e,setShowStatusView:t,setInput:n}){const[r,o]=se({phase:"loading"});return ae(()=>{let e=!1;return gatherStatusData().then(t=>{e||o({phase:"ready",data:t})}).catch(t=>{if(e)return;const n=t instanceof Error?t.message:"Failed to gather status";o({phase:"error",message:n})}),()=>{e=!0}},[]),Z((e,r)=>{r.escape&&(n(""),t(!1))}),re.createElement(re.Fragment,null,re.createElement(Bx,{staticKey:e}),re.createElement(K,{flexDirection:"column",width:"100%"},"ready"===r.phase?re.createElement(StatusMessage,{statusData:r.data}):"error"===r.phase?re.createElement(Y,{dimColor:!0},"Could not load status: ",r.message):re.createElement(Y,{dimColor:!0},"Gathering status…"),re.createElement(K,{marginTop:1},re.createElement(Y,{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:o}=e;return o<=r?0:t<n?t:t>=n+r?t-r+1:n}function getSuggestionBase(e){const n=resolveDirectoryPath(e),r=/[\\/]$/.test(e),o=e.replace(/\\/g,"/");if(o.endsWith("/."))return{searchDirectory:n,prefix:".",outputPrefix:`${o.slice(0,-1)}`};if(r)return{searchDirectory:n,prefix:"",outputPrefix:o};const s=o.lastIndexOf("/");return-1===s?{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:""}:{searchDirectory:t.dirname(n),prefix:t.basename(n),outputPrefix:o.slice(0,s+1)}}function getDirectorySuggestions(e){const t=e.trim();if(!t)return[];try{const{searchDirectory:e,prefix:n,outputPrefix:r}=getSuggestionBase(t),o=n.startsWith(".")||r.includes("/.");return D.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>!!o||!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"),Ut(),Ut(),jo(),Ut(),jo(),__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"),jr(),zr();var HA=__name(({onClose:e})=>{const[t,n]=se(""),[r,o]=se(null),[s,i]=se([]),[a,l]=se(getAdditionalDirectories()),[u,d]=se({zone:"input",suggestionIndex:0,activeDirIndex:0}),[m,g]=se(0);ae(()=>{i(t?getDirectorySuggestions(t):[]),d(e=>({...e,zone:"input"})),g(0)},[t]),ae(()=>{if(!r||"success"!==r.tone)return;const e=setTimeout(()=>{o(null)},5e3);return()=>clearTimeout(e)},[r]);const h=__name(e=>{const t=addDirectory(e);"error"!==t.status?"skipped"!==t.status?(o({tone:"success",text:`Added ${t.displayPath} to directory scope`}),n(""),l(getAdditionalDirectories()),d({zone:"input",suggestionIndex:0,activeDirIndex:0})):o({tone:"warning",text:t.message}):o({tone:"error",text:t.message})},"submitPath"),f=__name(e=>{if(!removeAdditionalDirectory(e))return o({tone:"error",text:`${formatDirectoryForDisplay(e)} is no longer in workspace scope`}),void l(getAdditionalDirectories());o({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");Z((t,r)=>{if(r.escape)e();else{if(r.return)return"suggestions"===u.zone&&s[u.suggestionIndex]?void h(s[u.suggestionIndex]):void 0;if((r.delete||r.backspace)&&"active-dir"===u.zone&&a[u.activeDirIndex])f(a[u.activeDirIndex]);else{if(r.tab&&s.length>0){const e=s[u.suggestionIndex]??s[0];return void(e&&(n(e),d(e=>({...e,zone:"input"})),o(null)))}r.downArrow?d(e=>moveFocusDown(e,{suggestionCount:s.length,activeDirCount:a.length})):r.upArrow&&d(e=>moveFocusUp(e,{suggestionCount:s.length,activeDirCount:a.length}))}}}),ae(()=>{"suggestions"===u.zone&&g(e=>getAdjustedSuggestionOffset({selectedIndex:u.suggestionIndex,currentOffset:e,maxVisible:8,totalSuggestions:s.length}))},[u,s.length]),ae(()=>{d(e=>"suggestions"===e.zone&&e.suggestionIndex>=s.length?{...e,zone:"input",suggestionIndex:Math.max(0,s.length-1)}:"active-dir"===e.zone&&e.activeDirIndex>=a.length?{...e,zone:"input",activeDirIndex:Math.max(0,a.length-1)}:e)},[s.length,a.length]);const y=s.slice(m,m+8),w=getFooterText({focusZone:u.zone});return re.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:gr.CYAN,paddingX:1,paddingY:0},re.createElement(Y,{bold:!0,color:gr.CYAN},"Add directory to workspace"),re.createElement(Y,{color:gr.GRAY},"Command Code will be able to read files in this directory and make edits when accept edits mode is on."),re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:gr.GRAY},"Added directories"),0===a.length?re.createElement(Y,{color:gr.GRAY}," None yet"):a.map((e,t)=>{const n="active-dir"===u.zone&&u.activeDirIndex===t;return re.createElement(Y,{key:e,color:n?gr.YELLOW:gr.GREEN,bold:n},n?` ${Me.pointer} `:" ",formatDirectoryForDisplay(e))})),re.createElement(K,{marginTop:1},re.createElement(Y,{bold:!0,color:gr.WHITE},"Path")),re.createElement(K,null,re.createElement(TextInput,{value:t,focus:"input"===u.zone,prefix:`${"input"===u.zone?Me.pointer:" "} `,prefixColor:"input"===u.zone?gr.CYAN:gr.GRAY,onChange:e=>{n(e),o(null)},onSubmit:h})),!t&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.GRAY},"Examples: ../shared ~/docs /abs/path")),r&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:{error:gr.RED,warning:gr.YELLOW,success:gr.GREEN}[r.tone]},r.text)),s.length>0&&re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:gr.GRAY},"Suggestions"),y.map((e,t)=>{const n=m+t,r="suggestions"===u.zone&&u.suggestionIndex===n;return re.createElement(Y,{key:e,color:r?gr.CYAN:gr.GRAY,bold:r},r?` ${Me.pointer} `:" ",e)})),re.createElement(K,{marginTop:1},re.createElement(BracketedText,{text:w,color:gr.DIM})))},"AddDirModal");Ut(),Ut(),kn(),Ut(),Ut(),kn(),jr();var GA=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),VA=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),QA=__name(({config:e,onSaveComplete:n,viewOnly:r=!1})=>{const[o,s]=se("idle"),[i,a]=se(""),l=[...pT.map(e=>e.name),...gT.map(e=>e.name)],u=__name(async()=>{if(!e.agentType||!e.sysPrompt)return s("error"),void a("Agent configuration is incomplete");s("saving");try{const r="personal"===e.location?GA():VA();await k.mkdir(r,{recursive:!0});const o=`${e.agentType}.md`,s=t.join(r,o),i=Array.from(e.selectedTools).map(e=>yT[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 k.writeFile(s,u,"utf-8"),n(e.agentType)}catch(e){console.error("Error saving agent:",e),s("error"),a(e instanceof Error?e.message:"Unknown error occurred")}},"handleSaveAgent");Z((e,t)=>{r||!t.return||"idle"!==o&&"error"!==o||u()});const d=Array.from(e.selectedTools).map(e=>yT[e]||e).join(", "),m="personal"===e.location?`~/.commandcode/agents/${e.agentType}`:`.commandcode/agents/${e.agentType}`;return re.createElement(K,{flexDirection:"column",gap:1},re.createElement(K,{flexDirection:"column"},re.createElement(K,{gap:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"Name:"),re.createElement(Y,{color:gr.GRAY},e.agentType)),re.createElement(K,{gap:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"Location:"),re.createElement(Y,{color:gr.GRAY},m)),re.createElement(K,{gap:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"Tools:"),re.createElement(Y,{color:gr.GRAY},0===e.selectedTools.size?"None":e.selectedTools.size===l.length?"*":d))),re.createElement(K,{gap:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"Description"),re.createElement(Y,{color:gr.GRAY},"(Tells ","Command Code"," when to use this agent):")),re.createElement(Y,{color:gr.GRAY},e.ccToolDefinition),re.createElement(K,{gap:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"System Prompt:")),re.createElement(Y,{color:gr.GRAY},e.sysPrompt),!r&&re.createElement(K,{marginTop:1},"idle"===o&&re.createElement(K,{gap:1},re.createElement(Y,{color:gr.GREEN,dimColor:!0},"Press"),re.createElement(Y,{color:gr.GREEN,bold:!0},"Enter"),re.createElement(Y,{color:gr.GREEN,dimColor:!0},"to save • Esc to cancel")),"saving"===o&&re.createElement(Y,{color:gr.YELLOW},"Saving agent..."),"saved"===o&&re.createElement(Y,{color:gr.GREEN},Me.tick," ",i),"error"===o&&re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.RED},Me.cross," Error: ",i),re.createElement(Y,{color:gr.GRAY},"Press Enter to retry"))))},"AgentSummary");jr();var KA=__name(({agent:e,onBack:t,setRevalidateAgent:n,isReadOnly:r=!1})=>{const[o,s]=se("menu"),i=[...pT.map(e=>e.name),...gT.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=>wT[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?s("view"):"edit"===e.value?s("edit"):"delete"===e.value&&s("delete")},"handleMenuSelect"),m=[{label:"1. Yes, delete",value:"confirm-delete"},{label:"2. No, cancel",value:"cancel"}],g=__name(async r=>{if("confirm-delete"===r.value)try{await k.unlink(e.filePath),n(!0),t()}catch(e){console.error(`Failed to delete agent: ${e}`),s("menu")}else s("menu")},"handleDeleteSelect");return Z((e,n)=>{if(n.escape)"menu"===o?t():s("menu");else if(n.return&&"view"===o)s("menu");else if(1===e.length&&e>="1"&&e<="9"){const t=Number(e)-1;if("menu"===o){const e=u[t];e&&d(e)}else if("delete"===o){const e=m[t];e&&g(e)}}}),"view"===o?re.createElement(K,{flexDirection:"column"},re.createElement(QA,{config:l,onSaveComplete:()=>s("menu"),viewOnly:!0}),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.GRAY},"Press Enter to go back"))):"edit"===o?re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.YELLOW},"Edit functionality coming soon..."),re.createElement(Y,{color:gr.GRAY},"Press Esc to go back")):"delete"===o?re.createElement(K,{flexDirection:"column",gap:1},re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.RED},"Delete agent"),re.createElement(Y,{color:gr.GRAY},"Are you sure you want to delete the agent ",e.name,"?")),re.createElement(K,null,re.createElement(gt,{items:m,onSelect:g,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY,backgroundColor:e?xr:void 0,bold:e},` ${t} `)}))):re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.WHITE,bold:!0},e.name),re.createElement(K,{marginTop:1},re.createElement(gt,{items:u,onSelect:d,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY,backgroundColor:e?xr:void 0,bold:e},` ${t} `)})),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.GRAY},"Press ↑↓ to navigate · Enter to select · Esc to go back")))},"AgentDetails");jr();var YA=__name(({handleSelect:e,createdAgentName:n})=>{const[r,o]=se([]),[s,i]=se([]),[a,l]=se([]),[u,d]=se(!0),[m,g]=se(!1),[h,f]=se(null),[y,w]=se(!1),[E,v]=se(0),[C,T]=se(0),_=useTerminalHeight(),x=__name(()=>t.join(S.homedir(),".commandcode","agents"),"getRootAgentDir"),A=__name(()=>t.join(process.cwd(),".commandcode","agents"),"getLocalAgentDir"),P=__name(async(e,n)=>{try{g(!1);const r=(await k.readdir(e)).filter(e=>e.endsWith(".md"));return(await Promise.all(r.map(async r=>{try{const o=t.join(e,r),s=await k.readFile(o,"utf-8"),{data:i,content:a}=je(s);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:o}}catch(e){return console.error(`Error loading agent from ${r}:`,e),null}}))).filter(e=>null!==e)}catch{return[]}},"loadAgentsFromDirectory");ae(()=>{__name(async()=>{d(!0);const[e,t]=await Promise.all([P(x(),"personal"),P(A(),"project")]),n=jk.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}`}));o(e),i(t),l(n),d(!1)},"loadAgents")()},[m]);const I=[{label:"Create new agent",value:"create_new_agent"}];r.forEach(e=>{I.push({label:e.name,value:e.filePath})}),s.forEach(e=>{I.push({label:e.name,value:e.filePath})});const M=r.length+s.length,N=(r.length>0?1:0)+(s.length>0?1:0),R=__name(e=>0===e?"action":e<=r.length?"user":"project","sectionOf"),$=_-1,L=Math.max(4,$-11-a.length-2*N),D=__name(t=>{if("create_new_agent"===t.value)e(t);else{const e=[...r,...s].find(e=>e.filePath===t.value);e&&(f(e),w(!0))}},"handleAgentSelect");if(Z((e,t)=>{if(t.upArrow)v(e=>Math.max(0,e-1));else if(t.downArrow)v(e=>Math.min(I.length-1,e+1));else if(t.return){const e=I[E];e&&D(e)}},{isActive:!u&&!y}),ae(()=>{v(e=>Math.min(e,Math.max(0,I.length-1)))},[I.length]),ae(()=>{T(e=>clampScrollOffset({cursor:E,total:I.length,maxVisible:L,currentOffset:e}))},[E,I.length,L]),u)return re.createElement(Y,{color:gr.GRAY},"Loading agents...");if(y&&h){const e=h.filePath.startsWith("__builtin__:");return re.createElement(KA,{agent:h,onBack:()=>{w(!1),f(null)},setRevalidateAgent:g,isReadOnly:e})}const O=C,F=C+L,U=I.slice(O,F),j=I.length>L;let B=null;return re.createElement(K,{flexDirection:"column"},re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.WHITE,bold:!0},"Agents"),M>0?re.createElement(Y,{color:gr.GRAY}," ","(",M," agent",M>1?"s":"",")"):re.createElement(Y,{color:gr.GRAY}," (No custom agents)")),n&&re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{color:gr.GREEN,dimColor:!0},"Created agent: ",n)),re.createElement(K,{flexDirection:"column"},U.map((e,t)=>{const n=O+t,r=R(n),o="action"!==r&&r!==B;B=r;const s=n===E,i="user"===r?"User agents":"Project agents";return re.createElement(re.Fragment,{key:e.value},o&&re.createElement(K,{marginTop:0===t?0:1},re.createElement(Y,{color:Tr,bold:!0},i)),re.createElement(K,null,re.createElement(Y,{color:s?gr.WHITE:gr.GRAY,backgroundColor:s?xr:void 0,bold:s},e.label," ")))})),j&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",O+1,"–",Math.min(F,I.length)," of ",I.length,O>0?" · ↑ more":"",F<I.length?" · ↓ more":"")),a.length>0&&re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:Tr,bold:!0},"Default agents"),a.map(e=>re.createElement(Y,{key:e.filePath,color:gr.DIM},e.name.charAt(0).toUpperCase()+e.name.slice(1)))),re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(Y,{color:gr.DIM},"Create specialized subagents that Command Code can delegate to."),re.createElement(Y,{color:gr.DIM},"Each subagent has its own context window, custom system prompt, and specific tools.")))},"ManageAgents");Ut(),kn(),Ys(),jr(),Ut(),Ut(),kn(),jr();var JA=__name(({onSelect:e})=>re.createElement(gt,{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})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY},` ${t}`)}),"LocationSelector");Ut(),zr(),kn(),Kr(),Zr(),jr();var XA=__name(({step:e,agentType:t,sysPrompt:n,ccToolDefinition:r,onAgentTypeChange:o,onSysPromptChange:s,onCCToolDefinitionChange:i,onAgentTypeSubmit:a,onSysPromptSubmit:l,onCCToolDefinitionSubmit:u})=>{const[d,m]=se(!1),[g,h]=se(!1),f=ce(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?s(e):t.cleanedContent&&s(t.cleanedContent))}s(e)}}else if(m(!0),t.isPasteEnd){m(!1);const e=await detectClipboardText();return void(e?s(e):t.cleanedContent&&s(t.cleanedContent))}},[d,s]),y=ce(async e=>{const t=processBracketedPaste(e);if(!t.isPasteStart||g){if(!g||t.isPasteEnd){if(g&&t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}i(e)}}else if(h(!0),t.isPasteEnd){h(!1);const e=await detectClipboardText();return void(e?i(e):t.cleanedContent&&i(t.cleanedContent))}},[g,i]);return"agentType"===e?re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.WHITE},"Enter a unique identifier for your agent:"),t&&(Object.values(yT).some(e=>Be(e)===Be(t))||Object.keys(yT).some(e=>Be(e)===Be(t)))&&re.createElement(Y,{color:gr.RED},Me.warning," This name conflicts with an existing tool name. Please choose a different name."),t&&isReservedAgentName(Be(t))&&re.createElement(Y,{color:gr.RED},Me.warning," This name is reserved. Reserved names: ",Uk.join(", "))),re.createElement(TextInput,{showCursor:!0,value:t||"",onSubmit:()=>{if(null===t||0===t.trim().length)return;const e=Be(t);Object.values(yT).some(t=>Be(t)===e)||Object.keys(yT).some(t=>Be(t)===e)||isReservedAgentName(e)||a()},onChange:o,placeholder:"e.g. code-reviewer, unit-tester"})):"sysPrompt"===e?re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.WHITE},"Enter the system prompt for your agent:"),re.createElement(Y,{color:gr.GRAY},"Be comprehensive for best results.")),re.createElement(TextInput,{showCursor:!0,value:n||"",onSubmit:()=>{null!==n&&0!==n.trim().length&&l()},onChange:f,placeholder:"You are a helpful coding reviewer..."})):"ccToolDefinition"===e?re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.WHITE},"When should ","Command Code"," use this agent?"),re.createElement(TextInput,{showCursor:!0,value:r,onSubmit:()=>{0!==r.trim().length&&u()},onChange:y,placeholder:"e.g., Use this agent when you are done writing code..."})):null},"ManualFlow");Ut(),jr();var ZA=__name(({onSelect:e})=>re.createElement(gt,{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})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY},e?">":" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY},` ${t}`)}),"MethodSelector");Ut(),zr(),Ut(),HE(),jr();var eP=["·","○","◇","☆","✧","☆","◇","○","⌘"],tP=[12,5,4,4,4,4,4,5,16],nP=[5,4,4,4,4,4,5];function getWaveSymbol(e){const t=e%88;let n=0;for(let e=0;e<tP.length;e++)if(n+=tP[e],t<n)return eP[e];const r=t-58;n=0;for(let e=0;e<nP.length;e++)if(n+=nP[e],r<n)return eP[7-e];return eP[0]}function ShimmerText({text:e,offset:t,bg:n}){const r=le(()=>e.split(""),[e]),o=__name(e=>{const n=e-(t-5);return n>=0&&n<$r.length?$r[n]:Lr},"getCharColor");return re.createElement(Y,null,r.map((e,t)=>re.createElement(Y,{key:`${t}:${e}`,color:o(t),backgroundColor:n},e)))}function CMDIcon({frame:e,color:t}){return re.createElement(Y,{color:t??hr,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 rP=__name(({status:e,timeElapsed:t,tokens:n})=>{const[r,o]=se(0),[s,i]=se(0),a=ie(n);a.current=n;const l=getTerminalWidth(),[u,d]=se(()=>l>=72?"all":l>=42?"medium":"none");ae(()=>{d(e=>"all"===e?l<68?l>=42?"medium":"none":"all":"medium"===e?l>=72?"all":l<38?"none":"medium":l>=72?"all":l>=42?"medium":"none")},[l]),ae(()=>{const e=setInterval(()=>{o(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 m=r%(e.length+10),g="all"===u,h="medium"===u;return BE.statusRender({width:l,layoutMode:u,status:e,frame:r}),re.createElement(K,{width:l,height:1,paddingLeft:0,marginLeft:0},re.createElement(K,{flexShrink:0},re.createElement(Y,{backgroundColor:Er.BG,color:Er.FG}," "),re.createElement(Y,{backgroundColor:Er.BG},re.createElement(CMDIcon,{frame:4*r})),re.createElement(ShimmerText,{text:e,offset:m,bg:Er.BG}),re.createElement(Y,{backgroundColor:Er.BG,color:Er.FG}," ")),g&&re.createElement(K,{columnGap:1,marginLeft:1},re.createElement(Y,{bold:!0,color:gr.GRAY},"esc"),re.createElement(Y,{color:gr.DIM},"to interrupt"),re.createElement(Y,{color:gr.DIM},"•"),re.createElement(Y,{color:gr.DIM},formatTime3(t)),re.createElement(Y,{color:gr.DIM},"•"),re.createElement(Y,{color:gr.GRAY},Me.arrowDown),re.createElement(Y,{color:gr.DIM},formatToken(Math.round(s)))),h&&re.createElement(K,{marginLeft:1},re.createElement(Y,{color:gr.DIM},formatToken(Math.round(s)))))},"Status");Zr(),Kr(),jr();var oP=__name(({description:e,onChange:t,onSubmit:n,loading:r,errorMessage:o})=>{const[s,i]=se(!1),[a,l]=se(0),[u,d]=se(0);ae(()=>{if(!r)return;const e=setInterval(()=>d(e=>e+1),50);return()=>clearInterval(e)},[r]);const m=ce(()=>{0!==e.trim().length&&n()},[e,n]),g=ce(async e=>{const n=processBracketedPaste(e);if(!n.isPasteStart||s){if(!s||n.isPasteEnd){if(s&&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)))}},[s,t]);return re.createElement(K,{flexDirection:"column"},r?re.createElement(K,null,re.createElement(CMDIcon,{frame:u}),re.createElement(Y,{color:gr.WHITE},"Generating agent from description...")):re.createElement(TextInput,{key:a,showCursor:!0,value:e,placeholder:"e.g. Help me review my code...",onChange:g,onSubmit:m}),o&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.RED},`${Me.warning} ${o}`)))},"RecommendedFlow");Ut(),jr();var sP=__name(({selectedTools:e,onToggleTool:t,onToggleCategory:n,onComplete:r})=>{const[o,s]=se(!1),[i,a]=se(0),[l,u]=se(0),d=useTerminalHeight(),m=le(()=>[...pT.map(e=>e.name),...gT.map(e=>e.name)],[]),g=le(()=>[{name:"All tools",tools:m},{name:"Read-only tools",tools:m.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:m.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:m.filter(e=>"shell_command"===e)},{name:"Search tools",tools:m.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:m.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),[m]),h=le(()=>{const e=[];return e.push({type:"continue",value:"continue"}),e.push({type:"divider",value:"divider-1"}),o?(g.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:"}),m.forEach(t=>{e.push({type:"tool",value:t})})):(g.forEach(t=>{e.push({type:"category",value:t.name})}),e.push({type:"divider",value:"divider-2"}),e.push({type:"toggle",value:"show-advanced"})),e},[o,g,e,m]),f=h.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=g.find(e=>e.name===t.value),o=r?.tools.every(t=>e.has(t));return r?.tools.some(t=>e.has(t)),{label:`${o?"[x]":"[ ]"} ${t.value}`,value:n,type:"category"}}return"tool"===t.type?{label:` ${e.has(t.value)?"[x]":"[ ]"} ${yT[t.value]||t.value}`,value:n,type:"tool"}:{label:"",value:n,type:"unknown"}}),y=f.filter(e=>"divider"!==e.type&&"spacer"!==e.type&&"label"!==e.type),w=Math.max(5,d-1-10),S=y[i]?.value??0;ae(()=>{u(e=>clampScrollOffset({cursor:S,total:f.length,maxVisible:w,currentOffset:e}))},[S,f.length,w]);const E=l,v=l+w,C=f.slice(E,v),k=f.length>w;return Z((e,l)=>{if(l.upArrow)a(e=>{const t=e-1;return t<0?y.length-1:t});else if(l.downArrow)a(e=>{const t=e+1;return t>=y.length?0:t});else if(l.return||" "===e){const e=y[i];if(e){const i=h[e.value];if(!i)return;"continue"===i.type?r():"toggle"===i.type?(s(!o),a(0)):"category"===i.type?n(i.value):"tool"===i.type&&t(i.value)}}}),re.createElement(K,{flexDirection:"column"},C.map(e=>{const t=y.findIndex(t=>t.value===e.value),n=-1!==t&&t===i;if("divider"===e.type)return re.createElement(K,{key:`divider-${e.value}`},re.createElement(Y,{color:gr.GRAY}," ",e.label));if("spacer"===e.type)return re.createElement(K,{key:`spacer-${e.value}`,height:1});if("label"===e.type)return re.createElement(K,{key:`label-${e.value}`},re.createElement(Y,{color:gr.GRAY}," ",e.label));const r="continue"===e.type;return re.createElement(K,{key:`item-${e.value}`},re.createElement(Y,{color:n?gr.WHITE:gr.GRAY,bold:r&&n},n?">":" "," ",e.label))}),k&&re.createElement(K,null,re.createElement(Y,{color:gr.GRAY}," ","Showing ",E+1,"–",Math.min(v,f.length)," of"," ",f.length,E>0?" · ↑ more":"",v<f.length?" · ↓ more":"")),re.createElement(K,{marginTop:1},e.size===m.length&&re.createElement(Y,{color:gr.GRAY},"All tools selected"),e.size>0&&e.size<m.length&&re.createElement(Y,{color:gr.GRAY},e.size," tools selected"),0===e.size&&re.createElement(Y,{color:gr.GRAY},"No tools selected")))},"ToolsSelector");Eo(),LS(),vS(),Gs(),YE(),co();var iP=__name(({onComplete:e})=>{const[t,n]=se("location"),[r,o]=se(!1),[s,i]=se(null),[a,l]=se("agentType"),u=le(()=>[...pT.map(e=>e.name),...gT.map(e=>e.name)],[]),d=__name(()=>({location:null,method:null,agentType:null,sysPrompt:null,ccToolDefinition:"",recommendedMethodDescription:"",selectedTools:new Set(u)}),"getInitialConfig"),[m,g]=se(d()),h=__name(t=>{n("location"),l("agentType"),g(d()),e(t)},"resetToDefaults"),f=__name(()=>{if("location"===t)return"Choose location";if("method"===t)return"Creation method";if("configuration"===t){if("recommended"===m.method)return"Describe what this agent should do and when it should be used (be comprehensive for best results)";if("agentType"===a)return"Agent type (identifier)";if("sysPrompt"===a)return"System prompt";if("ccToolDefinition"===a)return"Description (Tell Command Code when to use this agent)"}return"tools"===t?"Select tools":"summary"===t?"Confirm and save":""},"getSubText"),y=__name(e=>{g({...m,location:e}),n("method")},"handleLocationSelect"),w=__name(e=>{g({...m,method:e}),n("configuration")},"handleMethodSelect"),S=__name(async()=>{try{i(null),o(!0);const e=await getConfiguredProvider(),t=await isOAuthEnforced(),{token:r,oauthProvider:s}=await getOAuthCredentials({provider:e});validateOAuthToken({token:r,provider:e});const a={[zt.INTERNAL_TEAM_FLAG_HEADER]:t.toString()};r&&(a[zt.OAUTH_TOKEN]=`Bearer ${r}`,s&&(a[zt.OAUTH_PROVIDER]=s));const l=getApiBaseUrl(),u=new rS({baseUrl:l}),d=parseModelString(getConfiguredModel()).modelId,h=await u.post({headers:a,endpoint:Wt.ALPHA.AGENT.GENERATE,body:{description:m.recommendedMethodDescription,model:d}});g({...m,agentType:Be(h.agentName),sysPrompt:h.systemPrompt,ccToolDefinition:h.toolDescription}),n("tools")}catch(e){if(e instanceof Ls&&400===e.status&&e.message?.toLowerCase().includes("insufficient credits")){const e=await getBillingLink({billingLink:null,setBillingLink:__name(()=>{},"setBillingLink")})??"https://commandcode.ai/billing";i(`You have insufficient credits to make this request. Please purchase more credits to continue using Command Code: ${e}`)}else i("An error occurred while generating the agent. Please try again.")}finally{o(!1)}},"handleRecommendedSubmit"),E=__name(()=>{g({...m,agentType:Be(m.agentType)}),l("sysPrompt")},"handleManualAgentTypeSubmit"),v=__name(()=>{l("ccToolDefinition")},"handleManualSysPromptSubmit"),C=__name(()=>{n("tools")},"handleManualCCToolDefinitionSubmit"),k=__name(()=>{n("summary")},"handleToolsComplete"),T=__name(e=>{const t=new Set(m.selectedTools);t.has(e)?t.delete(e):t.add(e),g({...m,selectedTools:t})},"handleToggleTool"),_=__name(e=>{const t=[{name:"All tools",tools:u},{name:"Read-only tools",tools:u.filter(e=>"read_file"===e||"read_directory"===e||"read_multiple_files"===e||"grep"===e)},{name:"Edit tools",tools:u.filter(e=>"edit_file"===e||"write_file"===e)},{name:"Execution tools",tools:u.filter(e=>"shell_command"===e)},{name:"Search tools",tools:u.filter(e=>"web_search"===e||"web_fetch"===e)},{name:"Other tools",tools:u.filter(e=>!["read_file","read_directory","read_multiple_files","grep","edit_file","write_file","shell_command","web_search","web_fetch"].includes(e))}].find(t=>t.name===e);if(!t)return;const n=new Set(m.selectedTools);t.tools.every(e=>n.has(e))?t.tools.forEach(e=>n.delete(e)):t.tools.forEach(e=>n.add(e)),g({...m,selectedTools:n})},"handleToggleCategory");return re.createElement(K,{flexDirection:"column",gap:1},re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.WHITE,bold:!0},"Create new agent"),re.createElement(Y,{color:gr.GRAY},f())),re.createElement(K,null,"location"===t&&re.createElement(JA,{onSelect:y}),"method"===t&&re.createElement(ZA,{onSelect:w}),"configuration"===t&&"recommended"===m.method&&re.createElement(oP,{description:m.recommendedMethodDescription,onChange:e=>g({...m,recommendedMethodDescription:e}),loading:r,errorMessage:s,onSubmit:S}),"configuration"===t&&"manual"===m.method&&re.createElement(K,{flexDirection:"column",gap:1},re.createElement(XA,{step:a,agentType:m.agentType,sysPrompt:m.sysPrompt,ccToolDefinition:m.ccToolDefinition,onAgentTypeChange:e=>g({...m,agentType:e}),onSysPromptChange:e=>g({...m,sysPrompt:e}),onCCToolDefinitionChange:e=>g({...m,ccToolDefinition:e}),onAgentTypeSubmit:E,onSysPromptSubmit:v,onCCToolDefinitionSubmit:C})),"tools"===t&&re.createElement(sP,{selectedTools:m.selectedTools,onToggleTool:T,onToggleCategory:_,onComplete:k}),"summary"===t&&re.createElement(QA,{config:m,onSaveComplete:h})))},"AgentNew"),aP=__name(({onCancel:e})=>{const[t,n]=se(null),[r,o]=se(null),s=__name(e=>{n(e.value),o(null)},"handleSelect");return Z((t,n)=>{n.escape&&e()}),re.createElement(K,{width:"100%",flexDirection:"column"},null===t&&re.createElement(YA,{handleSelect:s,createdAgentName:r}),"create_new_agent"===t&&re.createElement(iP,{onComplete:e=>{o(e),n(null)}}))},"AgentsConfig");jr(),Ut(),co(),jr();var lP=[{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."}],cP=__name(({onSelect:e,onCancel:t})=>{const[n,r]=se(null);ae(()=>{loadUserConfig().then(e=>{r(e.compactMode??"default")})},[]);const o=__name(t=>{e(t.value)},"handleSelect");if(Z((e,n)=>{n.escape&&t()}),null===n)return null;const s=lP.findIndex(e=>e.value===n);return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Select a compact mode to compact sessions")),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"Choose how Command Code handles automatic context compaction.")),re.createElement(gt,{items:lP,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>{const r=lP.find(e=>e.label===t),o=r?.value===n,s=lP.findIndex(e=>e.label===t),i=e?xr:void 0;return re.createElement(K,{flexDirection:"column"},re.createElement(K,null,re.createElement(Y,{color:e||!o?gr.WHITE:gr.GREEN,backgroundColor:i,bold:e},` ${s+1}. ${r?.label??t} `),o&&re.createElement(Y,{color:gr.GREEN}," ",Me.tick)),re.createElement(Y,{color:e?gr.WHITE:gr.DIM,backgroundColor:i},` ${r?.description??""} `))}}),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press "),re.createElement(Y,{color:gr.DIM,bold:!0},"Esc"),re.createElement(Y,{color:gr.DIM}," to cancel")))},"CompactModeSelector");Ut(),kn(),io(),bo(),co(),yo(),Ut(),kn(),jr();var uP=__name(({model:e,providerId:t,isHighlighted:n,isCurrent:r,showProviderLabel:o,showDefaultBadge:s=!0})=>{const i=yn[t],a=o??i?.showProviderLabelInSelector??!1,l=e.vendorLabel??hn[e.provider],u=s&&e.id===gn,d="free"===e.badge,m=u?`${e.label} (default)`:e.label,g=d?" (FREE)":"",h=" ".repeat(Math.max(0,32-m.length-g.length)),f=n?xr:void 0,y=e.description?`${a?`${l} · `:""}${e.description}`:"",w=useTerminalWidth()>=70&&y;return re.createElement(K,null,re.createElement(Y,{backgroundColor:f,color:r?gr.GREEN:gr.WHITE},m),d&&re.createElement(Y,{backgroundColor:f,color:gr.GREEN,bold:!0},g),w&&re.createElement(re.Fragment,null,re.createElement(Y,{backgroundColor:f},h),re.createElement(Y,{backgroundColor:f,color:gr.DIM},y)),re.createElement(Y,{backgroundColor:f,color:gr.GREEN},r?` ${Me.tick} `:" "))},"ModelRow");jr();var dP=__name(e=>[{text:e.name,weight:100},{text:e.label,weight:50},{text:e.provider,weight:25},{text:e.description||"",weight:10}],"MODEL_SEARCH_FIELDS");function searchGroups(e,t){if(!t.trim())return e;const n=[];for(const r of e){const e=fuzzyFilter(r.models,t,dP);e.length>0&&n.push({...r,models:e})}return n}function groupByModelProvider(e,t){return groupModelsByDisplayOrder(e).map(e=>({providerId:t,label:e.label,models:e.models}))}__name(searchGroups,"searchGroups"),__name(groupByModelProvider,"groupByModelProvider");var mP=__name(({featureLabel:e,defaultLabel:t,currentModelId:n,onPick:r,onBack:o})=>{const[s,i]=se(""),a=le(()=>isInternalTeamFlagEnforced(),[]),[l,u]=se(()=>getCachedBillingContext());ae(()=>{if(l)return;let e=!0;return getBillingContext().then(t=>{e&&u(t)}),()=>{e=!1}},[l]);const d=null!==l,m=le(()=>a?wn:groupByModelProvider(Sn.flatMap(e=>e.models),yn["command-code"].id),[a]),g=le(()=>l?m.map(e=>({...e,models:e.models.filter(e=>checkModelAccess({model:{id:e.id,provider:e.provider,name:e.name},planId:l.planId,purchasedCredits:l.purchasedCredits,freeCredits:l.freeCredits}).allowed)})).filter(e=>e.models.length>0):[],[m,l]),h=le(()=>searchGroups(g,s),[g,s]),f=le(()=>{const e=[];for(const t of h)for(const n of t.models)e.push({kind:"model",providerId:t.providerId,model:n});return[{kind:"reset"},...e]},[h]),y=le(()=>{if(!n)return 0;const e=f.findIndex(e=>"model"===e.kind&&e.model.id===n);return e>=0?e:0},[f,n]),{cursor:w}=useListNavigation({items:f,initialIndex:y,searchCursorIndex:1,searchQuery:s,onSearchChange:i,onSelect:__name(e=>{d&&r("reset"===e.kind?void 0:e.model.id)},"onSelect"),onCancel:o}),[S,E]=se(0),v=useTerminalHeight()-1,C=Math.max(4,v-11-2*h.length);ae(()=>{E(e=>clampScrollOffset({cursor:w,total:f.length,maxVisible:C,currentOffset:e}))},[w,f.length,C]);const k=S,T=S+C,_=0===k;let x=1;const A=h.map(e=>{const t=sliceSectionForWindow({section:e.models,sectionBase:x,windowStart:k,windowEnd:T});return x+=e.models.length,{group:e,groupWindow:t}}).filter(e=>e.groupWindow.rows.length>0),P=f.length>C;return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},e," › select model")),re.createElement(K,{marginBottom:1},re.createElement(Y,{dimColor:!0},"Pick a model for this task, or reset it to the default.")),isCmdZdrEnabled()&&re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.YELLOW},"Your pick is saved but stays paused until CMD_ZDR is unset.")),re.createElement(K,{marginBottom:2,flexDirection:"column",width:"100%"},re.createElement(TA,{query:s,resultCount:s?f.length-1:void 0,placeholder:"Type to search models..."})),d?re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"column"},_&&re.createElement(K,{flexDirection:"column"},re.createElement(Y,{bold:!0,dimColor:!0},"Default"),re.createElement(K,null,re.createElement(Y,{backgroundColor:0===w?xr:void 0,color:n?gr.WHITE:gr.GREEN},t," "),!n&&re.createElement(Y,{color:gr.GREEN},Me.tick))),A.map(({group:e,groupWindow:t},r)=>re.createElement(K,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:0!==r||_?1:0},re.createElement(Y,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>re.createElement(uP,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===w,isCurrent:r.id===n,showProviderLabel:!!a&&void 0,showDefaultBadge:!1}))))),P&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",k+1,"–",Math.min(T,f.length)," of"," ",f.length,k>0?" · ↑ more":"",T<f.length?" · ↓ more":""))):re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"Loading available models…")),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"type to search · ↑/↓ navigate · enter select"),s?re.createElement(Y,{color:gr.DIM}," · esc to clear"):re.createElement(Y,{color:gr.DIM}," · esc back")))},"FeatureModelPicker");function sanitizeFeatureOverrides(e){const t={};for(const{key:n}of Zk){const r=e?.[n];"string"==typeof r&&r&&(t[n]=r)}return t}__name(sanitizeFeatureOverrides,"sanitizeFeatureOverrides");var pP=__name(({onClose:e})=>{const[t,n]=se(null),[r,o]=se(null),[s,i]=se(null);ae(()=>{loadUserConfig().then(e=>{n(sanitizeFeatureOverrides(e.featureModels))})},[]);const a=r?"picker":"list",{cursor:l}=useListNavigation({items:Zk,initialIndex:0,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,isActive:"list"===a&&null!==t,onSelect:__name(e=>{i(null),o(e.key)},"onSelect"),onCancel:e,onReset:__name(async e=>{try{await setFeatureModel({feature:e.key,model:void 0}),n(t=>{const n={...t??{}};return delete n[e.key],n}),i({text:`${e.label} reset to default`})}catch{i({text:`Couldn't reset ${e.label} — try again`,error:!0})}},"onReset")});if(null===t)return null;const u=Zk.find(e=>e.key===r)??null;if("picker"===a&&u)return re.createElement(mP,{featureLabel:u.label,defaultLabel:getFeatureDefaultLabel(u),currentModelId:t[u.key],onBack:()=>o(null),onPick:async e=>{try{await setFeatureModel({feature:u.key,model:e}),n(t=>{const n={...t??{}};return void 0===e?delete n[u.key]:n[u.key]=e,n}),i({text:void 0===e?`${u.label} reset to default`:`${u.label} → ${getModelDisplayName(e)}`})}catch{i({text:`Couldn't save ${u.label} — try again`,error:!0})}o(null)}});const d=isCmdZdrEnabled();return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Configure models")),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"Pick a model for each task. Applies to all sessions."," ",createOSC8Link("https://commandcode.ai/docs/troubleshooting/faqs#why-do-i-see-small-background-requests","Why background requests?",!1))),d&&re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.YELLOW},"Model overrides were reverted to ZDR safe defaults. Your overrides will be restored when CMD_ZDR is unset.")),Zk.map((e,n)=>{const r=t[e.key],o=e.defaultLabel?`Default (${getFeatureDefaultLabel(e)})`:`Uses current model (${getFeatureDefaultLabel(e)})`,s=r?getModelDisplayName(r):null,i=!!r&&!d,a=i&&s?s:o,u=n===l;return re.createElement(K,{key:e.key},re.createElement(Y,{backgroundColor:u?xr:void 0,color:gr.WHITE},e.label.padEnd(20)),re.createElement(Y,{backgroundColor:u?xr:void 0},re.createElement(Y,{color:i?gr.GREEN:gr.DIM},a),s&&d&&re.createElement(Y,{color:gr.DIM},` · ${s} paused`)))}),s&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:s.error?gr.RED:gr.GREEN},s.text)),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"↑/↓ navigate · enter to change · r to reset · esc to close")))},"ConfigureModelsSelector");function settingsFilePaths(e){return[getProjectLocalPath(e),getProjectSharedPath(e),getUserSettingsPath()]}function readInputSettings(e){try{const t=L.readFileSync(e,"utf-8");return parseJSON(t)?.input}catch{return}}function shouldCollapsePastedText(e=process.cwd()){for(const t of settingsFilePaths(e)){const e=readInputSettings(t)?.collapsePastedText;if("boolean"==typeof e)return e}return!0}Ut(),jr(),Ut(),zr(),kn(),Kr(),Ut(),Eo(),__name(settingsFilePaths,"settingsFilePaths"),__name(readInputSettings,"readInputSettings"),__name(shouldCollapsePastedText,"shouldCollapsePastedText"),Qn(),Ut();var gP=n(E(),"commandcode-images"),hP={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};function saveTempImage(e,t){try{O(gP)||B(gP,{recursive:!0});const r=hP[e.mediaType]||".png",o=`image-${t}-${Date.now()}${r}`,s=n(gP,o),i=Buffer.from(e.data,"base64");return q(s,i),s}catch{return null}}function stripInputAfterSuffix(e,t){return t&&e.endsWith(t)?e.slice(0,e.length-t.length):e}function extractAppendedChunk(e,t,n){const r=t+n;return e.length>=r.length&&e.startsWith(r)?e.slice(r.length):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:o,setDetectedContent:s,incrementInputKey:i,setInitialCursor:a,collapsePastedText:l=!0}=e,u=ce((e,t,n="")=>{o(t=>[...t,e]),r(t+n),a(t.length),i()},[o,r,a,i]),d=ie(!1),m=ie(""),g=ie(null),h=ie(""),f=ie(""),y=ce(async(e,t,o)=>{let d=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n");const m=await detectDroppedImageFile(d);if(m)return void u(m,t,o);const g=await detectClipboardImage();if(g)return void u(g,t,o);let h=d;if(0===h.length){const e=await detectClipboardText();h=e?e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"):""}if(!h&&!o)return;if(!h)return r(t+o),a(t.length),void i();if(l&&h.length>300){const e=t+`[Text#${n.length+1}]`;return s(e=>[...e,h]),r(e+o),a(e.length),void i()}const f=t+h;r(f+o),a(f.length),i()},[u,n.length,s,r,a,i,l]),w=ce(()=>{g.current&&clearTimeout(g.current),g.current=setTimeout(async()=>{if(d.current){const e=m.current,t=h.current,n=f.current;m.current="",h.current="",f.current="",d.current=!1,g.current=null,e?await y(e,t,n):n&&await y("",t,n)}},500)},[y]);return{handlePaste:ce(async e=>{const n=processBracketedPaste(e);if(n.isPasteStart&&n.isPasteEnd)return d.current&&(d.current=!1,m.current="",h.current="",f.current="",g.current&&(clearTimeout(g.current),g.current=null)),await y(n.pastedContent??n.cleanedContent,n.textBeforePaste??"",n.textAfterPaste??""),!0;if(n.isPasteStart&&!d.current){d.current=!0;const e=n.textBeforePaste??t,r=t.slice(e.length);h.current=e,f.current=r;const o=n.pastedContent??n.cleanedContent;return m.current=stripInputAfterSuffix(o,r),w(),!0}if(d.current&&!n.isPasteEnd){const e=h.current,t=f.current;if(void 0!==n.pastedContent)m.current=stripInputAfterSuffix(n.pastedContent,t);else if(n.cleanedContent){const r=extractAppendedChunk(n.cleanedContent,e,t);m.current=null!==r?m.current+r:accumulateDelta(n.cleanedContent,m.current,e)}return w(),!0}if(d.current&&n.isPasteEnd){g.current&&(clearTimeout(g.current),g.current=null);const e=h.current,t=f.current,r=n.textAfterPaste??"";let o=n.cleanedContent??"";if(r&&o.endsWith(r)&&(o=o.slice(0,o.length-r.length)),void 0!==n.pastedContent)m.current=stripInputAfterSuffix(n.pastedContent,t);else if(o){const n=extractAppendedChunk(o,e,t);m.current=null!==n?m.current+n:accumulateDelta(o,m.current,e)}const s=m.current,i=e,a=r||t;return m.current="",h.current="",f.current="",d.current=!1,await y(s,i,a),!0}if(n.isPasteEnd&&!n.isPasteStart&&!d.current)return!0;const r=e.slice(t.length);if(r.length>0){const e=await detectDroppedImageFile(r);if(e)return u(e,t),!0}return!1},[t,y,w,u]),resetPasteState:ce(()=>{d.current=!1,m.current="",h.current="",f.current="",g.current&&(clearTimeout(g.current),g.current=null)},[]),isPasting:ce(()=>d.current,[])}}function useExternalEditor({input:e,setInput:t,setInputKey:n,detectedContent:r,setDetectedContent:o,onEditorClose:s}){const[i,a]=se(!1),[l,u]=se(null),d=ce(async()=>{if(!i){a(!0),u(null);try{let i=e.replace(/\n+$/,"");r.forEach((e,t)=>{const n=`[Text#${t+1}]`;i.includes(n)&&(i=i.replace(n,e))});const a=await openInEditor2(i);t(a),o([]),n(e=>e+1),s?.()}catch(e){u(e instanceof T_?"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{a(!1)}}},[e,t,n,r,o,s,i]),m=ce(()=>{u(null)},[]);return{isEditorOpen:i,editorError:l,handleOpenInEditor:d,clearEditorError:m}}__name(saveTempImage,"saveTempImage"),mr(),Eo(),Ut(),Zr(),Kr(),__name(stripInputAfterSuffix,"stripInputAfterSuffix"),__name(extractAppendedChunk,"extractAppendedChunk"),__name(accumulateDelta,"accumulateDelta"),__name(useBracketedPaste,"useBracketedPaste"),Zr(),Ut(),__name(useExternalEditor,"useExternalEditor"),Ut();var fP=__name((e={})=>{const{enabled:t=!0}=e,[n,r]=se(null),o=ie(!1);return ae(()=>{if(!t||o.current)return;let e=!0;return o.current=!0,v_().then(t=>{e&&r(t)}),()=>{e=!1}},[t]),{pr:n}},"usePRDetection");jr(),Ut(),Ut();var yP=1e5,wP=null,SP=new Map;function memoKey(e,t){return`${e}\0${t}`}function memoize(e,t){if(SP.size>=128){const e=SP.keys().next().value;void 0!==e&&SP.delete(e)}return SP.set(e,t),t}function loadGitignore(e){const t=ot(),r=n(e,".gitignore");if(O(r))try{t.add(U(r,"utf8"))}catch{}return t.add(".git"),t}function isIgnored(e,t,n){return!!e.ignores(t)||n&&e.ignores(`${t}/`)}function listDirectory(e,t){const r=loadGitignore(t),o=[],i=W(e,{withFileTypes:!0});for(const a of i){const i=n(e,a.name),l=a.isDirectory();isIgnored(r,s(t,i),l)||o.push({name:a.name,path:i,isDirectory:l})}return sortDirectoriesFirst(o)}function sortDirectoriesFirst(e){return e.sort((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name))}function buildFileIndex(e){const t=loadGitignore(e),r=[],o=[{dirPath:e,depth:0}];for(let i=0;i<o.length;i++){const{dirPath:a,depth:l}=o[i];if(r.length>=yP)break;let u;try{u=W(a,{withFileTypes:!0})}catch{continue}for(const i of u){if(r.length>=yP)break;const u=n(a,i.name),d=s(e,u),m=i.isDirectory();isIgnored(t,d,m)||(r.push({name:d,path:u,isDirectory:m,nameLower:d.toLowerCase(),filenameLower:i.name.toLowerCase(),depth:l+1}),m&&"node_modules"!==i.name&&l<8&&o.push({dirPath:u,depth:l+1}))}}return r}function getFileIndex(e){if(wP&&wP.basePath===e&&Date.now()-wP.builtAt<3e4)return wP.entries;const t=buildFileIndex(e);return wP={basePath:e,entries:t,builtAt:Date.now()},SP.clear(),t}function invalidateFileIndex(){wP=null,SP.clear()}function compareByRelevance(e,t,n){const r=e.nameLower===n,o=t.nameLower===n;if(r&&!o)return-1;if(!r&&o)return 1;const s=e.filenameLower.includes(n),i=t.filenameLower.includes(n);return s&&!i?-1:!s&&i?1:e.depth!==t.depth?e.depth-t.depth:e.name.localeCompare(t.name)}function searchIndex(e,t){const n=e.toLowerCase(),r=[];for(const e of getFileIndex(t)){if(!e.nameLower.includes(n))continue;if(50===r.length&&compareByRelevance(e,r[r.length-1],n)>=0)continue;let t=0,o=r.length;for(;t<o;){const s=t+o>>1;compareByRelevance(e,r[s],n)<0?o=s:t=s+1}r.splice(t,0,e),r.length>50&&r.pop()}return r.map(({name:e,path:t,isDirectory:n})=>({name:e,path:t,isDirectory:n}))}function searchFiles(e,t=process.cwd()){if(!e.trim())return[];const r=memoKey(t,e),o=SP.get(r);if(o)return o;if(e.endsWith("/"))try{return memoize(r,listDirectory(n(t,e),t).map(e=>({...e,name:s(t,e.path)})).slice(0,50))}catch{}if(e.includes("/")){const o=e.split("/"),i=(o.pop()||"").toLowerCase();try{return memoize(r,listDirectory(n(t,o.join("/")),t).filter(e=>!i||e.name.toLowerCase().includes(i)).map(e=>({...e,name:s(t,e.path)})).slice(0,50))}catch{}}return memoize(r,searchIndex(e,t))}__name(memoKey,"memoKey"),__name(memoize,"memoize"),__name(loadGitignore,"loadGitignore"),__name(isIgnored,"isIgnored"),__name(listDirectory,"listDirectory"),__name(sortDirectoriesFirst,"sortDirectoriesFirst"),__name(buildFileIndex,"buildFileIndex"),__name(getFileIndex,"getFileIndex"),__name(invalidateFileIndex,"invalidateFileIndex"),__name(compareByRelevance,"compareByRelevance"),__name(searchIndex,"searchIndex"),__name(searchFiles,"searchFiles"),jr();var bP=__name(({onSelectFile:e,onClose:t,searchQuery:n=""})=>{const[o,s]=se(process.cwd()),[i,l]=se([]),[u,d]=se(0),[m,g]=se(0),h=n.trim()?15:10;ae(()=>{invalidateFileIndex()},[]);const f=ce(e=>{try{const t=[];"/"!==e&&t.push({name:"..",path:r(e),isDirectory:!0}),t.push(...listDirectory(e,process.cwd())),l(t),d(0),g(0)}catch{}},[]);ae(()=>{if(n.trim()){const e=searchFiles(n);l(e),d(0),g(0)}else f(o)},[o,f,n]),Z((r,o)=>{if(o.escape)t();else if(o.upArrow)d(e=>{const t=Math.max(0,e-1);return t<m&&g(t),t});else if(o.downArrow)d(e=>{const t=Math.min(i.length-1,e+1);return t>=m+h&&g(t-h+1),t});else{if(o.rightArrow){const e=i[u];if(!e)return;return void(e.isDirectory&&!n.trim()&&s(a(e.path)))}if(o.return){const t=i[u];if(!t)return;return void e(t.path)}}});const y=i.slice(m,m+h);return re.createElement(K,{flexDirection:"column",paddingLeft:1},re.createElement(K,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{color:gr.DIM},n.trim()?`Searching for: "${n}"`:`Files: ${o}`),re.createElement(Y,{color:gr.DIM},n.trim()?"↑↓ navigate • Enter to select • Esc to close":"↑↓ navigate • → to open folder • Enter to select • Esc to close")),0===y.length?re.createElement(Y,{color:gr.DIM},n.trim()?`No files found matching "${n}"`:"No files found in this directory"):y.map((e,t)=>{const n=m+t,r=e.name,o=n===u;return re.createElement(Y,{key:e.path,color:o?gr.GREEN:gr.DIM},e.isDirectory?`${r}/`:r)}))},"FileList");Ut(),kn(),bo(),jr(),Ut(),jr();var EP=__name(e=>{if(e>=1e6){const t=e/1e6;return`${t%1==0?t.toFixed(0):t.toFixed(1)}M`}return`${Math.round(e/1e3)}k`},"formatTokens"),vP=__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&&e.current>=18e4)return re.createElement(K,{paddingRight:3},re.createElement(Y,{color:gr.DIM},"~",EP(e.current)," tokens in context · try"," "),re.createElement(Y,{color:gr.DIM,bold:!0},"/compact"));if(n>20)return null;const r=__name(e=>e>=90?gr.RED:e>=70?gr.YELLOW:gr.DIM,"getColor"),o=t>=90?6:Math.round(t/100*6),s=6-o,i=Me.square.repeat(o),a=Me.squareLightShade.repeat(s),l=r(t);return re.createElement(K,{paddingRight:3},re.createElement(Y,{color:l},`Context left before auto-compact ${n}% `),re.createElement(Y,{color:l},i),s>0&&re.createElement(Y,{color:gr.DIM},a))},"ContextUsage");Ut(),bs(),jr();var CP=__name(()=>{const[e,t]=se("continuous learning"),[n,r]=se(!1),[o,s]=se(!1),i=ie([]),a=ie(0),l=ie(null),u=ie(!1);ae(()=>{const e=__name(e=>"analyzing"===e.type?(u.current=!0,r(!0),s(!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),s(!1),t("continuous learning")))):void 0,"handleNewEvent"),n=__name(()=>{if(a.current>=i.current.length)return r(!1),s(!1),t("continuous learning"),void(i.current=[]);const e=i.current[a.current];t(e.message);const o="learned"===e.type||"refactored"===e.type;s(o);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 BT.on("new-event",e),()=>{BT.off("new-event",e),l.current&&clearTimeout(l.current)}},[]);const d=` ${n?Me.squareSmallFilled:Me.squareSmall} TASTE`,m=9+e.length+d.length>ds;let g=e;g=truncateString(m?{text:e,maxChars:ds}:{text:e,maxChars:ds-d.length-9-10});const h=o?void 0:gr.DIM;return re.createElement(K,{paddingRight:2},!m&&re.createElement(re.Fragment,null,re.createElement(BracketWrap,{color:gr.DIM},"ctrl+t"),re.createElement(Y,{color:gr.DIM}," ")),re.createElement(Y,{color:h},g),!m&&re.createElement(Y,{color:fr.TEXT},d))},"LearningFeedMini");Ut(),jr();var kP=__name(({mode:e,pendingExitKey:t})=>t?re.createElement(Y,{color:gr.DIM},"Press Ctrl+C again to exit"):"bypass"===e?re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:gr.RED},"» permission bypass on "),re.createElement(BracketWrap,{color:gr.DIM},"shift+tab")):"auto-accept"===e?re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:Ir},"» accept edits on "),re.createElement(BracketWrap,{color:gr.DIM},"shift+tab")):"plan"===e?re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:Pr},"plan mode "),re.createElement(BracketWrap,{color:gr.DIM},"shift+tab")):re.createElement(Y,{color:gr.DIM},"? for shortcuts"),"ModeIndicator");Ut(),jr(),uo();var TP=__name(({prInfo:e,showSeparator:t=!0})=>{if(!e)return null;if("OPEN"!==e.state&&"MERGED"!==e.state)return null;const n="OPEN"===e.state?gr.DIM:Mr.MERGED;return re.createElement(re.Fragment,null,t&&re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:n},"PR "),re.createElement(ao,{url:e.url,text:`#${e.number}`,color:n}))},"PRLinkBadge"),_P=__name(({indicator:e,showSeparator:t=!0})=>e?.visible?re.createElement(re.Fragment,null,t&&re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{color:"connected"===e.type?gr.GREEN:gr.YELLOW},e.message)):null,"ConnectionIndicatorBadge"),xP=__name(({termWidth:e,indicatorText:t,isIDEIndicator:n,permissionMode:r="standard",prInfo:o,tasteLearning:s,contextUsage:i,connectionIndicator:a,pendingExitKey:l,updateStatus:u,updateFailedInfo:d,currentProvider:m,showProviderInfo:g,isBashMode:h,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E})=>{const v=e>=60;return re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"column",paddingLeft:2},"auto-accept"!==r&&"plan"!==r&&"bypass"!==r||l?re.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(K,{flexDirection:"row",columnGap:0},n&&!l?re.createElement(Y,{color:kr},t):re.createElement(kP,{mode:r,pendingExitKey:l}),!l&&re.createElement(TP,{prInfo:o}),!l&&re.createElement(_P,{indicator:a})),v&&re.createElement(K,{flexDirection:"column",alignItems:"flex-end"},s&&re.createElement(CP,null),i&&re.createElement(vP,{usage:i}))):re.createElement(re.Fragment,null,re.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(kP,{mode:r}),v&&s&&re.createElement(CP,null)),re.createElement(K,{flexDirection:"row",justifyContent:"space-between",width:e-1},re.createElement(K,{flexDirection:"row",columnGap:0},re.createElement(Y,{color:n?kr:gr.DIM},t),re.createElement(TP,{prInfo:o}),re.createElement(_P,{indicator:a})),v&&i&&re.createElement(vP,{usage:i}))),(u||d||g&&m)&&re.createElement(K,{flexDirection:"row",columnGap:1},u&&re.createElement(Y,null,Me.tick," ","Command Code"," updated:"," ",re.createElement(Y,{color:gr.DIM},"v",u.updatedFrom),re.createElement(Y,{color:gr.DIM}," ",Me.arrowRight," "),re.createElement(Y,null,"v",u.updatedTo)),!u&&d&&re.createElement(Y,{color:gr.YELLOW,dimColor:!0},Me.info," Update available:"," ",d.currentVersion," ",Me.arrowRight," ",d.latestVersion),g&&m&&re.createElement(Y,{color:gr.GREEN,dimColor:!0},Me.bullet," Provider:"," ",getProviderDisplayName(m)))),h&&re.createElement(K,{paddingLeft:2},re.createElement(Y,{color:gr.GREEN},"! for bash mode")),y&&f&&re.createElement(K,{paddingLeft:2},re.createElement(Y,{color:hr},"SHARED: ",f.url," (copied to clipboard)")),w&&re.createElement(K,{paddingLeft:2},re.createElement(Y,{color:w.includes("NOT SHARED")?gr.RED:hr},w)),S&&re.createElement(K,{paddingLeft:2},re.createElement(Y,{color:hr},S)),E&&re.createElement(K,{paddingLeft:2},re.createElement(Y,{color:gr.YELLOW},Me.warning," ",E)))},"BottomIndicator");Ut(),bs(),jr();var AP=__name((e,t)=>e.padEnd(t),"padCell"),PP=__name(e=>e instanceof Error&&e.message?e.message:"Unknown error","getDeleteErrorMessage"),IP=__name(e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),r=Math.floor(n/6e4),o=Math.floor(n/36e5),s=Math.floor(n/864e5);return r<1?"just now":r<60?`${r} min ago`:o<24?`${o}h ago`:`${s}d ago`},"formatRelativeTime"),MP=__name(e=>e.replace(/\s+/g," ").trim(),"normalizeSummary"),NP=__name(e=>truncateString({text:MP(e),maxChars:cs}),"truncateMessage"),RP=__name(e=>e.title?MP(e.title):NP(e.firstMessage),"getSessionSummary"),$P=__name(({onSelectSession:e,onClose:t})=>{const[n,r]=se([]),[o,s]=se(0),[i,a]=se(0),[l,u]=se(!0),[d,m]=se(!1),[g,h]=se(!1),[f,y]=se(null),[w]=se(()=>getCurrentGitBranch()),S=useTerminalHeight(),E=Math.max(6,S-14),v=ce(async()=>{u(!0);const e=await Hk.listSessions();r(e),u(!1)},[]);ae(()=>{v()},[v]);const C=ce(async e=>{try{await Hk.deleteSession(e),h(!1),y(null),s(0),a(0),await v()}catch(e){h(!1),y(`Failed to delete session: ${PP(e)}`)}},[v]),k=d&&w?n.filter(e=>e.gitBranch===w):n;if(Z((n,r)=>{if(g)if(r.return){if(k.length>0&&o<k.length){const e=k[o];C(e.id)}}else h(!1);else if(r.delete||r.ctrl&&"d"===n)k.length>0&&(y(null),h(!0));else{if(!r.escape)return r.ctrl&&"b"===n?(m(e=>!e),s(0),void a(0)):void(r.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):r.downArrow?s(e=>{const t=Math.min(k.length-1,e+1);return t>=i+E&&a(t-E+1),t}):r.return&&k.length>0&&o<k.length&&e(k[o].id));t()}}),l)return re.createElement(K,{flexDirection:"column",paddingLeft:2},re.createElement(Y,{color:gr.GRAY},"Loading sessions..."));if(0===k.length)return re.createElement(K,{flexDirection:"column",paddingLeft:2},re.createElement(Y,{color:gr.GRAY},d&&w?`No sessions found for branch "${w}"`:"No previous sessions found"),re.createElement(Y,{color:gr.DIM},d?"Press ctrl+b to show all branches, ESC to cancel":"Press ESC to go back"));const T=k.slice(i,i+E),_=o<k.length?k[o]:null,x=g&&_?`Delete "${RP(_)}"? Press Enter to confirm, any other key to cancel.`:null;return re.createElement(K,{flexDirection:"column",paddingLeft:1,width:"100%"},re.createElement(Y,{color:gr.CYAN,bold:!0},"Resume Session"),re.createElement(K,{marginTop:1}),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:Tr,bold:!0},AP("#",6),AP("Modified",12),AP("Git Branch",22),AP("Messages",12),"Summary")),re.createElement(K,{flexDirection:"column"},T.map((e,t)=>{const n=i+t,r=o===n,s=truncateString({text:e.gitBranch||"-",maxChars:20});return re.createElement(Y,{key:e.id,color:r?gr.WHITE:gr.GRAY,backgroundColor:r?xr:void 0,bold:r,wrap:"truncate-end"},AP(`${n+1}.`,6),AP(IP(e.lastModified),12),AP(s,22),AP(String(e.messageCount),12),RP(e)," ")})),re.createElement(K,{marginTop:1}),x&&re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.RED},x)),f&&re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.RED},f)),k.length>E&&re.createElement(Y,{color:gr.DIM},"Showing ",i+1,"–",Math.min(i+E,k.length)," ","of ",k.length,i>0?" · ↑ more":"",i+E<k.length?" · ↓ more":""),re.createElement(Y,{color:gr.DIM},"↑↓ navigate · Enter select · Del delete · ctrl+b ",d?`[branch: ${w??"unknown"}]`:"branch filter"," · ESC cancel"))},"SessionsResumeTable");function getImageHintText({selectedIndex:e,imageCount:t,inHistory:n}){return-1!==e?t>1?"← → · Delete to remove · Esc to deselect":"Delete to remove · Esc to deselect":n?"↓ · ↑ imgs":"↑ to select"}function buildImageRows({imageCount:e,rowWidth:t}){const n=[];let r=[],o=0;for(let s=0;s<e;s++){const e=`[Image #${s+1}]`.length,i=e+(r.length>0?1:0);r.length>0&&o+i>t?(n.push(r),r=[s],o=e):(r.push(s),o+=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 o=`[Image #${e+1}]`,s=n?createOSC8Link(`file://${n}`,o,!1):o;return re.createElement(Y,null,r?" ":"",t?re.createElement(Y,{inverse:!0},o):s)}function ImageRowsDisplay({detectedImages:e,selectedImageIndex:t,imageTempPaths:n,termWidth:r,inHistory:o}){if(0===e.length)return null;const s=getImageHintText({selectedIndex:t,imageCount:e.length,inHistory:o}),i=Math.max(1,r-(s.length+2)),a=buildImageRows({imageCount:e.length,rowWidth:i});return re.createElement(K,{flexDirection:"column",width:"100%",alignItems:"flex-end"},a.map((e,r)=>re.createElement(K,{key:r,flexDirection:"row"},re.createElement(K,{flexShrink:0,marginRight:1},0===r&&re.createElement(Y,{color:gr.DIM},s)),re.createElement(K,{flexDirection:"row"},e.map((e,r)=>re.createElement(ImageLabel,{key:e,index:e,isSelected:e===t,filePath:n[e],showSpaceBefore:r>0}))))))}Ut(),jr(),Ut(),__name(getImageHintText,"getImageHintText"),__name(buildImageRows,"buildImageRows"),__name(shouldSelectImageOnUpArrow,"shouldSelectImageOnUpArrow"),__name(nextImageIndex,"nextImageIndex"),__name(prevImageIndex,"prevImageIndex"),__name(removeImageAt,"removeImageAt"),yo(),__name(ImageLabel,"ImageLabel"),__name(ImageRowsDisplay,"ImageRowsDisplay"),Ut();var LP=__name((e={})=>{const{enabled:t=!0,paused:n=!1}=e,[r,o]=se(null),[s,i]=se(!1),a=ie(!1),l=ie(null),u=ie(n),[d,m]=se(!1),[g,h]=se("connected"),f=ie(null),y=ie(null),w=ce((e,t)=>{y.current&&(clearTimeout(y.current),y.current=null),h(e),m(!0),void 0!==t&&(y.current=setTimeout(()=>{m(!1)},t))},[]),S=ce(()=>{y.current&&(clearTimeout(y.current),y.current=null)},[]),E=ce(async(e=!1)=>{if(!a.current){a.current=!0;try{let t=l.current,n=t?.isConnected??!1;if(!n){t?.disconnect(),t=new kk,l.current=t;const r=e?200:500;n=await t.connect(r)}const r=f.current;if(null===r?n&&w("connected",3e3):r!==n&&(n?w("connected",2e3):w("disconnected",5e3)),f.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),o(r)}else o(null)}catch{!0===f.current&&w("disconnected",5e3),f.current=!1,i(!1),o(null),l.current?.disconnect(),l.current=null}finally{a.current=!1}}},[w]);ae(()=>{const e=u.current;u.current=n,e&&!n&&t&&null!==gk()&&E(!1)},[n,t,E]),ae(()=>{if(!t)return;if(null===gk())return;let e=null,n=!1,r=0;function schedule(t){n||(e=setTimeout(()=>{tick(!1)},t))}async function tick(e){if(u.current)return void schedule(500);if(await E(e),n)return;if(l.current?.isConnected)return r=0,void schedule(500);r+=1;const t=Math.min(r,6);schedule(Math.min(3e4,500*2**t)+250*Math.random())}return __name(schedule,"schedule"),__name(tick,"tick"),tick(!0),()=>{n=!0,e&&clearTimeout(e),S(),l.current?.disconnect(),l.current=null}},[t,E,S]);const v=gk(),C={visible:d,message:"connected"===g?`${v?N_[v]??"IDE":"IDE"} ${Me.tick}`:"run /ide",type:g};return{context:r,connected:s,refresh:E,connectionIndicator:C}},"useVSCodeContext");Ut();var DP=__name(e=>{if(!e.activeFile&&!e.selection)return"";const t=["<ide-context>"];if(e.activeFile){const{relativePath:n,language:r,cursor:o}=e.activeFile;t.push(`File: ${n} (${r}, line ${o.line})`)}if(e.selection){const{text:n,startLine:r,endLine:o}=e.selection,s=e.activeFile?.language??"";t.push(`Selected lines ${r}-${o}:`),t.push(`\`\`\`${s}`);const i=n.replace(/```/g,"` ` `").replace(/<\/ide-context>/gi,"&lt;/ide-context&gt;").replace(/[\u202A-\u202E\u2066-\u2069\u200B-\u200D\uFEFF]/g,"");t.push(i),t.push("```")}return t.push("</ide-context>"),t.join("\n")+"\n"},"formatContextForPrompt");function resolvePastedTextTokens({input:e,detectedContent:t}){return t.reduce((e,t,n)=>{const r=`[Text#${n+1}]`;return e.includes(r)?e.replace(r,()=>t):e},e)}Ut(),__name(resolvePastedTextTokens,"resolvePastedTextTokens");var OP=__name((e,t)=>!(!e||!t?.selection&&!t?.activeFile?.relativePath),"hasIDEContext"),FP=__name((e,t,n)=>{const r=e?t?.selection:null;if(r)return`${r.lineCount} lines selected`;const o=e?t?.activeFile:null;if(o?.relativePath){const e=o.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");function getModelShortName(e){const t=findModelById(e);if(t){const e=t.name.toLowerCase().replaceAll(" ","-");return"free"===t.badge?`${e} (free)`:e}return e}function getModelHintLayout(e){const{currentModel:t,terminalWidth:n}=e,r=getCommandMenuDescriptionWidth(n),o=modelSupportsReasoningEffort(t)?getReasoningEffort(t):null,s=o?` with ${o} effort`:"";return{descriptionWidth:r,text:truncateString({text:`${getModelShortName(t)}${s} (current)`,maxChars:r})}}Ut(),io(),co(),bs(),__name(getModelShortName,"getModelShortName"),__name(getModelHintLayout,"getModelHintLayout");var UP=["","","[118;5u"];function removeAltPCharacter(e){return e.includes("π")?e.replace(/π/g,""):null}function isPrecededByWhitespace(e){return!e||" "===e||"\n"===e||"\t"===e}function getCommandMenuStateFromQuery(e){return isDesignSubmenu(e)?{showMenu:!0,query:e}:e.includes(" ")?{showMenu:!1,query:""}:{showMenu:!0,query:e}}__name(removeAltPCharacter,"removeAltPCharacter"),__name(isPrecededByWhitespace,"isPrecededByWhitespace"),__name(getCommandMenuStateFromQuery,"getCommandMenuStateFromQuery");var jP=__name(()=>re.createElement(K,{flexDirection:"column",paddingLeft:1},re.createElement(Y,{color:gr.DIM,bold:!0},"Available Shortcuts:"),re.createElement(K,{columnGap:4},re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.DIM},"! for bash mode"),re.createElement(Y,{color:gr.DIM},"/ for commands"),re.createElement(Y,{color:gr.DIM},"@ for file paths"),re.createElement(Y,{color:gr.DIM},"shift + tab to toggle auto-accept")),re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.DIM},"double tap esc to clear input"),re.createElement(Y,{color:gr.DIM},"ctrl + j / shift + ⏎ for newline"),re.createElement(Y,{color:gr.DIM},"ctrl + g to open in editor"),re.createElement(Y,{color:gr.DIM},"ctrl + z to suspend")))),"ShortcutMenu"),BP=__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:g=!1,tasteUsage:h=!1,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E,updateStatus:v,updateFailedInfo:C,currentProvider:k,currentModel:T,showProviderInfo:_,permissionMode:x="standard",onToggleAutoAccept:A,hintMessage:P,historyManager:I,pendingExitKey:M=null,onOverlayVisibilityChange:N,onDoubleEscapeEmpty:R,onAltP:$,isProcessing:L=!1,ideContextEnabled:D=!0})=>{const[O,F]=se(0),[U,j]=se(!1),[B,q]=se(!1),[z,W]=se(!1),[H,G]=se(!1),[V,Q]=se(""),[J,ee]=se(null),[te,ne]=se(!1),oe=ie(0),ue=ie(0),[de,me]=se([]),[pe,ge]=se([]),[he,fe]=se(-1),[ye,we]=se(""),Se=ie(!1),be=ie(!1),Ee=ie(void 0),[ve,Ce]=se(-1),[ke,Te]=se(""),_e=ie(0),{isEditorOpen:xe,editorError:Ae,handleOpenInEditor:Pe,clearEditorError:Ie}=useExternalEditor({input:e,setInput:n,setInputKey:F,detectedContent:de,setDetectedContent:me,onEditorClose:__name(()=>{Se.current=!1},"onEditorClose")}),Ne=le(()=>shouldCollapsePastedText(),[]),{handlePaste:Re,resetPasteState:$e,isPasting:Le}=useBracketedPaste({input:e,detectedContent:de,setInput:n,setDetectedImages:ge,setDetectedContent:me,incrementInputKey:__name(()=>F(e=>e+1),"incrementInputKey"),setInitialCursor:__name(e=>{Ee.current=e},"setInitialCursor"),collapsePastedText:Ne}),{context:De,connected:Oe,refresh:Fe,connectionIndicator:Ue}=LP({enabled:D,paused:L}),{stdout:je}=X(),Be=je?.columns??80,{pr:qe}=fP();ae(()=>{const e=i||H||te;N?.(e)},[i,H,te,N]);const ze=ce(()=>{ge([]),fe(-1)},[]),We=ce(()=>{G(!1),ee(null)},[]),He=ce(()=>{n(""),q(!1),We(),Q(""),ne(!1),me([]),ze(),we(""),$e(),Ce(-1),Te(""),F(e=>e+1)},[n,$e,ze,We]),Ge=ce(()=>{Se.current=!0;const{text:t,cursor:r}=insertTextAt(e,_e.current,"\n");n(t),Ee.current=r,F(e=>e+1),setTimeout(()=>{Se.current=!1},0)},[e,n]);Z(async(t,r)=>{if(-1!==he&&r.leftArrow)return void fe(prevImageIndex({currentIndex:he,imageCount:pe.length}));if(-1!==he&&r.rightArrow)return void fe(nextImageIndex({currentIndex:he,imageCount:pe.length}));if(r.upArrow){if(i||H||te)return;const t=e.indexOf("\n"),r=-1===t||_e.current<=t;if(shouldSelectImageOnUpArrow({isOnFirstLine:r,imageCount:pe.length,selectedImageIndex:he,historyIndex:ve}))return void fe(pe.length-1);if(-1!==he&&fe(-1),0!==e.length&&-1===ve&&!r)return;const o=I?.count()??0;if(0===o)return;-1===ve&&Te(e);const s=Math.min(ve+1,o-1);return void(s!==ve&&(Ce(s),n(I?.getAt(s)||""),F(e=>e+1)))}if(r.downArrow){if(i||H||te)return;if(-1===ve)return;const t=e.lastIndexOf("\n");if(!(-1===t||_e.current>t))return;const r=ve-1;return Ce(r),n(-1===r?ke:I?.getAt(r)||""),void F(e=>e+1)}if(""===t||r.ctrl&&"c"===t)return void ze();if(isCtrlKey({inputChar:t,key:r,letter:"g",ctrlCode:7}))return Se.current=!0,void Pe();if(getIsExpandToolShortcut(r,t))return Se.current=!0,n(e),F(e=>e+1),void setTimeout(()=>{Se.current=!1},0);if(isNewlineShortcutKey({inputChar:t,key:r,isPasting:Le()}))return be.current=!0,Ge(),void setTimeout(()=>{be.current=!1},0);if(r.meta&&r.backspace)return void He();if(r.meta&&"w"===t)return Se.current=!0,void He();const o=r.ctrl&&"v"===t||UP.includes(t),s=r.meta&&"v"===t;if(o||s){if(o&&"darwin"===process.platform){const t=e;Se.current=!0;const r=await detectClipboardImage();return r&&(ge(e=>[...e,r]),n(t),F(e=>e+1)),void(Se.current=!1)}}else if(!r.ctrl&&!r.meta||"u"!==t){if(r.ctrl&&"z"===t?.toLowerCase())return W(!0),void setTimeout(()=>{process.kill(process.pid,"SIGTSTP")},100);if(-1!==he&&(r.delete||r.backspace)){const{remainingImages:e,nextSelectedIndex:t}=removeImageAt({images:pe,index:he});return ge([...e]),void fe(t)}if(r.escape){if(-1!==he)return void fe(-1);if(H)return;if(te)return ne(!1),n(ye),void F(e=>e+1);const t=Date.now();return t-oe.current<500?(e.length>0?He():R?.(),oe.current=0,ue.current=0):(oe.current=t,U||B||(ue.current=t)),j(!1),void q(!1)}U&&(r.backspace||r.delete)&&0===e.length&&j(!1)}});const Ve=ce(async t=>{if(xe)return;const r=removeAltPCharacter(t);if(null!==r)return n(r),void $?.();const o=processBracketedPaste(t);if((o.isPasteStart||o.isPasteEnd||Le())&&await Re(t))return;if(Se.current)return void(Se.current=!1);-1!==ve&&Ce(-1);const s=1===t.length,l=t.slice(-1);if(s){if("?"===l&&!U)return j(!0),n(""),void F(e=>e+1);if("!"===l&&!B)return j(!1),q(!0),n(""),void F(e=>e+1)}if("/"!==l||H||"/"!==t||(G(!0),Q("")),H)if(t.startsWith("/")){const e=t.substring(1),{showMenu:n,query:r}=getCommandMenuStateFromQuery(e);n?G(!0):We(),Q(r)}else We(),Q("");"@"!==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)}}U&&(t!==e||t.length<e.length)&&j(!1),Ae&&Ie(),0===t.length&&(q(!1),We(),Q(""),ne(!1),me([]),u(""),we(""),$e()),n(t)},[U,e,n,i,a,H,B,pe,ve,Re,$e,$,Ae,Ie,xe,We]),Qe=ce(async()=>{if(Fe(),ue.current=0,U)return void j(!1);const r=e.trim(),o=!B&&r.startsWith("/");let s=r;if(!B&&de.length>0&&(s=resolvePastedTextTokens({input:s,detectedContent:de})),o&&d&&(n(""),"handled"===(await d(s)).status))return I?.add(s),q(!1),We(),Q(""),ze(),me([]),Ce(-1),void Te("");Ce(-1),Te("");let i=[];const a=pe.length>0;!B&&a&&(i=[...pe]),s.length>0&&I?.add(s);const l=De?.selection?{lines:De.selection.lineCount,file:De.activeFile?.relativePath?.split("/").pop()??De.activeFile?.path?.split("/").pop()??"unknown",ide:N_[gk()??""]??"IDE"}:void 0;t({input:s,role:B?"bash":"user",images:i,ideContext:De?DP(De):void 0,ideHint:l}),q(!1),We(),Q(""),ze(),me([])},[t,d,U,e,B,pe,de,I,Fe,ze,We,n]),Ke=ce(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(""),F(e=>e+1)},[n,a,e,i,l,u]),Ye=ce(()=>{a(!1),u("")},[a,u]),Je=ce(e=>{const t=Px.has(e),r="/design"===e.trimEnd();if(t||r){const t=e.trimEnd();n(t+" "),Q(t.substring(1)+" ")}else We(),Q(""),n(e+" ");F(e=>e+1)},[n,We]),Xe=ce(t=>{if("/resume"===t||"/sessions"===t)return I?.add(t),Ce(-1),Te(""),we(e),We(),Q(""),ne(!0),n(""),void F(e=>e+1);if("/design help"===t)return We(),Q(""),n(""),F(e=>e+1),I?.add(t),void d?.("/design help");if(Ax.has(t))return We(),Q(""),I?.add(t),Ce(-1),Te(""),n(""),F(e=>e+1),void d?.(t);const r=Px.has(t),o=Ix.has(t);r?Je(t):(We(),Q(""),o?(I?.add(t),Ce(-1),Te(""),n(""),F(e=>e+1),d?.(t)):(n(t+" "),F(e=>e+1)))},[d,n,e,I,Je,We]),Ze=ce(()=>{We(),Q(""),n(""),Ce(-1),Te(""),F(e=>e+1)},[n,We]),et=ce(e=>{ne(!1),n(""),we(""),Ce(-1),Te(""),F(e=>e+1),d&&d(`/resume:${e}`)},[d,n]),tt=ce(()=>{ne(!1),n(ye),Ce(-1),Te(""),F(e=>e+1)},[ye,n]),nt=ce(e=>{_e.current=e,Ee.current=void 0},[]),rt=le(()=>{const t=qe&&("OPEN"===qe.state||"MERGED"===qe.state);return"auto-accept"===x||"plan"===x||"bypass"===x||Oe||t?!U&&!te:!U&&0===e.length&&!B&&!te},[U,e,B,te,x,Oe,qe]),ot=ie(new Map),st=le(()=>pe.map((e,t)=>{if(ot.current.has(e))return ot.current.get(e)??null;const n=saveTempImage(e,t+1);return ot.current.set(e,n),n}),[pe]),it=__name(()=>U||i||H||te||z?0:rt||M||B?3:4,"getBottomMargin");return re.createElement(K,{width:"100%",flexDirection:"column",marginBottom:it()},!te&&re.createElement(K,{flexDirection:"column",width:"100%"},re.createElement(ImageRowsDisplay,{detectedImages:pe,selectedImageIndex:he,imageTempPaths:st,termWidth:Be,inHistory:-1!==ve}),re.createElement(Y,{color:B?gr.GREEN:gr.GRAY},Me.line.repeat(Be)),(()=>{const t=__name(()=>{if(!be.current)return Date.now()-ue.current<100?(ue.current=0,void Ge()):void(i||H||te||xe||Qe());be.current=!1},"handleTextInputSubmit"),n=__name(n=>re.createElement(TextInput,{key:O,value:e,placeholder:xe?"Save and close the editor to continue...":o,onChange:Ve,onSubmit:t,showCursor:!xe&&r&&-1===he,onCursorChange:nt,initialCursor:Ee.current,prefix:`${B?"!":Me.pointer} `,prefixColor:B?gr.GREEN:gr.WHITE,singleLine:n?.singleLine,maxWidth:n?.maxWidth}),"renderTextInput");if(H&&T&&"/model"===J){const e=getModelHintLayout({currentModel:T,terminalWidth:Be});return re.createElement(K,{flexDirection:"row",width:"100%"},re.createElement(K,{width:25},n({singleLine:!0,maxWidth:25})),re.createElement(K,{width:e.descriptionWidth},re.createElement(Y,{color:gr.DIM,wrap:"truncate"},e.text)))}return n()})(),re.createElement(Y,{color:B?gr.GREEN:gr.GRAY},Me.line.repeat(Be))),U&&re.createElement(jP,null),z&&re.createElement(K,{paddingTop:1},re.createElement(Y,{color:gr.YELLOW},"Command Code has been suspended. Run `fg` to bring\n\t\t\t\t\t\tCommand Code back.")),i&&re.createElement(bP,{onSelectFile:Ke,onClose:Ye,searchQuery:l}),H&&re.createElement(Rx,{onSelectCommand:Xe,onInsertCommand:Je,onClose:Ze,searchQuery:V,onSelectedCommandChange:ee}),te&&re.createElement($P,{onSelectSession:et,onClose:tt}),!H&&(rt||M)&&re.createElement(xP,{termWidth:Be,indicatorText:FP(Oe,De,Be),isIDEIndicator:OP(Oe,De),permissionMode:x,prInfo:qe,tasteLearning:g,contextUsage:m,connectionIndicator:Ue,pendingExitKey:M,updateStatus:v,updateFailedInfo:C,currentProvider:k,showProviderInfo:_,isBashMode:B,shareInfo:f,showShareNotification:y,unshareNotificationMessage:w,tasteNotificationMessage:S,creditWarning:E}),Ae&&re.createElement(K,{paddingLeft:1,flexDirection:"column"},re.createElement(Y,{color:gr.YELLOW},Ae)))},"InputBox");Ut(),bs(),jr();var qP=__name(({messages:e})=>0===e.length?null:re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(K,{marginBottom:0},re.createElement(Y,{color:wr,inverse:!0},` Queued (${e.length}) `)),e.map((e,t)=>re.createElement(K,{key:t},re.createElement(Y,{color:gr.DIM},Me.pointerSmall," "),re.createElement(Y,{color:gr.DIM},truncateString({text:e.displayMessage??e.input,maxChars:80}))))),"QueuedMessages"),zP=re.memo(({queuedMessages:e,isProcessing:t,executionState:n,status:r,input:o,setInput:s,onSubmit:i,showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,outputTokens:g=0,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,currentModel:x,showProviderInfo:A,permissionMode:P,onToggleAutoAccept:I,hintMessage:M,historyManager:N,pendingExitKey:R,onResetPendingExitKey:$,onDoubleEscapeEmpty:L,retryAttempt:D,onAltP:O})=>{const[F,U]=se(0),j=ie(o);return ae(()=>{R&&o!==j.current&&o.length>0&&$?.(),j.current=o},[o,R,$]),ae(()=>{if(!t)return void U(0);const e=setInterval(()=>{U(e=>e+1e3)},1e3);return()=>{clearInterval(e)}},[t]),re.createElement(K,{flexDirection:"column"},re.createElement(qP,{messages:e}),re.createElement(K,{flexDirection:"row",justifyContent:"space-between"},re.createElement(K,{flexDirection:"column"},(t||n.isExecuting)&&null===D&&re.createElement(rP,{tokens:g,timeElapsed:F,status:n.isExecuting?`Executing: ${n.currentCommand}`:r}),M&&re.createElement(K,{marginLeft:1},re.createElement(Y,{color:gr.DIM}," ","⎿"," ","Tip: ",M)))),re.createElement(BP,{input:o,setInput:s,onSubmit:i,placeholder:"Ask your question...",showFileList:a,setShowFileList:l,fileSearchQuery:u,setFileSearchQuery:d,onCommand:m,contextUsage:h,tasteLearning:f,tasteUsage:y,shareInfo:w,showShareNotification:S,unshareNotificationMessage:E,tasteNotificationMessage:v,updateStatus:C,updateFailedInfo:k,creditWarning:T,currentProvider:_,currentModel:x,showProviderInfo:A,permissionMode:P,onToggleAutoAccept:I,hintMessage:M,historyManager:N,pendingExitKey:!R||t||n.isExecuting?null:R,onDoubleEscapeEmpty:L,onAltP:O,isProcessing:t}))});Ut(),iE(),dE(),mo(),bo();var WP=__name(({onComplete:e,onCancel:t})=>{const[n,r]=se(!1),[o,s]=se(""),{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m,cancel:g}=useAuthFlow({onSuccess:__name((t,n)=>{const o=t.userName&&"API Key"!==t.userName&&"Manual API Key"!==t.userName?t.userName:"";s(o),isInternalTeamFlagEnforced()?r(!0):e(!0,o?`Logged in as ${o}`:"Logged in successfully")},"onSuccess"),onFailure:__name((t,n)=>{e(!1,n)},"onFailure"),onCancel:__name(()=>{t()},"onCancel")});return Z((t,r)=>{if(r.ctrl&&"c"===t){if(n)return void e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.");g()}}),n?re.createElement(lo,{onSuccess:()=>{e(!0,o?`Logged in as ${o} with Anthropic`:"Logged in successfully with Anthropic")},onCancel:()=>{e(!0,o?`Logged in as ${o}. Note: Anthropic authentication skipped.`:"Logged in successfully. Note: Anthropic authentication skipped.")},onFailure:t=>{e(!0,o?`Logged in as ${o}. Anthropic auth failed: ${t}`:`Logged in successfully. Anthropic auth failed: ${t}`)}}):re.createElement(lE,{authState:i,statusMessage:a,browserUrl:l,apiKeyInput:u,setApiKeyInput:d,handleApiKeySubmit:m})},"LoginOverlay");function buildOAuthMetadataUrl(e){const t=new g(e),n="/"===t.pathname?"":t.pathname.replace(/\/+$/,"");return t.pathname=`/.well-known/oauth-authorization-server${n}`,t.search="",t.hash="",t.toString()}function buildOidcMetadataUrl(e){const t=new g(e),n=t.pathname.replace(/\/+$/,"");return t.pathname=`${n}/.well-known/openid-configuration`,t.search="",t.hash="",t.toString()}async function tryFetchAsMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return n.authorization_endpoint&&n.token_endpoint?{authorizationEndpoint:n.authorization_endpoint,tokenEndpoint:n.token_endpoint,registrationEndpoint:n.registration_endpoint,scopes:n.scopes_supported}:null}catch(t){return dlog(`[MCP] OAuth metadata fetch failed for ${e}`,t),null}}async function discoverOAuthMetadataFromIssuer(e){return await tryFetchAsMetadata(buildOAuthMetadataUrl(e))||await tryFetchAsMetadata(buildOidcMetadataUrl(e))}async function discoverOAuthMetadata(e){const t=new g(e),n=`${t.protocol}//${t.host}`;return await tryFetchAsMetadata(`${n}/.well-known/oauth-authorization-server`)||await tryFetchAsMetadata(`${n}/.well-known/openid-configuration`)}function parseResourceMetadataUrl(e){if(!e)return null;const t=e.match(/resource_metadata\s*=\s*"([^"]+)"|resource_metadata\s*=\s*([^\s,]+)/i);return t?t[1]??t[2]??null:null}async function fetchProtectedResourceMetadata(e){try{const t=await fetchWithTimeout(e,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)return null;const n=await t.json();return{authorizationServers:n.authorization_servers,scopesSupported:n.scopes_supported}}catch(e){return dlog("[MCP] Protected resource metadata fetch failed",e),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:OS,capabilities:{},clientInfo:FS}})});if(401===t.status||403===t.status){const n=parseResourceMetadataUrl(t.headers?.get?.("www-authenticate")??null);if(n){const e=await fetchProtectedResourceMetadata(n),t=e?.authorizationServers?.[0];if(t){const n=await discoverOAuthMetadataFromIssuer(t);if(n)return e?.scopesSupported&&(n.scopes=e.scopesSupported),{requiresAuth:!0,metadata:n}}}return{requiresAuth:!0,metadata:await discoverOAuthMetadata(e)||void 0}}return{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}async function discoverAndAuthenticate({serverName:e,serverUrl:t,onStatus:n}){const r=n??(()=>{});r("Probing server for OAuth requirements...");const o=await checkServerAuthRequirements(t);if(o.error)return{success:!1,error:o.error};if(!o.requiresAuth)return{success:!1,error:"Server does not require authentication"};if(!o.metadata)return{success:!1,error:"Server returned 401 but did not advertise OAuth metadata. Add `oauth` config manually via `mcp add-json`."};const{authorizationEndpoint:s,tokenEndpoint:i,registrationEndpoint:a,scopes:l}=o.metadata;if(!a)return{success:!1,error:"Server requires pre-registered OAuth credentials (no Dynamic Client Registration endpoint advertised). Register an OAuth client with the server, then add it via `mcp add-json` with an `oauth.clientId` field."};const u=`http://${rb}:${nb}/callback`;r("Registering OAuth client...");const d=await registerOAuthClient({registrationEndpoint:a,clientName:FS.name,redirectUris:[u]});if(!d)return{success:!1,error:"Dynamic client registration failed at "+a};const m={authorizationUrl:s,tokenUrl:i,clientId:d.clientId,clientSecret:d.clientSecret,scopes:l},g=await performOAuthFlow(e,t,m,{onStatus:n});return g.success&&(await storeDiscoveredClient(e,{authorizationUrl:s,tokenUrl:i,clientId:d.clientId,scopes:l}),d.clientSecret?await storeClientSecret(e,d.clientSecret):await deleteClientSecret(e)),g}Ut(),Ut(),QS(),BS(),JS(),KS(),ZS(),cb(),pb(),gb(),Ut(),pb(),gb(),HS(),lb(),Ut(),tb(),BS(),rr(),__name(buildOAuthMetadataUrl,"buildOAuthMetadataUrl"),__name(buildOidcMetadataUrl,"buildOidcMetadataUrl"),__name(tryFetchAsMetadata,"tryFetchAsMetadata"),__name(discoverOAuthMetadataFromIssuer,"discoverOAuthMetadataFromIssuer"),__name(discoverOAuthMetadata,"discoverOAuthMetadata"),__name(parseResourceMetadataUrl,"parseResourceMetadataUrl"),__name(fetchProtectedResourceMetadata,"fetchProtectedResourceMetadata"),__name(checkServerAuthRequirements,"checkServerAuthRequirements"),__name(registerOAuthClient,"registerOAuthClient"),Ut(),BS(),lb(),HS(),__name(discoverAndAuthenticate,"discoverAndAuthenticate"),jr(),uo();var HP=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se(!0),[s,i]=se(0),[a,l]=se("list"),[u,d]=se(null),[m,g]=se(0),h=useTerminalHeight(),f=ce(async()=>{o(!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,o,s="disconnected";return!1===e.config.enabled?s="disabled":n&&"connected"===n.status?(s="connected",r=n.tools.length):n&&"error"===n.status?(s="error",o=n.error):(e.config.oauth||"http"===e.config.transport)&&(await hasTokens(e.name)?s="authenticated":e.config.oauth&&(s="requires_auth")),{name:e.name,config:e.config,scope:e.scope,status:s,toolCount:r,error:o}}));n(r)}catch{}finally{o(!1)}},[]);ae(()=>{f()},[f]);const y=le(()=>{const e=[];for(const n of["local","project","user"])e.push(...t.filter(e=>e.scope===n));return e},[t]),w=y[s]??null,S=h-1,E=le(()=>new Set(y.map(e=>e.scope)).size,[y]),v=Math.max(4,S-8-2*E);ae(()=>{g(e=>clampScrollOffset({cursor:s,total:y.length,maxVisible:v,currentOffset:e}))},[s,y.length,v]),Z((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===y.length)return;const e=Math.max(0,y.length-1);i(t=>Math.min(e,t+1)),d(null)}n.return&&w&&(l("actions"),d(null))}});const C=__name((e,t)=>{const n=__name((e,n)=>re.createElement(Y,{color:e,backgroundColor:t},n),"icon");switch(e){case"connected":return n(gr.GREEN,Me.tick);case"authenticated":return n(gr.CYAN,Me.tick);case"requires_auth":return n(gr.YELLOW,Me.warning);case"error":return n(gr.RED,Me.cross);default:return n(gr.GRAY,Me.circle)}},"getStatusIcon"),k=__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"),T=__name(e=>{switch(e){case"local":return"Local MCPs";case"project":return"Project MCPs";case"user":return"User MCPs"}},"getScopeLabel"),_=__name(e=>{switch(e){case"local":return"~/.commandcode/projects/*/mcp.json";case"project":return".mcp.json";case"user":return"~/.commandcode/mcp.json"}},"getScopePath"),x=__name(async e=>{if(w)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 ${w.name}...`,color:gr.CYAN,loading:!0});try{if(!await updateMcpServerStatus({name:w.name,enabled:!0,scope:w.scope}))return void d({text:`${Me.cross} Failed to enable ${w.name}, server may no longer exist in ${w.scope} scope`,color:gr.YELLOW});await f(),d({text:`${Me.tick} Enabled ${w.name}`,color:gr.GREEN})}catch(e){d({text:`${Me.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:gr.RED})}}else{d({text:`Disabling ${w.name}...`,color:gr.CYAN,loading:!0});try{const e=getMcpConnectionManager();if(!await updateMcpServerStatus({name:w.name,enabled:!1,scope:w.scope}))return void d({text:`${Me.cross} Failed to disable ${w.name}, server may no longer exist in ${w.scope} scope`,color:gr.YELLOW});await e.disconnectServer(w.name),await f(),d({text:`${Me.tick} Disabled ${w.name}`,color:gr.GREEN})}catch(e){d({text:`${Me.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:gr.RED})}}else l("confirm-remove");else{if(!(w.config.oauth||"http"===w.config.transport&&w.config.url))return void d({text:"Authentication requires an http server with a url",color:gr.YELLOW});d({text:`Authenticating ${w.name}...`,color:gr.CYAN,loading:!0});try{let e;if(w.config.oauth){const t={authorizationUrl:w.config.oauth.authorizationUrl,tokenUrl:w.config.oauth.tokenUrl,clientId:w.config.oauth.clientId,clientSecret:w.config.oauth.clientSecret,scopes:w.config.oauth.scopes};e=await performOAuthFlow(w.name,w.config.url??"",t,{onStatus:__name(()=>{},"onStatus")})}else e=await discoverAndAuthenticate({serverName:w.name,serverUrl:w.config.url});if(e.success){d({text:`${Me.tick} Authenticated with ${w.name}`,color:gr.GREEN});try{const e=getMcpConnectionManager();await e.ensureServerConnection(w.name)}catch{}await f()}else d({text:`${Me.cross} Auth failed: ${e.error}`,color:gr.RED})}catch(e){d({text:`${Me.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:gr.RED})}}else{d({text:`Connecting ${w.name}...`,color:gr.CYAN,loading:!0});try{const e=getMcpConnectionManager();await e.ensureServerConnection(w.name),d({text:`${Me.tick} Connected to ${w.name}`,color:gr.GREEN}),await f()}catch(e){d({text:`${Me.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:gr.RED})}}else d({text:"Already authenticated",color:gr.GREEN});else d({text:"Already connected",color:gr.GREEN});else l("list")},"handleActionSelect"),A=__name(async e=>{if(w)if("yes"===e.value)try{const e=getMcpConnectionManager();"connected"===w.status&&await e.disconnectServer(w.name),await removeMcpServer({name:w.name,scope:w.scope}),l("list"),await f(),i(e=>Math.min(e,Math.max(0,y.length-2)))}catch(e){d({text:`${Me.cross} Failed: ${e instanceof Error?e.message:String(e)}`,color:gr.RED}),l("actions")}else l("actions")},"handleRemoveConfirm");if(r)return re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:hr,bold:!0},"Manage MCP servers"),re.createElement(Y,{color:gr.DIM},"Loading..."));if("confirm-remove"===a&&w)return re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:gr.RED,bold:!0},"Remove ",w.name,"?"),re.createElement(Y,{color:gr.DIM},"This will remove the server from ",w.scope," ","config."),re.createElement(K,{marginTop:1},re.createElement(gt,{items:[{label:"Yes, remove",value:"yes"},{label:"Cancel",value:"no"}],onSelect:A,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY,backgroundColor:e?xr:void 0,bold:e}," ",t," ")})),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"↑↓ navigate · Enter to select · Esc to cancel")));if("actions"===a&&w){const e=[],t="disabled"===w.status,n="connected"===w.status,r="authenticated"===w.status||n;t&&e.push({label:"Enable",value:"enable"}),!t&&n&&e.push({label:"Connected",value:"connected"}),t||n||e.push({label:"Connect",value:"connect"});const o=!t&&(w.config.oauth||"http"===w.config.transport);return o&&r&&e.push({label:"Authenticated",value:"authenticated"}),o&&!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"}),re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:hr,bold:!0},w.name),re.createElement(K,null,C(w.status),re.createElement(Y,{color:gr.DIM}," ",k(w))),re.createElement(K,{marginTop:1},re.createElement(gt,{items:e,onSelect:x,indicatorComponent:()=>null,itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.WHITE:gr.GRAY,backgroundColor:e?xr:void 0,bold:e}," ",t," ")})),u&&re.createElement(K,{marginTop:1},u.loading&&re.createElement(Y,{color:u.color},re.createElement(ze,{type:"dots"})," "),re.createElement(Y,{color:u.color},u.text)),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"↑↓ navigate · Enter to select · Esc to go back")))}let P=null;const I=m,M=m+v,N=y.slice(I,M),R=y.length>v;return re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:hr,bold:!0},"Manage MCP servers"),re.createElement(Y,{color:gr.DIM},t.length," ",1===t.length?"server":"servers"),0===t.length?re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(Y,{color:gr.DIM},"No MCP servers configured."),re.createElement(Y,{color:gr.DIM},'Use "cmd mcp add" to add a server.'),re.createElement(ao,{url:"https://commandcode.ai/docs/mcp",text:"View MCP Docs ↗",color:gr.CYAN,dimColor:!0})):re.createElement(K,{marginTop:1,flexDirection:"column"},N.map((e,t)=>{const n=I+t,r=e.scope!==P;P=e.scope;const o=n===s;return re.createElement(re.Fragment,{key:e.name},r&&re.createElement(K,{marginTop:0===t?0:1},re.createElement(Y,{bold:!0},T(e.scope)),re.createElement(Y,{color:gr.DIM}," ","(",_(e.scope),")")),re.createElement(K,null,re.createElement(Y,{color:o?gr.WHITE:void 0,backgroundColor:o?xr:void 0,bold:o},e.name),re.createElement(Y,{color:gr.DIM,backgroundColor:o?xr:void 0}," · "),C(e.status,o?xr:void 0),re.createElement(Y,{color:"connected"===e.status?gr.GREEN:"authenticated"===e.status?gr.CYAN:"requires_auth"===e.status?gr.YELLOW:gr.GRAY,backgroundColor:o?xr:void 0}," ",k(e)," ")))})),R&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",I+1,"–",Math.min(M,y.length)," of"," ",y.length,I>0?" · ↑ more":"",M<y.length?" · ↓ more":"")),u&&re.createElement(K,{marginTop:1},u.loading&&re.createElement(Y,{color:u.color},re.createElement(ze,{type:"dots"})," "),re.createElement(Y,{color:u.color},u.text)),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},0===t.length?"Esc to close":"↑↓ navigate · Enter to select · Esc to close")))},"McpManager");Ut(),kn(),Yn(),jr();var GP=__name(({onClose:e})=>{const[t,n]=se([]),[r,o]=se(0),[s,i]=se(!0),[a,l]=se(null);ae(()=>{__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(Z((t,n)=>{n.escape?e():n.upArrow?o(e=>Math.max(0,e-1)):n.downArrow?o(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]))}),s)return re.createElement(K,{paddingLeft:1,paddingTop:1},re.createElement(Y,{color:gr.DIM},"Loading memory files..."));if(a)return re.createElement(K,{paddingLeft:1,paddingTop:1},re.createElement(Y,{color:gr.RED},Me.cross," ",a));const m=d.map((e,t)=>{const n=t+1;let r="",o="";return"project"===e.type?(r=`${n}. Project memory`,o=e.exists?"Checked in at ./AGENTS.md":"Not found at ./AGENTS.md"):"user"===e.type&&(r=`${n}. User memory`,o=e.exists?"Saved in ~/.commandcode/AGENTS.md":"Not found in ~/.commandcode/AGENTS.md"),{label:r,value:e.path,description:o}});return re.createElement(K,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:gr.GRAY,paddingTop:1,paddingBottom:1,paddingLeft:2,paddingRight:2},re.createElement(K,null,re.createElement(Y,{color:gr.WHITE,bold:!0},"Select memory to edit:")),re.createElement(K,{columnGap:4,marginTop:1},re.createElement(K,{flexDirection:"column"},m.map((e,t)=>re.createElement(Y,{key:t,color:r===t?gr.WHITE:gr.DIM},r===t?`${qn} `:" ",e.label))),re.createElement(K,{flexDirection:"column"},m.map((e,t)=>re.createElement(Y,{key:t,color:r===t?gr.WHITE:gr.DIM},e.description)))))},"MemorySelector");function AutoCompactMessage({content:e}){return re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},Me.bullet," ",e))}function ZdrPausedMessage(){return re.createElement(K,{marginTop:1,marginBottom:1},re.createElement(Y,null,re.createElement(Y,{color:gr.DIM},Me.bullet," "),re.createElement(Y,{color:gr.DIM},"Per-task model overrides reverted to ZDR safe defaults. Run"," "),re.createElement(Y,{color:Rr.CODE},"/configure-models"),re.createElement(Y,{color:gr.DIM}," to review · esc to dismiss")))}function TasteSkipMessage(){return re.createElement(K,{marginTop:1,marginBottom:1},re.createElement(K,{flexShrink:0},re.createElement(Y,{backgroundColor:fr.BADGE_BG,color:fr.BADGE_FG,bold:!0},g_)),re.createElement(Y,{color:gr.DIM}," Skipped. Run "),re.createElement(Y,{color:Rr.CODE},"/learn-taste"),re.createElement(Y,{color:gr.DIM}," or "),re.createElement(Y,{color:Rr.CODE},"cmd learn-taste"),re.createElement(Y,{color:gr.DIM}," anytime."))}function HookWarningMessage({content:e}){return re.createElement(K,null,re.createElement(Y,{color:gr.YELLOW},Me.warning),re.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.YELLOW},e)))}function HookLineMessage({content:e}){return re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},` ${e}`))}function HookLineContinuationMessage({content:e}){return re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},` ${e}`))}function HookFrameMessage({lines:e,header:t}){return re.createElement(K,{flexDirection:"column"},void 0!==t&&re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},` ${t}`)),e.map((e,t)=>re.createElement(K,{key:t,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},e.primary?` └ ${e.text}`:` ${e.text}`))))}function InfoMessage({content:e,metadata:t}){return t?.isTasteSkip?re.createElement(TasteSkipMessage,null):t?.isAutoCompact?re.createElement(AutoCompactMessage,{content:e}):t?.hookFrame&&t.hookFrame.length>0?re.createElement(HookFrameMessage,{lines:t.hookFrame,header:t.hookFrameHeader}):t?.isHookLine?re.createElement(HookLineMessage,{content:e}):t?.isHookLineContinuation?re.createElement(HookLineContinuationMessage,{content:e}):t?.isHookWarning?re.createElement(HookWarningMessage,{content:e}):t?.isSuccess?re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.GREEN},Me.tick," ",e)):re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:gr.DIM},Me.bullet," ",e))}Ut(),jr(),__name(AutoCompactMessage,"AutoCompactMessage"),__name(ZdrPausedMessage,"ZdrPausedMessage"),__name(TasteSkipMessage,"TasteSkipMessage"),__name(HookWarningMessage,"HookWarningMessage"),__name(HookLineMessage,"HookLineMessage"),__name(HookLineContinuationMessage,"HookLineContinuationMessage"),__name(HookFrameMessage,"HookFrameMessage"),__name(InfoMessage,"InfoMessage"),Ut(),kn(),io(),Zb(),$o(),bo(),co(),jr(),Ut(),jr();var VP=wt()?"⠶":"#";function AssistantMessage({content:e}){return re.createElement(K,null,re.createElement(Y,{color:Ar},VP),re.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Markdown,null,e)))}function BashMessage({command:e,output:t,isPending:n=!1,hasError:r=!1}){let o=gr.GREEN,s=Me.tick,i="default",a=t||"(No output)";n&&(o=gr.YELLOW,s=Me.arrowRight,i=gr.YELLOW,a="Executing…"),r&&(o=gr.RED,s=Me.cross,i=gr.RED);const l=le(()=>buildTreeConnectors(a),[a]);return re.createElement(K,null,re.createElement(Y,{color:o},s),re.createElement(K,{flexDirection:"column",marginLeft:1},re.createElement(K,null,re.createElement(Y,{color:gr.GRAY},"$ "),re.createElement(Y,{color:o,bold:!0},e)),re.createElement(K,{columnGap:1,marginLeft:1},re.createElement(Y,{color:Dr},l),re.createElement(Y,{color:i,wrap:"wrap"},a))))}function CommandResultMessage({message:e,details:t,hasError:n=!1}){const r=n?gr.YELLOW:void 0,o=le(()=>buildTreeConnectors(e),[e]);return re.createElement(K,{flexDirection:"column",marginBottom:0,marginTop:-1},re.createElement(K,{columnGap:1},re.createElement(Y,{color:Dr},o),re.createElement(K,{flexGrow:1,flexShrink:1,minWidth:0},re.createElement(Y,{color:r},e))),t&&re.createElement(K,{marginLeft:3},re.createElement(Y,{color:gr.DIM},"See ",t)))}function ErrorMessage({content:e}){const t=e.includes("Interrupted by user");return re.createElement(K,null,re.createElement(Y,{color:gr.RED},t?Me.pointer:Me.warning),re.createElement(K,{marginLeft:1,flexGrow:1,flexShrink:1,minWidth:0},t?re.createElement(Y,{color:gr.RED,wrap:"wrap"},e):re.createElement(Markdown,{color:gr.RED},e)))}__name(AssistantMessage,"AssistantMessage"),Ut(),jr(),__name(BashMessage,"BashMessage"),Ut(),jr(),__name(CommandResultMessage,"CommandResultMessage"),Ut(),jr(),__name(ErrorMessage,"ErrorMessage"),Ut(),jr();var QP={connected:{char:Me.tick,color:gr.GREEN},installed:{char:Me.tick,color:gr.GREEN},up_to_date:{char:Me.tick,color:gr.GREEN},needs_reload:{char:Me.circle,color:gr.YELLOW},failed:{char:Me.cross,color:gr.RED},not_in_ide:{char:Me.circle,color:gr.YELLOW}};function IDEStatusMessage({status:e,ide:t,details:n}){const{prefix:r,ide:o,suffix:s}=getStatusHeadline(e,t),i=QP[e];return re.createElement(K,{flexDirection:"column"},re.createElement(K,null,re.createElement(Y,null,re.createElement(Y,{color:i.color},i.char),re.createElement(Y,null," ",r),o&&re.createElement(Y,{color:gr.CYAN},o),s&&re.createElement(Y,null,s))),n?.map((e,t)=>re.createElement(Y,{key:t,color:gr.DIM}," ",e)))}function ReasoningMessage({content:e,expandedOutput:t,expandKey:n,isStreaming:r=!1}){const o=e?Math.max(1,Math.round(e.length/500)):1,s=Boolean(e),i=(s?e.split("\n"):[]).length,a=`${r?"Thinking…":`Thought for ${o} second${1!==o?"s":""}`}${r&&!t&&i>0?` (${i} line${1!==i?"s":""})`:""}`,l=t&&s,u=!t&&s,d=r&&t&&e.length>560,m=d?e.length-560:0,g=80*Math.floor(m/80),h=d?(e.slice(0,g).match(/\n/g)??[]).length:0,f=d?e.slice(g):e;return re.createElement(K,{flexDirection:"column",width:"90%"},re.createElement(K,null,re.createElement(Y,{color:yr},"✻"," "),re.createElement(Y,{color:yr},u?`${a} `:a),u&&re.createElement(BracketWrap,{color:gr.DIM},`${n}+o to expand`)),l&&d&&re.createElement(K,{marginLeft:2},re.createElement(Y,{color:gr.DIM},h>0?`… (${h} more line${1!==h?"s":""})`:"…")),l&&re.createElement(K,{marginLeft:2,flexDirection:"column"},re.createElement(Y,{color:yr,wrap:"wrap",italic:!0},f)))}__name(IDEStatusMessage,"IDEStatusMessage"),Ut(),jr(),__name(ReasoningMessage,"ReasoningMessage"),Ut(),Ut(),kn();function HelpMessage(){const e=getInvokedCommandName(),t=le(()=>Rk.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced())),[]);return re.createElement(K,{flexDirection:"column",paddingY:1},re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(K,null,re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:gr.GRAY}," v","0.35.2")),re.createElement(Y,{color:gr.GRAY},Ak)),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Usage"),re.createElement(K,{paddingLeft:2},re.createElement(Y,null,e," <command> [options]"))),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Options"),re.createElement(K,{flexDirection:"column",paddingLeft:2},Nk.map(t=>re.createElement(K,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(Pk)),re.createElement(Y,{color:gr.GRAY},t.description))))),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Commands"),re.createElement(K,{flexDirection:"column",paddingLeft:2},$k.map(t=>re.createElement(K,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(Pk)),re.createElement(Y,{color:gr.GRAY},t.description))))),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Slash Commands"),re.createElement(K,{flexDirection:"column",paddingLeft:2},t.map(e=>re.createElement(K,{key:e.key},re.createElement(Y,null,e.key.padEnd(Pk)),re.createElement(Y,{color:gr.GRAY},e.description))))),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Keyboard Shortcuts"),re.createElement(K,{flexDirection:"column",paddingLeft:2},Mk.map(e=>re.createElement(K,{key:e.key},re.createElement(Y,null,e.key.padEnd(Pk)),re.createElement(Y,{color:gr.GRAY},e.description))))),re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(Y,{bold:!0},"Examples"),re.createElement(K,{flexDirection:"column",paddingLeft:2},Dk.map(t=>re.createElement(K,{key:t.key},re.createElement(Y,null,t.key.replace(/^cmd/,e).padEnd(Pk)),re.createElement(Y,{color:gr.GRAY},t.description))))),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.CYAN},Me.pointer),re.createElement(Y,{color:gr.GRAY}," ",Ok.replace(/cmd/,e))),re.createElement(K,{flexDirection:"column"},re.createElement(Y,{bold:!0},"Links"),re.createElement(K,{flexDirection:"column",paddingLeft:2},Lk.map(e=>re.createElement(K,{key:e.key},re.createElement(Y,null,e.key.padEnd(Pk)),re.createElement(Y,{color:gr.CYAN},e.description))))))}function SystemMessage({content:e}){return e.includes("KEYBOARD SHORTCUTS")&&e.includes("COMMANDS")?re.createElement(HelpMessage,null):re.createElement(K,{flexDirection:"column"},re.createElement(Y,{wrap:"wrap"},re.createElement(Markdown,null,e)))}jr(),ob(),bo(),__name(HelpMessage,"HelpMessage"),__name(SystemMessage,"SystemMessage"),Ut(),Yn(),yo(),jr();var KP={"Interrupted by user":"Interrupted by user","Insufficient credits":jn};function UserMessage({content:e,images:t,imageCount:n=0,ideHint:r}){const o="Interrupted by user"===e,s="Insufficient credits"===e,i=e.startsWith("Error:"),a=o||s||i,l=a&&KP[e]||e,u=null!=t?t.length:n,d=ie(null);null===d.current&&t&&t.length>0&&(d.current=t.map((e,t)=>saveTempImage(e,t+1)));const m=d.current??[];return re.createElement(K,{flexDirection:"column"},re.createElement(K,{backgroundColor:a?void 0:_r.BG,paddingRight:1},re.createElement(Y,{color:a?gr.RED:_r.POINTER,bold:!a},Me.pointer),re.createElement(K,{marginLeft:1},re.createElement(Y,{color:a?gr.RED:gr.WHITE,wrap:"wrap"},l))),u>0&&re.createElement(K,{marginLeft:1},re.createElement(Y,{color:gr.DIM},"⎿"," ",Array.from({length:u},(e,t)=>{const n=m[t],r=`[Image #${t+1}]`;return null!=n?createOSC8Link(`file://${n}`,r,!1):r}).join(" "))),r&&!a&&re.createElement(K,{marginLeft:2},re.createElement(Y,{color:Dr},d_),re.createElement(Y,{color:gr.DIM}," ","Selected ",r.lines," ",1===r.lines?"line":"lines"," from"," ",r.file," in ",r.ide)))}function renderFeedEntry(e,t){if("user"===e.role){const t=Array.isArray(e.metadata?.images)?e.metadata.images:void 0,n=e.metadata?.ideHint;return re.createElement(UserMessage,{content:e.input,images:t,ideHint:n})}return"assistant"===e.role?re.createElement(AssistantMessage,{content:e.input}):"reasoning"===e.role?re.createElement(ReasoningMessage,{content:e.input,expandedOutput:t,expandKey:"ctrl",isStreaming:"running"===e.metadata?.status}):"tool"===e.role?re.createElement(ToolMessage,{name:Vb(e.name||""),input:e.input,output:e.output||"",isPending:Wb(e),hasError:zb(e),metadata:e.metadata,expandedOutput:t}):"bash"===e.role?re.createElement(BashMessage,{command:e.command||"",output:e.output||"",isPending:Wb(e),hasError:zb(e)}):"system"===e.role?re.createElement(SystemMessage,{content:e.input}):"info"===e.role?re.createElement(InfoMessage,{content:e.input,metadata:e.metadata}):"error"===e.role?re.createElement(ErrorMessage,{content:e.input}):"command-result"===e.role?re.createElement(CommandResultMessage,{message:e.input,details:e.details,hasError:e.hasError??!1}):"ide-status"===e.role?re.createElement(IDEStatusMessage,{status:e.status,ide:e.ide,details:e.details}):null}function getModelShortName2(e){const t=findModelById(e);if(t){const e=t.name.toLowerCase().replaceAll(" ","-");return"free"===t.badge?`${e} (free)`:e}return e}function getProviderShortName(e){return e?yn[e]?.shortLabel??e.slice(0,4):""}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)),o="─".repeat(r);return re.createElement(K,{marginBottom:1},re.createElement(Y,{color:Tr},o),re.createElement(BracketedText,{text:n,color:Tr}),re.createElement(Y,{color:Tr},o))}__name(UserMessage,"UserMessage"),__name(renderFeedEntry,"renderFeedEntry"),__name(getModelShortName2,"getModelShortName"),__name(getProviderShortName,"getProviderShortName"),__name(TranscriptDivider,"TranscriptDivider");var YP=re.memo(({feed:e,showHeader:t=!1,staticKey:n,expandedToolOutput:r=!1,currentModel:o,currentProvider:s,hiddenCount:i=0})=>{const a=i>0?{role:"transcript-divider",count:i}:null,l=[...t?["header"]:[],...a?[a]:[],...e],u=useTerminalWidth(),d=le(()=>pA(u),[u]),m=le(()=>wA(u),[u]),g=le(()=>getPackageJson().version||"0.0.0",[]),h=le(()=>getGitHeaderInfo(),[]),f=le(()=>{const e=process.cwd(),t=process.env.HOME??process.env.USERPROFILE??"";return e.replace(t,"~")},[]),y=o?getModelShortName2(o):"sonnet-4.6",w="taste-1",S=le(()=>{if(!o)return"";if(!modelSupportsReasoningEffort(o))return"";const e=getReasoningEffort(o);return e?` with ${e} effort`:""},[o,n]),E=isInternalTeamFlagEnforced()&&!process.env.CMD_DEMO,v=E?" · co":"",C=E&&s?` · ${getProviderShortName(s)}`:"";return re.createElement(J,{items:l,key:n,style:{width:"100%"}},e=>{if("object"==typeof e&&"transcript-divider"===e.role)return re.createElement(TranscriptDivider,{key:"transcript-divider",count:e.count,width:u});if("header"===e)return"compact"===m?re.createElement(K,{key:"header",marginBottom:1,flexDirection:"row"},re.createElement(K,{width:fA,flexShrink:0},re.createElement(SA,null,hA)),re.createElement(K,{flexDirection:"column",marginLeft:2},re.createElement(K,null,re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:Tr}," ","v",g)),re.createElement(Y,{color:Tr},"models: ",y,S," ·"," ",w,v),re.createElement(Y,{color:Tr},f,h&&h.isLocal&&h.branch&&` (${h.branch})`))):re.createElement(K,{key:"header",marginBottom:1,flexDirection:"column"},re.createElement(SA,null,d.trimEnd()),re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(K,null,re.createElement(Y,{color:Tr},"# "),re.createElement(Y,{bold:!0},"Command Code"),re.createElement(Y,{color:Tr}," v",g)),re.createElement(Y,{color:Tr},"# models: ",y,S," · ",w,C,v),re.createElement(K,null,re.createElement(Y,{color:Tr},"# ",f,h&&h.isLocal&&h.branch&&re.createElement(Y,{color:Tr}," ","(branch:"," ",h.branch,")")))));const t=e,n=renderFeedEntry(t,r);return re.createElement(K,{key:t.id,paddingBottom:1,width:"90%"},n)})});Ut(),Zb(),Eo(),jr();var JP=oe(__name(function LiveAgentStatusInner2({entry:e}){const t=Vb(e.name||"Agent"),n=e.input||"",r=n.split(/[.\n]/)[0],o=r?r+(n.includes(".")||n.includes("\n")?".":""):n,s=e.metadata?.tokensUsed||0,i=e.metadata?.elapsedSeconds||0,a=e.metadata?.recentTools||[],[l,u]=se(".");return ae(()=>{const e=setInterval(()=>{u(e=>"..."===e?".":e+".")},500);return()=>clearInterval(e)},[]),re.createElement(K,{flexDirection:"column",marginBottom:1,width:"90%"},re.createElement(K,null,re.createElement(Y,{backgroundColor:vr.BG,color:vr.FG,bold:!0},` ${t} `),o&&re.createElement(Y,null," (",o,")")),re.createElement(K,{columnGap:1,marginLeft:1},re.createElement(Y,null,"⎿"," "),re.createElement(Y,{color:gr.GRAY},"Running (",formatTime2(i)," |"," ",formatTokens(s),")",l)),a.length>0&&re.createElement(K,{flexDirection:"column",marginLeft:1},a.map((e,t)=>{const n=Vb(e.name);return re.createElement(K,{key:t,columnGap:1},re.createElement(Y,{color:gr.GRAY},"⎿"),re.createElement(Y,{color:gr.GRAY}," ",n),e.input&&re.createElement(Y,{color:gr.GRAY},"(",e.input,")"))})))},"LiveAgentStatusInner")),XP=oe(__name(function LiveAgentStatus2({entry:e}){return"tool"!==e.role?null:re.createElement(JP,{entry:e})},"LiveAgentStatus"));Ut(),kn(),io(),co(),Eo(),bo(),jr(),Ut(),jr();var ZP={low:"Fast responses with lighter reasoning",medium:"Balances speed and reasoning depth for everyday tasks",high:"Greater reasoning depth for complex problems",xhigh:"Extra reasoning depth for complex problems",max:"Maximum reasoning budget for the hardest problems"},eI={value:void 0,label:"Default",description:"Use the provider default reasoning level"},tI=__name(({modelLabel:e,supportedEfforts:t,currentEffort:n,onSelect:r,onCancel:o})=>{const s=le(()=>[eI,...t.map(e=>({value:e,label:e,description:ZP[e]}))],[t]),i=le(()=>{if(void 0===n)return 0;const e=s.findIndex(e=>e.value===n);return e>=0?e:0},[s,n]),a=__name((e,t)=>`${e+1}. ${t}`,"labelText"),l=le(()=>Math.max(...s.map((e,t)=>a(t,e.label).length))+4,[s]),{cursor:u}=useListNavigation({items:s,onSelect:__name(e=>r(e.value),"onSelect"),onCancel:o,initialIndex:i,searchQuery:"",onSearchChange:__name(()=>{},"onSearchChange"),disableSearch:!0,selectByNumber:!0});return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,{marginBottom:1},re.createElement(Y,{color:hr,bold:!0},`Select reasoning effort for ${e}`)),re.createElement(K,{flexDirection:"column"},s.map((e,t)=>{const r=t===u,o=e.value===n;return re.createElement(K,{key:e.label},re.createElement(Y,{color:r||!o?gr.WHITE:gr.GREEN,backgroundColor:r?xr:void 0,bold:r},a(t,e.label).padEnd(l)),re.createElement(Y,{color:r?gr.WHITE:gr.DIM,backgroundColor:r?xr:void 0},e.description," "),o&&re.createElement(Y,{color:gr.GREEN}," ",Me.tick))})),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"↑/↓ navigate · enter to select · esc to go back")))},"ReasoningEffortSelector");rr();var nI="Loading plan info…",rI=__name(e=>[{text:e.name,weight:100},{text:e.label,weight:50},{text:e.provider,weight:25},{text:e.description||"",weight:10}],"MODEL_SEARCH_FIELDS");function searchGroups2(e,t){if(!t.trim())return e;const n=[];for(const r of e){const e=fuzzyFilter(r.models,t,rI);e.length>0&&n.push({...r,models:e})}return n}function flattenGroups(e){const t=[];for(const n of e)for(const e of n.models)t.push({providerId:n.providerId,model:e});return t}function groupByModelProvider2(e,t){return groupModelsByDisplayOrder(e).map(e=>({providerId:t,label:e.label,models:e.models}))}__name(searchGroups2,"searchGroups"),__name(flattenGroups,"flattenGroups"),__name(groupByModelProvider2,"groupByModelProvider");var oI=__name(({onSelect:e,onCancel:t,currentModel:n,currentProvider:r,planId:o,purchasedCredits:s=0,freeCredits:i=0,refreshBanner:a})=>{const[l,u]=se(""),[d,m]=se(null),[g,h]=se(()=>new Set),f=le(()=>isInternalTeamFlagEnforced(),[]),y=le(()=>f?wn:groupByModelProvider2(Sn.flatMap(e=>e.models),yn["command-code"].id),[f]),w=le(()=>searchGroups2(y,l),[y,l]),S=le(()=>flattenGroups(w),[w]),[E,v]=se(0),C=useTerminalHeight()-1,k=Math.max(4,C-14-2*w.length),T=void 0!==o,_=le(()=>T?null:getCachedBillingContext(),[T]),[x,A]=se(_),[P,I]=se(!T&&!_);ae(()=>{if(T)return;if(x)return;let e=!0;return getBillingContext().then(t=>{e&&(A(t),I(!1))}),()=>{e=!1}},[T,x]);const M=!T&&!0===x?.fetchFailed,N=T?o:x?.planId??null,R=T?s:x?.purchasedCredits??0,$=T?i:x?.freeCredits??0,L=f?yn.anthropic.id:yn["command-code"].id,D=r??L,O=n?Math.max(0,S.findIndex(e=>e.model.id===n&&e.providerId===D)):0,[F,U]=se("model"),[j,B]=se(null),{cursor:q,error:z,setError:W}=useListNavigation({items:S,onSelect:__name(t=>{const n=getSupportedEfforts(t.model.id);if(n&&n.length>0)return B(t),void U("effort");e(t.model.id,t.providerId)},"onSelect"),onCancel:t,initialIndex:O,searchQuery:l,onSearchChange:u,isActive:"model"===F,validate:__name(e=>{if(g.has(e.providerId))return`Run /provider to authenticate with ${getProviderConfig(e.providerId)?.displayName??e.providerId} first`;if(d&&!f){const t=yn[d]?.supportedModelProviders;if(t&&!t.includes(e.model.provider))return`${yn[d]?.label??d} does not support ${e.model.provider} models. Switch provider via /provider.`}if(P)return nI;const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:N,purchasedCredits:R,freeCredits:$});return t.allowed?null:t.errorMessage??"Model not available for your plan"},"validate")});ae(()=>{v(e=>clampScrollOffset({cursor:q,total:S.length,maxVisible:k,currentOffset:e}))},[q,S.length,k]);const H=ie(!1),G=__name(t=>{if(!j||H.current)return;H.current=!0;const{model:r,providerId:o}=j,s=getReasoningEffort(r.id),i=t!==s,l=r.id===n;(async()=>{try{i&&(await setReasoningEffort({modelId:r.id,effort:t}),l&&a?.())}catch(e){dlog(`[Model] Failed to persist reasoning effort: ${e}`)}finally{e(r.id,o)}})()},"handleEffortSelect"),V=__name(()=>{H.current||(B(null),U("model"))},"handleEffortCancel");if(ae(()=>{if(P)return;if(z!==nI)return;const e=S[q];if(!e||M)return void W(null);const t=checkModelAccess({model:{id:e.model.id,provider:e.model.provider,name:e.model.name},planId:N,purchasedCredits:R,freeCredits:$});W(t.allowed?null:t.errorMessage??"Model not available for your plan")},[P,M,z,W,S,q,N,R,$]),ae(()=>{(async()=>{await isOAuthEnforced()&&m(await getConfiguredProvider())})()},[]),ae(()=>{(async()=>{const e=new Set(y.map(e=>e.providerId)),t=new Set;for(const n of e){const e=getProviderConfig(n);e?.requiresAuth&&e.checkAuth&&(await e.checkAuth()||t.add(n))}h(t)})()},[y]),"effort"===F&&j){const e=getSupportedEfforts(j.model.id)??[];return re.createElement(tI,{modelLabel:j.model.label,supportedEfforts:e,currentEffort:getReasoningEffort(j.model.id),onSelect:G,onCancel:V})}const Q=E,J=E+k;let X=0;const Z=w.map(e=>{const t=sliceSectionForWindow({section:e.models,sectionBase:X,windowStart:Q,windowEnd:J});return X+=e.models.length,{group:e,groupWindow:t}}).filter(e=>e.groupWindow.rows.length>0),ee=S.length>k;return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,null,re.createElement(Y,{color:hr,bold:!0},"Select model")),re.createElement(K,{marginBottom:1},re.createElement(Y,{dimColor:!0},f?"Select a model and provider. Sets the default for new sessions; other open sessions are unaffected. Provider is saved.":"Switch between Command Code models. Sets the default for new sessions; other open sessions are unaffected.")),re.createElement(K,{marginBottom:2,flexDirection:"column",width:"100%"},re.createElement(TA,{query:l,resultCount:l?S.length:void 0,placeholder:"Type to search models..."})),0===S.length?re.createElement(K,{marginY:1},re.createElement(Y,{color:gr.GRAY},'No models match "',l,'"')):re.createElement(K,{flexDirection:"column"},Z.map(({group:e,groupWindow:t},r)=>re.createElement(K,{key:`${e.providerId}-${e.label}`,flexDirection:"column",marginTop:r>0?1:0},f?re.createElement(Y,{bold:!0,color:hr},e.label):re.createElement(Y,{bold:!0,dimColor:!0},e.label),t.rows.map((r,o)=>re.createElement(uP,{key:`${e.providerId}-${e.label}-${r.id}`,model:r,providerId:e.providerId,isHighlighted:t.baseIndex+o===q,isCurrent:r.id===n&&e.providerId===D,showProviderLabel:!!f&&void 0}))))),ee&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",Q+1,"–",Math.min(J,S.length)," of ",S.length,Q>0?" · ↑ more":"",J<S.length?" · ↓ more":"")),z&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.GRAY},z)),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"type to search · ↑/↓ navigate · enter to select"),l?re.createElement(Y,{color:gr.DIM}," · esc to clear"):re.createElement(Y,{color:gr.DIM}," · esc to cancel")))},"ModelSelector");Ut(),io(),co(),rr();var sI=__name(({currentModel:e,onClose:t,refreshBanner:n})=>{const r=getSupportedEfforts(e)??[],o=findModelById(e)?.label??getModelDisplayName(e),s=ie(!1),i=__name(r=>{if(s.current)return;s.current=!0;const o=r!==getReasoningEffort(e);(async()=>{try{o&&(await setReasoningEffort({modelId:e,effort:r}),n())}catch(e){dlog(`[Effort] Failed to persist reasoning effort: ${e}`)}finally{t()}})()},"handleSelect"),a=__name(()=>{s.current||t()},"handleCancel");return re.createElement(tI,{modelLabel:o,supportedEfforts:r,currentEffort:getReasoningEffort(e),onSelect:i,onCancel:a})},"EffortSelector");Ut(),bo(),jr();var iI=__name(({onSelect:e,onCancel:t,currentProvider:n})=>{const r=getProviderOptions(),o=__name(t=>{e(t.value)},"handleSelect");Z((e,n)=>{n.escape&&t()});const s=n?r.findIndex(e=>e.value===n):0,i=n&&-1===s;return re.createElement(K,{flexDirection:"column",paddingX:0,width:"100%"},re.createElement(K,{marginBottom:1,flexDirection:"row",justifyContent:"space-between"},re.createElement(K,null,re.createElement(Y,{bold:!0},"Select AI Provider")),n&&re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:gr.DIM},"Current: "),re.createElement(Y,{color:gr.GREEN},getProviderDisplayName(n)),i&&re.createElement(Y,{color:gr.YELLOW}," ","[OAuth enforced]"))),re.createElement(K,{marginBottom:0},re.createElement(Y,{color:gr.DIM},"Available Providers:")),re.createElement(gt,{items:r,onSelect:o,initialIndex:s>=0?s:0,indicatorComponent:({isSelected:e})=>re.createElement(Y,{color:e?gr.CYAN:gr.GRAY,bold:e},e?Me.triangleRightSmall:" "),itemComponent:({isSelected:e,label:t})=>re.createElement(Y,{color:e?gr.CYAN:gr.GRAY,bold:e},` ${t}`)}),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press ESC to cancel")))},"ProviderSelector");function RetryMessage({attempt:e}){const[t,n]=se(0);if(ae(()=>{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 re.createElement(K,{marginBottom:1},re.createElement(Y,{color:Nr,dimColor:!0},"Connection Issue. Retrying (attempt ",e,")",r))}Ut(),jr(),__name(RetryMessage,"RetryMessage"),Ut(),bs(),Yn(),jr();var aI=[{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"}],lI=__name(({checkpoints:e,onSelect:t,onCancel:n})=>{const r=le(()=>[...e].sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),[e]),[o,s]=se(Math.max(0,r.length-1)),[i,a]=se(Math.max(0,r.length-8)),[l,u]=se("checkpoint"),[d,m]=se(null),[g,h]=se(0),f=le(()=>{if(!d)return!0;const e=r.findIndex(e=>e.messageId===d.messageId);if(-1===e)return!0;for(let t=e;t<r.length;t++)if(r[t].filesModified.length>0)return!0;return!1},[d,r]),y=le(()=>f?aI:aI.filter(e=>"conversation"===e.mode),[f]);if(ae(()=>{if(r.length>0){const e=r.length-1;s(e),a(Math.max(0,r.length-8))}},[r.length,8]),Z((e,f)=>{f.escape?"mode"===l?(u("checkpoint"),m(null),h(0)):n():"checkpoint"===l?f.upArrow?s(e=>{const t=Math.max(0,e-1);return t<i&&a(t),t}):f.downArrow?s(e=>{const t=Math.min(r.length-1,e+1);return t>=i+8&&a(t-8+1),t}):f.return&&r.length>0&&(m(r[o]),u("mode"),h(0)):"mode"===l&&(f.upArrow?h(e=>Math.max(0,e-1)):f.downArrow?h(e=>Math.min(y.length-1,e+1)):f.return&&d&&y[g]&&t({messageId:d.messageId,mode:y[g].mode}))}),0===r.length)return re.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:hr,bold:!0},"Rewind"),re.createElement(Y,{color:gr.DIM},"No checkpoints available. Start a conversation to create checkpoints."),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press "),re.createElement(Y,{color:gr.DIM,bold:!0},"Esc"),re.createElement(Y,{color:gr.DIM}," to close")));if("mode"===l&&d)return re.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:hr,bold:!0},"Rewind"),re.createElement(K,{marginBottom:1},re.createElement(Y,{color:gr.DIM},"Restore to: "),re.createElement(Y,{color:gr.WHITE},truncateString({text:d.userPrompt||"checkpoint",maxChars:50}))),re.createElement(K,{flexDirection:"column"},y.map((e,t)=>{const n=g===t,r=t===y.length-1;return re.createElement(K,{key:e.mode,flexDirection:"column"},re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:n?hr:void 0},n?`${qn} `:" "),re.createElement(K,{flexDirection:"column"},re.createElement(Y,{color:n?hr:gr.WHITE},e.label),re.createElement(Y,{color:gr.DIM},e.description))),!r&&re.createElement(Y,null," "))})),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press "),re.createElement(Y,{color:gr.DIM,bold:!0},"Enter"),re.createElement(Y,{color:gr.DIM}," to confirm, "),re.createElement(Y,{color:gr.DIM,bold:!0},"Esc"),re.createElement(Y,{color:gr.DIM}," to go back")));const w=r.slice(i,i+8);return re.createElement(K,{flexDirection:"column",paddingLeft:2,paddingTop:1},re.createElement(Y,{color:hr,bold:!0},"Rewind"),re.createElement(Y,{color:gr.DIM},"Select a checkpoint to restore your session"),r.length>8&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Showing ",i+1,"-",Math.min(i+8,r.length)," ","of ",r.length)),re.createElement(K,{marginTop:1}),re.createElement(K,{flexDirection:"column"},w.map((e,t)=>{const n=i+t,s=o===n,a=e.filesModified.length,l=t===w.length-1,u=n===r.length-1;return re.createElement(K,{key:e.messageId,flexDirection:"column"},re.createElement(K,{flexDirection:"row"},re.createElement(Y,{color:s?hr:void 0},s?`${qn} `:" "),re.createElement(K,{flexDirection:"column"},re.createElement(K,null,re.createElement(Y,{color:s?hr:gr.WHITE},truncateString({text:e.userPrompt||"(no prompt)",maxChars:60})),re.createElement(Y,{color:gr.DIM}," • "),re.createElement(Y,{color:gr.DIM},getRelativeTimeString({timestamp:e.timestamp}),u&&" (latest)")),re.createElement(Y,{color:gr.DIM},a>0?`${a} file${a>1?"s":""} changed`:"No code changes"))),!l&&re.createElement(Y,null," "))})),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press "),re.createElement(Y,{color:gr.DIM,bold:!0},"Enter"),re.createElement(Y,{color:gr.DIM}," to select, "),re.createElement(Y,{color:gr.DIM,bold:!0},"Esc"),re.createElement(Y,{color:gr.DIM}," to cancel")))},"RewindSelector");Ut(),jr();var cI=[{label:"Complete brief",desc:"If the target, goal, audience, or artifact is clear, act without asking."},{label:"Composition",desc:"Choose layout from the work pattern: monitor, operate, compare, configure, learn, decide, or explore."},{label:"Scope",desc:"Broad prompts get the full mode pass. Narrow prompts stay narrow."},{label:"Truth",desc:"Only claim changes that exist in files and are visible or verifiable."},{label:"Templates",desc:"design-html and report-html are documentation templates, not UI inspiration."},{label:"Reports",desc:"Follow-up modes read markdown reports, apply relevant findings, then still run their own full mode pass."}],uI=['/design redesign "Make this dashboard feel like an operator console"','/design motion "Animate the whole page and add missing interactions"','/design checkup "Audit this UI and generate the design report"','/design "Build a landing page for a privacy-first contract review tool"'],dI=__name(({onCancel:e})=>(Z((t,n)=>{n.escape&&e()}),re.createElement(K,{flexDirection:"column",paddingLeft:2,paddingRight:2},re.createElement(K,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:hr},"Use"),re.createElement(K,{paddingLeft:2,flexDirection:"column"},re.createElement(Y,{color:gr.DIM},'/design <mode> "target or request"'),re.createElement(Y,{color:gr.DIM},'/design "freeform request" also works. The closest mode is inferred.'))),re.createElement(K,{marginBottom:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:hr},"Modes"),re.createElement(K,{paddingLeft:2,flexDirection:"column"},kx.map(e=>re.createElement(K,{key:e.name,columnGap:2},re.createElement(K,{width:18,flexShrink:0},re.createElement(Y,{color:gr.CYAN},"/design ",e.name)),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},e.description)))))),re.createElement(K,{marginBottom:1,marginTop:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:hr},"Working rules"),re.createElement(K,{paddingLeft:2,flexDirection:"column"},cI.map(e=>re.createElement(K,{key:e.label,columnGap:2},re.createElement(K,{width:16,flexShrink:0},re.createElement(Y,{color:gr.CYAN},e.label)),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},e.desc)))))),re.createElement(K,{marginBottom:1,marginTop:1,flexDirection:"column"},re.createElement(Y,{bold:!0,color:hr},"Quick examples:"),re.createElement(K,{paddingLeft:2,flexDirection:"column"},uI.map(e=>re.createElement(Y,{key:e,color:gr.DIM},e)))),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"Press Esc to close. Type /design help anytime to return.")))),"DesignGuide");Ut(),rr(),Ut(),Ut();var mI=__name(e=>{const[t,n]=se(e),[r,o]=se(null);return ae(()=>{const t=__name(()=>{n(e.map(e=>({...e,active:!1,complete:!1,items:[],insights:[],message:""}))),o(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}):o(e.message)},"handleNewEvent");return BT.on("reset",t),BT.on("new-event",r),()=>{BT.off("reset",t),BT.off("new-event",r)}},[e]),{steps:t,importError:r,setImportError:o}},"useProgressEvents");async function createRequestClient(){const e=getApiBaseUrl(),t=new rS({baseUrl:e}),n=await getConfiguredProvider(),r=await isOAuthEnforced();let o,s;try{const e=await getOAuthCredentials({provider:n});o=e.token,s=e.oauthProvider,validateOAuthToken({token:o,provider:n})}catch(e){dlog("Failed to get or validate OAuth token:",e instanceof Error?e.message:String(e))}const i={[zt.PROJECT_SLUG]:Hk.getCurrentProjectDirName(),[zt.INTERNAL_TEAM_FLAG_HEADER]:r.toString()};return o&&(i[zt.OAUTH_TOKEN]=`Bearer ${o}`,s&&(i[zt.OAUTH_PROVIDER]=s)),{request:t,headers:i}}function splitPromptsIntoBatches(e){const t=[];let n=[],r=0;for(const o of e){const e=estimateTokens(o);e>2e3?(n.length>0&&(t.push(n),n=[],r=0),t.push([o])):r+e>2e3?(n.length>0&&t.push(n),n=[o],r=e):(n.push(o),r+=e)}return n.length>0&&t.push(n),t}function buildObserverPrompt(e,t){return`Produce ${t} varied observations for these prompts:\n\n${e.map((e,t)=>`${t+1}. ${e}`).join("\n")}\n\nVaried observations:`}function createInsightEmitter(){let e="",t=0;const n=__name(()=>{if(e.includes("\n")){const t=e.split("\n");for(let e=0;e<t.length-1;e++){const n=t[e].trim();n&&(dlog(`[ObserverAPI] emitting insight: ${n}`),BT.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()}`),BT.addEvent({type:"insight",message:e.trim()}))},"emitRemaining"),getChunkCount:__name(()=>t,"getChunkCount")}}async function callObserverAPI(e,t,n){const r=getTasteObserverModel();dlog(`[ObserverAPI] calling ${Wt.ALPHA.GENERATE} with model: ${r}`);const o={config:getEnvironmentContext(),memory:"",taste:"",skills:"",params:{tools:[],messages:[{role:"user",content:n}],model:r,system:"You scan prompts and produce casual observations like a dev friend glancing at someone's 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 per observation\n- one observation per line\n- sound human, not robotic\n- output only the observations, no preamble",max_tokens:200,temperature:.7,stream:!0},threadId:Ie()},s=await e.post({endpoint:Wt.ALPHA.GENERATE,body:o,headers:t,stream:!0});dlog("[ObserverAPI] got response stream");const i=createInsightEmitter();await consumeSSEStream(s,{onText:__name(e=>{i.addText(e)},"onText")}),dlog(`[ObserverAPI] stream complete, ${i.getChunkCount()} chunks received`),i.emitRemaining(),dlog("[ObserverAPI] done")}async function processBatch(e,t,n,r,o){let s=0;for(const e of n)s+=estimateTokens(e);dlog(`[Observer] batch ${r}/${o}: ${n.length} prompts`);const i=buildObserverPrompt(n,4);await callObserverAPI(e,t,i)}async function observeSessionPrompts(e){if(BT.observerHasRun)return;BT.markObserverRun();const{prompts:t}=e;try{const{request:e,headers:n}=await createRequestClient(),r={...n,[zt.SESSION_ID]:`observer-${Ie()}`},o=splitPromptsIntoBatches(t);dlog(`[Observer] ${t.length} prompts → ${o.length} batches`);const s=Math.min(o.length,6);for(let t=0;t<s;t++){if(BT.learningComplete){dlog(`[Observer] stopped at batch ${t} (learning complete)`);break}const n=o[t];try{await processBatch(e,r,n,t+1,o.length)}catch{}}dlog("[Observer] done")}catch(e){dlog(`[Observer] failed (non-critical): ${e instanceof Error?e.message:String(e)}`),BT.addEvent({type:"progress",message:"Continuing without live observations..."})}}Ut(),Ut(),vS(),LS(),rr(),Ut(),kn(),rr(),Ut(),Ut(),kn(),vS(),LS(),rr(),co(),Eo(),__name(createRequestClient,"createRequestClient"),Ut(),__name(splitPromptsIntoBatches,"splitPromptsIntoBatches"),__name(function calculateObservationsPerBatch(e){return 4},"calculateObservationsPerBatch"),Ut(),Ut(),rr(),Go(),Ut(),kn(),__name(buildObserverPrompt,"buildObserverPrompt"),__name(createInsightEmitter,"createInsightEmitter"),__name(callObserverAPI,"callObserverAPI"),__name(processBatch,"processBatch"),__name(observeSessionPrompts,"observeSessionPrompts");var pI=class{static{__name(this,"SessionImporter")}static async findClaudeCodeSessions(t=0){const n=[];try{const r=e.join(w.homedir(),".claude","projects");await C.access(r);const o=process.cwd().replace(/[/\\]/g,"-");dlog(`[Import] scanning project: ${o}`);const s=(await C.readdir(r)).filter(e=>e===o);for(const o of s){const s=e.join(r,o);try{if(!(await C.stat(s)).isDirectory())continue;const r=(await C.readdir(s)).filter(e=>e.endsWith(".jsonl")&&!e.includes(".checkpoints"));dlog(`[Import] found ${r.length} sessions`);for(const o of r){const r=e.join(s,o),i=await C.stat(r),a=o.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{BT.addEvent({type:"progress",message:"Scanning Codex sessions..."});const n=await findCodexSessions(process.cwd(),e=>{t?.(e),"reading"===e.phase&&BT.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{BT.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 C.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=[],o=0;for(const s of e){const e=estimateTokens(s);if(e>t){r.length>0&&(n.push(r),r=[],o=0);const e=this.splitLargePrompt(s,t);for(const t of e)n.push([t])}else o+e<=t?(r.push(s),o+=e):(r.length>0&&n.push(r),r=[s],o=e)}return r.length>0&&n.push(r),n}static splitLargePrompt(e,t){const n=[],r=e.split("\n");let o="",s=0;for(const e of r){const r=estimateTokens(e);s+r<=t?(o+=(o?"\n":"")+e,s+=r):(o&&n.push(o),o=e,s=r)}return o&&n.push(o),n}static async importAndLearn(){const e=[],t=[],n=[],r=[],o=[];try{BT.addEvent({type:"step_start",step:"importing",label:"Started Learning Taste",message:"Scanning for coding sessions..."});const s=await loadProjectSettings(),i=s.tasteOnboarding?.learnedSessions||{},a=i["claude-code"]?.length||0,l=i.codex?.length||0,u=i.cursor?.length||0;dlog(`[Import] loaded settings: claude-code=${a} learned, codex=${l} learned, cursor=${u} learned`);const d=await findNewSessions(i),m=d["claude-code"]||[],g=d.codex||[],h=d.cursor||[],f=m.length+g.length+h.length;if(dlog(`[Import] findNewSessions returned: claude-code=${m.length} new, codex=${g.length} new, cursor=${h.length} new`),0===f){const e=await this.findClaudeCodeSessions(),t=await findCodexSessions(process.cwd()),n=await findCursorSessions(process.cwd()),r=e.length+t.length+n.length,o=[{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}`);BT.addEvent({type:"step_start",step:"complete",label:"Taste Already Learned",message:r>0?`From ${o.join(" + ")} sessions`:"No sessions found for this project"});const s=[];return e.length>0&&s.push({agent:"claude-code",sessionIds:e.map(e=>e.id),displayName:"Claude Code"}),t.length>0&&s.push({agent:"codex",sessionIds:t.map(e=>e.id),displayName:"Codex"}),n.length>0&&s.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:s,status:"already-learned"}}if(m.length>0){const e=(await this.findClaudeCodeSessions()).filter(e=>m.includes(e.id));n.push(...e)}if(g.length>0){const e=(await this.findCodexSessions()).filter(e=>g.includes(e.id));r.push(...e)}if(h.length>0){const e=(await this.findCursorSessions()).filter(e=>h.includes(e.id));o.push(...e)}const y=n.length+r.length+o.length;dlog(`[Import] total sessions: ${y} (claude-code: ${n.length}, codex: ${r.length}, cursor: ${o.length})`),BT.addEvent({type:"step_start",step:"batching",label:"Organizing your sessions",message:""});const w=[{name:"Claude Code",sessions:n,extractPrompts:this.extractUserPrompts},{name:"Codex",sessions:r,extractPrompts:extractCodexPrompts},{name:"Cursor",sessions:o,extractPrompts:extractCursorPrompts}].filter(e=>e.sessions.length>0).sort((e,t)=>t.sessions.length-e.sessions.length);for(const n of w){BT.addEvent({type:"progress",message:`${n.name}: ${n.sessions.length} sessions`});for(const r of n.sessions)try{const e=await n.extractPrompts(r.filePath);e.length>0&&t.push(...e)}catch(t){e.push(`${n.name} import failed: ${t instanceof Error?t.message:String(t)}`)}}if(0===t.length)return{success:!1,totalPrompts:0,preferencesLearned:0,errors:["No prompts found in sessions"]};const S=this.splitPromptsIntoBatches(t);dlog(`[Import] batched: ${t.length} prompts → ${S.length} batches`);const E=observeSessionPrompts({prompts:t}).catch(e=>{dlog(`[Import] observer error: ${e instanceof Error?e.message:String(e)}`)});BT.addEvent({type:"step_start",step:"learning",label:"Learning your coding taste",message:`Processing ${S.length} batch${1===S.length?"":"es"}`});try{const s=getApiBaseUrl(),i=new rS({baseUrl:s});let a=!0;for(let e=0;e<S.length;e++){const t=S[e],n=e+1,r=S.length;r>1&&BT.addEvent({type:"progress",message:`Processing batch ${n}/${r}...`});const o=this.formatBatchLearning(t),s=new HT({request:i,sessionId:crypto.randomUUID(),projectRoot:process.cwd()}),l=[{role:"user",content:o}];dlog(`[Import] batch ${n}/${r}: ${t.length} prompts`),(await s.checkAndProcess({messages:l})).success||(a=!1,dlog(`[Import] batch ${n}/${r} failed`))}if(dlog(`[Import] all batches complete, success: ${a}`),BT.markLearningComplete(),await E,a){if(n.length>0){const e=n.map(e=>e.id);await markSessionsAsLearned("claude-code",e),dlog(`[Import] marked ${e.length} claude-code sessions as learned`)}if(r.length>0){const e=r.map(e=>e.id);await markSessionsAsLearned("codex",e),dlog(`[Import] marked ${e.length} codex sessions as learned`)}if(o.length>0){const e=o.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})`),o.length>0&&u.push(`Cursor (${o.length})`),!a){const s=BT.getEvents().some(e=>"error"===e.type&&e.message?.toLowerCase().includes("insufficient credits")),i="Learning failed - sessions not marked as learned";return e.push(i),s||BT.addEvent({type:"error",message:i}),{success:!1,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}return BT.addEvent({type:"step_start",step:"complete",label:"Learning Complete",message:`Learned from ${u.join(" + ")}`,learningCount:l.totalLearnings,categories:l.categories,storage:".commandcode/taste/taste.md"}),{success:!0,totalPrompts:t.length,preferencesLearned:l.totalLearnings,errors:e,totalSessions:y,agentSessions:[...n.length>0?[{agent:"claude-code",sessionIds:n.map(e=>e.id),displayName:"Claude Code"}]:[],...r.length>0?[{agent:"codex",sessionIds:r.map(e=>e.id),displayName:"Codex"}]:[],...o.length>0?[{agent:"cursor",sessionIds:o.map(e=>e.id),displayName:"Cursor"}]:[]]}}catch(n){const r=`Learning agent failed: ${n instanceof Error?n.message:String(n)}`;return e.push(r),BT.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 C.readFile(t,"utf-8"),r=n.match(/^- .+Confidence:/gm),o=r?r.length:0;return{totalLearnings:o,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")}},gI=__name(e=>new Promise((t,n)=>setTimeout(()=>n(new Error("Learning timed out. Try again with /learn-taste")),e)),"createTimeout"),hI=__name(e=>{const[t,n]=se({isImporting:!0,waitingForInput:!1,alreadyLearned:!1,learnedSessionCount:0,totalSessionCount:0,agentSessions:[],error:null});return ae(()=>{BT.reset(),BT.markImportStarted(),(async()=>{try{const t=await Promise.race([pI.importAndLearn(),gI(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");Ut();var fI=__name(({onEscape:e,onEnter:t,enabled:n=!0})=>{Z((r,o)=>{n&&(o.escape&&e(),(o.return||"\n"===r)&&t())})},"useKeyboardInput");Ut(),rr();var yI=__name(({autoLearn:e,onShouldSkip:t})=>{const[n,r]=se(null),[o,s]=se(null),i=ie(!1);return ae(()=>{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),s(r),n=setTimeout(()=>t(),2e3)}})(),()=>{n&&clearTimeout(n)}},[e,t]),{conditions:n,error:o,isLoading:!n&&!o}},"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{BT.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{BT.reset(),e()}}Ut(),rr(),Ut(),rr(),__name(completeOnboarding,"completeOnboarding"),__name(skipOnboarding,"skipOnboarding");var wI=__name(({onStepChange:e,onError:t,onCompleteCallback:n})=>{const r=ie(n),o=ce(()=>{dlog("[Handler] import started → learning"),e("learning")},[e]),s=ce(async()=>{dlog("[Handler] import complete → done"),e("done"),await completeOnboarding(()=>r.current())},[e]),i=ce(e=>{dlog(`[Handler] import error: ${e}`),t(e)},[t]),a=ce(async()=>{dlog("[Handler] error dismissed by user → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]),l=ce(async()=>{dlog("[Handler] skipped → done"),e("done"),await skipOnboarding(()=>r.current({skipped:!0}))},[e]);return n!==r.current&&(r.current=n),{handleImportStart:o,handleImportComplete:s,handleImportError:i,handleErrorDismiss:a,handleSkip:l}},"useOnboardingHandlers");Ut(),rr();var SI=__name(({conditions:e,autoLearn:t})=>{const[n,r]=se("checking"),o=ie(!1);return ae(()=>{if(e&&!o.current){if(o.current=!0,t)return dlog("[Flow] autoLearn → learning"),void r("learning");dlog(`[Flow] → asking (${e.reason})`),r("asking")}},[e,t]),ae(()=>{dlog(`[Flow] step: ${n}`)},[n]),{step:n,setStep:r}},"useOnboardingFlow");Ut(),Ut(),jr();var bI=__name(({error:e})=>re.createElement(K,{padding:1},re.createElement(K,{flexDirection:"column",borderColor:gr.RED,padding:1},re.createElement(K,{marginBottom:1},re.createElement(Y,null,"Error initializing onboarding: ",e)),re.createElement(K,null,re.createElement(Y,null,"Continuing without onboarding...")))),"OnboardingError");Ut(),Ut(),jr();var EI=__name(()=>re.createElement(Y,null,"Skip"),"SkipOptionText"),vI=__name(({sessionCount:e,agentSessions:t,onImport:n,onSkip:r})=>{const[o,s]=se(1);return Z((e,t)=>{t.escape?r():"n"!==e&&"N"!==e?t.upArrow||t.downArrow?s(e=>1===e?2:1):"1"!==e?"2"!==e?t.return&&(1===o?n():r()):r():n():dismissOnboardingForeverForProject().then(()=>r())}),re.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:fr.TEXT,paddingX:1,paddingY:0},re.createElement(Y,{color:fr.TEXT,bold:!0},"Build Your Coding Taste"),re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(Y,null,"Found"," ",1===e?"one session":`${e} sessions`," ","from"," ",t.map(e=>e.displayName).join(", ")," ","for this project."),re.createElement(K,{marginTop:1},re.createElement(Y,null,"Analyze"," ",1===e?"that session":"those sessions"," ","to build your coding taste package?"))),re.createElement(K,{marginTop:1,flexDirection:"column"},re.createElement(K,null,re.createElement(Y,{color:1===o?fr.TEXT:gr.GRAY},1===o?Me.pointer:" "," 1. Yes, learn (recommended)")),re.createElement(K,null,re.createElement(Y,{color:2===o?fr.TEXT:gr.GRAY},2===o?Me.pointer:" "," 2."," ",re.createElement(EI,null)))),re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"↑↓ · "),re.createElement(Y,{color:Rr.CODE},"enter"),re.createElement(Y,{color:gr.DIM}," ok · "),re.createElement(Y,{color:Rr.CODE},"esc"),re.createElement(Y,{color:gr.DIM}," skip · "),re.createElement(Y,{color:Rr.CODE},"n"),re.createElement(Y,{color:gr.DIM}," never")))},"ImportChoice");Ut(),Ut(),jr();var CI=__name(({error:e})=>re.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:gr.RED,paddingX:2,paddingY:1,marginBottom:2},re.createElement(Y,{color:gr.RED,bold:!0},"Oops, something went wrong:"),re.createElement(K,{marginTop:1},re.createElement(Y,null,e))),"ErrorSection");Ut(),Ut(),jr(),Ut(),Ut(),Ut(),jr(),Ut(),jr();var kI=__name(()=>re.createElement(Y,{backgroundColor:fr.BADGE_BG,color:fr.BADGE_FG},g_),"TasteBadge");Ut(),jr(),Ut();var TI=["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"],_I="⎿",xI=__name(()=>{const[e,t]=se(()=>Math.floor(Math.random()*TI.length));return ae(()=>{const e=setInterval(()=>{t(Math.floor(Math.random()*TI.length))},2e3);return()=>clearInterval(e)},[]),re.createElement(Y,{color:gr.YELLOW},TI[e],"...")},"PulsingText");Ut(),jr();var AI=[Me.bullet,Me.squareSmallFilled,Me.lozenge,Me.star,Me.triangleRight,Me.triangleUp,Me.circleFilled,Me.pointer],PI=__name(e=>String(e).padStart(3," "),"padNum"),II=__name(e=>AI[e%AI.length],"getSymbol"),MI=__name((e,t,n,r)=>r?`${e} observations (↑↓ scroll)`:`↑${PI(t)} ↓${PI(n)} (↑↓ scroll)`,"buildStatusLine"),NI=__name(({insights:e})=>{const[t,n]=se(0),[r,o]=se(!0),s=e.length,i=s>10,a=Math.max(0,s-10);if(ae(()=>{r&&i&&n(a)},[s,r,i,a]),Z((e,t)=>{if(i)return t.upArrow?(o(!1),void n(e=>Math.max(0,e-1))):void(t.downArrow&&n(e=>{const t=Math.min(a,e+1);return t===a&&o(!0),t}))}),0===s)return null;const l=e.slice(t,t+10),u=t,d=s-t-10;return re.createElement(K,{flexDirection:"column",marginLeft:4,marginBottom:0},i&&re.createElement(Y,{color:gr.DIM},MI(s,u,d,r)),l.map((e,n)=>{const r=t+n;return re.createElement(K,{key:r,marginBottom:0},re.createElement(Y,{color:gr.DIM},II(r)," ",e))}))},"ScrollableInsights");Ut(),jr();var RI=__name(()=>{const[e,t]=se(!0);return ae(()=>{const e=setInterval(()=>{t(e=>!e)},500);return()=>clearInterval(e)},[]),re.createElement(Y,{color:gr.YELLOW},e?Me.circleFilled:Me.circle)},"PulsingDot"),$I=__name(({label:e,message:t,active:n,complete:r,items:o,insights:s,isIntro:i,isAllComplete:a,summary:l})=>{if(i)return re.createElement(K,{flexDirection:"column",marginBottom:0},re.createElement(kI,null),re.createElement(K,{marginTop:0},re.createElement(Y,{color:gr.DIM},_I),re.createElement(K,{marginLeft:2},a?re.createElement(Y,{color:fr.TEXT},"learned your coding taste"):re.createElement(xI,null))));const u=__name(()=>r?re.createElement(Y,{color:br.BG},Me.square):n?re.createElement(RI,null):re.createElement(Y,{color:gr.DIM},Me.circle),"getStatusIcon"),d=o.length>0||s.length>0||t||l&&l.learningCount>0;return!r||n||d?re.createElement(K,{flexDirection:"column",marginBottom:0},(n||r)&&re.createElement(K,{marginBottom:0},re.createElement(K,{marginRight:1},u()),re.createElement(Y,{color:r?gr.WHITE:n?gr.YELLOW:gr.DIM},e)),r&&t&&(!l||0===l.learningCount)&&re.createElement(K,{marginLeft:3,marginBottom:0},re.createElement(Y,{color:gr.DIM},t)),o.length>0&&re.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},o.map((e,t)=>re.createElement(Y,{key:t,color:gr.DIM},`${Me.bullet} ${e}`))),s.length>0&&re.createElement(NI,{insights:s}),r&&l&&l.learningCount>0&&re.createElement(K,{flexDirection:"column",marginLeft:1,marginBottom:0},re.createElement(K,{marginBottom:1,flexDirection:"row"},re.createElement(Y,null,_I),re.createElement(K,{marginLeft:2},re.createElement(Y,{color:fr.TEXT},"Learned ",l.learningCount," preference",1===l.learningCount?"":"s",l.categories.length>0?` across ${l.categories.length} ${1===l.categories.length?"category":"categories"}`:""))),re.createElement(K,{flexDirection:"column",marginLeft:1},re.createElement(Y,{color:gr.DIM},Me.pointerSmall," Stored in ",l.storage),re.createElement(Y,{color:gr.DIM},"Command Code automatically uses & updates taste files.")))):null},"StepItem"),LI=__name(({steps:e})=>{const t=e.find(e=>"complete"===e.id)?.complete??!1;return re.createElement(K,{flexDirection:"column",marginBottom:1},e.map((e,n)=>re.createElement(K,{key:e.id,marginLeft:0===n?0:3},re.createElement($I,{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"),DI=__name(({steps:e})=>re.createElement(LI,{steps:e}),"ProgressSection");Ut(),jr();var OI=__name(({isImporting:e=!1,waitingForInput:t=!1})=>re.createElement(re.Fragment,null,e&&re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"ESC to cancel")),t&&re.createElement(K,{marginTop:1},re.createElement(Y,{bold:!0},"Press ENTER to continue"))),"HelpTextSection");Ut();var FI=[{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"}}],UI=__name(({onComplete:e,onError:t,onErrorDismiss:n})=>{const{steps:r,importError:o}=mI(FI),{isImporting:s,waitingForInput:i,error:a}=hI(t);return fI({onEscape:__name(()=>{i&&((a||o)&&n?n():e())},"onEscape"),onEnter:__name(()=>{i&&((a||o)&&n?n():e())},"onEnter"),enabled:s||i}),re.createElement(K,{flexDirection:"column",padding:1},o&&re.createElement(CI,{error:o}),!o&&re.createElement(DI,{steps:r}),re.createElement(OI,{isImporting:s,waitingForInput:i}))},"ImportProgress"),jI=__name(({step:e,conditions:t,onImportStart:n,onImportComplete:r,onImportError:o,onErrorDismiss:s,onSkip:i})=>"asking"===e?t&&"has_sessions"===t.reason?re.createElement(vI,{sessionCount:t.sessionCount,agentSessions:t.agentSessions,onImport:n,onSkip:i}):null:"learning"===e?re.createElement(UI,{onComplete:r,onError:o,onErrorDismiss:s}):null,"OnboardingStepRenderer"),BI=__name(({onComplete:e,autoLearn:t=!1})=>{ae(()=>(dlog("[UI:Onboarding] mounted"),()=>{dlog("[UI:Onboarding] unmounted")}),[]);const{conditions:n,error:r,isLoading:o}=yI({autoLearn:t,onShouldSkip:e}),{step:s,setStep:i}=SI({conditions:n,autoLearn:t}),{handleImportStart:a,handleImportComplete:l,handleImportError:u,handleErrorDismiss:d,handleSkip:m}=wI({onStepChange:__name(e=>{i(e)},"onStepChange"),onError:__name(()=>{},"onError"),onCompleteCallback:e});return dlog(`[UI:Onboarding] render: ${s}${n?.reason?` (${n.reason})`:""}${r?" ERROR":""}`),o?null:r?re.createElement(bI,{error:r}):"done"===s?null:re.createElement(jI,{step:s,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 o=[];for(const e of n)if(o.unshift(e),r-=getEntryCharCount(e),r<=0)break;return o}__name(getEntryCharCount,"getEntryCharCount"),__name(getBudgetedFeed,"getBudgetedFeed");var qI=oe(__name(function MainView2({feed:e,liveEntries:t,queuedMessages:n,isCmdCodeBusy:r,staticKey:o,setStaticKey:s,transcriptMode:i,tasteOnboardingEntryId:a,autoLearnTaste:l,showTasteSkipBanner:u,showZdrNotice:d,retryAttempt:m,input:g,setInput:h,fileSearchQuery:f,setFileSearchQuery:y,showFileList:w,setShowFileList:S,showProviderSelector:E,showModelSelector:v,showEffortSelector:C,showMemorySelector:k,showMcpManager:T,showAgentsConfig:_,showRewindSelector:x,showLoginOverlay:A,showUsageOverlay:P,showAddDirModal:I,showCompactModeSelector:M,showConfigureModels:N,setShowConfigureModels:R,authComponentInfo:$,status:L,currentProvider:D,currentModel:O,showProviderNotification:F,shareInfo:U,showShareNotification:j,unshareNotificationMessage:B,updateStatus:q,updateFailedInfo:z,creditWarning:W,permissionMode:H,hintMessage:G,pendingExitKey:V,tasteLearningEnabled:Q,interactionTokens:J,contextUsage:X,historyManagerRef:Z,executionState:ee,contextEngineRef:te,onSubmit:ne,onCommand:oe,onToggleAutoAccept:se,onResetPendingExitKey:ie,onDoubleEscapeEmpty:ae,onTasteOnboardingComplete:ue,permissionPanel:de,questionPanel:me,designSuggestionPanel:pe,onRewindSelect:ge,onRewindCancel:he,onLoginComplete:fe,onLoginCancel:ye,setShowProviderSelector:we,setShowModelSelector:Se,setShowEffortSelector:be,setShowMemorySelector:Ee,setShowMcpManager:ve,setShowAgentsConfig:Ce,setShowAddDirModal:ke,setShowUsageOverlay:Te,handleProviderSelect:_e,handleProviderCancel:xe,handleModelSelect:Ae,handleModelCancel:Pe,handleCompactModeSelect:Ie,handleCompactModeCancel:Me,handleAuthSuccess:Ne,handleAuthCancel:Re,showDesignGuide:$e,setShowDesignGuide:Le}){const De=le(()=>e.filter(e=>"taste-onboarding"!==e.role),[e]),Oe=ce(()=>Le(!1),[Le]),Fe=useTerminalWidth(),Ue=le(()=>"off"===i?De:getBudgetedFeed(De,"limited"===i?15e3:5e4),[De,i]),je=le(()=>"off"===i?0:Math.max(0,De.length-Ue.length),[De.length,Ue.length,i]),Be=le(()=>0===je?Ue:Ue.filter(e=>"user"!==e.role),[Ue,je]),qe=ce(()=>Ce(!1),[Ce]),ze=ce(()=>Ee(!1),[Ee]),We=ce(()=>ve(!1),[ve]),He=ce(()=>ke(!1),[ke]),Ge=ce(()=>Se(!0),[Se]),Ve=ce(()=>be(!1),[be]),Qe=ce(()=>{hardResetForResize(),s(e=>e+1)},[s]),Ke=!("off"!==i||de||me||pe||E||v||C||$||k||T||_||x||A||P||I||M||N||$e||a);return re.createElement(K,{flexDirection:"column",width:"100%"},re.createElement(YP,{staticKey:o,feed:Be,showHeader:!0,expandedToolOutput:"off"!==i,currentModel:O,currentProvider:D,hiddenCount:je}),a&&re.createElement(BI,{onComplete:ue,autoLearn:l}),u&&re.createElement(TasteSkipMessage,null),d&&re.createElement(ZdrPausedMessage,null),t.map(e=>e.metadata?.isAgent?re.createElement(XP,{key:e.id,entry:e}):re.createElement(K,{key:e.id,marginBottom:1,width:"90%"},renderFeedEntry(e,"off"!==i))),re.createElement(RetryMessage,{attempt:m}),pe,me,de,"off"!==i&&re.createElement(K,{flexDirection:"column",marginTop:1},re.createElement(K,null,re.createElement(Y,{color:gr.DIM},"─".repeat(Fe))),re.createElement(K,{paddingRight:1},re.createElement(Y,{backgroundColor:br.BG,color:br.FG,bold:!0},`${p_}DETAILED TRANSCRIPT${p_}`),re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{bold:!0},"ctrl+o"),re.createElement(Y,{color:gr.DIM}," to toggle"),re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{bold:!0},"ctrl+e"),re.createElement(Y,{color:gr.DIM}," ","to"," ","limited"===i?"show all":"collapse"),re.createElement(Y,{color:gr.DIM}," · "),re.createElement(Y,{bold:!0},"esc"),re.createElement(Y,{color:gr.DIM}," to exit"))),Ke&&re.createElement(zP,{queuedMessages:n,isProcessing:r,executionState:ee,status:L,input:g,setInput:h,onSubmit:ne,showFileList:w,setShowFileList:S,fileSearchQuery:f,setFileSearchQuery:y,onCommand:oe,outputTokens:J,contextUsage:X,tasteLearning:Q,shareInfo:U,showShareNotification:j,unshareNotificationMessage:B,updateStatus:q,updateFailedInfo:z,creditWarning:W,currentProvider:D,currentModel:O,showProviderInfo:F,permissionMode:H,onToggleAutoAccept:se,hintMessage:G,historyManager:Z.current,pendingExitKey:V,onResetPendingExitKey:ie,onDoubleEscapeEmpty:ae,retryAttempt:m,onAltP:Ge}),E&&re.createElement(K,{marginY:1},re.createElement(iI,{onSelect:_e,onCancel:xe,currentProvider:D})),v&&re.createElement(K,{marginY:1},re.createElement(oI,{onSelect:Ae,onCancel:Pe,currentModel:O,currentProvider:D,refreshBanner:Qe})),C&&re.createElement(K,{marginY:1},re.createElement(sI,{currentModel:O,onClose:Ve,refreshBanner:Qe})),$e&&re.createElement(K,{marginY:1},re.createElement(dI,{onCancel:Oe})),M&&re.createElement(K,{marginY:1},re.createElement(cP,{onSelect:Ie,onCancel:Me})),N&&re.createElement(K,{marginY:1},re.createElement(pP,{onClose:()=>R(!1)})),_&&re.createElement(K,{marginY:1},re.createElement(aP,{onCancel:qe})),k&&re.createElement(K,{marginY:1},re.createElement(GP,{onClose:ze})),T&&re.createElement(K,{marginY:1},re.createElement(HP,{onClose:We})),x&&te.current&&re.createElement(K,{marginY:1},re.createElement(lI,{checkpoints:te.current.listCheckpoints(),onSelect:ge,onCancel:he})),$&&re.createElement(K,{marginY:1},re.createElement($.Component,{onSuccess:Ne,onCancel:Re})),A&&re.createElement(K,{marginY:1},re.createElement(WP,{onComplete:fe,onCancel:ye})),I&&re.createElement(K,{marginY:1},re.createElement(HA,{onClose:He})))},"MainView"));function renderView({feedState:e,sessionState:t,statusState:n,authState:r,uiOverlays:o,onboarding:s,exitState:i,pendingOps:a,permissionState:l,contextEngineRef:u,historyManagerRef:d,executionState:m,actionCallbacks:g,onSubmit:h,onCommand:f,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,updateFailedInfo:v,creditWarning:C,handleTrust:k,handleNoTrust:T,handleToggleAutoAccept:_,handleDoubleEscapeEmpty:x,handleTasteOnboardingComplete:A,loadTasteStatus:P}){if(i.shouldExit)return null;if(s.checkingProject)return null;if(s.showTrustPrompt)return re.createElement(zx,{staticKey:o.staticKey,onTrust:k,onExit:T});if(o.showSessionSelector)return re.createElement(Vx,{onSelectSession:g.onSelectSession,onNewSession:g.onNewSession});if(!s.projectTrusted)return null;const I=o.pendingDesignSuggestion?re.createElement(jx,{suggestion:o.pendingDesignSuggestion,onSelect:e=>{f(`/design ${e}`)},onClose:()=>o.setPendingDesignSuggestion(null)}):null,M=a.pendingQuestion?re.createElement(QuestionView,{pendingQuestion:a.pendingQuestion,permissionMode:l.permissionMode,setPermissionMode:l.setPermissionMode,dangerouslySkipPermissions:l.dangerouslySkipPermissions,setPendingQuestion:a.setPendingQuestion,setStatus:n.setStatus,setStaticKey:o.setStaticKey}):null,N=a.pendingPermission?re.createElement(iA,{pendingPermission:a.pendingPermission,permissionMode:l.permissionMode,setPendingPermission:a.setPendingPermission,setStatus:n.setStatus,respondToPrompt:l.respondToPrompt,showHintMessage:n.showHintMessage,handleToggleAutoAccept:_}):null;return o.showLearningFeed?re.createElement(LearningView,{setShowLearningFeed:o.setShowLearningFeed,setStaticKey:o.setStaticKey,onExit:()=>i.setShouldExit(!0)}):o.showTasteConfig?re.createElement(TasteConfigView,{staticKey:o.staticKey,setShowTasteConfig:o.setShowTasteConfig,loadTasteStatus:P}):o.showSkillsConfig?re.createElement(SkillsConfigView,{staticKey:o.staticKey,setShowSkillsConfig:o.setShowSkillsConfig,setStaticKey:o.setStaticKey}):o.showUsageOverlay?re.createElement(UsageView,{staticKey:o.staticKey,setShowUsageOverlay:o.setShowUsageOverlay}):o.showContextView?re.createElement(ContextConfigView,{staticKey:o.staticKey,contextEngineRef:u,setShowContextView:o.setShowContextView,setInput:w}):o.showStatusView?re.createElement(StatusConfigView,{staticKey:o.staticKey,setShowStatusView:o.setShowStatusView,setInput:w}):re.createElement(qI,{feed:e.feed,liveEntries:e.liveEntries,queuedMessages:e.queuedMessages,isCmdCodeBusy:e.isCmdCodeBusy,staticKey:o.staticKey,setStaticKey:o.setStaticKey,transcriptMode:o.transcriptMode,tasteOnboardingEntryId:s.tasteOnboardingEntryId,autoLearnTaste:s.autoLearnTaste,showTasteSkipBanner:o.showTasteSkipBanner,showZdrNotice:o.showZdrNotice,retryAttempt:n.retryAttempt,input:y,setInput:w,fileSearchQuery:S,setFileSearchQuery:E,showFileList:o.showFileList,setShowFileList:o.setShowFileList,showProviderSelector:o.showProviderSelector,showModelSelector:o.showModelSelector,showEffortSelector:o.showEffortSelector,showMemorySelector:o.showMemorySelector,showMcpManager:o.showMcpManager,showAgentsConfig:o.showAgentsConfig,showRewindSelector:o.showRewindSelector,showLoginOverlay:o.showLoginOverlay,showUsageOverlay:o.showUsageOverlay,setShowUsageOverlay:o.setShowUsageOverlay,showAddDirModal:o.showAddDirModal,showCompactModeSelector:o.showCompactModeSelector,showConfigureModels:o.showConfigureModels,setShowConfigureModels:o.setShowConfigureModels,authComponentInfo:r.authComponentInfo,status:n.status,currentProvider:r.currentProvider,currentModel:r.currentModel,showProviderNotification:r.showProviderNotification,shareInfo:n.shareInfo,showShareNotification:n.showShareNotification,unshareNotificationMessage:n.unshareNotificationMessage,updateStatus:n.updateStatus,updateFailedInfo:v,creditWarning:C,permissionMode:l.permissionMode,hintMessage:n.hintMessage,pendingExitKey:i.pendingExitKey,tasteLearningEnabled:n.tasteLearningEnabled,interactionTokens:n.interactionTokens,contextUsage:n.contextUsage,historyManagerRef:d,executionState:m,contextEngineRef:u,onSubmit:h,onCommand:f,onToggleAutoAccept:_,onResetPendingExitKey:i.resetPendingExitKey,onDoubleEscapeEmpty:x,onTasteOnboardingComplete:A,permissionPanel:N,questionPanel:M,designSuggestionPanel:I,onRewindSelect:g.onRewindSelect,onRewindCancel:g.onRewindCancel,onLoginComplete:g.onLoginComplete,onLoginCancel:g.onLoginCancel,setShowProviderSelector:o.setShowProviderSelector,setShowModelSelector:o.setShowModelSelector,setShowEffortSelector:o.setShowEffortSelector,setShowMemorySelector:o.setShowMemorySelector,setShowMcpManager:o.setShowMcpManager,setShowAgentsConfig:o.setShowAgentsConfig,setShowRewindSelector:o.setShowRewindSelector,setShowLoginOverlay:o.setShowLoginOverlay,setShowAddDirModal:o.setShowAddDirModal,handleProviderSelect:g.handleProviderSelect,handleProviderCancel:g.handleProviderCancel,handleModelSelect:g.handleModelSelect,handleModelCancel:g.handleModelCancel,handleCompactModeSelect:g.handleCompactModeSelect,handleCompactModeCancel:g.handleCompactModeCancel,handleAuthSuccess:g.handleAuthSuccess,handleAuthCancel:g.handleAuthCancel,showDesignGuide:o.showDesignGuide,setShowDesignGuide:o.setShowDesignGuide})}__name(renderView,"renderView");var zI=__name(({resume:e=!1,resumeSessionId:t,continue:n=!1,trust:r=!1,dangerouslySkipPermissions:o=!1,updateStatus:s,updateFailedInfo:i,initialPrompt:a,skipOnboarding:l=!1,initialPermissionMode:u,sessionTitleHolder:d})=>{const{exit:m}=te(),{stdout:g}=X();ae(()=>{prefetchBillingContext()},[]);const[h,f]=se(""),[y,w]=se(""),S=ie(!1),E=ie(!1),v=ie(null),C=ie(null),k=useUiOverlays(),T=useFeed(),_=useSession(),x=useStatus(s),A=useAuth(),P=usePendingOps(),I=useOnboarding(),M=useExit(),{executeBash:N,executionState:R}=AT(),$=usePermissionMode({initialPermissionMode:u,dangerouslySkipPermissions:o,setPendingPermission:P.setPendingPermission,setStatus:x.setStatus,contextEngineRef:C}),{createContextEngineCallbacks:L}=useContextEngine({sessionId:_.sessionId,sessionLoaded:_.sessionLoaded,showSessionSelector:k.showSessionSelector,projectTrusted:I.projectTrusted,setFeed:T.setFeed,setLiveEntries:T.setLiveEntries,setQueuedMessages:T.setQueuedMessages,queuedMessagesRef:T.queuedMessagesRef,setStatus:x.setStatus,pinnedStatusRef:x.pinnedStatusRef,setRetryAttempt:x.setRetryAttempt,setInteractionTokens:x.setInteractionTokens,setContextUsage:x.setContextUsage,setCurrentProvider:A.setCurrentProvider,shareInfoRef:x.shareInfoRef,permissionsService:$.permissionsService,permissionModeRef:$.permissionModeRef,setPendingQuestion:P.setPendingQuestion,contextEngineRef:C}),{onCommand:D}=useCommandCtx({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:M,permissionState:$,contextEngineRef:C,isSubmittingRef:S,executeBash:N,createContextEngineCallbacks:L,setInput:f}),{loadTasteStatus:O,loadCurrentProvider:F,onSubmit:U}=useStartup({resume:e,resumeSessionId:t,continueLatest:n,trust:r,initialPrompt:a,stdout:g,feedState:T,sessionState:_,statusState:x,authState:A,onboarding:I,uiOverlays:k,permissionState:$,contextEngineRef:C,isSubmittingRef:S,initialPromptSubmittedRef:E,historyManagerRef:v,executeBash:N,createContextEngineCallbacks:L,setInput:f,onCommand:D});useLifecycle({exit:m,feedState:T,exitState:M,statusState:x,authState:A,onboarding:I,uiOverlays:k,skipOnboarding:l,contextEngineRef:C,sessionTitleHolder:d});const{handleToggleAutoAccept:j,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:q,handleTrust:z,handleNoTrust:W}=useHandlers({resume:e,feedState:T,onboarding:I,uiOverlays:k,exitState:M,pendingOps:P,permissionState:$,statusState:x,authState:A,contextEngineRef:C,loadTasteStatus:O,loadCurrentProvider:F,setInput:__name(e=>f(e),"setInput")}),H=useMainActionCallbacks({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,permissionState:$,contextEngineRef:C,createContextEngineCallbacks:L,setInput:f}),{creditWarning:G}=useCreditWarning({interactionTokens:x.interactionTokens});return renderView({feedState:T,sessionState:_,statusState:x,authState:A,uiOverlays:k,onboarding:I,exitState:M,pendingOps:P,permissionState:$,contextEngineRef:C,historyManagerRef:v,executionState:R,actionCallbacks:H,onSubmit:U,onCommand:D,input:h,setInput:f,fileSearchQuery:y,setFileSearchQuery:w,updateFailedInfo:i,creditWarning:G,handleTrust:z,handleNoTrust:W,handleToggleAutoAccept:j,handleDoubleEscapeEmpty:B,handleTasteOnboardingComplete:q,loadTasteStatus:O})},"InteractiveCLI");Zr(),ob(),lr(),jr();var WI=__name(e=>e.replace(/\x1B\[[0-9;]*[A-Za-z]/g,"").replace(/[\x00-\x1F\x7F]/g," ").trim(),"sanitizeTitleForOutput"),HI=ue.hex(gr.DIM),GI=__name(e=>{const t=getInvokedCommandName(),n=rt([e]);return`${HI("To continue this session, run:")}\n${HI(`${t} --resume ${n}`)}\n`},"formatResumeHint"),VI=__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"),QI=__name(e=>Boolean(e.resume||e.continue),"shouldValidateSessions"),KI=__name(({isInitialized:e,sessionCount:t})=>e&&0===t?{canProceed:!1,exitCode:0,message:"No conversations found to resume."}:{canProceed:!0},"validateSessionAvailability"),YI=__name(({options:e,resumeSessionId:t,sessionTitleHolder:n})=>{let r;return e.permissionMode?r=e.permissionMode:e.plan&&(r="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:r,sessionTitleHolder:n}},"buildInteractiveCLIProps"),JI=__name(()=>({stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,exitOnCtrlC:!1}),"getInkRenderOptions"),XI=__name(()=>{enableBracketedPasteMode(),process.on("exit",()=>{disableBracketedPasteMode()})},"setupBracketedPasteMode"),ZI=__name(()=>{XI()},"initializeTerminal"),eM=__name(async(e={})=>{const t=VI(process.stdin.isTTY);let n;if(t.isValid||(console.error(t.errorMessage),process.exit(1)),ZI(),"string"==typeof e.resume){const t=e.resume;await Hk.isProjectInitialized()||(console.error("Project not initialized. Run cmd to start a conversation first."),process.exit(1));const r=await Hk.findSessionByName(t);r||(console.error(`No session named "${t}" found.`),process.exit(1)),n=r.id}if(QI(e)&&!n){const e=await Hk.isProjectInitialized(),t=e?await Hk.listSessions():[],n=KI({isInitialized:e,sessionCount:t.length});n.canProceed||(console.log(n.message),process.exit(n.exitCode))}startEarlyInputCapture();const r={},o=YI({options:e,resumeSessionId:n,sessionTitleHolder:r}),s=JI(),i=ee(re.createElement(zI,{...o}),s);registerInkControl({clear:i.clear,stdout:process.stdout,instance:await resolveInkInstance(process.stdout)}),await i.waitUntilExit();const a=await(r.loadTitle?.());if(a){const e=WI(a);e&&process.stdout.write(GI(e))}},"interactiveMode");jo(),Ut(),kn(),zE(),AE();var tM=__name(async()=>{try{return await runLogin(),!!await getAuthKey()||(console.error(`${Me.cross} Authentication failed. Please try again with: cmd login`),!1)}catch(e){return isUserCancellation(e)||(console.error(`${Me.cross} Login failed: ${getErrorMessage2(e)}`),console.error("Please try again with: cmd login")),!1}},"attemptLogin");async function ensureAuthenticated(){try{return!!await getAuthKey()||tM()}catch(e){return console.error("Error checking authentication:",e),!1}}__name(ensureAuthenticated,"ensureAuthenticated"),co(),Ut(),kn(),io();var nM={bold:__name((e,t)=>t?`${e}`:e,"bold"),dim:__name((e,t)=>t?`${e}`:e,"dim"),green:__name((e,t)=>t?`${e}`:e,"green")};function modelNameOf(e){const t=e.lastIndexOf("/");return(-1===t?e:e.slice(t+1)).toLowerCase()}function displayModelId(e){return e.replace(Jr,"")}function resolveModelFlag({model:e}){const t=resolveKnownModelId(e);if(t)return t;const n=modelNameOf(e),r=getAllModelOptions().filter(e=>modelNameOf(e.id)===n);return 1===r.length?r[0].id:void 0}function editDistance(e,t){const n=e.length+1,r=t.length+1;let o=Array.from({length:r},(e,t)=>t);for(let s=1;s<n;s++){const n=[s];for(let i=1;i<r;i++){const r=e[s-1]===t[i-1]?0:1;n[i]=Math.min(o[i]+1,n[i-1]+1,o[i-1]+r)}o=n}return o[r-1]}function suggestModel(e){const t=e.trim().toLowerCase();if(!t)return;let n;for(const e of getAllModelOptions()){const r=displayModelId(e.id),o=Math.min(editDistance(t,r.toLowerCase()),editDistance(t,modelNameOf(r)));(!n||o<n.distance)&&(n={id:r,distance:o})}if(!n)return;const r=Math.min(4,Math.ceil(t.length/3));return n.distance<=r?n.id:void 0}function formatModelList(e={}){const t=e.color??!1,n=getModelGroupsInOrder(),r=n.flatMap(e=>e.models),o=Math.max(...r.map(e=>displayModelId(e.id).length)),s=n.map(e=>{const n=e.models.map(e=>{const n=displayModelId(e.id).padEnd(o),r=nM.dim(e.description,t);return`${n} ${"free"===e.badge?`${nM.green("FREE",t)} `:""}${r}${e.id===gn?` ${nM.green("(default)",t)}`:""}`});return[nM.bold(e.label,t),"",...n].join("\n")});return[`${nM.bold("Available models",t)} ${nM.dim(`· ${r.length} models`,t)}`,"",s.join("\n\n"),"",nM.dim('Pass the full id, or just the short name after the last "/":',t),"cmd --model moonshotai/Kimi-K2.5","cmd --model kimi-k2.5","","Docs: https://commandcode.ai/docs/reference/cli/models"].join("\n")}function printModelList(){const e=Boolean(process.stdout.isTTY)&&void 0===process.env.NO_COLOR;process.stdout.write(`${formatModelList({color:e})}\n`)}function resolveModelFlagOrExit({model:e}){const t=resolveModelFlag({model:e});if(t)return t;const n=suggestModel(e),r=n?` Did you mean "${n}"?`:"";process.stderr.write(`Error: unknown model "${e}".${r}\nRun "cmd --list-models" to see all available models\n`),process.exit(1)}__name(modelNameOf,"modelNameOf"),__name(displayModelId,"displayModelId"),__name(resolveModelFlag,"resolveModelFlag"),__name(editDistance,"editDistance"),__name(suggestModel,"suggestModel"),__name(formatModelList,"formatModelList"),__name(printModelList,"printModelList"),__name(resolveModelFlagOrExit,"resolveModelFlagOrExit");var rM=__name(e=>e&&!e.startsWith("-")?e:void 0,"parsePrompt"),oM=__name(async()=>{await ensureAuthenticated()||process.exit(1)},"requireAuth"),sM=__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"),iM=__name(({options:e,runtimeOptions:t,initialPrompt:n})=>{const r=e.resume??e.sessions;return r?{resume:r,...t}:e.continue?{continue:!0,...t}:{...t,initialPrompt:n}},"getInteractiveConfig"),aM=__name((e,t)=>"string"==typeof e.print&&e.print.trim()?e.print:t&&!t.startsWith("-")?t:"","extractPrintQuery");async function interactiveModeAction(e,t){if(t.listModels)return void printModelList();if(t.addDir&&t.addDir.length>0)for(const e of t.addDir)addDirectory(e);const n=t.model?resolveModelFlagOrExit({model:t.model}):void 0;if(void 0!==t.print){const r=aM(t,e);return void await printMode({query:r,dangerouslySkipPermissions:t.dangerouslySkipPermissions,maxTurns:t.maxTurns,verbose:t.verbose,model:n,benchmarkOutput:t.benchmarkOutput})}n&&setModelOverride(n);const r=rM(e);await oM();const o=sM(t),s=iM({options:t,runtimeOptions:o,initialPrompt:r});await eM(s)}__name(interactiveModeAction,"interactiveModeAction"),Ut(),rr(),Ps(),co(),_E(),zE();var lM=new Set(["update"]),cM=__name(()=>process.argv.slice(2).find(e=>!e.startsWith("-")),"getInvokedCommand");globalThis.COMMAND_CODE_CWD=process.cwd();var uM=__name(()=>process.cwd(),"getCwd"),dM=__name(()=>process.argv.slice(2),"getArgs"),mM=__name(e=>e.includes("--local")?"local":e.includes("--staging")?"staging":"production","getEnv"),pM=__name(()=>{const e=uM(),t=dM(),n=mM(t);dlog(`[Startup] cwd: ${e}`),dlog(`[Startup] args: ${t.join(" ")}`),dlog(`[Startup] env: ${n}`),dlog(`[Startup] traceId: ${getTraceId()??"unavailable"}`)},"logStartupInfo");async function preRun(){if(pM(),process.argv.includes("--ide-setup")){const e=await runIDESetup();formatSetupResult(e).forEach(e=>console.log(e)),process.exit("failed"===e.status?1:0)}const e=lM.has(cM()??"");e||(notifyCompletedUpdate(),maybeRunPendingUpdate()),await migrateDeprecatedModel(),await getAuthKey()&&detectAndTrackFirstInstall().catch(()=>{}),e||checkForUpdateAsync(),setTimeout(()=>ensureExtensionInstalled().catch(()=>{}),100).unref()}__name(preRun,"preRun"),Ut(),kn(),rr(),$o(),ob(),bo();var gM=getPackageJson(),hM=__name((e,t=[])=>[...t,e],"collectAddDir");function displayCustomHelp(){const e=gM.version,t=getInvokedCommandName(),n=Rk.filter(e=>!("/provider"===e.key&&!isInternalTeamFlagEnforced()));console.log(),console.log(ue.bold("Command Code")+ue.gray(` v${e}`)),console.log(ue.gray(Ak)),console.log(),console.log(ue.bold("Usage")),console.log(` ${t} <command> [options]`),console.log(),console.log(ue.bold("Options"));for(const e of Nk){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Pk)+ue.gray(e.description))}console.log(),console.log(ue.bold("Commands"));for(const e of $k){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Pk)+ue.gray(e.description))}console.log(),console.log(ue.bold("Slash Commands"));for(const e of n)console.log(" "+e.key.padEnd(Pk)+ue.gray(e.description));console.log(),console.log(ue.bold("Keyboard Shortcuts"));for(const e of Mk)console.log(" "+e.key.padEnd(Pk)+ue.gray(e.description));console.log(),console.log(ue.bold("Examples"));for(const e of Dk){const n=e.key.replace(/^cmd/,t);console.log(" "+n.padEnd(Pk)+ue.gray(e.description))}console.log(),console.log(ue.cyan("❯")+" "+ue.gray(Ok.replace(/cmd/,t))),console.log(),console.log(ue.bold("Links"));for(const e of Lk)console.log(" "+e.key.padEnd(Pk)+ue.cyan(e.description));console.log()}function createProgram(){const e=new Ne;return e.name(getInvokedCommandName()).description("Command Code with your coding taste.").version(gM.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("--sessions [name]","Alias of --resume — 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 Re("--dangerously-skip-permissions","Bypass all permission prompts (use with caution)").hideHelp()).addOption(new Re("--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 Re("--auto-accept","Start in auto-accept mode").implies({permissionMode:"auto-accept"})).addOption(new Re("--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",Ik).option("--add-dir <directory>","Add directory to workspace context",hM,[]).option("-m, --model <model>","Run on a specific model this session (e.g. claude-sonnet-4-6, kimi-k2.5). Unknown ids are rejected; see --list-models.").option("--list-models","List the models available for use").addOption(new Re("--benchmark-output <path>","Path to write benchmark metrics JSON").hideHelp()).addOption(new Re("--experimental","Enable experimental features").hideHelp()).addOption(new Re(Bt).hideHelp()).addOption(new Re(qt).hideHelp()).addOption(new Re("-d, --debug","Enable debug mode").hideHelp()).addOption(new Re("--local","Use local server").hideHelp()).addOption(new Re("--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 o=t.opts(),s=Object.entries(o).filter(([,e])=>void 0!==e&&!1!==e).map(([e,t])=>!0===t?`--${e}`:`--${e}=${t}`).join(" ");s&&dlog(`[cmd] options: ${s}`);const i=t.args;i.length>0&&dlog(`[cmd] arguments: ${i.join(" ")}`)}),e.hook("postAction",()=>{dlogSection("Done")})}function isTTY(){return Boolean(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.CI)}__name(displayCustomHelp,"displayCustomHelp"),__name(createProgram,"createProgram"),__name(setupCommanderHooks,"setupCommanderHooks"),Ut(),Ps(),Ko(),sE(),VE(),wE(),$o(),zE(),Ut(),__name(isTTY,"isTTY");var fM=!1;function setupTelemetry(){initTelemetry()&&(startSession(),registerStartupTask(trackSystemInfo()),trackCliSessionExistsEvent(),registerCleanupHandlers())}async function trackSystemInfo(){try{const e=w.platform(),t=w.arch();let n,r,o,s;try{const e=await getAuthenticatedEntity();e.success&&(n=e.user?.userName,r=e.user?.id,o=e.org?.login,s=e.org?.id)}catch{}if(!r)try{const e=await loadCredentials();r=e?.userId}catch{}systemInfo({userName:n,userId:r,orgLogin:o,orgId:s,platform:e,arch:t})}catch{}}function registerCleanupHandlers(){process.on("beforeExit",async()=>{await shutdownTelemetry()}),process.on("exit",()=>{shutdownTelemetrySync()}),process.on("SIGINT",handleShutdownSignal),process.on("SIGTERM",handleShutdownSignal)}function handleShutdownSignal(){fM||(fM=!0,shutdownTelemetry().finally(()=>{process.exit(0)}))}async function trackCliSessionExistsEvent(){try{if(!await getAuthKey())return;const e=getSessionId();if(!e)return;const t=getPackageJson().version||"unknown",n=w.platform(),r=w.arch(),o=isTTY()?"interactive":"non-interactive";await trackLifecycleEvent({eventType:"cli_session_exists",metadata:{sessionId:e,cliVersion:t,mode:o,os:`${n}-${r}`}})}catch{}}async function openGitHubIssue(e){const t=buildGitHubIssueUrl(e),n=$e("Opening GitHub issues...").start();try{await he(t,{wait:!1,background:!0}),n.succeed(`Opened ${createOSC8Link(t,"GitHub issue")} in your browser`),console.log("")}catch(e){n.fail("Failed to open browser"),console.log(""),console.log(createOSC8Link(t,"Open GitHub issue manually")),console.log("")}}__name(setupTelemetry,"setupTelemetry"),__name(trackSystemInfo,"trackSystemInfo"),__name(registerCleanupHandlers,"registerCleanupHandlers"),__name(handleShutdownSignal,"handleShutdownSignal"),__name(trackCliSessionExistsEvent,"trackCliSessionExistsEvent"),zE(),Ut(),yo(),__name(openGitHubIssue,"openGitHubIssue");var yM=new Ne("feedback").description("Open GitHub issues to share feedback or report bugs").argument("[title]","Optional issue title").action(openGitHubIssue);Ut();var wM=new Ne("help").description("Display help information").allowUnknownOption().allowExcessArguments().action(function(){this.parent?.help()});async function runInfo(e){const t=getSystemInfo(),{waitUntilExit:n}=ee(re.createElement(H_,{verbose:e.verbose,text:e.text,systemInfo:t}));await n()}Ut(),Ut(),__name(runInfo,"runInfo");var SM=new Ne("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}=ee(re.createElement(UI,{onComplete:__name(()=>{e(),process.exit(0)},"onComplete"),onErrorDismiss:__name(()=>{e(),process.exit(1)},"onErrorDismiss")}))}Ut(),kn(),Ut(),__name(runLearnTaste,"runLearnTaste"),rr(),Ps();var bM=new Ne(on.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:vs.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 Ne("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 Re("-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 o=getInvokedCommandName();try{let s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ue.red(`Error: Invalid server name '${e}'`)),console.error(ue.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(ue.red(`Error: Invalid transport type '${n.transport}'`)),console.error(ue.gray("Valid options: stdio, http")),process.exit(1));let i=!1;if("http"===n.transport){t||(console.error(ue.red("Error: URL is required for http transport")),console.error(ue.gray("Usage: cmd mcp add --transport http <name> <url>")),process.exit(1));try{new URL(t)}catch{console.error(ue.red(`Error: Invalid URL '${t}'`)),process.exit(1)}s={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(ue.gray("Checking server authentication requirements..."));const r=await checkServerAuthRequirements(t);if(r.error&&console.log(ue.yellow(`Warning: ${r.error}`)),r.requiresAuth&&r.metadata){console.log(ue.cyan("Server requires OAuth authentication.")),isSecureOrLoopback(t)||(console.error(ue.red(`Error: Server '${e}' requires OAuth, but URL '${t}' is not secure.`)),console.error(ue.gray("OAuth requires https:// (http:// is only allowed for loopback hosts: localhost, 127.0.0.1, [::1]).")),console.error(ue.gray("Switch the URL to https:// or use a non-OAuth server.")),process.exit(1));let n,o="command-code";if(r.metadata.registrationEndpoint){console.log(ue.gray("Registering OAuth client..."));const e=await registerOAuthClient({registrationEndpoint:r.metadata.registrationEndpoint,clientName:"Command Code CLI",redirectUris:[`http://127.0.0.1:${nb}/callback`]});e&&(o=e.clientId,n=e.clientSecret)}s.oauth={authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},console.log(ue.gray("A browser window will open for authentication.\n"));const a=await performOAuthFlow(e,t,{authorizationUrl:r.metadata.authorizationEndpoint,tokenUrl:r.metadata.tokenEndpoint,clientId:o,clientSecret:n,scopes:r.metadata.scopes},{onStatus:__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus")});a.success?console.log(ue.green("✓ Successfully authenticated")):(i=!0,console.log(ue.yellow(`Warning: Authentication failed: ${a.error}`)),console.log(ue.gray("You can retry with: cmd mcp auth "+e)),console.log(ue.gray("Or authenticate via the /mcp menu in a session")))}}else{const o=r.args,i=process.argv.indexOf("--");let a,l=[];if(-1!==i){const e=process.argv.slice(i+1);0===e.length&&(console.error(ue.red("Error: Command is required for stdio transport")),console.error(ue.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=o.indexOf(e);-1!==n&&o.length>n+2&&(l=o.slice(n+2))}else console.error(ue.red("Error: Command is required for stdio transport")),console.error(ue.gray("Usage: cmd mcp add --transport stdio <name> -- <command> [args...]")),console.error(ue.gray(" or: cmd mcp add <name> <command> [args...]")),process.exit(1);looksLikeHttpUrl2(a)&&(console.error(ue.red(`Error: '${a}' looks like a URL, not a local command.`)),console.error(ue.gray(`Did you mean: cmd mcp add --transport http ${e} ${a}`)),process.exit(1)),s={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:s,scope:n.scope});const a="user"===n.scope?"global":"project"===n.scope?"project":"local";if(i?console.log(ue.yellow(`✓ Added MCP server '${e}' to ${a} config (authentication pending)`)):console.log(ue.green(`✓ Added MCP server '${e}' to ${a} config`)),"http"===s.transport)console.log(ue.gray(` URL: ${s.url}`));else{const e=[s.command,...s.args||[]].join(" ");console.log(ue.gray(` Command: ${e}`))}console.log(""),console.log(ue.cyan("Next steps:")),console.log(ue.gray(`Start ${o} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function looksLikeHttpUrl2(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return!1}}function collectKeyValue(e,t){const[n,...r]=e.split("=");return n&&0!==r.length||(console.error(ue.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(ue.red(`Error: Invalid header format '${e}', expected 'Header: value'`)),process.exit(1));const r=e.substring(0,n).trim(),o=e.substring(n+1).trim();return r||(console.error(ue.red(`Error: Empty header name in '${e}'`)),process.exit(1)),t[r]=o,t}function listMcpCommand(){const e=new Ne("list");return e.description("List configured MCP servers").action(async()=>{try{const e=await listMcpServers();if(0===e.length)return console.log(ue.yellow("\nNo MCP servers configured\n")),console.log(ue.gray("Add a server with:")),console.log(ue.gray(" cmd mcp add --transport http <name> <url>")),console.log(ue.gray(" cmd mcp add --transport stdio <name> -- <command>")),void console.log(ue.gray("\nDocs: https://commandcode.ai/docs/mcp"));console.log(ue.hex("#E4CCFF").bold("\nMCP Servers\n"));const t=Math.max(4,...e.map(e=>e.name.length)),n=5,r=7;console.log(ue.dim(` ${"NAME".padEnd(t)} ${"TYPE".padEnd(n)} ${"SCOPE".padEnd(r)} AUTH STATUS`));for(const o of e){const e=o.config.enabled?ue.green("enabled"):ue.gray("disabled");let s;s=o.config.oauth?await hasTokens(o.name)?ue.green(Me.tick):ue.red(Me.cross):o.config.headers||o.config.env?ue.green(Me.tick):ue.gray("-"),console.log(` ${ue.white(o.name.padEnd(t))} ${ue.cyan(o.config.transport.padEnd(n))} ${ue.gray(o.scope.padEnd(r))} ${s} ${e}`)}console.log(ue.dim(`\nTotal: ${e.length} server${1!==e.length?"s":""}\n`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function getMcpCommand(){const e=new Ne("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(ue.red(`Error: MCP server '${e}' not found`)),process.exit(1));const{config:n,scope:r}=t;if(console.log(ue.hex("#E4CCFF").bold(`\nMCP Server: ${e}\n`)),console.log(` ${ue.dim("Scope:")} ${r}`),console.log(` ${ue.dim("Transport:")} ${n.transport}`),console.log(` ${ue.dim("Status:")} ${n.enabled?ue.green("enabled"):ue.gray("disabled")}`),"http"===n.transport){if(console.log(` ${ue.dim("URL:")} ${n.url}`),n.headers&&Object.keys(n.headers).length>0){console.log(` ${ue.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(` ${ue.dim("Command:")} ${n.command}`),n.args&&n.args.length>0&&console.log(` ${ue.dim("Args:")} ${n.args.join(" ")}`);if(n.env&&Object.keys(n.env).length>0){console.log(` ${ue.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(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function removeMcpCommand(){const e=new Ne("remove");return e.description("Remove an MCP server").argument("<name>","Server name").addOption(new Re("-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(ue.red(`Error: MCP server '${e}' not found`)),process.exit(1));const r=t.scope||n.scope;t.scope&&t.scope!==n.scope&&(console.error(ue.red(`Error: Server '${e}' is defined in '${n.scope}' scope, not '${t.scope}'`)),process.exit(1)),await removeMcpServer({name:e,scope:r})||(console.error(ue.red(`Error: Failed to remove server '${e}'`)),process.exit(1));const o="user"===r?"global":"project"===r?"project":"local";console.log(ue.green(`✓ Removed MCP server '${e}' from ${o} config`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function addJsonMcpCommand(){const e=new Ne("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 Re("-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 o,s;/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(e)&&!e.includes("__")||(console.error(ue.red(`Error: Invalid server name '${e}'`)),console.error(ue.gray("Names must start with a letter or number, contain only letters, numbers, hyphens, and single underscores")),process.exit(1));try{o=JSON.parse(t)}catch{console.error(ue.red("Error: Invalid JSON")),console.error(ue.gray("Make sure to quote the JSON string properly")),console.error(ue.gray(`Example: ${r} mcp add-json github '{"type":"stdio","command":"npx"}'`)),process.exit(1)}o?.oauth?.callbackPort&&(s=o.oauth.callbackPort,delete o.oauth.callbackPort),n.clientSecret&&o?.oauth&&(o.oauth.clientSecret=n.clientSecret);const i=WS.safeParse(o);if(!i.success){console.error(ue.red("Error: Invalid server configuration"));for(const e of i.error.issues)console.error(ue.gray(` ${e.path.join(".")}: ${e.message}`));process.exit(1)}const a=i.data;let l=!1;if("http"!==a.transport||a.url||(console.error(ue.red("Error: URL is required for http type")),process.exit(1)),"stdio"!==a.transport||a.command||(console.error(ue.red("Error: Command is required for stdio type")),process.exit(1)),await addMcpServer({name:e,serverConfig:a,scope:n.scope}),a.oauth){console.log(ue.cyan("Starting OAuth authentication...")),console.log(ue.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,a.url??"",t,{...s&&{port:s},onStatus:__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus")});n.success?console.log(ue.green(`\n✓ Successfully authenticated with '${e}'`)):(l=!0,console.error(ue.yellow(`\nWarning: Authentication failed: ${n.error}`)),console.error(ue.gray(`You can retry with: ${r} mcp auth ${e}`)),console.error(ue.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(ue.yellow(`✓ Added MCP server '${e}' to ${u} config (authentication pending)`)):console.log(ue.green(`✓ Added MCP server '${e}' to ${u} config`)),"http"===a.transport)console.log(ue.gray(` URL: ${a.url}`));else{const e=[a.command,...a.args||[]].join(" ");console.log(ue.gray(` Command: ${e}`))}console.log(""),console.log(ue.cyan("Next steps:")),console.log(ue.gray(`Start ${r} and run /mcp to manage configured MCP servers.`))}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function authMcpCommand(){const e=new Ne("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(ue.yellow("No servers with stored authentication."));console.log(ue.hex("#E4CCFF").bold("\nAuthenticated MCP Servers\n"));for(const t of e){const e=await getTokens(t),n=!e||isTokenExpired(e)?ue.yellow("expired"):ue.green("valid");console.log(` ${t}: ${n}`)}return void console.log("")}if(e||(console.error(ue.red("Error: Server name is required")),console.error(ue.gray(`Usage: ${n} mcp auth <server>`)),console.error(ue.gray(` ${n} mcp auth --list`)),process.exit(1)),t.status){if(!await hasTokens(e))return void console.log(ue.yellow(`No authentication stored for '${e}'`));const t=await getTokens(e);if(!t)return void console.log(ue.yellow(`No authentication stored for '${e}'`));if(isTokenExpired(t))console.log(ue.yellow(`Authentication for '${e}' has expired`)),t.refreshToken&&console.log(ue.gray(" A refresh token is available for re-authentication"));else{if(console.log(ue.green(`Authentication for '${e}' is valid`)),t.expiresAt){const e=Math.round((t.expiresAt-Date.now())/1e3/60);console.log(ue.gray(` Expires in ${e} minutes`))}t.scope&&console.log(ue.gray(` Scopes: ${t.scope}`))}return}if(t.clear)return void(await deleteTokens(e)?console.log(ue.green(`✓ Cleared authentication for '${e}'`)):console.log(ue.yellow(`No authentication stored for '${e}'`)));const r=await getMcpServer({name:e});r||(console.error(ue.red(`Error: MCP server '${e}' not found`)),console.error(ue.gray(`Use "${n} mcp list" to see configured servers`)),process.exit(1)),console.log(ue.cyan(`Authenticating with '${e}'...`)),console.log(ue.gray("A browser window will open for authentication.\n"));const o=__name(e=>{console.log(ue.gray(` ${e}`))},"onStatus");let s;if(r.config.oauth){const t={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};s=await performOAuthFlow(e,r.config.url??"",t,{onStatus:o})}else"http"===r.config.transport&&r.config.url||(console.error(ue.red("Error: Discovery-based auth requires an http server with a url")),process.exit(1)),s=await discoverAndAuthenticate({serverName:e,serverUrl:r.config.url,onStatus:o});if(s.success)return console.log(ue.green(`\n✓ Successfully authenticated with '${e}'`)),void console.log(ue.gray("Restart the session to connect with the authenticated server."));console.error(ue.red(`\nError: Authentication failed: ${s.error}`)),console.log(ue.gray(`Try again with "${n} mcp auth ${e}"`)),process.exit(1)}catch(e){console.error(ue.red(`Error: ${e instanceof Error?e.message:String(e)}`)),process.exit(1)}}),e}function createMcpCommand(){const e=new Ne("mcp");return e.description("Manage MCP (Model Context Protocol) servers").allowUnknownOption().allowExcessArguments(),e.addCommand(addMcpCommand()),e.addCommand(listMcpCommand()),e.addCommand(getMcpCommand()),e.addCommand(removeMcpCommand()),e.addCommand(addJsonMcpCommand()),e.addCommand(authMcpCommand()),e}async function runCommand(e){return new Promise((t,n)=>{const r=Ce(e.cmd,e.args,{stdio:["ignore","pipe","pipe"],env:process.env});let o="",s="";r.stdout.on("data",e=>{o+=String(e)}),r.stderr.on("data",e=>{s+=String(e)}),r.on("error",n),r.on("close",r=>{0!==r?n(new Error(`${e.cmd} ${e.args.join(" ")} failed${s?`: ${s.trim()}`:""}`)):t({stdout:o,stderr:s})})})}async function detectDefaultBranch(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"symbolic-ref","refs/remotes/origin/HEAD","--short"]}),n=t.trim().replace(/^origin\//,"");if(n)return n}catch{}for(const t of["main","master"])try{return await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--verify",t]}),t}catch{}try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"rev-parse","--abbrev-ref","HEAD"]});return t.trim()}catch{return"main"}}async function findGitRoot4(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.dir,"rev-parse","--show-toplevel"]});return t.trim()}catch{return null}}async function countLearnings(e){try{return(await C.readFile(e,"utf-8")).split("\n").filter(e=>e.trim().startsWith("- ")&&e.includes("Confidence:")).length}catch{return 0}}async function resolveSource(t){const n=t.source.trim(),r=e.resolve(n);try{if(!(await C.stat(r)).isDirectory())throw new Error(`Source must be a repository directory: ${n}`);return{type:"local",displayName:r,repoDir:r,repoName:e.basename(r),github:await inferGitHubRepo({repoDir:r})}}catch(e){if(e instanceof Error&&e.message.startsWith("Source must be"))throw e}const o=parseGitHubSource({source:n});if(!o){const e=n.startsWith("git@")?" SSH URLs are not supported. Use HTTPS or owner/repo instead.":"";throw new Error(`Unsupported source '${n}'.${e} Use a local path, GitHub HTTPS URL, or owner/repo.`)}const s=String(t.maxCommits??200),i=`https://github.com/${o.owner}/${o.repo}.git`,a=await C.mkdtemp(e.join(w.tmpdir(),"taste-learn-"));try{await runCommand({cmd:"git",args:["clone","--depth",s,"--single-branch",...t.branch?["--branch",t.branch]:[],"--",i,a]})}catch{throw await C.rm(a,{recursive:!0,force:!0}).catch(()=>{}),new Error(`Repository not found: ${o.owner}/${o.repo}. Check the owner and repo name, or verify it's a public repository.`)}return{type:"github",displayName:`${o.owner}/${o.repo}`,repoDir:a,repoName:o.repo,github:o,cleanup:__name(async()=>{await C.rm(a,{recursive:!0,force:!0})},"cleanup")}}function getTastePathForDir(t){return e.join(t.projectRoot,".commandcode","taste")}async function resolveDisplayName(t){if(t.startsWith("/")||t.startsWith(".")){const n=e.resolve(t),r=await findGitRoot4({dir:n});return r?e.basename(r):e.basename(n)}return t}function parseGitHubSource(e){const t=e.source.match(/^([\w.-]+)\/([\w.-]+)$/);if(t)return{owner:t[1],repo:t[2].replace(/\.git$/,"")};try{const t=new URL(e.source);if("github.com"!==t.hostname)return null;const n=t.pathname.split("/").filter(Boolean);return n.length<2?null:{owner:n[0],repo:n[1].replace(/\.git$/,"")}}catch{return null}}async function inferGitHubRepo(e){try{const{stdout:t}=await runCommand({cmd:"git",args:["-C",e.repoDir,"remote","get-url","origin"]});return parseGitHubSource({source:t.trim()})??void 0}catch{return}}async function feedToLearningAgent(e){const t=await getConfiguredProvider(),n=await getOAuthCredentials({provider:t});if(await isOAuthEnforced()&&!n?.token)throw new Error("Authentication required. Run: cmd login");n?.token&&validateOAuthToken({token:n.token,provider:t});const r=getApiBaseUrl(),o=new rS({baseUrl:r}),s=new HT({request:o,sessionId:crypto.randomUUID(),projectRoot:e.outputDir}),i=[{role:"user",content:e.compiledContext}];await s.checkAndProcess({messages:i})}function logLearnSummary(e){const{summary:t}=e;console.log(ue.cyan("\n ─── Results ───\n")),console.log(` Source: ${t.sourceName}`),console.log(` Signals: ${t.signalCount} extracted`),console.log(` Context: ${t.contextLength} chars compiled`),console.log(` Taste dir: ${t.tasteDir}`),console.log("")}function shouldContinueExtraction(e){return!(e.offset>=e.commitsLength||e.signalCount>=e.signalCap||e.commitsWithDiffs>=50)}async function extractAllSignals(e){e.onProgress?.("Collecting commits");const t=await collectCommits(e);if(0===t.length)return e.onProgress?.("No commits found"),{signals:[],commitCount:0};e.onProgress?.(`Found ${t.length} commits to analyze`);const n=e.maxSignals??50,r=[];let o=0;for(let s=0;shouldContinueExtraction({offset:s,commitsLength:t.length,signalCount:r.length,signalCap:n,commitsWithDiffs:o});s+=10){const i=t.slice(s,s+10);if(0===i.length)break;const a=await runBounded(5,i,async t=>({commit:t,subs:await getSubstitutions(e.repoDir,t.hash)}));for(const{commit:e,subs:t}of a){if(0===t.length)continue;o++;const s=groupCrossFilePatterns(t);for(const t of s.slice(0,5)){if(t.removed.length>200||t.added.length>200)continue;const o=[`Commit: ${e.subject}`];o.push(`File: ${t.file}`),t.context&&o.push(`In: ${t.context}`);const s=buildSnippet(t.codeBefore,t.added,t.codeAfter);if(s&&o.push(s),r.push({text:`${truncate3(t.removed,60)} → ${truncate3(t.added,60)}`,evidence:o,category:inferCategory(t.removed,t.added)}),r.length>=n)break}if(r.length>=n)break}}return e.onProgress?.(`Extracted ${r.length} diff signals from ${o} commits`),{signals:r,commitCount:t.length}}async function collectCommits(e){const t=buildAuthorPattern(e.author,e.authorAliases),n=t?.includes("|")??!1,r=t?[...n?["--extended-regexp"]:[],"--author",t,"--regexp-ignore-case"]:[],o=e.branch?[e.branch]:[],s=e.author?e.maxCommits:3*e.maxCommits,{stdout:i}=await runCommand({cmd:"git",args:["-C",e.repoDir,"log",...o,"--no-merges",...r,"--pretty=format:%H%x1f%aI%x1f%aN%x1f%s%x1e","-n",String(s)]});return i.split("").map(e=>e.trim()).filter(Boolean).map(e=>{const[t="",n="",r="",o=""]=e.split("");return{hash:t.trim(),subject:o.trim(),authorDate:n.trim(),authorName:r.trim()}}).filter(e=>!isDependencyBot(e.authorName,e.subject)).slice(0,e.maxCommits)}async function getSubstitutions(e,t){try{const{stdout:n}=await runCommand({cmd:"git",args:["-C",e,"show","--format=","-U3","--diff-algorithm=histogram","-b","--ignore-blank-lines","-M",t]}),r=[];let o="",s="",i=[],a=[],l=[];const u=2;let d=null;const m=__name(()=>{d&&(r.push({removed:d.removed,added:d.added,file:d.file,context:d.context,codeBefore:d.codeBefore.length>0?d.codeBefore:void 0,codeAfter:d.codeAfter.length>0?d.codeAfter:void 0}),d=null)},"commitPending"),g=__name(()=>{if(i.length>0&&a.length>0){const e=i.join("\n").trim(),t=a.join("\n").trim();e===t||isVersionBump(e,t)||isTrivialChange(e,t)||(m(),d={removed:e,added:t,file:o,context:s||void 0,codeBefore:[...l],codeAfter:[]})}i=[],a=[]},"flush");for(const e of n.split("\n")){if(e.startsWith("diff --git")){g(),m(),o=e.match(/b\/(.+)$/)?.[1]??"",s="",l=[],isNoiseFile(o)&&(o="");continue}if(e.startsWith("@@")){g(),m(),s=e.match(/@@ .+ @@\s*(.+)/)?.[1]?.trim()??"",l=[];continue}if(!o)continue;if(e.startsWith("-")&&!e.startsWith("---")){a.length>0&&g(),i.push(e.slice(1));continue}if(e.startsWith("+")&&!e.startsWith("+++")){a.push(e.slice(1));continue}g();const t=e.startsWith(" ")?e.slice(1):e;if(!t.trim())continue;const n=d;null!==n&&n.codeAfter.length<u&&(n.codeAfter.push(t),n.codeAfter.length>=u&&m()),l.push(t),l.length>u&&l.shift()}return g(),m(),r}catch(e){return process.env.DEBUG&&console.error(`[taste-learn] getSubstitutions failed for ${t}:`,e instanceof Error?e.message:e),[]}}function groupCrossFilePatterns(e){const t=new Map;for(const n of e){const e=`${n.removed.trim()}\0${n.added.trim()}`,r=t.get(e)??[];r.push(n),t.set(e,r)}const n=[];for(const[,e]of t)if(e.length>=2){const t=e.map(e=>e.file).join(", ");n.push({...e[0],file:t,context:`Same change across ${e.length} files`})}else n.push(e[0]);return n}Ut(),Ut(),ob(),__name(addMcpCommand,"addMcpCommand"),__name(looksLikeHttpUrl2,"looksLikeHttpUrl"),__name(collectKeyValue,"collectKeyValue"),__name(collectHeaders,"collectHeaders"),Ut(),__name(listMcpCommand,"listMcpCommand"),Ut(),__name(getMcpCommand,"getMcpCommand"),Ut(),__name(removeMcpCommand,"removeMcpCommand"),Ut(),ob(),__name(addJsonMcpCommand,"addJsonMcpCommand"),Ut(),ob(),__name(authMcpCommand,"authMcpCommand"),__name(createMcpCommand,"createMcpCommand"),Ut(),kn(),Ut(),GE(),Ut(),kn(),Ut(),__name(runCommand,"runCommand"),Ut(),__name(detectDefaultBranch,"detectDefaultBranch"),__name(findGitRoot4,"findGitRoot"),__name(countLearnings,"countLearnings"),__name(resolveSource,"resolveSource"),__name(getTastePathForDir,"getTastePathForDir"),__name(resolveDisplayName,"resolveDisplayName"),__name(parseGitHubSource,"parseGitHubSource"),__name(inferGitHubRepo,"inferGitHubRepo"),Ut(),vS(),LS(),co(),Eo(),__name(feedToLearningAgent,"feedToLearningAgent"),__name(logLearnSummary,"logLearnSummary"),Ut(),Ut(),__name(shouldContinueExtraction,"shouldContinueExtraction"),__name(extractAllSignals,"extractAllSignals"),__name(collectCommits,"collectCommits"),__name(getSubstitutions,"getSubstitutions"),__name(groupCrossFilePatterns,"groupCrossFilePatterns");var EM=5,vM=3;function buildSnippet(e,t,n){const r=e??[],o=n??[],s=t.split("\n").map(e=>e.trimEnd());if(0===s.length&&0===r.length&&0===o.length)return;let i,a=0;s.length>vM?(i=s.slice(0,vM-1),a=s.length-i.length):i=s;const l=i.length+(a>0?1:0),u=Math.max(0,EM-l),d=Math.min(r.length,Math.ceil(u/2)),m=Math.min(o.length,u-d),g=[];for(const e of r.slice(-d))g.push(` ${e.trimEnd()}`);for(const e of i)g.push(`→ ${e}`);a>0&&g.push(`→ ... (+${a} more changed ${1===a?"line":"lines"})`);for(const e of o.slice(0,m))g.push(` ${e.trimEnd()}`);return 0!==g.length?`Snippet:\n${g.join("\n")}`:void 0}__name(buildSnippet,"buildSnippet");var CM=[/package-lock\.json$/,/pnpm-lock\.yaml$/,/yarn\.lock$/,/CHANGELOG\.(md|yml|yaml)$/i,/\.versionbot\//,/\.min\.(js|css)$/,/dist\//,/\.map$/];function isNoiseFile(e){return CM.some(t=>t.test(e))}function isTrivialChange(e,t){return e.trim().length<3&&t.trim().length<3}function isVersionBump(e,t){const n=/^"?version"?\s*:\s*"?\d+\.\d+/;return n.test(e.trim())&&n.test(t.trim())}function inferCategory(e,t){const n=`${e} ${t}`.toLowerCase();return/import|require|from\s+['"]/.test(n)?"imports":/function|=>|async|return/.test(n)?"code-style":/class|interface|type\s+/.test(n)?"types":/test|describe|it\(|expect/.test(n)?"testing":/console|log|debug|error/.test(n)?"logging":/try|catch|throw|Error/.test(n)?"error-handling":"code-style"}function buildAuthorPattern(e,t){return t&&t.length>0?t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"):e??void 0}__name(isNoiseFile,"isNoiseFile"),__name(isTrivialChange,"isTrivialChange"),__name(isVersionBump,"isVersionBump"),__name(inferCategory,"inferCategory"),__name(buildAuthorPattern,"buildAuthorPattern");var kM=new Set(["renovate[bot]","renovate","dependabot[bot]","dependabot","greenkeeper[bot]","snyk-bot"]),TM=[/^update .+ digest to /i,/^update .+ action to /i,/^update .+ to v?\d/i,/^update lock file maintenance/i,/^update dependency .+ to /i,/^chore\(deps\)/i,/^bump .+ from .+ to /i,/^lock file maintenance/i];function isDependencyBot(e,t){const n=e.toLowerCase();return!!kM.has(n)||!(!n.includes("[bot]")||!TM.some(e=>e.test(t)))}function truncate3(e,t){const n=e.replace(/\n/g," ").trim();return n.length<=t?n:`${n.slice(0,t-3)}...`}async function runBounded(e,t,n){const r=[];let o=0;const s=__name(async()=>{for(;o<t.length;){const e=o++;r[e]=await n(t[e])}},"next");return await Promise.all(Array.from({length:Math.min(e,t.length)},()=>s())),r}function compileTasteContext(e){const{signals:t,repoName:n,author:r,commitCount:o}=e,s=r?`Target author: ${r}\n`:"",i=[];if(i.push(`# Dynamic Taste Analysis — Code Change Patterns\n\nRepository: ${n}\n${s}Commits analyzed: ${o}\nSignals extracted: ${t.length}\n\nThis analysis was generated by examining actual code changes (diffs, substitutions, refactoring patterns) rather than static file contents. Every signal below comes from real commits.`),t.length>0){const e=["## Correction Diffs — What Wrong→Right Looks Like"];for(const n of t.slice(0,50)){e.push(`\n**${n.text}**`);for(const t of n.evidence)e.push(`- ${t}`)}i.push(e.join("\n"))}const a=r?` for ${r}`:"";return i.push(`## Instructions for Taste Learning\n\nYou are analyzing code change patterns from a real repository${a}. Based on the correction diffs above, generate deeply personal and opinionated coding taste.\n\n**Critical guidelines:**\n\n1. **Be specific, not generic.** Instead of "Use TypeScript", write "Use branded types for IDs and explicit return types on every function. Prefer \`readonly\` arrays and objects by default."\n\n2. **Extract the WHY from patterns.** If you see verbose names being replaced with concise ones, don't just say "use short names" — say "Prefer concise variable names that derive meaning from context rather than encoding type information."\n\n3. **Look for recurring themes.** If multiple substitutions show the same pattern (e.g., nested if→guard clauses), that's a strong taste signal worth capturing.\n\n4. **Make it actionable.** Every taste entry should be specific enough that another developer could follow it and produce code that looks like it belongs in this repository.\n\n5. **Prioritize quality corrections** — these are the purest taste signals (wrong→right pairs with explicit WHY context from commit messages).\n\n6. **Capture anti-patterns too.** If you see code being removed in refactors, note what the developer avoids: "Never nest deeper than 2 levels — flatten with early returns."\n\n7. **Don't repeat generic tool preferences** like "Use pnpm" or "Use TypeScript" unless the substitutions show something specific about HOW they use those tools.\n\n8. **Prioritize opinionated preferences.** The goal is taste that makes someone's code distinctly theirs — not industry best practices.\n\nWrite the taste entries to the taste.md file using the standard format with confidence scores.`),i.join("\n\n")}async function runLearnPipeline(t){const n=__name(()=>({outputDir:"",tasteDir:"",sourceName:t.source,signalCount:0,contextLength:0}),"abortedResult");if(t.needsAuth){BT.addEvent({type:"auth_required",step:"auth",message:"Login to synthesize your taste profile",label:"Signing in"});try{await BT.waitForAuth()}catch{return BT.emitStepStart({step:"complete",label:"Login skipped",message:"Login skipped",learningCount:0,storage:""}),BT.markLearningComplete(),{summary:n()}}}t.isLocalSource||BT.emitStepStart({step:"cloning",label:"Cloning repository",message:`Cloning ${t.source}`});const r=await resolveSource({source:t.source,maxCommits:t.maxCommits});if(t.signal.aborted)return{summary:n(),resolved:r};const o="github"===r.type,s=r.repoName,i=await findGitRoot4({dir:r.repoDir});if(!i)throw new Error(`Not a git repository: ${r.repoDir}. Run inside a git repo or pass the path: npx taste learn /path/to/repo`);const a=o?e.resolve(process.cwd(),s):i;o&&BT.emitStepStart({step:"collecting",label:"Collecting commits",message:`Cloned ${r.displayName} → ${a}`});const l=t.branch??await detectDefaultBranch({repoDir:i});await C.mkdir(a,{recursive:!0}),BT.emitStepStart({step:"collecting",label:"Collecting commits",message:`Fetching up to ${t.maxCommits} commits from ${l}`});const{signals:u,commitCount:d}=await extractAllSignals({repoDir:i,maxCommits:t.maxCommits,maxSignals:t.maxSignals,branch:l,onProgress:__name(e=>{BT.emitProgress({step:"extracting",message:e})},"onProgress")});if(t.signal.aborted)return{summary:n(),resolved:r};if(0===u.length)throw new Error("No signals extracted. Check the repository has commit history.");BT.emitStepStart({step:"extracting",label:"Extracting taste signals",message:`${u.length} before/after code changes extracted`}),BT.emitStepStart({step:"compiling",label:"Compiling taste context",message:`Formatting ${u.length} signals for the learning agent`});const m=compileTasteContext({signals:u,repoName:s,commitCount:d});if(t.signal.aborted)return{summary:n(),resolved:r};BT.emitStepStart({step:"learning",label:"Learning taste",message:"Interpreting code change patterns with AI"}),await feedToLearningAgent({compiledContext:m,outputDir:a});const g=getTastePathForDir({projectRoot:a}),h=e.join(g,"taste.md"),f=await countLearnings(h);return BT.emitStepStart({step:"complete",label:"Taste learned",message:"Taste learned",learningCount:f,storage:h}),BT.markLearningComplete(),{summary:{outputDir:a,tasteDir:g,sourceName:r.displayName,signalCount:u.length,contextLength:m.length},resolved:r}}__name(isDependencyBot,"isDependencyBot"),__name(truncate3,"truncate"),__name(runBounded,"runBounded"),Ut(),__name(compileTasteContext,"compileTasteContext"),__name(runLearnPipeline,"runLearnPipeline"),Ut(),Ut(),Ut();var _M=[/MallocStackLogging: can't turn off malloc stack logging because it was not enabled/i];function shouldIgnoreChunk(e){return _M.some(t=>t.test(e))}function chunkToString(e){return"string"==typeof e?e:Buffer.isBuffer(e)?e.toString("utf-8"):""}async function withFilteredStderrNoise(e){const t=process.stderr.write.bind(process.stderr);process.stderr.write=(e,...n)=>{const r=chunkToString(e);return!(!r||!shouldIgnoreChunk(r))||("function"==typeof n[0]?t(e,n[0]):t(e,n[0],n[1]))};try{return await e()}finally{process.stderr.write=t}}function toRepoLearnErrorMessage(e){return e instanceof Error?e.message:String(e)}function isRepoLearnMetricLikeText(e){const t=e.trim().toLowerCase();return/^\d+\s/.test(t)||/^saved\s/.test(t)||/^output\s/.test(t)||/^target\s/.test(t)||/\bcandidates\b/.test(t)||/\bevidence records\b/.test(t)||/\bhistory and review signals\b/.test(t)}function truncateRepoLearnPanelText(e,t=12){return truncateString({text:e,maxChars:Math.min(96,getEffectiveWidth({padding:t}))})}__name(shouldIgnoreChunk,"shouldIgnoreChunk"),__name(chunkToString,"chunkToString"),__name(withFilteredStderrNoise,"withFilteredStderrNoise"),Ut(),bs(),__name(toRepoLearnErrorMessage,"toRepoLearnErrorMessage"),__name(isRepoLearnMetricLikeText,"isRepoLearnMetricLikeText"),__name(truncateRepoLearnPanelText,"truncateRepoLearnPanelText"),Ut(),Ut();var xM=[{id:"collecting",label:"Collecting commits from repository"},{id:"extracting",label:"Extracting taste signals from diffs"},{id:"compiling",label:"Compiling taste context"},{id:"learning",label:"Learning taste from change patterns"},{id:"complete",label:"Taste learned"}],AM=[{id:"cloning",label:"Cloning repository"},...xM],PM=[Me.bullet,Me.squareSmallFilled,Me.lozenge,Me.star,Me.triangleRight,Me.triangleUp];function createInitialRepoLearnSteps(e){return(e??xM).map(e=>({...e,status:"pending"}))}__name(createInitialRepoLearnSteps,"createInitialRepoLearnSteps"),Ut();var IM={learningCount:0,storage:"",topLearnings:[]};function getStepStatus(e,t){return e<t?"complete":e===t?"active":"pending"}function deriveStepStates(e,t){return e.map((e,n)=>({...e,status:getStepStatus(n,t)}))}function parseSummaryMetric(e){if(e.startsWith("Maintainer: "))return{maintainerLabel:e.replace(/^Maintainer:\s+/,"")};const t=e.match(/^(\d+)\s+maintainer-specific preferences$/);if(t)return{maintainerCount:Number(t[1])};const n=e.match(/^(\d+)\s+repository conventions$/);return n?{repoCount:Number(n[1])}:null}__name(getStepStatus,"getStepStatus"),__name(deriveStepStates,"deriveStepStates"),__name(parseSummaryMetric,"parseSummaryMetric");var MM=__name(e=>e.map(e=>({...e,status:"complete"})),"markAllStepsComplete"),NM=__name(e=>e??IM,"withBase");function useRepoLearnState(e){const t=e??xM,[n,r]=se(()=>createInitialRepoLearnSteps(t)),[o,s]=se(""),[i,a]=se([]),[l,u]=se(null),[d,m]=se(!1),[g,h]=se(!1),[f,y]=se(null),[w,S]=se(0),E=ie(null),[v,C]=se(null),k=ce(()=>{E.current=Date.now()},[]);return ae(()=>{const e=__name(()=>{r(createInitialRepoLearnSteps(t)),s(""),a([]),u(null),h(!1),y(null),S(0),E.current=null,C(null),m(!1)},"handleReset"),n=__name(e=>{if("error"===e.type)return y(e.message),h(!0),r(MM),void s("");if("auth_required"!==e.type){if("step_start"===e.type&&e.step){const n=t.findIndex(t=>t.id===e.step);return n>=0&&r(deriveStepStates(t,n)),s(e.message||e.label||""),void("complete"===e.step&&u(t=>{const n=NM(t);return{...n,learningCount:e.learningCount??n.learningCount,storage:e.storage??n.storage}}))}"progress"!==e.type||"complete"!==e.step?"progress"!==e.type?"insight"===e.type&&(isRepoLearnMetricLikeText(e.message)||("complete"!==e.step?(S(e=>e+1),a(t=>[...t,e.message].slice(-4))):u(t=>{const n=NM(t);return{...n,topLearnings:[...n.topLearnings,e.message].slice(0,3)}}))):s(e.message):u(t=>{const n=NM(t),r=parseSummaryMetric(e.message);return r?{...n,...r}:n})}else m(!0)},"handleEvent"),o=__name(()=>{h(e=>e||(r(MM),!0)),s(""),E.current&&C(Math.round((Date.now()-E.current)/1e3))},"handleComplete");return BT.on("reset",e),BT.on("new-event",n),BT.on("learning-complete",o),()=>{BT.off("reset",e),BT.off("new-event",n),BT.off("learning-complete",o)}},[t]),{steps:n,currentMessage:o,insights:i,insightCount:w,summary:l,done:g,error:f,showLogin:d,setShowLogin:m,elapsedSeconds:v,markStarted:k}}__name(useRepoLearnState,"useRepoLearnState"),Ut(),Ut(),jr();var RM=__name(({isComplete:e,hasError:t})=>re.createElement(K,{flexDirection:"column",marginTop:1,marginBottom:0},re.createElement(kI,null),re.createElement(K,{marginTop:0},re.createElement(Y,{color:gr.DIM},_I),re.createElement(K,{marginLeft:2},t?re.createElement(Y,{color:gr.DIM},"learning interrupted"):e?re.createElement(Y,{color:fr.TEXT},"learned your coding taste"):re.createElement(xI,null)))),"RepoLearnTastePill");Ut(),jr();var $M=__name(({status:e})=>"active"===e?re.createElement(K,null,re.createElement(Y,{color:gr.YELLOW},re.createElement(ze,{type:"dots"})),re.createElement(Y,null," ")):"complete"===e?re.createElement(Y,{color:br.BG},Me.square," "):re.createElement(Y,{color:gr.DIM},Me.circle," "),"StepStatusIndicator"),LM=__name(({steps:e,currentMessage:t})=>re.createElement(K,{flexDirection:"column",marginTop:1},e.map(e=>{const n="active"===e.status;return re.createElement(K,{key:e.id,flexDirection:"column",marginBottom:0,marginLeft:3},re.createElement(K,null,re.createElement(K,{marginRight:1},re.createElement($M,{status:e.status})),re.createElement(Y,{bold:n,color:"complete"===e.status?gr.WHITE:n?gr.YELLOW:gr.DIM},e.label)),n&&t?re.createElement(K,{marginLeft:3},re.createElement(Y,{color:gr.DIM},truncateRepoLearnPanelText(t))):null)})),"RepoLearnStepList");Ut(),jr();var DM=__name(({insights:e,insightCount:t})=>0===e.length?null:re.createElement(K,{flexDirection:"column",marginTop:1,marginLeft:4},re.createElement(Y,{color:gr.CYAN},t>0?`Recent signals · ${t} ${1===t?"preference":"preferences"} learned`:"Recent signals"),e.map((e,t)=>re.createElement(Y,{key:`${t}-${e}`,color:gr.DIM},PM[t%PM.length]," ",truncateRepoLearnPanelText(e,14)))),"RepoLearnRollingInsights");Ut(),jr();var OM=__name(({message:e})=>re.createElement(K,{flexDirection:"column",borderStyle:"single",borderColor:gr.RED,paddingX:2,paddingY:1,marginTop:1},re.createElement(Y,{color:gr.RED,bold:!0},"Oops, something went wrong:"),re.createElement(K,{marginTop:1},re.createElement(Y,null,e))),"RepoLearnErrorPanel");Ut(),jr(),uo();var FM=__name(({summary:e,elapsedSeconds:n})=>{if(!e)return null;const r=t.relative(process.cwd(),e.storage),o=e.learningCount>0;return re.createElement(K,{flexDirection:"column",marginLeft:3},re.createElement(K,{marginBottom:1,flexDirection:"row"},re.createElement(Y,{color:gr.DIM},_I),re.createElement(K,{marginLeft:2},re.createElement(Y,{color:fr.TEXT},o?`Learned ${e.learningCount} ${1===e.learningCount?"preference":"preferences"}`:"Taste profile initialized",n?` in ${n} ${1===n?"second":"seconds"}`:""))),re.createElement(K,{flexDirection:"column",marginLeft:1},re.createElement(K,null,re.createElement(Y,{color:gr.DIM},Me.pointerSmall," Taste stored in"," "),re.createElement(ao,{url:`file://${e.storage}`,text:r||".commandcode/taste/taste.md",color:gr.CYAN})),re.createElement(K,null,re.createElement(Y,{color:gr.DIM},Me.pointerSmall," Share your coding taste:"," ",re.createElement(Y,{color:gr.CYAN},"npx taste push --all")))),re.createElement(K,{marginTop:1,marginLeft:1},re.createElement(Y,{color:gr.DIM},o?"Command Code automatically uses & updates taste files as you code.":"Command Code will learn your preferences as you code.")))},"RepoLearnCompletionSummary");Ut(),jr();var UM=__name(({done:e,error:t})=>t?re.createElement(K,{marginTop:1},re.createElement(Y,{bold:!0},"Press ESC to exit")):e?re.createElement(K,{marginTop:1},re.createElement(Y,{bold:!0},"Press ENTER to continue")):re.createElement(K,{marginTop:1},re.createElement(Y,{color:gr.DIM},"ESC to cancel")),"RepoLearnFooter");Ut(),jr();var jM=__name(({text:e,repoName:t})=>{const n=useTerminalWidth(),r=le(()=>pA(n),[n]);return re.createElement(K,{flexDirection:"column"},re.createElement(K,{flexDirection:"column",marginBottom:1},re.createElement(SA,null,r.trimEnd())),e?re.createElement(Y,{color:gr.WHITE},e):re.createElement(re.Fragment,null,re.createElement(Y,{color:gr.WHITE},"Learning your coding taste from"," ",re.createElement(Y,{bold:!0,color:gr.CYAN},t??"repository")),re.createElement(Y,{color:gr.DIM},"This may take a few minutes depending on repository size")))},"RepoLearnHeader");function StatusPanel({error:e,done:t,summary:n,elapsedSeconds:r,insights:o,insightCount:s}){return e?re.createElement(OM,{message:e}):t?re.createElement(FM,{summary:n,elapsedSeconds:r}):re.createElement(DM,{insights:o,insightCount:s})}function RepoLearnProgressApp({runTask:e,onExit:t,stepOrder:n,headerText:r,repoName:o}){const s=useRepoLearnState(n),i=ie(!1);return ae(()=>{i.current||(i.current=!0,s.markStarted(),e().catch(()=>{}))},[e,s.markStarted]),Z((e,n)=>{if(s.showLogin)return;const r=n.escape||""===e,o=n.return||"\n"===e||"\r"===e;r?t({published:!1,cancelled:!0}):(s.done||s.error)&&o&&t({published:!1,cancelled:!!s.error})}),s.showLogin?re.createElement(K,{flexDirection:"column"},re.createElement(jM,{text:r,repoName:o}),re.createElement(WP,{onComplete:(e,t)=>{s.setShowLogin(!1),e?BT.resolveAuth():BT.rejectAuth(t)},onCancel:()=>{s.setShowLogin(!1),BT.rejectAuth("Login cancelled"),t({published:!1,cancelled:!0})}})):re.createElement(K,{flexDirection:"column"},re.createElement(jM,{text:r,repoName:o}),re.createElement(RM,{isComplete:s.done&&!s.error,hasError:Boolean(s.error)}),re.createElement(LM,{steps:s.steps,currentMessage:s.currentMessage}),re.createElement(StatusPanel,{error:s.error,done:s.done,summary:s.summary,elapsedSeconds:s.elapsedSeconds,insights:s.insights,insightCount:s.insightCount}),re.createElement(UM,{done:s.done,error:s.error}))}async function runRepoLearnProgress(e){return withFilteredStderrNoise(()=>renderProgressUI(e))}function renderProgressUI(e){return new Promise((t,n)=>{BT.reset();const r=new AbortController;let o,s,i=!1,a=!1;const l=__name(async()=>{try{o=await e.runTask(r.signal)}catch(e){r.signal.aborted||(s=e,BT.addEvent({type:"error",message:toRepoLearnErrorMessage(e)}),BT.markLearningComplete())}},"handleRunTask"),u=__name(({published:e,cancelled:l})=>{a||(a=!0,i=e,r.abort(),d.unmount(),BT.reset(),s?n(s):t({result:o,published:i,cancelled:l}))},"handleExit"),d=ee(re.createElement(RepoLearnProgressApp,{stepOrder:e.stepOrder,headerText:e.headerText,repoName:e.repoName,runTask:l,onExit:u}));d.waitUntilExit().catch(e=>{BT.reset(),n(e)})})}__name(StatusPanel,"StatusPanel"),__name(RepoLearnProgressApp,"RepoLearnProgressApp"),__name(runRepoLearnProgress,"runRepoLearnProgress"),__name(renderProgressUI,"renderProgressUI"),zE();var BM=__name(e=>t=>{const n=parseInt(t,10);if(isNaN(n)||n<1)throw new Error(`${e} must be a positive integer`);return n},"parsePositiveInt");function createLearnCommand(){return new Ne("learn").description("Learn coding taste from repository change history").argument("[source]","Local path, GitHub URL, or owner/repo (defaults to current directory)").option("--max-commits <number>","Maximum commits to analyze",BM("--max-commits"),200).addOption(new Re("--max-signals <number>","Maximum diff signals to extract").default(50).argParser(BM("--max-signals")).hideHelp()).option("--branch <name>","Branch to analyze (defaults to main/master)").action(async(e,t)=>{try{await learnTaste({source:e??".",maxCommits:t.maxCommits??200,maxSignals:t.maxSignals??50,branch:t.branch})}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`Error: ${t}`),process.exit(1)}})}async function learnTaste(t){const n=await C.stat(e.resolve(t.source)).then(e=>e.isDirectory()).catch(()=>!1),r=isTTY(),o=await resolveDisplayName(t.source),s=!await getAuthKey();if(s&&!r)return console.log(""),console.log(" Login required to learn taste."),console.log(""),console.log(" Run: cmd login"),console.log(` Then: npx taste learn ${t.source}`),void console.log("");let i;const a=__name(()=>{i?.().finally(()=>process.exit(130))},"sigintHandler");process.once("SIGINT",a);let l=!1;try{const e=__name(async e=>{const{summary:r,resolved:o}=await runLearnPipeline({...t,isLocalSource:n,needsAuth:s,signal:e});return i=o?.cleanup,r},"runTask");if(r){const t=n?void 0:[...AM];({cancelled:l}=await runRepoLearnProgress({runTask:e,repoName:o,stepOrder:t}))}else logLearnSummary({summary:await e((new AbortController).signal)})}finally{process.off("SIGINT",a),i&&await i()}r&&!l||process.exit(0),WE(),await eM({skipOnboarding:!0})}function getTastePath(t){const{target:n}=t;if("local-project"===n)return e.join(process.cwd(),".commandcode","taste");if("local-global"===n)return e.join(w.homedir(),".commandcode","taste");throw new Error(`Remote storage not yet implemented: ${n}`)}function getRootTasteFile(t){const{target:n}=t;return e.join(getTastePath({target:n}),"taste.md")}function getCategoryPath(t){const{target:n,category:r}=t;return e.join(getTastePath({target:n}),r)}function getCategoryTasteFile(t){const{target:n,category:r}=t;return e.join(getCategoryPath({target:n,category:r}),"taste.md")}__name(createLearnCommand,"createLearnCommand"),__name(learnTaste,"learnTaste"),Ut(),Ut(),Ut(),kn(),__name(getTastePath,"getTastePath"),__name(getRootTasteFile,"getRootTasteFile"),__name(getCategoryPath,"getCategoryPath"),__name(getCategoryTasteFile,"getCategoryTasteFile"),Ut(),Ut();var qM=/confidence:/i;function findLookaheadEnd(e,t){const n=e.slice(t),r=n.findIndex(e=>{const t=e.trim();return t.startsWith("#")||t.startsWith("-")||qM.test(t)});if(-1===r)return{endIdx:e.length,inclusive:!1};const o=n[r].trim();return{endIdx:t+r,inclusive:qM.test(o)&&!o.startsWith("#")&&!o.startsWith("-")}}function joinMultiLineLearning(e,t,n){const{endIdx:r,inclusive:o}=findLookaheadEnd(e,t),s=o?r+1:r;return{combined:[n,...e.slice(t,s).map(e=>e.trim()).filter(e=>e.length>0)].join(" "),nextIdx:s}}function processRawLine(e,t){const n=e[t],r=t+1,o=n.trim();if(!o.startsWith("-"))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};if(qM.test(o))return{entry:{text:n,originalLineNum:r},nextIdx:t+1};const{combined:s,nextIdx:i}=joinMultiLineLearning(e,t+1,n);return{entry:{text:s,originalLineNum:r},nextIdx:i}}function preprocessLines(e){const t=[];let n=0;for(;n<e.length;){const{entry:r,nextIdx:o}=processRawLine(e,n);t.push(r),n=o}return t}function validateLearningLine(e){const{line:t,lineNum:n}=e,r=[],o=t.substring(1).trim();if(!qM.test(o))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 s=Array.from(o.matchAll(/confidence:\s*(\S+)/gi)),i=s.length>0?s[s.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?o.substring(0,i.index).trim():o.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),o=r.findIndex(e=>e.trim().startsWith("# "));return(-1===o?r:r.slice(0,o)).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),o=t.filter(e=>"warning"===e.severity),s=0===r.length;if(0===t.length)return{valid:s,issues:[...t],summary:`${Me.tick} ${n} is valid`};const i=[];r.length>0&&i.push(`${r.length} error${r.length>1?"s":""}`),o.length>0&&i.push(`${o.length} warning${o.length>1?"s":""}`);const a=r.length>0?Me.cross:Me.warning;return{valid:s,issues:[...t],summary:`${a} ${n} has ${i.join(", ")}`}}function formatSingleIssue(e,t){const n=[`${e.line?ue.dim(` Line ${e.line}: `):" "}${t(e.message)}`];return e.suggestion&&n.push(ue.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`${ue.green(e)} ${ue.dim(n)}`}if(!n)return t.summary;const r=t.issues.filter(e=>"error"===e.severity),o=t.issues.filter(e=>"warning"===e.severity);return[r.length>0?ue.red(t.summary):ue.yellow(t.summary),"",...formatIssueGroup(r,ue.red,ue.bold(ue.red("Errors:"))),...formatIssueGroup(o,ue.yellow,ue.bold(ue.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"),Ut(),__name(formatSingleIssue,"formatSingleIssue"),__name(formatIssueGroup,"formatIssueGroup"),__name(formatValidationIssues,"formatValidationIssues");var zM=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:o}=e;zM.has(t.trim())||(r.hasAnyCategory=!0,warnIfEmptyCategory(r,o),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 WM=/^see \[[^\]]+\/taste\.md\]\([^\)]+\/taste\.md\)$/i,HM=/^\[cmd\]: https:\/\/commandcode\.ai\/$/i;function processLine(e){const{line:t,lineNum:n,state:r,rawLines:o}=e,s=t.trim();s&&(s.startsWith("# ")?processHeading({line:t,lineNum:n,state:r,rawLines:o}):s.startsWith("-")?processLearning({line:t,lineNum:n,state:r}):WM.test(s)||HM.test(s)||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 o=t.split("\n"),s=preprocessLines(o),i={currentCategory:null,categoryLineNumber:null,learningsInCurrentCategory:0,hasAnyCategory:!1,issues:r};for(const{text:e,originalLineNum:t}of s)processLine({line:e,lineNum:t,state:i,rawLines:o});return checkFinalCategory({state:i,rawLines:o}),buildResult({issues:r,filePath:n})}__name(processLine,"processLine"),__name(checkFinalCategory,"checkFinalCategory"),__name(validateTasteFile,"validateTasteFile");var GM=__name(e=>"local-global"===e?"global":"project","locationLabel"),VM=__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 O(n)?{result:{path:n,displayName:`${e}/taste.md`}}:{error:{file:e,error:`Taste package '${e}' not found in ${GM(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=[],o=getRootTasteFile({target:n});O(o)&&r.push({path:o,displayName:"taste.md"});const s=(await C.readdir(t,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>({entry:e,categoryFile:getCategoryTasteFile({target:n,category:e.name})})).filter(({categoryFile:e})=>O(e)).map(({entry:e,categoryFile:t})=>({path:t,displayName:`${e.name}/taste.md`}));return r.push(...s),r}async function lintFile(e){let t=await C.readFile(e.path,"utf-8");const n=migrateHeader({content:t});n!==t&&(await C.writeFile(e.path,n,"utf-8"),t=n);const r=validateTasteFile({content:t,filePath:e.displayName}),o=r.issues.filter(e=>"error"===e.severity).length,s=r.issues.filter(e=>"warning"===e.severity).length,i=formatValidationIssues({result:r});return{file:e.displayName,valid:r.valid,errors:o,warnings:s,formatted:i}}async function lintSpecificPackages(e){const{packages:t,target:n}=e,{files:r,errors:o}=collectSpecificFiles({packages:t,target:n});if(0===r.length&&o.length>0)return{success:!1,filesLinted:[],errors:o,totalErrors:0,totalWarnings:0};if(0===r.length)return VM({file:"all",error:`No taste files found in ${GM(n)}`});const s=await Promise.all(r.map(lintFile)),i=s.reduce((e,t)=>e+t.errors,0),a=s.reduce((e,t)=>e+t.warnings,0);return{success:s.every(e=>e.valid)&&0===o.length,filesLinted:s,errors:o,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 VM({file:"all",error:`No taste files found in ${GM(n)}`});const o=await Promise.all(r.map(lintFile)),s=o.reduce((e,t)=>e+t.errors,0),i=o.reduce((e,t)=>e+t.warnings,0);return{success:o.every(e=>e.valid),filesLinted:o,errors:[],totalErrors:s,totalWarnings:i}}async function lint(e){const{packages:t,target:n}=e,r=getTastePath({target:n});return O(r)?t.length>0?lintSpecificPackages({packages:t,target:n}):lintAllFiles({tastePath:r,target:n}):VM({file:"all",error:`No taste directory found in ${GM(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"),Ut(),Ps(),__name(resolveConflictStrategy,"resolveConflictStrategy");var QM=ue.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(`${ue.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?`${ue.dim(t[1])}${ue.green(t[2])}${ue.white(t[3]??"")}${t[4]?ue.dim(t[4]):""}`:ue.dim(e)}function exitWithUsage({message:e,usage:t}){console.error(`${ue.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 KM=__name((e,t)=>t,"linkFallback");function getPackageLink({owner:e,packageName:t}){return Et(`commandcode.ai/${e}/${t}`,`https://commandcode.ai/${e}/${t}`,{fallback:KM})}function getProfileLink(e){return Et(`commandcode.ai/${e}`,`https://commandcode.ai/${e}`,{fallback:KM})}function wrapLine(e,t=0){const n=(process.stdout.columns||80)-t;return bt(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(ue.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(`${ue.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),o=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`:`${o} day${o>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(ue.red(`Error: ${t}`)),await flushAndExit(1)}}}function createLintCommand(){return new Ne("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 ${ue.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(`${ue.green(Me.tick)} All ${ue.green(e.length)} taste files are valid`);const r=[];t>0&&r.push(ue.red(`${t} error${t>1?"s":""}`)),n>0&&r.push(ue.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(ue.red(`Error: ${e.error}`));process.exit(1)}logLintResults(n)}function parseSection(e){const{section:t,sourcePath:n}=e,r=t.split("\n"),o=r[0].trim(),s=r.map(e=>parseLearning({line:e})).filter(e=>null!==e);return 0===s.length?null:{category:normalizeCategory({category:o}),learnings:s,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 C.readFile(t,"utf-8"),r=migrateHeader({content:n});return r===n?n:(await C.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 o=t.findIndex((e,t)=>t>r&&e.startsWith("# "));if(-1===o)return{start:r,end:t.length-1};const s=trimTrailingBlanks({lines:t,from:o-1,until:r});return{start:r,end:s}}function ensureHeader(e){if(!e)return cv+"\n\n";const t=e.trim();return t.startsWith(av)||t.startsWith(uv)||t.startsWith(dv)?e:cv+"\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"),Ut(),Hs(),Ut(),Ut(),Ut(),__name(parseSection,"parseSection"),__name(parsePackages,"parsePackages"),__name(parseLearning,"parseLearning"),__name(normalizeCategory,"normalizeCategory"),__name(denormalizeCategory,"denormalizeCategory"),Ut(),__name(formatPackage,"formatPackage"),Ut(),__name(readAndMigrateFile,"readAndMigrateFile"),__name(trimTrailingBlanks,"trimTrailingBlanks"),__name(findCategoryRange,"findCategoryRange"),__name(ensureHeader,"ensureHeader"),__name(ensureTrailingNewlines,"ensureTrailingNewlines");var YM="local-global";async function loadCategoryPackages(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:YM,category:e.name});return O(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getPackageInfo(e){try{const t=await C.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:YM});if(!O(e))return[];const t=await C.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(loadCategoryPackages))).flat()}async function getPackage(e){const{category:t}=e,n=getCategoryTasteFile({target:YM,category:t});return O(n)&&parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n})[0]||null}async function writePackage(t){const{pkg:n}=t,r=getTastePath({target:YM});await C.mkdir(r,{recursive:!0});const o=getCategoryTasteFile({target:YM,category:n.category}),s=e.dirname(o);await C.mkdir(s,{recursive:!0});const i=formatPackage({pkg:n});await C.writeFile(o,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"),Ut(),Ut();var JM="local-project";async function removeCategoryFromRoot(e){const{category:t,rootFile:n}=e;if(!O(n))return null;const r=migrateHeader({content:await C.readFile(n,"utf-8")}).split("\n"),o=findCategoryRange({lines:r,pattern:new RegExp(`^# ${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i")});if(!o)return null;const s=r.slice(0,o.start),i=o.end<r.length-1?r.slice(o.end+1):[],a={before:s.join("\n").trim(),after:i.join("\n").trim()},l=[...s,...i].join("\n").trim();return""===l&&await C.rm(n,{force:!0}),""!==l&&await C.writeFile(n,l+"\n","utf-8"),a}async function removePackage(t){const{category:n}=t,r=getRootTasteFile({target:JM}),o=await removeCategoryFromRoot({category:n,rootFile:r}),s=getCategoryTasteFile({target:JM,category:n}),i=e.dirname(s);return O(i)&&await C.rm(i,{recursive:!0,force:!0}),o}async function writeToRoot(e){const{pkg:t,rootFile:n,categoryPosition:r}=e,o=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+=o.trim()+t,void await C.writeFile(n,e.trim()+"\n","utf-8")}let s="";O(n)&&(s=await C.readFile(n,"utf-8"),s=migrateHeader({content:s})),s=ensureHeader(s),s=ensureTrailingNewlines(s),s+=o,await C.writeFile(n,s.trim()+"\n","utf-8")}async function writeToSubdirectory(t){const{pkg:n,rootFile:r,categoryPosition:o}=t,s=getCategoryTasteFile({target:JM,category:n.category}),i=e.dirname(s);await C.mkdir(i,{recursive:!0});const a=formatPackage({pkg:n});await C.writeFile(s,a,"utf-8");const l=`# ${n.category}\nSee [${n.category}/taste.md](${n.category}/taste.md)\n`;if(o){let e=ensureHeader(migrateHeader({content:o.before}));e=ensureTrailingNewlines(e);const t=o.after?"\n\n"+o.after:"";return e+=l.trim()+t,void await C.writeFile(r,e.trim()+"\n","utf-8")}let u="";O(r)&&(u=await C.readFile(r,"utf-8"),u=migrateHeader({content:u})),u=ensureHeader(u),u=ensureTrailingNewlines(u),u+=l,await C.writeFile(r,u.trim()+"\n","utf-8")}__name(removeCategoryFromRoot,"removeCategoryFromRoot"),__name(removePackage,"removePackage"),__name(writeToRoot,"writeToRoot"),__name(writeToSubdirectory,"writeToSubdirectory");var XM="local-project";async function loadCategoryPackages2(e){if(!e.isDirectory())return[];const t=getCategoryTasteFile({target:XM,category:e.name});return O(t)?parsePackages({content:await readAndMigrateFile({filePath:t}),sourcePath:t}).map(t=>({...t,category:e.name})):[]}async function getAllPackages2(){const e=getTastePath({target:XM});if(!O(e))return[];const t=[],n=getRootTasteFile({target:XM});if(O(n)){const e=parsePackages({content:await readAndMigrateFile({filePath:n}),sourcePath:n});t.push(...e)}const r=await C.readdir(e,{withFileTypes:!0}),o=(await Promise.all(r.map(loadCategoryPackages2))).flat();return t.push(...o),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:XM});await C.mkdir(n,{recursive:!0});const r=getRootTasteFile({target:XM}),o=await removePackage({category:t.category});t.learnings.length<=5?await writeToRoot({pkg:t,rootFile:r,categoryPosition:o}):await writeToSubdirectory({pkg:t,rootFile:r,categoryPosition:o})}function exists2(){const e=getTastePath({target:XM});return O(e)}async function appendCategoryFile(e,t){const n=getCategoryTasteFile({target:"local-project",category:t.category});if(!O(n))return;const r=await C.readFile(n,"utf-8"),o=new Blob([r],{type:"text/markdown"}),s=new File([o],"taste.md",{type:"text/markdown"});e.append(`files[${t.category}/taste.md]`,s)}async function prepareUploadFormData(t){const{packageName:n,pkg:r,description:o,type:s="category",isPublic:i=!1,overwrite:a=!1}=t,l=new FormData;l.append("name",n),o&&l.append("description",o),l.append("type",s),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"===s)return l;const g=getTastePath({target:"local-project"}),h=e.join(g,r.category);if(!O(h))return l;const f=getCategoryTasteFile({target:"local-project",category:r.category});if(!O(f))return l;const y=await C.readFile(f,"utf-8"),w=new Blob([y],{type:"text/markdown"}),S=new File([w],"taste.md",{type:"text/markdown"});return l.append(`files[${r.category}/taste.md]`,S),l}async function prepareMultiplePackagesUpload(e){const{pkgs:t,projectName:n,description:r,isPublic:o=!1,overwrite:s=!1}=e,i=new FormData;i.append("name",n),r&&i.append("description",r),i.append("type","project"),i.append("isPublic",String(o)),i.append("overwrite",String(s));const a=getRootTasteFile({target:"local-project"});if(O(a)){const e=await C.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:o,extra:s}=e,i=new Error(t);throw trackError({error:sanitizeErrorForTelemetry({error:i,label:n}),context:{component:vs.TASTE_REMOTE_STORAGE,heading:r,"http.status":o,...s}}),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(),o=await tryPublicDownload({baseUrl:r,owner:t,packageName:n});if(o)return o;const s=await getAuthKey();if(!s)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:s})}async function tryPublicDownload(e){const{baseUrl:t,owner:n,packageName:r}=e,o=`${t}${Wt.INTERNAL.PROFILE.PACKAGE_DOWNLOAD.replace(":login",n).replace(":packageName",r)}`;let s;try{s=await fetch(o,{method:"GET"})}catch{return null}if(s.ok){const{data:e}=await s.json();return{type:e.type||"category",files:e.files||[],isPublic:!0}}if(404===s.status)return null;throwTrackedError({message:await parseApiError({response:s,fallback:`Failed to download taste package (${s.status})`}),label:"download_public_error",heading:"Failed to download taste package (public)",status:s.status})}async function tryAuthenticatedDownload(e){const{baseUrl:t,owner:n,packageName:r,apiKey:o}=e,s=`${t}${Wt.BETA.TASTE.PACKAGES.DOWNLOAD.replace(":namespace",n).replace(":packageName",r)}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${o}`}});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:vs.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()}${Wt.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(),o=r.packages||[];if(0===o.length)return[];const s=[];for(let e=0;e<o.length;e+=5){const t=o.slice(e,e+5),n=await Promise.all(t.map(fetchSinglePackage));s.push(...n.filter(e=>null!==e))}return s}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:vs.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 o=r.files||[];if(0===o.length)return null;const s=o.find(e=>"taste.md"===e.file);if(!s)throw new Error(`No taste.md file found in package '${n}'`);return{category:n,learnings:parseTasteContent(s.content),sourcePath:`remote:${n}`,isPublic:r.isPublic??!1}}async function writePackage3(e){const{pkg:t,owner:n,isPublic:r=!1,overwrite:o=!1}=e,s=await requireAuthKey(),i=await prepareUploadFormData({packageName:t.category,pkg:t,type:"category",isPublic:r,overwrite:o}),a=`${getApiBaseUrl()}${Wt.BETA.TASTE.PACKAGES.UPLOAD.replace(":namespace",n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${s}`},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:o=!1,overwrite:s=!1}=e,i=await requireAuthKey(),a=await prepareMultiplePackagesUpload({pkgs:t,projectName:n,isPublic:o,overwrite:s}),l=`${getApiBaseUrl()}${Wt.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()}${Wt.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 C.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 Ne("list").alias("ls").option("-g, --global","List global packages").addOption(new Re("-l, --local","Use local server").hideHelp()).option("--remote","List remote packages").addOption(new Re("--staging","Use staging environment").hideHelp()).description(`List available packages ${ue.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"),Ut(),LS(),Ut(),__name(appendCategoryFile,"appendCategoryFile"),__name(prepareUploadFormData,"prepareUploadFormData"),__name(prepareMultiplePackagesUpload,"prepareMultiplePackagesUpload"),kn(),Ut(),__name(parseLearningLine,"parseLearningLine"),__name(parseTasteContent,"parseTasteContent"),VE(),Ps(),Ut(),zE(),Ps(),__name(parseApiError,"parseApiError"),__name(throwTrackedError,"throwTrackedError"),__name(requireAuthKey,"requireAuthKey"),Ut(),LS(),zE(),kn(),__name(downloadPackage,"downloadPackage"),__name(tryPublicDownload,"tryPublicDownload"),__name(tryAuthenticatedDownload,"tryAuthenticatedDownload"),rr(),__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 ZM={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?ZM.remote:e.global?ZM.global:ZM.project}function getPackageDisplayLength(e){let t=e.category.length;return e.isPublic&&(t+=9),e.isPublic&&e.starCount&&(t+=` ${Me.star}${e.starCount}`.length),e.downloadCount&&(t+=` ${Me.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,o=r?`, updated ${r}`:"";return` ${ue.white(e.category)}${e.isPublic?ue.green(" [public]"):""}${e.isPublic&&e.starCount?ue.yellow(` ${Me.star}${e.starCount}`):""}${e.downloadCount?ue.gray(` ${Me.arrowDown}${e.downloadCount}`):""}${n}${ue.dim.gray(`(${e.learningCount} learnings${o})`)}`}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?$e(`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${QM} Packages`),console.log(`${ue.gray("⎿")} ${ue.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(ue.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(ue.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,o=await C.readFile(n,"utf-8");if("taste.md"===e.basename(n)&&e.basename(e.dirname(n))===r)return 1;const s=o.split("\n").findIndex(e=>e.trim().toLowerCase()===`# ${r.toLowerCase()}`);return s>=0?s+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 o=r.sourcePath,s=await findCategoryLineNumber({filePath:o,category:t});return await St([{file:o,line:s}]),{success:!0,filePath:o,lineNumber:s}}__name(resolveStorage,"resolveStorage"),__name(getPackageDisplayLength,"getPackageDisplayLength"),__name(formatPackageLine,"formatPackageLine"),__name(validateListOptions,"validateListOptions"),__name(fetchPackages,"fetchPackages"),__name(getStorageLabel,"getStorageLabel"),__name(printPackageTable,"printPackageTable"),__name(runList,"runList"),Ut(),Ut(),__name(fetchAllPackages,"fetchAllPackages"),__name(handleOpenError,"handleOpenError"),__name(readCategoryLineNumber,"readCategoryLineNumber"),__name(findCategoryLineNumber,"findCategoryLineNumber"),__name(openPackage,"openPackage");var eN=new Set(["local-project","local-global","remote-project","remote-user"]);async function open11(e){const{package:t,target:n}=e;if(!eN.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=vt.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 Ne("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 ${ue.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 he(t);const n=getPackageLink({owner:e.owner,packageName:e.packageName});console.log(`${ue.green(Me.tick)} Opened ${n} in browser`)}async function openInEditor3({packageName:e,options:t}){const n=t.global?"local-global":"local-project",r=await open11({package:e,target:n});r.success||exitWithError(r.error??"Unknown error"),console.log(`${ue.green(Me.tick)} Opened ${ue.green(`'${e}'`)} taste package from ${t.global?"global":"project"}`)}__name(open11,"open"),__name(getEditorSetupInstructions,"getEditorSetupInstructions"),__name(createOpenCommand,"createOpenCommand"),__name(validateOpenOptions,"validateOpenOptions"),__name(runOpen,"runOpen"),__name(openInBrowser,"openInBrowser"),__name(openInEditor3,"openInEditor"),Ut(),Ut(),Ut(),Ut();var tN=null,nN=!1;function setActiveSpinner(e){tN=e}function stopActiveSpinner(e){tN&&(tN.stop(e),tN=null)}function setPrompted(e){nN=e}function wasPrompted(){return nN}function beginPrompt(e,t){stopActiveSpinner(),We.intro(ue.dim(e)),t&&We.log.message(ue.dim(t)),setPrompted(!0)}function handleCancel(e){We.isCancel(e)&&(We.cancel("Operation cancelled"),process.exit(0))}function startStrategySpinner(e){if("skip"===e){const e=We.spinner();return e.start("Skipping"),void e.stop("Skipped")}const t="merge"===e?"Merging":"Overwriting",n="merge"===e?"Merged":"Overwritten",r=We.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:o}=e,s="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),We.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ue.green(`'${t}'`)} from ${n}`,s),We.log.message(`Local: ${r.learnings.length} learnings\nRemote: ${o} learnings ${ue.dim(`(from ${n})`)}`);const i=await We.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} → ${o} 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,o="This package already exists in global storage";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),We.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pushing ${ue.green(`'${t}'`)} to global`,o),We.log.message(`Local: ${n} learnings\nGlobal: ${r.learnings.length} learnings`);const s=await We.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(s);const i=s;return startStrategySpinner(i),i}async function promptGlobalPullStrategy(e){const{packageName:t,localPkg:n,globalLearningsCount:r}=e,o="This package already exists locally";if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(o),setPrompted(!0),We.log.warn("Non-interactive terminal detected, using default merge strategy"),"merge";beginPrompt(`Pulling ${ue.green(`'${t}'`)} from global`,o),We.log.message(`Local: ${n.learnings.length} learnings\nGlobal: ${r} learnings`);const s=await We.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(s);const i=s;return startStrategySpinner(i),i}async function promptTypeMismatchStrategy(e){const{packageName:t,owner:n,localLearningsCount:r,remoteLearningsCount:o}=e,s=`Pushing local project taste to individual package '${t}'`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),We.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=Et(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ue.green(`'${t}'`)} to ${n}`,s),We.log.message(`Local: ${t} (${r} learnings)\nRemote: ${t} (${o} learnings) in ${n}`),We.log.info(`Current package: ${ue.cyan(i)} ${ue.dim("(review)")}`);const a=await We.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:o}=e,s=`This package already exists in ${n}`;if(!process.stdout.isTTY||!process.stdin.isTTY)return stopActiveSpinner(s),setPrompted(!0),We.log.warn("Non-interactive terminal detected, skipping push"),"skip";const i=Et(`commandcode.ai/${n}/${t}`,`https://commandcode.ai/${n}/${t}`,{fallback:__name((e,t)=>t,"fallback")});beginPrompt(`Pushing ${ue.green(`'${t}'`)} to ${n}`,s),We.log.message(`Local: ${r} learnings\nRemote: ${o} learnings`),We.log.info(`Current package: ${ue.cyan(i)} ${ue.dim("(review)")}`);const a=await We.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 (${o} → ${r} learnings)`}],initialValue:"skip"});handleCancel(a);const l=a;return startStrategySpinner(l),l}function mergeSingleLearning(e,t,n,r){const o=t.get(e.text);return o?e.confidence>o.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},o=new Map(n.map(e=>[e.text,e])),s=new Map(o);for(const e of t)mergeSingleLearning(e,o,s,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(s.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:o,owner:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r?promptMergeStrategy({packageName:o.category,owner:s,localPkg:r,remoteLearningsCount:o.learnings.length}):"merge"}async function executePackageStrategy(e){const{tastePkg:t,owner:n,overwrite:r,flagStrategy:o,result:s}=e,i=await getPackage2({category:t.category}),a=await resolveRemotePullStrategy({flagStrategy:o,overwrite:r,existingPkg:i,tastePkg:t,owner:n});if("skip"===a)return void s.skipped?.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});s.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:o,flagStrategy:s,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:o,flagStrategy:s,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:o,flagStrategy:s,result:i})}}async function pullCategoryPackage(e){const{files:t,packageName:n,owner:r,overwrite:o,flagStrategy:s,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:o,flagStrategy:s,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"),Ut(),Ut(),__name(mergeSingleLearning,"mergeSingleLearning"),__name(mergePackages,"mergePackages"),__name(validateSinglePackage,"validateSinglePackage"),__name(validateSingleRemoteFile,"validateSingleRemoteFile"),__name(validatePackages,"validatePackages"),__name(validateRemoteFiles,"validateRemoteFiles"),__name(mergeOrKeep,"mergeOrKeep"),Ut(),__name(resolveRemotePullStrategy,"resolveRemotePullStrategy"),__name(executePackageStrategy,"executePackageStrategy"),__name(processPackage,"processPackage"),__name(pullProjectPackage,"pullProjectPackage"),__name(pullCategoryPackage,"pullCategoryPackage");var rN=__name(({pkg:e,error:t})=>({success:!1,packagesPulled:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),oN=__name(()=>({success:!0,packagesPulled:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult"),sN=__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:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPullStrategy({packageName:s.category,localPkg:r,globalLearningsCount:s.learnings.length}):"merge"}async function executePullStrategy(e){const{tastePkg:t,source:n,flagStrategy:r,overwrite:o,result:s}=e,i=await getPackage2({category:t.category}),a=await resolvePullStrategy({flagStrategy:r,overwrite:o,existingPkg:i,source:n,tastePkg:t});if("skip"===a)return void s.skipped.push(t.category);if("overwrite"===a&&(await writePackage2({pkg:t}),s.packagesPulled.push(t.category),s.overwritten.push(t.category)),"merge"===a){const{pkg:e,details:n}=mergeOrKeep({source:t,existing:i});await writePackage2({pkg:e}),s.packagesPulled.push(t.category),s.mergeDetails[t.category]=n}const l=getCategoryTasteFile({target:"local-project",category:t.category});s.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:o}=e;if("local-global"!==n&&"remote-project"!==n&&"remote-user"!==n)return rN({pkg:"all",error:`Invalid source: ${n}`});const s=sN(n);let i;try{i="local-global"===n?await getAllPackages():await getAllPackages3()}catch(e){return rN({pkg:"all",error:e instanceof Error?e.message:String(e)})}if(0===i.length)return rN({pkg:"all",error:`No taste packages found in ${s}`});const a=validatePackages({packages:i,label:s});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 ${s}`})),mergeDetails:{},overwritten:[],filePaths:{}};const u=oN();for(const e of l)await pullSinglePackage({tastePkg:e,source:n,flagStrategy:o,overwrite:r,result:u});return u}async function executePullRemote(e){const{owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s}=e,i=await downloadPackage({owner:t,packageName:n});if(!i)return rN({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:o,result:s};return"project"===a?(await pullProjectPackage(d),s):(await pullCategoryPackage(d),s)}async function pullRemote(e){const{owner:t,packageName:n,overwrite:r=!1,strategy:o}=e,s=oN();try{return await executePullRemote({owner:t,packageName:n,overwrite:r,flagStrategy:o,result:s})}catch(e){return rN({pkg:n,error:e instanceof Error?e.message:String(e)})}}function logResult(e){if(wasPrompted())return We.outro(e),void setPrompted(!1);console.log(e)}function buildPullMessage(e){const{pkgName:t,sourceName:n,filePath:r,options:o,mergeDetails:s}=e,i=wasPrompted()?"":`${Me.tick} `,a=r?ue.dim(`\n ${shortenPath(r)}`):"";if(o.overwrite)return`${ue.green(i)}Replaced ${ue.green(`'${t}'`)} taste package in project`+a;if(s){const e=formatMergeParts(s);return`${ue.green(i)}Pulled ${ue.green(`'${t}'`)} taste package from ${n} ${ue.gray(`(${e.join(", ")})`)}`+a}return`${ue.green(i)}Pulled ${ue.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 o=t.packagesPulled[0],s=t.filePaths?.[o],i=t.mergeDetails?.[o];return logResult(buildPullMessage({pkgName:o,sourceName:n,filePath:s,options:r,mergeDetails:i})),!r.overwrite&&!!i&&hasMergeConflictRisk(i)}function logPullSummary(e){const{result:t,sourceName:n}=e,r=t.overwritten??[],o=t.skipped??[],s=t.packagesPulled.filter(e=>!r.includes(e)),i=t.packagesPulled.length+o.length,a=`${i} ${1===i?"package":"packages"}`,l=[];return s.length>0&&l.push(wrapLine(`${ue.green("Pulled")} (${s.length}) ${s.join(", ")}`,wasPrompted()?4:0)),r.length>0&&l.push(wrapLine(`${ue.yellow("Overwritten")} (${r.length}) ${r.join(", ")}`,wasPrompted()?4:0)),o.length>0&&l.push(wrapLine(`${ue.dim("Skipped")} (${o.length}) ${ue.dim(o.join(", "))}`,wasPrompted()?4:0)),wasPrompted()?(l.length>0&&We.log.message(l.join("\n")),We.outro(`${a} from ${n}`),setPrompted(!1),hasMergeConflictRiskInRecord(t.mergeDetails??{})):(console.log(`${ue.green(Me.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,o=t.skipped??[];t.packagesPulled.length+o.length>1?logPullSummary({result:t,sourceName:n})&&logMergeReviewTip():o.length>0?logResult(ue.yellow(`Skipped '${o[0]}' — kept local version`)):logPullSingleSuccess({result:t,sourceName:n,options:r})&&logMergeReviewTip()}function createPullCommand(){return new Ne("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 Re("--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 Re("--staging","Use staging environment").hideHelp()).description(`Pull taste packages from remote or global into the project ${ue.dim("(prompts on conflicts)")}`).action(withErrorHandler(async(e,t)=>{setPrompted(!1);const n=resolveRemoteDefault(t),{result:r,owner:o}=await runPull({packageName:e,options:n});r.success||handleResultErrors(r.errors),logPullSuccess({result:r,sourceName:n.remote?o??"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 o=resolveConflictStrategy(r);return r.remote&&t?pullRemoteSingle({packageName:t,options:r,strategy:o}):pullGlobal({packageName:t,options:r,strategy:o})}async function pullRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,o=parseOwnerPackage(t);o||exitWithError("Invalid format — use owner/package (e.g. ahmadawais/code-style)"),setActiveSpinner($e("Pulling taste package").start());const s=await pullRemote({owner:o.owner,packageName:o.packageName,overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s,owner:o.owner}}async function pullGlobal(e){const{packageName:t,options:n,strategy:r}=e;setActiveSpinner($e("Pulling taste package").start());const o=n.all||!t?[]:[t],s=await pull({packages:o,source:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),{result:s}}async function fetchUserNamespaces(){const e=getApiBaseUrl(),t=new rS({baseUrl:e}),n=await t.get({endpoint:Wt.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 We.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()?"":`${Me.tick} `,n=`${e} ${1===e?"package":"packages"}`;logResult2(`${ue.green(t)}Skipped ${n}`)}return!1}const o=n.packagesPushed.length,s=`${o} ${1===o?"package":"packages"}`,i=n.filePaths?.[n.packagesPushed[0]],a=r.global&&i?shortenPath(e.dirname(e.dirname(i))):i,l=wasPrompted()?"":`${Me.tick} `;if(!a)return logResult2(`${ue.green(l)}Pushed ${s} 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?` ${ue.gray(`(${e} ${1===e?"learning":"learnings"} replaced)`)}`:"";return logResult2(`${ue.green(l)}Replaced ${s} in ${a}${t}`),!1}if(!n.mergeDetails||0===Object.keys(n.mergeDetails).length)return logResult2(`${ue.green(l)}Pushed ${s} to ${a}`),!1;let u=0,d=0,m=0;for(const e of Object.values(n.mergeDetails))u+=e.added??0,d+=e.updated??0,m+=e.unchanged??0;const g=formatMergeParts({added:u,updated:d,unchanged:m}),h=g.length>0?` ${ue.gray(`(${g.join(", ")})`)}`:"";return logResult2(`${ue.green(l)}Pushed ${s} to ${a}${h}`),(u>0||d>0)&&m>0}function logPushSingleSuccess(e){const{result:t,options:n}=e;if(n.all)return!1;if(1!==t.packagesPushed.length)return!1;const r=t.packagesPushed[0],o=t.filePaths?.[r],s=n.remote&&o,i=s?o:"global",a=wasPrompted()?"":`${Me.tick} `,l=!s&&o?ue.dim(`\n ${shortenPath(o)}`):"";if(n.overwrite)return logResult2(`${ue.green(a)}Replaced ${ue.green(`'${r}'`)} taste package in ${i}`+l),!1;if(t.mergeDetails?.[r]){const e=t.mergeDetails[r],n=formatMergeParts(e);return logResult2(`${ue.green(a)}Pushed ${ue.green(`'${r}'`)} taste package to ${i} ${ue.gray(`(${n.join(", ")})`)}`+l),hasMergeConflictRisk(e)}return logResult2(`${ue.green(a)}Pushed ${ue.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",o=wasPrompted()?"":`${Me.tick} `;return logResult2(wrapLine(`${ue.green(o)}Pushed ${ue.green(t.packagesPushed.length)} taste packages ${ue.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[o,s]=n.split("/");if(!o||!s)continue;const i=getPackageLink({owner:o,packageName:s});r.has(i)||(r.add(i),console.log(ue.gray(` ${i}`)))}}function logConflictSummary(e){const{result:t}=e,n=t.overwritten??[],r=t.skipped??[],o=t.packagesPushed.filter(e=>!n.includes(e)),s=t.packagesPushed.length+r.length,i=[];o.length>0&&i.push(wrapLine(`${ue.green("Merged")} (${o.length}) ${o.join(", ")}`,4)),n.length>0&&i.push(wrapLine(`${ue.yellow("Overwritten")} (${n.length}) ${n.join(", ")}`,4)),r.length>0&&i.push(wrapLine(`${ue.dim("Skipped")} (${r.length}) ${ue.dim(r.join(", "))}`,4)),i.length>0&&We.log.message(i.join("\n"));const a=`${s} ${1===s?"package":"packages"}`;We.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)),o=[];r.length>0&&o.push(wrapLine(`${ue.green("Pushed")} (${r.length}) ${r.join(", ")}`)),t.length>0&&o.push(wrapLine(`${ue.yellow("Overwritten")} (${t.length}) ${t.join(", ")}`)),n.length>0&&o.push(wrapLine(`${ue.dim("Skipped")} (${n.length}) ${ue.dim(n.join(", "))}`)),o.length>0&&console.log(o.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"),Ut(),__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"),Ut(),rr(),Ut(),LS(),vS(),kn(),__name(fetchUserNamespaces,"fetchUserNamespaces"),Ut(),__name(logResult2,"logResult"),__name(logPushAllSuccess,"logPushAllSuccess"),__name(logPushSingleSuccess,"logPushSingleSuccess"),__name(logPushMultiSuccess,"logPushMultiSuccess"),__name(logPushUrls,"logPushUrls"),__name(logConflictSummary,"logConflictSummary"),__name(logPushBreakdown,"logPushBreakdown"),__name(logPushSuccess,"logPushSuccess"),Ut(),VE(),Ut();var iN=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),aN=__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:o,projectName:s,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=o.reduce((e,t)=>e+t.learnings.length,0),u=aN(r.files);return"project"!==a?promptTypeMismatchStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u}):promptSameTypeStrategy({packageName:s,owner:i,localLearningsCount:l,remoteLearningsCount:u})}async function executePushAllRemote(t){const{packagesToPush:n,owner:r,overwrite:o,isPublic:s,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:o,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?s: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 iN({pkg:"all",error:e instanceof Error?e.message:String(e)})}}__name(resolvePushAllStrategy,"resolvePushAllStrategy"),__name(executePushAllRemote,"executePushAllRemote"),__name(pushAllRemote,"pushAllRemote");var lN=__name(({pkg:e,error:t})=>({success:!1,packagesPushed:[],skipped:[],errors:[{pkg:e,error:t}],mergeDetails:{},overwritten:[],filePaths:{}}),"fail"),cN=__name(()=>({success:!0,packagesPushed:[],skipped:[],errors:[],mergeDetails:{},overwritten:[],filePaths:{}}),"emptyResult");async function writePkg(e){const{pkg:t,target:n,owner:r,isPublic:o,overwrite:s}=e;if("local-global"!==n){if(!r)throw new Error("Failed to get owner for remote push");await writePackage3({pkg:t,owner:r,isPublic:o,overwrite:s})}else await writePackage({pkg:t})}__name(writePkg,"writePkg");var uN=__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:o,tastePkg:s}=e;return"skip"===t?r?"skip":"merge":"merge"===t?"merge":"overwrite"===t||n?"overwrite":r&&"local-global"===o?promptGlobalPushStrategy({packageName:s.category,localLearningsCount:s.learnings.length,globalPkg:r}):"merge"}async function executePushStrategy(e){const{tastePkg:t,target:n,flagStrategy:r,overwrite:o,userOwner:s,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:o,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:s,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:s,isPublic:i}),a.packagesPushed.push(t.category),a.mergeDetails[t.category]=r}const d=uN({target:n,category:t.category,owner:s});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:o=!1,isPublic:s=!1,strategy:i}=e;if(!exists2())return lN({pkg:"all",error:"No taste directory found in project"});const a=await getAllPackages2();if(0===a.length)return lN({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:o,isPublic:s,isPublicExplicitlySet:t,flagStrategy:i}):lN({pkg:"all",error:"Failed to get owner for remote push"});if("local-global"!==r&&"remote-project"!==r&&"remote-user"!==r)return lN({pkg:"all",error:`Invalid target: ${r}`});const m=cN();for(const e of u)await pushSinglePackage({tastePkg:e,target:r,flagStrategy:i,overwrite:o,userOwner:d,isPublic:s,result:m});return m}async function executeRemotePush(e){const t=void 0!==e.isPublic,{owner:n,packageName:r,overwrite:o=!1,isPublic:s=!1,strategy:i}=e,a=await getPackage2({category:r});if(!a)return lN({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 lN({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:o,existingPkg:u,target:"remote-project",tastePkg:a}),m=t?s:u?.isPublic??!1,g=cN();if("skip"===d)return g.skipped.push(r),g;if("overwrite"===d&&(await writePackage3({pkg:a,owner:n,isPublic:m,overwrite:!0}),g.packagesPushed.push(r),g.overwritten.push(r)),"merge"===d){const{pkg:e,details:t}=mergeOrKeep({source:a,existing:u});await writePackage3({pkg:e,owner:n,isPublic:m}),g.packagesPushed.push(r),g.mergeDetails[r]=t}return g.filePaths[r]=`${n}/${r}`,g}async function pushRemote(e){const{packageName:t}=e;if(!exists2())return lN({pkg:t,error:"No taste directory found in project"});try{return await executeRemotePush(e)}catch(e){return lN({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"}))],o=await We.select({message:"Owner",options:r,initialValue:t});return We.isCancel(o)&&(We.cancel("Operation cancelled"),process.exit(0)),o}function createPushCommand(){return new Ne("push").description(`Push taste packages to remote ${ue.dim("(commandcode.ai)")} or global ${ue.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 Re("--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 Re("--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"),Ut(),__name(promptOwnerSelection,"promptOwnerSelection"),__name(createPushCommand,"createPushCommand"),__name(validatePushOptions,"validatePushOptions");var dN=__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};We.intro(ue.dim(`pushing ${t}`)),setPrompted(!0);const o=We.spinner();o.start("Resolving"),(await list({location:"local-project"})).some(e=>e.category===t)||(o.error("Failed"),We.outro(ue.red(`Taste package '${t}' not found in project`)),process.exit(1));const s=await fetchUserNamespaces();return o.stop(s.orgs.length>0?"Select owner to push to":""),{owner:s.orgs.length>0?await promptOwnerSelection(s):s.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 o=resolveConflictStrategy(r);return r.remote&&r.all?pushRemoteAll({options:r,strategy:o}):r.remote?pushRemoteSingle({packageName:t,options:r,strategy:o}):pushGlobal({packageName:t,options:r,strategy:o})}async function pushRemoteAll(t){const{options:n,strategy:r}=t;n.owner&&await validateOwnerAccess(n.owner);const o=(await getAllPackages2()).length,s=`${o} ${1===o?"package":"packages"}`,i=e.basename(process.cwd()),a=resolveStrategyLabel({strategy:r,isRemote:!0});console.log(ue.dim(` Pushing ${s} to ${i} (remote)${a}`)),console.log(""),setActiveSpinner($e("Pushing taste packages").start());const l=await push({packages:[],target:"remote-project",overwrite:n.overwrite,isPublic:dN(n),strategy:r,owner:n.owner});return stopActiveSpinner(),l}async function pushRemoteSingle(e){const{packageName:t,options:n,strategy:r}=e,{owner:o,packageName:s}=await resolveOwnerForPush({packageName:t,owner:n.owner});startPushSpinner({owner:o,pkgName:s});const i=await pushRemote({owner:o,packageName:s,overwrite:n.overwrite,isPublic:dN(n),strategy:r});return stopActiveSpinner(`Pushed to ${o}/${s}`),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=We.spinner();return e.start(`Pushing to ${t}/${n}`),void setActiveSpinner(e)}setActiveSpinner($e("Pushing taste package").start())}async function pushGlobal(e){const{packageName:t,options:n,strategy:r}=e,o=n.all||!t?[]:[t],s=await getAllPackages2(),i=o.length>0?o.length:s.length,a=`${i} ${1===i?"package":"packages"}`,l=shortenPath(getTastePath({target:"local-global"})),u=resolveStrategyLabel({strategy:r});console.log(ue.dim(` Pushing ${a} to ${l}${u}`)),console.log(""),setActiveSpinner($e("Pushing taste packages").start());const d=await push({packages:o,target:"local-global",overwrite:n.overwrite,strategy:r});return stopActiveSpinner(),d}function createTasteCommand(){const e=new Ne(on.TASTE);return e.description("Manage taste learning packages").allowUnknownOption().allowExcessArguments(),e.addCommand(createPushCommand()),e.addCommand(createPullCommand()),e.addCommand(createListCommand()),e.addCommand(createLintCommand()),e.addCommand(createOpenCommand()),isExperimentalEnabled()&&e.addCommand(createLearnCommand()),e}function formatVersion(e,t,n=!1){const r=n?de.bold(de.green(t)):de.white(t);return`${de.dim(e)} ${r}`}function showVersionDetails(e){console.log(formatVersion("Current:",e.currentVersion)),console.log(formatVersion("Latest: ",e.latestVersion,!0)),console.log(""),console.log(`Run ${de.bold(de.green("cmd update"))} to install.`)}function showUpdateSuccessHint(){console.log(de.dim(`Run ${de.cyan("cmd")} to start using the new version.`))}function showManualUpdateHint(e){console.log(de.dim("Try updating manually:")),console.log(de.cyan(`npm i -g command-code@${e}`))}function showCheckFailure(){console.log(de.dim("Please check your internet connection or try again later."))}async function checkAction(){const e=$e("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(`${de.green(Me.tick)} Update available`),showVersionDetails(t)):e.succeed(`Up to date ${de.dim(`(${t.currentVersion})`)}`)}async function performUpdateAction(){const e=$e("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} ${Me.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:vs.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 ${de.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"),co(),__name(createTasteCommand,"createTasteCommand"),Ut(),kn(),Ps(),__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 mN=new Ne("update").description("Update Command Code to the latest version").option("--check-only","Check for updates without installing").allowUnknownOption().allowExcessArguments().action(updateAction);Ut(),zE(),VE();var pN=__name((e,t)=>`${Me.info} ${e}: ${de.cyan(t)}`,"formatInfoLine"),gN=__name(e=>de.bold(`${e}:`),"formatSectionHeader"),hN=__name(e=>de.red(e),"formatError"),fN=__name(e=>e instanceof Error?e.message:"Unknown error","formatErrorMessage"),yN=__name(e=>["",gN("User Information"),pN("Name",e.name),pN("Email",e.email),pN("Username",e.userName)],"buildUserOutput"),wN=__name(e=>["",gN("Organization"),pN("Name",e.name),pN("Login",e.login)],"buildOrgOutput"),SN=__name(e=>{e.forEach(e=>console.log(e))},"printLines"),bN=__name((e,t)=>{SN(yN(e)),t&&SN(wN(t)),console.log("")},"displayUserInfo"),EN=__name(e=>null!==e&&e.length>0,"validateApiKey"),vN=__name(e=>e.success&&null!==e.user,"validateUserData");async function whoamiAction(){const e=$e("Fetching user information...").start();try{const t=await getAuthKey();EN(t)||(e.fail(hN('Not authenticated. Please login using "cmd auth login"')),process.exit(1));const n=await getAuthenticatedEntity();vN(n)||(e.fail(hN("Failed to fetch user info")),process.exit(1)),e.succeed("User information loaded"),bN(n.user,n.org)}catch(t){e.fail(hN(`Error: ${fN(t)}`)),process.exit(1)}}__name(whoamiAction,"whoamiAction");var CN=new Ne("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"!==Ee("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=Ee("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=Ee("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(!Ee(`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:""===Ee("git status --porcelain",{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}}Ut(),Ut(),kn(),vS(),Gs(),LS(),Fn(),bo(),Ut(),__name(normalizeGitUrl,"normalizeGitUrl"),__name(validateGitRepo,"validateGitRepo"),Ut(),LS(),zE(),Ut();var kN=["completed","failed","cancelled","timed_out"];function isTerminalStatus(e){return kN.includes(e)}__name(isTerminalStatus,"isTerminalStatus");var TN={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=TN[n],o="setup"===t.phase;if(t.isResume&&o&&!isTerminalStatus(n)&&"running"!==n)r&&t.workingSpinner&&(t.workingSpinner.text=r);else{if(r&&o&&(t.currentSpinner&&t.currentSpinner.succeed(),t.currentSpinner=$e({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=$e({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: ${de.cyan(n)}`))}if("failed"===n){const n=e.data.message||"Unknown error";return t.workingSpinner&&(t.workingSpinner.fail(n),t.workingSpinner=null),t.currentSpinner&&(t.currentSpinner.fail(n),t.currentSpinner=null),void(t.phase="done")}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${de.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(`${Me.cross} ${de.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 o=getApiBaseUrl().replace(/^http/,"ws"),s=await getAuthKey();if(!s)throw new Error("Not authenticated. Run: cmd login");const i=new URLSearchParams({token:s,...n>0?{lastEventId:String(n)}:{}}),a=`${o}/alpha/sandbox/stream/${e}?${i.toString()}`;return new Promise((t,o)=>{const s=new WebSocket(a),i={currentSpinner:null,workingSpinner:null,phase:"setup",lastEventId:n,isResume:r};r&&(i.currentSpinner=$e({stream:process.stderr,text:"Reconnecting..."}).start());const l=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.close(),console.error(`\n${de.yellow("Detached.")} Session still running.`),console.error(`Resume with: ${de.cyan(`cmd --experimental sandbox --id ${e}`)}`),g(),t()},"detach"),u=__name(()=>{i.phase="done",stopAllSpinners({state:i}),s.readyState===WebSocket.OPEN&&s.send(JSON.stringify({action:"cancel"})),s.close(),console.error(`\n${de.yellow("Sandbox stopped.")}`),g(),t()},"cancelSandbox"),d=setupResizeForwarding({ws:s}),m=setupInputHandling({callbacks:{onCancel:u,onDetach:l}});process.once("SIGTERM",l);const g=__name(()=>{d(),m(),process.removeListener("SIGTERM",l)},"teardown");s.addEventListener("open",()=>{sendTerminalSize({ws:s}),i.currentSpinner&&(i.currentSpinner.stop(),i.currentSpinner=null),console.error(""),console.error(`${de.yellow("[Ctrl+C]")} ${de.dim("stop")} ${de.yellow("[Ctrl+D]")} ${de.dim("detach")}`),console.error(`${de.dim("Session:")} ${de.gray(e)}`),console.error(""),r&&(i.workingSpinner=$e({stream:process.stderr}).start())}),s.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)&&(s.close(),g(),t())}catch{}}),s.addEventListener("error",()=>{g(),i.currentSpinner&&(i.currentSpinner.fail("Connection error"),i.currentSpinner=null),o(new Error("WebSocket connection failed"))}),s.addEventListener("close",()=>{"done"!==i.phase&&(i.phase="done",stopAllSpinners({state:i}),g(),console.error(`\n${de.yellow("Disconnected.")} Session still running.`),console.error(`Resume with: ${de.cyan(`cmd --experimental sandbox --id ${e}`)}`),t())})})}function readLocalConfigFiles(){let e="",t="";try{e=L.readFileSync(getAuthFile(),"utf-8")}catch{}try{t=L.readFileSync(getConfigFile(),"utf-8")}catch{}return{auth:e,config:t}}async function askQuestion(e){const t=ct.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,isInternalTeam:r,configFiles:o}){return new rS({baseUrl:getApiBaseUrl()}).post({endpoint:Wt.ALPHA.SANDBOX.START,body:{repoUrl:e,branch:t,prompt:n,isInternalTeam:r,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(de.yellow("Warning: You have uncommitted changes. The sandbox clones from remote, so local changes won't be included."));const r=isInternalTeamFlagPresent(),o=readLocalConfigFiles(),s=e||await askQuestion(`${de.bold("What do you want to do?")}\n${de.cyan(">")} `);if(!s.trim())return void console.error(de.yellow("No prompt provided. Aborting."));const i=s.trim().slice(0,sn.MAX_PROMPT_CHARS),a=$e({stream:process.stderr,text:"Starting sandbox session..."}).start();try{const e=await startSandboxSession({repoUrl:n.repoUrl,branch:n.branch,prompt:i,isInternalTeam:r,configFiles:o});a.succeed("Sandbox started"),await streamSession({sessionId:e.sessionId,prompt:i}),process.exit(0)}catch(e){a.fail("Failed to start sandbox session");const t=e instanceof Rs,r=t?e.code:void 0;if(401===(t?e.status:void 0)||"UNAUTHORIZED"===r)console.error(de.red("\nAuthentication failed. Try logging in again: cmd login"));else if("GITHUB_APP_NOT_INSTALLED"===r){const e=de.cyan(de.underline(n.repoUrl)),t=de.cyan(de.underline("https://github.com/apps/command-code-ai/installations/new"));console.error(`\n${de.red("✖")} Command Code GitHub App isn't installed on ${e}`),console.error(` Install it here: ${t}`),console.error(de.dim(" Then run this command again."))}else{const n=t&&"string"==typeof e.message?e.message:"Something went wrong. Please try again.";console.error(de.red(`\n${n}`))}process.exit(1)}}function createSandboxCommand(){return new Ne("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(de.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 o=n.split("/");if(o.length<2)throw new Error("Invalid GitHub repository format. Expected: owner/repo or owner/repo/path");const[s,i,...a]=o;validateSafeString(s,"owner"),validateSafeString(i,"repository");const l=a.length>0?a.join("/"):void 0;return l&&validateSafeString(l,"path"),{owner:s,repo:i,path:l,branch:t}}function buildGigetSource(e){const{owner:t,repo:n,path:r,branch:o}=e;let s=`gh:${t}/${n}`;return r&&(s+=`/${r}`),o&&(s+=`#${o}`),s}async function fetchSkillFromGitHub(e){await cleanupStaleTempDirectories();const n=parseGitHubRepo(e),{owner:r,repo:o,path:s}=n;let i;if(s){const e=s.split("/").filter(Boolean);i=e[e.length-1]}else i=o;const a=t.join(S.tmpdir(),`commandcode-skill-${R()}`);await k.mkdir(a,{recursive:!0});try{const e=buildGigetSource(n),{downloadTemplate:s}=await import("giget");try{await s(e,{dir:a,force:!0,silent:!0})}catch(t){if(!isCorruptedArchiveError(t))throw t;await clearGigetCache(r,o),await s(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 k.access(l),d=!0}catch{}if(!d)try{await k.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 k.rm(a,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&e.message.includes("SKILL.md not found"))throw e;throw wrapFetchError(e,r,o)}}async function discoverSkillsInRepo(e,t){const n=parseGitHubRepo(e),{owner:r,repo:o,path:s,branch:i}=n,{keepTempDir:a=!1}=t||{},{discoverSkillsLocally:l}=await Promise.resolve().then(()=>(tv(),ev)),u=await l({owner:r,repo:o,path:s,branch:i,keepTempDir:a});if(0===u.skills.length)throw new Error(`No skills found in repository ${r}/${o}${s?` at path "${s}"`:""}. Ensure the repository contains SKILL.md files.`);return u}async function resolveSkillMdPath(e){const n=t.join(e,"SKILL.md");try{return await k.access(n),n}catch{}const r=t.join(e,"skill.md");try{return await k.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 k.readFile(t,"utf-8"),{data:r}=je(n),o=Mf.parse(r);return{name:validateSkillName(o.name),description:o.description}}async function skillExists(e){const{skillName:n,location:r}=e,o="global"===r?getGlobalSkillsDir():getProjectSkillsDir(),s=t.join(o,n);try{return await k.access(s),!0}catch{return!1}}async function discoverSkills(e,t){return discoverSkillsInRepo(e,t)}async function installSkill(e){const{repoInput:n,options:r={}}=e,{global:o=!1,force:s=!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("/"),o=r?`${t.owner}/${t.repo}/${r}`:`${t.owner}/${t.repo}`;m=t.branch?`${o}@${t.branch}`:o}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=o?"global":"project",a="global"===i?getGlobalSkillsDir():getProjectSkillsDir(),l=await skillExists({skillName:r,location:i});if(l&&!s)throw new Error(`Skill "${r}" already exists in ${"global"===i?"~/.commandcode/skills/":".commandcode/skills/"}. Use --force to overwrite.`);await k.mkdir(a,{recursive:!0});const d=t.join(a,r),{randomUUID:m}=await import("crypto"),g=t.join(a,`.${r}.tmp.${m()}`);try{await k.cp(u,g,{recursive:!0,force:!0,dereference:!1}),l&&s&&await k.rm(d,{recursive:!0,force:!0}),await k.rename(g,d)}catch(e){if(await k.rm(g,{recursive:!0,force:!0}).catch(()=>{}),e instanceof Error&&"code"in e&&("EEXIST"===e.code||"ENOTEMPTY"===e.code))throw new Error(`Skill "${r}" was created by another process during installation. Use --force to overwrite.`);throw e}let h;try{h=await resolveSkillMdPath(d)}catch{h=t.join(d,"SKILL.md")}return{name:r,description:n,location:i,path:h}}finally{d&&await k.rm(u,{recursive:!0,force:!0}).catch(()=>{})}}async function removeSkill(e){const{global:n=!1}=e,r=validateSkillName(e.skillName),o=n?"global":"project",s="global"===o?getGlobalSkillsDir():getProjectSkillsDir(),i=t.join(s,r);if(!await skillExists({skillName:r,location:o}))throw new Error(`Skill "${r}" not found in ${"global"===o?"global (~/.commandcode/skills/)":"project (.commandcode/skills/)"} skills.${"global"===o?"":" Use -g/--global to check global skills."}`);await k.rm(i,{recursive:!0,force:!0})}async function listSkills(){const{global:e,project:t,warnings:n}=await loadAllSkillSummariesWithWarnings(),r=getBundledSkillsDir(),o=[],s=[];for(const t of e){const e={name:t.name,description:t.description,location:isBundledSkillPath({filePath:t.filePath,bundledDir:r})?"bundled":"global",path:t.filePath};("bundled"===e.location?o:s).push(e)}return{global:s,project:t.map(e=>({name:e.name,description:e.description,location:"project",path:e.filePath})),bundled:o,warnings:n}}__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"),co(),Ut(),Ut(),Ut(),Ut(),ZE(),__name(validateSafeString,"validateSafeString"),__name(parseGitHubRepo,"parseGitHubRepo"),__name(buildGigetSource,"buildGigetSource"),__name(fetchSkillFromGitHub,"fetchSkillFromGitHub"),__name(discoverSkillsInRepo,"discoverSkillsInRepo"),jS(),Qf(),__name(resolveSkillMdPath,"resolveSkillMdPath"),__name(validateSkillName,"validateSkillName"),__name(validateSkillContent,"validateSkillContent"),__name(skillExists,"skillExists"),__name(discoverSkills,"discoverSkills"),__name(installSkill,"installSkill"),__name(removeSkill,"removeSkill"),__name(listSkills,"listSkills"),kn();var _N=[`${de.dim("Usage:")}`,` ${de.cyan("cmd skills add")} ${de.white("<owner/repo>")}`,"",`${de.dim("Examples:")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/my-skills")} ${de.dim("# single-skill repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/skills/path/to/skill")} ${de.dim("# specific path in repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/multi-skills -s my-skill")} ${de.dim("# pick one from multi-skill repo")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/repo@branch")} ${de.dim("# specific branch")}`,` ${de.cyan("cmd skills add")} ${de.white("acme/repo --global")} ${de.dim("# install to ~/.commandcode/skills/")}`],xN=__name((e,t)=>`${de.green(Me.tick)} Installed ${de.cyan(e)} ${de.dim(`${Me.arrowRight} ${t}/`)}`,"formatInstalled"),AN=__name(e=>`${de.red(Me.cross)} ${e}`,"formatError");async function cleanupAndExit(e,t){e&&await x(e,{recursive:!0,force:!0}).catch(()=>{}),process.exit(t)}function validateRepoFormat(e){(e.startsWith(".")||e.startsWith("/")||e.startsWith("~"))&&(console.error(AN("Local paths are not supported. Skills must be installed from GitHub.")),console.log(""),_N.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(AN(`Invalid repository: "${e}"`)),console.log(""),console.log(`Expected format: ${de.cyan("owner/repo")} or ${de.cyan("owner/repo/path")}`),console.log(""),_N.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 o;validateRepoFormat(e);const s=$e({text:`Fetching ${de.cyan(e)}...`,color:"cyan"});try{let i=[];s.start();const a=await discoverSkills(e,{keepTempDir:!0}),{skills:l,tempDir:u}=a;if(o=u,s.stop(),0===l.length&&(console.error(AN(`No skills found in ${de.cyan(e)}`)),console.log(de.dim("The repository must contain at least one SKILL.md file.")),await cleanupAndExit(o,1)),t.skill){const n=l.find(e=>e.name.toLowerCase()===t.skill.toLowerCase());n||(console.error(AN(`Skill "${t.skill}" not found in ${de.cyan(e)}`)),console.log(""),console.log(de.dim("Available skills:")),l.forEach(e=>console.log(` ${de.cyan(e.name)}`)),await cleanupAndExit(o,1)),i=[n]}else if(1===l.length)i=[l[0]];else if(n){const t=await He({message:`Select skills to install from ${e}`,options:l.map(e=>({value:e.name,label:e.name})),required:!0});"symbol"==typeof t&&(console.log(de.dim("Cancelled")),await cleanupAndExit(o,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 s=$e({text:`Installing ${de.cyan(n.name)}...`,color:"cyan"});s.start();const i=await installSkill({repoInput:e,options:{global:t.global,force:t.force,skillName:n.name,discoveredSkill:n,cachedTempDir:o}});s.stop(),console.log(xN(i.name,r))}catch(e){d++;const t=e instanceof Error?e.message:String(e);console.error(AN(`Failed to install "${n.name}"`)),console.log(de.dim(` ${t}`))}await cleanupAndExit(o,d>0?1:0)}catch(e){s.stop();const t=e instanceof Error?e.message:String(e);console.error(AN(t)),await cleanupAndExit(o,1)}}__name(cleanupAndExit,"cleanupAndExit"),__name(validateRepoFormat,"validateRepoFormat"),__name(addAction,"addAction");var PN=new Ne("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${_N.join("\n")}`).configureOutput({outputError:__name((e,t)=>{e.includes("missing required argument")?(console.error(AN("No repository specified.")),console.log(""),_N.forEach(e=>console.log(e))):t(e)},"outputError")}).action(addAction);Ut(),kn();var IN=__name((e,t)=>`${de.green(Me.tick)} Removed ${de.cyan(e)} from ${t} skills`,"formatRemoved"),MN=__name(e=>`${de.red(Me.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",o=validateSkillNameEarly(e);if(o&&(console.error(MN(o)),console.log(de.dim(`Run ${de.cyan("cmd skills list")} to see installed skills.`)),process.exit(1)),!t.yes&&n){const t=await Ge({message:`Remove ${de.cyan(e)} from ${r} skills?`});"symbol"!=typeof t&&t||(console.log(de.dim("Cancelled")),process.exit(0))}await removeSkill({skillName:e,global:t.global}),console.log(IN(e,r)),process.exit(0)}catch(n){const r=n instanceof Error?n.message:"Failed to remove skill";r.includes("not found")?(console.error(MN(`Skill "${e}" not found in ${t.global?"global":"project"} skills`)),t.global||console.log(de.dim(`Try ${de.cyan(`cmd skills remove ${e} --global`)} to check global skills.`)),console.log(de.dim(`Run ${de.cyan("cmd skills list")} to see installed skills.`))):console.error(MN(r)),process.exit(1)}}__name(validateSkillNameEarly,"validateSkillNameEarly"),__name(removeAction,"removeAction");var NN=new Ne("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);Ut(),jS(),pE(),kn();var RN=__name((e,t)=>{const n=t.length>60?t.substring(0,57)+"...":t;return` ${de.cyan(e)} ${de.dim(`· ${n}`)}`},"formatSkillLine"),$N=__name((e,t)=>`${de.bold(de.white(e))} ${de.dim(`(${t})`)}`,"formatSectionHeader"),LN=__name(e=>{if(0===e.length)return;const t=groupWarnings(e);console.log(""),console.log(`${de.bold(de.yellow("Skipped"))} ${de.dim(`(${e.length})`)}`);for(const e of t){console.log(""),console.log(` ${de.bold(e.category)} ${de.dim(`(${e.items.length})`)}`);for(const t of e.items)console.log(` ${de.bold(skillIdentifier(t.path))}`),console.log(` ${de.dim(t.reason)}`)}},"printWarnings"),DN=__name(()=>{const e=process.cwd(),n=t.join(e,".commandcode","skills"),r=t.join(e,".agents","skills"),o=getProjectSkillsDir(),s=getProjectAgentsCompatSkillsDir(),i=["",de.dim("No skills installed."),"",de.dim("Looking in:"),de.dim(` ${getGlobalSkillsDir()} ${de.white("(global)")}`),de.dim(` ${getGlobalAgentsCompatSkillsDir()} ${de.white("(global, .agents)")}`)];return n!==o&&i.push(de.dim(` ${n} ${de.white("(cwd)")}`)),r!==s&&i.push(de.dim(` ${r} ${de.white("(cwd, .agents)")}`)),i.push(de.dim(` ${o} ${de.white("(project)")}`),de.dim(` ${s} ${de.white("(project, .agents)")}`),"",`Install a skill: ${de.cyan("cmd skills add")} ${de.dim("<owner/repo>")}`,""),i},"formatEmptyHint"),ON=__name(e=>{e.forEach(e=>console.log(e))},"printLines");async function listAction(){const e="true"===process.env.DEBUG;try{const{global:t,project:n,bundled:r,warnings:o}=await listSkills(),s=t.length+n.length,i=__name(()=>{e||0===o.length||(console.log(""),console.log(de.dim(`${o.length} skill${1===o.length?"":"s"} skipped · run with ${de.cyan("--debug")} to see issues`)))},"printDebugHint");0===s&&(ON(DN()),r.length>0&&(console.log($N("Bundled",r.length)),r.forEach(e=>{console.log(RN(e.name,e.description))}),console.log("")),e&&(LN(o),o.length>0&&console.log("")),e||(i(),console.log("")),process.exit(0)),console.log(""),console.log(heading({text:"Skills",sub:de.dim(`${s} installed`)})),n.length>0&&(console.log(""),console.log($N("Project",n.length)),n.forEach(e=>{console.log(RN(e.name,e.description))})),t.length>0&&(console.log(""),console.log($N("Global",t.length)),t.forEach(e=>{console.log(RN(e.name,e.description))})),r.length>0&&(console.log(""),console.log($N("Bundled",r.length)),r.forEach(e=>{console.log(RN(e.name,e.description))})),e&&LN(o),e||i(),console.log(""),process.exit(0)}catch(e){const t=e instanceof Error?e.message:"Unknown error";console.error(`${de.red(Me.cross)} Failed to list skills: ${t}`),process.exit(1)}}__name(listAction,"listAction");var FN=new Ne("list").description("List all installed skills. Run with -d/--debug to also see why any skills were skipped.").action(listAction),UN=new Ne("skills").description("Manage skills from GitHub repositories").addCommand(PN).addCommand(NN).addCommand(FN);handleUnhandledErrors(),setupTelemetry(),await preRun();var jN=createProgram();jN.action(interactiveModeAction),jN.addCommand(wM),jN.addCommand(SM),jN.addCommand(CN),jN.addCommand(mN),jN.addCommand(yM),jN.addCommand(createTasteCommand()),jN.addCommand(createMcpCommand()),jN.addCommand(bM),jN.addCommand(Ms),jN.addCommand(TE),jN.addCommand($E),jN.addCommand(UN),isExperimentalEnabled()&&jN.addCommand(createSandboxCommand()),setupCommanderHooks(jN),jN.parse();